@secondlayer/shared 15.2.1 → 15.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/dist/src/archive/range-digest.d.ts +61 -9
  2. package/dist/src/archive/semantic-digest-builder.d.ts +61 -9
  3. package/dist/src/coverage/index.d.ts +64 -9
  4. package/dist/src/coverage/index.js.map +2 -2
  5. package/dist/src/db/index.d.ts +63 -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 +61 -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 +108 -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 +69 -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 +77 -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 +69 -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 +61 -9
  24. package/dist/src/db/queries/subgraphs.d.ts +122 -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 +61 -9
  28. package/dist/src/db/queries/webhook-replays.d.ts +73 -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 +96 -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 +62 -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 +11 -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 +98 -19
  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 +62 -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 +61 -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/package.json +9 -1
@@ -247,6 +247,12 @@ interface SubgraphVerification {
247
247
  /** What stays unproven even at this level, e.g. tx attribution of writes. */
248
248
  unproven: string[];
249
249
  }
250
+ /** Every state `subgraphs.status` can hold; mirrored by the
251
+ * `subgraphs_status_check` CHECK (migration 0189). */
252
+ declare const SUBGRAPH_STATES: readonly ["active", "reindexing", "error"];
253
+ type SubgraphStatus = (typeof SUBGRAPH_STATES)[number];
254
+ /** Why a webhook is paused: the customer did it, or the circuit breaker did. */
255
+ type WebhookPauseReason = "user" | "circuit";
250
256
  interface BlocksTable {
251
257
  height: number;
252
258
  hash: string;
@@ -386,7 +392,7 @@ interface SubgraphsTable {
386
392
  id: Generated<string>;
387
393
  name: string;
388
394
  version: Generated<string>;
389
- status: Generated<string>;
395
+ status: Generated<SubgraphStatus>;
390
396
  definition: Record<string, unknown>;
391
397
  schema_hash: string;
392
398
  handler_path: string;
@@ -403,8 +409,10 @@ interface SubgraphsTable {
403
409
  handler_code: string | null;
404
410
  source_code: string | null;
405
411
  project_id: string | null;
406
- /** Paid (wallet-ghost) deploys expire unless renewed or claimed; NULL = no expiry. */
407
- expires_at: Date | null;
412
+ /** Set while the account's metered reads are refused (spend cap, credits).
413
+ * Both columns are set or both null; `last_error` stays for real errors. */
414
+ billing_paused_at: Date | null;
415
+ billing_paused_code: string | null;
408
416
  /** (event type, contract) probe pairs persisted at deploy for weight classification. */
409
417
  sparse_probe_targets: unknown | null;
410
418
  /** sha256 over everything that shapes rows (schema, handler bundle,
@@ -418,6 +426,9 @@ interface SubgraphsTable {
418
426
  created_at: Generated<Date>;
419
427
  updated_at: Generated<Date>;
420
428
  }
429
+ /** Mirrored by the CHECK on `contracts.abi_status`. */
430
+ declare const ABI_STATUSES: readonly ["pending", "fetched", "unparseable", "failed"];
431
+ type AbiStatus = (typeof ABI_STATUSES)[number];
421
432
  interface ContractsTable {
422
433
  contract_id: string;
423
434
  deployer: string;
@@ -426,17 +437,23 @@ interface ContractsTable {
426
437
  abi: unknown | null;
427
438
  declared_traits: Generated<string[]>;
428
439
  inferred_standards: Generated<string[]>;
429
- abi_status: Generated<string>;
440
+ abi_status: Generated<AbiStatus>;
430
441
  abi_fetched_at: Date | null;
442
+ /** Failed fetches so far; `failed` re-polls until the registry's attempt cap. */
443
+ abi_attempts: Generated<number>;
444
+ /** When a `failed` row is next due; NULL once attempts are exhausted. */
445
+ abi_next_attempt_at: Date | null;
431
446
  created_at: Generated<Date>;
432
447
  }
448
+ /** The only reasons the runtime records; mirrored by a CHECK on `subgraph_gaps.reason`. */
449
+ type GapReason = "block_missing" | "processing_error";
433
450
  interface SubgraphGapsTable {
434
451
  id: Generated<string>;
435
452
  subgraph_id: string;
436
453
  subgraph_name: string;
437
454
  gap_start: number;
438
455
  gap_end: number;
439
- reason: string;
456
+ reason: GapReason;
440
457
  detected_at: Generated<Date>;
441
458
  resolved_at: Date | null;
442
459
  }
@@ -482,12 +499,13 @@ interface SubgraphOperationsTable {
482
499
  * (those checkpoint on subgraphs.last_processed_block). */
483
500
  cursor_block: string | number | bigint | null;
484
501
  }
502
+ type ApiKeyStatus = "active" | "revoked";
485
503
  interface ApiKeysTable {
486
504
  id: Generated<string>;
487
505
  key_hash: string;
488
506
  key_prefix: string;
489
507
  name: string | null;
490
- status: Generated<string>;
508
+ status: Generated<ApiKeyStatus>;
491
509
  rate_limit: Generated<number>;
492
510
  ip_address: string;
493
511
  account_id: string;
@@ -848,6 +866,10 @@ interface SbtcSettlementsTable {
848
866
  last_checked_at: Generated<Date>;
849
867
  /** Set once, when `settlement_confirmed` first flips true. */
850
868
  confirmed_at: Date | null;
869
+ /** Monotonic stamp from `sbtc_settlements_seq`, retaken each time the sweep
870
+ * becomes confirmed. The webhook scan's watermark. BIGINT: a string at
871
+ * runtime. */
872
+ seq: Generated<number | string>;
851
873
  updated_at: Generated<Date>;
852
874
  }
853
875
  type BnsNameEventTopic = "new-name" | "transfer-name" | "renew-name" | "burn-name" | "new-airdrop";
@@ -967,7 +989,9 @@ interface PendingForkBlocksTable {
967
989
  payload: ColumnType<unknown, unknown, unknown>;
968
990
  received_at: Generated<Date>;
969
991
  }
970
- type ObserverJournalStatus = "received" | "processed" | "failed" | "retried";
992
+ /** Mirrored by the CHECK on `observer_journal.status`. */
993
+ declare const OBSERVER_JOURNAL_STATUSES: readonly ["received", "processed", "failed", "retried", "poisoned", "skipped"];
994
+ type ObserverJournalStatus = (typeof OBSERVER_JOURNAL_STATUSES)[number];
971
995
  /**
972
996
  * Exact observer callback receipt. `raw_body` is immutable evidence; the
973
997
  * processing columns are updated only after the current derived-state write
@@ -1002,7 +1026,7 @@ interface StageRegistryTable {
1002
1026
  enabled: Generated<boolean>;
1003
1027
  created_at: Generated<Date>;
1004
1028
  }
1005
- /** One versioned sweep of a stage. */
1029
+ /** One versioned sweep of a stage. Nothing writes this table yet; kept because the receipts and failures tables reference it. */
1006
1030
  interface StageRunsTable {
1007
1031
  id: Generated<string>;
1008
1032
  stage_id: string;
@@ -1136,6 +1160,7 @@ interface Database {
1136
1160
  archive_fetches: ArchiveFetchesTable;
1137
1161
  usage_ledger: UsageLedgerTable;
1138
1162
  account_balance_alerts: AccountBalanceAlertsTable;
1163
+ hosted_stack_state: HostedStackStateTable;
1139
1164
  webhook_incident_alerts: WebhookIncidentAlertsTable;
1140
1165
  cli_device_logins: CliDeviceLoginsTable;
1141
1166
  oauth_clients: OauthClientsTable;
@@ -1219,7 +1244,11 @@ interface UsageLedgerTable {
1219
1244
  * floor to observe past. */
1220
1245
  observed_quantity: string | number | null;
1221
1246
  usd_micros: string | number | bigint;
1247
+ /** True when the whole price was taken; derived from `debited_usd_micros`. */
1222
1248
  debited: Generated<boolean>;
1249
+ /** Amount actually taken from the balance, `0..usd_micros` (bounded the
1250
+ * other way for a negative top-up/grant row). Unpaid = price - this. */
1251
+ debited_usd_micros: Generated<string | number | bigint>;
1223
1252
  source: string;
1224
1253
  /** API key behind a metered read; null for non-read units and older rows. */
1225
1254
  api_key_id: string | null;
@@ -1237,6 +1266,14 @@ interface AccountBalanceAlertsTable {
1237
1266
  sent_2d_at: Date | null;
1238
1267
  sent_stopped_at: Date | null;
1239
1268
  }
1269
+ /** The workload host's report of one account's hosted stack. Written only by
1270
+ * `POST /internal/stack-state`; `reported_at` is the host's observation time. */
1271
+ interface HostedStackStateTable {
1272
+ account_id: string;
1273
+ state: "provisioning" | "running" | "stopped" | "destroyed";
1274
+ stop_reason: "credits" | "cap" | "idle" | null;
1275
+ reported_at: Date;
1276
+ }
1240
1277
  /** Debounce state for the webhook-down email: one row per incident, open
1241
1278
  * while `resolved_at` is null. No preference columns by design. */
1242
1279
  interface WebhookIncidentAlertsTable {
@@ -1373,7 +1410,7 @@ interface SentinelAccountsTable {
1373
1410
  linked_at: Generated<Date>;
1374
1411
  via: "created" | "consent";
1375
1412
  }
1376
- type WebhookStatus = "active" | "paused" | "error";
1413
+ type WebhookStatus = "active" | "paused";
1377
1414
  /** Webhooks react to raw chain events matched directly off the Index/Streams
1378
1415
  * clock. `chain` is the only kind since migration 0159 removed subgraph-row
1379
1416
  * webhooks; the column stays as the discriminator. */
@@ -1399,6 +1436,8 @@ interface WebhooksTable {
1399
1436
  concurrency: Generated<number>;
1400
1437
  circuit_failures: Generated<number>;
1401
1438
  circuit_opened_at: Date | null;
1439
+ /** Why a paused webhook is paused. Set exactly while `status` is `paused`. */
1440
+ pause_reason: WebhookPauseReason | null;
1402
1441
  last_delivery_at: Date | null;
1403
1442
  last_success_at: Date | null;
1404
1443
  last_error: string | null;
@@ -1409,6 +1448,10 @@ interface WebhooksTable {
1409
1448
  updated_at: Generated<Date>;
1410
1449
  }
1411
1450
  type OutboxStatus = "pending" | "delivered" | "dead";
1451
+ /** Why a row is dead: retries ran out, or a reorg removed its event. An
1452
+ * orphaned row stays dead; requeueing it would resend an event the chain no
1453
+ * longer contains. */
1454
+ type DeadReason = "exhausted" | "orphaned";
1412
1455
  interface WebhookOutboxTable {
1413
1456
  id: Generated<string>;
1414
1457
  webhook_id: string;
@@ -1438,6 +1481,8 @@ interface WebhookOutboxTable {
1438
1481
  * into an orphaned fork. Null otherwise — delivery failures track their
1439
1482
  * history on `webhooks.last_error`, not per-row. */
1440
1483
  last_error: string | null;
1484
+ /** Set exactly while `status` is `dead`. */
1485
+ dead_reason: DeadReason | null;
1441
1486
  created_at: Generated<Date>;
1442
1487
  }
1443
1488
  type WebhookReplayStatus = "scanning" | "running" | "done" | "failed";
@@ -1487,6 +1532,13 @@ interface TriggerEvaluatorStateTable {
1487
1532
  /** Watermark for the async sBTC settlement-confirmed webhook scan; null until
1488
1533
  * the evaluator fast-forwards it on first run. */
1489
1534
  last_settlement_scan_at: ColumnType<Date | null, Date | null | undefined, Date | null>;
1535
+ /** `sbtc_settlements.seq` watermark. Null until the first settlement row is
1536
+ * scanned; `last_settlement_scan_at` is the forward-only floor until then. */
1537
+ last_settlement_scan_seq: ColumnType<bigint | null, bigint | number | null | undefined, bigint | number | null>;
1538
+ /** Counts reorg rewinds. The evaluator checks it under the row lock in the
1539
+ * transaction that emits a batch and advances the cursor, so a reorg that
1540
+ * lands mid-tick rolls the batch back. */
1541
+ reorg_generation: ColumnType<bigint, bigint | number | undefined, bigint | number>;
1490
1542
  /** Streams cursor (`<block_height>:<event_index>`) for the Bitcoin (Runes)
1491
1543
  * chain-trigger evaluator (plan 060) — a separate clock from
1492
1544
  * `last_processed_block` (Stacks). Null until the evaluator fast-forwards
@@ -1781,6 +1833,7 @@ declare function runRules<Input>(rules: InsightRule<Input>[], input: Input, reso
1781
1833
  id: string
1782
1834
  }, opts?: {
1783
1835
  active?: boolean
1836
+ keep?: readonly string[]
1784
1837
  }): {
1785
1838
  fired: DetectedInsight[]
1786
1839
  evaluated: EvaluatedKey[]
@@ -1106,6 +1106,8 @@ var lag = {
1106
1106
  evaluate(input) {
1107
1107
  if (input.subgraph.status !== "active")
1108
1108
  return null;
1109
+ if (input.subgraph.billingPausedAt)
1110
+ return null;
1109
1111
  const newest = lagSamples(input).slice(0, SUBGRAPH_LAG_SNAPSHOTS);
1110
1112
  if (newest.length < SUBGRAPH_LAG_SNAPSHOTS)
1111
1113
  return null;
@@ -1178,7 +1180,7 @@ var SUBGRAPH_RULES = [
1178
1180
  lag
1179
1181
  ];
1180
1182
  async function loadSubgraphInputs(db, now) {
1181
- const subgraphs = await db.selectFrom("subgraphs").select(["id", "name", "status"]).execute();
1183
+ const subgraphs = await db.selectFrom("subgraphs").select(["id", "name", "status", "billing_paused_at"]).execute();
1182
1184
  if (subgraphs.length === 0)
1183
1185
  return [];
1184
1186
  const since = new Date(now.getTime() - 25 * HOUR_MS2);
@@ -1200,7 +1202,12 @@ async function loadSubgraphInputs(db, now) {
1200
1202
  `.execute(db);
1201
1203
  return subgraphs.map((subgraph) => ({
1202
1204
  now,
1203
- subgraph,
1205
+ subgraph: {
1206
+ id: subgraph.id,
1207
+ name: subgraph.name,
1208
+ status: subgraph.status,
1209
+ billingPausedAt: subgraph.billing_paused_at
1210
+ },
1204
1211
  snapshots: snapshots.filter((s) => s.subgraph_id === subgraph.id),
1205
1212
  errorGroups: groups.rows.filter((g) => g.subgraph_name === subgraph.name).slice(0, ERROR_GROUPS_SHOWN).map((g) => ({
1206
1213
  message: g.message,
@@ -1218,6 +1225,36 @@ async function loadSubgraphInputs(db, now) {
1218
1225
 
1219
1226
  // src/insights/webhook-rules.ts
1220
1227
  import { sql as sql4 } from "kysely";
1228
+
1229
+ // src/webhooks/health.ts
1230
+ var DOWN_MIN_MS = 15 * 60000;
1231
+ var ms = (d) => typeof d === "string" ? Date.parse(d) : d.getTime();
1232
+ function pauseReasonOf(w) {
1233
+ if (w.status !== "paused")
1234
+ return null;
1235
+ if (w.pauseReason)
1236
+ return w.pauseReason;
1237
+ return w.circuitOpenedAt ? "circuit" : "user";
1238
+ }
1239
+ function isReceiverDown(w, now) {
1240
+ if (pauseReasonOf(w) === "user")
1241
+ return false;
1242
+ if (w.circuitFailures < DOWN_MIN_CONSECUTIVE)
1243
+ return false;
1244
+ return now - ms(w.lastSuccessAt ?? w.createdAt) >= DOWN_MIN_MS;
1245
+ }
1246
+ function webhookHealth(w, now) {
1247
+ const reason = pauseReasonOf(w);
1248
+ if (reason === "user")
1249
+ return "paused_user";
1250
+ if (reason === "circuit")
1251
+ return "paused_circuit";
1252
+ if (isReceiverDown(w, now))
1253
+ return "down";
1254
+ return w.circuitFailures > 0 ? "failing" : "ok";
1255
+ }
1256
+
1257
+ // src/insights/webhook-rules.ts
1221
1258
  var MINUTE_MS = 60000;
1222
1259
  var DAY_MS = 86400000;
1223
1260
  var BUCKET_MS = 10 * MINUTE_MS;
@@ -2089,6 +2126,8 @@ async function loadWebhookInputs(db, now, abiDeps) {
2089
2126
  "id",
2090
2127
  "name",
2091
2128
  "status",
2129
+ "pause_reason",
2130
+ "circuit_failures",
2092
2131
  "url",
2093
2132
  "triggers",
2094
2133
  "timeout_ms",
@@ -2251,6 +2290,13 @@ async function loadWebhookInputs(db, now, abiDeps) {
2251
2290
  id: w.id,
2252
2291
  name: w.name,
2253
2292
  status: w.status,
2293
+ health: webhookHealth({
2294
+ status: w.status,
2295
+ pauseReason: w.pause_reason,
2296
+ circuitFailures: w.circuit_failures,
2297
+ lastSuccessAt: w.last_success_at,
2298
+ createdAt: w.created_at
2299
+ }, nowMs),
2254
2300
  url: w.url,
2255
2301
  triggers: w.triggers,
2256
2302
  timeoutMs: w.timeout_ms,
@@ -2296,7 +2342,8 @@ function runRules2(rules, input, resource, opts = {}) {
2296
2342
  if (rule.skip?.(input))
2297
2343
  continue;
2298
2344
  const key = { kind: resource.kind, id: resource.id, rule: rule.id };
2299
- const result = opts.active === false ? null : rule.evaluate(input);
2345
+ const inactive = opts.active === false && !opts.keep?.includes(rule.id);
2346
+ const result = inactive ? null : rule.evaluate(input);
2300
2347
  evaluated.push(key);
2301
2348
  if (result)
2302
2349
  fired.push(result);
@@ -2323,7 +2370,10 @@ async function evaluateTenantInsights(db, deps = {}) {
2323
2370
  const fired = [];
2324
2371
  const evaluated = [];
2325
2372
  for (const input of webhookInputs) {
2326
- const result = runRules2(WEBHOOK_RULES, input, { kind: "webhook", id: input.webhook.id }, { active: input.webhook.status !== "paused" });
2373
+ const result = runRules2(WEBHOOK_RULES, input, { kind: "webhook", id: input.webhook.id }, {
2374
+ active: input.webhook.health !== "paused_user" && input.webhook.health !== "paused_circuit",
2375
+ keep: input.webhook.health === "paused_circuit" ? ["receiver_down"] : []
2376
+ });
2327
2377
  fired.push(...result.fired);
2328
2378
  evaluated.push(...result.evaluated);
2329
2379
  }
@@ -2422,5 +2472,5 @@ export {
2422
2472
  utcTime
2423
2473
  };
2424
2474
 
2425
- //# debugId=A21ED385DD61B76864756E2164756E21
2475
+ //# debugId=9B78F5D8116C10C164756E2164756E21
2426
2476
  //# sourceMappingURL=index.js.map