@query-farm/vgi 0.50.1 → 0.52.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/README.md +45 -3
- package/dist/client-entry.js +833 -775
- package/dist/client-entry.js.map +10 -10
- package/dist/functions/aggregate.d.ts +25 -21
- package/dist/functions/execution-cache.d.ts +11 -0
- package/dist/functions/storage-blobs.d.ts +173 -0
- package/dist/functions/storage-cf-do.d.ts +50 -0
- package/dist/functions/storage-seal.d.ts +27 -0
- package/dist/functions/storage.d.ts +71 -1
- package/dist/functions/table-buffering.d.ts +30 -0
- package/dist/functions/table.d.ts +6 -1
- package/dist/generated/vgi-client.d.ts +7 -1
- package/dist/generated/vgi-protocol-schemas.d.ts +10 -9
- package/dist/generated/vgi-protocol-types.d.ts +244 -2
- package/dist/generated/vgi-service.d.ts +1 -1
- package/dist/hosted.d.ts +117 -0
- package/dist/http/blob-vendor.d.ts +33 -0
- package/dist/http/fetch.d.ts +60 -2
- package/dist/http/hosted-auth.d.ts +45 -0
- package/dist/index.core.d.ts +11 -3
- package/dist/index.js +8661 -6677
- package/dist/index.js.map +52 -34
- package/dist/protocol/arguments-ref.d.ts +107 -0
- package/dist/protocol/dispatch.d.ts +12 -2
- 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 +23 -0
- package/dist/protocol/handlers/table-buffering.d.ts +1 -1
- package/dist/protocol/serialize.d.ts +1 -1
- package/dist/protocol/serializers/bind.d.ts +27 -1
- package/dist/protocol/serializers/cardinality.d.ts +1 -1
- package/dist/protocol/serializers/splits.d.ts +7 -0
- package/dist/protocol/state-serializer.d.ts +8 -7
- package/dist/protocol/stream-init.d.ts +17 -0
- package/dist/protocol/types.d.ts +32 -0
- package/dist/secrets/lookups.d.ts +31 -0
- package/dist/serve-entry.d.ts +41 -6
- package/dist/serve-entry.js +8531 -6302
- package/dist/serve-entry.js.map +52 -35
- package/dist/worker-cf-entry.d.ts +5 -0
- package/dist/worker-cf-entry.js +7191 -4990
- package/dist/worker-cf-entry.js.map +59 -41
- package/package.json +5 -4
- 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-blobs.ts +654 -0
- package/src/functions/storage-cf-do.ts +176 -22
- package/src/functions/storage-seal.ts +208 -0
- package/src/functions/storage.ts +174 -8
- package/src/functions/table-buffering.ts +104 -18
- package/src/functions/table-in-out.ts +3 -1
- package/src/functions/table.ts +12 -8
- package/src/generated/vgi-client.ts +9 -2
- package/src/generated/vgi-protocol-schemas.ts +115 -107
- package/src/generated/vgi-protocol-types.ts +640 -3
- package/src/generated/vgi-service.ts +2 -2
- package/src/hosted.ts +254 -0
- package/src/http/blob-vendor.ts +80 -0
- package/src/http/fetch.ts +179 -8
- package/src/http/hosted-auth.ts +326 -0
- package/src/index.core.ts +66 -1
- package/src/protocol/arguments-ref.ts +260 -0
- package/src/protocol/dispatch.ts +15 -4
- package/src/protocol/handlers/aggregate.ts +123 -82
- package/src/protocol/handlers/catalog/shared.ts +20 -0
- package/src/protocol/handlers/function.ts +135 -59
- package/src/protocol/handlers/table-buffering.ts +49 -32
- package/src/protocol/serialize.ts +3 -0
- package/src/protocol/serializers/bind.ts +96 -69
- package/src/protocol/serializers/cardinality.ts +4 -7
- package/src/protocol/serializers/init.ts +5 -11
- package/src/protocol/serializers/splits.ts +31 -4
- package/src/protocol/state-serializer.ts +27 -39
- package/src/protocol/stream-init.ts +87 -0
- package/src/protocol/types.ts +33 -0
- package/src/secrets/lookups.ts +53 -0
- package/src/serve-entry.ts +138 -11
- package/src/worker-cf-entry.ts +33 -0
- package/src/worker.ts +25 -0
- package/dist/protocol/carried-init-request.d.ts +0 -28
- package/dist/util/zstd-sync.d.ts +0 -7
- package/src/protocol/carried-init-request.ts +0 -139
- package/src/util/zstd-sync.ts +0 -50
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@query-farm/vgi",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.52.0",
|
|
4
4
|
"description": "TypeScript framework for extending DuckDB with user-defined functions via the Vector Gateway Interface (VGI) over Arrow IPC.",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE",
|
|
6
6
|
"author": "Query Farm LLC (https://query.farm)",
|
|
@@ -89,16 +89,17 @@
|
|
|
89
89
|
},
|
|
90
90
|
"dependencies": {
|
|
91
91
|
"@noble/ciphers": "^2.3.0",
|
|
92
|
-
"@query-farm/flechette": "^2.7.1"
|
|
92
|
+
"@query-farm/flechette": "^2.7.1",
|
|
93
|
+
"jose": "^6.2.0"
|
|
93
94
|
},
|
|
94
95
|
"peerDependencies": {
|
|
95
96
|
"@query-farm/apache-arrow": "^21.1.1",
|
|
96
|
-
"@query-farm/vgi-rpc": "^0.
|
|
97
|
+
"@query-farm/vgi-rpc": "^0.30.0"
|
|
97
98
|
},
|
|
98
99
|
"devDependencies": {
|
|
99
100
|
"@duckdb/node-api": "^1.5.5-r.4",
|
|
100
101
|
"@query-farm/apache-arrow": "^21.1.1",
|
|
101
|
-
"@query-farm/vgi-rpc": "^0.
|
|
102
|
+
"@query-farm/vgi-rpc": "^0.30.0",
|
|
102
103
|
"@types/bun": "latest",
|
|
103
104
|
"typescript": "^7.0.2"
|
|
104
105
|
},
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
// Copyright 2025, 2026 Query Farm LLC - https://query.farm
|
|
2
2
|
// Aggregate function framework — mirrors vgi-python's vgi/aggregate_function.py
|
|
3
|
-
// protocol at the wire level. Per-execution state lives in
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
3
|
+
// protocol at the wire level. Per-execution state lives in FunctionStorage
|
|
4
|
+
// (sharded per attach, like every other function kind), so any worker process
|
|
5
|
+
// -- or host, or Cloudflare isolate -- can serve any aggregate RPC of an
|
|
6
|
+
// execution: group states under FrameworkNS.AGGREGATE_STATE keyed by
|
|
7
|
+
// packIntKey(group_id), and the bind context, sealed, at packIntKey(-2).
|
|
7
8
|
//
|
|
8
9
|
// DuckDB drives the lifecycle via five unary RPCs:
|
|
9
10
|
//
|
|
@@ -28,32 +29,9 @@ import type {
|
|
|
28
29
|
} from "./types.js";
|
|
29
30
|
import { DEFAULT_MAX_WORKERS } from "../types.js";
|
|
30
31
|
import type { FunctionExample } from "./types.js";
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
// node:* modules through indirect string variables that esbuild can't trace.
|
|
35
|
-
// The bundle stays clean even without nodejs_compat polyfills.
|
|
36
|
-
const _NODE_FS_MOD = "node:fs";
|
|
37
|
-
const _NODE_PATH_MOD = "node:path";
|
|
38
|
-
const _NODE_OS_MOD = "node:os";
|
|
39
|
-
function _aggReq(): any {
|
|
40
|
-
const req: any = (import.meta as any).require ?? (globalThis as any).require ?? null;
|
|
41
|
-
if (!req) {
|
|
42
|
-
throw new Error(
|
|
43
|
-
"Aggregate state persistence requires Node.js or Bun (node:fs/path/os).",
|
|
44
|
-
);
|
|
45
|
-
}
|
|
46
|
-
return req;
|
|
47
|
-
}
|
|
48
|
-
const fs: any = new Proxy({} as any, {
|
|
49
|
-
get: (_t, prop) => (_aggReq()(_NODE_FS_MOD) as any)[prop],
|
|
50
|
-
});
|
|
51
|
-
const path: any = new Proxy({} as any, {
|
|
52
|
-
get: (_t, prop) => (_aggReq()(_NODE_PATH_MOD) as any)[prop],
|
|
53
|
-
});
|
|
54
|
-
const os: any = new Proxy({} as any, {
|
|
55
|
-
get: (_t, prop) => (_aggReq()(_NODE_OS_MOD) as any)[prop],
|
|
56
|
-
});
|
|
32
|
+
import { FrameworkNS, packIntKey, type BoundStorage } from "./storage.js";
|
|
33
|
+
import { ExecutionCache } from "./execution-cache.js";
|
|
34
|
+
import { StoragePayloadError } from "./storage-seal.js";
|
|
57
35
|
|
|
58
36
|
// Column name DuckDB prepends to every aggregate_update batch. One entry per
|
|
59
37
|
// input row; the value identifies which group the row belongs to.
|
|
@@ -169,30 +147,34 @@ export interface AggregateFunctionConfig<TArgs = Record<string, any>, TState = a
|
|
|
169
147
|
requiredSecrets?: RequiredSecret[];
|
|
170
148
|
}
|
|
171
149
|
|
|
172
|
-
//
|
|
150
|
+
// ============================================================================
|
|
151
|
+
// Execution state in FunctionStorage
|
|
173
152
|
//
|
|
174
|
-
// Under DuckDB's parallel aggregate with worker pooling
|
|
175
|
-
//
|
|
176
|
-
//
|
|
177
|
-
// store
|
|
178
|
-
// atomic rename-on-write. Fine for subprocess transport and for
|
|
179
|
-
// single-instance HTTP; multi-host HTTP would need a shared path or a
|
|
180
|
-
// swap-in network backend. Override with VGI_AGG_STATE_DIR.
|
|
153
|
+
// Under DuckDB's parallel aggregate with worker pooling (and over HTTP, where
|
|
154
|
+
// every RPC may land on another host), the aggregate_* RPCs of one execution
|
|
155
|
+
// reach different processes, so state lives in FunctionStorage, the same
|
|
156
|
+
// shared store the table functions use:
|
|
181
157
|
//
|
|
182
|
-
//
|
|
183
|
-
//
|
|
184
|
-
//
|
|
185
|
-
|
|
186
|
-
|
|
158
|
+
// ns = FrameworkNS.AGGREGATE_STATE ("_vgi/aggregate_state")
|
|
159
|
+
// key = packIntKey(group_id) → that group's state (JSON, bigint-tagged);
|
|
160
|
+
// the function's own data, not sealed
|
|
161
|
+
// key = packIntKey(-2) → the bind context (constant arguments, input
|
|
162
|
+
// schema, argument names), SEALED to its slot
|
|
163
|
+
//
|
|
164
|
+
// Each update/combine/finalize RPC is one batched read of the groups it
|
|
165
|
+
// touches plus (update/combine) one batched write: two storage round trips per
|
|
166
|
+
// batch, whatever the group count. The bind context is written once at bind
|
|
167
|
+
// and cached per (shard, execution) in-process, so it costs a read only on a
|
|
168
|
+
// process's first RPC of an execution. Secret VALUES are never stored: they are
|
|
169
|
+
// delivered on aggregate_bind only, and update/combine/finalize see an empty
|
|
170
|
+
// `secrets` -- the documented contract (see `requiredSecrets`).
|
|
171
|
+
// ============================================================================
|
|
187
172
|
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
bindArgs: Arguments;
|
|
191
|
-
bindParams: AggregateBindParams<any>;
|
|
192
|
-
loaded: Set<bigint>; // gids fetched from disk (so we don't refetch in same call)
|
|
193
|
-
}
|
|
173
|
+
/** Key of the sealed bind context within FrameworkNS.AGGREGATE_STATE. */
|
|
174
|
+
export const AGGREGATE_CONTEXT_KEY = packIntKey(-2);
|
|
194
175
|
|
|
195
|
-
|
|
176
|
+
/** Per-(shard, execution) cache of the decoded bind context. */
|
|
177
|
+
export const aggregateContextCache = new ExecutionCache<AggregateBindParams<any>>(64);
|
|
196
178
|
|
|
197
179
|
// Custom JSON codec: BigInt ↔ {"__bigint__":"…"}. Keep the encoder/decoder
|
|
198
180
|
// centralized so aggregate state classes with int64 fields (CountState,
|
|
@@ -208,127 +190,94 @@ function jsonReviver(_: string, v: any): any {
|
|
|
208
190
|
return v;
|
|
209
191
|
}
|
|
210
192
|
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
}
|
|
193
|
+
const UTF8_ENC = new TextEncoder();
|
|
194
|
+
const UTF8_DEC = new TextDecoder();
|
|
214
195
|
|
|
215
|
-
|
|
216
|
-
|
|
196
|
+
/** Encode one group's state for storage. */
|
|
197
|
+
export function encodeGroupState(state: unknown): Uint8Array {
|
|
198
|
+
return UTF8_ENC.encode(JSON.stringify(state, jsonReplacer));
|
|
217
199
|
}
|
|
218
200
|
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
return s;
|
|
201
|
+
/** Decode one group's state from storage. */
|
|
202
|
+
export function decodeGroupState(bytes: Uint8Array): any {
|
|
203
|
+
return JSON.parse(UTF8_DEC.decode(bytes), jsonReviver);
|
|
223
204
|
}
|
|
224
205
|
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
const parent = path.dirname(filePath);
|
|
230
|
-
fs.mkdirSync(parent, { recursive: true });
|
|
231
|
-
fs.writeFileSync(tmp, JSON.stringify(value, jsonReplacer));
|
|
232
|
-
fs.renameSync(tmp, filePath);
|
|
206
|
+
function b64(buf: Uint8Array): string {
|
|
207
|
+
let binary = "";
|
|
208
|
+
for (let i = 0; i < buf.length; i++) binary += String.fromCharCode(buf[i]!);
|
|
209
|
+
return btoa(binary);
|
|
233
210
|
}
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
} catch (e: any) {
|
|
240
|
-
if (e?.code === "ENOENT") return undefined;
|
|
241
|
-
throw e;
|
|
242
|
-
}
|
|
211
|
+
function unb64(s: string): Uint8Array {
|
|
212
|
+
const binary = atob(s);
|
|
213
|
+
const out = new Uint8Array(binary.length);
|
|
214
|
+
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
|
215
|
+
return out;
|
|
243
216
|
}
|
|
244
217
|
|
|
245
218
|
/**
|
|
246
|
-
*
|
|
247
|
-
*
|
|
248
|
-
*
|
|
249
|
-
*
|
|
219
|
+
* The stored bind context: the wire `arguments` and `input_schema` bytes and
|
|
220
|
+
* the argument names, exactly as aggregate_bind received them, so a cold
|
|
221
|
+
* process rebuilds the same AggregateBindParams (args are re-extracted from
|
|
222
|
+
* the arguments with the function's declaration). No secrets.
|
|
250
223
|
*/
|
|
251
|
-
export
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
224
|
+
export interface StoredAggregateContext {
|
|
225
|
+
argumentsIpc: Uint8Array;
|
|
226
|
+
inputSchemaIpc: Uint8Array | null;
|
|
227
|
+
argumentNames: (string | null)[] | null;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export function encodeAggregateContext(ctx: StoredAggregateContext): Uint8Array {
|
|
231
|
+
return UTF8_ENC.encode(
|
|
232
|
+
JSON.stringify({
|
|
233
|
+
v: 1,
|
|
234
|
+
arguments: b64(ctx.argumentsIpc),
|
|
235
|
+
input_schema: ctx.inputSchemaIpc ? b64(ctx.inputSchemaIpc) : null,
|
|
236
|
+
argument_names: ctx.argumentNames,
|
|
237
|
+
}),
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
export function decodeAggregateContext(bytes: Uint8Array): StoredAggregateContext {
|
|
242
|
+
let d: any;
|
|
243
|
+
try {
|
|
244
|
+
d = JSON.parse(UTF8_DEC.decode(bytes));
|
|
245
|
+
} catch {
|
|
246
|
+
throw new StoragePayloadError("aggregate: unrecognized bind context payload");
|
|
270
247
|
}
|
|
271
|
-
if (
|
|
272
|
-
|
|
273
|
-
// written a newer value for this gid; relying on our in-memory cache
|
|
274
|
-
// would overwrite their update on our next persist (read-modify-write
|
|
275
|
-
// race). File I/O per-RPC is cheap compared to the RPC overhead.
|
|
276
|
-
for (const gid of requestedGids) {
|
|
277
|
-
const stateFile = path.join(execDir(key), gid.toString() + ".json");
|
|
278
|
-
const s = tryReadJson(stateFile);
|
|
279
|
-
if (s !== undefined) {
|
|
280
|
-
entry.states.set(gid, s);
|
|
281
|
-
} else {
|
|
282
|
-
entry.states.delete(gid);
|
|
283
|
-
}
|
|
284
|
-
entry.loaded.add(gid);
|
|
285
|
-
}
|
|
248
|
+
if (!d || d.v !== 1 || typeof d.arguments !== "string") {
|
|
249
|
+
throw new StoragePayloadError("aggregate: unrecognized bind context payload format");
|
|
286
250
|
}
|
|
287
|
-
return
|
|
251
|
+
return {
|
|
252
|
+
argumentsIpc: unb64(d.arguments),
|
|
253
|
+
inputSchemaIpc: typeof d.input_schema === "string" ? unb64(d.input_schema) : null,
|
|
254
|
+
argumentNames: Array.isArray(d.argument_names) ? d.argument_names : null,
|
|
255
|
+
};
|
|
288
256
|
}
|
|
289
257
|
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
)
|
|
294
|
-
const
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
// if needed for future state-dependent behavior. Workers reading the
|
|
301
|
-
// context receive `bindParams.args` which is what update/finalize use.
|
|
302
|
-
});
|
|
258
|
+
/** Read the stored states of `gids` (absent groups are left out of the map). */
|
|
259
|
+
export async function loadGroupStates(storage: BoundStorage, gids: bigint[]): Promise<Map<bigint, any>> {
|
|
260
|
+
const states = new Map<bigint, any>();
|
|
261
|
+
if (gids.length === 0) return states;
|
|
262
|
+
const values = await storage.stateGetMany(FrameworkNS.AGGREGATE_STATE, gids.map((g) => packIntKey(g)));
|
|
263
|
+
for (let i = 0; i < gids.length; i++) {
|
|
264
|
+
const v = values[i];
|
|
265
|
+
if (v != null) states.set(gids[i]!, decodeGroupState(v));
|
|
266
|
+
}
|
|
267
|
+
return states;
|
|
303
268
|
}
|
|
304
269
|
|
|
305
|
-
/**
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
*/
|
|
310
|
-
export function persistGroupStates(
|
|
311
|
-
executionId: Uint8Array,
|
|
270
|
+
/** Write the states of `gids` that are present in `states` (one batched put). */
|
|
271
|
+
export async function storeGroupStates(
|
|
272
|
+
storage: BoundStorage,
|
|
273
|
+
states: Map<bigint, any>,
|
|
312
274
|
gids: Iterable<bigint>,
|
|
313
|
-
): void {
|
|
314
|
-
const
|
|
315
|
-
const entry = stateStore.get(key);
|
|
316
|
-
if (!entry) return;
|
|
275
|
+
): Promise<void> {
|
|
276
|
+
const items: Array<[Uint8Array, Uint8Array]> = [];
|
|
317
277
|
for (const gid of gids) {
|
|
318
|
-
|
|
319
|
-
if (entry.states.has(gid)) {
|
|
320
|
-
atomicWriteJson(stateFile, entry.states.get(gid));
|
|
321
|
-
} else {
|
|
322
|
-
try { fs.unlinkSync(stateFile); } catch { /* already gone */ }
|
|
323
|
-
}
|
|
324
|
-
entry.loaded.add(gid);
|
|
278
|
+
if (states.has(gid)) items.push([packIntKey(gid), encodeGroupState(states.get(gid))]);
|
|
325
279
|
}
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
export function deleteExecutionState(executionId: Uint8Array): void {
|
|
329
|
-
const key = execKey(executionId);
|
|
330
|
-
stateStore.delete(key);
|
|
331
|
-
try { fs.rmSync(execDir(key), { recursive: true, force: true }); } catch { /* best-effort */ }
|
|
280
|
+
if (items.length > 0) await storage.statePutMany(FrameworkNS.AGGREGATE_STATE, items);
|
|
332
281
|
}
|
|
333
282
|
|
|
334
283
|
/**
|
|
@@ -34,7 +34,7 @@ import type { CopySecretLookup } from "./copy-to.js";
|
|
|
34
34
|
import type { ArgumentSpec } from "../arguments/argument-spec.js";
|
|
35
35
|
import { narrowArgValue } from "../arguments/argument-spec.js";
|
|
36
36
|
import { batchToScalarDict, batchToSecretDict, safeNumber } from "../util/arrow/index.js";
|
|
37
|
-
import { BoundStorage, storage as globalStorage } from "./storage.js";
|
|
37
|
+
import { BoundStorage, storage as globalStorage, shardKeyOf } from "./storage.js";
|
|
38
38
|
import type { TableProcessParams } from "./table.js";
|
|
39
39
|
|
|
40
40
|
/** Declaration of a single COPY option (a named function argument). */
|
|
@@ -240,7 +240,7 @@ export function defineCopyFromFunction<TArgs = Record<string, unknown>>(
|
|
|
240
240
|
const settings = batchToScalarDict(request.bind_call.settings);
|
|
241
241
|
const secrets = batchToSecretDict(request.bind_call.secrets);
|
|
242
242
|
const outputSchema = request.output_schema;
|
|
243
|
-
const boundStorage = new BoundStorage(globalStorage, response.execution_id);
|
|
243
|
+
const boundStorage = new BoundStorage(globalStorage, response.execution_id, null, shardKeyOf(request.bind_call));
|
|
244
244
|
|
|
245
245
|
const processParams: TableProcessParams<TArgs> = {
|
|
246
246
|
args,
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// Copyright 2025, 2026 Query Farm LLC - https://query.farm
|
|
2
|
+
// A small bounded LRU of per-execution framework context, keyed by
|
|
3
|
+
// (attach shard, execution id).
|
|
4
|
+
//
|
|
5
|
+
// Framework context an execution writes once and never changes (the buffered
|
|
6
|
+
// init, an aggregate's bind context) is read on every unary RPC of that
|
|
7
|
+
// execution. Caching the decoded value in-process saves one storage round trip
|
|
8
|
+
// per batch — 30-90 ms each on the Cloudflare DO. Storage stays authoritative:
|
|
9
|
+
// a miss (another process wrote it, the entry was evicted, a fresh isolate)
|
|
10
|
+
// falls through to a storage read, and the destructor evicts. Entries hold only
|
|
11
|
+
// values that were authenticated (opened from a sealed payload) or produced in
|
|
12
|
+
// this process. Sized for a Cloudflare isolate's memory, not a server's.
|
|
13
|
+
|
|
14
|
+
function hex(b: Uint8Array): string {
|
|
15
|
+
let s = "";
|
|
16
|
+
for (let i = 0; i < b.length; i++) s += b[i]!.toString(16).padStart(2, "0");
|
|
17
|
+
return s;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export class ExecutionCache<V> {
|
|
21
|
+
private readonly _map = new Map<string, V>();
|
|
22
|
+
|
|
23
|
+
constructor(readonly maxEntries: number) {}
|
|
24
|
+
|
|
25
|
+
private static _key(shardKey: string, executionId: Uint8Array): string {
|
|
26
|
+
return `${shardKey}\u0000${hex(executionId)}`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
get(shardKey: string, executionId: Uint8Array): V | undefined {
|
|
30
|
+
const k = ExecutionCache._key(shardKey, executionId);
|
|
31
|
+
const v = this._map.get(k);
|
|
32
|
+
if (v === undefined) return undefined;
|
|
33
|
+
// Refresh recency.
|
|
34
|
+
this._map.delete(k);
|
|
35
|
+
this._map.set(k, v);
|
|
36
|
+
return v;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
set(shardKey: string, executionId: Uint8Array, value: V): void {
|
|
40
|
+
const k = ExecutionCache._key(shardKey, executionId);
|
|
41
|
+
this._map.delete(k);
|
|
42
|
+
this._map.set(k, value);
|
|
43
|
+
while (this._map.size > this.maxEntries) {
|
|
44
|
+
this._map.delete(this._map.keys().next().value!);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
delete(shardKey: string, executionId: Uint8Array): void {
|
|
49
|
+
this._map.delete(ExecutionCache._key(shardKey, executionId));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
clear(): void {
|
|
53
|
+
this._map.clear();
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
get size(): number {
|
|
57
|
+
return this._map.size;
|
|
58
|
+
}
|
|
59
|
+
}
|