@query-farm/vgi 0.50.1 → 0.51.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/functions/aggregate.d.ts +25 -21
- package/dist/functions/execution-cache.d.ts +11 -0
- package/dist/functions/storage-cf-do.d.ts +38 -0
- package/dist/functions/storage-seal.d.ts +27 -0
- package/dist/functions/storage.d.ts +49 -1
- package/dist/functions/table-buffering.d.ts +30 -0
- package/dist/http/fetch.d.ts +7 -0
- package/dist/index.core.d.ts +3 -2
- package/dist/index.js +749 -384
- package/dist/index.js.map +20 -18
- package/dist/protocol/dispatch.d.ts +9 -0
- package/dist/protocol/handlers/aggregate.d.ts +1 -1
- package/dist/protocol/handlers/catalog/shared.d.ts +10 -0
- package/dist/protocol/handlers/function.d.ts +2 -0
- package/dist/protocol/handlers/table-buffering.d.ts +1 -1
- package/dist/protocol/types.d.ts +8 -0
- package/dist/serve-entry.d.ts +16 -2
- package/dist/serve-entry.js +1034 -526
- package/dist/serve-entry.js.map +20 -18
- package/dist/worker-cf-entry.js +2713 -2217
- package/dist/worker-cf-entry.js.map +26 -24
- package/package.json +1 -1
- package/src/functions/aggregate.ts +101 -152
- package/src/functions/copy-from.ts +2 -2
- package/src/functions/execution-cache.ts +59 -0
- package/src/functions/storage-cf-do.ts +152 -22
- package/src/functions/storage-seal.ts +208 -0
- package/src/functions/storage.ts +120 -3
- package/src/functions/table-buffering.ts +91 -15
- package/src/functions/table-in-out.ts +3 -1
- package/src/functions/table.ts +4 -4
- package/src/http/fetch.ts +9 -0
- package/src/index.core.ts +3 -1
- package/src/protocol/dispatch.ts +12 -2
- package/src/protocol/handlers/aggregate.ts +123 -82
- package/src/protocol/handlers/catalog/shared.ts +20 -0
- package/src/protocol/handlers/function.ts +38 -11
- package/src/protocol/handlers/table-buffering.ts +44 -32
- package/src/protocol/types.ts +8 -0
- package/src/serve-entry.ts +33 -3
package/dist/serve-entry.js
CHANGED
|
@@ -48,6 +48,251 @@ var __esm = (fn, res, err) => () => {
|
|
|
48
48
|
return res;
|
|
49
49
|
};
|
|
50
50
|
|
|
51
|
+
// src/attach-secret-keyfile.ts
|
|
52
|
+
function builtins() {
|
|
53
|
+
const proc = globalThis.process;
|
|
54
|
+
const get = proc?.getBuiltinModule?.bind(proc);
|
|
55
|
+
const fs = get?.("node:fs");
|
|
56
|
+
const os = get?.("node:os");
|
|
57
|
+
const path = get?.("node:path");
|
|
58
|
+
if (!fs || !os || !path)
|
|
59
|
+
throw new Error("this runtime has no filesystem for the host-local attach secret key file.");
|
|
60
|
+
return { fs, os, path };
|
|
61
|
+
}
|
|
62
|
+
function username() {
|
|
63
|
+
try {
|
|
64
|
+
const name = builtins().os.userInfo().username;
|
|
65
|
+
if (name)
|
|
66
|
+
return name;
|
|
67
|
+
} catch {}
|
|
68
|
+
return process.env.USER || process.env.USERNAME || String(process.getuid?.() ?? "user");
|
|
69
|
+
}
|
|
70
|
+
function isDirectory(path) {
|
|
71
|
+
try {
|
|
72
|
+
return builtins().fs.statSync(path).isDirectory();
|
|
73
|
+
} catch {
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function hostLocalAttachSecretKeyPath(env = globalThis.process?.env ?? {}) {
|
|
78
|
+
const { os, path: { join } } = builtins();
|
|
79
|
+
const explicit = env[ATTACH_SECRET_KEY_FILE_ENV];
|
|
80
|
+
if (explicit)
|
|
81
|
+
return explicit;
|
|
82
|
+
const xdg = env.XDG_RUNTIME_DIR;
|
|
83
|
+
if (xdg && isDirectory(xdg))
|
|
84
|
+
return join(xdg, "vgi", FILE_NAME);
|
|
85
|
+
return join(os.tmpdir(), `vgi-${username()}`, FILE_NAME);
|
|
86
|
+
}
|
|
87
|
+
function checkOwnedPrivate(path, mode, uid, what) {
|
|
88
|
+
if (!POSIX)
|
|
89
|
+
return;
|
|
90
|
+
const me = process.getuid?.();
|
|
91
|
+
if (me !== undefined && uid !== me) {
|
|
92
|
+
throw new Error(`attach secret key ${what} ${path} is not owned by the current user. ${REMEDY}`);
|
|
93
|
+
}
|
|
94
|
+
if ((mode & 63) !== 0) {
|
|
95
|
+
throw new Error(`attach secret key ${what} ${path} is accessible by group/other (mode ${(mode & 511).toString(8)}); ` + `it must be ${what === "directory" ? "0700" : "0600"}. ${REMEDY}`);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
function ensureDir(dir) {
|
|
99
|
+
const { mkdirSync, lstatSync } = builtins().fs;
|
|
100
|
+
try {
|
|
101
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
102
|
+
} catch (e) {
|
|
103
|
+
if (e.code !== "EEXIST")
|
|
104
|
+
throw e;
|
|
105
|
+
}
|
|
106
|
+
const st = lstatSync(dir);
|
|
107
|
+
if (!st.isDirectory())
|
|
108
|
+
throw new Error(`attach secret key directory ${dir} is not a directory. ${REMEDY}`);
|
|
109
|
+
checkOwnedPrivate(dir, st.mode, st.uid, "directory");
|
|
110
|
+
}
|
|
111
|
+
function readKey(path) {
|
|
112
|
+
const { openSync, fstatSync, readSync, closeSync, constants } = builtins().fs;
|
|
113
|
+
let fd;
|
|
114
|
+
try {
|
|
115
|
+
fd = openSync(path, constants.O_RDONLY | (POSIX ? constants.O_NOFOLLOW : 0));
|
|
116
|
+
} catch (e) {
|
|
117
|
+
if (e.code === "ENOENT")
|
|
118
|
+
return null;
|
|
119
|
+
throw new Error(`attach secret key file ${path} cannot be opened (${e.code}). ${REMEDY}`);
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
const st = fstatSync(fd);
|
|
123
|
+
if (!st.isFile())
|
|
124
|
+
throw new Error(`attach secret key file ${path} is not a regular file. ${REMEDY}`);
|
|
125
|
+
checkOwnedPrivate(path, st.mode, st.uid, "file");
|
|
126
|
+
const buf = new Uint8Array(KEY_LEN + 1);
|
|
127
|
+
let n = 0;
|
|
128
|
+
for (;; ) {
|
|
129
|
+
const got = readSync(fd, buf, n, buf.length - n, null);
|
|
130
|
+
if (got <= 0)
|
|
131
|
+
break;
|
|
132
|
+
n += got;
|
|
133
|
+
if (n === buf.length)
|
|
134
|
+
break;
|
|
135
|
+
}
|
|
136
|
+
if (n !== KEY_LEN || st.size !== KEY_LEN) {
|
|
137
|
+
throw new Error(`attach secret key file ${path} must contain exactly ${KEY_LEN} raw bytes (found ${st.size}). ${REMEDY}`);
|
|
138
|
+
}
|
|
139
|
+
return buf.subarray(0, KEY_LEN);
|
|
140
|
+
} finally {
|
|
141
|
+
closeSync(fd);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
function createKey(path) {
|
|
145
|
+
const { openSync, writeSync, fsyncSync, closeSync, linkSync, unlinkSync, constants } = builtins().fs;
|
|
146
|
+
const { dirname, join } = builtins().path;
|
|
147
|
+
const tmp = join(dirname(path), `.${FILE_NAME}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);
|
|
148
|
+
const fd = openSync(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 384);
|
|
149
|
+
try {
|
|
150
|
+
const key = crypto.getRandomValues(new Uint8Array(KEY_LEN));
|
|
151
|
+
let off = 0;
|
|
152
|
+
while (off < KEY_LEN)
|
|
153
|
+
off += writeSync(fd, key, off, KEY_LEN - off);
|
|
154
|
+
fsyncSync(fd);
|
|
155
|
+
} finally {
|
|
156
|
+
closeSync(fd);
|
|
157
|
+
}
|
|
158
|
+
try {
|
|
159
|
+
linkSync(tmp, path);
|
|
160
|
+
} catch (e) {
|
|
161
|
+
if (e.code !== "EEXIST") {
|
|
162
|
+
unlinkSync(tmp);
|
|
163
|
+
throw e;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
unlinkSync(tmp);
|
|
167
|
+
}
|
|
168
|
+
function loadHostLocalAttachSecretKey(path = hostLocalAttachSecretKeyPath()) {
|
|
169
|
+
ensureDir(builtins().path.dirname(path));
|
|
170
|
+
const existing = readKey(path);
|
|
171
|
+
if (existing)
|
|
172
|
+
return existing;
|
|
173
|
+
createKey(path);
|
|
174
|
+
const created = readKey(path);
|
|
175
|
+
if (!created)
|
|
176
|
+
throw new Error(`attach secret key file ${path} vanished after creation. ${REMEDY}`);
|
|
177
|
+
return created;
|
|
178
|
+
}
|
|
179
|
+
async function hostLocalAttachSecretKey() {
|
|
180
|
+
const path = hostLocalAttachSecretKeyPath();
|
|
181
|
+
if (cached?.path === path)
|
|
182
|
+
return cached.key;
|
|
183
|
+
const key = loadHostLocalAttachSecretKey(path);
|
|
184
|
+
cached = { path, key };
|
|
185
|
+
return key;
|
|
186
|
+
}
|
|
187
|
+
var ATTACH_SECRET_KEY_FILE_ENV = "VGI_ATTACH_SECRET_KEY_FILE", KEY_LEN = 32, FILE_NAME = "attach-secret-options.key", REMEDY = "Set VGI_SIGNING_KEY (or configure attachSecretKey), or point VGI_ATTACH_SECRET_KEY_FILE at a valid key file.", POSIX, cached;
|
|
188
|
+
var init_attach_secret_keyfile = __esm(() => {
|
|
189
|
+
POSIX = typeof process === "undefined" || process.platform !== "win32";
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
// src/functions/storage-seal.ts
|
|
193
|
+
function lp(b) {
|
|
194
|
+
const out = new Uint8Array(4 + b.length);
|
|
195
|
+
new DataView(out.buffer).setUint32(0, b.length, false);
|
|
196
|
+
out.set(b, 4);
|
|
197
|
+
return out;
|
|
198
|
+
}
|
|
199
|
+
function concat(parts) {
|
|
200
|
+
let n = 0;
|
|
201
|
+
for (const p of parts)
|
|
202
|
+
n += p.length;
|
|
203
|
+
const out = new Uint8Array(n);
|
|
204
|
+
let off = 0;
|
|
205
|
+
for (const p of parts) {
|
|
206
|
+
out.set(p, off);
|
|
207
|
+
off += p.length;
|
|
208
|
+
}
|
|
209
|
+
return out;
|
|
210
|
+
}
|
|
211
|
+
function hex(b) {
|
|
212
|
+
let s = "";
|
|
213
|
+
for (let i = 0;i < b.length; i++)
|
|
214
|
+
s += b[i].toString(16).padStart(2, "0");
|
|
215
|
+
return s;
|
|
216
|
+
}
|
|
217
|
+
function storagePayloadAad(slot) {
|
|
218
|
+
return concat([INFO_BYTES, lp(UTF82.encode(slot.shardKey)), lp(slot.scopeId), lp(slot.ns), lp(slot.key)]);
|
|
219
|
+
}
|
|
220
|
+
async function deriveStoragePayloadKey(ikm) {
|
|
221
|
+
const base = await crypto.subtle.importKey("raw", ikm, "HKDF", false, ["deriveBits"]);
|
|
222
|
+
const bits = await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: INFO_BYTES }, base, KEY_LEN2 * 8);
|
|
223
|
+
return new Uint8Array(bits);
|
|
224
|
+
}
|
|
225
|
+
function aesKey(ikm) {
|
|
226
|
+
const id = hex(ikm);
|
|
227
|
+
let k = keyCache.get(id);
|
|
228
|
+
if (!k) {
|
|
229
|
+
k = (async () => {
|
|
230
|
+
const raw = await deriveStoragePayloadKey(ikm);
|
|
231
|
+
return crypto.subtle.importKey("raw", raw, "AES-GCM", false, ["encrypt", "decrypt"]);
|
|
232
|
+
})();
|
|
233
|
+
if (keyCache.size >= KEY_CACHE_MAX)
|
|
234
|
+
keyCache.delete(keyCache.keys().next().value);
|
|
235
|
+
keyCache.set(id, k);
|
|
236
|
+
k.catch(() => keyCache.delete(id));
|
|
237
|
+
}
|
|
238
|
+
return k;
|
|
239
|
+
}
|
|
240
|
+
async function sealWith(payload, ikm, slot, nonce) {
|
|
241
|
+
if (nonce !== undefined && nonce.length !== NONCE_LEN)
|
|
242
|
+
throw new Error(`nonce must be ${NONCE_LEN} bytes`);
|
|
243
|
+
const iv = nonce ?? crypto.getRandomValues(new Uint8Array(NONCE_LEN));
|
|
244
|
+
const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: storagePayloadAad(slot), tagLength: TAG_LEN * 8 }, await aesKey(ikm), payload));
|
|
245
|
+
const out = new Uint8Array(1 + NONCE_LEN + ct.length);
|
|
246
|
+
out[0] = STORAGE_PAYLOAD_VERSION;
|
|
247
|
+
out.set(iv, 1);
|
|
248
|
+
out.set(ct, 1 + NONCE_LEN);
|
|
249
|
+
return out;
|
|
250
|
+
}
|
|
251
|
+
async function openWith(blob, ikm, slot) {
|
|
252
|
+
const what = `framework storage payload ${JSON.stringify(new TextDecoder().decode(slot.ns))} for execution ${hex(slot.scopeId)}`;
|
|
253
|
+
if (blob.length < 1 + NONCE_LEN + TAG_LEN) {
|
|
254
|
+
throw new StoragePayloadError(`${what} is too short to be a sealed payload`);
|
|
255
|
+
}
|
|
256
|
+
if (blob[0] !== STORAGE_PAYLOAD_VERSION) {
|
|
257
|
+
throw new StoragePayloadError(`${what} has unknown seal version 0x${blob[0].toString(16).padStart(2, "0")}`);
|
|
258
|
+
}
|
|
259
|
+
const iv = blob.subarray(1, 1 + NONCE_LEN);
|
|
260
|
+
const body = blob.subarray(1 + NONCE_LEN);
|
|
261
|
+
try {
|
|
262
|
+
return new Uint8Array(await crypto.subtle.decrypt({ name: "AES-GCM", iv, additionalData: storagePayloadAad(slot), tagLength: TAG_LEN * 8 }, await aesKey(ikm), body));
|
|
263
|
+
} catch {
|
|
264
|
+
throw new StoragePayloadError(`${what} failed authentication (tampered, moved, or sealed under another key)`);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
async function ikmFor(signingKey) {
|
|
268
|
+
if (signingKey && signingKey.length > 0)
|
|
269
|
+
return signingKey;
|
|
270
|
+
try {
|
|
271
|
+
return await (hostLocalOverride ?? hostLocalAttachSecretKey)();
|
|
272
|
+
} catch (e) {
|
|
273
|
+
throw new StoragePayloadError(`no key to seal framework storage payloads: ${e?.message ?? e}`);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
async function sealPayload(payload, signingKey, slot) {
|
|
277
|
+
return sealWith(payload, await ikmFor(signingKey), slot);
|
|
278
|
+
}
|
|
279
|
+
async function openPayload(blob, signingKey, slot) {
|
|
280
|
+
return openWith(blob, await ikmFor(signingKey), slot);
|
|
281
|
+
}
|
|
282
|
+
var STORAGE_PAYLOAD_INFO = "vgi.storage.payload.v1", STORAGE_PAYLOAD_VERSION = 1, KEY_LEN2 = 32, NONCE_LEN = 12, TAG_LEN = 16, UTF82, INFO_BYTES, StoragePayloadError, KEY_CACHE_MAX = 16, keyCache, hostLocalOverride = null;
|
|
283
|
+
var init_storage_seal = __esm(() => {
|
|
284
|
+
init_attach_secret_keyfile();
|
|
285
|
+
UTF82 = new TextEncoder;
|
|
286
|
+
INFO_BYTES = UTF82.encode(STORAGE_PAYLOAD_INFO);
|
|
287
|
+
StoragePayloadError = class StoragePayloadError extends Error {
|
|
288
|
+
constructor(message) {
|
|
289
|
+
super(message);
|
|
290
|
+
this.name = "StoragePayloadError";
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
keyCache = new Map;
|
|
294
|
+
});
|
|
295
|
+
|
|
51
296
|
// src/functions/storage-cf-do.ts
|
|
52
297
|
var exports_storage_cf_do = {};
|
|
53
298
|
__export(exports_storage_cf_do, {
|
|
@@ -59,11 +304,27 @@ class FunctionStorageCfDo {
|
|
|
59
304
|
_token;
|
|
60
305
|
_shardKey;
|
|
61
306
|
_fetch;
|
|
307
|
+
_retry;
|
|
308
|
+
_sleep;
|
|
62
309
|
constructor(opts) {
|
|
63
310
|
this._baseUrl = opts.url.replace(/\/+$/, "");
|
|
64
311
|
this._token = opts.token ?? null;
|
|
65
|
-
|
|
312
|
+
const shard = opts.shardKey ?? "";
|
|
313
|
+
if (shard !== "" && !SHARD_KEY_RE.test(shard)) {
|
|
314
|
+
throw new Error(`invalid CF DO shard_key ${JSON.stringify(shard)} (1-128 chars, [A-Za-z0-9._-])`);
|
|
315
|
+
}
|
|
316
|
+
this._shardKey = shard;
|
|
66
317
|
this._fetch = opts.fetch ?? ((input, init) => fetch(input, init));
|
|
318
|
+
this._retry = {
|
|
319
|
+
timeoutMs: opts.retry?.timeoutMs ?? 30000,
|
|
320
|
+
maxAttempts: Math.max(1, opts.retry?.maxAttempts ?? 4),
|
|
321
|
+
baseDelayMs: opts.retry?.baseDelayMs ?? 100,
|
|
322
|
+
maxDelayMs: opts.retry?.maxDelayMs ?? 2000
|
|
323
|
+
};
|
|
324
|
+
this._sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
325
|
+
}
|
|
326
|
+
get shardKey() {
|
|
327
|
+
return this._shardKey;
|
|
67
328
|
}
|
|
68
329
|
static fromEnv() {
|
|
69
330
|
const url = process.env.VGI_CF_DO_URL;
|
|
@@ -76,11 +337,15 @@ class FunctionStorageCfDo {
|
|
|
76
337
|
});
|
|
77
338
|
}
|
|
78
339
|
forShard(shardKey) {
|
|
340
|
+
if (shardKey === this._shardKey)
|
|
341
|
+
return this;
|
|
79
342
|
return new FunctionStorageCfDo({
|
|
80
343
|
url: this._baseUrl,
|
|
81
344
|
token: this._token,
|
|
82
345
|
shardKey,
|
|
83
|
-
fetch: this._fetch
|
|
346
|
+
fetch: this._fetch,
|
|
347
|
+
retry: this._retry,
|
|
348
|
+
sleep: this._sleep
|
|
84
349
|
});
|
|
85
350
|
}
|
|
86
351
|
async workerPut(executionId, worker, state) {
|
|
@@ -117,16 +382,29 @@ class FunctionStorageCfDo {
|
|
|
117
382
|
return Number(data.cleared);
|
|
118
383
|
}
|
|
119
384
|
async stateGet(scopeId, ns, key) {
|
|
385
|
+
return (await this.stateGetMany(scopeId, ns, [key]))[0] ?? null;
|
|
386
|
+
}
|
|
387
|
+
async statePut(scopeId, ns, key, value) {
|
|
388
|
+
await this._statePutMany(scopeId, ns, [[key, value]]);
|
|
389
|
+
}
|
|
390
|
+
async stateGetMany(scopeId, ns, keys) {
|
|
391
|
+
if (keys.length === 0)
|
|
392
|
+
return [];
|
|
120
393
|
const data = await this._post("state_get_many", {
|
|
121
394
|
scope_id: bytesToB64(scopeId),
|
|
122
395
|
ns: bytesToB64(ns),
|
|
123
|
-
keys:
|
|
396
|
+
keys: keys.map(bytesToB64)
|
|
397
|
+
});
|
|
398
|
+
const rows = data.rows ?? [];
|
|
399
|
+
return keys.map((_, i) => {
|
|
400
|
+
const row = rows[i];
|
|
401
|
+
return row ? b64ToBytes(row.value) : null;
|
|
124
402
|
});
|
|
125
|
-
const row = (data.rows ?? [])[0];
|
|
126
|
-
return row ? b64ToBytes(row.value) : null;
|
|
127
403
|
}
|
|
128
|
-
async
|
|
129
|
-
|
|
404
|
+
async statePutMany(scopeId, ns, items) {
|
|
405
|
+
if (items.length === 0)
|
|
406
|
+
return;
|
|
407
|
+
await this._statePutMany(scopeId, ns, items);
|
|
130
408
|
}
|
|
131
409
|
async stateAppend(scopeId, ns, key, item) {
|
|
132
410
|
const data = await this._post("state_append", {
|
|
@@ -188,20 +466,56 @@ class FunctionStorageCfDo {
|
|
|
188
466
|
const headers = { "Content-Type": "application/json" };
|
|
189
467
|
if (this._token)
|
|
190
468
|
headers["Authorization"] = `Bearer ${this._token}`;
|
|
191
|
-
const payload = JSON.stringify({ ...body, shard_key: this._shardKey });
|
|
469
|
+
const payload = JSON.stringify({ ...body, shard_key: this._shardKey || ANONYMOUS_SHARD_KEY });
|
|
470
|
+
const { maxAttempts, baseDelayMs, maxDelayMs } = this._retry;
|
|
192
471
|
let lastErr;
|
|
193
|
-
for (let attempt = 0;attempt <
|
|
472
|
+
for (let attempt = 0;attempt < maxAttempts; attempt++) {
|
|
473
|
+
if (attempt > 0) {
|
|
474
|
+
const cap = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1));
|
|
475
|
+
const jittered = Math.random() * cap;
|
|
476
|
+
const hinted = lastErr instanceof RetryableError && lastErr.retryAfterMs != null ? Math.min(maxDelayMs, lastErr.retryAfterMs) : 0;
|
|
477
|
+
await this._sleep(Math.max(jittered, hinted));
|
|
478
|
+
}
|
|
479
|
+
try {
|
|
480
|
+
return await this._once(url, endpoint, headers, payload);
|
|
481
|
+
} catch (e) {
|
|
482
|
+
if (!(e instanceof RetryableError))
|
|
483
|
+
throw e;
|
|
484
|
+
lastErr = e;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
throw new Error(`CF DO storage ${endpoint} failed after ${maxAttempts} attempts: ${lastErr?.message ?? "unknown error"}`);
|
|
488
|
+
}
|
|
489
|
+
async _once(url, endpoint, headers, payload) {
|
|
490
|
+
const { timeoutMs } = this._retry;
|
|
491
|
+
const controller = timeoutMs > 0 ? new AbortController : null;
|
|
492
|
+
const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
|
|
493
|
+
try {
|
|
194
494
|
let resp;
|
|
195
495
|
try {
|
|
196
|
-
resp = await this._fetch(url, {
|
|
496
|
+
resp = await this._fetch(url, {
|
|
497
|
+
method: "POST",
|
|
498
|
+
headers,
|
|
499
|
+
body: payload,
|
|
500
|
+
...controller ? { signal: controller.signal } : {}
|
|
501
|
+
});
|
|
197
502
|
} catch (err) {
|
|
198
|
-
|
|
199
|
-
|
|
503
|
+
if (controller?.signal.aborted) {
|
|
504
|
+
throw new RetryableError(`timed out after ${timeoutMs} ms on ${endpoint}`);
|
|
505
|
+
}
|
|
506
|
+
throw new RetryableError(`transport error on ${endpoint}: ${err?.message ?? String(err)}`);
|
|
507
|
+
}
|
|
508
|
+
if (resp.status === 429 || resp.status >= 500) {
|
|
509
|
+
const text = await resp.text().catch(() => "");
|
|
510
|
+
throw new RetryableError(`CF DO storage error ${resp.status} on ${endpoint}: ${text.slice(0, 200) || "<empty body>"}`, parseRetryAfter(resp.headers?.get?.("Retry-After") ?? null));
|
|
200
511
|
}
|
|
201
512
|
let data;
|
|
202
513
|
try {
|
|
203
514
|
data = await resp.json();
|
|
204
|
-
} catch {
|
|
515
|
+
} catch (err) {
|
|
516
|
+
if (controller?.signal.aborted) {
|
|
517
|
+
throw new RetryableError(`timed out after ${timeoutMs} ms reading ${endpoint}`);
|
|
518
|
+
}
|
|
205
519
|
if (!resp.ok) {
|
|
206
520
|
throw new Error(`CF DO storage error ${resp.status} on ${endpoint}: <non-json body>`);
|
|
207
521
|
}
|
|
@@ -217,10 +531,18 @@ class FunctionStorageCfDo {
|
|
|
217
531
|
throw new Error(`CF DO storage error ${resp.status} on ${endpoint}: ${JSON.stringify(data)}`);
|
|
218
532
|
}
|
|
219
533
|
return data;
|
|
534
|
+
} finally {
|
|
535
|
+
if (timer)
|
|
536
|
+
clearTimeout(timer);
|
|
220
537
|
}
|
|
221
|
-
throw lastErr instanceof Error ? lastErr : new Error(`CF DO storage transport error on ${endpoint}: ${String(lastErr)}`);
|
|
222
538
|
}
|
|
223
539
|
}
|
|
540
|
+
function parseRetryAfter(v) {
|
|
541
|
+
if (!v)
|
|
542
|
+
return null;
|
|
543
|
+
const n = Number(v.trim());
|
|
544
|
+
return Number.isFinite(n) && n >= 0 ? n * 1000 : null;
|
|
545
|
+
}
|
|
224
546
|
function newAttemptId() {
|
|
225
547
|
const b = new Uint8Array(16);
|
|
226
548
|
crypto.getRandomValues(b);
|
|
@@ -247,9 +569,17 @@ function b64ToBytes(b64) {
|
|
|
247
569
|
out[i] = binary.charCodeAt(i);
|
|
248
570
|
return out;
|
|
249
571
|
}
|
|
250
|
-
var NS_WORKER;
|
|
572
|
+
var SHARD_KEY_RE, ANONYMOUS_SHARD_KEY = "loc-anon", RetryableError, NS_WORKER;
|
|
251
573
|
var init_storage_cf_do = __esm(() => {
|
|
252
574
|
init_storage();
|
|
575
|
+
SHARD_KEY_RE = /^[A-Za-z0-9._-]{1,128}$/;
|
|
576
|
+
RetryableError = class RetryableError extends Error {
|
|
577
|
+
retryAfterMs;
|
|
578
|
+
constructor(message, retryAfterMs = null) {
|
|
579
|
+
super(message);
|
|
580
|
+
this.retryAfterMs = retryAfterMs;
|
|
581
|
+
}
|
|
582
|
+
};
|
|
253
583
|
NS_WORKER = new TextEncoder().encode("worker");
|
|
254
584
|
});
|
|
255
585
|
|
|
@@ -274,10 +604,10 @@ function _loadDatabase() {
|
|
|
274
604
|
function _loadNodeIo() {
|
|
275
605
|
const r = _req();
|
|
276
606
|
return {
|
|
277
|
-
homedir: r(
|
|
278
|
-
platform: r(
|
|
279
|
-
join: r(
|
|
280
|
-
mkdirSync: r(
|
|
607
|
+
homedir: r(_NODE_OS_MOD).homedir,
|
|
608
|
+
platform: r(_NODE_OS_MOD).platform,
|
|
609
|
+
join: r(_NODE_PATH_MOD).join,
|
|
610
|
+
mkdirSync: r(_NODE_FS_MOD).mkdirSync
|
|
281
611
|
};
|
|
282
612
|
}
|
|
283
613
|
function hexEncode(buf) {
|
|
@@ -298,7 +628,7 @@ function getDefaultDbPath() {
|
|
|
298
628
|
const { homedir, platform, join, mkdirSync } = _loadNodeIo();
|
|
299
629
|
const home = homedir();
|
|
300
630
|
const stateDir = platform() === "darwin" ? join(home, "Library", "Application Support", "vgi") : join(home, ".local", "state", "vgi");
|
|
301
|
-
mkdirSync(stateDir, { recursive: true });
|
|
631
|
+
mkdirSync(stateDir, { recursive: true, mode: 448 });
|
|
302
632
|
return join(stateDir, "vgi_storage.db");
|
|
303
633
|
}
|
|
304
634
|
function int64Key(v) {
|
|
@@ -410,6 +740,33 @@ class FunctionStorageSqlite {
|
|
|
410
740
|
async statePut(scopeId, ns, key, value) {
|
|
411
741
|
this._db.prepare("INSERT OR REPLACE INTO function_state (scope_id, ns, key, value) VALUES (?, ?, ?, ?)").run(bufferArg(scopeId), bufferArg(ns), bufferArg(key), bufferArg(value));
|
|
412
742
|
}
|
|
743
|
+
async stateGetMany(scopeId, ns, keys) {
|
|
744
|
+
if (keys.length === 0)
|
|
745
|
+
return [];
|
|
746
|
+
const stmt = this._db.prepare("SELECT value FROM function_state WHERE scope_id = ? AND ns = ? AND key = ?");
|
|
747
|
+
const sid = bufferArg(scopeId);
|
|
748
|
+
const nsb = bufferArg(ns);
|
|
749
|
+
return keys.map((k) => {
|
|
750
|
+
const row = stmt.get(sid, nsb, bufferArg(k));
|
|
751
|
+
return row ? new Uint8Array(row.value) : null;
|
|
752
|
+
});
|
|
753
|
+
}
|
|
754
|
+
async statePutMany(scopeId, ns, items) {
|
|
755
|
+
if (items.length === 0)
|
|
756
|
+
return;
|
|
757
|
+
const stmt = this._db.prepare("INSERT OR REPLACE INTO function_state (scope_id, ns, key, value) VALUES (?, ?, ?, ?)");
|
|
758
|
+
const sid = bufferArg(scopeId);
|
|
759
|
+
const nsb = bufferArg(ns);
|
|
760
|
+
this._db.exec("BEGIN IMMEDIATE");
|
|
761
|
+
try {
|
|
762
|
+
for (const [k, v] of items)
|
|
763
|
+
stmt.run(sid, nsb, bufferArg(k), bufferArg(v));
|
|
764
|
+
this._db.exec("COMMIT");
|
|
765
|
+
} catch (e) {
|
|
766
|
+
this._db.exec("ROLLBACK");
|
|
767
|
+
throw e;
|
|
768
|
+
}
|
|
769
|
+
}
|
|
413
770
|
async stateAppend(scopeId, ns, key, item) {
|
|
414
771
|
const res = this._db.prepare("INSERT INTO function_state_log (scope_id, ns, key, value) VALUES (?, ?, ?, ?)").run(bufferArg(scopeId), bufferArg(ns), bufferArg(key), bufferArg(item));
|
|
415
772
|
return Number(res.lastInsertRowid);
|
|
@@ -470,10 +827,18 @@ class BoundStorage {
|
|
|
470
827
|
_base;
|
|
471
828
|
_executionId;
|
|
472
829
|
_substreamId;
|
|
473
|
-
|
|
474
|
-
|
|
830
|
+
_shardKey;
|
|
831
|
+
constructor(storage, executionId, substreamId = null, shardKey = "") {
|
|
832
|
+
this._base = typeof storage.forShard === "function" ? storage.forShard(shardKey) : storage;
|
|
475
833
|
this._executionId = executionId;
|
|
476
834
|
this._substreamId = substreamId;
|
|
835
|
+
this._shardKey = shardKey;
|
|
836
|
+
}
|
|
837
|
+
get shardKey() {
|
|
838
|
+
return this._shardKey;
|
|
839
|
+
}
|
|
840
|
+
get executionId() {
|
|
841
|
+
return this._executionId;
|
|
477
842
|
}
|
|
478
843
|
put(state) {
|
|
479
844
|
return this._base.workerPut(this._executionId, this._substreamId ?? process.pid, state);
|
|
@@ -499,6 +864,12 @@ class BoundStorage {
|
|
|
499
864
|
statePut(ns, key, value) {
|
|
500
865
|
return this._base.statePut(this._executionId, ns, key, value);
|
|
501
866
|
}
|
|
867
|
+
stateGetMany(ns, keys) {
|
|
868
|
+
return this._base.stateGetMany(this._executionId, ns, keys);
|
|
869
|
+
}
|
|
870
|
+
statePutMany(ns, items) {
|
|
871
|
+
return this._base.statePutMany(this._executionId, ns, items);
|
|
872
|
+
}
|
|
502
873
|
stateAppend(ns, key, item) {
|
|
503
874
|
return this._base.stateAppend(this._executionId, ns, key, item);
|
|
504
875
|
}
|
|
@@ -508,10 +879,28 @@ class BoundStorage {
|
|
|
508
879
|
executionClear() {
|
|
509
880
|
return this._base.executionClear(this._executionId);
|
|
510
881
|
}
|
|
882
|
+
_slot(ns, key) {
|
|
883
|
+
return { shardKey: this._shardKey, scopeId: this._executionId, ns, key };
|
|
884
|
+
}
|
|
885
|
+
async sealedPut(ns, key, payload, signingKey) {
|
|
886
|
+
const sealed = await sealPayload(payload, signingKey, this._slot(ns, key));
|
|
887
|
+
await this.statePut(ns, key, sealed);
|
|
888
|
+
return sealed;
|
|
889
|
+
}
|
|
890
|
+
openSealed(ns, key, sealed, signingKey) {
|
|
891
|
+
return openPayload(sealed, signingKey, this._slot(ns, key));
|
|
892
|
+
}
|
|
893
|
+
async sealedGet(ns, key, signingKey) {
|
|
894
|
+
const sealed = await this.stateGet(ns, key);
|
|
895
|
+
return sealed == null ? null : this.openSealed(ns, key, sealed, signingKey);
|
|
896
|
+
}
|
|
511
897
|
static packIntKey(i) {
|
|
512
898
|
return packIntKey(i);
|
|
513
899
|
}
|
|
514
900
|
}
|
|
901
|
+
function shardKeyOf(bindCall) {
|
|
902
|
+
return bindCall?.storage_shard_key ?? "";
|
|
903
|
+
}
|
|
515
904
|
function resolveStorageFromEnv() {
|
|
516
905
|
const backend = (process.env.VGI_WORKER_SHARED_STORAGE ?? "sqlite").toLowerCase();
|
|
517
906
|
if (backend === "memory") {
|
|
@@ -534,8 +923,9 @@ function getDefaultStorage() {
|
|
|
534
923
|
function bufferArg(data) {
|
|
535
924
|
return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
|
|
536
925
|
}
|
|
537
|
-
var _BUN_SQLITE_MOD = "bun:sqlite",
|
|
926
|
+
var _BUN_SQLITE_MOD = "bun:sqlite", _NODE_OS_MOD = "node:os", _NODE_PATH_MOD = "node:path", _NODE_FS_MOD = "node:fs", _Database = null, UnknownInvocationError, FrameworkNS, NS_WORKER2, BUSY_TIMEOUT_MS = 30000, _SLEEP_CELL, _resolved = null, storage;
|
|
538
927
|
var init_storage = __esm(() => {
|
|
928
|
+
init_storage_seal();
|
|
539
929
|
UnknownInvocationError = class UnknownInvocationError extends Error {
|
|
540
930
|
constructor(message) {
|
|
541
931
|
let text;
|
|
@@ -550,7 +940,8 @@ var init_storage = __esm(() => {
|
|
|
550
940
|
};
|
|
551
941
|
FrameworkNS = {
|
|
552
942
|
BUFFERING_INIT: textBytes("_vgi/buffering_init"),
|
|
553
|
-
STREAMING_FINALIZE: textBytes("_vgi/streaming_finalize")
|
|
943
|
+
STREAMING_FINALIZE: textBytes("_vgi/streaming_finalize"),
|
|
944
|
+
AGGREGATE_STATE: textBytes("_vgi/aggregate_state")
|
|
554
945
|
};
|
|
555
946
|
NS_WORKER2 = new TextEncoder().encode("worker");
|
|
556
947
|
_SLEEP_CELL = new Int32Array(new SharedArrayBuffer(4));
|
|
@@ -3981,6 +4372,48 @@ function unwrapScalar(val) {
|
|
|
3981
4372
|
}
|
|
3982
4373
|
|
|
3983
4374
|
// src/protocol/serializers/arguments.ts
|
|
4375
|
+
function serializeArguments(args) {
|
|
4376
|
+
const structFields = [];
|
|
4377
|
+
const structValues = {};
|
|
4378
|
+
for (let i = 0;i < args.positional.length; i++) {
|
|
4379
|
+
const val = args.positional[i];
|
|
4380
|
+
const fieldName = `positional_${i}`;
|
|
4381
|
+
structFields.push(field2(fieldName, inferScalarType(val), true));
|
|
4382
|
+
structValues[fieldName] = val;
|
|
4383
|
+
}
|
|
4384
|
+
for (const [name, val] of args.named) {
|
|
4385
|
+
const fieldName = `named_${name}`;
|
|
4386
|
+
structFields.push(field2(fieldName, inferScalarType(val), true));
|
|
4387
|
+
structValues[fieldName] = val;
|
|
4388
|
+
}
|
|
4389
|
+
const structType = struct2(structFields);
|
|
4390
|
+
const sch = schema2([field2("args", structType, true)]);
|
|
4391
|
+
const structRow = {};
|
|
4392
|
+
for (const f of structFields) {
|
|
4393
|
+
let val = structValues[f.name];
|
|
4394
|
+
if (isInt(f.type) && f.type.bitWidth === 64 && typeof val === "number") {
|
|
4395
|
+
val = BigInt(val);
|
|
4396
|
+
}
|
|
4397
|
+
structRow[f.name] = val;
|
|
4398
|
+
}
|
|
4399
|
+
const batch = batchFromColumns({ args: [structRow] }, sch);
|
|
4400
|
+
return serializeBatch(batch);
|
|
4401
|
+
}
|
|
4402
|
+
function inferScalarType(val) {
|
|
4403
|
+
if (val === null || val === undefined)
|
|
4404
|
+
return nullType2();
|
|
4405
|
+
if (typeof val === "string")
|
|
4406
|
+
return utf82();
|
|
4407
|
+
if (typeof val === "boolean")
|
|
4408
|
+
return bool2();
|
|
4409
|
+
if (typeof val === "number")
|
|
4410
|
+
return int642();
|
|
4411
|
+
if (typeof val === "bigint")
|
|
4412
|
+
return int642();
|
|
4413
|
+
if (val instanceof Uint8Array || val instanceof ArrayBuffer)
|
|
4414
|
+
return binary2();
|
|
4415
|
+
return utf82();
|
|
4416
|
+
}
|
|
3984
4417
|
function deserializeArguments(bytes) {
|
|
3985
4418
|
if (!bytes || bytes.length === 0)
|
|
3986
4419
|
return new Arguments;
|
|
@@ -4168,6 +4601,18 @@ function toUint8Array2(val) {
|
|
|
4168
4601
|
}
|
|
4169
4602
|
return result;
|
|
4170
4603
|
}
|
|
4604
|
+
function buildSingleRowBatch(schema, values) {
|
|
4605
|
+
const cols = {};
|
|
4606
|
+
const row = conformRecord(schema, values);
|
|
4607
|
+
for (const f of schema.fields) {
|
|
4608
|
+
let val = row[f.name];
|
|
4609
|
+
if (isInt(f.type) && f.type.bitWidth === 64 && typeof val === "number") {
|
|
4610
|
+
val = BigInt(val);
|
|
4611
|
+
}
|
|
4612
|
+
cols[f.name] = [val];
|
|
4613
|
+
}
|
|
4614
|
+
return batchFromColumns(cols, schema);
|
|
4615
|
+
}
|
|
4171
4616
|
|
|
4172
4617
|
// src/protocol/serializers/bind.ts
|
|
4173
4618
|
var COPY_FROM_STRUCT_TYPE = struct2([
|
|
@@ -4196,6 +4641,29 @@ var BIND_REQUEST_SCHEMA = schema2([
|
|
|
4196
4641
|
field2("schema_path", list2(field2("item", utf82(), true)), true),
|
|
4197
4642
|
field2("argument_names", list2(field2("item", utf82(), true)), true)
|
|
4198
4643
|
]);
|
|
4644
|
+
function serializeBindRequest(req) {
|
|
4645
|
+
return buildSingleRowBatch(BIND_REQUEST_SCHEMA, {
|
|
4646
|
+
function_name: req.function_name,
|
|
4647
|
+
arguments: serializeArguments(req.arguments),
|
|
4648
|
+
function_type: req.function_type == null ? req.function_type : String(req.function_type).toUpperCase(),
|
|
4649
|
+
input_schema: req.input_schema ? serializeSchema(req.input_schema) : null,
|
|
4650
|
+
settings: req.settings ? serializeBatch(req.settings) : null,
|
|
4651
|
+
secrets: req.secrets ? serializeBatch(req.secrets) : null,
|
|
4652
|
+
attach_opaque_data: req.attach_opaque_data ?? null,
|
|
4653
|
+
transaction_opaque_data: req.transaction_opaque_data ?? null,
|
|
4654
|
+
resolved_secrets_provided: req.resolved_secrets_provided ?? false,
|
|
4655
|
+
at_unit: req.at_unit ?? null,
|
|
4656
|
+
at_value: req.at_value ?? null,
|
|
4657
|
+
copy_from: req.copy_from ? {
|
|
4658
|
+
format: req.copy_from.format,
|
|
4659
|
+
file_path: req.copy_from.file_path,
|
|
4660
|
+
expected_schema: serializeSchema(req.copy_from.expected_schema)
|
|
4661
|
+
} : null,
|
|
4662
|
+
copy_to: req.copy_to ? { format: req.copy_to.format, file_path: req.copy_to.file_path } : null,
|
|
4663
|
+
schema_path: req.schema_path ?? null,
|
|
4664
|
+
argument_names: req.argument_names ?? null
|
|
4665
|
+
});
|
|
4666
|
+
}
|
|
4199
4667
|
function parseCopyFromContext(raw) {
|
|
4200
4668
|
if (raw == null)
|
|
4201
4669
|
return null;
|
|
@@ -4327,6 +4795,32 @@ var GLOBAL_INIT_RESPONSE_SCHEMA = schema2([
|
|
|
4327
4795
|
field2("opaque_data", binary2(), true),
|
|
4328
4796
|
field2("max_workers", int642(), false)
|
|
4329
4797
|
]);
|
|
4798
|
+
function serializeInitRequest(req) {
|
|
4799
|
+
const bindCallBatch = serializeBindRequest(req.bind_call);
|
|
4800
|
+
const bindCallBytes = serializeBatch(bindCallBatch);
|
|
4801
|
+
const row = {
|
|
4802
|
+
bind_call: bindCallBytes,
|
|
4803
|
+
output_schema: serializeSchema(req.output_schema),
|
|
4804
|
+
bind_opaque_data: req.bind_opaque_data ?? null,
|
|
4805
|
+
projection_ids: req.projection_ids?.map((n) => BigInt(n)) ?? null,
|
|
4806
|
+
pushdown_filters: req.pushdown_filters ? serializeBatch(req.pushdown_filters) : null,
|
|
4807
|
+
join_keys: (req.join_keys ?? []).map((b) => serializeBatch(b)),
|
|
4808
|
+
split_tokens: req.split_tokens ?? null,
|
|
4809
|
+
row_limit: req.row_limit ?? null,
|
|
4810
|
+
phase: req.phase ?? null,
|
|
4811
|
+
finalize_state_id: req.finalize_state_id ?? null,
|
|
4812
|
+
execution_id: req.execution_id ?? null,
|
|
4813
|
+
init_opaque_data: req.init_opaque_data ?? null,
|
|
4814
|
+
substream_id: req.substream_id ?? null,
|
|
4815
|
+
order_by_column_name: req.order_by_column_name ?? null,
|
|
4816
|
+
order_by_direction: req.order_by_direction ?? null,
|
|
4817
|
+
order_by_null_order: req.order_by_null_order ?? null,
|
|
4818
|
+
order_by_limit: req.order_by_limit ?? null,
|
|
4819
|
+
tablesample_percentage: req.tablesample_percentage ?? null,
|
|
4820
|
+
tablesample_seed: req.tablesample_seed ?? null
|
|
4821
|
+
};
|
|
4822
|
+
return buildSingleRowBatch(INIT_REQUEST_SCHEMA, row);
|
|
4823
|
+
}
|
|
4330
4824
|
function deserializeInitRequest(params) {
|
|
4331
4825
|
const bindCallBytes = toUint8Array2(params.bind_call);
|
|
4332
4826
|
const bindCallBatch = deserializeBatch(bindCallBytes);
|
|
@@ -8727,17 +9221,238 @@ function refuseMoreOutput(name, out) {
|
|
|
8727
9221
|
}
|
|
8728
9222
|
}
|
|
8729
9223
|
|
|
8730
|
-
// src/
|
|
8731
|
-
|
|
8732
|
-
|
|
8733
|
-
|
|
8734
|
-
|
|
8735
|
-
|
|
8736
|
-
|
|
8737
|
-
|
|
8738
|
-
}
|
|
8739
|
-
|
|
8740
|
-
|
|
9224
|
+
// src/errors.ts
|
|
9225
|
+
class VgiError extends Error {
|
|
9226
|
+
errorCode;
|
|
9227
|
+
constructor(message, code) {
|
|
9228
|
+
super(message);
|
|
9229
|
+
this.name = "VgiError";
|
|
9230
|
+
if (code !== undefined)
|
|
9231
|
+
this.errorCode = code;
|
|
9232
|
+
}
|
|
9233
|
+
}
|
|
9234
|
+
class ArgumentValidationError extends VgiError {
|
|
9235
|
+
constructor(message) {
|
|
9236
|
+
super(message, "INVALID_ARGUMENT");
|
|
9237
|
+
this.name = "ArgumentValidationError";
|
|
9238
|
+
}
|
|
9239
|
+
}
|
|
9240
|
+
|
|
9241
|
+
class NoCatalogError extends VgiError {
|
|
9242
|
+
constructor() {
|
|
9243
|
+
super("No catalog is configured for this worker", "UNIMPLEMENTED");
|
|
9244
|
+
this.name = "NoCatalogError";
|
|
9245
|
+
}
|
|
9246
|
+
}
|
|
9247
|
+
|
|
9248
|
+
// src/arguments/argument-spec.ts
|
|
9249
|
+
function toNumber(value) {
|
|
9250
|
+
if (typeof value === "number")
|
|
9251
|
+
return value;
|
|
9252
|
+
if (typeof value === "bigint")
|
|
9253
|
+
return Number(value);
|
|
9254
|
+
return;
|
|
9255
|
+
}
|
|
9256
|
+
function choiceEquals(choice, value) {
|
|
9257
|
+
const cn = toNumber(choice);
|
|
9258
|
+
const vn = toNumber(value);
|
|
9259
|
+
if (cn !== undefined && vn !== undefined)
|
|
9260
|
+
return cn === vn;
|
|
9261
|
+
return choice === value;
|
|
9262
|
+
}
|
|
9263
|
+
function validateConstConstraints(name, constraints, value) {
|
|
9264
|
+
if (value === null || value === undefined)
|
|
9265
|
+
return;
|
|
9266
|
+
const num = toNumber(value);
|
|
9267
|
+
if (num !== undefined) {
|
|
9268
|
+
if (constraints.ge !== undefined && num < constraints.ge) {
|
|
9269
|
+
throw new ArgumentValidationError(`argument '${name}' must be >= ${constraints.ge}`);
|
|
9270
|
+
}
|
|
9271
|
+
if (constraints.le !== undefined && num > constraints.le) {
|
|
9272
|
+
throw new ArgumentValidationError(`argument '${name}' must be <= ${constraints.le}`);
|
|
9273
|
+
}
|
|
9274
|
+
if (constraints.gt !== undefined && num <= constraints.gt) {
|
|
9275
|
+
throw new ArgumentValidationError(`argument '${name}' must be > ${constraints.gt}`);
|
|
9276
|
+
}
|
|
9277
|
+
if (constraints.lt !== undefined && num >= constraints.lt) {
|
|
9278
|
+
throw new ArgumentValidationError(`argument '${name}' must be < ${constraints.lt}`);
|
|
9279
|
+
}
|
|
9280
|
+
}
|
|
9281
|
+
if (constraints.choices !== undefined && constraints.choices.length > 0) {
|
|
9282
|
+
if (!constraints.choices.some((c) => choiceEquals(c, value))) {
|
|
9283
|
+
throw new ArgumentValidationError(`argument '${name}' must be one of ${JSON.stringify([...constraints.choices])}`);
|
|
9284
|
+
}
|
|
9285
|
+
}
|
|
9286
|
+
if (constraints.pattern !== undefined && typeof value === "string") {
|
|
9287
|
+
let re;
|
|
9288
|
+
try {
|
|
9289
|
+
re = new RegExp(constraints.pattern);
|
|
9290
|
+
} catch {
|
|
9291
|
+
re = undefined;
|
|
9292
|
+
}
|
|
9293
|
+
if (re !== undefined && !re.test(value)) {
|
|
9294
|
+
throw new ArgumentValidationError(`argument '${name}' must match pattern ${JSON.stringify(constraints.pattern)}`);
|
|
9295
|
+
}
|
|
9296
|
+
}
|
|
9297
|
+
}
|
|
9298
|
+
|
|
9299
|
+
// src/functions/table-buffering.ts
|
|
9300
|
+
init_storage();
|
|
9301
|
+
|
|
9302
|
+
// src/functions/execution-cache.ts
|
|
9303
|
+
function hex2(b) {
|
|
9304
|
+
let s = "";
|
|
9305
|
+
for (let i = 0;i < b.length; i++)
|
|
9306
|
+
s += b[i].toString(16).padStart(2, "0");
|
|
9307
|
+
return s;
|
|
9308
|
+
}
|
|
9309
|
+
|
|
9310
|
+
class ExecutionCache {
|
|
9311
|
+
maxEntries;
|
|
9312
|
+
_map = new Map;
|
|
9313
|
+
constructor(maxEntries) {
|
|
9314
|
+
this.maxEntries = maxEntries;
|
|
9315
|
+
}
|
|
9316
|
+
static _key(shardKey, executionId) {
|
|
9317
|
+
return `${shardKey}\x00${hex2(executionId)}`;
|
|
9318
|
+
}
|
|
9319
|
+
get(shardKey, executionId) {
|
|
9320
|
+
const k = ExecutionCache._key(shardKey, executionId);
|
|
9321
|
+
const v = this._map.get(k);
|
|
9322
|
+
if (v === undefined)
|
|
9323
|
+
return;
|
|
9324
|
+
this._map.delete(k);
|
|
9325
|
+
this._map.set(k, v);
|
|
9326
|
+
return v;
|
|
9327
|
+
}
|
|
9328
|
+
set(shardKey, executionId, value) {
|
|
9329
|
+
const k = ExecutionCache._key(shardKey, executionId);
|
|
9330
|
+
this._map.delete(k);
|
|
9331
|
+
this._map.set(k, value);
|
|
9332
|
+
while (this._map.size > this.maxEntries) {
|
|
9333
|
+
this._map.delete(this._map.keys().next().value);
|
|
9334
|
+
}
|
|
9335
|
+
}
|
|
9336
|
+
delete(shardKey, executionId) {
|
|
9337
|
+
this._map.delete(ExecutionCache._key(shardKey, executionId));
|
|
9338
|
+
}
|
|
9339
|
+
clear() {
|
|
9340
|
+
this._map.clear();
|
|
9341
|
+
}
|
|
9342
|
+
get size() {
|
|
9343
|
+
return this._map.size;
|
|
9344
|
+
}
|
|
9345
|
+
}
|
|
9346
|
+
|
|
9347
|
+
// src/functions/table-buffering.ts
|
|
9348
|
+
init_storage_seal();
|
|
9349
|
+
var BUFFERING_INIT_KEY = BoundStorage.packIntKey(-1);
|
|
9350
|
+
var bufferingInitCache = new ExecutionCache(64);
|
|
9351
|
+
async function persistBufferingInit(request, response, signingKey) {
|
|
9352
|
+
const shardKey = shardKeyOf(request.bind_call);
|
|
9353
|
+
const stored = {
|
|
9354
|
+
...request,
|
|
9355
|
+
bind_call: { ...request.bind_call, attach_opaque_data: null, transaction_opaque_data: null }
|
|
9356
|
+
};
|
|
9357
|
+
const bound = new BoundStorage(storage, response.execution_id, null, shardKey);
|
|
9358
|
+
await bound.sealedPut(FrameworkNS.BUFFERING_INIT, BUFFERING_INIT_KEY, encodeBufferingInit(stored, response), signingKey);
|
|
9359
|
+
bufferingInitCache.set(shardKey, response.execution_id, { request: stored, response });
|
|
9360
|
+
}
|
|
9361
|
+
async function loadBufferingInit(bound, signingKey) {
|
|
9362
|
+
const cached = bufferingInitCache.get(bound.shardKey, bound.executionId);
|
|
9363
|
+
if (cached)
|
|
9364
|
+
return cached;
|
|
9365
|
+
const payload = await bound.sealedGet(FrameworkNS.BUFFERING_INIT, BUFFERING_INIT_KEY, signingKey);
|
|
9366
|
+
if (payload == null) {
|
|
9367
|
+
throw new Error(`table_buffering: unknown execution_id ${hexOf(bound.executionId)} ` + `(init never ran or destructor already fired)`);
|
|
9368
|
+
}
|
|
9369
|
+
const decoded = decodeBufferingInit(payload);
|
|
9370
|
+
bufferingInitCache.set(bound.shardKey, bound.executionId, decoded);
|
|
9371
|
+
return decoded;
|
|
9372
|
+
}
|
|
9373
|
+
function hexOf(buf) {
|
|
9374
|
+
return Array.from(buf, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
9375
|
+
}
|
|
9376
|
+
function encodeBufferingInit(request, response) {
|
|
9377
|
+
const initBatch = serializeInitRequest(request);
|
|
9378
|
+
const initBytes = serializeBatch(initBatch);
|
|
9379
|
+
const respBatch = serializeGlobalInitResponse(response);
|
|
9380
|
+
const respBytes = encodeGlobalInitResponse(respBatch);
|
|
9381
|
+
return concatLenPrefixed([initBytes, respBytes]);
|
|
9382
|
+
}
|
|
9383
|
+
function decodeBufferingInit(payload) {
|
|
9384
|
+
const [initBytes, respBytes] = splitLenPrefixed(payload, 2);
|
|
9385
|
+
const initBatch = deserializeBatch(initBytes);
|
|
9386
|
+
const initDict = batchToScalarDict(initBatch);
|
|
9387
|
+
const request = deserializeInitRequest(initDict);
|
|
9388
|
+
const response = decodeGlobalInitResponse(respBytes);
|
|
9389
|
+
return { request, response };
|
|
9390
|
+
}
|
|
9391
|
+
function encodeGlobalInitResponse(dict) {
|
|
9392
|
+
const eid = dict.execution_id ?? new Uint8Array(0);
|
|
9393
|
+
const opaque = dict.opaque_data ?? null;
|
|
9394
|
+
const maxWorkers = Number(dict.max_workers ?? 1);
|
|
9395
|
+
const mwBuf = new Uint8Array(8);
|
|
9396
|
+
new DataView(mwBuf.buffer).setBigInt64(0, BigInt(maxWorkers), true);
|
|
9397
|
+
return concatLenPrefixed([eid, opaque ?? new Uint8Array(0), mwBuf]);
|
|
9398
|
+
}
|
|
9399
|
+
function decodeGlobalInitResponse(bytes) {
|
|
9400
|
+
const [eid, opaque, mwBuf] = splitLenPrefixed(bytes, 3);
|
|
9401
|
+
const maxWorkers = Number(new DataView(mwBuf.buffer, mwBuf.byteOffset, 8).getBigInt64(0, true));
|
|
9402
|
+
return {
|
|
9403
|
+
execution_id: eid,
|
|
9404
|
+
opaque_data: opaque.length > 0 ? opaque : null,
|
|
9405
|
+
max_workers: maxWorkers
|
|
9406
|
+
};
|
|
9407
|
+
}
|
|
9408
|
+
function concatLenPrefixed(parts) {
|
|
9409
|
+
let total = 0;
|
|
9410
|
+
for (const p of parts)
|
|
9411
|
+
total += 4 + p.length;
|
|
9412
|
+
const out = new Uint8Array(total);
|
|
9413
|
+
const dv = new DataView(out.buffer);
|
|
9414
|
+
let off = 0;
|
|
9415
|
+
for (const p of parts) {
|
|
9416
|
+
dv.setUint32(off, p.length, true);
|
|
9417
|
+
off += 4;
|
|
9418
|
+
out.set(p, off);
|
|
9419
|
+
off += p.length;
|
|
9420
|
+
}
|
|
9421
|
+
return out;
|
|
9422
|
+
}
|
|
9423
|
+
function splitLenPrefixed(buf, count) {
|
|
9424
|
+
const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
9425
|
+
const parts = [];
|
|
9426
|
+
let off = 0;
|
|
9427
|
+
for (let i = 0;i < count; i++) {
|
|
9428
|
+
if (off + 4 > buf.length) {
|
|
9429
|
+
throw new StoragePayloadError(`table_buffering: truncated init payload (part ${i} header)`);
|
|
9430
|
+
}
|
|
9431
|
+
const len = dv.getUint32(off, true);
|
|
9432
|
+
off += 4;
|
|
9433
|
+
if (len > buf.length - off) {
|
|
9434
|
+
throw new StoragePayloadError(`table_buffering: truncated init payload (part ${i} is ${len} bytes, ${buf.length - off} left)`);
|
|
9435
|
+
}
|
|
9436
|
+
parts.push(buf.subarray(off, off + len));
|
|
9437
|
+
off += len;
|
|
9438
|
+
}
|
|
9439
|
+
if (off !== buf.length) {
|
|
9440
|
+
throw new StoragePayloadError(`table_buffering: ${buf.length - off} trailing bytes in init payload`);
|
|
9441
|
+
}
|
|
9442
|
+
return parts;
|
|
9443
|
+
}
|
|
9444
|
+
|
|
9445
|
+
// src/util/statistics.ts
|
|
9446
|
+
function serializeColumnStatistics(stats, _cacheMaxAgeSeconds) {
|
|
9447
|
+
return serializeBatch(buildStatisticsBatch(stats));
|
|
9448
|
+
}
|
|
9449
|
+
|
|
9450
|
+
// src/schema-path.ts
|
|
9451
|
+
function normalizeSchemaPath(path) {
|
|
9452
|
+
return typeof path === "string" ? [path] : Array.from(path, String);
|
|
9453
|
+
}
|
|
9454
|
+
|
|
9455
|
+
// src/protocol/handlers/shared.ts
|
|
8741
9456
|
var RESULT_BINARY_SCHEMA = schema2([
|
|
8742
9457
|
field2("result", binary2(), false)
|
|
8743
9458
|
]);
|
|
@@ -8781,30 +9496,6 @@ function overloadContext(req, catalogInterface) {
|
|
|
8781
9496
|
};
|
|
8782
9497
|
}
|
|
8783
9498
|
|
|
8784
|
-
// src/errors.ts
|
|
8785
|
-
class VgiError extends Error {
|
|
8786
|
-
errorCode;
|
|
8787
|
-
constructor(message, code) {
|
|
8788
|
-
super(message);
|
|
8789
|
-
this.name = "VgiError";
|
|
8790
|
-
if (code !== undefined)
|
|
8791
|
-
this.errorCode = code;
|
|
8792
|
-
}
|
|
8793
|
-
}
|
|
8794
|
-
class ArgumentValidationError extends VgiError {
|
|
8795
|
-
constructor(message) {
|
|
8796
|
-
super(message, "INVALID_ARGUMENT");
|
|
8797
|
-
this.name = "ArgumentValidationError";
|
|
8798
|
-
}
|
|
8799
|
-
}
|
|
8800
|
-
|
|
8801
|
-
class NoCatalogError extends VgiError {
|
|
8802
|
-
constructor() {
|
|
8803
|
-
super("No catalog is configured for this worker", "UNIMPLEMENTED");
|
|
8804
|
-
this.name = "NoCatalogError";
|
|
8805
|
-
}
|
|
8806
|
-
}
|
|
8807
|
-
|
|
8808
9499
|
// node_modules/@noble/ciphers/utils.js
|
|
8809
9500
|
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
|
|
8810
9501
|
function isBytes(a) {
|
|
@@ -9523,9 +10214,9 @@ var _UTF8 = new TextEncoder;
|
|
|
9523
10214
|
var ATTACH_ENVELOPE_VERSION = 2;
|
|
9524
10215
|
var TRANSACTION_ENVELOPE_VERSION = 2;
|
|
9525
10216
|
var ATTACH_UUID_LEN = 16;
|
|
9526
|
-
var
|
|
9527
|
-
var
|
|
9528
|
-
var MIN_ENVELOPE_LEN = 1 +
|
|
10217
|
+
var NONCE_LEN2 = 24;
|
|
10218
|
+
var TAG_LEN2 = 16;
|
|
10219
|
+
var MIN_ENVELOPE_LEN = 1 + NONCE_LEN2 + TAG_LEN2;
|
|
9529
10220
|
var ATTACH_AAD_PREFIX = _UTF8.encode("vgi.attach_opaque_data.v1\x00");
|
|
9530
10221
|
var TRANSACTION_AAD_PREFIX = _UTF8.encode("vgi.transaction_opaque_data.v1\x00");
|
|
9531
10222
|
|
|
@@ -9537,7 +10228,7 @@ class OpaqueDataRejectedError extends Error {
|
|
|
9537
10228
|
this.name = "OpaqueDataRejectedError";
|
|
9538
10229
|
}
|
|
9539
10230
|
}
|
|
9540
|
-
function
|
|
10231
|
+
function concat2(...parts) {
|
|
9541
10232
|
let total = 0;
|
|
9542
10233
|
for (const p of parts)
|
|
9543
10234
|
total += p.length;
|
|
@@ -9549,201 +10240,59 @@ function concat(...parts) {
|
|
|
9549
10240
|
}
|
|
9550
10241
|
return out;
|
|
9551
10242
|
}
|
|
9552
|
-
async function normalizeKey(key) {
|
|
9553
|
-
if (key.length === 32)
|
|
9554
|
-
return key;
|
|
9555
|
-
return new Uint8Array(await crypto.subtle.digest("SHA-256", key));
|
|
9556
|
-
}
|
|
9557
|
-
function identityTail(auth) {
|
|
9558
|
-
if (!auth || !auth.authenticated)
|
|
9559
|
-
return _UTF8.encode("\x00anonymous");
|
|
9560
|
-
const domain = _UTF8.encode(auth.domain ?? "");
|
|
9561
|
-
const principal = _UTF8.encode(auth.principal ?? "");
|
|
9562
|
-
return
|
|
9563
|
-
}
|
|
9564
|
-
function attachAad(auth) {
|
|
9565
|
-
return
|
|
9566
|
-
}
|
|
9567
|
-
function transactionAad(auth, attachEnvelope) {
|
|
9568
|
-
return
|
|
9569
|
-
}
|
|
9570
|
-
async function sealBytes(payload, key, aad, version, fixedNonce) {
|
|
9571
|
-
if (fixedNonce !== undefined && fixedNonce.length !==
|
|
9572
|
-
throw new Error(`nonce must be ${
|
|
9573
|
-
}
|
|
9574
|
-
const nonce = fixedNonce ?? crypto.getRandomValues(new Uint8Array(NONCE_LEN));
|
|
9575
|
-
const ciphertext = xchacha20poly1305(await normalizeKey(key), nonce, aad).encrypt(payload);
|
|
9576
|
-
const out = new Uint8Array(1 + NONCE_LEN + ciphertext.length);
|
|
9577
|
-
out[0] = version & 255;
|
|
9578
|
-
out.set(nonce, 1);
|
|
9579
|
-
out.set(ciphertext, 1 + NONCE_LEN);
|
|
9580
|
-
return out;
|
|
9581
|
-
}
|
|
9582
|
-
async function openBytes(token, key, aad, version, field = "opaque data") {
|
|
9583
|
-
if (token.length < MIN_ENVELOPE_LEN || token[0] !== (version & 255)) {
|
|
9584
|
-
throw new OpaqueDataRejectedError(field);
|
|
9585
|
-
}
|
|
9586
|
-
const nonce = token.subarray(1, 1 + NONCE_LEN);
|
|
9587
|
-
const ciphertext = token.subarray(1 + NONCE_LEN);
|
|
9588
|
-
try {
|
|
9589
|
-
return xchacha20poly1305(await normalizeKey(key), nonce, aad).decrypt(ciphertext);
|
|
9590
|
-
} catch {
|
|
9591
|
-
throw new OpaqueDataRejectedError(field);
|
|
9592
|
-
}
|
|
9593
|
-
}
|
|
9594
|
-
|
|
9595
|
-
// src/attach-secret-keyfile.ts
|
|
9596
|
-
function builtins() {
|
|
9597
|
-
const proc = globalThis.process;
|
|
9598
|
-
const get = proc?.getBuiltinModule?.bind(proc);
|
|
9599
|
-
const fs = get?.("node:fs");
|
|
9600
|
-
const os = get?.("node:os");
|
|
9601
|
-
const path = get?.("node:path");
|
|
9602
|
-
if (!fs || !os || !path)
|
|
9603
|
-
throw new Error("this runtime has no filesystem for the host-local attach secret key file.");
|
|
9604
|
-
return { fs, os, path };
|
|
9605
|
-
}
|
|
9606
|
-
var ATTACH_SECRET_KEY_FILE_ENV = "VGI_ATTACH_SECRET_KEY_FILE";
|
|
9607
|
-
var KEY_LEN = 32;
|
|
9608
|
-
var FILE_NAME = "attach-secret-options.key";
|
|
9609
|
-
var REMEDY = "Set VGI_SIGNING_KEY (or configure attachSecretKey), or point VGI_ATTACH_SECRET_KEY_FILE at a valid key file.";
|
|
9610
|
-
function username() {
|
|
9611
|
-
try {
|
|
9612
|
-
const name = builtins().os.userInfo().username;
|
|
9613
|
-
if (name)
|
|
9614
|
-
return name;
|
|
9615
|
-
} catch {}
|
|
9616
|
-
return process.env.USER || process.env.USERNAME || String(process.getuid?.() ?? "user");
|
|
9617
|
-
}
|
|
9618
|
-
function isDirectory(path) {
|
|
9619
|
-
try {
|
|
9620
|
-
return builtins().fs.statSync(path).isDirectory();
|
|
9621
|
-
} catch {
|
|
9622
|
-
return false;
|
|
9623
|
-
}
|
|
9624
|
-
}
|
|
9625
|
-
function hostLocalAttachSecretKeyPath(env = globalThis.process?.env ?? {}) {
|
|
9626
|
-
const { os, path: { join } } = builtins();
|
|
9627
|
-
const explicit = env[ATTACH_SECRET_KEY_FILE_ENV];
|
|
9628
|
-
if (explicit)
|
|
9629
|
-
return explicit;
|
|
9630
|
-
const xdg = env.XDG_RUNTIME_DIR;
|
|
9631
|
-
if (xdg && isDirectory(xdg))
|
|
9632
|
-
return join(xdg, "vgi", FILE_NAME);
|
|
9633
|
-
return join(os.tmpdir(), `vgi-${username()}`, FILE_NAME);
|
|
9634
|
-
}
|
|
9635
|
-
var POSIX = typeof process === "undefined" || process.platform !== "win32";
|
|
9636
|
-
function checkOwnedPrivate(path, mode, uid, what) {
|
|
9637
|
-
if (!POSIX)
|
|
9638
|
-
return;
|
|
9639
|
-
const me = process.getuid?.();
|
|
9640
|
-
if (me !== undefined && uid !== me) {
|
|
9641
|
-
throw new Error(`attach secret key ${what} ${path} is not owned by the current user. ${REMEDY}`);
|
|
9642
|
-
}
|
|
9643
|
-
if ((mode & 63) !== 0) {
|
|
9644
|
-
throw new Error(`attach secret key ${what} ${path} is accessible by group/other (mode ${(mode & 511).toString(8)}); ` + `it must be ${what === "directory" ? "0700" : "0600"}. ${REMEDY}`);
|
|
9645
|
-
}
|
|
9646
|
-
}
|
|
9647
|
-
function ensureDir(dir) {
|
|
9648
|
-
const { mkdirSync, lstatSync } = builtins().fs;
|
|
9649
|
-
try {
|
|
9650
|
-
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
9651
|
-
} catch (e) {
|
|
9652
|
-
if (e.code !== "EEXIST")
|
|
9653
|
-
throw e;
|
|
9654
|
-
}
|
|
9655
|
-
const st = lstatSync(dir);
|
|
9656
|
-
if (!st.isDirectory())
|
|
9657
|
-
throw new Error(`attach secret key directory ${dir} is not a directory. ${REMEDY}`);
|
|
9658
|
-
checkOwnedPrivate(dir, st.mode, st.uid, "directory");
|
|
9659
|
-
}
|
|
9660
|
-
function readKey(path) {
|
|
9661
|
-
const { openSync, fstatSync, readSync, closeSync, constants } = builtins().fs;
|
|
9662
|
-
let fd;
|
|
9663
|
-
try {
|
|
9664
|
-
fd = openSync(path, constants.O_RDONLY | (POSIX ? constants.O_NOFOLLOW : 0));
|
|
9665
|
-
} catch (e) {
|
|
9666
|
-
if (e.code === "ENOENT")
|
|
9667
|
-
return null;
|
|
9668
|
-
throw new Error(`attach secret key file ${path} cannot be opened (${e.code}). ${REMEDY}`);
|
|
9669
|
-
}
|
|
9670
|
-
try {
|
|
9671
|
-
const st = fstatSync(fd);
|
|
9672
|
-
if (!st.isFile())
|
|
9673
|
-
throw new Error(`attach secret key file ${path} is not a regular file. ${REMEDY}`);
|
|
9674
|
-
checkOwnedPrivate(path, st.mode, st.uid, "file");
|
|
9675
|
-
const buf = new Uint8Array(KEY_LEN + 1);
|
|
9676
|
-
let n = 0;
|
|
9677
|
-
for (;; ) {
|
|
9678
|
-
const got = readSync(fd, buf, n, buf.length - n, null);
|
|
9679
|
-
if (got <= 0)
|
|
9680
|
-
break;
|
|
9681
|
-
n += got;
|
|
9682
|
-
if (n === buf.length)
|
|
9683
|
-
break;
|
|
9684
|
-
}
|
|
9685
|
-
if (n !== KEY_LEN || st.size !== KEY_LEN) {
|
|
9686
|
-
throw new Error(`attach secret key file ${path} must contain exactly ${KEY_LEN} raw bytes (found ${st.size}). ${REMEDY}`);
|
|
9687
|
-
}
|
|
9688
|
-
return buf.subarray(0, KEY_LEN);
|
|
9689
|
-
} finally {
|
|
9690
|
-
closeSync(fd);
|
|
10243
|
+
async function normalizeKey(key) {
|
|
10244
|
+
if (key.length === 32)
|
|
10245
|
+
return key;
|
|
10246
|
+
return new Uint8Array(await crypto.subtle.digest("SHA-256", key));
|
|
10247
|
+
}
|
|
10248
|
+
function identityTail(auth) {
|
|
10249
|
+
if (!auth || !auth.authenticated)
|
|
10250
|
+
return _UTF8.encode("\x00anonymous");
|
|
10251
|
+
const domain = _UTF8.encode(auth.domain ?? "");
|
|
10252
|
+
const principal = _UTF8.encode(auth.principal ?? "");
|
|
10253
|
+
return concat2(Uint8Array.of(1), domain, Uint8Array.of(0), principal);
|
|
10254
|
+
}
|
|
10255
|
+
function attachAad(auth) {
|
|
10256
|
+
return concat2(ATTACH_AAD_PREFIX, identityTail(auth));
|
|
10257
|
+
}
|
|
10258
|
+
function transactionAad(auth, attachEnvelope) {
|
|
10259
|
+
return concat2(TRANSACTION_AAD_PREFIX, identityTail(auth), Uint8Array.of(0), attachEnvelope);
|
|
10260
|
+
}
|
|
10261
|
+
async function sealBytes(payload, key, aad, version, fixedNonce) {
|
|
10262
|
+
if (fixedNonce !== undefined && fixedNonce.length !== NONCE_LEN2) {
|
|
10263
|
+
throw new Error(`nonce must be ${NONCE_LEN2} bytes`);
|
|
9691
10264
|
}
|
|
10265
|
+
const nonce = fixedNonce ?? crypto.getRandomValues(new Uint8Array(NONCE_LEN2));
|
|
10266
|
+
const ciphertext = xchacha20poly1305(await normalizeKey(key), nonce, aad).encrypt(payload);
|
|
10267
|
+
const out = new Uint8Array(1 + NONCE_LEN2 + ciphertext.length);
|
|
10268
|
+
out[0] = version & 255;
|
|
10269
|
+
out.set(nonce, 1);
|
|
10270
|
+
out.set(ciphertext, 1 + NONCE_LEN2);
|
|
10271
|
+
return out;
|
|
9692
10272
|
}
|
|
9693
|
-
function
|
|
9694
|
-
|
|
9695
|
-
|
|
9696
|
-
const tmp = join(dirname(path), `.${FILE_NAME}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);
|
|
9697
|
-
const fd = openSync(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 384);
|
|
9698
|
-
try {
|
|
9699
|
-
const key = crypto.getRandomValues(new Uint8Array(KEY_LEN));
|
|
9700
|
-
let off = 0;
|
|
9701
|
-
while (off < KEY_LEN)
|
|
9702
|
-
off += writeSync(fd, key, off, KEY_LEN - off);
|
|
9703
|
-
fsyncSync(fd);
|
|
9704
|
-
} finally {
|
|
9705
|
-
closeSync(fd);
|
|
10273
|
+
async function openBytes(token, key, aad, version, field = "opaque data") {
|
|
10274
|
+
if (token.length < MIN_ENVELOPE_LEN || token[0] !== (version & 255)) {
|
|
10275
|
+
throw new OpaqueDataRejectedError(field);
|
|
9706
10276
|
}
|
|
10277
|
+
const nonce = token.subarray(1, 1 + NONCE_LEN2);
|
|
10278
|
+
const ciphertext = token.subarray(1 + NONCE_LEN2);
|
|
9707
10279
|
try {
|
|
9708
|
-
|
|
9709
|
-
} catch
|
|
9710
|
-
|
|
9711
|
-
unlinkSync(tmp);
|
|
9712
|
-
throw e;
|
|
9713
|
-
}
|
|
10280
|
+
return xchacha20poly1305(await normalizeKey(key), nonce, aad).decrypt(ciphertext);
|
|
10281
|
+
} catch {
|
|
10282
|
+
throw new OpaqueDataRejectedError(field);
|
|
9714
10283
|
}
|
|
9715
|
-
unlinkSync(tmp);
|
|
9716
|
-
}
|
|
9717
|
-
function loadHostLocalAttachSecretKey(path = hostLocalAttachSecretKeyPath()) {
|
|
9718
|
-
ensureDir(builtins().path.dirname(path));
|
|
9719
|
-
const existing = readKey(path);
|
|
9720
|
-
if (existing)
|
|
9721
|
-
return existing;
|
|
9722
|
-
createKey(path);
|
|
9723
|
-
const created = readKey(path);
|
|
9724
|
-
if (!created)
|
|
9725
|
-
throw new Error(`attach secret key file ${path} vanished after creation. ${REMEDY}`);
|
|
9726
|
-
return created;
|
|
9727
|
-
}
|
|
9728
|
-
var cached;
|
|
9729
|
-
async function hostLocalAttachSecretKey() {
|
|
9730
|
-
const path = hostLocalAttachSecretKeyPath();
|
|
9731
|
-
if (cached?.path === path)
|
|
9732
|
-
return cached.key;
|
|
9733
|
-
const key = loadHostLocalAttachSecretKey(path);
|
|
9734
|
-
cached = { path, key };
|
|
9735
|
-
return key;
|
|
9736
10284
|
}
|
|
9737
10285
|
|
|
9738
10286
|
// src/attach-secret-options.ts
|
|
9739
|
-
|
|
10287
|
+
init_attach_secret_keyfile();
|
|
10288
|
+
var UTF83 = new TextEncoder;
|
|
9740
10289
|
var ATTACH_SECRET_OPTIONS_INFO = "vgi.attach_secret_options.v1";
|
|
9741
10290
|
var ATTACH_SECRET_OPTIONS_VERSION = 1;
|
|
9742
10291
|
var TRAILER_MAGIC = Uint8Array.of(0, 86, 71, 73, 65, 79, 1, 255);
|
|
9743
10292
|
var TRAILER_FIXED = 4 + TRAILER_MAGIC.length;
|
|
9744
|
-
var
|
|
9745
|
-
var
|
|
9746
|
-
var AAD_PREFIX =
|
|
10293
|
+
var NONCE_LEN3 = 24;
|
|
10294
|
+
var TAG_LEN3 = 16;
|
|
10295
|
+
var AAD_PREFIX = UTF83.encode(`${ATTACH_SECRET_OPTIONS_INFO}\x00`);
|
|
9747
10296
|
var UUID_LEN = 16;
|
|
9748
10297
|
var FIELD = "attach_opaque_data";
|
|
9749
10298
|
|
|
@@ -9754,19 +10303,19 @@ class AttachSecretKeyUnavailableError extends Error {
|
|
|
9754
10303
|
}
|
|
9755
10304
|
}
|
|
9756
10305
|
var subkeys = new Map;
|
|
9757
|
-
function
|
|
10306
|
+
function hexOf2(b) {
|
|
9758
10307
|
let s = "";
|
|
9759
10308
|
for (let i = 0;i < b.length; i++)
|
|
9760
10309
|
s += b[i].toString(16).padStart(2, "0");
|
|
9761
10310
|
return s;
|
|
9762
10311
|
}
|
|
9763
10312
|
function deriveAttachSecretKey(root) {
|
|
9764
|
-
const id =
|
|
10313
|
+
const id = hexOf2(root);
|
|
9765
10314
|
let derived = subkeys.get(id);
|
|
9766
10315
|
if (!derived) {
|
|
9767
10316
|
derived = (async () => {
|
|
9768
10317
|
const ikm = await crypto.subtle.importKey("raw", root, "HKDF", false, ["deriveBits"]);
|
|
9769
|
-
const bits = await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info:
|
|
10318
|
+
const bits = await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: UTF83.encode(ATTACH_SECRET_OPTIONS_INFO) }, ikm, 256);
|
|
9770
10319
|
return new Uint8Array(bits);
|
|
9771
10320
|
})();
|
|
9772
10321
|
subkeys.set(id, derived);
|
|
@@ -9801,7 +10350,7 @@ function u32le(n) {
|
|
|
9801
10350
|
function readU32le(b, off) {
|
|
9802
10351
|
return new DataView(b.buffer, b.byteOffset, b.byteLength).getUint32(off, true);
|
|
9803
10352
|
}
|
|
9804
|
-
function
|
|
10353
|
+
function concat3(...parts) {
|
|
9805
10354
|
let total = 0;
|
|
9806
10355
|
for (const p of parts)
|
|
9807
10356
|
total += p.length;
|
|
@@ -9855,12 +10404,12 @@ async function packAttachOptionsTrailer(uuid, optionsIpc, secretNames, keys, fix
|
|
|
9855
10404
|
throw new AttachSecretKeyUnavailableError(`${noKeyMessage()} ${e.message}`);
|
|
9856
10405
|
}
|
|
9857
10406
|
const key = await deriveAttachSecretKey(root);
|
|
9858
|
-
const nonce = fixedNonce ?? crypto.getRandomValues(new Uint8Array(
|
|
10407
|
+
const nonce = fixedNonce ?? crypto.getRandomValues(new Uint8Array(NONCE_LEN3));
|
|
9859
10408
|
const ct = xchacha20poly1305(key, nonce, aadFor(uuid)).encrypt(split.secret);
|
|
9860
|
-
secret =
|
|
10409
|
+
secret = concat3(Uint8Array.of(ATTACH_SECRET_OPTIONS_VERSION), nonce, ct);
|
|
9861
10410
|
}
|
|
9862
|
-
const body =
|
|
9863
|
-
return
|
|
10411
|
+
const body = concat3(u32le(plain.length), plain, secret);
|
|
10412
|
+
return concat3(body, u32le(body.length), TRAILER_MAGIC);
|
|
9864
10413
|
}
|
|
9865
10414
|
function endsWithMagic(b) {
|
|
9866
10415
|
if (b.length < TRAILER_MAGIC.length)
|
|
@@ -9904,14 +10453,14 @@ async function openFrameworkAttach(full, keys) {
|
|
|
9904
10453
|
throw new OpaqueDataRejectedError(FIELD);
|
|
9905
10454
|
}
|
|
9906
10455
|
if (secret.length) {
|
|
9907
|
-
if (secret.length < 1 +
|
|
10456
|
+
if (secret.length < 1 + NONCE_LEN3 + TAG_LEN3 || secret[0] !== ATTACH_SECRET_OPTIONS_VERSION) {
|
|
9908
10457
|
throw new OpaqueDataRejectedError(FIELD);
|
|
9909
10458
|
}
|
|
9910
10459
|
let opened;
|
|
9911
10460
|
try {
|
|
9912
10461
|
const key = await deriveAttachSecretKey(await rootKey(keys));
|
|
9913
|
-
const nonce = secret.subarray(1, 1 +
|
|
9914
|
-
opened = xchacha20poly1305(key, nonce, aadFor(copy.subarray(0, UUID_LEN))).decrypt(secret.subarray(1 +
|
|
10462
|
+
const nonce = secret.subarray(1, 1 + NONCE_LEN3);
|
|
10463
|
+
opened = xchacha20poly1305(key, nonce, aadFor(copy.subarray(0, UUID_LEN))).decrypt(secret.subarray(1 + NONCE_LEN3));
|
|
9915
10464
|
} catch {
|
|
9916
10465
|
throw new OpaqueDataRejectedError(FIELD);
|
|
9917
10466
|
}
|
|
@@ -9981,6 +10530,36 @@ async function openAttach(envelope, auth, signingKey, attachSecretKey) {
|
|
|
9981
10530
|
const full = await openAttachFull(envelope, auth, signingKey);
|
|
9982
10531
|
return openFrameworkAttach(full, { explicit: attachSecretKey, signingKey });
|
|
9983
10532
|
}
|
|
10533
|
+
async function openAttachWithShard(envelope, auth, signingKey, attachSecretKey) {
|
|
10534
|
+
if (envelope == null)
|
|
10535
|
+
return { attach: null, shardKey: "" };
|
|
10536
|
+
if (envelope.length === 0)
|
|
10537
|
+
return { attach: envelope, shardKey: "" };
|
|
10538
|
+
const full = await openAttachFull(envelope, auth, signingKey);
|
|
10539
|
+
const shardKey = full.length >= ATTACH_UUID_LEN ? deriveShardKey(full.subarray(0, ATTACH_UUID_LEN)) : "";
|
|
10540
|
+
const attach = await openFrameworkAttach(full, { explicit: attachSecretKey, signingKey });
|
|
10541
|
+
return { attach, shardKey };
|
|
10542
|
+
}
|
|
10543
|
+
function toHex(b) {
|
|
10544
|
+
let s = "";
|
|
10545
|
+
for (let i = 0;i < b.length; i++)
|
|
10546
|
+
s += b[i].toString(16).padStart(2, "0");
|
|
10547
|
+
return s;
|
|
10548
|
+
}
|
|
10549
|
+
function deriveShardKey(attachUuid) {
|
|
10550
|
+
if (attachUuid.length !== ATTACH_UUID_LEN) {
|
|
10551
|
+
throw new Error(`shard_key requires a ${ATTACH_UUID_LEN}-byte attach uuid, got ${attachUuid.length}`);
|
|
10552
|
+
}
|
|
10553
|
+
return "att-" + toHex(attachUuid);
|
|
10554
|
+
}
|
|
10555
|
+
async function shardKeyForAttach(sealed, auth, signingKey) {
|
|
10556
|
+
if (!sealed || sealed.length === 0)
|
|
10557
|
+
return "";
|
|
10558
|
+
const full = await openAttachFull(sealed, auth, signingKey);
|
|
10559
|
+
if (full.length < ATTACH_UUID_LEN)
|
|
10560
|
+
return "";
|
|
10561
|
+
return deriveShardKey(full.subarray(0, ATTACH_UUID_LEN));
|
|
10562
|
+
}
|
|
9984
10563
|
async function sealTransaction(plaintext, attachEnvelope, auth, signingKey) {
|
|
9985
10564
|
if (!signingKey)
|
|
9986
10565
|
return plaintext;
|
|
@@ -10171,7 +10750,7 @@ class SplitTokenError extends Error {
|
|
|
10171
10750
|
this.kind = kind;
|
|
10172
10751
|
}
|
|
10173
10752
|
}
|
|
10174
|
-
function
|
|
10753
|
+
function concat4(...parts) {
|
|
10175
10754
|
const total = parts.reduce((n, p) => n + p.length, 0);
|
|
10176
10755
|
const out = new Uint8Array(total);
|
|
10177
10756
|
let at = 0;
|
|
@@ -10192,13 +10771,13 @@ function equalBytes2(a, b) {
|
|
|
10192
10771
|
async function bindFingerprint(schemaPath, functionName, args, settings, projection) {
|
|
10193
10772
|
const enc = new TextEncoder;
|
|
10194
10773
|
const zero = Uint8Array.of(0);
|
|
10195
|
-
const field = (label, value) =>
|
|
10196
|
-
const message =
|
|
10774
|
+
const field = (label, value) => concat4(enc.encode(label), zero, value, zero);
|
|
10775
|
+
const message = concat4(AAD_PREFIX2, field("schema_path", enc.encode(JSON.stringify(schemaPath))), field("function_name", enc.encode(functionName)), field("arguments", args), field("settings", settings), field("projection_ids", projection));
|
|
10197
10776
|
const digest = await crypto.subtle.digest("SHA-256", message);
|
|
10198
10777
|
return new Uint8Array(digest).slice(0, FINGERPRINT_LEN);
|
|
10199
10778
|
}
|
|
10200
10779
|
function splitTokenAad(header, auth) {
|
|
10201
|
-
return
|
|
10780
|
+
return concat4(header, identityTail(auth));
|
|
10202
10781
|
}
|
|
10203
10782
|
function splitAnchor(catalogVersion) {
|
|
10204
10783
|
const out = new Uint8Array(8);
|
|
@@ -10217,11 +10796,11 @@ async function buildSplitToken(opts) {
|
|
|
10217
10796
|
head[0] = SPLIT_TOKEN_FORMAT_VERSION;
|
|
10218
10797
|
head[1] = signingKey ? FLAG_PAYLOAD_SEALED : 0;
|
|
10219
10798
|
new DataView(head.buffer).setUint16(2, anchor.length, true);
|
|
10220
|
-
const body =
|
|
10799
|
+
const body = concat4(head, fingerprint, anchor);
|
|
10221
10800
|
if (!signingKey)
|
|
10222
|
-
return
|
|
10801
|
+
return concat4(body, payload);
|
|
10223
10802
|
const sealed = await sealBytes(payload, signingKey, splitTokenAad(body, auth), SEAL_VERSION);
|
|
10224
|
-
return
|
|
10803
|
+
return concat4(body, sealed);
|
|
10225
10804
|
}
|
|
10226
10805
|
async function openSplitToken(token, opts = {}) {
|
|
10227
10806
|
const { signingKey, auth, expectedFingerprint, currentAnchor } = opts;
|
|
@@ -10308,20 +10887,15 @@ async function resolveSplitPayloads(request, innerParams, opts) {
|
|
|
10308
10887
|
}
|
|
10309
10888
|
function functionHandlers(config) {
|
|
10310
10889
|
const { registry, signingKey, catalogInterface, attachSecretKey } = config;
|
|
10311
|
-
|
|
10312
|
-
if (attach == null)
|
|
10313
|
-
return null;
|
|
10314
|
-
const env = toUint8Array(attach);
|
|
10315
|
-
if (env.length === 0)
|
|
10316
|
-
return env;
|
|
10317
|
-
return openAttach(env, ctx?.auth ?? currentRequestAuth(), signingKey, attachSecretKey);
|
|
10318
|
-
}
|
|
10890
|
+
const storageSealKey = config.storageSealKey ?? signingKey;
|
|
10319
10891
|
async function openOpaque(bindCall, ctx) {
|
|
10320
10892
|
const sealedAttach = bindCall.attach_opaque_data != null ? toUint8Array(bindCall.attach_opaque_data) : new Uint8Array(0);
|
|
10321
10893
|
if (bindCall.transaction_opaque_data != null) {
|
|
10322
10894
|
bindCall.transaction_opaque_data = await openTransaction(toUint8Array(bindCall.transaction_opaque_data), sealedAttach, ctx?.auth ?? currentRequestAuth(), signingKey);
|
|
10323
10895
|
}
|
|
10324
|
-
bindCall.attach_opaque_data
|
|
10896
|
+
const opened = await openAttachWithShard(bindCall.attach_opaque_data != null ? toUint8Array(bindCall.attach_opaque_data) : null, ctx?.auth ?? currentRequestAuth(), signingKey, attachSecretKey);
|
|
10897
|
+
bindCall.attach_opaque_data = opened.attach;
|
|
10898
|
+
bindCall.storage_shard_key = opened.shardKey;
|
|
10325
10899
|
}
|
|
10326
10900
|
async function strippedContext(bindCall, ctx) {
|
|
10327
10901
|
const copy = { ...bindCall };
|
|
@@ -10365,6 +10939,9 @@ function functionHandlers(config) {
|
|
|
10365
10939
|
});
|
|
10366
10940
|
const func = registry.get(request.bind_call.function_name, overloadContext(request.bind_call, catalogInterface));
|
|
10367
10941
|
const initResponse = await func.globalInit(request);
|
|
10942
|
+
if (func.kind === "table_buffering" && request.phase === "TABLE_BUFFERING" /* TABLE_BUFFERING */) {
|
|
10943
|
+
await persistBufferingInit(request, initResponse, storageSealKey);
|
|
10944
|
+
}
|
|
10368
10945
|
const handlers = func.createStreamHandlers(request, initResponse);
|
|
10369
10946
|
let handlerState;
|
|
10370
10947
|
if (handlers.producerInit) {
|
|
@@ -10514,6 +11091,11 @@ function functionHandlers(config) {
|
|
|
10514
11091
|
const globalExecutionId = toUint8Array(innerParams.global_execution_id);
|
|
10515
11092
|
const bindOpaqueData = innerParams.bind_opaque_data ? toUint8Array(innerParams.bind_opaque_data) : null;
|
|
10516
11093
|
const func = registry.get(bindCall.function_name, await strippedContext(bindCall));
|
|
11094
|
+
try {
|
|
11095
|
+
bindCall.storage_shard_key = await shardKeyForAttach(bindCall.attach_opaque_data ?? undefined, currentRequestAuth(), signingKey);
|
|
11096
|
+
} catch {
|
|
11097
|
+
bindCall.storage_shard_key = "";
|
|
11098
|
+
}
|
|
10517
11099
|
const map = func.dynamicToString ? await func.dynamicToString({ bindCall, bindOpaqueData, globalExecutionId }) : {};
|
|
10518
11100
|
const keys = Object.keys(map);
|
|
10519
11101
|
const values = keys.map((k) => map[k] ?? "");
|
|
@@ -10557,79 +11139,12 @@ function functionHandlers(config) {
|
|
|
10557
11139
|
};
|
|
10558
11140
|
}
|
|
10559
11141
|
|
|
10560
|
-
// src/arguments/argument-spec.ts
|
|
10561
|
-
function toNumber(value) {
|
|
10562
|
-
if (typeof value === "number")
|
|
10563
|
-
return value;
|
|
10564
|
-
if (typeof value === "bigint")
|
|
10565
|
-
return Number(value);
|
|
10566
|
-
return;
|
|
10567
|
-
}
|
|
10568
|
-
function choiceEquals(choice, value) {
|
|
10569
|
-
const cn = toNumber(choice);
|
|
10570
|
-
const vn = toNumber(value);
|
|
10571
|
-
if (cn !== undefined && vn !== undefined)
|
|
10572
|
-
return cn === vn;
|
|
10573
|
-
return choice === value;
|
|
10574
|
-
}
|
|
10575
|
-
function validateConstConstraints(name, constraints, value) {
|
|
10576
|
-
if (value === null || value === undefined)
|
|
10577
|
-
return;
|
|
10578
|
-
const num = toNumber(value);
|
|
10579
|
-
if (num !== undefined) {
|
|
10580
|
-
if (constraints.ge !== undefined && num < constraints.ge) {
|
|
10581
|
-
throw new ArgumentValidationError(`argument '${name}' must be >= ${constraints.ge}`);
|
|
10582
|
-
}
|
|
10583
|
-
if (constraints.le !== undefined && num > constraints.le) {
|
|
10584
|
-
throw new ArgumentValidationError(`argument '${name}' must be <= ${constraints.le}`);
|
|
10585
|
-
}
|
|
10586
|
-
if (constraints.gt !== undefined && num <= constraints.gt) {
|
|
10587
|
-
throw new ArgumentValidationError(`argument '${name}' must be > ${constraints.gt}`);
|
|
10588
|
-
}
|
|
10589
|
-
if (constraints.lt !== undefined && num >= constraints.lt) {
|
|
10590
|
-
throw new ArgumentValidationError(`argument '${name}' must be < ${constraints.lt}`);
|
|
10591
|
-
}
|
|
10592
|
-
}
|
|
10593
|
-
if (constraints.choices !== undefined && constraints.choices.length > 0) {
|
|
10594
|
-
if (!constraints.choices.some((c) => choiceEquals(c, value))) {
|
|
10595
|
-
throw new ArgumentValidationError(`argument '${name}' must be one of ${JSON.stringify([...constraints.choices])}`);
|
|
10596
|
-
}
|
|
10597
|
-
}
|
|
10598
|
-
if (constraints.pattern !== undefined && typeof value === "string") {
|
|
10599
|
-
let re;
|
|
10600
|
-
try {
|
|
10601
|
-
re = new RegExp(constraints.pattern);
|
|
10602
|
-
} catch {
|
|
10603
|
-
re = undefined;
|
|
10604
|
-
}
|
|
10605
|
-
if (re !== undefined && !re.test(value)) {
|
|
10606
|
-
throw new ArgumentValidationError(`argument '${name}' must match pattern ${JSON.stringify(constraints.pattern)}`);
|
|
10607
|
-
}
|
|
10608
|
-
}
|
|
10609
|
-
}
|
|
10610
|
-
|
|
10611
11142
|
// src/functions/aggregate.ts
|
|
10612
|
-
|
|
10613
|
-
|
|
10614
|
-
var _NODE_OS_MOD = "node:os";
|
|
10615
|
-
function _aggReq() {
|
|
10616
|
-
const req = import.meta.require ?? globalThis.require ?? null;
|
|
10617
|
-
if (!req) {
|
|
10618
|
-
throw new Error("Aggregate state persistence requires Node.js or Bun (node:fs/path/os).");
|
|
10619
|
-
}
|
|
10620
|
-
return req;
|
|
10621
|
-
}
|
|
10622
|
-
var fs = new Proxy({}, {
|
|
10623
|
-
get: (_t, prop) => _aggReq()(_NODE_FS_MOD)[prop]
|
|
10624
|
-
});
|
|
10625
|
-
var path = new Proxy({}, {
|
|
10626
|
-
get: (_t, prop) => _aggReq()(_NODE_PATH_MOD)[prop]
|
|
10627
|
-
});
|
|
10628
|
-
var os = new Proxy({}, {
|
|
10629
|
-
get: (_t, prop) => _aggReq()(_NODE_OS_MOD)[prop]
|
|
10630
|
-
});
|
|
11143
|
+
init_storage();
|
|
11144
|
+
init_storage_seal();
|
|
10631
11145
|
var GROUP_COLUMN_NAME = "__vgi_group_id";
|
|
10632
|
-
var
|
|
11146
|
+
var AGGREGATE_CONTEXT_KEY = packIntKey(-2);
|
|
11147
|
+
var aggregateContextCache = new ExecutionCache(64);
|
|
10633
11148
|
function jsonReplacer(_, v) {
|
|
10634
11149
|
if (typeof v === "bigint")
|
|
10635
11150
|
return { __bigint__: v.toString() };
|
|
@@ -10641,91 +11156,76 @@ function jsonReviver(_, v) {
|
|
|
10641
11156
|
}
|
|
10642
11157
|
return v;
|
|
10643
11158
|
}
|
|
10644
|
-
|
|
10645
|
-
|
|
11159
|
+
var UTF8_ENC = new TextEncoder;
|
|
11160
|
+
var UTF8_DEC = new TextDecoder;
|
|
11161
|
+
function encodeGroupState(state) {
|
|
11162
|
+
return UTF8_ENC.encode(JSON.stringify(state, jsonReplacer));
|
|
10646
11163
|
}
|
|
10647
|
-
function
|
|
10648
|
-
return
|
|
11164
|
+
function decodeGroupState(bytes) {
|
|
11165
|
+
return JSON.parse(UTF8_DEC.decode(bytes), jsonReviver);
|
|
10649
11166
|
}
|
|
10650
|
-
function
|
|
10651
|
-
let
|
|
10652
|
-
for (
|
|
10653
|
-
|
|
10654
|
-
return
|
|
11167
|
+
function b64(buf) {
|
|
11168
|
+
let binary = "";
|
|
11169
|
+
for (let i = 0;i < buf.length; i++)
|
|
11170
|
+
binary += String.fromCharCode(buf[i]);
|
|
11171
|
+
return btoa(binary);
|
|
11172
|
+
}
|
|
11173
|
+
function unb64(s) {
|
|
11174
|
+
const binary = atob(s);
|
|
11175
|
+
const out = new Uint8Array(binary.length);
|
|
11176
|
+
for (let i = 0;i < binary.length; i++)
|
|
11177
|
+
out[i] = binary.charCodeAt(i);
|
|
11178
|
+
return out;
|
|
10655
11179
|
}
|
|
10656
|
-
function
|
|
10657
|
-
|
|
10658
|
-
|
|
10659
|
-
|
|
10660
|
-
|
|
10661
|
-
|
|
11180
|
+
function encodeAggregateContext(ctx) {
|
|
11181
|
+
return UTF8_ENC.encode(JSON.stringify({
|
|
11182
|
+
v: 1,
|
|
11183
|
+
arguments: b64(ctx.argumentsIpc),
|
|
11184
|
+
input_schema: ctx.inputSchemaIpc ? b64(ctx.inputSchemaIpc) : null,
|
|
11185
|
+
argument_names: ctx.argumentNames
|
|
11186
|
+
}));
|
|
10662
11187
|
}
|
|
10663
|
-
function
|
|
11188
|
+
function decodeAggregateContext(bytes) {
|
|
11189
|
+
let d;
|
|
10664
11190
|
try {
|
|
10665
|
-
|
|
10666
|
-
|
|
10667
|
-
|
|
10668
|
-
if (e?.code === "ENOENT")
|
|
10669
|
-
return;
|
|
10670
|
-
throw e;
|
|
11191
|
+
d = JSON.parse(UTF8_DEC.decode(bytes));
|
|
11192
|
+
} catch {
|
|
11193
|
+
throw new StoragePayloadError("aggregate: unrecognized bind context payload");
|
|
10671
11194
|
}
|
|
10672
|
-
|
|
10673
|
-
|
|
10674
|
-
const key = execKey(executionId);
|
|
10675
|
-
let entry = stateStore.get(key);
|
|
10676
|
-
if (!entry) {
|
|
10677
|
-
const ctx = tryReadJson(path.join(execDir(key), "context.json"));
|
|
10678
|
-
if (!ctx)
|
|
10679
|
-
return;
|
|
10680
|
-
entry = {
|
|
10681
|
-
states: new Map,
|
|
10682
|
-
bindArgs: ctx.bindArgs,
|
|
10683
|
-
bindParams: ctx.bindParams,
|
|
10684
|
-
loaded: new Set
|
|
10685
|
-
};
|
|
10686
|
-
stateStore.set(key, entry);
|
|
10687
|
-
}
|
|
10688
|
-
if (requestedGids) {
|
|
10689
|
-
for (const gid of requestedGids) {
|
|
10690
|
-
const stateFile = path.join(execDir(key), gid.toString() + ".json");
|
|
10691
|
-
const s = tryReadJson(stateFile);
|
|
10692
|
-
if (s !== undefined) {
|
|
10693
|
-
entry.states.set(gid, s);
|
|
10694
|
-
} else {
|
|
10695
|
-
entry.states.delete(gid);
|
|
10696
|
-
}
|
|
10697
|
-
entry.loaded.add(gid);
|
|
10698
|
-
}
|
|
11195
|
+
if (!d || d.v !== 1 || typeof d.arguments !== "string") {
|
|
11196
|
+
throw new StoragePayloadError("aggregate: unrecognized bind context payload format");
|
|
10699
11197
|
}
|
|
10700
|
-
return
|
|
11198
|
+
return {
|
|
11199
|
+
argumentsIpc: unb64(d.arguments),
|
|
11200
|
+
inputSchemaIpc: typeof d.input_schema === "string" ? unb64(d.input_schema) : null,
|
|
11201
|
+
argumentNames: Array.isArray(d.argument_names) ? d.argument_names : null
|
|
11202
|
+
};
|
|
10701
11203
|
}
|
|
10702
|
-
function
|
|
10703
|
-
const
|
|
10704
|
-
|
|
10705
|
-
|
|
10706
|
-
|
|
10707
|
-
|
|
11204
|
+
async function loadGroupStates(storage, gids) {
|
|
11205
|
+
const states = new Map;
|
|
11206
|
+
if (gids.length === 0)
|
|
11207
|
+
return states;
|
|
11208
|
+
const values = await storage.stateGetMany(FrameworkNS.AGGREGATE_STATE, gids.map((g) => packIntKey(g)));
|
|
11209
|
+
for (let i = 0;i < gids.length; i++) {
|
|
11210
|
+
const v = values[i];
|
|
11211
|
+
if (v != null)
|
|
11212
|
+
states.set(gids[i], decodeGroupState(v));
|
|
11213
|
+
}
|
|
11214
|
+
return states;
|
|
10708
11215
|
}
|
|
10709
|
-
function
|
|
10710
|
-
const
|
|
10711
|
-
const entry = stateStore.get(key);
|
|
10712
|
-
if (!entry)
|
|
10713
|
-
return;
|
|
11216
|
+
async function storeGroupStates(storage, states, gids) {
|
|
11217
|
+
const items = [];
|
|
10714
11218
|
for (const gid of gids) {
|
|
10715
|
-
|
|
10716
|
-
|
|
10717
|
-
atomicWriteJson(stateFile, entry.states.get(gid));
|
|
10718
|
-
} else {
|
|
10719
|
-
try {
|
|
10720
|
-
fs.unlinkSync(stateFile);
|
|
10721
|
-
} catch {}
|
|
10722
|
-
}
|
|
10723
|
-
entry.loaded.add(gid);
|
|
11219
|
+
if (states.has(gid))
|
|
11220
|
+
items.push([packIntKey(gid), encodeGroupState(states.get(gid))]);
|
|
10724
11221
|
}
|
|
11222
|
+
if (items.length > 0)
|
|
11223
|
+
await storage.statePutMany(FrameworkNS.AGGREGATE_STATE, items);
|
|
10725
11224
|
}
|
|
10726
11225
|
|
|
10727
11226
|
// src/protocol/handlers/aggregate.ts
|
|
10728
|
-
|
|
11227
|
+
init_storage();
|
|
11228
|
+
function aggregateHandlers(registry, signingKey, attachSecretKey, storageSealKey = signingKey) {
|
|
10729
11229
|
function resolveAggregate(name, schemaPath) {
|
|
10730
11230
|
const func = registry.get(name, {
|
|
10731
11231
|
arguments: new Arguments,
|
|
@@ -10738,36 +11238,62 @@ function aggregateHandlers(registry) {
|
|
|
10738
11238
|
}
|
|
10739
11239
|
return func.aggregateConfig;
|
|
10740
11240
|
}
|
|
10741
|
-
|
|
11241
|
+
async function boundFor(innerParams, ctx, executionId) {
|
|
11242
|
+
const raw = innerParams.attach_opaque_data ? toUint8Array(innerParams.attach_opaque_data) : null;
|
|
11243
|
+
const { shardKey } = await openAttachWithShard(raw, ctx?.auth ?? currentRequestAuth(), signingKey, attachSecretKey);
|
|
11244
|
+
return new BoundStorage(storage, executionId, null, shardKey);
|
|
11245
|
+
}
|
|
11246
|
+
async function loadContext(cfg, storage, rpc) {
|
|
11247
|
+
const cached = aggregateContextCache.get(storage.shardKey, storage.executionId);
|
|
11248
|
+
if (cached)
|
|
11249
|
+
return cached;
|
|
11250
|
+
const payload = await storage.sealedGet(FrameworkNS.AGGREGATE_STATE, AGGREGATE_CONTEXT_KEY, storageSealKey);
|
|
11251
|
+
if (payload == null) {
|
|
11252
|
+
throw new Error(`${rpc}: unknown execution_id for '${cfg.name}' (bind missing or state dropped)`);
|
|
11253
|
+
}
|
|
11254
|
+
const stored = decodeAggregateContext(payload);
|
|
11255
|
+
const args = deserializeArguments(stored.argumentsIpc);
|
|
11256
|
+
const params = {
|
|
11257
|
+
args: extractArgMap(cfg, args),
|
|
11258
|
+
arguments: args,
|
|
11259
|
+
inputSchema: stored.inputSchemaIpc ? deserializeSchema(stored.inputSchemaIpc) : null,
|
|
11260
|
+
settings: {},
|
|
11261
|
+
secrets: {},
|
|
11262
|
+
argumentNames: stored.argumentNames
|
|
11263
|
+
};
|
|
11264
|
+
aggregateContextCache.set(storage.shardKey, storage.executionId, params);
|
|
11265
|
+
return params;
|
|
11266
|
+
}
|
|
11267
|
+
const aggregateBind = async (params, ctx) => {
|
|
10742
11268
|
const innerParams = unwrapRequest(params.request);
|
|
10743
11269
|
const functionName = innerParams.function_name;
|
|
10744
11270
|
const cfg = resolveAggregate(functionName, innerParams.schema_path ?? null);
|
|
10745
11271
|
const argBytes = toUint8Array(innerParams.arguments);
|
|
10746
11272
|
const args = deserializeArguments(argBytes);
|
|
10747
|
-
const
|
|
11273
|
+
const inputSchemaIpc = innerParams.input_schema ? toUint8Array(innerParams.input_schema) : null;
|
|
11274
|
+
const inputSchema = inputSchemaIpc && inputSchemaIpc.length > 0 ? deserializeSchema(inputSchemaIpc) : null;
|
|
10748
11275
|
const secretsBytes = innerParams.secrets ? toUint8Array(innerParams.secrets) : null;
|
|
10749
11276
|
const secretsBatch = secretsBytes && secretsBytes.length > 0 ? deserializeBatch(secretsBytes) : null;
|
|
10750
11277
|
const secrets = secretsBatch ? batchToSecretDict(secretsBatch) : {};
|
|
11278
|
+
const argumentNames = innerParams.argument_names ? (Array.isArray(innerParams.argument_names) ? innerParams.argument_names : [...innerParams.argument_names]).map((value) => value == null ? null : String(value)) : null;
|
|
10751
11279
|
const bindParams = {
|
|
10752
11280
|
args: extractArgMap(cfg, args),
|
|
10753
11281
|
arguments: args,
|
|
10754
11282
|
inputSchema,
|
|
10755
11283
|
settings: {},
|
|
10756
11284
|
secrets,
|
|
10757
|
-
argumentNames
|
|
11285
|
+
argumentNames
|
|
10758
11286
|
};
|
|
10759
|
-
const executionId = new Uint8Array(16);
|
|
10760
|
-
crypto.getRandomValues(executionId);
|
|
10761
|
-
setExecutionState(executionId, {
|
|
10762
|
-
states: new Map,
|
|
10763
|
-
bindArgs: args,
|
|
10764
|
-
bindParams
|
|
10765
|
-
});
|
|
10766
11287
|
const outType = cfg.onBind ? await cfg.onBind(bindParams) : cfg.outputType;
|
|
10767
11288
|
const outSchema = schema2([field2("result", outType, true)]);
|
|
11289
|
+
const executionId = new Uint8Array(16);
|
|
11290
|
+
crypto.getRandomValues(executionId);
|
|
11291
|
+
const storage = await boundFor(innerParams, ctx, executionId);
|
|
11292
|
+
await storage.sealedPut(FrameworkNS.AGGREGATE_STATE, AGGREGATE_CONTEXT_KEY, encodeAggregateContext({ argumentsIpc: argBytes, inputSchemaIpc, argumentNames }), storageSealKey);
|
|
11293
|
+
aggregateContextCache.set(storage.shardKey, executionId, { ...bindParams, secrets: {} });
|
|
10768
11294
|
return wrapResult({ output_schema: serializeSchema(outSchema), execution_id: executionId }, AggregateBindResultSchema);
|
|
10769
11295
|
};
|
|
10770
|
-
const aggregateUpdate = (params) => {
|
|
11296
|
+
const aggregateUpdate = async (params, ctx) => {
|
|
10771
11297
|
const innerParams = unwrapRequest(params.request);
|
|
10772
11298
|
const functionName = innerParams.function_name;
|
|
10773
11299
|
const executionId = toUint8Array(innerParams.execution_id);
|
|
@@ -10788,10 +11314,10 @@ function aggregateHandlers(registry) {
|
|
|
10788
11314
|
groupIds.push(g);
|
|
10789
11315
|
uniqueGids.add(g);
|
|
10790
11316
|
}
|
|
10791
|
-
const
|
|
10792
|
-
|
|
10793
|
-
|
|
10794
|
-
|
|
11317
|
+
const storage = await boundFor(innerParams, ctx, executionId);
|
|
11318
|
+
const bindParams = await loadContext(cfg, storage, "aggregate_update");
|
|
11319
|
+
const gids = [...uniqueGids];
|
|
11320
|
+
const states = await loadGroupStates(storage, gids);
|
|
10795
11321
|
const columns = [];
|
|
10796
11322
|
for (let i = 0;i < batch.schema.fields.length; i++) {
|
|
10797
11323
|
if (i === gidIdx)
|
|
@@ -10799,24 +11325,24 @@ function aggregateHandlers(registry) {
|
|
|
10799
11325
|
columns.push(batch.getChildAt(i));
|
|
10800
11326
|
}
|
|
10801
11327
|
const ensureState = (gid) => {
|
|
10802
|
-
let s =
|
|
11328
|
+
let s = states.get(gid);
|
|
10803
11329
|
if (s === undefined) {
|
|
10804
|
-
s = cfg.initialState(
|
|
10805
|
-
|
|
11330
|
+
s = cfg.initialState(bindParams);
|
|
11331
|
+
states.set(gid, s);
|
|
10806
11332
|
}
|
|
10807
11333
|
return s;
|
|
10808
11334
|
};
|
|
10809
11335
|
cfg.update({
|
|
10810
|
-
states
|
|
11336
|
+
states,
|
|
10811
11337
|
groupIds,
|
|
10812
11338
|
columns,
|
|
10813
|
-
args:
|
|
11339
|
+
args: bindParams.args,
|
|
10814
11340
|
ensureState
|
|
10815
11341
|
});
|
|
10816
|
-
|
|
11342
|
+
await storeGroupStates(storage, states, gids);
|
|
10817
11343
|
return wrapResult({}, schema2([]));
|
|
10818
11344
|
};
|
|
10819
|
-
const aggregateCombine = (params) => {
|
|
11345
|
+
const aggregateCombine = async (params, ctx) => {
|
|
10820
11346
|
const innerParams = unwrapRequest(params.request);
|
|
10821
11347
|
const functionName = innerParams.function_name;
|
|
10822
11348
|
const executionId = toUint8Array(innerParams.execution_id);
|
|
@@ -10837,27 +11363,26 @@ function aggregateHandlers(registry) {
|
|
|
10837
11363
|
referencedGids.add(src);
|
|
10838
11364
|
referencedGids.add(tgt);
|
|
10839
11365
|
}
|
|
10840
|
-
const
|
|
10841
|
-
|
|
10842
|
-
|
|
10843
|
-
}
|
|
11366
|
+
const storage = await boundFor(innerParams, ctx, executionId);
|
|
11367
|
+
const bindParams = await loadContext(cfg, storage, "aggregate_combine");
|
|
11368
|
+
const states = await loadGroupStates(storage, [...referencedGids]);
|
|
10844
11369
|
const touchedTargets = new Set;
|
|
10845
11370
|
for (let i = 0;i < batch.numRows; i++) {
|
|
10846
11371
|
const src = srcIds[i];
|
|
10847
11372
|
const tgt = tgtIds[i];
|
|
10848
|
-
const srcHas =
|
|
10849
|
-
const tgtHas =
|
|
11373
|
+
const srcHas = states.has(src);
|
|
11374
|
+
const tgtHas = states.has(tgt);
|
|
10850
11375
|
if (!srcHas && !tgtHas)
|
|
10851
11376
|
continue;
|
|
10852
|
-
const srcState = srcHas ?
|
|
10853
|
-
const tgtState = tgtHas ?
|
|
10854
|
-
|
|
11377
|
+
const srcState = srcHas ? states.get(src) : cfg.initialState(bindParams);
|
|
11378
|
+
const tgtState = tgtHas ? states.get(tgt) : cfg.initialState(bindParams);
|
|
11379
|
+
states.set(tgt, cfg.combine(srcState, tgtState, bindParams));
|
|
10855
11380
|
touchedTargets.add(tgt);
|
|
10856
11381
|
}
|
|
10857
|
-
|
|
11382
|
+
await storeGroupStates(storage, states, touchedTargets);
|
|
10858
11383
|
return wrapResult({}, schema2([]));
|
|
10859
11384
|
};
|
|
10860
|
-
const aggregateFinalize = (params) => {
|
|
11385
|
+
const aggregateFinalize = async (params, ctx) => {
|
|
10861
11386
|
const innerParams = unwrapRequest(params.request);
|
|
10862
11387
|
const functionName = innerParams.function_name;
|
|
10863
11388
|
const executionId = toUint8Array(innerParams.execution_id);
|
|
@@ -10875,40 +11400,29 @@ function aggregateHandlers(registry) {
|
|
|
10875
11400
|
uniqueGids.add(g);
|
|
10876
11401
|
}
|
|
10877
11402
|
}
|
|
10878
|
-
const
|
|
10879
|
-
|
|
10880
|
-
|
|
10881
|
-
}
|
|
11403
|
+
const storage = await boundFor(innerParams, ctx, executionId);
|
|
11404
|
+
const bindParams = await loadContext(cfg, storage, "aggregate_finalize");
|
|
11405
|
+
const stored = await loadGroupStates(storage, [...uniqueGids]);
|
|
10882
11406
|
const states = new Map;
|
|
10883
11407
|
for (const gid of groupIds) {
|
|
10884
|
-
states.set(gid,
|
|
11408
|
+
states.set(gid, stored.has(gid) ? stored.get(gid) : null);
|
|
10885
11409
|
}
|
|
10886
11410
|
const resultBatch = cfg.finalize({
|
|
10887
11411
|
groupIds,
|
|
10888
11412
|
states,
|
|
10889
11413
|
outputSchema,
|
|
10890
|
-
args:
|
|
11414
|
+
args: bindParams.args
|
|
10891
11415
|
});
|
|
10892
11416
|
return wrapResult({ result_batch: serializeBatchWithSchema(resultBatch) }, AggregateFinalizeResultSchema);
|
|
10893
11417
|
};
|
|
10894
|
-
const aggregateDestructor = (params) => {
|
|
10895
|
-
|
|
10896
|
-
|
|
10897
|
-
|
|
10898
|
-
|
|
10899
|
-
|
|
10900
|
-
|
|
10901
|
-
|
|
10902
|
-
return wrapResult({}, schema2([]));
|
|
10903
|
-
const col = gidBatch.getChild("group_id");
|
|
10904
|
-
const toDrop = new Set;
|
|
10905
|
-
for (let i = 0;i < gidBatch.numRows; i++) {
|
|
10906
|
-
const v = col.get(i);
|
|
10907
|
-
const g = typeof v === "bigint" ? v : BigInt(v);
|
|
10908
|
-
exec.states.delete(g);
|
|
10909
|
-
toDrop.add(g);
|
|
10910
|
-
}
|
|
10911
|
-
persistGroupStates(executionId, toDrop);
|
|
11418
|
+
const aggregateDestructor = async (params, ctx) => {
|
|
11419
|
+
try {
|
|
11420
|
+
const innerParams = unwrapRequest(params.request);
|
|
11421
|
+
const executionId = toUint8Array(innerParams.execution_id);
|
|
11422
|
+
const storage = await boundFor(innerParams, ctx, executionId);
|
|
11423
|
+
aggregateContextCache.delete(storage.shardKey, executionId);
|
|
11424
|
+
await storage.executionClear();
|
|
11425
|
+
} catch {}
|
|
10912
11426
|
return wrapResult({}, schema2([]));
|
|
10913
11427
|
};
|
|
10914
11428
|
return { aggregateBind, aggregateUpdate, aggregateCombine, aggregateFinalize, aggregateDestructor };
|
|
@@ -10970,40 +11484,7 @@ function serializeBatchWithSchema(batch) {
|
|
|
10970
11484
|
|
|
10971
11485
|
// src/protocol/handlers/table-buffering.ts
|
|
10972
11486
|
init_storage();
|
|
10973
|
-
|
|
10974
|
-
// src/functions/table-buffering.ts
|
|
10975
|
-
function decodeBufferingInit(payload) {
|
|
10976
|
-
const [initBytes, respBytes] = splitLenPrefixed(payload, 2);
|
|
10977
|
-
const initBatch = deserializeBatch(initBytes);
|
|
10978
|
-
const initDict = batchToScalarDict(initBatch);
|
|
10979
|
-
const request = deserializeInitRequest(initDict);
|
|
10980
|
-
const response = decodeGlobalInitResponse(respBytes);
|
|
10981
|
-
return { request, response };
|
|
10982
|
-
}
|
|
10983
|
-
function decodeGlobalInitResponse(bytes) {
|
|
10984
|
-
const [eid, opaque, mwBuf] = splitLenPrefixed(bytes, 3);
|
|
10985
|
-
const maxWorkers = Number(new DataView(mwBuf.buffer, mwBuf.byteOffset, 8).getBigInt64(0, true));
|
|
10986
|
-
return {
|
|
10987
|
-
execution_id: eid,
|
|
10988
|
-
opaque_data: opaque.length > 0 ? opaque : null,
|
|
10989
|
-
max_workers: maxWorkers
|
|
10990
|
-
};
|
|
10991
|
-
}
|
|
10992
|
-
function splitLenPrefixed(buf, count) {
|
|
10993
|
-
const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
10994
|
-
const parts = [];
|
|
10995
|
-
let off = 0;
|
|
10996
|
-
for (let i = 0;i < count; i++) {
|
|
10997
|
-
const len = dv.getUint32(off, true);
|
|
10998
|
-
off += 4;
|
|
10999
|
-
parts.push(buf.subarray(off, off + len));
|
|
11000
|
-
off += len;
|
|
11001
|
-
}
|
|
11002
|
-
return parts;
|
|
11003
|
-
}
|
|
11004
|
-
|
|
11005
|
-
// src/protocol/handlers/table-buffering.ts
|
|
11006
|
-
function tableBufferingHandlers(registry, signingKey, attachSecretKey) {
|
|
11487
|
+
function tableBufferingHandlers(registry, signingKey, attachSecretKey, storageSealKey = signingKey) {
|
|
11007
11488
|
function resolveBuffering(name, schemaPath) {
|
|
11008
11489
|
const func = registry.get(name, {
|
|
11009
11490
|
arguments: new Arguments,
|
|
@@ -11019,16 +11500,28 @@ function tableBufferingHandlers(registry, signingKey, attachSecretKey) {
|
|
|
11019
11500
|
async function loadParams(inner, clientLog, ctx) {
|
|
11020
11501
|
const functionName = inner.function_name;
|
|
11021
11502
|
const executionId = toUint8Array(inner.execution_id);
|
|
11503
|
+
const auth = ctx?.auth ?? currentRequestAuth();
|
|
11022
11504
|
const rawAttach = inner.attach_opaque_data ? toUint8Array(inner.attach_opaque_data) : null;
|
|
11023
|
-
const attach
|
|
11505
|
+
const { attach, shardKey } = await openAttachWithShard(rawAttach, auth, signingKey, attachSecretKey);
|
|
11024
11506
|
const transactionId = inner.transaction_id ? toUint8Array(inner.transaction_id) : null;
|
|
11025
11507
|
const func = resolveBuffering(functionName, inner.schema_path ?? null);
|
|
11026
|
-
const bound = new BoundStorage(storage, executionId);
|
|
11027
|
-
const
|
|
11028
|
-
|
|
11029
|
-
|
|
11508
|
+
const bound = new BoundStorage(storage, executionId, null, shardKey);
|
|
11509
|
+
const init = await loadBufferingInit(bound, storageSealKey);
|
|
11510
|
+
let txnPlain = transactionId;
|
|
11511
|
+
if (txnPlain && txnPlain.length > 0 && signingKey && rawAttach) {
|
|
11512
|
+
try {
|
|
11513
|
+
txnPlain = await openTransaction(txnPlain, rawAttach, auth, signingKey);
|
|
11514
|
+
} catch {}
|
|
11030
11515
|
}
|
|
11031
|
-
const
|
|
11516
|
+
const request = {
|
|
11517
|
+
...init.request,
|
|
11518
|
+
bind_call: {
|
|
11519
|
+
...init.request.bind_call,
|
|
11520
|
+
attach_opaque_data: attach,
|
|
11521
|
+
transaction_opaque_data: txnPlain,
|
|
11522
|
+
storage_shard_key: shardKey
|
|
11523
|
+
}
|
|
11524
|
+
};
|
|
11032
11525
|
const args = func.bufferingExtractArgs(request.bind_call);
|
|
11033
11526
|
const settings = batchToScalarDict(request.bind_call.settings);
|
|
11034
11527
|
const secrets = batchToSecretDict(request.bind_call.secrets);
|
|
@@ -11076,11 +11569,14 @@ function tableBufferingHandlers(registry, signingKey, attachSecretKey) {
|
|
|
11076
11569
|
});
|
|
11077
11570
|
return wrapResult({ finalize_state_ids: out }, TableBufferingCombineResultSchema);
|
|
11078
11571
|
};
|
|
11079
|
-
const tableBufferingDestructor = async (rpcParams) => {
|
|
11572
|
+
const tableBufferingDestructor = async (rpcParams, ctx) => {
|
|
11080
11573
|
try {
|
|
11081
11574
|
const inner = unwrapRequest(rpcParams.request);
|
|
11082
11575
|
const executionId = toUint8Array(inner.execution_id);
|
|
11083
|
-
const
|
|
11576
|
+
const rawAttach = inner.attach_opaque_data ? toUint8Array(inner.attach_opaque_data) : null;
|
|
11577
|
+
const { shardKey } = await openAttachWithShard(rawAttach, ctx?.auth ?? currentRequestAuth(), signingKey, attachSecretKey);
|
|
11578
|
+
bufferingInitCache.delete(shardKey, executionId);
|
|
11579
|
+
const bound = new BoundStorage(storage, executionId, null, shardKey);
|
|
11084
11580
|
await bound.executionClear();
|
|
11085
11581
|
} catch {}
|
|
11086
11582
|
return wrapResult({}, TableBufferingDestructorResultSchema);
|
|
@@ -11105,9 +11601,6 @@ function decodeBytesList(raw) {
|
|
|
11105
11601
|
}
|
|
11106
11602
|
return out;
|
|
11107
11603
|
}
|
|
11108
|
-
function hex(buf) {
|
|
11109
|
-
return Array.from(buf, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
11110
|
-
}
|
|
11111
11604
|
|
|
11112
11605
|
// src/generated/vgi-client.ts
|
|
11113
11606
|
var encodeCatalogInfo = (v) => encodeASD(CatalogInfoSchema, v);
|
|
@@ -12507,9 +13000,9 @@ var TICKET_ENVELOPE_VERSION = 1;
|
|
|
12507
13000
|
var MAX_OPTIONS_BYTES = 16 * 1024;
|
|
12508
13001
|
var MAX_TICKET_CHARS = 32 * 1024;
|
|
12509
13002
|
var CLOCK_SKEW_SECONDS = 60;
|
|
12510
|
-
var
|
|
13003
|
+
var UTF84 = new TextEncoder;
|
|
12511
13004
|
var STRICT_UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
12512
|
-
var TICKET_AAD_DOMAIN =
|
|
13005
|
+
var TICKET_AAD_DOMAIN = UTF84.encode("vgi.attach_ticket.v1\x00");
|
|
12513
13006
|
var TICKET_ID = /^[0-9a-f]{32}$/;
|
|
12514
13007
|
var B64URL = /^[A-Za-z0-9_-]+$/;
|
|
12515
13008
|
var MAX_TEXT = 65535;
|
|
@@ -12563,14 +13056,14 @@ class SealAttachDeniedError extends Error {
|
|
|
12563
13056
|
}
|
|
12564
13057
|
}
|
|
12565
13058
|
function attachTicketAad(principal) {
|
|
12566
|
-
const p =
|
|
13059
|
+
const p = UTF84.encode(principal);
|
|
12567
13060
|
const out = new Uint8Array(TICKET_AAD_DOMAIN.length + p.length);
|
|
12568
13061
|
out.set(TICKET_AAD_DOMAIN, 0);
|
|
12569
13062
|
out.set(p, TICKET_AAD_DOMAIN.length);
|
|
12570
13063
|
return out;
|
|
12571
13064
|
}
|
|
12572
13065
|
function packText(value, name) {
|
|
12573
|
-
const raw =
|
|
13066
|
+
const raw = UTF84.encode(value);
|
|
12574
13067
|
if (raw.length > MAX_TEXT)
|
|
12575
13068
|
throw new Error(`${name} is longer than 65535 bytes`);
|
|
12576
13069
|
const out = new Uint8Array(2 + raw.length);
|
|
@@ -13419,10 +13912,11 @@ function buildVgiService(config) {
|
|
|
13419
13912
|
registry: config.registry,
|
|
13420
13913
|
signingKey: config.signingKey,
|
|
13421
13914
|
attachSecretKey: config.attachSecretKey,
|
|
13422
|
-
catalogInterface: config.catalogInterface
|
|
13915
|
+
catalogInterface: config.catalogInterface,
|
|
13916
|
+
storageSealKey: config.storageSealKey ?? config.signingKey
|
|
13423
13917
|
}),
|
|
13424
|
-
...aggregateHandlers(config.registry),
|
|
13425
|
-
...tableBufferingHandlers(config.registry, config.signingKey, config.attachSecretKey),
|
|
13918
|
+
...aggregateHandlers(config.registry, config.signingKey, config.attachSecretKey, config.storageSealKey ?? config.signingKey),
|
|
13919
|
+
...tableBufferingHandlers(config.registry, config.signingKey, config.attachSecretKey, config.storageSealKey ?? config.signingKey),
|
|
13426
13920
|
...catalogHandlers(config.catalogInterface, config.signingKey, config.attachSecretKey)
|
|
13427
13921
|
};
|
|
13428
13922
|
}
|
|
@@ -13698,6 +14192,7 @@ function createVgiFetch(opts) {
|
|
|
13698
14192
|
const serverId = opts.serverId ?? "vgi-cf";
|
|
13699
14193
|
const protocol = buildVgiProtocol({
|
|
13700
14194
|
signingKey: opts.signingKey,
|
|
14195
|
+
storageSealKey: typeof opts.storageSealKey === "string" ? new TextEncoder().encode(opts.storageSealKey) : opts.storageSealKey,
|
|
13701
14196
|
...opts.protocol
|
|
13702
14197
|
});
|
|
13703
14198
|
const server = buildRpcServer(protocol, opts, {
|
|
@@ -13768,6 +14263,16 @@ function resolveSigningKey(explicit, env, warn = console.error) {
|
|
|
13768
14263
|
` + ` Set it for any real deployment: openssl rand -hex ${SIGNING_KEY_BYTES}`);
|
|
13769
14264
|
return crypto.getRandomValues(new Uint8Array(SIGNING_KEY_BYTES));
|
|
13770
14265
|
}
|
|
14266
|
+
function resolveStorageSealKey(explicit, env, resolvedSigningKey) {
|
|
14267
|
+
if (typeof explicit === "string")
|
|
14268
|
+
return new TextEncoder().encode(explicit);
|
|
14269
|
+
if (explicit)
|
|
14270
|
+
return explicit;
|
|
14271
|
+
const raw = env.VGI_SIGNING_KEY;
|
|
14272
|
+
if (raw && raw.trim())
|
|
14273
|
+
return new TextEncoder().encode(raw);
|
|
14274
|
+
return resolvedSigningKey;
|
|
14275
|
+
}
|
|
13771
14276
|
function resolvePort(explicit, env) {
|
|
13772
14277
|
if (explicit !== undefined)
|
|
13773
14278
|
return explicit;
|
|
@@ -13794,7 +14299,8 @@ function resolveTokenTtl(explicit, env) {
|
|
|
13794
14299
|
}
|
|
13795
14300
|
function createVgiWorkerFetch(opts) {
|
|
13796
14301
|
const env = opts.env ?? process.env;
|
|
13797
|
-
const signingKey = resolveSigningKey(opts.signingKey, env);
|
|
14302
|
+
const signingKey = resolveSigningKey(typeof opts.signingKey === "string" ? parseSigningKeyHex(opts.signingKey) : opts.signingKey, env);
|
|
14303
|
+
const storageSealKey = resolveStorageSealKey(opts.signingKey, env, signingKey);
|
|
13798
14304
|
const signingKeyConfigured = opts.signingKey !== undefined || !!env.VGI_SIGNING_KEY?.trim();
|
|
13799
14305
|
const tokenTtl = resolveTokenTtl(opts.tokenTtl, env);
|
|
13800
14306
|
const corsOrigins = opts.corsOrigins === null ? null : opts.corsOrigins ?? env.CORS_ORIGINS;
|
|
@@ -13807,6 +14313,7 @@ function createVgiWorkerFetch(opts) {
|
|
|
13807
14313
|
protocol: { registry: opts.registry, catalogInterface: opts.catalogInterface, attachSecretKey: opts.attachSecretKey },
|
|
13808
14314
|
signingKey,
|
|
13809
14315
|
signingKeyConfigured,
|
|
14316
|
+
storageSealKey,
|
|
13810
14317
|
tokenTtl,
|
|
13811
14318
|
prefix: opts.prefix ?? "",
|
|
13812
14319
|
serverId: opts.serverId ?? opts.name,
|
|
@@ -13867,7 +14374,8 @@ export {
|
|
|
13867
14374
|
createVgiWorkerFetch,
|
|
13868
14375
|
parseSigningKeyHex,
|
|
13869
14376
|
resolveSigningKey,
|
|
14377
|
+
resolveStorageSealKey,
|
|
13870
14378
|
serveVgiWorker
|
|
13871
14379
|
};
|
|
13872
14380
|
|
|
13873
|
-
//# debugId=
|
|
14381
|
+
//# debugId=919A0BBC2C4200EB64756E2164756E21
|