@secondlayer/shared 11.7.1 → 11.8.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.
- package/dist/src/archive/copy-loader.d.ts +1 -1
- package/dist/src/archive/copy-loader.js +4 -20
- package/dist/src/archive/copy-loader.js.map +2 -2
- package/dist/src/archive/derived-stage-report.d.ts +1 -1
- package/dist/src/archive/derived-stage-report.js +3 -19
- package/dist/src/archive/derived-stage-report.js.map +2 -2
- package/dist/src/archive/disk-guard.d.ts +1 -1
- package/dist/src/archive/disk-guard.js +3 -19
- package/dist/src/archive/disk-guard.js.map +2 -2
- package/dist/src/archive/instance-diagnosis.d.ts +1 -1
- package/dist/src/archive/instance-diagnosis.js +6 -22
- package/dist/src/archive/instance-diagnosis.js.map +2 -2
- package/dist/src/archive/key-registry.d.ts +1 -1
- package/dist/src/archive/key-registry.js +12 -12
- package/dist/src/archive/key-registry.js.map +1 -1
- package/dist/src/archive/per-height-digest.d.ts +1 -1
- package/dist/src/archive/per-height-digest.js +3 -17
- package/dist/src/archive/per-height-digest.js.map +5 -5
- package/dist/src/archive/progress.d.ts +1 -1
- package/dist/src/archive/progress.js +4 -20
- package/dist/src/archive/progress.js.map +2 -2
- package/dist/src/archive/range-digest.d.ts +28 -3
- package/dist/src/archive/range-digest.js +4 -20
- package/dist/src/archive/range-digest.js.map +2 -2
- package/dist/src/archive/reference.d.ts +1 -1
- package/dist/src/archive/reference.js +14 -12
- package/dist/src/archive/reference.js.map +5 -5
- package/dist/src/archive/root-key.d.ts +1 -1
- package/dist/src/archive/root-key.js +3 -19
- package/dist/src/archive/root-key.js.map +2 -2
- package/dist/src/archive/semantic-digest-builder.d.ts +28 -3
- package/dist/src/archive/semantic-digest-builder.js +5 -19
- package/dist/src/archive/semantic-digest-builder.js.map +5 -5
- package/dist/src/archive/semantic-digest.d.ts +1 -1
- package/dist/src/archive/semantic-digest.js +4 -20
- package/dist/src/archive/semantic-digest.js.map +2 -2
- package/dist/src/archive/status.d.ts +1 -1
- package/dist/src/archive/status.js +4 -20
- package/dist/src/archive/status.js.map +2 -2
- package/dist/src/coverage/index.d.ts +27 -2
- package/dist/src/coverage/index.js +80 -96
- package/dist/src/coverage/index.js.map +2 -2
- package/dist/src/crypto/ed25519.d.ts +1 -1
- package/dist/src/crypto/ed25519.js +13 -13
- package/dist/src/crypto/ed25519.js.map +1 -1
- package/dist/src/crypto/hmac.d.ts +1 -1
- package/dist/src/crypto/hmac.js +9 -9
- package/dist/src/crypto/hmac.js.map +1 -1
- package/dist/src/crypto/secondlayer-webhook.d.ts +1 -1
- package/dist/src/crypto/secondlayer-webhook.js +14 -14
- package/dist/src/crypto/secondlayer-webhook.js.map +2 -2
- package/dist/src/crypto/secrets.d.ts +1 -1
- package/dist/src/crypto/secrets.js +15 -29
- package/dist/src/crypto/secrets.js.map +5 -5
- package/dist/src/crypto/standard-webhooks.d.ts +1 -1
- package/dist/src/crypto/standard-webhooks.js +3 -19
- package/dist/src/crypto/standard-webhooks.js.map +2 -2
- package/dist/src/db/index.d.ts +48 -19
- package/dist/src/db/index.js +41 -55
- package/dist/src/db/index.js.map +6 -6
- package/dist/src/db/jsonb.d.ts +1 -1
- package/dist/src/db/jsonb.js +3 -19
- package/dist/src/db/jsonb.js.map +2 -2
- package/dist/src/db/queries/chain-reorgs.d.ts +27 -2
- package/dist/src/db/queries/chain-reorgs.js +28 -42
- package/dist/src/db/queries/chain-reorgs.js.map +6 -6
- package/dist/src/db/queries/contracts.d.ts +27 -2
- package/dist/src/db/queries/contracts.js +9 -23
- package/dist/src/db/queries/contracts.js.map +5 -5
- package/dist/src/db/queries/instance.d.ts +27 -2
- package/dist/src/db/queries/instance.js +7 -23
- package/dist/src/db/queries/instance.js.map +2 -2
- package/dist/src/db/queries/integrity.d.ts +27 -2
- package/dist/src/db/queries/integrity.js +5 -21
- package/dist/src/db/queries/integrity.js.map +2 -2
- package/dist/src/db/queries/subgraph-gaps.d.ts +27 -2
- package/dist/src/db/queries/subgraph-gaps.js +5 -21
- package/dist/src/db/queries/subgraph-gaps.js.map +2 -2
- package/dist/src/db/queries/subgraph-operations.d.ts +27 -2
- package/dist/src/db/queries/subgraph-operations.js +17 -33
- package/dist/src/db/queries/subgraph-operations.js.map +2 -2
- package/dist/src/db/queries/subgraphs.d.ts +28 -14
- package/dist/src/db/queries/subgraphs.js +15 -37
- package/dist/src/db/queries/subgraphs.js.map +5 -5
- package/dist/src/db/queries/sync-scope.d.ts +27 -2
- package/dist/src/db/queries/sync-scope.js +6 -22
- package/dist/src/db/queries/sync-scope.js.map +2 -2
- package/dist/src/db/queries/webhooks.d.ts +27 -2
- package/dist/src/db/queries/webhooks.js +54 -50
- package/dist/src/db/queries/webhooks.js.map +5 -5
- package/dist/src/db/schema.d.ts +30 -2
- package/dist/src/env.d.ts +1 -1
- package/dist/src/env.js +7 -23
- package/dist/src/env.js.map +2 -2
- package/dist/src/errors.d.ts +4 -4
- package/dist/src/errors.js +15 -31
- package/dist/src/errors.js.map +3 -3
- package/dist/src/index-http.d.ts +1 -1
- package/dist/src/index-http.js +4 -20
- package/dist/src/index-http.js.map +3 -3
- package/dist/src/index-internal-auth.d.ts +4 -7
- package/dist/src/index-internal-auth.js +8 -24
- package/dist/src/index-internal-auth.js.map +3 -3
- package/dist/src/index.d.ts +176 -152
- package/dist/src/index.js +305 -317
- package/dist/src/index.js.map +15 -15
- package/dist/src/leader.d.ts +1 -1
- package/dist/src/leader.js +7 -21
- package/dist/src/leader.js.map +5 -5
- package/dist/src/logger.js +1 -17
- package/dist/src/logger.js.map +2 -2
- package/dist/src/mode.d.ts +1 -1
- package/dist/src/mode.js +5 -21
- package/dist/src/mode.js.map +2 -2
- package/dist/src/node/archive-client.d.ts +1 -1
- package/dist/src/node/archive-client.js +9 -23
- package/dist/src/node/archive-client.js.map +5 -5
- package/dist/src/node/client.d.ts +1 -1
- package/dist/src/node/client.js +4 -18
- package/dist/src/node/client.js.map +5 -5
- package/dist/src/node/consensus.d.ts +1 -1
- package/dist/src/node/consensus.js +5 -21
- package/dist/src/node/consensus.js.map +2 -2
- package/dist/src/node/hiro-client.d.ts +1 -1
- package/dist/src/node/hiro-client.js +1 -17
- package/dist/src/node/hiro-client.js.map +2 -2
- package/dist/src/node/hiro-pg-client.js +1 -17
- package/dist/src/node/hiro-pg-client.js.map +2 -2
- package/dist/src/node/local-client.d.ts +27 -2
- package/dist/src/node/local-client.js +3 -19
- package/dist/src/node/local-client.js.map +2 -2
- package/dist/src/node/nakamoto.d.ts +1 -1
- package/dist/src/node/nakamoto.js +12 -28
- package/dist/src/node/nakamoto.js.map +2 -2
- package/dist/src/queue/listener.d.ts +1 -1
- package/dist/src/queue/listener.js +4 -20
- package/dist/src/queue/listener.js.map +2 -2
- package/dist/src/runtime/index.d.ts +1 -1
- package/dist/src/runtime/index.js +51 -67
- package/dist/src/runtime/index.js.map +2 -2
- package/dist/src/schemas/index.d.ts +8 -4
- package/dist/src/schemas/index.js +64 -41
- package/dist/src/schemas/index.js.map +4 -4
- package/dist/src/schemas/subgraphs.d.ts +1 -4
- package/dist/src/schemas/subgraphs.js +1 -18
- package/dist/src/schemas/subgraphs.js.map +3 -3
- package/dist/src/schemas/webhooks.d.ts +19 -1
- package/dist/src/schemas/webhooks.js +70 -41
- package/dist/src/schemas/webhooks.js.map +3 -3
- package/dist/src/streams-bulk-manifest.d.ts +1 -1
- package/dist/src/streams-bulk-manifest.js +9 -9
- package/dist/src/streams-bulk-manifest.js.map +1 -1
- package/dist/src/streams-rows/index.d.ts +1 -1
- package/dist/src/streams-rows/index.js +32 -48
- package/dist/src/streams-rows/index.js.map +2 -2
- package/dist/src/subgraphs/spec.d.ts +1 -11
- package/dist/src/subgraphs/spec.js +27 -93
- package/dist/src/subgraphs/spec.js.map +3 -3
- package/dist/src/types.d.ts +1 -1
- package/migrations/0136_drop_subgraph_visibility.ts +34 -0
- package/migrations/0137_webhook_outbox_last_error.ts +27 -0
- package/migrations/0138_usage_ledger.ts +46 -0
- package/package.json +1 -1
|
@@ -1,18 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
var __returnValue = (v) => v;
|
|
4
|
-
function __exportSetter(name, newValue) {
|
|
5
|
-
this[name] = __returnValue.bind(null, newValue);
|
|
6
|
-
}
|
|
7
|
-
var __export = (target, all) => {
|
|
8
|
-
for (var name in all)
|
|
9
|
-
__defProp(target, name, {
|
|
10
|
-
get: all[name],
|
|
11
|
-
enumerable: true,
|
|
12
|
-
configurable: true,
|
|
13
|
-
set: __exportSetter.bind(all, name)
|
|
14
|
-
});
|
|
15
|
-
};
|
|
1
|
+
// src/db/queries/subgraphs.ts
|
|
2
|
+
import { sql as sql2 } from "kysely";
|
|
16
3
|
|
|
17
4
|
// src/mode.ts
|
|
18
5
|
var VALID_MODES = [
|
|
@@ -67,7 +54,6 @@ function parseJsonb(value) {
|
|
|
67
54
|
}
|
|
68
55
|
|
|
69
56
|
// src/db/queries/subgraphs.ts
|
|
70
|
-
import { sql as sql2 } from "kysely";
|
|
71
57
|
function pgSchemaName(subgraphName) {
|
|
72
58
|
const safeName = subgraphName.replace(/-/g, "_");
|
|
73
59
|
return `subgraph_${safeName}`;
|
|
@@ -77,13 +63,6 @@ function localSubgraphAccountId(accountId) {
|
|
|
77
63
|
return "";
|
|
78
64
|
return accountId ?? "";
|
|
79
65
|
}
|
|
80
|
-
function pgSchemaNameFor(accountId, subgraphName) {
|
|
81
|
-
if (!accountId)
|
|
82
|
-
return pgSchemaName(subgraphName);
|
|
83
|
-
const accountPrefix = accountId.slice(0, 8).replace(/-/g, "_");
|
|
84
|
-
const safeName = subgraphName.replace(/-/g, "_");
|
|
85
|
-
return `subgraph_${accountPrefix}_${safeName}`;
|
|
86
|
-
}
|
|
87
66
|
async function registerSubgraph(db, data) {
|
|
88
67
|
const accountId = localSubgraphAccountId(data.accountId);
|
|
89
68
|
const values = {
|
|
@@ -197,21 +176,20 @@ async function rewindLiveProgress(db, name, lastProcessedBlock) {
|
|
|
197
176
|
}).where("name", "=", name).execute();
|
|
198
177
|
}
|
|
199
178
|
export {
|
|
200
|
-
|
|
201
|
-
updateSubgraphHandlerPath,
|
|
202
|
-
updateSubgraphExpiry,
|
|
203
|
-
rewindLiveProgress,
|
|
204
|
-
registerSubgraph,
|
|
205
|
-
recordSubgraphProcessed,
|
|
206
|
-
recordLiveProgress,
|
|
207
|
-
recordLiveError,
|
|
208
|
-
pgSchemaNameFor,
|
|
209
|
-
pgSchemaName,
|
|
210
|
-
localSubgraphAccountId,
|
|
211
|
-
listSubgraphs,
|
|
179
|
+
deleteSubgraph,
|
|
212
180
|
getSubgraph,
|
|
213
|
-
|
|
181
|
+
listSubgraphs,
|
|
182
|
+
localSubgraphAccountId,
|
|
183
|
+
pgSchemaName,
|
|
184
|
+
recordLiveError,
|
|
185
|
+
recordLiveProgress,
|
|
186
|
+
recordSubgraphProcessed,
|
|
187
|
+
registerSubgraph,
|
|
188
|
+
rewindLiveProgress,
|
|
189
|
+
updateSubgraphExpiry,
|
|
190
|
+
updateSubgraphHandlerPath,
|
|
191
|
+
updateSubgraphStatus
|
|
214
192
|
};
|
|
215
193
|
|
|
216
|
-
//# debugId=
|
|
194
|
+
//# debugId=BAA950C11B40A13F64756E2164756E21
|
|
217
195
|
//# sourceMappingURL=subgraphs.js.map
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/
|
|
3
|
+
"sources": ["../src/db/queries/subgraphs.ts", "../src/mode.ts", "../src/db/jsonb.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
+
"import { type Kysely, sql } from \"kysely\";\nimport { isPlatformMode } from \"../../mode.ts\";\nimport { jsonb } from \"../jsonb.ts\";\nimport type { Database, Subgraph } from \"../types.ts\";\n\n/** Convert a subgraph name to its PostgreSQL schema name. */\nexport function pgSchemaName(subgraphName: string): string {\n\tconst safeName = subgraphName.replace(/-/g, \"_\");\n\treturn `subgraph_${safeName}`;\n}\n\n/** OSS writes empty account_id — name is the local unique key. */\nexport function localSubgraphAccountId(accountId?: string): string {\n\tif (!isPlatformMode()) return \"\";\n\treturn accountId ?? \"\";\n}\n\nexport async function registerSubgraph(\n\tdb: Kysely<Database>,\n\tdata: {\n\t\tname: string;\n\t\tversion: string;\n\t\tdefinition: Record<string, unknown>;\n\t\tschemaHash: string;\n\t\thandlerPath: string;\n\t\tapiKeyId?: string;\n\t\taccountId?: string;\n\t\tschemaName?: string;\n\t\tstartBlock?: number;\n\t\thandlerCode?: string;\n\t\tsourceCode?: string;\n\t},\n): Promise<Subgraph> {\n\tconst accountId = localSubgraphAccountId(data.accountId);\n\tconst values = {\n\t\tname: data.name,\n\t\tversion: data.version,\n\t\tdefinition: jsonb<Record<string, unknown>>(data.definition),\n\t\tschema_hash: data.schemaHash,\n\t\thandler_path: data.handlerPath,\n\t\taccount_id: accountId,\n\t\thandler_code: data.handlerCode ?? null,\n\t\tsource_code: data.sourceCode ?? null,\n\t\tschema_name: data.schemaName ?? null,\n\t\tstart_block: data.startBlock ?? 0,\n\t};\n\tconst updateSet = {\n\t\tversion: data.version,\n\t\tdefinition: jsonb<Record<string, unknown>>(data.definition),\n\t\tschema_hash: data.schemaHash,\n\t\thandler_path: data.handlerPath,\n\t\thandler_code: data.handlerCode ?? null,\n\t\tsource_code: data.sourceCode ?? null,\n\t\tschema_name: data.schemaName ?? null,\n\t\tstart_block: data.startBlock ?? 0,\n\t\tupdated_at: new Date(),\n\t};\n\n\t// OSS: name is unique. Upsert by name so leftover rows with a non-empty\n\t// account_id (pre-local-namespace deploys) don't insert a second row.\n\tif (!isPlatformMode()) {\n\t\tconst existing = await db\n\t\t\t.selectFrom(\"subgraphs\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"name\", \"=\", data.name)\n\t\t\t.executeTakeFirst();\n\t\tif (existing) {\n\t\t\treturn await db\n\t\t\t\t.updateTable(\"subgraphs\")\n\t\t\t\t.set({ ...updateSet, account_id: \"\" })\n\t\t\t\t.where(\"id\", \"=\", existing.id)\n\t\t\t\t.returningAll()\n\t\t\t\t.executeTakeFirstOrThrow();\n\t\t}\n\t\treturn await db\n\t\t\t.insertInto(\"subgraphs\")\n\t\t\t.values(values)\n\t\t\t.returningAll()\n\t\t\t.executeTakeFirstOrThrow();\n\t}\n\n\treturn await db\n\t\t.insertInto(\"subgraphs\")\n\t\t.values(values)\n\t\t.onConflict((oc) =>\n\t\t\toc.columns([\"name\", \"account_id\"]).doUpdateSet(updateSet),\n\t\t)\n\t\t.returningAll()\n\t\t.executeTakeFirstOrThrow();\n}\n\nexport async function getSubgraph(\n\tdb: Kysely<Database>,\n\tname: string,\n\taccountId?: string,\n): Promise<Subgraph | null> {\n\tlet query = db.selectFrom(\"subgraphs\").selectAll().where(\"name\", \"=\", name);\n\n\tif (isPlatformMode() && accountId !== undefined) {\n\t\tquery = query.where(\"account_id\", \"=\", accountId);\n\t}\n\n\treturn (await query.executeTakeFirst()) ?? null;\n}\n\nexport async function listSubgraphs(\n\tdb: Kysely<Database>,\n\taccountId?: string,\n): Promise<Subgraph[]> {\n\tlet query = db.selectFrom(\"subgraphs\").selectAll();\n\tif (isPlatformMode() && accountId !== undefined) {\n\t\tquery = query.where(\"account_id\", \"=\", accountId);\n\t}\n\treturn query.execute();\n}\n\nexport async function updateSubgraphStatus(\n\tdb: Kysely<Database>,\n\tname: string,\n\tstatus: string,\n\tlastProcessedBlock?: number,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tstatus,\n\t\t\t...(lastProcessedBlock !== undefined\n\t\t\t\t? { last_processed_block: lastProcessedBlock }\n\t\t\t\t: {}),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.execute();\n}\n\n/** Live-walk ERROR write (f069): a block whose handlers ALL failed\n * (`processed === 0 && errors > 0`, `block-processor.ts`'s `applyProgress`)\n * is stamped 'error' and its height is recorded as processed, same as\n * `updateSubgraphStatus(db, name, \"error\", blockHeight)` — except the\n * cursor half of that write now goes through the same conditional `<`\n * guard as {@link recordLiveProgress}. Marking a subgraph 'error' is not\n * itself replay-sensitive, but it shares the `last_processed_block` column\n * with the replay guard: an unconditional write here could regress the\n * cursor a racing (successful) writer already advanced past, which is\n * exactly the regress-then-re-walk loop this guard exists to close. In\n * practice `ctx.rollbackTo` (`runner.ts`) means an all-failed block never\n * flushes writes, so a lost race here is always a silent no-op, never a\n * case that needs `CursorRaceLostError`-style tx abort. Returns whether\n * the write applied. Live path only — reindex/backfill's error stamping\n * goes through {@link updateSubgraphStatus} unconditionally, as before. */\nexport async function recordLiveError(\n\tdb: Kysely<Database>,\n\tname: string,\n\tblockHeight: number,\n): Promise<boolean> {\n\tconst result = await db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tstatus: \"error\",\n\t\t\tlast_processed_block: blockHeight,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.where(\"last_processed_block\", \"<\", blockHeight)\n\t\t.executeTakeFirst();\n\treturn Number(result.numUpdatedRows ?? 0n) > 0;\n}\n\nexport async function recordSubgraphProcessed(\n\tdb: Kysely<Database>,\n\tname: string,\n\tprocessed: number,\n\terrors: number,\n\tlastError?: string,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\ttotal_processed: sql`total_processed + ${processed}`,\n\t\t\ttotal_errors: sql`total_errors + ${errors}`,\n\t\t\t...(lastError\n\t\t\t\t? { last_error: lastError, last_error_at: new Date() }\n\t\t\t\t: {}),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.execute();\n}\n\nexport async function updateSubgraphHandlerPath(\n\tdb: Kysely<Database>,\n\tname: string,\n\thandlerPath: string,\n\topts?: { handlerCode?: string; sourceCode?: string },\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\thandler_path: handlerPath,\n\t\t\t...(opts?.handlerCode != null ? { handler_code: opts.handlerCode } : {}),\n\t\t\t...(opts?.sourceCode != null ? { source_code: opts.sourceCode } : {}),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.execute();\n}\n\nexport async function deleteSubgraph(\n\tdb: Kysely<Database>,\n\tname: string,\n\taccountId?: string,\n): Promise<Subgraph | null> {\n\tconst subgraph = await getSubgraph(db, name, accountId);\n\tif (!subgraph) return null;\n\n\t// Use stored schema_name if available, otherwise compute\n\tconst schemaName = subgraph.schema_name ?? pgSchemaName(name);\n\n\t// Cascade to webhooks: a webhook pointing at a deleted\n\t// subgraph + table will throw `relation does not exist` on every\n\t// subsequent emission. Pause active subs and purge any pending outbox\n\t// rows so receivers don't get phantom replays. We don't delete the\n\t// webhooks themselves — operators may want to repoint them at a\n\t// resurrected subgraph; we just stop them firing.\n\tawait db\n\t\t.updateTable(\"webhooks\")\n\t\t.set({\n\t\t\tstatus: \"paused\",\n\t\t\tlast_error: `Subgraph \"${name}\" deleted; webhook auto-paused.`,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"subgraph_name\", \"=\", name)\n\t\t.execute();\n\tawait db\n\t\t.deleteFrom(\"webhook_outbox\")\n\t\t.where(\"status\", \"=\", \"pending\")\n\t\t.where(\"webhook_id\", \"in\", (qb) =>\n\t\t\tqb.selectFrom(\"webhooks\").select(\"id\").where(\"subgraph_name\", \"=\", name),\n\t\t)\n\t\t.execute();\n\n\t// Drop the subgraph's schema (CASCADE drops all tables within).\n\tawait sql`DROP SCHEMA IF EXISTS ${sql.raw(`\"${schemaName}\"`)} CASCADE`.execute(\n\t\tdb,\n\t);\n\n\t// Remove from registry\n\tawait db.deleteFrom(\"subgraphs\").where(\"id\", \"=\", subgraph.id).execute();\n\n\treturn subgraph;\n}\n\n/** Set or clear a paid subgraph's expiry (NULL = no expiry, e.g. on claim). */\nexport async function updateSubgraphExpiry(\n\tdb: Kysely<Database>,\n\tname: string,\n\taccountId: string,\n\texpiresAt: Date | null,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({ expires_at: expiresAt })\n\t\t.where(\"name\", \"=\", name)\n\t\t.where(\"account_id\", \"=\", accountId)\n\t\t.execute();\n}\n\n/** Live-walk progress write: advances the cursor and PROMOTES toward\n * 'active' (deploying/error → active keeps reorg eligibility, reorg.ts gates\n * on it) but never overwrites an explicit 'reindexing' park — unconditional\n * status stamping let catch-up flap a parked subgraph back into its own path\n * per block, fighting the queued reindex op.\n *\n * `last_processed_block` is now written CONDITIONALLY — `WHERE\n * last_processed_block < lastProcessedBlock`, mirroring\n * `advanceOperationCursor`'s (`subgraph-operations.ts`) comparison shape —\n * and returns whether THIS call actually advanced it. This used to be\n * unconditional by design, on the premise that the only two writers able to\n * advance/rewind a given subgraph's cursor concurrently (the catch-up walk\n * and the reorg handler) serialize on an in-process per-subgraph lock +\n * reorg epoch guard (`packages/subgraphs/src/runtime/catchup.ts`,\n * `subgraphBlockLockHeld` / `reorgEpoch`; f057). That guard is in-process\n * only. The f068 investigation\n * (`docs/internal/audits/asset-holdings-unreproducible-balances-f068.md`)\n * found a cross-process sequence it does not cover: a catch-up leader that\n * loses its advisory-lock connection mid-walk keeps writing (leadership is\n * checked only at walk entry, not per-iteration) while a new leader takes\n * over and walks the same range — both commit increments for overlapping\n * heights, and every regressed cursor write from the laggard re-triggers a\n * full re-walk, growing per-height application without bound. The\n * conditional advance here (paired with the fast-path replay guard armed on\n * the live path in `block-processor.ts`) is now the cross-process\n * guarantee: a block at/below the current cursor can never re-advance it,\n * so a laggard's commits can no longer regress-then-retrigger.\n *\n * This conditionality is why the reorg rewind can no longer go through this\n * function — a rewind's whole point is to move the cursor *backward*, which\n * the `<` guard would silently refuse. Reorg mode calls\n * {@link rewindLiveProgress} instead, which keeps the old unconditional\n * semantics and is safe specifically because the reorg path takes a\n * transaction-scoped advisory lock (`reorg.ts`) other writers can't cross. */\nexport async function recordLiveProgress(\n\tdb: Kysely<Database>,\n\tname: string,\n\tlastProcessedBlock: number,\n): Promise<boolean> {\n\tconst result = await db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tlast_processed_block: lastProcessedBlock,\n\t\t\tstatus: sql`CASE WHEN status = 'reindexing' THEN status ELSE 'active' END`,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.where(\"last_processed_block\", \"<\", lastProcessedBlock)\n\t\t.executeTakeFirst();\n\treturn Number(result.numUpdatedRows ?? 0n) > 0;\n}\n\n/** Reorg-rewind progress write: the OLD unconditional `recordLiveProgress`\n * semantics, verbatim — moves `last_processed_block` to the fork height\n * regardless of its current value, because that is by definition a\n * backward move the conditional `<` guard in `recordLiveProgress` would\n * refuse. Same status-promotion CASE (never unparks an explicit\n * 'reindexing').\n *\n * Callers: exclusively the subgraph-reorg path\n * (`packages/subgraphs/src/runtime/reorg.ts`, via `block-processor.ts`'s\n * `reorgRewind` mode), which is safe from the cross-process race this\n * function reintroduces because it holds a transaction-scoped Postgres\n * advisory lock (`pg_advisory_xact_lock`) for the whole\n * delete+reprocess+rewind sequence — no other writer can interleave a\n * forward write between the rewind and the fork block's reprocess. Do not\n * call this from the live catch-up path. */\nexport async function rewindLiveProgress(\n\tdb: Kysely<Database>,\n\tname: string,\n\tlastProcessedBlock: number,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tlast_processed_block: lastProcessedBlock,\n\t\t\tstatus: sql`CASE WHEN status = 'reindexing' THEN status ELSE 'active' END`,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.execute();\n}\n",
|
|
5
6
|
"/**\n * Instance modes for the Secondlayer platform.\n *\n * - `oss`: self-hosted, single-tenant. No auth middleware, no platform routes\n * (projects, admin). Everything runs against a single `DATABASE_URL`.\n * Intended for `docker compose up`.\n *\n * - `platform`: the metered archive deployment. Magic-link auth, API keys,\n * accounts, credits, and metered `/v1` reads (Index + Streams + subgraphs)\n * against a single shared DB. No paid tier ladder — one metered `free`\n * tier plus first-party internal service credentials.\n */\n\nexport type InstanceMode = \"oss\" | \"platform\";\n\n/** What the operator wrote in the env — `archive` is the honest name for the\n * metered public-archive deployment and aliases `platform` behaviorally. */\nexport type DeclaredInstanceMode = InstanceMode | \"archive\";\n\nconst VALID_MODES: readonly DeclaredInstanceMode[] = [\n\t\"oss\",\n\t\"platform\",\n\t\"archive\",\n];\n\nfunction declaredMode(): DeclaredInstanceMode {\n\tconst raw = process.env.INSTANCE_MODE?.trim().toLowerCase();\n\tif (raw && (VALID_MODES as readonly string[]).includes(raw)) {\n\t\treturn raw as DeclaredInstanceMode;\n\t}\n\treturn \"oss\";\n}\n\n/**\n * Resolve the active instance mode from `process.env.INSTANCE_MODE`.\n * Defaults to `\"oss\"` — the safest default for self-hosters who deploy\n * without setting the variable. `archive` normalizes to `platform` here so\n * every behavioral branch stays a two-way choice; use\n * `getDeclaredInstanceMode()` for display surfaces.\n */\nexport function getInstanceMode(): InstanceMode {\n\tconst declared = declaredMode();\n\treturn declared === \"archive\" ? \"platform\" : declared;\n}\n\n/** The mode as declared in the env, for status/identity surfaces. */\nexport function getDeclaredInstanceMode(): DeclaredInstanceMode {\n\treturn declaredMode();\n}\n\n/**\n * True when public reads are credit-metered (the free window, retention, and\n * credits gates arm). Platform/archive deployments meter by default;\n * self-host never does unless the operator explicitly sets\n * `METERED_READS=true`. `METERED_READS=false` disarms a metered deployment.\n */\nexport function isMeteredReads(): boolean {\n\tconst override = process.env.METERED_READS?.trim().toLowerCase();\n\tif (override === \"true\") return true;\n\tif (override === \"false\") return false;\n\treturn getInstanceMode() === \"platform\";\n}\n\n/** True when the active mode is `\"platform\"` (shared multi-tenant). */\nexport function isPlatformMode(): boolean {\n\treturn getInstanceMode() === \"platform\";\n}\n\n/** True when the active mode is `\"oss\"` (self-hosted). */\nexport function isOssMode(): boolean {\n\treturn getInstanceMode() === \"oss\";\n}\n",
|
|
6
|
-
"import { type RawBuilder, sql } from \"kysely\";\n\n/**\n * Safely encode a JS value as a JSONB literal for Kysely inserts/updates.\n * Kysely + postgres.js double-encodes JSON when using parameterized queries\n * with ::jsonb casts. This uses sql.raw to inline a properly escaped literal.\n *\n * Generic parameter lets callers set the RawBuilder's output type so they\n * don't need to cast at the insert site. Default is `unknown` — widen at\n * the call site when the column type is narrower, e.g. `jsonb<MyShape>(...)`.\n */\nexport function jsonb<T = unknown>(value: T): RawBuilder<T> {\n\tconst escaped = JSON.stringify(value, (_k, v) =>\n\t\ttypeof v === \"bigint\" ? v.toString() : v,\n\t).replace(/'/g, \"''\");\n\treturn sql`${sql.raw(`'${escaped}'::jsonb`)}`;\n}\n\n/**\n * Safely parse a JSONB value from the database.\n * Handles double-encoded strings where postgres.js returns a JSON string\n * instead of a parsed object.\n */\nexport function parseJsonb<T = unknown>(value: unknown): T {\n\tif (typeof value === \"string\") {\n\t\ttry {\n\t\t\treturn JSON.parse(value) as T;\n\t\t} catch {\n\t\t\treturn value as T;\n\t\t}\n\t}\n\treturn (value ?? {}) as T;\n}\n"
|
|
7
|
-
"import { type Kysely, sql } from \"kysely\";\nimport { isPlatformMode } from \"../../mode.ts\";\nimport { jsonb } from \"../jsonb.ts\";\nimport type { Database, Subgraph } from \"../types.ts\";\n\n/**\n * Convert a subgraph name to its PostgreSQL schema name (legacy form).\n * Pre shared-rip every tenant DB had its own schema namespace so disambiguation\n * was implicit. Kept for oss mode (single-tenant) and legacy-row fallback.\n * Platform-mode deploys use `pgSchemaNameFor(accountId, name)`.\n */\nexport function pgSchemaName(subgraphName: string): string {\n\tconst safeName = subgraphName.replace(/-/g, \"_\");\n\treturn `subgraph_${safeName}`;\n}\n\n/** OSS writes empty account_id — name is the local unique key. */\nexport function localSubgraphAccountId(accountId?: string): string {\n\tif (!isPlatformMode()) return \"\";\n\treturn accountId ?? \"\";\n}\n\n/**\n * Account-scoped schema name. Matches migration 0028's rename pattern:\n * subgraph_{first8charsOfAccountId, dashes-as-underscores}_{name}\n * Empty accountId falls back to legacy form (oss mode).\n */\nexport function pgSchemaNameFor(\n\taccountId: string,\n\tsubgraphName: string,\n): string {\n\tif (!accountId) return pgSchemaName(subgraphName);\n\tconst accountPrefix = accountId.slice(0, 8).replace(/-/g, \"_\");\n\tconst safeName = subgraphName.replace(/-/g, \"_\");\n\treturn `subgraph_${accountPrefix}_${safeName}`;\n}\n\nexport async function registerSubgraph(\n\tdb: Kysely<Database>,\n\tdata: {\n\t\tname: string;\n\t\tversion: string;\n\t\tdefinition: Record<string, unknown>;\n\t\tschemaHash: string;\n\t\thandlerPath: string;\n\t\tapiKeyId?: string;\n\t\taccountId?: string;\n\t\tschemaName?: string;\n\t\tstartBlock?: number;\n\t\thandlerCode?: string;\n\t\tsourceCode?: string;\n\t},\n): Promise<Subgraph> {\n\tconst accountId = localSubgraphAccountId(data.accountId);\n\tconst values = {\n\t\tname: data.name,\n\t\tversion: data.version,\n\t\tdefinition: jsonb<Record<string, unknown>>(data.definition),\n\t\tschema_hash: data.schemaHash,\n\t\thandler_path: data.handlerPath,\n\t\taccount_id: accountId,\n\t\thandler_code: data.handlerCode ?? null,\n\t\tsource_code: data.sourceCode ?? null,\n\t\tschema_name: data.schemaName ?? null,\n\t\tstart_block: data.startBlock ?? 0,\n\t};\n\tconst updateSet = {\n\t\tversion: data.version,\n\t\tdefinition: jsonb<Record<string, unknown>>(data.definition),\n\t\tschema_hash: data.schemaHash,\n\t\thandler_path: data.handlerPath,\n\t\thandler_code: data.handlerCode ?? null,\n\t\tsource_code: data.sourceCode ?? null,\n\t\tschema_name: data.schemaName ?? null,\n\t\tstart_block: data.startBlock ?? 0,\n\t\tupdated_at: new Date(),\n\t};\n\n\t// OSS: name is unique. Upsert by name so leftover rows with a non-empty\n\t// account_id (pre-local-namespace deploys) don't insert a second row.\n\tif (!isPlatformMode()) {\n\t\tconst existing = await db\n\t\t\t.selectFrom(\"subgraphs\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"name\", \"=\", data.name)\n\t\t\t.executeTakeFirst();\n\t\tif (existing) {\n\t\t\treturn await db\n\t\t\t\t.updateTable(\"subgraphs\")\n\t\t\t\t.set({ ...updateSet, account_id: \"\" })\n\t\t\t\t.where(\"id\", \"=\", existing.id)\n\t\t\t\t.returningAll()\n\t\t\t\t.executeTakeFirstOrThrow();\n\t\t}\n\t\treturn await db\n\t\t\t.insertInto(\"subgraphs\")\n\t\t\t.values(values)\n\t\t\t.returningAll()\n\t\t\t.executeTakeFirstOrThrow();\n\t}\n\n\treturn await db\n\t\t.insertInto(\"subgraphs\")\n\t\t.values(values)\n\t\t.onConflict((oc) =>\n\t\t\toc.columns([\"name\", \"account_id\"]).doUpdateSet(updateSet),\n\t\t)\n\t\t.returningAll()\n\t\t.executeTakeFirstOrThrow();\n}\n\nexport async function getSubgraph(\n\tdb: Kysely<Database>,\n\tname: string,\n\taccountId?: string,\n): Promise<Subgraph | null> {\n\tlet query = db.selectFrom(\"subgraphs\").selectAll().where(\"name\", \"=\", name);\n\n\tif (isPlatformMode() && accountId !== undefined) {\n\t\tquery = query.where(\"account_id\", \"=\", accountId);\n\t}\n\n\treturn (await query.executeTakeFirst()) ?? null;\n}\n\nexport async function listSubgraphs(\n\tdb: Kysely<Database>,\n\taccountId?: string,\n): Promise<Subgraph[]> {\n\tlet query = db.selectFrom(\"subgraphs\").selectAll();\n\tif (isPlatformMode() && accountId !== undefined) {\n\t\tquery = query.where(\"account_id\", \"=\", accountId);\n\t}\n\treturn query.execute();\n}\n\nexport async function updateSubgraphStatus(\n\tdb: Kysely<Database>,\n\tname: string,\n\tstatus: string,\n\tlastProcessedBlock?: number,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tstatus,\n\t\t\t...(lastProcessedBlock !== undefined\n\t\t\t\t? { last_processed_block: lastProcessedBlock }\n\t\t\t\t: {}),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.execute();\n}\n\n/** Live-walk ERROR write (f069): a block whose handlers ALL failed\n * (`processed === 0 && errors > 0`, `block-processor.ts`'s `applyProgress`)\n * is stamped 'error' and its height is recorded as processed, same as\n * `updateSubgraphStatus(db, name, \"error\", blockHeight)` — except the\n * cursor half of that write now goes through the same conditional `<`\n * guard as {@link recordLiveProgress}. Marking a subgraph 'error' is not\n * itself replay-sensitive, but it shares the `last_processed_block` column\n * with the replay guard: an unconditional write here could regress the\n * cursor a racing (successful) writer already advanced past, which is\n * exactly the regress-then-re-walk loop this guard exists to close. In\n * practice `ctx.rollbackTo` (`runner.ts`) means an all-failed block never\n * flushes writes, so a lost race here is always a silent no-op, never a\n * case that needs `CursorRaceLostError`-style tx abort. Returns whether\n * the write applied. Live path only — reindex/backfill's error stamping\n * goes through {@link updateSubgraphStatus} unconditionally, as before. */\nexport async function recordLiveError(\n\tdb: Kysely<Database>,\n\tname: string,\n\tblockHeight: number,\n): Promise<boolean> {\n\tconst result = await db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tstatus: \"error\",\n\t\t\tlast_processed_block: blockHeight,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.where(\"last_processed_block\", \"<\", blockHeight)\n\t\t.executeTakeFirst();\n\treturn Number(result.numUpdatedRows ?? 0n) > 0;\n}\n\nexport async function recordSubgraphProcessed(\n\tdb: Kysely<Database>,\n\tname: string,\n\tprocessed: number,\n\terrors: number,\n\tlastError?: string,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\ttotal_processed: sql`total_processed + ${processed}`,\n\t\t\ttotal_errors: sql`total_errors + ${errors}`,\n\t\t\t...(lastError\n\t\t\t\t? { last_error: lastError, last_error_at: new Date() }\n\t\t\t\t: {}),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.execute();\n}\n\nexport async function updateSubgraphHandlerPath(\n\tdb: Kysely<Database>,\n\tname: string,\n\thandlerPath: string,\n\topts?: { handlerCode?: string; sourceCode?: string },\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\thandler_path: handlerPath,\n\t\t\t...(opts?.handlerCode != null ? { handler_code: opts.handlerCode } : {}),\n\t\t\t...(opts?.sourceCode != null ? { source_code: opts.sourceCode } : {}),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.execute();\n}\n\nexport async function deleteSubgraph(\n\tdb: Kysely<Database>,\n\tname: string,\n\taccountId?: string,\n): Promise<Subgraph | null> {\n\tconst subgraph = await getSubgraph(db, name, accountId);\n\tif (!subgraph) return null;\n\n\t// Use stored schema_name if available, otherwise compute\n\tconst schemaName = subgraph.schema_name ?? pgSchemaName(name);\n\n\t// Cascade to webhooks: a webhook pointing at a deleted\n\t// subgraph + table will throw `relation does not exist` on every\n\t// subsequent emission. Pause active subs and purge any pending outbox\n\t// rows so receivers don't get phantom replays. We don't delete the\n\t// webhooks themselves — operators may want to repoint them at a\n\t// resurrected subgraph; we just stop them firing.\n\tawait db\n\t\t.updateTable(\"webhooks\")\n\t\t.set({\n\t\t\tstatus: \"paused\",\n\t\t\tlast_error: `Subgraph \"${name}\" deleted; webhook auto-paused.`,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"subgraph_name\", \"=\", name)\n\t\t.execute();\n\tawait db\n\t\t.deleteFrom(\"webhook_outbox\")\n\t\t.where(\"status\", \"=\", \"pending\")\n\t\t.where(\"webhook_id\", \"in\", (qb) =>\n\t\t\tqb.selectFrom(\"webhooks\").select(\"id\").where(\"subgraph_name\", \"=\", name),\n\t\t)\n\t\t.execute();\n\n\t// Drop the subgraph's schema (CASCADE drops all tables within).\n\tawait sql`DROP SCHEMA IF EXISTS ${sql.raw(`\"${schemaName}\"`)} CASCADE`.execute(\n\t\tdb,\n\t);\n\n\t// Remove from registry\n\tawait db.deleteFrom(\"subgraphs\").where(\"id\", \"=\", subgraph.id).execute();\n\n\treturn subgraph;\n}\n\n/** Set or clear a paid subgraph's expiry (NULL = no expiry, e.g. on claim). */\nexport async function updateSubgraphExpiry(\n\tdb: Kysely<Database>,\n\tname: string,\n\taccountId: string,\n\texpiresAt: Date | null,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({ expires_at: expiresAt })\n\t\t.where(\"name\", \"=\", name)\n\t\t.where(\"account_id\", \"=\", accountId)\n\t\t.execute();\n}\n\n/** Live-walk progress write: advances the cursor and PROMOTES toward\n * 'active' (deploying/error → active keeps reorg eligibility, reorg.ts gates\n * on it) but never overwrites an explicit 'reindexing' park — unconditional\n * status stamping let catch-up flap a parked subgraph back into its own path\n * per block, fighting the queued reindex op.\n *\n * `last_processed_block` is now written CONDITIONALLY — `WHERE\n * last_processed_block < lastProcessedBlock`, mirroring\n * `advanceOperationCursor`'s (`subgraph-operations.ts`) comparison shape —\n * and returns whether THIS call actually advanced it. This used to be\n * unconditional by design, on the premise that the only two writers able to\n * advance/rewind a given subgraph's cursor concurrently (the catch-up walk\n * and the reorg handler) serialize on an in-process per-subgraph lock +\n * reorg epoch guard (`packages/subgraphs/src/runtime/catchup.ts`,\n * `subgraphBlockLockHeld` / `reorgEpoch`; f057). That guard is in-process\n * only. The f068 investigation\n * (`docs/internal/audits/asset-holdings-unreproducible-balances-f068.md`)\n * found a cross-process sequence it does not cover: a catch-up leader that\n * loses its advisory-lock connection mid-walk keeps writing (leadership is\n * checked only at walk entry, not per-iteration) while a new leader takes\n * over and walks the same range — both commit increments for overlapping\n * heights, and every regressed cursor write from the laggard re-triggers a\n * full re-walk, growing per-height application without bound. The\n * conditional advance here (paired with the fast-path replay guard armed on\n * the live path in `block-processor.ts`) is now the cross-process\n * guarantee: a block at/below the current cursor can never re-advance it,\n * so a laggard's commits can no longer regress-then-retrigger.\n *\n * This conditionality is why the reorg rewind can no longer go through this\n * function — a rewind's whole point is to move the cursor *backward*, which\n * the `<` guard would silently refuse. Reorg mode calls\n * {@link rewindLiveProgress} instead, which keeps the old unconditional\n * semantics and is safe specifically because the reorg path takes a\n * transaction-scoped advisory lock (`reorg.ts`) other writers can't cross. */\nexport async function recordLiveProgress(\n\tdb: Kysely<Database>,\n\tname: string,\n\tlastProcessedBlock: number,\n): Promise<boolean> {\n\tconst result = await db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tlast_processed_block: lastProcessedBlock,\n\t\t\tstatus: sql`CASE WHEN status = 'reindexing' THEN status ELSE 'active' END`,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.where(\"last_processed_block\", \"<\", lastProcessedBlock)\n\t\t.executeTakeFirst();\n\treturn Number(result.numUpdatedRows ?? 0n) > 0;\n}\n\n/** Reorg-rewind progress write: the OLD unconditional `recordLiveProgress`\n * semantics, verbatim — moves `last_processed_block` to the fork height\n * regardless of its current value, because that is by definition a\n * backward move the conditional `<` guard in `recordLiveProgress` would\n * refuse. Same status-promotion CASE (never unparks an explicit\n * 'reindexing').\n *\n * Callers: exclusively the subgraph-reorg path\n * (`packages/subgraphs/src/runtime/reorg.ts`, via `block-processor.ts`'s\n * `reorgRewind` mode), which is safe from the cross-process race this\n * function reintroduces because it holds a transaction-scoped Postgres\n * advisory lock (`pg_advisory_xact_lock`) for the whole\n * delete+reprocess+rewind sequence — no other writer can interleave a\n * forward write between the rewind and the fork block's reprocess. Do not\n * call this from the live catch-up path. */\nexport async function rewindLiveProgress(\n\tdb: Kysely<Database>,\n\tname: string,\n\tlastProcessedBlock: number,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tlast_processed_block: lastProcessedBlock,\n\t\t\tstatus: sql`CASE WHEN status = 'reindexing' THEN status ELSE 'active' END`,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.execute();\n}\n"
|
|
7
|
+
"import { type RawBuilder, sql } from \"kysely\";\n\n/**\n * Safely encode a JS value as a JSONB literal for Kysely inserts/updates.\n * Kysely + postgres.js double-encodes JSON when using parameterized queries\n * with ::jsonb casts. This uses sql.raw to inline a properly escaped literal.\n *\n * Generic parameter lets callers set the RawBuilder's output type so they\n * don't need to cast at the insert site. Default is `unknown` — widen at\n * the call site when the column type is narrower, e.g. `jsonb<MyShape>(...)`.\n */\nexport function jsonb<T = unknown>(value: T): RawBuilder<T> {\n\tconst escaped = JSON.stringify(value, (_k, v) =>\n\t\ttypeof v === \"bigint\" ? v.toString() : v,\n\t).replace(/'/g, \"''\");\n\treturn sql`${sql.raw(`'${escaped}'::jsonb`)}`;\n}\n\n/**\n * Safely parse a JSONB value from the database.\n * Handles double-encoded strings where postgres.js returns a JSON string\n * instead of a parsed object.\n */\nexport function parseJsonb<T = unknown>(value: unknown): T {\n\tif (typeof value === \"string\") {\n\t\ttry {\n\t\t\treturn JSON.parse(value) as T;\n\t\t} catch {\n\t\t\treturn value as T;\n\t\t}\n\t}\n\treturn (value ?? {}) as T;\n}\n"
|
|
8
8
|
],
|
|
9
|
-
"mappings": "
|
|
10
|
-
"debugId": "
|
|
9
|
+
"mappings": ";AAAA,gBAAsB;;;ACmBtB,IAAM,cAA+C;AAAA,EACpD;AAAA,EACA;AAAA,EACA;AACD;AAEA,SAAS,YAAY,GAAyB;AAAA,EAC7C,MAAM,MAAM,QAAQ,IAAI,eAAe,KAAK,EAAE,YAAY;AAAA,EAC1D,IAAI,OAAQ,YAAkC,SAAS,GAAG,GAAG;AAAA,IAC5D,OAAO;AAAA,EACR;AAAA,EACA,OAAO;AAAA;AAUD,SAAS,eAAe,GAAiB;AAAA,EAC/C,MAAM,WAAW,aAAa;AAAA,EAC9B,OAAO,aAAa,YAAY,aAAa;AAAA;AAIvC,SAAS,uBAAuB,GAAyB;AAAA,EAC/D,OAAO,aAAa;AAAA;AASd,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AAK,IAAI,EACvB,MAAM,cAAc,KAAK,SAAS,EAClC,QAAQ;AAAA;AAqCX,eAAsB,kBAAkB,CACvC,IACA,MACA,oBACmB;AAAA,EACnB,MAAM,SAAS,MAAM,GACnB,YAAY,WAAW,EACvB,IAAI;AAAA,IACJ,sBAAsB;AAAA,IACtB,QAAQ;AAAA,IACR,YAAY,IAAI;AAAA,EACjB,CAAC,EACA,MAAM,QAAQ,KAAK,IAAI,EACvB,MAAM,wBAAwB,KAAK,kBAAkB,EACrD,iBAAiB;AAAA,EACnB,OAAO,OAAO,OAAO,kBAAkB,EAAE,IAAI;AAAA;AAkB9C,eAAsB,kBAAkB,CACvC,IACA,MACA,oBACgB;AAAA,EAChB,MAAM,GACJ,YAAY,WAAW,EACvB,IAAI;AAAA,IACJ,sBAAsB;AAAA,IACtB,QAAQ;AAAA,IACR,YAAY,IAAI;AAAA,EACjB,CAAC,EACA,MAAM,QAAQ,KAAK,IAAI,EACvB,QAAQ;AAAA;",
|
|
10
|
+
"debugId": "BAA950C11B40A13F64756E2164756E21",
|
|
11
11
|
"names": []
|
|
12
12
|
}
|
|
@@ -163,7 +163,6 @@ interface SubgraphsTable {
|
|
|
163
163
|
handler_code: string | null;
|
|
164
164
|
source_code: string | null;
|
|
165
165
|
project_id: string | null;
|
|
166
|
-
visibility: Generated<string>;
|
|
167
166
|
/** Paid (wallet-ghost) deploys expire unless renewed or claimed; NULL = no expiry. */
|
|
168
167
|
expires_at: Date | null;
|
|
169
168
|
/** (event type, contract) probe pairs persisted at deploy for weight classification. */
|
|
@@ -793,6 +792,7 @@ interface Database {
|
|
|
793
792
|
coverage_segments: CoverageSegmentsTable;
|
|
794
793
|
stage_failures: StageFailuresTable;
|
|
795
794
|
archive_fetches: ArchiveFetchesTable;
|
|
795
|
+
usage_ledger: UsageLedgerTable;
|
|
796
796
|
waitlists: WaitlistsTable;
|
|
797
797
|
waitlist_signups: WaitlistSignupsTable;
|
|
798
798
|
}
|
|
@@ -837,6 +837,27 @@ interface ArchiveFetchesTable {
|
|
|
837
837
|
via_allowance: Generated<boolean>;
|
|
838
838
|
charged_at: Generated<Date>;
|
|
839
839
|
}
|
|
840
|
+
/**
|
|
841
|
+
* One metered ledger for every billable unit (archive partitions, hosted
|
|
842
|
+
* Index/Streams rows, and future hosted-stack meters). Append-only, written
|
|
843
|
+
* only by `meter()`. `idempotency_key` is UNIQUE so a retried submission
|
|
844
|
+
* no-ops instead of double-charging. `debited` is false when the balance
|
|
845
|
+
* (or a spend cap) refused the charge — the row still exists so the gap is
|
|
846
|
+
* visible, never silently dropped. `usd_micros` is negative for a Stripe
|
|
847
|
+
* top-up (`unit: "topup"`).
|
|
848
|
+
*/
|
|
849
|
+
interface UsageLedgerTable {
|
|
850
|
+
id: Generated<string>;
|
|
851
|
+
account_id: string;
|
|
852
|
+
unit: string;
|
|
853
|
+
quantity: string | number | bigint;
|
|
854
|
+
usd_micros: string | number | bigint;
|
|
855
|
+
debited: Generated<boolean>;
|
|
856
|
+
source: string;
|
|
857
|
+
idempotency_key: string;
|
|
858
|
+
occurred_at: Generated<Date>;
|
|
859
|
+
recorded_at: Generated<Date>;
|
|
860
|
+
}
|
|
840
861
|
type WebhookStatus = "active" | "paused" | "error";
|
|
841
862
|
/** Polymorphic webhook mode: `subgraph` reacts to processed table rows;
|
|
842
863
|
* `chain` reacts to raw chain events matched directly off the Index/Streams
|
|
@@ -899,6 +920,10 @@ interface WebhookOutboxTable {
|
|
|
899
920
|
failed_at: Date | null;
|
|
900
921
|
locked_by: string | null;
|
|
901
922
|
locked_until: Date | null;
|
|
923
|
+
/** Set when a reorg marks an in-flight row `dead` instead of retrying it
|
|
924
|
+
* into an orphaned fork. Null otherwise — delivery failures track their
|
|
925
|
+
* history on `webhooks.last_error`, not per-row. */
|
|
926
|
+
last_error: string | null;
|
|
902
927
|
created_at: Generated<Date>;
|
|
903
928
|
}
|
|
904
929
|
interface WebhookDeliveriesTable {
|
|
@@ -994,4 +1019,4 @@ declare function upsertSyncScope(db: Kysely<Database>, scope: SyncScope): Promis
|
|
|
994
1019
|
* restore we can vouch for.
|
|
995
1020
|
*/
|
|
996
1021
|
declare function resolveSyncScope(db: Kysely<Database>, network: string): Promise<SyncScope>;
|
|
997
|
-
export {
|
|
1022
|
+
export { InvalidSyncStartHeightError, SYNC_START_HEIGHT_ENV, getSyncScope, resolveSyncScope, syncStartHeightFromEnv, upsertSyncScope };
|
|
@@ -1,19 +1,3 @@
|
|
|
1
|
-
import { createRequire } from "node:module";
|
|
2
|
-
var __defProp = Object.defineProperty;
|
|
3
|
-
var __returnValue = (v) => v;
|
|
4
|
-
function __exportSetter(name, newValue) {
|
|
5
|
-
this[name] = __returnValue.bind(null, newValue);
|
|
6
|
-
}
|
|
7
|
-
var __export = (target, all) => {
|
|
8
|
-
for (var name in all)
|
|
9
|
-
__defProp(target, name, {
|
|
10
|
-
get: all[name],
|
|
11
|
-
enumerable: true,
|
|
12
|
-
configurable: true,
|
|
13
|
-
set: __exportSetter.bind(all, name)
|
|
14
|
-
});
|
|
15
|
-
};
|
|
16
|
-
|
|
17
1
|
// src/db/queries/sync-scope.ts
|
|
18
2
|
var SYNC_START_HEIGHT_ENV = "SECONDLAYER_SYNC_START_HEIGHT";
|
|
19
3
|
|
|
@@ -104,13 +88,13 @@ async function resolveSyncScope(db, network) {
|
|
|
104
88
|
};
|
|
105
89
|
}
|
|
106
90
|
export {
|
|
107
|
-
|
|
108
|
-
syncStartHeightFromEnv,
|
|
109
|
-
resolveSyncScope,
|
|
110
|
-
getSyncScope,
|
|
91
|
+
InvalidSyncStartHeightError,
|
|
111
92
|
SYNC_START_HEIGHT_ENV,
|
|
112
|
-
|
|
93
|
+
getSyncScope,
|
|
94
|
+
resolveSyncScope,
|
|
95
|
+
syncStartHeightFromEnv,
|
|
96
|
+
upsertSyncScope
|
|
113
97
|
};
|
|
114
98
|
|
|
115
|
-
//# debugId=
|
|
99
|
+
//# debugId=0BAF9C1F28590E5C64756E2164756E21
|
|
116
100
|
//# sourceMappingURL=sync-scope.js.map
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"import type { Kysely } from \"kysely\";\nimport type { BootstrapSource, SyncScope } from \"../../coverage/evaluate.ts\";\nimport type { Database } from \"../types.ts\";\n\n/**\n * The instance's declared sync scope.\n *\n * An instance that starts at height N is not an instance missing the first N\n * blocks — but nothing in the schema said so, so every consumer had to guess\n * from `MIN(height)`. `sync_scopes` records the declaration; this module is the\n * only place that reads it, and it always answers in the `SyncScope` shape the\n * coverage evaluator consumes.\n *\n * `resolveSyncScope` never fails on an instance that predates the table: with\n * no row it derives a scope from what the database already shows, so an\n * existing install keeps working without a backfill dance.\n */\n\n/**\n * Declares a forward-only instance: history below this height is deliberately\n * absent, not lost. Read only when no `sync_scopes` row exists — a recorded\n * scope always wins, because it is the one an operator committed to.\n */\nexport const SYNC_START_HEIGHT_ENV = \"SECONDLAYER_SYNC_START_HEIGHT\";\n\nexport class InvalidSyncStartHeightError extends Error {\n\treadonly name = \"InvalidSyncStartHeightError\";\n\tconstructor(readonly value: string) {\n\t\tsuper(\n\t\t\t`${SYNC_START_HEIGHT_ENV} must be a non-negative integer (got ${value})`,\n\t\t);\n\t}\n}\n\n/**\n * Throws rather than ignoring a malformed value: a typo'd start height that\n * silently falls back to genesis would report a real forward-only instance as\n * an 8M-block gap, which is the exact confusion this table exists to end.\n */\nexport function syncStartHeightFromEnv(\n\tenv: NodeJS.ProcessEnv = process.env,\n): number | null {\n\tconst raw = env[SYNC_START_HEIGHT_ENV];\n\tif (raw === undefined || raw.trim() === \"\") return null;\n\tconst height = Number(raw.trim());\n\tif (!Number.isInteger(height) || height < 0) {\n\t\tthrow new InvalidSyncStartHeightError(raw);\n\t}\n\treturn height;\n}\n\nfunction toScope(row: {\n\tnetwork: string;\n\tstart_height: number | string;\n\ttarget_height: number | string | null;\n\tbootstrap_source: BootstrapSource;\n\tbootstrap_manifest_digest: string | null;\n\tgenesis_hash: string | null;\n}): SyncScope {\n\treturn {\n\t\tnetwork: row.network,\n\t\tstart_height: Number(row.start_height),\n\t\ttarget_height:\n\t\t\trow.target_height === null ? null : Number(row.target_height),\n\t\tbootstrap: {\n\t\t\tsource: row.bootstrap_source,\n\t\t\tmanifest_digest: row.bootstrap_manifest_digest,\n\t\t\tgenesis_hash: row.genesis_hash,\n\t\t},\n\t};\n}\n\nexport async function getSyncScope(\n\tdb: Kysely<Database>,\n\tnetwork: string,\n): Promise<SyncScope | null> {\n\tconst row = await db\n\t\t.selectFrom(\"sync_scopes\")\n\t\t.select([\n\t\t\t\"network\",\n\t\t\t\"start_height\",\n\t\t\t\"target_height\",\n\t\t\t\"bootstrap_source\",\n\t\t\t\"bootstrap_manifest_digest\",\n\t\t\t\"genesis_hash\",\n\t\t])\n\t\t.where(\"network\", \"=\", network)\n\t\t.executeTakeFirst();\n\treturn row ? toScope(row) : null;\n}\n\n/**\n * Record (or restate) the scope for a network. Bootstrap and re-bootstrap are\n * the writers; the upsert is idempotent so re-running a restore over the same\n * archive does not fork the declaration.\n */\nexport async function upsertSyncScope(\n\tdb: Kysely<Database>,\n\tscope: SyncScope,\n): Promise<SyncScope> {\n\tconst row = await db\n\t\t.insertInto(\"sync_scopes\")\n\t\t.values({\n\t\t\tnetwork: scope.network,\n\t\t\tstart_height: scope.start_height,\n\t\t\ttarget_height: scope.target_height,\n\t\t\tbootstrap_source: scope.bootstrap.source,\n\t\t\tbootstrap_manifest_digest: scope.bootstrap.manifest_digest,\n\t\t\tgenesis_hash: scope.bootstrap.genesis_hash,\n\t\t})\n\t\t.onConflict((oc) =>\n\t\t\toc.column(\"network\").doUpdateSet({\n\t\t\t\tstart_height: scope.start_height,\n\t\t\t\ttarget_height: scope.target_height,\n\t\t\t\tbootstrap_source: scope.bootstrap.source,\n\t\t\t\tbootstrap_manifest_digest: scope.bootstrap.manifest_digest,\n\t\t\t\tgenesis_hash: scope.bootstrap.genesis_hash,\n\t\t\t\tupdated_at: new Date(),\n\t\t\t}),\n\t\t)\n\t\t.returning([\n\t\t\t\"network\",\n\t\t\t\"start_height\",\n\t\t\t\"target_height\",\n\t\t\t\"bootstrap_source\",\n\t\t\t\"bootstrap_manifest_digest\",\n\t\t\t\"genesis_hash\",\n\t\t])\n\t\t.executeTakeFirstOrThrow();\n\treturn toScope(row);\n}\n\n/**\n * The persisted scope, or one derived from the database when none was ever\n * recorded.\n *\n * The derivation is deliberately conservative: it claims only what the data\n * already shows (the lowest canonical block, the genesis hash if genesis is\n * present) and never invents provenance — an instance whose history starts\n * above genesis with no recorded bootstrap is an `import`, not an archive\n * restore we can vouch for.\n */\nexport async function resolveSyncScope(\n\tdb: Kysely<Database>,\n\tnetwork: string,\n): Promise<SyncScope> {\n\tconst persisted = await getSyncScope(db, network);\n\tif (persisted) return persisted;\n\n\tconst declaredStart = syncStartHeightFromEnv();\n\tconst lowest = await db\n\t\t.selectFrom(\"blocks\")\n\t\t.select(({ fn }) => fn.min(\"height\").as(\"min\"))\n\t\t.where(\"canonical\", \"=\", true)\n\t\t.executeTakeFirst();\n\tconst lowestStored =\n\t\tlowest?.min === null || lowest?.min === undefined\n\t\t\t? null\n\t\t\t: Number(lowest.min);\n\tconst startHeight = declaredStart ?? lowestStored ?? 0;\n\n\tconst genesis =\n\t\tstartHeight === 0\n\t\t\t? await db\n\t\t\t\t\t.selectFrom(\"blocks\")\n\t\t\t\t\t.select(\"hash\")\n\t\t\t\t\t.where(\"canonical\", \"=\", true)\n\t\t\t\t\t.where(\"height\", \"=\", 0)\n\t\t\t\t\t.executeTakeFirst()\n\t\t\t: undefined;\n\n\treturn {\n\t\tnetwork,\n\t\tstart_height: startHeight,\n\t\ttarget_height: null,\n\t\tbootstrap: {\n\t\t\tsource: startHeight === 0 ? \"genesis\" : \"import\",\n\t\t\tmanifest_digest: null,\n\t\t\tgenesis_hash: genesis?.hash ?? null,\n\t\t},\n\t};\n}\n"
|
|
6
6
|
],
|
|
7
|
-
"mappings": "
|
|
8
|
-
"debugId": "
|
|
7
|
+
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gBAAgB,IAAI,YAAY;AAAA,MACxC,iBAAiB;AAAA,MACjB,cAAc,SAAS,QAAQ;AAAA,IAChC;AAAA,EACD;AAAA;",
|
|
8
|
+
"debugId": "0BAF9C1F28590E5C64756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -153,7 +153,6 @@ interface SubgraphsTable {
|
|
|
153
153
|
handler_code: string | null;
|
|
154
154
|
source_code: string | null;
|
|
155
155
|
project_id: string | null;
|
|
156
|
-
visibility: Generated<string>;
|
|
157
156
|
/** Paid (wallet-ghost) deploys expire unless renewed or claimed; NULL = no expiry. */
|
|
158
157
|
expires_at: Date | null;
|
|
159
158
|
/** (event type, contract) probe pairs persisted at deploy for weight classification. */
|
|
@@ -783,6 +782,7 @@ interface Database {
|
|
|
783
782
|
coverage_segments: CoverageSegmentsTable;
|
|
784
783
|
stage_failures: StageFailuresTable;
|
|
785
784
|
archive_fetches: ArchiveFetchesTable;
|
|
785
|
+
usage_ledger: UsageLedgerTable;
|
|
786
786
|
waitlists: WaitlistsTable;
|
|
787
787
|
waitlist_signups: WaitlistSignupsTable;
|
|
788
788
|
}
|
|
@@ -827,6 +827,27 @@ interface ArchiveFetchesTable {
|
|
|
827
827
|
via_allowance: Generated<boolean>;
|
|
828
828
|
charged_at: Generated<Date>;
|
|
829
829
|
}
|
|
830
|
+
/**
|
|
831
|
+
* One metered ledger for every billable unit (archive partitions, hosted
|
|
832
|
+
* Index/Streams rows, and future hosted-stack meters). Append-only, written
|
|
833
|
+
* only by `meter()`. `idempotency_key` is UNIQUE so a retried submission
|
|
834
|
+
* no-ops instead of double-charging. `debited` is false when the balance
|
|
835
|
+
* (or a spend cap) refused the charge — the row still exists so the gap is
|
|
836
|
+
* visible, never silently dropped. `usd_micros` is negative for a Stripe
|
|
837
|
+
* top-up (`unit: "topup"`).
|
|
838
|
+
*/
|
|
839
|
+
interface UsageLedgerTable {
|
|
840
|
+
id: Generated<string>;
|
|
841
|
+
account_id: string;
|
|
842
|
+
unit: string;
|
|
843
|
+
quantity: string | number | bigint;
|
|
844
|
+
usd_micros: string | number | bigint;
|
|
845
|
+
debited: Generated<boolean>;
|
|
846
|
+
source: string;
|
|
847
|
+
idempotency_key: string;
|
|
848
|
+
occurred_at: Generated<Date>;
|
|
849
|
+
recorded_at: Generated<Date>;
|
|
850
|
+
}
|
|
830
851
|
type WebhookStatus = "active" | "paused" | "error";
|
|
831
852
|
/** Polymorphic webhook mode: `subgraph` reacts to processed table rows;
|
|
832
853
|
* `chain` reacts to raw chain events matched directly off the Index/Streams
|
|
@@ -890,6 +911,10 @@ interface WebhookOutboxTable {
|
|
|
890
911
|
failed_at: Date | null;
|
|
891
912
|
locked_by: string | null;
|
|
892
913
|
locked_until: Date | null;
|
|
914
|
+
/** Set when a reorg marks an in-flight row `dead` instead of retrying it
|
|
915
|
+
* into an orphaned fork. Null otherwise — delivery failures track their
|
|
916
|
+
* history on `webhooks.last_error`, not per-row. */
|
|
917
|
+
last_error: string | null;
|
|
893
918
|
created_at: Generated<Date>;
|
|
894
919
|
}
|
|
895
920
|
interface WebhookDeliveriesTable {
|
|
@@ -1004,4 +1029,4 @@ declare function rotateWebhookSecret(db: Kysely<Database>, accountId: string, id
|
|
|
1004
1029
|
declare function getWebhookSigningSecret(webhook: Webhook): string;
|
|
1005
1030
|
/** Fire `webhooks:changed` notify so the emitter hot-reloads its cache. */
|
|
1006
1031
|
declare function notifyWebhooksChanged(db: Kysely<Database>, accountId: string): Promise<void>;
|
|
1007
|
-
export {
|
|
1032
|
+
export { CreateWebhookInput, CreateWebhookResult, RotateSecretResult, UpdateWebhookInput, createWebhook, deleteWebhook, getWebhook, getWebhookByName, getWebhookSigningSecret, listActiveChainWebhooks, listWebhooks, notifyWebhooksChanged, rotateWebhookSecret, toggleWebhookStatus, updateWebhook };
|
|
@@ -14,49 +14,17 @@ var __export = (target, all) => {
|
|
|
14
14
|
});
|
|
15
15
|
};
|
|
16
16
|
|
|
17
|
-
// src/
|
|
18
|
-
|
|
19
|
-
"oss",
|
|
20
|
-
"platform",
|
|
21
|
-
"archive"
|
|
22
|
-
];
|
|
23
|
-
function declaredMode() {
|
|
24
|
-
const raw = process.env.INSTANCE_MODE?.trim().toLowerCase();
|
|
25
|
-
if (raw && VALID_MODES.includes(raw)) {
|
|
26
|
-
return raw;
|
|
27
|
-
}
|
|
28
|
-
return "oss";
|
|
29
|
-
}
|
|
30
|
-
function getInstanceMode() {
|
|
31
|
-
const declared = declaredMode();
|
|
32
|
-
return declared === "archive" ? "platform" : declared;
|
|
33
|
-
}
|
|
34
|
-
function getDeclaredInstanceMode() {
|
|
35
|
-
return declaredMode();
|
|
36
|
-
}
|
|
37
|
-
function isMeteredReads() {
|
|
38
|
-
const override = process.env.METERED_READS?.trim().toLowerCase();
|
|
39
|
-
if (override === "true")
|
|
40
|
-
return true;
|
|
41
|
-
if (override === "false")
|
|
42
|
-
return false;
|
|
43
|
-
return getInstanceMode() === "platform";
|
|
44
|
-
}
|
|
45
|
-
function isPlatformMode() {
|
|
46
|
-
return getInstanceMode() === "platform";
|
|
47
|
-
}
|
|
48
|
-
function isOssMode() {
|
|
49
|
-
return getInstanceMode() === "oss";
|
|
50
|
-
}
|
|
17
|
+
// src/db/queries/webhooks.ts
|
|
18
|
+
import { sql } from "kysely";
|
|
51
19
|
|
|
52
20
|
// src/crypto/hmac.ts
|
|
53
21
|
var exports_hmac = {};
|
|
54
22
|
__export(exports_hmac, {
|
|
55
|
-
|
|
56
|
-
verifySignature: () => verifySignature,
|
|
57
|
-
signPayload: () => signPayload,
|
|
23
|
+
createSignatureHeader: () => createSignatureHeader,
|
|
58
24
|
generateSecret: () => generateSecret,
|
|
59
|
-
|
|
25
|
+
signPayload: () => signPayload,
|
|
26
|
+
verifySignature: () => verifySignature,
|
|
27
|
+
verifySignatureHeader: () => verifySignatureHeader
|
|
60
28
|
});
|
|
61
29
|
import { createHmac, randomBytes } from "node:crypto";
|
|
62
30
|
function generateSecret() {
|
|
@@ -114,6 +82,43 @@ import {
|
|
|
114
82
|
unlinkSync
|
|
115
83
|
} from "node:fs";
|
|
116
84
|
import { resolve } from "node:path";
|
|
85
|
+
|
|
86
|
+
// src/mode.ts
|
|
87
|
+
var VALID_MODES = [
|
|
88
|
+
"oss",
|
|
89
|
+
"platform",
|
|
90
|
+
"archive"
|
|
91
|
+
];
|
|
92
|
+
function declaredMode() {
|
|
93
|
+
const raw = process.env.INSTANCE_MODE?.trim().toLowerCase();
|
|
94
|
+
if (raw && VALID_MODES.includes(raw)) {
|
|
95
|
+
return raw;
|
|
96
|
+
}
|
|
97
|
+
return "oss";
|
|
98
|
+
}
|
|
99
|
+
function getInstanceMode() {
|
|
100
|
+
const declared = declaredMode();
|
|
101
|
+
return declared === "archive" ? "platform" : declared;
|
|
102
|
+
}
|
|
103
|
+
function getDeclaredInstanceMode() {
|
|
104
|
+
return declaredMode();
|
|
105
|
+
}
|
|
106
|
+
function isMeteredReads() {
|
|
107
|
+
const override = process.env.METERED_READS?.trim().toLowerCase();
|
|
108
|
+
if (override === "true")
|
|
109
|
+
return true;
|
|
110
|
+
if (override === "false")
|
|
111
|
+
return false;
|
|
112
|
+
return getInstanceMode() === "platform";
|
|
113
|
+
}
|
|
114
|
+
function isPlatformMode() {
|
|
115
|
+
return getInstanceMode() === "platform";
|
|
116
|
+
}
|
|
117
|
+
function isOssMode() {
|
|
118
|
+
return getInstanceMode() === "oss";
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// src/crypto/secrets.ts
|
|
117
122
|
var KEY_ENV = "SECONDLAYER_SECRETS_KEY";
|
|
118
123
|
var IV_LEN = 12;
|
|
119
124
|
var TAG_LEN = 16;
|
|
@@ -228,7 +233,6 @@ function generateSecretsKey() {
|
|
|
228
233
|
}
|
|
229
234
|
|
|
230
235
|
// src/db/queries/webhooks.ts
|
|
231
|
-
import { sql } from "kysely";
|
|
232
236
|
async function createWebhook(db, input) {
|
|
233
237
|
const signingSecret = generateSecret();
|
|
234
238
|
const kind = input.kind ?? "subgraph";
|
|
@@ -344,18 +348,18 @@ async function notifyWebhooksChanged(db, accountId) {
|
|
|
344
348
|
await sql`SELECT pg_notify('webhooks:changed', ${accountId})`.execute(db);
|
|
345
349
|
}
|
|
346
350
|
export {
|
|
347
|
-
|
|
348
|
-
toggleWebhookStatus,
|
|
349
|
-
rotateWebhookSecret,
|
|
350
|
-
notifyWebhooksChanged,
|
|
351
|
-
listWebhooks,
|
|
352
|
-
listActiveChainWebhooks,
|
|
353
|
-
getWebhookSigningSecret,
|
|
354
|
-
getWebhookByName,
|
|
355
|
-
getWebhook,
|
|
351
|
+
createWebhook,
|
|
356
352
|
deleteWebhook,
|
|
357
|
-
|
|
353
|
+
getWebhook,
|
|
354
|
+
getWebhookByName,
|
|
355
|
+
getWebhookSigningSecret,
|
|
356
|
+
listActiveChainWebhooks,
|
|
357
|
+
listWebhooks,
|
|
358
|
+
notifyWebhooksChanged,
|
|
359
|
+
rotateWebhookSecret,
|
|
360
|
+
toggleWebhookStatus,
|
|
361
|
+
updateWebhook
|
|
358
362
|
};
|
|
359
363
|
|
|
360
|
-
//# debugId=
|
|
364
|
+
//# debugId=0300624A605962A764756E2164756E21
|
|
361
365
|
//# sourceMappingURL=webhooks.js.map
|