@tgoliveira/outpost 1.2.1 → 2.0.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.
- package/AGENTS.md +172 -18
- package/README.md +17 -12
- package/dist/adapters/drizzle/index.cjs +194 -15
- package/dist/adapters/drizzle/index.cjs.map +1 -1
- package/dist/adapters/drizzle/index.d.cts +124 -7
- package/dist/adapters/drizzle/index.d.ts +124 -7
- package/dist/adapters/drizzle/index.js +194 -15
- package/dist/adapters/drizzle/index.js.map +1 -1
- package/dist/adapters/index.cjs +148 -38
- package/dist/adapters/index.cjs.map +1 -1
- package/dist/adapters/index.d.cts +21 -13
- package/dist/adapters/index.d.ts +21 -13
- package/dist/adapters/index.js +149 -39
- package/dist/adapters/index.js.map +1 -1
- package/dist/admin/index.cjs +10 -3
- package/dist/admin/index.cjs.map +1 -1
- package/dist/admin/index.d.cts +7 -7
- package/dist/admin/index.d.ts +7 -7
- package/dist/admin/index.js +10 -3
- package/dist/admin/index.js.map +1 -1
- package/dist/{fake-BY6t7UXb.d.cts → fake-B6OIEdod.d.ts} +6 -4
- package/dist/{fake-en-oOdg0.d.ts → fake-CpQc9p0N.d.cts} +6 -4
- package/dist/http/index.cjs.map +1 -1
- package/dist/http/index.d.cts +6 -6
- package/dist/http/index.d.ts +6 -6
- package/dist/http/index.js.map +1 -1
- package/dist/{index-c6caPsUG.d.ts → index-B4F7euCt.d.cts} +53 -21
- package/dist/{index-BO0GiZmP.d.cts → index-Cn1YsmGe.d.ts} +53 -21
- package/dist/index.cjs +509 -146
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +17 -15
- package/dist/index.d.ts +17 -15
- package/dist/index.js +509 -148
- package/dist/index.js.map +1 -1
- package/dist/modules/ui/index.cjs +38 -21
- package/dist/modules/ui/index.cjs.map +1 -1
- package/dist/modules/ui/index.js +38 -21
- package/dist/modules/ui/index.js.map +1 -1
- package/dist/modules/ui/pages/admin/admin-config-page.cjs +39 -20
- package/dist/modules/ui/pages/admin/admin-config-page.cjs.map +1 -1
- package/dist/modules/ui/pages/admin/admin-config-page.d.cts +23 -1
- package/dist/modules/ui/pages/admin/admin-config-page.d.ts +23 -1
- package/dist/modules/ui/pages/admin/admin-config-page.js +38 -20
- package/dist/modules/ui/pages/admin/admin-config-page.js.map +1 -1
- package/dist/modules/ui/pages/admin/admin-panel-page.cjs +1 -1
- package/dist/modules/ui/pages/admin/admin-panel-page.js +1 -1
- package/dist/modules/ui/pages/index.cjs +38 -21
- package/dist/modules/ui/pages/index.cjs.map +1 -1
- package/dist/modules/ui/pages/index.js +38 -21
- package/dist/modules/ui/pages/index.js.map +1 -1
- package/dist/{outpost-client-BItbgqIo.d.ts → outpost-client-BX3SsOFb.d.ts} +50 -21
- package/dist/{outpost-client-BlVf4gjo.d.cts → outpost-client-DhQgZY16.d.cts} +50 -21
- package/dist/react/index.cjs +38 -21
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.js +38 -21
- package/dist/react/index.js.map +1 -1
- package/dist/repositories-DJYu4nGV.d.ts +322 -0
- package/dist/repositories-sMN6RHZJ.d.cts +322 -0
- package/dist/{services-CfTEsetF.d.ts → services-DZwZjDn_.d.cts} +9 -3
- package/dist/{services-CQINhAGo.d.cts → services-PoM2bxjP.d.ts} +9 -3
- package/dist/{template-DxI_p2Ny.d.cts → template-Dl1_ciRo.d.ts} +24 -4
- package/dist/{template-CREUq7bB.d.ts → template-Dny_7Ymi.d.cts} +24 -4
- package/dist/testing/index.cjs +200 -15
- package/dist/testing/index.cjs.map +1 -1
- package/dist/testing/index.d.cts +26 -7
- package/dist/testing/index.d.ts +26 -7
- package/dist/testing/index.js +200 -15
- package/dist/testing/index.js.map +1 -1
- package/dist/{webhook-kp6CiXk-.d.cts → webhook-B158Vi6p.d.cts} +20 -4
- package/dist/{webhook-kp6CiXk-.d.ts → webhook-B158Vi6p.d.ts} +20 -4
- package/dist/workers/index.cjs +471 -85
- package/dist/workers/index.cjs.map +1 -1
- package/dist/workers/index.d.cts +5 -5
- package/dist/workers/index.d.ts +5 -5
- package/dist/workers/index.js +471 -85
- package/dist/workers/index.js.map +1 -1
- package/package.json +6 -3
- package/dist/repositories-CHIOFGn3.d.cts +0 -182
- package/dist/repositories-WyhvxzyY.d.ts +0 -182
package/dist/workers/index.cjs
CHANGED
|
@@ -1,5 +1,60 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
// src/domain/provider-failure.ts
|
|
4
|
+
function classifyProviderFailure(err) {
|
|
5
|
+
if (typeof err !== "object" || err === null) return void 0;
|
|
6
|
+
const errorClass = err.errorClass;
|
|
7
|
+
const code = err.code;
|
|
8
|
+
if (errorClass === "permanent" && code === "provider_permanent") return "permanent";
|
|
9
|
+
if (errorClass === "transient" && code === "provider_transient") return "transient";
|
|
10
|
+
return void 0;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// src/domain/webhook.ts
|
|
14
|
+
function webhookToState(type) {
|
|
15
|
+
switch (type) {
|
|
16
|
+
case "delivered":
|
|
17
|
+
return "delivered";
|
|
18
|
+
case "bounced":
|
|
19
|
+
return "bounced";
|
|
20
|
+
case "complained":
|
|
21
|
+
return "complained";
|
|
22
|
+
case "failed":
|
|
23
|
+
return "failed";
|
|
24
|
+
case "opened":
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// src/domain/lifecycle.ts
|
|
30
|
+
var TERMINAL_STATES = [
|
|
31
|
+
"delivered",
|
|
32
|
+
"bounced",
|
|
33
|
+
"complained",
|
|
34
|
+
"failed",
|
|
35
|
+
"suppressed"
|
|
36
|
+
];
|
|
37
|
+
new Set(TERMINAL_STATES);
|
|
38
|
+
var ALLOWED_TRANSITIONS = {
|
|
39
|
+
// Dead-letter is `sending` → `failed`, or a `failed` webhook from `sent`.
|
|
40
|
+
queued: ["sending", "suppressed"],
|
|
41
|
+
// `sending` can fall back to `queued` on a transient error (retry).
|
|
42
|
+
sending: ["sent", "queued", "failed", "suppressed"],
|
|
43
|
+
sent: ["delivered", "bounced", "complained", "failed"],
|
|
44
|
+
delivered: [],
|
|
45
|
+
bounced: [],
|
|
46
|
+
complained: [],
|
|
47
|
+
failed: ["queued"],
|
|
48
|
+
// DLQ replay re-enqueues a failed message
|
|
49
|
+
suppressed: []
|
|
50
|
+
};
|
|
51
|
+
function canTransition(from, to) {
|
|
52
|
+
return ALLOWED_TRANSITIONS[from].includes(to);
|
|
53
|
+
}
|
|
54
|
+
function shouldSuppressOn(state) {
|
|
55
|
+
return state === "bounced" || state === "complained";
|
|
56
|
+
}
|
|
57
|
+
|
|
3
58
|
// src/domain/errors.ts
|
|
4
59
|
var OutpostError = class extends Error {
|
|
5
60
|
code;
|
|
@@ -16,21 +71,199 @@ var ValidationError = class extends OutpostError {
|
|
|
16
71
|
this.details = details;
|
|
17
72
|
}
|
|
18
73
|
};
|
|
19
|
-
var
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
constructor(errorClass, message, options) {
|
|
23
|
-
super(`provider_${errorClass}`, message, options);
|
|
24
|
-
this.errorClass = errorClass;
|
|
25
|
-
this.providerCode = options?.providerCode;
|
|
74
|
+
var WebhookVerificationError = class extends OutpostError {
|
|
75
|
+
constructor(message = "Webhook signature verification failed") {
|
|
76
|
+
super("webhook_unverified", message);
|
|
26
77
|
}
|
|
27
|
-
|
|
28
|
-
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
// src/application/ingest-webhook.ts
|
|
81
|
+
var WEBHOOK_FRESHNESS_WINDOW_MS = 3e5;
|
|
82
|
+
var IngestWebhook = class {
|
|
83
|
+
constructor(deps) {
|
|
84
|
+
this.deps = deps;
|
|
29
85
|
}
|
|
30
|
-
|
|
31
|
-
|
|
86
|
+
async execute(providerName, raw) {
|
|
87
|
+
const { deps } = this;
|
|
88
|
+
const provider = deps.providers.get(providerName);
|
|
89
|
+
if (!provider) {
|
|
90
|
+
throw new WebhookVerificationError(`Unknown provider "${providerName}"`);
|
|
91
|
+
}
|
|
92
|
+
return deps.telemetry.span("outpost.webhook.ingest", { provider: providerName }, async () => {
|
|
93
|
+
const event = await provider.verifyWebhook(raw);
|
|
94
|
+
if (!event) {
|
|
95
|
+
return { accepted: true, messageId: null, note: "ignored" };
|
|
96
|
+
}
|
|
97
|
+
this.assertFresh(event);
|
|
98
|
+
const duplicate = await deps.webhookEvents.findByIdentity?.(identityQuery(event));
|
|
99
|
+
if (duplicate) return this.duplicateResult(event);
|
|
100
|
+
const message = await deps.outbox.findByProviderMessageId(event.providerMessageId);
|
|
101
|
+
if (!message) {
|
|
102
|
+
const settled = event.providerEventId ? null : await deps.webhookEvents.findByIdentity?.({
|
|
103
|
+
match: "settledWithoutEventId",
|
|
104
|
+
provider: event.provider,
|
|
105
|
+
providerMessageId: event.providerMessageId,
|
|
106
|
+
type: event.type
|
|
107
|
+
});
|
|
108
|
+
if (settled) {
|
|
109
|
+
return {
|
|
110
|
+
accepted: true,
|
|
111
|
+
eventType: event.type,
|
|
112
|
+
messageId: null,
|
|
113
|
+
note: "duplicate provider event"
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
await this.store(event, "pending", providerName);
|
|
117
|
+
return {
|
|
118
|
+
accepted: true,
|
|
119
|
+
eventType: event.type,
|
|
120
|
+
messageId: null,
|
|
121
|
+
note: "no matching message for providerMessageId"
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
const effect = await this.applyEffects(event, message);
|
|
125
|
+
await this.store(event, effect.disposition, providerName);
|
|
126
|
+
return effect.result;
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Apply pending rows for a provider message id, oldest `receivedAt` first.
|
|
131
|
+
* No freshness check. Skips the call when the repository has no list method.
|
|
132
|
+
* Does not store another row or increment `outpost.webhook.received`.
|
|
133
|
+
*/
|
|
134
|
+
async applyPending(providerMessageId) {
|
|
135
|
+
const list = this.deps.webhookEvents.listPendingByProviderMessageId;
|
|
136
|
+
if (!list) return;
|
|
137
|
+
const rows = await list.call(this.deps.webhookEvents, providerMessageId);
|
|
138
|
+
const ordered = [...rows].sort((a, b) => a.receivedAt.getTime() - b.receivedAt.getTime());
|
|
139
|
+
for (const row of ordered) {
|
|
140
|
+
if (row.disposition !== "pending") continue;
|
|
141
|
+
const message = await this.deps.outbox.findByProviderMessageId(providerMessageId);
|
|
142
|
+
if (!message) continue;
|
|
143
|
+
const effect = await this.applyEffects(row.event, message);
|
|
144
|
+
await this.deps.webhookEvents.setDisposition?.(row.id, effect.disposition);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
/** `verifiedAt` wins. Otherwise `occurredAt`. Neither present: do not reject. */
|
|
148
|
+
assertFresh(event) {
|
|
149
|
+
const timestamp = event.verifiedAt !== void 0 ? event.verifiedAt : event.occurredAt;
|
|
150
|
+
if (timestamp === void 0) return;
|
|
151
|
+
const skew = Math.abs(this.deps.clock.now().getTime() - timestamp.getTime());
|
|
152
|
+
if (skew > WEBHOOK_FRESHNESS_WINDOW_MS) {
|
|
153
|
+
throw new WebhookVerificationError("Webhook timestamp is stale");
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
async duplicateResult(event) {
|
|
157
|
+
const message = await this.deps.outbox.findByProviderMessageId(event.providerMessageId);
|
|
158
|
+
return {
|
|
159
|
+
accepted: true,
|
|
160
|
+
eventType: event.type,
|
|
161
|
+
messageId: message?.id ?? null,
|
|
162
|
+
note: "duplicate provider event"
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* State change, suppression, and one audit. Disposition is the caller's
|
|
167
|
+
* to persist: `applied` after a committed effect, `rejected` when the
|
|
168
|
+
* transition is not allowed.
|
|
169
|
+
*/
|
|
170
|
+
async applyEffects(event, message) {
|
|
171
|
+
const target = webhookToState(event.type);
|
|
172
|
+
if (target === null) {
|
|
173
|
+
await this.appendAudit(event, message.id);
|
|
174
|
+
return {
|
|
175
|
+
disposition: "applied",
|
|
176
|
+
result: { accepted: true, eventType: event.type, messageId: message.id }
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
if (!canTransition(message.state, target)) {
|
|
180
|
+
return {
|
|
181
|
+
disposition: "rejected",
|
|
182
|
+
result: {
|
|
183
|
+
accepted: true,
|
|
184
|
+
eventType: event.type,
|
|
185
|
+
messageId: message.id,
|
|
186
|
+
note: "transition rejected"
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
await this.deps.outbox.updateState(message.id, { state: target });
|
|
191
|
+
if (shouldSuppressOn(target) && this.isSuppressable(event)) {
|
|
192
|
+
const reason = target === "bounced" ? "hard_bounce" : "complaint";
|
|
193
|
+
const already = await this.deps.suppressions.get(message.recipientHmac);
|
|
194
|
+
await this.deps.suppressions.add({
|
|
195
|
+
recipientHmac: message.recipientHmac,
|
|
196
|
+
reason,
|
|
197
|
+
createdBy: `provider:${event.provider}`,
|
|
198
|
+
note: `webhook ${event.type}`
|
|
199
|
+
});
|
|
200
|
+
if (!already) {
|
|
201
|
+
this.deps.telemetry.counter("outpost.suppression.added", 1, { reason });
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
await this.appendAudit(event, message.id);
|
|
205
|
+
return {
|
|
206
|
+
disposition: "applied",
|
|
207
|
+
result: { accepted: true, eventType: event.type, messageId: message.id }
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
async store(event, disposition, providerName) {
|
|
211
|
+
await this.deps.webhookEvents.record(event, { disposition });
|
|
212
|
+
this.deps.telemetry.counter("outpost.webhook.received", 1, {
|
|
213
|
+
provider: providerName,
|
|
214
|
+
type: event.type
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
async appendAudit(event, messageId) {
|
|
218
|
+
const detail = {
|
|
219
|
+
type: event.type,
|
|
220
|
+
occurredAt: event.occurredAt?.toISOString() ?? null
|
|
221
|
+
};
|
|
222
|
+
if (event.providerEventId) detail.providerEventId = event.providerEventId;
|
|
223
|
+
await this.deps.audit.append({
|
|
224
|
+
messageId,
|
|
225
|
+
eventType: this.auditType(event.type),
|
|
226
|
+
actor: `provider:${event.provider}`,
|
|
227
|
+
detail
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
/** A soft bounce must not suppress; only hard bounces and complaints do. */
|
|
231
|
+
isSuppressable(event) {
|
|
232
|
+
if (event.type === "complained") return true;
|
|
233
|
+
if (event.type === "bounced") return event.isHardBounce !== false;
|
|
234
|
+
return false;
|
|
235
|
+
}
|
|
236
|
+
auditType(type) {
|
|
237
|
+
switch (type) {
|
|
238
|
+
case "delivered":
|
|
239
|
+
return "webhook_delivered";
|
|
240
|
+
case "bounced":
|
|
241
|
+
return "webhook_bounced";
|
|
242
|
+
case "complained":
|
|
243
|
+
return "webhook_complained";
|
|
244
|
+
case "opened":
|
|
245
|
+
return "webhook_opened";
|
|
246
|
+
case "failed":
|
|
247
|
+
return "dispatch_failed";
|
|
248
|
+
}
|
|
32
249
|
}
|
|
33
250
|
};
|
|
251
|
+
function identityQuery(event) {
|
|
252
|
+
if (event.providerEventId) {
|
|
253
|
+
return {
|
|
254
|
+
match: "providerEvent",
|
|
255
|
+
provider: event.provider,
|
|
256
|
+
providerEventId: event.providerEventId
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
return {
|
|
260
|
+
match: "providerMessage",
|
|
261
|
+
provider: event.provider,
|
|
262
|
+
providerMessageId: event.providerMessageId,
|
|
263
|
+
type: event.type,
|
|
264
|
+
occurredAt: event.occurredAt ?? null
|
|
265
|
+
};
|
|
266
|
+
}
|
|
34
267
|
function isExhausted(attempts, config) {
|
|
35
268
|
return attempts >= config.maxAttempts;
|
|
36
269
|
}
|
|
@@ -74,11 +307,7 @@ async function validateRecipient(address, config, deps) {
|
|
|
74
307
|
const cached = deps.mxCache?.get(domain, deps.nowMs);
|
|
75
308
|
let hosts = cached;
|
|
76
309
|
if (hosts === void 0) {
|
|
77
|
-
|
|
78
|
-
hosts = await deps.mxResolver.resolveMx(domain);
|
|
79
|
-
} catch {
|
|
80
|
-
hosts = [];
|
|
81
|
-
}
|
|
310
|
+
hosts = await deps.mxResolver.resolveMx(domain);
|
|
82
311
|
deps.mxCache?.set(domain, hosts, deps.nowMs);
|
|
83
312
|
}
|
|
84
313
|
if (hosts.length === 0) {
|
|
@@ -133,13 +362,26 @@ function assertBodyWithinLimits(body, limits = DEFAULT_SANITIZE_LIMITS) {
|
|
|
133
362
|
}
|
|
134
363
|
|
|
135
364
|
// src/application/dispatch-message.ts
|
|
365
|
+
function failureReason(err) {
|
|
366
|
+
if (typeof err === "object" && err !== null) {
|
|
367
|
+
const message = err.message;
|
|
368
|
+
if (typeof message === "string") return message;
|
|
369
|
+
}
|
|
370
|
+
return String(err);
|
|
371
|
+
}
|
|
136
372
|
var DispatchMessage = class {
|
|
137
373
|
constructor(deps) {
|
|
138
374
|
this.deps = deps;
|
|
139
375
|
this.mxCache = new MxCache(deps.config.domainValidation.mxCacheTtlMs ?? 36e5);
|
|
376
|
+
this.webhooks = new IngestWebhook(deps);
|
|
140
377
|
}
|
|
141
378
|
mxCache;
|
|
379
|
+
webhooks;
|
|
142
380
|
async execute(message) {
|
|
381
|
+
const claim = { updatedAt: new Date(message.updatedAt.getTime()) };
|
|
382
|
+
if (!this.deps.outbox.updateStateWhileSending) {
|
|
383
|
+
throw new Error("OutboxRepository.updateStateWhileSending is required to dispatch");
|
|
384
|
+
}
|
|
143
385
|
const { deps } = this;
|
|
144
386
|
return deps.telemetry.span(
|
|
145
387
|
"outpost.dispatch",
|
|
@@ -149,13 +391,37 @@ var DispatchMessage = class {
|
|
|
149
391
|
if (!fresh || fresh.state !== "sending") {
|
|
150
392
|
return { kind: "skipped", reason: "no longer in sending state" };
|
|
151
393
|
}
|
|
394
|
+
try {
|
|
395
|
+
await deps.audit.append({
|
|
396
|
+
messageId: fresh.id,
|
|
397
|
+
eventType: "dispatch_started",
|
|
398
|
+
actor: "system:dispatch",
|
|
399
|
+
detail: { provider: fresh.provider }
|
|
400
|
+
});
|
|
401
|
+
} catch (err) {
|
|
402
|
+
this.logWrite("dispatch_started audit failed; dispatch continues", fresh.id, err);
|
|
403
|
+
}
|
|
404
|
+
let listed;
|
|
405
|
+
try {
|
|
406
|
+
listed = await deps.suppressions.isSuppressed(fresh.recipientHmac);
|
|
407
|
+
} catch (err) {
|
|
408
|
+
return this.handleError(fresh, claim, err);
|
|
409
|
+
}
|
|
410
|
+
if (listed) return this.suppressListed(fresh, claim);
|
|
152
411
|
const provider = deps.providers.get(fresh.provider);
|
|
153
412
|
if (!provider) {
|
|
154
|
-
return this.fail(fresh, `No provider registered for "${fresh.provider}"`);
|
|
413
|
+
return this.fail(fresh, claim, `No provider registered for "${fresh.provider}"`);
|
|
155
414
|
}
|
|
415
|
+
let receipt;
|
|
156
416
|
try {
|
|
157
|
-
const to = await deps.openEncryptor.open(fresh.recipientSealed
|
|
158
|
-
|
|
417
|
+
const to = await deps.openEncryptor.open(fresh.recipientSealed, {
|
|
418
|
+
messageId: fresh.id,
|
|
419
|
+
column: "recipient"
|
|
420
|
+
});
|
|
421
|
+
const bodyJson = await deps.openEncryptor.open(fresh.bodySealed, {
|
|
422
|
+
messageId: fresh.id,
|
|
423
|
+
column: "body"
|
|
424
|
+
});
|
|
159
425
|
const body = JSON.parse(bodyJson);
|
|
160
426
|
const cleanTo = sanitizeRecipient(to, deps.config.sanitize);
|
|
161
427
|
const cleanSubject = sanitizeSubject(fresh.subject, deps.config.sanitize);
|
|
@@ -167,7 +433,7 @@ var DispatchMessage = class {
|
|
|
167
433
|
});
|
|
168
434
|
const limited = await this.checkRateLimits(fresh.provider, cleanTo);
|
|
169
435
|
if (limited) {
|
|
170
|
-
return this.requeueRateLimited(fresh);
|
|
436
|
+
return this.requeueRateLimited(fresh, claim);
|
|
171
437
|
}
|
|
172
438
|
const dispatchable = {
|
|
173
439
|
id: fresh.id,
|
|
@@ -177,91 +443,175 @@ var DispatchMessage = class {
|
|
|
177
443
|
headers: this.buildHeaders(),
|
|
178
444
|
metadata: fresh.metadata
|
|
179
445
|
};
|
|
180
|
-
|
|
181
|
-
|
|
446
|
+
receipt = await provider.send(dispatchable);
|
|
447
|
+
} catch (err) {
|
|
448
|
+
return this.handleError(fresh, claim, err);
|
|
449
|
+
}
|
|
450
|
+
const wrote = await this.commitWhileSending(
|
|
451
|
+
fresh.id,
|
|
452
|
+
{
|
|
182
453
|
state: "sent",
|
|
183
454
|
providerMessageId: receipt.providerMessageId,
|
|
184
455
|
lastError: null
|
|
185
|
-
}
|
|
456
|
+
},
|
|
457
|
+
claim,
|
|
458
|
+
true
|
|
459
|
+
);
|
|
460
|
+
if (!wrote) return { kind: "skipped", reason: "claim lost" };
|
|
461
|
+
try {
|
|
186
462
|
await deps.audit.append({
|
|
187
463
|
messageId: fresh.id,
|
|
188
464
|
eventType: "dispatch_accepted",
|
|
189
465
|
actor: `provider:${fresh.provider}`,
|
|
190
466
|
detail: { providerMessageId: receipt.providerMessageId }
|
|
191
467
|
});
|
|
192
|
-
deps.telemetry.counter("outpost.dispatch.sent", 1, { provider: fresh.provider });
|
|
193
|
-
return { kind: "sent", providerMessageId: receipt.providerMessageId };
|
|
194
468
|
} catch (err) {
|
|
195
|
-
|
|
469
|
+
this.logWrite("dispatch audit failed after sent; message stays sent", fresh.id, err);
|
|
470
|
+
}
|
|
471
|
+
try {
|
|
472
|
+
await this.webhooks.applyPending(receipt.providerMessageId);
|
|
473
|
+
} catch (err) {
|
|
474
|
+
this.logWrite("pending webhook apply failed after sent; message stays sent", fresh.id, err);
|
|
196
475
|
}
|
|
476
|
+
deps.telemetry.counter("outpost.dispatch.sent", 1, { provider: fresh.provider });
|
|
477
|
+
return { kind: "sent", providerMessageId: receipt.providerMessageId };
|
|
197
478
|
}
|
|
198
479
|
);
|
|
199
480
|
}
|
|
200
|
-
/**
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
481
|
+
/**
|
|
482
|
+
* Recipient was listed after enqueue. `sending` → `suppressed` on the
|
|
483
|
+
* stored HMAC. Do not decrypt, call the provider, or add a suppression row.
|
|
484
|
+
* A lost claim does not audit. An audit failure leaves the row suppressed.
|
|
485
|
+
*/
|
|
486
|
+
async suppressListed(message, claim) {
|
|
487
|
+
const wrote = await this.commitWhileSending(message.id, { state: "suppressed" }, claim);
|
|
488
|
+
if (!wrote) return { kind: "skipped", reason: "claim lost" };
|
|
489
|
+
try {
|
|
490
|
+
await this.deps.audit.append({
|
|
491
|
+
messageId: message.id,
|
|
492
|
+
eventType: "suppressed",
|
|
493
|
+
actor: "system:dispatch",
|
|
494
|
+
detail: { reason: "recipient_on_suppression_list" }
|
|
495
|
+
});
|
|
496
|
+
} catch (err) {
|
|
497
|
+
this.logWrite("dispatch audit failed after suppressed; message stays suppressed", message.id, err);
|
|
498
|
+
}
|
|
499
|
+
return { kind: "skipped", reason: "recipient suppressed" };
|
|
500
|
+
}
|
|
501
|
+
/** Classify a provider or pipeline error and either retry or dead-letter. */
|
|
502
|
+
async handleError(message, claim, err) {
|
|
503
|
+
const permanent = classifyProviderFailure(err) === "permanent";
|
|
504
|
+
const reason = failureReason(err);
|
|
204
505
|
if (permanent) {
|
|
205
|
-
return this.fail(message, reason);
|
|
506
|
+
return this.fail(message, claim, reason);
|
|
206
507
|
}
|
|
207
508
|
const attempts = message.attempts + 1;
|
|
208
509
|
if (isExhausted(attempts, this.deps.config.retry)) {
|
|
209
|
-
return this.fail(message, `Retries exhausted (${attempts}): ${reason}`, attempts);
|
|
510
|
+
return this.fail(message, claim, `Retries exhausted (${attempts}): ${reason}`, attempts);
|
|
210
511
|
}
|
|
211
512
|
const delay = backoffMs(attempts, this.deps.config.retry, this.deps.random());
|
|
212
513
|
const nextAttemptAt = new Date(this.deps.clock.now().getTime() + delay);
|
|
213
|
-
await this.
|
|
214
|
-
|
|
215
|
-
attempts,
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
514
|
+
const wrote = await this.commitWhileSending(
|
|
515
|
+
message.id,
|
|
516
|
+
{ state: "queued", attempts, nextAttemptAt, lastError: reason, providerMessageId: null },
|
|
517
|
+
claim
|
|
518
|
+
);
|
|
519
|
+
if (!wrote) return { kind: "skipped", reason: "claim lost" };
|
|
520
|
+
try {
|
|
521
|
+
await this.deps.audit.append({
|
|
522
|
+
messageId: message.id,
|
|
523
|
+
eventType: "retry_scheduled",
|
|
524
|
+
actor: `provider:${message.provider}`,
|
|
525
|
+
detail: { attempts, nextAttemptAt: nextAttemptAt.toISOString(), reason }
|
|
526
|
+
});
|
|
527
|
+
} catch (auditErr) {
|
|
528
|
+
this.logWrite("retry audit failed after requeue", message.id, auditErr);
|
|
529
|
+
}
|
|
225
530
|
this.deps.telemetry.counter("outpost.dispatch.retry", 1, { provider: message.provider });
|
|
226
531
|
return { kind: "retry", nextAttemptAt };
|
|
227
532
|
}
|
|
228
533
|
/** Move to `failed` (terminal) and record in the Dead Letter Queue. */
|
|
229
|
-
async fail(message, reason, attempts) {
|
|
230
|
-
await this.
|
|
231
|
-
|
|
232
|
-
attempts: attempts ?? message.attempts,
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
534
|
+
async fail(message, claim, reason, attempts) {
|
|
535
|
+
const wrote = await this.commitWhileSending(
|
|
536
|
+
message.id,
|
|
537
|
+
{ state: "failed", attempts: attempts ?? message.attempts, lastError: reason },
|
|
538
|
+
claim
|
|
539
|
+
);
|
|
540
|
+
if (!wrote) return { kind: "skipped", reason: "claim lost" };
|
|
541
|
+
try {
|
|
542
|
+
await this.deps.audit.append({
|
|
543
|
+
messageId: message.id,
|
|
544
|
+
eventType: "dead_lettered",
|
|
545
|
+
actor: `provider:${message.provider}`,
|
|
546
|
+
detail: { reason }
|
|
547
|
+
});
|
|
548
|
+
} catch (auditErr) {
|
|
549
|
+
this.logWrite("dead-letter audit failed after failed", message.id, auditErr);
|
|
550
|
+
}
|
|
241
551
|
this.deps.telemetry.counter("outpost.dispatch.failed", 1, { provider: message.provider });
|
|
242
552
|
return { kind: "failed", reason };
|
|
243
553
|
}
|
|
244
554
|
/** Re-queue without counting a failed attempt; short, jittered backoff. */
|
|
245
|
-
async requeueRateLimited(message) {
|
|
555
|
+
async requeueRateLimited(message, claim) {
|
|
246
556
|
const delay = 1e3 + Math.floor(this.deps.random() * 4e3);
|
|
247
557
|
const nextAttemptAt = new Date(this.deps.clock.now().getTime() + delay);
|
|
248
|
-
await this.
|
|
249
|
-
|
|
250
|
-
nextAttemptAt
|
|
251
|
-
|
|
558
|
+
const wrote = await this.commitWhileSending(
|
|
559
|
+
message.id,
|
|
560
|
+
{ state: "queued", nextAttemptAt, providerMessageId: null },
|
|
561
|
+
claim
|
|
562
|
+
);
|
|
563
|
+
if (!wrote) return { kind: "skipped", reason: "claim lost" };
|
|
252
564
|
this.deps.telemetry.counter("outpost.dispatch.rate_limited", 1, { provider: message.provider });
|
|
253
565
|
return { kind: "rate_limited", nextAttemptAt };
|
|
254
566
|
}
|
|
567
|
+
/**
|
|
568
|
+
* Fence write. `false` means the claim no longer owns the row, or the driver
|
|
569
|
+
* threw. Neither path is a provider retry. When the provider may already
|
|
570
|
+
* have accepted, the log says so and the caller leaves the row alone.
|
|
571
|
+
*/
|
|
572
|
+
async commitWhileSending(id, patch, claim, providerMayHaveAccepted = false) {
|
|
573
|
+
const write = this.deps.outbox.updateStateWhileSending;
|
|
574
|
+
if (!write) {
|
|
575
|
+
throw new Error("OutboxRepository.updateStateWhileSending is required to dispatch");
|
|
576
|
+
}
|
|
577
|
+
try {
|
|
578
|
+
const wrote = await write.call(this.deps.outbox, id, patch, claim);
|
|
579
|
+
if (!wrote && providerMayHaveAccepted) {
|
|
580
|
+
this.deps.logger.log(
|
|
581
|
+
"error",
|
|
582
|
+
"provider may already have accepted; claim lost and the row was left unchanged",
|
|
583
|
+
{ messageId: id }
|
|
584
|
+
);
|
|
585
|
+
}
|
|
586
|
+
return wrote;
|
|
587
|
+
} catch (err) {
|
|
588
|
+
this.logWrite(
|
|
589
|
+
providerMayHaveAccepted ? "provider may already have accepted; state write failed and the row was left unchanged" : "dispatch state write failed and the row was left unchanged",
|
|
590
|
+
id,
|
|
591
|
+
err
|
|
592
|
+
);
|
|
593
|
+
return false;
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
logWrite(message, messageId, err) {
|
|
597
|
+
this.deps.logger.log("error", message, {
|
|
598
|
+
messageId,
|
|
599
|
+
error: err instanceof Error ? err.message : String(err)
|
|
600
|
+
});
|
|
601
|
+
}
|
|
255
602
|
async checkRateLimits(provider, to) {
|
|
256
|
-
const
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
603
|
+
const scopes = [
|
|
604
|
+
{ kind: "global" },
|
|
605
|
+
{ kind: "provider", key: provider },
|
|
606
|
+
{ kind: "recipientDomain", key: extractDomain(to) }
|
|
260
607
|
];
|
|
261
|
-
|
|
608
|
+
if (this.deps.rateLimiter.acquireAll) {
|
|
609
|
+
return !await this.deps.rateLimiter.acquireAll(scopes);
|
|
610
|
+
}
|
|
611
|
+
const results = await Promise.all(scopes.map((scope) => this.deps.rateLimiter.acquire(scope)));
|
|
262
612
|
return results.some((ok) => ok === false);
|
|
263
613
|
}
|
|
264
|
-
/**
|
|
614
|
+
/** No headers are added. List-Unsubscribe is not set. */
|
|
265
615
|
buildHeaders() {
|
|
266
616
|
return {};
|
|
267
617
|
}
|
|
@@ -340,6 +690,17 @@ async function runWithConcurrency(items, limit, fn) {
|
|
|
340
690
|
}
|
|
341
691
|
|
|
342
692
|
// src/domain/retention.ts
|
|
693
|
+
function normalizeBatchPauseMs(ms) {
|
|
694
|
+
if (!Number.isFinite(ms) || ms <= 0) return 0;
|
|
695
|
+
return ms;
|
|
696
|
+
}
|
|
697
|
+
function waitForBatchPause(ms) {
|
|
698
|
+
const pause = normalizeBatchPauseMs(ms);
|
|
699
|
+
if (pause === 0) return Promise.resolve();
|
|
700
|
+
return new Promise((resolve) => {
|
|
701
|
+
setTimeout(resolve, pause);
|
|
702
|
+
});
|
|
703
|
+
}
|
|
343
704
|
function purgeCutoff(policy, now) {
|
|
344
705
|
const ttlCutoff = now.getTime() - policy.operationalTtlDays * 24 * 60 * 60 * 1e3;
|
|
345
706
|
const windowCutoff = now.getTime() - policy.webhookWindowHours * 60 * 60 * 1e3;
|
|
@@ -357,12 +718,20 @@ var PurgeRetention = class {
|
|
|
357
718
|
const now = deps.clock.now();
|
|
358
719
|
const policy = deps.config.retention;
|
|
359
720
|
const cutoff = purgeCutoff(policy, now);
|
|
721
|
+
const pauseMs = normalizeBatchPauseMs(policy.batchPauseMs);
|
|
722
|
+
const redactEligible = deps.outbox.redactBatchIfEligible;
|
|
723
|
+
const deleteEligible = deps.outbox.deleteBatchIfEligible;
|
|
724
|
+
if (typeof redactEligible !== "function" || typeof deleteEligible !== "function") {
|
|
725
|
+
throw new Error(
|
|
726
|
+
"OutboxRepository must implement redactBatchIfEligible and deleteBatchIfEligible. Retention throws before it writes and does not call redactBatch or deleteBatch."
|
|
727
|
+
);
|
|
728
|
+
}
|
|
360
729
|
let operationalProcessed = 0;
|
|
361
730
|
for (; ; ) {
|
|
362
731
|
const batch = await deps.outbox.claimTerminalForPurge(cutoff, policy.batchSize);
|
|
363
732
|
if (batch.length === 0) break;
|
|
364
733
|
const ids = batch.map((m) => m.id);
|
|
365
|
-
const count = policy.redactOnPurge ? await deps.outbox
|
|
734
|
+
const count = policy.redactOnPurge ? await redactEligible.call(deps.outbox, ids, cutoff) : await deleteEligible.call(deps.outbox, ids, cutoff);
|
|
366
735
|
operationalProcessed += count;
|
|
367
736
|
await deps.audit.append({
|
|
368
737
|
messageId: null,
|
|
@@ -371,14 +740,18 @@ var PurgeRetention = class {
|
|
|
371
740
|
detail: { count, cutoff: cutoff.toISOString() }
|
|
372
741
|
});
|
|
373
742
|
if (batch.length < policy.batchSize) break;
|
|
743
|
+
await waitForBatchPause(pauseMs);
|
|
374
744
|
}
|
|
745
|
+
const deleteWebhooks = deps.webhookEvents.deleteOlderThan;
|
|
746
|
+
const webhooksDeleted = typeof deleteWebhooks === "function" ? await deleteWebhooks.call(deps.webhookEvents, cutoff) : 0;
|
|
375
747
|
const auditCutoff = new Date(now.getTime() - policy.auditTtlDays * 24 * 60 * 60 * 1e3);
|
|
376
|
-
const auditDeleted = await deps.audit.purgeOlderThan(auditCutoff, policy.batchSize);
|
|
748
|
+
const auditDeleted = await deps.audit.purgeOlderThan(auditCutoff, policy.batchSize, pauseMs);
|
|
377
749
|
deps.telemetry.gauge("outpost.retention.operational_processed", operationalProcessed);
|
|
378
750
|
deps.telemetry.gauge("outpost.retention.audit_deleted", auditDeleted);
|
|
379
751
|
deps.logger.log("info", "retention cycle complete", {
|
|
380
752
|
operationalProcessed,
|
|
381
753
|
auditDeleted,
|
|
754
|
+
webhooksDeleted,
|
|
382
755
|
redacted: policy.redactOnPurge
|
|
383
756
|
});
|
|
384
757
|
return { operationalProcessed, auditDeleted, redacted: policy.redactOnPurge };
|
|
@@ -396,31 +769,44 @@ var RetentionWorker = class {
|
|
|
396
769
|
purge;
|
|
397
770
|
running = false;
|
|
398
771
|
timer = null;
|
|
772
|
+
inFlight = false;
|
|
399
773
|
async tick() {
|
|
400
774
|
return this.purge.execute();
|
|
401
775
|
}
|
|
402
776
|
start() {
|
|
403
777
|
if (this.running) return;
|
|
404
778
|
this.running = true;
|
|
405
|
-
|
|
406
|
-
const loop = async () => {
|
|
407
|
-
if (!this.running) return;
|
|
408
|
-
try {
|
|
409
|
-
await this.tick();
|
|
410
|
-
} catch (err) {
|
|
411
|
-
this.deps.logger.log("error", "retention worker tick failed", {
|
|
412
|
-
error: err instanceof Error ? err.message : String(err)
|
|
413
|
-
});
|
|
414
|
-
} finally {
|
|
415
|
-
if (this.running) this.timer = setTimeout(loop, interval);
|
|
416
|
-
}
|
|
417
|
-
};
|
|
418
|
-
void loop();
|
|
779
|
+
void this.runLoopTick();
|
|
419
780
|
}
|
|
420
781
|
stop() {
|
|
421
782
|
this.running = false;
|
|
422
|
-
if (this.timer)
|
|
423
|
-
|
|
783
|
+
if (this.timer !== null) {
|
|
784
|
+
clearTimeout(this.timer);
|
|
785
|
+
this.timer = null;
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
intervalMs() {
|
|
789
|
+
return this.options.intervalMs ?? 60 * 60 * 1e3;
|
|
790
|
+
}
|
|
791
|
+
async runLoopTick() {
|
|
792
|
+
if (this.inFlight) return;
|
|
793
|
+
if (!this.running) return;
|
|
794
|
+
this.inFlight = true;
|
|
795
|
+
try {
|
|
796
|
+
await this.tick();
|
|
797
|
+
} catch (err) {
|
|
798
|
+
this.deps.logger.log("error", "retention worker tick failed", {
|
|
799
|
+
error: err instanceof Error ? err.message : String(err)
|
|
800
|
+
});
|
|
801
|
+
} finally {
|
|
802
|
+
this.inFlight = false;
|
|
803
|
+
if (this.running) {
|
|
804
|
+
this.timer = setTimeout(() => {
|
|
805
|
+
this.timer = null;
|
|
806
|
+
void this.runLoopTick();
|
|
807
|
+
}, this.intervalMs());
|
|
808
|
+
}
|
|
809
|
+
}
|
|
424
810
|
}
|
|
425
811
|
};
|
|
426
812
|
|