@adcp/sdk 15.3.0 → 15.5.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 (130) hide show
  1. package/dist/lib/advanced.d.mts +2 -2
  2. package/dist/lib/advanced.d.ts +2 -2
  3. package/dist/lib/advanced.js +8 -2
  4. package/dist/lib/advanced.mjs +8 -2
  5. package/dist/lib/core/AgentClient.d.mts +4 -0
  6. package/dist/lib/core/AgentClient.d.ts +4 -0
  7. package/dist/lib/core/AgentClient.js +8 -0
  8. package/dist/lib/core/AgentClient.mjs +8 -0
  9. package/dist/lib/core/SingleAgentClient.d.mts +154 -0
  10. package/dist/lib/core/SingleAgentClient.d.ts +154 -0
  11. package/dist/lib/core/SingleAgentClient.js +661 -23
  12. package/dist/lib/core/SingleAgentClient.mjs +666 -23
  13. package/dist/lib/core/agent-discovery-cache.d.mts +103 -0
  14. package/dist/lib/core/agent-discovery-cache.d.ts +103 -0
  15. package/dist/lib/core/agent-discovery-cache.js +121 -0
  16. package/dist/lib/core/agent-discovery-cache.mjs +92 -0
  17. package/dist/lib/index.d.mts +5 -3
  18. package/dist/lib/index.d.ts +5 -3
  19. package/dist/lib/index.js +7 -0
  20. package/dist/lib/index.mjs +6 -0
  21. package/dist/lib/protocols/index.d.mts +2 -2
  22. package/dist/lib/protocols/index.d.ts +2 -2
  23. package/dist/lib/protocols/index.js +1 -1
  24. package/dist/lib/protocols/index.mjs +1 -1
  25. package/dist/lib/protocols/mcp-call-context.d.mts +109 -0
  26. package/dist/lib/protocols/mcp-call-context.d.ts +109 -0
  27. package/dist/lib/protocols/mcp-call-context.js +221 -0
  28. package/dist/lib/protocols/mcp-call-context.mjs +186 -0
  29. package/dist/lib/protocols/mcp-modern.d.mts +9 -1
  30. package/dist/lib/protocols/mcp-modern.d.ts +9 -1
  31. package/dist/lib/protocols/mcp-modern.js +180 -104
  32. package/dist/lib/protocols/mcp-modern.mjs +193 -104
  33. package/dist/lib/protocols/mcp-scope.d.mts +15 -0
  34. package/dist/lib/protocols/mcp-scope.d.ts +15 -0
  35. package/dist/lib/protocols/mcp.d.mts +4 -2
  36. package/dist/lib/protocols/mcp.d.ts +4 -2
  37. package/dist/lib/protocols/mcp.js +178 -154
  38. package/dist/lib/protocols/mcp.mjs +189 -153
  39. package/dist/lib/protocols/transportDiagnostics.d.mts +33 -1
  40. package/dist/lib/protocols/transportDiagnostics.d.ts +33 -1
  41. package/dist/lib/protocols/transportDiagnostics.js +128 -12
  42. package/dist/lib/protocols/transportDiagnostics.mjs +128 -12
  43. package/dist/lib/reporting/gcs/index.d.mts +2 -0
  44. package/dist/lib/reporting/gcs/index.d.ts +2 -0
  45. package/dist/lib/reporting/gcs/index.js +3 -0
  46. package/dist/lib/reporting/gcs/index.mjs +2 -0
  47. package/dist/lib/reporting/gcs/row-provider.d.mts +32 -0
  48. package/dist/lib/reporting/gcs/row-provider.d.ts +32 -0
  49. package/dist/lib/reporting/gcs/row-provider.js +205 -0
  50. package/dist/lib/reporting/gcs/row-provider.mjs +188 -0
  51. package/dist/lib/reporting/ledger/change-feed.d.mts +41 -0
  52. package/dist/lib/reporting/ledger/change-feed.d.ts +41 -0
  53. package/dist/lib/reporting/ledger/change-feed.js +101 -0
  54. package/dist/lib/reporting/ledger/change-feed.mjs +74 -0
  55. package/dist/lib/reporting/ledger/handler.d.mts +6 -0
  56. package/dist/lib/reporting/ledger/handler.d.ts +6 -0
  57. package/dist/lib/reporting/ledger/handler.js +51 -8
  58. package/dist/lib/reporting/ledger/handler.mjs +50 -8
  59. package/dist/lib/reporting/ledger/index.d.mts +5 -0
  60. package/dist/lib/reporting/ledger/index.d.ts +5 -0
  61. package/dist/lib/reporting/ledger/index.js +11 -1
  62. package/dist/lib/reporting/ledger/index.mjs +5 -0
  63. package/dist/lib/reporting/ledger/lifecycle.js +3 -2
  64. package/dist/lib/reporting/ledger/lifecycle.mjs +3 -2
  65. package/dist/lib/reporting/ledger/managed-postgres.d.mts +2 -0
  66. package/dist/lib/reporting/ledger/managed-postgres.d.ts +2 -0
  67. package/dist/lib/reporting/ledger/managed-postgres.js +26 -6
  68. package/dist/lib/reporting/ledger/managed-postgres.mjs +26 -6
  69. package/dist/lib/reporting/ledger/managed.d.mts +9 -0
  70. package/dist/lib/reporting/ledger/managed.d.ts +9 -0
  71. package/dist/lib/reporting/ledger/managed.js +18 -0
  72. package/dist/lib/reporting/ledger/managed.mjs +18 -0
  73. package/dist/lib/reporting/ledger/postgres.d.mts +179 -1
  74. package/dist/lib/reporting/ledger/postgres.d.ts +179 -1
  75. package/dist/lib/reporting/ledger/postgres.js +882 -19
  76. package/dist/lib/reporting/ledger/postgres.mjs +890 -19
  77. package/dist/lib/reporting/ledger/producer.js +13 -3
  78. package/dist/lib/reporting/ledger/producer.mjs +13 -3
  79. package/dist/lib/reporting/ledger/revision-metadata.d.mts +17 -0
  80. package/dist/lib/reporting/ledger/revision-metadata.d.ts +17 -0
  81. package/dist/lib/reporting/ledger/revision-metadata.js +71 -0
  82. package/dist/lib/reporting/ledger/revision-metadata.mjs +44 -0
  83. package/dist/lib/reporting/ledger/row-encoding.d.mts +128 -0
  84. package/dist/lib/reporting/ledger/row-encoding.d.ts +128 -0
  85. package/dist/lib/reporting/ledger/row-encoding.js +355 -0
  86. package/dist/lib/reporting/ledger/row-encoding.mjs +315 -0
  87. package/dist/lib/reporting/ledger/row-storage-errors.d.mts +7 -0
  88. package/dist/lib/reporting/ledger/row-storage-errors.d.ts +7 -0
  89. package/dist/lib/reporting/ledger/row-storage-errors.js +41 -0
  90. package/dist/lib/reporting/ledger/row-storage-errors.mjs +16 -0
  91. package/dist/lib/reporting/ledger/row-storage-migration.d.mts +41 -0
  92. package/dist/lib/reporting/ledger/row-storage-migration.d.ts +41 -0
  93. package/dist/lib/reporting/ledger/row-storage-migration.js +234 -0
  94. package/dist/lib/reporting/ledger/row-storage-migration.mjs +208 -0
  95. package/dist/lib/reporting/ledger/row-storage-object.d.mts +112 -0
  96. package/dist/lib/reporting/ledger/row-storage-object.d.ts +112 -0
  97. package/dist/lib/reporting/ledger/row-storage-object.js +281 -0
  98. package/dist/lib/reporting/ledger/row-storage-object.mjs +239 -0
  99. package/dist/lib/reporting/ledger/row-storage-provider-io.d.mts +51 -0
  100. package/dist/lib/reporting/ledger/row-storage-provider-io.d.ts +51 -0
  101. package/dist/lib/reporting/ledger/row-storage-provider-io.js +152 -0
  102. package/dist/lib/reporting/ledger/row-storage-provider-io.mjs +119 -0
  103. package/dist/lib/reporting/ledger/row-storage.d.mts +224 -0
  104. package/dist/lib/reporting/ledger/row-storage.d.ts +224 -0
  105. package/dist/lib/reporting/ledger/row-storage.js +692 -0
  106. package/dist/lib/reporting/ledger/row-storage.mjs +680 -0
  107. package/dist/lib/reporting/ledger/types.d.mts +45 -0
  108. package/dist/lib/reporting/ledger/types.d.ts +45 -0
  109. package/dist/lib/reporting/service/index.d.mts +41 -1
  110. package/dist/lib/reporting/service/index.d.ts +41 -1
  111. package/dist/lib/reporting/service/index.js +68 -1
  112. package/dist/lib/reporting/service/index.mjs +70 -1
  113. package/dist/lib/schemas-data/v2.5/_provenance.json +1 -1
  114. package/dist/lib/signing/agent-resolver/fetch-helpers.js +1 -1
  115. package/dist/lib/signing/agent-resolver/fetch-helpers.mjs +1 -1
  116. package/dist/lib/testing/storyboard/validations.d.mts +1 -1
  117. package/dist/lib/testing/storyboard/validations.d.ts +1 -1
  118. package/dist/lib/version.d.mts +3 -3
  119. package/dist/lib/version.d.ts +3 -3
  120. package/dist/lib/version.js +3 -3
  121. package/dist/lib/version.mjs +3 -3
  122. package/docs/README.md +1 -1
  123. package/docs/TYPE-SUMMARY.md +35 -2
  124. package/docs/guides/DISCOVERY-CACHE-AND-SESSION-REUSE.md +142 -0
  125. package/docs/guides/EXISTING-PLATFORM.md +43 -12
  126. package/docs/guides/REPORTING-LEDGER.md +209 -0
  127. package/docs/llms.txt +4 -2
  128. package/docs/migration-14.x-rc-worksheet.md +4 -4
  129. package/docs/recipes/verifying-inbound-webhooks.md +8 -0
  130. package/package.json +1 -1
@@ -0,0 +1,692 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var row_storage_exports = {};
20
+ __export(row_storage_exports, {
21
+ ReportingRowStorageV1: () => ReportingRowStorageV1,
22
+ ReportingRowStoreError: () => import_row_storage_errors2.ReportingRowStoreError,
23
+ isReportingRowStoreError: () => import_row_storage_errors2.isReportingRowStoreError,
24
+ reportingRowWriteIntentIdV1: () => reportingRowWriteIntentIdV1
25
+ });
26
+ module.exports = __toCommonJS(row_storage_exports);
27
+ var import_crypto = require("crypto");
28
+ var import_zlib = require("zlib");
29
+ var import_jcs = require('../../utils/jcs.js');
30
+ var import_row_encoding = require('./row-encoding.js');
31
+ var import_row_storage_migration = require('./row-storage-migration.js');
32
+ var import_row_storage_errors = require('./row-storage-errors.js');
33
+ var import_row_storage_object = require('./row-storage-object.js');
34
+ var import_row_storage_errors2 = require('./row-storage-errors.js');
35
+ const DEFAULT_BINDING_ID = "postgres";
36
+ const BINDING_ID = /^[A-Za-z0-9_.:-]{1,128}$/;
37
+ const CREDENTIAL_REF = /^[A-Za-z0-9_.:-]{1,128}$/;
38
+ const MAX_ADOPTED_OBJECT_BYTES = 2 * import_row_encoding.REPORTING_ROW_CHUNK_MAX_BYTES + 1024 * 1024;
39
+ class ReportingRowStorageV1 {
40
+ constructor(pool, options = {}) {
41
+ this.pool = pool;
42
+ this.options = options;
43
+ const bindings = options.bindings ?? { [DEFAULT_BINDING_ID]: { kind: "postgres" } };
44
+ this.providers = Object.freeze({ ...options.providers ?? {} });
45
+ const ids = Object.keys(bindings);
46
+ if (ids.length === 0) throw new import_row_storage_errors.ReportingRowStoreError("INVALID_INPUT", "at least one row binding is required");
47
+ for (const id of ids) {
48
+ if (!BINDING_ID.test(id)) throw new import_row_storage_errors.ReportingRowStoreError("INVALID_INPUT", `invalid row binding ID ${id}`);
49
+ const binding = bindings[id];
50
+ if (binding.kind === "postgres") continue;
51
+ if (binding.kind !== "object") {
52
+ throw new import_row_storage_errors.ReportingRowStoreError("INVALID_INPUT", `row binding ${id} has an unsupported kind`);
53
+ }
54
+ const provider = this.providers[binding.provider];
55
+ if (!provider) throw new import_row_storage_errors.ReportingRowStoreError("INVALID_INPUT", `row binding ${id} names an unknown provider`);
56
+ provider.validateLocation(binding.location);
57
+ (0, import_row_storage_object.assertReportingRowPrefixV1)(binding.prefix);
58
+ (0, import_row_storage_object.assertReportingRowKeyTemplateV1)(binding.keyTemplate ?? import_row_storage_object.REPORTING_ROW_DEFAULT_KEY_TEMPLATE);
59
+ if (binding.credentialRef !== void 0 && !CREDENTIAL_REF.test(binding.credentialRef)) {
60
+ throw new import_row_storage_errors.ReportingRowStoreError("INVALID_INPUT", `row binding ${id} has an invalid credentialRef`);
61
+ }
62
+ }
63
+ this.bindings = Object.freeze({ ...bindings });
64
+ this.deploymentNamespace = options.deploymentNamespace ?? "default";
65
+ if (!this.deploymentNamespace || this.deploymentNamespace.length > 256) {
66
+ throw new import_row_storage_errors.ReportingRowStoreError("INVALID_INPUT", "deploymentNamespace must be 1-256 characters");
67
+ }
68
+ this.writeDeadline = positiveMilliseconds(options.writeDeadlineMilliseconds ?? 6e4, "writeDeadlineMilliseconds");
69
+ this.readDeadline = positiveMilliseconds(options.readDeadlineMilliseconds ?? 3e4, "readDeadlineMilliseconds");
70
+ }
71
+ pool;
72
+ options;
73
+ bindings;
74
+ providers;
75
+ deploymentNamespace;
76
+ writeDeadline;
77
+ readDeadline;
78
+ readied;
79
+ installation;
80
+ /** Deadline budget a writer must still hold on its lease before uploading. */
81
+ get writeDeadlineMilliseconds() {
82
+ return this.writeDeadline;
83
+ }
84
+ /** Probe the schema and every provider, and register (or verify) every configured binding. Idempotent. */
85
+ ready() {
86
+ this.readied ??= this.register().catch((error) => {
87
+ this.readied = void 0;
88
+ throw error;
89
+ });
90
+ return this.readied;
91
+ }
92
+ /** Encode rows, prove the chunks reproduce the committed binding, select a binding and plan objects. */
93
+ async prepare(input) {
94
+ await this.ready();
95
+ let encoded;
96
+ try {
97
+ encoded = (0, import_row_encoding.encodeReportingRowsV1)(input.rows);
98
+ } catch (error) {
99
+ if ((0, import_row_encoding.isReportingRowEncodingError)(error)) throw new import_row_storage_errors.ReportingRowStoreError("INVALID_INPUT", error.message);
100
+ throw error;
101
+ }
102
+ const digestProfile = input.rowSetKind === "revision" ? "revision_envelope_v1" : "rows_v1";
103
+ const hasher = digestProfile === "revision_envelope_v1" ? (0, import_row_encoding.createReportingRevisionEnvelopeHasherV1)({
104
+ reporting_revision_id: input.rowSetId,
105
+ row_count: input.rows.length,
106
+ control_totals: input.controlTotals ?? []
107
+ }) : (0, import_row_encoding.createReportingRowsOnlyHasherV1)(input.rows.length);
108
+ for (const chunk of encoded.chunks) hasher.update(chunk.bytes);
109
+ const digest = hasher.digest();
110
+ if (digest.sha256 !== input.binding.sha256 || digest.byteCount !== input.binding.byteCount || input.binding.rowCount !== input.rows.length) {
111
+ throw new import_row_storage_errors.ReportingRowStoreError("INVALID_INPUT", "rows do not reproduce their committed binding");
112
+ }
113
+ const ids = Object.keys(this.bindings);
114
+ const bindingId = input.bindingId ? input.bindingId : this.options.selectRowBinding ? await this.options.selectRowBinding({
115
+ account_id: input.accountId,
116
+ reporting_obligation_id: input.obligationId,
117
+ row_set_kind: input.rowSetKind,
118
+ ...input.finality ? { finality: input.finality } : {},
119
+ row_count: input.rows.length,
120
+ canonical_byte_count: digest.byteCount
121
+ }) : ids.length === 1 ? ids[0] : DEFAULT_BINDING_ID;
122
+ const binding = this.bindings[bindingId];
123
+ if (!binding) throw new import_row_storage_errors.ReportingRowStoreError("STATE_UNAVAILABLE", `row binding ${bindingId} is not configured`);
124
+ if (binding.kind === "postgres") return Object.freeze({ input, encoded, bindingId, binding, digestProfile });
125
+ const compression = binding.compression ?? "gzip";
126
+ const namespaceKey = this.installation.namespaceKey;
127
+ const objects = encoded.chunks.map((chunk) => {
128
+ const physicalBytes = compression === "gzip" ? (0, import_zlib.gzipSync)(chunk.bytes, { level: 6 }) : chunk.bytes;
129
+ return Object.freeze({
130
+ key: (0, import_row_storage_object.renderReportingRowObjectKeyV1)({
131
+ template: binding.keyTemplate ?? import_row_storage_object.REPORTING_ROW_DEFAULT_KEY_TEMPLATE,
132
+ prefix: binding.prefix,
133
+ namespaceKey,
134
+ accountId: input.accountId,
135
+ rowSetId: input.rowSetId,
136
+ ...input.periodStart ? { periodStart: input.periodStart } : {},
137
+ ...input.finality ? { finality: input.finality } : {},
138
+ contentSha256: input.binding.sha256,
139
+ chunkIndex: chunk.manifest.chunk_index,
140
+ compression
141
+ }),
142
+ physicalBytes,
143
+ physicalSha256: sha256Hex(physicalBytes),
144
+ compression
145
+ });
146
+ });
147
+ return Object.freeze({ input, encoded, bindingId, binding, digestProfile, objects: Object.freeze(objects) });
148
+ }
149
+ /**
150
+ * Upload a prepared object-kind row set, create-only. An object already at a
151
+ * planned key is adopted only when its bytes decode to the exact chunk;
152
+ * otherwise `CONTENT_CONFLICT`. `onCreated` is awaited for every object this
153
+ * call created, before the next upload, so the caller can record it in its
154
+ * write intent.
155
+ */
156
+ async upload(prepared, intentId, onCreated, signal) {
157
+ const binding = prepared.binding;
158
+ if (binding.kind !== "object" || !prepared.objects) {
159
+ throw new import_row_storage_errors.ReportingRowStoreError("INVALID_INPUT", "only object-kind row sets are uploaded");
160
+ }
161
+ const provider = this.providers[binding.provider];
162
+ const context = { signal: deadlineSignal(this.writeDeadline, signal) };
163
+ const location = providerLocation(binding);
164
+ const locators = [];
165
+ for (const [index, object] of prepared.objects.entries()) {
166
+ const manifest = prepared.encoded.manifests[index];
167
+ const put = await this.provider(
168
+ () => provider.putIfAbsent(
169
+ {
170
+ ...location,
171
+ key: object.key,
172
+ bytes: object.physicalBytes,
173
+ contentType: object.compression === "gzip" ? "application/gzip" : "application/x-ndjson",
174
+ metadata: {
175
+ "adcp-installation": this.installation.installationId,
176
+ "adcp-intent": intentId
177
+ }
178
+ },
179
+ context
180
+ )
181
+ );
182
+ if (put.created) {
183
+ await onCreated({ objectKey: object.key, nativeVersion: put.nativeVersion });
184
+ locators.push({
185
+ objectKey: object.key,
186
+ nativeVersion: put.nativeVersion,
187
+ compression: object.compression,
188
+ physicalSha256: object.physicalSha256,
189
+ physicalByteCount: object.physicalBytes.byteLength,
190
+ created: true
191
+ });
192
+ continue;
193
+ }
194
+ const existing = await this.provider(
195
+ () => provider.get(
196
+ { ...location, key: object.key, nativeVersion: put.nativeVersion, maxBytes: MAX_ADOPTED_OBJECT_BYTES },
197
+ context
198
+ )
199
+ );
200
+ const logical = existing ? this.inflate(Buffer.from(existing), object.compression, manifest.byte_count) : null;
201
+ if (!existing || !logical || sha256Hex(logical) !== manifest.sha256) {
202
+ throw new import_row_storage_errors.ReportingRowStoreError("CONTENT_CONFLICT", `object for chunk ${index} holds different bytes`);
203
+ }
204
+ locators.push({
205
+ objectKey: object.key,
206
+ nativeVersion: put.nativeVersion,
207
+ compression: object.compression,
208
+ physicalSha256: sha256Hex(existing),
209
+ physicalByteCount: existing.byteLength,
210
+ created: false
211
+ });
212
+ }
213
+ return locators;
214
+ }
215
+ /**
216
+ * Persist a prepared row set inside the caller's ledger transaction:
217
+ * bodies for the `postgres` kind, or the uploaded locators for the object
218
+ * kind. Replays of an identical row set are no-ops; a conflicting row set
219
+ * under the same ID is refused.
220
+ */
221
+ async writeInTransaction(transaction, prepared, locators, sharedFromRowSetId) {
222
+ const { input, encoded } = prepared;
223
+ if (prepared.binding.kind === "object" && locators?.length !== encoded.chunks.length) {
224
+ throw new import_row_storage_errors.ReportingRowStoreError("INVALID_INPUT", "object-kind row sets need one locator per chunk");
225
+ }
226
+ const inserted = await transaction.query(
227
+ `INSERT INTO adcp_reporting_row_sets
228
+ (row_set_id, row_set_kind, account_id, obligation_id, encoding, digest_profile, content_sha256,
229
+ canonical_byte_count, row_count, row_manifest_sha256, chunk_count, row_binding_id,
230
+ rows_shared_from_row_set_id)
231
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
232
+ ON CONFLICT (row_set_id) DO NOTHING`,
233
+ [
234
+ input.rowSetId,
235
+ input.rowSetKind,
236
+ input.accountId,
237
+ input.obligationId,
238
+ import_row_encoding.REPORTING_ROW_ENCODING_V1,
239
+ prepared.digestProfile,
240
+ input.binding.sha256,
241
+ input.binding.byteCount,
242
+ encoded.rowCount,
243
+ encoded.rowManifestSha256,
244
+ encoded.chunks.length,
245
+ prepared.bindingId,
246
+ sharedFromRowSetId ?? null
247
+ ]
248
+ );
249
+ if (inserted.rowCount !== 1) {
250
+ const existing = await transaction.query(
251
+ "SELECT content_sha256, row_manifest_sha256 FROM adcp_reporting_row_sets WHERE row_set_id = $1",
252
+ [input.rowSetId]
253
+ );
254
+ const row = existing.rows[0];
255
+ if (!row || row.content_sha256 !== input.binding.sha256 || row.row_manifest_sha256 !== encoded.rowManifestSha256) {
256
+ throw new import_row_storage_errors.ReportingRowStoreError("CONTENT_CONFLICT", "row set identity names different content");
257
+ }
258
+ return;
259
+ }
260
+ for (const [index, chunk] of encoded.chunks.entries()) {
261
+ const manifest = chunk.manifest;
262
+ const locator = locators?.[index];
263
+ if (!locator) {
264
+ await transaction.query(
265
+ `INSERT INTO adcp_reporting_chunk_bodies (account_id, obligation_id, sha256, body)
266
+ VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING`,
267
+ [input.accountId, input.obligationId, manifest.sha256, chunk.bytes]
268
+ );
269
+ }
270
+ await transaction.query(
271
+ `INSERT INTO adcp_reporting_row_chunks
272
+ (row_set_id, chunk_index, account_id, obligation_id, first_ordinal, row_count, byte_count, sha256, segments,
273
+ object_key, native_version, compression, physical_sha256, physical_byte_count)
274
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb, $10, $11, $12, $13, $14)`,
275
+ [
276
+ input.rowSetId,
277
+ manifest.chunk_index,
278
+ input.accountId,
279
+ input.obligationId,
280
+ manifest.first_ordinal,
281
+ manifest.row_count,
282
+ manifest.byte_count,
283
+ manifest.sha256,
284
+ JSON.stringify(manifest.segments),
285
+ locator?.objectKey ?? null,
286
+ locator?.nativeVersion ?? null,
287
+ locator?.compression ?? "none",
288
+ locator?.physicalSha256 ?? null,
289
+ locator?.physicalByteCount ?? null
290
+ ]
291
+ );
292
+ }
293
+ }
294
+ /**
295
+ * Load a row set and verify its chunk manifest against the committed digest.
296
+ * Returns `null` when no row set exists (legacy inline rows) or it belongs
297
+ * to another account. Throws `ROWS_EXPIRED` / `ROWS_UNAVAILABLE` when the
298
+ * rows were pruned or lost.
299
+ */
300
+ async find(rowSetId, accountId, queryable = this.pool) {
301
+ const found = await queryable.query(
302
+ `SELECT row_set.row_set_id, row_set.row_set_kind, row_set.account_id, row_set.obligation_id,
303
+ row_set.digest_profile, row_set.content_sha256, row_set.canonical_byte_count, row_set.row_count,
304
+ row_set.row_manifest_sha256, row_set.chunk_count, row_set.row_binding_id,
305
+ row_set.row_location_version, row_set.rows_state, binding.kind, binding.identity_sha256
306
+ FROM adcp_reporting_row_sets row_set
307
+ JOIN adcp_reporting_row_bindings binding ON binding.row_binding_id = row_set.row_binding_id
308
+ WHERE row_set.row_set_id = $1 AND row_set.account_id = $2`,
309
+ [rowSetId, accountId]
310
+ );
311
+ const record = found.rows[0];
312
+ if (!record) return null;
313
+ if (record.rows_state === "pruning" || record.rows_state === "pruned") {
314
+ throw new import_row_storage_errors.ReportingRowStoreError("ROWS_EXPIRED");
315
+ }
316
+ if (record.rows_state === "unavailable") throw new import_row_storage_errors.ReportingRowStoreError("ROWS_UNAVAILABLE");
317
+ const chunks = await queryable.query(
318
+ `SELECT chunk_index, first_ordinal, row_count, byte_count, sha256, segments,
319
+ object_key, native_version, compression, physical_sha256, physical_byte_count
320
+ FROM adcp_reporting_row_chunks WHERE row_set_id = $1 ORDER BY chunk_index`,
321
+ [rowSetId]
322
+ );
323
+ const manifests = chunks.rows.map((chunk) => ({
324
+ chunk_index: chunk.chunk_index,
325
+ first_ordinal: Number(chunk.first_ordinal),
326
+ row_count: chunk.row_count,
327
+ byte_count: Number(chunk.byte_count),
328
+ sha256: chunk.sha256,
329
+ segments: chunk.segments.map((segment) => ({
330
+ first_ordinal: Number(segment.first_ordinal),
331
+ row_count: Number(segment.row_count),
332
+ byte_offset: Number(segment.byte_offset),
333
+ byte_count: Number(segment.byte_count),
334
+ sha256: segment.sha256
335
+ }))
336
+ }));
337
+ const rowCount = Number(record.row_count);
338
+ try {
339
+ (0, import_row_encoding.verifyReportingRowManifestsV1)(manifests, { rowCount, rowManifestSha256: record.row_manifest_sha256 });
340
+ } catch (error) {
341
+ if ((0, import_row_encoding.isReportingRowEncodingError)(error)) throw new import_row_storage_errors.ReportingRowStoreError("ROWS_INTEGRITY_FAILED", error.message);
342
+ throw error;
343
+ }
344
+ if (manifests.length !== record.chunk_count) {
345
+ throw new import_row_storage_errors.ReportingRowStoreError("ROWS_INTEGRITY_FAILED", "chunk count does not match the row set");
346
+ }
347
+ const locators = chunks.rows.map((chunk) => {
348
+ const hasLocation = chunk.object_key !== null;
349
+ if (hasLocation !== (record.kind === "object")) {
350
+ throw new import_row_storage_errors.ReportingRowStoreError("ROWS_INTEGRITY_FAILED", "chunk location does not match its binding kind");
351
+ }
352
+ return hasLocation ? Object.freeze({
353
+ objectKey: chunk.object_key,
354
+ nativeVersion: chunk.native_version,
355
+ compression: chunk.compression,
356
+ physicalSha256: chunk.physical_sha256,
357
+ physicalByteCount: Number(chunk.physical_byte_count)
358
+ }) : void 0;
359
+ });
360
+ return Object.freeze({
361
+ rowSetId: record.row_set_id,
362
+ rowSetKind: record.row_set_kind,
363
+ accountId: record.account_id,
364
+ obligationId: record.obligation_id,
365
+ digestProfile: record.digest_profile,
366
+ contentSha256: record.content_sha256,
367
+ canonicalByteCount: Number(record.canonical_byte_count),
368
+ rowCount,
369
+ rowManifestSha256: record.row_manifest_sha256,
370
+ bindingId: record.row_binding_id,
371
+ bindingIdentitySha256: record.identity_sha256,
372
+ kind: record.kind,
373
+ manifests: Object.freeze(manifests),
374
+ locators: Object.freeze(locators)
375
+ });
376
+ }
377
+ /** Verified rows `[offset, offset + limit)` in ordinal order. */
378
+ async readPage(handle, offset, limit, signal) {
379
+ if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(limit) || limit < 1) {
380
+ throw new import_row_storage_errors.ReportingRowStoreError("INVALID_INPUT", "row page bounds are invalid");
381
+ }
382
+ const end = Math.min(handle.rowCount, offset + limit);
383
+ const rows = [];
384
+ for (const manifest of handle.manifests) {
385
+ if (offset >= end) break;
386
+ const chunkEnd = manifest.first_ordinal + manifest.row_count;
387
+ if (chunkEnd <= offset || manifest.first_ordinal >= end) continue;
388
+ signal?.throwIfAborted();
389
+ const from = manifest.segments.findIndex(
390
+ (segment) => segment.first_ordinal + segment.row_count > Math.max(offset, manifest.first_ordinal)
391
+ );
392
+ let to = from;
393
+ while (to + 1 < manifest.segments.length && manifest.segments[to + 1].first_ordinal < end) to += 1;
394
+ const firstSegment = manifest.segments[from];
395
+ const lastSegment = manifest.segments[to];
396
+ const bytes = await this.readChunkRange(
397
+ handle,
398
+ manifest,
399
+ firstSegment.byte_offset,
400
+ lastSegment.byte_offset + lastSegment.byte_count - firstSegment.byte_offset,
401
+ signal
402
+ );
403
+ const decoded = this.decode(() => (0, import_row_encoding.decodeVerifiedReportingRowSegmentsV1)(manifest, [from, to], bytes));
404
+ const startIndex = Math.max(offset, firstSegment.first_ordinal) - firstSegment.first_ordinal;
405
+ const endIndex = Math.min(end, lastSegment.first_ordinal + lastSegment.row_count) - firstSegment.first_ordinal;
406
+ rows.push(...decoded.slice(startIndex, endIndex));
407
+ }
408
+ return rows;
409
+ }
410
+ /**
411
+ * Every row, verified chunk by chunk and against the committed binding.
412
+ * `controlTotals` are required for revision row sets.
413
+ */
414
+ async readAll(handle, controlTotals, options = {}) {
415
+ if (options.maxBytes !== void 0 && handle.canonicalByteCount > options.maxBytes) {
416
+ throw new import_row_storage_errors.ReportingRowStoreError("INVALID_INPUT", "row set exceeds the hydration byte limit");
417
+ }
418
+ const hasher = handle.digestProfile === "revision_envelope_v1" ? (0, import_row_encoding.createReportingRevisionEnvelopeHasherV1)({
419
+ reporting_revision_id: handle.rowSetId,
420
+ row_count: handle.rowCount,
421
+ control_totals: controlTotals ?? []
422
+ }) : (0, import_row_encoding.createReportingRowsOnlyHasherV1)(handle.rowCount);
423
+ const rows = [];
424
+ for (const manifest of handle.manifests) {
425
+ options.signal?.throwIfAborted();
426
+ const bytes = await this.readChunkRange(handle, manifest, 0, manifest.byte_count, options.signal);
427
+ this.decode(() => (0, import_row_encoding.verifyReportingRowChunkV1)(manifest, bytes));
428
+ hasher.update(bytes);
429
+ rows.push(
430
+ ...this.decode(() => (0, import_row_encoding.decodeVerifiedReportingRowSegmentsV1)(manifest, [0, manifest.segments.length - 1], bytes))
431
+ );
432
+ }
433
+ const digest = this.decode(() => hasher.digest());
434
+ if (digest.sha256 !== handle.contentSha256 || digest.byteCount !== handle.canonicalByteCount) {
435
+ throw new import_row_storage_errors.ReportingRowStoreError("ROWS_INTEGRITY_FAILED", "rows do not reproduce the committed binding");
436
+ }
437
+ return rows;
438
+ }
439
+ /**
440
+ * Delete exact object versions through the configured binding's provider.
441
+ * `absent` counts as success. Only object-kind bindings are accepted.
442
+ */
443
+ async deleteObjects(bindingId, objects, signal) {
444
+ await this.ready();
445
+ const binding = this.bindings[bindingId];
446
+ if (!binding || binding.kind !== "object") {
447
+ throw new import_row_storage_errors.ReportingRowStoreError("STATE_UNAVAILABLE", `row binding ${bindingId} is not configured for objects`);
448
+ }
449
+ const provider = this.providers[binding.provider];
450
+ const ownedPrefix = `${binding.prefix}/${this.installation.namespaceKey}/`;
451
+ const context = { signal: deadlineSignal(this.writeDeadline, signal) };
452
+ for (const object of objects) {
453
+ if (!object.objectKey.startsWith(ownedPrefix)) {
454
+ throw new import_row_storage_errors.ReportingRowStoreError("UNSAFE_BINDING", "refusing to delete an object outside the owned prefix");
455
+ }
456
+ await this.provider(
457
+ () => provider.delete(
458
+ { ...providerLocation(binding), key: object.objectKey, nativeVersion: object.nativeVersion },
459
+ context
460
+ )
461
+ );
462
+ }
463
+ }
464
+ /**
465
+ * A live row set in the same obligation and binding whose rows are
466
+ * byte-identical (same manifest digest), with its chunk locations. Sharing
467
+ * never crosses obligations, so it never crosses consumers.
468
+ */
469
+ async findShareable(queryable, prepared) {
470
+ if (prepared.encoded.chunks.length === 0) return void 0;
471
+ const found = await queryable.query(
472
+ `SELECT row_set_id FROM adcp_reporting_row_sets
473
+ WHERE obligation_id = $1 AND account_id = $2 AND row_binding_id = $3 AND row_manifest_sha256 = $4
474
+ AND rows_state = 'live' AND row_set_id <> $5
475
+ ORDER BY recorded_at DESC, row_set_id LIMIT 1
476
+ FOR SHARE`,
477
+ [
478
+ prepared.input.obligationId,
479
+ prepared.input.accountId,
480
+ prepared.bindingId,
481
+ prepared.encoded.rowManifestSha256,
482
+ prepared.input.rowSetId
483
+ ]
484
+ );
485
+ const rowSetId = found.rows[0]?.row_set_id;
486
+ if (!rowSetId) return void 0;
487
+ const chunks = await queryable.query(
488
+ `SELECT object_key, native_version, compression, physical_sha256, physical_byte_count
489
+ FROM adcp_reporting_row_chunks WHERE row_set_id = $1 ORDER BY chunk_index`,
490
+ [rowSetId]
491
+ );
492
+ if (chunks.rows.length !== prepared.encoded.chunks.length) return void 0;
493
+ if (prepared.binding.kind === "postgres") return { rowSetId, locators: [] };
494
+ if (chunks.rows.some((chunk) => chunk.object_key === null)) return void 0;
495
+ return {
496
+ rowSetId,
497
+ locators: chunks.rows.map((chunk) => ({
498
+ objectKey: chunk.object_key,
499
+ nativeVersion: chunk.native_version,
500
+ compression: chunk.compression,
501
+ physicalSha256: chunk.physical_sha256,
502
+ physicalByteCount: Number(chunk.physical_byte_count),
503
+ created: false
504
+ }))
505
+ };
506
+ }
507
+ /** Installation identity and namespace key; available after `ready()`. */
508
+ get installationIdentity() {
509
+ if (!this.installation) throw new import_row_storage_errors.ReportingRowStoreError("STATE_UNAVAILABLE", "row storage is not ready");
510
+ return this.installation;
511
+ }
512
+ async readChunkRange(handle, manifest, byteOffset, byteCount, signal) {
513
+ if (handle.kind === "postgres") {
514
+ const result = await this.pool.query(
515
+ `SELECT substring(body FROM $4::integer + 1 FOR $5::integer) AS bytes
516
+ FROM adcp_reporting_chunk_bodies
517
+ WHERE account_id = $1 AND obligation_id = $2 AND sha256 = $3`,
518
+ [handle.accountId, handle.obligationId, manifest.sha256, byteOffset, byteCount]
519
+ );
520
+ const bytes = result.rows[0]?.bytes;
521
+ if (!bytes) throw new import_row_storage_errors.ReportingRowStoreError("ROWS_UNAVAILABLE", `chunk ${manifest.chunk_index} body is missing`);
522
+ return bytes;
523
+ }
524
+ const binding = this.bindings[handle.bindingId];
525
+ if (!binding || binding.kind !== "object" || bindingIdentitySha256(binding) !== handle.bindingIdentitySha256) {
526
+ throw new import_row_storage_errors.ReportingRowStoreError("STATE_UNAVAILABLE", `row binding ${handle.bindingId} is not configured`);
527
+ }
528
+ const locator = handle.locators[manifest.chunk_index];
529
+ const provider = this.providers[binding.provider];
530
+ const context = { signal: deadlineSignal(this.readDeadline, signal) };
531
+ const location = providerLocation(binding);
532
+ if (locator.compression === "none" && provider.rangedReads) {
533
+ const bytes = await this.provider(
534
+ () => provider.get(
535
+ {
536
+ ...location,
537
+ key: locator.objectKey,
538
+ nativeVersion: locator.nativeVersion,
539
+ range: { offset: byteOffset, length: byteCount },
540
+ maxBytes: byteCount
541
+ },
542
+ context
543
+ )
544
+ );
545
+ if (!bytes)
546
+ throw new import_row_storage_errors.ReportingRowStoreError("ROWS_UNAVAILABLE", `chunk ${manifest.chunk_index} object is missing`);
547
+ if (bytes.byteLength !== byteCount) {
548
+ throw new import_row_storage_errors.ReportingRowStoreError("ROWS_INTEGRITY_FAILED", `chunk ${manifest.chunk_index} range is truncated`);
549
+ }
550
+ return Buffer.from(bytes);
551
+ }
552
+ const stored = await this.provider(
553
+ () => provider.get(
554
+ {
555
+ ...location,
556
+ key: locator.objectKey,
557
+ nativeVersion: locator.nativeVersion,
558
+ maxBytes: locator.physicalByteCount
559
+ },
560
+ context
561
+ )
562
+ );
563
+ if (!stored)
564
+ throw new import_row_storage_errors.ReportingRowStoreError("ROWS_UNAVAILABLE", `chunk ${manifest.chunk_index} object is missing`);
565
+ const physical = Buffer.from(stored);
566
+ if (physical.byteLength !== locator.physicalByteCount || sha256Hex(physical) !== locator.physicalSha256) {
567
+ throw new import_row_storage_errors.ReportingRowStoreError("ROWS_INTEGRITY_FAILED", `chunk ${manifest.chunk_index} stored bytes differ`);
568
+ }
569
+ const logical = this.inflate(physical, locator.compression, manifest.byte_count);
570
+ if (!logical) {
571
+ throw new import_row_storage_errors.ReportingRowStoreError("ROWS_INTEGRITY_FAILED", `chunk ${manifest.chunk_index} does not decompress`);
572
+ }
573
+ return logical.subarray(byteOffset, byteOffset + byteCount);
574
+ }
575
+ inflate(physical, compression, byteCount) {
576
+ if (compression === "none") return physical.byteLength === byteCount ? physical : null;
577
+ try {
578
+ const logical = (0, import_zlib.gunzipSync)(physical, { maxOutputLength: byteCount });
579
+ return logical.byteLength === byteCount ? logical : null;
580
+ } catch {
581
+ return null;
582
+ }
583
+ }
584
+ decode(operation) {
585
+ try {
586
+ return operation();
587
+ } catch (error) {
588
+ if ((0, import_row_encoding.isReportingRowEncodingError)(error)) throw new import_row_storage_errors.ReportingRowStoreError("ROWS_INTEGRITY_FAILED", error.message);
589
+ throw error;
590
+ }
591
+ }
592
+ /** Collapse provider failures to stable, secret-free codes. */
593
+ async provider(operation) {
594
+ try {
595
+ return await operation();
596
+ } catch (error) {
597
+ if ((0, import_row_storage_errors.isReportingRowStoreError)(error)) throw error;
598
+ if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) {
599
+ throw new import_row_storage_errors.ReportingRowStoreError(error.name === "TimeoutError" ? "DEADLINE_EXCEEDED" : "ABORTED");
600
+ }
601
+ throw new import_row_storage_errors.ReportingRowStoreError("PROVIDER_UNAVAILABLE");
602
+ }
603
+ }
604
+ async register() {
605
+ const { installationId } = await (0, import_row_storage_migration.probeReportingRowStorageSchemaV1)(this.pool);
606
+ const namespaceKey = sha256Hex((0, import_jcs.canonicalize)(["adcp.rows.v1", this.deploymentNamespace, installationId]));
607
+ this.installation = { installationId, namespaceKey };
608
+ for (const [bindingId, binding] of Object.entries(this.bindings)) {
609
+ if (binding.kind === "object") {
610
+ const provider = this.providers[binding.provider];
611
+ await this.provider(
612
+ () => provider.probe(
613
+ { ...providerLocation(binding), prefix: binding.prefix },
614
+ { signal: AbortSignal.timeout(this.readDeadline) }
615
+ )
616
+ );
617
+ }
618
+ const identityConfig = bindingIdentityConfig(binding);
619
+ const identitySha256 = bindingIdentitySha256(binding);
620
+ const operationalConfig = binding.kind === "object" ? {
621
+ compression: binding.compression ?? "gzip",
622
+ ...binding.credentialRef ? { credentialRef: binding.credentialRef } : {}
623
+ } : {};
624
+ await this.pool.query(
625
+ `INSERT INTO adcp_reporting_row_bindings
626
+ (row_binding_id, kind, provider, identity_config, identity_sha256, operational_config, namespace_key)
627
+ VALUES ($1, $2, $3, $4::jsonb, $5, $6::jsonb, $7)
628
+ ON CONFLICT (row_binding_id) DO NOTHING`,
629
+ [
630
+ bindingId,
631
+ binding.kind,
632
+ binding.kind === "object" ? binding.provider : "postgres",
633
+ JSON.stringify(identityConfig),
634
+ identitySha256,
635
+ JSON.stringify(operationalConfig),
636
+ namespaceKey
637
+ ]
638
+ );
639
+ const stored = await this.pool.query(
640
+ "SELECT identity_sha256, namespace_key, state FROM adcp_reporting_row_bindings WHERE row_binding_id = $1",
641
+ [bindingId]
642
+ );
643
+ const row = stored.rows[0];
644
+ if (!row || row.identity_sha256 !== identitySha256) {
645
+ throw new import_row_storage_errors.ReportingRowStoreError(
646
+ "UNSAFE_BINDING",
647
+ `row binding ${bindingId} identity differs from its definition`
648
+ );
649
+ }
650
+ if (row.namespace_key !== namespaceKey) {
651
+ throw new import_row_storage_errors.ReportingRowStoreError("UNSAFE_BINDING", `row binding ${bindingId} belongs to another installation`);
652
+ }
653
+ }
654
+ }
655
+ }
656
+ function bindingIdentityConfig(binding) {
657
+ return binding.kind === "object" ? {
658
+ location: { ...binding.location },
659
+ prefix: binding.prefix,
660
+ keyTemplate: binding.keyTemplate ?? import_row_storage_object.REPORTING_ROW_DEFAULT_KEY_TEMPLATE
661
+ } : {};
662
+ }
663
+ function bindingIdentitySha256(binding) {
664
+ const provider = binding.kind === "object" ? binding.provider : binding.kind;
665
+ return sha256Hex((0, import_jcs.canonicalize)([binding.kind, provider, bindingIdentityConfig(binding)]));
666
+ }
667
+ function providerLocation(binding) {
668
+ return { location: binding.location, ...binding.credentialRef ? { credentialRef: binding.credentialRef } : {} };
669
+ }
670
+ function deadlineSignal(milliseconds, signal) {
671
+ const timeout = AbortSignal.timeout(milliseconds);
672
+ return signal ? AbortSignal.any([signal, timeout]) : timeout;
673
+ }
674
+ function positiveMilliseconds(value, name) {
675
+ if (!Number.isSafeInteger(value) || value < 1e3 || value > 6e5) {
676
+ throw new import_row_storage_errors.ReportingRowStoreError("INVALID_INPUT", `${name} must be between 1000 and 600000`);
677
+ }
678
+ return value;
679
+ }
680
+ function sha256Hex(value) {
681
+ return (0, import_crypto.createHash)("sha256").update(value).digest("hex");
682
+ }
683
+ function reportingRowWriteIntentIdV1() {
684
+ return (0, import_crypto.randomUUID)();
685
+ }
686
+ // Annotate the CommonJS export names for ESM import in node:
687
+ 0 && (module.exports = {
688
+ ReportingRowStorageV1,
689
+ ReportingRowStoreError,
690
+ isReportingRowStoreError,
691
+ reportingRowWriteIntentIdV1
692
+ });