@adcp/sdk 16.0.0-beta.3 → 16.0.0-beta.4

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 (182) hide show
  1. package/dist/lib/auth/oauth/diagnose.js +3 -11
  2. package/dist/lib/auth/oauth/diagnose.mjs +4 -12
  3. package/dist/lib/auth/oauth/diagnostics.d.mts +2 -1
  4. package/dist/lib/auth/oauth/diagnostics.d.ts +2 -1
  5. package/dist/lib/auth/oauth/diagnostics.js +8 -10
  6. package/dist/lib/auth/oauth/diagnostics.mjs +7 -10
  7. package/dist/lib/index.d.mts +1 -1
  8. package/dist/lib/index.d.ts +1 -1
  9. package/dist/lib/index.js +2 -0
  10. package/dist/lib/index.mjs +7 -1
  11. package/dist/lib/reporting/consumer-runtime.js +2 -1
  12. package/dist/lib/reporting/consumer-runtime.mjs +2 -1
  13. package/dist/lib/reporting/ledger/handler.js +50 -11
  14. package/dist/lib/reporting/ledger/handler.mjs +50 -12
  15. package/dist/lib/reporting/ledger/index.d.mts +17 -14
  16. package/dist/lib/reporting/ledger/index.d.ts +17 -14
  17. package/dist/lib/reporting/ledger/index.js +32 -20
  18. package/dist/lib/reporting/ledger/index.mjs +21 -10
  19. package/dist/lib/reporting/ledger/offering-validation.d.mts +9 -0
  20. package/dist/lib/reporting/ledger/offering-validation.d.ts +9 -0
  21. package/dist/lib/reporting/{gcs/bucket-policy.js → ledger/offering-validation.js} +9 -8
  22. package/dist/lib/reporting/ledger/offering-validation.mjs +8 -0
  23. package/dist/lib/reporting/ledger/receipts.d.mts +48 -0
  24. package/dist/lib/reporting/ledger/receipts.d.ts +48 -0
  25. package/dist/lib/reporting/ledger/receipts.js +186 -0
  26. package/dist/lib/reporting/ledger/receipts.mjs +161 -0
  27. package/dist/lib/reporting/ledger/status-ingest.js +3 -3
  28. package/dist/lib/reporting/ledger/status-ingest.mjs +4 -5
  29. package/dist/lib/reporting/ledger/types.d.mts +43 -0
  30. package/dist/lib/reporting/ledger/types.d.ts +43 -0
  31. package/dist/lib/reporting/ledger/types.js +31 -2
  32. package/dist/lib/reporting/ledger/types.mjs +26 -1
  33. package/dist/lib/reporting/pagination.d.mts +6 -0
  34. package/dist/lib/reporting/pagination.d.ts +6 -0
  35. package/dist/lib/reporting/{gcs/errors.js → pagination.js} +12 -17
  36. package/dist/lib/reporting/pagination.mjs +12 -0
  37. package/dist/lib/reporting/reconciliation.d.mts +1 -0
  38. package/dist/lib/reporting/reconciliation.d.ts +1 -0
  39. package/dist/lib/reporting/reconciliation.js +3 -2
  40. package/dist/lib/reporting/reconciliation.mjs +3 -2
  41. package/dist/lib/reporting/service/index.d.mts +79 -153
  42. package/dist/lib/reporting/service/index.d.ts +79 -153
  43. package/dist/lib/reporting/service/index.js +34 -491
  44. package/dist/lib/reporting/service/index.mjs +36 -510
  45. package/dist/lib/reporting/service/scheduler-support.d.mts +43 -0
  46. package/dist/lib/reporting/service/scheduler-support.d.ts +43 -0
  47. package/dist/lib/reporting/service/scheduler-support.js +125 -0
  48. package/dist/lib/reporting/service/scheduler-support.mjs +96 -0
  49. package/dist/lib/schemas-data/v2.5/_provenance.json +1 -1
  50. package/dist/lib/signing/canonicalize.d.mts +4 -0
  51. package/dist/lib/signing/canonicalize.d.ts +4 -0
  52. package/dist/lib/signing/canonicalize.js +14 -8
  53. package/dist/lib/signing/canonicalize.mjs +14 -8
  54. package/dist/lib/signing/content-digest.d.mts +8 -0
  55. package/dist/lib/signing/content-digest.d.ts +8 -0
  56. package/dist/lib/signing/content-digest.js +11 -5
  57. package/dist/lib/signing/content-digest.mjs +10 -5
  58. package/dist/lib/signing/signer.js +9 -6
  59. package/dist/lib/signing/signer.mjs +10 -7
  60. package/dist/lib/signing/web-bot-auth.js +103 -37
  61. package/dist/lib/signing/web-bot-auth.mjs +108 -37
  62. package/dist/lib/testing/storyboard/junit.js +16 -3
  63. package/dist/lib/testing/storyboard/junit.mjs +16 -3
  64. package/dist/lib/testing/storyboard/request-signing/builder.js +10 -9
  65. package/dist/lib/testing/storyboard/request-signing/builder.mjs +10 -9
  66. package/dist/lib/testing/storyboard/runner.js +94 -25
  67. package/dist/lib/testing/storyboard/runner.mjs +94 -25
  68. package/dist/lib/testing/storyboard/types.d.mts +6 -0
  69. package/dist/lib/testing/storyboard/types.d.ts +6 -0
  70. package/dist/lib/testing/storyboard/validations.d.mts +1 -1
  71. package/dist/lib/testing/storyboard/validations.d.ts +1 -1
  72. package/dist/lib/version.d.mts +3 -3
  73. package/dist/lib/version.d.ts +3 -3
  74. package/dist/lib/version.js +3 -3
  75. package/dist/lib/version.mjs +3 -3
  76. package/docs/TYPE-SUMMARY.md +23 -5
  77. package/docs/guides/REPORTING-GCS-FENCE.md +3 -3
  78. package/docs/guides/REPORTING-GCS-MANAGED.md +4 -4
  79. package/docs/guides/REPORTING-LEDGER-CUTOVER.md +7 -7
  80. package/docs/guides/REPORTING-LEDGER.md +107 -51
  81. package/docs/guides/REPORTING-OPERATIONS.md +66 -5
  82. package/docs/guides/REPORTING-STABILITY.md +36 -32
  83. package/docs/llms.txt +4 -3
  84. package/docs/migration-14.x-rc-worksheet.md +4 -7
  85. package/docs/migration-reporting-storage-package.md +186 -0
  86. package/examples/README.md +1 -1
  87. package/package.json +13 -78
  88. package/dist/lib/reporting/azure/index.d.mts +0 -31
  89. package/dist/lib/reporting/azure/index.d.ts +0 -31
  90. package/dist/lib/reporting/azure/index.js +0 -266
  91. package/dist/lib/reporting/azure/index.mjs +0 -249
  92. package/dist/lib/reporting/bigquery/index.d.mts +0 -246
  93. package/dist/lib/reporting/bigquery/index.d.ts +0 -246
  94. package/dist/lib/reporting/bigquery/index.js +0 -633
  95. package/dist/lib/reporting/bigquery/index.mjs +0 -594
  96. package/dist/lib/reporting/gcs/adapter.d.mts +0 -38
  97. package/dist/lib/reporting/gcs/adapter.d.ts +0 -38
  98. package/dist/lib/reporting/gcs/adapter.js +0 -342
  99. package/dist/lib/reporting/gcs/adapter.mjs +0 -325
  100. package/dist/lib/reporting/gcs/bucket-policy.d.mts +0 -3
  101. package/dist/lib/reporting/gcs/bucket-policy.d.ts +0 -3
  102. package/dist/lib/reporting/gcs/bucket-policy.mjs +0 -7
  103. package/dist/lib/reporting/gcs/errors.d.mts +0 -11
  104. package/dist/lib/reporting/gcs/errors.d.ts +0 -11
  105. package/dist/lib/reporting/gcs/errors.mjs +0 -16
  106. package/dist/lib/reporting/gcs/fence.d.mts +0 -41
  107. package/dist/lib/reporting/gcs/fence.d.ts +0 -41
  108. package/dist/lib/reporting/gcs/fence.js +0 -250
  109. package/dist/lib/reporting/gcs/fence.mjs +0 -230
  110. package/dist/lib/reporting/gcs/index.d.mts +0 -18
  111. package/dist/lib/reporting/gcs/index.d.ts +0 -18
  112. package/dist/lib/reporting/gcs/index.js +0 -44
  113. package/dist/lib/reporting/gcs/index.mjs +0 -14
  114. package/dist/lib/reporting/gcs/io.d.mts +0 -7
  115. package/dist/lib/reporting/gcs/io.d.ts +0 -7
  116. package/dist/lib/reporting/gcs/io.js +0 -95
  117. package/dist/lib/reporting/gcs/io.mjs +0 -69
  118. package/dist/lib/reporting/gcs/reader.d.mts +0 -67
  119. package/dist/lib/reporting/gcs/reader.d.ts +0 -67
  120. package/dist/lib/reporting/gcs/reader.js +0 -193
  121. package/dist/lib/reporting/gcs/reader.mjs +0 -169
  122. package/dist/lib/reporting/gcs/row-provider.d.mts +0 -39
  123. package/dist/lib/reporting/gcs/row-provider.d.ts +0 -39
  124. package/dist/lib/reporting/gcs/row-provider.js +0 -225
  125. package/dist/lib/reporting/gcs/row-provider.mjs +0 -208
  126. package/dist/lib/reporting/gcs/validation.d.mts +0 -5
  127. package/dist/lib/reporting/gcs/validation.d.ts +0 -5
  128. package/dist/lib/reporting/gcs/validation.js +0 -49
  129. package/dist/lib/reporting/gcs/validation.mjs +0 -25
  130. package/dist/lib/reporting/ledger/change-feed.d.mts +0 -69
  131. package/dist/lib/reporting/ledger/change-feed.d.ts +0 -69
  132. package/dist/lib/reporting/ledger/change-feed.js +0 -107
  133. package/dist/lib/reporting/ledger/change-feed.mjs +0 -80
  134. package/dist/lib/reporting/ledger/managed-postgres.d.mts +0 -293
  135. package/dist/lib/reporting/ledger/managed-postgres.d.ts +0 -293
  136. package/dist/lib/reporting/ledger/managed-postgres.js +0 -2346
  137. package/dist/lib/reporting/ledger/managed-postgres.mjs +0 -2332
  138. package/dist/lib/reporting/ledger/managed-router.d.mts +0 -148
  139. package/dist/lib/reporting/ledger/managed-router.d.ts +0 -148
  140. package/dist/lib/reporting/ledger/managed-router.js +0 -280
  141. package/dist/lib/reporting/ledger/managed-router.mjs +0 -258
  142. package/dist/lib/reporting/ledger/managed.d.mts +0 -535
  143. package/dist/lib/reporting/ledger/managed.d.ts +0 -535
  144. package/dist/lib/reporting/ledger/managed.js +0 -761
  145. package/dist/lib/reporting/ledger/managed.mjs +0 -729
  146. package/dist/lib/reporting/ledger/notification-activity.d.mts +0 -332
  147. package/dist/lib/reporting/ledger/notification-activity.d.ts +0 -332
  148. package/dist/lib/reporting/ledger/notification-activity.js +0 -1366
  149. package/dist/lib/reporting/ledger/notification-activity.mjs +0 -1337
  150. package/dist/lib/reporting/ledger/object-writes.d.mts +0 -128
  151. package/dist/lib/reporting/ledger/object-writes.d.ts +0 -128
  152. package/dist/lib/reporting/ledger/object-writes.js +0 -147
  153. package/dist/lib/reporting/ledger/object-writes.mjs +0 -114
  154. package/dist/lib/reporting/ledger/postgres.d.mts +0 -689
  155. package/dist/lib/reporting/ledger/postgres.d.ts +0 -689
  156. package/dist/lib/reporting/ledger/postgres.js +0 -4462
  157. package/dist/lib/reporting/ledger/postgres.mjs +0 -4462
  158. package/dist/lib/reporting/ledger/row-storage-migration.d.mts +0 -59
  159. package/dist/lib/reporting/ledger/row-storage-migration.d.ts +0 -59
  160. package/dist/lib/reporting/ledger/row-storage-migration.js +0 -365
  161. package/dist/lib/reporting/ledger/row-storage-migration.mjs +0 -339
  162. package/dist/lib/reporting/ledger/row-storage-object.d.mts +0 -203
  163. package/dist/lib/reporting/ledger/row-storage-object.d.ts +0 -203
  164. package/dist/lib/reporting/ledger/row-storage-object.js +0 -379
  165. package/dist/lib/reporting/ledger/row-storage-object.mjs +0 -335
  166. package/dist/lib/reporting/ledger/row-storage-provider-io.d.mts +0 -44
  167. package/dist/lib/reporting/ledger/row-storage-provider-io.d.ts +0 -44
  168. package/dist/lib/reporting/ledger/row-storage-provider-io.js +0 -142
  169. package/dist/lib/reporting/ledger/row-storage-provider-io.mjs +0 -111
  170. package/dist/lib/reporting/ledger/row-storage.d.mts +0 -316
  171. package/dist/lib/reporting/ledger/row-storage.d.ts +0 -316
  172. package/dist/lib/reporting/ledger/row-storage.js +0 -812
  173. package/dist/lib/reporting/ledger/row-storage.mjs +0 -802
  174. package/dist/lib/reporting/s3/index.d.mts +0 -34
  175. package/dist/lib/reporting/s3/index.d.ts +0 -34
  176. package/dist/lib/reporting/s3/index.js +0 -347
  177. package/dist/lib/reporting/s3/index.mjs +0 -340
  178. package/dist/lib/reporting/service/maintenance.d.mts +0 -148
  179. package/dist/lib/reporting/service/maintenance.d.ts +0 -148
  180. package/dist/lib/reporting/service/maintenance.js +0 -185
  181. package/dist/lib/reporting/service/maintenance.mjs +0 -159
  182. package/examples/reliable-reporting-service/README.md +0 -169
@@ -1,1337 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import { notificationSuppressionDisposition } from "../../server/notification-subscriptions/index.mjs";
3
- import { canonicalJsonSha256 } from "../../utils/jcs.mjs";
4
- const DEFAULT_TABLE = "adcp_reporting_notification_activity";
5
- const REPORTING_STATUS_EVENT_TYPE = "reporting.status_changed";
6
- const REPORTING_LEDGER_EVENT_TYPE = "reporting.ledger_changed";
7
- const REPORTING_DELIVERY_EVENT_TYPE = "reporting.delivery_ready";
8
- const REPORTING_EVENT_STORAGE_PREFIX = "reporting-event:";
9
- const DEFAULT_NAMESPACE = "adcp-reporting";
10
- const DEFAULT_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
11
- const DEFAULT_MAX_PENDING_PER_TENANT = 1e5;
12
- const DEFAULT_MAX_ATTEMPTS = 100;
13
- const MAX_ACTIVITY_BYTES = 64 * 1024;
14
- const MAX_CURSOR_BYTES = 16 * 1024;
15
- class ReportingNotificationRetryableSuppressionError extends Error {
16
- constructor(reason) {
17
- super(`Reporting notification delivery authority failed closed (${reason}); no external attempt was made`);
18
- this.reason = reason;
19
- }
20
- reason;
21
- name = "ReportingNotificationRetryableSuppressionError";
22
- }
23
- const MAX_SUPPORTED_RECIPIENTS = 1e4;
24
- const MAX_SUPPORTED_RETAINED_RECIPIENTS = 1e5;
25
- const MAX_BTREE_ENTRY_BYTES = 2704;
26
- const RECIPIENT_FINGERPRINT_BYTES = 64;
27
- const RECIPIENT_ROUND_BYTES = 4;
28
- const MAX_TRANSITION_ID_BYTES = 512;
29
- const MAX_RECIPIENT_TABLE_BYTES = 53;
30
- function getReportingNotificationActivityMigration(options = {}) {
31
- const raw = options.tableName ?? DEFAULT_TABLE;
32
- const table = quoteIdentifier(raw);
33
- const rawRecipients = recipientTableName(raw);
34
- const recipientTable = quoteIdentifier(rawRecipients, MAX_RECIPIENT_TABLE_BYTES);
35
- const cursorTable = quoteIdentifier(`${raw}_cursor`, MAX_RECIPIENT_TABLE_BYTES);
36
- return `
37
- CREATE TABLE IF NOT EXISTS ${table} (
38
- namespace TEXT NOT NULL,
39
- transition_id TEXT NOT NULL,
40
- activity_sequence BIGSERIAL NOT NULL UNIQUE,
41
- tenant_scope TEXT NOT NULL,
42
- account_id TEXT NOT NULL,
43
- obligation_id TEXT NOT NULL,
44
- activity JSONB NOT NULL,
45
- intent_fingerprint TEXT NOT NULL,
46
- state TEXT NOT NULL DEFAULT 'pending',
47
- notification_required BOOLEAN NOT NULL,
48
- attempt_count INTEGER NOT NULL DEFAULT 0,
49
- next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
50
- lease_owner TEXT,
51
- lease_version BIGINT NOT NULL DEFAULT 0,
52
- lease_expires_at TIMESTAMPTZ,
53
- created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
54
- projected_at TIMESTAMPTZ,
55
- retain_until TIMESTAMPTZ,
56
- delivery_intent_at TIMESTAMPTZ,
57
- abandoned_at TIMESTAMPTZ,
58
- PRIMARY KEY (namespace, transition_id),
59
- CONSTRAINT ${raw}_valid_state CHECK (state IN ('pending', 'projected', 'abandoned')),
60
- CONSTRAINT ${raw}_valid_fingerprint CHECK (intent_fingerprint ~ '^[a-f0-9]{64}$'),
61
- CONSTRAINT ${raw}_valid_activity CHECK (jsonb_typeof(activity) = 'object'),
62
- CONSTRAINT ${raw}_valid_projection CHECK (
63
- (state = 'pending' AND notification_required AND projected_at IS NULL AND retain_until IS NULL) OR
64
- (state = 'projected' AND projected_at IS NOT NULL AND retain_until IS NOT NULL) OR
65
- -- Abandoned: bounded out of the pending set without ever being recorded as
66
- -- delivered, so it stops consuming tenant capacity but stays auditable.
67
- (state = 'abandoned' AND projected_at IS NULL AND retain_until IS NOT NULL AND abandoned_at IS NOT NULL)
68
- )
69
- );
70
-
71
- CREATE TABLE IF NOT EXISTS ${cursorTable} (
72
- namespace TEXT PRIMARY KEY,
73
- tenant_scope TEXT,
74
- changed_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()
75
- );
76
-
77
- -- Upgrade in place, once, and touch nothing on a rerun.
78
- --
79
- -- Every statement here is guarded on the catalog, including the column adds:
80
- -- \`ADD COLUMN IF NOT EXISTS\` still takes ACCESS EXCLUSIVE to discover the
81
- -- column already exists, so a rerun during normal traffic blocks behind ordinary
82
- -- readers and fails outright under a lock_timeout. An already-upgraded rerun now
83
- -- issues no table-locking statement at all.
84
- --
85
- -- Every guard is scoped to this schema's table by resolving it once to a
86
- -- regclass. A database-wide lookup by index name would see an upgraded index in
87
- -- another schema and skip the upgrade here, leaving that deployment with a
88
- -- projected-only retention index that cannot serve abandonment pruning.
89
- DO $$
90
- DECLARE
91
- activity_table regclass := to_regclass('${raw}');
92
- stale_index oid;
93
- BEGIN
94
- IF activity_table IS NULL THEN
95
- RETURN;
96
- END IF;
97
- IF NOT EXISTS (
98
- SELECT 1 FROM pg_attribute
99
- WHERE attrelid = activity_table AND attname = 'delivery_intent_at' AND NOT attisdropped
100
- ) THEN
101
- ALTER TABLE ${table} ADD COLUMN delivery_intent_at TIMESTAMPTZ;
102
- END IF;
103
- IF NOT EXISTS (
104
- SELECT 1 FROM pg_attribute
105
- WHERE attrelid = activity_table AND attname = 'abandoned_at' AND NOT attisdropped
106
- ) THEN
107
- ALTER TABLE ${table} ADD COLUMN abandoned_at TIMESTAMPTZ;
108
- END IF;
109
- IF NOT EXISTS (
110
- SELECT 1 FROM pg_constraint
111
- WHERE conrelid = activity_table AND conname = '${raw}_valid_state'
112
- AND pg_get_constraintdef(oid) LIKE '%abandoned%'
113
- ) THEN
114
- ALTER TABLE ${table} DROP CONSTRAINT IF EXISTS ${raw}_valid_state;
115
- ALTER TABLE ${table} ADD CONSTRAINT ${raw}_valid_state
116
- CHECK (state IN ('pending', 'projected', 'abandoned')) NOT VALID;
117
- ALTER TABLE ${table} VALIDATE CONSTRAINT ${raw}_valid_state;
118
- END IF;
119
- IF NOT EXISTS (
120
- SELECT 1 FROM pg_constraint
121
- WHERE conrelid = activity_table AND conname = '${raw}_valid_projection'
122
- AND pg_get_constraintdef(oid) LIKE '%abandoned_at%'
123
- ) THEN
124
- ALTER TABLE ${table} DROP CONSTRAINT IF EXISTS ${raw}_valid_projection;
125
- ALTER TABLE ${table} ADD CONSTRAINT ${raw}_valid_projection CHECK (
126
- (state = 'pending' AND notification_required AND projected_at IS NULL AND retain_until IS NULL) OR
127
- (state = 'projected' AND projected_at IS NOT NULL AND retain_until IS NOT NULL) OR
128
- (state = 'abandoned' AND projected_at IS NULL AND retain_until IS NOT NULL AND abandoned_at IS NOT NULL)
129
- ) NOT VALID;
130
- ALTER TABLE ${table} VALIDATE CONSTRAINT ${raw}_valid_projection;
131
- END IF;
132
- SELECT index_class.oid INTO stale_index
133
- FROM pg_index
134
- JOIN pg_class index_class ON index_class.oid = pg_index.indexrelid
135
- WHERE pg_index.indrelid = activity_table
136
- AND index_class.relname = 'idx_${raw}_retention'
137
- AND pg_get_indexdef(pg_index.indexrelid) NOT LIKE '%abandoned%';
138
- IF stale_index IS NOT NULL THEN
139
- EXECUTE format('DROP INDEX %s', stale_index::regclass);
140
- END IF;
141
- IF NOT EXISTS (
142
- SELECT 1 FROM pg_index
143
- JOIN pg_class index_class ON index_class.oid = pg_index.indexrelid
144
- WHERE pg_index.indrelid = activity_table AND index_class.relname = 'idx_${raw}_retention'
145
- ) THEN
146
- CREATE INDEX idx_${raw}_retention
147
- ON ${table}(namespace, retain_until, activity_sequence)
148
- WHERE state IN ('projected', 'abandoned');
149
- END IF;
150
- END $$;
151
-
152
- -- One row per frozen recipient, carrying that recipient's own delivery state.
153
- --
154
- -- Relational rather than one serialized document: a document needs a size cap,
155
- -- and a fanout that legitimately exceeded it could never be committed and would
156
- -- retry until it aged out. Only the bounded 64-hex fingerprint enters the index,
157
- -- so an individual recipient reference has no length limit of its own.
158
- --
159
- -- Per-recipient rather than per-emission: attempt_at is the durable pre-POST
160
- -- checkpoint for exactly one recipient, so one recipient's attempt cannot pin a
161
- -- sibling that was suppressed before its own first POST. Rows with no
162
- -- attempt_at are revisable and replaced in place, so a pre-attempt retry can
163
- -- never accumulate superseded state.
164
- --
165
- -- subscriber_key identifies the subscriber independently of its destination
166
- -- generation. Pinning is per subscriber: once a subscriber has been addressed,
167
- -- a later generation of the same subscriber is never addressed for this
168
- -- notification, because that would be the same logical delivery under a new
169
- -- idempotency key. A different subscriber is unaffected.
170
- CREATE TABLE IF NOT EXISTS ${recipientTable} (
171
- namespace TEXT NOT NULL,
172
- transition_id TEXT NOT NULL,
173
- recipient_fingerprint TEXT NOT NULL,
174
- subscriber_key TEXT NOT NULL,
175
- recipient JSONB NOT NULL,
176
- frozen_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
177
- attempt_at TIMESTAMPTZ,
178
- settled_at TIMESTAMPTZ,
179
- disposition TEXT,
180
- PRIMARY KEY (namespace, transition_id, recipient_fingerprint),
181
- CONSTRAINT ${rawRecipients}_fk FOREIGN KEY (namespace, transition_id)
182
- REFERENCES ${table}(namespace, transition_id) ON DELETE CASCADE,
183
- CONSTRAINT ${rawRecipients}_fp CHECK (recipient_fingerprint ~ '^[a-f0-9]{64}$'),
184
- CONSTRAINT ${rawRecipients}_sk CHECK (subscriber_key ~ '^[a-f0-9]{64}$'),
185
- CONSTRAINT ${rawRecipients}_obj CHECK (jsonb_typeof(recipient) = 'object'),
186
- CONSTRAINT ${rawRecipients}_set CHECK (
187
- (settled_at IS NULL AND disposition IS NULL) OR
188
- (settled_at IS NOT NULL AND disposition IN ('delivered', 'terminal'))
189
- )
190
- );
191
- -- Indexes are catalog-guarded too. CREATE INDEX IF NOT EXISTS still takes a
192
- -- ShareLock to discover the index already exists, which conflicts with the
193
- -- RowExclusiveLock every ordinary writer holds \u2014 so an already-current rerun
194
- -- would stall live traffic, or fail under a lock_timeout, despite creating
195
- -- nothing. Scoped to this schema's tables by regclass, like every other guard.
196
- DO $$
197
- DECLARE
198
- activity_table regclass := to_regclass('${raw}');
199
- recipient_table regclass := to_regclass('${rawRecipients}');
200
- BEGIN
201
- IF activity_table IS NULL OR recipient_table IS NULL THEN
202
- RETURN;
203
- END IF;
204
- IF NOT EXISTS (
205
- SELECT 1 FROM pg_index
206
- JOIN pg_class index_class ON index_class.oid = pg_index.indexrelid
207
- WHERE pg_index.indrelid = recipient_table AND index_class.relname = 'idx_${rawRecipients}_unsettled'
208
- ) THEN
209
- CREATE INDEX idx_${rawRecipients}_unsettled
210
- ON ${recipientTable}(namespace, transition_id)
211
- WHERE settled_at IS NULL;
212
- END IF;
213
- -- At most one addressed generation per subscriber, enforced by the database.
214
- --
215
- -- The checkpoint and a concurrent recipient replacement run as separate
216
- -- statements against a connection pool, so neither sees the other's
217
- -- uncommitted work: a freeze can propose a replacement generation while the
218
- -- original is being checkpointed, and PostgreSQL will keep both rows. This
219
- -- index is the serialization point. The second generation's checkpoint fails,
220
- -- so it is never POSTed, and the next freeze drops it because its subscriber
221
- -- is already claimed. One logical delivery, one idempotency key.
222
- IF NOT EXISTS (
223
- SELECT 1 FROM pg_index
224
- JOIN pg_class index_class ON index_class.oid = pg_index.indexrelid
225
- WHERE pg_index.indrelid = recipient_table
226
- AND index_class.relname = 'idx_${rawRecipients}_attempted_subscriber'
227
- ) THEN
228
- CREATE UNIQUE INDEX idx_${rawRecipients}_attempted_subscriber
229
- ON ${recipientTable}(namespace, transition_id, subscriber_key)
230
- WHERE attempt_at IS NOT NULL;
231
- END IF;
232
- IF NOT EXISTS (
233
- SELECT 1 FROM pg_index
234
- JOIN pg_class index_class ON index_class.oid = pg_index.indexrelid
235
- WHERE pg_index.indrelid = activity_table AND index_class.relname = 'idx_${raw}_pending'
236
- ) THEN
237
- CREATE INDEX idx_${raw}_pending
238
- ON ${table}(namespace, next_attempt_at, lease_expires_at, activity_sequence)
239
- WHERE state = 'pending';
240
- END IF;
241
- IF NOT EXISTS (
242
- SELECT 1 FROM pg_index
243
- JOIN pg_class index_class ON index_class.oid = pg_index.indexrelid
244
- WHERE pg_index.indrelid = activity_table AND index_class.relname = 'idx_${raw}_pending_tenant'
245
- ) THEN
246
- CREATE INDEX idx_${raw}_pending_tenant
247
- ON ${table}(namespace, tenant_scope)
248
- WHERE state = 'pending';
249
- END IF;
250
- IF NOT EXISTS (
251
- SELECT 1 FROM pg_index
252
- JOIN pg_class index_class ON index_class.oid = pg_index.indexrelid
253
- WHERE pg_index.indrelid = activity_table AND index_class.relname = 'idx_${raw}_pending_tenant_due'
254
- ) THEN
255
- CREATE INDEX idx_${raw}_pending_tenant_due
256
- ON ${table}(namespace, tenant_scope, next_attempt_at, lease_expires_at)
257
- WHERE state = 'pending';
258
- END IF;
259
- IF NOT EXISTS (
260
- SELECT 1 FROM pg_index
261
- JOIN pg_class index_class ON index_class.oid = pg_index.indexrelid
262
- WHERE pg_index.indrelid = activity_table AND index_class.relname = 'idx_${raw}_account_activity'
263
- ) THEN
264
- CREATE INDEX idx_${raw}_account_activity
265
- ON ${table}(namespace, tenant_scope, account_id, activity_sequence DESC);
266
- END IF;
267
- END $$;
268
- `.trim();
269
- }
270
- function recipientTableName(tableName = DEFAULT_TABLE) {
271
- return `${tableName}_recipients`;
272
- }
273
- const REPORTING_NOTIFICATION_ACTIVITY_MIGRATION = getReportingNotificationActivityMigration();
274
- function createPostgresReportingNotificationAttemptCheckpoint(options) {
275
- if (!options?.db || typeof options.db.query !== "function") {
276
- throw new TypeError("createPostgresReportingNotificationAttemptCheckpoint requires a PostgreSQL queryable");
277
- }
278
- const namespace = options.namespace ?? DEFAULT_NAMESPACE;
279
- assertIdentifier(namespace, "namespace", 255);
280
- const rawTable = options.tableName ?? DEFAULT_TABLE;
281
- const recipientTable = quoteIdentifier(recipientTableName(rawTable), MAX_RECIPIENT_TABLE_BYTES);
282
- const owned = /* @__PURE__ */ new Set([
283
- REPORTING_STATUS_EVENT_TYPE,
284
- REPORTING_LEDGER_EVENT_TYPE,
285
- REPORTING_DELIVERY_EVENT_TYPE,
286
- ...options.eventTypes ?? []
287
- ]);
288
- const checkpoint = async (input) => {
289
- if (!owned.has(input.eventType)) return;
290
- const fingerprint = recipientFingerprint({
291
- scope: input.scope,
292
- subscriberId: input.subscriberId,
293
- destinationGeneration: input.destinationGeneration
294
- });
295
- const marked = await reportingActivityDatabaseOperation(
296
- "Reporting notification delivery attempt could not be checkpointed",
297
- () => options.db.query(
298
- `UPDATE ${recipientTable} SET attempt_at = COALESCE(attempt_at, clock_timestamp())
299
- WHERE namespace = $1 AND transition_id = $2 AND recipient_fingerprint = $3`,
300
- [namespace, input.notificationId, fingerprint]
301
- )
302
- );
303
- if (marked.rowCount !== 1) {
304
- throw new Error(
305
- "Reporting notification delivery attempt has no frozen recipient to checkpoint; the emission owner must freeze its recipient set before any external attempt"
306
- );
307
- }
308
- };
309
- return Object.assign(checkpoint, {
310
- activityStore: Object.freeze({ db: options.db, namespace, tableName: rawTable })
311
- });
312
- }
313
- function createPostgresReportingNotificationActivityRuntime(options) {
314
- if (!options?.db || typeof options.db.query !== "function") {
315
- throw new TypeError("createPostgresReportingNotificationActivityRuntime requires a PostgreSQL queryable");
316
- }
317
- if (!options.notifications || typeof options.notifications.emit !== "function") {
318
- throw new TypeError(
319
- "createPostgresReportingNotificationActivityRuntime requires the persistent notification runtime"
320
- );
321
- }
322
- if (typeof options.tenantScopeForAccount !== "function") {
323
- throw new TypeError("tenantScopeForAccount must be a function");
324
- }
325
- if (options.notifications.hasDeliveryAttemptCheckpoint !== true && !options.acknowledgeMissingAttemptCheckpoint) {
326
- throw new TypeError(
327
- "createPostgresReportingNotificationActivityRuntime requires a notification port that runs the durable pre-POST attempt checkpoint. Build createPostgresReportingNotificationAttemptCheckpoint() and pass it as checkpointDeliveryAttempt; a custom port must set hasDeliveryAttemptCheckpoint: true to prove it forwards the event it is given."
328
- );
329
- }
330
- const namespace = options.namespace ?? DEFAULT_NAMESPACE;
331
- if (!options.attemptCheckpoint && !options.acknowledgeMissingAttemptCheckpoint) {
332
- throw new TypeError(
333
- "createPostgresReportingNotificationActivityRuntime requires attemptCheckpoint: pass the very checkpoint wired into the notification runtime so its durable store can be verified against this one."
334
- );
335
- }
336
- const wired = options.notifications.deliveryAttemptCheckpoint;
337
- if (wired !== void 0 && options.attemptCheckpoint && wired !== options.attemptCheckpoint) {
338
- throw new TypeError(
339
- "createPostgresReportingNotificationActivityRuntime: the notification runtime invokes a different checkpoint than the one passed as attemptCheckpoint. Each can be correctly built and still target a different store, in which case every delivery checkpoints nothing and is abandoned undelivered. Pass the very object wired into checkpointDeliveryAttempt."
340
- );
341
- }
342
- if (options.attemptCheckpoint && wired === void 0 && !options.attemptCheckpoint.activityStore) {
343
- throw new TypeError(
344
- "createPostgresReportingNotificationActivityRuntime: attemptCheckpoint declares no durable store and the notification port does not expose the checkpoint it invokes, so neither its identity nor its target can be verified. Build it with createPostgresReportingNotificationAttemptCheckpoint()."
345
- );
346
- }
347
- if (options.attemptCheckpoint?.activityStore) {
348
- const bound = options.attemptCheckpoint.activityStore;
349
- const mismatch = bound.db !== options.db || bound.namespace !== namespace || bound.tableName !== (options.tableName ?? DEFAULT_TABLE);
350
- if (mismatch) {
351
- throw new TypeError(
352
- `createPostgresReportingNotificationActivityRuntime: attemptCheckpoint is bound to a different durable store (namespace ${JSON.stringify(bound.namespace)}, table ${JSON.stringify(bound.tableName)}${bound.db === options.db ? "" : ", different queryable"}) than this runtime (namespace ${JSON.stringify(namespace)}, table ${JSON.stringify(options.tableName ?? DEFAULT_TABLE)}). A mismatched pair checkpoints nothing, so every delivery is suppressed until its binding retires and the notification is lost silently.`
353
- );
354
- }
355
- }
356
- const development = process.env.NODE_ENV === "test" || process.env.NODE_ENV === "development";
357
- if (!development && options.namespace === void 0 && !options.acknowledgeIsolatedDatabase) {
358
- throw new TypeError(
359
- "Production reporting notification activity requires an explicit deployment namespace or acknowledgeIsolatedDatabase: true"
360
- );
361
- }
362
- assertIdentifier(namespace, "namespace", 255);
363
- const rawTable = options.tableName ?? DEFAULT_TABLE;
364
- const table = quoteIdentifier(rawTable);
365
- const retentionMs = options.retentionMs ?? DEFAULT_RETENTION_MS;
366
- positiveInteger(retentionMs, "retentionMs");
367
- const maxPendingPerTenant = options.maxPendingPerTenant ?? DEFAULT_MAX_PENDING_PER_TENANT;
368
- boundedInteger(maxPendingPerTenant, "maxPendingPerTenant", 1, 1e6);
369
- const maxRecipients = options.maxRecipients ?? MAX_SUPPORTED_RECIPIENTS;
370
- boundedInteger(maxRecipients, "maxRecipients", 1, MAX_SUPPORTED_RECIPIENTS);
371
- const maxRetainedRecipients = options.maxRetainedRecipients ?? maxRecipients * 2;
372
- boundedInteger(maxRetainedRecipients, "maxRetainedRecipients", 1, MAX_SUPPORTED_RETAINED_RECIPIENTS);
373
- if (maxRetainedRecipients < maxRecipients) {
374
- throw new TypeError(
375
- `maxRetainedRecipients ${maxRetainedRecipients} is below maxRecipients ${maxRecipients}; a full fanout could then never be retained and every claim at that size would abandon undelivered`
376
- );
377
- }
378
- const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
379
- boundedInteger(maxAttempts, "maxAttempts", 1, 1e5);
380
- const recipientRawTable = recipientTableName(rawTable);
381
- const recipientTable = quoteIdentifier(recipientRawTable, MAX_RECIPIENT_TABLE_BYTES);
382
- const cursorTable = quoteIdentifier(`${rawTable}_cursor`, MAX_RECIPIENT_TABLE_BYTES);
383
- const worstCaseIndexBytes = Buffer.byteLength(namespace, "utf8") + MAX_TRANSITION_ID_BYTES + RECIPIENT_ROUND_BYTES + RECIPIENT_FINGERPRINT_BYTES;
384
- if (worstCaseIndexBytes > MAX_BTREE_ENTRY_BYTES) {
385
- throw new TypeError(
386
- `Reporting notification activity namespace is too long to index recipient intent (${worstCaseIndexBytes} of ${MAX_BTREE_ENTRY_BYTES} bytes); shorten namespace`
387
- );
388
- }
389
- const persistActivity = async (transaction, input) => {
390
- const { activity, eventId, notificationRequired, obligation } = input;
391
- const persistenceEventId = activity.activityType === "reporting.lifecycle_changed" ? eventId.startsWith(REPORTING_EVENT_STORAGE_PREFIX) || Buffer.byteLength(eventId, "utf8") > 255 || !/^[A-Za-z0-9_.:-]+$/.test(eventId) ? `${REPORTING_EVENT_STORAGE_PREFIX}${canonicalJsonSha256({ kind: "lifecycle", eventId })}` : eventId : `${REPORTING_EVENT_STORAGE_PREFIX}${canonicalJsonSha256({
392
- kind: activity.activityType,
393
- changeKind: activity.activityType === "reporting.ledger_changed" ? activity.changeKind : "ready",
394
- eventId
395
- })}`;
396
- const accountId = obligation.account.account_id;
397
- const tenantId = activity.tenantId;
398
- if (Buffer.byteLength(JSON.stringify(activity), "utf8") > MAX_ACTIVITY_BYTES) {
399
- throw new RangeError("Reporting notification/activity intent exceeds 64 KiB");
400
- }
401
- const fingerprint = canonicalJsonSha256(activity);
402
- if (notificationRequired) {
403
- await reportingActivityDatabaseOperation("Reporting notification/activity capacity check failed", async () => {
404
- await transaction.query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", [
405
- `adcp-reporting-activity-cap:${namespace}:${tenantId}`
406
- ]);
407
- const existing = await transaction.query(
408
- `SELECT intent_fingerprint, tenant_scope, account_id, obligation_id
409
- FROM ${table}
410
- WHERE namespace = $1 AND transition_id = $2`,
411
- [namespace, persistenceEventId]
412
- );
413
- const existingIntent = existing.rows[0];
414
- if (existingIntent) {
415
- if (existingIntent.intent_fingerprint !== fingerprint || existingIntent.tenant_scope !== tenantId || existingIntent.account_id !== accountId || existingIntent.obligation_id !== obligation.reporting_obligation_id) {
416
- throw new Error("Reporting event identity conflicts with existing notification/activity intent");
417
- }
418
- return;
419
- }
420
- const pending = await transaction.query(
421
- `SELECT COUNT(*)::integer AS count
422
- FROM (
423
- SELECT 1 FROM ${table}
424
- WHERE namespace = $1 AND tenant_scope = $2 AND state = 'pending'
425
- LIMIT $3
426
- ) bounded_pending`,
427
- [namespace, tenantId, maxPendingPerTenant]
428
- );
429
- if ((pending.rows[0]?.count ?? 0) >= maxPendingPerTenant) {
430
- throw new Error("Reporting notification activity pending capacity reached; recovery must catch up");
431
- }
432
- });
433
- }
434
- let write;
435
- try {
436
- write = await transaction.query(
437
- `INSERT INTO ${table} (
438
- namespace, transition_id, tenant_scope, account_id, obligation_id,
439
- activity, intent_fingerprint, notification_required, state,
440
- projected_at, retain_until
441
- ) VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7, $8,
442
- CASE WHEN $8 THEN 'pending' ELSE 'projected' END,
443
- CASE WHEN $8 THEN NULL ELSE clock_timestamp() END,
444
- CASE WHEN $8 THEN NULL ELSE clock_timestamp() + ($9::bigint * INTERVAL '1 millisecond') END)
445
- ON CONFLICT (namespace, transition_id) DO UPDATE SET
446
- transition_id = EXCLUDED.transition_id
447
- WHERE ${table}.intent_fingerprint = EXCLUDED.intent_fingerprint
448
- AND ${table}.tenant_scope = EXCLUDED.tenant_scope
449
- AND ${table}.account_id = EXCLUDED.account_id
450
- AND ${table}.obligation_id = EXCLUDED.obligation_id
451
- RETURNING transition_id`,
452
- [
453
- namespace,
454
- persistenceEventId,
455
- tenantId,
456
- accountId,
457
- obligation.reporting_obligation_id,
458
- JSON.stringify(activity),
459
- fingerprint,
460
- notificationRequired,
461
- retentionMs
462
- ]
463
- );
464
- } catch (cause) {
465
- if (isPostgresUndefinedTable(cause)) {
466
- throw new Error(
467
- "Reporting notification/activity persistence failed: run getReportingNotificationActivityMigration() before serving",
468
- { cause }
469
- );
470
- }
471
- throw new Error("Reporting notification/activity persistence failed", { cause });
472
- }
473
- if (write.rowCount !== 1) {
474
- throw new Error("Reporting event identity conflicts with existing notification/activity intent");
475
- }
476
- };
477
- const activityScope = (transaction, obligation, eventId) => {
478
- if (!transaction || typeof transaction.query !== "function") {
479
- throw new TypeError("Reporting notification/activity persistence requires the active ledger transaction");
480
- }
481
- const accountId = obligation.account.account_id;
482
- assertIdentifier(accountId, "accountId", 512);
483
- assertIdentifier(eventId, "eventId", MAX_TRANSITION_ID_BYTES);
484
- const tenantId = options.tenantScopeForAccount(accountId);
485
- if (isPromiseLike(tenantId)) {
486
- throw new TypeError("tenantScopeForAccount must be synchronous and side-effect free");
487
- }
488
- assertIdentifier(tenantId, "tenantId", 512);
489
- return { accountId, tenantId };
490
- };
491
- const databaseNow = async (transaction) => {
492
- const result = await transaction.query("SELECT clock_timestamp() AS now");
493
- if (!result.rows[0]) throw new Error("Reporting notification/activity database clock is unavailable");
494
- return asIso(result.rows[0].now);
495
- };
496
- const port = {
497
- async recordTransition(input, transaction) {
498
- const { tenantId } = activityScope(transaction, input.obligation, input.transition.transitionId);
499
- if (input.transition.reporting_obligation_id !== input.obligation.reporting_obligation_id) {
500
- throw new Error("Reporting transition and authoritative obligation identities disagree");
501
- }
502
- const activity = buildActivity(namespace, tenantId, input.transition, input.obligation);
503
- const notificationRequired = input.transition.previousHealth !== input.transition.health;
504
- await persistActivity(transaction, {
505
- eventId: input.transition.transitionId,
506
- obligation: input.obligation,
507
- activity,
508
- notificationRequired
509
- });
510
- },
511
- async recordLedgerChanged(input, transaction) {
512
- const record = "revision" in input ? input.revision : input.adjustment;
513
- const eventId = "revision" in input ? input.revision.reporting_revision_id : input.adjustment.reporting_adjustment_id;
514
- const { tenantId } = activityScope(transaction, input.obligation, eventId);
515
- if (record.reporting_obligation_id !== input.obligation.reporting_obligation_id) {
516
- throw new Error("Reporting ledger record and authoritative obligation identities disagree");
517
- }
518
- const occurredAt = await databaseNow(transaction);
519
- const activity = buildLedgerChangedActivity(namespace, tenantId, occurredAt, input);
520
- await persistActivity(transaction, {
521
- eventId,
522
- obligation: input.obligation,
523
- activity,
524
- notificationRequired: true
525
- });
526
- },
527
- async recordDeliveryReady(input, transaction) {
528
- const eventId = input.materialization.reporting_materialization_id;
529
- const { tenantId } = activityScope(transaction, input.obligation, eventId);
530
- if (input.revision.reporting_obligation_id !== input.obligation.reporting_obligation_id || input.materialization.reporting_revision_id !== input.revision.reporting_revision_id) {
531
- throw new Error("Reporting delivery-ready records do not share one authoritative ledger identity");
532
- }
533
- if (input.materialization.status !== "available" && input.materialization.status !== "delivered") {
534
- throw new Error("Reporting delivery-ready activity requires a successful materialization");
535
- }
536
- const occurredAt = await databaseNow(transaction);
537
- const activity = buildDeliveryReadyActivity(namespace, tenantId, occurredAt, input);
538
- await persistActivity(transaction, {
539
- eventId,
540
- obligation: input.obligation,
541
- activity,
542
- notificationRequired: true
543
- });
544
- }
545
- };
546
- const readActivity = async (input, lifecycleOnly) => {
547
- assertIdentifier(input.tenantId, "tenantId", 512);
548
- assertIdentifier(input.accountId, "accountId", 512);
549
- const expectedTenantId = options.tenantScopeForAccount(input.accountId);
550
- if (isPromiseLike(expectedTenantId)) {
551
- throw new TypeError("tenantScopeForAccount must be synchronous and side-effect free");
552
- }
553
- assertIdentifier(expectedTenantId, "tenantId", 512);
554
- if (expectedTenantId !== input.tenantId) {
555
- throw new TypeError("Reporting account activity scope does not match the trusted account directory");
556
- }
557
- const limit = input.limit ?? 100;
558
- boundedInteger(limit, "limit", 1, 200);
559
- const before = decodeCursor(input.cursor, namespace, input.tenantId, input.accountId);
560
- const result = await reportingActivityDatabaseOperation(
561
- "Reporting account activity read failed",
562
- () => options.db.query(
563
- `SELECT activity, state, created_at, projected_at, abandoned_at, activity_sequence
564
- FROM ${table}
565
- WHERE namespace = $1 AND tenant_scope = $2 AND account_id = $3
566
- AND ($4::bigint IS NULL OR activity_sequence < $4)
567
- AND ($6::boolean = false OR activity->>'activityType' = 'reporting.lifecycle_changed')
568
- ORDER BY activity_sequence DESC
569
- LIMIT $5`,
570
- [namespace, input.tenantId, input.accountId, before ?? null, limit + 1, lifecycleOnly]
571
- )
572
- );
573
- const selected = result.rows.slice(0, limit);
574
- const activities = selected.map((row) => ({
575
- ...structuredClone(row.activity),
576
- recordedAt: asIso(row.created_at),
577
- ...row.projected_at ? { notificationProjectedAt: asIso(row.projected_at) } : {},
578
- ...row.abandoned_at ? { notificationAbandonedAt: asIso(row.abandoned_at) } : {}
579
- }));
580
- const hasMore = result.rows.length > limit;
581
- return {
582
- activities,
583
- hasMore,
584
- ...hasMore && selected.length > 0 ? {
585
- nextCursor: encodeCursor(
586
- namespace,
587
- input.tenantId,
588
- input.accountId,
589
- String(selected[selected.length - 1].activity_sequence)
590
- )
591
- } : {}
592
- };
593
- };
594
- return {
595
- port,
596
- migrations: {
597
- activity: getReportingNotificationActivityMigration({ tableName: rawTable }),
598
- all: [getReportingNotificationActivityMigration({ tableName: rawTable })]
599
- },
600
- async probe() {
601
- if (options.notifications.hasDeliveryAttemptCheckpoint !== true) {
602
- throw new Error(
603
- "Reporting notification/activity probe failed: the notification port does not prove it runs the durable pre-POST attempt checkpoint. Wire createPostgresReportingNotificationAttemptCheckpoint() into checkpointDeliveryAttempt, or set hasDeliveryAttemptCheckpoint: true on a custom port that forwards the event it is given."
604
- );
605
- }
606
- try {
607
- await options.db.query(
608
- `SELECT namespace, transition_id, tenant_scope, account_id, obligation_id,
609
- activity, intent_fingerprint, state, notification_required, lease_owner, lease_version,
610
- lease_expires_at, projected_at, retain_until, delivery_intent_at, abandoned_at
611
- FROM ${table} LIMIT 0`
612
- );
613
- await options.db.query(
614
- `SELECT namespace, transition_id, recipient_fingerprint, recipient, frozen_at,
615
- attempt_at, settled_at, disposition
616
- FROM ${recipientTable} LIMIT 0`
617
- );
618
- await options.db.query(`SELECT namespace, tenant_scope, changed_at FROM ${cursorTable} LIMIT 0`);
619
- } catch (cause) {
620
- throw new Error(
621
- "Reporting notification/activity probe failed: run getReportingNotificationActivityMigration() before serving",
622
- { cause }
623
- );
624
- }
625
- },
626
- async recoverOnce(recoveryOptions = {}) {
627
- const ownerToken = recoveryOptions.ownerToken ?? randomUUID();
628
- assertIdentifier(ownerToken, "ownerToken", 255);
629
- if (ownerToken.length < 8) throw new TypeError("ownerToken must contain at least 8 characters");
630
- const leaseMs = recoveryOptions.leaseMs ?? 6e4;
631
- const limit = recoveryOptions.limit ?? 50;
632
- const retryAfterMs = recoveryOptions.retryAfterMs ?? 3e4;
633
- boundedInteger(leaseMs, "leaseMs", 1e3, 3e5);
634
- boundedInteger(limit, "limit", 1, 1e3);
635
- boundedInteger(retryAfterMs, "retryAfterMs", 1, 6048e5);
636
- const metrics = {
637
- claimed: 0,
638
- matched: 0,
639
- projected: 0,
640
- retried: 0,
641
- leaseLost: 0,
642
- abandoned: 0
643
- };
644
- let emptyTenantClaims = 0;
645
- while (metrics.claimed < limit && emptyTenantClaims < 8) {
646
- recoveryOptions.signal?.throwIfAborted();
647
- const [claim] = await claimPending(options.db, table, cursorTable, namespace, ownerToken, leaseMs, 1);
648
- if (!claim) {
649
- emptyTenantClaims += 1;
650
- continue;
651
- }
652
- emptyTenantClaims = 0;
653
- metrics.claimed += 1;
654
- let leaseLost = false;
655
- let renewing = false;
656
- const heartbeat = setInterval(
657
- () => {
658
- if (renewing || leaseLost) return;
659
- renewing = true;
660
- void renewClaim(options.db, table, namespace, claim, leaseMs).then((renewed) => {
661
- if (!renewed) leaseLost = true;
662
- }).catch(() => {
663
- leaseLost = true;
664
- }).finally(() => {
665
- renewing = false;
666
- });
667
- },
668
- Math.max(250, Math.floor(leaseMs / 3))
669
- );
670
- heartbeat.unref?.();
671
- try {
672
- const notificationType = claim.activity.notificationType;
673
- if (!notificationType) throw new Error("Pending reporting activity has no notification type");
674
- let frozen = [];
675
- let froze = false;
676
- const result = await options.notifications.emit({
677
- emissionId: claim.activity.activityId,
678
- notificationId: claim.transitionId,
679
- notificationType,
680
- anchor: "account",
681
- tenantId: claim.tenantId,
682
- accountId: claim.accountId,
683
- payload: notificationPayload(claim.activity),
684
- // Commit the recipient set under this lease before anything leaves
685
- // the process. Each recipient is revisable until its own durable
686
- // pre-POST checkpoint and pinned afterwards.
687
- freezeRecipients: async (candidates) => {
688
- froze = true;
689
- frozen = await freezeClaimRecipients(
690
- options.db,
691
- table,
692
- recipientTable,
693
- namespace,
694
- claim,
695
- maxRecipients,
696
- maxRetainedRecipients,
697
- candidates
698
- );
699
- return frozen;
700
- }
701
- });
702
- if (!froze) {
703
- throw new Error(
704
- "Reporting notification port did not freeze its recipient set; it must forward the emitted event, including freezeRecipients, to a runtime that honours it. Nothing was projected."
705
- );
706
- }
707
- metrics.matched += result.matched;
708
- const outcomes = result.deliveries.map((delivery) => classifyDelivery(delivery));
709
- const settlement = await settleClaimRecipients(
710
- options.db,
711
- table,
712
- recipientTable,
713
- namespace,
714
- claim,
715
- frozen,
716
- outcomes
717
- );
718
- if (!settlement.settled) {
719
- const retryable = outcomes.find((outcome) => outcome.disposition === "retryable");
720
- throw retryable?.suppression ? new ReportingNotificationRetryableSuppressionError(retryable.suppression) : new Error(
721
- `Reporting notification delivery is not settled for ${settlement.unsettled} recipient(s); retrying`
722
- );
723
- }
724
- const projected = !leaseLost && await projectClaim(options.db, table, namespace, claim, retentionMs);
725
- if (projected) metrics.projected += 1;
726
- else metrics.leaseLost += 1;
727
- } catch (error) {
728
- reportProjectionError(recoveryOptions.onError, error, claim);
729
- if (!leaseLost && claim.attemptCount >= maxAttempts) {
730
- const abandoned = await abandonClaim(options.db, table, namespace, claim, retentionMs);
731
- if (abandoned) metrics.abandoned += 1;
732
- else metrics.leaseLost += 1;
733
- } else {
734
- const released = !leaseLost && await releaseClaim(options.db, table, namespace, claim, retryAfterMs);
735
- if (released) metrics.retried += 1;
736
- else metrics.leaseLost += 1;
737
- }
738
- } finally {
739
- clearInterval(heartbeat);
740
- }
741
- }
742
- return metrics;
743
- },
744
- async listActivity(input) {
745
- return await readActivity(input, true);
746
- },
747
- async listNotificationActivity(input) {
748
- return readActivity(input, false);
749
- },
750
- async pruneProjected(pruneOptions = {}) {
751
- const limit = pruneOptions.limit ?? 1e3;
752
- boundedInteger(limit, "limit", 1, 1e4);
753
- const result = await reportingActivityDatabaseOperation(
754
- "Reporting account activity pruning failed",
755
- () => options.db.query(
756
- `WITH expired AS (
757
- SELECT namespace, transition_id FROM ${table}
758
- WHERE namespace = $1 AND state IN ('projected', 'abandoned')
759
- AND retain_until <= clock_timestamp()
760
- ORDER BY retain_until, activity_sequence
761
- FOR UPDATE SKIP LOCKED LIMIT $2
762
- )
763
- DELETE FROM ${table} target USING expired
764
- WHERE target.namespace = expired.namespace AND target.transition_id = expired.transition_id`,
765
- [namespace, limit]
766
- )
767
- );
768
- return result.rowCount ?? 0;
769
- }
770
- };
771
- }
772
- function buildActivity(namespace, tenantId, transition, obligation) {
773
- const identity = canonicalJsonSha256({
774
- namespace,
775
- tenantId,
776
- accountId: obligation.account.account_id,
777
- transitionId: transition.transitionId
778
- });
779
- return {
780
- activityId: `ract_${identity.slice(0, 32)}`,
781
- transitionId: transition.transitionId,
782
- activityType: "reporting.lifecycle_changed",
783
- ...transition.previousHealth === transition.health ? {} : { notificationType: "reporting.status_changed" },
784
- tenantId,
785
- accountId: obligation.account.account_id,
786
- reporting_obligation_id: obligation.reporting_obligation_id,
787
- previousHealth: transition.previousHealth,
788
- health: transition.health,
789
- previousFinality: transition.previousFinality ?? "none",
790
- finality: transition.finality ?? "none",
791
- issueIds: [...transition.issueIds],
792
- occurredAt: transition.occurredAt,
793
- correlation: {
794
- delivery_config_id: obligation.delivery_config_id,
795
- delivery_config_version: obligation.delivery_config_version,
796
- report_definition_id: obligation.report_definition_id,
797
- feed_purpose: obligation.feedPurpose,
798
- period: { start: obligation.period.start, end: obligation.period.end }
799
- }
800
- };
801
- }
802
- function activityIdentity(namespace, tenantId, accountId, eventId, eventType) {
803
- return `ract_${canonicalJsonSha256({ namespace, tenantId, accountId, eventId, eventType }).slice(0, 32)}`;
804
- }
805
- function buildLedgerChangedActivity(namespace, tenantId, occurredAt, input) {
806
- const accountId = input.obligation.account.account_id;
807
- if ("revision" in input) {
808
- const eventId2 = input.revision.reporting_revision_id;
809
- return {
810
- activityId: activityIdentity(
811
- namespace,
812
- tenantId,
813
- accountId,
814
- eventId2,
815
- `${REPORTING_LEDGER_EVENT_TYPE}:revision_published`
816
- ),
817
- transitionId: eventId2,
818
- activityType: REPORTING_LEDGER_EVENT_TYPE,
819
- notificationType: REPORTING_LEDGER_EVENT_TYPE,
820
- tenantId,
821
- accountId,
822
- reporting_obligation_id: input.obligation.reporting_obligation_id,
823
- occurredAt,
824
- changeKind: "revision_published",
825
- reporting_revision_id: eventId2,
826
- ...input.revision.supersedes_reporting_revision_id ? { supersedes_reporting_revision_id: input.revision.supersedes_reporting_revision_id } : {},
827
- finality: input.revision.finality
828
- };
829
- }
830
- const eventId = input.adjustment.reporting_adjustment_id;
831
- return {
832
- activityId: activityIdentity(
833
- namespace,
834
- tenantId,
835
- accountId,
836
- eventId,
837
- `${REPORTING_LEDGER_EVENT_TYPE}:adjustment_published`
838
- ),
839
- transitionId: eventId,
840
- activityType: REPORTING_LEDGER_EVENT_TYPE,
841
- notificationType: REPORTING_LEDGER_EVENT_TYPE,
842
- tenantId,
843
- accountId,
844
- reporting_obligation_id: input.obligation.reporting_obligation_id,
845
- occurredAt,
846
- changeKind: "adjustment_published",
847
- reporting_adjustment_id: eventId,
848
- adjusts_reporting_revision_id: input.adjustment.adjusts_reporting_revision_id
849
- };
850
- }
851
- function buildDeliveryReadyActivity(namespace, tenantId, occurredAt, input) {
852
- const accountId = input.obligation.account.account_id;
853
- const eventId = input.materialization.reporting_materialization_id;
854
- const readiness = input.materialization.status;
855
- if (readiness !== "available" && readiness !== "delivered") {
856
- throw new Error("Reporting delivery-ready activity requires a successful materialization");
857
- }
858
- return {
859
- activityId: activityIdentity(namespace, tenantId, accountId, eventId, REPORTING_DELIVERY_EVENT_TYPE),
860
- transitionId: eventId,
861
- activityType: REPORTING_DELIVERY_EVENT_TYPE,
862
- notificationType: REPORTING_DELIVERY_EVENT_TYPE,
863
- tenantId,
864
- accountId,
865
- reporting_obligation_id: input.obligation.reporting_obligation_id,
866
- occurredAt,
867
- delivery_config_id: input.obligation.delivery_config_id,
868
- delivery_config_version: input.obligation.delivery_config_version,
869
- feed_purpose: input.obligation.feedPurpose,
870
- reporting_revision_id: input.revision.reporting_revision_id,
871
- reporting_materialization_id: eventId,
872
- readiness,
873
- finality: input.revision.finality,
874
- data_through: input.revision.dataThrough
875
- };
876
- }
877
- function notificationPayload(activity) {
878
- if (activity.activityType === "reporting.lifecycle_changed") {
879
- return {
880
- reporting_obligation_id: activity.reporting_obligation_id,
881
- previous_health: activity.previousHealth,
882
- health: activity.health,
883
- issue_ids: [...activity.issueIds],
884
- fired_at: activity.occurredAt,
885
- delivery_config_id: activity.correlation.delivery_config_id,
886
- delivery_config_version: activity.correlation.delivery_config_version,
887
- feed_purpose: activity.correlation.feed_purpose
888
- };
889
- }
890
- if (activity.activityType === REPORTING_LEDGER_EVENT_TYPE) {
891
- return {
892
- fired_at: activity.occurredAt,
893
- change_kind: activity.changeKind,
894
- ...activity.reporting_revision_id ? { reporting_revision_id: activity.reporting_revision_id } : {},
895
- ...activity.supersedes_reporting_revision_id ? { supersedes_reporting_revision_id: activity.supersedes_reporting_revision_id } : {},
896
- ...activity.finality ? { finality: activity.finality } : {},
897
- ...activity.reporting_adjustment_id ? { reporting_adjustment_id: activity.reporting_adjustment_id } : {},
898
- ...activity.adjusts_reporting_revision_id ? { adjusts_reporting_revision_id: activity.adjusts_reporting_revision_id } : {}
899
- };
900
- }
901
- return {
902
- fired_at: activity.occurredAt,
903
- delivery_config_id: activity.delivery_config_id,
904
- delivery_config_version: activity.delivery_config_version,
905
- feed_purpose: activity.feed_purpose,
906
- reporting_revision_id: activity.reporting_revision_id,
907
- reporting_materialization_id: activity.reporting_materialization_id,
908
- readiness: activity.readiness,
909
- finality: activity.finality,
910
- data_through: activity.data_through
911
- };
912
- }
913
- async function claimPending(db, table, cursorTable, namespace, ownerToken, leaseMs, limit) {
914
- const result = await reportingActivityDatabaseOperation(
915
- "Reporting notification recovery claim failed",
916
- () => db.query(
917
- `WITH selected_tenant AS (
918
- INSERT INTO ${cursorTable} (namespace, tenant_scope)
919
- VALUES (
920
- $1,
921
- (SELECT MIN(tenant_scope) FROM ${table}
922
- WHERE namespace = $1 AND state = 'pending' AND next_attempt_at <= clock_timestamp()
923
- AND (lease_expires_at IS NULL OR lease_expires_at < clock_timestamp()))
924
- )
925
- ON CONFLICT (namespace) DO UPDATE SET
926
- tenant_scope = COALESCE(
927
- (SELECT MIN(candidate.tenant_scope) FROM ${table} candidate
928
- WHERE candidate.namespace = $1 AND candidate.state = 'pending'
929
- AND candidate.next_attempt_at <= clock_timestamp()
930
- AND (candidate.lease_expires_at IS NULL OR candidate.lease_expires_at < clock_timestamp())
931
- AND candidate.tenant_scope > ${cursorTable}.tenant_scope),
932
- (SELECT MIN(candidate.tenant_scope) FROM ${table} candidate
933
- WHERE candidate.namespace = $1 AND candidate.state = 'pending'
934
- AND candidate.next_attempt_at <= clock_timestamp()
935
- AND (candidate.lease_expires_at IS NULL OR candidate.lease_expires_at < clock_timestamp()))
936
- ),
937
- changed_at = clock_timestamp()
938
- RETURNING tenant_scope
939
- ), candidates AS (
940
- SELECT activity.namespace, activity.transition_id FROM ${table} activity
941
- CROSS JOIN selected_tenant selected
942
- WHERE activity.namespace = $1 AND activity.state = 'pending'
943
- AND activity.tenant_scope = selected.tenant_scope
944
- AND activity.next_attempt_at <= clock_timestamp()
945
- AND (activity.lease_expires_at IS NULL OR activity.lease_expires_at < clock_timestamp())
946
- ORDER BY activity.next_attempt_at, activity.activity_sequence
947
- FOR UPDATE OF activity SKIP LOCKED LIMIT $4
948
- )
949
- UPDATE ${table} target SET
950
- lease_owner = $2,
951
- lease_version = target.lease_version + 1,
952
- lease_expires_at = clock_timestamp() + ($3::bigint * INTERVAL '1 millisecond'),
953
- attempt_count = target.attempt_count + 1
954
- FROM candidates
955
- WHERE target.namespace = candidates.namespace AND target.transition_id = candidates.transition_id
956
- RETURNING target.transition_id, target.tenant_scope, target.account_id,
957
- target.activity, target.lease_version::text, target.attempt_count`,
958
- [namespace, ownerToken, leaseMs, limit]
959
- )
960
- );
961
- return result.rows.map((row) => ({
962
- transitionId: row.transition_id,
963
- tenantId: row.tenant_scope,
964
- accountId: row.account_id,
965
- activity: structuredClone(row.activity),
966
- leaseOwner: ownerToken,
967
- leaseVersion: row.lease_version,
968
- attemptCount: row.attempt_count
969
- }));
970
- }
971
- async function freezeClaimRecipients(db, table, recipientTable, namespace, claim, maxRecipients, maxRetainedRecipients, candidates) {
972
- if (candidates.length > maxRecipients) {
973
- throw new Error(
974
- `Reporting notification fanout of ${candidates.length} recipients exceeds maxRecipients ${maxRecipients}; raise maxRecipients to at least the notification runtime maxFanoutCandidates`
975
- );
976
- }
977
- const fenced = await reportingActivityDatabaseOperation(
978
- "Reporting notification recipient intent could not be committed",
979
- () => db.query(
980
- `UPDATE ${table} SET delivery_intent_at = COALESCE(delivery_intent_at, clock_timestamp())
981
- WHERE namespace = $1 AND transition_id = $2 AND state = 'pending'
982
- AND lease_owner = $3 AND lease_version = $4::bigint
983
- AND lease_expires_at >= clock_timestamp()`,
984
- [namespace, claim.transitionId, claim.leaseOwner, claim.leaseVersion]
985
- )
986
- );
987
- if (fenced.rowCount !== 1) {
988
- throw new Error("Reporting notification recipient intent was not committed; the recovery lease was lost");
989
- }
990
- const rows = canonicalRecipients(candidates);
991
- await compactSettledRecipients(db, table, recipientTable, namespace, claim);
992
- const committed = await reportingActivityDatabaseOperation(
993
- "Reporting notification recipient intent could not be committed",
994
- () => db.query(
995
- `WITH leased AS MATERIALIZED (
996
- -- The parent row is the serialization point, and MATERIALIZED makes
997
- -- its lock the statement's first act. Reading the lease without
998
- -- locking it only proved the lease was live when the snapshot was
999
- -- taken: a statement that then blocked on a recipient lock could
1000
- -- resume long after a successor had claimed, still see its own lease
1001
- -- in the cached snapshot, and mutate the successor's rows. Holding
1002
- -- this lock means a takeover cannot complete while this statement
1003
- -- runs, and a statement that starts after one sees the new lease and
1004
- -- matches nothing.
1005
- SELECT transition_id FROM ${table}
1006
- WHERE namespace = $1 AND transition_id = $2 AND state = 'pending'
1007
- AND lease_owner = $3 AND lease_version = $4::bigint
1008
- AND lease_expires_at >= clock_timestamp()
1009
- FOR UPDATE
1010
- ), existing AS (
1011
- -- FOR UPDATE is what serializes this statement against a concurrent
1012
- -- checkpoint. Without it the budget is computed from a snapshot in
1013
- -- which a row is still revisable, the DELETE then re-checks the
1014
- -- locked row, finds it attempted and skips it, and the retained set
1015
- -- lands one row above the budget that approved the write.
1016
- SELECT current.recipient_fingerprint, current.subscriber_key, current.recipient,
1017
- current.attempt_at, current.settled_at
1018
- FROM ${recipientTable} current, leased
1019
- WHERE current.namespace = $1 AND current.transition_id = $2
1020
- FOR UPDATE OF current
1021
- ), claimed AS (
1022
- SELECT subscriber_key FROM existing
1023
- WHERE attempt_at IS NOT NULL OR settled_at IS NOT NULL
1024
- ), proposed AS (
1025
- SELECT entry.fingerprint, entry.subscriber_key, entry.recipient::jsonb AS recipient
1026
- FROM leased, unnest($5::text[], $6::text[], $7::text[])
1027
- AS entry(fingerprint, subscriber_key, recipient)
1028
- WHERE NOT EXISTS (SELECT 1 FROM claimed WHERE claimed.subscriber_key = entry.subscriber_key)
1029
- ), budget AS (
1030
- SELECT
1031
- (SELECT count(*) FROM existing
1032
- WHERE attempt_at IS NOT NULL OR settled_at IS NOT NULL
1033
- OR recipient_fingerprint IN (SELECT fingerprint FROM proposed))
1034
- + (SELECT count(*) FROM proposed
1035
- WHERE fingerprint NOT IN (SELECT recipient_fingerprint FROM existing)) AS retained
1036
- ), gate AS (
1037
- -- The lease is part of the gate, not just of the row sources. A
1038
- -- stale worker sees an empty \`leased\`, which makes every source
1039
- -- empty and the budget zero; without this predicate the budget would
1040
- -- be satisfied and the delete below would reap the rows the
1041
- -- successor had already frozen under its own lease.
1042
- SELECT retained, retained <= $8::integer AND EXISTS (SELECT 1 FROM leased) AS ok FROM budget
1043
- ), dropped AS (
1044
- DELETE FROM ${recipientTable} stale USING gate, leased
1045
- WHERE gate.ok AND stale.namespace = $1 AND stale.transition_id = $2
1046
- AND stale.attempt_at IS NULL AND stale.settled_at IS NULL
1047
- AND NOT (stale.recipient_fingerprint IN (SELECT fingerprint FROM proposed))
1048
- ), added AS (
1049
- INSERT INTO ${recipientTable}
1050
- (namespace, transition_id, recipient_fingerprint, subscriber_key, recipient)
1051
- SELECT $1, $2, proposed.fingerprint, proposed.subscriber_key, proposed.recipient
1052
- FROM proposed, gate, leased WHERE gate.ok
1053
- ON CONFLICT (namespace, transition_id, recipient_fingerprint) DO NOTHING
1054
- ), pinned AS (
1055
- SELECT recipient FROM existing WHERE attempt_at IS NOT NULL AND settled_at IS NULL
1056
- )
1057
- SELECT (SELECT count(*) FROM leased) = 1 AS leased, gate.ok, gate.retained, entry.recipient
1058
- FROM gate
1059
- LEFT JOIN (SELECT recipient FROM proposed UNION ALL SELECT recipient FROM pinned) entry ON TRUE`,
1060
- [
1061
- namespace,
1062
- claim.transitionId,
1063
- claim.leaseOwner,
1064
- claim.leaseVersion,
1065
- rows.map((entry) => entry.fingerprint),
1066
- rows.map((entry) => entry.subscriberKey),
1067
- rows.map((entry) => JSON.stringify(entry.recipient)),
1068
- maxRetainedRecipients
1069
- ]
1070
- )
1071
- );
1072
- const verdict = committed.rows[0];
1073
- if (!verdict?.leased) {
1074
- throw new Error("Reporting notification recipient intent was not committed; the recovery lease was lost");
1075
- }
1076
- if (!verdict.ok) {
1077
- throw new Error(
1078
- `Reporting notification recipient intent would hold ${verdict.retained} recipients, above maxRetainedRecipients ${maxRetainedRecipients}; nothing was changed. Raise maxRetainedRecipients to at least the fanout plus the distinct subscribers this notification can replace, or reduce its destination churn`
1079
- );
1080
- }
1081
- return committed.rows.flatMap((row) => row.recipient === null ? [] : [row.recipient]);
1082
- }
1083
- async function settleClaimRecipients(db, table, recipientTable, namespace, claim, frozen, deliveries) {
1084
- const outcomes = new Map(deliveries.map((delivery) => [recipientFingerprint(delivery.recipient), delivery]));
1085
- const terminal = [];
1086
- const delivered = [];
1087
- for (const recipient of frozen) {
1088
- const fingerprint = recipientFingerprint(recipient);
1089
- const outcome = outcomes.get(fingerprint);
1090
- if (outcome === void 0) {
1091
- terminal.push(fingerprint);
1092
- continue;
1093
- }
1094
- if (outcome.disposition === "delivered") delivered.push(fingerprint);
1095
- else if (outcome.disposition === "terminal") terminal.push(fingerprint);
1096
- }
1097
- if (delivered.length > 0 || terminal.length > 0) {
1098
- await reportingActivityDatabaseOperation(
1099
- "Reporting notification recipient settlement failed",
1100
- () => db.query(
1101
- `WITH leased AS MATERIALIZED (
1102
- SELECT transition_id FROM ${table}
1103
- WHERE namespace = $1 AND transition_id = $2 AND state = 'pending'
1104
- AND lease_owner = $5 AND lease_version = $6::bigint
1105
- AND lease_expires_at >= clock_timestamp()
1106
- FOR UPDATE
1107
- )
1108
- UPDATE ${recipientTable} AS target SET settled_at = clock_timestamp(),
1109
- disposition = CASE WHEN target.recipient_fingerprint = ANY($3::text[]) THEN 'delivered' ELSE 'terminal' END
1110
- FROM leased
1111
- WHERE target.namespace = $1 AND target.transition_id = $2 AND target.settled_at IS NULL
1112
- AND (target.recipient_fingerprint = ANY($3::text[]) OR target.recipient_fingerprint = ANY($4::text[]))`,
1113
- [namespace, claim.transitionId, delivered, terminal, claim.leaseOwner, claim.leaseVersion]
1114
- )
1115
- );
1116
- await compactSettledRecipients(db, table, recipientTable, namespace, claim);
1117
- }
1118
- const remaining = await reportingActivityDatabaseOperation(
1119
- "Reporting notification recipient settlement failed",
1120
- () => db.query(
1121
- `SELECT count(*)::integer AS unsettled FROM ${recipientTable}
1122
- WHERE namespace = $1 AND transition_id = $2 AND settled_at IS NULL`,
1123
- [namespace, claim.transitionId]
1124
- )
1125
- );
1126
- const unsettled = remaining.rows[0]?.unsettled ?? 0;
1127
- return { settled: unsettled === 0, unsettled };
1128
- }
1129
- async function compactSettledRecipients(db, table, recipientTable, namespace, claim) {
1130
- await reportingActivityDatabaseOperation(
1131
- "Reporting notification recipient compaction failed",
1132
- () => db.query(
1133
- `WITH leased AS MATERIALIZED (
1134
- SELECT transition_id FROM ${table}
1135
- WHERE namespace = $1 AND transition_id = $2 AND state = 'pending'
1136
- AND lease_owner = $3 AND lease_version = $4::bigint
1137
- AND lease_expires_at >= clock_timestamp()
1138
- FOR UPDATE
1139
- )
1140
- DELETE FROM ${recipientTable} superseded USING leased
1141
- WHERE superseded.namespace = $1 AND superseded.transition_id = $2
1142
- AND superseded.settled_at IS NOT NULL
1143
- AND EXISTS (
1144
- SELECT 1 FROM ${recipientTable} survivor
1145
- WHERE survivor.namespace = superseded.namespace
1146
- AND survivor.transition_id = superseded.transition_id
1147
- AND survivor.subscriber_key = superseded.subscriber_key
1148
- AND survivor.settled_at IS NOT NULL
1149
- AND (survivor.disposition, survivor.recipient_fingerprint)
1150
- > (superseded.disposition, superseded.recipient_fingerprint)
1151
- )`,
1152
- [namespace, claim.transitionId, claim.leaseOwner, claim.leaseVersion]
1153
- )
1154
- );
1155
- }
1156
- function classifyDelivery(delivery) {
1157
- const recipient = {
1158
- scope: delivery.scope,
1159
- subscriberId: delivery.subscriberId,
1160
- destinationGeneration: delivery.destinationGeneration
1161
- };
1162
- if (delivery.failure !== void 0 || !delivery.result) {
1163
- return { recipient, disposition: delivery.failure?.terminal === true ? "terminal" : "retryable" };
1164
- }
1165
- const suppression = delivery.result.suppression;
1166
- if (suppression) {
1167
- return {
1168
- recipient,
1169
- disposition: notificationSuppressionDisposition(suppression.reason) === "retryable" ? "retryable" : "terminal",
1170
- suppression: suppression.reason
1171
- };
1172
- }
1173
- if (delivery.result.delivered) return { recipient, disposition: "delivered" };
1174
- return { recipient, disposition: delivery.result.terminal === true ? "terminal" : "retryable" };
1175
- }
1176
- function recipientFingerprint(recipient) {
1177
- return canonicalJsonSha256({
1178
- scope: recipient.scope,
1179
- subscriberId: recipient.subscriberId,
1180
- destinationGeneration: recipient.destinationGeneration
1181
- });
1182
- }
1183
- function canonicalRecipients(candidates) {
1184
- return candidates.map((candidate) => {
1185
- const recipient = {
1186
- scope: candidate.scope,
1187
- subscriberId: candidate.subscriberId,
1188
- destinationGeneration: candidate.destinationGeneration
1189
- };
1190
- return {
1191
- fingerprint: recipientFingerprint(recipient),
1192
- subscriberKey: subscriberKey(recipient),
1193
- recipient
1194
- };
1195
- }).sort((left, right) => left.fingerprint < right.fingerprint ? -1 : 1);
1196
- }
1197
- function subscriberKey(recipient) {
1198
- return canonicalJsonSha256({ scope: recipient.scope, subscriberId: recipient.subscriberId });
1199
- }
1200
- async function renewClaim(db, table, namespace, claim, leaseMs) {
1201
- const result = await reportingActivityDatabaseOperation(
1202
- "Reporting notification lease renewal failed",
1203
- () => db.query(
1204
- `UPDATE ${table} SET lease_expires_at = clock_timestamp() + ($5::bigint * INTERVAL '1 millisecond')
1205
- WHERE namespace = $1 AND transition_id = $2 AND state = 'pending'
1206
- AND lease_owner = $3 AND lease_version = $4::bigint
1207
- AND lease_expires_at >= clock_timestamp()`,
1208
- [namespace, claim.transitionId, claim.leaseOwner, claim.leaseVersion, leaseMs]
1209
- )
1210
- );
1211
- return result.rowCount === 1;
1212
- }
1213
- async function projectClaim(db, table, namespace, claim, retentionMs) {
1214
- const result = await reportingActivityDatabaseOperation(
1215
- "Reporting notification projection settlement failed",
1216
- () => db.query(
1217
- `UPDATE ${table} SET state = 'projected', projected_at = clock_timestamp(),
1218
- retain_until = clock_timestamp() + ($5::bigint * INTERVAL '1 millisecond'),
1219
- lease_owner = NULL, lease_expires_at = NULL
1220
- WHERE namespace = $1 AND transition_id = $2 AND state = 'pending'
1221
- AND lease_owner = $3 AND lease_version = $4::bigint
1222
- AND lease_expires_at >= clock_timestamp()`,
1223
- [namespace, claim.transitionId, claim.leaseOwner, claim.leaseVersion, retentionMs]
1224
- )
1225
- );
1226
- return result.rowCount === 1;
1227
- }
1228
- async function releaseClaim(db, table, namespace, claim, retryAfterMs) {
1229
- const result = await reportingActivityDatabaseOperation(
1230
- "Reporting notification lease release failed",
1231
- () => db.query(
1232
- `UPDATE ${table} SET lease_owner = NULL, lease_expires_at = NULL,
1233
- next_attempt_at = clock_timestamp() + ($5::bigint * INTERVAL '1 millisecond')
1234
- WHERE namespace = $1 AND transition_id = $2 AND state = 'pending'
1235
- AND lease_owner = $3 AND lease_version = $4::bigint
1236
- AND lease_expires_at >= clock_timestamp()`,
1237
- [namespace, claim.transitionId, claim.leaseOwner, claim.leaseVersion, retryAfterMs]
1238
- )
1239
- );
1240
- return result.rowCount === 1;
1241
- }
1242
- async function abandonClaim(db, table, namespace, claim, retentionMs) {
1243
- const result = await reportingActivityDatabaseOperation(
1244
- "Reporting notification abandonment failed",
1245
- () => db.query(
1246
- `UPDATE ${table} SET state = 'abandoned',
1247
- abandoned_at = clock_timestamp(),
1248
- retain_until = clock_timestamp() + ($5::bigint * INTERVAL '1 millisecond'),
1249
- lease_owner = NULL, lease_expires_at = NULL
1250
- WHERE namespace = $1 AND transition_id = $2 AND state = 'pending'
1251
- AND lease_owner = $3 AND lease_version = $4::bigint
1252
- AND lease_expires_at >= clock_timestamp()`,
1253
- [namespace, claim.transitionId, claim.leaseOwner, claim.leaseVersion, retentionMs]
1254
- )
1255
- );
1256
- return result.rowCount === 1;
1257
- }
1258
- function encodeCursor(namespace, tenantId, accountId, before) {
1259
- const cursor = `ract1.${Buffer.from(JSON.stringify({ namespace, tenantId, accountId, before })).toString("base64url")}`;
1260
- if (Buffer.byteLength(cursor, "utf8") > MAX_CURSOR_BYTES) {
1261
- throw new Error("Reporting account activity cursor exceeds its internal bound");
1262
- }
1263
- return cursor;
1264
- }
1265
- function decodeCursor(cursor, namespace, tenantId, accountId) {
1266
- if (cursor === void 0) return void 0;
1267
- try {
1268
- if (Buffer.byteLength(cursor, "utf8") > MAX_CURSOR_BYTES) throw new Error();
1269
- if (!cursor.startsWith("ract1.")) throw new Error();
1270
- const value = JSON.parse(Buffer.from(cursor.slice(6), "base64url").toString("utf8"));
1271
- if (value.namespace !== namespace || value.tenantId !== tenantId || value.accountId !== accountId || typeof value.before !== "string" || !/^[1-9][0-9]*$/.test(value.before)) {
1272
- throw new Error();
1273
- }
1274
- if (BigInt(value.before) > 9223372036854775807n) throw new Error();
1275
- return value.before;
1276
- } catch {
1277
- throw new TypeError("Reporting account activity cursor is invalid for the authenticated scope");
1278
- }
1279
- }
1280
- function quoteIdentifier(value, maxBytes = 42) {
1281
- if (!/^[a-z_][a-z0-9_]*$/.test(value) || Buffer.byteLength(value, "utf8") > maxBytes) {
1282
- throw new TypeError(
1283
- `Invalid reporting activity table name ${JSON.stringify(value)}: use at most ${maxBytes} lowercase characters`
1284
- );
1285
- }
1286
- return `"${value}"`;
1287
- }
1288
- function assertIdentifier(value, name, maxBytes) {
1289
- if (typeof value !== "string" || value.length === 0 || value.includes("\0") || Buffer.byteLength(value) > maxBytes) {
1290
- throw new TypeError(`${name} must be a non-empty UTF-8 string of at most ${maxBytes} bytes without NUL`);
1291
- }
1292
- }
1293
- function positiveInteger(value, name) {
1294
- if (!Number.isSafeInteger(value) || value < 1) throw new TypeError(`${name} must be a positive safe integer`);
1295
- }
1296
- function boundedInteger(value, name, minimum, maximum) {
1297
- if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
1298
- throw new TypeError(`${name} must be an integer from ${minimum} through ${maximum}`);
1299
- }
1300
- }
1301
- function isPromiseLike(value) {
1302
- return value != null && typeof value === "object" && typeof value.then === "function";
1303
- }
1304
- function isPostgresUndefinedTable(value) {
1305
- return typeof value === "object" && value !== null && value.code === "42P01";
1306
- }
1307
- function reportProjectionError(observer, error, claim) {
1308
- try {
1309
- const result = observer?.(error, {
1310
- transitionId: claim.transitionId,
1311
- tenantId: claim.tenantId,
1312
- accountId: claim.accountId,
1313
- attemptCount: claim.attemptCount
1314
- });
1315
- if (isPromiseLike(result)) void Promise.resolve(result).catch(() => {
1316
- });
1317
- } catch {
1318
- }
1319
- }
1320
- async function reportingActivityDatabaseOperation(message, operation) {
1321
- try {
1322
- return await operation();
1323
- } catch (cause) {
1324
- throw new Error(message, { cause });
1325
- }
1326
- }
1327
- function asIso(value) {
1328
- return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
1329
- }
1330
- export {
1331
- REPORTING_NOTIFICATION_ACTIVITY_MIGRATION,
1332
- ReportingNotificationRetryableSuppressionError,
1333
- createPostgresReportingNotificationActivityRuntime,
1334
- createPostgresReportingNotificationAttemptCheckpoint,
1335
- getReportingNotificationActivityMigration,
1336
- recipientTableName
1337
- };