@query-farm/vgi 0.48.3 → 0.48.5

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 (50) hide show
  1. package/README.md +51 -0
  2. package/dist/attach-secret-keyfile.d.ts +11 -0
  3. package/dist/attach-secret-options.d.ts +96 -0
  4. package/dist/catalog/attach-option.d.ts +6 -0
  5. package/dist/catalog/descriptors.d.ts +30 -0
  6. package/dist/catalog/interface.d.ts +43 -0
  7. package/dist/catalog/read-only.d.ts +16 -2
  8. package/dist/client-entry.js +1 -1
  9. package/dist/client-entry.js.map +4 -4
  10. package/dist/index.core.d.ts +4 -0
  11. package/dist/index.js +5854 -5234
  12. package/dist/index.js.map +28 -25
  13. package/dist/protocol/dispatch.d.ts +11 -0
  14. package/dist/protocol/handlers/catalog/admin.d.ts +1 -1
  15. package/dist/protocol/handlers/catalog/index.d.ts +1 -1
  16. package/dist/protocol/handlers/catalog/index_methods.d.ts +1 -1
  17. package/dist/protocol/handlers/catalog/macro.d.ts +1 -1
  18. package/dist/protocol/handlers/catalog/shared.d.ts +36 -3
  19. package/dist/protocol/handlers/catalog/table.d.ts +1 -1
  20. package/dist/protocol/handlers/catalog/view.d.ts +1 -1
  21. package/dist/protocol/handlers/function.d.ts +2 -0
  22. package/dist/protocol/handlers/table-buffering.d.ts +1 -1
  23. package/dist/serve-entry.d.ts +5 -0
  24. package/dist/serve-entry.js +514 -99
  25. package/dist/serve-entry.js.map +18 -16
  26. package/dist/worker-cf-entry.js +629 -108
  27. package/dist/worker-cf-entry.js.map +21 -18
  28. package/dist/worker.d.ts +10 -0
  29. package/dist/write-results.d.ts +57 -0
  30. package/package.json +1 -1
  31. package/src/attach-secret-keyfile.ts +185 -0
  32. package/src/attach-secret-options.ts +418 -0
  33. package/src/catalog/attach-option.ts +6 -0
  34. package/src/catalog/descriptors.ts +30 -0
  35. package/src/catalog/interface.ts +70 -0
  36. package/src/catalog/read-only.ts +123 -18
  37. package/src/index.core.ts +33 -0
  38. package/src/protocol/dispatch.ts +14 -2
  39. package/src/protocol/handlers/catalog/admin.ts +33 -18
  40. package/src/protocol/handlers/catalog/index.ts +6 -5
  41. package/src/protocol/handlers/catalog/index_methods.ts +5 -3
  42. package/src/protocol/handlers/catalog/macro.ts +7 -5
  43. package/src/protocol/handlers/catalog/shared.ts +69 -6
  44. package/src/protocol/handlers/catalog/table.ts +58 -19
  45. package/src/protocol/handlers/catalog/view.ts +9 -7
  46. package/src/protocol/handlers/function.ts +53 -19
  47. package/src/protocol/handlers/table-buffering.ts +2 -1
  48. package/src/serve-entry.ts +6 -1
  49. package/src/worker.ts +12 -0
  50. package/src/write-results.ts +174 -0
@@ -0,0 +1,418 @@
1
+ // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
+ // SPDX-License-Identifier: LicenseRef-QueryFarm-Source-Available-1.0
3
+
4
+ // Framework-owned delivery of ATTACH options to functions and transaction
5
+ // hooks — secret ones (`AttachOptionSpec.secret`) encrypted with a key the
6
+ // client never has.
7
+ //
8
+ // The client hands `attach_opaque_data` back on every function call and hook,
9
+ // so the attach value is the only thing that can carry an option from
10
+ // `catalog_attach` to a later call: a catalog_attach and the function calls of
11
+ // its queries may run in different worker processes (launcher pools, HTTP). On
12
+ // HTTP the whole value is sealed, but on stdio / AF_UNIX it is raw bytes the
13
+ // client can read, and the sealing spec's rule 5 forbids a secret in plaintext
14
+ // in any opaque value. So the framework packs the options itself, after the
15
+ // catalog's own bytes, and encrypts the secret ones (SPEC-secret-options.md):
16
+ //
17
+ // framework attach plaintext = uuid(16) || catalog_bytes || trailer
18
+ // trailer = body || u32le(len(body)) || TRAILER_MAGIC(8)
19
+ // body = u32le(len(plain)) || plain || secret
20
+ // plain = Arrow IPC batch (1 row) of the non-secret options, or empty
21
+ // secret = empty, or SECRET_VERSION(1) || nonce(24) || XChaCha20-Poly1305(
22
+ // ciphertext || tag) of an Arrow IPC batch of the secret options
23
+ // AEAD key = HKDF-SHA256(root, salt = "", info = "vgi.attach_secret_options.v1", 32)
24
+ // AAD = "vgi.attach_secret_options.v1" 0x00 || uuid
25
+ //
26
+ // `root` is the explicitly configured `attachSecretKey`, else the HTTP signing
27
+ // key (when the worker seals), else the host-local key file shared by every
28
+ // VGI worker of this user on this host (./attach-secret-keyfile.ts). The AAD
29
+ // binds the blob to its attach's framework UUID, so a blob copied into another
30
+ // attach value does not open. XChaCha20-Poly1305 comes from @noble/ciphers
31
+ // (pure JS: Node, Bun, browsers, workerd); HKDF from WebCrypto.
32
+ //
33
+ // Catalog and function code never sees the trailer: the framework strips it
34
+ // (with the UUID) before any catalog or function body runs, and records the
35
+ // decoded options against the opened bytes, where `attachOptions()` finds
36
+ // them. An attach with no options carries no trailer at all, so its bytes are
37
+ // exactly what they were before this module existed.
38
+
39
+ import { xchacha20poly1305 } from "@noble/ciphers/chacha.js";
40
+ import {
41
+ batchFromColumns,
42
+ deserializeBatch,
43
+ iterRows,
44
+ schema as makeSchema,
45
+ serializeBatch,
46
+ type VgiField,
47
+ } from "./arrow/index.js";
48
+ import { OpaqueDataRejectedError } from "./crypto.js";
49
+ import { hostLocalAttachSecretKey } from "./attach-secret-keyfile.js";
50
+
51
+ const UTF8 = new TextEncoder();
52
+
53
+ /** HKDF `info`, and the AAD prefix (before the 0x00 and the attach uuid). */
54
+ export const ATTACH_SECRET_OPTIONS_INFO = "vgi.attach_secret_options.v1";
55
+
56
+ /** First byte of the secret blob: XChaCha20-Poly1305 with a 24-byte nonce. */
57
+ export const ATTACH_SECRET_OPTIONS_VERSION = 1;
58
+
59
+ /** Last 8 bytes of a framework attach plaintext that carries options. */
60
+ const TRAILER_MAGIC = Uint8Array.of(0x00, 0x56, 0x47, 0x49, 0x41, 0x4f, 0x01, 0xff); // \0 V G I A O \1 \xff
61
+ const TRAILER_FIXED = 4 + TRAILER_MAGIC.length;
62
+ const NONCE_LEN = 24;
63
+ const TAG_LEN = 16;
64
+ const AAD_PREFIX = UTF8.encode(`${ATTACH_SECRET_OPTIONS_INFO}\0`);
65
+ const UUID_LEN = 16;
66
+ const FIELD = "attach_opaque_data";
67
+
68
+ /** A decoded ATTACH options record: option name → value, as `attach()` got it. */
69
+ export type AttachOptionValues = Readonly<Record<string, unknown>>;
70
+
71
+ /**
72
+ * Where the secret-options root key comes from. `explicit` is the optional
73
+ * `attachSecretKey` configuration; `signingKey` the HTTP sealing key.
74
+ * `hostLocal` is resolved lazily, and only when a secret option has a value.
75
+ */
76
+ export interface AttachSecretKeySource {
77
+ explicit?: Uint8Array | undefined;
78
+ signingKey?: Uint8Array | undefined;
79
+ /** Override for tests; defaults to the host-local key file. */
80
+ hostLocal?: (() => Promise<Uint8Array>) | undefined;
81
+ }
82
+
83
+ /** Raised when a secret option has a value but no key can be obtained. */
84
+ export class AttachSecretKeyUnavailableError extends Error {
85
+ constructor(message: string) {
86
+ super(message);
87
+ this.name = "AttachSecretKeyUnavailableError";
88
+ }
89
+ }
90
+
91
+ /** Raised by {@link attachOptions} for bytes the framework did not hand out. */
92
+ export class AttachOptionsUnavailableError extends Error {
93
+ constructor() {
94
+ super(
95
+ "attachOptions(): these bytes are not an attach_opaque_data value the framework handed to this call. " +
96
+ "Pass the attach value exactly as received (bindCall.attach_opaque_data, a TableBuffering attachId, or a " +
97
+ "catalog method's attachOpaqueData argument, or a subarray of it), not a copy.",
98
+ );
99
+ this.name = "AttachOptionsUnavailableError";
100
+ }
101
+ }
102
+
103
+ // ----------------------------------------------------------------- the key
104
+
105
+ const subkeys = new Map<string, Promise<Uint8Array>>();
106
+
107
+ function hexOf(b: Uint8Array): string {
108
+ let s = "";
109
+ for (let i = 0; i < b.length; i++) s += b[i]!.toString(16).padStart(2, "0");
110
+ return s;
111
+ }
112
+
113
+ /**
114
+ * The AEAD key for secret ATTACH options derived from `root`:
115
+ * HKDF-SHA256(ikm = root, salt = empty, info = "vgi.attach_secret_options.v1", L = 32).
116
+ * The root itself is never used as the cipher key.
117
+ */
118
+ export function deriveAttachSecretKey(root: Uint8Array): Promise<Uint8Array> {
119
+ const id = hexOf(root);
120
+ let derived = subkeys.get(id);
121
+ if (!derived) {
122
+ derived = (async () => {
123
+ const ikm = await crypto.subtle.importKey("raw", root as BufferSource, "HKDF", false, ["deriveBits"]);
124
+ const bits = await crypto.subtle.deriveBits(
125
+ { name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: UTF8.encode(ATTACH_SECRET_OPTIONS_INFO) },
126
+ ikm,
127
+ 256,
128
+ );
129
+ return new Uint8Array(bits);
130
+ })();
131
+ subkeys.set(id, derived);
132
+ // A failed derivation must not stick.
133
+ derived.catch(() => subkeys.delete(id));
134
+ }
135
+ return derived;
136
+ }
137
+
138
+ function defaultHostLocal(): Promise<Uint8Array> {
139
+ return hostLocalAttachSecretKey();
140
+ }
141
+
142
+ function noKeyMessage(): string {
143
+ return (
144
+ "A secret ATTACH option has a value but this worker has no key to encrypt it with: configure " +
145
+ "`attachSecretKey`, run with a signing key (VGI_SIGNING_KEY), or run where the host-local key file " +
146
+ "(VGI_ATTACH_SECRET_KEY_FILE) can be used."
147
+ );
148
+ }
149
+
150
+ /** The root key: explicit, else the signing key, else the host-local key. */
151
+ async function rootKey(source: AttachSecretKeySource): Promise<Uint8Array> {
152
+ if (source.explicit && source.explicit.length > 0) return source.explicit;
153
+ if (source.signingKey && source.signingKey.length > 0) return source.signingKey;
154
+ return (source.hostLocal ?? defaultHostLocal)();
155
+ }
156
+
157
+ function aadFor(uuid: Uint8Array): Uint8Array {
158
+ const out = new Uint8Array(AAD_PREFIX.length + uuid.length);
159
+ out.set(AAD_PREFIX, 0);
160
+ out.set(uuid, AAD_PREFIX.length);
161
+ return out;
162
+ }
163
+
164
+ // ------------------------------------------------------------------ packing
165
+
166
+ function u32le(n: number): Uint8Array {
167
+ const b = new Uint8Array(4);
168
+ new DataView(b.buffer).setUint32(0, n, true);
169
+ return b;
170
+ }
171
+
172
+ function readU32le(b: Uint8Array, off: number): number {
173
+ return new DataView(b.buffer, b.byteOffset, b.byteLength).getUint32(off, true);
174
+ }
175
+
176
+ function concat(...parts: Uint8Array[]): Uint8Array {
177
+ let total = 0;
178
+ for (const p of parts) total += p.length;
179
+ const out = new Uint8Array(total);
180
+ let off = 0;
181
+ for (const p of parts) {
182
+ out.set(p, off);
183
+ off += p.length;
184
+ }
185
+ return out;
186
+ }
187
+
188
+ /**
189
+ * Split a catalog_attach `options` IPC batch into one batch of the non-secret
190
+ * options and one of the secret options that have a value (a NULL secret is
191
+ * not a secret). `secretNames` are compared case-insensitively. Returns null
192
+ * for absent / empty options.
193
+ */
194
+ function splitOptions(
195
+ optionsIpc: Uint8Array | null | undefined,
196
+ secretNames: ReadonlySet<string>,
197
+ ): { plain: Uint8Array | null; secret: Uint8Array | null } | null {
198
+ if (!optionsIpc || optionsIpc.length === 0) return null;
199
+ const batch = deserializeBatch(optionsIpc);
200
+ if (batch.numRows === 0 || batch.schema.fields.length === 0) return null;
201
+ const row = (iterRows(batch).next().value ?? {}) as Record<string, unknown>;
202
+ const plainFields: VgiField[] = [];
203
+ const secretFields: VgiField[] = [];
204
+ const plainCols: Record<string, unknown[]> = {};
205
+ const secretCols: Record<string, unknown[]> = {};
206
+ for (const f of batch.schema.fields) {
207
+ const value = row[f.name];
208
+ if (secretNames.has(f.name.toLowerCase()) && value !== null && value !== undefined) {
209
+ secretFields.push(f);
210
+ secretCols[f.name] = [value];
211
+ } else {
212
+ plainFields.push(f);
213
+ plainCols[f.name] = [value ?? null];
214
+ }
215
+ }
216
+ return {
217
+ plain: plainFields.length ? serializeBatch(batchFromColumns(plainCols, makeSchema(plainFields))) : null,
218
+ secret: secretFields.length ? serializeBatch(batchFromColumns(secretCols, makeSchema(secretFields))) : null,
219
+ };
220
+ }
221
+
222
+ /**
223
+ * The trailer the framework appends to `uuid || catalog_bytes` for an attach
224
+ * with options, or an empty array when there are none. Encrypts the secret
225
+ * options (obtaining the key only if there is one); never logs anything.
226
+ *
227
+ * @throws {AttachSecretKeyUnavailableError} A secret option has a value and no key can be obtained.
228
+ */
229
+ export async function packAttachOptionsTrailer(
230
+ uuid: Uint8Array,
231
+ optionsIpc: Uint8Array | null | undefined,
232
+ secretNames: ReadonlySet<string>,
233
+ keys: AttachSecretKeySource,
234
+ fixedNonce?: Uint8Array,
235
+ ): Promise<Uint8Array> {
236
+ const split = splitOptions(optionsIpc, secretNames);
237
+ if (split === null) return new Uint8Array(0);
238
+ const plain = split.plain ?? new Uint8Array(0);
239
+ let secret: Uint8Array = new Uint8Array(0);
240
+ if (split.secret) {
241
+ let root: Uint8Array;
242
+ try {
243
+ root = await rootKey(keys);
244
+ } catch (e) {
245
+ if (e instanceof AttachSecretKeyUnavailableError) throw e;
246
+ // The key file's own messages name the file and the remedies; keep them.
247
+ throw new AttachSecretKeyUnavailableError(`${noKeyMessage()} ${(e as Error).message}`);
248
+ }
249
+ const key = await deriveAttachSecretKey(root);
250
+ const nonce = fixedNonce ?? crypto.getRandomValues(new Uint8Array(NONCE_LEN));
251
+ const ct = xchacha20poly1305(key, nonce, aadFor(uuid)).encrypt(split.secret);
252
+ secret = concat(Uint8Array.of(ATTACH_SECRET_OPTIONS_VERSION), nonce, ct);
253
+ }
254
+ const body = concat(u32le(plain.length), plain, secret);
255
+ return concat(body, u32le(body.length), TRAILER_MAGIC);
256
+ }
257
+
258
+ function endsWithMagic(b: Uint8Array): boolean {
259
+ if (b.length < TRAILER_MAGIC.length) return false;
260
+ const off = b.length - TRAILER_MAGIC.length;
261
+ for (let i = 0; i < TRAILER_MAGIC.length; i++) if (b[off + i] !== TRAILER_MAGIC[i]) return false;
262
+ return true;
263
+ }
264
+
265
+ function decodeOptions(ipc: Uint8Array): Record<string, unknown> {
266
+ const batch = deserializeBatch(ipc);
267
+ if (batch.numRows === 0) return {};
268
+ return { ...((iterRows(batch).next().value ?? {}) as Record<string, unknown>) };
269
+ }
270
+
271
+ // --------------------------------------------------------------- accessor
272
+
273
+ /** Opened attach buffers → their options. Keyed by the ArrayBuffer so any view
274
+ * of the bytes the framework handed out (a composite's subarray) resolves. */
275
+ const registry = new WeakMap<ArrayBufferLike, AttachOptionValues>();
276
+ const EMPTY: AttachOptionValues = Object.freeze({});
277
+
278
+ /**
279
+ * Turn a FULL framework attach plaintext (`uuid || catalog_bytes [|| trailer]`,
280
+ * already unsealed on HTTP) into the catalog's own bytes, decrypting any
281
+ * secret options and recording all options for {@link attachOptions}.
282
+ *
283
+ * Returns a view of a private copy, so the record cannot be confused with
284
+ * other bytes of the request. A value shorter than a UUID passes through
285
+ * as-is (with no options), as before.
286
+ *
287
+ * @throws {OpaqueDataRejectedError} The trailer is malformed or the secret blob
288
+ * does not open (wrong key, tampered, or moved from another attach).
289
+ */
290
+ export async function openFrameworkAttach(full: Uint8Array, keys: AttachSecretKeySource): Promise<Uint8Array> {
291
+ if (full.length < UUID_LEN) return full;
292
+ const copy = full.slice();
293
+ let end = copy.length;
294
+ let options: AttachOptionValues = EMPTY;
295
+ if (copy.length >= UUID_LEN + TRAILER_FIXED && endsWithMagic(copy)) {
296
+ const bodyLen = readU32le(copy, copy.length - TRAILER_FIXED);
297
+ const bodyStart = copy.length - TRAILER_FIXED - bodyLen;
298
+ if (bodyLen < 4 || bodyStart < UUID_LEN) throw new OpaqueDataRejectedError(FIELD);
299
+ const body = copy.subarray(bodyStart, copy.length - TRAILER_FIXED);
300
+ const plainLen = readU32le(body, 0);
301
+ if (4 + plainLen > body.length) throw new OpaqueDataRejectedError(FIELD);
302
+ const plain = body.subarray(4, 4 + plainLen);
303
+ const secret = body.subarray(4 + plainLen);
304
+ const values: Record<string, unknown> = {};
305
+ try {
306
+ if (plain.length) Object.assign(values, decodeOptions(plain));
307
+ } catch {
308
+ throw new OpaqueDataRejectedError(FIELD);
309
+ }
310
+ if (secret.length) {
311
+ if (secret.length < 1 + NONCE_LEN + TAG_LEN || secret[0] !== ATTACH_SECRET_OPTIONS_VERSION) {
312
+ throw new OpaqueDataRejectedError(FIELD);
313
+ }
314
+ let opened: Uint8Array;
315
+ try {
316
+ const key = await deriveAttachSecretKey(await rootKey(keys));
317
+ const nonce = secret.subarray(1, 1 + NONCE_LEN);
318
+ opened = xchacha20poly1305(key, nonce, aadFor(copy.subarray(0, UUID_LEN))).decrypt(secret.subarray(1 + NONCE_LEN));
319
+ } catch {
320
+ // Uniform: no key, wrong key, tampered and moved all read the same.
321
+ throw new OpaqueDataRejectedError(FIELD);
322
+ }
323
+ try {
324
+ Object.assign(values, decodeOptions(opened));
325
+ } catch {
326
+ throw new OpaqueDataRejectedError(FIELD);
327
+ }
328
+ }
329
+ options = Object.freeze(values);
330
+ end = bodyStart;
331
+ }
332
+ registry.set(copy.buffer, options);
333
+ return copy.subarray(UUID_LEN, end);
334
+ }
335
+
336
+ /**
337
+ * The ATTACH options of the attach a call belongs to — every supplied option,
338
+ * secret ones included, decoded exactly as `CatalogInterface.attach()`
339
+ * received them.
340
+ *
341
+ * Pass the attach value the framework handed the call: `bindCall.attach_opaque_data`
342
+ * (bind, and `initCall.bind_call` at init/process, for every function kind), a
343
+ * table-buffering function's `attachId`, or the `attachOpaqueData` argument of
344
+ * a catalog method or transaction hook (`transactionBegin` / `transactionCommit`
345
+ * / `transactionRollback`). Any subarray of those bytes works too; a copy does
346
+ * not.
347
+ *
348
+ * Secret options (declared `secret: true`) reach this accessor on every
349
+ * transport without ever being in plaintext in `attach_opaque_data`: the
350
+ * framework encrypts them inside the attach value with a worker-held key. A
351
+ * catalog therefore never needs to pack options into its own attach bytes,
352
+ * and must not put a secret there.
353
+ *
354
+ * Returns `{}` for a null attach value (a call outside any attach) and for
355
+ * an attach that had no options.
356
+ *
357
+ * @throws {AttachOptionsUnavailableError} The bytes were not handed out by the framework.
358
+ */
359
+ export function attachOptions(attachOpaqueData: Uint8Array | null | undefined): AttachOptionValues {
360
+ if (attachOpaqueData == null) return EMPTY;
361
+ // Looked up even when empty: a catalog whose own attach bytes are empty
362
+ // still gets a (zero-length) view of the framework value.
363
+ const found = registry.get(attachOpaqueData.buffer);
364
+ if (found !== undefined) return found;
365
+ if (attachOpaqueData.length === 0) return EMPTY;
366
+ throw new AttachOptionsUnavailableError();
367
+ }
368
+
369
+ /**
370
+ * One option from {@link attachOptions}, looked up case-insensitively (DuckDB
371
+ * option names are case-insensitive). `undefined` when it was not supplied.
372
+ */
373
+ export function attachOption(attachOpaqueData: Uint8Array | null | undefined, name: string): unknown {
374
+ const all = attachOptions(attachOpaqueData);
375
+ if (Object.hasOwn(all, name)) return all[name];
376
+ const lower = name.toLowerCase();
377
+ for (const key of Object.keys(all)) if (key.toLowerCase() === lower) return all[key];
378
+ return undefined;
379
+ }
380
+
381
+ /**
382
+ * Names (lower-cased) of the options `catalog` declares `secret: true` for
383
+ * catalog `name`, read from what it advertises in `catalogsInfo()` — the same
384
+ * specs the extension redacts by — or its `attachOptionSpecs(name)`.
385
+ */
386
+ export async function secretAttachOptionNames(
387
+ catalog: {
388
+ catalogsInfo?(): unknown;
389
+ attachOptionSpecs?(name: string): Array<{ name: string; secret?: boolean }>;
390
+ },
391
+ name: string,
392
+ deserialize: (bytes: Uint8Array) => { name: string; secret?: boolean },
393
+ ): Promise<Set<string>> {
394
+ const names = new Set<string>();
395
+ if (typeof catalog.attachOptionSpecs === "function") {
396
+ for (const spec of catalog.attachOptionSpecs(name) ?? []) if (spec.secret) names.add(spec.name.toLowerCase());
397
+ }
398
+ if (typeof catalog.catalogsInfo === "function") {
399
+ let infos: unknown;
400
+ try {
401
+ infos = await catalog.catalogsInfo();
402
+ } catch {
403
+ infos = [];
404
+ }
405
+ for (const info of (infos ?? []) as Array<{ name?: string; attach_option_specs?: unknown[] | null }>) {
406
+ if (info.name !== name) continue;
407
+ for (const raw of info.attach_option_specs ?? []) {
408
+ try {
409
+ const spec = deserialize(raw as Uint8Array);
410
+ if (spec.secret) names.add(spec.name.toLowerCase());
411
+ } catch {
412
+ // An undecodable spec declares nothing.
413
+ }
414
+ }
415
+ }
416
+ }
417
+ return names;
418
+ }
@@ -97,6 +97,12 @@ export interface AttachOptionSpec {
97
97
  * api_key getenv('SALES_API_KEY'));
98
98
  * ```
99
99
  *
100
+ * Functions and transaction hooks read the value with `attachOptions()`
101
+ * (`CatalogInterface.attachOptions()` in hooks), like any other option: the
102
+ * framework carries it to them encrypted inside `attach_opaque_data` with a
103
+ * worker-held key, so it is never in plaintext in any opaque value. Never
104
+ * put a secret into your catalog's own attach bytes.
105
+ *
100
106
  * Combines with `required` (a credential the catalog cannot attach without,
101
107
  * which a client can then ask for before attaching). It is allowed together
102
108
  * with `default`, but a secret option normally has none: a default would be
@@ -4,6 +4,7 @@
4
4
  import type { VgiSchema, VgiDataType } from "../arrow/index.js";
5
5
  import type { AttachCatalogInfo } from "./interface.js";
6
6
  import type { AttachOptionSpec } from "./attach-option.js";
7
+ import type { WriteOperation, WriteResultMode } from "../write-results.js";
7
8
  import type { VgiFunction } from "../functions/types.js";
8
9
  import type { Arguments } from "../arguments/arguments.js";
9
10
  import type { ColumnStatistics } from "../util/statistics.js";
@@ -40,6 +41,35 @@ export interface TableDescriptor {
40
41
  columns?: VgiSchema;
41
42
  function?: VgiFunction;
42
43
  arguments?: Arguments;
44
+ /**
45
+ * Table in-out function backing `INSERT INTO <table>`. It receives the new
46
+ * rows (the table's user columns) and returns a `writeResultSchema` batch
47
+ * for the mode in its `write_options` (see `write-results.ts`). Omitted
48
+ * means the table does not accept INSERT.
49
+ */
50
+ insertFunction?: VgiFunction;
51
+ /**
52
+ * Table in-out function backing `UPDATE <table>`. It receives the changed
53
+ * columns plus the row-id column (`rowIdField()`, which the scan
54
+ * `function` must emit) for each updated row. Requires `function`, which
55
+ * must also support projection pushdown and be listed in the schema's
56
+ * `functions` (see `rowIdField`).
57
+ */
58
+ updateFunction?: VgiFunction;
59
+ /**
60
+ * Table in-out function backing `DELETE FROM <table>`. It receives the
61
+ * row-id column of each deleted row. Requires `function`, with the same
62
+ * projection-pushdown conditions as `updateFunction`.
63
+ */
64
+ deleteFunction?: VgiFunction;
65
+ /**
66
+ * The richest result mode each write function produces: `count` (plain
67
+ * DML), `rows` (`RETURNING`) or `changes` (old/new pairs). Ordered
68
+ * `count < rows < changes`; supporting one mode promises every lower one.
69
+ * An operation with a write function but no entry defaults to `count`.
70
+ * Mirrors vgi-python's `Table.write_result_modes`.
71
+ */
72
+ writeResultModes?: Partial<Record<WriteOperation, WriteResultMode>>;
43
73
  /** @deprecated Not sent under vgi.v3 (serving throws). Use `constraints: [constraintRecord({ kind: "NOT_NULL", ... })]`. */
44
74
  notNull?: string[];
45
75
  /** @deprecated Not sent under vgi.v3 (serving throws). Use `constraints: [constraintRecord({ kind: "UNIQUE", ... })]`. */
@@ -5,6 +5,7 @@ import type { CatalogSnapshotPolicy } from "./publication.js";
5
5
 
6
6
  import { CatalogNotFoundError, CatalogReadOnlyError, VgiError } from "../errors.js";
7
7
  import { schemaPathsEqual } from "../schema-path.js";
8
+ import { attachOptions } from "../attach-secret-options.js";
8
9
  import type { CatalogCapabilities, ConstraintSnapshot, ConstraintsApplyRequest } from "../generated/vgi-protocol-types.js";
9
10
  import { decodeCatalogObjectRef, decodeConstraintChange, decodeConstraintDefinition } from "../generated/vgi-protocol-types.js";
10
11
  import { constraintCapabilities, readConstraintRecord } from "./constraints.js";
@@ -201,6 +202,19 @@ export interface ScanFunctionResult {
201
202
  schemaPath: string[] | null;
202
203
  }
203
204
 
205
+ /**
206
+ * The `ScanFunctionResult` wire record as a catalog method returns it:
207
+ * `tableScanFunctionGet` (untyped, for history) and the write-function lookups
208
+ * `tableInsertFunctionGet` / `tableUpdateFunctionGet` / `tableDeleteFunctionGet`.
209
+ * `arguments` is the serialized inner arguments batch.
210
+ */
211
+ export interface ScanFunctionResultRecord {
212
+ function_name: string;
213
+ arguments: Uint8Array;
214
+ required_extensions: string[];
215
+ schema_path: string[] | null;
216
+ }
217
+
204
218
  /**
205
219
  * Encode a ScanFunctionResult wire record — the single-row batch shape
206
220
  * `{ function_name, arguments, required_extensions, schema_path }` that
@@ -839,6 +853,44 @@ export abstract class CatalogInterface {
839
853
  ): Awaitable<any> {
840
854
  throw new CatalogReadOnlyError("table_scan_function_get");
841
855
  }
856
+ /**
857
+ * The table in-out function backing `INSERT INTO` this table. Default:
858
+ * the table is read-only. `writableBranchFunctionName` names the writable
859
+ * arm of a multi-branch table (null for a single-branch one).
860
+ */
861
+ tableInsertFunctionGet(
862
+ attachOpaqueData: AttachOpaqueData,
863
+ schemaPath: string[],
864
+ name: string,
865
+ transactionOpaqueData?: TransactionOpaqueData,
866
+ writableBranchFunctionName?: string | null,
867
+ ): Awaitable<ScanFunctionResultRecord> {
868
+ throw new CatalogReadOnlyError("table_insert_function_get");
869
+ }
870
+ /**
871
+ * The table in-out function backing `UPDATE` of this table. Its input is the
872
+ * changed columns plus the row-id column. Default: the table is read-only.
873
+ */
874
+ tableUpdateFunctionGet(
875
+ attachOpaqueData: AttachOpaqueData,
876
+ schemaPath: string[],
877
+ name: string,
878
+ transactionOpaqueData?: TransactionOpaqueData,
879
+ ): Awaitable<ScanFunctionResultRecord> {
880
+ throw new CatalogReadOnlyError("table_update_function_get");
881
+ }
882
+ /**
883
+ * The table in-out function backing `DELETE FROM` this table. Its input is
884
+ * the row-id column. Default: the table is read-only.
885
+ */
886
+ tableDeleteFunctionGet(
887
+ attachOpaqueData: AttachOpaqueData,
888
+ schemaPath: string[],
889
+ name: string,
890
+ transactionOpaqueData?: TransactionOpaqueData,
891
+ ): Awaitable<ScanFunctionResultRecord> {
892
+ throw new CatalogReadOnlyError("table_delete_function_get");
893
+ }
842
894
  /**
843
895
  * Return the scan branches for a (possibly multi-source) table. Default
844
896
  * delegates to `tableScanFunctionGet` and wraps the single result as a
@@ -1197,6 +1249,24 @@ export abstract class CatalogInterface {
1197
1249
  catalogContentsOwner(_attachOpaqueData: AttachOpaqueData): CatalogInterface {
1198
1250
  return this;
1199
1251
  }
1252
+ /**
1253
+ * The ATTACH options of the attach `attachOpaqueData` belongs to — every
1254
+ * supplied option, secret ones (`AttachOptionSpec.secret`) included, as
1255
+ * `attach()` received them. Works in every catalog method and transaction
1256
+ * hook (`transactionBegin` / `transactionCommit` / `transactionRollback`)
1257
+ * on the `attachOpaqueData` argument it was given; functions use the
1258
+ * standalone {@link attachOptions} on `bindCall.attach_opaque_data`.
1259
+ *
1260
+ * The framework carries the options inside `attach_opaque_data` itself and
1261
+ * encrypts the secret ones with a worker-held key, so they never appear in
1262
+ * plaintext in any opaque value on any transport. An `attach()` override
1263
+ * therefore never needs to pack options into its own attach bytes, and must
1264
+ * not put a credential there.
1265
+ */
1266
+ attachOptions(attachOpaqueData: AttachOpaqueData): Readonly<Record<string, unknown>> {
1267
+ return attachOptions(attachOpaqueData);
1268
+ }
1269
+
1200
1270
  transactionBegin(attachOpaqueData: AttachOpaqueData): Awaitable<Uint8Array | null> {
1201
1271
  return null;
1202
1272
  }