@query-farm/vgi 0.50.0 → 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/index.js
CHANGED
|
@@ -2057,6 +2057,251 @@ var init_arrow = __esm(() => {
|
|
|
2057
2057
|
init_branded();
|
|
2058
2058
|
});
|
|
2059
2059
|
|
|
2060
|
+
// src/attach-secret-keyfile.ts
|
|
2061
|
+
function builtins() {
|
|
2062
|
+
const proc = globalThis.process;
|
|
2063
|
+
const get = proc?.getBuiltinModule?.bind(proc);
|
|
2064
|
+
const fs = get?.("node:fs");
|
|
2065
|
+
const os = get?.("node:os");
|
|
2066
|
+
const path = get?.("node:path");
|
|
2067
|
+
if (!fs || !os || !path)
|
|
2068
|
+
throw new Error("this runtime has no filesystem for the host-local attach secret key file.");
|
|
2069
|
+
return { fs, os, path };
|
|
2070
|
+
}
|
|
2071
|
+
function username() {
|
|
2072
|
+
try {
|
|
2073
|
+
const name = builtins().os.userInfo().username;
|
|
2074
|
+
if (name)
|
|
2075
|
+
return name;
|
|
2076
|
+
} catch {}
|
|
2077
|
+
return process.env.USER || process.env.USERNAME || String(process.getuid?.() ?? "user");
|
|
2078
|
+
}
|
|
2079
|
+
function isDirectory(path) {
|
|
2080
|
+
try {
|
|
2081
|
+
return builtins().fs.statSync(path).isDirectory();
|
|
2082
|
+
} catch {
|
|
2083
|
+
return false;
|
|
2084
|
+
}
|
|
2085
|
+
}
|
|
2086
|
+
function hostLocalAttachSecretKeyPath(env = globalThis.process?.env ?? {}) {
|
|
2087
|
+
const { os, path: { join } } = builtins();
|
|
2088
|
+
const explicit = env[ATTACH_SECRET_KEY_FILE_ENV];
|
|
2089
|
+
if (explicit)
|
|
2090
|
+
return explicit;
|
|
2091
|
+
const xdg = env.XDG_RUNTIME_DIR;
|
|
2092
|
+
if (xdg && isDirectory(xdg))
|
|
2093
|
+
return join(xdg, "vgi", FILE_NAME);
|
|
2094
|
+
return join(os.tmpdir(), `vgi-${username()}`, FILE_NAME);
|
|
2095
|
+
}
|
|
2096
|
+
function checkOwnedPrivate(path, mode, uid, what) {
|
|
2097
|
+
if (!POSIX)
|
|
2098
|
+
return;
|
|
2099
|
+
const me = process.getuid?.();
|
|
2100
|
+
if (me !== undefined && uid !== me) {
|
|
2101
|
+
throw new Error(`attach secret key ${what} ${path} is not owned by the current user. ${REMEDY}`);
|
|
2102
|
+
}
|
|
2103
|
+
if ((mode & 63) !== 0) {
|
|
2104
|
+
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}`);
|
|
2105
|
+
}
|
|
2106
|
+
}
|
|
2107
|
+
function ensureDir(dir) {
|
|
2108
|
+
const { mkdirSync, lstatSync } = builtins().fs;
|
|
2109
|
+
try {
|
|
2110
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
2111
|
+
} catch (e) {
|
|
2112
|
+
if (e.code !== "EEXIST")
|
|
2113
|
+
throw e;
|
|
2114
|
+
}
|
|
2115
|
+
const st = lstatSync(dir);
|
|
2116
|
+
if (!st.isDirectory())
|
|
2117
|
+
throw new Error(`attach secret key directory ${dir} is not a directory. ${REMEDY}`);
|
|
2118
|
+
checkOwnedPrivate(dir, st.mode, st.uid, "directory");
|
|
2119
|
+
}
|
|
2120
|
+
function readKey(path) {
|
|
2121
|
+
const { openSync, fstatSync, readSync, closeSync, constants } = builtins().fs;
|
|
2122
|
+
let fd;
|
|
2123
|
+
try {
|
|
2124
|
+
fd = openSync(path, constants.O_RDONLY | (POSIX ? constants.O_NOFOLLOW : 0));
|
|
2125
|
+
} catch (e) {
|
|
2126
|
+
if (e.code === "ENOENT")
|
|
2127
|
+
return null;
|
|
2128
|
+
throw new Error(`attach secret key file ${path} cannot be opened (${e.code}). ${REMEDY}`);
|
|
2129
|
+
}
|
|
2130
|
+
try {
|
|
2131
|
+
const st = fstatSync(fd);
|
|
2132
|
+
if (!st.isFile())
|
|
2133
|
+
throw new Error(`attach secret key file ${path} is not a regular file. ${REMEDY}`);
|
|
2134
|
+
checkOwnedPrivate(path, st.mode, st.uid, "file");
|
|
2135
|
+
const buf = new Uint8Array(KEY_LEN + 1);
|
|
2136
|
+
let n = 0;
|
|
2137
|
+
for (;; ) {
|
|
2138
|
+
const got = readSync(fd, buf, n, buf.length - n, null);
|
|
2139
|
+
if (got <= 0)
|
|
2140
|
+
break;
|
|
2141
|
+
n += got;
|
|
2142
|
+
if (n === buf.length)
|
|
2143
|
+
break;
|
|
2144
|
+
}
|
|
2145
|
+
if (n !== KEY_LEN || st.size !== KEY_LEN) {
|
|
2146
|
+
throw new Error(`attach secret key file ${path} must contain exactly ${KEY_LEN} raw bytes (found ${st.size}). ${REMEDY}`);
|
|
2147
|
+
}
|
|
2148
|
+
return buf.subarray(0, KEY_LEN);
|
|
2149
|
+
} finally {
|
|
2150
|
+
closeSync(fd);
|
|
2151
|
+
}
|
|
2152
|
+
}
|
|
2153
|
+
function createKey(path) {
|
|
2154
|
+
const { openSync, writeSync, fsyncSync, closeSync, linkSync, unlinkSync, constants } = builtins().fs;
|
|
2155
|
+
const { dirname, join } = builtins().path;
|
|
2156
|
+
const tmp = join(dirname(path), `.${FILE_NAME}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);
|
|
2157
|
+
const fd = openSync(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 384);
|
|
2158
|
+
try {
|
|
2159
|
+
const key = crypto.getRandomValues(new Uint8Array(KEY_LEN));
|
|
2160
|
+
let off = 0;
|
|
2161
|
+
while (off < KEY_LEN)
|
|
2162
|
+
off += writeSync(fd, key, off, KEY_LEN - off);
|
|
2163
|
+
fsyncSync(fd);
|
|
2164
|
+
} finally {
|
|
2165
|
+
closeSync(fd);
|
|
2166
|
+
}
|
|
2167
|
+
try {
|
|
2168
|
+
linkSync(tmp, path);
|
|
2169
|
+
} catch (e) {
|
|
2170
|
+
if (e.code !== "EEXIST") {
|
|
2171
|
+
unlinkSync(tmp);
|
|
2172
|
+
throw e;
|
|
2173
|
+
}
|
|
2174
|
+
}
|
|
2175
|
+
unlinkSync(tmp);
|
|
2176
|
+
}
|
|
2177
|
+
function loadHostLocalAttachSecretKey(path = hostLocalAttachSecretKeyPath()) {
|
|
2178
|
+
ensureDir(builtins().path.dirname(path));
|
|
2179
|
+
const existing = readKey(path);
|
|
2180
|
+
if (existing)
|
|
2181
|
+
return existing;
|
|
2182
|
+
createKey(path);
|
|
2183
|
+
const created = readKey(path);
|
|
2184
|
+
if (!created)
|
|
2185
|
+
throw new Error(`attach secret key file ${path} vanished after creation. ${REMEDY}`);
|
|
2186
|
+
return created;
|
|
2187
|
+
}
|
|
2188
|
+
async function hostLocalAttachSecretKey() {
|
|
2189
|
+
const path = hostLocalAttachSecretKeyPath();
|
|
2190
|
+
if (cached?.path === path)
|
|
2191
|
+
return cached.key;
|
|
2192
|
+
const key = loadHostLocalAttachSecretKey(path);
|
|
2193
|
+
cached = { path, key };
|
|
2194
|
+
return key;
|
|
2195
|
+
}
|
|
2196
|
+
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;
|
|
2197
|
+
var init_attach_secret_keyfile = __esm(() => {
|
|
2198
|
+
POSIX = typeof process === "undefined" || process.platform !== "win32";
|
|
2199
|
+
});
|
|
2200
|
+
|
|
2201
|
+
// src/functions/storage-seal.ts
|
|
2202
|
+
function lp(b) {
|
|
2203
|
+
const out = new Uint8Array(4 + b.length);
|
|
2204
|
+
new DataView(out.buffer).setUint32(0, b.length, false);
|
|
2205
|
+
out.set(b, 4);
|
|
2206
|
+
return out;
|
|
2207
|
+
}
|
|
2208
|
+
function concat(parts) {
|
|
2209
|
+
let n = 0;
|
|
2210
|
+
for (const p of parts)
|
|
2211
|
+
n += p.length;
|
|
2212
|
+
const out = new Uint8Array(n);
|
|
2213
|
+
let off = 0;
|
|
2214
|
+
for (const p of parts) {
|
|
2215
|
+
out.set(p, off);
|
|
2216
|
+
off += p.length;
|
|
2217
|
+
}
|
|
2218
|
+
return out;
|
|
2219
|
+
}
|
|
2220
|
+
function hex(b) {
|
|
2221
|
+
let s = "";
|
|
2222
|
+
for (let i = 0;i < b.length; i++)
|
|
2223
|
+
s += b[i].toString(16).padStart(2, "0");
|
|
2224
|
+
return s;
|
|
2225
|
+
}
|
|
2226
|
+
function storagePayloadAad(slot) {
|
|
2227
|
+
return concat([INFO_BYTES, lp(UTF82.encode(slot.shardKey)), lp(slot.scopeId), lp(slot.ns), lp(slot.key)]);
|
|
2228
|
+
}
|
|
2229
|
+
async function deriveStoragePayloadKey(ikm) {
|
|
2230
|
+
const base = await crypto.subtle.importKey("raw", ikm, "HKDF", false, ["deriveBits"]);
|
|
2231
|
+
const bits = await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: INFO_BYTES }, base, KEY_LEN2 * 8);
|
|
2232
|
+
return new Uint8Array(bits);
|
|
2233
|
+
}
|
|
2234
|
+
function aesKey(ikm) {
|
|
2235
|
+
const id = hex(ikm);
|
|
2236
|
+
let k = keyCache.get(id);
|
|
2237
|
+
if (!k) {
|
|
2238
|
+
k = (async () => {
|
|
2239
|
+
const raw = await deriveStoragePayloadKey(ikm);
|
|
2240
|
+
return crypto.subtle.importKey("raw", raw, "AES-GCM", false, ["encrypt", "decrypt"]);
|
|
2241
|
+
})();
|
|
2242
|
+
if (keyCache.size >= KEY_CACHE_MAX)
|
|
2243
|
+
keyCache.delete(keyCache.keys().next().value);
|
|
2244
|
+
keyCache.set(id, k);
|
|
2245
|
+
k.catch(() => keyCache.delete(id));
|
|
2246
|
+
}
|
|
2247
|
+
return k;
|
|
2248
|
+
}
|
|
2249
|
+
async function sealWith(payload, ikm, slot, nonce) {
|
|
2250
|
+
if (nonce !== undefined && nonce.length !== NONCE_LEN)
|
|
2251
|
+
throw new Error(`nonce must be ${NONCE_LEN} bytes`);
|
|
2252
|
+
const iv = nonce ?? crypto.getRandomValues(new Uint8Array(NONCE_LEN));
|
|
2253
|
+
const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: storagePayloadAad(slot), tagLength: TAG_LEN * 8 }, await aesKey(ikm), payload));
|
|
2254
|
+
const out = new Uint8Array(1 + NONCE_LEN + ct.length);
|
|
2255
|
+
out[0] = STORAGE_PAYLOAD_VERSION;
|
|
2256
|
+
out.set(iv, 1);
|
|
2257
|
+
out.set(ct, 1 + NONCE_LEN);
|
|
2258
|
+
return out;
|
|
2259
|
+
}
|
|
2260
|
+
async function openWith(blob, ikm, slot) {
|
|
2261
|
+
const what = `framework storage payload ${JSON.stringify(new TextDecoder().decode(slot.ns))} for execution ${hex(slot.scopeId)}`;
|
|
2262
|
+
if (blob.length < 1 + NONCE_LEN + TAG_LEN) {
|
|
2263
|
+
throw new StoragePayloadError(`${what} is too short to be a sealed payload`);
|
|
2264
|
+
}
|
|
2265
|
+
if (blob[0] !== STORAGE_PAYLOAD_VERSION) {
|
|
2266
|
+
throw new StoragePayloadError(`${what} has unknown seal version 0x${blob[0].toString(16).padStart(2, "0")}`);
|
|
2267
|
+
}
|
|
2268
|
+
const iv = blob.subarray(1, 1 + NONCE_LEN);
|
|
2269
|
+
const body = blob.subarray(1 + NONCE_LEN);
|
|
2270
|
+
try {
|
|
2271
|
+
return new Uint8Array(await crypto.subtle.decrypt({ name: "AES-GCM", iv, additionalData: storagePayloadAad(slot), tagLength: TAG_LEN * 8 }, await aesKey(ikm), body));
|
|
2272
|
+
} catch {
|
|
2273
|
+
throw new StoragePayloadError(`${what} failed authentication (tampered, moved, or sealed under another key)`);
|
|
2274
|
+
}
|
|
2275
|
+
}
|
|
2276
|
+
async function ikmFor(signingKey) {
|
|
2277
|
+
if (signingKey && signingKey.length > 0)
|
|
2278
|
+
return signingKey;
|
|
2279
|
+
try {
|
|
2280
|
+
return await (hostLocalOverride ?? hostLocalAttachSecretKey)();
|
|
2281
|
+
} catch (e) {
|
|
2282
|
+
throw new StoragePayloadError(`no key to seal framework storage payloads: ${e?.message ?? e}`);
|
|
2283
|
+
}
|
|
2284
|
+
}
|
|
2285
|
+
async function sealPayload(payload, signingKey, slot) {
|
|
2286
|
+
return sealWith(payload, await ikmFor(signingKey), slot);
|
|
2287
|
+
}
|
|
2288
|
+
async function openPayload(blob, signingKey, slot) {
|
|
2289
|
+
return openWith(blob, await ikmFor(signingKey), slot);
|
|
2290
|
+
}
|
|
2291
|
+
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;
|
|
2292
|
+
var init_storage_seal = __esm(() => {
|
|
2293
|
+
init_attach_secret_keyfile();
|
|
2294
|
+
UTF82 = new TextEncoder;
|
|
2295
|
+
INFO_BYTES = UTF82.encode(STORAGE_PAYLOAD_INFO);
|
|
2296
|
+
StoragePayloadError = class StoragePayloadError extends Error {
|
|
2297
|
+
constructor(message) {
|
|
2298
|
+
super(message);
|
|
2299
|
+
this.name = "StoragePayloadError";
|
|
2300
|
+
}
|
|
2301
|
+
};
|
|
2302
|
+
keyCache = new Map;
|
|
2303
|
+
});
|
|
2304
|
+
|
|
2060
2305
|
// src/functions/storage-cf-do.ts
|
|
2061
2306
|
var exports_storage_cf_do = {};
|
|
2062
2307
|
__export(exports_storage_cf_do, {
|
|
@@ -2068,11 +2313,27 @@ class FunctionStorageCfDo {
|
|
|
2068
2313
|
_token;
|
|
2069
2314
|
_shardKey;
|
|
2070
2315
|
_fetch;
|
|
2316
|
+
_retry;
|
|
2317
|
+
_sleep;
|
|
2071
2318
|
constructor(opts) {
|
|
2072
2319
|
this._baseUrl = opts.url.replace(/\/+$/, "");
|
|
2073
2320
|
this._token = opts.token ?? null;
|
|
2074
|
-
|
|
2321
|
+
const shard = opts.shardKey ?? "";
|
|
2322
|
+
if (shard !== "" && !SHARD_KEY_RE.test(shard)) {
|
|
2323
|
+
throw new Error(`invalid CF DO shard_key ${JSON.stringify(shard)} (1-128 chars, [A-Za-z0-9._-])`);
|
|
2324
|
+
}
|
|
2325
|
+
this._shardKey = shard;
|
|
2075
2326
|
this._fetch = opts.fetch ?? ((input, init) => fetch(input, init));
|
|
2327
|
+
this._retry = {
|
|
2328
|
+
timeoutMs: opts.retry?.timeoutMs ?? 30000,
|
|
2329
|
+
maxAttempts: Math.max(1, opts.retry?.maxAttempts ?? 4),
|
|
2330
|
+
baseDelayMs: opts.retry?.baseDelayMs ?? 100,
|
|
2331
|
+
maxDelayMs: opts.retry?.maxDelayMs ?? 2000
|
|
2332
|
+
};
|
|
2333
|
+
this._sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
2334
|
+
}
|
|
2335
|
+
get shardKey() {
|
|
2336
|
+
return this._shardKey;
|
|
2076
2337
|
}
|
|
2077
2338
|
static fromEnv() {
|
|
2078
2339
|
const url = process.env.VGI_CF_DO_URL;
|
|
@@ -2085,11 +2346,15 @@ class FunctionStorageCfDo {
|
|
|
2085
2346
|
});
|
|
2086
2347
|
}
|
|
2087
2348
|
forShard(shardKey) {
|
|
2349
|
+
if (shardKey === this._shardKey)
|
|
2350
|
+
return this;
|
|
2088
2351
|
return new FunctionStorageCfDo({
|
|
2089
2352
|
url: this._baseUrl,
|
|
2090
2353
|
token: this._token,
|
|
2091
2354
|
shardKey,
|
|
2092
|
-
fetch: this._fetch
|
|
2355
|
+
fetch: this._fetch,
|
|
2356
|
+
retry: this._retry,
|
|
2357
|
+
sleep: this._sleep
|
|
2093
2358
|
});
|
|
2094
2359
|
}
|
|
2095
2360
|
async workerPut(executionId, worker, state) {
|
|
@@ -2126,16 +2391,29 @@ class FunctionStorageCfDo {
|
|
|
2126
2391
|
return Number(data.cleared);
|
|
2127
2392
|
}
|
|
2128
2393
|
async stateGet(scopeId, ns, key) {
|
|
2394
|
+
return (await this.stateGetMany(scopeId, ns, [key]))[0] ?? null;
|
|
2395
|
+
}
|
|
2396
|
+
async statePut(scopeId, ns, key, value) {
|
|
2397
|
+
await this._statePutMany(scopeId, ns, [[key, value]]);
|
|
2398
|
+
}
|
|
2399
|
+
async stateGetMany(scopeId, ns, keys) {
|
|
2400
|
+
if (keys.length === 0)
|
|
2401
|
+
return [];
|
|
2129
2402
|
const data = await this._post("state_get_many", {
|
|
2130
2403
|
scope_id: bytesToB64(scopeId),
|
|
2131
2404
|
ns: bytesToB64(ns),
|
|
2132
|
-
keys:
|
|
2405
|
+
keys: keys.map(bytesToB64)
|
|
2406
|
+
});
|
|
2407
|
+
const rows = data.rows ?? [];
|
|
2408
|
+
return keys.map((_, i) => {
|
|
2409
|
+
const row = rows[i];
|
|
2410
|
+
return row ? b64ToBytes(row.value) : null;
|
|
2133
2411
|
});
|
|
2134
|
-
const row = (data.rows ?? [])[0];
|
|
2135
|
-
return row ? b64ToBytes(row.value) : null;
|
|
2136
2412
|
}
|
|
2137
|
-
async
|
|
2138
|
-
|
|
2413
|
+
async statePutMany(scopeId, ns, items) {
|
|
2414
|
+
if (items.length === 0)
|
|
2415
|
+
return;
|
|
2416
|
+
await this._statePutMany(scopeId, ns, items);
|
|
2139
2417
|
}
|
|
2140
2418
|
async stateAppend(scopeId, ns, key, item) {
|
|
2141
2419
|
const data = await this._post("state_append", {
|
|
@@ -2197,20 +2475,56 @@ class FunctionStorageCfDo {
|
|
|
2197
2475
|
const headers = { "Content-Type": "application/json" };
|
|
2198
2476
|
if (this._token)
|
|
2199
2477
|
headers["Authorization"] = `Bearer ${this._token}`;
|
|
2200
|
-
const payload = JSON.stringify({ ...body, shard_key: this._shardKey });
|
|
2478
|
+
const payload = JSON.stringify({ ...body, shard_key: this._shardKey || ANONYMOUS_SHARD_KEY });
|
|
2479
|
+
const { maxAttempts, baseDelayMs, maxDelayMs } = this._retry;
|
|
2201
2480
|
let lastErr;
|
|
2202
|
-
for (let attempt = 0;attempt <
|
|
2481
|
+
for (let attempt = 0;attempt < maxAttempts; attempt++) {
|
|
2482
|
+
if (attempt > 0) {
|
|
2483
|
+
const cap = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1));
|
|
2484
|
+
const jittered = Math.random() * cap;
|
|
2485
|
+
const hinted = lastErr instanceof RetryableError && lastErr.retryAfterMs != null ? Math.min(maxDelayMs, lastErr.retryAfterMs) : 0;
|
|
2486
|
+
await this._sleep(Math.max(jittered, hinted));
|
|
2487
|
+
}
|
|
2488
|
+
try {
|
|
2489
|
+
return await this._once(url, endpoint, headers, payload);
|
|
2490
|
+
} catch (e) {
|
|
2491
|
+
if (!(e instanceof RetryableError))
|
|
2492
|
+
throw e;
|
|
2493
|
+
lastErr = e;
|
|
2494
|
+
}
|
|
2495
|
+
}
|
|
2496
|
+
throw new Error(`CF DO storage ${endpoint} failed after ${maxAttempts} attempts: ${lastErr?.message ?? "unknown error"}`);
|
|
2497
|
+
}
|
|
2498
|
+
async _once(url, endpoint, headers, payload) {
|
|
2499
|
+
const { timeoutMs } = this._retry;
|
|
2500
|
+
const controller = timeoutMs > 0 ? new AbortController : null;
|
|
2501
|
+
const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
|
|
2502
|
+
try {
|
|
2203
2503
|
let resp;
|
|
2204
2504
|
try {
|
|
2205
|
-
resp = await this._fetch(url, {
|
|
2505
|
+
resp = await this._fetch(url, {
|
|
2506
|
+
method: "POST",
|
|
2507
|
+
headers,
|
|
2508
|
+
body: payload,
|
|
2509
|
+
...controller ? { signal: controller.signal } : {}
|
|
2510
|
+
});
|
|
2206
2511
|
} catch (err) {
|
|
2207
|
-
|
|
2208
|
-
|
|
2512
|
+
if (controller?.signal.aborted) {
|
|
2513
|
+
throw new RetryableError(`timed out after ${timeoutMs} ms on ${endpoint}`);
|
|
2514
|
+
}
|
|
2515
|
+
throw new RetryableError(`transport error on ${endpoint}: ${err?.message ?? String(err)}`);
|
|
2516
|
+
}
|
|
2517
|
+
if (resp.status === 429 || resp.status >= 500) {
|
|
2518
|
+
const text = await resp.text().catch(() => "");
|
|
2519
|
+
throw new RetryableError(`CF DO storage error ${resp.status} on ${endpoint}: ${text.slice(0, 200) || "<empty body>"}`, parseRetryAfter(resp.headers?.get?.("Retry-After") ?? null));
|
|
2209
2520
|
}
|
|
2210
2521
|
let data;
|
|
2211
2522
|
try {
|
|
2212
2523
|
data = await resp.json();
|
|
2213
|
-
} catch {
|
|
2524
|
+
} catch (err) {
|
|
2525
|
+
if (controller?.signal.aborted) {
|
|
2526
|
+
throw new RetryableError(`timed out after ${timeoutMs} ms reading ${endpoint}`);
|
|
2527
|
+
}
|
|
2214
2528
|
if (!resp.ok) {
|
|
2215
2529
|
throw new Error(`CF DO storage error ${resp.status} on ${endpoint}: <non-json body>`);
|
|
2216
2530
|
}
|
|
@@ -2226,10 +2540,18 @@ class FunctionStorageCfDo {
|
|
|
2226
2540
|
throw new Error(`CF DO storage error ${resp.status} on ${endpoint}: ${JSON.stringify(data)}`);
|
|
2227
2541
|
}
|
|
2228
2542
|
return data;
|
|
2543
|
+
} finally {
|
|
2544
|
+
if (timer)
|
|
2545
|
+
clearTimeout(timer);
|
|
2229
2546
|
}
|
|
2230
|
-
throw lastErr instanceof Error ? lastErr : new Error(`CF DO storage transport error on ${endpoint}: ${String(lastErr)}`);
|
|
2231
2547
|
}
|
|
2232
2548
|
}
|
|
2549
|
+
function parseRetryAfter(v) {
|
|
2550
|
+
if (!v)
|
|
2551
|
+
return null;
|
|
2552
|
+
const n = Number(v.trim());
|
|
2553
|
+
return Number.isFinite(n) && n >= 0 ? n * 1000 : null;
|
|
2554
|
+
}
|
|
2233
2555
|
function newAttemptId() {
|
|
2234
2556
|
const b = new Uint8Array(16);
|
|
2235
2557
|
crypto.getRandomValues(b);
|
|
@@ -2256,9 +2578,17 @@ function b64ToBytes(b64) {
|
|
|
2256
2578
|
out[i] = binary.charCodeAt(i);
|
|
2257
2579
|
return out;
|
|
2258
2580
|
}
|
|
2259
|
-
var NS_WORKER;
|
|
2581
|
+
var SHARD_KEY_RE, ANONYMOUS_SHARD_KEY = "loc-anon", RetryableError, NS_WORKER;
|
|
2260
2582
|
var init_storage_cf_do = __esm(() => {
|
|
2261
2583
|
init_storage();
|
|
2584
|
+
SHARD_KEY_RE = /^[A-Za-z0-9._-]{1,128}$/;
|
|
2585
|
+
RetryableError = class RetryableError extends Error {
|
|
2586
|
+
retryAfterMs;
|
|
2587
|
+
constructor(message, retryAfterMs = null) {
|
|
2588
|
+
super(message);
|
|
2589
|
+
this.retryAfterMs = retryAfterMs;
|
|
2590
|
+
}
|
|
2591
|
+
};
|
|
2262
2592
|
NS_WORKER = new TextEncoder().encode("worker");
|
|
2263
2593
|
});
|
|
2264
2594
|
|
|
@@ -2307,7 +2637,7 @@ function getDefaultDbPath() {
|
|
|
2307
2637
|
const { homedir, platform, join, mkdirSync } = _loadNodeIo();
|
|
2308
2638
|
const home = homedir();
|
|
2309
2639
|
const stateDir = platform() === "darwin" ? join(home, "Library", "Application Support", "vgi") : join(home, ".local", "state", "vgi");
|
|
2310
|
-
mkdirSync(stateDir, { recursive: true });
|
|
2640
|
+
mkdirSync(stateDir, { recursive: true, mode: 448 });
|
|
2311
2641
|
return join(stateDir, "vgi_storage.db");
|
|
2312
2642
|
}
|
|
2313
2643
|
function int64Key(v) {
|
|
@@ -2419,6 +2749,33 @@ class FunctionStorageSqlite {
|
|
|
2419
2749
|
async statePut(scopeId, ns, key, value) {
|
|
2420
2750
|
this._db.prepare("INSERT OR REPLACE INTO function_state (scope_id, ns, key, value) VALUES (?, ?, ?, ?)").run(bufferArg(scopeId), bufferArg(ns), bufferArg(key), bufferArg(value));
|
|
2421
2751
|
}
|
|
2752
|
+
async stateGetMany(scopeId, ns, keys) {
|
|
2753
|
+
if (keys.length === 0)
|
|
2754
|
+
return [];
|
|
2755
|
+
const stmt = this._db.prepare("SELECT value FROM function_state WHERE scope_id = ? AND ns = ? AND key = ?");
|
|
2756
|
+
const sid = bufferArg(scopeId);
|
|
2757
|
+
const nsb = bufferArg(ns);
|
|
2758
|
+
return keys.map((k) => {
|
|
2759
|
+
const row = stmt.get(sid, nsb, bufferArg(k));
|
|
2760
|
+
return row ? new Uint8Array(row.value) : null;
|
|
2761
|
+
});
|
|
2762
|
+
}
|
|
2763
|
+
async statePutMany(scopeId, ns, items) {
|
|
2764
|
+
if (items.length === 0)
|
|
2765
|
+
return;
|
|
2766
|
+
const stmt = this._db.prepare("INSERT OR REPLACE INTO function_state (scope_id, ns, key, value) VALUES (?, ?, ?, ?)");
|
|
2767
|
+
const sid = bufferArg(scopeId);
|
|
2768
|
+
const nsb = bufferArg(ns);
|
|
2769
|
+
this._db.exec("BEGIN IMMEDIATE");
|
|
2770
|
+
try {
|
|
2771
|
+
for (const [k, v] of items)
|
|
2772
|
+
stmt.run(sid, nsb, bufferArg(k), bufferArg(v));
|
|
2773
|
+
this._db.exec("COMMIT");
|
|
2774
|
+
} catch (e) {
|
|
2775
|
+
this._db.exec("ROLLBACK");
|
|
2776
|
+
throw e;
|
|
2777
|
+
}
|
|
2778
|
+
}
|
|
2422
2779
|
async stateAppend(scopeId, ns, key, item) {
|
|
2423
2780
|
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));
|
|
2424
2781
|
return Number(res.lastInsertRowid);
|
|
@@ -2479,10 +2836,18 @@ class BoundStorage {
|
|
|
2479
2836
|
_base;
|
|
2480
2837
|
_executionId;
|
|
2481
2838
|
_substreamId;
|
|
2482
|
-
|
|
2483
|
-
|
|
2839
|
+
_shardKey;
|
|
2840
|
+
constructor(storage, executionId, substreamId = null, shardKey = "") {
|
|
2841
|
+
this._base = typeof storage.forShard === "function" ? storage.forShard(shardKey) : storage;
|
|
2484
2842
|
this._executionId = executionId;
|
|
2485
2843
|
this._substreamId = substreamId;
|
|
2844
|
+
this._shardKey = shardKey;
|
|
2845
|
+
}
|
|
2846
|
+
get shardKey() {
|
|
2847
|
+
return this._shardKey;
|
|
2848
|
+
}
|
|
2849
|
+
get executionId() {
|
|
2850
|
+
return this._executionId;
|
|
2486
2851
|
}
|
|
2487
2852
|
put(state) {
|
|
2488
2853
|
return this._base.workerPut(this._executionId, this._substreamId ?? process.pid, state);
|
|
@@ -2508,6 +2873,12 @@ class BoundStorage {
|
|
|
2508
2873
|
statePut(ns, key, value) {
|
|
2509
2874
|
return this._base.statePut(this._executionId, ns, key, value);
|
|
2510
2875
|
}
|
|
2876
|
+
stateGetMany(ns, keys) {
|
|
2877
|
+
return this._base.stateGetMany(this._executionId, ns, keys);
|
|
2878
|
+
}
|
|
2879
|
+
statePutMany(ns, items) {
|
|
2880
|
+
return this._base.statePutMany(this._executionId, ns, items);
|
|
2881
|
+
}
|
|
2511
2882
|
stateAppend(ns, key, item) {
|
|
2512
2883
|
return this._base.stateAppend(this._executionId, ns, key, item);
|
|
2513
2884
|
}
|
|
@@ -2517,10 +2888,28 @@ class BoundStorage {
|
|
|
2517
2888
|
executionClear() {
|
|
2518
2889
|
return this._base.executionClear(this._executionId);
|
|
2519
2890
|
}
|
|
2891
|
+
_slot(ns, key) {
|
|
2892
|
+
return { shardKey: this._shardKey, scopeId: this._executionId, ns, key };
|
|
2893
|
+
}
|
|
2894
|
+
async sealedPut(ns, key, payload, signingKey) {
|
|
2895
|
+
const sealed = await sealPayload(payload, signingKey, this._slot(ns, key));
|
|
2896
|
+
await this.statePut(ns, key, sealed);
|
|
2897
|
+
return sealed;
|
|
2898
|
+
}
|
|
2899
|
+
openSealed(ns, key, sealed, signingKey) {
|
|
2900
|
+
return openPayload(sealed, signingKey, this._slot(ns, key));
|
|
2901
|
+
}
|
|
2902
|
+
async sealedGet(ns, key, signingKey) {
|
|
2903
|
+
const sealed = await this.stateGet(ns, key);
|
|
2904
|
+
return sealed == null ? null : this.openSealed(ns, key, sealed, signingKey);
|
|
2905
|
+
}
|
|
2520
2906
|
static packIntKey(i) {
|
|
2521
2907
|
return packIntKey(i);
|
|
2522
2908
|
}
|
|
2523
2909
|
}
|
|
2910
|
+
function shardKeyOf(bindCall) {
|
|
2911
|
+
return bindCall?.storage_shard_key ?? "";
|
|
2912
|
+
}
|
|
2524
2913
|
function resolveStorageFromEnv() {
|
|
2525
2914
|
const backend = (process.env.VGI_WORKER_SHARED_STORAGE ?? "sqlite").toLowerCase();
|
|
2526
2915
|
if (backend === "memory") {
|
|
@@ -2548,6 +2937,7 @@ function bufferArg(data) {
|
|
|
2548
2937
|
}
|
|
2549
2938
|
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;
|
|
2550
2939
|
var init_storage = __esm(() => {
|
|
2940
|
+
init_storage_seal();
|
|
2551
2941
|
UnknownInvocationError = class UnknownInvocationError extends Error {
|
|
2552
2942
|
constructor(message) {
|
|
2553
2943
|
let text;
|
|
@@ -2562,7 +2952,8 @@ var init_storage = __esm(() => {
|
|
|
2562
2952
|
};
|
|
2563
2953
|
FrameworkNS = {
|
|
2564
2954
|
BUFFERING_INIT: textBytes("_vgi/buffering_init"),
|
|
2565
|
-
STREAMING_FINALIZE: textBytes("_vgi/streaming_finalize")
|
|
2955
|
+
STREAMING_FINALIZE: textBytes("_vgi/streaming_finalize"),
|
|
2956
|
+
AGGREGATE_STATE: textBytes("_vgi/aggregate_state")
|
|
2566
2957
|
};
|
|
2567
2958
|
NS_WORKER2 = new TextEncoder().encode("worker");
|
|
2568
2959
|
_SLEEP_CELL = new Int32Array(new SharedArrayBuffer(4));
|
|
@@ -5132,7 +5523,7 @@ function defineTableFunction(config) {
|
|
|
5132
5523
|
}
|
|
5133
5524
|
if (config.onInit) {
|
|
5134
5525
|
const args = extractArgs(request.bind_call);
|
|
5135
|
-
const boundStorage = new BoundStorage(storage, executionId);
|
|
5526
|
+
const boundStorage = new BoundStorage(storage, executionId, null, shardKeyOf(request.bind_call));
|
|
5136
5527
|
return await config.onInit({
|
|
5137
5528
|
args,
|
|
5138
5529
|
initCall: request,
|
|
@@ -5162,7 +5553,7 @@ function defineTableFunction(config) {
|
|
|
5162
5553
|
};
|
|
5163
5554
|
const carriedFilterHistory = filterHistory ?? EMPTY_FILTER_HISTORY;
|
|
5164
5555
|
const pushdownFilters = replayFilterHistory(request.pushdown_filters ? deserializeFilters(request.pushdown_filters, filterOptions) : undefined, carriedFilterHistory);
|
|
5165
|
-
const boundStorage = new BoundStorage(storage, response.execution_id);
|
|
5556
|
+
const boundStorage = new BoundStorage(storage, response.execution_id, null, shardKeyOf(request.bind_call));
|
|
5166
5557
|
const processParams = {
|
|
5167
5558
|
args,
|
|
5168
5559
|
initCall: request,
|
|
@@ -5262,7 +5653,7 @@ function defineTableFunction(config) {
|
|
|
5262
5653
|
const args = extractArgs(request.bindCall);
|
|
5263
5654
|
const settings = batchToScalarDict(request.bindCall.settings);
|
|
5264
5655
|
const secrets = batchToSecretDict(request.bindCall.secrets);
|
|
5265
|
-
const storage2 = new BoundStorage(storage, request.globalExecutionId);
|
|
5656
|
+
const storage2 = new BoundStorage(storage, request.globalExecutionId, null, shardKeyOf(request.bindCall));
|
|
5266
5657
|
return config.dynamicToString({
|
|
5267
5658
|
args,
|
|
5268
5659
|
bindCall: request.bindCall,
|
|
@@ -5276,27 +5667,58 @@ function defineTableFunction(config) {
|
|
|
5276
5667
|
}
|
|
5277
5668
|
// src/functions/aggregate.ts
|
|
5278
5669
|
init_arrow();
|
|
5279
|
-
|
|
5280
|
-
|
|
5281
|
-
|
|
5282
|
-
function
|
|
5283
|
-
|
|
5284
|
-
|
|
5285
|
-
|
|
5670
|
+
init_storage();
|
|
5671
|
+
|
|
5672
|
+
// src/functions/execution-cache.ts
|
|
5673
|
+
function hex2(b) {
|
|
5674
|
+
let s = "";
|
|
5675
|
+
for (let i = 0;i < b.length; i++)
|
|
5676
|
+
s += b[i].toString(16).padStart(2, "0");
|
|
5677
|
+
return s;
|
|
5678
|
+
}
|
|
5679
|
+
|
|
5680
|
+
class ExecutionCache {
|
|
5681
|
+
maxEntries;
|
|
5682
|
+
_map = new Map;
|
|
5683
|
+
constructor(maxEntries) {
|
|
5684
|
+
this.maxEntries = maxEntries;
|
|
5685
|
+
}
|
|
5686
|
+
static _key(shardKey, executionId) {
|
|
5687
|
+
return `${shardKey}\x00${hex2(executionId)}`;
|
|
5688
|
+
}
|
|
5689
|
+
get(shardKey, executionId) {
|
|
5690
|
+
const k = ExecutionCache._key(shardKey, executionId);
|
|
5691
|
+
const v = this._map.get(k);
|
|
5692
|
+
if (v === undefined)
|
|
5693
|
+
return;
|
|
5694
|
+
this._map.delete(k);
|
|
5695
|
+
this._map.set(k, v);
|
|
5696
|
+
return v;
|
|
5697
|
+
}
|
|
5698
|
+
set(shardKey, executionId, value) {
|
|
5699
|
+
const k = ExecutionCache._key(shardKey, executionId);
|
|
5700
|
+
this._map.delete(k);
|
|
5701
|
+
this._map.set(k, value);
|
|
5702
|
+
while (this._map.size > this.maxEntries) {
|
|
5703
|
+
this._map.delete(this._map.keys().next().value);
|
|
5704
|
+
}
|
|
5705
|
+
}
|
|
5706
|
+
delete(shardKey, executionId) {
|
|
5707
|
+
this._map.delete(ExecutionCache._key(shardKey, executionId));
|
|
5708
|
+
}
|
|
5709
|
+
clear() {
|
|
5710
|
+
this._map.clear();
|
|
5711
|
+
}
|
|
5712
|
+
get size() {
|
|
5713
|
+
return this._map.size;
|
|
5286
5714
|
}
|
|
5287
|
-
return req;
|
|
5288
5715
|
}
|
|
5289
|
-
|
|
5290
|
-
|
|
5291
|
-
|
|
5292
|
-
var path = new Proxy({}, {
|
|
5293
|
-
get: (_t, prop) => _aggReq()(_NODE_PATH_MOD2)[prop]
|
|
5294
|
-
});
|
|
5295
|
-
var os = new Proxy({}, {
|
|
5296
|
-
get: (_t, prop) => _aggReq()(_NODE_OS_MOD2)[prop]
|
|
5297
|
-
});
|
|
5716
|
+
|
|
5717
|
+
// src/functions/aggregate.ts
|
|
5718
|
+
init_storage_seal();
|
|
5298
5719
|
var GROUP_COLUMN_NAME = "__vgi_group_id";
|
|
5299
|
-
var
|
|
5720
|
+
var AGGREGATE_CONTEXT_KEY = packIntKey(-2);
|
|
5721
|
+
var aggregateContextCache = new ExecutionCache(64);
|
|
5300
5722
|
function jsonReplacer(_, v) {
|
|
5301
5723
|
if (typeof v === "bigint")
|
|
5302
5724
|
return { __bigint__: v.toString() };
|
|
@@ -5308,87 +5730,71 @@ function jsonReviver(_, v) {
|
|
|
5308
5730
|
}
|
|
5309
5731
|
return v;
|
|
5310
5732
|
}
|
|
5311
|
-
|
|
5312
|
-
|
|
5733
|
+
var UTF8_ENC = new TextEncoder;
|
|
5734
|
+
var UTF8_DEC = new TextDecoder;
|
|
5735
|
+
function encodeGroupState(state) {
|
|
5736
|
+
return UTF8_ENC.encode(JSON.stringify(state, jsonReplacer));
|
|
5313
5737
|
}
|
|
5314
|
-
function
|
|
5315
|
-
return
|
|
5738
|
+
function decodeGroupState(bytes) {
|
|
5739
|
+
return JSON.parse(UTF8_DEC.decode(bytes), jsonReviver);
|
|
5316
5740
|
}
|
|
5317
|
-
function
|
|
5318
|
-
let
|
|
5319
|
-
for (
|
|
5320
|
-
|
|
5321
|
-
return
|
|
5741
|
+
function b64(buf) {
|
|
5742
|
+
let binary = "";
|
|
5743
|
+
for (let i = 0;i < buf.length; i++)
|
|
5744
|
+
binary += String.fromCharCode(buf[i]);
|
|
5745
|
+
return btoa(binary);
|
|
5322
5746
|
}
|
|
5323
|
-
function
|
|
5324
|
-
const
|
|
5325
|
-
const
|
|
5326
|
-
|
|
5327
|
-
|
|
5328
|
-
|
|
5747
|
+
function unb64(s) {
|
|
5748
|
+
const binary = atob(s);
|
|
5749
|
+
const out = new Uint8Array(binary.length);
|
|
5750
|
+
for (let i = 0;i < binary.length; i++)
|
|
5751
|
+
out[i] = binary.charCodeAt(i);
|
|
5752
|
+
return out;
|
|
5329
5753
|
}
|
|
5330
|
-
function
|
|
5754
|
+
function encodeAggregateContext(ctx) {
|
|
5755
|
+
return UTF8_ENC.encode(JSON.stringify({
|
|
5756
|
+
v: 1,
|
|
5757
|
+
arguments: b64(ctx.argumentsIpc),
|
|
5758
|
+
input_schema: ctx.inputSchemaIpc ? b64(ctx.inputSchemaIpc) : null,
|
|
5759
|
+
argument_names: ctx.argumentNames
|
|
5760
|
+
}));
|
|
5761
|
+
}
|
|
5762
|
+
function decodeAggregateContext(bytes) {
|
|
5763
|
+
let d;
|
|
5331
5764
|
try {
|
|
5332
|
-
|
|
5333
|
-
|
|
5334
|
-
|
|
5335
|
-
if (e?.code === "ENOENT")
|
|
5336
|
-
return;
|
|
5337
|
-
throw e;
|
|
5765
|
+
d = JSON.parse(UTF8_DEC.decode(bytes));
|
|
5766
|
+
} catch {
|
|
5767
|
+
throw new StoragePayloadError("aggregate: unrecognized bind context payload");
|
|
5338
5768
|
}
|
|
5339
|
-
|
|
5340
|
-
|
|
5341
|
-
const key = execKey(executionId);
|
|
5342
|
-
let entry = stateStore.get(key);
|
|
5343
|
-
if (!entry) {
|
|
5344
|
-
const ctx = tryReadJson(path.join(execDir(key), "context.json"));
|
|
5345
|
-
if (!ctx)
|
|
5346
|
-
return;
|
|
5347
|
-
entry = {
|
|
5348
|
-
states: new Map,
|
|
5349
|
-
bindArgs: ctx.bindArgs,
|
|
5350
|
-
bindParams: ctx.bindParams,
|
|
5351
|
-
loaded: new Set
|
|
5352
|
-
};
|
|
5353
|
-
stateStore.set(key, entry);
|
|
5354
|
-
}
|
|
5355
|
-
if (requestedGids) {
|
|
5356
|
-
for (const gid of requestedGids) {
|
|
5357
|
-
const stateFile = path.join(execDir(key), gid.toString() + ".json");
|
|
5358
|
-
const s = tryReadJson(stateFile);
|
|
5359
|
-
if (s !== undefined) {
|
|
5360
|
-
entry.states.set(gid, s);
|
|
5361
|
-
} else {
|
|
5362
|
-
entry.states.delete(gid);
|
|
5363
|
-
}
|
|
5364
|
-
entry.loaded.add(gid);
|
|
5365
|
-
}
|
|
5769
|
+
if (!d || d.v !== 1 || typeof d.arguments !== "string") {
|
|
5770
|
+
throw new StoragePayloadError("aggregate: unrecognized bind context payload format");
|
|
5366
5771
|
}
|
|
5367
|
-
return
|
|
5772
|
+
return {
|
|
5773
|
+
argumentsIpc: unb64(d.arguments),
|
|
5774
|
+
inputSchemaIpc: typeof d.input_schema === "string" ? unb64(d.input_schema) : null,
|
|
5775
|
+
argumentNames: Array.isArray(d.argument_names) ? d.argument_names : null
|
|
5776
|
+
};
|
|
5368
5777
|
}
|
|
5369
|
-
function
|
|
5370
|
-
const
|
|
5371
|
-
|
|
5372
|
-
|
|
5373
|
-
|
|
5374
|
-
|
|
5778
|
+
async function loadGroupStates(storage, gids) {
|
|
5779
|
+
const states = new Map;
|
|
5780
|
+
if (gids.length === 0)
|
|
5781
|
+
return states;
|
|
5782
|
+
const values = await storage.stateGetMany(FrameworkNS.AGGREGATE_STATE, gids.map((g) => packIntKey(g)));
|
|
5783
|
+
for (let i = 0;i < gids.length; i++) {
|
|
5784
|
+
const v = values[i];
|
|
5785
|
+
if (v != null)
|
|
5786
|
+
states.set(gids[i], decodeGroupState(v));
|
|
5787
|
+
}
|
|
5788
|
+
return states;
|
|
5375
5789
|
}
|
|
5376
|
-
function
|
|
5377
|
-
const
|
|
5378
|
-
const entry = stateStore.get(key);
|
|
5379
|
-
if (!entry)
|
|
5380
|
-
return;
|
|
5790
|
+
async function storeGroupStates(storage, states, gids) {
|
|
5791
|
+
const items = [];
|
|
5381
5792
|
for (const gid of gids) {
|
|
5382
|
-
|
|
5383
|
-
|
|
5384
|
-
atomicWriteJson(stateFile, entry.states.get(gid));
|
|
5385
|
-
} else {
|
|
5386
|
-
try {
|
|
5387
|
-
fs.unlinkSync(stateFile);
|
|
5388
|
-
} catch {}
|
|
5389
|
-
}
|
|
5390
|
-
entry.loaded.add(gid);
|
|
5793
|
+
if (states.has(gid))
|
|
5794
|
+
items.push([packIntKey(gid), encodeGroupState(states.get(gid))]);
|
|
5391
5795
|
}
|
|
5796
|
+
if (items.length > 0)
|
|
5797
|
+
await storage.statePutMany(FrameworkNS.AGGREGATE_STATE, items);
|
|
5392
5798
|
}
|
|
5393
5799
|
function defineAggregate(config) {
|
|
5394
5800
|
assertArrowTypes(config.args, `defineAggregate("${config.name}"): args`);
|
|
@@ -6668,7 +7074,7 @@ function defineTableInOutFunction(config) {
|
|
|
6668
7074
|
runtimeAlgorithms: meta.runtimeFilterAlgorithms,
|
|
6669
7075
|
evaluationContexts: meta.filterEvaluationContexts
|
|
6670
7076
|
}) : undefined, carriedFilterHistory);
|
|
6671
|
-
const boundStorage = new BoundStorage(storage, response.execution_id ?? new Uint8Array(16), request.substream_id ?? null);
|
|
7077
|
+
const boundStorage = new BoundStorage(storage, response.execution_id ?? new Uint8Array(16), request.substream_id ?? null, shardKeyOf(request.bind_call));
|
|
6672
7078
|
const processParams = {
|
|
6673
7079
|
args,
|
|
6674
7080
|
initCall: request,
|
|
@@ -6965,7 +7371,7 @@ function defineRowTransformFunction(config) {
|
|
|
6965
7371
|
runtimeAlgorithms: meta.runtimeFilterAlgorithms,
|
|
6966
7372
|
evaluationContexts: meta.filterEvaluationContexts
|
|
6967
7373
|
}) : undefined, carriedFilterHistory);
|
|
6968
|
-
const boundStorage = new BoundStorage(storage, response.execution_id ?? new Uint8Array(16), request.substream_id ?? null);
|
|
7374
|
+
const boundStorage = new BoundStorage(storage, response.execution_id ?? new Uint8Array(16), request.substream_id ?? null, shardKeyOf(request.bind_call));
|
|
6969
7375
|
const processParams = {
|
|
6970
7376
|
args,
|
|
6971
7377
|
initCall: request,
|
|
@@ -7022,6 +7428,7 @@ init_arrow();
|
|
|
7022
7428
|
init_arrow();
|
|
7023
7429
|
init_registry();
|
|
7024
7430
|
init_storage();
|
|
7431
|
+
init_storage_seal();
|
|
7025
7432
|
function defineTableBufferingFunction(config) {
|
|
7026
7433
|
assertArrowTypes(config.args, `defineTableBufferingFunction("${config.name}"): args`);
|
|
7027
7434
|
if (config.sinkOrderDependent && config.requiresInputBatchIndex) {
|
|
@@ -7138,10 +7545,6 @@ function defineTableBufferingFunction(config) {
|
|
|
7138
7545
|
execution_id: executionId,
|
|
7139
7546
|
opaque_data: null
|
|
7140
7547
|
};
|
|
7141
|
-
if (request.phase === "TABLE_BUFFERING" /* TABLE_BUFFERING */) {
|
|
7142
|
-
const bound = new BoundStorage(storage, executionId);
|
|
7143
|
-
await bound.statePut(FrameworkNS.BUFFERING_INIT, BoundStorage.packIntKey(-1), encodeBufferingInit(request, response));
|
|
7144
|
-
}
|
|
7145
7548
|
return response;
|
|
7146
7549
|
},
|
|
7147
7550
|
createStreamHandlers(request, response) {
|
|
@@ -7157,7 +7560,7 @@ function defineTableBufferingFunction(config) {
|
|
|
7157
7560
|
runtimeAlgorithms: meta.runtimeFilterAlgorithms,
|
|
7158
7561
|
evaluationContexts: meta.filterEvaluationContexts
|
|
7159
7562
|
}) : undefined;
|
|
7160
|
-
const bound = new BoundStorage(storage, response.execution_id ?? new Uint8Array(16));
|
|
7563
|
+
const bound = new BoundStorage(storage, response.execution_id ?? new Uint8Array(16), null, shardKeyOf(request.bind_call));
|
|
7161
7564
|
const params = {
|
|
7162
7565
|
args,
|
|
7163
7566
|
initCall: request,
|
|
@@ -7263,6 +7666,33 @@ function makeProjectingCollector2(inner, targetSchema) {
|
|
|
7263
7666
|
}
|
|
7264
7667
|
});
|
|
7265
7668
|
}
|
|
7669
|
+
var BUFFERING_INIT_KEY = BoundStorage.packIntKey(-1);
|
|
7670
|
+
var bufferingInitCache = new ExecutionCache(64);
|
|
7671
|
+
async function persistBufferingInit(request, response, signingKey) {
|
|
7672
|
+
const shardKey = shardKeyOf(request.bind_call);
|
|
7673
|
+
const stored = {
|
|
7674
|
+
...request,
|
|
7675
|
+
bind_call: { ...request.bind_call, attach_opaque_data: null, transaction_opaque_data: null }
|
|
7676
|
+
};
|
|
7677
|
+
const bound = new BoundStorage(storage, response.execution_id, null, shardKey);
|
|
7678
|
+
await bound.sealedPut(FrameworkNS.BUFFERING_INIT, BUFFERING_INIT_KEY, encodeBufferingInit(stored, response), signingKey);
|
|
7679
|
+
bufferingInitCache.set(shardKey, response.execution_id, { request: stored, response });
|
|
7680
|
+
}
|
|
7681
|
+
async function loadBufferingInit(bound, signingKey) {
|
|
7682
|
+
const cached = bufferingInitCache.get(bound.shardKey, bound.executionId);
|
|
7683
|
+
if (cached)
|
|
7684
|
+
return cached;
|
|
7685
|
+
const payload = await bound.sealedGet(FrameworkNS.BUFFERING_INIT, BUFFERING_INIT_KEY, signingKey);
|
|
7686
|
+
if (payload == null) {
|
|
7687
|
+
throw new Error(`table_buffering: unknown execution_id ${hexOf(bound.executionId)} ` + `(init never ran or destructor already fired)`);
|
|
7688
|
+
}
|
|
7689
|
+
const decoded = decodeBufferingInit(payload);
|
|
7690
|
+
bufferingInitCache.set(bound.shardKey, bound.executionId, decoded);
|
|
7691
|
+
return decoded;
|
|
7692
|
+
}
|
|
7693
|
+
function hexOf(buf) {
|
|
7694
|
+
return Array.from(buf, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
7695
|
+
}
|
|
7266
7696
|
function encodeBufferingInit(request, response) {
|
|
7267
7697
|
const initBatch = serializeInitRequest(request);
|
|
7268
7698
|
const initBytes = serializeBatch(initBatch);
|
|
@@ -7315,11 +7745,20 @@ function splitLenPrefixed(buf, count) {
|
|
|
7315
7745
|
const parts = [];
|
|
7316
7746
|
let off = 0;
|
|
7317
7747
|
for (let i = 0;i < count; i++) {
|
|
7748
|
+
if (off + 4 > buf.length) {
|
|
7749
|
+
throw new StoragePayloadError(`table_buffering: truncated init payload (part ${i} header)`);
|
|
7750
|
+
}
|
|
7318
7751
|
const len = dv.getUint32(off, true);
|
|
7319
7752
|
off += 4;
|
|
7753
|
+
if (len > buf.length - off) {
|
|
7754
|
+
throw new StoragePayloadError(`table_buffering: truncated init payload (part ${i} is ${len} bytes, ${buf.length - off} left)`);
|
|
7755
|
+
}
|
|
7320
7756
|
parts.push(buf.subarray(off, off + len));
|
|
7321
7757
|
off += len;
|
|
7322
7758
|
}
|
|
7759
|
+
if (off !== buf.length) {
|
|
7760
|
+
throw new StoragePayloadError(`table_buffering: ${buf.length - off} trailing bytes in init payload`);
|
|
7761
|
+
}
|
|
7323
7762
|
return parts;
|
|
7324
7763
|
}
|
|
7325
7764
|
// src/functions/copy-from.ts
|
|
@@ -7417,7 +7856,7 @@ function defineCopyFromFunction(config) {
|
|
|
7417
7856
|
const settings = batchToScalarDict(request.bind_call.settings);
|
|
7418
7857
|
const secrets = batchToSecretDict(request.bind_call.secrets);
|
|
7419
7858
|
const outputSchema = request.output_schema;
|
|
7420
|
-
const boundStorage = new BoundStorage(storage, response.execution_id);
|
|
7859
|
+
const boundStorage = new BoundStorage(storage, response.execution_id, null, shardKeyOf(request.bind_call));
|
|
7421
7860
|
const processParams = {
|
|
7422
7861
|
args,
|
|
7423
7862
|
initCall: request,
|
|
@@ -8306,9 +8745,9 @@ var _UTF8 = new TextEncoder;
|
|
|
8306
8745
|
var ATTACH_ENVELOPE_VERSION = 2;
|
|
8307
8746
|
var TRANSACTION_ENVELOPE_VERSION = 2;
|
|
8308
8747
|
var ATTACH_UUID_LEN = 16;
|
|
8309
|
-
var
|
|
8310
|
-
var
|
|
8311
|
-
var MIN_ENVELOPE_LEN = 1 +
|
|
8748
|
+
var NONCE_LEN2 = 24;
|
|
8749
|
+
var TAG_LEN2 = 16;
|
|
8750
|
+
var MIN_ENVELOPE_LEN = 1 + NONCE_LEN2 + TAG_LEN2;
|
|
8312
8751
|
var ATTACH_AAD_PREFIX = _UTF8.encode("vgi.attach_opaque_data.v1\x00");
|
|
8313
8752
|
var TRANSACTION_AAD_PREFIX = _UTF8.encode("vgi.transaction_opaque_data.v1\x00");
|
|
8314
8753
|
|
|
@@ -8320,7 +8759,7 @@ class OpaqueDataRejectedError extends Error {
|
|
|
8320
8759
|
this.name = "OpaqueDataRejectedError";
|
|
8321
8760
|
}
|
|
8322
8761
|
}
|
|
8323
|
-
function
|
|
8762
|
+
function concat2(...parts) {
|
|
8324
8763
|
let total = 0;
|
|
8325
8764
|
for (const p of parts)
|
|
8326
8765
|
total += p.length;
|
|
@@ -8342,32 +8781,32 @@ function identityTail(auth) {
|
|
|
8342
8781
|
return _UTF8.encode("\x00anonymous");
|
|
8343
8782
|
const domain = _UTF8.encode(auth.domain ?? "");
|
|
8344
8783
|
const principal = _UTF8.encode(auth.principal ?? "");
|
|
8345
|
-
return
|
|
8784
|
+
return concat2(Uint8Array.of(1), domain, Uint8Array.of(0), principal);
|
|
8346
8785
|
}
|
|
8347
8786
|
function attachAad(auth) {
|
|
8348
|
-
return
|
|
8787
|
+
return concat2(ATTACH_AAD_PREFIX, identityTail(auth));
|
|
8349
8788
|
}
|
|
8350
8789
|
function transactionAad(auth, attachEnvelope) {
|
|
8351
|
-
return
|
|
8790
|
+
return concat2(TRANSACTION_AAD_PREFIX, identityTail(auth), Uint8Array.of(0), attachEnvelope);
|
|
8352
8791
|
}
|
|
8353
8792
|
async function sealBytes(payload, key, aad, version, fixedNonce) {
|
|
8354
|
-
if (fixedNonce !== undefined && fixedNonce.length !==
|
|
8355
|
-
throw new Error(`nonce must be ${
|
|
8793
|
+
if (fixedNonce !== undefined && fixedNonce.length !== NONCE_LEN2) {
|
|
8794
|
+
throw new Error(`nonce must be ${NONCE_LEN2} bytes`);
|
|
8356
8795
|
}
|
|
8357
|
-
const nonce = fixedNonce ?? crypto.getRandomValues(new Uint8Array(
|
|
8796
|
+
const nonce = fixedNonce ?? crypto.getRandomValues(new Uint8Array(NONCE_LEN2));
|
|
8358
8797
|
const ciphertext = xchacha20poly1305(await normalizeKey(key), nonce, aad).encrypt(payload);
|
|
8359
|
-
const out = new Uint8Array(1 +
|
|
8798
|
+
const out = new Uint8Array(1 + NONCE_LEN2 + ciphertext.length);
|
|
8360
8799
|
out[0] = version & 255;
|
|
8361
8800
|
out.set(nonce, 1);
|
|
8362
|
-
out.set(ciphertext, 1 +
|
|
8801
|
+
out.set(ciphertext, 1 + NONCE_LEN2);
|
|
8363
8802
|
return out;
|
|
8364
8803
|
}
|
|
8365
8804
|
async function openBytes(token, key, aad, version, field = "opaque data") {
|
|
8366
8805
|
if (token.length < MIN_ENVELOPE_LEN || token[0] !== (version & 255)) {
|
|
8367
8806
|
throw new OpaqueDataRejectedError(field);
|
|
8368
8807
|
}
|
|
8369
|
-
const nonce = token.subarray(1, 1 +
|
|
8370
|
-
const ciphertext = token.subarray(1 +
|
|
8808
|
+
const nonce = token.subarray(1, 1 + NONCE_LEN2);
|
|
8809
|
+
const ciphertext = token.subarray(1 + NONCE_LEN2);
|
|
8371
8810
|
try {
|
|
8372
8811
|
return xchacha20poly1305(await normalizeKey(key), nonce, aad).decrypt(ciphertext);
|
|
8373
8812
|
} catch {
|
|
@@ -8375,158 +8814,16 @@ async function openBytes(token, key, aad, version, field = "opaque data") {
|
|
|
8375
8814
|
}
|
|
8376
8815
|
}
|
|
8377
8816
|
|
|
8378
|
-
// src/attach-secret-keyfile.ts
|
|
8379
|
-
function builtins() {
|
|
8380
|
-
const proc = globalThis.process;
|
|
8381
|
-
const get = proc?.getBuiltinModule?.bind(proc);
|
|
8382
|
-
const fs = get?.("node:fs");
|
|
8383
|
-
const os = get?.("node:os");
|
|
8384
|
-
const path = get?.("node:path");
|
|
8385
|
-
if (!fs || !os || !path)
|
|
8386
|
-
throw new Error("this runtime has no filesystem for the host-local attach secret key file.");
|
|
8387
|
-
return { fs, os, path };
|
|
8388
|
-
}
|
|
8389
|
-
var ATTACH_SECRET_KEY_FILE_ENV = "VGI_ATTACH_SECRET_KEY_FILE";
|
|
8390
|
-
var KEY_LEN = 32;
|
|
8391
|
-
var FILE_NAME = "attach-secret-options.key";
|
|
8392
|
-
var REMEDY = "Set VGI_SIGNING_KEY (or configure attachSecretKey), or point VGI_ATTACH_SECRET_KEY_FILE at a valid key file.";
|
|
8393
|
-
function username() {
|
|
8394
|
-
try {
|
|
8395
|
-
const name = builtins().os.userInfo().username;
|
|
8396
|
-
if (name)
|
|
8397
|
-
return name;
|
|
8398
|
-
} catch {}
|
|
8399
|
-
return process.env.USER || process.env.USERNAME || String(process.getuid?.() ?? "user");
|
|
8400
|
-
}
|
|
8401
|
-
function isDirectory(path) {
|
|
8402
|
-
try {
|
|
8403
|
-
return builtins().fs.statSync(path).isDirectory();
|
|
8404
|
-
} catch {
|
|
8405
|
-
return false;
|
|
8406
|
-
}
|
|
8407
|
-
}
|
|
8408
|
-
function hostLocalAttachSecretKeyPath(env = globalThis.process?.env ?? {}) {
|
|
8409
|
-
const { os, path: { join } } = builtins();
|
|
8410
|
-
const explicit = env[ATTACH_SECRET_KEY_FILE_ENV];
|
|
8411
|
-
if (explicit)
|
|
8412
|
-
return explicit;
|
|
8413
|
-
const xdg = env.XDG_RUNTIME_DIR;
|
|
8414
|
-
if (xdg && isDirectory(xdg))
|
|
8415
|
-
return join(xdg, "vgi", FILE_NAME);
|
|
8416
|
-
return join(os.tmpdir(), `vgi-${username()}`, FILE_NAME);
|
|
8417
|
-
}
|
|
8418
|
-
var POSIX = typeof process === "undefined" || process.platform !== "win32";
|
|
8419
|
-
function checkOwnedPrivate(path, mode, uid, what) {
|
|
8420
|
-
if (!POSIX)
|
|
8421
|
-
return;
|
|
8422
|
-
const me = process.getuid?.();
|
|
8423
|
-
if (me !== undefined && uid !== me) {
|
|
8424
|
-
throw new Error(`attach secret key ${what} ${path} is not owned by the current user. ${REMEDY}`);
|
|
8425
|
-
}
|
|
8426
|
-
if ((mode & 63) !== 0) {
|
|
8427
|
-
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}`);
|
|
8428
|
-
}
|
|
8429
|
-
}
|
|
8430
|
-
function ensureDir(dir) {
|
|
8431
|
-
const { mkdirSync, lstatSync } = builtins().fs;
|
|
8432
|
-
try {
|
|
8433
|
-
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
8434
|
-
} catch (e) {
|
|
8435
|
-
if (e.code !== "EEXIST")
|
|
8436
|
-
throw e;
|
|
8437
|
-
}
|
|
8438
|
-
const st = lstatSync(dir);
|
|
8439
|
-
if (!st.isDirectory())
|
|
8440
|
-
throw new Error(`attach secret key directory ${dir} is not a directory. ${REMEDY}`);
|
|
8441
|
-
checkOwnedPrivate(dir, st.mode, st.uid, "directory");
|
|
8442
|
-
}
|
|
8443
|
-
function readKey(path) {
|
|
8444
|
-
const { openSync, fstatSync, readSync, closeSync, constants } = builtins().fs;
|
|
8445
|
-
let fd;
|
|
8446
|
-
try {
|
|
8447
|
-
fd = openSync(path, constants.O_RDONLY | (POSIX ? constants.O_NOFOLLOW : 0));
|
|
8448
|
-
} catch (e) {
|
|
8449
|
-
if (e.code === "ENOENT")
|
|
8450
|
-
return null;
|
|
8451
|
-
throw new Error(`attach secret key file ${path} cannot be opened (${e.code}). ${REMEDY}`);
|
|
8452
|
-
}
|
|
8453
|
-
try {
|
|
8454
|
-
const st = fstatSync(fd);
|
|
8455
|
-
if (!st.isFile())
|
|
8456
|
-
throw new Error(`attach secret key file ${path} is not a regular file. ${REMEDY}`);
|
|
8457
|
-
checkOwnedPrivate(path, st.mode, st.uid, "file");
|
|
8458
|
-
const buf = new Uint8Array(KEY_LEN + 1);
|
|
8459
|
-
let n = 0;
|
|
8460
|
-
for (;; ) {
|
|
8461
|
-
const got = readSync(fd, buf, n, buf.length - n, null);
|
|
8462
|
-
if (got <= 0)
|
|
8463
|
-
break;
|
|
8464
|
-
n += got;
|
|
8465
|
-
if (n === buf.length)
|
|
8466
|
-
break;
|
|
8467
|
-
}
|
|
8468
|
-
if (n !== KEY_LEN || st.size !== KEY_LEN) {
|
|
8469
|
-
throw new Error(`attach secret key file ${path} must contain exactly ${KEY_LEN} raw bytes (found ${st.size}). ${REMEDY}`);
|
|
8470
|
-
}
|
|
8471
|
-
return buf.subarray(0, KEY_LEN);
|
|
8472
|
-
} finally {
|
|
8473
|
-
closeSync(fd);
|
|
8474
|
-
}
|
|
8475
|
-
}
|
|
8476
|
-
function createKey(path) {
|
|
8477
|
-
const { openSync, writeSync, fsyncSync, closeSync, linkSync, unlinkSync, constants } = builtins().fs;
|
|
8478
|
-
const { dirname, join } = builtins().path;
|
|
8479
|
-
const tmp = join(dirname(path), `.${FILE_NAME}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);
|
|
8480
|
-
const fd = openSync(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 384);
|
|
8481
|
-
try {
|
|
8482
|
-
const key = crypto.getRandomValues(new Uint8Array(KEY_LEN));
|
|
8483
|
-
let off = 0;
|
|
8484
|
-
while (off < KEY_LEN)
|
|
8485
|
-
off += writeSync(fd, key, off, KEY_LEN - off);
|
|
8486
|
-
fsyncSync(fd);
|
|
8487
|
-
} finally {
|
|
8488
|
-
closeSync(fd);
|
|
8489
|
-
}
|
|
8490
|
-
try {
|
|
8491
|
-
linkSync(tmp, path);
|
|
8492
|
-
} catch (e) {
|
|
8493
|
-
if (e.code !== "EEXIST") {
|
|
8494
|
-
unlinkSync(tmp);
|
|
8495
|
-
throw e;
|
|
8496
|
-
}
|
|
8497
|
-
}
|
|
8498
|
-
unlinkSync(tmp);
|
|
8499
|
-
}
|
|
8500
|
-
function loadHostLocalAttachSecretKey(path = hostLocalAttachSecretKeyPath()) {
|
|
8501
|
-
ensureDir(builtins().path.dirname(path));
|
|
8502
|
-
const existing = readKey(path);
|
|
8503
|
-
if (existing)
|
|
8504
|
-
return existing;
|
|
8505
|
-
createKey(path);
|
|
8506
|
-
const created = readKey(path);
|
|
8507
|
-
if (!created)
|
|
8508
|
-
throw new Error(`attach secret key file ${path} vanished after creation. ${REMEDY}`);
|
|
8509
|
-
return created;
|
|
8510
|
-
}
|
|
8511
|
-
var cached;
|
|
8512
|
-
async function hostLocalAttachSecretKey() {
|
|
8513
|
-
const path = hostLocalAttachSecretKeyPath();
|
|
8514
|
-
if (cached?.path === path)
|
|
8515
|
-
return cached.key;
|
|
8516
|
-
const key = loadHostLocalAttachSecretKey(path);
|
|
8517
|
-
cached = { path, key };
|
|
8518
|
-
return key;
|
|
8519
|
-
}
|
|
8520
|
-
|
|
8521
8817
|
// src/attach-secret-options.ts
|
|
8522
|
-
|
|
8818
|
+
init_attach_secret_keyfile();
|
|
8819
|
+
var UTF83 = new TextEncoder;
|
|
8523
8820
|
var ATTACH_SECRET_OPTIONS_INFO = "vgi.attach_secret_options.v1";
|
|
8524
8821
|
var ATTACH_SECRET_OPTIONS_VERSION = 1;
|
|
8525
8822
|
var TRAILER_MAGIC = Uint8Array.of(0, 86, 71, 73, 65, 79, 1, 255);
|
|
8526
8823
|
var TRAILER_FIXED = 4 + TRAILER_MAGIC.length;
|
|
8527
|
-
var
|
|
8528
|
-
var
|
|
8529
|
-
var AAD_PREFIX =
|
|
8824
|
+
var NONCE_LEN3 = 24;
|
|
8825
|
+
var TAG_LEN3 = 16;
|
|
8826
|
+
var AAD_PREFIX = UTF83.encode(`${ATTACH_SECRET_OPTIONS_INFO}\x00`);
|
|
8530
8827
|
var UUID_LEN = 16;
|
|
8531
8828
|
var FIELD = "attach_opaque_data";
|
|
8532
8829
|
|
|
@@ -8544,19 +8841,19 @@ class AttachOptionsUnavailableError extends Error {
|
|
|
8544
8841
|
}
|
|
8545
8842
|
}
|
|
8546
8843
|
var subkeys = new Map;
|
|
8547
|
-
function
|
|
8844
|
+
function hexOf2(b) {
|
|
8548
8845
|
let s = "";
|
|
8549
8846
|
for (let i = 0;i < b.length; i++)
|
|
8550
8847
|
s += b[i].toString(16).padStart(2, "0");
|
|
8551
8848
|
return s;
|
|
8552
8849
|
}
|
|
8553
8850
|
function deriveAttachSecretKey(root) {
|
|
8554
|
-
const id =
|
|
8851
|
+
const id = hexOf2(root);
|
|
8555
8852
|
let derived = subkeys.get(id);
|
|
8556
8853
|
if (!derived) {
|
|
8557
8854
|
derived = (async () => {
|
|
8558
8855
|
const ikm = await crypto.subtle.importKey("raw", root, "HKDF", false, ["deriveBits"]);
|
|
8559
|
-
const bits = await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info:
|
|
8856
|
+
const bits = await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: UTF83.encode(ATTACH_SECRET_OPTIONS_INFO) }, ikm, 256);
|
|
8560
8857
|
return new Uint8Array(bits);
|
|
8561
8858
|
})();
|
|
8562
8859
|
subkeys.set(id, derived);
|
|
@@ -8591,7 +8888,7 @@ function u32le(n) {
|
|
|
8591
8888
|
function readU32le(b, off) {
|
|
8592
8889
|
return new DataView(b.buffer, b.byteOffset, b.byteLength).getUint32(off, true);
|
|
8593
8890
|
}
|
|
8594
|
-
function
|
|
8891
|
+
function concat3(...parts) {
|
|
8595
8892
|
let total = 0;
|
|
8596
8893
|
for (const p of parts)
|
|
8597
8894
|
total += p.length;
|
|
@@ -8645,12 +8942,12 @@ async function packAttachOptionsTrailer(uuid, optionsIpc, secretNames, keys, fix
|
|
|
8645
8942
|
throw new AttachSecretKeyUnavailableError(`${noKeyMessage()} ${e.message}`);
|
|
8646
8943
|
}
|
|
8647
8944
|
const key = await deriveAttachSecretKey(root);
|
|
8648
|
-
const nonce = fixedNonce ?? crypto.getRandomValues(new Uint8Array(
|
|
8945
|
+
const nonce = fixedNonce ?? crypto.getRandomValues(new Uint8Array(NONCE_LEN3));
|
|
8649
8946
|
const ct = xchacha20poly1305(key, nonce, aadFor(uuid)).encrypt(split.secret);
|
|
8650
|
-
secret =
|
|
8947
|
+
secret = concat3(Uint8Array.of(ATTACH_SECRET_OPTIONS_VERSION), nonce, ct);
|
|
8651
8948
|
}
|
|
8652
|
-
const body =
|
|
8653
|
-
return
|
|
8949
|
+
const body = concat3(u32le(plain.length), plain, secret);
|
|
8950
|
+
return concat3(body, u32le(body.length), TRAILER_MAGIC);
|
|
8654
8951
|
}
|
|
8655
8952
|
function endsWithMagic(b) {
|
|
8656
8953
|
if (b.length < TRAILER_MAGIC.length)
|
|
@@ -8694,14 +8991,14 @@ async function openFrameworkAttach(full, keys) {
|
|
|
8694
8991
|
throw new OpaqueDataRejectedError(FIELD);
|
|
8695
8992
|
}
|
|
8696
8993
|
if (secret.length) {
|
|
8697
|
-
if (secret.length < 1 +
|
|
8994
|
+
if (secret.length < 1 + NONCE_LEN3 + TAG_LEN3 || secret[0] !== ATTACH_SECRET_OPTIONS_VERSION) {
|
|
8698
8995
|
throw new OpaqueDataRejectedError(FIELD);
|
|
8699
8996
|
}
|
|
8700
8997
|
let opened;
|
|
8701
8998
|
try {
|
|
8702
8999
|
const key = await deriveAttachSecretKey(await rootKey(keys));
|
|
8703
|
-
const nonce = secret.subarray(1, 1 +
|
|
8704
|
-
opened = xchacha20poly1305(key, nonce, aadFor(copy.subarray(0, UUID_LEN))).decrypt(secret.subarray(1 +
|
|
9000
|
+
const nonce = secret.subarray(1, 1 + NONCE_LEN3);
|
|
9001
|
+
opened = xchacha20poly1305(key, nonce, aadFor(copy.subarray(0, UUID_LEN))).decrypt(secret.subarray(1 + NONCE_LEN3));
|
|
8705
9002
|
} catch {
|
|
8706
9003
|
throw new OpaqueDataRejectedError(FIELD);
|
|
8707
9004
|
}
|
|
@@ -16192,6 +16489,36 @@ async function openAttach(envelope, auth, signingKey, attachSecretKey) {
|
|
|
16192
16489
|
const full = await openAttachFull(envelope, auth, signingKey);
|
|
16193
16490
|
return openFrameworkAttach(full, { explicit: attachSecretKey, signingKey });
|
|
16194
16491
|
}
|
|
16492
|
+
async function openAttachWithShard(envelope, auth, signingKey, attachSecretKey) {
|
|
16493
|
+
if (envelope == null)
|
|
16494
|
+
return { attach: null, shardKey: "" };
|
|
16495
|
+
if (envelope.length === 0)
|
|
16496
|
+
return { attach: envelope, shardKey: "" };
|
|
16497
|
+
const full = await openAttachFull(envelope, auth, signingKey);
|
|
16498
|
+
const shardKey = full.length >= ATTACH_UUID_LEN ? deriveShardKey(full.subarray(0, ATTACH_UUID_LEN)) : "";
|
|
16499
|
+
const attach = await openFrameworkAttach(full, { explicit: attachSecretKey, signingKey });
|
|
16500
|
+
return { attach, shardKey };
|
|
16501
|
+
}
|
|
16502
|
+
function toHex(b) {
|
|
16503
|
+
let s = "";
|
|
16504
|
+
for (let i = 0;i < b.length; i++)
|
|
16505
|
+
s += b[i].toString(16).padStart(2, "0");
|
|
16506
|
+
return s;
|
|
16507
|
+
}
|
|
16508
|
+
function deriveShardKey(attachUuid) {
|
|
16509
|
+
if (attachUuid.length !== ATTACH_UUID_LEN) {
|
|
16510
|
+
throw new Error(`shard_key requires a ${ATTACH_UUID_LEN}-byte attach uuid, got ${attachUuid.length}`);
|
|
16511
|
+
}
|
|
16512
|
+
return "att-" + toHex(attachUuid);
|
|
16513
|
+
}
|
|
16514
|
+
async function shardKeyForAttach(sealed, auth, signingKey) {
|
|
16515
|
+
if (!sealed || sealed.length === 0)
|
|
16516
|
+
return "";
|
|
16517
|
+
const full = await openAttachFull(sealed, auth, signingKey);
|
|
16518
|
+
if (full.length < ATTACH_UUID_LEN)
|
|
16519
|
+
return "";
|
|
16520
|
+
return deriveShardKey(full.subarray(0, ATTACH_UUID_LEN));
|
|
16521
|
+
}
|
|
16195
16522
|
async function sealTransaction(plaintext, attachEnvelope, auth, signingKey) {
|
|
16196
16523
|
if (!signingKey)
|
|
16197
16524
|
return plaintext;
|
|
@@ -16379,7 +16706,7 @@ class SplitTokenError extends Error {
|
|
|
16379
16706
|
this.kind = kind;
|
|
16380
16707
|
}
|
|
16381
16708
|
}
|
|
16382
|
-
function
|
|
16709
|
+
function concat4(...parts) {
|
|
16383
16710
|
const total = parts.reduce((n, p) => n + p.length, 0);
|
|
16384
16711
|
const out = new Uint8Array(total);
|
|
16385
16712
|
let at = 0;
|
|
@@ -16400,13 +16727,13 @@ function equalBytes2(a, b) {
|
|
|
16400
16727
|
async function bindFingerprint(schemaPath, functionName, args, settings, projection) {
|
|
16401
16728
|
const enc = new TextEncoder;
|
|
16402
16729
|
const zero = Uint8Array.of(0);
|
|
16403
|
-
const field = (label, value) =>
|
|
16404
|
-
const message =
|
|
16730
|
+
const field = (label, value) => concat4(enc.encode(label), zero, value, zero);
|
|
16731
|
+
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));
|
|
16405
16732
|
const digest = await crypto.subtle.digest("SHA-256", message);
|
|
16406
16733
|
return new Uint8Array(digest).slice(0, FINGERPRINT_LEN);
|
|
16407
16734
|
}
|
|
16408
16735
|
function splitTokenAad(header, auth) {
|
|
16409
|
-
return
|
|
16736
|
+
return concat4(header, identityTail(auth));
|
|
16410
16737
|
}
|
|
16411
16738
|
function splitAnchor(catalogVersion) {
|
|
16412
16739
|
const out = new Uint8Array(8);
|
|
@@ -16425,11 +16752,11 @@ async function buildSplitToken(opts) {
|
|
|
16425
16752
|
head[0] = SPLIT_TOKEN_FORMAT_VERSION;
|
|
16426
16753
|
head[1] = signingKey ? FLAG_PAYLOAD_SEALED : 0;
|
|
16427
16754
|
new DataView(head.buffer).setUint16(2, anchor.length, true);
|
|
16428
|
-
const body =
|
|
16755
|
+
const body = concat4(head, fingerprint, anchor);
|
|
16429
16756
|
if (!signingKey)
|
|
16430
|
-
return
|
|
16757
|
+
return concat4(body, payload);
|
|
16431
16758
|
const sealed = await sealBytes(payload, signingKey, splitTokenAad(body, auth), SEAL_VERSION);
|
|
16432
|
-
return
|
|
16759
|
+
return concat4(body, sealed);
|
|
16433
16760
|
}
|
|
16434
16761
|
async function openSplitToken(token, opts = {}) {
|
|
16435
16762
|
const { signingKey, auth, expectedFingerprint, currentAnchor } = opts;
|
|
@@ -16516,20 +16843,15 @@ async function resolveSplitPayloads(request, innerParams, opts) {
|
|
|
16516
16843
|
}
|
|
16517
16844
|
function functionHandlers(config) {
|
|
16518
16845
|
const { registry, signingKey, catalogInterface, attachSecretKey } = config;
|
|
16519
|
-
|
|
16520
|
-
if (attach == null)
|
|
16521
|
-
return null;
|
|
16522
|
-
const env = toUint8Array(attach);
|
|
16523
|
-
if (env.length === 0)
|
|
16524
|
-
return env;
|
|
16525
|
-
return openAttach(env, ctx?.auth ?? currentRequestAuth(), signingKey, attachSecretKey);
|
|
16526
|
-
}
|
|
16846
|
+
const storageSealKey = config.storageSealKey ?? signingKey;
|
|
16527
16847
|
async function openOpaque(bindCall, ctx) {
|
|
16528
16848
|
const sealedAttach = bindCall.attach_opaque_data != null ? toUint8Array(bindCall.attach_opaque_data) : new Uint8Array(0);
|
|
16529
16849
|
if (bindCall.transaction_opaque_data != null) {
|
|
16530
16850
|
bindCall.transaction_opaque_data = await openTransaction(toUint8Array(bindCall.transaction_opaque_data), sealedAttach, ctx?.auth ?? currentRequestAuth(), signingKey);
|
|
16531
16851
|
}
|
|
16532
|
-
bindCall.attach_opaque_data
|
|
16852
|
+
const opened = await openAttachWithShard(bindCall.attach_opaque_data != null ? toUint8Array(bindCall.attach_opaque_data) : null, ctx?.auth ?? currentRequestAuth(), signingKey, attachSecretKey);
|
|
16853
|
+
bindCall.attach_opaque_data = opened.attach;
|
|
16854
|
+
bindCall.storage_shard_key = opened.shardKey;
|
|
16533
16855
|
}
|
|
16534
16856
|
async function strippedContext(bindCall, ctx) {
|
|
16535
16857
|
const copy = { ...bindCall };
|
|
@@ -16573,6 +16895,9 @@ function functionHandlers(config) {
|
|
|
16573
16895
|
});
|
|
16574
16896
|
const func = registry.get(request.bind_call.function_name, overloadContext(request.bind_call, catalogInterface));
|
|
16575
16897
|
const initResponse = await func.globalInit(request);
|
|
16898
|
+
if (func.kind === "table_buffering" && request.phase === "TABLE_BUFFERING" /* TABLE_BUFFERING */) {
|
|
16899
|
+
await persistBufferingInit(request, initResponse, storageSealKey);
|
|
16900
|
+
}
|
|
16576
16901
|
const handlers = func.createStreamHandlers(request, initResponse);
|
|
16577
16902
|
let handlerState;
|
|
16578
16903
|
if (handlers.producerInit) {
|
|
@@ -16722,6 +17047,11 @@ function functionHandlers(config) {
|
|
|
16722
17047
|
const globalExecutionId = toUint8Array(innerParams.global_execution_id);
|
|
16723
17048
|
const bindOpaqueData = innerParams.bind_opaque_data ? toUint8Array(innerParams.bind_opaque_data) : null;
|
|
16724
17049
|
const func = registry.get(bindCall.function_name, await strippedContext(bindCall));
|
|
17050
|
+
try {
|
|
17051
|
+
bindCall.storage_shard_key = await shardKeyForAttach(bindCall.attach_opaque_data ?? undefined, currentRequestAuth(), signingKey);
|
|
17052
|
+
} catch {
|
|
17053
|
+
bindCall.storage_shard_key = "";
|
|
17054
|
+
}
|
|
16725
17055
|
const map = func.dynamicToString ? await func.dynamicToString({ bindCall, bindOpaqueData, globalExecutionId }) : {};
|
|
16726
17056
|
const keys = Object.keys(map);
|
|
16727
17057
|
const values = keys.map((k) => map[k] ?? "");
|
|
@@ -16767,7 +17097,8 @@ function functionHandlers(config) {
|
|
|
16767
17097
|
|
|
16768
17098
|
// src/protocol/handlers/aggregate.ts
|
|
16769
17099
|
init_arrow();
|
|
16770
|
-
|
|
17100
|
+
init_storage();
|
|
17101
|
+
function aggregateHandlers(registry, signingKey, attachSecretKey, storageSealKey = signingKey) {
|
|
16771
17102
|
function resolveAggregate(name, schemaPath) {
|
|
16772
17103
|
const func = registry.get(name, {
|
|
16773
17104
|
arguments: new Arguments,
|
|
@@ -16780,36 +17111,62 @@ function aggregateHandlers(registry) {
|
|
|
16780
17111
|
}
|
|
16781
17112
|
return func.aggregateConfig;
|
|
16782
17113
|
}
|
|
16783
|
-
|
|
17114
|
+
async function boundFor(innerParams, ctx, executionId) {
|
|
17115
|
+
const raw = innerParams.attach_opaque_data ? toUint8Array(innerParams.attach_opaque_data) : null;
|
|
17116
|
+
const { shardKey } = await openAttachWithShard(raw, ctx?.auth ?? currentRequestAuth(), signingKey, attachSecretKey);
|
|
17117
|
+
return new BoundStorage(storage, executionId, null, shardKey);
|
|
17118
|
+
}
|
|
17119
|
+
async function loadContext(cfg, storage, rpc) {
|
|
17120
|
+
const cached = aggregateContextCache.get(storage.shardKey, storage.executionId);
|
|
17121
|
+
if (cached)
|
|
17122
|
+
return cached;
|
|
17123
|
+
const payload = await storage.sealedGet(FrameworkNS.AGGREGATE_STATE, AGGREGATE_CONTEXT_KEY, storageSealKey);
|
|
17124
|
+
if (payload == null) {
|
|
17125
|
+
throw new Error(`${rpc}: unknown execution_id for '${cfg.name}' (bind missing or state dropped)`);
|
|
17126
|
+
}
|
|
17127
|
+
const stored = decodeAggregateContext(payload);
|
|
17128
|
+
const args = deserializeArguments(stored.argumentsIpc);
|
|
17129
|
+
const params = {
|
|
17130
|
+
args: extractArgMap(cfg, args),
|
|
17131
|
+
arguments: args,
|
|
17132
|
+
inputSchema: stored.inputSchemaIpc ? deserializeSchema(stored.inputSchemaIpc) : null,
|
|
17133
|
+
settings: {},
|
|
17134
|
+
secrets: {},
|
|
17135
|
+
argumentNames: stored.argumentNames
|
|
17136
|
+
};
|
|
17137
|
+
aggregateContextCache.set(storage.shardKey, storage.executionId, params);
|
|
17138
|
+
return params;
|
|
17139
|
+
}
|
|
17140
|
+
const aggregateBind = async (params, ctx) => {
|
|
16784
17141
|
const innerParams = unwrapRequest(params.request);
|
|
16785
17142
|
const functionName = innerParams.function_name;
|
|
16786
17143
|
const cfg = resolveAggregate(functionName, innerParams.schema_path ?? null);
|
|
16787
17144
|
const argBytes = toUint8Array(innerParams.arguments);
|
|
16788
17145
|
const args = deserializeArguments(argBytes);
|
|
16789
|
-
const
|
|
17146
|
+
const inputSchemaIpc = innerParams.input_schema ? toUint8Array(innerParams.input_schema) : null;
|
|
17147
|
+
const inputSchema = inputSchemaIpc && inputSchemaIpc.length > 0 ? deserializeSchema(inputSchemaIpc) : null;
|
|
16790
17148
|
const secretsBytes = innerParams.secrets ? toUint8Array(innerParams.secrets) : null;
|
|
16791
17149
|
const secretsBatch = secretsBytes && secretsBytes.length > 0 ? deserializeBatch(secretsBytes) : null;
|
|
16792
17150
|
const secrets = secretsBatch ? batchToSecretDict(secretsBatch) : {};
|
|
17151
|
+
const argumentNames = innerParams.argument_names ? (Array.isArray(innerParams.argument_names) ? innerParams.argument_names : [...innerParams.argument_names]).map((value) => value == null ? null : String(value)) : null;
|
|
16793
17152
|
const bindParams = {
|
|
16794
17153
|
args: extractArgMap(cfg, args),
|
|
16795
17154
|
arguments: args,
|
|
16796
17155
|
inputSchema,
|
|
16797
17156
|
settings: {},
|
|
16798
17157
|
secrets,
|
|
16799
|
-
argumentNames
|
|
17158
|
+
argumentNames
|
|
16800
17159
|
};
|
|
16801
|
-
const executionId = new Uint8Array(16);
|
|
16802
|
-
crypto.getRandomValues(executionId);
|
|
16803
|
-
setExecutionState(executionId, {
|
|
16804
|
-
states: new Map,
|
|
16805
|
-
bindArgs: args,
|
|
16806
|
-
bindParams
|
|
16807
|
-
});
|
|
16808
17160
|
const outType = cfg.onBind ? await cfg.onBind(bindParams) : cfg.outputType;
|
|
16809
17161
|
const outSchema = schema2([field2("result", outType, true)]);
|
|
17162
|
+
const executionId = new Uint8Array(16);
|
|
17163
|
+
crypto.getRandomValues(executionId);
|
|
17164
|
+
const storage = await boundFor(innerParams, ctx, executionId);
|
|
17165
|
+
await storage.sealedPut(FrameworkNS.AGGREGATE_STATE, AGGREGATE_CONTEXT_KEY, encodeAggregateContext({ argumentsIpc: argBytes, inputSchemaIpc, argumentNames }), storageSealKey);
|
|
17166
|
+
aggregateContextCache.set(storage.shardKey, executionId, { ...bindParams, secrets: {} });
|
|
16810
17167
|
return wrapResult({ output_schema: serializeSchema(outSchema), execution_id: executionId }, AggregateBindResultSchema);
|
|
16811
17168
|
};
|
|
16812
|
-
const aggregateUpdate = (params) => {
|
|
17169
|
+
const aggregateUpdate = async (params, ctx) => {
|
|
16813
17170
|
const innerParams = unwrapRequest(params.request);
|
|
16814
17171
|
const functionName = innerParams.function_name;
|
|
16815
17172
|
const executionId = toUint8Array(innerParams.execution_id);
|
|
@@ -16830,10 +17187,10 @@ function aggregateHandlers(registry) {
|
|
|
16830
17187
|
groupIds.push(g);
|
|
16831
17188
|
uniqueGids.add(g);
|
|
16832
17189
|
}
|
|
16833
|
-
const
|
|
16834
|
-
|
|
16835
|
-
|
|
16836
|
-
|
|
17190
|
+
const storage = await boundFor(innerParams, ctx, executionId);
|
|
17191
|
+
const bindParams = await loadContext(cfg, storage, "aggregate_update");
|
|
17192
|
+
const gids = [...uniqueGids];
|
|
17193
|
+
const states = await loadGroupStates(storage, gids);
|
|
16837
17194
|
const columns = [];
|
|
16838
17195
|
for (let i = 0;i < batch.schema.fields.length; i++) {
|
|
16839
17196
|
if (i === gidIdx)
|
|
@@ -16841,24 +17198,24 @@ function aggregateHandlers(registry) {
|
|
|
16841
17198
|
columns.push(batch.getChildAt(i));
|
|
16842
17199
|
}
|
|
16843
17200
|
const ensureState = (gid) => {
|
|
16844
|
-
let s =
|
|
17201
|
+
let s = states.get(gid);
|
|
16845
17202
|
if (s === undefined) {
|
|
16846
|
-
s = cfg.initialState(
|
|
16847
|
-
|
|
17203
|
+
s = cfg.initialState(bindParams);
|
|
17204
|
+
states.set(gid, s);
|
|
16848
17205
|
}
|
|
16849
17206
|
return s;
|
|
16850
17207
|
};
|
|
16851
17208
|
cfg.update({
|
|
16852
|
-
states
|
|
17209
|
+
states,
|
|
16853
17210
|
groupIds,
|
|
16854
17211
|
columns,
|
|
16855
|
-
args:
|
|
17212
|
+
args: bindParams.args,
|
|
16856
17213
|
ensureState
|
|
16857
17214
|
});
|
|
16858
|
-
|
|
17215
|
+
await storeGroupStates(storage, states, gids);
|
|
16859
17216
|
return wrapResult({}, schema2([]));
|
|
16860
17217
|
};
|
|
16861
|
-
const aggregateCombine = (params) => {
|
|
17218
|
+
const aggregateCombine = async (params, ctx) => {
|
|
16862
17219
|
const innerParams = unwrapRequest(params.request);
|
|
16863
17220
|
const functionName = innerParams.function_name;
|
|
16864
17221
|
const executionId = toUint8Array(innerParams.execution_id);
|
|
@@ -16879,27 +17236,26 @@ function aggregateHandlers(registry) {
|
|
|
16879
17236
|
referencedGids.add(src);
|
|
16880
17237
|
referencedGids.add(tgt);
|
|
16881
17238
|
}
|
|
16882
|
-
const
|
|
16883
|
-
|
|
16884
|
-
|
|
16885
|
-
}
|
|
17239
|
+
const storage = await boundFor(innerParams, ctx, executionId);
|
|
17240
|
+
const bindParams = await loadContext(cfg, storage, "aggregate_combine");
|
|
17241
|
+
const states = await loadGroupStates(storage, [...referencedGids]);
|
|
16886
17242
|
const touchedTargets = new Set;
|
|
16887
17243
|
for (let i = 0;i < batch.numRows; i++) {
|
|
16888
17244
|
const src = srcIds[i];
|
|
16889
17245
|
const tgt = tgtIds[i];
|
|
16890
|
-
const srcHas =
|
|
16891
|
-
const tgtHas =
|
|
17246
|
+
const srcHas = states.has(src);
|
|
17247
|
+
const tgtHas = states.has(tgt);
|
|
16892
17248
|
if (!srcHas && !tgtHas)
|
|
16893
17249
|
continue;
|
|
16894
|
-
const srcState = srcHas ?
|
|
16895
|
-
const tgtState = tgtHas ?
|
|
16896
|
-
|
|
17250
|
+
const srcState = srcHas ? states.get(src) : cfg.initialState(bindParams);
|
|
17251
|
+
const tgtState = tgtHas ? states.get(tgt) : cfg.initialState(bindParams);
|
|
17252
|
+
states.set(tgt, cfg.combine(srcState, tgtState, bindParams));
|
|
16897
17253
|
touchedTargets.add(tgt);
|
|
16898
17254
|
}
|
|
16899
|
-
|
|
17255
|
+
await storeGroupStates(storage, states, touchedTargets);
|
|
16900
17256
|
return wrapResult({}, schema2([]));
|
|
16901
17257
|
};
|
|
16902
|
-
const aggregateFinalize = (params) => {
|
|
17258
|
+
const aggregateFinalize = async (params, ctx) => {
|
|
16903
17259
|
const innerParams = unwrapRequest(params.request);
|
|
16904
17260
|
const functionName = innerParams.function_name;
|
|
16905
17261
|
const executionId = toUint8Array(innerParams.execution_id);
|
|
@@ -16917,40 +17273,29 @@ function aggregateHandlers(registry) {
|
|
|
16917
17273
|
uniqueGids.add(g);
|
|
16918
17274
|
}
|
|
16919
17275
|
}
|
|
16920
|
-
const
|
|
16921
|
-
|
|
16922
|
-
|
|
16923
|
-
}
|
|
17276
|
+
const storage = await boundFor(innerParams, ctx, executionId);
|
|
17277
|
+
const bindParams = await loadContext(cfg, storage, "aggregate_finalize");
|
|
17278
|
+
const stored = await loadGroupStates(storage, [...uniqueGids]);
|
|
16924
17279
|
const states = new Map;
|
|
16925
17280
|
for (const gid of groupIds) {
|
|
16926
|
-
states.set(gid,
|
|
17281
|
+
states.set(gid, stored.has(gid) ? stored.get(gid) : null);
|
|
16927
17282
|
}
|
|
16928
17283
|
const resultBatch = cfg.finalize({
|
|
16929
17284
|
groupIds,
|
|
16930
17285
|
states,
|
|
16931
17286
|
outputSchema,
|
|
16932
|
-
args:
|
|
17287
|
+
args: bindParams.args
|
|
16933
17288
|
});
|
|
16934
17289
|
return wrapResult({ result_batch: serializeBatchWithSchema(resultBatch) }, AggregateFinalizeResultSchema);
|
|
16935
17290
|
};
|
|
16936
|
-
const aggregateDestructor = (params) => {
|
|
16937
|
-
|
|
16938
|
-
|
|
16939
|
-
|
|
16940
|
-
|
|
16941
|
-
|
|
16942
|
-
|
|
16943
|
-
|
|
16944
|
-
return wrapResult({}, schema2([]));
|
|
16945
|
-
const col = gidBatch.getChild("group_id");
|
|
16946
|
-
const toDrop = new Set;
|
|
16947
|
-
for (let i = 0;i < gidBatch.numRows; i++) {
|
|
16948
|
-
const v = col.get(i);
|
|
16949
|
-
const g = typeof v === "bigint" ? v : BigInt(v);
|
|
16950
|
-
exec.states.delete(g);
|
|
16951
|
-
toDrop.add(g);
|
|
16952
|
-
}
|
|
16953
|
-
persistGroupStates(executionId, toDrop);
|
|
17291
|
+
const aggregateDestructor = async (params, ctx) => {
|
|
17292
|
+
try {
|
|
17293
|
+
const innerParams = unwrapRequest(params.request);
|
|
17294
|
+
const executionId = toUint8Array(innerParams.execution_id);
|
|
17295
|
+
const storage = await boundFor(innerParams, ctx, executionId);
|
|
17296
|
+
aggregateContextCache.delete(storage.shardKey, executionId);
|
|
17297
|
+
await storage.executionClear();
|
|
17298
|
+
} catch {}
|
|
16954
17299
|
return wrapResult({}, schema2([]));
|
|
16955
17300
|
};
|
|
16956
17301
|
return { aggregateBind, aggregateUpdate, aggregateCombine, aggregateFinalize, aggregateDestructor };
|
|
@@ -17013,7 +17358,7 @@ function serializeBatchWithSchema(batch) {
|
|
|
17013
17358
|
// src/protocol/handlers/table-buffering.ts
|
|
17014
17359
|
init_arrow();
|
|
17015
17360
|
init_storage();
|
|
17016
|
-
function tableBufferingHandlers(registry, signingKey, attachSecretKey) {
|
|
17361
|
+
function tableBufferingHandlers(registry, signingKey, attachSecretKey, storageSealKey = signingKey) {
|
|
17017
17362
|
function resolveBuffering(name, schemaPath) {
|
|
17018
17363
|
const func = registry.get(name, {
|
|
17019
17364
|
arguments: new Arguments,
|
|
@@ -17029,16 +17374,28 @@ function tableBufferingHandlers(registry, signingKey, attachSecretKey) {
|
|
|
17029
17374
|
async function loadParams(inner, clientLog, ctx) {
|
|
17030
17375
|
const functionName = inner.function_name;
|
|
17031
17376
|
const executionId = toUint8Array(inner.execution_id);
|
|
17377
|
+
const auth = ctx?.auth ?? currentRequestAuth();
|
|
17032
17378
|
const rawAttach = inner.attach_opaque_data ? toUint8Array(inner.attach_opaque_data) : null;
|
|
17033
|
-
const attach
|
|
17379
|
+
const { attach, shardKey } = await openAttachWithShard(rawAttach, auth, signingKey, attachSecretKey);
|
|
17034
17380
|
const transactionId = inner.transaction_id ? toUint8Array(inner.transaction_id) : null;
|
|
17035
17381
|
const func = resolveBuffering(functionName, inner.schema_path ?? null);
|
|
17036
|
-
const bound = new BoundStorage(storage, executionId);
|
|
17037
|
-
const
|
|
17038
|
-
|
|
17039
|
-
|
|
17382
|
+
const bound = new BoundStorage(storage, executionId, null, shardKey);
|
|
17383
|
+
const init = await loadBufferingInit(bound, storageSealKey);
|
|
17384
|
+
let txnPlain = transactionId;
|
|
17385
|
+
if (txnPlain && txnPlain.length > 0 && signingKey && rawAttach) {
|
|
17386
|
+
try {
|
|
17387
|
+
txnPlain = await openTransaction(txnPlain, rawAttach, auth, signingKey);
|
|
17388
|
+
} catch {}
|
|
17040
17389
|
}
|
|
17041
|
-
const
|
|
17390
|
+
const request = {
|
|
17391
|
+
...init.request,
|
|
17392
|
+
bind_call: {
|
|
17393
|
+
...init.request.bind_call,
|
|
17394
|
+
attach_opaque_data: attach,
|
|
17395
|
+
transaction_opaque_data: txnPlain,
|
|
17396
|
+
storage_shard_key: shardKey
|
|
17397
|
+
}
|
|
17398
|
+
};
|
|
17042
17399
|
const args = func.bufferingExtractArgs(request.bind_call);
|
|
17043
17400
|
const settings = batchToScalarDict(request.bind_call.settings);
|
|
17044
17401
|
const secrets = batchToSecretDict(request.bind_call.secrets);
|
|
@@ -17086,11 +17443,14 @@ function tableBufferingHandlers(registry, signingKey, attachSecretKey) {
|
|
|
17086
17443
|
});
|
|
17087
17444
|
return wrapResult({ finalize_state_ids: out }, TableBufferingCombineResultSchema);
|
|
17088
17445
|
};
|
|
17089
|
-
const tableBufferingDestructor = async (rpcParams) => {
|
|
17446
|
+
const tableBufferingDestructor = async (rpcParams, ctx) => {
|
|
17090
17447
|
try {
|
|
17091
17448
|
const inner = unwrapRequest(rpcParams.request);
|
|
17092
17449
|
const executionId = toUint8Array(inner.execution_id);
|
|
17093
|
-
const
|
|
17450
|
+
const rawAttach = inner.attach_opaque_data ? toUint8Array(inner.attach_opaque_data) : null;
|
|
17451
|
+
const { shardKey } = await openAttachWithShard(rawAttach, ctx?.auth ?? currentRequestAuth(), signingKey, attachSecretKey);
|
|
17452
|
+
bufferingInitCache.delete(shardKey, executionId);
|
|
17453
|
+
const bound = new BoundStorage(storage, executionId, null, shardKey);
|
|
17094
17454
|
await bound.executionClear();
|
|
17095
17455
|
} catch {}
|
|
17096
17456
|
return wrapResult({}, TableBufferingDestructorResultSchema);
|
|
@@ -17115,9 +17475,6 @@ function decodeBytesList(raw) {
|
|
|
17115
17475
|
}
|
|
17116
17476
|
return out;
|
|
17117
17477
|
}
|
|
17118
|
-
function hex(buf) {
|
|
17119
|
-
return Array.from(buf, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
17120
|
-
}
|
|
17121
17478
|
|
|
17122
17479
|
// src/protocol/handlers/catalog/admin.ts
|
|
17123
17480
|
import { MethodNotImplementedError as MethodNotImplementedError2 } from "@query-farm/vgi-rpc";
|
|
@@ -17795,9 +18152,9 @@ var TICKET_ENVELOPE_VERSION = 1;
|
|
|
17795
18152
|
var MAX_OPTIONS_BYTES = 16 * 1024;
|
|
17796
18153
|
var MAX_TICKET_CHARS = 32 * 1024;
|
|
17797
18154
|
var CLOCK_SKEW_SECONDS = 60;
|
|
17798
|
-
var
|
|
18155
|
+
var UTF84 = new TextEncoder;
|
|
17799
18156
|
var STRICT_UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
17800
|
-
var TICKET_AAD_DOMAIN =
|
|
18157
|
+
var TICKET_AAD_DOMAIN = UTF84.encode("vgi.attach_ticket.v1\x00");
|
|
17801
18158
|
var TICKET_ID = /^[0-9a-f]{32}$/;
|
|
17802
18159
|
var B64URL = /^[A-Za-z0-9_-]+$/;
|
|
17803
18160
|
var MAX_TEXT = 65535;
|
|
@@ -17851,14 +18208,14 @@ class SealAttachDeniedError extends Error {
|
|
|
17851
18208
|
}
|
|
17852
18209
|
}
|
|
17853
18210
|
function attachTicketAad(principal) {
|
|
17854
|
-
const p =
|
|
18211
|
+
const p = UTF84.encode(principal);
|
|
17855
18212
|
const out = new Uint8Array(TICKET_AAD_DOMAIN.length + p.length);
|
|
17856
18213
|
out.set(TICKET_AAD_DOMAIN, 0);
|
|
17857
18214
|
out.set(p, TICKET_AAD_DOMAIN.length);
|
|
17858
18215
|
return out;
|
|
17859
18216
|
}
|
|
17860
18217
|
function packText(value, name) {
|
|
17861
|
-
const raw =
|
|
18218
|
+
const raw = UTF84.encode(value);
|
|
17862
18219
|
if (raw.length > MAX_TEXT)
|
|
17863
18220
|
throw new Error(`${name} is longer than 65535 bytes`);
|
|
17864
18221
|
const out = new Uint8Array(2 + raw.length);
|
|
@@ -18709,10 +19066,11 @@ function buildVgiService(config) {
|
|
|
18709
19066
|
registry: config.registry,
|
|
18710
19067
|
signingKey: config.signingKey,
|
|
18711
19068
|
attachSecretKey: config.attachSecretKey,
|
|
18712
|
-
catalogInterface: config.catalogInterface
|
|
19069
|
+
catalogInterface: config.catalogInterface,
|
|
19070
|
+
storageSealKey: config.storageSealKey ?? config.signingKey
|
|
18713
19071
|
}),
|
|
18714
|
-
...aggregateHandlers(config.registry),
|
|
18715
|
-
...tableBufferingHandlers(config.registry, config.signingKey, config.attachSecretKey),
|
|
19072
|
+
...aggregateHandlers(config.registry, config.signingKey, config.attachSecretKey, config.storageSealKey ?? config.signingKey),
|
|
19073
|
+
...tableBufferingHandlers(config.registry, config.signingKey, config.attachSecretKey, config.storageSealKey ?? config.signingKey),
|
|
18716
19074
|
...catalogHandlers(config.catalogInterface, config.signingKey, config.attachSecretKey)
|
|
18717
19075
|
};
|
|
18718
19076
|
}
|
|
@@ -18821,6 +19179,10 @@ function createLandingRoutes(info) {
|
|
|
18821
19179
|
return null;
|
|
18822
19180
|
};
|
|
18823
19181
|
}
|
|
19182
|
+
|
|
19183
|
+
// src/index.core.ts
|
|
19184
|
+
init_attach_secret_keyfile();
|
|
19185
|
+
|
|
18824
19186
|
// src/secrets/helpers.ts
|
|
18825
19187
|
function scalarStr(v) {
|
|
18826
19188
|
if (v === null || v === undefined)
|
|
@@ -18900,6 +19262,7 @@ function selectForScope(secrets, path, type) {
|
|
|
18900
19262
|
init_arrow();
|
|
18901
19263
|
init_storage();
|
|
18902
19264
|
init_storage_cf_do();
|
|
19265
|
+
init_storage_seal();
|
|
18903
19266
|
|
|
18904
19267
|
// src/client/client.ts
|
|
18905
19268
|
init_arrow();
|
|
@@ -20531,6 +20894,7 @@ export {
|
|
|
20531
20894
|
ScanPlanningFilters,
|
|
20532
20895
|
SealAttachDeniedError,
|
|
20533
20896
|
StatusError,
|
|
20897
|
+
StoragePayloadError,
|
|
20534
20898
|
TRANSACTION_DDL,
|
|
20535
20899
|
TableInOutPhase,
|
|
20536
20900
|
TimeUnit2 as TimeUnit,
|
|
@@ -20776,6 +21140,7 @@ export {
|
|
|
20776
21140
|
servedTableInfo,
|
|
20777
21141
|
servedTableSchema,
|
|
20778
21142
|
setStorage,
|
|
21143
|
+
shardKeyOf,
|
|
20779
21144
|
sparseUnion2 as sparseUnion,
|
|
20780
21145
|
sqlExpression,
|
|
20781
21146
|
str,
|
|
@@ -20818,4 +21183,4 @@ export {
|
|
|
20818
21183
|
writeRowsBatch
|
|
20819
21184
|
};
|
|
20820
21185
|
|
|
20821
|
-
//# debugId=
|
|
21186
|
+
//# debugId=96F1F8130C67C5FF64756E2164756E21
|