diff --git a/app/pages/index.vue b/app/pages/index.vue index ce72a3de..bf65662c 100644 --- a/app/pages/index.vue +++ b/app/pages/index.vue @@ -145,7 +145,7 @@ const homeTrendingRows = computed(() => { .map((row, index) => ({ row, rank: index + 1 })) .filter(({ row }) => !missingAvatars.value.has(row.owner)) const positions = new Map(trendingOrder.value.map((key, index) => [key, index])) - return rows.toSorted((a, b) => (positions.get(a.row.key) ?? a.rank) - (positions.get(b.row.key) ?? b.rank)) + return rows.sort((a, b) => (positions.get(a.row.key) ?? a.rank) - (positions.get(b.row.key) ?? b.rank)) }) /** diff --git a/eslint.config.mjs b/eslint.config.mjs index bf19fe74..20bc140e 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -11,6 +11,26 @@ export default antfu({ 'ts/no-redeclare': 'off', }, }, ...harlanzw({ base: { type: 'app' } }), { + // Browsers that load the client still lack the ES2023 array copies, and one + // call broke the homepage there (Sentry SKILLD-4P). The first five entries + // repeat antfu's defaults, since a rule override replaces the whole list. + files: ['app/**', 'layers/*/app/**'], + name: 'skilld/client-array-copies', + rules: { + 'no-restricted-properties': [ + 'error', + { property: '__proto__', message: 'Use `Object.getPrototypeOf` or `Object.setPrototypeOf` instead.' }, + { property: '__defineGetter__', message: 'Use `Object.defineProperty` instead.' }, + { property: '__defineSetter__', message: 'Use `Object.defineProperty` instead.' }, + { property: '__lookupGetter__', message: 'Use `Object.getOwnPropertyDescriptor` instead.' }, + { property: '__lookupSetter__', message: 'Use `Object.getOwnPropertyDescriptor` instead.' }, + ...['toSorted', 'toReversed', 'toSpliced'].map(property => ({ + property, + message: 'Older browsers that load the client lack this ES2023 method. Copy the array first, for example `[...items].sort()`.', + })), + ], + }, +}, { // The isolated proof needs Container 1.0 tooling. The site keeps its version. files: ['pnpm-workspace.yaml'], rules: { diff --git a/layers/identity/server/utils/signup-click-proof.ts b/layers/identity/server/utils/signup-click-proof.ts index 325fbd76..d6a4b797 100644 --- a/layers/identity/server/utils/signup-click-proof.ts +++ b/layers/identity/server/utils/signup-click-proof.ts @@ -1,4 +1,5 @@ import type { H3Event } from 'h3' +import { retryIdempotentD1Write } from '@harlan-zw/nuxt-cloudflare/d1' import { getHeader, getRequestURL, setHeader, useSession } from 'h3' import { useRuntimeConfig } from 'nitropack/runtime' @@ -54,10 +55,15 @@ export async function issueSignupClickProof(event: H3Event): Promise db.batch([ + db.prepare('DELETE FROM signup_click_proofs WHERE expires_at <= ?1').bind(now), + db.prepare('INSERT OR IGNORE INTO signup_click_proofs (nonce, expires_at) VALUES (?1, ?2)').bind(nonce, expiresAt), + ]), + }) await session.update({ nonce, page, client: clientKey(event), expiresAt }) return nonce } diff --git a/layers/registry/server/api/skill-asset/[...slug].get.ts b/layers/registry/server/api/skill-asset/[...slug].get.ts index 814fd60b..9ad8dc82 100644 --- a/layers/registry/server/api/skill-asset/[...slug].get.ts +++ b/layers/registry/server/api/skill-asset/[...slug].get.ts @@ -1,4 +1,5 @@ import { readCache, writeCache } from '#shared/server/cache' +import { dependencyOutageError } from '#shared/server/dependency-outage' import { defineApiHandler } from '#shared/server/handler' import { normalizeSkillAssetFilePath } from '#shared/skill-asset-path' import { resolveRepoSourceIdentityFromRow } from '../../utils/repo-source-identity' @@ -130,7 +131,7 @@ export default defineApiHandler({ // reads as deleted for the rest of the cache window. emitOperationalEvent(createWideEvent({ 'operation': 'skill-asset-fetch', 'outcome': 'failed', 'upstream.status': upstream.status ?? 0, 'attempt': upstream.attempts })) setHeader(event, 'retry-after', ASSET_RETRY_AFTER) - throw createError({ statusCode: 503, message: 'Asset source is unavailable upstream' }) + throw dependencyOutageError({ dependency: 'raw.githubusercontent.com', message: 'Asset source is unavailable upstream' }) } const raw = upstream.body diff --git a/layers/registry/server/api/skill-package/[...slug].get.ts b/layers/registry/server/api/skill-package/[...slug].get.ts index e073df26..2e017119 100644 --- a/layers/registry/server/api/skill-package/[...slug].get.ts +++ b/layers/registry/server/api/skill-package/[...slug].get.ts @@ -1,4 +1,5 @@ import { readThroughCache } from '#shared/server/cache' +import { dependencyOutageError } from '#shared/server/dependency-outage' import { defineApiHandler } from '#shared/server/handler' import { presentPnpmPackage } from '../../presenters/pnpm-package' import { pnpmPackageQuery, pnpmPackageSlug } from '../../schemas/pnpm-package' @@ -36,7 +37,10 @@ export default defineApiHandler({ if (!row.rendered_skill_path || row.source_resolved === 0) return { _tag: 'Absent' } as const const source = resolveRepoSourceIdentityFromRow({ owner: row.owner, repo: row.repo }, row) - return detectPnpmPackage({ ...source, ref: row.rendered_commit_sha ?? row.default_branch ?? 'HEAD', skillPath: row.rendered_skill_path! }, fetch) + const detected = await detectPnpmPackage({ ...source, ref: row.rendered_commit_sha ?? row.default_branch ?? 'HEAD', skillPath: row.rendered_skill_path! }, fetch) + if (detected._tag === 'Unavailable') + emitOperationalEvent(createWideEvent({ operation: 'skill-package-detect', outcome: 'failed' })) + return detected }, { ttl: 3600, @@ -45,7 +49,7 @@ export default defineApiHandler({ }, ) if (result._tag === 'Unavailable') - throw createError({ statusCode: 503, message: 'Package details are unavailable. Try again later.' }) + throw dependencyOutageError({ dependency: 'GitHub or npm', message: 'Package details are unavailable. Try again later.' }) return result }, presenter: presentPnpmPackage, diff --git a/layers/registry/server/api/skills-raw/[...slug].get.ts b/layers/registry/server/api/skills-raw/[...slug].get.ts index b388646d..d536aa81 100644 --- a/layers/registry/server/api/skills-raw/[...slug].get.ts +++ b/layers/registry/server/api/skills-raw/[...slug].get.ts @@ -1,5 +1,6 @@ import type { ReadThroughCache } from '#shared/server/cache' import { readThroughCache } from '#shared/server/cache' +import { dependencyOutageError } from '#shared/server/dependency-outage' import { defineApiHandler } from '#shared/server/handler' import { normalizeSkillAssetFilePath } from '#shared/skill-asset-path' import { loadStoredSkillRow, readReferencedFile, readStoredSkillMd, resolveReferencedFileTarget } from '../../utils/skill-stored-source' @@ -94,7 +95,7 @@ export default defineApiHandler({ throw createError({ statusCode: 404, message: 'Referenced file not found in repository' }) if (raw._tag === 'unavailable') { emitOperationalEvent(createWideEvent({ 'operation': 'skill-raw-content-fetch', 'outcome': 'failed', 'upstream.status': raw.status ?? 0, 'attempt': raw.attempts })) - throw createError({ statusCode: 503, message: 'Referenced file source is unavailable upstream' }) + throw dependencyOutageError({ dependency: 'raw.githubusercontent.com', message: 'Referenced file source is unavailable upstream' }) } return { body: raw.body, source: target.source } satisfies ReferencedFile }, diff --git a/layers/registry/server/utils/skill-search.ts b/layers/registry/server/utils/skill-search.ts index 03e86e70..a4391598 100644 --- a/layers/registry/server/utils/skill-search.ts +++ b/layers/registry/server/utils/skill-search.ts @@ -1,8 +1,8 @@ import type { H3Event } from 'h3' import type { DuplicateCandidate, DuplicateGroupRecommendation } from './skill-duplicate-canonical' import type { RegistrySkill } from './skills-registry' -import { createError } from 'h3' import { getDB } from '#server/utils/db' +import { dependencyOutageError } from '#shared/server/dependency-outage' import { canonicalTrustFirstSort, duplicateRankingSignals, @@ -382,8 +382,9 @@ export async function hybridSkillSearch( semantic && expansion ? semanticSkillSearch(event, expansion, SEMANTIC_TOP_K) : Promise.resolve(null), ]) + // Each lane already recorded its own failure as a wide event. if (lexicalKeys === null && semanticHits === null && expansionHits === null) - throw createError({ statusCode: 503, statusMessage: 'Search is temporarily unavailable.' }) + throw dependencyOutageError({ dependency: 'D1 and Vectorize', statusMessage: 'Search is temporarily unavailable.' }) const semanticKeys = semanticHits?.map(skillKey) ?? [] const expansionKeys = expansionHits?.map(skillKey) ?? [] diff --git a/nuxt.config.ts b/nuxt.config.ts index b6b8dafe..33ff2508 100644 --- a/nuxt.config.ts +++ b/nuxt.config.ts @@ -513,9 +513,9 @@ export default defineNuxtConfig({ binding: 'KV_DATA', }, 'cache': { - // Best-effort route-cache writes over KV_CACHE: the driver wraps + // Best-effort route-cache reads and writes over KV_CACHE: the driver wraps // unstorage's cloudflare-kv-binding, floors every TTL at Cloudflare's - // 60-second minimum, and turns write rejections into wide events + // 60-second minimum, and turns read and write rejections into wide events // instead of propagating them to Nitro's `captureError` (issue #156). driver: fileURLToPath(new URL('./server/runtime/kv-cache-storage.ts', import.meta.url)), binding: 'KV_CACHE', diff --git a/sentry.client.config.ts b/sentry.client.config.ts index 7480865e..ed53b93d 100644 --- a/sentry.client.config.ts +++ b/sentry.client.config.ts @@ -1,6 +1,6 @@ import { createSentryInitOptions } from '@harlan-zw/nuxt-sentry/server' import * as Sentry from '@sentry/nuxt' -import { isClosedBroadcastChannelError, isLocalReportingHost, scrubSentryBreadcrumb, scrubSentryEvent, SENTRY_DSN, SENTRY_TUNNEL_PATH } from './shared/sentry' +import { filterClientReport, isLocalReportingHost, scrubSentryBreadcrumb, scrubSentryEvent, SENTRY_DSN, SENTRY_TUNNEL_PATH } from './shared/sentry' if (!import.meta.dev && window.location.protocol === 'https:' && !isLocalReportingHost(window.location.hostname)) { // No `release` here on purpose. The Sentry bundler plugin injects the release @@ -30,15 +30,8 @@ if (!import.meta.dev && window.location.protocol === 'https:' && !isLocalReporti /Importing a module script failed/i, /error loading dynamically imported module/i, ], - // nuxt-skew-protection's multi-tab plugin closes its BroadcastChannel on - // app:error, and an in-flight version update can still post to it. The - // rejection is a benign tab-close race (SKILLD-12), so drop that one - // signature and keep every other error. - beforeSend(event, hint) { - const values = event.exception?.values ?? [] - if (isClosedBroadcastChannelError(hint.originalException) || values.some(isClosedBroadcastChannelError)) - return null - return scrubSentryEvent(event) - }, + // Drops the closed BroadcastChannel race (SKILLD-12), cancelled requests, + // and other reports that name no site defect. See `filterClientReport`. + beforeSend: filterClientReport, }) } diff --git a/server/plugins/sentry.ts b/server/plugins/sentry.ts index 075fb5b8..1d3e2d94 100644 --- a/server/plugins/sentry.ts +++ b/server/plugins/sentry.ts @@ -1,10 +1,11 @@ import { createSentryInitOptions } from '@harlan-zw/nuxt-sentry/server' import { SDK_VERSION } from '@sentry/cloudflare' import { sentryCloudflareNitroPlugin } from '@sentry/nuxt/module/plugins' -import { isBestEffortCacheWriteError, isExpectedUpstreamOutageError, isMcpAcceptProbeError, isMcpProtocolProbeError, scrubSentryBreadcrumb, scrubSentryEvent } from '../../shared/sentry' +import { isBestEffortCacheWriteError, isMcpAcceptProbeError, isMcpProtocolProbeError, scrubSentryBreadcrumb, scrubSentryEvent } from '../../shared/sentry' +import { isDependencyOutageError } from '../../shared/server/dependency-outage' function isDroppedSignature(error: unknown): boolean { - return isBestEffortCacheWriteError(error) || isExpectedUpstreamOutageError(error) || isMcpAcceptProbeError(error) || isMcpProtocolProbeError(error) + return isBestEffortCacheWriteError(error) || isDependencyOutageError(error) || isMcpAcceptProbeError(error) || isMcpProtocolProbeError(error) } export default defineNitroPlugin((nitroApp) => { @@ -26,9 +27,9 @@ export default defineNitroPlugin((nitroApp) => { traceLifecycle: 'static', beforeSendTransaction: scrubSentryEvent, // Nitro's route cache catches its own KV write failures and forwards the - // caught error here as unhandled (SKILLD-17). The registry handlers' - // intended upstream-outage 503s land here the same way (SKILLD-11, - // SKILLD-1E), as do MCP probe rejections: 406 (SKILLD-35) and 400 (SKILLD-3H). + // caught error here as unhandled (SKILLD-17). A handler's + // `dependencyOutageError` 503 lands here the same way (SKILLD-11, + // SKILLD-44), as do MCP probe rejections: 406 (SKILLD-35) and 400 (SKILLD-3H). // All are failure classes already answered or recorded, so drop the // duplicates and keep the wide events as the visibility path. beforeSend(event, hint) { diff --git a/server/runtime/kv-cache-storage.ts b/server/runtime/kv-cache-storage.ts index af5f231f..5e54e30d 100644 --- a/server/runtime/kv-cache-storage.ts +++ b/server/runtime/kv-cache-storage.ts @@ -27,8 +27,13 @@ export interface KvCacheStorageOptions { * * So a rejected write resolves and reports as a `cache-write` wide event * instead. This is not a silent catch: a KV outage stays visible as a rise in - * failed cache writes, and reads are untouched, so a failed read still behaves - * as a miss. + * failed cache writes. + * + * Reads follow the same rule. Nitro already treats a rejected read as a miss, + * then forwards the rejection to `captureError` too, so each `KV GET failed: + * 500` became an unhandled Sentry issue on a request that was still served + * (SKILLD-28). A rejected read resolves to a miss here and reports as a + * `cache-read` wide event, the event `readCache` already records. * * Every write carries a TTL of at least 60 seconds, the floor Cloudflare KV * enforces, matching the guarantee `@harlan-zw/nuxt-cloudflare`'s own cache @@ -40,7 +45,7 @@ export default defineDriver((options: KvCacheStorageOptions) => { throw new Error(`[kv-cache-storage] defaultTtl must be an integer of at least ${MIN_TTL_SECONDS} seconds, received ${options.defaultTtl}`) const driver = cloudflareKvBinding(options) - const { setItem } = driver + const { getItem, setItem } = driver if (!setItem) throw new Error('[kv-cache-storage] cloudflare-kv-binding driver must implement setItem') @@ -49,6 +54,17 @@ export default defineDriver((options: KvCacheStorageOptions) => { options, name: 'cloudflare-kv-cache', flags: { ...driver.flags, ttl: true }, + getItem(key, transactionOptions) { + return Promise.resolve(getItem(key, transactionOptions)).catch((error: unknown) => { + emitOperationalEvent(createWideEvent({ + 'operation': 'cache-read', + 'outcome': 'failed', + 'cache.readFailed': true, + 'reason': error instanceof Error ? error.message : String(error), + })) + return null + }) + }, setItem(key, value, transactionOptions = {}) { const requestedTtl = Number(transactionOptions.ttl) const ttl = Number.isFinite(requestedTtl) && requestedTtl > 0 diff --git a/shared/sentry.ts b/shared/sentry.ts index f570b14c..5b1ea3cf 100644 --- a/shared/sentry.ts +++ b/shared/sentry.ts @@ -1,4 +1,5 @@ -import type { Breadcrumb, Event } from '@sentry/nuxt' +import type { Breadcrumb, Event, EventHint } from '@sentry/nuxt' +import { isTransientError } from '@harlan-zw/nuxt-sentry/server' export const SENTRY_DSN = 'https://b275b367f8096d04db8c2ebcfadc3aba@o4510507748163584.ingest.us.sentry.io/4511781692506112' @@ -76,24 +77,6 @@ export function isBestEffortCacheWriteError(error: unknown): boolean { return typeof message === 'string' && message.startsWith('KV PUT failed:') } -/** - * The suffix shared by the intended upstream-outage 503s the registry handlers - * raise after `fetchUpstreamTree` or `fetchUpstreamText` reports the outage as - * an operational wide event ('Skill source is unavailable upstream', - * 'SKILL.md source is unavailable upstream', 'Asset source is unavailable - * upstream', Sentry SKILLD-11 and SKILLD-1E). Nitro forwards the thrown - * `createError` to Sentry as unhandled, so the capture duplicates a failure - * class the wide event already records. The server Sentry config drops that - * signature in `beforeSend`; every other error still reaches Sentry. - * - * The gone-source 410 ('Skill source is gone upstream') is a permanent - * verdict, not an outage, and does not carry the suffix, so it still lands. - */ -export function isExpectedUpstreamOutageError(error: unknown): boolean { - const message = sentryExceptionMessage(error) - return typeof message === 'string' && message.endsWith('unavailable upstream') -} - /** * The message Chrome rejects a `postMessage` on a closed `BroadcastChannel` * with (`InvalidStateError`, Sentry SKILLD-12). nuxt-skew-protection's @@ -108,6 +91,67 @@ export function isClosedBroadcastChannelError(error: unknown): boolean { return message === 'Failed to execute \'postMessage\' on \'BroadcastChannel\': Channel is closed' } +const CLIENT_NOISE_MESSAGE = /ResizeObserver loop|AsyncData request cancelled by |signal is aborted without reason|\/builds\/meta\/[\w-]+\.json": 404 / + +/** + * Browser reports that name no site defect. + * + * - `ResizeObserver loop ...`: a browser layout notice that `window.onerror` + * delivers as an error (SKILLD-5B). + * - A cancelled request: Nuxt aborts an AsyncData fetch that a newer call or an + * unmount replaced (SKILLD-4Q, SKILLD-4S, SKILLD-59). `isTransientError` is + * the rule every site using `@harlan-zw/nuxt-sentry` already applies. + * - A retired build's meta: a tab older than the skew protection window asks + * for its own build meta and gets 404 (SKILLD-4Y), the stale-deploy class + * `ignoreErrors` already drops for chunks. + */ +function isClientNoiseError(error: unknown): boolean { + if (isTransientError(error)) + return true + const message = sentryExceptionMessage(error) + return typeof message === 'string' && CLIENT_NOISE_MESSAGE.test(message) +} + +function isClientDroppedSignature(error: unknown): boolean { + return isClosedBroadcastChannelError(error) || isClientNoiseError(error) +} + +/** + * The kind of value a messageless error was thrown with, never its content. + * + * Nuxt wraps a thrown non-Error, such as a load `Event`, in an H3 error with + * an empty message, so the report reads "No error message" and loses the one + * fact that explains it (SKILLD-54). + */ +function describeThrownCause(error: unknown): string | undefined { + if (!(error instanceof Error) || error.message !== '' || error.cause === undefined) + return undefined + const cause = error.cause + if (typeof globalThis.Event === 'function' && cause instanceof globalThis.Event) { + const target = cause.target as { tagName?: unknown } | null + return typeof target?.tagName === 'string' ? `Event:${cause.type}:${target.tagName}` : `Event:${cause.type}` + } + if (cause instanceof Error) + return cause.name + if (typeof cause !== 'object' || cause === null) + return typeof cause + return Object.prototype.toString.call(cause).slice(8, -1) +} + +/** + * The browser `beforeSend`: drops the signatures above, tags what a + * messageless error was thrown with, and scrubs everything it keeps. + */ +export function filterClientReport(event: T, hint: EventHint): T | null { + const values = event.exception?.values ?? [] + if (isClientDroppedSignature(hint.originalException) || values.some(isClientDroppedSignature)) + return null + const thrownCause = describeThrownCause(hint.originalException) + if (thrownCause) + event.tags = { ...event.tags, 'thrown.cause': thrownCause } + return scrubSentryEvent(event) +} + /** * The message prefix the MCP streamable transport rejects a probe with * ('Not Acceptable: Client must accept text/event-stream' for an Accept-less diff --git a/shared/server/dependency-outage.ts b/shared/server/dependency-outage.ts new file mode 100644 index 00000000..671ac48b --- /dev/null +++ b/shared/server/dependency-outage.ts @@ -0,0 +1,45 @@ +import type { H3Error } from 'h3' +import { createError } from 'h3' + +/** The cause a dependency outage 503 carries. Sentry reads the tag, never the message. */ +export interface DependencyOutage { + _tag: 'DependencyOutage' + /** The service that failed, such as `raw.githubusercontent.com` or `d1`. */ + dependency: string +} + +export type DependencyOutageInput + = | { dependency: string, message: string } + | { dependency: string, statusMessage: string } + +/** + * The 503 a handler answers when a dependency it needs is down. + * + * Throw it only after a wide event has recorded the outage. Nitro forwards + * every thrown 5xx to Sentry as unhandled, and the server `beforeSend` drops + * this one by its cause, so the wide event stays the one record of the outage + * (Sentry SKILLD-11, SKILLD-1E, SKILLD-44, SKILLD-4Z). A 503 thrown any other + * way still reaches Sentry, because a missing binding or secret is a defect. + * + * The mark is structural on purpose. The filter used to match a message + * suffix, so every new outage message that did not end the same way reached + * Sentry as a new issue. + */ +export function dependencyOutageError(input: DependencyOutageInput): H3Error { + const { dependency, ...message } = input + const cause: DependencyOutage = { _tag: 'DependencyOutage', dependency } + return createError({ statusCode: 503, ...message, cause }) +} + +/** Whether an error, or any error in its cause chain, is a `dependencyOutageError`. */ +export function isDependencyOutageError(error: unknown): boolean { + const seen = new Set() + let current = error + while (typeof current === 'object' && current !== null && !seen.has(current)) { + seen.add(current) + if ((current as { _tag?: unknown })._tag === 'DependencyOutage') + return true + current = (current as { cause?: unknown }).cause + } + return false +} diff --git a/test/unit/nitro-cache-storage.test.ts b/test/unit/nitro-cache-storage.test.ts index ed69865e..e936a573 100644 --- a/test/unit/nitro-cache-storage.test.ts +++ b/test/unit/nitro-cache-storage.test.ts @@ -14,9 +14,9 @@ vi.mock('@harlan-zw/nuxt-wide-events/standalone', () => ({ }, })) -function kvNamespace(put: KVNamespace['put']): KVNamespace { +function kvNamespace(put: KVNamespace['put'], get: KVNamespace['get'] = vi.fn(async () => null) as unknown as KVNamespace['get']): KVNamespace { return { - get: vi.fn(async () => null), + get, put, delete: vi.fn(async () => {}), } as unknown as KVNamespace @@ -50,6 +50,26 @@ describe('kv-cache-storage driver', () => { vi.unstubAllGlobals() }) + it('reads a KV outage as a miss and reports it as a failed cache read', async () => { + const get = vi.fn(async () => { + throw new Error('KV GET failed: 500 Internal Server Error') + }) + vi.stubGlobal('KV_CACHE_TEST', kvNamespace(vi.fn(async () => {}), get as unknown as KVNamespace['get'])) + + const storage = createStorage() + storage.mount('cache', kvCacheDriver({ binding: 'KV_CACHE_TEST', defaultTtl: 120 })) + + await expect(storage.getItem('cache:nitro:handlers:repo:tag-network.json')).resolves.toBeNull() + expect(emitted).toEqual([{ + 'operation': 'cache-read', + 'outcome': 'failed', + 'cache.readFailed': true, + 'reason': 'KV GET failed: 500 Internal Server Error', + }]) + + vi.unstubAllGlobals() + }) + it('applies the default TTL when the caller requests none', async () => { const put = vi.fn(async () => {}) vi.stubGlobal('KV_CACHE_TEST', kvNamespace(put as unknown as KVNamespace['put'])) diff --git a/test/unit/pnpm-package-cache.test.ts b/test/unit/pnpm-package-cache.test.ts index c39d0025..1514b6b0 100644 --- a/test/unit/pnpm-package-cache.test.ts +++ b/test/unit/pnpm-package-cache.test.ts @@ -1,13 +1,15 @@ import type { H3Event } from 'h3' import type { SqliteD1 } from './helpers/d1-sqlite' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { isDependencyOutageError } from '../../shared/server/dependency-outage' import { tarGzFixture } from '../fixtures/tar-archive' import { allMigrations, createSqliteD1 } from './helpers/d1-sqlite' describe('package detection cache', () => { let harness: SqliteD1 let handler: (event: H3Event) => Promise - let failure: 'oversized' | 'upstream' | null + let failure: 'oversized' | 'upstream' | 'rate-limited' | null + let emitOperationalEvent: ReturnType let archiveReads: number let manifestReads: number @@ -19,6 +21,9 @@ describe('package detection cache', () => { vi.stubGlobal('getUserSession', () => Promise.resolve(null)) vi.stubGlobal('getQuery', () => ({})) vi.stubGlobal('getRouterParam', () => 'acme/kit/auth') + emitOperationalEvent = vi.fn() + vi.stubGlobal('emitOperationalEvent', emitOperationalEvent) + vi.stubGlobal('createWideEvent', (fields: Record) => fields) const entries = new Map() vi.stubGlobal('useStorage', () => ({ getItem: async (key: string) => entries.get(key) ?? null, @@ -35,6 +40,8 @@ describe('package detection cache', () => { const url = String(input) if (url.includes('raw.githubusercontent.com')) { manifestReads++ + if (failure === 'rate-limited') + return new Response(null, { status: 429 }) return Response.json({ name: 'kit', version: '1.0.0' }) } if (url.endsWith('/latest')) { @@ -82,6 +89,15 @@ describe('package detection cache', () => { expect(manifestReads).toBe(3) }) + it('answers a GitHub rate limit as a recorded dependency outage (SKILLD-44)', async () => { + failure = 'rate-limited' + const error: unknown = await handler(event()).catch((thrown: unknown) => thrown) + + expect(error).toMatchObject({ statusCode: 503 }) + expect(isDependencyOutageError(error)).toBe(true) + expect(emitOperationalEvent).toHaveBeenCalledWith({ operation: 'skill-package-detect', outcome: 'failed' }) + }) + it('caches a Skill outside the package layout for one hour', async () => { harness.raw.prepare('UPDATE skills SET rendered_skill_path = \'SKILL.md\'').run() await expect(handler(event())).resolves.toEqual({ _tag: 'Absent' }) diff --git a/test/unit/sentry-cache-write-filter.nuxt.test.ts b/test/unit/sentry-cache-write-filter.nuxt.test.ts index 448a2b5c..673231df 100644 --- a/test/unit/sentry-cache-write-filter.nuxt.test.ts +++ b/test/unit/sentry-cache-write-filter.nuxt.test.ts @@ -1,5 +1,7 @@ +import { createError } from 'h3' import { beforeEach, describe, expect, it, vi } from 'vitest' -import { isBestEffortCacheWriteError, isClosedBroadcastChannelError, isExpectedUpstreamOutageError, isMcpAcceptProbeError } from '../../shared/sentry' +import { isBestEffortCacheWriteError, isClosedBroadcastChannelError, isMcpAcceptProbeError } from '../../shared/sentry' +import { dependencyOutageError, isDependencyOutageError } from '../../shared/server/dependency-outage' describe('isClosedBroadcastChannelError', () => { const closed = 'Failed to execute \'postMessage\' on \'BroadcastChannel\': Channel is closed' @@ -56,29 +58,25 @@ describe('isBestEffortCacheWriteError', () => { }) }) -describe('isExpectedUpstreamOutageError', () => { - it('matches the three upstream-outage 503 signatures the handlers throw', () => { - expect(isExpectedUpstreamOutageError(new Error('Skill source is unavailable upstream'))).toBe(true) - expect(isExpectedUpstreamOutageError(new Error('SKILL.md source is unavailable upstream'))).toBe(true) - expect(isExpectedUpstreamOutageError(new Error('Asset source is unavailable upstream'))).toBe(true) +describe('isDependencyOutageError', () => { + it('matches the 503 a handler raises for a dependency outage it already recorded', () => { + expect(isDependencyOutageError(dependencyOutageError({ dependency: 'raw.githubusercontent.com', message: 'Package details are unavailable. Try again later.' }))).toBe(true) + expect(isDependencyOutageError(dependencyOutageError({ dependency: 'search lanes', statusMessage: 'Search is temporarily unavailable.' }))).toBe(true) }) - it('matches the Sentry-serialized exception, whose message arrives as value', () => { - expect(isExpectedUpstreamOutageError({ - type: 'Error', - value: 'SKILL.md source is unavailable upstream', - mechanism: { handled: false, type: 'auto.function.nuxt.nitro' }, - })).toBe(true) + it('answers 503 and keeps the message the client reads', () => { + expect(dependencyOutageError({ dependency: 'raw.githubusercontent.com', message: 'Asset source is unavailable upstream' })) + .toMatchObject({ statusCode: 503, message: 'Asset source is unavailable upstream' }) }) - it('ignores the gone-source 410, a permanent verdict rather than an outage', () => { - expect(isExpectedUpstreamOutageError(new Error('Skill source is gone upstream'))).toBe(false) + it('ignores a 503 without the mark, whatever its message says', () => { + expect(isDependencyOutageError(createError({ statusCode: 503, message: 'Asset source is unavailable upstream' }))).toBe(false) + expect(isDependencyOutageError(createError({ statusCode: 503, message: 'Check-in bindings or deployment identity are missing.' }))).toBe(false) }) - it('ignores unrelated errors and values that are not errors', () => { - expect(isExpectedUpstreamOutageError(new Error('KV PUT failed: 429 Too Many Requests'))).toBe(false) - expect(isExpectedUpstreamOutageError('Skill source is unavailable upstream')).toBe(false) - expect(isExpectedUpstreamOutageError(undefined)).toBe(false) + it('ignores values that are not errors', () => { + expect(isDependencyOutageError({ type: 'Error', value: 'Package details are unavailable. Try again later.' })).toBe(false) + expect(isDependencyOutageError(undefined)).toBe(false) }) }) @@ -151,19 +149,18 @@ describe('sentry beforeSend cache-write filter', () => { expect(beforeSend(event, {})).toBeNull() }) - it('drops the intended upstream-outage 503 the handler already reported as a wide event', () => { - const event: SentryEventFixture = { - exception: { values: [{ type: 'Error', value: 'Skill source is unavailable upstream' }] }, - } - expect(beforeSend(event, { originalException: new Error('Skill source is unavailable upstream') })) - .toBeNull() + it.each([ + { issue: 'SKILLD-44', dependency: 'raw.githubusercontent.com', message: 'Package details are unavailable. Try again later.' }, + { issue: 'SKILLD-11', dependency: 'raw.githubusercontent.com', message: 'Asset source is unavailable upstream' }, + ])('drops the dependency outage 503 a handler already recorded ($issue)', ({ dependency, message }) => { + const event: SentryEventFixture = { exception: { values: [{ type: 'Error', value: message }] } } + expect(beforeSend(event, { originalException: dependencyOutageError({ dependency, message }) })).toBeNull() }) - it('drops the outage on the serialized exception alone, when the original error is absent', () => { - const event: SentryEventFixture = { - exception: { values: [{ type: 'Error', value: 'Asset source is unavailable upstream' }] }, - } - expect(beforeSend(event, {})).toBeNull() + it('keeps a 503 that carries no outage mark, such as missing deployment bindings', () => { + const message = 'Check-in bindings or deployment identity are missing.' + const event: SentryEventFixture = { exception: { values: [{ type: 'Error', value: message }] } } + expect(beforeSend(event, { originalException: createError({ statusCode: 503, message }) })).toBe(event) }) it('drops the intended MCP 406 the transport already answered to the probe', () => { diff --git a/test/unit/sentry-client-report.test.ts b/test/unit/sentry-client-report.test.ts new file mode 100644 index 00000000..f2a57b2f --- /dev/null +++ b/test/unit/sentry-client-report.test.ts @@ -0,0 +1,51 @@ +import type { Event } from '@sentry/nuxt' +import { createError } from 'h3' +import { describe, expect, it } from 'vitest' +import { filterClientReport } from '../../shared/sentry' + +function report(type: string, value: string): Event { + return { exception: { values: [{ type, value }] } } +} + +function namedError(name: string, message: string): Error { + return Object.assign(new Error(message), { name }) +} + +describe('filterClientReport', () => { + it.each([ + { issue: 'SKILLD-5B', thrown: 'ResizeObserver loop limit exceeded', event: report('Error', 'ResizeObserver loop limit exceeded') }, + { issue: 'SKILLD-4Q', thrown: new DOMException('AsyncData request cancelled by deduplication', 'AbortError'), event: report('AbortError', 'AsyncData request cancelled by deduplication') }, + { issue: 'SKILLD-4W', thrown: new Error('AbortError: AsyncData request cancelled by deduplication'), event: report('Error', 'AbortError: AsyncData request cancelled by deduplication') }, + { issue: 'SKILLD-4T', thrown: namedError('FetchError', '[GET] "/api/feed/trending?limit=30": AsyncData request cancelled by unmount'), event: report('FetchError', '[GET] "/api/feed/trending?limit=30": AsyncData request cancelled by unmount') }, + { issue: 'SKILLD-59', thrown: new DOMException('signal is aborted without reason', 'AbortError'), event: report('AbortError', 'signal is aborted without reason') }, + { issue: 'SKILLD-4Y', thrown: namedError('FetchError', '[GET] "/_nuxt/v2/builds/meta/f992d060-9682-4700-9b5e-fb06ae8e7456.json": 404 Not Found'), event: report('FetchError', '[GET] "/_nuxt/v2/builds/meta/f992d060-9682-4700-9b5e-fb06ae8e7456.json": 404 Not Found') }, + ])('drops the $issue report that names no site defect', ({ thrown, event }) => { + expect(filterClientReport(event, { originalException: thrown })).toBeNull() + expect(filterClientReport(structuredClone(event), {})).toBeNull() + }) + + it.each([ + { issue: 'SKILLD-4P', event: report('TypeError', 'e.toSorted is not a function') }, + { issue: 'SKILLD-4N', event: report('TypeError', 'Failed to fetch') }, + { issue: 'server error', event: report('FetchError', '[GET] "/api/skills": 500 Internal Server Error') }, + { issue: 'current build', event: report('FetchError', '[GET] "/_nuxt/v2/builds/latest.json": 404 Not Found') }, + ])('keeps the $issue report', ({ event }) => { + expect(filterClientReport(event, {})).toBe(event) + }) + + // Nuxt's `createErrorFromThrown` hands the thrown value to h3's `createError`, as here. + it('names what a messageless error was thrown with, and never its content (SKILLD-54)', () => { + const loadFailure = new globalThis.Event('error') + Object.defineProperty(loadFailure, 'target', { value: { tagName: 'SCRIPT', src: 'https://skilld.dev/_nuxt/v2/BzUDwpzU.js' } }) + const fromEvent = filterClientReport(report('Error', ''), { originalException: createError(loadFailure as never) }) + expect(fromEvent?.tags).toEqual({ 'thrown.cause': 'Event:error:SCRIPT' }) + + const fromObject = filterClientReport(report('Error', ''), { originalException: createError({ secret: 'value' } as never) }) + expect(fromObject?.tags).toEqual({ 'thrown.cause': 'Object' }) + }) + + it('leaves the tags alone when the error carries its own message', () => { + const event = report('Error', 'Skill not found') + expect(filterClientReport(event, { originalException: new Error('Skill not found', { cause: new globalThis.Event('error') }) })?.tags).toBeUndefined() + }) +}) diff --git a/test/unit/signup-click-proof.test.ts b/test/unit/signup-click-proof.test.ts index 84b04b2b..b5c7c598 100644 --- a/test/unit/signup-click-proof.test.ts +++ b/test/unit/signup-click-proof.test.ts @@ -91,6 +91,37 @@ describe('anonymous click proof', () => { expect(limit).toHaveBeenLastCalledWith({ key: 'signup-click:192.0.2.1' }) }) + // SKILLD-42 and SKILLD-5H: D1 does not retry a write, so one lost connection failed the request. + it.each([ + { lost: 'before the batch ran', commits: false }, + { lost: 'after the batch committed', commits: true }, + ])('issues one usable proof when D1 loses the connection $lost', async ({ commits }) => { + let failed = false + const db = new Proxy(d1.db, { + get(target, property, receiver) { + if (property !== 'batch') + return Reflect.get(target, property, receiver) + return async (statements: D1PreparedStatement[]) => { + if (failed) + return target.batch(statements) + failed = true + if (commits) + await target.batch(statements) + throw new Error('D1_ERROR: Network connection lost.') + } + }, + }) + const request = event() + request.context.platform.db = db + + const issued = issueSignupClickProof(request) + await vi.runAllTimersAsync() + const nonce = await issued + + expect(d1.raw.prepare('SELECT nonce FROM signup_click_proofs').all()).toEqual([{ nonce }]) + await expect(consumeSignupClickProof(event({ 'x-signup-proof': nonce! }))).resolves.toBe(true) + }) + it('removes expired nonce rows when preparing the next page', async () => { const old = await issueSignupClickProof(event()) vi.advanceTimersByTime(300_000)