@query-farm/vgi 0.44.0 → 0.45.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 (55) hide show
  1. package/dist/arrow/impl-arrowjs/index.d.ts +1 -1
  2. package/dist/arrow/impl-arrowjs/ipc.d.ts +6 -0
  3. package/dist/arrow/impl-flechette/build.d.ts +2 -2
  4. package/dist/arrow/impl-flechette/canonical.d.ts +1 -1
  5. package/dist/arrow/impl-flechette/index.d.ts +1 -1
  6. package/dist/arrow/impl-flechette/ipc.d.ts +6 -0
  7. package/dist/arrow/index.d.ts +1 -1
  8. package/dist/catalog/contents-codec.d.ts +7 -0
  9. package/dist/catalog/contents-digest.d.ts +2 -1
  10. package/dist/catalog/interface.d.ts +3 -0
  11. package/dist/catalog/publication-envelope.d.ts +1 -0
  12. package/dist/catalog/publication.d.ts +142 -0
  13. package/dist/catalog/s3-publication.d.ts +38 -0
  14. package/dist/client-entry.js +136 -25
  15. package/dist/client-entry.js.map +13 -12
  16. package/dist/codec/asd.d.ts +4 -0
  17. package/dist/generated/vgi-client.d.ts +6 -14
  18. package/dist/generated/vgi-protocol-schemas.d.ts +2 -0
  19. package/dist/generated/vgi-protocol-types.d.ts +26 -3
  20. package/dist/generated/vgi-service.d.ts +3 -3
  21. package/dist/index.d.ts +4 -0
  22. package/dist/index.js +739 -81
  23. package/dist/index.js.map +24 -20
  24. package/dist/protocol/dispatch.d.ts +1 -1
  25. package/dist/protocol/handlers/catalog/contents.d.ts +4 -4
  26. package/dist/serve-entry.js +610 -78
  27. package/dist/serve-entry.js.map +19 -16
  28. package/dist/worker-cf-entry.js +626 -86
  29. package/dist/worker-cf-entry.js.map +21 -18
  30. package/package.json +3 -3
  31. package/src/arrow/impl-arrowjs/index.ts +1 -0
  32. package/src/arrow/impl-arrowjs/ipc.ts +23 -0
  33. package/src/arrow/impl-flechette/build.ts +4 -2
  34. package/src/arrow/impl-flechette/canonical.ts +7 -2
  35. package/src/arrow/impl-flechette/index.ts +1 -0
  36. package/src/arrow/impl-flechette/ipc.ts +19 -0
  37. package/src/arrow/index.ts +1 -1
  38. package/src/catalog/contents-codec.ts +77 -0
  39. package/src/catalog/contents-digest.ts +20 -17
  40. package/src/catalog/interface.ts +3 -0
  41. package/src/catalog/publication-envelope.ts +62 -0
  42. package/src/catalog/publication.ts +290 -0
  43. package/src/catalog/read-only.ts +0 -2
  44. package/src/catalog/s3-publication.ts +81 -0
  45. package/src/client/client.ts +2 -19
  46. package/src/codec/asd.ts +40 -1
  47. package/src/codec/conform.ts +2 -1
  48. package/src/generated/vgi-client.ts +7 -16
  49. package/src/generated/vgi-protocol-schemas.ts +13 -6
  50. package/src/generated/vgi-protocol-types.ts +39 -5
  51. package/src/generated/vgi-service.ts +4 -3
  52. package/src/index.ts +5 -0
  53. package/src/protocol/dispatch.ts +1 -1
  54. package/src/protocol/handlers/catalog/admin.ts +7 -4
  55. package/src/protocol/handlers/catalog/contents.ts +50 -35
package/dist/index.js CHANGED
@@ -1729,7 +1729,26 @@ function deserializeBatch(bytes) {
1729
1729
  }
1730
1730
  return batches[0];
1731
1731
  }
1732
+ function deserializeBatches(bytes) {
1733
+ return [...RecordBatchReader.from(bytes)];
1734
+ }
1735
+ function serializeBatches(batches, schema) {
1736
+ const writer = new RecordBatchStreamWriter;
1737
+ writer.reset(undefined, schema);
1738
+ for (const batch of batches)
1739
+ writer._writeRecordBatch(batch);
1740
+ writer.close();
1741
+ return writer.toUint8Array(true);
1742
+ }
1743
+ function serializeCollectionRows(schema, rows, maxBatchRows) {
1744
+ const batch = batchFromRows(rows, schema);
1745
+ const batches = [];
1746
+ for (let offset = 0;offset < batch.numRows; offset += maxBatchRows)
1747
+ batches.push(batch.slice(offset, offset + maxBatchRows));
1748
+ return serializeBatches(batches, schema);
1749
+ }
1732
1750
  var init_ipc = __esm(() => {
1751
+ init_build();
1733
1752
  init_empty();
1734
1753
  });
1735
1754
 
@@ -1883,6 +1902,7 @@ __export(exports_impl_arrowjs, {
1883
1902
  decodeDictValue: () => decodeDictValue,
1884
1903
  denseUnion: () => denseUnion,
1885
1904
  deserializeBatch: () => deserializeBatch,
1905
+ deserializeBatches: () => deserializeBatches,
1886
1906
  deserializeSchema: () => deserializeSchema,
1887
1907
  dictionary: () => dictionary,
1888
1908
  duration: () => duration,
@@ -1912,6 +1932,8 @@ __export(exports_impl_arrowjs, {
1912
1932
  safeNumber: () => safeNumber,
1913
1933
  schema: () => schema,
1914
1934
  serializeBatch: () => serializeBatch,
1935
+ serializeBatches: () => serializeBatches,
1936
+ serializeCollectionRows: () => serializeCollectionRows,
1915
1937
  serializeSchema: () => serializeSchema,
1916
1938
  sparseUnion: () => sparseUnion,
1917
1939
  struct: () => struct,
@@ -5433,7 +5455,9 @@ function mapPairs(raw) {
5433
5455
  return Object.entries(raw);
5434
5456
  }
5435
5457
  function zeroValue(type) {
5436
- if (isUtf8(type) || isDictionary(type))
5458
+ if (isDictionary(type))
5459
+ return zeroValue(type.dictionary);
5460
+ if (isUtf8(type))
5437
5461
  return "";
5438
5462
  if (isBinary(type))
5439
5463
  return new Uint8Array(0);
@@ -7331,7 +7355,7 @@ function normalizeValue(raw, type) {
7331
7355
  return out;
7332
7356
  }
7333
7357
  if (isDictionary(type)) {
7334
- return raw == null ? null : String(raw);
7358
+ return normalizeValue(raw, type.dictionary);
7335
7359
  }
7336
7360
  if (isBinary(type)) {
7337
7361
  return toUint8Array3(raw);
@@ -7360,9 +7384,44 @@ function toUint8Array3(val) {
7360
7384
  }
7361
7385
  return new Uint8Array(0);
7362
7386
  }
7387
+ function encodeASDCollection(schema, records) {
7388
+ if (records.length === 0)
7389
+ return null;
7390
+ return serializeCollectionRows(schema, records.map((record) => sortMapsForSchema(schema, conformRecord(schema, record))), 1024);
7391
+ }
7392
+ function decodeASDCollection(schema, bytes) {
7393
+ if (bytes == null)
7394
+ return [];
7395
+ const output = [];
7396
+ const batches = deserializeBatches(bytes);
7397
+ const validateSchema = (actualSchema) => {
7398
+ if (actualSchema.fields.length !== schema.fields.length || schema.fields.some((field, i) => {
7399
+ const actual = actualSchema.fields[i];
7400
+ return actual.name !== field.name || actual.nullable !== field.nullable || typeSignature(actual.type) !== typeSignature(field.type);
7401
+ }))
7402
+ throw new Error("catalog collection has an incompatible metadata schema");
7403
+ };
7404
+ if (batches.length === 0)
7405
+ validateSchema(deserializeSchema(bytes));
7406
+ for (const batch of batches) {
7407
+ validateSchema(batch.schema);
7408
+ for (let row = 0;row < batch.numRows; row++) {
7409
+ const item = {};
7410
+ for (const field of schema.fields) {
7411
+ const value = batch.getChild(field.name)?.get(row);
7412
+ if (value == null && !field.nullable)
7413
+ throw new Error(`catalog collection has null ${field.name}`);
7414
+ item[field.name] = normalizeValue(value, field.type);
7415
+ }
7416
+ output.push(item);
7417
+ }
7418
+ }
7419
+ return output;
7420
+ }
7363
7421
 
7364
7422
  // src/generated/vgi-protocol-schemas.ts
7365
7423
  init_arrow();
7424
+ var VGI_CATALOG_CONTRACT_HASH = "121e8fe1c074bce00a6d0fcec49d7a90f05e45498cd9ca8a5a3b4a9ae2377a2d";
7366
7425
  var CatalogInfoSchema = schema2([
7367
7426
  field2("name", utf82(), false),
7368
7427
  field2("implementation_version", utf82(), true),
@@ -7374,7 +7433,6 @@ var CatalogInfoSchema = schema2([
7374
7433
  var SchemaInfoSchema = schema2([
7375
7434
  field2("comment", utf82(), true),
7376
7435
  field2("tags", map2(field2("key", utf82(), false), field2("value", utf82(), true), false), false),
7377
- field2("attach_opaque_data", binary2(), false),
7378
7436
  field2("path", list2(field2("item", utf82(), true)), false),
7379
7437
  field2("estimated_object_count", map2(field2("key", utf82(), false), field2("value", int642(), true), false), true)
7380
7438
  ]);
@@ -7415,9 +7473,9 @@ var FunctionInfoSchema = schema2([
7415
7473
  field2("name", utf82(), false),
7416
7474
  field2("schema_path", list2(field2("item", utf82(), true)), false),
7417
7475
  field2("function_type", dictionary2(utf82(), int162()), false),
7418
- field2("arguments", binary2(), false),
7419
- field2("output_schema", binary2(), false),
7420
- field2("parameter_default_values", binary2(), true),
7476
+ field2("arguments", dictionary2(binary2(), int322()), false),
7477
+ field2("output_schema", dictionary2(binary2(), int322()), false),
7478
+ field2("parameter_default_values", dictionary2(binary2(), int322()), true),
7421
7479
  field2("stability", dictionary2(utf82(), int162()), true),
7422
7480
  field2("null_handling", dictionary2(utf82(), int162()), true),
7423
7481
  field2("argument_monotonicity", list2(field2("item", utf82(), true)), true),
@@ -7878,7 +7936,12 @@ var CatalogContentsResultSchema = schema2([
7878
7936
  field2("catalog_version", int642(), false),
7879
7937
  field2("etag", utf82(), true),
7880
7938
  field2("not_modified", bool2(), false),
7881
- field2("schemas", list2(field2("item", struct2([field2("path", list2(field2("item", utf82(), true)), false), field2("schema", binary2(), false), field2("tables", list2(field2("item", binary2(), true)), false), field2("views", list2(field2("item", binary2(), true)), false), field2("scalar_functions", list2(field2("item", binary2(), true)), false), field2("aggregate_functions", list2(field2("item", binary2(), true)), false), field2("table_functions", list2(field2("item", binary2(), true)), false), field2("scalar_macros", list2(field2("item", binary2(), true)), false), field2("table_macros", list2(field2("item", binary2(), true)), false), field2("indexes", list2(field2("item", binary2(), true)), false)]), true)), false)
7939
+ field2("schemas", binary2(), true),
7940
+ field2("tables", binary2(), true),
7941
+ field2("views", binary2(), true),
7942
+ field2("functions", binary2(), true),
7943
+ field2("macros", binary2(), true),
7944
+ field2("indexes", binary2(), true)
7882
7945
  ]);
7883
7946
  var CatalogCopyFromFormatsResultSchema = schema2([
7884
7947
  field2("items", list2(field2("item", binary2(), true)), false)
@@ -8355,26 +8418,17 @@ function buildCatalogAttachResult(init) {
8355
8418
  supports_catalog_contents: init.supports_catalog_contents ?? false
8356
8419
  };
8357
8420
  }
8358
- function buildSchemaContents(init) {
8359
- return {
8360
- path: init.path,
8361
- schema: init.schema,
8362
- tables: init.tables ?? [],
8363
- views: init.views ?? [],
8364
- scalar_functions: init.scalar_functions ?? [],
8365
- aggregate_functions: init.aggregate_functions ?? [],
8366
- table_functions: init.table_functions ?? [],
8367
- scalar_macros: init.scalar_macros ?? [],
8368
- table_macros: init.table_macros ?? [],
8369
- indexes: init.indexes ?? []
8370
- };
8371
- }
8372
8421
  function buildCatalogContentsResponse(init) {
8373
8422
  return {
8374
8423
  catalog_version: init.catalog_version,
8375
8424
  etag: init.etag ?? null,
8376
8425
  not_modified: init.not_modified ?? false,
8377
- schemas: init.schemas ?? []
8426
+ schemas: init.schemas ?? null,
8427
+ tables: init.tables ?? null,
8428
+ views: init.views ?? null,
8429
+ functions: init.functions ?? null,
8430
+ macros: init.macros ?? null,
8431
+ indexes: init.indexes ?? null
8378
8432
  };
8379
8433
  }
8380
8434
  var decodeCatalogContentsResponse = (b) => decodeASD(CatalogContentsResultSchema, b);
@@ -8527,6 +8581,7 @@ function isPromise(v) {
8527
8581
  }
8528
8582
 
8529
8583
  class CatalogInterface {
8584
+ catalogSnapshotPolicy = null;
8530
8585
  catalogContentsEtag = null;
8531
8586
  catalogContentsAttachIndependent = false;
8532
8587
  catalogVersionFrozen = false;
@@ -9097,7 +9152,6 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
9097
9152
  }
9098
9153
  schemas(attachOpaqueData, transactionOpaqueData) {
9099
9154
  return this._descriptor.schemas.map((s) => ({
9100
- attach_opaque_data: this.itemAttachId(attachOpaqueData),
9101
9155
  path: schemaDescriptorPath(s),
9102
9156
  comment: s.comment ?? null,
9103
9157
  tags: s.tags ?? {},
@@ -9129,7 +9183,6 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
9129
9183
  if (!desc)
9130
9184
  return null;
9131
9185
  return {
9132
- attach_opaque_data: this.itemAttachId(attachOpaqueData),
9133
9186
  path: schemaDescriptorPath(desc),
9134
9187
  comment: desc.comment ?? null,
9135
9188
  tags: desc.tags ?? {},
@@ -11204,7 +11257,7 @@ import {
11204
11257
  Protocol
11205
11258
  } from "@query-farm/vgi-rpc";
11206
11259
  var VGI_PROTOCOL_NAME = "vgi.v2";
11207
- var VGI_PROTOCOL_VERSION = "2.1.0";
11260
+ var VGI_PROTOCOL_VERSION = "2.2.0";
11208
11261
  function exchangeStream(callbacks) {
11209
11262
  return { kind: "exchange", ...callbacks };
11210
11263
  }
@@ -13356,18 +13409,97 @@ function hex(buf) {
13356
13409
  return Array.from(buf, (b) => b.toString(16).padStart(2, "0")).join("");
13357
13410
  }
13358
13411
 
13412
+ // src/protocol/handlers/catalog/contents.ts
13413
+ import { ExternalRef as ExternalRef2 } from "@query-farm/vgi-rpc";
13414
+
13415
+ // src/catalog/publication.ts
13416
+ init_arrow();
13417
+ import { ExternalRef, publishExternalResult, resolveExternalLocation } from "@query-farm/vgi-rpc";
13418
+
13419
+ // src/catalog/contents-codec.ts
13420
+ var schemaPathKey2 = (path) => JSON.stringify(path.map((part) => part.toLowerCase()));
13421
+ var CATALOG_STREAM_KINDS = ["schemas", "tables", "views", "functions", "macros", "indexes"];
13422
+ function encodeCatalogStreams(inventory) {
13423
+ const streams = {
13424
+ schemas: encodeASDCollection(SchemaInfoSchema, inventory.map((s) => s.schema)),
13425
+ tables: encodeASDCollection(TableInfoSchema, inventory.flatMap((s) => s.tables)),
13426
+ views: encodeASDCollection(ViewInfoSchema, inventory.flatMap((s) => s.views)),
13427
+ functions: encodeASDCollection(FunctionInfoSchema, inventory.flatMap((s) => [...s.scalar_functions, ...s.aggregate_functions, ...s.table_functions])),
13428
+ macros: encodeASDCollection(MacroInfoSchema, inventory.flatMap((s) => [...s.scalar_macros, ...s.table_macros])),
13429
+ indexes: encodeASDCollection(IndexInfoSchema, inventory.flatMap((s) => s.indexes))
13430
+ };
13431
+ return streams;
13432
+ }
13433
+ function decodeCatalogStreams(response, ifNoneMatch) {
13434
+ if (response.not_modified) {
13435
+ if (response.etag == null || ifNoneMatch !== undefined && response.etag !== ifNoneMatch || CATALOG_STREAM_KINDS.some((kind) => response[kind] != null)) {
13436
+ throw new Error("invalid catalog_contents not_modified response");
13437
+ }
13438
+ return [];
13439
+ }
13440
+ const infos = decodeASDCollection(SchemaInfoSchema, response.schemas);
13441
+ const schemas = [];
13442
+ const index = new Map;
13443
+ for (const schema of infos) {
13444
+ if (!Array.isArray(schema.path) || schema.path.length === 0)
13445
+ throw new Error("catalog schema has an empty path");
13446
+ const key = schemaPathKey2(schema.path);
13447
+ if (index.has(key))
13448
+ throw new Error("catalog contains duplicate schema paths");
13449
+ if (schema.path.length > 1 && !index.has(schemaPathKey2(schema.path.slice(0, -1)))) {
13450
+ throw new Error("catalog schema is missing its preceding parent");
13451
+ }
13452
+ const entry = { schema, tables: [], views: [], scalar_functions: [], aggregate_functions: [], table_functions: [], scalar_macros: [], table_macros: [], indexes: [] };
13453
+ index.set(key, entry);
13454
+ schemas.push(entry);
13455
+ }
13456
+ const owner = (item) => {
13457
+ const entry = index.get(schemaPathKey2(item.schema_path));
13458
+ if (!entry)
13459
+ throw new Error("catalog object references an absent schema");
13460
+ return entry;
13461
+ };
13462
+ for (const item of decodeASDCollection(TableInfoSchema, response.tables))
13463
+ owner(item).tables.push(item);
13464
+ for (const item of decodeASDCollection(ViewInfoSchema, response.views))
13465
+ owner(item).views.push(item);
13466
+ for (const item of decodeASDCollection(FunctionInfoSchema, response.functions)) {
13467
+ const entry = owner(item);
13468
+ switch (String(item.function_type).toUpperCase()) {
13469
+ case "SCALAR":
13470
+ entry.scalar_functions.push(item);
13471
+ break;
13472
+ case "AGGREGATE":
13473
+ entry.aggregate_functions.push(item);
13474
+ break;
13475
+ case "TABLE":
13476
+ case "TABLE_BUFFERING":
13477
+ entry.table_functions.push(item);
13478
+ break;
13479
+ default:
13480
+ throw new Error(`unknown catalog function type ${item.function_type}`);
13481
+ }
13482
+ }
13483
+ for (const item of decodeASDCollection(MacroInfoSchema, response.macros)) {
13484
+ const entry = owner(item);
13485
+ switch (String(item.macro_type).toUpperCase()) {
13486
+ case "SCALAR":
13487
+ entry.scalar_macros.push(item);
13488
+ break;
13489
+ case "TABLE":
13490
+ entry.table_macros.push(item);
13491
+ break;
13492
+ default:
13493
+ throw new Error(`unknown catalog macro type ${item.macro_type}`);
13494
+ }
13495
+ }
13496
+ for (const item of decodeASDCollection(IndexInfoSchema, response.indexes))
13497
+ owner(item).indexes.push(item);
13498
+ return schemas;
13499
+ }
13500
+
13359
13501
  // src/catalog/contents-digest.ts
13360
- var KINDS = [
13361
- "tables",
13362
- "views",
13363
- "scalar_functions",
13364
- "aggregate_functions",
13365
- "table_functions",
13366
- "scalar_macros",
13367
- "table_macros",
13368
- "indexes"
13369
- ];
13370
- async function catalogContentsDigest(schemas) {
13502
+ async function catalogContentsDigest(streams, version = 0) {
13371
13503
  const utf8 = new TextEncoder;
13372
13504
  const parts = [];
13373
13505
  let total = 0;
@@ -13387,12 +13519,23 @@ async function catalogContentsDigest(schemas) {
13387
13519
  for (const v of values)
13388
13520
  chunk(v);
13389
13521
  };
13390
- count(schemas.length);
13391
- for (const entry of schemas) {
13392
- chunks(entry.path.map((p) => utf8.encode(p)));
13393
- chunk(entry.schema);
13394
- for (const kind of KINDS)
13395
- chunks(entry[kind]);
13522
+ if (Array.isArray(streams)) {
13523
+ count(streams.length);
13524
+ for (const entry of streams) {
13525
+ chunks(entry.path.map((p) => utf8.encode(p)));
13526
+ chunk(entry.schema);
13527
+ for (const kind of ["tables", "views", "scalar_functions", "aggregate_functions", "table_functions", "scalar_macros", "table_macros", "indexes"])
13528
+ chunks(entry[kind]);
13529
+ }
13530
+ } else {
13531
+ chunk(utf8.encode("vgi.catalog-contents.2.2"));
13532
+ count(version);
13533
+ for (const kind of CATALOG_STREAM_KINDS) {
13534
+ const value = streams[kind];
13535
+ count(value == null ? 0 : 1);
13536
+ if (value != null)
13537
+ chunk(value);
13538
+ }
13396
13539
  }
13397
13540
  const buf = new Uint8Array(total);
13398
13541
  let off = 0;
@@ -13407,7 +13550,391 @@ async function catalogContentsDigest(schemas) {
13407
13550
  return hex;
13408
13551
  }
13409
13552
 
13553
+ // src/catalog/publication-envelope.ts
13554
+ function validateCatalogPublicationEnvelope(bytes) {
13555
+ try {
13556
+ const stream = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
13557
+ let position = 0, messages = 0;
13558
+ while (position < bytes.length) {
13559
+ let length = stream.getInt32(position, true);
13560
+ position += 4;
13561
+ if (length === -1) {
13562
+ length = stream.getInt32(position, true);
13563
+ position += 4;
13564
+ }
13565
+ if (length === 0) {
13566
+ if (position !== bytes.length)
13567
+ throw new Error("trailing data");
13568
+ break;
13569
+ }
13570
+ if (length < 4 || length > bytes.length - position)
13571
+ throw new Error("invalid message length");
13572
+ const head = new DataView(bytes.buffer, bytes.byteOffset + position, length);
13573
+ const tableField = (table, field) => {
13574
+ const vtable = table - head.getInt32(table, true);
13575
+ const vlength = head.getUint16(vtable, true);
13576
+ if (vlength < 4 || vlength % 2 || vtable + vlength > length)
13577
+ throw new Error("invalid vtable");
13578
+ if (4 + 2 * field >= vlength)
13579
+ return null;
13580
+ const offset = head.getUint16(vtable + 4 + 2 * field, true);
13581
+ return offset === 0 ? null : table + offset;
13582
+ };
13583
+ const follow = (pointer) => pointer + head.getUint32(pointer, true);
13584
+ const root = head.getUint32(0, true);
13585
+ const typePosition = tableField(root, 1);
13586
+ const type = typePosition == null ? 0 : head.getUint8(typePosition);
13587
+ if (type !== (messages === 0 ? 1 : messages === 1 ? 3 : -1))
13588
+ throw new Error("expected one schema and one record batch");
13589
+ if (type === 3) {
13590
+ const header = tableField(root, 2);
13591
+ if (header == null)
13592
+ throw new Error("missing record header");
13593
+ const rows = tableField(follow(header), 0);
13594
+ if (rows == null || head.getBigInt64(rows, true) !== 1n)
13595
+ throw new Error("expected one response row");
13596
+ }
13597
+ const metadata = tableField(root, 4);
13598
+ if (metadata != null) {
13599
+ const vector = follow(metadata), count = head.getUint32(vector, true);
13600
+ if (count > length / 4)
13601
+ throw new Error("invalid metadata vector");
13602
+ for (let i = 0;i < count; i++) {
13603
+ const keyPointer = tableField(follow(vector + 4 + 4 * i), 0);
13604
+ if (keyPointer == null)
13605
+ continue;
13606
+ const keyStart = follow(keyPointer), keyLength = head.getUint32(keyStart, true);
13607
+ if (keyStart + 4 + keyLength > length)
13608
+ throw new Error("invalid metadata key");
13609
+ const key = new TextDecoder().decode(new Uint8Array(head.buffer, head.byteOffset + keyStart + 4, keyLength));
13610
+ if (key === "vgi_rpc.location" || key === "vgi_rpc.log_level")
13611
+ throw new Error("pointer/log metadata is not a catalog result");
13612
+ }
13613
+ }
13614
+ const bodyPosition = tableField(root, 3);
13615
+ const bodyLength = bodyPosition == null ? 0 : Number(head.getBigInt64(bodyPosition, true));
13616
+ position += length;
13617
+ if (!Number.isSafeInteger(bodyLength) || bodyLength < 0 || bodyLength > bytes.length - position)
13618
+ throw new Error("invalid body length");
13619
+ position += bodyLength;
13620
+ messages++;
13621
+ }
13622
+ if (messages !== 2)
13623
+ throw new Error("missing response batch");
13624
+ } catch (error) {
13625
+ throw new Error(`invalid published RPC envelope: ${error instanceof Error ? error.message : String(error)}`);
13626
+ }
13627
+ }
13628
+
13629
+ // src/catalog/publication.ts
13630
+ var OUTER_SCHEMA = schema2([field2("result", binary2(), false)]);
13631
+ var DEFAULT_MAX = 64 * 1024 * 1024;
13632
+ var utf83 = new TextEncoder;
13633
+ var equalBytes3 = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
13634
+ async function digest(value) {
13635
+ const bytes = new Uint8Array(await crypto.subtle.digest("SHA-256", utf83.encode(value)));
13636
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
13637
+ }
13638
+ function assertRenewedPublication(before, after) {
13639
+ const unchanged = (m) => JSON.stringify([m.key, m.formatVersion, m.protocolName, m.protocolVersion, m.contractHash, m.codecRevision, m.catalogVersion, m.etag, m.sha256, m.rawSize, m.storedSize, m.objectId, m.retainUntil, m.stable, m.validated]);
13640
+ if (unchanged(before) !== unchanged(after))
13641
+ throw new Error("renewal changed immutable catalog identity");
13642
+ }
13643
+ var manifestSame = (a, b) => a.manifestId === b.manifestId;
13644
+
13645
+ class MemoryCatalogPublicationRepository {
13646
+ profile;
13647
+ storage;
13648
+ resolver;
13649
+ describe;
13650
+ manifests = new Map;
13651
+ constructor(profile, storage, resolver, describe) {
13652
+ this.profile = profile;
13653
+ this.storage = storage;
13654
+ this.resolver = resolver;
13655
+ this.describe = describe;
13656
+ }
13657
+ async lookup(key) {
13658
+ return this.manifests.get(key) ?? null;
13659
+ }
13660
+ async commitIfAbsent(manifest) {
13661
+ const existing = this.manifests.get(manifest.key);
13662
+ if (existing)
13663
+ return existing;
13664
+ const committed = Object.freeze({ ...manifest });
13665
+ this.manifests.set(manifest.key, committed);
13666
+ return committed;
13667
+ }
13668
+ async invalidate(key, expected) {
13669
+ const current = this.manifests.get(key);
13670
+ if (current && manifestSame(current, expected))
13671
+ this.manifests.delete(key);
13672
+ }
13673
+ }
13674
+
13675
+ class S3CatalogPublicationRepository {
13676
+ profile;
13677
+ storage;
13678
+ resolver;
13679
+ objects;
13680
+ describe;
13681
+ prefix;
13682
+ renewReference;
13683
+ constructor(profile, storage, resolver, objects, describe, prefix = "vgi/catalog-manifests/") {
13684
+ this.profile = profile;
13685
+ this.storage = storage;
13686
+ this.resolver = resolver;
13687
+ this.objects = objects;
13688
+ this.describe = describe;
13689
+ this.prefix = prefix;
13690
+ }
13691
+ objectKey(key) {
13692
+ if (!/^[0-9a-f]{64}$/.test(key))
13693
+ throw new Error("invalid publication key");
13694
+ return `${this.prefix}${key}.json`;
13695
+ }
13696
+ async lookup(key) {
13697
+ const value = await this.objects.get(this.objectKey(key));
13698
+ if (!value)
13699
+ return null;
13700
+ if (value.body.byteLength > 64 * 1024)
13701
+ throw new Error("catalog manifest exceeds 64 KiB");
13702
+ return JSON.parse(new TextDecoder().decode(value.body));
13703
+ }
13704
+ async commitIfAbsent(manifest) {
13705
+ const stored = await this.objects.put(this.objectKey(manifest.key), utf83.encode(JSON.stringify(manifest)), { ifNoneMatch: "*" });
13706
+ if (stored)
13707
+ return manifest;
13708
+ const current = await this.lookup(manifest.key);
13709
+ if (!current)
13710
+ throw new Error("catalog manifest changed during commit");
13711
+ return current;
13712
+ }
13713
+ async renew(manifest) {
13714
+ if (!this.renewReference)
13715
+ return null;
13716
+ const current = await this.objects.get(this.objectKey(manifest.key));
13717
+ if (!current)
13718
+ return null;
13719
+ const existing = JSON.parse(new TextDecoder().decode(current.body));
13720
+ if (!manifestSame(existing, manifest))
13721
+ return existing;
13722
+ const renewed = await this.renewReference(manifest);
13723
+ if (!renewed)
13724
+ return null;
13725
+ assertRenewedPublication(manifest, renewed);
13726
+ if (await this.objects.put(this.objectKey(manifest.key), utf83.encode(JSON.stringify(renewed)), { ifMatch: current.etag }))
13727
+ return renewed;
13728
+ return this.lookup(manifest.key);
13729
+ }
13730
+ async invalidate(key, expected) {
13731
+ const current = await this.objects.get(this.objectKey(key));
13732
+ if (current && manifestSame(JSON.parse(new TextDecoder().decode(current.body)), expected)) {
13733
+ await this.objects.delete(this.objectKey(key), { ifMatch: current.etag });
13734
+ }
13735
+ }
13736
+ }
13737
+
13738
+ class CatalogSnapshotManager {
13739
+ policy;
13740
+ cached = new Map;
13741
+ pending = new Map;
13742
+ constructor(policy) {
13743
+ this.policy = policy;
13744
+ for (const value of [policy.maxRawBytes, policy.maxStoredBytes, policy.maxCachedManifests]) {
13745
+ if (value != null && (!Number.isSafeInteger(value) || value <= 0))
13746
+ throw new Error("catalog publication limits must be positive safe integers");
13747
+ }
13748
+ if (policy.referenceGraceMs != null && (!Number.isSafeInteger(policy.referenceGraceMs) || policy.referenceGraceMs < 0))
13749
+ throw new Error("catalog publication reference grace must be a nonnegative safe integer");
13750
+ }
13751
+ usable(m) {
13752
+ const deadline = Date.now() + (this.policy.referenceGraceMs ?? 60000);
13753
+ return (m.stable || m.expiresAt != null) && (m.expiresAt == null || m.expiresAt > deadline) && (m.retainUntil == null || m.retainUntil > deadline);
13754
+ }
13755
+ async key(identity) {
13756
+ for (const value of [identity.catalogNamespace, identity.sourceRevision, identity.visibilityScope])
13757
+ if (!value)
13758
+ throw new Error("published catalogs require explicit namespace, revision and visibility scope");
13759
+ if (!Number.isSafeInteger(identity.catalogVersion))
13760
+ throw new Error("catalog version is not a safe integer");
13761
+ return digest(JSON.stringify([
13762
+ VGI_PROTOCOL_NAME,
13763
+ VGI_PROTOCOL_VERSION,
13764
+ VGI_CATALOG_CONTRACT_HASH,
13765
+ 1,
13766
+ identity.catalogNamespace,
13767
+ identity.sourceRevision,
13768
+ identity.visibilityScope,
13769
+ identity.catalogVersion,
13770
+ this.policy.repository.profile,
13771
+ this.policy.compression ?? "identity"
13772
+ ]));
13773
+ }
13774
+ remember(m) {
13775
+ this.cached.delete(m.key);
13776
+ this.cached.set(m.key, Object.freeze({ ...m }));
13777
+ while (this.cached.size > (this.policy.maxCachedManifests ?? 128))
13778
+ this.cached.delete(this.cached.keys().next().value);
13779
+ }
13780
+ async invalidate(key) {
13781
+ await this.pending.get(key)?.catch(() => {
13782
+ return;
13783
+ });
13784
+ const m = this.cached.get(key) ?? await this.policy.repository.lookup(key);
13785
+ this.cached.delete(key);
13786
+ if (m)
13787
+ await this.policy.repository.invalidate(key, m);
13788
+ }
13789
+ async validate(m, key, identity, expected) {
13790
+ if (m.formatVersion !== 1 || typeof m.manifestId !== "string" || !m.manifestId || m.key !== key || m.protocolName !== VGI_PROTOCOL_NAME || m.protocolVersion !== VGI_PROTOCOL_VERSION || m.contractHash !== VGI_CATALOG_CONTRACT_HASH || m.codecRevision !== 1 || m.catalogVersion !== identity.catalogVersion || m.validated !== true || typeof m.stable !== "boolean" || typeof m.etag !== "string" || !/^[0-9a-f]{64}$/.test(m.sha256) || !Number.isSafeInteger(m.rawSize) || !Number.isSafeInteger(m.storedSize) || m.rawSize <= 0 || m.storedSize <= 0 || m.rawSize > (this.policy.maxRawBytes ?? DEFAULT_MAX) || m.storedSize > (this.policy.maxStoredBytes ?? DEFAULT_MAX) || !this.usable(m))
13791
+ throw new Error("invalid or expired catalog publication manifest");
13792
+ const ref = new ExternalRef(m.url, m.sha256);
13793
+ const configuredFetch = this.policy.repository.resolver.fetch ?? fetch;
13794
+ const resolved = await resolveExternalLocation(ref.pointerBatch(OUTER_SCHEMA), {
13795
+ ...this.policy.repository.resolver,
13796
+ fetch: (input, init) => configuredFetch(input, { ...init, signal: AbortSignal.any([...init?.signal ? [init.signal] : [], AbortSignal.timeout(30000)]) }),
13797
+ maxFetchBytes: Math.min(this.policy.maxStoredBytes ?? DEFAULT_MAX, this.policy.repository.resolver.maxFetchBytes ?? Infinity),
13798
+ maxDecompressedBytes: Math.min(this.policy.maxRawBytes ?? DEFAULT_MAX, this.policy.repository.resolver.maxDecompressedBytes ?? Infinity),
13799
+ validateFetchedIpc: (bytes) => {
13800
+ this.policy.repository.resolver.validateFetchedIpc?.(bytes);
13801
+ if (bytes.length !== m.rawSize)
13802
+ throw new Error("catalog publication raw size mismatch");
13803
+ validateCatalogPublicationEnvelope(bytes);
13804
+ }
13805
+ });
13806
+ if (resolved.numRows !== 1 || resolved.schema.fields.length !== 1 || resolved.schema.fields[0].name !== "result" || typeSignature(resolved.schema.fields[0].type) !== typeSignature(binary2()) || resolved.schema.fields[0].nullable)
13807
+ throw new Error("invalid published RPC envelope");
13808
+ const bytes = resolved.getChild("result")?.get(0);
13809
+ if (!(bytes instanceof Uint8Array))
13810
+ throw new Error("published catalog has no result bytes");
13811
+ const decoded = decodeASDCollection(CatalogContentsResultSchema, bytes);
13812
+ if (decoded.length !== 1)
13813
+ throw new Error("published catalog must contain exactly one response row");
13814
+ const response = decoded[0];
13815
+ if (response.not_modified || Number(response.catalog_version) !== identity.catalogVersion || response.etag !== m.etag)
13816
+ throw new Error("published catalog version or ETag mismatch");
13817
+ decodeCatalogStreams(response);
13818
+ if (expected)
13819
+ for (const kind of CATALOG_STREAM_KINDS) {
13820
+ const a = response[kind], b = expected[kind];
13821
+ if (a == null !== (b == null) || a != null && b != null && !equalBytes3(a, b))
13822
+ throw new Error("publication readback changed catalog metadata");
13823
+ }
13824
+ }
13825
+ async import(manifest, identity) {
13826
+ const key = await this.key(identity);
13827
+ await this.validate(manifest, key, identity);
13828
+ const winner = await this.policy.repository.commitIfAbsent(manifest);
13829
+ if (!manifestSame(manifest, winner))
13830
+ await this.validate(winner, key, identity);
13831
+ this.remember(winner);
13832
+ return winner;
13833
+ }
13834
+ async warm(identity, build) {
13835
+ const key = await this.key(identity);
13836
+ const cached = this.cached.get(key);
13837
+ if (cached && this.usable(cached))
13838
+ return cached;
13839
+ const active = this.pending.get(key);
13840
+ if (active)
13841
+ return active;
13842
+ const pending = this.recoverOrPublish(key, identity, build);
13843
+ this.pending.set(key, pending);
13844
+ try {
13845
+ const m = await pending;
13846
+ this.remember(m);
13847
+ return m;
13848
+ } finally {
13849
+ if (this.pending.get(key) === pending)
13850
+ this.pending.delete(key);
13851
+ }
13852
+ }
13853
+ async recoverOrPublish(key, identity, build) {
13854
+ const repository = this.policy.repository;
13855
+ let existing = await repository.lookup(key);
13856
+ if (existing) {
13857
+ try {
13858
+ if (!this.usable(existing) && repository.renew) {
13859
+ const renewed = await repository.renew(existing);
13860
+ if (renewed) {
13861
+ assertRenewedPublication(existing, renewed);
13862
+ existing = renewed;
13863
+ }
13864
+ }
13865
+ await this.validate(existing, key, identity);
13866
+ return existing;
13867
+ } catch {
13868
+ await repository.invalidate(key, existing);
13869
+ }
13870
+ }
13871
+ const response = await build();
13872
+ if (response.not_modified || Number(response.catalog_version) !== identity.catalogVersion)
13873
+ throw new Error("publication requires a full snapshot of the requested version");
13874
+ decodeCatalogStreams(response);
13875
+ response.etag ??= await catalogContentsDigest(response, identity.catalogVersion);
13876
+ const payload = encodeASD(CatalogContentsResultSchema, response);
13877
+ let rawSize = 0, storedSize = 0;
13878
+ const bounded = { upload: async (data, encoding) => {
13879
+ if (encoding)
13880
+ throw new Error("catalog publication uploader requires identity encoding");
13881
+ rawSize = data.byteLength;
13882
+ if (rawSize > (this.policy.maxRawBytes ?? DEFAULT_MAX))
13883
+ throw new Error("catalog publication exceeds byte limit");
13884
+ let body = data;
13885
+ const compression = this.policy.compression ?? "identity";
13886
+ if (compression !== "identity" && compression !== "gzip" && compression !== "zstd")
13887
+ throw new Error("catalog publication compression must be identity, gzip or zstd");
13888
+ if (compression === "gzip") {
13889
+ body = new Uint8Array(await new Response(new Blob([data]).stream().pipeThrough(new CompressionStream("gzip"))).arrayBuffer());
13890
+ } else if (compression === "zstd") {
13891
+ const runtime = globalThis.Bun;
13892
+ if (typeof runtime?.zstdCompress === "function") {
13893
+ body = new Uint8Array(await runtime.zstdCompress(data));
13894
+ } else if (typeof process !== "undefined" && process.versions?.node) {
13895
+ const nodeZlib = "node:zlib";
13896
+ const zlib = await import(nodeZlib);
13897
+ if (typeof zlib.zstdCompressSync !== "function")
13898
+ throw new Error("zstd catalog publication requires Node >=22.15, Bun, or an encoder-capable runtime");
13899
+ body = new Uint8Array(zlib.zstdCompressSync(data));
13900
+ } else {
13901
+ throw new Error("zstd catalog publication requires an encoder-capable runtime; use gzip or identity here");
13902
+ }
13903
+ }
13904
+ storedSize = body.byteLength;
13905
+ if (storedSize > (this.policy.maxStoredBytes ?? DEFAULT_MAX))
13906
+ throw new Error("catalog publication exceeds byte limit");
13907
+ return repository.storage.upload(body, compression === "identity" ? "" : compression);
13908
+ } };
13909
+ const ref = await publishExternalResult(OUTER_SCHEMA, { result: payload }, bounded, { includeSha256: true });
13910
+ const m = {
13911
+ formatVersion: 1,
13912
+ manifestId: crypto.randomUUID(),
13913
+ key,
13914
+ protocolName: VGI_PROTOCOL_NAME,
13915
+ protocolVersion: VGI_PROTOCOL_VERSION,
13916
+ contractHash: VGI_CATALOG_CONTRACT_HASH,
13917
+ codecRevision: 1,
13918
+ catalogVersion: identity.catalogVersion,
13919
+ etag: response.etag,
13920
+ sha256: ref.sha256,
13921
+ rawSize,
13922
+ storedSize,
13923
+ url: ref.url,
13924
+ validated: true,
13925
+ ...await repository.describe(ref.url)
13926
+ };
13927
+ await this.validate(m, key, identity, response);
13928
+ const winner = await repository.commitIfAbsent(m);
13929
+ if (!manifestSame(m, winner))
13930
+ await this.validate(winner, key, identity);
13931
+ return winner;
13932
+ }
13933
+ }
13934
+
13410
13935
  // src/protocol/handlers/catalog/contents.ts
13936
+ var schemaPathKey3 = (path) => JSON.stringify(path.map((part) => part.toLowerCase()));
13937
+ var PUBLICATIONS = new WeakMap;
13411
13938
  var CACHE = new WeakMap;
13412
13939
  async function buildCatalogContents(cat, owner, attach, version, ifNoneMatch) {
13413
13940
  const result = await cat.catalogContents(attach, ifNoneMatch);
@@ -13422,39 +13949,74 @@ async function buildCatalogContents(cat, owner, attach, version, ifNoneMatch) {
13422
13949
  return buildCatalogContentsResponse({ catalog_version: version, etag: etag0, not_modified: true });
13423
13950
  }
13424
13951
  const infos = [...result.schemas ?? []];
13425
- const keys = infos.map((c) => schemaPathKey(c.schema.path));
13952
+ const keys = infos.map((c) => schemaPathKey3(c.schema.path));
13426
13953
  const keySet = new Set(keys);
13427
13954
  if (keySet.size !== keys.length)
13428
13955
  throw new Error("catalog_contents returned duplicate schema paths");
13429
13956
  for (const c of infos) {
13430
- if (c.schema.path.length > 1 && !keySet.has(schemaPathKey(c.schema.path.slice(0, -1)))) {
13957
+ if (c.schema.path.length > 1 && !keySet.has(schemaPathKey3(c.schema.path.slice(0, -1)))) {
13431
13958
  throw new Error(`catalog_contents returned schema path ${JSON.stringify(c.schema.path)} without its parent`);
13432
13959
  }
13433
13960
  }
13434
- const schemas = infos.sort((a, b) => a.schema.path.length - b.schema.path.length).map((c) => buildSchemaContents({
13435
- path: [...c.schema.path],
13436
- schema: encodeSchemaInfo(c.schema),
13437
- tables: c.tables.map((t) => encodeTableInfo(t)),
13438
- views: c.views.map((v) => encodeViewInfo(v)),
13439
- scalar_functions: c.scalar_functions.map((f) => encodeFunctionInfoOnce(f)),
13440
- aggregate_functions: c.aggregate_functions.map((f) => encodeFunctionInfoOnce(f)),
13441
- table_functions: c.table_functions.map((f) => encodeFunctionInfoOnce(f)),
13442
- scalar_macros: c.scalar_macros.map((m) => encodeMacroInfo(m)),
13443
- table_macros: c.table_macros.map((m) => encodeMacroInfo(m)),
13444
- indexes: c.indexes.map((i) => encodeIndexInfo(i))
13445
- }));
13961
+ const streams = encodeCatalogStreams(infos.sort((a, b) => a.schema.path.length - b.schema.path.length));
13446
13962
  let etag = etag0;
13447
13963
  if (etag === null && owner.catalogContentsEtag === "content-hash") {
13448
- etag = await catalogContentsDigest(schemas);
13964
+ etag = await catalogContentsDigest(streams, version);
13449
13965
  }
13450
13966
  if (etag !== null && ifNoneMatch !== null && etag === ifNoneMatch) {
13451
13967
  return buildCatalogContentsResponse({ catalog_version: version, etag, not_modified: true });
13452
13968
  }
13453
- return buildCatalogContentsResponse({ catalog_version: version, etag, schemas });
13969
+ const response = buildCatalogContentsResponse({ catalog_version: version, etag, ...streams });
13970
+ decodeCatalogStreams(response);
13971
+ return response;
13454
13972
  }
13455
- async function serveCatalogContents(cat, attach, ifNoneMatch) {
13973
+ async function serveCatalogContents(cat, attach, ifNoneMatch, callContext, sealedAttach = attach) {
13456
13974
  const owner = cat.catalogContentsOwner(attach);
13457
13975
  const version = Number(await cat.version(attach));
13976
+ const policy = owner.catalogSnapshotPolicy;
13977
+ if (policy?.delivery === "published") {
13978
+ const request = { catalog: cat, attachOpaqueData: attach, callContext, catalogVersion: version };
13979
+ const inline = (etag) => wrapResult(buildCatalogContentsResponse({ catalog_version: version, etag, not_modified: true }), CatalogContentsResultSchema);
13980
+ const cheapEtag = await policy.etag?.(request);
13981
+ if (cheapEtag != null && cheapEtag === ifNoneMatch)
13982
+ return inline(cheapEtag);
13983
+ let manager = PUBLICATIONS.get(policy);
13984
+ if (!manager) {
13985
+ manager = new CatalogSnapshotManager(policy);
13986
+ PUBLICATIONS.set(policy, manager);
13987
+ }
13988
+ const scopeBytes = new Uint8Array(await crypto.subtle.digest("SHA-256", sealedAttach));
13989
+ const attachmentScope = "attachment:" + Array.from(scopeBytes, (b) => b.toString(16).padStart(2, "0")).join("");
13990
+ const identify = async (input) => {
13991
+ const id = await policy.identity(input);
13992
+ return { ...id, visibilityScope: id.visibilityScope ?? attachmentScope };
13993
+ };
13994
+ const identity = await identify(request);
13995
+ if (identity.catalogVersion !== version)
13996
+ throw new Error("snapshot identity version differs from the attached catalog");
13997
+ const assertCurrentIdentity = async () => {
13998
+ const currentVersion = Number(await cat.version(attach));
13999
+ const current = await identify({ ...request, catalogVersion: currentVersion });
14000
+ if (currentVersion !== version || await manager.key(identity) !== await manager.key(current))
14001
+ throw new Error("catalog changed while resolving its publication");
14002
+ };
14003
+ const buildSnapshot = async (validator) => {
14004
+ const response = await buildCatalogContents(cat, owner, attach, version, validator);
14005
+ await assertCurrentIdentity();
14006
+ return response;
14007
+ };
14008
+ try {
14009
+ const manifest = await manager.warm(identity, () => buildSnapshot(null));
14010
+ await assertCurrentIdentity();
14011
+ if (manifest.etag === ifNoneMatch)
14012
+ return inline(manifest.etag);
14013
+ return new ExternalRef2(manifest.url, manifest.sha256);
14014
+ } catch (error) {
14015
+ if (policy.onPublicationFailure !== "ordinary")
14016
+ throw error;
14017
+ return wrapResult(await buildSnapshot(ifNoneMatch), CatalogContentsResultSchema);
14018
+ }
14019
+ }
13458
14020
  if (owner.catalogContentsCacheable()) {
13459
14021
  let pending = CACHE.get(owner);
13460
14022
  let snapshot = pending ? await pending.catch(() => null) : null;
@@ -13966,10 +14528,13 @@ function catalogAdminHandlers(getCatalog, signingKey) {
13966
14528
  items: schemas.map((s) => encodeSchemaInfo(s))
13967
14529
  }, CatalogSchemasResultSchema);
13968
14530
  });
13969
- const catalogContents = catalogHandler(signingKey, async (params) => {
13970
- const ifNoneMatch = params.if_none_match == null ? null : String(params.if_none_match);
13971
- return serveCatalogContents(getCatalog(), toUint8Array(params.attach_opaque_data), ifNoneMatch);
13972
- });
14531
+ const catalogContents = async (params, ctx) => {
14532
+ const sealedAttach = toUint8Array(params.attach_opaque_data).slice();
14533
+ return catalogHandler(signingKey, async (opened, context) => {
14534
+ const ifNoneMatch = opened.if_none_match == null ? null : String(opened.if_none_match);
14535
+ return serveCatalogContents(getCatalog(), toUint8Array(opened.attach_opaque_data), ifNoneMatch, context, sealedAttach);
14536
+ })(params, ctx);
14537
+ };
13973
14538
  const catalogCopyFromFormats = catalogHandler(signingKey, async (params) => {
13974
14539
  const cat = getCatalog();
13975
14540
  const formats = await cat.copyFromFormats(toUint8Array(params.attach_opaque_data), params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
@@ -14896,23 +15461,7 @@ class VgiClient {
14896
15461
  if (!result)
14897
15462
  throw new VgiClientError("catalog_contents returned null");
14898
15463
  const response = decodeCatalogContentsResponse(toUint8Array(result.result));
14899
- const schemas = response.schemas.map((c) => {
14900
- const schema = decodeSchemaInfo(c.schema);
14901
- if (JSON.stringify(c.path) !== JSON.stringify(schema.path)) {
14902
- throw new VgiClientError(`catalog_contents: SchemaContents.path ${JSON.stringify(c.path)} != SchemaInfo.path ${JSON.stringify(schema.path)}`);
14903
- }
14904
- return {
14905
- schema,
14906
- tables: c.tables.map(decodeTableInfo),
14907
- views: c.views.map(decodeViewInfo),
14908
- scalar_functions: c.scalar_functions.map(decodeFunctionInfo),
14909
- aggregate_functions: c.aggregate_functions.map(decodeFunctionInfo),
14910
- table_functions: c.table_functions.map(decodeFunctionInfo),
14911
- scalar_macros: c.scalar_macros.map(decodeMacroInfo),
14912
- table_macros: c.table_macros.map(decodeMacroInfo),
14913
- indexes: c.indexes.map(decodeIndexInfo)
14914
- };
14915
- });
15464
+ const schemas = decodeCatalogStreams(response, ifNoneMatch);
14916
15465
  return {
14917
15466
  catalog_version: Number(response.catalog_version ?? 0),
14918
15467
  etag: response.etag ?? null,
@@ -15741,6 +16290,111 @@ ${err.stack}
15741
16290
  await serveStreamRpc(this.buildServer(this.buildProtocol(), "stream"), { readable, writable });
15742
16291
  }
15743
16292
  }
16293
+ // src/catalog/s3-publication.ts
16294
+ class S3CatalogObjectStorage {
16295
+ sign;
16296
+ request;
16297
+ objectPrefix;
16298
+ retentionMs;
16299
+ locations = new Map;
16300
+ constructor(sign, request = fetch, objectPrefix = "vgi/catalog-results/", retentionMs) {
16301
+ this.sign = sign;
16302
+ this.request = request;
16303
+ this.objectPrefix = objectPrefix;
16304
+ this.retentionMs = retentionMs;
16305
+ }
16306
+ async upload(data, contentEncoding) {
16307
+ const key = `${this.objectPrefix}${crypto.randomUUID()}.arrow`;
16308
+ const headers = { "Content-Type": "application/vnd.apache.arrow.stream", "If-None-Match": "*" };
16309
+ if (contentEncoding)
16310
+ headers["Content-Encoding"] = contentEncoding;
16311
+ const put = await this.sign({ key, method: "PUT", headers });
16312
+ const response = await this.request(put.url, { method: "PUT", headers, body: data, redirect: "error", signal: AbortSignal.timeout(30000) });
16313
+ if (!response.ok)
16314
+ throw new Error(`catalog object upload failed (${response.status})`);
16315
+ const get = await this.sign({ key, method: "GET", headers: {} });
16316
+ if (!get.stable && get.expiresAt == null)
16317
+ throw new Error("S3 catalog signer must declare GET URL expiration or stability");
16318
+ this.locations.set(get.url, {
16319
+ objectId: key,
16320
+ expiresAt: get.expiresAt,
16321
+ stable: get.stable ?? false,
16322
+ retainUntil: this.retentionMs == null ? undefined : Date.now() + this.retentionMs
16323
+ });
16324
+ return get.url;
16325
+ }
16326
+ async describe(url) {
16327
+ const value = this.locations.get(url);
16328
+ if (!value)
16329
+ throw new Error("unknown catalog object location");
16330
+ this.locations.delete(url);
16331
+ return value;
16332
+ }
16333
+ async get(key) {
16334
+ const signed = await this.sign({ key, method: "GET", headers: {} });
16335
+ const response = await this.request(signed.url, { redirect: "error", signal: AbortSignal.timeout(30000) });
16336
+ if (response.status === 404)
16337
+ return null;
16338
+ if (!response.ok)
16339
+ throw new Error(`catalog manifest GET failed (${response.status})`);
16340
+ const etag = response.headers.get("etag");
16341
+ if (!etag)
16342
+ throw new Error("S3 catalog manifest lacks conditional-operation ETag");
16343
+ const reader = response.body?.getReader();
16344
+ if (!reader)
16345
+ throw new Error("empty catalog manifest body");
16346
+ let size = 0;
16347
+ const parts = [];
16348
+ while (true) {
16349
+ const { done, value } = await reader.read();
16350
+ if (done)
16351
+ break;
16352
+ size += value.byteLength;
16353
+ if (size > 64 * 1024) {
16354
+ await reader.cancel();
16355
+ throw new Error("catalog manifest exceeds 64 KiB");
16356
+ }
16357
+ parts.push(value);
16358
+ }
16359
+ const body = new Uint8Array(size);
16360
+ let offset = 0;
16361
+ for (const part of parts) {
16362
+ body.set(part, offset);
16363
+ offset += part.byteLength;
16364
+ }
16365
+ return { body, etag };
16366
+ }
16367
+ async put(key, body, condition) {
16368
+ const headers = { "Content-Type": "application/json", ..."ifNoneMatch" in condition ? { "If-None-Match": condition.ifNoneMatch } : { "If-Match": condition.ifMatch } };
16369
+ const signed = await this.sign({ key, method: "PUT", headers });
16370
+ const response = await this.request(signed.url, { method: "PUT", headers, body, redirect: "error", signal: AbortSignal.timeout(30000) });
16371
+ if (response.status === 412 || response.status === 409)
16372
+ return false;
16373
+ if (!response.ok)
16374
+ throw new Error(`catalog manifest PUT failed (${response.status})`);
16375
+ return true;
16376
+ }
16377
+ async delete(key, condition) {
16378
+ const headers = { "If-Match": condition.ifMatch };
16379
+ const signed = await this.sign({ key, method: "DELETE", headers });
16380
+ const response = await this.request(signed.url, { method: "DELETE", headers, redirect: "error", signal: AbortSignal.timeout(30000) });
16381
+ if (response.status === 412 || response.status === 404)
16382
+ return false;
16383
+ if (!response.ok)
16384
+ throw new Error(`catalog manifest DELETE failed (${response.status})`);
16385
+ return true;
16386
+ }
16387
+ repository(profile, resolver = {}, manifestPrefix = "vgi/catalog-manifests/") {
16388
+ const repository = new S3CatalogPublicationRepository(profile, this, { ...resolver, storage: this }, this, (url) => this.describe(url), manifestPrefix);
16389
+ repository.renewReference = async (manifest) => {
16390
+ if (!manifest.objectId)
16391
+ return null;
16392
+ const signed = await this.sign({ key: manifest.objectId, method: "GET", headers: {} });
16393
+ return { ...manifest, manifestId: crypto.randomUUID(), url: signed.url, expiresAt: signed.expiresAt, stable: signed.stable ?? false };
16394
+ };
16395
+ return repository;
16396
+ }
16397
+ }
15744
16398
  export {
15745
16399
  ATTACH_TICKETS_PROTOCOL_NAME,
15746
16400
  ATTACH_TICKETS_PROTOCOL_VERSION,
@@ -15778,6 +16432,7 @@ export {
15778
16432
  CatalogInterface,
15779
16433
  CatalogNotFoundError,
15780
16434
  CatalogReadOnlyError,
16435
+ CatalogSnapshotManager,
15781
16436
  ComparisonOp,
15782
16437
  CompositeCatalogInterface,
15783
16438
  DEFAULT_MAX_WORKERS,
@@ -15797,6 +16452,7 @@ export {
15797
16452
  INTROSPECT_PRINCIPALS_ENV,
15798
16453
  IdentityUnavailableError,
15799
16454
  IntervalUnit2 as IntervalUnit,
16455
+ MemoryCatalogPublicationRepository,
15800
16456
  NoCatalogError,
15801
16457
  NullHandling,
15802
16458
  OrderDependence,
@@ -15809,6 +16465,8 @@ export {
15809
16465
  ReadOnlyCatalogInterface,
15810
16466
  ReservedAttachOptionError,
15811
16467
  RowCountMismatchError,
16468
+ S3CatalogObjectStorage,
16469
+ S3CatalogPublicationRepository,
15812
16470
  SEAL_ATTACH_REQUEST_SCHEMA,
15813
16471
  ScanFunctionResultSchema,
15814
16472
  SealAttachDeniedError,
@@ -16011,4 +16669,4 @@ export {
16011
16669
  utf82 as utf8
16012
16670
  };
16013
16671
 
16014
- //# debugId=2C6F34EB0944BDD764756E2164756E21
16672
+ //# debugId=0EC791465ED38B7C64756E2164756E21