@secondlayer/shared 18.0.2 → 19.0.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 (43) hide show
  1. package/dist/src/archive/range-digest.d.ts +10 -0
  2. package/dist/src/archive/semantic-digest-builder.d.ts +10 -0
  3. package/dist/src/coverage/index.d.ts +11 -341
  4. package/dist/src/coverage/index.js +2 -751
  5. package/dist/src/coverage/index.js.map +4 -13
  6. package/dist/src/db/index.d.ts +12 -1
  7. package/dist/src/db/index.js +2 -1
  8. package/dist/src/db/index.js.map +4 -4
  9. package/dist/src/db/queries/api-keys.d.ts +38 -0
  10. package/dist/src/db/queries/api-keys.js +89 -0
  11. package/dist/src/db/queries/api-keys.js.map +11 -0
  12. package/dist/src/db/queries/chain-reorgs.d.ts +10 -0
  13. package/dist/src/db/queries/chain-reorgs.js +2 -1
  14. package/dist/src/db/queries/chain-reorgs.js.map +4 -4
  15. package/dist/src/db/queries/contracts.d.ts +10 -0
  16. package/dist/src/db/queries/contracts.js.map +1 -1
  17. package/dist/src/db/queries/instance.d.ts +10 -0
  18. package/dist/src/db/queries/integrity.d.ts +10 -0
  19. package/dist/src/db/queries/subgraph-gaps.d.ts +10 -0
  20. package/dist/src/db/queries/subgraph-operations.d.ts +10 -0
  21. package/dist/src/db/queries/subgraphs.d.ts +10 -0
  22. package/dist/src/db/queries/sync-scope.d.ts +10 -0
  23. package/dist/src/db/queries/webhook-replays.d.ts +10 -0
  24. package/dist/src/db/queries/webhooks.d.ts +10 -0
  25. package/dist/src/db/schema.d.ts +11 -1
  26. package/dist/src/db/schema.js.map +1 -1
  27. package/dist/src/index.d.ts +12 -1
  28. package/dist/src/index.js +2 -1
  29. package/dist/src/index.js.map +4 -4
  30. package/dist/src/insights/index.d.ts +10 -0
  31. package/dist/src/leader.js +2 -1
  32. package/dist/src/leader.js.map +4 -4
  33. package/dist/src/node/local-client.d.ts +10 -0
  34. package/dist/src/queue/listener.js +2 -1
  35. package/dist/src/queue/listener.js.map +4 -4
  36. package/dist/src/runtime/index.d.ts +1 -120
  37. package/dist/src/runtime/index.js +1 -310
  38. package/dist/src/runtime/index.js.map +3 -7
  39. package/dist/src/streams-rows/index.d.ts +0 -12
  40. package/dist/src/streams-rows/index.js +2 -3
  41. package/dist/src/streams-rows/index.js.map +8 -8
  42. package/migrations/0217_usage_monthly_totals.ts +41 -0
  43. package/package.json +6 -2
@@ -0,0 +1,89 @@
1
+ // src/db/queries/api-keys.ts
2
+ import {
3
+ sql as sql2
4
+ } from "kysely";
5
+
6
+ // src/db/transition.ts
7
+ import { sql } from "kysely";
8
+ function defineMachine(def) {
9
+ const canTransition = (from, to) => def.transitions[from]?.includes(to) ?? false;
10
+ return {
11
+ states: def.states,
12
+ canTransition,
13
+ assert(from, to) {
14
+ if (!canTransition(from, to)) {
15
+ throw new Error(`illegal transition ${from} -> ${to}`);
16
+ }
17
+ }
18
+ };
19
+ }
20
+ async function casTransition(db, t) {
21
+ const column = sql.id(t.column ?? "status");
22
+ const assignments = [sql`${column} = ${t.to}`];
23
+ if (t.stampUpdatedAt !== false)
24
+ assignments.push(sql`updated_at = now()`);
25
+ for (const [key, value] of Object.entries(t.set ?? {})) {
26
+ assignments.push(sql`${sql.id(key)} = ${value}`);
27
+ }
28
+ const returning = t.returning ? sql.join(t.returning.map((c) => sql.id(c))) : sql.raw("*");
29
+ const { rows } = await sql`
30
+ UPDATE ${sql.table(t.table)}
31
+ SET ${sql.join(assignments)}
32
+ WHERE ${sql.id(t.key ?? "id")} = ${t.id} AND ${column} = ANY(${sql.val([...t.from])})
33
+ RETURNING ${returning}
34
+ `.execute(db);
35
+ return rows[0] ?? null;
36
+ }
37
+
38
+ // src/db/queries/api-keys.ts
39
+ var KEY_STATES = [
40
+ "active",
41
+ "revoked"
42
+ ];
43
+ function keyLiveness(row, now = new Date) {
44
+ if (row.status !== "active")
45
+ return "revoked";
46
+ if (row.expires_at && row.expires_at.getTime() <= now.getTime()) {
47
+ return "expired";
48
+ }
49
+ return "live";
50
+ }
51
+ function isKeyLive(row, now = new Date) {
52
+ return keyLiveness(row, now) === "live";
53
+ }
54
+ function notExpiredWhere(now) {
55
+ return (eb) => {
56
+ const at = now ?? sql2`now()`;
57
+ return eb.or([eb("expires_at", "is", null), eb("expires_at", ">", at)]);
58
+ };
59
+ }
60
+ function liveKeyWhere(now) {
61
+ return (eb) => eb.and([eb("status", "=", "active"), notExpiredWhere(now)(eb)]);
62
+ }
63
+ var apiKeyMachine = defineMachine({
64
+ states: KEY_STATES,
65
+ transitions: { active: ["revoked"] }
66
+ });
67
+ function revokeApiKey(db, id, now = new Date) {
68
+ return casTransition(db, {
69
+ table: "api_keys",
70
+ id,
71
+ from: ["active"],
72
+ to: "revoked",
73
+ set: { revoked_at: now },
74
+ stampUpdatedAt: false,
75
+ returning: ["id"]
76
+ });
77
+ }
78
+ export {
79
+ KEY_STATES,
80
+ apiKeyMachine,
81
+ isKeyLive,
82
+ keyLiveness,
83
+ liveKeyWhere,
84
+ notExpiredWhere,
85
+ revokeApiKey
86
+ };
87
+
88
+ //# debugId=A19CF0ED6CAF1F5A64756E2164756E21
89
+ //# sourceMappingURL=api-keys.js.map
@@ -0,0 +1,11 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/db/queries/api-keys.ts", "../src/db/transition.ts"],
4
+ "sourcesContent": [
5
+ "import {\n\ttype Expression,\n\ttype ExpressionBuilder,\n\ttype Kysely,\n\ttype SqlBool,\n\tsql,\n} from \"kysely\";\nimport { type Machine, casTransition, defineMachine } from \"../transition.ts\";\nimport type { ApiKeyStatus } from \"../types.ts\";\n\n/** Stored states of `api_keys.status`, mirrored by `api_keys_status_check`. */\nexport const KEY_STATES = [\n\t\"active\",\n\t\"revoked\",\n] as const satisfies readonly ApiKeyStatus[];\n\n/** What a key is right now: `expired` is derived from `expires_at`, never stored. */\nexport type KeyLiveness = \"live\" | \"revoked\" | \"expired\";\n\ntype KeyRow = { status: ApiKeyStatus; expires_at?: Date | null };\n\n/** The one definition of \"this key may authenticate\". Every reader goes\n * through here (or `liveKeyWhere`, its SQL twin); no inline copies. */\nexport function keyLiveness(row: KeyRow, now: Date = new Date()): KeyLiveness {\n\tif (row.status !== \"active\") return \"revoked\";\n\tif (row.expires_at && row.expires_at.getTime() <= now.getTime()) {\n\t\treturn \"expired\";\n\t}\n\treturn \"live\";\n}\n\nexport function isKeyLive(row: KeyRow, now: Date = new Date()): boolean {\n\treturn keyLiveness(row, now) === \"live\";\n}\n\n/** Not past `expires_at`, whatever the status (a key list hides expired keys\n * but still shows revoked ones). Without `now` the database clock decides. */\nexport function notExpiredWhere(now?: Date) {\n\treturn (\n\t\t// biome-ignore lint/suspicious/noExplicitAny: used against api_keys from any query shape\n\t\teb: ExpressionBuilder<any, any>,\n\t): Expression<SqlBool> => {\n\t\tconst at = now ?? sql<Date>`now()`;\n\t\treturn eb.or([eb(\"expires_at\", \"is\", null), eb(\"expires_at\", \">\", at)]);\n\t};\n}\n\n/** SQL twin of `isKeyLive` for `api_keys`, as a `.where(...)` callback:\n * active and not expired. */\nexport function liveKeyWhere(now?: Date) {\n\treturn (\n\t\t// biome-ignore lint/suspicious/noExplicitAny: used against api_keys from any query shape\n\t\teb: ExpressionBuilder<any, any>,\n\t): Expression<SqlBool> =>\n\t\teb.and([eb(\"status\", \"=\", \"active\"), notExpiredWhere(now)(eb)]);\n}\n\n/** Keys only ever move active -> revoked; revoked is final. */\nexport const apiKeyMachine: Machine<ApiKeyStatus> = defineMachine({\n\tstates: KEY_STATES,\n\ttransitions: { active: [\"revoked\"] },\n});\n\n/** Revoke one key if it is still active. `null` = already revoked or gone (a lost race). */\nexport function revokeApiKey(\n\t// biome-ignore lint/suspicious/noExplicitAny: accepts Kysely<Database> and Transaction<Database>\n\tdb: Kysely<any>,\n\tid: string,\n\tnow: Date = new Date(),\n): Promise<{ id: string } | null> {\n\treturn casTransition<ApiKeyStatus, { id: string }>(db, {\n\t\ttable: \"api_keys\",\n\t\tid,\n\t\tfrom: [\"active\"],\n\t\tto: \"revoked\",\n\t\tset: { revoked_at: now },\n\t\tstampUpdatedAt: false,\n\t\treturning: [\"id\"],\n\t});\n}\n",
6
+ "import { type Kysely, sql } from \"kysely\";\n\n/**\n * The one convention for state machines: states are a const array (mirrored by\n * a DB CHECK), transitions are a table next to the states, and every status\n * write goes through `casTransition`.\n */\n\nexport interface Machine<S extends string> {\n\treadonly states: readonly S[];\n\tcanTransition(from: S, to: S): boolean;\n\t/** Throws on an illegal move. */\n\tassert(from: S, to: S): void;\n}\n\n/** Pure transition table. `transitions` lists, per state, the states it may move to. */\nexport function defineMachine<const S extends string>(def: {\n\tstates: readonly S[];\n\ttransitions: { readonly [K in S]?: readonly S[] };\n}): Machine<S> {\n\tconst canTransition = (from: S, to: S) =>\n\t\tdef.transitions[from]?.includes(to) ?? false;\n\treturn {\n\t\tstates: def.states,\n\t\tcanTransition,\n\t\tassert(from, to) {\n\t\t\tif (!canTransition(from, to)) {\n\t\t\t\tthrow new Error(`illegal transition ${from} -> ${to}`);\n\t\t\t}\n\t\t},\n\t};\n}\n\nexport interface CasTransition<S extends string> {\n\ttable: string;\n\t/** Value of the row key. */\n\tid: string | number;\n\t/** Row key column, `id` unless the table is addressed by another unique column (`name`). */\n\tkey?: string;\n\t/** Status column, `status` unless the machine lives in another column. */\n\tcolumn?: string;\n\t/** The row moves only if it is currently in one of these states. */\n\tfrom: readonly S[];\n\tto: S;\n\t/** Extra columns written in the same statement. Wrap jsonb values with `jsonb()`. */\n\tset?: Record<string, unknown>;\n\t/** Stamp `updated_at = now()`. Pass `false` for tables without that column. */\n\tstampUpdatedAt?: boolean;\n\t/** Columns to return, `*` unless the row carries a large payload (`[\"sequence\"]`). */\n\treturning?: readonly string[];\n}\n\n/**\n * Compare-and-swap a status column: `UPDATE ... WHERE key = ? AND column = ANY(from)`.\n * Returns the updated row (or the `returning` columns), or `null` when the row was missing or not in a `from`\n * state (a lost race). The caller decides what `null` means; usually log and stop.\n * Works with `db` and inside a transaction (`trx`).\n */\nexport async function casTransition<\n\tS extends string,\n\t// biome-ignore lint/suspicious/noExplicitAny: dynamic table name, row shape is the caller's\n\tRow = Record<string, any>,\n>(\n\t// biome-ignore lint/suspicious/noExplicitAny: accepts Kysely<Database> and Transaction<Database>\n\tdb: Kysely<any>,\n\tt: CasTransition<S>,\n): Promise<Row | null> {\n\tconst column = sql.id(t.column ?? \"status\");\n\tconst assignments = [sql`${column} = ${t.to}`];\n\tif (t.stampUpdatedAt !== false) assignments.push(sql`updated_at = now()`);\n\tfor (const [key, value] of Object.entries(t.set ?? {})) {\n\t\tassignments.push(sql`${sql.id(key)} = ${value}`);\n\t}\n\n\tconst returning = t.returning\n\t\t? sql.join(t.returning.map((c) => sql.id(c)))\n\t\t: sql.raw(\"*\");\n\n\tconst { rows } = await sql<Row>`\n\t\tUPDATE ${sql.table(t.table)}\n\t\tSET ${sql.join(assignments)}\n\t\tWHERE ${sql.id(t.key ?? \"id\")} = ${t.id} AND ${column} = ANY(${sql.val([...t.from])})\n\t\tRETURNING ${returning}\n\t`.execute(db);\n\treturn rows[0] ?? null;\n}\n"
7
+ ],
8
+ "mappings": ";AAAA;AAAA,SAKC;AAAA;;;ACLD;AAgBO,SAAS,aAAqC,CAAC,KAGvC;AAAA,EACd,MAAM,gBAAgB,CAAC,MAAS,OAC/B,IAAI,YAAY,OAAO,SAAS,EAAE,KAAK;AAAA,EACxC,OAAO;AAAA,IACN,QAAQ,IAAI;AAAA,IACZ;AAAA,IACA,MAAM,CAAC,MAAM,IAAI;AAAA,MAChB,IAAI,CAAC,cAAc,MAAM,EAAE,GAAG;AAAA,QAC7B,MAAM,IAAI,MAAM,sBAAsB,WAAW,IAAI;AAAA,MACtD;AAAA;AAAA,EAEF;AAAA;AA4BD,eAAsB,aAIrB,CAEA,IACA,GACsB;AAAA,EACtB,MAAM,SAAS,IAAI,GAAG,EAAE,UAAU,QAAQ;AAAA,EAC1C,MAAM,cAAc,CAAC,MAAM,YAAY,EAAE,IAAI;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Y;AAAA,EACxC,OAAO,CAEN,OAEA,GAAG,IAAI,CAAC,GAAG,UAAU,KAAK,QAAQ,GAAG,gBAAgB,GAAG,EAAE,EAAE,CAAC,CAAC;AAAA;AAIzD,IAAM,gBAAuC,cAAc;AAAA,EACjE,QAAQ;AAAA,EACR,aAAa,EAAE,QAAQ,CAAC,SAAS,EAAE;AACpC,CAAC;AAGM,SAAS,YAAY,CAE3B,IACA,IACA,MAAY,IAAI,MACiB;AAAA,EACjC,OAAO,cAA4C,IAAI;AAAA,IACtD,OAAO;AAAA,IACP;AAAA,IACA,MAAM,CAAC,QAAQ;AAAA,IACf,IAAI;AAAA,IACJ,KAAK,EAAE,YAAY,IAAI;AAAA,IACvB,gBAAgB;AAAA,IAChB,WAAW,CAAC,IAAI;AAAA,EACjB,CAAC;AAAA;",
9
+ "debugId": "A19CF0ED6CAF1F5A64756E2164756E21",
10
+ "names": []
11
+ }
@@ -873,6 +873,7 @@ interface Database {
873
873
  stage_failures: StageFailuresTable;
874
874
  archive_fetches: ArchiveFetchesTable;
875
875
  usage_ledger: UsageLedgerTable;
876
+ usage_monthly_totals: UsageMonthlyTotalsTable;
876
877
  account_balance_alerts: AccountBalanceAlertsTable;
877
878
  hosted_stack_state: HostedStackStateTable;
878
879
  webhook_incident_alerts: WebhookIncidentAlertsTable;
@@ -939,6 +940,15 @@ interface ArchiveFetchesTable {
939
940
  via_allowance: Generated<boolean>;
940
941
  charged_at: Generated<Date>;
941
942
  }
943
+ /** Running `usage_ledger` quantity per account, unit and UTC month of
944
+ * `occurred_at` — kept in step by `claimLedgerEntry`. */
945
+ interface UsageMonthlyTotalsTable {
946
+ account_id: string;
947
+ unit: string;
948
+ /** `YYYY-MM`, UTC. */
949
+ month: string;
950
+ quantity: Generated<string | number | bigint>;
951
+ }
942
952
  /**
943
953
  * One metered ledger for every billable unit (archive partitions, hosted
944
954
  * Index/Streams rows, and future hosted-stack meters). Append-only, written
@@ -744,6 +744,7 @@ var TABLE_TO_DB = {
744
744
  account_credits: "target",
745
745
  archive_fetches: "target",
746
746
  usage_ledger: "target",
747
+ usage_monthly_totals: "target",
747
748
  account_balance_alerts: "target",
748
749
  hosted_stack_state: "target",
749
750
  webhook_incident_alerts: "target",
@@ -1059,5 +1060,5 @@ export {
1059
1060
  readChainReorgsSince
1060
1061
  };
1061
1062
 
1062
- //# debugId=63CC1C36192F86A664756E2164756E21
1063
+ //# debugId=6732646F9B2173B364756E2164756E21
1063
1064
  //# sourceMappingURL=chain-reorgs.js.map