@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.
Files changed (40) hide show
  1. package/dist/functions/aggregate.d.ts +25 -21
  2. package/dist/functions/execution-cache.d.ts +11 -0
  3. package/dist/functions/storage-cf-do.d.ts +38 -0
  4. package/dist/functions/storage-seal.d.ts +27 -0
  5. package/dist/functions/storage.d.ts +49 -1
  6. package/dist/functions/table-buffering.d.ts +30 -0
  7. package/dist/http/fetch.d.ts +7 -0
  8. package/dist/index.core.d.ts +3 -2
  9. package/dist/index.js +749 -384
  10. package/dist/index.js.map +20 -18
  11. package/dist/protocol/dispatch.d.ts +9 -0
  12. package/dist/protocol/handlers/aggregate.d.ts +1 -1
  13. package/dist/protocol/handlers/catalog/shared.d.ts +10 -0
  14. package/dist/protocol/handlers/function.d.ts +2 -0
  15. package/dist/protocol/handlers/table-buffering.d.ts +1 -1
  16. package/dist/protocol/types.d.ts +8 -0
  17. package/dist/serve-entry.d.ts +16 -2
  18. package/dist/serve-entry.js +1034 -526
  19. package/dist/serve-entry.js.map +20 -18
  20. package/dist/worker-cf-entry.js +2713 -2217
  21. package/dist/worker-cf-entry.js.map +26 -24
  22. package/package.json +1 -1
  23. package/src/functions/aggregate.ts +101 -152
  24. package/src/functions/copy-from.ts +2 -2
  25. package/src/functions/execution-cache.ts +59 -0
  26. package/src/functions/storage-cf-do.ts +152 -22
  27. package/src/functions/storage-seal.ts +208 -0
  28. package/src/functions/storage.ts +120 -3
  29. package/src/functions/table-buffering.ts +91 -15
  30. package/src/functions/table-in-out.ts +3 -1
  31. package/src/functions/table.ts +4 -4
  32. package/src/http/fetch.ts +9 -0
  33. package/src/index.core.ts +3 -1
  34. package/src/protocol/dispatch.ts +12 -2
  35. package/src/protocol/handlers/aggregate.ts +123 -82
  36. package/src/protocol/handlers/catalog/shared.ts +20 -0
  37. package/src/protocol/handlers/function.ts +38 -11
  38. package/src/protocol/handlers/table-buffering.ts +44 -32
  39. package/src/protocol/types.ts +8 -0
  40. package/src/serve-entry.ts +33 -3
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@query-farm/vgi",
3
- "version": "0.50.0",
3
+ "version": "0.51.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)",
@@ -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 an in-memory store
4
- // keyed by (execution_id, group_id); fine for subprocess workers and for
5
- // single-instance HTTP. Multi-host HTTP deployments would need a pluggable
6
- // state backend (same tradeoff Python's FunctionStorage wraps).
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
- // Aggregate state persistence uses node:fs/path/os to spill per-group state to
32
- // disk under VGI_AGG_STATE_DIR. Workers (Cloudflare workerd / browsers)
33
- // don't define aggregate functions in the first place, so we resolve the
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
- // Per-execution state registry. Value = (gid → state) + bind context.
150
+ // ============================================================================
151
+ // Execution state in FunctionStorage
173
152
  //
174
- // Under DuckDB's parallel aggregate with worker pooling, aggregate_* RPCs for
175
- // the same execution_id can land on different worker processes — so state
176
- // needs to live in a place all workers can reach. We use a filesystem-backed
177
- // store (one directory per execution_id, one JSON file per group_id) with
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
- // In-memory cache sits in front of the filesystem to keep single-process
183
- // workloads fast — writes go to disk, reads prefer cache, and getExecutionState
184
- // lazily reconstructs from disk when a different worker's exec is requested.
185
-
186
- type StateMap = Map<bigint, any>;
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
- interface ExecEntry {
189
- states: StateMap;
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
- const stateStore = new Map<string, ExecEntry>();
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
- function stateDirRoot(): string {
212
- return process.env.VGI_AGG_STATE_DIR ?? path.join(os.tmpdir(), "vgi-agg");
213
- }
193
+ const UTF8_ENC = new TextEncoder();
194
+ const UTF8_DEC = new TextDecoder();
214
195
 
215
- function execDir(execHex: string): string {
216
- return path.join(stateDirRoot(), execHex);
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
- function execKey(executionId: Uint8Array): string {
220
- let s = "";
221
- for (const b of executionId) s += b.toString(16).padStart(2, "0");
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
- // Atomic write: write to tmp then rename. Avoids partial reads from another
226
- // worker mid-update. Node's fs.renameSync is atomic on POSIX for same FS.
227
- function atomicWriteJson(filePath: string, value: any): void {
228
- const tmp = filePath + ".tmp." + process.pid + "." + Math.random().toString(36).slice(2);
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
- function tryReadJson(filePath: string): any | undefined {
236
- try {
237
- const text = fs.readFileSync(filePath, "utf8");
238
- return JSON.parse(text, jsonReviver);
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
- * Fetch the execution context — bind args/params + states for requested gids.
247
- * On cache miss, tries to reconstruct from on-disk files written by a
248
- * sibling worker. Returns undefined if the exec never existed anywhere.
249
- * `requestedGids` (optional) tells us which group states to pre-load.
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 function getExecutionState(
252
- executionId: Uint8Array,
253
- requestedGids?: Iterable<bigint>,
254
- ): ExecEntry | undefined {
255
- const key = execKey(executionId);
256
- let entry = stateStore.get(key);
257
- if (!entry) {
258
- // Try to reconstruct bind context from disk.
259
- const ctx = tryReadJson(path.join(execDir(key), "context.json"));
260
- if (!ctx) return undefined;
261
- // Restore bindParams + args from the serialized context. args is kept
262
- // only as a plain dict; the Arguments instance isn't needed after bind.
263
- entry = {
264
- states: new Map(),
265
- bindArgs: ctx.bindArgs, // placeholder — Arguments instance is only needed during bind
266
- bindParams: ctx.bindParams,
267
- loaded: new Set(),
268
- };
269
- stateStore.set(key, entry);
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 (requestedGids) {
272
- // Always re-read from disk each RPC. A sibling worker may have just
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 entry;
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
- export function setExecutionState(
291
- executionId: Uint8Array,
292
- entry: Omit<ExecEntry, "loaded">,
293
- ): void {
294
- const key = execKey(executionId);
295
- stateStore.set(key, { ...entry, loaded: new Set() });
296
- // Persist bind context so sibling workers can reconstruct it on demand.
297
- atomicWriteJson(path.join(execDir(key), "context.json"), {
298
- bindParams: entry.bindParams,
299
- // bindArgs is a live Arguments instance; stash its args map separately
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
- * Persist the given group states to disk so sibling workers can pick them up.
307
- * Deletes the on-disk entry when the in-memory state was removed (gid no
308
- * longer present in states map).
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 key = execKey(executionId);
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
- const stateFile = path.join(execDir(key), gid.toString() + ".json");
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
+ }
@@ -4,8 +4,9 @@
4
4
  // Port of vgi-python's vgi/function_storage_cf_do.py. Talks the Cloudflare
5
5
  // Worker + Durable Object's unified state_* / queue_* protocol
6
6
  // (vgi-cloudflare-durable-object-storage/src/index.ts). Every request carries
7
- // the per-attach `shard_key` (set via forShard); destructive ops carry a fresh
8
- // 32-hex `attempt_id`. The DO is single-threaded SQLite, so ops are atomic.
7
+ // the per-attach `shard_key` (BoundStorage calls forShard with the shard the
8
+ // framework derived from the request's attach; "" goes to `loc-anon`);
9
+ // destructive ops carry a fresh 32-hex `attempt_id`, reused across retries. The DO is single-threaded SQLite, so ops are atomic.
9
10
  //
10
11
  // Usage:
11
12
  // Set `VGI_WORKER_SHARED_STORAGE=cloudflare-do` plus `VGI_CF_DO_URL`.
@@ -18,9 +19,38 @@ import { UnknownInvocationError, workerStateKey } from "./storage.js";
18
19
  * Cloudflare service-binding Fetcher (`env.<BINDING>`). */
19
20
  export type FetchLike = (
20
21
  input: string,
21
- init?: { method?: string; headers?: Record<string, string>; body?: string },
22
+ init?: { method?: string; headers?: Record<string, string>; body?: string; signal?: AbortSignal },
22
23
  ) => Promise<Response>;
23
24
 
25
+ /** The DO server's shard_key rule (vgi-cloudflare-durable-object-storage). */
26
+ export const SHARD_KEY_RE = /^[A-Za-z0-9._-]{1,128}$/;
27
+
28
+ /**
29
+ * Shard for a call not bound to an ATTACH (no attach uuid to shard on): one
30
+ * shared DO per tenant, as vgi-python's client does. Every attach-bound call
31
+ * carries its own `att-<uuid hex>` shard instead.
32
+ */
33
+ export const ANONYMOUS_SHARD_KEY = "loc-anon";
34
+
35
+ /** Retry policy for the DO client. */
36
+ export interface CfDoRetryOptions {
37
+ /** Per-attempt fetch timeout, ms (default 30000; 0 disables). */
38
+ timeoutMs?: number;
39
+ /** Total attempts including the first (default 4). */
40
+ maxAttempts?: number;
41
+ /** First backoff, ms (default 100); doubles per attempt, full jitter. */
42
+ baseDelayMs?: number;
43
+ /** Backoff cap, ms (default 2000). */
44
+ maxDelayMs?: number;
45
+ }
46
+
47
+ /** A transient failure worth retrying: transport error, timeout, 5xx or 429. */
48
+ class RetryableError extends Error {
49
+ constructor(message: string, readonly retryAfterMs: number | null = null) {
50
+ super(message);
51
+ }
52
+ }
53
+
24
54
  // Namespaces under the unified state_* table for the legacy worker/queue
25
55
  // families the DO no longer has dedicated endpoints for.
26
56
  const NS_WORKER = new TextEncoder().encode("worker");
@@ -35,18 +65,39 @@ export class FunctionStorageCfDo implements FunctionStorage {
35
65
  * the same account/zone — a same-zone public-URL fetch is rejected (CF
36
66
  * error 1042), but a service binding routes worker-to-worker directly. */
37
67
  private readonly _fetch: FetchLike;
68
+ private readonly _retry: Required<CfDoRetryOptions>;
69
+ /** Test hook: how the client waits between attempts. */
70
+ private readonly _sleep: (ms: number) => Promise<void>;
38
71
 
39
72
  constructor(opts: {
40
73
  url: string;
41
74
  token?: string | null;
42
75
  shardKey?: string;
43
76
  fetch?: FetchLike;
77
+ retry?: CfDoRetryOptions;
78
+ sleep?: (ms: number) => Promise<void>;
44
79
  }) {
45
80
  // Strip trailing slash so endpoint paths can be appended unconditionally.
46
81
  this._baseUrl = opts.url.replace(/\/+$/, "");
47
82
  this._token = opts.token ?? null;
48
- this._shardKey = opts.shardKey ?? "";
83
+ const shard = opts.shardKey ?? "";
84
+ if (shard !== "" && !SHARD_KEY_RE.test(shard)) {
85
+ throw new Error(`invalid CF DO shard_key ${JSON.stringify(shard)} (1-128 chars, [A-Za-z0-9._-])`);
86
+ }
87
+ this._shardKey = shard;
49
88
  this._fetch = opts.fetch ?? ((input, init) => fetch(input as any, init));
89
+ this._retry = {
90
+ timeoutMs: opts.retry?.timeoutMs ?? 30_000,
91
+ maxAttempts: Math.max(1, opts.retry?.maxAttempts ?? 4),
92
+ baseDelayMs: opts.retry?.baseDelayMs ?? 100,
93
+ maxDelayMs: opts.retry?.maxDelayMs ?? 2_000,
94
+ };
95
+ this._sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
96
+ }
97
+
98
+ /** The shard this instance routes to ("" = the anonymous shard). */
99
+ get shardKey(): string {
100
+ return this._shardKey;
50
101
  }
51
102
 
52
103
  /** Build an instance from environment variables. */
@@ -69,11 +120,14 @@ export class FunctionStorageCfDo implements FunctionStorage {
69
120
  * per logical ATTACH. Shares the URL/token; only the shard key differs.
70
121
  */
71
122
  forShard(shardKey: string): FunctionStorageCfDo {
123
+ if (shardKey === this._shardKey) return this;
72
124
  return new FunctionStorageCfDo({
73
125
  url: this._baseUrl,
74
126
  token: this._token,
75
127
  shardKey,
76
128
  fetch: this._fetch,
129
+ retry: this._retry,
130
+ sleep: this._sleep,
77
131
  });
78
132
  }
79
133
 
@@ -123,17 +177,30 @@ export class FunctionStorageCfDo implements FunctionStorage {
123
177
  // --- Namespaced key/value state ---
124
178
 
125
179
  async stateGet(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array): Promise<Uint8Array | null> {
180
+ return (await this.stateGetMany(scopeId, ns, [key]))[0] ?? null;
181
+ }
182
+
183
+ async statePut(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array, value: Uint8Array): Promise<void> {
184
+ await this._statePutMany(scopeId, ns, [[key, value]]);
185
+ }
186
+
187
+ async stateGetMany(scopeId: Uint8Array, ns: Uint8Array, keys: Uint8Array[]): Promise<Array<Uint8Array | null>> {
188
+ if (keys.length === 0) return [];
126
189
  const data = await this._post<{ rows: Array<{ value: string } | null> }>("state_get_many", {
127
190
  scope_id: bytesToB64(scopeId),
128
191
  ns: bytesToB64(ns),
129
- keys: [bytesToB64(key)],
192
+ keys: keys.map(bytesToB64),
193
+ });
194
+ const rows = data.rows ?? [];
195
+ return keys.map((_, i) => {
196
+ const row = rows[i];
197
+ return row ? b64ToBytes(row.value) : null;
130
198
  });
131
- const row = (data.rows ?? [])[0];
132
- return row ? b64ToBytes(row.value) : null;
133
199
  }
134
200
 
135
- async statePut(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array, value: Uint8Array): Promise<void> {
136
- await this._statePutMany(scopeId, ns, [[key, value]]);
201
+ async statePutMany(scopeId: Uint8Array, ns: Uint8Array, items: Array<[Uint8Array, Uint8Array]>): Promise<void> {
202
+ if (items.length === 0) return;
203
+ await this._statePutMany(scopeId, ns, items);
137
204
  }
138
205
 
139
206
  // --- Append-only log ---
@@ -216,6 +283,14 @@ export class FunctionStorageCfDo implements FunctionStorage {
216
283
 
217
284
  // --- HTTP plumbing ---
218
285
 
286
+ /**
287
+ * POST one call. The body (and so its `attempt_id`, for destructive ops) is
288
+ * built once and resent unchanged on every retry, so the DO's replay
289
+ * detection makes a retried put/drain/pop a no-op. Retries transport errors,
290
+ * timeouts, 5xx and 429 with exponential backoff and full jitter, bounded by
291
+ * `maxAttempts`. 4xx other than 429 is the caller's error and is not retried.
292
+ * The bearer token never appears in an error message.
293
+ */
219
294
  private async _post<T = Record<string, unknown>>(
220
295
  endpoint: string,
221
296
  body: Record<string, unknown>,
@@ -224,24 +299,73 @@ export class FunctionStorageCfDo implements FunctionStorage {
224
299
  const headers: Record<string, string> = { "Content-Type": "application/json" };
225
300
  if (this._token) headers["Authorization"] = `Bearer ${this._token}`;
226
301
  // The Worker routes on shard_key (idFromName) and rejects requests without
227
- // one — always splice it in.
228
- const payload = JSON.stringify({ ...body, shard_key: this._shardKey });
302
+ // one. An attach-bound call carries att-<uuid hex>; one bound to no ATTACH
303
+ // goes to the shared anonymous shard, as in vgi-python.
304
+ const payload = JSON.stringify({ ...body, shard_key: this._shardKey || ANONYMOUS_SHARD_KEY });
305
+
306
+ const { maxAttempts, baseDelayMs, maxDelayMs } = this._retry;
307
+ let lastErr: Error | undefined;
308
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
309
+ if (attempt > 0) {
310
+ const cap = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1));
311
+ const jittered = Math.random() * cap;
312
+ const hinted = lastErr instanceof RetryableError && lastErr.retryAfterMs != null
313
+ ? Math.min(maxDelayMs, lastErr.retryAfterMs)
314
+ : 0;
315
+ await this._sleep(Math.max(jittered, hinted));
316
+ }
317
+ try {
318
+ return await this._once<T>(url, endpoint, headers, payload);
319
+ } catch (e) {
320
+ if (!(e instanceof RetryableError)) throw e;
321
+ lastErr = e;
322
+ }
323
+ }
324
+ throw new Error(
325
+ `CF DO storage ${endpoint} failed after ${maxAttempts} attempts: ${lastErr?.message ?? "unknown error"}`,
326
+ );
327
+ }
229
328
 
230
- let lastErr: unknown;
231
- // One retry on transport-level failures, matching the python client.
232
- for (let attempt = 0; attempt < 2; attempt++) {
329
+ private async _once<T>(
330
+ url: string,
331
+ endpoint: string,
332
+ headers: Record<string, string>,
333
+ payload: string,
334
+ ): Promise<T> {
335
+ const { timeoutMs } = this._retry;
336
+ const controller = timeoutMs > 0 ? new AbortController() : null;
337
+ const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
338
+ try {
233
339
  let resp: Response;
234
340
  try {
235
- resp = await this._fetch(url, { method: "POST", headers, body: payload });
236
- } catch (err) {
237
- lastErr = err;
238
- continue;
341
+ resp = await this._fetch(url, {
342
+ method: "POST",
343
+ headers,
344
+ body: payload,
345
+ ...(controller ? { signal: controller.signal } : {}),
346
+ });
347
+ } catch (err: any) {
348
+ if (controller?.signal.aborted) {
349
+ throw new RetryableError(`timed out after ${timeoutMs} ms on ${endpoint}`);
350
+ }
351
+ throw new RetryableError(`transport error on ${endpoint}: ${err?.message ?? String(err)}`);
352
+ }
353
+
354
+ if (resp.status === 429 || resp.status >= 500) {
355
+ const text = await resp.text().catch(() => "");
356
+ throw new RetryableError(
357
+ `CF DO storage error ${resp.status} on ${endpoint}: ${text.slice(0, 200) || "<empty body>"}`,
358
+ parseRetryAfter(resp.headers?.get?.("Retry-After") ?? null),
359
+ );
239
360
  }
240
361
 
241
362
  let data: any;
242
363
  try {
243
364
  data = await resp.json();
244
- } catch {
365
+ } catch (err: any) {
366
+ if (controller?.signal.aborted) {
367
+ throw new RetryableError(`timed out after ${timeoutMs} ms reading ${endpoint}`);
368
+ }
245
369
  if (!resp.ok) {
246
370
  throw new Error(`CF DO storage error ${resp.status} on ${endpoint}: <non-json body>`);
247
371
  }
@@ -261,13 +385,19 @@ export class FunctionStorageCfDo implements FunctionStorage {
261
385
  throw new Error(`CF DO storage error ${resp.status} on ${endpoint}: ${JSON.stringify(data)}`);
262
386
  }
263
387
  return data as T;
388
+ } finally {
389
+ if (timer) clearTimeout(timer);
264
390
  }
265
- throw lastErr instanceof Error
266
- ? lastErr
267
- : new Error(`CF DO storage transport error on ${endpoint}: ${String(lastErr)}`);
268
391
  }
269
392
  }
270
393
 
394
+ /** `Retry-After` in ms (delta-seconds form only), or null. */
395
+ function parseRetryAfter(v: string | null): number | null {
396
+ if (!v) return null;
397
+ const n = Number(v.trim());
398
+ return Number.isFinite(n) && n >= 0 ? n * 1000 : null;
399
+ }
400
+
271
401
  /** Fresh 32-char lowercase-hex idempotency token (the DO's attempt_id shape). */
272
402
  function newAttemptId(): string {
273
403
  const b = new Uint8Array(16);