@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.
- package/dist/src/archive/range-digest.d.ts +61 -9
- package/dist/src/archive/semantic-digest-builder.d.ts +61 -9
- package/dist/src/coverage/index.d.ts +64 -9
- package/dist/src/coverage/index.js.map +2 -2
- package/dist/src/db/index.d.ts +63 -10
- package/dist/src/db/index.js +19 -1
- package/dist/src/db/index.js.map +5 -4
- package/dist/src/db/queries/chain-reorgs.d.ts +61 -9
- package/dist/src/db/queries/chain-reorgs.js +17 -1
- package/dist/src/db/queries/chain-reorgs.js.map +5 -4
- package/dist/src/db/queries/contracts.d.ts +108 -28
- package/dist/src/db/queries/contracts.js +115 -15
- package/dist/src/db/queries/contracts.js.map +7 -5
- package/dist/src/db/queries/instance.d.ts +69 -10
- package/dist/src/db/queries/instance.js +147 -3
- package/dist/src/db/queries/instance.js.map +6 -4
- package/dist/src/db/queries/integrity.d.ts +77 -10
- package/dist/src/db/queries/integrity.js +236 -2
- package/dist/src/db/queries/integrity.js.map +7 -4
- package/dist/src/db/queries/subgraph-gaps.d.ts +69 -12
- package/dist/src/db/queries/subgraph-gaps.js +7 -3
- package/dist/src/db/queries/subgraph-gaps.js.map +3 -3
- package/dist/src/db/queries/subgraph-operations.d.ts +61 -9
- package/dist/src/db/queries/subgraphs.d.ts +122 -42
- package/dist/src/db/queries/subgraphs.js +85 -27
- package/dist/src/db/queries/subgraphs.js.map +7 -6
- package/dist/src/db/queries/sync-scope.d.ts +61 -9
- package/dist/src/db/queries/webhook-replays.d.ts +73 -13
- package/dist/src/db/queries/webhook-replays.js +468 -19
- package/dist/src/db/queries/webhook-replays.js.map +9 -4
- package/dist/src/db/queries/webhooks.d.ts +96 -21
- package/dist/src/db/queries/webhooks.js +72 -17
- package/dist/src/db/queries/webhooks.js.map +6 -5
- package/dist/src/db/schema.d.ts +62 -10
- package/dist/src/db/schema.js +20 -1
- package/dist/src/db/schema.js.map +4 -3
- package/dist/src/db/transition.d.ts +46 -0
- package/dist/src/db/transition.js +38 -0
- package/dist/src/db/transition.js.map +10 -0
- package/dist/src/email/index.d.ts +16 -1
- package/dist/src/email/index.js +186 -130
- package/dist/src/email/index.js.map +5 -4
- package/dist/src/errors.d.ts +7 -1
- package/dist/src/errors.js +12 -1
- package/dist/src/errors.js.map +3 -3
- package/dist/src/index-http.d.ts +11 -3
- package/dist/src/index-http.js +3 -3
- package/dist/src/index-http.js.map +3 -3
- package/dist/src/index.d.ts +98 -19
- package/dist/src/index.js +41 -8
- package/dist/src/index.js.map +8 -7
- package/dist/src/insights/index.d.ts +62 -9
- package/dist/src/insights/index.js +55 -5
- package/dist/src/insights/index.js.map +7 -6
- package/dist/src/node/local-client.d.ts +61 -9
- package/dist/src/queue/listener.js +17 -1
- package/dist/src/queue/listener.js.map +5 -4
- package/dist/src/runtime/index.d.ts +0 -4
- package/dist/src/runtime/index.js +54 -4
- package/dist/src/runtime/index.js.map +6 -5
- package/dist/src/schemas/index.d.ts +36 -10
- package/dist/src/schemas/index.js +12 -8
- package/dist/src/schemas/index.js.map +4 -4
- package/dist/src/schemas/subgraphs.d.ts +22 -9
- package/dist/src/schemas/subgraphs.js +10 -6
- package/dist/src/schemas/subgraphs.js.map +3 -3
- package/dist/src/schemas/webhooks.d.ts +15 -2
- package/dist/src/schemas/webhooks.js +2 -2
- package/dist/src/schemas/webhooks.js.map +3 -3
- package/dist/src/subgraphs/spec.d.ts +5 -1
- package/dist/src/webhooks/health.d.ts +27 -0
- package/dist/src/webhooks/health.js +84 -0
- package/dist/src/webhooks/health.js.map +11 -0
- package/migrations/0184_status_checks.ts +92 -0
- package/migrations/0185_reorg_generation_settlement_seq.ts +89 -0
- package/migrations/0186_api_keys_one_active_tenant_per_name.ts +43 -0
- package/migrations/0187_accounts_email_lower_unique.ts +27 -0
- package/migrations/0188_webhook_reasons.ts +124 -0
- package/migrations/0189_subgraph_lifecycle.ts +83 -0
- package/migrations/0190_usage_ledger_debited_usd_micros.ts +59 -0
- package/migrations/0191_indexer_state_machines.ts +83 -0
- package/migrations/0192_hosted_stack_state.ts +37 -0
- package/migrations/0193_accounts_ghost_has_no_email.ts +34 -0
- package/package.json +9 -1
|
@@ -1,5 +1,444 @@
|
|
|
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
|
+
// src/crypto/hmac.ts
|
|
18
|
+
var exports_hmac = {};
|
|
19
|
+
__export(exports_hmac, {
|
|
20
|
+
createSignatureHeader: () => createSignatureHeader,
|
|
21
|
+
generateSecret: () => generateSecret,
|
|
22
|
+
signPayload: () => signPayload,
|
|
23
|
+
verifySignature: () => verifySignature,
|
|
24
|
+
verifySignatureHeader: () => verifySignatureHeader
|
|
25
|
+
});
|
|
26
|
+
|
|
1
27
|
// src/db/queries/webhook-replays.ts
|
|
28
|
+
import { sql as sql3 } from "kysely";
|
|
29
|
+
|
|
30
|
+
// src/db/queries/webhooks.ts
|
|
31
|
+
import {
|
|
32
|
+
sql as sql2
|
|
33
|
+
} from "kysely";
|
|
34
|
+
|
|
35
|
+
// src/crypto/hmac.ts
|
|
36
|
+
import { createHmac, randomBytes } from "node:crypto";
|
|
37
|
+
function generateSecret() {
|
|
38
|
+
return randomBytes(32).toString("hex");
|
|
39
|
+
}
|
|
40
|
+
function signPayload(payload, secret) {
|
|
41
|
+
const hmac = createHmac("sha256", secret);
|
|
42
|
+
hmac.update(payload);
|
|
43
|
+
return hmac.digest("hex");
|
|
44
|
+
}
|
|
45
|
+
function verifySignature(payload, signature, secret) {
|
|
46
|
+
const expectedSignature = signPayload(payload, secret);
|
|
47
|
+
if (signature.length !== expectedSignature.length) {
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
let result = 0;
|
|
51
|
+
for (let i = 0;i < signature.length; i++) {
|
|
52
|
+
result |= signature.charCodeAt(i) ^ expectedSignature.charCodeAt(i);
|
|
53
|
+
}
|
|
54
|
+
return result === 0;
|
|
55
|
+
}
|
|
56
|
+
function createSignatureHeader(payload, secret, timestamp) {
|
|
57
|
+
const ts = timestamp ?? Math.floor(Date.now() / 1000);
|
|
58
|
+
const signedPayload = `${ts}.${payload}`;
|
|
59
|
+
const signature = signPayload(signedPayload, secret);
|
|
60
|
+
return `t=${ts},v1=${signature}`;
|
|
61
|
+
}
|
|
62
|
+
function verifySignatureHeader(payload, header, secret, toleranceSeconds = 300) {
|
|
63
|
+
const parts = header.split(",");
|
|
64
|
+
const timestamp = parts.find((p) => p.startsWith("t="))?.slice(2);
|
|
65
|
+
const signature = parts.find((p) => p.startsWith("v1="))?.slice(3);
|
|
66
|
+
if (!timestamp || !signature) {
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
const ts = Number.parseInt(timestamp, 10);
|
|
70
|
+
if (Number.isNaN(ts)) {
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
const now = Math.floor(Date.now() / 1000);
|
|
74
|
+
if (Math.abs(now - ts) > toleranceSeconds) {
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
const signedPayload = `${ts}.${payload}`;
|
|
78
|
+
return verifySignature(signedPayload, signature, secret);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// src/crypto/secrets.ts
|
|
82
|
+
import { createCipheriv, createDecipheriv, randomBytes as randomBytes2 } from "node:crypto";
|
|
83
|
+
import {
|
|
84
|
+
appendFileSync,
|
|
85
|
+
closeSync,
|
|
86
|
+
existsSync,
|
|
87
|
+
openSync,
|
|
88
|
+
readFileSync,
|
|
89
|
+
unlinkSync
|
|
90
|
+
} from "node:fs";
|
|
91
|
+
import { resolve } from "node:path";
|
|
92
|
+
|
|
93
|
+
// src/mode.ts
|
|
94
|
+
var VALID_MODES = [
|
|
95
|
+
"oss",
|
|
96
|
+
"platform",
|
|
97
|
+
"archive"
|
|
98
|
+
];
|
|
99
|
+
function declaredMode() {
|
|
100
|
+
const raw = process.env.INSTANCE_MODE?.trim().toLowerCase();
|
|
101
|
+
if (raw && VALID_MODES.includes(raw)) {
|
|
102
|
+
return raw;
|
|
103
|
+
}
|
|
104
|
+
return "oss";
|
|
105
|
+
}
|
|
106
|
+
function getInstanceMode() {
|
|
107
|
+
const declared = declaredMode();
|
|
108
|
+
return declared === "archive" ? "platform" : declared;
|
|
109
|
+
}
|
|
110
|
+
function getDeclaredInstanceMode() {
|
|
111
|
+
return declaredMode();
|
|
112
|
+
}
|
|
113
|
+
function isMeteredReads() {
|
|
114
|
+
const override = process.env.METERED_READS?.trim().toLowerCase();
|
|
115
|
+
if (override === "true")
|
|
116
|
+
return true;
|
|
117
|
+
if (override === "false")
|
|
118
|
+
return false;
|
|
119
|
+
return getInstanceMode() === "platform";
|
|
120
|
+
}
|
|
121
|
+
function isPlatformMode() {
|
|
122
|
+
return getInstanceMode() === "platform";
|
|
123
|
+
}
|
|
124
|
+
function isOssMode() {
|
|
125
|
+
return getInstanceMode() === "oss";
|
|
126
|
+
}
|
|
127
|
+
function isTestnetWebhookStack() {
|
|
128
|
+
return process.env.TESTNET_WEBHOOK_STACK === "true";
|
|
129
|
+
}
|
|
130
|
+
function isWebhookAccountScoped() {
|
|
131
|
+
return isPlatformMode() || isTestnetWebhookStack();
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// src/crypto/secrets.ts
|
|
135
|
+
var KEY_ENV = "SECONDLAYER_SECRETS_KEY";
|
|
136
|
+
var IV_LEN = 12;
|
|
137
|
+
var TAG_LEN = 16;
|
|
138
|
+
function readExistingKey(envPath) {
|
|
139
|
+
if (!existsSync(envPath))
|
|
140
|
+
return null;
|
|
141
|
+
const contents = readFileSync(envPath, "utf8");
|
|
142
|
+
const match = contents.match(/^SECONDLAYER_SECRETS_KEY=([a-fA-F0-9]{64})/m);
|
|
143
|
+
return match ? match[1] : null;
|
|
144
|
+
}
|
|
145
|
+
var STALE_LOCK_MS = 1e4;
|
|
146
|
+
var POLL_MS = 25;
|
|
147
|
+
function bootstrapOssKey() {
|
|
148
|
+
const envPath = resolve(process.cwd(), ".env.local");
|
|
149
|
+
const existing = readExistingKey(envPath);
|
|
150
|
+
if (existing) {
|
|
151
|
+
process.env[KEY_ENV] = existing;
|
|
152
|
+
return existing;
|
|
153
|
+
}
|
|
154
|
+
const lockPath = `${envPath}.secret-bootstrap.lock`;
|
|
155
|
+
let lockFd = null;
|
|
156
|
+
try {
|
|
157
|
+
lockFd = openSync(lockPath, "wx", 384);
|
|
158
|
+
} catch (err) {
|
|
159
|
+
const e = err;
|
|
160
|
+
if (e.code !== "EEXIST")
|
|
161
|
+
throw err;
|
|
162
|
+
}
|
|
163
|
+
if (lockFd === null) {
|
|
164
|
+
const deadline = Date.now() + STALE_LOCK_MS;
|
|
165
|
+
while (Date.now() < deadline) {
|
|
166
|
+
const key = readExistingKey(envPath);
|
|
167
|
+
if (key) {
|
|
168
|
+
process.env[KEY_ENV] = key;
|
|
169
|
+
return key;
|
|
170
|
+
}
|
|
171
|
+
Bun.sleepSync(POLL_MS);
|
|
172
|
+
}
|
|
173
|
+
try {
|
|
174
|
+
unlinkSync(lockPath);
|
|
175
|
+
} catch {}
|
|
176
|
+
return bootstrapOssKey();
|
|
177
|
+
}
|
|
178
|
+
try {
|
|
179
|
+
const hex = randomBytes2(32).toString("hex");
|
|
180
|
+
const line = `${existsSync(envPath) ? `
|
|
181
|
+
` : ""}${KEY_ENV}=${hex}
|
|
182
|
+
`;
|
|
183
|
+
appendFileSync(envPath, line, { mode: 384 });
|
|
184
|
+
process.env[KEY_ENV] = hex;
|
|
185
|
+
console.log(`[secondlayer] generated ${KEY_ENV}; saved to ${envPath} (mode 0600)`);
|
|
186
|
+
return hex;
|
|
187
|
+
} finally {
|
|
188
|
+
closeSync(lockFd);
|
|
189
|
+
try {
|
|
190
|
+
unlinkSync(lockPath);
|
|
191
|
+
} catch {}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
function loadKey() {
|
|
195
|
+
let hex = process.env[KEY_ENV];
|
|
196
|
+
if (!hex) {
|
|
197
|
+
if (getInstanceMode() === "oss") {
|
|
198
|
+
hex = bootstrapOssKey();
|
|
199
|
+
} else {
|
|
200
|
+
throw new Error(`${KEY_ENV} not set. Generate one with: openssl rand -hex 32`);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
const key = Buffer.from(hex, "hex");
|
|
204
|
+
if (key.length !== 32) {
|
|
205
|
+
throw new Error(`${KEY_ENV} must be 32 bytes hex (got ${key.length})`);
|
|
206
|
+
}
|
|
207
|
+
return key;
|
|
208
|
+
}
|
|
209
|
+
var _cachedKey = null;
|
|
210
|
+
function getKey() {
|
|
211
|
+
if (!_cachedKey)
|
|
212
|
+
_cachedKey = loadKey();
|
|
213
|
+
return _cachedKey;
|
|
214
|
+
}
|
|
215
|
+
function secretsKeyAvailable() {
|
|
216
|
+
if (process.env[KEY_ENV])
|
|
217
|
+
return true;
|
|
218
|
+
if (getInstanceMode() === "oss") {
|
|
219
|
+
const envPath = resolve(process.cwd(), ".env.local");
|
|
220
|
+
return readExistingKey(envPath) !== null;
|
|
221
|
+
}
|
|
222
|
+
return false;
|
|
223
|
+
}
|
|
224
|
+
function encryptSecret(plaintext) {
|
|
225
|
+
const key = getKey();
|
|
226
|
+
const iv = randomBytes2(IV_LEN);
|
|
227
|
+
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
|
228
|
+
const ciphertext = Buffer.concat([
|
|
229
|
+
cipher.update(plaintext, "utf8"),
|
|
230
|
+
cipher.final()
|
|
231
|
+
]);
|
|
232
|
+
const tag = cipher.getAuthTag();
|
|
233
|
+
return Buffer.concat([iv, tag, ciphertext]);
|
|
234
|
+
}
|
|
235
|
+
function decryptSecret(envelope) {
|
|
236
|
+
const key = getKey();
|
|
237
|
+
const iv = envelope.subarray(0, IV_LEN);
|
|
238
|
+
const tag = envelope.subarray(IV_LEN, IV_LEN + TAG_LEN);
|
|
239
|
+
const ciphertext = envelope.subarray(IV_LEN + TAG_LEN);
|
|
240
|
+
const decipher = createDecipheriv("aes-256-gcm", key, iv);
|
|
241
|
+
decipher.setAuthTag(tag);
|
|
242
|
+
return decipher.update(ciphertext).toString("utf8") + decipher.final("utf8");
|
|
243
|
+
}
|
|
244
|
+
function generateSecretsKey() {
|
|
245
|
+
return randomBytes2(32).toString("hex");
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// src/db/transition.ts
|
|
2
249
|
import { sql } from "kysely";
|
|
250
|
+
function defineMachine(def) {
|
|
251
|
+
const canTransition = (from, to) => def.transitions[from]?.includes(to) ?? false;
|
|
252
|
+
return {
|
|
253
|
+
states: def.states,
|
|
254
|
+
canTransition,
|
|
255
|
+
assert(from, to) {
|
|
256
|
+
if (!canTransition(from, to)) {
|
|
257
|
+
throw new Error(`illegal transition ${from} -> ${to}`);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
async function casTransition(db, t) {
|
|
263
|
+
const column = sql.id(t.column ?? "status");
|
|
264
|
+
const assignments = [sql`${column} = ${t.to}`];
|
|
265
|
+
if (t.stampUpdatedAt !== false)
|
|
266
|
+
assignments.push(sql`updated_at = now()`);
|
|
267
|
+
for (const [key, value] of Object.entries(t.set ?? {})) {
|
|
268
|
+
assignments.push(sql`${sql.id(key)} = ${value}`);
|
|
269
|
+
}
|
|
270
|
+
const returning = t.returning ? sql.join(t.returning.map((c) => sql.id(c))) : sql.raw("*");
|
|
271
|
+
const { rows } = await sql`
|
|
272
|
+
UPDATE ${sql.table(t.table)}
|
|
273
|
+
SET ${sql.join(assignments)}
|
|
274
|
+
WHERE ${sql.id(t.key ?? "id")} = ${t.id} AND ${column} = ANY(${sql.val([...t.from])})
|
|
275
|
+
RETURNING ${returning}
|
|
276
|
+
`.execute(db);
|
|
277
|
+
return rows[0] ?? null;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// src/db/queries/webhooks.ts
|
|
281
|
+
async function createWebhook(db, input) {
|
|
282
|
+
const signingSecret = generateSecret();
|
|
283
|
+
const row = {
|
|
284
|
+
account_id: isWebhookAccountScoped() ? input.accountId : "",
|
|
285
|
+
project_id: input.projectId ?? null,
|
|
286
|
+
name: input.name,
|
|
287
|
+
status: "active",
|
|
288
|
+
kind: "chain",
|
|
289
|
+
triggers: input.triggers,
|
|
290
|
+
format: input.format ?? "standard-webhooks",
|
|
291
|
+
url: input.url,
|
|
292
|
+
signing_secret_enc: encryptSecret(signingSecret),
|
|
293
|
+
auth_config: input.authConfig ?? {},
|
|
294
|
+
...input.maxRetries !== undefined ? { max_retries: input.maxRetries } : {},
|
|
295
|
+
...input.timeoutMs !== undefined ? { timeout_ms: input.timeoutMs } : {},
|
|
296
|
+
...input.concurrency !== undefined ? { concurrency: input.concurrency } : {}
|
|
297
|
+
};
|
|
298
|
+
const webhook = await db.insertInto("webhooks").values(row).returningAll().executeTakeFirstOrThrow();
|
|
299
|
+
return { webhook, signingSecret };
|
|
300
|
+
}
|
|
301
|
+
async function listWebhooks(db, accountId, opts) {
|
|
302
|
+
let q = db.selectFrom("webhooks").selectAll().orderBy("created_at", "desc");
|
|
303
|
+
if (isWebhookAccountScoped())
|
|
304
|
+
q = q.where("account_id", "=", accountId);
|
|
305
|
+
if (opts?.limit !== undefined)
|
|
306
|
+
q = q.limit(opts.limit);
|
|
307
|
+
if (opts?.offset !== undefined)
|
|
308
|
+
q = q.offset(opts.offset);
|
|
309
|
+
return q.execute();
|
|
310
|
+
}
|
|
311
|
+
async function listActiveChainWebhooks(db) {
|
|
312
|
+
return db.selectFrom("webhooks").selectAll().where("kind", "=", "chain").where("status", "=", "active").execute();
|
|
313
|
+
}
|
|
314
|
+
var WEBHOOK_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
315
|
+
var isWebhookId = (id) => WEBHOOK_ID_RE.test(id);
|
|
316
|
+
var REORG_ORPHANED_ERROR_PREFIX = "orphaned by reorg at ";
|
|
317
|
+
function notReorgOrphaned(eb) {
|
|
318
|
+
return eb.or([
|
|
319
|
+
eb("dead_reason", "is", null),
|
|
320
|
+
eb("dead_reason", "!=", "orphaned")
|
|
321
|
+
]);
|
|
322
|
+
}
|
|
323
|
+
async function getWebhook(db, accountId, id) {
|
|
324
|
+
if (!isWebhookId(id))
|
|
325
|
+
return null;
|
|
326
|
+
let q = db.selectFrom("webhooks").selectAll().where("id", "=", id);
|
|
327
|
+
if (isWebhookAccountScoped())
|
|
328
|
+
q = q.where("account_id", "=", accountId);
|
|
329
|
+
return await q.executeTakeFirst() ?? null;
|
|
330
|
+
}
|
|
331
|
+
async function getWebhookByName(db, accountId, name) {
|
|
332
|
+
let q = db.selectFrom("webhooks").selectAll().where("name", "=", name);
|
|
333
|
+
if (isWebhookAccountScoped())
|
|
334
|
+
q = q.where("account_id", "=", accountId);
|
|
335
|
+
return await q.executeTakeFirst() ?? null;
|
|
336
|
+
}
|
|
337
|
+
async function updateWebhook(db, accountId, id, patch) {
|
|
338
|
+
if (!isWebhookId(id))
|
|
339
|
+
return null;
|
|
340
|
+
const update = { updated_at: new Date };
|
|
341
|
+
if (patch.name !== undefined)
|
|
342
|
+
update.name = patch.name;
|
|
343
|
+
if (patch.format !== undefined)
|
|
344
|
+
update.format = patch.format;
|
|
345
|
+
if (patch.url !== undefined)
|
|
346
|
+
update.url = patch.url;
|
|
347
|
+
if (patch.authConfig !== undefined)
|
|
348
|
+
update.auth_config = patch.authConfig;
|
|
349
|
+
if (patch.maxRetries !== undefined)
|
|
350
|
+
update.max_retries = patch.maxRetries;
|
|
351
|
+
if (patch.timeoutMs !== undefined)
|
|
352
|
+
update.timeout_ms = patch.timeoutMs;
|
|
353
|
+
if (patch.concurrency !== undefined)
|
|
354
|
+
update.concurrency = patch.concurrency;
|
|
355
|
+
let q = db.updateTable("webhooks").set(update).where("id", "=", id);
|
|
356
|
+
if (isWebhookAccountScoped())
|
|
357
|
+
q = q.where("account_id", "=", accountId);
|
|
358
|
+
return await q.returningAll().executeTakeFirst() ?? null;
|
|
359
|
+
}
|
|
360
|
+
var webhookMachine = defineMachine({
|
|
361
|
+
states: ["active", "paused"],
|
|
362
|
+
transitions: { active: ["active", "paused"], paused: ["active", "paused"] }
|
|
363
|
+
});
|
|
364
|
+
async function toggleWebhookStatus(db, accountId, id, status) {
|
|
365
|
+
if (!await getWebhook(db, accountId, id))
|
|
366
|
+
return null;
|
|
367
|
+
return casTransition(db, {
|
|
368
|
+
table: "webhooks",
|
|
369
|
+
id,
|
|
370
|
+
from: webhookMachine.states,
|
|
371
|
+
to: status,
|
|
372
|
+
set: {
|
|
373
|
+
pause_reason: status === "paused" ? "user" : null,
|
|
374
|
+
circuit_failures: 0,
|
|
375
|
+
circuit_opened_at: null
|
|
376
|
+
}
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
var WEBHOOK_DELETE_BATCH = 5000;
|
|
380
|
+
async function deleteWebhookChildren(db, webhookId) {
|
|
381
|
+
for (const table of ["webhook_deliveries", "webhook_outbox"]) {
|
|
382
|
+
for (;; ) {
|
|
383
|
+
const result = await sql2`
|
|
384
|
+
DELETE FROM ${sql2.table(table)}
|
|
385
|
+
WHERE id IN (
|
|
386
|
+
SELECT id FROM ${sql2.table(table)}
|
|
387
|
+
WHERE webhook_id = ${webhookId}
|
|
388
|
+
LIMIT ${WEBHOOK_DELETE_BATCH}
|
|
389
|
+
)
|
|
390
|
+
`.execute(db);
|
|
391
|
+
if (Number(result.numAffectedRows ?? 0n) === 0)
|
|
392
|
+
break;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
async function deleteWebhook(db, accountId, id) {
|
|
397
|
+
if (!isWebhookId(id))
|
|
398
|
+
return false;
|
|
399
|
+
let owned = db.selectFrom("webhooks").select("id").where("id", "=", id);
|
|
400
|
+
if (isWebhookAccountScoped())
|
|
401
|
+
owned = owned.where("account_id", "=", accountId);
|
|
402
|
+
const row = await owned.executeTakeFirst();
|
|
403
|
+
if (!row)
|
|
404
|
+
return false;
|
|
405
|
+
await casTransition(db, {
|
|
406
|
+
table: "webhooks",
|
|
407
|
+
id,
|
|
408
|
+
from: ["active"],
|
|
409
|
+
to: "paused",
|
|
410
|
+
set: { pause_reason: "user" }
|
|
411
|
+
});
|
|
412
|
+
await deleteWebhookChildren(db, id);
|
|
413
|
+
let q = db.deleteFrom("webhooks").where("id", "=", id);
|
|
414
|
+
if (isWebhookAccountScoped())
|
|
415
|
+
q = q.where("account_id", "=", accountId);
|
|
416
|
+
const res = await q.executeTakeFirst();
|
|
417
|
+
return Number(res.numDeletedRows ?? 0) > 0;
|
|
418
|
+
}
|
|
419
|
+
async function rotateWebhookSecret(db, accountId, id) {
|
|
420
|
+
if (!isWebhookId(id))
|
|
421
|
+
return null;
|
|
422
|
+
const signingSecret = generateSecret();
|
|
423
|
+
let q = db.updateTable("webhooks").set({
|
|
424
|
+
signing_secret_enc: encryptSecret(signingSecret),
|
|
425
|
+
updated_at: new Date
|
|
426
|
+
}).where("id", "=", id);
|
|
427
|
+
if (isWebhookAccountScoped())
|
|
428
|
+
q = q.where("account_id", "=", accountId);
|
|
429
|
+
const row = await q.returningAll().executeTakeFirst();
|
|
430
|
+
if (!row)
|
|
431
|
+
return null;
|
|
432
|
+
return { webhook: row, signingSecret };
|
|
433
|
+
}
|
|
434
|
+
function getWebhookSigningSecret(webhook) {
|
|
435
|
+
return decryptSecret(webhook.signing_secret_enc);
|
|
436
|
+
}
|
|
437
|
+
async function notifyWebhooksChanged(db, accountId) {
|
|
438
|
+
await sql2`SELECT pg_notify('webhooks:changed', ${accountId})`.execute(db);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// src/db/queries/webhook-replays.ts
|
|
3
442
|
var STALE_SCAN_MINUTES = 30;
|
|
4
443
|
|
|
5
444
|
class ReplayInProgressError extends Error {
|
|
@@ -15,14 +454,20 @@ function isOneScanningConflict(err) {
|
|
|
15
454
|
const candidate = err;
|
|
16
455
|
return candidate.code === "23505" && (candidate.constraint === ONE_SCANNING_CONSTRAINT || candidate.constraint_name === ONE_SCANNING_CONSTRAINT);
|
|
17
456
|
}
|
|
457
|
+
async function reapStaleScans(db, webhookId) {
|
|
458
|
+
let q = db.updateTable("webhook_replays").set({
|
|
459
|
+
status: "failed",
|
|
460
|
+
error: "scan interrupted",
|
|
461
|
+
finished_at: sql3`now()`
|
|
462
|
+
}).where("status", "=", "scanning").where("started_at", "<", sql3`now() - ${sql3.lit(`${STALE_SCAN_MINUTES} minutes`)}::interval`);
|
|
463
|
+
if (webhookId)
|
|
464
|
+
q = q.where("webhook_id", "=", webhookId);
|
|
465
|
+
await q.execute();
|
|
466
|
+
}
|
|
18
467
|
async function beginReplay(db, input) {
|
|
19
468
|
try {
|
|
20
469
|
await db.transaction().execute(async (trx) => {
|
|
21
|
-
await trx.
|
|
22
|
-
status: "failed",
|
|
23
|
-
error: "scan interrupted",
|
|
24
|
-
finished_at: sql`now()`
|
|
25
|
-
}).where("webhook_id", "=", input.webhookId).where("status", "=", "scanning").where("started_at", "<", sql`now() - ${sql.lit(`${STALE_SCAN_MINUTES} minutes`)}::interval`).execute();
|
|
470
|
+
await reapStaleScans(trx, input.webhookId);
|
|
26
471
|
const row = await trx.insertInto("webhook_replays").values({
|
|
27
472
|
id: input.id,
|
|
28
473
|
webhook_id: input.webhookId,
|
|
@@ -31,7 +476,7 @@ async function beginReplay(db, input) {
|
|
|
31
476
|
status: "scanning"
|
|
32
477
|
}).onConflict((oc) => oc.column("id").doUpdateSet({
|
|
33
478
|
status: "scanning",
|
|
34
|
-
started_at:
|
|
479
|
+
started_at: sql3`now()`,
|
|
35
480
|
finished_at: null,
|
|
36
481
|
error: null,
|
|
37
482
|
total: null,
|
|
@@ -48,21 +493,23 @@ async function beginReplay(db, input) {
|
|
|
48
493
|
}
|
|
49
494
|
}
|
|
50
495
|
async function finishScan(db, id, counts) {
|
|
51
|
-
await db.updateTable("webhook_replays").set({
|
|
496
|
+
const result = await db.updateTable("webhook_replays").set({
|
|
52
497
|
status: "running",
|
|
53
498
|
scanned_count: counts.scanned,
|
|
54
|
-
enqueued_count:
|
|
55
|
-
}).where("id", "=", id).
|
|
499
|
+
enqueued_count: sql3`enqueued_count + ${counts.enqueued}`
|
|
500
|
+
}).where("id", "=", id).where("status", "=", "scanning").executeTakeFirst();
|
|
501
|
+
return Number(result.numUpdatedRows ?? 0) > 0;
|
|
56
502
|
}
|
|
57
503
|
async function failScan(db, id, error) {
|
|
58
|
-
await db.updateTable("webhook_replays").set({ status: "failed", error, finished_at:
|
|
504
|
+
const result = await db.updateTable("webhook_replays").set({ status: "failed", error, finished_at: sql3`now()` }).where("id", "=", id).where("status", "=", "scanning").executeTakeFirst();
|
|
505
|
+
return Number(result.numUpdatedRows ?? 0) > 0;
|
|
59
506
|
}
|
|
60
507
|
async function pendingCount(db, id) {
|
|
61
|
-
const row = await db.selectFrom("webhook_outbox").select(
|
|
508
|
+
const row = await db.selectFrom("webhook_outbox").select(sql3`count(*)`.as("n")).where("status", "=", "pending").where("replay_id", "=", id).executeTakeFirstOrThrow();
|
|
62
509
|
return Number(row.n);
|
|
63
510
|
}
|
|
64
511
|
async function deadCount(db, webhookId, id) {
|
|
65
|
-
const row = await db.selectFrom("webhook_outbox").select(
|
|
512
|
+
const row = await db.selectFrom("webhook_outbox").select(sql3`count(*)`.as("n")).where("webhook_id", "=", webhookId).where("replay_id", "=", id).where("status", "=", "dead").executeTakeFirstOrThrow();
|
|
66
513
|
return Number(row.n);
|
|
67
514
|
}
|
|
68
515
|
function progressOf(record, pending) {
|
|
@@ -93,10 +540,10 @@ async function progressWithFinalize(db, record) {
|
|
|
93
540
|
const dead = await deadCount(db, record.webhook_id, record.id);
|
|
94
541
|
const finalized = await db.updateTable("webhook_replays").set({
|
|
95
542
|
status: "done",
|
|
96
|
-
finished_at:
|
|
97
|
-
total:
|
|
543
|
+
finished_at: sql3`now()`,
|
|
544
|
+
total: sql3`enqueued_count`,
|
|
98
545
|
gave_up: dead,
|
|
99
|
-
delivered:
|
|
546
|
+
delivered: sql3`enqueued_count - ${dead}`
|
|
100
547
|
}).where("id", "=", record.id).where("status", "=", "running").returningAll().executeTakeFirst();
|
|
101
548
|
if (finalized)
|
|
102
549
|
return progressOf(finalized, 0);
|
|
@@ -122,18 +569,19 @@ async function listWebhookReplays(db, webhookId, limit) {
|
|
|
122
569
|
return Promise.all(records.map((r) => progressWithFinalize(db, r)));
|
|
123
570
|
}
|
|
124
571
|
async function finalizeReplays(db) {
|
|
572
|
+
await reapStaleScans(db);
|
|
125
573
|
const running = await db.selectFrom("webhook_replays").selectAll().where("status", "=", "running").execute();
|
|
126
574
|
for (const record of running)
|
|
127
575
|
await progressWithFinalize(db, record);
|
|
128
576
|
}
|
|
129
577
|
async function deadSince(db, webhookId, since) {
|
|
130
|
-
let q = db.selectFrom("webhook_outbox").select(
|
|
578
|
+
let q = db.selectFrom("webhook_outbox").select(sql3`count(*)`.as("n")).where("webhook_id", "=", webhookId).where("status", "=", "dead").where(notReorgOrphaned);
|
|
131
579
|
if (since)
|
|
132
580
|
q = q.where("failed_at", ">=", since);
|
|
133
581
|
return Number((await q.executeTakeFirstOrThrow()).n);
|
|
134
582
|
}
|
|
135
583
|
async function knownEventsInRange(db, webhookId, from, to) {
|
|
136
|
-
const row = await db.selectFrom("webhook_outbox").select(
|
|
584
|
+
const row = await db.selectFrom("webhook_outbox").select(sql3`count(*)`.as("n")).where("webhook_id", "=", webhookId).where("block_height", ">=", from).where("block_height", "<=", to).executeTakeFirstOrThrow();
|
|
137
585
|
return Number(row.n);
|
|
138
586
|
}
|
|
139
587
|
export {
|
|
@@ -149,8 +597,9 @@ export {
|
|
|
149
597
|
listWebhookReplays,
|
|
150
598
|
pendingCount,
|
|
151
599
|
progressOf,
|
|
152
|
-
readReplay
|
|
600
|
+
readReplay,
|
|
601
|
+
reapStaleScans
|
|
153
602
|
};
|
|
154
603
|
|
|
155
|
-
//# debugId=
|
|
604
|
+
//# debugId=1C69B30BE979C07264756E2164756E21
|
|
156
605
|
//# sourceMappingURL=webhook-replays.js.map
|