@secondlayer/shared 15.2.1 → 15.3.1

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.
Files changed (85) hide show
  1. package/dist/src/archive/range-digest.d.ts +67 -9
  2. package/dist/src/archive/semantic-digest-builder.d.ts +67 -9
  3. package/dist/src/coverage/index.d.ts +70 -9
  4. package/dist/src/coverage/index.js.map +2 -2
  5. package/dist/src/db/index.d.ts +69 -10
  6. package/dist/src/db/index.js +19 -1
  7. package/dist/src/db/index.js.map +5 -4
  8. package/dist/src/db/queries/chain-reorgs.d.ts +67 -9
  9. package/dist/src/db/queries/chain-reorgs.js +17 -1
  10. package/dist/src/db/queries/chain-reorgs.js.map +5 -4
  11. package/dist/src/db/queries/contracts.d.ts +114 -28
  12. package/dist/src/db/queries/contracts.js +115 -15
  13. package/dist/src/db/queries/contracts.js.map +7 -5
  14. package/dist/src/db/queries/instance.d.ts +75 -10
  15. package/dist/src/db/queries/instance.js +147 -3
  16. package/dist/src/db/queries/instance.js.map +6 -4
  17. package/dist/src/db/queries/integrity.d.ts +83 -10
  18. package/dist/src/db/queries/integrity.js +236 -2
  19. package/dist/src/db/queries/integrity.js.map +7 -4
  20. package/dist/src/db/queries/subgraph-gaps.d.ts +75 -12
  21. package/dist/src/db/queries/subgraph-gaps.js +7 -3
  22. package/dist/src/db/queries/subgraph-gaps.js.map +3 -3
  23. package/dist/src/db/queries/subgraph-operations.d.ts +67 -9
  24. package/dist/src/db/queries/subgraphs.d.ts +128 -42
  25. package/dist/src/db/queries/subgraphs.js +85 -27
  26. package/dist/src/db/queries/subgraphs.js.map +7 -6
  27. package/dist/src/db/queries/sync-scope.d.ts +67 -9
  28. package/dist/src/db/queries/webhook-replays.d.ts +79 -13
  29. package/dist/src/db/queries/webhook-replays.js +468 -19
  30. package/dist/src/db/queries/webhook-replays.js.map +9 -4
  31. package/dist/src/db/queries/webhooks.d.ts +102 -21
  32. package/dist/src/db/queries/webhooks.js +72 -17
  33. package/dist/src/db/queries/webhooks.js.map +6 -5
  34. package/dist/src/db/schema.d.ts +68 -10
  35. package/dist/src/db/schema.js +20 -1
  36. package/dist/src/db/schema.js.map +4 -3
  37. package/dist/src/db/transition.d.ts +46 -0
  38. package/dist/src/db/transition.js +38 -0
  39. package/dist/src/db/transition.js.map +10 -0
  40. package/dist/src/email/index.d.ts +16 -1
  41. package/dist/src/email/index.js +186 -130
  42. package/dist/src/email/index.js.map +5 -4
  43. package/dist/src/errors.d.ts +7 -1
  44. package/dist/src/errors.js +12 -1
  45. package/dist/src/errors.js.map +3 -3
  46. package/dist/src/index-http.d.ts +13 -3
  47. package/dist/src/index-http.js +3 -3
  48. package/dist/src/index-http.js.map +3 -3
  49. package/dist/src/index.d.ts +109 -20
  50. package/dist/src/index.js +41 -8
  51. package/dist/src/index.js.map +8 -7
  52. package/dist/src/insights/index.d.ts +68 -9
  53. package/dist/src/insights/index.js +55 -5
  54. package/dist/src/insights/index.js.map +7 -6
  55. package/dist/src/node/local-client.d.ts +67 -9
  56. package/dist/src/queue/listener.js +17 -1
  57. package/dist/src/queue/listener.js.map +5 -4
  58. package/dist/src/runtime/index.d.ts +0 -4
  59. package/dist/src/runtime/index.js +54 -4
  60. package/dist/src/runtime/index.js.map +6 -5
  61. package/dist/src/schemas/index.d.ts +36 -10
  62. package/dist/src/schemas/index.js +12 -8
  63. package/dist/src/schemas/index.js.map +4 -4
  64. package/dist/src/schemas/subgraphs.d.ts +22 -9
  65. package/dist/src/schemas/subgraphs.js +10 -6
  66. package/dist/src/schemas/subgraphs.js.map +3 -3
  67. package/dist/src/schemas/webhooks.d.ts +15 -2
  68. package/dist/src/schemas/webhooks.js +2 -2
  69. package/dist/src/schemas/webhooks.js.map +3 -3
  70. package/dist/src/subgraphs/spec.d.ts +5 -1
  71. package/dist/src/webhooks/health.d.ts +27 -0
  72. package/dist/src/webhooks/health.js +84 -0
  73. package/dist/src/webhooks/health.js.map +11 -0
  74. package/migrations/0184_status_checks.ts +92 -0
  75. package/migrations/0185_reorg_generation_settlement_seq.ts +89 -0
  76. package/migrations/0186_api_keys_one_active_tenant_per_name.ts +43 -0
  77. package/migrations/0187_accounts_email_lower_unique.ts +27 -0
  78. package/migrations/0188_webhook_reasons.ts +124 -0
  79. package/migrations/0189_subgraph_lifecycle.ts +83 -0
  80. package/migrations/0190_usage_ledger_debited_usd_micros.ts +59 -0
  81. package/migrations/0191_indexer_state_machines.ts +83 -0
  82. package/migrations/0192_hosted_stack_state.ts +37 -0
  83. package/migrations/0193_accounts_ghost_has_no_email.ts +34 -0
  84. package/migrations/0194_webhook_outbox_block_hash.ts +46 -0
  85. package/package.json +9 -1
@@ -1,4 +1,4 @@
1
- import { Kysely } from "kysely";
1
+ import { Kysely as Kysely2 } from "kysely";
2
2
  /**
3
3
  * How far a subgraph's rows can be checked without trusting the server,
4
4
  * derived from its sources and a scan of its handler. Never configured.
@@ -20,6 +20,21 @@ interface SubgraphVerification {
20
20
  /** What stays unproven even at this level, e.g. tx attribution of writes. */
21
21
  unproven: string[];
22
22
  }
23
+ /** Every state `subgraphs.status` can hold; mirrored by the
24
+ * `subgraphs_status_check` CHECK (migration 0189). */
25
+ declare const SUBGRAPH_STATES: readonly ["active", "reindexing", "error"];
26
+ type SubgraphStatus = (typeof SUBGRAPH_STATES)[number];
27
+ /**
28
+ * The one convention for state machines: states are a const array (mirrored by
29
+ * a DB CHECK), transitions are a table next to the states, and every status
30
+ * write goes through `casTransition`.
31
+ */
32
+ interface Machine<S extends string> {
33
+ readonly states: readonly S[];
34
+ canTransition(from: S, to: S): boolean;
35
+ /** Throws on an illegal move. */
36
+ assert(from: S, to: S): void;
37
+ }
23
38
  import { ColumnType, Generated, Selectable } from "kysely";
24
39
  /**
25
40
  * Coverage-kernel constraints. SQL CHECKs in migration 0116 must stay
@@ -40,6 +55,8 @@ type FailureClass = (typeof FAILURE_CLASSES)[number];
40
55
  declare const RETRY_STATES: readonly ["open", "retrying", "halted", "resolved"];
41
56
  type RetryState = (typeof RETRY_STATES)[number];
42
57
  type BootstrapSource = "archive" | "genesis" | "import";
58
+ /** Why a webhook is paused: the customer did it, or the circuit breaker did. */
59
+ type WebhookPauseReason = "user" | "circuit";
43
60
  interface BlocksTable {
44
61
  height: number;
45
62
  hash: string;
@@ -179,7 +196,7 @@ interface SubgraphsTable {
179
196
  id: Generated<string>;
180
197
  name: string;
181
198
  version: Generated<string>;
182
- status: Generated<string>;
199
+ status: Generated<SubgraphStatus>;
183
200
  definition: Record<string, unknown>;
184
201
  schema_hash: string;
185
202
  handler_path: string;
@@ -196,8 +213,10 @@ interface SubgraphsTable {
196
213
  handler_code: string | null;
197
214
  source_code: string | null;
198
215
  project_id: string | null;
199
- /** Paid (wallet-ghost) deploys expire unless renewed or claimed; NULL = no expiry. */
200
- expires_at: Date | null;
216
+ /** Set while the account's metered reads are refused (spend cap, credits).
217
+ * Both columns are set or both null; `last_error` stays for real errors. */
218
+ billing_paused_at: Date | null;
219
+ billing_paused_code: string | null;
201
220
  /** (event type, contract) probe pairs persisted at deploy for weight classification. */
202
221
  sparse_probe_targets: unknown | null;
203
222
  /** sha256 over everything that shapes rows (schema, handler bundle,
@@ -211,6 +230,9 @@ interface SubgraphsTable {
211
230
  created_at: Generated<Date>;
212
231
  updated_at: Generated<Date>;
213
232
  }
233
+ /** Mirrored by the CHECK on `contracts.abi_status`. */
234
+ declare const ABI_STATUSES: readonly ["pending", "fetched", "unparseable", "failed"];
235
+ type AbiStatus = (typeof ABI_STATUSES)[number];
214
236
  interface ContractsTable {
215
237
  contract_id: string;
216
238
  deployer: string;
@@ -219,17 +241,23 @@ interface ContractsTable {
219
241
  abi: unknown | null;
220
242
  declared_traits: Generated<string[]>;
221
243
  inferred_standards: Generated<string[]>;
222
- abi_status: Generated<string>;
244
+ abi_status: Generated<AbiStatus>;
223
245
  abi_fetched_at: Date | null;
246
+ /** Failed fetches so far; `failed` re-polls until the registry's attempt cap. */
247
+ abi_attempts: Generated<number>;
248
+ /** When a `failed` row is next due; NULL once attempts are exhausted. */
249
+ abi_next_attempt_at: Date | null;
224
250
  created_at: Generated<Date>;
225
251
  }
252
+ /** The only reasons the runtime records; mirrored by a CHECK on `subgraph_gaps.reason`. */
253
+ type GapReason = "block_missing" | "processing_error";
226
254
  interface SubgraphGapsTable {
227
255
  id: Generated<string>;
228
256
  subgraph_id: string;
229
257
  subgraph_name: string;
230
258
  gap_start: number;
231
259
  gap_end: number;
232
- reason: string;
260
+ reason: GapReason;
233
261
  detected_at: Generated<Date>;
234
262
  resolved_at: Date | null;
235
263
  }
@@ -275,12 +303,13 @@ interface SubgraphOperationsTable {
275
303
  * (those checkpoint on subgraphs.last_processed_block). */
276
304
  cursor_block: string | number | bigint | null;
277
305
  }
306
+ type ApiKeyStatus = "active" | "revoked";
278
307
  interface ApiKeysTable {
279
308
  id: Generated<string>;
280
309
  key_hash: string;
281
310
  key_prefix: string;
282
311
  name: string | null;
283
- status: Generated<string>;
312
+ status: Generated<ApiKeyStatus>;
284
313
  rate_limit: Generated<number>;
285
314
  ip_address: string;
286
315
  account_id: string;
@@ -641,6 +670,10 @@ interface SbtcSettlementsTable {
641
670
  last_checked_at: Generated<Date>;
642
671
  /** Set once, when `settlement_confirmed` first flips true. */
643
672
  confirmed_at: Date | null;
673
+ /** Monotonic stamp from `sbtc_settlements_seq`, retaken each time the sweep
674
+ * becomes confirmed. The webhook scan's watermark. BIGINT: a string at
675
+ * runtime. */
676
+ seq: Generated<number | string>;
644
677
  updated_at: Generated<Date>;
645
678
  }
646
679
  type BnsNameEventTopic = "new-name" | "transfer-name" | "renew-name" | "burn-name" | "new-airdrop";
@@ -760,7 +793,9 @@ interface PendingForkBlocksTable {
760
793
  payload: ColumnType<unknown, unknown, unknown>;
761
794
  received_at: Generated<Date>;
762
795
  }
763
- type ObserverJournalStatus = "received" | "processed" | "failed" | "retried";
796
+ /** Mirrored by the CHECK on `observer_journal.status`. */
797
+ declare const OBSERVER_JOURNAL_STATUSES: readonly ["received", "processed", "failed", "retried", "poisoned", "skipped"];
798
+ type ObserverJournalStatus = (typeof OBSERVER_JOURNAL_STATUSES)[number];
764
799
  /**
765
800
  * Exact observer callback receipt. `raw_body` is immutable evidence; the
766
801
  * processing columns are updated only after the current derived-state write
@@ -795,7 +830,7 @@ interface StageRegistryTable {
795
830
  enabled: Generated<boolean>;
796
831
  created_at: Generated<Date>;
797
832
  }
798
- /** One versioned sweep of a stage. */
833
+ /** One versioned sweep of a stage. Nothing writes this table yet; kept because the receipts and failures tables reference it. */
799
834
  interface StageRunsTable {
800
835
  id: Generated<string>;
801
836
  stage_id: string;
@@ -929,6 +964,7 @@ interface Database {
929
964
  archive_fetches: ArchiveFetchesTable;
930
965
  usage_ledger: UsageLedgerTable;
931
966
  account_balance_alerts: AccountBalanceAlertsTable;
967
+ hosted_stack_state: HostedStackStateTable;
932
968
  webhook_incident_alerts: WebhookIncidentAlertsTable;
933
969
  cli_device_logins: CliDeviceLoginsTable;
934
970
  oauth_clients: OauthClientsTable;
@@ -1012,7 +1048,11 @@ interface UsageLedgerTable {
1012
1048
  * floor to observe past. */
1013
1049
  observed_quantity: string | number | null;
1014
1050
  usd_micros: string | number | bigint;
1051
+ /** True when the whole price was taken; derived from `debited_usd_micros`. */
1015
1052
  debited: Generated<boolean>;
1053
+ /** Amount actually taken from the balance, `0..usd_micros` (bounded the
1054
+ * other way for a negative top-up/grant row). Unpaid = price - this. */
1055
+ debited_usd_micros: Generated<string | number | bigint>;
1016
1056
  source: string;
1017
1057
  /** API key behind a metered read; null for non-read units and older rows. */
1018
1058
  api_key_id: string | null;
@@ -1030,6 +1070,14 @@ interface AccountBalanceAlertsTable {
1030
1070
  sent_2d_at: Date | null;
1031
1071
  sent_stopped_at: Date | null;
1032
1072
  }
1073
+ /** The workload host's report of one account's hosted stack. Written only by
1074
+ * `POST /internal/stack-state`; `reported_at` is the host's observation time. */
1075
+ interface HostedStackStateTable {
1076
+ account_id: string;
1077
+ state: "provisioning" | "running" | "stopped" | "destroyed";
1078
+ stop_reason: "credits" | "cap" | "idle" | null;
1079
+ reported_at: Date;
1080
+ }
1033
1081
  /** Debounce state for the webhook-down email: one row per incident, open
1034
1082
  * while `resolved_at` is null. No preference columns by design. */
1035
1083
  interface WebhookIncidentAlertsTable {
@@ -1167,7 +1215,7 @@ interface SentinelAccountsTable {
1167
1215
  via: "created" | "consent";
1168
1216
  }
1169
1217
  type Subgraph = Selectable<SubgraphsTable>;
1170
- type WebhookStatus = "active" | "paused" | "error";
1218
+ type WebhookStatus = "active" | "paused";
1171
1219
  /** Webhooks react to raw chain events matched directly off the Index/Streams
1172
1220
  * clock. `chain` is the only kind since migration 0159 removed subgraph-row
1173
1221
  * webhooks; the column stays as the discriminator. */
@@ -1193,6 +1241,8 @@ interface WebhooksTable {
1193
1241
  concurrency: Generated<number>;
1194
1242
  circuit_failures: Generated<number>;
1195
1243
  circuit_opened_at: Date | null;
1244
+ /** Why a paused webhook is paused. Set exactly while `status` is `paused`. */
1245
+ pause_reason: WebhookPauseReason | null;
1196
1246
  last_delivery_at: Date | null;
1197
1247
  last_success_at: Date | null;
1198
1248
  last_error: string | null;
@@ -1203,6 +1253,10 @@ interface WebhooksTable {
1203
1253
  updated_at: Generated<Date>;
1204
1254
  }
1205
1255
  type OutboxStatus = "pending" | "delivered" | "dead";
1256
+ /** Why a row is dead: retries ran out, or a reorg removed its event. An
1257
+ * orphaned row stays dead; requeueing it would resend an event the chain no
1258
+ * longer contains. */
1259
+ type DeadReason = "exhausted" | "orphaned";
1206
1260
  interface WebhookOutboxTable {
1207
1261
  id: Generated<string>;
1208
1262
  webhook_id: string;
@@ -1232,6 +1286,14 @@ interface WebhookOutboxTable {
1232
1286
  * into an orphaned fork. Null otherwise — delivery failures track their
1233
1287
  * history on `webhooks.last_error`, not per-row. */
1234
1288
  last_error: string | null;
1289
+ /** Set exactly while `status` is `dead`. */
1290
+ dead_reason: DeadReason | null;
1291
+ /** Hash of the block a chain apply row was emitted for. Null on rows
1292
+ * written before the column existed (the payload carries it too). */
1293
+ block_hash: string | null;
1294
+ /** Set when a reorg rollback recalled this delivered apply row, so a
1295
+ * later rollback for the same reorg skips it. */
1296
+ rolled_back_at: Date | null;
1235
1297
  created_at: Generated<Date>;
1236
1298
  }
1237
1299
  type WebhookReplayStatus = "scanning" | "running" | "done" | "failed";
@@ -1281,6 +1343,13 @@ interface TriggerEvaluatorStateTable {
1281
1343
  /** Watermark for the async sBTC settlement-confirmed webhook scan; null until
1282
1344
  * the evaluator fast-forwards it on first run. */
1283
1345
  last_settlement_scan_at: ColumnType<Date | null, Date | null | undefined, Date | null>;
1346
+ /** `sbtc_settlements.seq` watermark. Null until the first settlement row is
1347
+ * scanned; `last_settlement_scan_at` is the forward-only floor until then. */
1348
+ last_settlement_scan_seq: ColumnType<bigint | null, bigint | number | null | undefined, bigint | number | null>;
1349
+ /** Counts reorg rewinds. The evaluator checks it under the row lock in the
1350
+ * transaction that emits a batch and advances the cursor, so a reorg that
1351
+ * lands mid-tick rolls the batch back. */
1352
+ reorg_generation: ColumnType<bigint, bigint | number | undefined, bigint | number>;
1284
1353
  /** Streams cursor (`<block_height>:<event_index>`) for the Bitcoin (Runes)
1285
1354
  * chain-trigger evaluator (plan 060) — a separate clock from
1286
1355
  * `last_processed_block` (Stacks). Null until the evaluator fast-forwards
@@ -1412,11 +1481,27 @@ interface FeedbackTicketsTable {
1412
1481
  classified_at: Date | null;
1413
1482
  created_at: Generated<Date>;
1414
1483
  }
1484
+ /**
1485
+ * Subgraph lifecycle. `error` is sticky: a live walk never clears it, only a
1486
+ * redeploy (`error -> active`) or a reindex (`error -> reindexing`) does.
1487
+ * Every status write goes through {@link transitionSubgraph}; the live
1488
+ * progress writes below touch the cursor only and are gated on the status
1489
+ * they are valid for.
1490
+ */
1491
+ declare const subgraphMachine: Machine<SubgraphStatus>;
1492
+ /**
1493
+ * Move a subgraph from one of `from` to `to`, writing `set` in the same
1494
+ * statement. Returns the row, or `null` when it was not in a `from` state
1495
+ * (something else, a halt or a redeploy, decided first): log and stop, never
1496
+ * retry. Staying in the same state (`reindexing -> reindexing`) is a plain
1497
+ * conditional write, not a transition.
1498
+ */
1499
+ declare function transitionSubgraph(db: Kysely2<Database>, name: string, from: readonly SubgraphStatus[], to: SubgraphStatus, set?: Record<string, unknown>): Promise<Subgraph | null>;
1415
1500
  /** Convert a subgraph name to its PostgreSQL schema name. */
1416
1501
  declare function pgSchemaName(subgraphName: string): string;
1417
1502
  /** OSS writes empty account_id — name is the local unique key. */
1418
1503
  declare function localSubgraphAccountId(accountId?: string): string;
1419
- declare function registerSubgraph(db: Kysely<Database>, data: {
1504
+ declare function registerSubgraph(db: Kysely2<Database>, data: {
1420
1505
  name: string
1421
1506
  version: string
1422
1507
  definition: Record<string, unknown>
@@ -1432,15 +1517,21 @@ declare function registerSubgraph(db: Kysely<Database>, data: {
1432
1517
  pinPreimage?: string | null
1433
1518
  verification?: SubgraphVerification | null
1434
1519
  }): Promise<Subgraph>;
1435
- declare function getSubgraph(db: Kysely<Database>, name: string, accountId?: string): Promise<Subgraph | null>;
1436
- declare function listSubgraphs(db: Kysely<Database>, accountId?: string): Promise<Subgraph[]>;
1437
- declare function updateSubgraphStatus(db: Kysely<Database>, name: string, status: string, lastProcessedBlock?: number): Promise<void>;
1520
+ declare function getSubgraph(db: Kysely2<Database>, name: string, accountId?: string): Promise<Subgraph | null>;
1521
+ declare function listSubgraphs(db: Kysely2<Database>, accountId?: string): Promise<Subgraph[]>;
1522
+ /**
1523
+ * Reindex progress: moves the cursor of a subgraph that is still
1524
+ * `reindexing`, and nothing else. Returns `false` when the subgraph left that
1525
+ * state (halted, cancelled, redeployed): the walk must not write on, and its
1526
+ * progress never revives a halt.
1527
+ */
1528
+ declare function setReindexCursor(db: Kysely2<Database>, name: string, lastProcessedBlock: number): Promise<boolean>;
1438
1529
  /** Live-walk ERROR write (f069): a block whose handlers ALL failed
1439
1530
  * (`processed === 0 && errors > 0`, `block-processor.ts`'s `applyProgress`)
1440
- * is stamped 'error' and its height is recorded as processed, same as
1441
- * `updateSubgraphStatus(db, name, "error", blockHeight)` — except the
1442
- * cursor half of that write now goes through the same conditional `<`
1443
- * guard as {@link recordLiveProgress}. Marking a subgraph 'error' is not
1531
+ * moves an `active` subgraph to 'error' and records its height as processed;
1532
+ * the cursor half goes through the same conditional `<` guard as
1533
+ * {@link recordLiveProgress}. A reindexing or already-halted subgraph is left
1534
+ * alone. Marking a subgraph 'error' is not
1444
1535
  * itself replay-sensitive, but it shares the `last_processed_block` column
1445
1536
  * with the replay guard: an unconditional write here could regress the
1446
1537
  * cursor a racing (successful) writer already advanced past, which is
@@ -1448,31 +1539,27 @@ declare function updateSubgraphStatus(db: Kysely<Database>, name: string, status
1448
1539
  * practice `ctx.rollbackTo` (`runner.ts`) means an all-failed block never
1449
1540
  * flushes writes, so a lost race here is always a silent no-op, never a
1450
1541
  * case that needs `CursorRaceLostError`-style tx abort. Returns whether
1451
- * the write applied. Live path only — reindex/backfill's error stamping
1452
- * goes through {@link updateSubgraphStatus} unconditionally, as before. */
1453
- declare function recordLiveError(db: Kysely<Database>, name: string, blockHeight: number): Promise<boolean>;
1454
- declare function recordSubgraphProcessed(db: Kysely<Database>, name: string, processed: number, errors: number, lastError?: string): Promise<void>;
1455
- /** Record a billing pause on the existing health fields. Status and counters
1456
- * are untouched: a paused subgraph is healthy, just waiting on its account. */
1457
- declare function markSubgraphBillingPaused(db: Kysely<Database>, name: string, code: string): Promise<void>;
1458
- /** Clear a billing pause once reads succeed again. Leaves any other
1459
- * `last_error` alone. */
1460
- declare function clearSubgraphBillingPaused(db: Kysely<Database>, name: string): Promise<void>;
1461
- declare function updateSubgraphHandlerPath(db: Kysely<Database>, name: string, handlerPath: string, opts?: {
1542
+ * the write applied. Live path only: reindex/backfill halts go through
1543
+ * {@link transitionSubgraph}. */
1544
+ declare function recordLiveError(db: Kysely2<Database>, name: string, blockHeight: number): Promise<boolean>;
1545
+ declare function recordSubgraphProcessed(db: Kysely2<Database>, name: string, processed: number, errors: number, lastError?: string): Promise<void>;
1546
+ /** Record a billing pause. Status, cursor, counters and `last_error` are
1547
+ * untouched: a paused subgraph is healthy, just waiting on its account. */
1548
+ declare function markSubgraphBillingPaused(db: Kysely2<Database>, name: string, code: string): Promise<void>;
1549
+ /** Clear a billing pause once reads succeed again. */
1550
+ declare function clearSubgraphBillingPaused(db: Kysely2<Database>, name: string): Promise<void>;
1551
+ declare function updateSubgraphHandlerPath(db: Kysely2<Database>, name: string, handlerPath: string, opts?: {
1462
1552
  handlerCode?: string
1463
1553
  sourceCode?: string
1464
1554
  pin?: string | null
1465
1555
  pinPreimage?: string | null
1466
1556
  verification?: SubgraphVerification | null
1467
1557
  }): Promise<void>;
1468
- declare function deleteSubgraph(db: Kysely<Database>, name: string, accountId?: string): Promise<Subgraph | null>;
1469
- /** Set or clear a paid subgraph's expiry (NULL = no expiry, e.g. on claim). */
1470
- declare function updateSubgraphExpiry(db: Kysely<Database>, name: string, accountId: string, expiresAt: Date | null): Promise<void>;
1471
- /** Live-walk progress write: advances the cursor and PROMOTES toward
1472
- * 'active' (deploying/error → active keeps reorg eligibility, reorg.ts gates
1473
- * on it) but never overwrites an explicit 'reindexing' park — unconditional
1474
- * status stamping let catch-up flap a parked subgraph back into its own path
1475
- * per block, fighting the queued reindex op.
1558
+ declare function deleteSubgraph(db: Kysely2<Database>, name: string, accountId?: string): Promise<Subgraph | null>;
1559
+ /** Live-walk progress write: advances the cursor of an `active` subgraph and
1560
+ * never touches status. A `reindexing` or `error` subgraph is a no-op here:
1561
+ * the old promote-toward-active CASE let a live commit undo a halt and flap
1562
+ * a parked subgraph back into catch-up against its own reindex op.
1476
1563
  *
1477
1564
  * `last_processed_block` is now written CONDITIONALLY — `WHERE
1478
1565
  * last_processed_block < lastProcessedBlock`, mirroring
@@ -1502,13 +1589,12 @@ declare function updateSubgraphExpiry(db: Kysely<Database>, name: string, accoun
1502
1589
  * {@link rewindLiveProgress} instead, which keeps the old unconditional
1503
1590
  * semantics and is safe specifically because the reorg path takes a
1504
1591
  * transaction-scoped advisory lock (`reorg.ts`) other writers can't cross. */
1505
- declare function recordLiveProgress(db: Kysely<Database>, name: string, lastProcessedBlock: number): Promise<boolean>;
1592
+ declare function recordLiveProgress(db: Kysely2<Database>, name: string, lastProcessedBlock: number): Promise<boolean>;
1506
1593
  /** Reorg-rewind progress write: the OLD unconditional `recordLiveProgress`
1507
1594
  * semantics, verbatim — moves `last_processed_block` to the fork height
1508
1595
  * regardless of its current value, because that is by definition a
1509
1596
  * backward move the conditional `<` guard in `recordLiveProgress` would
1510
- * refuse. Same status-promotion CASE (never unparks an explicit
1511
- * 'reindexing').
1597
+ * refuse. Cursor only, `active` subgraphs only.
1512
1598
  *
1513
1599
  * Callers: exclusively the subgraph-reorg path
1514
1600
  * (`packages/subgraphs/src/runtime/reorg.ts`, via `block-processor.ts`'s
@@ -1518,5 +1604,5 @@ declare function recordLiveProgress(db: Kysely<Database>, name: string, lastProc
1518
1604
  * delete+reprocess+rewind sequence — no other writer can interleave a
1519
1605
  * forward write between the rewind and the fork block's reprocess. Do not
1520
1606
  * call this from the live catch-up path. */
1521
- declare function rewindLiveProgress(db: Kysely<Database>, name: string, lastProcessedBlock: number): Promise<void>;
1522
- export { clearSubgraphBillingPaused, deleteSubgraph, getSubgraph, listSubgraphs, localSubgraphAccountId, markSubgraphBillingPaused, pgSchemaName, recordLiveError, recordLiveProgress, recordSubgraphProcessed, registerSubgraph, rewindLiveProgress, updateSubgraphExpiry, updateSubgraphHandlerPath, updateSubgraphStatus };
1607
+ declare function rewindLiveProgress(db: Kysely2<Database>, name: string, lastProcessedBlock: number): Promise<void>;
1608
+ export { clearSubgraphBillingPaused, deleteSubgraph, getSubgraph, listSubgraphs, localSubgraphAccountId, markSubgraphBillingPaused, pgSchemaName, recordLiveError, recordLiveProgress, recordSubgraphProcessed, registerSubgraph, rewindLiveProgress, setReindexCursor, subgraphMachine, transitionSubgraph, updateSubgraphHandlerPath };
@@ -1,5 +1,5 @@
1
1
  // src/db/queries/subgraphs.ts
2
- import { sql as sql2 } from "kysely";
2
+ import { sql as sql3 } from "kysely";
3
3
 
4
4
  // src/mode.ts
5
5
  var VALID_MODES = [
@@ -54,9 +54,13 @@ var DeploySubgraphRequestSchema = z.object({
54
54
  sourceCode: z.string().max(1048576, "source code exceeds 1MB limit").optional(),
55
55
  dryRun: z.boolean().optional()
56
56
  });
57
- var BILLING_PAUSED_PREFIX = "billing_paused: ";
58
- function billingPausedCode(lastError) {
59
- return lastError?.startsWith(BILLING_PAUSED_PREFIX) ? lastError.slice(BILLING_PAUSED_PREFIX.length) : null;
57
+ var SUBGRAPH_STATES = ["active", "reindexing", "error"];
58
+ function syncState(subgraph, tip) {
59
+ if (subgraph.status === "reindexing")
60
+ return "reindexing";
61
+ if (subgraph.status === "error")
62
+ return "error";
63
+ return Number(subgraph.lastProcessedBlock) < tip ? "catching_up" : "synced";
60
64
  }
61
65
 
62
66
  // src/db/jsonb.ts
@@ -76,7 +80,61 @@ function parseJsonb(value) {
76
80
  return value ?? {};
77
81
  }
78
82
 
83
+ // src/db/transition.ts
84
+ import { sql as sql2 } from "kysely";
85
+ function defineMachine(def) {
86
+ const canTransition = (from, to) => def.transitions[from]?.includes(to) ?? false;
87
+ return {
88
+ states: def.states,
89
+ canTransition,
90
+ assert(from, to) {
91
+ if (!canTransition(from, to)) {
92
+ throw new Error(`illegal transition ${from} -> ${to}`);
93
+ }
94
+ }
95
+ };
96
+ }
97
+ async function casTransition(db, t) {
98
+ const column = sql2.id(t.column ?? "status");
99
+ const assignments = [sql2`${column} = ${t.to}`];
100
+ if (t.stampUpdatedAt !== false)
101
+ assignments.push(sql2`updated_at = now()`);
102
+ for (const [key, value] of Object.entries(t.set ?? {})) {
103
+ assignments.push(sql2`${sql2.id(key)} = ${value}`);
104
+ }
105
+ const returning = t.returning ? sql2.join(t.returning.map((c) => sql2.id(c))) : sql2.raw("*");
106
+ const { rows } = await sql2`
107
+ UPDATE ${sql2.table(t.table)}
108
+ SET ${sql2.join(assignments)}
109
+ WHERE ${sql2.id(t.key ?? "id")} = ${t.id} AND ${column} = ANY(${sql2.val([...t.from])})
110
+ RETURNING ${returning}
111
+ `.execute(db);
112
+ return rows[0] ?? null;
113
+ }
114
+
79
115
  // src/db/queries/subgraphs.ts
116
+ var subgraphMachine = defineMachine({
117
+ states: SUBGRAPH_STATES,
118
+ transitions: {
119
+ active: ["reindexing", "error"],
120
+ reindexing: ["active", "error"],
121
+ error: ["reindexing", "active"]
122
+ }
123
+ });
124
+ function transitionSubgraph(db, name, from, to, set) {
125
+ for (const state of from) {
126
+ if (state !== to)
127
+ subgraphMachine.assert(state, to);
128
+ }
129
+ return casTransition(db, {
130
+ table: "subgraphs",
131
+ key: "name",
132
+ id: name,
133
+ from,
134
+ to,
135
+ set
136
+ });
137
+ }
80
138
  function pgSchemaName(subgraphName) {
81
139
  const safeName = subgraphName.replace(/-/g, "_");
82
140
  return `subgraph_${safeName}`;
@@ -140,38 +198,42 @@ async function listSubgraphs(db, accountId) {
140
198
  }
141
199
  return query.execute();
142
200
  }
143
- async function updateSubgraphStatus(db, name, status, lastProcessedBlock) {
144
- await db.updateTable("subgraphs").set({
145
- status,
146
- ...lastProcessedBlock !== undefined ? { last_processed_block: lastProcessedBlock } : {},
201
+ async function setReindexCursor(db, name, lastProcessedBlock) {
202
+ const result = await db.updateTable("subgraphs").set({
203
+ last_processed_block: lastProcessedBlock,
147
204
  updated_at: new Date
148
- }).where("name", "=", name).execute();
205
+ }).where("name", "=", name).where("status", "=", "reindexing").executeTakeFirst();
206
+ return Number(result.numUpdatedRows ?? 0n) > 0;
149
207
  }
150
208
  async function recordLiveError(db, name, blockHeight) {
151
209
  const result = await db.updateTable("subgraphs").set({
152
210
  status: "error",
153
211
  last_processed_block: blockHeight,
154
212
  updated_at: new Date
155
- }).where("name", "=", name).where("last_processed_block", "<", blockHeight).executeTakeFirst();
213
+ }).where("name", "=", name).where("status", "=", "active").where("last_processed_block", "<", blockHeight).executeTakeFirst();
156
214
  return Number(result.numUpdatedRows ?? 0n) > 0;
157
215
  }
158
216
  async function recordSubgraphProcessed(db, name, processed, errors, lastError) {
159
217
  await db.updateTable("subgraphs").set({
160
- total_processed: sql2`total_processed + ${processed}`,
161
- total_errors: sql2`total_errors + ${errors}`,
218
+ total_processed: sql3`total_processed + ${processed}`,
219
+ total_errors: sql3`total_errors + ${errors}`,
162
220
  ...lastError ? { last_error: lastError, last_error_at: new Date } : {},
163
221
  updated_at: new Date
164
222
  }).where("name", "=", name).execute();
165
223
  }
166
224
  async function markSubgraphBillingPaused(db, name, code) {
167
225
  await db.updateTable("subgraphs").set({
168
- last_error: `${BILLING_PAUSED_PREFIX}${code}`,
169
- last_error_at: new Date,
226
+ billing_paused_at: sql3`COALESCE(billing_paused_at, now())`,
227
+ billing_paused_code: code,
170
228
  updated_at: new Date
171
229
  }).where("name", "=", name).execute();
172
230
  }
173
231
  async function clearSubgraphBillingPaused(db, name) {
174
- await db.updateTable("subgraphs").set({ last_error: null, last_error_at: null, updated_at: new Date }).where("name", "=", name).where("last_error", "like", `${BILLING_PAUSED_PREFIX}%`).execute();
232
+ await db.updateTable("subgraphs").set({
233
+ billing_paused_at: null,
234
+ billing_paused_code: null,
235
+ updated_at: new Date
236
+ }).where("name", "=", name).where("billing_paused_at", "is not", null).execute();
175
237
  }
176
238
  async function updateSubgraphHandlerPath(db, name, handlerPath, opts) {
177
239
  await db.updateTable("subgraphs").set({
@@ -191,27 +253,22 @@ async function deleteSubgraph(db, name, accountId) {
191
253
  if (!subgraph)
192
254
  return null;
193
255
  const schemaName = subgraph.schema_name ?? pgSchemaName(name);
194
- await sql2`DROP SCHEMA IF EXISTS ${sql2.raw(`"${schemaName}"`)} CASCADE`.execute(db);
256
+ await sql3`DROP SCHEMA IF EXISTS ${sql3.raw(`"${schemaName}"`)} CASCADE`.execute(db);
195
257
  await db.deleteFrom("subgraphs").where("id", "=", subgraph.id).execute();
196
258
  return subgraph;
197
259
  }
198
- async function updateSubgraphExpiry(db, name, accountId, expiresAt) {
199
- await db.updateTable("subgraphs").set({ expires_at: expiresAt }).where("name", "=", name).where("account_id", "=", accountId).execute();
200
- }
201
260
  async function recordLiveProgress(db, name, lastProcessedBlock) {
202
261
  const result = await db.updateTable("subgraphs").set({
203
262
  last_processed_block: lastProcessedBlock,
204
- status: sql2`CASE WHEN status = 'reindexing' THEN status ELSE 'active' END`,
205
263
  updated_at: new Date
206
- }).where("name", "=", name).where("last_processed_block", "<", lastProcessedBlock).executeTakeFirst();
264
+ }).where("name", "=", name).where("status", "=", "active").where("last_processed_block", "<", lastProcessedBlock).executeTakeFirst();
207
265
  return Number(result.numUpdatedRows ?? 0n) > 0;
208
266
  }
209
267
  async function rewindLiveProgress(db, name, lastProcessedBlock) {
210
268
  await db.updateTable("subgraphs").set({
211
269
  last_processed_block: lastProcessedBlock,
212
- status: sql2`CASE WHEN status = 'reindexing' THEN status ELSE 'active' END`,
213
270
  updated_at: new Date
214
- }).where("name", "=", name).execute();
271
+ }).where("name", "=", name).where("status", "=", "active").execute();
215
272
  }
216
273
  export {
217
274
  clearSubgraphBillingPaused,
@@ -226,10 +283,11 @@ export {
226
283
  recordSubgraphProcessed,
227
284
  registerSubgraph,
228
285
  rewindLiveProgress,
229
- updateSubgraphExpiry,
230
- updateSubgraphHandlerPath,
231
- updateSubgraphStatus
286
+ setReindexCursor,
287
+ subgraphMachine,
288
+ transitionSubgraph,
289
+ updateSubgraphHandlerPath
232
290
  };
233
291
 
234
- //# debugId=097B919B6A957DFE64756E2164756E21
292
+ //# debugId=18FBED4BFEDAFACD64756E2164756E21
235
293
  //# sourceMappingURL=subgraphs.js.map