@aglyn/tenant-data-admin 1.13.0 → 1.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/scope-sharing-sweep.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * KEEPING \"ALL SITES EXCEPT…\" TRUE AS SITES COME AND GO (AGL-4047).\n *\n * A document shared this way names its included sites in `visibleTo`, the one\n * field readers enforce. A new site therefore has to be added to it, and a\n * site that left has to come off it. {@link sweepScopeSharingAfterSiteChange}\n * does that after every change to `orgs/{orgId}.hosts`: a site created, moved\n * in or out, or erased.\n *\n * ## What it costs when nothing is marked\n *\n * One query per declared collection, each answering nothing, and not one\n * write. Every workspace pays that on a site change and nothing more, which\n * is why a sweep document is only written once a marked document turns up.\n *\n * ## Each document in its own transaction, reading the org document\n *\n * The transaction reads `orgs/{orgId}` as well as the document, so what it\n * writes is computed from the sites that are true at commit. A site claimed\n * while the sweep runs either serializes before it (and the sweep sees the\n * site) or after it (and the sweep that claim starts sees the document).\n *\n * ## Inline for a few seconds, then the job\n *\n * The caller is a person creating or deleting a site, so a trigger works for\n * {@link INLINE_BUDGET_MS} and leaves the rest to the job, from a cursor in\n * `orgs/{orgId}/scopeSweeps/{sweepId}`. That document exists only while work\n * is left, so the job's query answers nothing on a quiet beat. No rule opens\n * the path: only this server code reads or writes it.\n *\n * Every step is idempotent. A second sweep, or a resumed one going over a\n * document again, reads `current` and writes nothing.\n */\n\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport {\n reconcileAllExcept,\n SCOPE_MODE_ALL_EXCEPT,\n type ScopeSharingFields,\n} from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { runPluginDeclarationsRepair } from '@aglyn/aglyn/plugin-manager/plugin-declarations-repair'\nimport {\n listScopeSharingCollections,\n type ResolvedScopeSharingCollection,\n scopeSharingPatchFor,\n} from '@aglyn/aglyn/plugin-manager/plugin-scope-sharing'\nimport {\n type CollectionReference,\n type DocumentReference,\n FieldPath,\n FieldValue,\n type Firestore,\n type QueryDocumentSnapshot,\n type QuerySnapshot,\n} from 'firebase-admin/firestore'\nimport firebaseAdmin from './firebase-admin'\n\n/** Where a sweep with work left records its cursor. */\nexport const SCOPE_SWEEPS_COLLECTION = 'scopeSweeps'\n/** Marked documents read at a time in one collection. */\nconst PAGE_SIZE = 100\n/** Transactions running at once. */\nconst CONCURRENCY = 8\n/** How long a person's site change waits for the sweep. */\nexport const INLINE_BUDGET_MS = 3_000\n/** How long one job beat spends, across every sweep it takes. */\nexport const JOB_BUDGET_MS = 20_000\n/** Sweeps one beat reads. */\nconst SWEEPS_PER_BEAT = 10\n/** Beats a failing sweep gets. The weekly drift report still counts its documents. */\nexport const MAX_SWEEP_ATTEMPTS = 5\n\nexport type ScopeSweepReason = 'site-added' | 'site-removed' | 'drift-repair'\n\nexport interface ScopeSweepCounts {\n /** Marked documents read. */\n marked: number\n /** Written because they had fallen behind. */\n changed: number\n /** Past their collection's limit, and so no longer widening. */\n capped: number\n /** A marker the helper cannot act on: left alone, and reported. */\n invalid: number\n /** A transaction or patch that threw. */\n failed: number\n}\n\nexport interface ScopeSweepResult extends ScopeSweepCounts {\n /** Every declared collection was walked to its end. */\n complete: boolean\n /** Where to carry on from, when `complete` is false. */\n cursor: ScopeSweepCursor | null\n}\n\n/** A position in {@link listScopeSharingCollections}. */\nexport interface ScopeSweepCursor {\n collection: string\n afterId: string | null\n}\n\nconst emptyCounts = (): ScopeSweepCounts => ({\n marked: 0,\n changed: 0,\n capped: 0,\n invalid: 0,\n failed: 0,\n})\n\nconst platformFirestore = () => firebaseAdmin.app().firestore() as unknown as Firestore\n\n/** The sites `orgs/{orgId}.hosts` names. */\nexport function orgHostIdsFromDoc(org: Readonly<Record<string, unknown>> | undefined): string[] {\n const hosts = org?.['hosts']\n if (!hosts || typeof hosts !== 'object' || Array.isArray(hosts)) return []\n return Object.entries(hosts as Record<string, unknown>)\n .filter(([, on]) => Boolean(on))\n .map(([hostId]) => hostId)\n}\n\n/** The sites a document keeps whatever it excludes, per its declaration. */\nfunction keptHostIds(\n declared: ResolvedScopeSharingCollection,\n doc: Readonly<Record<string, unknown>>,\n): string[] {\n const kept: string[] = []\n for (const field of declared.keepSiteFields ?? []) {\n const value = doc[field]\n if (typeof value === 'string' && value) kept.push(value)\n if (Array.isArray(value)) {\n for (const id of value) if (typeof id === 'string' && id) kept.push(id)\n }\n }\n return kept\n}\n\n/** The marked documents of one collection, in the order a cursor can resume. */\nfunction markedPage(collectionRef: CollectionReference, afterId: string | null): Promise<QuerySnapshot> {\n const ordered = collectionRef\n .where('scopeMode', '==', SCOPE_MODE_ALL_EXCEPT)\n .orderBy(FieldPath.documentId())\n return (afterId ? ordered.startAfter(afterId) : ordered).limit(PAGE_SIZE).get()\n}\n\n/** Runs `work` over `items`, at most {@link CONCURRENCY} at a time. */\nasync function eachConcurrently<T>(\n items: readonly T[],\n work: (item: T) => Promise<void>,\n): Promise<void> {\n let next = 0\n await Promise.all(\n Array.from({ length: Math.min(CONCURRENCY, items.length) }, async () => {\n while (next < items.length) {\n const item = items[next]\n next += 1\n await work(item)\n }\n }),\n )\n}\n\n/** A write's data: a `null` marker field is deleted, never stored. */\nfunction fieldsToWrite(fields: ScopeSharingFields): Record<string, unknown> {\n return {\n visibleTo: fields.visibleTo,\n scopeMode: fields.scopeMode ?? FieldValue.delete(),\n scopeExcept: fields.scopeExcept ?? FieldValue.delete(),\n }\n}\n\n/** The document as it will read after the write, for a patch to work from. */\nfunction asStored(\n data: Readonly<Record<string, unknown>>,\n fields: ScopeSharingFields,\n): Record<string, unknown> {\n const next: Record<string, unknown> = { ...data, visibleTo: fields.visibleTo }\n if (fields.scopeMode) {\n next['scopeMode'] = fields.scopeMode\n next['scopeExcept'] = fields.scopeExcept\n } else {\n delete next['scopeMode']\n delete next['scopeExcept']\n }\n return next\n}\n\n/** Brings one marked document level, in its own transaction. */\nasync function reconcileDocument(\n db: Firestore,\n orgRef: DocumentReference,\n declared: ResolvedScopeSharingCollection,\n docRef: DocumentReference,\n counts: ScopeSweepCounts,\n): Promise<void> {\n const status = await db.runTransaction(async (tx) => {\n const [org, doc] = await tx.getAll(orgRef, docRef)\n // The workspace went while this ran, and the document with it.\n if (!org.exists || !doc.exists) return 'current'\n const data = doc.data() as Record<string, unknown>\n const answer = reconcileAllExcept(data, orgHostIdsFromDoc(org.data()), {\n maxIncluded: declared.maxIncluded ?? null,\n keepHostIds: keptHostIds(declared, data),\n })\n if (answer.fields) {\n const patch = declared.patch\n ? await requiredPatch(declared.name)(declared.name, asStored(data, answer.fields))\n : {}\n // Not an edit, so `updatedAt` stays: a list ordered by it must not\n // reshuffle because a site was added somewhere in the workspace.\n tx.update(docRef, { ...fieldsToWrite(answer.fields), ...patch })\n }\n return answer.status\n })\n if (status === 'changed') counts.changed += 1\n if (status === 'capped') counts.capped += 1\n if (status === 'invalid') counts.invalid += 1\n}\n\nfunction requiredPatch(collection: string) {\n const patch = scopeSharingPatchFor(collection)\n if (!patch) throw new Error(`no scope-sharing patch is registered for ${collection}`)\n return patch\n}\n\n/**\n * A declared patch is missing where the boot step has not run. Runs it once,\n * and only when a marked document needs one, so a sweep that finds nothing\n * never pays for it.\n */\nasync function ensurePatches(\n collections: readonly ResolvedScopeSharingCollection[],\n): Promise<void> {\n if (collections.every((row) => !row.patch || scopeSharingPatchFor(row.name))) return\n await runPluginDeclarationsRepair().catch((error: unknown) => {\n console.error('[scope-sweep] the declarations repair failed', error)\n })\n}\n\nexport interface RunScopeSharingSweepInput {\n orgId: string\n /** Stops starting new work past this; omit to walk to the end. */\n budgetMs?: number\n /** Resume from here. */\n from?: ScopeSweepCursor | null\n /**\n * Called the first time a marked document turns up, so a sweep that finds\n * nothing writes nothing. A trigger records its sweep document here.\n */\n onFirstMarked?: () => Promise<void>\n firestore?: Firestore\n}\n\n/**\n * Walks every declared collection's marked documents and brings each level.\n * Throws only on a failed query; one document failing is counted and the walk\n * goes on, and an incomplete walk answers where it stopped.\n */\nexport async function runScopeSharingSweep(\n input: RunScopeSharingSweepInput,\n): Promise<ScopeSweepResult> {\n const db = input.firestore ?? platformFirestore()\n const orgRef = db.collection('orgs').doc(input.orgId)\n const collections = listScopeSharingCollections()\n const startAt = input.from\n ? Math.max(0, collections.findIndex((row) => row.name === input.from?.collection))\n : 0\n const remaining = collections.slice(startAt)\n const deadline = input.budgetMs == null ? null : Date.now() + input.budgetMs\n const counts = emptyCounts()\n\n // Every collection's first page at once, so the common answer of nothing\n // costs one round of queries rather than one after another.\n const pages = new Map<string, QueryDocumentSnapshot[]>()\n const firstAfter = (name: string) =>\n input.from && input.from.collection === name ? input.from.afterId : null\n await eachConcurrently(remaining, async (declared) => {\n const snapshot = await markedPage(orgRef.collection(declared.name), firstAfter(declared.name))\n pages.set(declared.name, snapshot.docs)\n })\n if ([...pages.values()].every((docs) => !docs.length)) {\n return { ...counts, complete: true, cursor: null }\n }\n await input.onFirstMarked?.()\n await ensurePatches(remaining)\n\n for (const declared of remaining) {\n let docs = pages.get(declared.name) ?? []\n let afterId = firstAfter(declared.name)\n while (docs.length) {\n if (deadline != null && Date.now() >= deadline) {\n return { ...counts, complete: false, cursor: { collection: declared.name, afterId } }\n }\n counts.marked += docs.length\n await eachConcurrently(docs, async (doc) => {\n try {\n await reconcileDocument(db, orgRef, declared, doc.ref, counts)\n } catch (error) {\n counts.failed += 1\n console.error(`[scope-sweep] ${declared.name}/${doc.id} in ${input.orgId} was not brought level`, error)\n }\n })\n afterId = docs[docs.length - 1].id\n if (docs.length < PAGE_SIZE) break\n docs = (await markedPage(orgRef.collection(declared.name), afterId)).docs\n }\n }\n return { ...counts, complete: true, cursor: null }\n}\n\n/**\n * What a change to a workspace's sites runs, once the change has committed.\n *\n * NEVER THROWS, because the site change is done and is what the person asked\n * for. Work it could not finish is left in a sweep document for the job, and\n * if even that write fails the weekly drift report finds what is behind.\n */\nexport async function sweepScopeSharingAfterSiteChange(input: {\n orgId: string\n reason: ScopeSweepReason\n hostId?: string\n firestore?: Firestore\n}): Promise<void> {\n const { orgId, reason, hostId } = input\n let sweepRef: DocumentReference | null = null\n const leaveForTheJob = async (cursor: ScopeSweepCursor | null, attempts: number) => {\n const db = input.firestore ?? platformFirestore()\n sweepRef ??= db.collection('orgs').doc(orgId).collection(SCOPE_SWEEPS_COLLECTION).doc(createResourceUid())\n await sweepRef.set({\n reason,\n ...(hostId ? { hostId } : {}),\n cursor,\n attempts,\n createdAtMs: Date.now(),\n })\n }\n try {\n const result = await runScopeSharingSweep({\n orgId,\n budgetMs: INLINE_BUDGET_MS,\n ...(input.firestore ? { firestore: input.firestore } : {}),\n onFirstMarked: () => leaveForTheJob(null, 0),\n })\n if (!result.complete) {\n await leaveForTheJob(result.cursor, 0)\n return\n }\n if (result.failed) {\n await leaveForTheJob(null, 1)\n return\n }\n await sweepRef?.delete()\n } catch (error) {\n console.error(`[scope-sweep] the sweep of ${orgId} after ${reason} did not finish`, error)\n await leaveForTheJob(null, 1).catch((writeError: unknown) => {\n console.error(`[scope-sweep] could not leave ${orgId}'s sweep for the job`, writeError)\n })\n }\n}\n\n/**\n * Carries on every unfinished sweep: the job's handler. A sweep document exists\n * only while work is left, so the unfiltered query needs no index and answers\n * nothing on a quiet beat, for one read.\n */\nexport async function resumeScopeSweeps(\n options: { budgetMs?: number; firestore?: Firestore } = {},\n): Promise<{ resumed: number; finished: number; droppedAfterFailing: number }> {\n const db = options.firestore ?? platformFirestore()\n const pending = await db.collectionGroup(SCOPE_SWEEPS_COLLECTION).limit(SWEEPS_PER_BEAT).get()\n const tally = { resumed: 0, finished: 0, droppedAfterFailing: 0 }\n const deadline = Date.now() + (options.budgetMs ?? JOB_BUDGET_MS)\n for (const sweep of pending.docs) {\n const budgetMs = deadline - Date.now()\n if (budgetMs <= 0) break\n tally.resumed += 1\n const orgRef = sweep.ref.parent.parent\n const attempts = Number(sweep.get('attempts') ?? 0)\n try {\n const org = orgRef ? await orgRef.get() : null\n // The workspace was erased after this was left. Nothing to bring level.\n if (!org?.exists) {\n await sweep.ref.delete()\n tally.finished += 1\n continue\n }\n const result = await runScopeSharingSweep({\n orgId: org.id,\n budgetMs,\n from: (sweep.get('cursor') as ScopeSweepCursor | null | undefined) ?? null,\n firestore: db,\n })\n if (!result.complete) {\n await sweep.ref.update({ cursor: result.cursor })\n continue\n }\n if (!result.failed) {\n await sweep.ref.delete()\n tally.finished += 1\n continue\n }\n throw new Error(`${result.failed} document(s) failed`)\n } catch (error) {\n console.error(`[scope-sweep] ${sweep.ref.path} failed on attempt ${attempts + 1}`, error)\n if (attempts + 1 >= MAX_SWEEP_ATTEMPTS) {\n // Stops holding a place in the beat. What it left behind is what the\n // weekly drift report counts, and that report goes to staff.\n await sweep.ref.delete().catch(() => undefined)\n tally.droppedAfterFailing += 1\n } else {\n await sweep.ref.update({ attempts: attempts + 1, cursor: null }).catch(() => undefined)\n }\n }\n }\n return tally\n}\n\n/** What the weekly report asks of one workspace. Reads only. */\nexport interface ScopeSharingDrift {\n /** Marked documents read. */\n marked: number\n /** Should read differently from how they read: what a sweep would write. */\n stale: number\n /** Past their collection's limit. A known state, reported and not alarmed. */\n capped: number\n /** A marker that cannot be acted on. */\n invalid: number\n}\n\nexport function emptyScopeSharingDrift(): ScopeSharingDrift {\n return { marked: 0, stale: 0, capped: 0, invalid: 0 }\n}\n\n/**\n * How far one workspace's marked documents are from what a sweep would write,\n * with the same helper the sweep uses. One query per declared collection when\n * nothing is marked.\n */\nexport async function scopeSharingDriftForOrg(\n orgRef: DocumentReference,\n orgData: Readonly<Record<string, unknown>> | undefined,\n): Promise<ScopeSharingDrift> {\n const drift = emptyScopeSharingDrift()\n const hostIds = orgHostIdsFromDoc(orgData)\n await eachConcurrently(listScopeSharingCollections(), async (declared) => {\n let afterId: string | null = null\n for (;;) {\n const page: QuerySnapshot = await markedPage(orgRef.collection(declared.name), afterId)\n for (const doc of page.docs) {\n const data = doc.data() as Record<string, unknown>\n const answer = reconcileAllExcept(data, hostIds, {\n maxIncluded: declared.maxIncluded ?? null,\n keepHostIds: keptHostIds(declared, data),\n })\n drift.marked += 1\n if (answer.status === 'invalid') drift.invalid += 1\n if (answer.status === 'capped') drift.capped += 1\n if (answer.fields) drift.stale += 1\n }\n if (page.docs.length < PAGE_SIZE) return\n afterId = page.docs[page.docs.length - 1].id\n }\n })\n return drift\n}\n"],"names":["createResourceUid","reconcileAllExcept","SCOPE_MODE_ALL_EXCEPT","runPluginDeclarationsRepair","listScopeSharingCollections","scopeSharingPatchFor","FieldPath","FieldValue","firebaseAdmin","SCOPE_SWEEPS_COLLECTION","PAGE_SIZE","CONCURRENCY","INLINE_BUDGET_MS","JOB_BUDGET_MS","SWEEPS_PER_BEAT","MAX_SWEEP_ATTEMPTS","emptyCounts","marked","changed","capped","invalid","failed","platformFirestore","app","firestore","orgHostIdsFromDoc","org","hosts","Array","isArray","Object","entries","filter","on","Boolean","map","hostId","keptHostIds","declared","doc","kept","field","keepSiteFields","value","push","id","markedPage","collectionRef","afterId","ordered","where","orderBy","documentId","startAfter","limit","get","eachConcurrently","items","work","next","Promise","all","from","length","Math","min","item","fieldsToWrite","fields","visibleTo","scopeMode","delete","scopeExcept","asStored","data","reconcileDocument","db","orgRef","docRef","counts","status","runTransaction","tx","getAll","exists","answer","maxIncluded","keepHostIds","patch","requiredPatch","name","update","collection","Error","ensurePatches","collections","every","row","catch","error","console","runScopeSharingSweep","input","orgId","startAt","max","findIndex","remaining","slice","deadline","budgetMs","Date","now","pages","Map","firstAfter","snapshot","set","docs","values","complete","cursor","onFirstMarked","ref","sweepScopeSharingAfterSiteChange","reason","sweepRef","leaveForTheJob","attempts","createdAtMs","result","writeError","resumeScopeSweeps","options","pending","collectionGroup","tally","resumed","finished","droppedAfterFailing","sweep","parent","Number","path","undefined","emptyScopeSharingDrift","stale","scopeSharingDriftForOrg","orgData","drift","hostIds","page"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgCC,GAED,SAASA,iBAAiB,QAAQ,6CAA4C;AAC9E,SACEC,kBAAkB,EAClBC,qBAAqB,QAEhB,sCAAqC;AAC5C,SAASC,2BAA2B,QAAQ,yDAAwD;AACpG,SACEC,2BAA2B,EAE3BC,oBAAoB,QACf,mDAAkD;AACzD,SAGEC,SAAS,EACTC,UAAU,QAIL,2BAA0B;AACjC,OAAOC,mBAAmB,sBAAkB;AAE5C,qDAAqD,GACrD,OAAO,MAAMC,0BAA0B,cAAa;AACpD,uDAAuD,GACvD,MAAMC,YAAY;AAClB,kCAAkC,GAClC,MAAMC,cAAc;AACpB,yDAAyD,GACzD,OAAO,MAAMC,mBAAmB,KAAK;AACrC,+DAA+D,GAC/D,OAAO,MAAMC,gBAAgB,MAAM;AACnC,2BAA2B,GAC3B,MAAMC,kBAAkB;AACxB,oFAAoF,GACpF,OAAO,MAAMC,qBAAqB,EAAC;AA8BnC,MAAMC,cAAc,IAAyB,CAAA;QAC3CC,QAAQ;QACRC,SAAS;QACTC,QAAQ;QACRC,SAAS;QACTC,QAAQ;IACV,CAAA;AAEA,MAAMC,oBAAoB,IAAMd,cAAce,GAAG,GAAGC,SAAS;AAE7D,0CAA0C,GAC1C,OAAO,SAASC,kBAAkBC,GAAkD;IAClF,MAAMC,QAAQD,uBAAAA,GAAK,CAAC,QAAQ;IAC5B,IAAI,CAACC,SAAS,OAAOA,UAAU,YAAYC,MAAMC,OAAO,CAACF,QAAQ,OAAO,EAAE;IAC1E,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IAClC,MAAM5F,iBAAiBpD,+BAA+B,OAAOkC;QAC3D,IAAIU,UAAyB;QAC7B,OAAS;YACP,MAAMuG,OAAsB,MAAMzG,WAAW+B,OAAOe,UAAU,CAACtD,SAASoD,IAAI,GAAG1C;YAC/E,KAAK,MAAMT,OAAOgH,KAAKjC,IAAI,CAAE;oBAGZhF;gBAFf,MAAMoC,OAAOnC,IAAImC,IAAI;gBACrB,MAAMW,SAASpF,mBAAmByE,MAAM4E,SAAS;oBAC/ChE,WAAW,GAAEhD,wBAAAA,SAASgD,WAAW,YAApBhD,wBAAwB;oBACrCiD,aAAalD,YAAYC,UAAUoC;gBACrC;gBACA2E,MAAMpI,MAAM,IAAI;gBAChB,IAAIoE,OAAOL,MAAM,KAAK,WAAWqE,MAAMjI,OAAO,IAAI;gBAClD,IAAIiE,OAAOL,MAAM,KAAK,UAAUqE,MAAMlI,MAAM,IAAI;gBAChD,IAAIkE,OAAOjB,MAAM,EAAEiF,MAAMH,KAAK,IAAI;YACpC;YACA,IAAIK,KAAKjC,IAAI,CAACvD,MAAM,GAAGrD,WAAW;YAClCsC,UAAUuG,KAAKjC,IAAI,CAACiC,KAAKjC,IAAI,CAACvD,MAAM,GAAG,EAAE,CAAClB,EAAE;QAC9C;IACF;IACA,OAAOwG;AACT"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/scope-sharing-sweep.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * KEEPING \"ALL SITES EXCEPT…\" TRUE AS SITES COME AND GO (AGL-4047).\n *\n * A document shared this way names its included sites in `visibleTo`, the one\n * field readers enforce. A new site therefore has to be added to it, and a\n * site that left has to come off it. {@link sweepScopeSharingAfterSiteChange}\n * does that after every change to `orgs/{orgId}.hosts`: a site created, moved\n * in or out, or erased.\n *\n * ## What it costs when nothing is marked\n *\n * One query per declared collection, each answering nothing, and not one\n * write. Every workspace pays that on a site change and nothing more, which\n * is why a sweep document is only written once a marked document turns up.\n *\n * ## Each document in its own transaction, reading the org document\n *\n * The transaction reads `orgs/{orgId}` as well as the document, so what it\n * writes is computed from the sites that are true at commit. A site claimed\n * while the sweep runs either serializes before it (and the sweep sees the\n * site) or after it (and the sweep that claim starts sees the document).\n *\n * ## Inline for a few seconds, then the job\n *\n * The caller is a person creating or deleting a site, so a trigger works for\n * {@link INLINE_BUDGET_MS} and leaves the rest to the job, from a cursor in\n * `orgs/{orgId}/scopeSweeps/{sweepId}`. That document exists only while work\n * is left, so the job's query answers nothing on a quiet beat. No rule opens\n * the path: only this server code reads or writes it.\n *\n * Every step is idempotent. A second sweep, or a resumed one going over a\n * document again, reads `current` and writes nothing.\n */\n\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport {\n reconcileAllExcept,\n SCOPE_MODE_ALL_EXCEPT,\n type ScopeSharingFields,\n} from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { runPluginDeclarationsRepair } from '@aglyn/aglyn/plugin-manager/plugin-declarations-repair'\nimport {\n listScopeSharingCollections,\n type ResolvedScopeSharingCollection,\n scopeSharingPatchFor,\n} from '@aglyn/aglyn/plugin-manager/plugin-scope-sharing'\nimport {\n type CollectionReference,\n type DocumentReference,\n FieldPath,\n FieldValue,\n type Firestore,\n type QueryDocumentSnapshot,\n type QuerySnapshot,\n} from 'firebase-admin/firestore'\nimport firebaseAdmin from './firebase-admin'\n\n/** Where a sweep with work left records its cursor. */\nexport const SCOPE_SWEEPS_COLLECTION = 'scopeSweeps'\n/** Marked documents read at a time in one collection. */\nconst PAGE_SIZE = 100\n/** Transactions running at once. */\nconst CONCURRENCY = 8\n/** How long a person's site change waits for the sweep. */\nexport const INLINE_BUDGET_MS = 3_000\n/** How long one job beat spends, across every sweep it takes. */\nexport const JOB_BUDGET_MS = 20_000\n/** Sweeps one beat reads. */\nconst SWEEPS_PER_BEAT = 10\n/** Beats a failing sweep gets. The weekly drift report still counts its documents. */\nexport const MAX_SWEEP_ATTEMPTS = 5\n\nexport type ScopeSweepReason = 'site-added' | 'site-removed' | 'drift-repair'\n\nexport interface ScopeSweepCounts {\n /** Marked documents read. */\n marked: number\n /** Written because they had fallen behind. */\n changed: number\n /** Past their collection's limit, and so no longer widening. */\n capped: number\n /** A marker the helper cannot act on: left alone, and reported. */\n invalid: number\n /** A transaction or patch that threw. */\n failed: number\n}\n\nexport interface ScopeSweepResult extends ScopeSweepCounts {\n /** Every declared collection was walked to its end. */\n complete: boolean\n /** Where to carry on from, when `complete` is false. */\n cursor: ScopeSweepCursor | null\n}\n\n/** A position in {@link listScopeSharingCollections}. */\nexport interface ScopeSweepCursor {\n collection: string\n afterId: string | null\n}\n\nconst emptyCounts = (): ScopeSweepCounts => ({\n marked: 0,\n changed: 0,\n capped: 0,\n invalid: 0,\n failed: 0,\n})\n\nconst platformFirestore = () => firebaseAdmin.app().firestore() as unknown as Firestore\n\n/** The sites `orgs/{orgId}.hosts` names. */\nexport function orgHostIdsFromDoc(org: Readonly<Record<string, unknown>> | undefined): string[] {\n const hosts = org?.['hosts']\n if (!hosts || typeof hosts !== 'object' || Array.isArray(hosts)) return []\n return Object.entries(hosts as Record<string, unknown>)\n .filter(([, on]) => Boolean(on))\n .map(([hostId]) => hostId)\n}\n\n/** The sites a document keeps whatever it excludes, per its declaration. */\nfunction keptHostIds(\n declared: ResolvedScopeSharingCollection,\n doc: Readonly<Record<string, unknown>>,\n): string[] {\n const kept: string[] = []\n for (const field of declared.keepSiteFields ?? []) {\n const value = doc[field]\n if (typeof value === 'string' && value) kept.push(value)\n if (Array.isArray(value)) {\n for (const id of value) if (typeof id === 'string' && id) kept.push(id)\n }\n }\n return kept\n}\n\n/** The marked documents of one collection, in the order a cursor can resume. */\nfunction markedPage(collectionRef: CollectionReference, afterId: string | null): Promise<QuerySnapshot> {\n const ordered = collectionRef\n .where('scopeMode', '==', SCOPE_MODE_ALL_EXCEPT)\n .orderBy(FieldPath.documentId())\n return (afterId ? ordered.startAfter(afterId) : ordered).limit(PAGE_SIZE).get()\n}\n\n/** Runs `work` over `items`, at most {@link CONCURRENCY} at a time. */\nasync function eachConcurrently<T>(\n items: readonly T[],\n work: (item: T) => Promise<void>,\n): Promise<void> {\n let next = 0\n await Promise.all(\n Array.from({ length: Math.min(CONCURRENCY, items.length) }, async () => {\n while (next < items.length) {\n const item = items[next]\n next += 1\n await work(item)\n }\n }),\n )\n}\n\n/** A write's data: a `null` marker field is deleted, never stored. */\nexport function fieldsToWrite(fields: ScopeSharingFields): Record<string, unknown> {\n return {\n visibleTo: fields.visibleTo,\n scopeMode: fields.scopeMode ?? FieldValue.delete(),\n scopeExcept: fields.scopeExcept ?? FieldValue.delete(),\n }\n}\n\n/** The document as it will read after the write, for a patch to work from. */\nfunction asStored(\n data: Readonly<Record<string, unknown>>,\n fields: ScopeSharingFields,\n): Record<string, unknown> {\n const next: Record<string, unknown> = { ...data, visibleTo: fields.visibleTo }\n if (fields.scopeMode) {\n next['scopeMode'] = fields.scopeMode\n next['scopeExcept'] = fields.scopeExcept\n } else {\n delete next['scopeMode']\n delete next['scopeExcept']\n }\n return next\n}\n\n/** Brings one marked document level, in its own transaction. */\nasync function reconcileDocument(\n db: Firestore,\n orgRef: DocumentReference,\n declared: ResolvedScopeSharingCollection,\n docRef: DocumentReference,\n counts: ScopeSweepCounts,\n): Promise<void> {\n const status = await db.runTransaction(async (tx) => {\n const [org, doc] = await tx.getAll(orgRef, docRef)\n // The workspace went while this ran, and the document with it.\n if (!org.exists || !doc.exists) return 'current'\n const data = doc.data() as Record<string, unknown>\n const answer = reconcileAllExcept(data, orgHostIdsFromDoc(org.data()), {\n maxIncluded: declared.maxIncluded ?? null,\n keepHostIds: keptHostIds(declared, data),\n })\n if (answer.fields) {\n const patch = declared.patch\n ? await requiredPatch(declared.name)(declared.name, asStored(data, answer.fields))\n : {}\n // Not an edit, so `updatedAt` stays: a list ordered by it must not\n // reshuffle because a site was added somewhere in the workspace.\n tx.update(docRef, { ...fieldsToWrite(answer.fields), ...patch })\n }\n return answer.status\n })\n if (status === 'changed') counts.changed += 1\n if (status === 'capped') counts.capped += 1\n if (status === 'invalid') counts.invalid += 1\n}\n\nfunction requiredPatch(collection: string) {\n const patch = scopeSharingPatchFor(collection)\n if (!patch) throw new Error(`no scope-sharing patch is registered for ${collection}`)\n return patch\n}\n\n/**\n * A declared patch is missing where the boot step has not run. Runs it once,\n * and only when a marked document needs one, so a sweep that finds nothing\n * never pays for it.\n */\nasync function ensurePatches(\n collections: readonly ResolvedScopeSharingCollection[],\n): Promise<void> {\n if (collections.every((row) => !row.patch || scopeSharingPatchFor(row.name))) return\n await runPluginDeclarationsRepair().catch((error: unknown) => {\n console.error('[scope-sweep] the declarations repair failed', error)\n })\n}\n\nexport interface RunScopeSharingSweepInput {\n orgId: string\n /** Stops starting new work past this; omit to walk to the end. */\n budgetMs?: number\n /** Resume from here. */\n from?: ScopeSweepCursor | null\n /**\n * Called the first time a marked document turns up, so a sweep that finds\n * nothing writes nothing. A trigger records its sweep document here.\n */\n onFirstMarked?: () => Promise<void>\n firestore?: Firestore\n}\n\n/**\n * Walks every declared collection's marked documents and brings each level.\n * Throws only on a failed query; one document failing is counted and the walk\n * goes on, and an incomplete walk answers where it stopped.\n */\nexport async function runScopeSharingSweep(\n input: RunScopeSharingSweepInput,\n): Promise<ScopeSweepResult> {\n const db = input.firestore ?? platformFirestore()\n const orgRef = db.collection('orgs').doc(input.orgId)\n const collections = listScopeSharingCollections()\n const startAt = input.from\n ? Math.max(0, collections.findIndex((row) => row.name === input.from?.collection))\n : 0\n const remaining = collections.slice(startAt)\n const deadline = input.budgetMs == null ? null : Date.now() + input.budgetMs\n const counts = emptyCounts()\n\n // Every collection's first page at once, so the common answer of nothing\n // costs one round of queries rather than one after another.\n const pages = new Map<string, QueryDocumentSnapshot[]>()\n const firstAfter = (name: string) =>\n input.from && input.from.collection === name ? input.from.afterId : null\n await eachConcurrently(remaining, async (declared) => {\n const snapshot = await markedPage(orgRef.collection(declared.name), firstAfter(declared.name))\n pages.set(declared.name, snapshot.docs)\n })\n if ([...pages.values()].every((docs) => !docs.length)) {\n return { ...counts, complete: true, cursor: null }\n }\n await input.onFirstMarked?.()\n await ensurePatches(remaining)\n\n for (const declared of remaining) {\n let docs = pages.get(declared.name) ?? []\n let afterId = firstAfter(declared.name)\n while (docs.length) {\n if (deadline != null && Date.now() >= deadline) {\n return { ...counts, complete: false, cursor: { collection: declared.name, afterId } }\n }\n counts.marked += docs.length\n await eachConcurrently(docs, async (doc) => {\n try {\n await reconcileDocument(db, orgRef, declared, doc.ref, counts)\n } catch (error) {\n counts.failed += 1\n console.error(`[scope-sweep] ${declared.name}/${doc.id} in ${input.orgId} was not brought level`, error)\n }\n })\n afterId = docs[docs.length - 1].id\n if (docs.length < PAGE_SIZE) break\n docs = (await markedPage(orgRef.collection(declared.name), afterId)).docs\n }\n }\n return { ...counts, complete: true, cursor: null }\n}\n\n/**\n * What a change to a workspace's sites runs, once the change has committed.\n *\n * NEVER THROWS, because the site change is done and is what the person asked\n * for. Work it could not finish is left in a sweep document for the job, and\n * if even that write fails the weekly drift report finds what is behind.\n */\nexport async function sweepScopeSharingAfterSiteChange(input: {\n orgId: string\n reason: ScopeSweepReason\n hostId?: string\n firestore?: Firestore\n}): Promise<void> {\n const { orgId, reason, hostId } = input\n let sweepRef: DocumentReference | null = null\n const leaveForTheJob = async (cursor: ScopeSweepCursor | null, attempts: number) => {\n const db = input.firestore ?? platformFirestore()\n sweepRef ??= db.collection('orgs').doc(orgId).collection(SCOPE_SWEEPS_COLLECTION).doc(createResourceUid())\n await sweepRef.set({\n reason,\n ...(hostId ? { hostId } : {}),\n cursor,\n attempts,\n createdAtMs: Date.now(),\n })\n }\n try {\n const result = await runScopeSharingSweep({\n orgId,\n budgetMs: INLINE_BUDGET_MS,\n ...(input.firestore ? { firestore: input.firestore } : {}),\n onFirstMarked: () => leaveForTheJob(null, 0),\n })\n if (!result.complete) {\n await leaveForTheJob(result.cursor, 0)\n return\n }\n if (result.failed) {\n await leaveForTheJob(null, 1)\n return\n }\n await sweepRef?.delete()\n } catch (error) {\n console.error(`[scope-sweep] the sweep of ${orgId} after ${reason} did not finish`, error)\n await leaveForTheJob(null, 1).catch((writeError: unknown) => {\n console.error(`[scope-sweep] could not leave ${orgId}'s sweep for the job`, writeError)\n })\n }\n}\n\n/**\n * Carries on every unfinished sweep: the job's handler. A sweep document exists\n * only while work is left, so the unfiltered query needs no index and answers\n * nothing on a quiet beat, for one read.\n */\nexport async function resumeScopeSweeps(\n options: { budgetMs?: number; firestore?: Firestore } = {},\n): Promise<{ resumed: number; finished: number; droppedAfterFailing: number }> {\n const db = options.firestore ?? platformFirestore()\n const pending = await db.collectionGroup(SCOPE_SWEEPS_COLLECTION).limit(SWEEPS_PER_BEAT).get()\n const tally = { resumed: 0, finished: 0, droppedAfterFailing: 0 }\n const deadline = Date.now() + (options.budgetMs ?? JOB_BUDGET_MS)\n for (const sweep of pending.docs) {\n const budgetMs = deadline - Date.now()\n if (budgetMs <= 0) break\n tally.resumed += 1\n const orgRef = sweep.ref.parent.parent\n const attempts = Number(sweep.get('attempts') ?? 0)\n try {\n const org = orgRef ? await orgRef.get() : null\n // The workspace was erased after this was left. Nothing to bring level.\n if (!org?.exists) {\n await sweep.ref.delete()\n tally.finished += 1\n continue\n }\n const result = await runScopeSharingSweep({\n orgId: org.id,\n budgetMs,\n from: (sweep.get('cursor') as ScopeSweepCursor | null | undefined) ?? null,\n firestore: db,\n })\n if (!result.complete) {\n await sweep.ref.update({ cursor: result.cursor })\n continue\n }\n if (!result.failed) {\n await sweep.ref.delete()\n tally.finished += 1\n continue\n }\n throw new Error(`${result.failed} document(s) failed`)\n } catch (error) {\n console.error(`[scope-sweep] ${sweep.ref.path} failed on attempt ${attempts + 1}`, error)\n if (attempts + 1 >= MAX_SWEEP_ATTEMPTS) {\n // Stops holding a place in the beat. What it left behind is what the\n // weekly drift report counts, and that report goes to staff.\n await sweep.ref.delete().catch(() => undefined)\n tally.droppedAfterFailing += 1\n } else {\n await sweep.ref.update({ attempts: attempts + 1, cursor: null }).catch(() => undefined)\n }\n }\n }\n return tally\n}\n\n/** What the weekly report asks of one workspace. Reads only. */\nexport interface ScopeSharingDrift {\n /** Marked documents read. */\n marked: number\n /** Should read differently from how they read: what a sweep would write. */\n stale: number\n /** Past their collection's limit. A known state, reported and not alarmed. */\n capped: number\n /** A marker that cannot be acted on. */\n invalid: number\n}\n\nexport function emptyScopeSharingDrift(): ScopeSharingDrift {\n return { marked: 0, stale: 0, capped: 0, invalid: 0 }\n}\n\n/**\n * How far one workspace's marked documents are from what a sweep would write,\n * with the same helper the sweep uses. One query per declared collection when\n * nothing is marked.\n */\nexport async function scopeSharingDriftForOrg(\n orgRef: DocumentReference,\n orgData: Readonly<Record<string, unknown>> | undefined,\n): Promise<ScopeSharingDrift> {\n const drift = emptyScopeSharingDrift()\n const hostIds = orgHostIdsFromDoc(orgData)\n await eachConcurrently(listScopeSharingCollections(), async (declared) => {\n let afterId: string | null = null\n for (;;) {\n const page: QuerySnapshot = await markedPage(orgRef.collection(declared.name), afterId)\n for (const doc of page.docs) {\n const data = doc.data() as Record<string, unknown>\n const answer = reconcileAllExcept(data, hostIds, {\n maxIncluded: declared.maxIncluded ?? null,\n keepHostIds: keptHostIds(declared, data),\n })\n drift.marked += 1\n if (answer.status === 'invalid') drift.invalid += 1\n if (answer.status === 'capped') drift.capped += 1\n if (answer.fields) drift.stale += 1\n }\n if (page.docs.length < PAGE_SIZE) return\n afterId = page.docs[page.docs.length - 1].id\n }\n })\n return drift\n}\n"],"names":["createResourceUid","reconcileAllExcept","SCOPE_MODE_ALL_EXCEPT","runPluginDeclarationsRepair","listScopeSharingCollections","scopeSharingPatchFor","FieldPath","FieldValue","firebaseAdmin","SCOPE_SWEEPS_COLLECTION","PAGE_SIZE","CONCURRENCY","INLINE_BUDGET_MS","JOB_BUDGET_MS","SWEEPS_PER_BEAT","MAX_SWEEP_ATTEMPTS","emptyCounts","marked","changed","capped","invalid","failed","platformFirestore","app","firestore","orgHostIdsFromDoc","org","hosts","Array","isArray","Object","entries","filter","on","Boolean","map","hostId","keptHostIds","declared","doc","kept","field","keepSiteFields","value","push","id","markedPage","collectionRef","afterId","ordered","where","orderBy","documentId","startAfter","limit","get","eachConcurrently","items","work","next","Promise","all","from","length","Math","min","item","fieldsToWrite","fields","visibleTo","scopeMode","delete","scopeExcept","asStored","data","reconcileDocument","db","orgRef","docRef","counts","status","runTransaction","tx","getAll","exists","answer","maxIncluded","keepHostIds","patch","requiredPatch","name","update","collection","Error","ensurePatches","collections","every","row","catch","error","console","runScopeSharingSweep","input","orgId","startAt","max","findIndex","remaining","slice","deadline","budgetMs","Date","now","pages","Map","firstAfter","snapshot","set","docs","values","complete","cursor","onFirstMarked","ref","sweepScopeSharingAfterSiteChange","reason","sweepRef","leaveForTheJob","attempts","createdAtMs","result","writeError","resumeScopeSweeps","options","pending","collectionGroup","tally","resumed","finished","droppedAfterFailing","sweep","parent","Number","path","undefined","emptyScopeSharingDrift","stale","scopeSharingDriftForOrg","orgData","drift","hostIds","page"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgCC,GAED,SAASA,iBAAiB,QAAQ,6CAA4C;AAC9E,SACEC,kBAAkB,EAClBC,qBAAqB,QAEhB,sCAAqC;AAC5C,SAASC,2BAA2B,QAAQ,yDAAwD;AACpG,SACEC,2BAA2B,EAE3BC,oBAAoB,QACf,mDAAkD;AACzD,SAGEC,SAAS,EACTC,UAAU,QAIL,2BAA0B;AACjC,OAAOC,mBAA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;gBAChD,IAAIkE,OAAOjB,MAAM,EAAEiF,MAAMH,KAAK,IAAI;YACpC;YACA,IAAIK,KAAKjC,IAAI,CAACvD,MAAM,GAAGrD,WAAW;YAClCsC,UAAUuG,KAAKjC,IAAI,CAACiC,KAAKjC,IAAI,CAACvD,MAAM,GAAG,EAAE,CAAClB,EAAE;QAC9C;IACF;IACA,OAAOwG;AACT"}
@@ -176,6 +176,27 @@ export declare const HEALTH_ROUTE_PREFIX = "/api/health";
176
176
  * so fails the status test above.
177
177
  */
178
178
  export declare function isHealthContractEntry(entry: VercelDrainEntry): boolean;
179
+ /**
180
+ * The path Vercel stamps on an entry the MIDDLEWARE wrote (`source: edge`,
181
+ * `type: middleware-invocation`), rather than a route pattern.
182
+ */
183
+ export declare const MIDDLEWARE_ENTRY_PATH = "_middleware";
184
+ /**
185
+ * Is this the middleware sending a closed site's notice as its 503?
186
+ *
187
+ * Since AGL-4110 a site in maintenance or preview answers the public with its
188
+ * own notice page AS a 503 with `Retry-After`, and the middleware is the only
189
+ * layer that can set that status, so the drain sees it as a `_middleware`
190
+ * entry with status 503. Forwarded, every visit to a closed site paged the
191
+ * operator as "Server errors": on 2026-11-05 nine of them came from two demo
192
+ * sites in maintenance and kept the AGL-1921 policy's incident open all day.
193
+ *
194
+ * The middleware has no other 503. The platform's own middleware failures
195
+ * are `MIDDLEWARE_INVOCATION_FAILED` (500) and `MIDDLEWARE_INVOCATION_TIMEOUT`
196
+ * (504), and a crash is `-1` or a `fatal` line, so all of those still
197
+ * forward. Narrow in the same three ways as {@link isLockdownNoticeEntry}.
198
+ */
199
+ export declare function isSiteNoticeEntry(entry: VercelDrainEntry): boolean;
179
200
  /**
180
201
  * THE COST GATE (requirement 3). Everything false here is dropped unwritten.
181
202
  *
@@ -49,7 +49,8 @@
49
49
  * the stream unreadable: measured over the 48 hours to 2026-09-09, 229 of
50
50
  * the 251 entries in this log were `/api/health/*` reporting degraded and
51
51
  * 22 were the only real outage in the window. See `isLockdownNoticeEntry`
52
- * and `isHealthContractEntry` (AGL-2709).
52
+ * and `isHealthContractEntry` (AGL-2709). A closed site's notice is the
53
+ * third: `isSiteNoticeEntry`.
53
54
  * 5. **A per-instance budget per window**, with suppression REPORTED. A
54
55
  * monitoring path that hides its own lossiness is the bug shape this repo
55
56
  * keeps rediscovering.
@@ -300,6 +301,34 @@ function clampString(value, max) {
300
301
  return pathname === HEALTH_ROUTE_PREFIX || pathname.startsWith(`${HEALTH_ROUTE_PREFIX}/`);
301
302
  });
302
303
  }
304
+ /**
305
+ * The path Vercel stamps on an entry the MIDDLEWARE wrote (`source: edge`,
306
+ * `type: middleware-invocation`), rather than a route pattern.
307
+ */ export const MIDDLEWARE_ENTRY_PATH = '_middleware';
308
+ /**
309
+ * Is this the middleware sending a closed site's notice as its 503?
310
+ *
311
+ * Since AGL-4110 a site in maintenance or preview answers the public with its
312
+ * own notice page AS a 503 with `Retry-After`, and the middleware is the only
313
+ * layer that can set that status, so the drain sees it as a `_middleware`
314
+ * entry with status 503. Forwarded, every visit to a closed site paged the
315
+ * operator as "Server errors": on 2026-11-05 nine of them came from two demo
316
+ * sites in maintenance and kept the AGL-1921 policy's incident open all day.
317
+ *
318
+ * The middleware has no other 503. The platform's own middleware failures
319
+ * are `MIDDLEWARE_INVOCATION_FAILED` (500) and `MIDDLEWARE_INVOCATION_TIMEOUT`
320
+ * (504), and a crash is `-1` or a `fatal` line, so all of those still
321
+ * forward. Narrow in the same three ways as {@link isLockdownNoticeEntry}.
322
+ */ export function isSiteNoticeEntry(entry) {
323
+ var _entry_proxy;
324
+ if (entry.level === 'fatal' || entry.type === 'fatal') return false;
325
+ const statuses = [
326
+ entry.statusCode,
327
+ (_entry_proxy = entry.proxy) == null ? void 0 : _entry_proxy.statusCode
328
+ ].filter((status)=>typeof status === 'number');
329
+ if (!statuses.length || statuses.some((status)=>status !== 503)) return false;
330
+ return entry.path === MIDDLEWARE_ENTRY_PATH;
331
+ }
303
332
  /**
304
333
  * THE COST GATE (requirement 3). Everything false here is dropped unwritten.
305
334
  *
@@ -338,7 +367,7 @@ function clampString(value, max) {
338
367
  * Everything above, in the order the cost argument requires.
339
368
  * Exported so the tests can assert the gate without a transport.
340
369
  */ export function selectForwardableEntries(entries) {
341
- return entries.filter((entry)=>!isReceiverEntry(entry) && !isLockdownNoticeEntry(entry) && !isHealthContractEntry(entry) && isServerErrorEntry(entry));
370
+ return entries.filter((entry)=>!isReceiverEntry(entry) && !isLockdownNoticeEntry(entry) && !isHealthContractEntry(entry) && !isSiteNoticeEntry(entry) && isServerErrorEntry(entry));
342
371
  }
343
372
  /**
344
373
  * One Cloud Logging entry, carrying ONLY fields that are already inside the
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/vercel-log-drain.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The Vercel log-drain receiver (AGL-1921, third and last arm).\n *\n * ## Why this arm exists at all\n *\n * The two arms already shipped both start from OUR code running. The\n * `onRequestError` hook (`reportServerError`) sees a render or route handler\n * throw; `/api/health/server-errors` grades the markers that hook writes.\n * Neither can see:\n *\n * - an error that kills the process before the hook runs,\n * - a platform-level 5xx that never reaches our code at all — a function\n * timeout, an OOM kill, a cold-start 502,\n * - anything thrown in the edge runtime.\n *\n * A log drain sees all three, because Vercel emits the request log whether or\n * not our code got far enough to have an opinion. That is why this is the arm\n * that closes the issue rather than a fourth partial view.\n *\n * ## The shape of the risk, and what each rule below buys\n *\n * A drain streams EVERY request log for both projects. The account's whole\n * monitoring budget is about $20/month, so the dangerous failure mode here is\n * not missing an error — it is faithfully forwarding a million healthy 200s\n * into Cloud Logging and getting a bill for it. Hence, in order:\n *\n * 1. **Signature first, fail closed.** HMAC-SHA1 of the RAW body keyed by the\n * drain secret, timing-safe compared. Unsigned means unwritten, always.\n * 2. **Filter before writing.** `isServerErrorEntry` is the cost gate: an\n * entry that is not a server error costs one predicate and zero writes.\n * 3. **Never our own route.** See `RECEIVER_ROUTE_PATH`.\n * 4. **Never a deliberate 5xx.** A 503 is how the lockdown notice and every\n * health contract SAY something, and forwarding a verdict as a fault makes\n * the stream unreadable: measured over the 48 hours to 2026-09-09, 229 of\n * the 251 entries in this log were `/api/health/*` reporting degraded and\n * 22 were the only real outage in the window. See `isLockdownNoticeEntry`\n * and `isHealthContractEntry` (AGL-2709).\n * 5. **A per-instance budget per window**, with suppression REPORTED. A\n * monitoring path that hides its own lossiness is the bug shape this repo\n * keeps rediscovering.\n *\n * ## Where it writes, and why not next door\n *\n * `vercel-runtime`, DELIBERATELY NOT `server-errors`. That log is the\n * `onRequestError` hook's, and the alert policy\n * `projects/aglyn-main/alertPolicies/11610705614308437855` keys on it. A 500\n * our code threw is seen by BOTH arms, so merging the streams would count one\n * incident twice and make triage start by asking which arm saw it. The same\n * separation `client-errors` and `server-errors` already keep, for the same\n * reason.\n *\n * The entries carry a real `httpRequest.status`, which is what makes the\n * policy AGL-1921 originally specified — a log filter on logName matching\n * \"vercel\" and httpRequest.status at or above 500 — expressible without a\n * log-based metric on a jsonPayload field first.\n */\n\n/**\n * LAZY, and that is load-bearing rather than stylistic (AGL-1921, 2026-08-26).\n *\n * `client-error-report` reaches `firebase-admin`. A static import here would\n * pull the whole SDK into anything that bundles this module — including the\n * Cloud Run receiver, whose entire reason for existing is to run this gate\n * OFF Vercel with nothing but `node:crypto` and a metadata-server token. That\n * receiver always supplies its own {@link DrainIngestOptions.target}, so this\n * path is never reached there and the SDK is never resolved.\n *\n * Called through `defaultLoggingTarget` below, never at module scope.\n */\nasync function defaultLoggingTarget(): Promise<{\n token: string\n projectId: string\n} | null> {\n const { beaconLoggingTarget } = await import('./client-error-report')\n return beaconLoggingTarget()\n}\n\n/**\n * The log id the drain writes to. Contains \"vercel\" on purpose: the alert\n * policy `projects/aglyn-main/alertPolicies/14031689508473384486` matches\n * `logName=~\"vercel\"`, so the name is load-bearing. Renaming this log without\n * repointing that policy silences the platform-5xx arm.\n */\nexport const VERCEL_RUNTIME_LOG_ID = 'vercel-runtime'\n\n/** The env var holding the drain's signature secret. Fails closed if unset. */\nexport const DRAIN_SECRET_ENV = 'VERCEL_LOG_DRAIN_SECRET'\n\n/**\n * The receiver's own path — the FEEDBACK-LOOP GUARD (requirement 5).\n *\n * ⚠️ HISTORICAL, AND KEPT AS DEFENCE IN DEPTH (2026-08-26). The receiver USED\n * to run on `aglyn-console`, whose logs the console drain collects, and the\n * two cuts below were the answer to one receiver 500 draining back in.\n *\n * They were not enough, and the reason is worth stating plainly because the\n * docstring that used to live here got it wrong: **both cuts are about the\n * WRITE, and the cost was the DELIVERY.** Nothing inside a receiver can\n * decline to be requested, and every delivery POST is itself a request that\n * produces a log the same drain then delivers. Measured at 695K invocations\n * in nine hours. Vercel's drain `sampling` rules are not a fix either — a\n * single `{rate: 0}` rule with no path prefix moved delivery volume from 31\n * to 32 per five minutes, i.e. the whole `schemas.log` filter block is stored\n * and never applied.\n *\n * The receiver now lives OFF Vercel, at `cloud/log-drain` on Cloud Run, which\n * no drain watches — so the loop is structurally impossible rather than\n * filtered against. These cuts stay because they cost nothing and they are\n * the backstop if anyone ever mounts this gate on a Vercel route again.\n *\n * Two structural cuts, not one:\n *\n * a. Every entry whose path is this route is dropped before the 5xx filter —\n * so even the receiver's OWN 500s can never be forwarded, by anything, at\n * any budget. It is not \"we try not to error\"; it is that its errors are\n * unforwardable.\n * b. Every line this module logs about itself is `console.warn`, i.e. Vercel\n * `level: \"warning\"`, and the filter forwards only 5xx and `fatal`. A\n * suppression summary drained back in is therefore dropped a second time,\n * on a different property, by a different rule.\n *\n * Matched as a PREFIX so `/api/log-drain`, a future `/api/log-drain/test` and\n * the query-bearing `proxy.path` form all fall on the same side of it.\n */\nexport const RECEIVER_ROUTE_PATH = '/api/log-drain'\n\n/**\n * The lockdown notice route — a route whose 503 is the FEATURE, not a fault.\n *\n * `apps/tenant/app/api/locked/route.ts` answers every request with a real 503\n * carrying `Retry-After`, and the middleware rewrites every path of a locked\n * or bandwidth-capped host to it. That status is deliberate: a takedown\n * notice answering 200 would tell crawlers and uptime checks the site is\n * fine, which is the whole reason the notice is a route handler rather than a\n * page.\n *\n * Forwarded, it is indistinguishable from an outage. One suspended host being\n * crawled emits a 5xx per request, forever, into the arm whose only consumer\n * is an alert policy — so the policy fires on a working feature and the next\n * real incident arrives in a stream that is already red.\n *\n * Matched EXACTLY, not as a prefix: the notice is one path, and a future\n * `/api/locked/*` would be a different route with no such guarantee about its\n * status.\n */\nexport const LOCKDOWN_NOTICE_ROUTE_PATH = '/api/locked'\n\n/**\n * Per-instance write budget, mirroring `reportServerError`'s (same file\n * neighbourhood, same rationale): the failure being watched is a SPIKE, and a\n * spike is when an unbounded forwarder turns one incident into a second one\n * denominated in dollars. 60 entries a minute per instance is far more than\n * any threshold policy needs to cross — the shape of the spike survives; the\n * bill does not follow it.\n */\nconst DRAIN_BUDGET_PER_WINDOW = 60\nconst DRAIN_WINDOW_MS = 60_000\nlet drainWindowStartedAt = 0\nlet drainWritten = 0\nlet drainSuppressed = 0\n\nconst MAX_MESSAGE = 1_024\nconst WRITE_TIMEOUT_MS = 4_000\n\n/** Reset the budget counters. Test seam only — never called in production. */\nexport function resetDrainBudgetForTests(): void {\n drainWindowStartedAt = 0\n drainWritten = 0\n drainSuppressed = 0\n}\n\n/**\n * One log entry as a Vercel drain delivers it. Only the fields this receiver\n * reads are named; the wire object carries many more (client IP, user agent,\n * referer, the query-bearing `proxy.path`) which are deliberately NOT in this\n * type, because a field that has no name here cannot be forwarded by accident.\n */\nexport interface VercelDrainEntry {\n id?: string\n deploymentId?: string\n projectId?: string\n projectName?: string\n source?: string\n host?: string\n timestamp?: number\n level?: string\n type?: string\n message?: string\n path?: string\n entrypoint?: string\n requestId?: string\n statusCode?: number\n environment?: string\n executionRegion?: string\n proxy?: {\n method?: string\n statusCode?: number\n path?: string\n pathType?: string\n }\n}\n\nfunction clampString(value: unknown, max: number): string {\n return typeof value === 'string' ? value.slice(0, max) : ''\n}\n\n/**\n * The entries in one delivery, in either format Vercel will send.\n *\n * `json` delivers an array (and, per the reference's own example, sometimes a\n * newline-separated sequence of objects); `ndjson` delivers one object per\n * line. Parsing both means the drain's `deliveryFormat` can be changed in the\n * dashboard without a deploy, and a malformed line is skipped rather than\n * failing the whole delivery — Vercel disables a drain that errors too often,\n * so a receiver that 500s on one bad line silences itself.\n */\nexport function parseDrainPayload(rawBody: string): VercelDrainEntry[] {\n const body = rawBody.trim()\n if (!body) return []\n try {\n const parsed: unknown = JSON.parse(body)\n if (Array.isArray(parsed)) {\n return parsed.filter(\n (entry): entry is VercelDrainEntry =>\n Boolean(entry) && typeof entry === 'object',\n )\n }\n if (parsed && typeof parsed === 'object')\n return [parsed as VercelDrainEntry]\n } catch {\n // Not a single JSON document — fall through to line-by-line.\n }\n const entries: VercelDrainEntry[] = []\n for (const line of body.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed) continue\n try {\n const parsed: unknown = JSON.parse(trimmed)\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n entries.push(parsed as VercelDrainEntry)\n }\n } catch {\n // One unreadable line never fails a delivery.\n }\n }\n return entries\n}\n\n/** Does this entry describe the receiver's own route? See RECEIVER_ROUTE_PATH. */\nexport function isReceiverEntry(entry: VercelDrainEntry): boolean {\n const paths = [entry.path, entry.proxy?.path]\n return paths.some((path) => {\n if (typeof path !== 'string') return false\n // `proxy.path` carries the query string; compare the path part only.\n const [pathname] = path.split('?')\n return (\n pathname === RECEIVER_ROUTE_PATH ||\n pathname.startsWith(`${RECEIVER_ROUTE_PATH}/`)\n )\n })\n}\n\n/**\n * Is this the lockdown notice serving its deliberate 503? See\n * {@link LOCKDOWN_NOTICE_ROUTE_PATH}.\n *\n * Narrow on purpose — the route being exempt must not make the route\n * unwatchable. Only a clean 503 is excused: a 500 the handler threw, the\n * `statusCode -1` of a crashed lambda, and a `fatal` line all still forward,\n * because those say the notice itself is broken and a locked host is then\n * serving nothing at all.\n */\nexport function isLockdownNoticeEntry(entry: VercelDrainEntry): boolean {\n if (entry.level === 'fatal' || entry.type === 'fatal') return false\n const statuses = [entry.statusCode, entry.proxy?.statusCode].filter(\n (status): status is number => typeof status === 'number',\n )\n if (!statuses.length || statuses.some((status) => status !== 503))\n return false\n return [entry.path, entry.proxy?.path].some((path) => {\n if (typeof path !== 'string') return false\n // `proxy.path` carries the query string; compare the path part only.\n const [pathname] = path.split('?')\n return pathname === LOCKDOWN_NOTICE_ROUTE_PATH\n })\n}\n\n/**\n * The health contract's routes, whose 503 is a VERDICT and not a fault.\n *\n * Prefix, not an exact path: every endpoint under it speaks the same contract\n * — `healthHttpStatus` answers 200 while a check reports ok and 503 the moment\n * it reports degraded — so `/api/health`, `/api/health/crons` and\n * `/api/health/render/site` are all the same case.\n */\nexport const HEALTH_ROUTE_PREFIX = '/api/health'\n\n/**\n * Is this a health endpoint answering 503 because it is doing its job?\n * (AGL-2709)\n *\n * ⚠️ THE STREAM WAS 91% THIS. Measured over the 48 hours to 2026-09-09, the\n * drain forwarded 251 entries into `vercel-runtime`. **229 were `/api/health/*`\n * answering 503** — `crons` 113, `funnel` 73, `server-errors` 18 — and 22 were\n * the AGL-2708 outage, the only real server errors in the window. The policy\n * on that log (`logName=~\"vercel\" AND severity>=ERROR`, one notification an\n * hour) therefore mails about a working health check for as long as any\n * subsystem is degraded: `/api/health/crons` was CORRECTLY reporting a broken\n * job for six hours on 2026-09-07, which is six hours of \"server errors\" mail\n * arriving in the same inbox that then had to notice 04:02 on 2026-09-09.\n *\n * Excusing it removes a DUPLICATE, not a signal, and the reason is structural\n * rather than a judgement call: every `/api/health/*` route both apps ship has\n * a monitor reading it, and `evaluateSubsystemReaders` fails the build if one\n * ever does not. The 503 is already on the uptime probe's board, in an\n * UptimeRobot monitor and on `docs.aglyn.com/status`, said in a body that\n * names WHICH check failed — which the drain entry never could.\n *\n * Narrow in exactly the same three ways as {@link isLockdownNoticeEntry}, and\n * each one is load-bearing:\n *\n * - a clean 503 only. A 500 the handler threw means the health route itself\n * is broken, and a check that cannot answer must never look calm;\n * - never a `fatal` line, which is process death rather than a verdict;\n * - never `statusCode -1`, the crashed-lambda sentinel, which is not 503 and\n * so fails the status test above.\n */\nexport function isHealthContractEntry(entry: VercelDrainEntry): boolean {\n if (entry.level === 'fatal' || entry.type === 'fatal') return false\n const statuses = [entry.statusCode, entry.proxy?.statusCode].filter(\n (status): status is number => typeof status === 'number',\n )\n if (!statuses.length || statuses.some((status) => status !== 503))\n return false\n return [entry.path, entry.proxy?.path].some((path) => {\n if (typeof path !== 'string') return false\n // `proxy.path` carries the query string; compare the path part only.\n const [pathname] = path.split('?')\n return (\n pathname === HEALTH_ROUTE_PREFIX ||\n pathname.startsWith(`${HEALTH_ROUTE_PREFIX}/`)\n )\n })\n}\n\n/**\n * THE COST GATE (requirement 3). Everything false here is dropped unwritten.\n *\n * What counts as a server error:\n *\n * - `statusCode >= 500` or `proxy.statusCode >= 500` — the platform 5xx this\n * whole arm exists for, including the ones our code never saw.\n * - `statusCode === -1` — documented as \"no response returned and the lambda\n * crashed\". The OOM/hard-crash case, and the single most important entry\n * shape the `onRequestError` hook is structurally unable to produce.\n * - `level === 'fatal'` or `type === 'fatal'` — the edge-runtime and\n * process-death shape, which may carry no status at all.\n *\n * What deliberately does NOT count:\n *\n * - `level === 'error'`. That is any `console.error`, including the fail-soft\n * warn/error lines the beacons themselves write, and forwarding it would\n * mean paying per line for a stream the `onRequestError` hook already\n * covers properly. If an errored request matters, it has a status.\n * - `proxy.statusCode === -1`. Same sentinel, opposite meaning: on the proxy\n * object it documents a BACKGROUND REVALIDATION, which is a healthy ISR\n * refresh. Reading it as a crash would forward a steady trickle of normal\n * traffic forever — the exact bill this gate exists to prevent.\n */\nexport function isServerErrorEntry(entry: VercelDrainEntry): boolean {\n if (typeof entry.statusCode === 'number') {\n if (entry.statusCode >= 500) return true\n if (entry.statusCode === -1) return true\n }\n const proxyStatus = entry.proxy?.statusCode\n if (typeof proxyStatus === 'number' && proxyStatus >= 500) return true\n if (entry.level === 'fatal' || entry.type === 'fatal') return true\n return false\n}\n\n/**\n * Everything above, in the order the cost argument requires.\n * Exported so the tests can assert the gate without a transport.\n */\nexport function selectForwardableEntries(\n entries: readonly VercelDrainEntry[],\n): VercelDrainEntry[] {\n return entries.filter(\n (entry) =>\n !isReceiverEntry(entry) &&\n !isLockdownNoticeEntry(entry) &&\n !isHealthContractEntry(entry) &&\n isServerErrorEntry(entry),\n )\n}\n\n/**\n * One Cloud Logging entry, carrying ONLY fields that are already inside the\n * envelope the shipped beacons send (requirement 8).\n *\n * Explicitly absent, and each for a reason:\n * `proxy.path` (query string — the AGL-1538 boundary is origin+pathname and\n * this is the same boundary), `proxy.clientIp` and `proxy.userAgent` and\n * `proxy.referer` (visitor identity; also why Vercel's own IP-visibility\n * toggle exists), request or response bodies (never delivered, never wanted).\n * `path` IS forwarded because Vercel documents it as the function or dynamic\n * path — the route PATTERN, which is what you group and alert on anyway, and\n * exactly what `reportServerError` already sends as `route`.\n */\nfunction toLogEntry(entry: VercelDrainEntry): Record<string, unknown> {\n const status =\n typeof entry.statusCode === 'number' && entry.statusCode >= 0\n ? entry.statusCode\n : typeof entry.proxy?.statusCode === 'number' &&\n entry.proxy.statusCode >= 0\n ? entry.proxy.statusCode\n : undefined\n return {\n severity: 'ERROR',\n // The structured field the AGL-1921 policy matches on. A jsonPayload key\n // would need a log-based metric first; this one is queryable as shipped.\n httpRequest: {\n requestMethod: clampString(entry.proxy?.method, 16) || undefined,\n status,\n },\n jsonPayload: {\n // No ReportedErrorEvent `@type`: these are NOT ingested into Error\n // Reporting. A function timeout has no stack, would group as one giant\n // bucket, and would drown the real grouped errors the hook reports.\n source: clampString(entry.source, 32) || undefined,\n level: clampString(entry.level, 16) || undefined,\n type: clampString(entry.type, 32) || undefined,\n route: clampString(entry.path, 512) || undefined,\n entrypoint: clampString(entry.entrypoint, 256) || undefined,\n host: clampString(entry.host, 256) || undefined,\n environment: clampString(entry.environment, 32) || undefined,\n region: clampString(entry.executionRegion, 32) || undefined,\n project: clampString(entry.projectName, 64) || undefined,\n projectId: clampString(entry.projectId, 64) || undefined,\n deploymentId: clampString(entry.deploymentId, 64) || undefined,\n requestId: clampString(entry.requestId, 64) || undefined,\n logId: clampString(entry.id, 64) || undefined,\n statusCode:\n typeof entry.statusCode === 'number' ? entry.statusCode : undefined,\n proxyStatusCode:\n typeof entry.proxy?.statusCode === 'number'\n ? entry.proxy.statusCode\n : undefined,\n // Clamped like the beacon's own message. This is where \"Task timed out\n // after 10.01 seconds\" lives, which is the whole triage value of the\n // platform-5xx case.\n message: clampString(entry.message, MAX_MESSAGE) || undefined,\n },\n }\n}\n\n/** What one delivery did, for the response body, the tests and the caller. */\nexport interface DrainIngestResult {\n /** Entries in the delivery. */\n received: number\n /** Entries that passed the receiver-path and 5xx gates. */\n matched: number\n /** Entries actually written to Cloud Logging. */\n forwarded: number\n /** Entries dropped by the per-window budget — REPORTED, never silent. */\n suppressed: number\n /** Set when nothing could be written at all; a stable code, never a message. */\n code?: 'no-credential' | 'transport' | `http-${number}`\n}\n\n/**\n * Where the write goes, and under whose credential.\n *\n * Injectable because the receiver has to be able to run somewhere that is NOT\n * a Vercel project this drain watches — a delivery POST is a request to\n * whatever hosts it, and a request produces a log the same drain then\n * delivers, which is the AGL-1921 feedback loop. Vercel's drain `sampling`\n * rules look like the answer and are NOT: measured 2026-08-26, a single\n * `{rate: 0}` rule with no path prefix — literally \"drop everything\" — changed\n * delivery volume from 31 to 32 per five minutes. The whole `schemas.log`\n * filter block is accepted by the API, echoed back on `GET`, and never\n * applied. Separation is what stops the loop.\n *\n * The drain's newer top-level OData `filter` IS applied, and is what keeps the\n * delivery volume down (AGL-4121). It cannot replace the gate here: Vercel's\n * `log/statusCode` reads only `proxy.statusCode`, so the drains drop what is\n * proven healthy and this module still decides what is a server error.\n *\n * The default keeps every existing caller on the Firebase admin credential.\n * A receiver hosted off Vercel (Cloud Run in `aglyn-main`) passes its own\n * resolver instead and never imports `firebase-admin` at all, which is what\n * lets this module be bundled for it without dragging the SDK along.\n */\nexport interface DrainIngestOptions {\n /**\n * Resolve the Cloud Logging bearer token and project. Returning `null`\n * means \"no credential\" and the delivery is dropped, reported, and answered\n * 200 — never an error, because Vercel disables a drain whose endpoint\n * fails often enough.\n */\n target?: () => Promise<{ token: string; projectId: string } | null>\n}\n\n/**\n * Ingest ONE verified delivery: filter, budget, then a single batched write.\n *\n * Never throws. Vercel disables a drain whose endpoint fails often enough, so\n * a receiver that propagated a Logging outage would end by turning itself off\n * during the incident it exists to report.\n */\nexport async function ingestDrainDelivery(\n entries: readonly VercelDrainEntry[],\n options?: DrainIngestOptions,\n): Promise<DrainIngestResult> {\n const received = entries.length\n const matched = selectForwardableEntries(entries)\n const result: DrainIngestResult = {\n received,\n matched: matched.length,\n forwarded: 0,\n suppressed: 0,\n }\n if (!matched.length) return result\n\n const now = Date.now()\n if (now - drainWindowStartedAt >= DRAIN_WINDOW_MS) {\n if (drainSuppressed > 0) {\n // ⚠️ The lossiness is REPORTED. `level: \"warning\"`, so guard (b) in\n // RECEIVER_ROUTE_PATH keeps this line from ever draining back in.\n console.warn(\n JSON.stringify({\n tag: 'AGL-1921:vercel-log-drain',\n suppressed: drainSuppressed,\n written: drainWritten,\n windowMs: DRAIN_WINDOW_MS,\n }),\n )\n }\n drainWindowStartedAt = now\n drainWritten = 0\n drainSuppressed = 0\n }\n\n const room = Math.max(0, DRAIN_BUDGET_PER_WINDOW - drainWritten)\n const writable = matched.slice(0, room)\n const suppressed = matched.length - writable.length\n if (suppressed > 0) drainSuppressed += suppressed\n result.suppressed = suppressed\n if (!writable.length) return result\n\n const target = await (options?.target ?? defaultLoggingTarget)()\n if (!target) {\n console.warn(\n JSON.stringify({\n tag: 'AGL-1921:vercel-log-drain',\n drop: writable.length,\n reason: 'no-credential',\n }),\n )\n result.code = 'no-credential'\n return result\n }\n\n try {\n const response = await fetch(\n 'https://logging.googleapis.com/v2/entries:write',\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${target.token}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n logName: `projects/${target.projectId}/logs/${VERCEL_RUNTIME_LOG_ID}`,\n resource: { type: 'global' },\n entries: writable.map(toLogEntry),\n }),\n signal: AbortSignal.timeout(WRITE_TIMEOUT_MS),\n },\n )\n if (!response.ok) {\n console.warn(\n JSON.stringify({\n tag: 'AGL-1921:vercel-log-drain',\n status: response.status,\n drop: writable.length,\n }),\n )\n result.code = `http-${response.status}`\n return result\n }\n drainWritten += writable.length\n result.forwarded = writable.length\n return result\n } catch (error) {\n console.warn(\n JSON.stringify({\n tag: 'AGL-1921:vercel-log-drain',\n transport: String(error).slice(0, 200),\n }),\n )\n result.code = 'transport'\n return result\n }\n}\n"],"names":["defaultLoggingTarget","beaconLoggingTarget","VERCEL_RUNTIME_LOG_ID","DRAIN_SECRET_ENV","RECEIVER_ROUTE_PATH","LOCKDOWN_NOTICE_ROUTE_PATH","DRAIN_BUDGET_PER_WINDOW","DRAIN_WINDOW_MS","drainWindowStartedAt","drainWritten","drainSuppressed","MAX_MESSAGE","WRITE_TIMEOUT_MS","resetDrainBudgetForTests","clampString","value","max","slice","parseDrainPayload","rawBody","body","trim","parsed","JSON","parse","Array","isArray","filter","entry","Boolean","entries","line","split","trimmed","push","isReceiverEntry","paths","path","proxy","some","pathname","startsWith","isLockdownNoticeEntry","level","type","statuses","statusCode","status","length","HEALTH_ROUTE_PREFIX","isHealthContractEntry","isServerErrorEntry","proxyStatus","selectForwardableEntries","toLogEntry","undefined","severity","httpRequest","requestMethod","method","jsonPayload","source","route","entrypoint","host","environment","region","executionRegion","project","projectName","projectId","deploymentId","requestId","logId","id","proxyStatusCode","message","ingestDrainDelivery","options","received","matched","result","forwarded","suppressed","now","Date","console","warn","stringify","tag","written","windowMs","room","Math","writable","target","drop","reason","code","response","fetch","headers","Authorization","token","logName","resource","map","signal","AbortSignal","timeout","ok","error","transport","String"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuDC,GAED;;;;;;;;;;;CAWC,GACD,eAAeA;IAIb,MAAM,EAAEC,mBAAmB,EAAE,GAAG,MAAM,MAAM,CAAC;IAC7C,OAAOA;AACT;AAEA;;;;;CAKC,GACD,OAAO,MAAMC,wBAAwB,iBAAgB;AAErD,6EAA6E,GAC7E,OAAO,MAAMC,mBAAmB,0BAAyB;AAEzD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmCC,GACD,OAAO,MAAMC,sBAAsB,iBAAgB;AAEnD;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,MAAMC,6BAA6B,cAAa;AAEvD;;;;;;;CAOC,GACD,MAAMC,0BAA0B;AAChC,MAAMC,kBAAkB;AACxB,IAAIC,uBAAuB;AAC3B,IAAIC,eAAe;AACnB,IAAIC,kBAAkB;AAEtB,MAAMC,cAAc;AACpB,MAAMC,mBAAmB;AAEzB,4EAA4E,GAC5E,OAAO,SAASC;IACdL,uBAAuB;IACvBC,eAAe;IACfC,kBAAkB;AACpB;AAiCA,SAASI,YAAYC,KAAc,EAAEC,GAAW;IAC9C,OAAO,OAAOD,UAAU,WAAWA,MAAME,KAAK,CAAC,GAAGD,OAAO;AAC3D;AAEA;;;;;;;;;CASC,GACD,OAAO,SAASE,kBAAkBC,OAAe;IAC/C,MAAMC,OAAOD,QAAQE,IAAI;IACzB,IAAI,CAACD,MAAM,OAAO,EAAE;IACpB,IAAI;QACF,MAAME,SAAkBC,KAAKC,KAAK,CAACJ;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,CAAC,KAAK,EAAEC,SAASpD,MAAM,EAAE;YACvC,OAAOkC;QACT;QACAxE,gBAAgBqF,SAAS9C,MAAM;QAC/BiC,OAAOC,SAAS,GAAGY,SAAS9C,MAAM;QAClC,OAAOiC;IACT,EAAE,OAAO8B,OAAO;QACdzB,QAAQC,IAAI,CACVhE,KAAKiE,SAAS,CAAC;YACbC,KAAK;YACLuB,WAAWC,OAAOF,OAAO9F,KAAK,CAAC,GAAG;QACpC;QAEFgE,OAAOiB,IAAI,GAAG;QACd,OAAOjB;IACT;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/vercel-log-drain.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The Vercel log-drain receiver (AGL-1921, third and last arm).\n *\n * ## Why this arm exists at all\n *\n * The two arms already shipped both start from OUR code running. The\n * `onRequestError` hook (`reportServerError`) sees a render or route handler\n * throw; `/api/health/server-errors` grades the markers that hook writes.\n * Neither can see:\n *\n * - an error that kills the process before the hook runs,\n * - a platform-level 5xx that never reaches our code at all — a function\n * timeout, an OOM kill, a cold-start 502,\n * - anything thrown in the edge runtime.\n *\n * A log drain sees all three, because Vercel emits the request log whether or\n * not our code got far enough to have an opinion. That is why this is the arm\n * that closes the issue rather than a fourth partial view.\n *\n * ## The shape of the risk, and what each rule below buys\n *\n * A drain streams EVERY request log for both projects. The account's whole\n * monitoring budget is about $20/month, so the dangerous failure mode here is\n * not missing an error — it is faithfully forwarding a million healthy 200s\n * into Cloud Logging and getting a bill for it. Hence, in order:\n *\n * 1. **Signature first, fail closed.** HMAC-SHA1 of the RAW body keyed by the\n * drain secret, timing-safe compared. Unsigned means unwritten, always.\n * 2. **Filter before writing.** `isServerErrorEntry` is the cost gate: an\n * entry that is not a server error costs one predicate and zero writes.\n * 3. **Never our own route.** See `RECEIVER_ROUTE_PATH`.\n * 4. **Never a deliberate 5xx.** A 503 is how the lockdown notice and every\n * health contract SAY something, and forwarding a verdict as a fault makes\n * the stream unreadable: measured over the 48 hours to 2026-09-09, 229 of\n * the 251 entries in this log were `/api/health/*` reporting degraded and\n * 22 were the only real outage in the window. See `isLockdownNoticeEntry`\n * and `isHealthContractEntry` (AGL-2709). A closed site's notice is the\n * third: `isSiteNoticeEntry`.\n * 5. **A per-instance budget per window**, with suppression REPORTED. A\n * monitoring path that hides its own lossiness is the bug shape this repo\n * keeps rediscovering.\n *\n * ## Where it writes, and why not next door\n *\n * `vercel-runtime`, DELIBERATELY NOT `server-errors`. That log is the\n * `onRequestError` hook's, and the alert policy\n * `projects/aglyn-main/alertPolicies/11610705614308437855` keys on it. A 500\n * our code threw is seen by BOTH arms, so merging the streams would count one\n * incident twice and make triage start by asking which arm saw it. The same\n * separation `client-errors` and `server-errors` already keep, for the same\n * reason.\n *\n * The entries carry a real `httpRequest.status`, which is what makes the\n * policy AGL-1921 originally specified — a log filter on logName matching\n * \"vercel\" and httpRequest.status at or above 500 — expressible without a\n * log-based metric on a jsonPayload field first.\n */\n\n/**\n * LAZY, and that is load-bearing rather than stylistic (AGL-1921, 2026-08-26).\n *\n * `client-error-report` reaches `firebase-admin`. A static import here would\n * pull the whole SDK into anything that bundles this module — including the\n * Cloud Run receiver, whose entire reason for existing is to run this gate\n * OFF Vercel with nothing but `node:crypto` and a metadata-server token. That\n * receiver always supplies its own {@link DrainIngestOptions.target}, so this\n * path is never reached there and the SDK is never resolved.\n *\n * Called through `defaultLoggingTarget` below, never at module scope.\n */\nasync function defaultLoggingTarget(): Promise<{\n token: string\n projectId: string\n} | null> {\n const { beaconLoggingTarget } = await import('./client-error-report')\n return beaconLoggingTarget()\n}\n\n/**\n * The log id the drain writes to. Contains \"vercel\" on purpose: the alert\n * policy `projects/aglyn-main/alertPolicies/14031689508473384486` matches\n * `logName=~\"vercel\"`, so the name is load-bearing. Renaming this log without\n * repointing that policy silences the platform-5xx arm.\n */\nexport const VERCEL_RUNTIME_LOG_ID = 'vercel-runtime'\n\n/** The env var holding the drain's signature secret. Fails closed if unset. */\nexport const DRAIN_SECRET_ENV = 'VERCEL_LOG_DRAIN_SECRET'\n\n/**\n * The receiver's own path — the FEEDBACK-LOOP GUARD (requirement 5).\n *\n * ⚠️ HISTORICAL, AND KEPT AS DEFENCE IN DEPTH (2026-08-26). The receiver USED\n * to run on `aglyn-console`, whose logs the console drain collects, and the\n * two cuts below were the answer to one receiver 500 draining back in.\n *\n * They were not enough, and the reason is worth stating plainly because the\n * docstring that used to live here got it wrong: **both cuts are about the\n * WRITE, and the cost was the DELIVERY.** Nothing inside a receiver can\n * decline to be requested, and every delivery POST is itself a request that\n * produces a log the same drain then delivers. Measured at 695K invocations\n * in nine hours. Vercel's drain `sampling` rules are not a fix either — a\n * single `{rate: 0}` rule with no path prefix moved delivery volume from 31\n * to 32 per five minutes, i.e. the whole `schemas.log` filter block is stored\n * and never applied.\n *\n * The receiver now lives OFF Vercel, at `cloud/log-drain` on Cloud Run, which\n * no drain watches — so the loop is structurally impossible rather than\n * filtered against. These cuts stay because they cost nothing and they are\n * the backstop if anyone ever mounts this gate on a Vercel route again.\n *\n * Two structural cuts, not one:\n *\n * a. Every entry whose path is this route is dropped before the 5xx filter —\n * so even the receiver's OWN 500s can never be forwarded, by anything, at\n * any budget. It is not \"we try not to error\"; it is that its errors are\n * unforwardable.\n * b. Every line this module logs about itself is `console.warn`, i.e. Vercel\n * `level: \"warning\"`, and the filter forwards only 5xx and `fatal`. A\n * suppression summary drained back in is therefore dropped a second time,\n * on a different property, by a different rule.\n *\n * Matched as a PREFIX so `/api/log-drain`, a future `/api/log-drain/test` and\n * the query-bearing `proxy.path` form all fall on the same side of it.\n */\nexport const RECEIVER_ROUTE_PATH = '/api/log-drain'\n\n/**\n * The lockdown notice route — a route whose 503 is the FEATURE, not a fault.\n *\n * `apps/tenant/app/api/locked/route.ts` answers every request with a real 503\n * carrying `Retry-After`, and the middleware rewrites every path of a locked\n * or bandwidth-capped host to it. That status is deliberate: a takedown\n * notice answering 200 would tell crawlers and uptime checks the site is\n * fine, which is the whole reason the notice is a route handler rather than a\n * page.\n *\n * Forwarded, it is indistinguishable from an outage. One suspended host being\n * crawled emits a 5xx per request, forever, into the arm whose only consumer\n * is an alert policy — so the policy fires on a working feature and the next\n * real incident arrives in a stream that is already red.\n *\n * Matched EXACTLY, not as a prefix: the notice is one path, and a future\n * `/api/locked/*` would be a different route with no such guarantee about its\n * status.\n */\nexport const LOCKDOWN_NOTICE_ROUTE_PATH = '/api/locked'\n\n/**\n * Per-instance write budget, mirroring `reportServerError`'s (same file\n * neighbourhood, same rationale): the failure being watched is a SPIKE, and a\n * spike is when an unbounded forwarder turns one incident into a second one\n * denominated in dollars. 60 entries a minute per instance is far more than\n * any threshold policy needs to cross — the shape of the spike survives; the\n * bill does not follow it.\n */\nconst DRAIN_BUDGET_PER_WINDOW = 60\nconst DRAIN_WINDOW_MS = 60_000\nlet drainWindowStartedAt = 0\nlet drainWritten = 0\nlet drainSuppressed = 0\n\nconst MAX_MESSAGE = 1_024\nconst WRITE_TIMEOUT_MS = 4_000\n\n/** Reset the budget counters. Test seam only — never called in production. */\nexport function resetDrainBudgetForTests(): void {\n drainWindowStartedAt = 0\n drainWritten = 0\n drainSuppressed = 0\n}\n\n/**\n * One log entry as a Vercel drain delivers it. Only the fields this receiver\n * reads are named; the wire object carries many more (client IP, user agent,\n * referer, the query-bearing `proxy.path`) which are deliberately NOT in this\n * type, because a field that has no name here cannot be forwarded by accident.\n */\nexport interface VercelDrainEntry {\n id?: string\n deploymentId?: string\n projectId?: string\n projectName?: string\n source?: string\n host?: string\n timestamp?: number\n level?: string\n type?: string\n message?: string\n path?: string\n entrypoint?: string\n requestId?: string\n statusCode?: number\n environment?: string\n executionRegion?: string\n proxy?: {\n method?: string\n statusCode?: number\n path?: string\n pathType?: string\n }\n}\n\nfunction clampString(value: unknown, max: number): string {\n return typeof value === 'string' ? value.slice(0, max) : ''\n}\n\n/**\n * The entries in one delivery, in either format Vercel will send.\n *\n * `json` delivers an array (and, per the reference's own example, sometimes a\n * newline-separated sequence of objects); `ndjson` delivers one object per\n * line. Parsing both means the drain's `deliveryFormat` can be changed in the\n * dashboard without a deploy, and a malformed line is skipped rather than\n * failing the whole delivery — Vercel disables a drain that errors too often,\n * so a receiver that 500s on one bad line silences itself.\n */\nexport function parseDrainPayload(rawBody: string): VercelDrainEntry[] {\n const body = rawBody.trim()\n if (!body) return []\n try {\n const parsed: unknown = JSON.parse(body)\n if (Array.isArray(parsed)) {\n return parsed.filter(\n (entry): entry is VercelDrainEntry =>\n Boolean(entry) && typeof entry === 'object',\n )\n }\n if (parsed && typeof parsed === 'object')\n return [parsed as VercelDrainEntry]\n } catch {\n // Not a single JSON document — fall through to line-by-line.\n }\n const entries: VercelDrainEntry[] = []\n for (const line of body.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed) continue\n try {\n const parsed: unknown = JSON.parse(trimmed)\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n entries.push(parsed as VercelDrainEntry)\n }\n } catch {\n // One unreadable line never fails a delivery.\n }\n }\n return entries\n}\n\n/** Does this entry describe the receiver's own route? See RECEIVER_ROUTE_PATH. */\nexport function isReceiverEntry(entry: VercelDrainEntry): boolean {\n const paths = [entry.path, entry.proxy?.path]\n return paths.some((path) => {\n if (typeof path !== 'string') return false\n // `proxy.path` carries the query string; compare the path part only.\n const [pathname] = path.split('?')\n return (\n pathname === RECEIVER_ROUTE_PATH ||\n pathname.startsWith(`${RECEIVER_ROUTE_PATH}/`)\n )\n })\n}\n\n/**\n * Is this the lockdown notice serving its deliberate 503? See\n * {@link LOCKDOWN_NOTICE_ROUTE_PATH}.\n *\n * Narrow on purpose — the route being exempt must not make the route\n * unwatchable. Only a clean 503 is excused: a 500 the handler threw, the\n * `statusCode -1` of a crashed lambda, and a `fatal` line all still forward,\n * because those say the notice itself is broken and a locked host is then\n * serving nothing at all.\n */\nexport function isLockdownNoticeEntry(entry: VercelDrainEntry): boolean {\n if (entry.level === 'fatal' || entry.type === 'fatal') return false\n const statuses = [entry.statusCode, entry.proxy?.statusCode].filter(\n (status): status is number => typeof status === 'number',\n )\n if (!statuses.length || statuses.some((status) => status !== 503))\n return false\n return [entry.path, entry.proxy?.path].some((path) => {\n if (typeof path !== 'string') return false\n // `proxy.path` carries the query string; compare the path part only.\n const [pathname] = path.split('?')\n return pathname === LOCKDOWN_NOTICE_ROUTE_PATH\n })\n}\n\n/**\n * The health contract's routes, whose 503 is a VERDICT and not a fault.\n *\n * Prefix, not an exact path: every endpoint under it speaks the same contract\n * — `healthHttpStatus` answers 200 while a check reports ok and 503 the moment\n * it reports degraded — so `/api/health`, `/api/health/crons` and\n * `/api/health/render/site` are all the same case.\n */\nexport const HEALTH_ROUTE_PREFIX = '/api/health'\n\n/**\n * Is this a health endpoint answering 503 because it is doing its job?\n * (AGL-2709)\n *\n * ⚠️ THE STREAM WAS 91% THIS. Measured over the 48 hours to 2026-09-09, the\n * drain forwarded 251 entries into `vercel-runtime`. **229 were `/api/health/*`\n * answering 503** — `crons` 113, `funnel` 73, `server-errors` 18 — and 22 were\n * the AGL-2708 outage, the only real server errors in the window. The policy\n * on that log (`logName=~\"vercel\" AND severity>=ERROR`, one notification an\n * hour) therefore mails about a working health check for as long as any\n * subsystem is degraded: `/api/health/crons` was CORRECTLY reporting a broken\n * job for six hours on 2026-09-07, which is six hours of \"server errors\" mail\n * arriving in the same inbox that then had to notice 04:02 on 2026-09-09.\n *\n * Excusing it removes a DUPLICATE, not a signal, and the reason is structural\n * rather than a judgement call: every `/api/health/*` route both apps ship has\n * a monitor reading it, and `evaluateSubsystemReaders` fails the build if one\n * ever does not. The 503 is already on the uptime probe's board, in an\n * UptimeRobot monitor and on `docs.aglyn.com/status`, said in a body that\n * names WHICH check failed — which the drain entry never could.\n *\n * Narrow in exactly the same three ways as {@link isLockdownNoticeEntry}, and\n * each one is load-bearing:\n *\n * - a clean 503 only. A 500 the handler threw means the health route itself\n * is broken, and a check that cannot answer must never look calm;\n * - never a `fatal` line, which is process death rather than a verdict;\n * - never `statusCode -1`, the crashed-lambda sentinel, which is not 503 and\n * so fails the status test above.\n */\nexport function isHealthContractEntry(entry: VercelDrainEntry): boolean {\n if (entry.level === 'fatal' || entry.type === 'fatal') return false\n const statuses = [entry.statusCode, entry.proxy?.statusCode].filter(\n (status): status is number => typeof status === 'number',\n )\n if (!statuses.length || statuses.some((status) => status !== 503))\n return false\n return [entry.path, entry.proxy?.path].some((path) => {\n if (typeof path !== 'string') return false\n // `proxy.path` carries the query string; compare the path part only.\n const [pathname] = path.split('?')\n return (\n pathname === HEALTH_ROUTE_PREFIX ||\n pathname.startsWith(`${HEALTH_ROUTE_PREFIX}/`)\n )\n })\n}\n\n/**\n * The path Vercel stamps on an entry the MIDDLEWARE wrote (`source: edge`,\n * `type: middleware-invocation`), rather than a route pattern.\n */\nexport const MIDDLEWARE_ENTRY_PATH = '_middleware'\n\n/**\n * Is this the middleware sending a closed site's notice as its 503?\n *\n * Since AGL-4110 a site in maintenance or preview answers the public with its\n * own notice page AS a 503 with `Retry-After`, and the middleware is the only\n * layer that can set that status, so the drain sees it as a `_middleware`\n * entry with status 503. Forwarded, every visit to a closed site paged the\n * operator as \"Server errors\": on 2026-11-05 nine of them came from two demo\n * sites in maintenance and kept the AGL-1921 policy's incident open all day.\n *\n * The middleware has no other 503. The platform's own middleware failures\n * are `MIDDLEWARE_INVOCATION_FAILED` (500) and `MIDDLEWARE_INVOCATION_TIMEOUT`\n * (504), and a crash is `-1` or a `fatal` line, so all of those still\n * forward. Narrow in the same three ways as {@link isLockdownNoticeEntry}.\n */\nexport function isSiteNoticeEntry(entry: VercelDrainEntry): boolean {\n if (entry.level === 'fatal' || entry.type === 'fatal') return false\n const statuses = [entry.statusCode, entry.proxy?.statusCode].filter(\n (status): status is number => typeof status === 'number',\n )\n if (!statuses.length || statuses.some((status) => status !== 503))\n return false\n return entry.path === MIDDLEWARE_ENTRY_PATH\n}\n\n/**\n * THE COST GATE (requirement 3). Everything false here is dropped unwritten.\n *\n * What counts as a server error:\n *\n * - `statusCode >= 500` or `proxy.statusCode >= 500` — the platform 5xx this\n * whole arm exists for, including the ones our code never saw.\n * - `statusCode === -1` — documented as \"no response returned and the lambda\n * crashed\". The OOM/hard-crash case, and the single most important entry\n * shape the `onRequestError` hook is structurally unable to produce.\n * - `level === 'fatal'` or `type === 'fatal'` — the edge-runtime and\n * process-death shape, which may carry no status at all.\n *\n * What deliberately does NOT count:\n *\n * - `level === 'error'`. That is any `console.error`, including the fail-soft\n * warn/error lines the beacons themselves write, and forwarding it would\n * mean paying per line for a stream the `onRequestError` hook already\n * covers properly. If an errored request matters, it has a status.\n * - `proxy.statusCode === -1`. Same sentinel, opposite meaning: on the proxy\n * object it documents a BACKGROUND REVALIDATION, which is a healthy ISR\n * refresh. Reading it as a crash would forward a steady trickle of normal\n * traffic forever — the exact bill this gate exists to prevent.\n */\nexport function isServerErrorEntry(entry: VercelDrainEntry): boolean {\n if (typeof entry.statusCode === 'number') {\n if (entry.statusCode >= 500) return true\n if (entry.statusCode === -1) return true\n }\n const proxyStatus = entry.proxy?.statusCode\n if (typeof proxyStatus === 'number' && proxyStatus >= 500) return true\n if (entry.level === 'fatal' || entry.type === 'fatal') return true\n return false\n}\n\n/**\n * Everything above, in the order the cost argument requires.\n * Exported so the tests can assert the gate without a transport.\n */\nexport function selectForwardableEntries(\n entries: readonly VercelDrainEntry[],\n): VercelDrainEntry[] {\n return entries.filter(\n (entry) =>\n !isReceiverEntry(entry) &&\n !isLockdownNoticeEntry(entry) &&\n !isHealthContractEntry(entry) &&\n !isSiteNoticeEntry(entry) &&\n isServerErrorEntry(entry),\n )\n}\n\n/**\n * One Cloud Logging entry, carrying ONLY fields that are already inside the\n * envelope the shipped beacons send (requirement 8).\n *\n * Explicitly absent, and each for a reason:\n * `proxy.path` (query string — the AGL-1538 boundary is origin+pathname and\n * this is the same boundary), `proxy.clientIp` and `proxy.userAgent` and\n * `proxy.referer` (visitor identity; also why Vercel's own IP-visibility\n * toggle exists), request or response bodies (never delivered, never wanted).\n * `path` IS forwarded because Vercel documents it as the function or dynamic\n * path — the route PATTERN, which is what you group and alert on anyway, and\n * exactly what `reportServerError` already sends as `route`.\n */\nfunction toLogEntry(entry: VercelDrainEntry): Record<string, unknown> {\n const status =\n typeof entry.statusCode === 'number' && entry.statusCode >= 0\n ? entry.statusCode\n : typeof entry.proxy?.statusCode === 'number' &&\n entry.proxy.statusCode >= 0\n ? entry.proxy.statusCode\n : undefined\n return {\n severity: 'ERROR',\n // The structured field the AGL-1921 policy matches on. A jsonPayload key\n // would need a log-based metric first; this one is queryable as shipped.\n httpRequest: {\n requestMethod: clampString(entry.proxy?.method, 16) || undefined,\n status,\n },\n jsonPayload: {\n // No ReportedErrorEvent `@type`: these are NOT ingested into Error\n // Reporting. A function timeout has no stack, would group as one giant\n // bucket, and would drown the real grouped errors the hook reports.\n source: clampString(entry.source, 32) || undefined,\n level: clampString(entry.level, 16) || undefined,\n type: clampString(entry.type, 32) || undefined,\n route: clampString(entry.path, 512) || undefined,\n entrypoint: clampString(entry.entrypoint, 256) || undefined,\n host: clampString(entry.host, 256) || undefined,\n environment: clampString(entry.environment, 32) || undefined,\n region: clampString(entry.executionRegion, 32) || undefined,\n project: clampString(entry.projectName, 64) || undefined,\n projectId: clampString(entry.projectId, 64) || undefined,\n deploymentId: clampString(entry.deploymentId, 64) || undefined,\n requestId: clampString(entry.requestId, 64) || undefined,\n logId: clampString(entry.id, 64) || undefined,\n statusCode:\n typeof entry.statusCode === 'number' ? entry.statusCode : undefined,\n proxyStatusCode:\n typeof entry.proxy?.statusCode === 'number'\n ? entry.proxy.statusCode\n : undefined,\n // Clamped like the beacon's own message. This is where \"Task timed out\n // after 10.01 seconds\" lives, which is the whole triage value of the\n // platform-5xx case.\n message: clampString(entry.message, MAX_MESSAGE) || undefined,\n },\n }\n}\n\n/** What one delivery did, for the response body, the tests and the caller. */\nexport interface DrainIngestResult {\n /** Entries in the delivery. */\n received: number\n /** Entries that passed the receiver-path and 5xx gates. */\n matched: number\n /** Entries actually written to Cloud Logging. */\n forwarded: number\n /** Entries dropped by the per-window budget — REPORTED, never silent. */\n suppressed: number\n /** Set when nothing could be written at all; a stable code, never a message. */\n code?: 'no-credential' | 'transport' | `http-${number}`\n}\n\n/**\n * Where the write goes, and under whose credential.\n *\n * Injectable because the receiver has to be able to run somewhere that is NOT\n * a Vercel project this drain watches — a delivery POST is a request to\n * whatever hosts it, and a request produces a log the same drain then\n * delivers, which is the AGL-1921 feedback loop. Vercel's drain `sampling`\n * rules look like the answer and are NOT: measured 2026-08-26, a single\n * `{rate: 0}` rule with no path prefix — literally \"drop everything\" — changed\n * delivery volume from 31 to 32 per five minutes. The whole `schemas.log`\n * filter block is accepted by the API, echoed back on `GET`, and never\n * applied. Separation is what stops the loop.\n *\n * The drain's newer top-level OData `filter` IS applied, and is what keeps the\n * delivery volume down (AGL-4121). It cannot replace the gate here: Vercel's\n * `log/statusCode` reads only `proxy.statusCode`, so the drains drop what is\n * proven healthy and this module still decides what is a server error.\n *\n * The default keeps every existing caller on the Firebase admin credential.\n * A receiver hosted off Vercel (Cloud Run in `aglyn-main`) passes its own\n * resolver instead and never imports `firebase-admin` at all, which is what\n * lets this module be bundled for it without dragging the SDK along.\n */\nexport interface DrainIngestOptions {\n /**\n * Resolve the Cloud Logging bearer token and project. Returning `null`\n * means \"no credential\" and the delivery is dropped, reported, and answered\n * 200 — never an error, because Vercel disables a drain whose endpoint\n * fails often enough.\n */\n target?: () => Promise<{ token: string; projectId: string } | null>\n}\n\n/**\n * Ingest ONE verified delivery: filter, budget, then a single batched write.\n *\n * Never throws. Vercel disables a drain whose endpoint fails often enough, so\n * a receiver that propagated a Logging outage would end by turning itself off\n * during the incident it exists to report.\n */\nexport async function ingestDrainDelivery(\n entries: readonly VercelDrainEntry[],\n options?: DrainIngestOptions,\n): Promise<DrainIngestResult> {\n const received = entries.length\n const matched = selectForwardableEntries(entries)\n const result: DrainIngestResult = {\n received,\n matched: matched.length,\n forwarded: 0,\n suppressed: 0,\n }\n if (!matched.length) return result\n\n const now = Date.now()\n if (now - drainWindowStartedAt >= DRAIN_WINDOW_MS) {\n if (drainSuppressed > 0) {\n // ⚠️ The lossiness is REPORTED. `level: \"warning\"`, so guard (b) in\n // RECEIVER_ROUTE_PATH keeps this line from ever draining back in.\n console.warn(\n JSON.stringify({\n tag: 'AGL-1921:vercel-log-drain',\n suppressed: drainSuppressed,\n written: drainWritten,\n windowMs: DRAIN_WINDOW_MS,\n }),\n )\n }\n drainWindowStartedAt = now\n drainWritten = 0\n drainSuppressed = 0\n }\n\n const room = Math.max(0, DRAIN_BUDGET_PER_WINDOW - drainWritten)\n const writable = matched.slice(0, room)\n const suppressed = matched.length - writable.length\n if (suppressed > 0) drainSuppressed += suppressed\n result.suppressed = suppressed\n if (!writable.length) return result\n\n const target = await (options?.target ?? defaultLoggingTarget)()\n if (!target) {\n console.warn(\n JSON.stringify({\n tag: 'AGL-1921:vercel-log-drain',\n drop: writable.length,\n reason: 'no-credential',\n }),\n )\n result.code = 'no-credential'\n return result\n }\n\n try {\n const response = await fetch(\n 'https://logging.googleapis.com/v2/entries:write',\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${target.token}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n logName: `projects/${target.projectId}/logs/${VERCEL_RUNTIME_LOG_ID}`,\n resource: { type: 'global' },\n entries: writable.map(toLogEntry),\n }),\n signal: AbortSignal.timeout(WRITE_TIMEOUT_MS),\n },\n )\n if (!response.ok) {\n console.warn(\n JSON.stringify({\n tag: 'AGL-1921:vercel-log-drain',\n status: response.status,\n drop: writable.length,\n }),\n )\n result.code = `http-${response.status}`\n return result\n }\n drainWritten += writable.length\n result.forwarded = writable.length\n return result\n } catch (error) {\n console.warn(\n JSON.stringify({\n tag: 'AGL-1921:vercel-log-drain',\n transport: String(error).slice(0, 200),\n }),\n )\n result.code = 'transport'\n return result\n }\n}\n"],"names":["defaultLoggingTarget","beaconLoggingTarget","VERCEL_RUNTIME_LOG_ID","DRAIN_SECRET_ENV","RECEIVER_ROUTE_PATH","LOCKDOWN_NOTICE_ROUTE_PATH","DRAIN_BUDGET_PER_WINDOW","DRAIN_WINDOW_MS","drainWindowStartedAt","drainWritten","drainSuppressed","MAX_MESSAGE","WRITE_TIMEOUT_MS","resetDrainBudgetForTests","clampString","value","max","slice","parseDrainPayload","rawBody","body","trim","parsed","JSON","parse","Array","isArray","filter","entry","Boolean","entries","line","split","trimmed","push","isReceiverEntry","paths","path","proxy","some","pathname","startsWith","isLockdownNoticeEntry","level","type","statuses","statusCode","status","length","HEALTH_ROUTE_PREFIX","isHealthContractEntry","MIDDLEWARE_ENTRY_PATH","isSiteNoticeEntry","isServerErrorEntry","proxyStatus","selectForwardableEntries","toLogEntry","undefined","severity","httpRequest","requestMethod","method","jsonPayload","source","route","entrypoint","host","environment","region","executionRegion","project","projectName","projectId","deploymentId","requestId","logId","id","proxyStatusCode","message","ingestDrainDelivery","options","received","matched","result","forwarded","suppressed","now","Date","console","warn","stringify","tag","written","windowMs","room","Math","writable","target","drop","reason","code","response","fetch","headers","Authorization","token","logName","resource","map","signal","AbortSignal","timeout","ok","error","transport","String"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAwDC,GAED;;;;;;;;;;;CAWC,GACD,eAAeA;IAIb,MAAM,EAAEC,mBAAmB,EAAE,GAAG,MAAM,MAAM,CAAC;IAC7C,OAAOA;AACT;AAEA;;;;;CAKC,G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