@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
package/dist/worker.d.ts CHANGED
@@ -19,12 +19,22 @@ export interface WorkerConfig extends HostingOptions {
19
19
  * dispatches on. Omit to have the worker create its own.
20
20
  */
21
21
  registry?: FunctionRegistry;
22
+ /**
23
+ * Optional root key for secret ATTACH options (`AttachOptionSpec.secret`),
24
+ * which the framework encrypts inside `attach_opaque_data` for
25
+ * `attachOptions()`. Defaults to the host-local key file
26
+ * (`$VGI_ATTACH_SECRET_KEY_FILE`, else `vgi/attach-secret-options.key` under
27
+ * `$XDG_RUNTIME_DIR` or the per-user temp dir). Every worker process that may
28
+ * receive a given attach must use the same key.
29
+ */
30
+ attachSecretKey?: Uint8Array;
22
31
  }
23
32
  export declare class Worker {
24
33
  private _registry;
25
34
  private _hosting;
26
35
  private _catalogInterface;
27
36
  private _catalogName;
37
+ private _attachSecretKey;
28
38
  constructor(config: WorkerConfig);
29
39
  run(argv?: readonly string[]): void;
30
40
  private _serve;
@@ -0,0 +1,57 @@
1
+ import { type VgiBatch, type VgiField, type VgiSchema } from "./arrow/index.js";
2
+ import type { BindRequest } from "./protocol/types.js";
3
+ export type WriteOperation = "insert" | "update" | "delete";
4
+ export type WriteResultMode = "count" | "rows" | "changes";
5
+ export declare const WRITE_OPERATIONS: readonly WriteOperation[];
6
+ export declare const WRITE_RESULT_MODES: readonly WriteResultMode[];
7
+ /** Field metadata key that marks a table's row-id column. */
8
+ export declare const ROW_ID_METADATA_KEY = "is_row_id";
9
+ /**
10
+ * A row-id field for a writable table's columns and its scan's output:
11
+ * `rowIdField()` is DuckDB's conventional `rowid BIGINT`.
12
+ *
13
+ * DuckDB reads the row id as a *virtual* column, which it only requests from a
14
+ * scan that supports projection pushdown. So a table with UPDATE or DELETE
15
+ * needs a scan function that (1) emits this field, (2) is declared with
16
+ * `projectionPushdown: true` and honours `params.outputSchema`, and (3) is
17
+ * listed in its schema's `functions`, which is how DuckDB learns (2). Missing
18
+ * any of these, UPDATE/DELETE fail with "Virtual columns require projection
19
+ * pushdown". Row ids must be unique and stable for the life of a statement.
20
+ */
21
+ export declare function rowIdField(name?: string, type?: import("./index.core.js").Int64Type): VgiField;
22
+ /** Return a validated copy of an operation -> maximum-mode mapping. */
23
+ export declare function validateWriteResultModes(modes: Partial<Record<string, string>>): Partial<Record<WriteOperation, WriteResultMode>>;
24
+ /** Whether a table whose maximum is `maximum` supports `requested`. */
25
+ export declare function supportsWriteResultMode(maximum: string, requested: string): boolean;
26
+ /** Validate a wire value and narrow it to a `WriteResultMode`. */
27
+ export declare function coerceWriteResultMode(value: unknown): WriteResultMode;
28
+ /**
29
+ * The table's user columns: `columns` without the row-id field. Write results
30
+ * (`rows`, and both halves of `changes`) use this schema.
31
+ */
32
+ export declare function userColumns(columns: VgiSchema): VgiSchema;
33
+ /** The exact output schema a write function must bind for `mode`. */
34
+ export declare function writeResultSchema(mode: WriteResultMode, tableSchema: VgiSchema): VgiSchema;
35
+ /** A `count` result batch. */
36
+ export declare function writeCountBatch(count: number | bigint): VgiBatch;
37
+ /** A `rows` result batch: the written rows as plain objects keyed by column. */
38
+ export declare function writeRowsBatch(tableSchema: VgiSchema, rows: readonly Record<string, unknown>[]): VgiBatch;
39
+ /**
40
+ * A `changes` result batch, one OLD/NEW pair per written row: `old` is null
41
+ * for an insert, `new` is null for a delete.
42
+ */
43
+ export declare function writeChangesBatch(tableSchema: VgiSchema, oldRows: readonly (Record<string, unknown> | null)[], newRows: readonly (Record<string, unknown> | null)[]): VgiBatch;
44
+ /** The result batch for `mode`, from the written rows' before/after images. */
45
+ export declare function writeResultBatch(mode: WriteResultMode, tableSchema: VgiSchema, oldRows: readonly (Record<string, unknown> | null)[], newRows: readonly (Record<string, unknown> | null)[]): VgiBatch;
46
+ /** What DuckDB asked a write function for, decoded from `write_options`. */
47
+ export interface WriteOptions {
48
+ resultMode: WriteResultMode;
49
+ /** `throw` (default), or the INSERT ... ON CONFLICT action DuckDB requested. */
50
+ onConflict: string;
51
+ onConflictColumns: string[];
52
+ }
53
+ /**
54
+ * Decode the `write_options` named argument of a write function's bind (a
55
+ * serialized one-row batch). Missing options mean a plain `count` write.
56
+ */
57
+ export declare function writeOptions(bindCall: Pick<BindRequest, "arguments">): WriteOptions;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@query-farm/vgi",
3
- "version": "0.48.3",
3
+ "version": "0.48.5",
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)",
@@ -0,0 +1,185 @@
1
+ // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
+ // SPDX-License-Identifier: LicenseRef-QueryFarm-Source-Available-1.0
3
+
4
+ // The host-local root key for secret ATTACH options on OS-owned transports
5
+ // (stdio, AF_UNIX, launcher pools), where there is no signing key. Shared by
6
+ // every VGI worker of this user on this host, whatever its SDK, so a launcher
7
+ // pool's processes — and workers of different SDKs — agree on it.
8
+ //
9
+ // Identical across SDKs (SPEC-secret-options.md, requirement 4):
10
+ // path $VGI_ATTACH_SECRET_KEY_FILE if set and non-empty; else
11
+ // $XDG_RUNTIME_DIR/vgi/attach-secret-options.key if XDG_RUNTIME_DIR is
12
+ // a directory; else <os.tmpdir()>/vgi-<username>/attach-secret-options.key
13
+ // content exactly 32 raw CSPRNG bytes
14
+ // perms directory 0700, file 0600, both owned by this user and not
15
+ // group/other-accessible (POSIX) — refused otherwise
16
+ // create temp file (0600) in the same directory, hard-linked into place;
17
+ // an existing key is never overwritten, concurrent first starts agree
18
+ //
19
+ // Node / Bun only (it needs a filesystem), and read only when a secret option
20
+ // actually has a value.
21
+
22
+ type NodeFs = typeof import("node:fs");
23
+ type NodeOs = typeof import("node:os");
24
+ type NodePath = typeof import("node:path");
25
+
26
+ /**
27
+ * Node built-ins via `process.getBuiltinModule` (Node >= 22.3, Bun) rather than
28
+ * static imports, so the browser / workerd bundles that reach this module
29
+ * through the catalog code carry no `node:` imports. Throws where there is no
30
+ * filesystem; the caller turns that into "no key available".
31
+ */
32
+ function builtins(): { fs: NodeFs; os: NodeOs; path: NodePath } {
33
+ const proc = (globalThis as { process?: { getBuiltinModule?: (id: string) => unknown } }).process;
34
+ const get = proc?.getBuiltinModule?.bind(proc);
35
+ const fs = get?.("node:fs") as NodeFs | undefined;
36
+ const os = get?.("node:os") as NodeOs | undefined;
37
+ const path = get?.("node:path") as NodePath | undefined;
38
+ if (!fs || !os || !path) throw new Error("this runtime has no filesystem for the host-local attach secret key file.");
39
+ return { fs, os, path };
40
+ }
41
+
42
+ export const ATTACH_SECRET_KEY_FILE_ENV = "VGI_ATTACH_SECRET_KEY_FILE";
43
+ const KEY_LEN = 32;
44
+ const FILE_NAME = "attach-secret-options.key";
45
+ const REMEDY = "Set VGI_SIGNING_KEY (or configure attachSecretKey), or point VGI_ATTACH_SECRET_KEY_FILE at a valid key file.";
46
+
47
+ function username(): string {
48
+ try {
49
+ const name = builtins().os.userInfo().username;
50
+ if (name) return name;
51
+ } catch {
52
+ // no passwd entry (containers): fall through
53
+ }
54
+ return process.env.USER || process.env.USERNAME || String(process.getuid?.() ?? "user");
55
+ }
56
+
57
+ function isDirectory(path: string): boolean {
58
+ try {
59
+ return builtins().fs.statSync(path).isDirectory();
60
+ } catch {
61
+ return false;
62
+ }
63
+ }
64
+
65
+ /** The key file path this process uses, per the cross-SDK rules above. */
66
+ export function hostLocalAttachSecretKeyPath(env: Record<string, string | undefined> = (globalThis as { process?: { env: Record<string, string | undefined> } }).process?.env ?? {}): string {
67
+ const { os, path: { join } } = builtins();
68
+ const explicit = env[ATTACH_SECRET_KEY_FILE_ENV];
69
+ if (explicit) return explicit;
70
+ const xdg = env.XDG_RUNTIME_DIR;
71
+ if (xdg && isDirectory(xdg)) return join(xdg, "vgi", FILE_NAME);
72
+ return join(os.tmpdir(), `vgi-${username()}`, FILE_NAME);
73
+ }
74
+
75
+ const POSIX = typeof process === "undefined" || process.platform !== "win32";
76
+
77
+ function checkOwnedPrivate(path: string, mode: number, uid: number, what: string): void {
78
+ if (!POSIX) return;
79
+ const me = process.getuid?.();
80
+ if (me !== undefined && uid !== me) {
81
+ throw new Error(`attach secret key ${what} ${path} is not owned by the current user. ${REMEDY}`);
82
+ }
83
+ if ((mode & 0o077) !== 0) {
84
+ throw new Error(
85
+ `attach secret key ${what} ${path} is accessible by group/other (mode ${(mode & 0o777).toString(8)}); ` +
86
+ `it must be ${what === "directory" ? "0700" : "0600"}. ${REMEDY}`,
87
+ );
88
+ }
89
+ }
90
+
91
+ function ensureDir(dir: string): void {
92
+ const { mkdirSync, lstatSync } = builtins().fs;
93
+ try {
94
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
95
+ } catch (e) {
96
+ if ((e as NodeJS.ErrnoException).code !== "EEXIST") throw e;
97
+ }
98
+ const st = lstatSync(dir);
99
+ if (!st.isDirectory()) throw new Error(`attach secret key directory ${dir} is not a directory. ${REMEDY}`);
100
+ checkOwnedPrivate(dir, st.mode, st.uid, "directory");
101
+ }
102
+
103
+ function readKey(path: string): Uint8Array | null {
104
+ const { openSync, fstatSync, readSync, closeSync, constants } = builtins().fs;
105
+ let fd: number;
106
+ try {
107
+ fd = openSync(path, constants.O_RDONLY | (POSIX ? constants.O_NOFOLLOW : 0));
108
+ } catch (e) {
109
+ if ((e as NodeJS.ErrnoException).code === "ENOENT") return null;
110
+ throw new Error(`attach secret key file ${path} cannot be opened (${(e as NodeJS.ErrnoException).code}). ${REMEDY}`);
111
+ }
112
+ try {
113
+ const st = fstatSync(fd);
114
+ if (!st.isFile()) throw new Error(`attach secret key file ${path} is not a regular file. ${REMEDY}`);
115
+ checkOwnedPrivate(path, st.mode, st.uid, "file");
116
+ const buf = new Uint8Array(KEY_LEN + 1);
117
+ let n = 0;
118
+ for (;;) {
119
+ const got = readSync(fd, buf, n, buf.length - n, null);
120
+ if (got <= 0) break;
121
+ n += got;
122
+ if (n === buf.length) break;
123
+ }
124
+ if (n !== KEY_LEN || st.size !== KEY_LEN) {
125
+ throw new Error(
126
+ `attach secret key file ${path} must contain exactly ${KEY_LEN} raw bytes (found ${st.size}). ${REMEDY}`,
127
+ );
128
+ }
129
+ return buf.subarray(0, KEY_LEN);
130
+ } finally {
131
+ closeSync(fd);
132
+ }
133
+ }
134
+
135
+ /** Create the key atomically unless it exists; never overwrite one. */
136
+ function createKey(path: string): void {
137
+ const { openSync, writeSync, fsyncSync, closeSync, linkSync, unlinkSync, constants } = builtins().fs;
138
+ const { dirname, join } = builtins().path;
139
+ const tmp = join(dirname(path), `.${FILE_NAME}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);
140
+ const fd = openSync(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600);
141
+ try {
142
+ const key = crypto.getRandomValues(new Uint8Array(KEY_LEN));
143
+ let off = 0;
144
+ while (off < KEY_LEN) off += writeSync(fd, key, off, KEY_LEN - off);
145
+ fsyncSync(fd);
146
+ } finally {
147
+ closeSync(fd);
148
+ }
149
+ try {
150
+ linkSync(tmp, path);
151
+ } catch (e) {
152
+ // Another process won the race: use its key.
153
+ if ((e as NodeJS.ErrnoException).code !== "EEXIST") {
154
+ unlinkSync(tmp);
155
+ throw e;
156
+ }
157
+ }
158
+ unlinkSync(tmp);
159
+ }
160
+
161
+ /**
162
+ * Read (creating on first use) the host-local key file at `path`
163
+ * (default {@link hostLocalAttachSecretKeyPath}). Synchronous and uncached;
164
+ * see {@link hostLocalAttachSecretKey} for the cached form the framework uses.
165
+ */
166
+ export function loadHostLocalAttachSecretKey(path: string = hostLocalAttachSecretKeyPath()): Uint8Array {
167
+ ensureDir(builtins().path.dirname(path));
168
+ const existing = readKey(path);
169
+ if (existing) return existing;
170
+ createKey(path);
171
+ const created = readKey(path);
172
+ if (!created) throw new Error(`attach secret key file ${path} vanished after creation. ${REMEDY}`);
173
+ return created;
174
+ }
175
+
176
+ let cached: { path: string; key: Uint8Array } | undefined;
177
+
178
+ /** The host-local root key, read once per process (per resolved path). */
179
+ export async function hostLocalAttachSecretKey(): Promise<Uint8Array> {
180
+ const path = hostLocalAttachSecretKeyPath();
181
+ if (cached?.path === path) return cached.key;
182
+ const key = loadHostLocalAttachSecretKey(path);
183
+ cached = { path, key };
184
+ return key;
185
+ }