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