@secondlayer/shared 11.19.0 → 11.19.2

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.
@@ -160,7 +160,6 @@ interface SubgraphsTable {
160
160
  expires_at: Date | null;
161
161
  /** (event type, contract) probe pairs persisted at deploy for weight classification. */
162
162
  sparse_probe_targets: unknown | null;
163
- sandbox_workers: Generated<boolean>;
164
163
  created_at: Generated<Date>;
165
164
  updated_at: Generated<Date>;
166
165
  }
@@ -160,7 +160,6 @@ interface SubgraphsTable {
160
160
  expires_at: Date | null;
161
161
  /** (event type, contract) probe pairs persisted at deploy for weight classification. */
162
162
  sparse_probe_targets: unknown | null;
163
- sandbox_workers: Generated<boolean>;
164
163
  created_at: Generated<Date>;
165
164
  updated_at: Generated<Date>;
166
165
  }
@@ -477,7 +477,6 @@ interface SubgraphsTable {
477
477
  expires_at: Date | null;
478
478
  /** (event type, contract) probe pairs persisted at deploy for weight classification. */
479
479
  sparse_probe_targets: unknown | null;
480
- sandbox_workers: Generated<boolean>;
481
480
  created_at: Generated<Date>;
482
481
  updated_at: Generated<Date>;
483
482
  }
@@ -161,7 +161,6 @@ interface SubgraphsTable {
161
161
  expires_at: Date | null;
162
162
  /** (event type, contract) probe pairs persisted at deploy for weight classification. */
163
163
  sparse_probe_targets: unknown | null;
164
- sandbox_workers: Generated<boolean>;
165
164
  created_at: Generated<Date>;
166
165
  updated_at: Generated<Date>;
167
166
  }
@@ -160,7 +160,6 @@ interface SubgraphsTable {
160
160
  expires_at: Date | null;
161
161
  /** (event type, contract) probe pairs persisted at deploy for weight classification. */
162
162
  sparse_probe_targets: unknown | null;
163
- sandbox_workers: Generated<boolean>;
164
163
  created_at: Generated<Date>;
165
164
  updated_at: Generated<Date>;
166
165
  }
@@ -160,7 +160,6 @@ interface SubgraphsTable {
160
160
  expires_at: Date | null;
161
161
  /** (event type, contract) probe pairs persisted at deploy for weight classification. */
162
162
  sparse_probe_targets: unknown | null;
163
- sandbox_workers: Generated<boolean>;
164
163
  created_at: Generated<Date>;
165
164
  updated_at: Generated<Date>;
166
165
  }
@@ -160,7 +160,6 @@ interface SubgraphsTable {
160
160
  expires_at: Date | null;
161
161
  /** (event type, contract) probe pairs persisted at deploy for weight classification. */
162
162
  sparse_probe_targets: unknown | null;
163
- sandbox_workers: Generated<boolean>;
164
163
  created_at: Generated<Date>;
165
164
  updated_at: Generated<Date>;
166
165
  }
@@ -160,7 +160,6 @@ interface SubgraphsTable {
160
160
  expires_at: Date | null;
161
161
  /** (event type, contract) probe pairs persisted at deploy for weight classification. */
162
162
  sparse_probe_targets: unknown | null;
163
- sandbox_workers: Generated<boolean>;
164
163
  created_at: Generated<Date>;
165
164
  updated_at: Generated<Date>;
166
165
  }
@@ -160,7 +160,6 @@ interface SubgraphsTable {
160
160
  expires_at: Date | null;
161
161
  /** (event type, contract) probe pairs persisted at deploy for weight classification. */
162
162
  sparse_probe_targets: unknown | null;
163
- sandbox_workers: Generated<boolean>;
164
163
  created_at: Generated<Date>;
165
164
  updated_at: Generated<Date>;
166
165
  }
@@ -160,7 +160,6 @@ interface SubgraphsTable {
160
160
  expires_at: Date | null;
161
161
  /** (event type, contract) probe pairs persisted at deploy for weight classification. */
162
162
  sparse_probe_targets: unknown | null;
163
- sandbox_workers: Generated<boolean>;
164
163
  created_at: Generated<Date>;
165
164
  updated_at: Generated<Date>;
166
165
  }
@@ -1051,6 +1050,18 @@ declare function findActiveSubgraphOperation(db: Kysely<Database>, subgraphId: s
1051
1050
  declare function requestSubgraphOperationCancel(db: Kysely<Database>, subgraphId: string): Promise<SubgraphOperation | null>;
1052
1051
  declare function requestSubgraphOperationsCancelForDelete(db: Kysely<Database>, subgraphId: string): Promise<SubgraphOperation[]>;
1053
1052
  /**
1053
+ * Settle cancel-requested operations nobody is running: a queued one (no
1054
+ * runner ever claimed it) and a running one whose lock has lapsed (its runner
1055
+ * died without releasing the row; heartbeats renew the lock every 15s, so a
1056
+ * lapsed one is a dead process, not a slow one). Returns how many rows were
1057
+ * cancelled.
1058
+ *
1059
+ * An operation whose lock is still live is NEVER touched: its runner is
1060
+ * alive, and the only safe way to stop it is the runner observing
1061
+ * `cancel_requested` itself and releasing the row and advisory locks.
1062
+ */
1063
+ declare function cancelOrphanedSubgraphOperations(db: Kysely<Database>, subgraphId: string): Promise<number>;
1064
+ /**
1054
1065
  * Poll until no active subgraph operations remain for the subgraph or until
1055
1066
  * `timeoutMs` elapses. Returns true if all active operations cleared, false
1056
1067
  * if we timed out. Callers should use this before `DROP SCHEMA` so the active
@@ -1084,4 +1095,4 @@ declare function updateOperationProcessedEvents(db: Kysely<Database>, operationI
1084
1095
  * whether THIS caller advanced (false = a racing writer already covered h).
1085
1096
  */
1086
1097
  declare function advanceOperationCursor(db: Kysely<Database>, operationId: string, height: number): Promise<boolean>;
1087
- export { advanceOperationCursor, cancelSubgraphOperation, claimSubgraphOperation, completeSubgraphOperation, createSubgraphOperation, failSubgraphOperation, findActiveSubgraphOperation, getOperationQueuePosition, getRecentOperationMedianDuration, getSubgraphOperation, heartbeatSubgraphOperation, isActiveSubgraphOperationConflict, listSubgraphOperations, requestSubgraphOperationCancel, requestSubgraphOperationsCancelForDelete, updateOperationProcessedEvents, waitForSubgraphOperationsClear };
1098
+ export { advanceOperationCursor, cancelOrphanedSubgraphOperations, cancelSubgraphOperation, claimSubgraphOperation, completeSubgraphOperation, createSubgraphOperation, failSubgraphOperation, findActiveSubgraphOperation, getOperationQueuePosition, getRecentOperationMedianDuration, getSubgraphOperation, heartbeatSubgraphOperation, isActiveSubgraphOperationConflict, listSubgraphOperations, requestSubgraphOperationCancel, requestSubgraphOperationsCancelForDelete, updateOperationProcessedEvents, waitForSubgraphOperationsClear };
@@ -34,6 +34,20 @@ async function requestSubgraphOperationCancel(db, subgraphId) {
34
34
  async function requestSubgraphOperationsCancelForDelete(db, subgraphId) {
35
35
  return await db.updateTable("subgraph_operations").set({ cancel_requested: true, updated_at: new Date }).where("subgraph_id", "=", subgraphId).where("status", "in", ACTIVE_STATUSES).returningAll().execute();
36
36
  }
37
+ async function cancelOrphanedSubgraphOperations(db, subgraphId) {
38
+ const cancelled = await db.updateTable("subgraph_operations").set({
39
+ status: "cancelled",
40
+ finished_at: new Date,
41
+ locked_by: null,
42
+ locked_until: null,
43
+ updated_at: new Date
44
+ }).where("subgraph_id", "=", subgraphId).where("cancel_requested", "=", true).where("status", "in", ACTIVE_STATUSES).where((eb) => eb.or([
45
+ eb("status", "=", "queued"),
46
+ eb("locked_until", "is", null),
47
+ eb("locked_until", "<", sql`now()`)
48
+ ])).returning("id").execute();
49
+ return cancelled.length;
50
+ }
37
51
  async function waitForSubgraphOperationsClear(db, subgraphId, opts) {
38
52
  const timeoutMs = opts?.timeoutMs ?? 30000;
39
53
  const pollMs = opts?.pollMs ?? 500;
@@ -207,6 +221,7 @@ async function advanceOperationCursor(db, operationId, height) {
207
221
  }
208
222
  export {
209
223
  advanceOperationCursor,
224
+ cancelOrphanedSubgraphOperations,
210
225
  cancelSubgraphOperation,
211
226
  claimSubgraphOperation,
212
227
  completeSubgraphOperation,
@@ -225,5 +240,5 @@ export {
225
240
  waitForSubgraphOperationsClear
226
241
  };
227
242
 
228
- //# debugId=82AB266EA49F95E564756E2164756E21
243
+ //# debugId=09A116F9451DB4F164756E2164756E21
229
244
  //# sourceMappingURL=subgraph-operations.js.map
@@ -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 * 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). */\nfunction resolveHeavyOpBudget(): number {\n\tconst parsed = Number.parseInt(\n\t\tprocess.env.SUBGRAPH_HEAVY_OP_BUDGET ?? \"2\",\n\t\t10,\n\t);\n\treturn Number.isFinite(parsed) && parsed > 0 ? parsed : 2;\n}\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 when SUBGRAPH_OPERATION_CONCURRENCY > 1.\n\tconst heavyBudget = resolveHeavyOpBudget();\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) < ${heavyBudget}\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// 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). */\nfunction resolveHeavyOpBudget(): number {\n\tconst parsed = Number.parseInt(\n\t\tprocess.env.SUBGRAPH_HEAVY_OP_BUDGET ?? \"2\",\n\t\t10,\n\t);\n\treturn Number.isFinite(parsed) && parsed > 0 ? parsed : 2;\n}\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 when SUBGRAPH_OPERATION_CONCURRENCY > 1.\n\tconst heavyBudget = resolveHeavyOpBudget();\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) < ${heavyBudget}\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"
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,EAG7B,IAAI,eAAgD;AAAA,EACpD,IACC,KAAK,SAAS,cACd,KAAK,aAAa,QAClB,KAAK,WAAW,MACf;AAAA,IACD,MAAM,QAAQ,MAAM,GAClB,WAAW,qBAAqB,EAChC,OAAO,CAAC,OAAO,GAAG,GAAG,IAAI,cAAc,EAAE,GAAG,YAAY,CAAC,EACzD,MAAM,eAAe,KAAK,KAAK,UAAU,EACzC,MAAM,QAAQ,KAAK,UAAU,EAC7B,MAAM,UAAU,MAAM,CAAC,UAAU,WAAW,CAAC,EAC7C,MAAM,cAAc,MAAM,KAAK,OAAO,EACtC,MAAM,YAAY,MAAM,KAAK,SAAS,EACtC,iBAAiB;AAAA,IACnB,eAAe,OAAO,cAAc;AAAA,EACrC;AAAA,EACA,OAAO,MAAM,GACX,WAAW,qBAAqB,EAChC,OAAO;AAAA,IACP,aAAa,KAAK;AAAA,IAClB,eAAe,KAAK;AAAA,IACpB,YAAY,KAAK,aAAa;AAAA,IAC9B,MAAM,KAAK;AAAA,IACX,YAAY,KAAK,aAAa;AAAA,IAC9B,UAAU,KAAK,WAAW;AAAA,OACtB,KAAK,SAAS,EAAE,QAAQ,KAAK,OAAO,IAAI,CAAC;AAAA,IAC7C,kBAAkB,KAAK,mBAAmB;AAAA,IAC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-160,7 +160,6 @@ interface SubgraphsTable {
160
160
  expires_at: Date | null;
161
161
  /** (event type, contract) probe pairs persisted at deploy for weight classification. */
162
162
  sparse_probe_targets: unknown | null;
163
- sandbox_workers: Generated<boolean>;
164
163
  created_at: Generated<Date>;
165
164
  updated_at: Generated<Date>;
166
165
  }
@@ -170,7 +170,6 @@ interface SubgraphsTable {
170
170
  expires_at: Date | null;
171
171
  /** (event type, contract) probe pairs persisted at deploy for weight classification. */
172
172
  sparse_probe_targets: unknown | null;
173
- sandbox_workers: Generated<boolean>;
174
173
  created_at: Generated<Date>;
175
174
  updated_at: Generated<Date>;
176
175
  }
@@ -160,7 +160,6 @@ interface SubgraphsTable {
160
160
  expires_at: Date | null;
161
161
  /** (event type, contract) probe pairs persisted at deploy for weight classification. */
162
162
  sparse_probe_targets: unknown | null;
163
- sandbox_workers: Generated<boolean>;
164
163
  created_at: Generated<Date>;
165
164
  updated_at: Generated<Date>;
166
165
  }
@@ -159,7 +159,6 @@ interface SubgraphsTable {
159
159
  expires_at: Date | null;
160
160
  /** (event type, contract) probe pairs persisted at deploy for weight classification. */
161
161
  sparse_probe_targets: unknown | null;
162
- sandbox_workers: Generated<boolean>;
163
162
  created_at: Generated<Date>;
164
163
  updated_at: Generated<Date>;
165
164
  }
@@ -251,7 +251,7 @@ declare class IndexHttpClient {
251
251
  /** Lowest block height in [fromHeight, toHeight] with a matching event, or
252
252
  * null. One page, limit 1 — built for sparse-scan probes. */
253
253
  firstEventHeight(eventType: string, fromHeight: number, toHeight: number, contractId?: string): Promise<number | null>;
254
- walkEvents(eventType: string, fromHeight: number, toHeight: number, withTx?: boolean): Promise<IndexEventRow[]>;
254
+ walkEvents(eventType: string, fromHeight: number, toHeight: number, withTx?: boolean, contractId?: string): Promise<IndexEventRow[]>;
255
255
  walkTransactions(fromHeight: number, toHeight: number): Promise<IndexTransactionRow[]>;
256
256
  /** Canonical tip height from the Streams clock. */
257
257
  getStreamsTip(): Promise<number>;
@@ -146,10 +146,11 @@ class IndexHttpClient {
146
146
  const { items } = await this.getPage("/v1/index/events", "events", params);
147
147
  return items[0]?.block_height ?? null;
148
148
  }
149
- walkEvents(eventType, fromHeight, toHeight, withTx = false) {
149
+ walkEvents(eventType, fromHeight, toHeight, withTx = false, contractId) {
150
150
  return this.walk("/v1/index/events", "events", fromHeight, toHeight, {
151
151
  event_type: eventType,
152
- ...withTx ? { tx_context: "true" } : {}
152
+ ...withTx ? { tx_context: "true" } : {},
153
+ ...contractId ? { contract_id: contractId } : {}
153
154
  });
154
155
  }
155
156
  walkTransactions(fromHeight, toHeight) {
@@ -245,5 +246,5 @@ export {
245
246
  createInternalIndexHttpClient
246
247
  };
247
248
 
248
- //# debugId=D65DB2A28558841F64756E2164756E21
249
+ //# debugId=64784D5C41871B7164756E2164756E21
249
250
  //# sourceMappingURL=index-http.js.map
@@ -3,9 +3,9 @@
3
3
  "sources": ["../src/index-internal-auth.ts", "../src/index-http.ts"],
4
4
  "sourcesContent": [
5
5
  "// Internal service credentials for first-party consumers of /v1/index and\n// /v1/streams over HTTP (decoder, subgraph processor PublicApiBlockSource).\n// Seeded as internal tenants with NO account_id, so these reads are\n// unmetered (metering gates on account_id). Lives in shared so the API (seed)\n// and the consumers import it without a cycle.\n//\n// Resolution: STREAMS_INTERNAL_API_KEY / INDEX_INTERNAL_API_KEY, then\n// INSTANCE_TOKEN (OSS). No committed fallback. Empty-string env values fall\n// through (`trim()`, then empty): compose interpolates\n// `${STREAMS_INTERNAL_API_KEY:-}` which is \"\" when unset.\n//\n// Archive keys must not use the `sk-sl_` prefix; generate with `sl-int_`.\n// OSS compose should omit the internal env and send INSTANCE_TOKEN.\nexport const INDEX_INTERNAL_TENANT_ID = \"tenant_index_internal\";\nexport const INTERNAL_STREAMS_TENANT_ID = \"tenant_streams_decode_internal\";\n\nconst DEFAULT_INTERNAL_INDEX_BASE_URL = \"http://api:3800\";\n\nconst MISSING_INTERNAL_STREAMS_API_KEY =\n\t\"Set STREAMS_INTERNAL_API_KEY (archive; prefix sl-int_) or INSTANCE_TOKEN (OSS). Empty env no longer falls back to a committed secret.\";\n\nconst MISSING_INTERNAL_INDEX_API_KEY =\n\t\"Set INDEX_INTERNAL_API_KEY (archive; prefix sl-int_) or INSTANCE_TOKEN (OSS). Without one, Index reads carry no credential and platform mode 401s every one of them.\";\n\nexport function defaultInternalIndexApiKey(\n\tenv: NodeJS.ProcessEnv = process.env,\n): string | undefined {\n\tconst internal = env.INDEX_INTERNAL_API_KEY?.trim();\n\tif (internal) return internal;\n\tconst instance = env.INSTANCE_TOKEN?.trim();\n\tif (instance) return instance;\n\treturn undefined;\n}\n\nexport function defaultInternalStreamsApiKey(\n\tenv: NodeJS.ProcessEnv = process.env,\n): string | undefined {\n\tconst internal = env.STREAMS_INTERNAL_API_KEY?.trim();\n\tif (internal) return internal;\n\tconst instance = env.INSTANCE_TOKEN?.trim();\n\tif (instance) return instance;\n\treturn undefined;\n}\n\n/**\n * Platform-mode Index consumer: refuse to run with neither credential.\n *\n * Platform mode requires a credential on every Index read (a keyless read\n * 401s, `api/src/index/auth.ts`) — a first-party consumer with no internal\n * key would fail every request at call time. Fail here at startup instead.\n *\n * Self-hosted (oss/dedicated) instances are not gated, so they must NOT call\n * this — `defaultInternalIndexApiKey()` returning undefined is correct there.\n */\nexport function requireInternalIndexApiKey(\n\tenv: NodeJS.ProcessEnv = process.env,\n): string {\n\tconst key = defaultInternalIndexApiKey(env);\n\tif (!key) throw new Error(MISSING_INTERNAL_INDEX_API_KEY);\n\treturn key;\n}\n\n/** Decoder startup: refuse to run with neither credential. */\nexport function requireInternalStreamsApiKey(\n\tenv: NodeJS.ProcessEnv = process.env,\n): string {\n\tconst key = defaultInternalStreamsApiKey(env);\n\tif (!key) throw new Error(MISSING_INTERNAL_STREAMS_API_KEY);\n\treturn key;\n}\n\n/** Shared env contract for decoder + subgraph HTTP dogfood. */\nexport function defaultInternalIndexBaseUrl(): string {\n\treturn (\n\t\tprocess.env.SUBGRAPH_INDEX_API_URL ||\n\t\tprocess.env.STREAMS_API_URL ||\n\t\tDEFAULT_INTERNAL_INDEX_BASE_URL\n\t);\n}\n",
6
- "import {\n\tdefaultInternalIndexApiKey,\n\tdefaultInternalIndexBaseUrl,\n\tdefaultInternalStreamsApiKey,\n} from \"./index-internal-auth.ts\";\nimport type { RuneStreamsEvent } from \"./streams-rows/events.ts\";\n\n/**\n * Low-level transport for the public Index (`/v1/index`) + Streams clock\n * (`/v1/streams`) HTTP APIs: cursor-paginated reads, tip, reorgs. Lives in\n * `shared` (a leaf both the SDK and the subgraph runtime depend on) so the wire\n * format has one home and no package cycle. The SDK's ergonomic client should\n * eventually consume these row types too (see the plan's convergence task).\n *\n * This is intentionally minimal — just the GETs the subgraph runtime's\n * PublicApiBlockSource needs. It is NOT the SDK's full client (walk/consume/\n * retries/auth resolution).\n */\n\nconst PAGE_LIMIT = 1000;\n\n/** Ceiling on the Index long-poll `wait` param (seconds), shared by client and\n * server so neither drifts from the other. Kept comfortably under app-server\n * Caddy's `reverse_proxy` (no read/write timeout override, so this is a\n * self-imposed ceiling, not one it's protecting against) and Bun's own\n * 90s idleTimeout on the api listener. */\nexport const MAX_INDEX_WAIT_SECONDS = 25;\n\n// Transport resilience for the streams-index data plane. The api runs N>1\n// replicas behind Caddy; during a rolling deploy one replica is briefly\n// unreachable, surfacing as a thrown fetch (connection refused/reset) or a\n// Caddy 502/503/504 while it fails over. Retrying a few times with backoff\n// makes a single-replica recreate transparent to the subgraph-processor /\n// decoder — closing the processors-depend-on-api coupling.\nconst MAX_ATTEMPTS = 4;\nconst RETRY_BASE_MS = 150;\nconst RETRYABLE_STATUS = new Set([502, 503, 504]);\n\nconst delay = (ms: number): Promise<void> =>\n\tnew Promise((resolve) => setTimeout(resolve, ms));\n\n/** A non-2xx Index/Streams response, carrying the status so a caller can\n * distinguish \"the server rejected this request\" (e.g. a `wait`/`from_height`\n * param an older server's `validateQueryParams` doesn't recognize, HTTP 400)\n * from a transient outage — see `getIndexTipEnvelope`'s wait fallback. */\nexport class IndexHttpStatusError extends Error {\n\tconstructor(\n\t\treadonly status: number,\n\t\tmessage: string,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"IndexHttpStatusError\";\n\t}\n}\n\ntype Envelope<K extends string, T> = {\n\t[P in K]: T[];\n} & { next_cursor: string | null };\n\n// ── Index API wire shapes (single source of truth) ─────────────────────────\nexport type IndexBlockRow = {\n\tblock_height: number;\n\tblock_hash: string;\n\tparent_hash: string;\n\tburn_block_height: number;\n\tburn_block_hash: string | null;\n\t/** Nakamoto StacksBlockId. Absent from pre-2026-07 API deployments. */\n\tindex_block_hash?: string | null;\n\tblock_time: string | null;\n};\n\ntype IndexEventCommon = {\n\tblock_height: number;\n\ttx_id: string;\n\ttx_index?: number;\n\tevent_index: number;\n\tcontract_id: string | null;\n\t/** Submitting-tx context — present only when the read passed `tx_context=true`.\n\t * Lets a consumer build the tx for `ctx.tx` without a separate\n\t * walkTransactions (the ~37x reindex over-fetch; see indexing-speed plan). */\n\ttx_sender?: string | null;\n\ttx_type?: string | null;\n\ttx_status?: string | null;\n\ttx_contract_id?: string | null;\n\ttx_function_name?: string | null;\n};\n\nexport type IndexEventRow = IndexEventCommon &\n\t(\n\t\t| {\n\t\t\t\tevent_type: \"ft_transfer\" | \"ft_mint\" | \"ft_burn\";\n\t\t\t\tasset_identifier: string;\n\t\t\t\tsender?: string;\n\t\t\t\trecipient?: string;\n\t\t\t\tamount: string;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"nft_transfer\" | \"nft_mint\" | \"nft_burn\";\n\t\t\t\tasset_identifier: string;\n\t\t\t\tsender?: string;\n\t\t\t\trecipient?: string;\n\t\t\t\tvalue: string;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"stx_transfer\" | \"stx_mint\" | \"stx_burn\";\n\t\t\t\tsender?: string;\n\t\t\t\trecipient?: string;\n\t\t\t\tamount: string;\n\t\t\t\tmemo?: string | null;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"stx_lock\";\n\t\t\t\tsender: string;\n\t\t\t\tamount: string;\n\t\t\t\tpayload: { unlock_height: string | null };\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"print\";\n\t\t\t\tpayload: {\n\t\t\t\t\ttopic: string | null;\n\t\t\t\t\tvalue: unknown;\n\t\t\t\t\traw_value: string | null;\n\t\t\t\t};\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"nested_contract_call\";\n\t\t\t\tsender?: string | null;\n\t\t\t\tcaller: string;\n\t\t\t\tfunction_name: string;\n\t\t\t\tfunction_args?: unknown;\n\t\t\t\traw_result?: string | null;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"var_set\";\n\t\t\t\tvar_name: string;\n\t\t\t\traw_value?: string | null;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"map_set\" | \"map_insert\";\n\t\t\t\tmap: string;\n\t\t\t\traw_key?: string | null;\n\t\t\t\traw_value?: string | null;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"map_delete\";\n\t\t\t\tmap: string;\n\t\t\t\traw_key?: string | null;\n\t\t }\n\t);\n\nexport type IndexTransactionRow = {\n\ttx_id: string;\n\tblock_height: number;\n\tblock_time?: string | null;\n\tburn_block_height?: number | null;\n\ttx_index: number;\n\ttx_type: string;\n\tsender: string;\n\tstatus: string;\n\tcontract_call?: {\n\t\tcontract_id: string;\n\t\tfunction_name: string;\n\t\tfunction_args_hex?: string[] | null;\n\t\tresult_hex?: string | null;\n\t} | null;\n\tsmart_contract?: { contract_id: string | null } | null;\n};\n\nexport type StreamsReorgRow = {\n\tid: string;\n\tdetected_at: string;\n\tfork_point_height: number;\n\torphaned_range: { from: string; to: string };\n\tnew_canonical_tip: string;\n};\n\nexport type IndexHttpOptions = {\n\t/** Base URL for /v1/index (the decoded data plane). */\n\tindexBaseUrl: string;\n\t/** Bearer for /v1/index. Empty/unset omits the header. */\n\tindexApiKey?: string;\n\t/** Base URL for /v1/streams (the canonical clock). */\n\tstreamsBaseUrl: string;\n\t/** Bearer for /v1/streams. Empty/unset omits the header. */\n\tstreamsApiKey?: string;\n};\n\n/** `/v1/index/blocks?limit=1`'s envelope — read for its `tip`, not its rows. */\nexport type IndexTipEnvelope = {\n\ttip: {\n\t\tblock_height: number;\n\t\tsource_block_height?: number;\n\t\t/**\n\t\t * Committed height per classic decoded event_type, e.g.\n\t\t * `{ ft_transfer: 950, stx_transfer: 940 }`. `null` means that decoder\n\t\t * has no checkpoint yet (fail-closed for a caller that references it,\n\t\t * not \"committed to height 0\"); a missing key means an older server\n\t\t * that doesn't send this field at all. Absent on an instance built\n\t\t * before this field was added.\n\t\t */\n\t\tdecoded_heights?: Record<string, number | null>;\n\t};\n};\n\nexport class IndexHttpClient {\n\tprivate readonly indexBaseUrl: string;\n\tprivate readonly indexApiKey: string | undefined;\n\tprivate readonly streamsBaseUrl: string;\n\tprivate readonly streamsApiKey: string | undefined;\n\t/** Populated by the last `getIndexTipEnvelope()` call (via `getIndexTip`/\n\t * `getIndexSourceTip`) so `getDecodedHeights()` can read the SAME response\n\t * synchronously instead of making a second request. */\n\tprivate lastTipEnvelope: IndexTipEnvelope | undefined;\n\t/** Flips false the first time a `wait` request 400s — see\n\t * `getIndexTipEnvelope`'s catch. Per-instance, not global: a fresh client\n\t * (e.g. against a different/upgraded server) always tries wait again. */\n\tprivate waitSupported = true;\n\n\tconstructor(opts: IndexHttpOptions) {\n\t\tthis.indexBaseUrl = opts.indexBaseUrl.replace(/\\/+$/, \"\");\n\t\tthis.indexApiKey = opts.indexApiKey ?? defaultInternalIndexApiKey();\n\t\tthis.streamsBaseUrl = opts.streamsBaseUrl.replace(/\\/+$/, \"\");\n\t\tthis.streamsApiKey = opts.streamsApiKey;\n\t}\n\n\tprivate async get<T>(url: string, apiKey: string | undefined): Promise<T> {\n\t\t// Index reads are anon — omit the header entirely when no key is set, so\n\t\t// an empty key reads anonymously rather than 401-ing as an invalid bearer.\n\t\tconst headers: Record<string, string> = apiKey\n\t\t\t? { authorization: `Bearer ${apiKey}` }\n\t\t\t: {};\n\t\tlet lastErr: unknown;\n\t\tfor (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {\n\t\t\tlet res: Response;\n\t\t\ttry {\n\t\t\t\tres = await fetch(url, { headers });\n\t\t\t} catch (err) {\n\t\t\t\t// An explicit abort/cancel is intentional — surface it immediately\n\t\t\t\t// rather than burning the retry budget masking it as transient.\n\t\t\t\tif (err instanceof Error && err.name === \"AbortError\") throw err;\n\t\t\t\t// Otherwise a transport-level failure (connection refused/reset) —\n\t\t\t\t// e.g. an api replica mid-recreate. Retry; the next attempt\n\t\t\t\t// round-robins to a healthy replica.\n\t\t\t\tlastErr = err;\n\t\t\t\tif (attempt >= MAX_ATTEMPTS) break;\n\t\t\t\tawait delay(RETRY_BASE_MS * 2 ** (attempt - 1));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!res.ok) {\n\t\t\t\tif (RETRYABLE_STATUS.has(res.status) && attempt < MAX_ATTEMPTS) {\n\t\t\t\t\t// Drain the body so the connection can be reused, then back off.\n\t\t\t\t\tawait res.text().catch(() => {});\n\t\t\t\t\tawait delay(RETRY_BASE_MS * 2 ** (attempt - 1));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthrow new IndexHttpStatusError(\n\t\t\t\t\tres.status,\n\t\t\t\t\t`GET ${url} → ${res.status} ${await res.text()}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn (await res.json()) as T;\n\t\t}\n\t\tthrow (\n\t\t\tlastErr ?? new Error(`GET ${url} failed after ${MAX_ATTEMPTS} attempts`)\n\t\t);\n\t}\n\n\t/** Fetch a single cursor page of an Index collection. */\n\tprivate async getPage<K extends string, T>(\n\t\tpath: string,\n\t\tkey: K,\n\t\tparams: URLSearchParams,\n\t): Promise<{ items: T[]; next_cursor: string | null }> {\n\t\tconst env: Envelope<K, T> = await this.get(\n\t\t\t`${this.indexBaseUrl}${path}?${params}`,\n\t\t\tthis.indexApiKey,\n\t\t);\n\t\treturn { items: env[key], next_cursor: env.next_cursor };\n\t}\n\n\t/** Drain a cursor-paginated Index collection over [fromHeight, toHeight]. */\n\tprivate async walk<K extends string, T>(\n\t\tpath: string,\n\t\tkey: K,\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\textraParams: Record<string, string> = {},\n\t): Promise<T[]> {\n\t\tconst out: T[] = [];\n\t\tlet cursor: string | null = null;\n\t\tdo {\n\t\t\tconst params = new URLSearchParams({\n\t\t\t\tto_height: String(toHeight),\n\t\t\t\tlimit: String(PAGE_LIMIT),\n\t\t\t\t...extraParams,\n\t\t\t});\n\t\t\t// from_height and cursor are mutually exclusive — anchor the first page\n\t\t\t// by height, then page forward by cursor only.\n\t\t\tif (cursor) params.set(\"cursor\", cursor);\n\t\t\telse params.set(\"from_height\", String(fromHeight));\n\t\t\tconst { items, next_cursor } = await this.getPage<K, T>(\n\t\t\t\tpath,\n\t\t\t\tkey,\n\t\t\t\tparams,\n\t\t\t);\n\t\t\tout.push(...items);\n\t\t\tcursor = next_cursor;\n\t\t} while (cursor);\n\t\treturn out;\n\t}\n\n\t/**\n\t * Fetch ONE page of contract-call transactions filtered to `contractId`.\n\t * Unlike walk(), this does NOT drain — the caller pages by feeding back\n\t * next_cursor — so a sparse high-volume filter (e.g. a single contract over\n\t * all history) costs one request per batch, not O(all-history) per tick.\n\t * `cursor` is exclusive (rows strictly after it); on the first call pass\n\t * `fromHeight` to anchor the backfill start instead.\n\t */\n\tasync fetchContractCalls(\n\t\tcontractId: string,\n\t\topts: {\n\t\t\ttoHeight: number;\n\t\t\tcursor?: string | null;\n\t\t\tfromHeight?: number;\n\t\t\tlimit?: number;\n\t\t},\n\t): Promise<{\n\t\ttransactions: IndexTransactionRow[];\n\t\tnext_cursor: string | null;\n\t}> {\n\t\tconst params = new URLSearchParams({\n\t\t\tto_height: String(opts.toHeight),\n\t\t\tlimit: String(opts.limit ?? PAGE_LIMIT),\n\t\t\tcontract_id: contractId,\n\t\t});\n\t\tif (opts.cursor) params.set(\"cursor\", opts.cursor);\n\t\telse params.set(\"from_height\", String(opts.fromHeight ?? 0));\n\t\tconst { items, next_cursor } = await this.getPage<\n\t\t\t\"transactions\",\n\t\t\tIndexTransactionRow\n\t\t>(\"/v1/index/transactions\", \"transactions\", params);\n\t\treturn { transactions: items, next_cursor };\n\t}\n\n\twalkBlocks(fromHeight: number, toHeight: number): Promise<IndexBlockRow[]> {\n\t\treturn this.walk<\"blocks\", IndexBlockRow>(\n\t\t\t\"/v1/index/blocks\",\n\t\t\t\"blocks\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t);\n\t}\n\n\t/** Lowest block height in [fromHeight, toHeight] with a matching event, or\n\t * null. One page, limit 1 — built for sparse-scan probes. */\n\tasync firstEventHeight(\n\t\teventType: string,\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\tcontractId?: string,\n\t): Promise<number | null> {\n\t\tconst params = new URLSearchParams({\n\t\t\tevent_type: eventType,\n\t\t\tfrom_height: String(fromHeight),\n\t\t\tto_height: String(toHeight),\n\t\t\tlimit: \"1\",\n\t\t\t...(contractId ? { contract_id: contractId } : {}),\n\t\t});\n\t\tconst { items } = await this.getPage<\"events\", IndexEventRow>(\n\t\t\t\"/v1/index/events\",\n\t\t\t\"events\",\n\t\t\tparams,\n\t\t);\n\t\treturn items[0]?.block_height ?? null;\n\t}\n\n\twalkEvents(\n\t\teventType: string,\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\t/** Join the submitting tx so each row carries `tx_*` — lets an event-only\n\t\t * subgraph skip walkTransactions and build `ctx.tx` from the event. */\n\t\twithTx = false,\n\t): Promise<IndexEventRow[]> {\n\t\treturn this.walk<\"events\", IndexEventRow>(\n\t\t\t\"/v1/index/events\",\n\t\t\t\"events\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t\t{\n\t\t\t\tevent_type: eventType,\n\t\t\t\t...(withTx ? { tx_context: \"true\" } : {}),\n\t\t\t},\n\t\t);\n\t}\n\n\twalkTransactions(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<IndexTransactionRow[]> {\n\t\treturn this.walk<\"transactions\", IndexTransactionRow>(\n\t\t\t\"/v1/index/transactions\",\n\t\t\t\"transactions\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t);\n\t}\n\n\t/** Canonical tip height from the Streams clock. */\n\tasync getStreamsTip(): Promise<number> {\n\t\tconst tip = await this.get<{ block_height: number }>(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/tip`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t\treturn Number(tip.block_height) || 0;\n\t}\n\n\t/**\n\t * Highest block height the Index data plane can serve (tip is inline in every\n\t * envelope). This is the data-availability bound — a consumer must not\n\t * process past it, even if the Streams clock is ahead.\n\t *\n\t * `opts.wait` (seconds, clamped to `MAX_INDEX_WAIT_SECONDS`) long-polls:\n\t * the server holds the request until a fresher tip than `opts.knownHeight`\n\t * is available or `wait` elapses. Pass `knownHeight` —\n\t * the last tip THIS caller observed — or `wait` is a no-op (nothing to\n\t * compare against). A caller that only wants the plain tip omits both.\n\t */\n\tasync getIndexTip(opts?: {\n\t\twait?: number;\n\t\tknownHeight?: number;\n\t\t/**\n\t\t * Event types this caller actually reads (e.g. a chain evaluator's\n\t\t * `referencedEventTypes`). Narrows the returned tip — and, together with\n\t\t * `wait`, what counts as \"nothing new\" — to the MIN committed height\n\t\t * over just these types, instead of the global floor over EVERY classic\n\t\t * decoder. Without it, an unrelated decoder committing (any of ~15,\n\t\t * several times a block) moves the global floor and makes an unrelated\n\t\t * `wait` return early — the exact busy-idle pattern this fixes. Omit\n\t\t * when there's no meaningful subset (falls back to the global floor,\n\t\t * unchanged from before this option existed).\n\t\t */\n\t\teventTypes?: readonly string[];\n\t}): Promise<number> {\n\t\t// `tip_only`: this method never reads `blocks[]`, only `tip`, so the\n\t\t// server can skip the row query. It ALSO fixes what `tip_only` exists\n\t\t// for: `blocks.length` is governed by the SOURCE tip (`/blocks` windows\n\t\t// to it), but `knownHeight` here is the DECODED tip this method itself\n\t\t// returns — comparing against raw rows made an idle `wait` return\n\t\t// almost instantly whenever ingest ran even slightly ahead of decode\n\t\t// (routes/index.ts's /blocks handler judges emptiness against\n\t\t// `tip.block_height` directly when `tip_only` is set, sidestepping the\n\t\t// mismatch). Do NOT set this on `getIndexSourceTip` below — its\n\t\t// `knownHeight` baseline is the source tip already, so the row-based\n\t\t// check is the CORRECT one there, not a bug to route around.\n\t\tconst env = await this.getIndexTipEnvelope({\n\t\t\t...opts,\n\t\t\ttipOnly: true,\n\t\t\teventTypes: opts?.eventTypes,\n\t\t});\n\t\treturn Number(env.tip?.block_height) || 0;\n\t}\n\n\t/** Ingest tip. VM rows land with the block; decoded `block_height` can lag.\n\t * Same `wait`/`knownHeight` long-poll contract as {@link getIndexTip}. */\n\tasync getIndexSourceTip(opts?: {\n\t\twait?: number;\n\t\tknownHeight?: number;\n\t}): Promise<number> {\n\t\tconst env = await this.getIndexTipEnvelope(opts);\n\t\treturn Number(env.tip?.source_block_height ?? env.tip?.block_height) || 0;\n\t}\n\n\t/**\n\t * Per-decoder committed heights from the last tip envelope fetched by\n\t * `getIndexTip()`/`getIndexSourceTip()` — reads the cached response, no\n\t * extra request. `undefined` before either has been called, or against an\n\t * older server that doesn't send the field. A caller (the chain evaluator)\n\t * uses this to bound itself by the decoders it actually reads instead of\n\t * the conservative cross-decoder floor `block_height` itself carries.\n\t */\n\tgetDecodedHeights(): Record<string, number | null> | undefined {\n\t\treturn this.lastTipEnvelope?.tip.decoded_heights;\n\t}\n\n\t/** False once a `wait`/`tip_only` request has 400'd on THIS client instance\n\t * (see the catch in `getIndexTipEnvelope`) — an older server that doesn't\n\t * recognize these params. A caller that reuses one client across many\n\t * calls (the chain evaluator) uses this to stop scheduling\n\t * itself as if `wait` actually blocked, instead of re-discovering the 400\n\t * on every single call. */\n\twaitIsSupported(): boolean {\n\t\treturn this.waitSupported;\n\t}\n\n\tprivate async getIndexTipEnvelope(opts?: {\n\t\twait?: number;\n\t\tknownHeight?: number;\n\t\ttipOnly?: boolean;\n\t\teventTypes?: readonly string[];\n\t}): Promise<IndexTipEnvelope> {\n\t\tconst wantsWait = this.waitSupported && (opts?.wait ?? 0) > 0;\n\t\tconst wantsTipOnly = this.waitSupported && Boolean(opts?.tipOnly);\n\t\tconst wantsEventTypes =\n\t\t\tthis.waitSupported && wantsTipOnly && Boolean(opts?.eventTypes?.length);\n\t\tconst params = new URLSearchParams({ limit: \"1\" });\n\t\tif (wantsTipOnly) params.set(\"tip_only\", \"true\");\n\t\t// Only meaningful alongside tip_only — it narrows what the returned\n\t\t// (and wait-compared) tip means, and tip_only is what makes the server\n\t\t// return a tip at all instead of a page of rows.\n\t\tif (wantsEventTypes && opts?.eventTypes) {\n\t\t\tparams.set(\"event_types\", opts.eventTypes.join(\",\"));\n\t\t}\n\t\tif (wantsWait) {\n\t\t\tparams.set(\n\t\t\t\t\"wait\",\n\t\t\t\tString(Math.min(MAX_INDEX_WAIT_SECONDS, Math.max(0, opts?.wait ?? 0))),\n\t\t\t);\n\t\t\t// `from_height` is what makes the wait meaningful here: with no cursor,\n\t\t\t// `/v1/index/blocks?limit=1` always returns a row (the default window's\n\t\t\t// oldest block), so the server would never see \"nothing new\" to wait\n\t\t\t// on. Anchoring one past the last height THIS caller saw makes the page\n\t\t\t// empty until a fresher block lands — the same signal the endpoint\n\t\t\t// already uses for a normal forward walk.\n\t\t\tif (opts?.knownHeight !== undefined) {\n\t\t\t\tparams.set(\"from_height\", String(opts.knownHeight + 1));\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tconst env = await this.get<IndexTipEnvelope>(\n\t\t\t\t`${this.indexBaseUrl}/v1/index/blocks?${params}`,\n\t\t\t\tthis.indexApiKey,\n\t\t\t);\n\t\t\tthis.lastTipEnvelope = env;\n\t\t\treturn env;\n\t\t} catch (err) {\n\t\t\t// An older server's `validateQueryParams` 400s on `wait`/`from_height`/\n\t\t\t// `tip_only`/`event_types` it doesn't recognize. Treat that ONE status\n\t\t\t// as \"this server predates long-poll\", not an outage: disable every\n\t\t\t// extension for the rest of this client's life (event_types is only\n\t\t\t// ever sent alongside tip_only, so gating on `wantsTipOnly` already\n\t\t\t// covers a server that knows `wait`/`tip_only` but not `event_types`\n\t\t\t// yet) and retry plainly, so `FallbackBlockSource` never mistakes a\n\t\t\t// version-skew 400 for the api being down and routes to the DB tap.\n\t\t\t// Gating on `wantsWait || wantsTipOnly` (not `wantsWait` alone)\n\t\t\t// matters mid-rollout: a server already upgraded for `wait` but not\n\t\t\t// yet for `tip_only` still 400s on the one it doesn't know, even on a\n\t\t\t// plain, non-waiting `getIndexTip()` call.\n\t\t\tif (\n\t\t\t\t(wantsWait || wantsTipOnly) &&\n\t\t\t\terr instanceof IndexHttpStatusError &&\n\t\t\t\terr.status === 400\n\t\t\t) {\n\t\t\t\tthis.waitSupported = false;\n\t\t\t\treturn this.getIndexTipEnvelope(opts);\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\t/** Reorgs since a resume token (wall-clock `detected_at`-keyed). `chain`\n\t * defaults to `\"stacks\"` (unchanged); `\"bitcoin\"` reads Runes reorgs\n\t * (`btc_reorgs`, plan 060) instead — a separate feed, own resume tokens. */\n\tasync listReorgs(\n\t\tsince: string,\n\t\tchain: \"stacks\" | \"bitcoin\" = \"stacks\",\n\t): Promise<{ reorgs: StreamsReorgRow[]; next_since: string | null }> {\n\t\tconst params = new URLSearchParams({ since });\n\t\tif (chain === \"bitcoin\") params.set(\"chain\", \"bitcoin\");\n\t\treturn this.get(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/reorgs?${params}`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t}\n\n\t/** Bitcoin (Runes) Streams tip height — `chain=bitcoin`'s own clock,\n\t * unrelated to the Stacks tip (plan 060). */\n\tasync getBitcoinStreamsTip(): Promise<number> {\n\t\tconst tip = await this.get<{ block_height: number }>(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/tip?chain=bitcoin`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t\treturn Number(tip.block_height) || 0;\n\t}\n\n\t/**\n\t * One page of `chain=bitcoin` Streams events (Runes activity, plan 060's\n\t * evaluator source). Unlike `walkEvents`, this does NOT drain — the caller\n\t * pages by feeding back `next_cursor` — so a tick bounds its own work\n\t * instead of draining an unbounded backlog in one call. `afterCursor`\n\t * (exclusive) takes precedence over `fromHeight` when both are given,\n\t * mirroring the REST endpoint's own `cursor`/`from_height` exclusivity.\n\t */\n\tasync getBitcoinStreamsEventsPage(opts: {\n\t\ttypes: readonly string[];\n\t\ttoHeight: number;\n\t\tafterCursor?: string;\n\t\tfromHeight?: number;\n\t\tlimit?: number;\n\t}): Promise<{ events: RuneStreamsEvent[]; next_cursor: string | null }> {\n\t\tconst params = new URLSearchParams({\n\t\t\tchain: \"bitcoin\",\n\t\t\tto_height: String(opts.toHeight),\n\t\t\tlimit: String(opts.limit ?? PAGE_LIMIT),\n\t\t\ttypes: opts.types.join(\",\"),\n\t\t});\n\t\tif (opts.afterCursor) params.set(\"from_cursor\", opts.afterCursor);\n\t\telse params.set(\"from_height\", String(opts.fromHeight ?? 0));\n\t\treturn this.get(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/events?${params}`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t}\n}\n\n/** Decoder + subgraph processor client. One env contract; omits bearer when no key. */\nexport function createInternalIndexHttpClient(): IndexHttpClient {\n\tconst baseUrl = defaultInternalIndexBaseUrl();\n\treturn new IndexHttpClient({\n\t\tindexBaseUrl: baseUrl,\n\t\tstreamsBaseUrl: baseUrl,\n\t\tindexApiKey: defaultInternalIndexApiKey(),\n\t\tstreamsApiKey: defaultInternalStreamsApiKey(),\n\t});\n}\n"
6
+ "import {\n\tdefaultInternalIndexApiKey,\n\tdefaultInternalIndexBaseUrl,\n\tdefaultInternalStreamsApiKey,\n} from \"./index-internal-auth.ts\";\nimport type { RuneStreamsEvent } from \"./streams-rows/events.ts\";\n\n/**\n * Low-level transport for the public Index (`/v1/index`) + Streams clock\n * (`/v1/streams`) HTTP APIs: cursor-paginated reads, tip, reorgs. Lives in\n * `shared` (a leaf both the SDK and the subgraph runtime depend on) so the wire\n * format has one home and no package cycle. The SDK's ergonomic client should\n * eventually consume these row types too (see the plan's convergence task).\n *\n * This is intentionally minimal — just the GETs the subgraph runtime's\n * PublicApiBlockSource needs. It is NOT the SDK's full client (walk/consume/\n * retries/auth resolution).\n */\n\nconst PAGE_LIMIT = 1000;\n\n/** Ceiling on the Index long-poll `wait` param (seconds), shared by client and\n * server so neither drifts from the other. Kept comfortably under app-server\n * Caddy's `reverse_proxy` (no read/write timeout override, so this is a\n * self-imposed ceiling, not one it's protecting against) and Bun's own\n * 90s idleTimeout on the api listener. */\nexport const MAX_INDEX_WAIT_SECONDS = 25;\n\n// Transport resilience for the streams-index data plane. The api runs N>1\n// replicas behind Caddy; during a rolling deploy one replica is briefly\n// unreachable, surfacing as a thrown fetch (connection refused/reset) or a\n// Caddy 502/503/504 while it fails over. Retrying a few times with backoff\n// makes a single-replica recreate transparent to the subgraph-processor /\n// decoder — closing the processors-depend-on-api coupling.\nconst MAX_ATTEMPTS = 4;\nconst RETRY_BASE_MS = 150;\nconst RETRYABLE_STATUS = new Set([502, 503, 504]);\n\nconst delay = (ms: number): Promise<void> =>\n\tnew Promise((resolve) => setTimeout(resolve, ms));\n\n/** A non-2xx Index/Streams response, carrying the status so a caller can\n * distinguish \"the server rejected this request\" (e.g. a `wait`/`from_height`\n * param an older server's `validateQueryParams` doesn't recognize, HTTP 400)\n * from a transient outage — see `getIndexTipEnvelope`'s wait fallback. */\nexport class IndexHttpStatusError extends Error {\n\tconstructor(\n\t\treadonly status: number,\n\t\tmessage: string,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"IndexHttpStatusError\";\n\t}\n}\n\ntype Envelope<K extends string, T> = {\n\t[P in K]: T[];\n} & { next_cursor: string | null };\n\n// ── Index API wire shapes (single source of truth) ─────────────────────────\nexport type IndexBlockRow = {\n\tblock_height: number;\n\tblock_hash: string;\n\tparent_hash: string;\n\tburn_block_height: number;\n\tburn_block_hash: string | null;\n\t/** Nakamoto StacksBlockId. Absent from pre-2026-07 API deployments. */\n\tindex_block_hash?: string | null;\n\tblock_time: string | null;\n};\n\ntype IndexEventCommon = {\n\tblock_height: number;\n\ttx_id: string;\n\ttx_index?: number;\n\tevent_index: number;\n\tcontract_id: string | null;\n\t/** Submitting-tx context — present only when the read passed `tx_context=true`.\n\t * Lets a consumer build the tx for `ctx.tx` without a separate\n\t * walkTransactions (the ~37x reindex over-fetch; see indexing-speed plan). */\n\ttx_sender?: string | null;\n\ttx_type?: string | null;\n\ttx_status?: string | null;\n\ttx_contract_id?: string | null;\n\ttx_function_name?: string | null;\n};\n\nexport type IndexEventRow = IndexEventCommon &\n\t(\n\t\t| {\n\t\t\t\tevent_type: \"ft_transfer\" | \"ft_mint\" | \"ft_burn\";\n\t\t\t\tasset_identifier: string;\n\t\t\t\tsender?: string;\n\t\t\t\trecipient?: string;\n\t\t\t\tamount: string;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"nft_transfer\" | \"nft_mint\" | \"nft_burn\";\n\t\t\t\tasset_identifier: string;\n\t\t\t\tsender?: string;\n\t\t\t\trecipient?: string;\n\t\t\t\tvalue: string;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"stx_transfer\" | \"stx_mint\" | \"stx_burn\";\n\t\t\t\tsender?: string;\n\t\t\t\trecipient?: string;\n\t\t\t\tamount: string;\n\t\t\t\tmemo?: string | null;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"stx_lock\";\n\t\t\t\tsender: string;\n\t\t\t\tamount: string;\n\t\t\t\tpayload: { unlock_height: string | null };\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"print\";\n\t\t\t\tpayload: {\n\t\t\t\t\ttopic: string | null;\n\t\t\t\t\tvalue: unknown;\n\t\t\t\t\traw_value: string | null;\n\t\t\t\t};\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"nested_contract_call\";\n\t\t\t\tsender?: string | null;\n\t\t\t\tcaller: string;\n\t\t\t\tfunction_name: string;\n\t\t\t\tfunction_args?: unknown;\n\t\t\t\traw_result?: string | null;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"var_set\";\n\t\t\t\tvar_name: string;\n\t\t\t\traw_value?: string | null;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"map_set\" | \"map_insert\";\n\t\t\t\tmap: string;\n\t\t\t\traw_key?: string | null;\n\t\t\t\traw_value?: string | null;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"map_delete\";\n\t\t\t\tmap: string;\n\t\t\t\traw_key?: string | null;\n\t\t }\n\t);\n\nexport type IndexTransactionRow = {\n\ttx_id: string;\n\tblock_height: number;\n\tblock_time?: string | null;\n\tburn_block_height?: number | null;\n\ttx_index: number;\n\ttx_type: string;\n\tsender: string;\n\tstatus: string;\n\tcontract_call?: {\n\t\tcontract_id: string;\n\t\tfunction_name: string;\n\t\tfunction_args_hex?: string[] | null;\n\t\tresult_hex?: string | null;\n\t} | null;\n\tsmart_contract?: { contract_id: string | null } | null;\n};\n\nexport type StreamsReorgRow = {\n\tid: string;\n\tdetected_at: string;\n\tfork_point_height: number;\n\torphaned_range: { from: string; to: string };\n\tnew_canonical_tip: string;\n};\n\nexport type IndexHttpOptions = {\n\t/** Base URL for /v1/index (the decoded data plane). */\n\tindexBaseUrl: string;\n\t/** Bearer for /v1/index. Empty/unset omits the header. */\n\tindexApiKey?: string;\n\t/** Base URL for /v1/streams (the canonical clock). */\n\tstreamsBaseUrl: string;\n\t/** Bearer for /v1/streams. Empty/unset omits the header. */\n\tstreamsApiKey?: string;\n};\n\n/** `/v1/index/blocks?limit=1`'s envelope — read for its `tip`, not its rows. */\nexport type IndexTipEnvelope = {\n\ttip: {\n\t\tblock_height: number;\n\t\tsource_block_height?: number;\n\t\t/**\n\t\t * Committed height per classic decoded event_type, e.g.\n\t\t * `{ ft_transfer: 950, stx_transfer: 940 }`. `null` means that decoder\n\t\t * has no checkpoint yet (fail-closed for a caller that references it,\n\t\t * not \"committed to height 0\"); a missing key means an older server\n\t\t * that doesn't send this field at all. Absent on an instance built\n\t\t * before this field was added.\n\t\t */\n\t\tdecoded_heights?: Record<string, number | null>;\n\t};\n};\n\nexport class IndexHttpClient {\n\tprivate readonly indexBaseUrl: string;\n\tprivate readonly indexApiKey: string | undefined;\n\tprivate readonly streamsBaseUrl: string;\n\tprivate readonly streamsApiKey: string | undefined;\n\t/** Populated by the last `getIndexTipEnvelope()` call (via `getIndexTip`/\n\t * `getIndexSourceTip`) so `getDecodedHeights()` can read the SAME response\n\t * synchronously instead of making a second request. */\n\tprivate lastTipEnvelope: IndexTipEnvelope | undefined;\n\t/** Flips false the first time a `wait` request 400s — see\n\t * `getIndexTipEnvelope`'s catch. Per-instance, not global: a fresh client\n\t * (e.g. against a different/upgraded server) always tries wait again. */\n\tprivate waitSupported = true;\n\n\tconstructor(opts: IndexHttpOptions) {\n\t\tthis.indexBaseUrl = opts.indexBaseUrl.replace(/\\/+$/, \"\");\n\t\tthis.indexApiKey = opts.indexApiKey ?? defaultInternalIndexApiKey();\n\t\tthis.streamsBaseUrl = opts.streamsBaseUrl.replace(/\\/+$/, \"\");\n\t\tthis.streamsApiKey = opts.streamsApiKey;\n\t}\n\n\tprivate async get<T>(url: string, apiKey: string | undefined): Promise<T> {\n\t\t// Index reads are anon — omit the header entirely when no key is set, so\n\t\t// an empty key reads anonymously rather than 401-ing as an invalid bearer.\n\t\tconst headers: Record<string, string> = apiKey\n\t\t\t? { authorization: `Bearer ${apiKey}` }\n\t\t\t: {};\n\t\tlet lastErr: unknown;\n\t\tfor (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {\n\t\t\tlet res: Response;\n\t\t\ttry {\n\t\t\t\tres = await fetch(url, { headers });\n\t\t\t} catch (err) {\n\t\t\t\t// An explicit abort/cancel is intentional — surface it immediately\n\t\t\t\t// rather than burning the retry budget masking it as transient.\n\t\t\t\tif (err instanceof Error && err.name === \"AbortError\") throw err;\n\t\t\t\t// Otherwise a transport-level failure (connection refused/reset) —\n\t\t\t\t// e.g. an api replica mid-recreate. Retry; the next attempt\n\t\t\t\t// round-robins to a healthy replica.\n\t\t\t\tlastErr = err;\n\t\t\t\tif (attempt >= MAX_ATTEMPTS) break;\n\t\t\t\tawait delay(RETRY_BASE_MS * 2 ** (attempt - 1));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!res.ok) {\n\t\t\t\tif (RETRYABLE_STATUS.has(res.status) && attempt < MAX_ATTEMPTS) {\n\t\t\t\t\t// Drain the body so the connection can be reused, then back off.\n\t\t\t\t\tawait res.text().catch(() => {});\n\t\t\t\t\tawait delay(RETRY_BASE_MS * 2 ** (attempt - 1));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthrow new IndexHttpStatusError(\n\t\t\t\t\tres.status,\n\t\t\t\t\t`GET ${url} → ${res.status} ${await res.text()}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn (await res.json()) as T;\n\t\t}\n\t\tthrow (\n\t\t\tlastErr ?? new Error(`GET ${url} failed after ${MAX_ATTEMPTS} attempts`)\n\t\t);\n\t}\n\n\t/** Fetch a single cursor page of an Index collection. */\n\tprivate async getPage<K extends string, T>(\n\t\tpath: string,\n\t\tkey: K,\n\t\tparams: URLSearchParams,\n\t): Promise<{ items: T[]; next_cursor: string | null }> {\n\t\tconst env: Envelope<K, T> = await this.get(\n\t\t\t`${this.indexBaseUrl}${path}?${params}`,\n\t\t\tthis.indexApiKey,\n\t\t);\n\t\treturn { items: env[key], next_cursor: env.next_cursor };\n\t}\n\n\t/** Drain a cursor-paginated Index collection over [fromHeight, toHeight]. */\n\tprivate async walk<K extends string, T>(\n\t\tpath: string,\n\t\tkey: K,\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\textraParams: Record<string, string> = {},\n\t): Promise<T[]> {\n\t\tconst out: T[] = [];\n\t\tlet cursor: string | null = null;\n\t\tdo {\n\t\t\tconst params = new URLSearchParams({\n\t\t\t\tto_height: String(toHeight),\n\t\t\t\tlimit: String(PAGE_LIMIT),\n\t\t\t\t...extraParams,\n\t\t\t});\n\t\t\t// from_height and cursor are mutually exclusive — anchor the first page\n\t\t\t// by height, then page forward by cursor only.\n\t\t\tif (cursor) params.set(\"cursor\", cursor);\n\t\t\telse params.set(\"from_height\", String(fromHeight));\n\t\t\tconst { items, next_cursor } = await this.getPage<K, T>(\n\t\t\t\tpath,\n\t\t\t\tkey,\n\t\t\t\tparams,\n\t\t\t);\n\t\t\tout.push(...items);\n\t\t\tcursor = next_cursor;\n\t\t} while (cursor);\n\t\treturn out;\n\t}\n\n\t/**\n\t * Fetch ONE page of contract-call transactions filtered to `contractId`.\n\t * Unlike walk(), this does NOT drain — the caller pages by feeding back\n\t * next_cursor — so a sparse high-volume filter (e.g. a single contract over\n\t * all history) costs one request per batch, not O(all-history) per tick.\n\t * `cursor` is exclusive (rows strictly after it); on the first call pass\n\t * `fromHeight` to anchor the backfill start instead.\n\t */\n\tasync fetchContractCalls(\n\t\tcontractId: string,\n\t\topts: {\n\t\t\ttoHeight: number;\n\t\t\tcursor?: string | null;\n\t\t\tfromHeight?: number;\n\t\t\tlimit?: number;\n\t\t},\n\t): Promise<{\n\t\ttransactions: IndexTransactionRow[];\n\t\tnext_cursor: string | null;\n\t}> {\n\t\tconst params = new URLSearchParams({\n\t\t\tto_height: String(opts.toHeight),\n\t\t\tlimit: String(opts.limit ?? PAGE_LIMIT),\n\t\t\tcontract_id: contractId,\n\t\t});\n\t\tif (opts.cursor) params.set(\"cursor\", opts.cursor);\n\t\telse params.set(\"from_height\", String(opts.fromHeight ?? 0));\n\t\tconst { items, next_cursor } = await this.getPage<\n\t\t\t\"transactions\",\n\t\t\tIndexTransactionRow\n\t\t>(\"/v1/index/transactions\", \"transactions\", params);\n\t\treturn { transactions: items, next_cursor };\n\t}\n\n\twalkBlocks(fromHeight: number, toHeight: number): Promise<IndexBlockRow[]> {\n\t\treturn this.walk<\"blocks\", IndexBlockRow>(\n\t\t\t\"/v1/index/blocks\",\n\t\t\t\"blocks\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t);\n\t}\n\n\t/** Lowest block height in [fromHeight, toHeight] with a matching event, or\n\t * null. One page, limit 1 — built for sparse-scan probes. */\n\tasync firstEventHeight(\n\t\teventType: string,\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\tcontractId?: string,\n\t): Promise<number | null> {\n\t\tconst params = new URLSearchParams({\n\t\t\tevent_type: eventType,\n\t\t\tfrom_height: String(fromHeight),\n\t\t\tto_height: String(toHeight),\n\t\t\tlimit: \"1\",\n\t\t\t...(contractId ? { contract_id: contractId } : {}),\n\t\t});\n\t\tconst { items } = await this.getPage<\"events\", IndexEventRow>(\n\t\t\t\"/v1/index/events\",\n\t\t\t\"events\",\n\t\t\tparams,\n\t\t);\n\t\treturn items[0]?.block_height ?? null;\n\t}\n\n\twalkEvents(\n\t\teventType: string,\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\t/** Join the submitting tx so each row carries `tx_*` — lets an event-only\n\t\t * subgraph skip walkTransactions and build `ctx.tx` from the event. */\n\t\twithTx = false,\n\t\t/** Scope the walk to one contract (what a filter pins), so the Index\n\t\t * returns, and meters, only that contract's rows. */\n\t\tcontractId?: string,\n\t): Promise<IndexEventRow[]> {\n\t\treturn this.walk<\"events\", IndexEventRow>(\n\t\t\t\"/v1/index/events\",\n\t\t\t\"events\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t\t{\n\t\t\t\tevent_type: eventType,\n\t\t\t\t...(withTx ? { tx_context: \"true\" } : {}),\n\t\t\t\t...(contractId ? { contract_id: contractId } : {}),\n\t\t\t},\n\t\t);\n\t}\n\n\twalkTransactions(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<IndexTransactionRow[]> {\n\t\treturn this.walk<\"transactions\", IndexTransactionRow>(\n\t\t\t\"/v1/index/transactions\",\n\t\t\t\"transactions\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t);\n\t}\n\n\t/** Canonical tip height from the Streams clock. */\n\tasync getStreamsTip(): Promise<number> {\n\t\tconst tip = await this.get<{ block_height: number }>(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/tip`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t\treturn Number(tip.block_height) || 0;\n\t}\n\n\t/**\n\t * Highest block height the Index data plane can serve (tip is inline in every\n\t * envelope). This is the data-availability bound — a consumer must not\n\t * process past it, even if the Streams clock is ahead.\n\t *\n\t * `opts.wait` (seconds, clamped to `MAX_INDEX_WAIT_SECONDS`) long-polls:\n\t * the server holds the request until a fresher tip than `opts.knownHeight`\n\t * is available or `wait` elapses. Pass `knownHeight` —\n\t * the last tip THIS caller observed — or `wait` is a no-op (nothing to\n\t * compare against). A caller that only wants the plain tip omits both.\n\t */\n\tasync getIndexTip(opts?: {\n\t\twait?: number;\n\t\tknownHeight?: number;\n\t\t/**\n\t\t * Event types this caller actually reads (e.g. a chain evaluator's\n\t\t * `referencedEventTypes`). Narrows the returned tip — and, together with\n\t\t * `wait`, what counts as \"nothing new\" — to the MIN committed height\n\t\t * over just these types, instead of the global floor over EVERY classic\n\t\t * decoder. Without it, an unrelated decoder committing (any of ~15,\n\t\t * several times a block) moves the global floor and makes an unrelated\n\t\t * `wait` return early — the exact busy-idle pattern this fixes. Omit\n\t\t * when there's no meaningful subset (falls back to the global floor,\n\t\t * unchanged from before this option existed).\n\t\t */\n\t\teventTypes?: readonly string[];\n\t}): Promise<number> {\n\t\t// `tip_only`: this method never reads `blocks[]`, only `tip`, so the\n\t\t// server can skip the row query. It ALSO fixes what `tip_only` exists\n\t\t// for: `blocks.length` is governed by the SOURCE tip (`/blocks` windows\n\t\t// to it), but `knownHeight` here is the DECODED tip this method itself\n\t\t// returns — comparing against raw rows made an idle `wait` return\n\t\t// almost instantly whenever ingest ran even slightly ahead of decode\n\t\t// (routes/index.ts's /blocks handler judges emptiness against\n\t\t// `tip.block_height` directly when `tip_only` is set, sidestepping the\n\t\t// mismatch). Do NOT set this on `getIndexSourceTip` below — its\n\t\t// `knownHeight` baseline is the source tip already, so the row-based\n\t\t// check is the CORRECT one there, not a bug to route around.\n\t\tconst env = await this.getIndexTipEnvelope({\n\t\t\t...opts,\n\t\t\ttipOnly: true,\n\t\t\teventTypes: opts?.eventTypes,\n\t\t});\n\t\treturn Number(env.tip?.block_height) || 0;\n\t}\n\n\t/** Ingest tip. VM rows land with the block; decoded `block_height` can lag.\n\t * Same `wait`/`knownHeight` long-poll contract as {@link getIndexTip}. */\n\tasync getIndexSourceTip(opts?: {\n\t\twait?: number;\n\t\tknownHeight?: number;\n\t}): Promise<number> {\n\t\tconst env = await this.getIndexTipEnvelope(opts);\n\t\treturn Number(env.tip?.source_block_height ?? env.tip?.block_height) || 0;\n\t}\n\n\t/**\n\t * Per-decoder committed heights from the last tip envelope fetched by\n\t * `getIndexTip()`/`getIndexSourceTip()` — reads the cached response, no\n\t * extra request. `undefined` before either has been called, or against an\n\t * older server that doesn't send the field. A caller (the chain evaluator)\n\t * uses this to bound itself by the decoders it actually reads instead of\n\t * the conservative cross-decoder floor `block_height` itself carries.\n\t */\n\tgetDecodedHeights(): Record<string, number | null> | undefined {\n\t\treturn this.lastTipEnvelope?.tip.decoded_heights;\n\t}\n\n\t/** False once a `wait`/`tip_only` request has 400'd on THIS client instance\n\t * (see the catch in `getIndexTipEnvelope`) — an older server that doesn't\n\t * recognize these params. A caller that reuses one client across many\n\t * calls (the chain evaluator) uses this to stop scheduling\n\t * itself as if `wait` actually blocked, instead of re-discovering the 400\n\t * on every single call. */\n\twaitIsSupported(): boolean {\n\t\treturn this.waitSupported;\n\t}\n\n\tprivate async getIndexTipEnvelope(opts?: {\n\t\twait?: number;\n\t\tknownHeight?: number;\n\t\ttipOnly?: boolean;\n\t\teventTypes?: readonly string[];\n\t}): Promise<IndexTipEnvelope> {\n\t\tconst wantsWait = this.waitSupported && (opts?.wait ?? 0) > 0;\n\t\tconst wantsTipOnly = this.waitSupported && Boolean(opts?.tipOnly);\n\t\tconst wantsEventTypes =\n\t\t\tthis.waitSupported && wantsTipOnly && Boolean(opts?.eventTypes?.length);\n\t\tconst params = new URLSearchParams({ limit: \"1\" });\n\t\tif (wantsTipOnly) params.set(\"tip_only\", \"true\");\n\t\t// Only meaningful alongside tip_only — it narrows what the returned\n\t\t// (and wait-compared) tip means, and tip_only is what makes the server\n\t\t// return a tip at all instead of a page of rows.\n\t\tif (wantsEventTypes && opts?.eventTypes) {\n\t\t\tparams.set(\"event_types\", opts.eventTypes.join(\",\"));\n\t\t}\n\t\tif (wantsWait) {\n\t\t\tparams.set(\n\t\t\t\t\"wait\",\n\t\t\t\tString(Math.min(MAX_INDEX_WAIT_SECONDS, Math.max(0, opts?.wait ?? 0))),\n\t\t\t);\n\t\t\t// `from_height` is what makes the wait meaningful here: with no cursor,\n\t\t\t// `/v1/index/blocks?limit=1` always returns a row (the default window's\n\t\t\t// oldest block), so the server would never see \"nothing new\" to wait\n\t\t\t// on. Anchoring one past the last height THIS caller saw makes the page\n\t\t\t// empty until a fresher block lands — the same signal the endpoint\n\t\t\t// already uses for a normal forward walk.\n\t\t\tif (opts?.knownHeight !== undefined) {\n\t\t\t\tparams.set(\"from_height\", String(opts.knownHeight + 1));\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tconst env = await this.get<IndexTipEnvelope>(\n\t\t\t\t`${this.indexBaseUrl}/v1/index/blocks?${params}`,\n\t\t\t\tthis.indexApiKey,\n\t\t\t);\n\t\t\tthis.lastTipEnvelope = env;\n\t\t\treturn env;\n\t\t} catch (err) {\n\t\t\t// An older server's `validateQueryParams` 400s on `wait`/`from_height`/\n\t\t\t// `tip_only`/`event_types` it doesn't recognize. Treat that ONE status\n\t\t\t// as \"this server predates long-poll\", not an outage: disable every\n\t\t\t// extension for the rest of this client's life (event_types is only\n\t\t\t// ever sent alongside tip_only, so gating on `wantsTipOnly` already\n\t\t\t// covers a server that knows `wait`/`tip_only` but not `event_types`\n\t\t\t// yet) and retry plainly, so `FallbackBlockSource` never mistakes a\n\t\t\t// version-skew 400 for the api being down and routes to the DB tap.\n\t\t\t// Gating on `wantsWait || wantsTipOnly` (not `wantsWait` alone)\n\t\t\t// matters mid-rollout: a server already upgraded for `wait` but not\n\t\t\t// yet for `tip_only` still 400s on the one it doesn't know, even on a\n\t\t\t// plain, non-waiting `getIndexTip()` call.\n\t\t\tif (\n\t\t\t\t(wantsWait || wantsTipOnly) &&\n\t\t\t\terr instanceof IndexHttpStatusError &&\n\t\t\t\terr.status === 400\n\t\t\t) {\n\t\t\t\tthis.waitSupported = false;\n\t\t\t\treturn this.getIndexTipEnvelope(opts);\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\t/** Reorgs since a resume token (wall-clock `detected_at`-keyed). `chain`\n\t * defaults to `\"stacks\"` (unchanged); `\"bitcoin\"` reads Runes reorgs\n\t * (`btc_reorgs`, plan 060) instead — a separate feed, own resume tokens. */\n\tasync listReorgs(\n\t\tsince: string,\n\t\tchain: \"stacks\" | \"bitcoin\" = \"stacks\",\n\t): Promise<{ reorgs: StreamsReorgRow[]; next_since: string | null }> {\n\t\tconst params = new URLSearchParams({ since });\n\t\tif (chain === \"bitcoin\") params.set(\"chain\", \"bitcoin\");\n\t\treturn this.get(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/reorgs?${params}`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t}\n\n\t/** Bitcoin (Runes) Streams tip height — `chain=bitcoin`'s own clock,\n\t * unrelated to the Stacks tip (plan 060). */\n\tasync getBitcoinStreamsTip(): Promise<number> {\n\t\tconst tip = await this.get<{ block_height: number }>(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/tip?chain=bitcoin`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t\treturn Number(tip.block_height) || 0;\n\t}\n\n\t/**\n\t * One page of `chain=bitcoin` Streams events (Runes activity, plan 060's\n\t * evaluator source). Unlike `walkEvents`, this does NOT drain — the caller\n\t * pages by feeding back `next_cursor` — so a tick bounds its own work\n\t * instead of draining an unbounded backlog in one call. `afterCursor`\n\t * (exclusive) takes precedence over `fromHeight` when both are given,\n\t * mirroring the REST endpoint's own `cursor`/`from_height` exclusivity.\n\t */\n\tasync getBitcoinStreamsEventsPage(opts: {\n\t\ttypes: readonly string[];\n\t\ttoHeight: number;\n\t\tafterCursor?: string;\n\t\tfromHeight?: number;\n\t\tlimit?: number;\n\t}): Promise<{ events: RuneStreamsEvent[]; next_cursor: string | null }> {\n\t\tconst params = new URLSearchParams({\n\t\t\tchain: \"bitcoin\",\n\t\t\tto_height: String(opts.toHeight),\n\t\t\tlimit: String(opts.limit ?? PAGE_LIMIT),\n\t\t\ttypes: opts.types.join(\",\"),\n\t\t});\n\t\tif (opts.afterCursor) params.set(\"from_cursor\", opts.afterCursor);\n\t\telse params.set(\"from_height\", String(opts.fromHeight ?? 0));\n\t\treturn this.get(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/events?${params}`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t}\n}\n\n/** Decoder + subgraph processor client. One env contract; omits bearer when no key. */\nexport function createInternalIndexHttpClient(): IndexHttpClient {\n\tconst baseUrl = defaultInternalIndexBaseUrl();\n\treturn new IndexHttpClient({\n\t\tindexBaseUrl: baseUrl,\n\t\tstreamsBaseUrl: baseUrl,\n\t\tindexApiKey: defaultInternalIndexApiKey(),\n\t\tstreamsApiKey: defaultInternalStreamsApiKey(),\n\t});\n}\n"
7
7
  ],
8
- "mappings": ";AAaO,IAAM,2BAA2B;AACjC,IAAM,6BAA6B;AAE1C,IAAM,kCAAkC;AAExC,IAAM,mCACL;AAED,IAAM,iCACL;AAEM,SAAS,0BAA0B,CACzC,MAAyB,QAAQ,KACZ;AAAA,EACrB,MAAM,WAAW,IAAI,wBA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;AAAA,OAKK,qBAAoB,GAAoB;AAAA,IAC7C,MAAM,MAAM,MAAM,KAAK,IACtB,GAAG,KAAK,+CACR,KAAK,aACN;AAAA,IACA,OAAO,OAAO,IAAI,YAAY,KAAK;AAAA;AAAA,OAW9B,4BAA2B,CAAC,MAMsC;AAAA,IACvE,MAAM,SAAS,IAAI,gBAAgB;AAAA,MAClC,OAAO;AAAA,MACP,WAAW,OAAO,KAAK,QAAQ;AAAA,MAC/B,OAAO,OAAO,KAAK,SAAS,UAAU;AAAA,MACtC,OAAO,KAAK,MAAM,KAAK,GAAG;AAAA,IAC3B,CAAC;AAAA,IACD,IAAI,KAAK;AAAA,MAAa,OAAO,IAAI,eAAe,KAAK,WAAW;AAAA,IAC3D;AAAA,aAAO,IAAI,eAAe,OAAO,KAAK,cAAc,CAAC,CAAC;AAAA,IAC3D,OAAO,KAAK,IACX,GAAG,KAAK,oCAAoC,UAC5C,KAAK,aACN;AAAA;AAEF;AAGO,SAAS,6BAA6B,GAAoB;AAAA,EAChE,MAAM,UAAU,4BAA4B;AAAA,EAC5C,OAAO,IAAI,gBAAgB;AAAA,IAC1B,cAAc;AAAA,IACd,gBAAgB;AAAA,IAChB,aAAa,2BAA2B;AAAA,IACxC,eAAe,6BAA6B;AAAA,EAC7C,CAAC;AAAA;",
9
+ "debugId": "64784D5C41871B7164756E2164756E21",
10
10
  "names": []
11
11
  }
@@ -159,7 +159,6 @@ interface SubgraphsTable {
159
159
  expires_at: Date | null;
160
160
  /** (event type, contract) probe pairs persisted at deploy for weight classification. */
161
161
  sparse_probe_targets: unknown | null;
162
- sandbox_workers: Generated<boolean>;
163
162
  created_at: Generated<Date>;
164
163
  updated_at: Generated<Date>;
165
164
  }
@@ -160,7 +160,6 @@ interface SubgraphsTable {
160
160
  expires_at: Date | null;
161
161
  /** (event type, contract) probe pairs persisted at deploy for weight classification. */
162
162
  sparse_probe_targets: unknown | null;
163
- sandbox_workers: Generated<boolean>;
164
163
  created_at: Generated<Date>;
165
164
  updated_at: Generated<Date>;
166
165
  }
@@ -0,0 +1,24 @@
1
+ import { type Kysely, sql } from "kysely";
2
+ import { onControlPlane } from "../src/db/migration-role.ts";
3
+
4
+ // The subprocess handler sandbox is gone (hosted stacks isolate handlers with
5
+ // gVisor), so its per-subgraph opt-in column has no reader. Control-plane
6
+ // (TARGET) — the subgraphs control-plane table.
7
+ export async function up(db: Kysely<unknown>): Promise<void> {
8
+ await sql`SET lock_timeout = '30s'`.execute(db);
9
+ await onControlPlane(async () => {
10
+ await sql`
11
+ ALTER TABLE subgraphs
12
+ DROP COLUMN IF EXISTS sandbox_workers
13
+ `.execute(db);
14
+ });
15
+ }
16
+
17
+ export async function down(db: Kysely<unknown>): Promise<void> {
18
+ await onControlPlane(async () => {
19
+ await sql`
20
+ ALTER TABLE subgraphs
21
+ ADD COLUMN IF NOT EXISTS sandbox_workers BOOLEAN NOT NULL DEFAULT FALSE
22
+ `.execute(db);
23
+ });
24
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@secondlayer/shared",
3
- "version": "11.19.0",
3
+ "version": "11.19.2",
4
4
  "description": "Internal building blocks shared across Secondlayer packages.",
5
5
  "license": "MIT",
6
6
  "repository": {