@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
|
@@ -0,0 +1,654 @@
|
|
|
1
|
+
// Copyright 2025, 2026 Query Farm LLC - https://query.farm
|
|
2
|
+
// Value envelope and blob-vendor externalization for any FunctionStorage.
|
|
3
|
+
// Port of vgi-python's vgi/function_storage_blobs.py; the stored bytes, the
|
|
4
|
+
// vendor scope names and the error messages are the same, so workers of one
|
|
5
|
+
// deployment written in either language read each other's values.
|
|
6
|
+
//
|
|
7
|
+
// `ExternalizingStorage` wraps a backend and stores values too large for it in
|
|
8
|
+
// the *blob vendor* (`VGI_BLOB_VENDOR_URL`), keeping only a small pointer in
|
|
9
|
+
// the backend. The FunctionStorage API does not change.
|
|
10
|
+
//
|
|
11
|
+
// Envelope (every value the wrapper writes: worker state, work-queue items,
|
|
12
|
+
// state_* values, log items):
|
|
13
|
+
//
|
|
14
|
+
// inline: 0x00 || raw
|
|
15
|
+
// pointer: 0x01 || u64be(size) || sha256(raw) (32 bytes) || object_id (ASCII)
|
|
16
|
+
//
|
|
17
|
+
// With a vendor client, a value of `threshold` bytes or more is uploaded
|
|
18
|
+
// *before* the backend call; reads fetch it back and verify size and SHA-256
|
|
19
|
+
// against the pointer. Without one every value is inline, and when the backend
|
|
20
|
+
// has a per-value cap (the Cloudflare DO's 1 MiB) a value whose envelope
|
|
21
|
+
// exceeds it is refused client-side with StorageValueTooLargeError, naming
|
|
22
|
+
// VGI_BLOB_VENDOR_URL. Decoding is strict: an empty value, an unknown tag, a
|
|
23
|
+
// truncated pointer or an object id outside the charset is a
|
|
24
|
+
// StorageEnvelopeError, as is a pointer read with no vendor configured.
|
|
25
|
+
//
|
|
26
|
+
// Where it applies (see wrapStorageFromEnv / resolveStorageFromEnv):
|
|
27
|
+
// * cloudflare-do: always wrapped, vendor or not, so the stored format never
|
|
28
|
+
// depends on a per-process environment variable.
|
|
29
|
+
// * any other backend: only with VGI_STORAGE_EXTERNALIZE=1 (which then
|
|
30
|
+
// requires the vendor). SQLite's on-disk format is unchanged by default.
|
|
31
|
+
//
|
|
32
|
+
// Clean-up: blobs are uploaded under the vendor scope (shard, "q.<hex
|
|
33
|
+
// execution id>") for queue items and (shard, "s.<hex scope id>") for state,
|
|
34
|
+
// worker state and log values. queueClear and executionClear delete the
|
|
35
|
+
// matching scope, workerCollect deletes the blobs it drained and queuePop the
|
|
36
|
+
// blob it claimed -- best effort, in the background, never on the query's
|
|
37
|
+
// critical path. stateDelete leaves blobs until the scope is cleared. The
|
|
38
|
+
// vendor's idle sweep and the bucket lifecycle rules are the backstop.
|
|
39
|
+
//
|
|
40
|
+
// Errors follow the SDK-neutral contract in the vgi extension's
|
|
41
|
+
// docs/testing/blob-test-catalog.md:
|
|
42
|
+
// StorageBlobIntegrityError "storage blob <id> failed its integrity check: sha256 mismatch" / "... size mismatch ..."
|
|
43
|
+
// StorageBlobMissingError "storage blob <id> is missing: not found in the blob vendor (expired or deleted?)"
|
|
44
|
+
// StorageBlobError "storage blob <id> could not be read: <detail>"
|
|
45
|
+
//
|
|
46
|
+
// Runtime-agnostic (fetch + Web Crypto through vgi-rpc's VendorBlobClient), so
|
|
47
|
+
// it wraps the Durable Object client on Cloudflare Workers as well as SQLite on
|
|
48
|
+
// Bun/Node.
|
|
49
|
+
|
|
50
|
+
import { VendorBlobClient, VendorError, type BlobRef, type BlobScope } from "@query-farm/vgi-rpc";
|
|
51
|
+
import type { FunctionStorage, WorkerStateKey } from "./storage.js";
|
|
52
|
+
|
|
53
|
+
/** Values of at least this many bytes go to the blob vendor (default). */
|
|
54
|
+
export const DEFAULT_EXTERNALIZE_BYTES = 512 * 1024;
|
|
55
|
+
/** Largest blob a read will fetch (the vendor's per-object cap). */
|
|
56
|
+
export const MAX_BLOB_BYTES = 4 * 1024 ** 3;
|
|
57
|
+
|
|
58
|
+
export const ENV_VENDOR_URL = "VGI_BLOB_VENDOR_URL";
|
|
59
|
+
export const ENV_VENDOR_TOKEN = "VGI_BLOB_VENDOR_TOKEN";
|
|
60
|
+
export const ENV_EXTERNALIZE = "VGI_STORAGE_EXTERNALIZE";
|
|
61
|
+
export const ENV_EXTERNALIZE_BYTES = "VGI_STORAGE_EXTERNALIZE_BYTES";
|
|
62
|
+
export const ENV_EXTERNALIZE_BYTES_ALIAS = "VGI_CF_DO_EXTERNALIZE_BYTES";
|
|
63
|
+
|
|
64
|
+
export const TAG_INLINE = 0x00;
|
|
65
|
+
export const TAG_POINTER = 0x01;
|
|
66
|
+
/** Tag + u64 size + 32-byte SHA-256: the pointer's fixed part. */
|
|
67
|
+
export const POINTER_FIXED_BYTES = 1 + 8 + 32;
|
|
68
|
+
const OBJECT_ID_RE = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
69
|
+
// The vendor's scope.shard charset; shard keys outside it are hashed.
|
|
70
|
+
const SHARD_RE = /^[A-Za-z0-9._-]{1,128}$/;
|
|
71
|
+
/** Concurrent vendor transfers per storage call. */
|
|
72
|
+
const TRANSFER_PARALLELISM = 8;
|
|
73
|
+
const TRUE_VALUES = new Set(["1", "true", "yes", "on"]);
|
|
74
|
+
|
|
75
|
+
type Env = Readonly<Record<string, string | undefined>>;
|
|
76
|
+
|
|
77
|
+
function processEnv(): Env {
|
|
78
|
+
return (globalThis as { process?: { env?: Env } }).process?.env ?? {};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// ============================================================================
|
|
82
|
+
// Errors
|
|
83
|
+
// ============================================================================
|
|
84
|
+
|
|
85
|
+
/** A value read from storage is not a valid envelope (empty, unknown tag,
|
|
86
|
+
* malformed pointer), or is a pointer read with no blob vendor configured. */
|
|
87
|
+
export class StorageEnvelopeError extends Error {
|
|
88
|
+
constructor(message: string) {
|
|
89
|
+
super(message);
|
|
90
|
+
this.name = "StorageEnvelopeError";
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** An externalized storage value's blob could not be read. The message starts
|
|
95
|
+
* `storage blob <object id>`. */
|
|
96
|
+
export class StorageBlobError extends Error {
|
|
97
|
+
constructor(message: string) {
|
|
98
|
+
super(message);
|
|
99
|
+
this.name = "StorageBlobError";
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The downloaded blob does not match the pointer's size or SHA-256. */
|
|
104
|
+
export class StorageBlobIntegrityError extends StorageBlobError {
|
|
105
|
+
constructor(message: string) {
|
|
106
|
+
super(message);
|
|
107
|
+
this.name = "StorageBlobIntegrityError";
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The blob is gone from the vendor or its storage (expired, deleted, never uploaded). */
|
|
112
|
+
export class StorageBlobMissingError extends StorageBlobError {
|
|
113
|
+
constructor(message: string) {
|
|
114
|
+
super(message);
|
|
115
|
+
this.name = "StorageBlobMissingError";
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** A value is too large for the backend and no blob vendor is configured. */
|
|
120
|
+
export class StorageValueTooLargeError extends Error {
|
|
121
|
+
constructor(message: string) {
|
|
122
|
+
super(message);
|
|
123
|
+
this.name = "StorageValueTooLargeError";
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const MISSING_CODES = new Set(["not_found", "not_uploaded", "NoSuchKey"]);
|
|
128
|
+
|
|
129
|
+
/** Map a vendor client failure onto the storage-blob error contract. */
|
|
130
|
+
function blobReadError(ref: BlobRef, error: unknown): StorageBlobError {
|
|
131
|
+
const code = error instanceof VendorError ? error.code : null;
|
|
132
|
+
const status = error instanceof VendorError ? error.status : null;
|
|
133
|
+
if (code === "sha256_mismatch") {
|
|
134
|
+
return new StorageBlobIntegrityError(`storage blob ${ref.objectId} failed its integrity check: sha256 mismatch`);
|
|
135
|
+
}
|
|
136
|
+
if (code === "size_mismatch") {
|
|
137
|
+
return new StorageBlobIntegrityError(
|
|
138
|
+
`storage blob ${ref.objectId} failed its integrity check: size mismatch (expected ${ref.size} bytes)`,
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
if (status === 404 || (code !== null && MISSING_CODES.has(code))) {
|
|
142
|
+
return new StorageBlobMissingError(
|
|
143
|
+
`storage blob ${ref.objectId} is missing: not found in the blob vendor (expired or deleted?)`,
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
return new StorageBlobError(
|
|
147
|
+
`storage blob ${ref.objectId} could not be read: ${(error as Error)?.message ?? String(error)}`,
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// ============================================================================
|
|
152
|
+
// Envelope
|
|
153
|
+
// ============================================================================
|
|
154
|
+
|
|
155
|
+
function hexToBytes(hex: string): Uint8Array {
|
|
156
|
+
if (!/^[0-9a-fA-F]*$/.test(hex) || hex.length % 2 !== 0) throw new Error(`not hex: ${hex}`);
|
|
157
|
+
const out = new Uint8Array(hex.length / 2);
|
|
158
|
+
for (let i = 0; i < out.length; i++) out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
159
|
+
return out;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function bytesToHex(bytes: Uint8Array): string {
|
|
163
|
+
let s = "";
|
|
164
|
+
for (let i = 0; i < bytes.length; i++) s += bytes[i]!.toString(16).padStart(2, "0");
|
|
165
|
+
return s;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async function sha256Hex(data: Uint8Array): Promise<string> {
|
|
169
|
+
const copy = new Uint8Array(data.byteLength);
|
|
170
|
+
copy.set(data);
|
|
171
|
+
return bytesToHex(new Uint8Array(await crypto.subtle.digest("SHA-256", copy.buffer)));
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** The inline envelope of `value`: `0x00 || value`. */
|
|
175
|
+
export function encodeInline(value: Uint8Array): Uint8Array {
|
|
176
|
+
const out = new Uint8Array(value.byteLength + 1);
|
|
177
|
+
out[0] = TAG_INLINE;
|
|
178
|
+
out.set(value, 1);
|
|
179
|
+
return out;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* The pointer envelope for a vendored blob:
|
|
184
|
+
* `0x01 || u64be(size) || sha256 || object_id`.
|
|
185
|
+
* @throws Error if the object id is outside `[A-Za-z0-9._:-]{1,128}`.
|
|
186
|
+
*/
|
|
187
|
+
export function encodePointer(ref: BlobRef): Uint8Array {
|
|
188
|
+
if (!OBJECT_ID_RE.test(ref.objectId)) {
|
|
189
|
+
throw new Error(`blob vendor returned an unusable object id ${JSON.stringify(ref.objectId)}`);
|
|
190
|
+
}
|
|
191
|
+
const digest = hexToBytes(ref.sha256);
|
|
192
|
+
if (digest.length !== 32) throw new Error("blob sha256 must be 32 bytes of hex");
|
|
193
|
+
const id = new TextEncoder().encode(ref.objectId);
|
|
194
|
+
const out = new Uint8Array(POINTER_FIXED_BYTES + id.length);
|
|
195
|
+
out[0] = TAG_POINTER;
|
|
196
|
+
new DataView(out.buffer).setBigUint64(1, BigInt(ref.size), false);
|
|
197
|
+
out.set(digest, 9);
|
|
198
|
+
out.set(id, POINTER_FIXED_BYTES);
|
|
199
|
+
return out;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Parse a pointer envelope (tag 0x01).
|
|
203
|
+
* @throws StorageEnvelopeError if it is truncated or its object id is malformed. */
|
|
204
|
+
export function decodePointer(envelope: Uint8Array): BlobRef {
|
|
205
|
+
const idBytes = envelope.subarray(POINTER_FIXED_BYTES);
|
|
206
|
+
let objectId = "";
|
|
207
|
+
for (let i = 0; i < idBytes.length; i++) objectId += String.fromCharCode(idBytes[i]!);
|
|
208
|
+
if (envelope.length <= POINTER_FIXED_BYTES || !OBJECT_ID_RE.test(objectId)) {
|
|
209
|
+
throw new StorageEnvelopeError(`malformed blob pointer in stored value (${envelope.length} bytes)`);
|
|
210
|
+
}
|
|
211
|
+
const view = new DataView(envelope.buffer, envelope.byteOffset, envelope.byteLength);
|
|
212
|
+
return {
|
|
213
|
+
objectId,
|
|
214
|
+
size: Number(view.getBigUint64(1, false)),
|
|
215
|
+
sha256: bytesToHex(envelope.subarray(9, POINTER_FIXED_BYTES)),
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** The envelope's tag.
|
|
220
|
+
* @throws StorageEnvelopeError for an empty value or an unknown tag. */
|
|
221
|
+
export function envelopeTag(envelope: Uint8Array): number {
|
|
222
|
+
if (envelope.length === 0) {
|
|
223
|
+
throw new StorageEnvelopeError("empty stored value: not a value envelope (written without the envelope?)");
|
|
224
|
+
}
|
|
225
|
+
const tag = envelope[0]!;
|
|
226
|
+
if (tag !== TAG_INLINE && tag !== TAG_POINTER) {
|
|
227
|
+
throw new StorageEnvelopeError(
|
|
228
|
+
`stored value has unknown envelope tag 0x${tag.toString(16).padStart(2, "0")} (written by an older client or ` +
|
|
229
|
+
"without the envelope? mixing client versions within one query is not supported)",
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
return tag;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Vendor `scope.execution_id` for one queue (`q`) or state scope (`s`):
|
|
236
|
+
* `<kind>.<hex ident>`, or `<kind>.h<hex sha256(ident)>` past 128 characters. */
|
|
237
|
+
export async function blobExecutionId(kind: "q" | "s", ident: Uint8Array): Promise<string> {
|
|
238
|
+
const text = `${kind}.${bytesToHex(ident)}`;
|
|
239
|
+
if (text.length <= 128) return text;
|
|
240
|
+
return `${kind}.h${await sha256Hex(ident)}`;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** Vendor `scope.shard` for a storage shard key: empty becomes `loc-anon`; a key
|
|
244
|
+
* outside `[A-Za-z0-9._-]{1,128}` becomes `h-<hex sha256(utf8 key)>`. */
|
|
245
|
+
export async function blobShard(shardKey: string): Promise<string> {
|
|
246
|
+
const shard = shardKey || "loc-anon";
|
|
247
|
+
if (SHARD_RE.test(shard)) return shard;
|
|
248
|
+
return `h-${await sha256Hex(new TextEncoder().encode(shard))}`;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
async function parallelMap<T, R>(items: readonly T[], fn: (item: T) => Promise<R>): Promise<R[]> {
|
|
252
|
+
if (items.length <= 1) return Promise.all(items.map(fn));
|
|
253
|
+
const out = new Array<R>(items.length);
|
|
254
|
+
let next = 0;
|
|
255
|
+
const workers = Array.from({ length: Math.min(TRANSFER_PARALLELISM, items.length) }, async () => {
|
|
256
|
+
for (;;) {
|
|
257
|
+
const i = next++;
|
|
258
|
+
if (i >= items.length) return;
|
|
259
|
+
out[i] = await fn(items[i]!);
|
|
260
|
+
}
|
|
261
|
+
});
|
|
262
|
+
await Promise.all(workers);
|
|
263
|
+
return out;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function newCallId(): string {
|
|
267
|
+
const b = new Uint8Array(16);
|
|
268
|
+
crypto.getRandomValues(b);
|
|
269
|
+
return bytesToHex(b);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// ============================================================================
|
|
273
|
+
// Environment
|
|
274
|
+
// ============================================================================
|
|
275
|
+
|
|
276
|
+
/** Read `VGI_STORAGE_EXTERNALIZE_BYTES` (alias `VGI_CF_DO_EXTERNALIZE_BYTES`);
|
|
277
|
+
* {@link DEFAULT_EXTERNALIZE_BYTES} when unset.
|
|
278
|
+
* @throws Error if the value is not a positive integer. */
|
|
279
|
+
export function externalizeBytesFromEnv(env: Env = processEnv()): number {
|
|
280
|
+
for (const name of [ENV_EXTERNALIZE_BYTES, ENV_EXTERNALIZE_BYTES_ALIAS]) {
|
|
281
|
+
const raw = (env[name] ?? "").trim();
|
|
282
|
+
if (!raw) continue;
|
|
283
|
+
if (!/^[+-]?\d+$/.test(raw)) throw new Error(`${name} must be an integer, got ${JSON.stringify(raw)}`);
|
|
284
|
+
const value = Number(raw);
|
|
285
|
+
if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`${name} must be positive, got ${value}`);
|
|
286
|
+
return value;
|
|
287
|
+
}
|
|
288
|
+
return DEFAULT_EXTERNALIZE_BYTES;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** The vendor client from `VGI_BLOB_VENDOR_URL` and its token (falling back to
|
|
292
|
+
* `VGI_CF_DO_TOKEN`), or `null` when the URL is unset.
|
|
293
|
+
* @throws Error if the URL is set but no token is. */
|
|
294
|
+
export function blobClientFromEnv(env: Env = processEnv()): VendorBlobClient | null {
|
|
295
|
+
const url = (env[ENV_VENDOR_URL] ?? "").trim();
|
|
296
|
+
if (!url) return null;
|
|
297
|
+
const token = (env[ENV_VENDOR_TOKEN] ?? "").trim() || (env.VGI_CF_DO_TOKEN ?? "").trim();
|
|
298
|
+
if (!token) throw new Error(`${ENV_VENDOR_URL} is set but neither ${ENV_VENDOR_TOKEN} nor VGI_CF_DO_TOKEN is`);
|
|
299
|
+
return new VendorBlobClient(url, token, { purpose: "fs", maxFetchBytes: MAX_BLOB_BYTES });
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** Options for {@link wrapStorageFromEnv}. */
|
|
303
|
+
export interface WrapStorageOptions {
|
|
304
|
+
/** The backend's per-value cap, or undefined for none. A backend with a cap
|
|
305
|
+
* (the Cloudflare DO) is always wrapped. */
|
|
306
|
+
maxValueBytes?: number | undefined;
|
|
307
|
+
/** Environment source (default `process.env`; on Cloudflare Workers pass the
|
|
308
|
+
* Worker's `env`). */
|
|
309
|
+
env?: Env | undefined;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* Wrap `base` in {@link ExternalizingStorage} when the environment asks for it.
|
|
314
|
+
*
|
|
315
|
+
* A backend with a per-value cap (`maxValueBytes`, i.e. the Cloudflare DO) is
|
|
316
|
+
* always wrapped, vendor or not, so its stored format is the same in every
|
|
317
|
+
* process. Any other backend is wrapped only with `VGI_STORAGE_EXTERNALIZE=1`,
|
|
318
|
+
* which then requires `VGI_BLOB_VENDOR_URL`. An already-wrapped backend is
|
|
319
|
+
* returned unchanged.
|
|
320
|
+
*
|
|
321
|
+
* @throws Error for `VGI_STORAGE_EXTERNALIZE=1` without a vendor, or a malformed variable.
|
|
322
|
+
*/
|
|
323
|
+
export function wrapStorageFromEnv(base: FunctionStorage, options: WrapStorageOptions = {}): FunctionStorage {
|
|
324
|
+
if (base instanceof ExternalizingStorage) return base;
|
|
325
|
+
const env = options.env ?? processEnv();
|
|
326
|
+
const enabled = TRUE_VALUES.has((env[ENV_EXTERNALIZE] ?? "").trim().toLowerCase());
|
|
327
|
+
const maxValueBytes = options.maxValueBytes;
|
|
328
|
+
if (maxValueBytes === undefined && !enabled) return base;
|
|
329
|
+
const blobs = blobClientFromEnv(env);
|
|
330
|
+
if (enabled && blobs === null) {
|
|
331
|
+
throw new Error(`${ENV_EXTERNALIZE}=1 needs the blob vendor: set ${ENV_VENDOR_URL}`);
|
|
332
|
+
}
|
|
333
|
+
let threshold = externalizeBytesFromEnv(env);
|
|
334
|
+
if (maxValueBytes !== undefined) threshold = Math.min(threshold, maxValueBytes);
|
|
335
|
+
return new ExternalizingStorage(base, { blobClient: blobs, threshold, maxValueBytes });
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// ============================================================================
|
|
339
|
+
// The wrapper
|
|
340
|
+
// ============================================================================
|
|
341
|
+
|
|
342
|
+
/** Options for {@link ExternalizingStorage}. */
|
|
343
|
+
export interface ExternalizingStorageOptions {
|
|
344
|
+
/** The vendor client, or null to keep every value inline. */
|
|
345
|
+
blobClient: VendorBlobClient | null;
|
|
346
|
+
/** With a vendor, values of at least this many bytes are stored as blobs
|
|
347
|
+
* (default {@link DEFAULT_EXTERNALIZE_BYTES}). */
|
|
348
|
+
threshold?: number | undefined;
|
|
349
|
+
/** The backend's per-value cap. The envelope of an inline value must fit, so
|
|
350
|
+
* `threshold` may not exceed it; with no vendor, an over-cap value raises
|
|
351
|
+
* {@link StorageValueTooLargeError}. */
|
|
352
|
+
maxValueBytes?: number | undefined;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** State one wrapper shares with its per-shard views. */
|
|
356
|
+
interface SharedState {
|
|
357
|
+
readonly blobs: VendorBlobClient | null;
|
|
358
|
+
readonly threshold: number;
|
|
359
|
+
readonly maxValueBytes: number | undefined;
|
|
360
|
+
readonly pending: Set<Promise<void>>;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* A FunctionStorage that envelopes values and externalizes large ones to the
|
|
365
|
+
* blob vendor. Delegates every operation to the wrapped backend; see the module
|
|
366
|
+
* header for the envelope, scoping and clean-up.
|
|
367
|
+
*/
|
|
368
|
+
export class ExternalizingStorage implements FunctionStorage {
|
|
369
|
+
private readonly _base: FunctionStorage;
|
|
370
|
+
private readonly _shared: SharedState;
|
|
371
|
+
private readonly _shardKey: string;
|
|
372
|
+
|
|
373
|
+
/** @throws Error if `threshold` is not positive or exceeds `maxValueBytes`. */
|
|
374
|
+
constructor(base: FunctionStorage, options: ExternalizingStorageOptions);
|
|
375
|
+
/** @internal A per-shard view sharing the vendor client and clean-up. */
|
|
376
|
+
constructor(base: FunctionStorage, options: ExternalizingStorageOptions, shared: SharedState, shardKey: string);
|
|
377
|
+
constructor(base: FunctionStorage, options: ExternalizingStorageOptions, shared?: SharedState, shardKey = "") {
|
|
378
|
+
this._base = base;
|
|
379
|
+
this._shardKey = shardKey;
|
|
380
|
+
if (shared) {
|
|
381
|
+
this._shared = shared;
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
const threshold = options.threshold ?? DEFAULT_EXTERNALIZE_BYTES;
|
|
385
|
+
const max = options.maxValueBytes;
|
|
386
|
+
if (!Number.isSafeInteger(threshold) || threshold < 1 || (max !== undefined && threshold > max)) {
|
|
387
|
+
throw new Error(
|
|
388
|
+
`externalize threshold (${ENV_EXTERNALIZE_BYTES}) must be between 1 and ` +
|
|
389
|
+
`${max !== undefined ? max : "unbounded"}, got ${threshold}`,
|
|
390
|
+
);
|
|
391
|
+
}
|
|
392
|
+
this._shared = { blobs: options.blobClient, threshold, maxValueBytes: max, pending: new Set() };
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** The wrapped backend. */
|
|
396
|
+
get base(): FunctionStorage {
|
|
397
|
+
return this._base;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** The vendor client, if any. */
|
|
401
|
+
get blobClient(): VendorBlobClient | null {
|
|
402
|
+
return this._shared.blobs;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** Values of at least this many bytes are externalized (with a vendor). */
|
|
406
|
+
get threshold(): number {
|
|
407
|
+
return this._shared.threshold;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** The shard this view routes to ("" = not bound to an ATTACH). */
|
|
411
|
+
get shardKey(): string {
|
|
412
|
+
return this._shardKey;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** A view routed to one attach shard (the wrapped backend's own view when it
|
|
416
|
+
* shards remotely), sharing the vendor client and clean-up. */
|
|
417
|
+
forShard(shardKey: string): ExternalizingStorage {
|
|
418
|
+
if (shardKey === this._shardKey) return this;
|
|
419
|
+
const base = typeof this._base.forShard === "function" ? this._base.forShard(shardKey) : this._base;
|
|
420
|
+
return new ExternalizingStorage(base, { blobClient: null }, this._shared, shardKey);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/** Wait for pending background blob clean-up, then close the backend. */
|
|
424
|
+
async close(): Promise<void> {
|
|
425
|
+
await this.flushBlobCleanup();
|
|
426
|
+
await this._base.close?.();
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// --- encode / decode -----------------------------------------------------
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* Envelope each value, uploading large ones first. Each upload carries the
|
|
433
|
+
* idempotency key `<call id>.<index>`, so a vendor-level retry of the same
|
|
434
|
+
* logical write reuses the object.
|
|
435
|
+
*/
|
|
436
|
+
async encodeValues(values: readonly Uint8Array[], blobExecId: string): Promise<Uint8Array[]> {
|
|
437
|
+
const { blobs, threshold, maxValueBytes } = this._shared;
|
|
438
|
+
const large: number[] = [];
|
|
439
|
+
const envelopes: Array<Uint8Array | null> = values.map((v, i) => {
|
|
440
|
+
if (blobs !== null && v.byteLength >= threshold) {
|
|
441
|
+
large.push(i);
|
|
442
|
+
return null;
|
|
443
|
+
}
|
|
444
|
+
return encodeInline(v);
|
|
445
|
+
});
|
|
446
|
+
if (blobs === null && maxValueBytes !== undefined) {
|
|
447
|
+
for (const env of envelopes) {
|
|
448
|
+
if (env !== null && env.byteLength > maxValueBytes) {
|
|
449
|
+
throw new StorageValueTooLargeError(
|
|
450
|
+
`storage value of ${env.byteLength - 1} bytes exceeds the backend's ${maxValueBytes}-byte limit; ` +
|
|
451
|
+
`set ${ENV_VENDOR_URL} (the blob vendor) so large values are stored as blobs`,
|
|
452
|
+
);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
if (large.length > 0 && blobs !== null) {
|
|
457
|
+
const callId = newCallId();
|
|
458
|
+
const scope: BlobScope = { shard: await blobShard(this._shardKey), executionId: blobExecId };
|
|
459
|
+
const pointers = await parallelMap(large, async (i) =>
|
|
460
|
+
encodePointer(await blobs.putBytes(values[i]!, { scope, idempotencyKey: `${callId}.${i}` })),
|
|
461
|
+
);
|
|
462
|
+
large.forEach((i, j) => {
|
|
463
|
+
envelopes[i] = pointers[j]!;
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
return envelopes as Uint8Array[];
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* Decode envelopes, fetching pointers in parallel (null passes through).
|
|
471
|
+
* @param refsOut When given, receives the blob references that were read.
|
|
472
|
+
* @throws StorageEnvelopeError for an invalid envelope or a pointer read with
|
|
473
|
+
* no vendor configured; StorageBlobError (or a subclass) when a pointer's
|
|
474
|
+
* blob is missing, fails its size or SHA-256 check, or cannot be fetched.
|
|
475
|
+
*/
|
|
476
|
+
async decodeValues(envelopes: ReadonlyArray<Uint8Array | null>, refsOut?: BlobRef[]): Promise<Array<Uint8Array | null>> {
|
|
477
|
+
const pointers: number[] = [];
|
|
478
|
+
const out: Array<Uint8Array | null> = envelopes.map((env, i) => {
|
|
479
|
+
if (env === null) return null;
|
|
480
|
+
if (envelopeTag(env) === TAG_POINTER) {
|
|
481
|
+
pointers.push(i);
|
|
482
|
+
return null;
|
|
483
|
+
}
|
|
484
|
+
return env.slice(1);
|
|
485
|
+
});
|
|
486
|
+
if (pointers.length === 0) return out;
|
|
487
|
+
const blobs = this._shared.blobs;
|
|
488
|
+
if (blobs === null) {
|
|
489
|
+
throw new StorageEnvelopeError(
|
|
490
|
+
`stored value is a blob pointer but ${ENV_VENDOR_URL} is not configured in this process`,
|
|
491
|
+
);
|
|
492
|
+
}
|
|
493
|
+
const refs = pointers.map((i) => decodePointer(envelopes[i]!));
|
|
494
|
+
const data = await parallelMap(refs, async (ref) => {
|
|
495
|
+
try {
|
|
496
|
+
return await blobs.getBytes(ref);
|
|
497
|
+
} catch (error) {
|
|
498
|
+
throw blobReadError(ref, error);
|
|
499
|
+
}
|
|
500
|
+
});
|
|
501
|
+
pointers.forEach((i, j) => {
|
|
502
|
+
out[i] = data[j]!;
|
|
503
|
+
});
|
|
504
|
+
refsOut?.push(...refs);
|
|
505
|
+
return out;
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
private async decodeAll(envelopes: readonly Uint8Array[], refsOut?: BlobRef[]): Promise<Uint8Array[]> {
|
|
509
|
+
return (await this.decodeValues(envelopes, refsOut)) as Uint8Array[];
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
// --- background clean-up -------------------------------------------------
|
|
513
|
+
|
|
514
|
+
private submitCleanup(fn: () => Promise<unknown>, what: string): void {
|
|
515
|
+
const pending = this._shared.pending;
|
|
516
|
+
const task: Promise<void> = fn()
|
|
517
|
+
.then(() => undefined)
|
|
518
|
+
.catch((error) => {
|
|
519
|
+
console.warn(`blob vendor clean-up after ${what} failed: ${(error as Error)?.message ?? error}`);
|
|
520
|
+
})
|
|
521
|
+
.finally(() => {
|
|
522
|
+
pending.delete(task);
|
|
523
|
+
});
|
|
524
|
+
pending.add(task);
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/** Wait for pending background blob clean-up (for tests and shutdown). */
|
|
528
|
+
async flushBlobCleanup(): Promise<void> {
|
|
529
|
+
while (this._shared.pending.size > 0) {
|
|
530
|
+
await Promise.all([...this._shared.pending]);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
private deleteBlobs(refs: BlobRef[], what: string): void {
|
|
535
|
+
const blobs = this._shared.blobs;
|
|
536
|
+
if (blobs === null || refs.length === 0) return;
|
|
537
|
+
this.submitCleanup(() => blobs.delete(refs), what);
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
private deleteBlobScope(kind: "q" | "s", ident: Uint8Array, what: string): void {
|
|
541
|
+
const blobs = this._shared.blobs;
|
|
542
|
+
if (blobs === null) return;
|
|
543
|
+
const shardKey = this._shardKey;
|
|
544
|
+
this.submitCleanup(
|
|
545
|
+
async () => blobs.deleteScope(await blobShard(shardKey), await blobExecutionId(kind, ident)),
|
|
546
|
+
what,
|
|
547
|
+
);
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
// --- FunctionStorage -----------------------------------------------------
|
|
551
|
+
|
|
552
|
+
async workerPut(executionId: Uint8Array, worker: WorkerStateKey, state: Uint8Array): Promise<void> {
|
|
553
|
+
const [encoded] = await this.encodeValues([state], await blobExecutionId("s", executionId));
|
|
554
|
+
await this._base.workerPut(executionId, worker, encoded!);
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/** Drain and decode; the drained blobs are deleted in the background. */
|
|
558
|
+
async workerCollect(executionId: Uint8Array): Promise<Uint8Array[]> {
|
|
559
|
+
const drained: BlobRef[] = [];
|
|
560
|
+
const values = await this.decodeAll(await this._base.workerCollect(executionId), drained);
|
|
561
|
+
this.deleteBlobs(drained, "workerCollect");
|
|
562
|
+
return values;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
async workerScan(executionId: Uint8Array): Promise<Array<[number, Uint8Array]>> {
|
|
566
|
+
const rows = await this._base.workerScan(executionId);
|
|
567
|
+
const values = await this.decodeAll(rows.map(([, v]) => v));
|
|
568
|
+
return rows.map(([id], i) => [id, values[i]!]);
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
async queuePush(executionId: Uint8Array, items: Uint8Array[]): Promise<number> {
|
|
572
|
+
const encoded = await this.encodeValues(items, await blobExecutionId("q", executionId));
|
|
573
|
+
return this._base.queuePush(executionId, encoded);
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/** Pop one item; its blob, if any, is deleted once fetched. */
|
|
577
|
+
async queuePop(executionId: Uint8Array): Promise<Uint8Array | null> {
|
|
578
|
+
const env = await this._base.queuePop(executionId);
|
|
579
|
+
if (env === null) return null;
|
|
580
|
+
const claimed: BlobRef[] = [];
|
|
581
|
+
const [value] = await this.decodeValues([env], claimed);
|
|
582
|
+
this.deleteBlobs(claimed, "queuePop");
|
|
583
|
+
return value ?? null;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/** Clear the queue and delete its blob scope. */
|
|
587
|
+
async queueClear(executionId: Uint8Array): Promise<number> {
|
|
588
|
+
const cleared = await this._base.queueClear(executionId);
|
|
589
|
+
this.deleteBlobScope("q", executionId, "queueClear");
|
|
590
|
+
return cleared;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
async stateGet(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array): Promise<Uint8Array | null> {
|
|
594
|
+
const env = await this._base.stateGet(scopeId, ns, key);
|
|
595
|
+
return env === null ? null : ((await this.decodeValues([env]))[0] ?? null);
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
async statePut(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array, value: Uint8Array): Promise<void> {
|
|
599
|
+
const [encoded] = await this.encodeValues([value], await blobExecutionId("s", scopeId));
|
|
600
|
+
await this._base.statePut(scopeId, ns, key, encoded!);
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
async stateGetMany(scopeId: Uint8Array, ns: Uint8Array, keys: Uint8Array[]): Promise<Array<Uint8Array | null>> {
|
|
604
|
+
return this.decodeValues(await this._base.stateGetMany(scopeId, ns, keys));
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
async statePutMany(scopeId: Uint8Array, ns: Uint8Array, items: Array<[Uint8Array, Uint8Array]>): Promise<void> {
|
|
608
|
+
if (items.length === 0) {
|
|
609
|
+
await this._base.statePutMany(scopeId, ns, items);
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
const encoded = await this.encodeValues(
|
|
613
|
+
items.map(([, v]) => v),
|
|
614
|
+
await blobExecutionId("s", scopeId),
|
|
615
|
+
);
|
|
616
|
+
await this._base.statePutMany(
|
|
617
|
+
scopeId,
|
|
618
|
+
ns,
|
|
619
|
+
items.map(([k], i) => [k, encoded[i]!]),
|
|
620
|
+
);
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/** Delete rows (their blobs stay until the scope is cleared). */
|
|
624
|
+
async stateDelete(scopeId: Uint8Array, ns: Uint8Array, keys: Uint8Array[]): Promise<number> {
|
|
625
|
+
if (typeof this._base.stateDelete !== "function") {
|
|
626
|
+
throw new Error("the wrapped storage backend does not implement stateDelete");
|
|
627
|
+
}
|
|
628
|
+
return this._base.stateDelete(scopeId, ns, keys);
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
async stateAppend(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array, item: Uint8Array): Promise<number> {
|
|
632
|
+
const [encoded] = await this.encodeValues([item], await blobExecutionId("s", scopeId));
|
|
633
|
+
return this._base.stateAppend(scopeId, ns, key, encoded!);
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
async stateLogScan(
|
|
637
|
+
scopeId: Uint8Array,
|
|
638
|
+
ns: Uint8Array,
|
|
639
|
+
key: Uint8Array,
|
|
640
|
+
afterId: number = -1,
|
|
641
|
+
limit: number | null = null,
|
|
642
|
+
): Promise<Array<[number, Uint8Array]>> {
|
|
643
|
+
const rows = await this._base.stateLogScan(scopeId, ns, key, afterId, limit);
|
|
644
|
+
const values = await this.decodeAll(rows.map(([, v]) => v));
|
|
645
|
+
return rows.map(([id], i) => [id, values[i]!]);
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
/** Clear the scope and delete its blob scope. */
|
|
649
|
+
async executionClear(scopeId: Uint8Array): Promise<number> {
|
|
650
|
+
const deleted = await this._base.executionClear(scopeId);
|
|
651
|
+
this.deleteBlobScope("s", scopeId, "executionClear");
|
|
652
|
+
return deleted;
|
|
653
|
+
}
|
|
654
|
+
}
|