@secondlayer/shared 15.3.3 → 15.4.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.
- package/dist/src/archive/range-digest.d.ts +7 -0
- package/dist/src/archive/semantic-digest-builder.d.ts +7 -0
- package/dist/src/classify/index.js +16 -2
- package/dist/src/classify/index.js.map +3 -3
- package/dist/src/coverage/index.d.ts +15 -1
- package/dist/src/coverage/index.js +57 -2
- package/dist/src/coverage/index.js.map +4 -4
- package/dist/src/crypto/secondlayer-webhook.js +16 -2
- package/dist/src/crypto/secondlayer-webhook.js.map +3 -3
- package/dist/src/crypto/secrets.d.ts +8 -2
- package/dist/src/crypto/secrets.js +21 -7
- package/dist/src/crypto/secrets.js.map +3 -3
- package/dist/src/db/index.d.ts +15 -1
- package/dist/src/db/index.js +29 -7
- package/dist/src/db/index.js.map +5 -5
- package/dist/src/db/queries/chain-reorgs.d.ts +7 -0
- package/dist/src/db/queries/chain-reorgs.js +27 -7
- package/dist/src/db/queries/chain-reorgs.js.map +5 -5
- package/dist/src/db/queries/contracts.d.ts +21 -1
- package/dist/src/db/queries/contracts.js +23 -1
- package/dist/src/db/queries/contracts.js.map +4 -4
- package/dist/src/db/queries/instance.d.ts +33 -5
- package/dist/src/db/queries/instance.js +224 -14
- package/dist/src/db/queries/instance.js.map +6 -5
- package/dist/src/db/queries/integrity.d.ts +84 -1
- package/dist/src/db/queries/integrity.js +430 -15
- package/dist/src/db/queries/integrity.js.map +8 -6
- package/dist/src/db/queries/subgraph-gaps.d.ts +18 -6
- package/dist/src/db/queries/subgraph-gaps.js +81 -14
- package/dist/src/db/queries/subgraph-gaps.js.map +3 -3
- package/dist/src/db/queries/subgraph-operations.d.ts +10 -1
- package/dist/src/db/queries/subgraph-operations.js +9 -5
- package/dist/src/db/queries/subgraph-operations.js.map +3 -3
- package/dist/src/db/queries/subgraphs.d.ts +11 -4
- package/dist/src/db/queries/subgraphs.js +13 -6
- package/dist/src/db/queries/subgraphs.js.map +4 -4
- package/dist/src/db/queries/sync-scope.d.ts +7 -0
- package/dist/src/db/queries/webhook-replays.d.ts +7 -0
- package/dist/src/db/queries/webhook-replays.js +20 -7
- package/dist/src/db/queries/webhook-replays.js.map +3 -3
- package/dist/src/db/queries/webhooks.d.ts +7 -0
- package/dist/src/db/queries/webhooks.js +20 -7
- package/dist/src/db/queries/webhooks.js.map +3 -3
- package/dist/src/db/schema.d.ts +7 -0
- package/dist/src/db/schema.js.map +2 -2
- package/dist/src/email/index.js +16 -2
- package/dist/src/email/index.js.map +3 -3
- package/dist/src/env.d.ts +8 -1
- package/dist/src/env.js +18 -3
- package/dist/src/env.js.map +3 -3
- package/dist/src/index.d.ts +59 -1
- package/dist/src/index.js +71 -8
- package/dist/src/index.js.map +8 -8
- package/dist/src/insights/index.d.ts +7 -0
- package/dist/src/insights/index.js +16 -2
- package/dist/src/insights/index.js.map +3 -3
- package/dist/src/leader.js +915 -27
- package/dist/src/leader.js.map +13 -6
- package/dist/src/logger.js +16 -2
- package/dist/src/logger.js.map +3 -3
- package/dist/src/node/local-client.d.ts +7 -0
- package/dist/src/node/tx-summary.js +16 -2
- package/dist/src/node/tx-summary.js.map +3 -3
- package/dist/src/queue/listener.js +27 -7
- package/dist/src/queue/listener.js.map +5 -5
- package/dist/src/schemas/index.js +2 -2
- package/dist/src/schemas/index.js.map +3 -3
- package/dist/src/schemas/subgraphs.js +2 -2
- package/dist/src/schemas/subgraphs.js.map +3 -3
- package/dist/src/types.d.ts +3 -0
- package/migrations/0197_subgraph_last_block_hash.ts +67 -0
- package/migrations/0198_blocks_event_count.ts +24 -0
- package/migrations/0199_transactions_height_tx_index_uniq.ts +77 -0
- package/migrations/0200_subgraphs_schema_name_unique.ts +39 -0
- package/migrations/0201_subgraph_gaps_range_check.ts +47 -0
- package/migrations/0202_instances_secrets_key_canary.ts +36 -0
- package/package.json +2 -2
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/db/queries/subgraph-operations.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import { type Kysely, sql } from \"kysely\";\nimport type {\n\tDatabase,\n\tSubgraphOperation,\n\tSubgraphOperationKind,\n\tSubgraphOperationStatus,\n} from \"../types.ts\";\n\nconst ACTIVE_STATUSES: SubgraphOperationStatus[] = [\"queued\", \"running\"];\n\nexport function isActiveSubgraphOperationConflict(err: unknown): boolean {\n\tif (!(err instanceof Error)) return false;\n\tconst candidate = err as Error & {\n\t\tcode?: string;\n\t\tconstraint?: string;\n\t\tconstraint_name?: string;\n\t};\n\treturn (\n\t\tcandidate.code === \"23505\" &&\n\t\t(candidate.constraint === \"subgraph_operations_active_unique\" ||\n\t\t\tcandidate.constraint_name === \"subgraph_operations_active_unique\")\n\t);\n}\n\nexport async function createSubgraphOperation(\n\tdb: Kysely<Database>,\n\tdata: {\n\t\tsubgraphId: string;\n\t\tsubgraphName: string;\n\t\taccountId?: string | null;\n\t\tkind: SubgraphOperationKind;\n\t\tfromBlock?: number;\n\t\ttoBlock?: number;\n\t\t/** 'light' | 'heavy' — claim budgets heavy ops. DB default 'heavy'. */\n\t\tweight?: \"light\" | \"heavy\";\n\t\testimatedEvents?: number | null;\n\t},\n): Promise<SubgraphOperation> {\n\t// Requeued backfills inherit the committed prefix of prior attempts over an\n\t// overlapping range — cancel/fail + requeue can't replay applied deltas.\n\tlet seededCursor: string | number | bigint | null = null;\n\tif (\n\t\tdata.kind === \"backfill\" &&\n\t\tdata.fromBlock != null &&\n\t\tdata.toBlock != null\n\t) {\n\t\tconst prior = await db\n\t\t\t.selectFrom(\"subgraph_operations\")\n\t\t\t.select((eb) => eb.fn.max(\"cursor_block\").as(\"max_cursor\"))\n\t\t\t.where(\"subgraph_id\", \"=\", data.subgraphId)\n\t\t\t.where(\"kind\", \"=\", \"backfill\")\n\t\t\t.where(\"status\", \"in\", [\"failed\", \"cancelled\"])\n\t\t\t.where(\"from_block\", \"<=\", data.toBlock)\n\t\t\t.where(\"to_block\", \">=\", data.fromBlock)\n\t\t\t.executeTakeFirst();\n\t\tseededCursor = prior?.max_cursor ?? null;\n\t}\n\treturn await db\n\t\t.insertInto(\"subgraph_operations\")\n\t\t.values({\n\t\t\tsubgraph_id: data.subgraphId,\n\t\t\tsubgraph_name: data.subgraphName,\n\t\t\taccount_id: data.accountId ?? null,\n\t\t\tkind: data.kind,\n\t\t\tfrom_block: data.fromBlock ?? null,\n\t\t\tto_block: data.toBlock ?? null,\n\t\t\t...(data.weight ? { weight: data.weight } : {}),\n\t\t\testimated_events: data.estimatedEvents ?? null,\n\t\t\tcursor_block: seededCursor,\n\t\t})\n\t\t.returningAll()\n\t\t.executeTakeFirstOrThrow();\n}\n\nexport async function findActiveSubgraphOperation(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n): Promise<SubgraphOperation | null> {\n\treturn (\n\t\t(await db\n\t\t\t.selectFrom(\"subgraph_operations\")\n\t\t\t.selectAll()\n\t\t\t.where(\"subgraph_id\", \"=\", subgraphId)\n\t\t\t.where(\"status\", \"in\", ACTIVE_STATUSES)\n\t\t\t.orderBy(\"created_at\", \"asc\")\n\t\t\t.executeTakeFirst()) ?? null\n\t);\n}\n\nexport async function requestSubgraphOperationCancel(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n): Promise<SubgraphOperation | null> {\n\treturn (\n\t\t(await db\n\t\t\t.updateTable(\"subgraph_operations\")\n\t\t\t.set({ cancel_requested: true, updated_at: new Date() })\n\t\t\t.where(\"subgraph_id\", \"=\", subgraphId)\n\t\t\t.where(\"status\", \"in\", ACTIVE_STATUSES)\n\t\t\t.returningAll()\n\t\t\t.executeTakeFirst()) ?? null\n\t);\n}\n\nexport async function requestSubgraphOperationsCancelForDelete(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n): Promise<SubgraphOperation[]> {\n\treturn await db\n\t\t.updateTable(\"subgraph_operations\")\n\t\t.set({ cancel_requested: true, updated_at: new Date() })\n\t\t.where(\"subgraph_id\", \"=\", subgraphId)\n\t\t.where(\"status\", \"in\", ACTIVE_STATUSES)\n\t\t.returningAll()\n\t\t.execute();\n}\n\n/**\n * Settle cancel-requested operations nobody is running: a queued one (no\n * runner ever claimed it) and a running one whose lock has lapsed (its runner\n * died without releasing the row; heartbeats renew the lock every 15s, so a\n * lapsed one is a dead process, not a slow one). Returns how many rows were\n * cancelled.\n *\n * An operation whose lock is still live is NEVER touched: its runner is\n * alive, and the only safe way to stop it is the runner observing\n * `cancel_requested` itself and releasing the row and advisory locks.\n */\nexport async function cancelOrphanedSubgraphOperations(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n): Promise<number> {\n\tconst cancelled = await db\n\t\t.updateTable(\"subgraph_operations\")\n\t\t.set({\n\t\t\tstatus: \"cancelled\",\n\t\t\tfinished_at: new Date(),\n\t\t\tlocked_by: null,\n\t\t\tlocked_until: null,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"subgraph_id\", \"=\", subgraphId)\n\t\t.where(\"cancel_requested\", \"=\", true)\n\t\t.where(\"status\", \"in\", ACTIVE_STATUSES)\n\t\t.where((eb) =>\n\t\t\teb.or([\n\t\t\t\teb(\"status\", \"=\", \"queued\"),\n\t\t\t\teb(\"locked_until\", \"is\", null),\n\t\t\t\teb(\"locked_until\", \"<\", sql<Date>`now()`),\n\t\t\t]),\n\t\t)\n\t\t.returning(\"id\")\n\t\t.execute();\n\treturn cancelled.length;\n}\n\n/**\n * Poll until no active subgraph operations remain for the subgraph or until\n * `timeoutMs` elapses. Returns true if all active operations cleared, false\n * if we timed out. Callers should use this before `DROP SCHEMA` so the active\n * processor has a chance to observe `cancel_requested` and release its row /\n * advisory locks. Without this, the DROP blocks behind the live transaction\n * and the API socket times out before the lock releases.\n */\nexport async function waitForSubgraphOperationsClear(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n\topts?: { timeoutMs?: number; pollMs?: number },\n): Promise<boolean> {\n\tconst timeoutMs = opts?.timeoutMs ?? 30_000;\n\tconst pollMs = opts?.pollMs ?? 500;\n\tconst deadline = Date.now() + timeoutMs;\n\twhile (Date.now() < deadline) {\n\t\tconst active = await db\n\t\t\t.selectFrom(\"subgraph_operations\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"subgraph_id\", \"=\", subgraphId)\n\t\t\t.where(\"status\", \"in\", ACTIVE_STATUSES)\n\t\t\t.limit(1)\n\t\t\t.executeTakeFirst();\n\t\tif (!active) return true;\n\t\tawait new Promise((r) => setTimeout(r, pollMs));\n\t}\n\treturn false;\n}\n\n/** Max concurrently-running 'heavy' ops (broad/non-sparse syncs). */\nconst HEAVY_OP_BUDGET = 2;\n\nexport async function claimSubgraphOperation(\n\tdb: Kysely<Database>,\n\tlockedBy: string,\n): Promise<SubgraphOperation | null> {\n\t// Fair queue: accounts with fewer currently-running operations are served first,\n\t// breaking ties by creation time. Prevents one user's long reindex from\n\t// starving other accounts.\n\tconst result = await sql<SubgraphOperation>`\n\t\tUPDATE subgraph_operations\n\t\tSET\n\t\t\tstatus = 'running',\n\t\t\tlocked_by = ${lockedBy},\n\t\t\tlocked_until = now() + interval '60 seconds',\n\t\t\tstarted_at = COALESCE(started_at, now()),\n\t\t\tupdated_at = now()\n\t\tWHERE id = (\n\t\t\tSELECT so.id\n\t\t\tFROM subgraph_operations so\n\t\t\tLEFT JOIN (\n\t\t\t\tSELECT account_id, COUNT(*) AS cnt\n\t\t\t\tFROM subgraph_operations\n\t\t\t\tWHERE status = 'running'\n\t\t\t\tGROUP BY account_id\n\t\t\t) rc ON so.account_id = rc.account_id\n\t\t\tWHERE\n\t\t\t\t(\n\t\t\t\t\tso.status = 'queued'\n\t\t\t\t\tOR (\n\t\t\t\t\t\tso.status = 'running'\n\t\t\t\t\t\tAND (so.locked_until IS NULL OR so.locked_until < now())\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t\t-- Heavy budget as an eligibility FILTER (not a post-claim refusal):\n\t\t\t\t-- a budget-blocked heavy op at the head must not starve the light\n\t\t\t\t-- ops behind it. Live-lock condition (locked_until > now()) keeps a\n\t\t\t\t-- STALE heavy op from blocking its own reclaim. Soft across\n\t\t\t\t-- concurrent claimers (can overshoot by one with multiple runners) —\n\t\t\t\t-- acceptable for the single-runner deployment.\n\t\t\t\tAND (\n\t\t\t\t\tso.weight = 'light'\n\t\t\t\t\tOR (\n\t\t\t\t\t\tSELECT COUNT(*)\n\t\t\t\t\t\tFROM subgraph_operations h\n\t\t\t\t\t\tWHERE h.status = 'running'\n\t\t\t\t\t\t\tAND h.weight = 'heavy'\n\t\t\t\t\t\t\tAND h.locked_until > now()\n\t\t\t\t\t\t\tAND h.id != so.id\n\t\t\t\t\t) < ${HEAVY_OP_BUDGET}\n\t\t\t\t)\n\t\t\tORDER BY\n\t\t\t\tCOALESCE(rc.cnt, 0) ASC,\n\t\t\t\tCASE WHEN so.status = 'queued' THEN 0 ELSE 1 END,\n\t\t\t\tso.created_at ASC\n\t\t\tFOR UPDATE OF so SKIP LOCKED\n\t\t\tLIMIT 1\n\t\t)\n\t\tRETURNING *\n\t`.execute(db);\n\treturn result.rows[0] ?? null;\n}\n\nexport async function heartbeatSubgraphOperation(\n\tdb: Kysely<Database>,\n\toperationId: string,\n\tlockedBy: string,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraph_operations\")\n\t\t.set({\n\t\t\tlocked_until: sql<Date>`now() + interval '60 seconds'`,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", operationId)\n\t\t.where(\"status\", \"=\", \"running\")\n\t\t.where(\"locked_by\", \"=\", lockedBy)\n\t\t.execute();\n}\n\nexport async function getSubgraphOperation(\n\tdb: Kysely<Database>,\n\toperationId: string,\n): Promise<SubgraphOperation | null> {\n\treturn (\n\t\t(await db\n\t\t\t.selectFrom(\"subgraph_operations\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", operationId)\n\t\t\t.executeTakeFirst()) ?? null\n\t);\n}\n\n/** Recent operations for a subgraph, newest first (for the status read API). */\nexport async function listSubgraphOperations(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n\tlimit = 20,\n): Promise<SubgraphOperation[]> {\n\treturn db\n\t\t.selectFrom(\"subgraph_operations\")\n\t\t.selectAll()\n\t\t.where(\"subgraph_id\", \"=\", subgraphId)\n\t\t.orderBy(\"created_at\", \"desc\")\n\t\t.limit(limit)\n\t\t.execute();\n}\n\nexport async function completeSubgraphOperation(\n\tdb: Kysely<Database>,\n\toperationId: string,\n\tlockedBy: string,\n\tprocessedBlocks: number,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraph_operations\")\n\t\t.set({\n\t\t\tstatus: \"completed\",\n\t\t\tfinished_at: new Date(),\n\t\t\tprocessed_blocks: processedBlocks,\n\t\t\tlocked_by: null,\n\t\t\tlocked_until: null,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", operationId)\n\t\t.where(\"locked_by\", \"=\", lockedBy)\n\t\t.execute();\n}\n\nexport async function cancelSubgraphOperation(\n\tdb: Kysely<Database>,\n\toperationId: string,\n\tlockedBy: string,\n\tprocessedBlocks: number,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraph_operations\")\n\t\t.set({\n\t\t\tstatus: \"cancelled\",\n\t\t\tfinished_at: new Date(),\n\t\t\tprocessed_blocks: processedBlocks,\n\t\t\tlocked_by: null,\n\t\t\tlocked_until: null,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", operationId)\n\t\t.where(\"locked_by\", \"=\", lockedBy)\n\t\t.execute();\n}\n\nexport async function failSubgraphOperation(\n\tdb: Kysely<Database>,\n\toperationId: string,\n\tlockedBy: string,\n\terror: string,\n\tprocessedBlocks?: number,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraph_operations\")\n\t\t.set({\n\t\t\tstatus: \"failed\",\n\t\t\tfinished_at: new Date(),\n\t\t\tprocessed_blocks: processedBlocks ?? null,\n\t\t\terror,\n\t\t\tlocked_by: null,\n\t\t\tlocked_until: null,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", operationId)\n\t\t.where(\"locked_by\", \"=\", lockedBy)\n\t\t.execute();\n}\n\n/**\n * 1-based position of a queued operation under the claim ordering (fairness →\n * queued-first → FIFO). The heavy-budget admission filter is NOT applied — a\n * heavy op's eligibility depends on runtime budget state — so the position is\n * approximate; render it as \"~N\". Returns null unless queued.\n */\nexport async function getOperationQueuePosition(\n\tdb: Kysely<Database>,\n\toperationId: string,\n): Promise<number | null> {\n\tconst result = await sql<{ rn: string | number }>`\n\t\tWITH candidates AS (\n\t\t\tSELECT\n\t\t\t\tso.id,\n\t\t\t\tROW_NUMBER() OVER (\n\t\t\t\t\tORDER BY\n\t\t\t\t\t\tCOALESCE(rc.cnt, 0) ASC,\n\t\t\t\t\t\tCASE WHEN so.status = 'queued' THEN 0 ELSE 1 END,\n\t\t\t\t\t\tso.created_at ASC\n\t\t\t\t) AS rn\n\t\t\tFROM subgraph_operations so\n\t\t\tLEFT JOIN (\n\t\t\t\tSELECT account_id, COUNT(*) AS cnt\n\t\t\t\tFROM subgraph_operations\n\t\t\t\tWHERE status = 'running'\n\t\t\t\tGROUP BY account_id\n\t\t\t) rc ON so.account_id = rc.account_id\n\t\t\tWHERE so.status = 'queued'\n\t\t)\n\t\tSELECT rn FROM candidates WHERE id = ${operationId}\n\t`.execute(db);\n\tconst rn = result.rows[0]?.rn;\n\treturn rn == null ? null : Number(rn);\n}\n\n/** Median duration (seconds) of the last 20 completed ops of a weight class —\n * the \"est. start\" multiplier for queued positions. Null with no history. */\nexport async function getRecentOperationMedianDuration(\n\tdb: Kysely<Database>,\n\tweight: \"light\" | \"heavy\",\n): Promise<number | null> {\n\tconst result = await sql<{ median: string | number | null }>`\n\t\tSELECT percentile_cont(0.5) WITHIN GROUP (\n\t\t\tORDER BY EXTRACT(EPOCH FROM (finished_at - started_at))\n\t\t) AS median\n\t\tFROM (\n\t\t\tSELECT started_at, finished_at\n\t\t\tFROM subgraph_operations\n\t\t\tWHERE status = 'completed'\n\t\t\t\tAND weight = ${weight}\n\t\t\t\tAND started_at IS NOT NULL\n\t\t\t\tAND finished_at IS NOT NULL\n\t\t\tORDER BY finished_at DESC\n\t\t\tLIMIT 20\n\t\t) recent\n\t`.execute(db);\n\tconst median = result.rows[0]?.median;\n\treturn median == null ? null : Number(median);\n}\n\n/** Progress-flush hook: events processed so far on a running operation. */\nexport async function updateOperationProcessedEvents(\n\tdb: Kysely<Database>,\n\toperationId: string,\n\tprocessedEvents: number,\n): Promise<void> {\n\t// Monotonic: a crash-resumed run restarts its in-memory counter from 0 —\n\t// never let that regress the op's ETA surfaces.\n\tawait db\n\t\t.updateTable(\"subgraph_operations\")\n\t\t.set({\n\t\t\tprocessed_events: sql`GREATEST(COALESCE(processed_events, 0), ${processedEvents})`,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", operationId)\n\t\t.execute();\n}\n\n/**\n * Conditionally advance a backfill operation's crash checkpoint. Monotonic by\n * construction: the WHERE clause makes concurrent writers serialize — exactly\n * one advance wins per height, regardless of lease/zombie timing. Returns\n * whether THIS caller advanced (false = a racing writer already covered h).\n */\nexport async function advanceOperationCursor(\n\tdb: Kysely<Database>,\n\toperationId: string,\n\theight: number,\n): Promise<boolean> {\n\tconst result = await db\n\t\t.updateTable(\"subgraph_operations\")\n\t\t.set({ cursor_block: height, updated_at: new Date() })\n\t\t.where(\"id\", \"=\", operationId)\n\t\t.where((eb) =>\n\t\t\teb.or([\n\t\t\t\teb(\"cursor_block\", \"is\", null),\n\t\t\t\teb(\"cursor_block\", \"<\", String(height)),\n\t\t\t]),\n\t\t)\n\t\t.executeTakeFirst();\n\treturn Number(result.numUpdatedRows ?? 0n) > 0;\n}\n"
|
|
5
|
+
"import { type Kysely, sql } from \"kysely\";\nimport type {\n\tDatabase,\n\tSubgraphOperation,\n\tSubgraphOperationKind,\n\tSubgraphOperationStatus,\n} from \"../types.ts\";\n\nconst ACTIVE_STATUSES: SubgraphOperationStatus[] = [\"queued\", \"running\"];\n\nexport function isActiveSubgraphOperationConflict(err: unknown): boolean {\n\tif (!(err instanceof Error)) return false;\n\tconst candidate = err as Error & {\n\t\tcode?: string;\n\t\tconstraint?: string;\n\t\tconstraint_name?: string;\n\t};\n\treturn (\n\t\tcandidate.code === \"23505\" &&\n\t\t(candidate.constraint === \"subgraph_operations_active_unique\" ||\n\t\t\tcandidate.constraint_name === \"subgraph_operations_active_unique\")\n\t);\n}\n\nexport async function createSubgraphOperation(\n\tdb: Kysely<Database>,\n\tdata: {\n\t\tsubgraphId: string;\n\t\tsubgraphName: string;\n\t\taccountId?: string | null;\n\t\tkind: SubgraphOperationKind;\n\t\tfromBlock?: number;\n\t\ttoBlock?: number;\n\t\t/** 'light' | 'heavy' — claim budgets heavy ops. DB default 'heavy'. */\n\t\tweight?: \"light\" | \"heavy\";\n\t\testimatedEvents?: number | null;\n\t},\n): Promise<SubgraphOperation> {\n\t// A requeued backfill inherits the committed prefix of an earlier attempt, so\n\t// cancel/fail + requeue can't replay applied deltas. Only an attempt that\n\t// started at or below this one's start covers a prefix of it: a narrower one\n\t// stopping at 950 says nothing about the heights below its own start. And only\n\t// one made against the current schema: a reindex drops the schema and every\n\t// row an earlier attempt wrote with it.\n\tlet seededCursor: string | number | bigint | null = null;\n\tif (\n\t\tdata.kind === \"backfill\" &&\n\t\tdata.fromBlock != null &&\n\t\tdata.toBlock != null\n\t) {\n\t\tconst schemaBuiltAt = (\n\t\t\tawait db\n\t\t\t\t.selectFrom(\"subgraph_operations\")\n\t\t\t\t.select((eb) => eb.fn.max(\"created_at\").as(\"at\"))\n\t\t\t\t.where(\"subgraph_id\", \"=\", data.subgraphId)\n\t\t\t\t.where(\"kind\", \"=\", \"reindex\")\n\t\t\t\t.executeTakeFirst()\n\t\t)?.at;\n\t\tlet prior = db\n\t\t\t.selectFrom(\"subgraph_operations\")\n\t\t\t.select((eb) => eb.fn.max(\"cursor_block\").as(\"max_cursor\"))\n\t\t\t.where(\"subgraph_id\", \"=\", data.subgraphId)\n\t\t\t.where(\"kind\", \"=\", \"backfill\")\n\t\t\t.where(\"status\", \"in\", [\"failed\", \"cancelled\"])\n\t\t\t.where(\"from_block\", \"<=\", data.fromBlock)\n\t\t\t.where(\"to_block\", \">=\", data.fromBlock);\n\t\tif (schemaBuiltAt) prior = prior.where(\"created_at\", \">\", schemaBuiltAt);\n\t\tseededCursor = (await prior.executeTakeFirst())?.max_cursor ?? null;\n\t}\n\treturn await db\n\t\t.insertInto(\"subgraph_operations\")\n\t\t.values({\n\t\t\tsubgraph_id: data.subgraphId,\n\t\t\tsubgraph_name: data.subgraphName,\n\t\t\taccount_id: data.accountId ?? null,\n\t\t\tkind: data.kind,\n\t\t\tfrom_block: data.fromBlock ?? null,\n\t\t\tto_block: data.toBlock ?? null,\n\t\t\t...(data.weight ? { weight: data.weight } : {}),\n\t\t\testimated_events: data.estimatedEvents ?? null,\n\t\t\tcursor_block: seededCursor,\n\t\t})\n\t\t.returningAll()\n\t\t.executeTakeFirstOrThrow();\n}\n\nexport async function findActiveSubgraphOperation(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n): Promise<SubgraphOperation | null> {\n\treturn (\n\t\t(await db\n\t\t\t.selectFrom(\"subgraph_operations\")\n\t\t\t.selectAll()\n\t\t\t.where(\"subgraph_id\", \"=\", subgraphId)\n\t\t\t.where(\"status\", \"in\", ACTIVE_STATUSES)\n\t\t\t.orderBy(\"created_at\", \"asc\")\n\t\t\t.executeTakeFirst()) ?? null\n\t);\n}\n\nexport async function requestSubgraphOperationCancel(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n): Promise<SubgraphOperation | null> {\n\treturn (\n\t\t(await db\n\t\t\t.updateTable(\"subgraph_operations\")\n\t\t\t.set({ cancel_requested: true, updated_at: new Date() })\n\t\t\t.where(\"subgraph_id\", \"=\", subgraphId)\n\t\t\t.where(\"status\", \"in\", ACTIVE_STATUSES)\n\t\t\t.returningAll()\n\t\t\t.executeTakeFirst()) ?? null\n\t);\n}\n\nexport async function requestSubgraphOperationsCancelForDelete(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n): Promise<SubgraphOperation[]> {\n\treturn await db\n\t\t.updateTable(\"subgraph_operations\")\n\t\t.set({ cancel_requested: true, updated_at: new Date() })\n\t\t.where(\"subgraph_id\", \"=\", subgraphId)\n\t\t.where(\"status\", \"in\", ACTIVE_STATUSES)\n\t\t.returningAll()\n\t\t.execute();\n}\n\n/**\n * Settle cancel-requested operations nobody is running: a queued one (no\n * runner ever claimed it) and a running one whose lock has lapsed (its runner\n * died without releasing the row; heartbeats renew the lock every 15s, so a\n * lapsed one is a dead process, not a slow one). Returns how many rows were\n * cancelled.\n *\n * An operation whose lock is still live is NEVER touched: its runner is\n * alive, and the only safe way to stop it is the runner observing\n * `cancel_requested` itself and releasing the row and advisory locks.\n */\nexport async function cancelOrphanedSubgraphOperations(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n): Promise<number> {\n\tconst cancelled = await db\n\t\t.updateTable(\"subgraph_operations\")\n\t\t.set({\n\t\t\tstatus: \"cancelled\",\n\t\t\tfinished_at: new Date(),\n\t\t\tlocked_by: null,\n\t\t\tlocked_until: null,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"subgraph_id\", \"=\", subgraphId)\n\t\t.where(\"cancel_requested\", \"=\", true)\n\t\t.where(\"status\", \"in\", ACTIVE_STATUSES)\n\t\t.where((eb) =>\n\t\t\teb.or([\n\t\t\t\teb(\"status\", \"=\", \"queued\"),\n\t\t\t\teb(\"locked_until\", \"is\", null),\n\t\t\t\teb(\"locked_until\", \"<\", sql<Date>`now()`),\n\t\t\t]),\n\t\t)\n\t\t.returning(\"id\")\n\t\t.execute();\n\treturn cancelled.length;\n}\n\n/**\n * Poll until no active subgraph operations remain for the subgraph or until\n * `timeoutMs` elapses. Returns true if all active operations cleared, false\n * if we timed out. Callers should use this before `DROP SCHEMA` so the active\n * processor has a chance to observe `cancel_requested` and release its row /\n * advisory locks. Without this, the DROP blocks behind the live transaction\n * and the API socket times out before the lock releases.\n */\nexport async function waitForSubgraphOperationsClear(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n\topts?: { timeoutMs?: number; pollMs?: number },\n): Promise<boolean> {\n\tconst timeoutMs = opts?.timeoutMs ?? 30_000;\n\tconst pollMs = opts?.pollMs ?? 500;\n\tconst deadline = Date.now() + timeoutMs;\n\twhile (Date.now() < deadline) {\n\t\tconst active = await db\n\t\t\t.selectFrom(\"subgraph_operations\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"subgraph_id\", \"=\", subgraphId)\n\t\t\t.where(\"status\", \"in\", ACTIVE_STATUSES)\n\t\t\t.limit(1)\n\t\t\t.executeTakeFirst();\n\t\tif (!active) return true;\n\t\tawait new Promise((r) => setTimeout(r, pollMs));\n\t}\n\treturn false;\n}\n\n/** Max concurrently-running 'heavy' ops (broad/non-sparse syncs). */\nconst HEAVY_OP_BUDGET = 2;\n\nexport async function claimSubgraphOperation(\n\tdb: Kysely<Database>,\n\tlockedBy: string,\n): Promise<SubgraphOperation | null> {\n\t// Fair queue: accounts with fewer currently-running operations are served first,\n\t// breaking ties by creation time. Prevents one user's long reindex from\n\t// starving other accounts.\n\tconst result = await sql<SubgraphOperation>`\n\t\tUPDATE subgraph_operations\n\t\tSET\n\t\t\tstatus = 'running',\n\t\t\tlocked_by = ${lockedBy},\n\t\t\tlocked_until = now() + interval '60 seconds',\n\t\t\tstarted_at = COALESCE(started_at, now()),\n\t\t\tupdated_at = now()\n\t\tWHERE id = (\n\t\t\tSELECT so.id\n\t\t\tFROM subgraph_operations so\n\t\t\tLEFT JOIN (\n\t\t\t\tSELECT account_id, COUNT(*) AS cnt\n\t\t\t\tFROM subgraph_operations\n\t\t\t\tWHERE status = 'running'\n\t\t\t\tGROUP BY account_id\n\t\t\t) rc ON so.account_id = rc.account_id\n\t\t\tWHERE\n\t\t\t\t(\n\t\t\t\t\tso.status = 'queued'\n\t\t\t\t\tOR (\n\t\t\t\t\t\tso.status = 'running'\n\t\t\t\t\t\tAND (so.locked_until IS NULL OR so.locked_until < now())\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t\t-- Heavy budget as an eligibility FILTER (not a post-claim refusal):\n\t\t\t\t-- a budget-blocked heavy op at the head must not starve the light\n\t\t\t\t-- ops behind it. Live-lock condition (locked_until > now()) keeps a\n\t\t\t\t-- STALE heavy op from blocking its own reclaim. Soft across\n\t\t\t\t-- concurrent claimers (can overshoot by one with multiple runners) —\n\t\t\t\t-- acceptable for the single-runner deployment.\n\t\t\t\tAND (\n\t\t\t\t\tso.weight = 'light'\n\t\t\t\t\tOR (\n\t\t\t\t\t\tSELECT COUNT(*)\n\t\t\t\t\t\tFROM subgraph_operations h\n\t\t\t\t\t\tWHERE h.status = 'running'\n\t\t\t\t\t\t\tAND h.weight = 'heavy'\n\t\t\t\t\t\t\tAND h.locked_until > now()\n\t\t\t\t\t\t\tAND h.id != so.id\n\t\t\t\t\t) < ${HEAVY_OP_BUDGET}\n\t\t\t\t)\n\t\t\tORDER BY\n\t\t\t\tCOALESCE(rc.cnt, 0) ASC,\n\t\t\t\tCASE WHEN so.status = 'queued' THEN 0 ELSE 1 END,\n\t\t\t\tso.created_at ASC\n\t\t\tFOR UPDATE OF so SKIP LOCKED\n\t\t\tLIMIT 1\n\t\t)\n\t\tRETURNING *\n\t`.execute(db);\n\treturn result.rows[0] ?? null;\n}\n\n/** Renews the runner's lease. Returns the rows renewed: 0 means it no longer\n * holds the operation. */\nexport async function heartbeatSubgraphOperation(\n\tdb: Kysely<Database>,\n\toperationId: string,\n\tlockedBy: string,\n): Promise<number> {\n\tconst result = await db\n\t\t.updateTable(\"subgraph_operations\")\n\t\t.set({\n\t\t\tlocked_until: sql<Date>`now() + interval '60 seconds'`,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", operationId)\n\t\t.where(\"status\", \"=\", \"running\")\n\t\t.where(\"locked_by\", \"=\", lockedBy)\n\t\t.executeTakeFirst();\n\t// 0 rows: the lease is gone (another runner holds it, or the op left\n\t// `running`), so the caller must stop writing.\n\treturn Number(result.numUpdatedRows ?? 0n);\n}\n\nexport async function getSubgraphOperation(\n\tdb: Kysely<Database>,\n\toperationId: string,\n): Promise<SubgraphOperation | null> {\n\treturn (\n\t\t(await db\n\t\t\t.selectFrom(\"subgraph_operations\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", operationId)\n\t\t\t.executeTakeFirst()) ?? null\n\t);\n}\n\n/** Recent operations for a subgraph, newest first (for the status read API). */\nexport async function listSubgraphOperations(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n\tlimit = 20,\n): Promise<SubgraphOperation[]> {\n\treturn db\n\t\t.selectFrom(\"subgraph_operations\")\n\t\t.selectAll()\n\t\t.where(\"subgraph_id\", \"=\", subgraphId)\n\t\t.orderBy(\"created_at\", \"desc\")\n\t\t.limit(limit)\n\t\t.execute();\n}\n\nexport async function completeSubgraphOperation(\n\tdb: Kysely<Database>,\n\toperationId: string,\n\tlockedBy: string,\n\tprocessedBlocks: number,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraph_operations\")\n\t\t.set({\n\t\t\tstatus: \"completed\",\n\t\t\tfinished_at: new Date(),\n\t\t\tprocessed_blocks: processedBlocks,\n\t\t\tlocked_by: null,\n\t\t\tlocked_until: null,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", operationId)\n\t\t.where(\"locked_by\", \"=\", lockedBy)\n\t\t.execute();\n}\n\nexport async function cancelSubgraphOperation(\n\tdb: Kysely<Database>,\n\toperationId: string,\n\tlockedBy: string,\n\tprocessedBlocks: number,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraph_operations\")\n\t\t.set({\n\t\t\tstatus: \"cancelled\",\n\t\t\tfinished_at: new Date(),\n\t\t\tprocessed_blocks: processedBlocks,\n\t\t\tlocked_by: null,\n\t\t\tlocked_until: null,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", operationId)\n\t\t.where(\"locked_by\", \"=\", lockedBy)\n\t\t.execute();\n}\n\nexport async function failSubgraphOperation(\n\tdb: Kysely<Database>,\n\toperationId: string,\n\tlockedBy: string,\n\terror: string,\n\tprocessedBlocks?: number,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraph_operations\")\n\t\t.set({\n\t\t\tstatus: \"failed\",\n\t\t\tfinished_at: new Date(),\n\t\t\tprocessed_blocks: processedBlocks ?? null,\n\t\t\terror,\n\t\t\tlocked_by: null,\n\t\t\tlocked_until: null,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", operationId)\n\t\t.where(\"locked_by\", \"=\", lockedBy)\n\t\t.execute();\n}\n\n/**\n * 1-based position of a queued operation under the claim ordering (fairness →\n * queued-first → FIFO). The heavy-budget admission filter is NOT applied — a\n * heavy op's eligibility depends on runtime budget state — so the position is\n * approximate; render it as \"~N\". Returns null unless queued.\n */\nexport async function getOperationQueuePosition(\n\tdb: Kysely<Database>,\n\toperationId: string,\n): Promise<number | null> {\n\tconst result = await sql<{ rn: string | number }>`\n\t\tWITH candidates AS (\n\t\t\tSELECT\n\t\t\t\tso.id,\n\t\t\t\tROW_NUMBER() OVER (\n\t\t\t\t\tORDER BY\n\t\t\t\t\t\tCOALESCE(rc.cnt, 0) ASC,\n\t\t\t\t\t\tCASE WHEN so.status = 'queued' THEN 0 ELSE 1 END,\n\t\t\t\t\t\tso.created_at ASC\n\t\t\t\t) AS rn\n\t\t\tFROM subgraph_operations so\n\t\t\tLEFT JOIN (\n\t\t\t\tSELECT account_id, COUNT(*) AS cnt\n\t\t\t\tFROM subgraph_operations\n\t\t\t\tWHERE status = 'running'\n\t\t\t\tGROUP BY account_id\n\t\t\t) rc ON so.account_id = rc.account_id\n\t\t\tWHERE so.status = 'queued'\n\t\t)\n\t\tSELECT rn FROM candidates WHERE id = ${operationId}\n\t`.execute(db);\n\tconst rn = result.rows[0]?.rn;\n\treturn rn == null ? null : Number(rn);\n}\n\n/** Median duration (seconds) of the last 20 completed ops of a weight class —\n * the \"est. start\" multiplier for queued positions. Null with no history. */\nexport async function getRecentOperationMedianDuration(\n\tdb: Kysely<Database>,\n\tweight: \"light\" | \"heavy\",\n): Promise<number | null> {\n\tconst result = await sql<{ median: string | number | null }>`\n\t\tSELECT percentile_cont(0.5) WITHIN GROUP (\n\t\t\tORDER BY EXTRACT(EPOCH FROM (finished_at - started_at))\n\t\t) AS median\n\t\tFROM (\n\t\t\tSELECT started_at, finished_at\n\t\t\tFROM subgraph_operations\n\t\t\tWHERE status = 'completed'\n\t\t\t\tAND weight = ${weight}\n\t\t\t\tAND started_at IS NOT NULL\n\t\t\t\tAND finished_at IS NOT NULL\n\t\t\tORDER BY finished_at DESC\n\t\t\tLIMIT 20\n\t\t) recent\n\t`.execute(db);\n\tconst median = result.rows[0]?.median;\n\treturn median == null ? null : Number(median);\n}\n\n/** Progress-flush hook: events processed so far on a running operation. */\nexport async function updateOperationProcessedEvents(\n\tdb: Kysely<Database>,\n\toperationId: string,\n\tprocessedEvents: number,\n): Promise<void> {\n\t// Monotonic: a crash-resumed run restarts its in-memory counter from 0 —\n\t// never let that regress the op's ETA surfaces.\n\tawait db\n\t\t.updateTable(\"subgraph_operations\")\n\t\t.set({\n\t\t\tprocessed_events: sql`GREATEST(COALESCE(processed_events, 0), ${processedEvents})`,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", operationId)\n\t\t.execute();\n}\n\n/**\n * Conditionally advance a backfill operation's crash checkpoint. Monotonic by\n * construction: the WHERE clause makes concurrent writers serialize — exactly\n * one advance wins per height, regardless of lease/zombie timing. Returns\n * whether THIS caller advanced (false = a racing writer already covered h).\n */\nexport async function advanceOperationCursor(\n\tdb: Kysely<Database>,\n\toperationId: string,\n\theight: number,\n): Promise<boolean> {\n\tconst result = await db\n\t\t.updateTable(\"subgraph_operations\")\n\t\t.set({ cursor_block: height, updated_at: new Date() })\n\t\t.where(\"id\", \"=\", operationId)\n\t\t.where((eb) =>\n\t\t\teb.or([\n\t\t\t\teb(\"cursor_block\", \"is\", null),\n\t\t\t\teb(\"cursor_block\", \"<\", String(height)),\n\t\t\t]),\n\t\t)\n\t\t.executeTakeFirst();\n\treturn Number(result.numUpdatedRows ?? 0n) > 0;\n}\n"
|
|
6
6
|
],
|
|
7
|
-
"mappings": ";AAAA;AAQA,IAAM,kBAA6C,CAAC,UAAU,SAAS;AAEhE,SAAS,iCAAiC,CAAC,KAAuB;AAAA,EACxE,IAAI,EAAE,eAAe;AAAA,IAAQ,OAAO;AAAA,EACpC,MAAM,YAAY;AAAA,EAKlB,OACC,UAAU,SAAS,YAClB,UAAU,eAAe,uCACzB,UAAU,oBAAoB;AAAA;AAIjC,eAAsB,uBAAuB,CAC5C,IACA,MAW6B;AAAA,
|
|
8
|
-
"debugId": "
|
|
7
|
+
"mappings": ";AAAA;AAQA,IAAM,kBAA6C,CAAC,UAAU,SAAS;AAEhE,SAAS,iCAAiC,CAAC,KAAuB;AAAA,EACxE,IAAI,EAAE,eAAe;AAAA,IAAQ,OAAO;AAAA,EACpC,MAAM,YAAY;AAAA,EAKlB,OACC,UAAU,SAAS,YAClB,UAAU,eAAe,uCACzB,UAAU,oBAAoB;AAAA;AAIjC,eAAsB,uBAAuB,CAC5C,IACA,MAW6B;AAAA,EAO7B,IAAI,eAAgD;AAAA,EACpD,IACC,KAAK,SAAS,cACd,KAAK,aAAa,QAClB,KAAK,WAAW,MACf;AAAA,IACD,MAAM,iBACL,MAAM,GACJ,WAAW,qBAAqB,EAChC,OAAO,CAAC,OAAO,GAAG,GAAG,IAAI,YAAY,EAAE,GAAG,IAAI,CAAC,EAC/C,MAAM,eAAe,KAAK,KAAK,UAAU,EACzC,MAAM,QAAQ,KAAK,SAAS,EAC5B,iBAAiB,IACjB;AAAA,IACH,IAAI,QAAQ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AAM,OAAO,OAAO,OAAO,EAAE;AAAA;AAKrC,eAAsB,gCAAgC,CACrD,IACA,QACyB;AAAA,EACzB,MAAM,SAAS,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAQH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,GAMhB,QAAQ,EAAE;AAAA,EACZ,MAAM,SAAS,OAAO,KAAK,IAAI;AAAA,EAC/B,OAAO,UAAU,OAAO,OAAO,OAAO,MAAM;AAAA;AAI7C,eAAsB,8BAA8B,CACnD,IACA,aACA,iBACgB;AAAA,EAGhB,MAAM,GACJ,YAAY,qBAAqB,EACjC,IAAI;AAAA,IACJ,kBAAkB,8CAA8C;AAAA,IAChE,YAAY,IAAI;AAAA,EACjB,CAAC,EACA,MAAM,MAAM,KAAK,WAAW,EAC5B,QAAQ;AAAA;AASX,eAAsB,sBAAsB,CAC3C,IACA,aACA,QACmB;AAAA,EACnB,MAAM,SAAS,MAAM,GACnB,YAAY,qBAAqB,EACjC,IAAI,EAAE,cAAc,QAAQ,YAAY,IAAI,KAAO,CAAC,EACpD,MAAM,MAAM,KAAK,WAAW,EAC5B,MAAM,CAAC,OACP,GAAG,GAAG;AAAA,IACL,GAAG,gBAAgB,MAAM,IAAI;AAAA,IAC7B,GAAG,gBAAgB,KAAK,OAAO,MAAM,CAAC;AAAA,EACvC,CAAC,CACF,EACC,iBAAiB;AAAA,EACnB,OAAO,OAAO,OAAO,kBAAkB,EAAE,IAAI;AAAA;",
|
|
8
|
+
"debugId": "A8800780F42DF57C64756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -70,6 +70,9 @@ interface BlocksTable {
|
|
|
70
70
|
/** Tx count `persistBlock` was handed for this height. Null on rows
|
|
71
71
|
* ingested before this column existed. */
|
|
72
72
|
tx_count: ColumnType<number | null, number | null | undefined, number | null>;
|
|
73
|
+
/** Event count `persistBlock` was handed for this height. Null on rows
|
|
74
|
+
* ingested before this column existed. */
|
|
75
|
+
event_count: ColumnType<number | null, number | null | undefined, number | null>;
|
|
73
76
|
created_at: Generated<Date>;
|
|
74
77
|
}
|
|
75
78
|
interface TransactionsTable {
|
|
@@ -203,6 +206,8 @@ interface SubgraphsTable {
|
|
|
203
206
|
schema_name: string | null;
|
|
204
207
|
start_block: Generated<number>;
|
|
205
208
|
last_processed_block: Generated<number>;
|
|
209
|
+
/** Hash of the block at `last_processed_block`; NULL = unknown (see 0197). */
|
|
210
|
+
last_processed_block_hash: Generated<string | null>;
|
|
206
211
|
reindex_from_block: number | null;
|
|
207
212
|
reindex_to_block: number | null;
|
|
208
213
|
last_error: string | null;
|
|
@@ -327,6 +332,8 @@ interface ApiKeysTable {
|
|
|
327
332
|
interface InstancesTable {
|
|
328
333
|
id: Generated<string>;
|
|
329
334
|
network: string;
|
|
335
|
+
/** `SECONDLAYER_SECRETS_KEY` sealed under itself; see `ensureSecretsKeyCanary`. */
|
|
336
|
+
secrets_key_canary: ColumnType<string | null, string | null | undefined, string | null>;
|
|
330
337
|
created_at: Generated<Date>;
|
|
331
338
|
}
|
|
332
339
|
interface AccountsTable {
|
|
@@ -1525,7 +1532,7 @@ declare function listSubgraphs(db: Kysely2<Database>, accountId?: string): Promi
|
|
|
1525
1532
|
* state (halted, cancelled, redeployed): the walk must not write on, and its
|
|
1526
1533
|
* progress never revives a halt.
|
|
1527
1534
|
*/
|
|
1528
|
-
declare function setReindexCursor(db: Kysely2<Database>, name: string, lastProcessedBlock: number): Promise<boolean>;
|
|
1535
|
+
declare function setReindexCursor(db: Kysely2<Database>, name: string, lastProcessedBlock: number, blockHash?: string): Promise<boolean>;
|
|
1529
1536
|
/** Live-walk ERROR write (f069): a block whose handlers ALL failed
|
|
1530
1537
|
* (`processed === 0 && errors > 0`, `block-processor.ts`'s `applyProgress`)
|
|
1531
1538
|
* moves an `active` subgraph to 'error' and records its height as processed;
|
|
@@ -1541,7 +1548,7 @@ declare function setReindexCursor(db: Kysely2<Database>, name: string, lastProce
|
|
|
1541
1548
|
* case that needs `CursorRaceLostError`-style tx abort. Returns whether
|
|
1542
1549
|
* the write applied. Live path only: reindex/backfill halts go through
|
|
1543
1550
|
* {@link transitionSubgraph}. */
|
|
1544
|
-
declare function recordLiveError(db: Kysely2<Database>, name: string, blockHeight: number): Promise<boolean>;
|
|
1551
|
+
declare function recordLiveError(db: Kysely2<Database>, name: string, blockHeight: number, blockHash?: string): Promise<boolean>;
|
|
1545
1552
|
declare function recordSubgraphProcessed(db: Kysely2<Database>, name: string, processed: number, errors: number, lastError?: string): Promise<void>;
|
|
1546
1553
|
/** Record a billing pause. Status, cursor, counters and `last_error` are
|
|
1547
1554
|
* untouched: a paused subgraph is healthy, just waiting on its account. */
|
|
@@ -1589,7 +1596,7 @@ declare function deleteSubgraph(db: Kysely2<Database>, name: string, accountId?:
|
|
|
1589
1596
|
* {@link rewindLiveProgress} instead, which keeps the old unconditional
|
|
1590
1597
|
* semantics and is safe specifically because the reorg path takes a
|
|
1591
1598
|
* transaction-scoped advisory lock (`reorg.ts`) other writers can't cross. */
|
|
1592
|
-
declare function recordLiveProgress(db: Kysely2<Database>, name: string, lastProcessedBlock: number): Promise<boolean>;
|
|
1599
|
+
declare function recordLiveProgress(db: Kysely2<Database>, name: string, lastProcessedBlock: number, blockHash?: string): Promise<boolean>;
|
|
1593
1600
|
/** Reorg-rewind progress write: the OLD unconditional `recordLiveProgress`
|
|
1594
1601
|
* semantics, verbatim — moves `last_processed_block` to the fork height
|
|
1595
1602
|
* regardless of its current value, because that is by definition a
|
|
@@ -1604,5 +1611,5 @@ declare function recordLiveProgress(db: Kysely2<Database>, name: string, lastPro
|
|
|
1604
1611
|
* delete+reprocess+rewind sequence — no other writer can interleave a
|
|
1605
1612
|
* forward write between the rewind and the fork block's reprocess. Do not
|
|
1606
1613
|
* call this from the live catch-up path. */
|
|
1607
|
-
declare function rewindLiveProgress(db: Kysely2<Database>, name: string, lastProcessedBlock: number): Promise<void>;
|
|
1614
|
+
declare function rewindLiveProgress(db: Kysely2<Database>, name: string, lastProcessedBlock: number, blockHash?: string): Promise<void>;
|
|
1608
1615
|
export { clearSubgraphBillingPaused, deleteSubgraph, getSubgraph, listSubgraphs, localSubgraphAccountId, markSubgraphBillingPaused, pgSchemaName, recordLiveError, recordLiveProgress, recordSubgraphProcessed, registerSubgraph, rewindLiveProgress, setReindexCursor, subgraphMachine, transitionSubgraph, updateSubgraphHandlerPath };
|
|
@@ -45,7 +45,7 @@ function isWebhookAccountScoped() {
|
|
|
45
45
|
// src/schemas/subgraphs.ts
|
|
46
46
|
import { z } from "zod";
|
|
47
47
|
var DeploySubgraphRequestSchema = z.object({
|
|
48
|
-
name: z.string().regex(/^[a-z0-9-]+$/, "lowercase alphanumeric + hyphens only").max(
|
|
48
|
+
name: z.string().regex(/^[a-z0-9-]+$/, "lowercase alphanumeric + hyphens only").max(54),
|
|
49
49
|
description: z.string().optional(),
|
|
50
50
|
sources: z.record(z.string(), z.record(z.string(), z.unknown())).refine((s) => Object.keys(s).length > 0, "Must have at least one source"),
|
|
51
51
|
schema: z.record(z.string(), z.unknown()),
|
|
@@ -198,17 +198,22 @@ async function listSubgraphs(db, accountId) {
|
|
|
198
198
|
}
|
|
199
199
|
return query.execute();
|
|
200
200
|
}
|
|
201
|
-
|
|
201
|
+
function cursorHash(blockHash) {
|
|
202
|
+
return blockHash === undefined ? {} : { last_processed_block_hash: blockHash };
|
|
203
|
+
}
|
|
204
|
+
async function setReindexCursor(db, name, lastProcessedBlock, blockHash) {
|
|
202
205
|
const result = await db.updateTable("subgraphs").set({
|
|
203
206
|
last_processed_block: lastProcessedBlock,
|
|
207
|
+
...cursorHash(blockHash),
|
|
204
208
|
updated_at: new Date
|
|
205
209
|
}).where("name", "=", name).where("status", "=", "reindexing").executeTakeFirst();
|
|
206
210
|
return Number(result.numUpdatedRows ?? 0n) > 0;
|
|
207
211
|
}
|
|
208
|
-
async function recordLiveError(db, name, blockHeight) {
|
|
212
|
+
async function recordLiveError(db, name, blockHeight, blockHash) {
|
|
209
213
|
const result = await db.updateTable("subgraphs").set({
|
|
210
214
|
status: "error",
|
|
211
215
|
last_processed_block: blockHeight,
|
|
216
|
+
...cursorHash(blockHash),
|
|
212
217
|
updated_at: new Date
|
|
213
218
|
}).where("name", "=", name).where("status", "=", "active").where("last_processed_block", "<", blockHeight).executeTakeFirst();
|
|
214
219
|
return Number(result.numUpdatedRows ?? 0n) > 0;
|
|
@@ -257,16 +262,18 @@ async function deleteSubgraph(db, name, accountId) {
|
|
|
257
262
|
await db.deleteFrom("subgraphs").where("id", "=", subgraph.id).execute();
|
|
258
263
|
return subgraph;
|
|
259
264
|
}
|
|
260
|
-
async function recordLiveProgress(db, name, lastProcessedBlock) {
|
|
265
|
+
async function recordLiveProgress(db, name, lastProcessedBlock, blockHash) {
|
|
261
266
|
const result = await db.updateTable("subgraphs").set({
|
|
262
267
|
last_processed_block: lastProcessedBlock,
|
|
268
|
+
...cursorHash(blockHash),
|
|
263
269
|
updated_at: new Date
|
|
264
270
|
}).where("name", "=", name).where("status", "=", "active").where("last_processed_block", "<", lastProcessedBlock).executeTakeFirst();
|
|
265
271
|
return Number(result.numUpdatedRows ?? 0n) > 0;
|
|
266
272
|
}
|
|
267
|
-
async function rewindLiveProgress(db, name, lastProcessedBlock) {
|
|
273
|
+
async function rewindLiveProgress(db, name, lastProcessedBlock, blockHash) {
|
|
268
274
|
await db.updateTable("subgraphs").set({
|
|
269
275
|
last_processed_block: lastProcessedBlock,
|
|
276
|
+
...cursorHash(blockHash),
|
|
270
277
|
updated_at: new Date
|
|
271
278
|
}).where("name", "=", name).where("status", "=", "active").execute();
|
|
272
279
|
}
|
|
@@ -289,5 +296,5 @@ export {
|
|
|
289
296
|
updateSubgraphHandlerPath
|
|
290
297
|
};
|
|
291
298
|
|
|
292
|
-
//# debugId=
|
|
299
|
+
//# debugId=0CD84579713DF11164756E2164756E21
|
|
293
300
|
//# sourceMappingURL=subgraphs.js.map
|
|
@@ -2,13 +2,13 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/db/queries/subgraphs.ts", "../src/mode.ts", "../src/schemas/subgraphs.ts", "../src/db/jsonb.ts", "../src/db/transition.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import { type Kysely, sql } from \"kysely\";\nimport { isPlatformMode } from \"../../mode.ts\";\nimport {\n\tSUBGRAPH_STATES,\n\ttype SubgraphStatus,\n\ttype SubgraphVerification,\n} from \"../../schemas/subgraphs.ts\";\nimport { jsonb } from \"../jsonb.ts\";\nimport { type Machine, casTransition, defineMachine } from \"../transition.ts\";\nimport type { Database, Subgraph } from \"../types.ts\";\n\n/**\n * Subgraph lifecycle. `error` is sticky: a live walk never clears it, only a\n * redeploy (`error -> active`) or a reindex (`error -> reindexing`) does.\n * Every status write goes through {@link transitionSubgraph}; the live\n * progress writes below touch the cursor only and are gated on the status\n * they are valid for.\n */\nexport const subgraphMachine: Machine<SubgraphStatus> = defineMachine({\n\tstates: SUBGRAPH_STATES,\n\ttransitions: {\n\t\tactive: [\"reindexing\", \"error\"],\n\t\treindexing: [\"active\", \"error\"],\n\t\terror: [\"reindexing\", \"active\"],\n\t},\n});\n\n/**\n * Move a subgraph from one of `from` to `to`, writing `set` in the same\n * statement. Returns the row, or `null` when it was not in a `from` state\n * (something else, a halt or a redeploy, decided first): log and stop, never\n * retry. Staying in the same state (`reindexing -> reindexing`) is a plain\n * conditional write, not a transition.\n */\nexport function transitionSubgraph(\n\tdb: Kysely<Database>,\n\tname: string,\n\tfrom: readonly SubgraphStatus[],\n\tto: SubgraphStatus,\n\tset?: Record<string, unknown>,\n): Promise<Subgraph | null> {\n\tfor (const state of from) {\n\t\tif (state !== to) subgraphMachine.assert(state, to);\n\t}\n\treturn casTransition<SubgraphStatus, Subgraph>(db, {\n\t\ttable: \"subgraphs\",\n\t\tkey: \"name\",\n\t\tid: name,\n\t\tfrom,\n\t\tto,\n\t\tset,\n\t});\n}\n\n/** Convert a subgraph name to its PostgreSQL schema name. */\nexport function pgSchemaName(subgraphName: string): string {\n\tconst safeName = subgraphName.replace(/-/g, \"_\");\n\treturn `subgraph_${safeName}`;\n}\n\n/** OSS writes empty account_id — name is the local unique key. */\nexport function localSubgraphAccountId(accountId?: string): string {\n\tif (!isPlatformMode()) return \"\";\n\treturn accountId ?? \"\";\n}\n\nexport async function registerSubgraph(\n\tdb: Kysely<Database>,\n\tdata: {\n\t\tname: string;\n\t\tversion: string;\n\t\tdefinition: Record<string, unknown>;\n\t\tschemaHash: string;\n\t\thandlerPath: string;\n\t\tapiKeyId?: string;\n\t\taccountId?: string;\n\t\tschemaName?: string;\n\t\tstartBlock?: number;\n\t\thandlerCode?: string;\n\t\tsourceCode?: string;\n\t\tpin?: string | null;\n\t\tpinPreimage?: string | null;\n\t\tverification?: SubgraphVerification | null;\n\t},\n): Promise<Subgraph> {\n\tconst accountId = localSubgraphAccountId(data.accountId);\n\tconst values = {\n\t\tname: data.name,\n\t\tversion: data.version,\n\t\tdefinition: jsonb<Record<string, unknown>>(data.definition),\n\t\tschema_hash: data.schemaHash,\n\t\thandler_path: data.handlerPath,\n\t\taccount_id: accountId,\n\t\thandler_code: data.handlerCode ?? null,\n\t\tsource_code: data.sourceCode ?? null,\n\t\tschema_name: data.schemaName ?? null,\n\t\tstart_block: data.startBlock ?? 0,\n\t\tpin: data.pin ?? null,\n\t\tpin_preimage: data.pinPreimage ?? null,\n\t\tverification: data.verification\n\t\t\t? jsonb<SubgraphVerification>(data.verification)\n\t\t\t: null,\n\t};\n\tconst updateSet = {\n\t\tversion: data.version,\n\t\tdefinition: jsonb<Record<string, unknown>>(data.definition),\n\t\tschema_hash: data.schemaHash,\n\t\thandler_path: data.handlerPath,\n\t\thandler_code: data.handlerCode ?? null,\n\t\tsource_code: data.sourceCode ?? null,\n\t\tschema_name: data.schemaName ?? null,\n\t\tstart_block: data.startBlock ?? 0,\n\t\tpin: values.pin,\n\t\tpin_preimage: values.pin_preimage,\n\t\tverification: values.verification,\n\t\tupdated_at: new Date(),\n\t};\n\n\t// OSS: name is unique. Upsert by name so leftover rows with a non-empty\n\t// account_id (pre-local-namespace deploys) don't insert a second row.\n\tif (!isPlatformMode()) {\n\t\tconst existing = await db\n\t\t\t.selectFrom(\"subgraphs\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"name\", \"=\", data.name)\n\t\t\t.executeTakeFirst();\n\t\tif (existing) {\n\t\t\treturn await db\n\t\t\t\t.updateTable(\"subgraphs\")\n\t\t\t\t.set({ ...updateSet, account_id: \"\" })\n\t\t\t\t.where(\"id\", \"=\", existing.id)\n\t\t\t\t.returningAll()\n\t\t\t\t.executeTakeFirstOrThrow();\n\t\t}\n\t\treturn await db\n\t\t\t.insertInto(\"subgraphs\")\n\t\t\t.values(values)\n\t\t\t.returningAll()\n\t\t\t.executeTakeFirstOrThrow();\n\t}\n\n\treturn await db\n\t\t.insertInto(\"subgraphs\")\n\t\t.values(values)\n\t\t.onConflict((oc) =>\n\t\t\toc.columns([\"name\", \"account_id\"]).doUpdateSet(updateSet),\n\t\t)\n\t\t.returningAll()\n\t\t.executeTakeFirstOrThrow();\n}\n\nexport async function getSubgraph(\n\tdb: Kysely<Database>,\n\tname: string,\n\taccountId?: string,\n): Promise<Subgraph | null> {\n\tlet query = db.selectFrom(\"subgraphs\").selectAll().where(\"name\", \"=\", name);\n\n\tif (isPlatformMode() && accountId !== undefined) {\n\t\tquery = query.where(\"account_id\", \"=\", accountId);\n\t}\n\n\treturn (await query.executeTakeFirst()) ?? null;\n}\n\nexport async function listSubgraphs(\n\tdb: Kysely<Database>,\n\taccountId?: string,\n): Promise<Subgraph[]> {\n\tlet query = db.selectFrom(\"subgraphs\").selectAll();\n\tif (isPlatformMode() && accountId !== undefined) {\n\t\tquery = query.where(\"account_id\", \"=\", accountId);\n\t}\n\treturn query.execute();\n}\n\n/**\n * Reindex progress: moves the cursor of a subgraph that is still\n * `reindexing`, and nothing else. Returns `false` when the subgraph left that\n * state (halted, cancelled, redeployed): the walk must not write on, and its\n * progress never revives a halt.\n */\nexport async function setReindexCursor(\n\tdb: Kysely<Database>,\n\tname: string,\n\tlastProcessedBlock: number,\n): Promise<boolean> {\n\tconst result = await db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tlast_processed_block: lastProcessedBlock,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.where(\"status\", \"=\", \"reindexing\")\n\t\t.executeTakeFirst();\n\treturn Number(result.numUpdatedRows ?? 0n) > 0;\n}\n\n/** Live-walk ERROR write (f069): a block whose handlers ALL failed\n * (`processed === 0 && errors > 0`, `block-processor.ts`'s `applyProgress`)\n * moves an `active` subgraph to 'error' and records its height as processed;\n * the cursor half goes through the same conditional `<` guard as\n * {@link recordLiveProgress}. A reindexing or already-halted subgraph is left\n * alone. Marking a subgraph 'error' is not\n * itself replay-sensitive, but it shares the `last_processed_block` column\n * with the replay guard: an unconditional write here could regress the\n * cursor a racing (successful) writer already advanced past, which is\n * exactly the regress-then-re-walk loop this guard exists to close. In\n * practice `ctx.rollbackTo` (`runner.ts`) means an all-failed block never\n * flushes writes, so a lost race here is always a silent no-op, never a\n * case that needs `CursorRaceLostError`-style tx abort. Returns whether\n * the write applied. Live path only: reindex/backfill halts go through\n * {@link transitionSubgraph}. */\nexport async function recordLiveError(\n\tdb: Kysely<Database>,\n\tname: string,\n\tblockHeight: number,\n): Promise<boolean> {\n\tconst result = await db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tstatus: \"error\",\n\t\t\tlast_processed_block: blockHeight,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.where(\"status\", \"=\", \"active\")\n\t\t.where(\"last_processed_block\", \"<\", blockHeight)\n\t\t.executeTakeFirst();\n\treturn Number(result.numUpdatedRows ?? 0n) > 0;\n}\n\nexport async function recordSubgraphProcessed(\n\tdb: Kysely<Database>,\n\tname: string,\n\tprocessed: number,\n\terrors: number,\n\tlastError?: string,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\ttotal_processed: sql`total_processed + ${processed}`,\n\t\t\ttotal_errors: sql`total_errors + ${errors}`,\n\t\t\t...(lastError\n\t\t\t\t? { last_error: lastError, last_error_at: new Date() }\n\t\t\t\t: {}),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.execute();\n}\n\n/** Record a billing pause. Status, cursor, counters and `last_error` are\n * untouched: a paused subgraph is healthy, just waiting on its account. */\nexport async function markSubgraphBillingPaused(\n\tdb: Kysely<Database>,\n\tname: string,\n\tcode: string,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tbilling_paused_at: sql`COALESCE(billing_paused_at, now())`,\n\t\t\tbilling_paused_code: code,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.execute();\n}\n\n/** Clear a billing pause once reads succeed again. */\nexport async function clearSubgraphBillingPaused(\n\tdb: Kysely<Database>,\n\tname: string,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tbilling_paused_at: null,\n\t\t\tbilling_paused_code: null,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.where(\"billing_paused_at\", \"is not\", null)\n\t\t.execute();\n}\n\nexport async function updateSubgraphHandlerPath(\n\tdb: Kysely<Database>,\n\tname: string,\n\thandlerPath: string,\n\topts?: {\n\t\thandlerCode?: string;\n\t\tsourceCode?: string;\n\t\tpin?: string | null;\n\t\tpinPreimage?: string | null;\n\t\tverification?: SubgraphVerification | null;\n\t},\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\thandler_path: handlerPath,\n\t\t\t...(opts?.handlerCode != null ? { handler_code: opts.handlerCode } : {}),\n\t\t\t...(opts?.sourceCode != null ? { source_code: opts.sourceCode } : {}),\n\t\t\t...(opts?.pin !== undefined ? { pin: opts.pin } : {}),\n\t\t\t...(opts?.pinPreimage !== undefined\n\t\t\t\t? { pin_preimage: opts.pinPreimage }\n\t\t\t\t: {}),\n\t\t\t...(opts?.verification !== undefined\n\t\t\t\t? {\n\t\t\t\t\t\tverification: opts.verification\n\t\t\t\t\t\t\t? jsonb<SubgraphVerification>(opts.verification)\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.execute();\n}\n\nexport async function deleteSubgraph(\n\tdb: Kysely<Database>,\n\tname: string,\n\taccountId?: string,\n): Promise<Subgraph | null> {\n\tconst subgraph = await getSubgraph(db, name, accountId);\n\tif (!subgraph) return null;\n\n\t// Use stored schema_name if available, otherwise compute\n\tconst schemaName = subgraph.schema_name ?? pgSchemaName(name);\n\n\t// Drop the subgraph's schema (CASCADE drops all tables within).\n\tawait sql`DROP SCHEMA IF EXISTS ${sql.raw(`\"${schemaName}\"`)} CASCADE`.execute(\n\t\tdb,\n\t);\n\n\t// Remove from registry\n\tawait db.deleteFrom(\"subgraphs\").where(\"id\", \"=\", subgraph.id).execute();\n\n\treturn subgraph;\n}\n\n/** Live-walk progress write: advances the cursor of an `active` subgraph and\n * never touches status. A `reindexing` or `error` subgraph is a no-op here:\n * the old promote-toward-active CASE let a live commit undo a halt and flap\n * a parked subgraph back into catch-up against its own reindex op.\n *\n * `last_processed_block` is now written CONDITIONALLY — `WHERE\n * last_processed_block < lastProcessedBlock`, mirroring\n * `advanceOperationCursor`'s (`subgraph-operations.ts`) comparison shape —\n * and returns whether THIS call actually advanced it. This used to be\n * unconditional by design, on the premise that the only two writers able to\n * advance/rewind a given subgraph's cursor concurrently (the catch-up walk\n * and the reorg handler) serialize on an in-process per-subgraph lock +\n * reorg epoch guard (`packages/subgraphs/src/runtime/catchup.ts`,\n * `subgraphBlockLockHeld` / `reorgEpoch`; f057). That guard is in-process\n * only. The f068 investigation\n * (`docs/internal/audits/asset-holdings-unreproducible-balances-f068.md`)\n * found a cross-process sequence it does not cover: a catch-up leader that\n * loses its advisory-lock connection mid-walk keeps writing (leadership is\n * checked only at walk entry, not per-iteration) while a new leader takes\n * over and walks the same range — both commit increments for overlapping\n * heights, and every regressed cursor write from the laggard re-triggers a\n * full re-walk, growing per-height application without bound. The\n * conditional advance here (paired with the fast-path replay guard armed on\n * the live path in `block-processor.ts`) is now the cross-process\n * guarantee: a block at/below the current cursor can never re-advance it,\n * so a laggard's commits can no longer regress-then-retrigger.\n *\n * This conditionality is why the reorg rewind can no longer go through this\n * function — a rewind's whole point is to move the cursor *backward*, which\n * the `<` guard would silently refuse. Reorg mode calls\n * {@link rewindLiveProgress} instead, which keeps the old unconditional\n * semantics and is safe specifically because the reorg path takes a\n * transaction-scoped advisory lock (`reorg.ts`) other writers can't cross. */\nexport async function recordLiveProgress(\n\tdb: Kysely<Database>,\n\tname: string,\n\tlastProcessedBlock: number,\n): Promise<boolean> {\n\tconst result = await db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tlast_processed_block: lastProcessedBlock,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.where(\"status\", \"=\", \"active\")\n\t\t.where(\"last_processed_block\", \"<\", lastProcessedBlock)\n\t\t.executeTakeFirst();\n\treturn Number(result.numUpdatedRows ?? 0n) > 0;\n}\n\n/** Reorg-rewind progress write: the OLD unconditional `recordLiveProgress`\n * semantics, verbatim — moves `last_processed_block` to the fork height\n * regardless of its current value, because that is by definition a\n * backward move the conditional `<` guard in `recordLiveProgress` would\n * refuse. Cursor only, `active` subgraphs only.\n *\n * Callers: exclusively the subgraph-reorg path\n * (`packages/subgraphs/src/runtime/reorg.ts`, via `block-processor.ts`'s\n * `reorgRewind` mode), which is safe from the cross-process race this\n * function reintroduces because it holds a transaction-scoped Postgres\n * advisory lock (`pg_advisory_xact_lock`) for the whole\n * delete+reprocess+rewind sequence — no other writer can interleave a\n * forward write between the rewind and the fork block's reprocess. Do not\n * call this from the live catch-up path. */\nexport async function rewindLiveProgress(\n\tdb: Kysely<Database>,\n\tname: string,\n\tlastProcessedBlock: number,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tlast_processed_block: lastProcessedBlock,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.where(\"status\", \"=\", \"active\")\n\t\t.execute();\n}\n",
|
|
5
|
+
"import { type Kysely, sql } from \"kysely\";\nimport { isPlatformMode } from \"../../mode.ts\";\nimport {\n\tSUBGRAPH_STATES,\n\ttype SubgraphStatus,\n\ttype SubgraphVerification,\n} from \"../../schemas/subgraphs.ts\";\nimport { jsonb } from \"../jsonb.ts\";\nimport { type Machine, casTransition, defineMachine } from \"../transition.ts\";\nimport type { Database, Subgraph } from \"../types.ts\";\n\n/**\n * Subgraph lifecycle. `error` is sticky: a live walk never clears it, only a\n * redeploy (`error -> active`) or a reindex (`error -> reindexing`) does.\n * Every status write goes through {@link transitionSubgraph}; the live\n * progress writes below touch the cursor only and are gated on the status\n * they are valid for.\n */\nexport const subgraphMachine: Machine<SubgraphStatus> = defineMachine({\n\tstates: SUBGRAPH_STATES,\n\ttransitions: {\n\t\tactive: [\"reindexing\", \"error\"],\n\t\treindexing: [\"active\", \"error\"],\n\t\terror: [\"reindexing\", \"active\"],\n\t},\n});\n\n/**\n * Move a subgraph from one of `from` to `to`, writing `set` in the same\n * statement. Returns the row, or `null` when it was not in a `from` state\n * (something else, a halt or a redeploy, decided first): log and stop, never\n * retry. Staying in the same state (`reindexing -> reindexing`) is a plain\n * conditional write, not a transition.\n */\nexport function transitionSubgraph(\n\tdb: Kysely<Database>,\n\tname: string,\n\tfrom: readonly SubgraphStatus[],\n\tto: SubgraphStatus,\n\tset?: Record<string, unknown>,\n): Promise<Subgraph | null> {\n\tfor (const state of from) {\n\t\tif (state !== to) subgraphMachine.assert(state, to);\n\t}\n\treturn casTransition<SubgraphStatus, Subgraph>(db, {\n\t\ttable: \"subgraphs\",\n\t\tkey: \"name\",\n\t\tid: name,\n\t\tfrom,\n\t\tto,\n\t\tset,\n\t});\n}\n\n/** Convert a subgraph name to its PostgreSQL schema name. */\nexport function pgSchemaName(subgraphName: string): string {\n\tconst safeName = subgraphName.replace(/-/g, \"_\");\n\treturn `subgraph_${safeName}`;\n}\n\n/** OSS writes empty account_id — name is the local unique key. */\nexport function localSubgraphAccountId(accountId?: string): string {\n\tif (!isPlatformMode()) return \"\";\n\treturn accountId ?? \"\";\n}\n\nexport async function registerSubgraph(\n\tdb: Kysely<Database>,\n\tdata: {\n\t\tname: string;\n\t\tversion: string;\n\t\tdefinition: Record<string, unknown>;\n\t\tschemaHash: string;\n\t\thandlerPath: string;\n\t\tapiKeyId?: string;\n\t\taccountId?: string;\n\t\tschemaName?: string;\n\t\tstartBlock?: number;\n\t\thandlerCode?: string;\n\t\tsourceCode?: string;\n\t\tpin?: string | null;\n\t\tpinPreimage?: string | null;\n\t\tverification?: SubgraphVerification | null;\n\t},\n): Promise<Subgraph> {\n\tconst accountId = localSubgraphAccountId(data.accountId);\n\tconst values = {\n\t\tname: data.name,\n\t\tversion: data.version,\n\t\tdefinition: jsonb<Record<string, unknown>>(data.definition),\n\t\tschema_hash: data.schemaHash,\n\t\thandler_path: data.handlerPath,\n\t\taccount_id: accountId,\n\t\thandler_code: data.handlerCode ?? null,\n\t\tsource_code: data.sourceCode ?? null,\n\t\tschema_name: data.schemaName ?? null,\n\t\tstart_block: data.startBlock ?? 0,\n\t\tpin: data.pin ?? null,\n\t\tpin_preimage: data.pinPreimage ?? null,\n\t\tverification: data.verification\n\t\t\t? jsonb<SubgraphVerification>(data.verification)\n\t\t\t: null,\n\t};\n\tconst updateSet = {\n\t\tversion: data.version,\n\t\tdefinition: jsonb<Record<string, unknown>>(data.definition),\n\t\tschema_hash: data.schemaHash,\n\t\thandler_path: data.handlerPath,\n\t\thandler_code: data.handlerCode ?? null,\n\t\tsource_code: data.sourceCode ?? null,\n\t\tschema_name: data.schemaName ?? null,\n\t\tstart_block: data.startBlock ?? 0,\n\t\tpin: values.pin,\n\t\tpin_preimage: values.pin_preimage,\n\t\tverification: values.verification,\n\t\tupdated_at: new Date(),\n\t};\n\n\t// OSS: name is unique. Upsert by name so leftover rows with a non-empty\n\t// account_id (pre-local-namespace deploys) don't insert a second row.\n\tif (!isPlatformMode()) {\n\t\tconst existing = await db\n\t\t\t.selectFrom(\"subgraphs\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"name\", \"=\", data.name)\n\t\t\t.executeTakeFirst();\n\t\tif (existing) {\n\t\t\treturn await db\n\t\t\t\t.updateTable(\"subgraphs\")\n\t\t\t\t.set({ ...updateSet, account_id: \"\" })\n\t\t\t\t.where(\"id\", \"=\", existing.id)\n\t\t\t\t.returningAll()\n\t\t\t\t.executeTakeFirstOrThrow();\n\t\t}\n\t\treturn await db\n\t\t\t.insertInto(\"subgraphs\")\n\t\t\t.values(values)\n\t\t\t.returningAll()\n\t\t\t.executeTakeFirstOrThrow();\n\t}\n\n\treturn await db\n\t\t.insertInto(\"subgraphs\")\n\t\t.values(values)\n\t\t.onConflict((oc) =>\n\t\t\toc.columns([\"name\", \"account_id\"]).doUpdateSet(updateSet),\n\t\t)\n\t\t.returningAll()\n\t\t.executeTakeFirstOrThrow();\n}\n\nexport async function getSubgraph(\n\tdb: Kysely<Database>,\n\tname: string,\n\taccountId?: string,\n): Promise<Subgraph | null> {\n\tlet query = db.selectFrom(\"subgraphs\").selectAll().where(\"name\", \"=\", name);\n\n\tif (isPlatformMode() && accountId !== undefined) {\n\t\tquery = query.where(\"account_id\", \"=\", accountId);\n\t}\n\n\treturn (await query.executeTakeFirst()) ?? null;\n}\n\nexport async function listSubgraphs(\n\tdb: Kysely<Database>,\n\taccountId?: string,\n): Promise<Subgraph[]> {\n\tlet query = db.selectFrom(\"subgraphs\").selectAll();\n\tif (isPlatformMode() && accountId !== undefined) {\n\t\tquery = query.where(\"account_id\", \"=\", accountId);\n\t}\n\treturn query.execute();\n}\n\n/** The hash half of a cursor write. Absent when the caller has none; the\n * `subgraphs_clear_stale_block_hash` trigger (0197) then clears the stored hash\n * for a moved cursor instead of leaving one that names another block. */\nfunction cursorHash(blockHash: string | undefined) {\n\treturn blockHash === undefined\n\t\t? {}\n\t\t: { last_processed_block_hash: blockHash };\n}\n\n/**\n * Reindex progress: moves the cursor of a subgraph that is still\n * `reindexing`, and nothing else. Returns `false` when the subgraph left that\n * state (halted, cancelled, redeployed): the walk must not write on, and its\n * progress never revives a halt.\n */\nexport async function setReindexCursor(\n\tdb: Kysely<Database>,\n\tname: string,\n\tlastProcessedBlock: number,\n\tblockHash?: string,\n): Promise<boolean> {\n\tconst result = await db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tlast_processed_block: lastProcessedBlock,\n\t\t\t...cursorHash(blockHash),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.where(\"status\", \"=\", \"reindexing\")\n\t\t.executeTakeFirst();\n\treturn Number(result.numUpdatedRows ?? 0n) > 0;\n}\n\n/** Live-walk ERROR write (f069): a block whose handlers ALL failed\n * (`processed === 0 && errors > 0`, `block-processor.ts`'s `applyProgress`)\n * moves an `active` subgraph to 'error' and records its height as processed;\n * the cursor half goes through the same conditional `<` guard as\n * {@link recordLiveProgress}. A reindexing or already-halted subgraph is left\n * alone. Marking a subgraph 'error' is not\n * itself replay-sensitive, but it shares the `last_processed_block` column\n * with the replay guard: an unconditional write here could regress the\n * cursor a racing (successful) writer already advanced past, which is\n * exactly the regress-then-re-walk loop this guard exists to close. In\n * practice `ctx.rollbackTo` (`runner.ts`) means an all-failed block never\n * flushes writes, so a lost race here is always a silent no-op, never a\n * case that needs `CursorRaceLostError`-style tx abort. Returns whether\n * the write applied. Live path only: reindex/backfill halts go through\n * {@link transitionSubgraph}. */\nexport async function recordLiveError(\n\tdb: Kysely<Database>,\n\tname: string,\n\tblockHeight: number,\n\tblockHash?: string,\n): Promise<boolean> {\n\tconst result = await db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tstatus: \"error\",\n\t\t\tlast_processed_block: blockHeight,\n\t\t\t...cursorHash(blockHash),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.where(\"status\", \"=\", \"active\")\n\t\t.where(\"last_processed_block\", \"<\", blockHeight)\n\t\t.executeTakeFirst();\n\treturn Number(result.numUpdatedRows ?? 0n) > 0;\n}\n\nexport async function recordSubgraphProcessed(\n\tdb: Kysely<Database>,\n\tname: string,\n\tprocessed: number,\n\terrors: number,\n\tlastError?: string,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\ttotal_processed: sql`total_processed + ${processed}`,\n\t\t\ttotal_errors: sql`total_errors + ${errors}`,\n\t\t\t...(lastError\n\t\t\t\t? { last_error: lastError, last_error_at: new Date() }\n\t\t\t\t: {}),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.execute();\n}\n\n/** Record a billing pause. Status, cursor, counters and `last_error` are\n * untouched: a paused subgraph is healthy, just waiting on its account. */\nexport async function markSubgraphBillingPaused(\n\tdb: Kysely<Database>,\n\tname: string,\n\tcode: string,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tbilling_paused_at: sql`COALESCE(billing_paused_at, now())`,\n\t\t\tbilling_paused_code: code,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.execute();\n}\n\n/** Clear a billing pause once reads succeed again. */\nexport async function clearSubgraphBillingPaused(\n\tdb: Kysely<Database>,\n\tname: string,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tbilling_paused_at: null,\n\t\t\tbilling_paused_code: null,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.where(\"billing_paused_at\", \"is not\", null)\n\t\t.execute();\n}\n\nexport async function updateSubgraphHandlerPath(\n\tdb: Kysely<Database>,\n\tname: string,\n\thandlerPath: string,\n\topts?: {\n\t\thandlerCode?: string;\n\t\tsourceCode?: string;\n\t\tpin?: string | null;\n\t\tpinPreimage?: string | null;\n\t\tverification?: SubgraphVerification | null;\n\t},\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\thandler_path: handlerPath,\n\t\t\t...(opts?.handlerCode != null ? { handler_code: opts.handlerCode } : {}),\n\t\t\t...(opts?.sourceCode != null ? { source_code: opts.sourceCode } : {}),\n\t\t\t...(opts?.pin !== undefined ? { pin: opts.pin } : {}),\n\t\t\t...(opts?.pinPreimage !== undefined\n\t\t\t\t? { pin_preimage: opts.pinPreimage }\n\t\t\t\t: {}),\n\t\t\t...(opts?.verification !== undefined\n\t\t\t\t? {\n\t\t\t\t\t\tverification: opts.verification\n\t\t\t\t\t\t\t? jsonb<SubgraphVerification>(opts.verification)\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.execute();\n}\n\nexport async function deleteSubgraph(\n\tdb: Kysely<Database>,\n\tname: string,\n\taccountId?: string,\n): Promise<Subgraph | null> {\n\tconst subgraph = await getSubgraph(db, name, accountId);\n\tif (!subgraph) return null;\n\n\t// Use stored schema_name if available, otherwise compute\n\tconst schemaName = subgraph.schema_name ?? pgSchemaName(name);\n\n\t// Drop the subgraph's schema (CASCADE drops all tables within).\n\tawait sql`DROP SCHEMA IF EXISTS ${sql.raw(`\"${schemaName}\"`)} CASCADE`.execute(\n\t\tdb,\n\t);\n\n\t// Remove from registry\n\tawait db.deleteFrom(\"subgraphs\").where(\"id\", \"=\", subgraph.id).execute();\n\n\treturn subgraph;\n}\n\n/** Live-walk progress write: advances the cursor of an `active` subgraph and\n * never touches status. A `reindexing` or `error` subgraph is a no-op here:\n * the old promote-toward-active CASE let a live commit undo a halt and flap\n * a parked subgraph back into catch-up against its own reindex op.\n *\n * `last_processed_block` is now written CONDITIONALLY — `WHERE\n * last_processed_block < lastProcessedBlock`, mirroring\n * `advanceOperationCursor`'s (`subgraph-operations.ts`) comparison shape —\n * and returns whether THIS call actually advanced it. This used to be\n * unconditional by design, on the premise that the only two writers able to\n * advance/rewind a given subgraph's cursor concurrently (the catch-up walk\n * and the reorg handler) serialize on an in-process per-subgraph lock +\n * reorg epoch guard (`packages/subgraphs/src/runtime/catchup.ts`,\n * `subgraphBlockLockHeld` / `reorgEpoch`; f057). That guard is in-process\n * only. The f068 investigation\n * (`docs/internal/audits/asset-holdings-unreproducible-balances-f068.md`)\n * found a cross-process sequence it does not cover: a catch-up leader that\n * loses its advisory-lock connection mid-walk keeps writing (leadership is\n * checked only at walk entry, not per-iteration) while a new leader takes\n * over and walks the same range — both commit increments for overlapping\n * heights, and every regressed cursor write from the laggard re-triggers a\n * full re-walk, growing per-height application without bound. The\n * conditional advance here (paired with the fast-path replay guard armed on\n * the live path in `block-processor.ts`) is now the cross-process\n * guarantee: a block at/below the current cursor can never re-advance it,\n * so a laggard's commits can no longer regress-then-retrigger.\n *\n * This conditionality is why the reorg rewind can no longer go through this\n * function — a rewind's whole point is to move the cursor *backward*, which\n * the `<` guard would silently refuse. Reorg mode calls\n * {@link rewindLiveProgress} instead, which keeps the old unconditional\n * semantics and is safe specifically because the reorg path takes a\n * transaction-scoped advisory lock (`reorg.ts`) other writers can't cross. */\nexport async function recordLiveProgress(\n\tdb: Kysely<Database>,\n\tname: string,\n\tlastProcessedBlock: number,\n\tblockHash?: string,\n): Promise<boolean> {\n\tconst result = await db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tlast_processed_block: lastProcessedBlock,\n\t\t\t...cursorHash(blockHash),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.where(\"status\", \"=\", \"active\")\n\t\t.where(\"last_processed_block\", \"<\", lastProcessedBlock)\n\t\t.executeTakeFirst();\n\treturn Number(result.numUpdatedRows ?? 0n) > 0;\n}\n\n/** Reorg-rewind progress write: the OLD unconditional `recordLiveProgress`\n * semantics, verbatim — moves `last_processed_block` to the fork height\n * regardless of its current value, because that is by definition a\n * backward move the conditional `<` guard in `recordLiveProgress` would\n * refuse. Cursor only, `active` subgraphs only.\n *\n * Callers: exclusively the subgraph-reorg path\n * (`packages/subgraphs/src/runtime/reorg.ts`, via `block-processor.ts`'s\n * `reorgRewind` mode), which is safe from the cross-process race this\n * function reintroduces because it holds a transaction-scoped Postgres\n * advisory lock (`pg_advisory_xact_lock`) for the whole\n * delete+reprocess+rewind sequence — no other writer can interleave a\n * forward write between the rewind and the fork block's reprocess. Do not\n * call this from the live catch-up path. */\nexport async function rewindLiveProgress(\n\tdb: Kysely<Database>,\n\tname: string,\n\tlastProcessedBlock: number,\n\tblockHash?: string,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tlast_processed_block: lastProcessedBlock,\n\t\t\t...cursorHash(blockHash),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.where(\"status\", \"=\", \"active\")\n\t\t.execute();\n}\n",
|
|
6
6
|
"/**\n * Instance modes for the Secondlayer platform.\n *\n * - `oss`: self-hosted, single-tenant. No auth middleware, no platform routes\n * (projects, admin). Everything runs against a single `DATABASE_URL`.\n * Intended for `docker compose up`.\n *\n * - `platform`: the metered archive deployment. Magic-link auth, API keys,\n * accounts, credits, and metered `/v1` reads (Index + Streams + subgraphs)\n * against a single shared DB. No paid tier ladder — one metered `free`\n * tier plus first-party internal service credentials.\n */\n\nexport type InstanceMode = \"oss\" | \"platform\";\n\n/** What the operator wrote in the env — `archive` is the honest name for the\n * metered public-archive deployment and aliases `platform` behaviorally. */\nexport type DeclaredInstanceMode = InstanceMode | \"archive\";\n\nconst VALID_MODES: readonly DeclaredInstanceMode[] = [\n\t\"oss\",\n\t\"platform\",\n\t\"archive\",\n];\n\nfunction declaredMode(): DeclaredInstanceMode {\n\tconst raw = process.env.INSTANCE_MODE?.trim().toLowerCase();\n\tif (raw && (VALID_MODES as readonly string[]).includes(raw)) {\n\t\treturn raw as DeclaredInstanceMode;\n\t}\n\treturn \"oss\";\n}\n\n/**\n * Resolve the active instance mode from `process.env.INSTANCE_MODE`.\n * Defaults to `\"oss\"` — the safest default for self-hosters who deploy\n * without setting the variable. `archive` normalizes to `platform` here so\n * every behavioral branch stays a two-way choice; use\n * `getDeclaredInstanceMode()` for display surfaces.\n */\nexport function getInstanceMode(): InstanceMode {\n\tconst declared = declaredMode();\n\treturn declared === \"archive\" ? \"platform\" : declared;\n}\n\n/** The mode as declared in the env, for status/identity surfaces. */\nexport function getDeclaredInstanceMode(): DeclaredInstanceMode {\n\treturn declaredMode();\n}\n\n/**\n * True when public reads are credit-metered (the free window, retention, and\n * credits gates arm). Platform/archive deployments meter by default;\n * self-host never does unless the operator explicitly sets\n * `METERED_READS=true`. `METERED_READS=false` disarms a metered deployment.\n */\nexport function isMeteredReads(): boolean {\n\tconst override = process.env.METERED_READS?.trim().toLowerCase();\n\tif (override === \"true\") return true;\n\tif (override === \"false\") return false;\n\treturn getInstanceMode() === \"platform\";\n}\n\n/** True when the active mode is `\"platform\"` (shared multi-tenant). */\nexport function isPlatformMode(): boolean {\n\treturn getInstanceMode() === \"platform\";\n}\n\n/** True when the active mode is `\"oss\"` (self-hosted). */\nexport function isOssMode(): boolean {\n\treturn getInstanceMode() === \"oss\";\n}\n\n/** The one shared testnet webhook stack (hosted). Off everywhere else. */\nexport function isTestnetWebhookStack(): boolean {\n\treturn process.env.TESTNET_WEBHOOK_STACK === \"true\";\n}\n\n/** Webhook rows are per-account: platform, or the shared testnet stack. */\nexport function isWebhookAccountScoped(): boolean {\n\treturn isPlatformMode() || isTestnetWebhookStack();\n}\n",
|
|
7
|
-
"import { z } from \"zod\";\n\n// ── Deploy Subgraph Request ─────────────────────────────────────────────────\n\n/** The body for deploying a subgraph: sources, schema, and handler code. */\nexport interface DeploySubgraphRequest {\n\tname: string;\n\tdescription?: string;\n\tsources: Record<string, Record<string, unknown>>;\n\tschema: Record<string, unknown>;\n\thandlerCode: string;\n\t/** Override the definition's startBlock for this deploy only. */\n\tstartBlock?: number;\n\t/** Original TypeScript source, persisted so chat can read/diff/edit later. */\n\tsourceCode?: string;\n\t/** Validate the definition + print the DDL plan without deploying. */\n\tdryRun?: boolean;\n}\n\nexport const DeploySubgraphRequestSchema: z.ZodType<DeploySubgraphRequest> =\n\tz.object({\n\t\tname: z\n\t\t\t.string()\n\t\t\t.regex(/^[a-z0-9-]+$/, \"lowercase alphanumeric + hyphens only\")\n\t\t\t.max(63),\n\t\tdescription: z.string().optional(),\n\t\tsources: z\n\t\t\t.record(z.string(), z.record(z.string(), z.unknown()))\n\t\t\t.refine(\n\t\t\t\t(s) => Object.keys(s).length > 0,\n\t\t\t\t\"Must have at least one source\",\n\t\t\t),\n\t\tschema: z.record(z.string(), z.unknown()),\n\t\thandlerCode: z.string().max(1_048_576, \"handler code exceeds 1MB limit\"),\n\t\tstartBlock: z.number().int().nonnegative().optional(),\n\t\tsourceCode: z\n\t\t\t.string()\n\t\t\t.max(1_048_576, \"source code exceeds 1MB limit\")\n\t\t\t.optional(),\n\t\tdryRun: z.boolean().optional(),\n\t});\n\n/**\n * How far a subgraph's rows can be checked without trusting the server,\n * derived from its sources and a scan of its handler. Never configured.\n *\n * - `state`: every input is a named state write, provable from block headers.\n * Handlers run in the deterministic realm. A deployed `state` subgraph is\n * verifiable: one with any reason is refused at deploy.\n * - `events`: an input (events, prints, tx results, `ctx.client`) needs\n * re-execution proofs, which are not served yet.\n * - `none`: a source can never be proven as written (trait scope, tip-first\n * backfill).\n */\nexport interface SubgraphVerification {\n\tlevel: \"state\" | \"events\" | \"none\";\n\t/** What stands between the subgraph and checkable rows, e.g.\n\t * `print_event source \"swaps\" needs event proofs` or\n\t * `subgraph.ts:41:12 Date: wall-clock time differs per run`. */\n\treasons: string[];\n\t/** What stays unproven even at this level, e.g. tx attribution of writes. */\n\tunproven: string[];\n}\n\n/** What a deploy did, the version, and where indexing starts. */\nexport interface DeploySubgraphResponse {\n\taction: \"created\" | \"unchanged\" | \"handler_updated\" | \"updated\" | \"reindexed\";\n\tsubgraphId: string;\n\tversion: string;\n\tmessage: string;\n\t/** Effective indexing start height. */\n\tstart_block?: number;\n\toperationId?: string;\n\treindexStarted?: boolean;\n\t/** Bounded candidate-event denominator for the reindex just started, when the\n\t * op was classifiable as sparse/light. Absent for heavy ops (no upfront estimate\n\t * possible) — check `sl subgraphs status` after ~30s for a rate-based ETA instead. */\n\testimatedEvents?: number;\n\t/** Non-blocking deploy lints (e.g. handler reads a print field never observed on-chain). */\n\twarnings?: string[];\n\t/** sha256 identity of what was deployed; absent on unbundled deploys. */\n\tpin?: string;\n\tverification?: SubgraphVerification;\n\tdiff?: {\n\t\taddedTables: string[];\n\t\tremovedTables: string[];\n\t\taddedColumns: Record<string, string[]>;\n\t\tbreakingChanges: string[];\n\t};\n}\n\n// Subgraph API response types\n\n/** Every state `subgraphs.status` can hold; mirrored by the\n * `subgraphs_status_check` CHECK (migration 0189). */\nexport const SUBGRAPH_STATES = [\"active\", \"reindexing\", \"error\"] as const;\nexport type SubgraphStatus = (typeof SUBGRAPH_STATES)[number];\n\n/** What an operator sees: `synced` and `catching_up` are both `active` rows. */\nexport type SubgraphSyncState =\n\t| \"synced\"\n\t| \"catching_up\"\n\t| \"reindexing\"\n\t| \"error\";\n\n/**\n * The one answer to \"is this subgraph caught up?\". `tip` is the chain tip the\n * subgraph is measured against (its reindex target while reindexing is the\n * caller's concern: a reindexing subgraph is `reindexing` whatever its cursor).\n */\nexport function syncState(\n\tsubgraph: {\n\t\tstatus: string;\n\t\tlastProcessedBlock: number | string;\n\t},\n\ttip: number,\n): SubgraphSyncState {\n\tif (subgraph.status === \"reindexing\") return \"reindexing\";\n\tif (subgraph.status === \"error\") return \"error\";\n\treturn Number(subgraph.lastProcessedBlock) < tip ? \"catching_up\" : \"synced\";\n}\n\n/** A subgraph's name, status, and indexing progress. */\nexport interface SubgraphSummary {\n\tname: string;\n\tversion: string;\n\tstatus: string;\n\tlastProcessedBlock: number;\n\ttotalProcessed: number;\n\ttotalRows?: number;\n\ttotalErrors: number;\n\ttables: string[];\n\tchainTip: number;\n\tsourceChainTip?: number;\n\ttargetBlock?: number;\n\tprogress: number;\n\tblocksRemaining?: number;\n\tsyncMode?: \"sync\" | \"reindex\";\n\tgapCount: number;\n\t/** history_filling = expected gaps while a tip-first backfill op runs. */\n\tintegrity: \"complete\" | \"gaps_detected\" | \"history_filling\";\n\t/** Most recent indexing error reason + when it occurred, if any. */\n\tlastError?: string | null;\n\tlastErrorAt?: string | null;\n\t/** Billing code (`spend_cap_reached`, `insufficient_credits`) while reads\n\t * are refused for the account; null otherwise. */\n\tbillingPausedCode?: string | null;\n\t/** Last row mutation timestamp; powers per-card freshness. */\n\tupdatedAt?: string | null;\n\tcreatedAt: string;\n}\n\nexport interface SubgraphGapRange {\n\tstart: number;\n\tend: number;\n\tsize: number;\n\treason: string;\n}\n\nexport interface SubgraphSyncInfo {\n\tstatus: SubgraphSyncState;\n\tmode?: \"sync\" | \"reindex\";\n\tstartBlock: number;\n\tlastProcessedBlock: number;\n\t/**\n\t * Backward-compatible denominator for progress displays. During reindexing,\n\t * this is the reindex target block rather than the live source chain tip.\n\t */\n\tchainTip: number;\n\tsourceChainTip?: number;\n\ttargetBlock?: number;\n\tblocksRemaining: number;\n\tprocessedBlocks?: number;\n\ttotalBlocks?: number;\n\tprogress: number;\n\t/** Present while the populating operation is queued: approximate claim\n\t * position + honest event denominator + naive start estimate. */\n\tqueue?: {\n\t\tposition: number | null;\n\t\testimatedEvents: number | null;\n\t\testimatedStartSeconds: number | null;\n\t};\n\t/** Event-based progress for sparse syncs (block pct is meaningless when\n\t * most heights are skipped). */\n\testimatedEvents?: number;\n\tprocessedEvents?: number;\n\tetaSeconds?: number | null;\n\tgaps: {\n\t\tcount: number;\n\t\ttotalMissingBlocks: number;\n\t\tranges: SubgraphGapRange[];\n\t};\n\t/** history_filling = expected gaps while a tip-first backfill op runs. */\n\tintegrity: \"complete\" | \"gaps_detected\" | \"history_filling\";\n}\n\n/** A subgraph's version, pin, status, tables, and sources. */\nexport interface SubgraphDetail {\n\tname: string;\n\tversion: string;\n\tschemaHash?: string;\n\t/** sha256 over schema, handler bundle, startBlock, network and runtime.\n\t * Null for subgraphs deployed before pins existed. */\n\tpin?: string | null;\n\t/** Null for subgraphs deployed before levels were derived. */\n\tverification?: SubgraphVerification | null;\n\tstatus: string;\n\tlastProcessedBlock: number;\n\tdescription?: string;\n\tsources?: Record<string, unknown>;\n\tdefinition?: Record<string, unknown>;\n\thealth: {\n\t\ttotalProcessed: number;\n\t\ttotalErrors: number;\n\t\terrorRate: number;\n\t\tlastError: string | null;\n\t\tlastErrorAt: string | null;\n\t\t/** Billing code while the account's reads are refused; null otherwise. */\n\t\tbillingPausedCode?: string | null;\n\t\t/** True after the processor matched work but user tables still have 0 rows. */\n\t\temptyMapping: boolean;\n\t};\n\tsync: SubgraphSyncInfo;\n\ttables: Record<\n\t\tstring,\n\t\t{\n\t\t\tendpoint: string;\n\t\t\tcolumns: Record<\n\t\t\t\tstring,\n\t\t\t\t{\n\t\t\t\t\ttype: string;\n\t\t\t\t\tnullable?: boolean;\n\t\t\t\t\tindexed?: boolean;\n\t\t\t\t\tsearchable?: boolean;\n\t\t\t\t\tdefault?: string | number | boolean;\n\t\t\t\t}\n\t\t\t>;\n\t\t\trowCount: number;\n\t\t\texample: string;\n\t\t\tindexes?: readonly (readonly string[])[];\n\t\t\tuniqueKeys?: readonly (readonly string[])[];\n\t\t}\n\t>;\n\tcreatedAt: string;\n\tupdatedAt: string;\n}\n\nexport interface SubgraphGapEntry {\n\tstart: number;\n\tend: number;\n\tsize: number;\n\treason: string;\n\tdetectedAt: string;\n\tresolvedAt: string | null;\n}\n\n/** Missing block ranges in a subgraph, with totals. */\nexport interface SubgraphGapsResponse {\n\tdata: SubgraphGapEntry[];\n\tmeta: {\n\t\ttotal: number;\n\t\ttotalMissingBlocks: number;\n\t\tlimit: number;\n\t\toffset: number;\n\t};\n}\n\n/** A queued reindex and the block range it covers. */\nexport interface ReindexResponse {\n\tmessage: string;\n\tfromBlock: number;\n\ttoBlock: number | string;\n\toperationId?: string;\n\tstatus?: \"queued\" | \"running\" | \"cancel_requested\";\n}\n\nexport interface SubgraphQueryParams {\n\tsort?: string;\n\torder?: string;\n\tlimit?: number;\n\toffset?: number;\n\tfields?: string;\n\tfilters?: Record<string, string>;\n}\n\n/**\n * Request shape for `GET /v1/subgraphs/:subgraphName/:tableName/aggregate`.\n * `filters` reuses the list/count where-surface; the rest name the columns to\n * aggregate. SUM/MIN/MAX columns must be numeric (uint/int, plus `_block_height`).\n */\nexport interface SubgraphAggregateParams {\n\tfilters?: Record<string, string>;\n\tcount?: boolean;\n\tcountDistinct?: string[];\n\tsum?: string[];\n\tmin?: string[];\n\tmax?: string[];\n}\n\n/**\n * Aggregate response. Keys are present only for requested aggregates.\n * `count`/`countDistinct` are JSON numbers (counts << 2^53); `sum`/`min`/`max`\n * are lossless strings (NUMERIC `::text`). `sum` of an empty set is `\"0\"`;\n * `min`/`max` are `null` when the filtered set is empty or all-null.\n */\nexport interface SubgraphAggregateResponse {\n\tcount?: number;\n\tcountDistinct?: Record<string, number>;\n\tsum?: Record<string, string>;\n\tmin?: Record<string, string | null>;\n\tmax?: Record<string, string | null>;\n}\n",
|
|
7
|
+
"import { z } from \"zod\";\n\n// ── Deploy Subgraph Request ─────────────────────────────────────────────────\n\n/** The body for deploying a subgraph: sources, schema, and handler code. */\nexport interface DeploySubgraphRequest {\n\tname: string;\n\tdescription?: string;\n\tsources: Record<string, Record<string, unknown>>;\n\tschema: Record<string, unknown>;\n\thandlerCode: string;\n\t/** Override the definition's startBlock for this deploy only. */\n\tstartBlock?: number;\n\t/** Original TypeScript source, persisted so chat can read/diff/edit later. */\n\tsourceCode?: string;\n\t/** Validate the definition + print the DDL plan without deploying. */\n\tdryRun?: boolean;\n}\n\nexport const DeploySubgraphRequestSchema: z.ZodType<DeploySubgraphRequest> =\n\tz.object({\n\t\tname: z\n\t\t\t.string()\n\t\t\t.regex(/^[a-z0-9-]+$/, \"lowercase alphanumeric + hyphens only\")\n\t\t\t// `subgraph_<name>` must fit Postgres' 63-byte identifier limit.\n\t\t\t.max(54),\n\t\tdescription: z.string().optional(),\n\t\tsources: z\n\t\t\t.record(z.string(), z.record(z.string(), z.unknown()))\n\t\t\t.refine(\n\t\t\t\t(s) => Object.keys(s).length > 0,\n\t\t\t\t\"Must have at least one source\",\n\t\t\t),\n\t\tschema: z.record(z.string(), z.unknown()),\n\t\thandlerCode: z.string().max(1_048_576, \"handler code exceeds 1MB limit\"),\n\t\tstartBlock: z.number().int().nonnegative().optional(),\n\t\tsourceCode: z\n\t\t\t.string()\n\t\t\t.max(1_048_576, \"source code exceeds 1MB limit\")\n\t\t\t.optional(),\n\t\tdryRun: z.boolean().optional(),\n\t});\n\n/**\n * How far a subgraph's rows can be checked without trusting the server,\n * derived from its sources and a scan of its handler. Never configured.\n *\n * - `state`: every input is a named state write, provable from block headers.\n * Handlers run in the deterministic realm. A deployed `state` subgraph is\n * verifiable: one with any reason is refused at deploy.\n * - `events`: an input (events, prints, tx results, `ctx.client`) needs\n * re-execution proofs, which are not served yet.\n * - `none`: a source can never be proven as written (trait scope, tip-first\n * backfill).\n */\nexport interface SubgraphVerification {\n\tlevel: \"state\" | \"events\" | \"none\";\n\t/** What stands between the subgraph and checkable rows, e.g.\n\t * `print_event source \"swaps\" needs event proofs` or\n\t * `subgraph.ts:41:12 Date: wall-clock time differs per run`. */\n\treasons: string[];\n\t/** What stays unproven even at this level, e.g. tx attribution of writes. */\n\tunproven: string[];\n}\n\n/** What a deploy did, the version, and where indexing starts. */\nexport interface DeploySubgraphResponse {\n\taction: \"created\" | \"unchanged\" | \"handler_updated\" | \"updated\" | \"reindexed\";\n\tsubgraphId: string;\n\tversion: string;\n\tmessage: string;\n\t/** Effective indexing start height. */\n\tstart_block?: number;\n\toperationId?: string;\n\treindexStarted?: boolean;\n\t/** Bounded candidate-event denominator for the reindex just started, when the\n\t * op was classifiable as sparse/light. Absent for heavy ops (no upfront estimate\n\t * possible) — check `sl subgraphs status` after ~30s for a rate-based ETA instead. */\n\testimatedEvents?: number;\n\t/** Non-blocking deploy lints (e.g. handler reads a print field never observed on-chain). */\n\twarnings?: string[];\n\t/** sha256 identity of what was deployed; absent on unbundled deploys. */\n\tpin?: string;\n\tverification?: SubgraphVerification;\n\tdiff?: {\n\t\taddedTables: string[];\n\t\tremovedTables: string[];\n\t\taddedColumns: Record<string, string[]>;\n\t\tbreakingChanges: string[];\n\t};\n}\n\n// Subgraph API response types\n\n/** Every state `subgraphs.status` can hold; mirrored by the\n * `subgraphs_status_check` CHECK (migration 0189). */\nexport const SUBGRAPH_STATES = [\"active\", \"reindexing\", \"error\"] as const;\nexport type SubgraphStatus = (typeof SUBGRAPH_STATES)[number];\n\n/** What an operator sees: `synced` and `catching_up` are both `active` rows. */\nexport type SubgraphSyncState =\n\t| \"synced\"\n\t| \"catching_up\"\n\t| \"reindexing\"\n\t| \"error\";\n\n/**\n * The one answer to \"is this subgraph caught up?\". `tip` is the chain tip the\n * subgraph is measured against (its reindex target while reindexing is the\n * caller's concern: a reindexing subgraph is `reindexing` whatever its cursor).\n */\nexport function syncState(\n\tsubgraph: {\n\t\tstatus: string;\n\t\tlastProcessedBlock: number | string;\n\t},\n\ttip: number,\n): SubgraphSyncState {\n\tif (subgraph.status === \"reindexing\") return \"reindexing\";\n\tif (subgraph.status === \"error\") return \"error\";\n\treturn Number(subgraph.lastProcessedBlock) < tip ? \"catching_up\" : \"synced\";\n}\n\n/** A subgraph's name, status, and indexing progress. */\nexport interface SubgraphSummary {\n\tname: string;\n\tversion: string;\n\tstatus: string;\n\tlastProcessedBlock: number;\n\ttotalProcessed: number;\n\ttotalRows?: number;\n\ttotalErrors: number;\n\ttables: string[];\n\tchainTip: number;\n\tsourceChainTip?: number;\n\ttargetBlock?: number;\n\tprogress: number;\n\tblocksRemaining?: number;\n\tsyncMode?: \"sync\" | \"reindex\";\n\tgapCount: number;\n\t/** history_filling = expected gaps while a tip-first backfill op runs. */\n\tintegrity: \"complete\" | \"gaps_detected\" | \"history_filling\";\n\t/** Most recent indexing error reason + when it occurred, if any. */\n\tlastError?: string | null;\n\tlastErrorAt?: string | null;\n\t/** Billing code (`spend_cap_reached`, `insufficient_credits`) while reads\n\t * are refused for the account; null otherwise. */\n\tbillingPausedCode?: string | null;\n\t/** Last row mutation timestamp; powers per-card freshness. */\n\tupdatedAt?: string | null;\n\tcreatedAt: string;\n}\n\nexport interface SubgraphGapRange {\n\tstart: number;\n\tend: number;\n\tsize: number;\n\treason: string;\n}\n\nexport interface SubgraphSyncInfo {\n\tstatus: SubgraphSyncState;\n\tmode?: \"sync\" | \"reindex\";\n\tstartBlock: number;\n\tlastProcessedBlock: number;\n\t/**\n\t * Backward-compatible denominator for progress displays. During reindexing,\n\t * this is the reindex target block rather than the live source chain tip.\n\t */\n\tchainTip: number;\n\tsourceChainTip?: number;\n\ttargetBlock?: number;\n\tblocksRemaining: number;\n\tprocessedBlocks?: number;\n\ttotalBlocks?: number;\n\tprogress: number;\n\t/** Present while the populating operation is queued: approximate claim\n\t * position + honest event denominator + naive start estimate. */\n\tqueue?: {\n\t\tposition: number | null;\n\t\testimatedEvents: number | null;\n\t\testimatedStartSeconds: number | null;\n\t};\n\t/** Event-based progress for sparse syncs (block pct is meaningless when\n\t * most heights are skipped). */\n\testimatedEvents?: number;\n\tprocessedEvents?: number;\n\tetaSeconds?: number | null;\n\tgaps: {\n\t\tcount: number;\n\t\ttotalMissingBlocks: number;\n\t\tranges: SubgraphGapRange[];\n\t};\n\t/** history_filling = expected gaps while a tip-first backfill op runs. */\n\tintegrity: \"complete\" | \"gaps_detected\" | \"history_filling\";\n}\n\n/** A subgraph's version, pin, status, tables, and sources. */\nexport interface SubgraphDetail {\n\tname: string;\n\tversion: string;\n\tschemaHash?: string;\n\t/** sha256 over schema, handler bundle, startBlock, network and runtime.\n\t * Null for subgraphs deployed before pins existed. */\n\tpin?: string | null;\n\t/** Null for subgraphs deployed before levels were derived. */\n\tverification?: SubgraphVerification | null;\n\tstatus: string;\n\tlastProcessedBlock: number;\n\tdescription?: string;\n\tsources?: Record<string, unknown>;\n\tdefinition?: Record<string, unknown>;\n\thealth: {\n\t\ttotalProcessed: number;\n\t\ttotalErrors: number;\n\t\terrorRate: number;\n\t\tlastError: string | null;\n\t\tlastErrorAt: string | null;\n\t\t/** Billing code while the account's reads are refused; null otherwise. */\n\t\tbillingPausedCode?: string | null;\n\t\t/** True after the processor matched work but user tables still have 0 rows. */\n\t\temptyMapping: boolean;\n\t};\n\tsync: SubgraphSyncInfo;\n\ttables: Record<\n\t\tstring,\n\t\t{\n\t\t\tendpoint: string;\n\t\t\tcolumns: Record<\n\t\t\t\tstring,\n\t\t\t\t{\n\t\t\t\t\ttype: string;\n\t\t\t\t\tnullable?: boolean;\n\t\t\t\t\tindexed?: boolean;\n\t\t\t\t\tsearchable?: boolean;\n\t\t\t\t\tdefault?: string | number | boolean;\n\t\t\t\t}\n\t\t\t>;\n\t\t\trowCount: number;\n\t\t\texample: string;\n\t\t\tindexes?: readonly (readonly string[])[];\n\t\t\tuniqueKeys?: readonly (readonly string[])[];\n\t\t}\n\t>;\n\tcreatedAt: string;\n\tupdatedAt: string;\n}\n\nexport interface SubgraphGapEntry {\n\tstart: number;\n\tend: number;\n\tsize: number;\n\treason: string;\n\tdetectedAt: string;\n\tresolvedAt: string | null;\n}\n\n/** Missing block ranges in a subgraph, with totals. */\nexport interface SubgraphGapsResponse {\n\tdata: SubgraphGapEntry[];\n\tmeta: {\n\t\ttotal: number;\n\t\ttotalMissingBlocks: number;\n\t\tlimit: number;\n\t\toffset: number;\n\t};\n}\n\n/** A queued reindex and the block range it covers. */\nexport interface ReindexResponse {\n\tmessage: string;\n\tfromBlock: number;\n\ttoBlock: number | string;\n\toperationId?: string;\n\tstatus?: \"queued\" | \"running\" | \"cancel_requested\";\n}\n\nexport interface SubgraphQueryParams {\n\tsort?: string;\n\torder?: string;\n\tlimit?: number;\n\toffset?: number;\n\tfields?: string;\n\tfilters?: Record<string, string>;\n}\n\n/**\n * Request shape for `GET /v1/subgraphs/:subgraphName/:tableName/aggregate`.\n * `filters` reuses the list/count where-surface; the rest name the columns to\n * aggregate. SUM/MIN/MAX columns must be numeric (uint/int, plus `_block_height`).\n */\nexport interface SubgraphAggregateParams {\n\tfilters?: Record<string, string>;\n\tcount?: boolean;\n\tcountDistinct?: string[];\n\tsum?: string[];\n\tmin?: string[];\n\tmax?: string[];\n}\n\n/**\n * Aggregate response. Keys are present only for requested aggregates.\n * `count`/`countDistinct` are JSON numbers (counts << 2^53); `sum`/`min`/`max`\n * are lossless strings (NUMERIC `::text`). `sum` of an empty set is `\"0\"`;\n * `min`/`max` are `null` when the filtered set is empty or all-null.\n */\nexport interface SubgraphAggregateResponse {\n\tcount?: number;\n\tcountDistinct?: Record<string, number>;\n\tsum?: Record<string, string>;\n\tmin?: Record<string, string | null>;\n\tmax?: Record<string, string | null>;\n}\n",
|
|
8
8
|
"import { type RawBuilder, sql } from \"kysely\";\n\n/**\n * Safely encode a JS value as a JSONB literal for Kysely inserts/updates.\n * Kysely + postgres.js double-encodes JSON when using parameterized queries\n * with ::jsonb casts. This uses sql.raw to inline a properly escaped literal.\n *\n * Generic parameter lets callers set the RawBuilder's output type so they\n * don't need to cast at the insert site. Default is `unknown` — widen at\n * the call site when the column type is narrower, e.g. `jsonb<MyShape>(...)`.\n */\nexport function jsonb<T = unknown>(value: T): RawBuilder<T> {\n\tconst escaped = JSON.stringify(value, (_k, v) =>\n\t\ttypeof v === \"bigint\" ? v.toString() : v,\n\t).replace(/'/g, \"''\");\n\treturn sql`${sql.raw(`'${escaped}'::jsonb`)}`;\n}\n\n/**\n * Safely parse a JSONB value from the database.\n * Handles double-encoded strings where postgres.js returns a JSON string\n * instead of a parsed object.\n */\nexport function parseJsonb<T = unknown>(value: unknown): T {\n\tif (typeof value === \"string\") {\n\t\ttry {\n\t\t\treturn JSON.parse(value) as T;\n\t\t} catch {\n\t\t\treturn value as T;\n\t\t}\n\t}\n\treturn (value ?? {}) as T;\n}\n",
|
|
9
9
|
"import { type Kysely, sql } from \"kysely\";\n\n/**\n * The one convention for state machines: states are a const array (mirrored by\n * a DB CHECK), transitions are a table next to the states, and every status\n * write goes through `casTransition`.\n */\n\nexport interface Machine<S extends string> {\n\treadonly states: readonly S[];\n\tcanTransition(from: S, to: S): boolean;\n\t/** Throws on an illegal move. */\n\tassert(from: S, to: S): void;\n}\n\n/** Pure transition table. `transitions` lists, per state, the states it may move to. */\nexport function defineMachine<const S extends string>(def: {\n\tstates: readonly S[];\n\ttransitions: { readonly [K in S]?: readonly S[] };\n}): Machine<S> {\n\tconst canTransition = (from: S, to: S) =>\n\t\tdef.transitions[from]?.includes(to) ?? false;\n\treturn {\n\t\tstates: def.states,\n\t\tcanTransition,\n\t\tassert(from, to) {\n\t\t\tif (!canTransition(from, to)) {\n\t\t\t\tthrow new Error(`illegal transition ${from} -> ${to}`);\n\t\t\t}\n\t\t},\n\t};\n}\n\nexport interface CasTransition<S extends string> {\n\ttable: string;\n\t/** Value of the row key. */\n\tid: string | number;\n\t/** Row key column, `id` unless the table is addressed by another unique column (`name`). */\n\tkey?: string;\n\t/** Status column, `status` unless the machine lives in another column. */\n\tcolumn?: string;\n\t/** The row moves only if it is currently in one of these states. */\n\tfrom: readonly S[];\n\tto: S;\n\t/** Extra columns written in the same statement. Wrap jsonb values with `jsonb()`. */\n\tset?: Record<string, unknown>;\n\t/** Stamp `updated_at = now()`. Pass `false` for tables without that column. */\n\tstampUpdatedAt?: boolean;\n\t/** Columns to return, `*` unless the row carries a large payload (`[\"sequence\"]`). */\n\treturning?: readonly string[];\n}\n\n/**\n * Compare-and-swap a status column: `UPDATE ... WHERE key = ? AND column = ANY(from)`.\n * Returns the updated row (or the `returning` columns), or `null` when the row was missing or not in a `from`\n * state (a lost race). The caller decides what `null` means; usually log and stop.\n * Works with `db` and inside a transaction (`trx`).\n */\nexport async function casTransition<\n\tS extends string,\n\t// biome-ignore lint/suspicious/noExplicitAny: dynamic table name, row shape is the caller's\n\tRow = Record<string, any>,\n>(\n\t// biome-ignore lint/suspicious/noExplicitAny: accepts Kysely<Database> and Transaction<Database>\n\tdb: Kysely<any>,\n\tt: CasTransition<S>,\n): Promise<Row | null> {\n\tconst column = sql.id(t.column ?? \"status\");\n\tconst assignments = [sql`${column} = ${t.to}`];\n\tif (t.stampUpdatedAt !== false) assignments.push(sql`updated_at = now()`);\n\tfor (const [key, value] of Object.entries(t.set ?? {})) {\n\t\tassignments.push(sql`${sql.id(key)} = ${value}`);\n\t}\n\n\tconst returning = t.returning\n\t\t? sql.join(t.returning.map((c) => sql.id(c)))\n\t\t: sql.raw(\"*\");\n\n\tconst { rows } = await sql<Row>`\n\t\tUPDATE ${sql.table(t.table)}\n\t\tSET ${sql.join(assignments)}\n\t\tWHERE ${sql.id(t.key ?? \"id\")} = ${t.id} AND ${column} = ANY(${sql.val([...t.from])})\n\t\tRETURNING ${returning}\n\t`.execute(db);\n\treturn rows[0] ?? null;\n}\n"
|
|
10
10
|
],
|
|
11
|
-
"mappings": ";AAAA,gBAAsB;;;ACmBtB,IAAM,cAA+C;AAAA,EACpD;AAAA,EACA;AAAA,EACA;AACD;AAEA,SAAS,YAAY,GAAyB;AAAA,EAC7C,MAAM,MAAM,QAAQ,IAAI,eAAe,KAAK,EAAE,YAAY;AAAA,EAC1D,IAAI,OAAQ,YAAkC,SAAS,GAA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AAAA;AAiB9C,eAAsB,kBAAkB,CACvC,IACA,MACA,oBACA,WACgB;AAAA,EAChB,MAAM,GACJ,YAAY,WAAW,EACvB,IAAI;AAAA,IACJ,sBAAsB;AAAA,OACnB,WAAW,SAAS;AAAA,IACvB,YAAY,IAAI;AAAA,EACjB,CAAC,EACA,MAAM,QAAQ,KAAK,IAAI,EACvB,MAAM,UAAU,KAAK,QAAQ,EAC7B,QAAQ;AAAA;",
|
|
12
|
+
"debugId": "0CD84579713DF11164756E2164756E21",
|
|
13
13
|
"names": []
|
|
14
14
|
}
|
|
@@ -69,6 +69,9 @@ interface BlocksTable {
|
|
|
69
69
|
/** Tx count `persistBlock` was handed for this height. Null on rows
|
|
70
70
|
* ingested before this column existed. */
|
|
71
71
|
tx_count: ColumnType<number | null, number | null | undefined, number | null>;
|
|
72
|
+
/** Event count `persistBlock` was handed for this height. Null on rows
|
|
73
|
+
* ingested before this column existed. */
|
|
74
|
+
event_count: ColumnType<number | null, number | null | undefined, number | null>;
|
|
72
75
|
created_at: Generated<Date>;
|
|
73
76
|
}
|
|
74
77
|
interface TransactionsTable {
|
|
@@ -202,6 +205,8 @@ interface SubgraphsTable {
|
|
|
202
205
|
schema_name: string | null;
|
|
203
206
|
start_block: Generated<number>;
|
|
204
207
|
last_processed_block: Generated<number>;
|
|
208
|
+
/** Hash of the block at `last_processed_block`; NULL = unknown (see 0197). */
|
|
209
|
+
last_processed_block_hash: Generated<string | null>;
|
|
205
210
|
reindex_from_block: number | null;
|
|
206
211
|
reindex_to_block: number | null;
|
|
207
212
|
last_error: string | null;
|
|
@@ -326,6 +331,8 @@ interface ApiKeysTable {
|
|
|
326
331
|
interface InstancesTable {
|
|
327
332
|
id: Generated<string>;
|
|
328
333
|
network: string;
|
|
334
|
+
/** `SECONDLAYER_SECRETS_KEY` sealed under itself; see `ensureSecretsKeyCanary`. */
|
|
335
|
+
secrets_key_canary: ColumnType<string | null, string | null | undefined, string | null>;
|
|
329
336
|
created_at: Generated<Date>;
|
|
330
337
|
}
|
|
331
338
|
interface AccountsTable {
|
|
@@ -79,6 +79,9 @@ interface BlocksTable {
|
|
|
79
79
|
/** Tx count `persistBlock` was handed for this height. Null on rows
|
|
80
80
|
* ingested before this column existed. */
|
|
81
81
|
tx_count: ColumnType<number | null, number | null | undefined, number | null>;
|
|
82
|
+
/** Event count `persistBlock` was handed for this height. Null on rows
|
|
83
|
+
* ingested before this column existed. */
|
|
84
|
+
event_count: ColumnType<number | null, number | null | undefined, number | null>;
|
|
82
85
|
created_at: Generated<Date>;
|
|
83
86
|
}
|
|
84
87
|
interface TransactionsTable {
|
|
@@ -212,6 +215,8 @@ interface SubgraphsTable {
|
|
|
212
215
|
schema_name: string | null;
|
|
213
216
|
start_block: Generated<number>;
|
|
214
217
|
last_processed_block: Generated<number>;
|
|
218
|
+
/** Hash of the block at `last_processed_block`; NULL = unknown (see 0197). */
|
|
219
|
+
last_processed_block_hash: Generated<string | null>;
|
|
215
220
|
reindex_from_block: number | null;
|
|
216
221
|
reindex_to_block: number | null;
|
|
217
222
|
last_error: string | null;
|
|
@@ -336,6 +341,8 @@ interface ApiKeysTable {
|
|
|
336
341
|
interface InstancesTable {
|
|
337
342
|
id: Generated<string>;
|
|
338
343
|
network: string;
|
|
344
|
+
/** `SECONDLAYER_SECRETS_KEY` sealed under itself; see `ensureSecretsKeyCanary`. */
|
|
345
|
+
secrets_key_canary: ColumnType<string | null, string | null | undefined, string | null>;
|
|
339
346
|
created_at: Generated<Date>;
|
|
340
347
|
}
|
|
341
348
|
interface AccountsTable {
|
|
@@ -84,11 +84,12 @@ import {
|
|
|
84
84
|
appendFileSync,
|
|
85
85
|
closeSync,
|
|
86
86
|
existsSync,
|
|
87
|
+
mkdirSync,
|
|
87
88
|
openSync,
|
|
88
89
|
readFileSync,
|
|
89
90
|
unlinkSync
|
|
90
91
|
} from "node:fs";
|
|
91
|
-
import { resolve } from "node:path";
|
|
92
|
+
import { dirname, resolve } from "node:path";
|
|
92
93
|
|
|
93
94
|
// src/mode.ts
|
|
94
95
|
var VALID_MODES = [
|
|
@@ -135,6 +136,13 @@ function isWebhookAccountScoped() {
|
|
|
135
136
|
var KEY_ENV = "SECONDLAYER_SECRETS_KEY";
|
|
136
137
|
var IV_LEN = 12;
|
|
137
138
|
var TAG_LEN = 16;
|
|
139
|
+
function keyFilePath() {
|
|
140
|
+
const dataDir = process.env.DATA_DIR?.trim();
|
|
141
|
+
return dataDir ? resolve(dataDir, "secrets.env") : resolve(process.cwd(), ".env.local");
|
|
142
|
+
}
|
|
143
|
+
function legacyKeyFilePath() {
|
|
144
|
+
return resolve(process.cwd(), ".env.local");
|
|
145
|
+
}
|
|
138
146
|
function readExistingKey(envPath) {
|
|
139
147
|
if (!existsSync(envPath))
|
|
140
148
|
return null;
|
|
@@ -145,12 +153,13 @@ function readExistingKey(envPath) {
|
|
|
145
153
|
var STALE_LOCK_MS = 1e4;
|
|
146
154
|
var POLL_MS = 25;
|
|
147
155
|
function bootstrapOssKey() {
|
|
148
|
-
const envPath =
|
|
156
|
+
const envPath = keyFilePath();
|
|
149
157
|
const existing = readExistingKey(envPath);
|
|
150
158
|
if (existing) {
|
|
151
159
|
process.env[KEY_ENV] = existing;
|
|
152
160
|
return existing;
|
|
153
161
|
}
|
|
162
|
+
mkdirSync(dirname(envPath), { recursive: true });
|
|
154
163
|
const lockPath = `${envPath}.secret-bootstrap.lock`;
|
|
155
164
|
let lockFd = null;
|
|
156
165
|
try {
|
|
@@ -176,13 +185,15 @@ function bootstrapOssKey() {
|
|
|
176
185
|
return bootstrapOssKey();
|
|
177
186
|
}
|
|
178
187
|
try {
|
|
179
|
-
const
|
|
188
|
+
const legacy = legacyKeyFilePath();
|
|
189
|
+
const carried = legacy === envPath ? null : readExistingKey(legacy);
|
|
190
|
+
const hex = carried ?? randomBytes2(32).toString("hex");
|
|
180
191
|
const line = `${existsSync(envPath) ? `
|
|
181
192
|
` : ""}${KEY_ENV}=${hex}
|
|
182
193
|
`;
|
|
183
194
|
appendFileSync(envPath, line, { mode: 384 });
|
|
184
195
|
process.env[KEY_ENV] = hex;
|
|
185
|
-
console.log(`[secondlayer] generated ${KEY_ENV}; saved to ${envPath} (mode 0600)`);
|
|
196
|
+
console.log(`[secondlayer] ${carried ? `moved ${KEY_ENV} from ${legacy} to` : `generated ${KEY_ENV}; saved to`} ${envPath} (mode 0600)`);
|
|
186
197
|
return hex;
|
|
187
198
|
} finally {
|
|
188
199
|
closeSync(lockFd);
|
|
@@ -216,11 +227,13 @@ function secretsKeyAvailable() {
|
|
|
216
227
|
if (process.env[KEY_ENV])
|
|
217
228
|
return true;
|
|
218
229
|
if (getInstanceMode() === "oss") {
|
|
219
|
-
|
|
220
|
-
return readExistingKey(envPath) !== null;
|
|
230
|
+
return readExistingKey(keyFilePath()) !== null || readExistingKey(legacyKeyFilePath()) !== null;
|
|
221
231
|
}
|
|
222
232
|
return false;
|
|
223
233
|
}
|
|
234
|
+
function resolveSecretsKeyHex() {
|
|
235
|
+
return getKey().toString("hex");
|
|
236
|
+
}
|
|
224
237
|
function encryptSecret(plaintext) {
|
|
225
238
|
const key = getKey();
|
|
226
239
|
const iv = randomBytes2(IV_LEN);
|
|
@@ -601,5 +614,5 @@ export {
|
|
|
601
614
|
reapStaleScans
|
|
602
615
|
};
|
|
603
616
|
|
|
604
|
-
//# debugId=
|
|
617
|
+
//# debugId=B47335099CB5B51B64756E2164756E21
|
|
605
618
|
//# sourceMappingURL=webhook-replays.js.map
|