@tgoliveira/outpost 1.1.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 +268 -0
- package/LICENSE +21 -0
- package/README.md +117 -0
- package/dist/adapters/drizzle/index.cjs +405 -0
- package/dist/adapters/drizzle/index.cjs.map +1 -0
- package/dist/adapters/drizzle/index.d.cts +1765 -0
- package/dist/adapters/drizzle/index.d.ts +1765 -0
- package/dist/adapters/drizzle/index.js +387 -0
- package/dist/adapters/drizzle/index.js.map +1 -0
- package/dist/adapters/index.cjs +584 -0
- package/dist/adapters/index.cjs.map +1 -0
- package/dist/adapters/index.d.cts +232 -0
- package/dist/adapters/index.d.ts +232 -0
- package/dist/adapters/index.js +565 -0
- package/dist/adapters/index.js.map +1 -0
- package/dist/fake-BY6t7UXb.d.cts +30 -0
- package/dist/fake-en-oOdg0.d.ts +30 -0
- package/dist/http/index.cjs +224 -0
- package/dist/http/index.cjs.map +1 -0
- package/dist/http/index.d.cts +49 -0
- package/dist/http/index.d.ts +49 -0
- package/dist/http/index.js +221 -0
- package/dist/http/index.js.map +1 -0
- package/dist/index-CVUvaJms.d.ts +179 -0
- package/dist/index-Dmt-aLH2.d.cts +179 -0
- package/dist/index.cjs +1387 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +153 -0
- package/dist/index.d.ts +153 -0
- package/dist/index.js +1331 -0
- package/dist/index.js.map +1 -0
- package/dist/outpost-client-yUijE00q.d.cts +271 -0
- package/dist/outpost-client-ymTJISpu.d.ts +271 -0
- package/dist/repositories-Bck6wJNS.d.ts +180 -0
- package/dist/repositories-DhUe8f2R.d.cts +180 -0
- package/dist/services-CQINhAGo.d.cts +90 -0
- package/dist/services-CfTEsetF.d.ts +90 -0
- package/dist/template-CREUq7bB.d.ts +260 -0
- package/dist/template-DxI_p2Ny.d.cts +260 -0
- package/dist/testing/index.cjs +321 -0
- package/dist/testing/index.cjs.map +1 -0
- package/dist/testing/index.d.cts +97 -0
- package/dist/testing/index.d.ts +97 -0
- package/dist/testing/index.js +312 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/webhook-kp6CiXk-.d.cts +149 -0
- package/dist/webhook-kp6CiXk-.d.ts +149 -0
- package/dist/workers/index.cjs +430 -0
- package/dist/workers/index.cjs.map +1 -0
- package/dist/workers/index.d.cts +5 -0
- package/dist/workers/index.d.ts +5 -0
- package/dist/workers/index.js +427 -0
- package/dist/workers/index.js.map +1 -0
- package/package.json +114 -0
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var pgCore = require('drizzle-orm/pg-core');
|
|
4
|
+
var drizzleOrm = require('drizzle-orm');
|
|
5
|
+
|
|
6
|
+
// src/adapters/drizzle/schema.ts
|
|
7
|
+
var lifecycleStateEnum = pgCore.pgEnum("outpost_lifecycle_state", [
|
|
8
|
+
"queued",
|
|
9
|
+
"sending",
|
|
10
|
+
"sent",
|
|
11
|
+
"delivered",
|
|
12
|
+
"bounced",
|
|
13
|
+
"complained",
|
|
14
|
+
"failed",
|
|
15
|
+
"suppressed"
|
|
16
|
+
]);
|
|
17
|
+
var suppressionReasonEnum = pgCore.pgEnum("outpost_suppression_reason", [
|
|
18
|
+
"hard_bounce",
|
|
19
|
+
"complaint",
|
|
20
|
+
"unsubscribe",
|
|
21
|
+
"invalid",
|
|
22
|
+
"manual"
|
|
23
|
+
]);
|
|
24
|
+
var outbox = pgCore.pgTable(
|
|
25
|
+
"outpost_outbox",
|
|
26
|
+
{
|
|
27
|
+
id: pgCore.uuid("id").primaryKey().defaultRandom(),
|
|
28
|
+
idempotencyKey: pgCore.text("idempotency_key").notNull(),
|
|
29
|
+
state: lifecycleStateEnum("state").notNull().default("queued").$type(),
|
|
30
|
+
recipientHmac: pgCore.text("recipient_hmac").notNull(),
|
|
31
|
+
recipientSealed: pgCore.jsonb("recipient_sealed").notNull().$type(),
|
|
32
|
+
bodySealed: pgCore.jsonb("body_sealed").notNull().$type(),
|
|
33
|
+
subject: pgCore.text("subject").notNull(),
|
|
34
|
+
templateId: pgCore.text("template_id"),
|
|
35
|
+
templateVersion: pgCore.integer("template_version"),
|
|
36
|
+
provider: pgCore.text("provider").notNull(),
|
|
37
|
+
metadata: pgCore.jsonb("metadata").notNull().default({}).$type(),
|
|
38
|
+
attempts: pgCore.integer("attempts").notNull().default(0),
|
|
39
|
+
nextAttemptAt: pgCore.timestamp("next_attempt_at", { withTimezone: true }).notNull().defaultNow(),
|
|
40
|
+
scheduledFor: pgCore.timestamp("scheduled_for", { withTimezone: true }),
|
|
41
|
+
providerMessageId: pgCore.text("provider_message_id"),
|
|
42
|
+
lastError: pgCore.text("last_error"),
|
|
43
|
+
createdAt: pgCore.timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
|
44
|
+
updatedAt: pgCore.timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
|
|
45
|
+
},
|
|
46
|
+
(t) => ({
|
|
47
|
+
idempotencyKeyUq: pgCore.uniqueIndex("outpost_outbox_idempotency_key_uq").on(t.idempotencyKey),
|
|
48
|
+
// Drives the polling send worker's claim query.
|
|
49
|
+
pollIdx: pgCore.index("outpost_outbox_poll_idx").on(t.state, t.nextAttemptAt),
|
|
50
|
+
recipientHmacIdx: pgCore.index("outpost_outbox_recipient_hmac_idx").on(t.recipientHmac),
|
|
51
|
+
providerMessageIdIdx: pgCore.index("outpost_outbox_provider_message_id_idx").on(t.providerMessageId)
|
|
52
|
+
})
|
|
53
|
+
);
|
|
54
|
+
var auditEvents = pgCore.pgTable(
|
|
55
|
+
"outpost_audit_events",
|
|
56
|
+
{
|
|
57
|
+
id: pgCore.uuid("id").primaryKey().defaultRandom(),
|
|
58
|
+
messageId: pgCore.uuid("message_id"),
|
|
59
|
+
eventType: pgCore.text("event_type").notNull(),
|
|
60
|
+
actor: pgCore.text("actor").notNull(),
|
|
61
|
+
detail: pgCore.jsonb("detail").$type(),
|
|
62
|
+
at: pgCore.timestamp("at", { withTimezone: true }).notNull().defaultNow()
|
|
63
|
+
},
|
|
64
|
+
(t) => ({
|
|
65
|
+
messageIdIdx: pgCore.index("outpost_audit_message_id_idx").on(t.messageId),
|
|
66
|
+
atIdx: pgCore.index("outpost_audit_at_idx").on(t.at)
|
|
67
|
+
})
|
|
68
|
+
);
|
|
69
|
+
var suppressions = pgCore.pgTable("outpost_suppressions", {
|
|
70
|
+
recipientHmac: pgCore.text("recipient_hmac").primaryKey(),
|
|
71
|
+
reason: suppressionReasonEnum("reason").notNull().$type(),
|
|
72
|
+
createdBy: pgCore.text("created_by").notNull(),
|
|
73
|
+
note: pgCore.text("note"),
|
|
74
|
+
createdAt: pgCore.timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
|
|
75
|
+
});
|
|
76
|
+
var webhookEvents = pgCore.pgTable(
|
|
77
|
+
"outpost_webhook_events",
|
|
78
|
+
{
|
|
79
|
+
id: pgCore.uuid("id").primaryKey().defaultRandom(),
|
|
80
|
+
provider: pgCore.text("provider").notNull(),
|
|
81
|
+
type: pgCore.text("type").notNull(),
|
|
82
|
+
providerMessageId: pgCore.text("provider_message_id").notNull(),
|
|
83
|
+
recipient: pgCore.text("recipient"),
|
|
84
|
+
isHardBounce: pgCore.boolean("is_hard_bounce"),
|
|
85
|
+
occurredAt: pgCore.timestamp("occurred_at", { withTimezone: true }),
|
|
86
|
+
raw: pgCore.jsonb("raw").notNull(),
|
|
87
|
+
receivedAt: pgCore.timestamp("received_at", { withTimezone: true }).notNull().defaultNow()
|
|
88
|
+
},
|
|
89
|
+
(t) => ({
|
|
90
|
+
providerMessageIdIdx: pgCore.index("outpost_webhook_provider_message_id_idx").on(t.providerMessageId)
|
|
91
|
+
})
|
|
92
|
+
);
|
|
93
|
+
var apiKeys = pgCore.pgTable(
|
|
94
|
+
"outpost_api_keys",
|
|
95
|
+
{
|
|
96
|
+
id: pgCore.uuid("id").primaryKey().defaultRandom(),
|
|
97
|
+
label: pgCore.text("label").notNull(),
|
|
98
|
+
keyHash: pgCore.text("key_hash").notNull(),
|
|
99
|
+
scopes: pgCore.jsonb("scopes").notNull().$type(),
|
|
100
|
+
expiresAt: pgCore.timestamp("expires_at", { withTimezone: true }),
|
|
101
|
+
revokedAt: pgCore.timestamp("revoked_at", { withTimezone: true }),
|
|
102
|
+
createdAt: pgCore.timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
|
103
|
+
lastUsedAt: pgCore.timestamp("last_used_at", { withTimezone: true })
|
|
104
|
+
},
|
|
105
|
+
(t) => ({
|
|
106
|
+
keyHashUq: pgCore.uniqueIndex("outpost_api_keys_key_hash_uq").on(t.keyHash)
|
|
107
|
+
})
|
|
108
|
+
);
|
|
109
|
+
var outpostSchema = {
|
|
110
|
+
outbox,
|
|
111
|
+
auditEvents,
|
|
112
|
+
suppressions,
|
|
113
|
+
webhookEvents,
|
|
114
|
+
apiKeys,
|
|
115
|
+
lifecycleStateEnum,
|
|
116
|
+
suppressionReasonEnum
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
// src/adapters/drizzle/mappers.ts
|
|
120
|
+
function rowToMessage(r) {
|
|
121
|
+
return {
|
|
122
|
+
id: r.id,
|
|
123
|
+
idempotencyKey: r.idempotencyKey,
|
|
124
|
+
state: r.state,
|
|
125
|
+
recipientHmac: r.recipientHmac,
|
|
126
|
+
recipientSealed: r.recipientSealed,
|
|
127
|
+
bodySealed: r.bodySealed,
|
|
128
|
+
subject: r.subject,
|
|
129
|
+
templateId: r.templateId,
|
|
130
|
+
templateVersion: r.templateVersion,
|
|
131
|
+
provider: r.provider,
|
|
132
|
+
metadata: r.metadata,
|
|
133
|
+
attempts: r.attempts,
|
|
134
|
+
nextAttemptAt: r.nextAttemptAt,
|
|
135
|
+
scheduledFor: r.scheduledFor,
|
|
136
|
+
providerMessageId: r.providerMessageId,
|
|
137
|
+
lastError: r.lastError,
|
|
138
|
+
createdAt: r.createdAt,
|
|
139
|
+
updatedAt: r.updatedAt
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
function rowToSuppression(r) {
|
|
143
|
+
return {
|
|
144
|
+
recipientHmac: r.recipientHmac,
|
|
145
|
+
reason: r.reason,
|
|
146
|
+
createdBy: r.createdBy,
|
|
147
|
+
createdAt: r.createdAt,
|
|
148
|
+
note: r.note ?? void 0
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
function rowToApiKey(r) {
|
|
152
|
+
return {
|
|
153
|
+
id: r.id,
|
|
154
|
+
label: r.label,
|
|
155
|
+
keyHash: r.keyHash,
|
|
156
|
+
scopes: r.scopes,
|
|
157
|
+
expiresAt: r.expiresAt,
|
|
158
|
+
revokedAt: r.revokedAt,
|
|
159
|
+
createdAt: r.createdAt,
|
|
160
|
+
lastUsedAt: r.lastUsedAt
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
function rowToAuditEvent(r) {
|
|
164
|
+
return {
|
|
165
|
+
id: r.id,
|
|
166
|
+
messageId: r.messageId,
|
|
167
|
+
eventType: r.eventType,
|
|
168
|
+
actor: r.actor,
|
|
169
|
+
detail: r.detail ?? null,
|
|
170
|
+
at: r.at
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// src/adapters/drizzle/repositories.ts
|
|
175
|
+
var REDACTED = { alg: "redacted", ciphertext: "" };
|
|
176
|
+
var DrizzleOutboxRepository = class {
|
|
177
|
+
constructor(db) {
|
|
178
|
+
this.db = db;
|
|
179
|
+
}
|
|
180
|
+
async insert(msg) {
|
|
181
|
+
const [row] = await this.db.insert(outbox).values({
|
|
182
|
+
idempotencyKey: msg.idempotencyKey,
|
|
183
|
+
state: msg.state,
|
|
184
|
+
recipientHmac: msg.recipientHmac,
|
|
185
|
+
recipientSealed: msg.recipientSealed,
|
|
186
|
+
bodySealed: msg.bodySealed,
|
|
187
|
+
subject: msg.subject,
|
|
188
|
+
templateId: msg.templateId,
|
|
189
|
+
templateVersion: msg.templateVersion,
|
|
190
|
+
provider: msg.provider,
|
|
191
|
+
metadata: msg.metadata,
|
|
192
|
+
scheduledFor: msg.scheduledFor,
|
|
193
|
+
nextAttemptAt: msg.nextAttemptAt
|
|
194
|
+
}).returning();
|
|
195
|
+
return rowToMessage(row);
|
|
196
|
+
}
|
|
197
|
+
async findById(id) {
|
|
198
|
+
const [row] = await this.db.select().from(outbox).where(drizzleOrm.eq(outbox.id, id)).limit(1);
|
|
199
|
+
return row ? rowToMessage(row) : null;
|
|
200
|
+
}
|
|
201
|
+
async findByIdempotencyKey(key) {
|
|
202
|
+
const [row] = await this.db.select().from(outbox).where(drizzleOrm.eq(outbox.idempotencyKey, key)).limit(1);
|
|
203
|
+
return row ? rowToMessage(row) : null;
|
|
204
|
+
}
|
|
205
|
+
async findByProviderMessageId(providerMessageId) {
|
|
206
|
+
const [row] = await this.db.select().from(outbox).where(drizzleOrm.eq(outbox.providerMessageId, providerMessageId)).limit(1);
|
|
207
|
+
return row ? rowToMessage(row) : null;
|
|
208
|
+
}
|
|
209
|
+
async list(query) {
|
|
210
|
+
const conds = [];
|
|
211
|
+
if (query.state) conds.push(drizzleOrm.eq(outbox.state, query.state));
|
|
212
|
+
if (query.recipientHmac) conds.push(drizzleOrm.eq(outbox.recipientHmac, query.recipientHmac));
|
|
213
|
+
if (query.provider) conds.push(drizzleOrm.eq(outbox.provider, query.provider));
|
|
214
|
+
if (query.createdAfter) conds.push(drizzleOrm.gte(outbox.createdAt, query.createdAfter));
|
|
215
|
+
if (query.createdBefore) conds.push(drizzleOrm.lt(outbox.createdAt, query.createdBefore));
|
|
216
|
+
const rows = await this.db.select().from(outbox).where(conds.length ? drizzleOrm.and(...conds) : void 0).orderBy(drizzleOrm.desc(outbox.createdAt)).limit(query.limit ?? 50).offset(query.offset ?? 0);
|
|
217
|
+
return rows.map(rowToMessage);
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Atomic claim using `FOR UPDATE SKIP LOCKED` so concurrent send workers
|
|
221
|
+
* never grab the same row (TDR §6). Only `queued` rows whose `next_attempt_at`
|
|
222
|
+
* has passed and whose `scheduled_for` (if any) has arrived are eligible.
|
|
223
|
+
*/
|
|
224
|
+
async claimBatchForSending(limit, now, reclaimBefore) {
|
|
225
|
+
return this.db.transaction(async (tx) => {
|
|
226
|
+
const rows = await tx.select().from(outbox).where(
|
|
227
|
+
drizzleOrm.or(
|
|
228
|
+
drizzleOrm.and(
|
|
229
|
+
drizzleOrm.eq(outbox.state, "queued"),
|
|
230
|
+
drizzleOrm.lte(outbox.nextAttemptAt, now),
|
|
231
|
+
drizzleOrm.or(drizzleOrm.isNull(outbox.scheduledFor), drizzleOrm.lte(outbox.scheduledFor, now))
|
|
232
|
+
),
|
|
233
|
+
// Reclaim abandoned `sending` rows past their lease.
|
|
234
|
+
drizzleOrm.and(drizzleOrm.eq(outbox.state, "sending"), drizzleOrm.lt(outbox.updatedAt, reclaimBefore))
|
|
235
|
+
)
|
|
236
|
+
).orderBy(drizzleOrm.asc(outbox.nextAttemptAt)).limit(limit).for("update", { skipLocked: true });
|
|
237
|
+
if (rows.length === 0) return [];
|
|
238
|
+
const ids = rows.map((r) => r.id);
|
|
239
|
+
await tx.update(outbox).set({ state: "sending", updatedAt: now }).where(drizzleOrm.inArray(outbox.id, ids));
|
|
240
|
+
return rows.map((r) => rowToMessage({ ...r, state: "sending" }));
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
async updateState(id, patch) {
|
|
244
|
+
const set = { state: patch.state, updatedAt: /* @__PURE__ */ new Date() };
|
|
245
|
+
if (patch.attempts !== void 0) set.attempts = patch.attempts;
|
|
246
|
+
if (patch.nextAttemptAt !== void 0) set.nextAttemptAt = patch.nextAttemptAt;
|
|
247
|
+
if (patch.providerMessageId !== void 0) set.providerMessageId = patch.providerMessageId;
|
|
248
|
+
if (patch.lastError !== void 0) set.lastError = patch.lastError;
|
|
249
|
+
await this.db.update(outbox).set(set).where(drizzleOrm.eq(outbox.id, id));
|
|
250
|
+
}
|
|
251
|
+
async claimTerminalForPurge(olderThan, limit) {
|
|
252
|
+
const rows = await this.db.select().from(outbox).where(
|
|
253
|
+
drizzleOrm.and(
|
|
254
|
+
drizzleOrm.inArray(outbox.state, ["delivered", "bounced", "complained", "failed", "suppressed"]),
|
|
255
|
+
drizzleOrm.lt(outbox.updatedAt, olderThan),
|
|
256
|
+
// Skip rows already redacted (idempotent purge).
|
|
257
|
+
drizzleOrm.sql`${outbox.bodySealed}->>'alg' <> 'redacted'`
|
|
258
|
+
)
|
|
259
|
+
).orderBy(drizzleOrm.asc(outbox.updatedAt)).limit(limit);
|
|
260
|
+
return rows.map(rowToMessage);
|
|
261
|
+
}
|
|
262
|
+
async redactBatch(ids) {
|
|
263
|
+
if (ids.length === 0) return 0;
|
|
264
|
+
const rows = await this.db.update(outbox).set({ recipientSealed: REDACTED, bodySealed: REDACTED, updatedAt: /* @__PURE__ */ new Date() }).where(drizzleOrm.inArray(outbox.id, [...ids])).returning({ id: outbox.id });
|
|
265
|
+
return rows.length;
|
|
266
|
+
}
|
|
267
|
+
async deleteBatch(ids) {
|
|
268
|
+
if (ids.length === 0) return 0;
|
|
269
|
+
const rows = await this.db.delete(outbox).where(drizzleOrm.inArray(outbox.id, [...ids])).returning({ id: outbox.id });
|
|
270
|
+
return rows.length;
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
var DrizzleSuppressionRepository = class {
|
|
274
|
+
constructor(db) {
|
|
275
|
+
this.db = db;
|
|
276
|
+
}
|
|
277
|
+
async isSuppressed(recipientHmac) {
|
|
278
|
+
const [row] = await this.db.select({ h: suppressions.recipientHmac }).from(suppressions).where(drizzleOrm.eq(suppressions.recipientHmac, recipientHmac)).limit(1);
|
|
279
|
+
return !!row;
|
|
280
|
+
}
|
|
281
|
+
async get(recipientHmac) {
|
|
282
|
+
const [row] = await this.db.select().from(suppressions).where(drizzleOrm.eq(suppressions.recipientHmac, recipientHmac)).limit(1);
|
|
283
|
+
return row ? rowToSuppression(row) : null;
|
|
284
|
+
}
|
|
285
|
+
async add(entry) {
|
|
286
|
+
const [row] = await this.db.insert(suppressions).values({
|
|
287
|
+
recipientHmac: entry.recipientHmac,
|
|
288
|
+
reason: entry.reason,
|
|
289
|
+
createdBy: entry.createdBy,
|
|
290
|
+
note: entry.note ?? null
|
|
291
|
+
}).onConflictDoNothing({ target: suppressions.recipientHmac }).returning();
|
|
292
|
+
return row ? rowToSuppression(row) : await this.get(entry.recipientHmac);
|
|
293
|
+
}
|
|
294
|
+
async remove(recipientHmac) {
|
|
295
|
+
const rows = await this.db.delete(suppressions).where(drizzleOrm.eq(suppressions.recipientHmac, recipientHmac)).returning({ h: suppressions.recipientHmac });
|
|
296
|
+
return rows.length > 0;
|
|
297
|
+
}
|
|
298
|
+
async list(limit, offset) {
|
|
299
|
+
const rows = await this.db.select().from(suppressions).orderBy(drizzleOrm.desc(suppressions.createdAt)).limit(limit).offset(offset);
|
|
300
|
+
return rows.map(rowToSuppression);
|
|
301
|
+
}
|
|
302
|
+
};
|
|
303
|
+
var DrizzleAuditRepository = class {
|
|
304
|
+
constructor(db) {
|
|
305
|
+
this.db = db;
|
|
306
|
+
}
|
|
307
|
+
async append(event) {
|
|
308
|
+
const [row] = await this.db.insert(auditEvents).values({
|
|
309
|
+
messageId: event.messageId,
|
|
310
|
+
eventType: event.eventType,
|
|
311
|
+
actor: event.actor,
|
|
312
|
+
detail: event.detail ?? null
|
|
313
|
+
}).returning();
|
|
314
|
+
return rowToAuditEvent(row);
|
|
315
|
+
}
|
|
316
|
+
async listForMessage(messageId) {
|
|
317
|
+
const rows = await this.db.select().from(auditEvents).where(drizzleOrm.eq(auditEvents.messageId, messageId)).orderBy(drizzleOrm.asc(auditEvents.at));
|
|
318
|
+
return rows.map(rowToAuditEvent);
|
|
319
|
+
}
|
|
320
|
+
async purgeOlderThan(cutoff, batchSize) {
|
|
321
|
+
let total = 0;
|
|
322
|
+
for (; ; ) {
|
|
323
|
+
const ids = await this.db.select({ id: auditEvents.id }).from(auditEvents).where(drizzleOrm.lt(auditEvents.at, cutoff)).limit(batchSize);
|
|
324
|
+
if (ids.length === 0) break;
|
|
325
|
+
await this.db.delete(auditEvents).where(
|
|
326
|
+
drizzleOrm.inArray(
|
|
327
|
+
auditEvents.id,
|
|
328
|
+
ids.map((r) => r.id)
|
|
329
|
+
)
|
|
330
|
+
);
|
|
331
|
+
total += ids.length;
|
|
332
|
+
if (ids.length < batchSize) break;
|
|
333
|
+
}
|
|
334
|
+
return total;
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
var DrizzleApiKeyRepository = class {
|
|
338
|
+
constructor(db) {
|
|
339
|
+
this.db = db;
|
|
340
|
+
}
|
|
341
|
+
async insert(key) {
|
|
342
|
+
const [row] = await this.db.insert(apiKeys).values({
|
|
343
|
+
label: key.label,
|
|
344
|
+
keyHash: key.keyHash,
|
|
345
|
+
scopes: [...key.scopes],
|
|
346
|
+
expiresAt: key.expiresAt
|
|
347
|
+
}).returning();
|
|
348
|
+
return rowToApiKey(row);
|
|
349
|
+
}
|
|
350
|
+
async findByHash(keyHash) {
|
|
351
|
+
const [row] = await this.db.select().from(apiKeys).where(drizzleOrm.eq(apiKeys.keyHash, keyHash)).limit(1);
|
|
352
|
+
return row ? rowToApiKey(row) : null;
|
|
353
|
+
}
|
|
354
|
+
async findById(id) {
|
|
355
|
+
const [row] = await this.db.select().from(apiKeys).where(drizzleOrm.eq(apiKeys.id, id)).limit(1);
|
|
356
|
+
return row ? rowToApiKey(row) : null;
|
|
357
|
+
}
|
|
358
|
+
async list() {
|
|
359
|
+
const rows = await this.db.select().from(apiKeys).orderBy(drizzleOrm.desc(apiKeys.createdAt));
|
|
360
|
+
return rows.map(rowToApiKey);
|
|
361
|
+
}
|
|
362
|
+
async revoke(id, at) {
|
|
363
|
+
const rows = await this.db.update(apiKeys).set({ revokedAt: at }).where(drizzleOrm.and(drizzleOrm.eq(apiKeys.id, id), drizzleOrm.isNull(apiKeys.revokedAt))).returning({ id: apiKeys.id });
|
|
364
|
+
return rows.length > 0;
|
|
365
|
+
}
|
|
366
|
+
async touchLastUsed(id, at) {
|
|
367
|
+
await this.db.update(apiKeys).set({ lastUsedAt: at }).where(drizzleOrm.eq(apiKeys.id, id));
|
|
368
|
+
}
|
|
369
|
+
};
|
|
370
|
+
var DrizzleWebhookEventRepository = class {
|
|
371
|
+
constructor(db) {
|
|
372
|
+
this.db = db;
|
|
373
|
+
}
|
|
374
|
+
async record(event) {
|
|
375
|
+
await this.db.insert(webhookEvents).values({
|
|
376
|
+
provider: event.provider,
|
|
377
|
+
type: event.type,
|
|
378
|
+
providerMessageId: event.providerMessageId,
|
|
379
|
+
recipient: event.recipient ?? null,
|
|
380
|
+
isHardBounce: event.isHardBounce ?? null,
|
|
381
|
+
occurredAt: event.occurredAt ?? null,
|
|
382
|
+
raw: event.raw
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
exports.DrizzleApiKeyRepository = DrizzleApiKeyRepository;
|
|
388
|
+
exports.DrizzleAuditRepository = DrizzleAuditRepository;
|
|
389
|
+
exports.DrizzleOutboxRepository = DrizzleOutboxRepository;
|
|
390
|
+
exports.DrizzleSuppressionRepository = DrizzleSuppressionRepository;
|
|
391
|
+
exports.DrizzleWebhookEventRepository = DrizzleWebhookEventRepository;
|
|
392
|
+
exports.apiKeys = apiKeys;
|
|
393
|
+
exports.auditEvents = auditEvents;
|
|
394
|
+
exports.lifecycleStateEnum = lifecycleStateEnum;
|
|
395
|
+
exports.outbox = outbox;
|
|
396
|
+
exports.outpostSchema = outpostSchema;
|
|
397
|
+
exports.rowToApiKey = rowToApiKey;
|
|
398
|
+
exports.rowToAuditEvent = rowToAuditEvent;
|
|
399
|
+
exports.rowToMessage = rowToMessage;
|
|
400
|
+
exports.rowToSuppression = rowToSuppression;
|
|
401
|
+
exports.suppressionReasonEnum = suppressionReasonEnum;
|
|
402
|
+
exports.suppressions = suppressions;
|
|
403
|
+
exports.webhookEvents = webhookEvents;
|
|
404
|
+
//# sourceMappingURL=index.cjs.map
|
|
405
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/adapters/drizzle/schema.ts","../../../src/adapters/drizzle/mappers.ts","../../../src/adapters/drizzle/repositories.ts"],"names":["pgEnum","pgTable","uuid","text","jsonb","integer","timestamp","uniqueIndex","index","boolean","eq","gte","lt","and","desc","or","lte","isNull","asc","inArray","sql"],"mappings":";;;;;;AA6BO,IAAM,kBAAA,GAAqBA,cAAO,yBAAA,EAA2B;AAAA,EAClE,QAAA;AAAA,EACA,SAAA;AAAA,EACA,MAAA;AAAA,EACA,WAAA;AAAA,EACA,SAAA;AAAA,EACA,YAAA;AAAA,EACA,QAAA;AAAA,EACA;AACF,CAAC;AAEM,IAAM,qBAAA,GAAwBA,cAAO,4BAAA,EAA8B;AAAA,EACxE,aAAA;AAAA,EACA,WAAA;AAAA,EACA,aAAA;AAAA,EACA,SAAA;AAAA,EACA;AACF,CAAC;AAEM,IAAM,MAAA,GAASC,cAAA;AAAA,EACpB,gBAAA;AAAA,EACA;AAAA,IACE,IAAIC,WAAA,CAAK,IAAI,CAAA,CAAE,UAAA,GAAa,aAAA,EAAc;AAAA,IAC1C,cAAA,EAAgBC,WAAA,CAAK,iBAAiB,CAAA,CAAE,OAAA,EAAQ;AAAA,IAChD,KAAA,EAAO,mBAAmB,OAAO,CAAA,CAAE,SAAQ,CAAE,OAAA,CAAQ,QAAQ,CAAA,CAAE,KAAA,EAAsB;AAAA,IACrF,aAAA,EAAeA,WAAA,CAAK,gBAAgB,CAAA,CAAE,OAAA,EAAQ;AAAA,IAC9C,iBAAiBC,YAAA,CAAM,kBAAkB,CAAA,CAAE,OAAA,GAAU,KAAA,EAAc;AAAA,IACnE,YAAYA,YAAA,CAAM,aAAa,CAAA,CAAE,OAAA,GAAU,KAAA,EAAc;AAAA,IACzD,OAAA,EAASD,WAAA,CAAK,SAAS,CAAA,CAAE,OAAA,EAAQ;AAAA,IACjC,UAAA,EAA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,EAAA,EAAI,EAAE,CAAA,EAAGO,iBAAA,CAAO,QAAQ,SAAS,CAAC,CAAC,CAAA,CACxD,SAAA,CAAU,EAAE,EAAA,EAAI,OAAA,CAAQ,IAAI,CAAA;AAC/B,IAAA,OAAO,KAAK,MAAA,GAAS,CAAA;AAAA,EACvB;AAAA,EAEA,MAAM,aAAA,CAAc,EAAA,EAAY,EAAA,EAAyB;AACvD,IAAA,MAAM,KAAK,EAAA,CAAG,MAAA,CAAO,OAAO,CAAA,CAAE,IAAI,EAAE,UAAA,EAAY,EAAA,EAAI,EAAE,KAAA,CAAMP,aAAA,CAAG,OAAA,CAAQ,EAAA,EAAI,EAAE,CAAC,CAAA;AAAA,EAChF;AACF;AAEO,IAAM,gCAAN,MAAsE;AAAA,EAC3E,YAA6B,EAAA,EAAe;AAAf,IAAA,IAAA,CAAA,EAAA,GAAA,EAAA;AAAA,EAAgB;AAAA,EAE7C,MAAM,OAAO,KAAA,EAAoC;AAC/C,IAAA,MAAM,IAAA,CAAK,EAAA,CAAG,MAAA,CAAO,aAAa,EAAE,MAAA,CAAO;AAAA,MACzC,UAAU,KAAA,CAAM,QAAA;AAAA,MAChB,MAAM,KAAA,CAAM,IAAA;AAAA,MACZ,mBAAmB,KAAA,CAAM,iBAAA;AAAA,MACzB,SAAA,EAAW,MAAM,SAAA,IAAa,IAAA;AAAA,MAC9B,YAAA,EAAc,MAAM,YAAA,IAAgB,IAAA;AAAA,MACpC,UAAA,EAAY,MAAM,UAAA,IAAc,IAAA;AAAA,MAChC,KAAK,KAAA,CAAM;AAAA,KACZ,CAAA;AAAA,EACH;AACF","file":"index.cjs","sourcesContent":["import {\n pgTable,\n pgEnum,\n uuid,\n text,\n integer,\n boolean,\n jsonb,\n timestamp,\n index,\n uniqueIndex,\n} from \"drizzle-orm/pg-core\";\nimport type { Sealed } from \"../../domain/message.js\";\nimport type { LifecycleState } from \"../../domain/lifecycle.js\";\nimport type { SuppressionReason } from \"../../domain/suppression.js\";\nimport type { ApiScope } from \"../../domain/api-key.js\";\n\n/**\n * Drizzle/PostgreSQL schema (TDR §7).\n *\n * PII columns (`recipient_sealed`, `body_sealed`) hold the `Sealed` envelope as\n * JSONB — ciphertext when encryption is on, base64 plaintext (`alg: \"plain\"`)\n * otherwise, so the column shape never changes. Index columns (`state`,\n * `next_attempt_at`, `recipient_hmac`, `idempotency_key`) stay clear so the\n * polling worker and suppression lookups remain functional (TDR §5.4).\n *\n * Generate a migration from this schema with drizzle-kit (see docs/database.md).\n */\n\nexport const lifecycleStateEnum = pgEnum(\"outpost_lifecycle_state\", [\n \"queued\",\n \"sending\",\n \"sent\",\n \"delivered\",\n \"bounced\",\n \"complained\",\n \"failed\",\n \"suppressed\",\n]);\n\nexport const suppressionReasonEnum = pgEnum(\"outpost_suppression_reason\", [\n \"hard_bounce\",\n \"complaint\",\n \"unsubscribe\",\n \"invalid\",\n \"manual\",\n]);\n\nexport const outbox = pgTable(\n \"outpost_outbox\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n idempotencyKey: text(\"idempotency_key\").notNull(),\n state: lifecycleStateEnum(\"state\").notNull().default(\"queued\").$type<LifecycleState>(),\n recipientHmac: text(\"recipient_hmac\").notNull(),\n recipientSealed: jsonb(\"recipient_sealed\").notNull().$type<Sealed>(),\n bodySealed: jsonb(\"body_sealed\").notNull().$type<Sealed>(),\n subject: text(\"subject\").notNull(),\n templateId: text(\"template_id\"),\n templateVersion: integer(\"template_version\"),\n provider: text(\"provider\").notNull(),\n metadata: jsonb(\"metadata\").notNull().default({}).$type<Record<string, unknown>>(),\n attempts: integer(\"attempts\").notNull().default(0),\n nextAttemptAt: timestamp(\"next_attempt_at\", { withTimezone: true }).notNull().defaultNow(),\n scheduledFor: timestamp(\"scheduled_for\", { withTimezone: true }),\n providerMessageId: text(\"provider_message_id\"),\n lastError: text(\"last_error\"),\n createdAt: timestamp(\"created_at\", { withTimezone: true }).notNull().defaultNow(),\n updatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull().defaultNow(),\n },\n (t) => ({\n idempotencyKeyUq: uniqueIndex(\"outpost_outbox_idempotency_key_uq\").on(t.idempotencyKey),\n // Drives the polling send worker's claim query.\n pollIdx: index(\"outpost_outbox_poll_idx\").on(t.state, t.nextAttemptAt),\n recipientHmacIdx: index(\"outpost_outbox_recipient_hmac_idx\").on(t.recipientHmac),\n providerMessageIdIdx: index(\"outpost_outbox_provider_message_id_idx\").on(t.providerMessageId),\n }),\n);\n\nexport const auditEvents = pgTable(\n \"outpost_audit_events\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n messageId: uuid(\"message_id\"),\n eventType: text(\"event_type\").notNull(),\n actor: text(\"actor\").notNull(),\n detail: jsonb(\"detail\").$type<Record<string, unknown> | null>(),\n at: timestamp(\"at\", { withTimezone: true }).notNull().defaultNow(),\n },\n (t) => ({\n messageIdIdx: index(\"outpost_audit_message_id_idx\").on(t.messageId),\n atIdx: index(\"outpost_audit_at_idx\").on(t.at),\n }),\n);\n\nexport const suppressions = pgTable(\"outpost_suppressions\", {\n recipientHmac: text(\"recipient_hmac\").primaryKey(),\n reason: suppressionReasonEnum(\"reason\").notNull().$type<SuppressionReason>(),\n createdBy: text(\"created_by\").notNull(),\n note: text(\"note\"),\n createdAt: timestamp(\"created_at\", { withTimezone: true }).notNull().defaultNow(),\n});\n\nexport const webhookEvents = pgTable(\n \"outpost_webhook_events\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n provider: text(\"provider\").notNull(),\n type: text(\"type\").notNull(),\n providerMessageId: text(\"provider_message_id\").notNull(),\n recipient: text(\"recipient\"),\n isHardBounce: boolean(\"is_hard_bounce\"),\n occurredAt: timestamp(\"occurred_at\", { withTimezone: true }),\n raw: jsonb(\"raw\").notNull(),\n receivedAt: timestamp(\"received_at\", { withTimezone: true }).notNull().defaultNow(),\n },\n (t) => ({\n providerMessageIdIdx: index(\"outpost_webhook_provider_message_id_idx\").on(t.providerMessageId),\n }),\n);\n\nexport const apiKeys = pgTable(\n \"outpost_api_keys\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n label: text(\"label\").notNull(),\n keyHash: text(\"key_hash\").notNull(),\n scopes: jsonb(\"scopes\").notNull().$type<ApiScope[]>(),\n expiresAt: timestamp(\"expires_at\", { withTimezone: true }),\n revokedAt: timestamp(\"revoked_at\", { withTimezone: true }),\n createdAt: timestamp(\"created_at\", { withTimezone: true }).notNull().defaultNow(),\n lastUsedAt: timestamp(\"last_used_at\", { withTimezone: true }),\n },\n (t) => ({\n keyHashUq: uniqueIndex(\"outpost_api_keys_key_hash_uq\").on(t.keyHash),\n }),\n);\n\n/** The full schema object — pass to `drizzle(client, { schema })`. */\nexport const outpostSchema = {\n outbox,\n auditEvents,\n suppressions,\n webhookEvents,\n apiKeys,\n lifecycleStateEnum,\n suppressionReasonEnum,\n};\n\nexport type OutboxRow = typeof outbox.$inferSelect;\nexport type AuditRow = typeof auditEvents.$inferSelect;\nexport type SuppressionRow = typeof suppressions.$inferSelect;\nexport type WebhookRow = typeof webhookEvents.$inferSelect;\nexport type ApiKeyRow = typeof apiKeys.$inferSelect;\n","import type { Message } from \"../../domain/message.js\";\nimport type { SuppressionEntry } from \"../../domain/suppression.js\";\nimport type { ApiKey } from \"../../domain/api-key.js\";\nimport type { AuditEvent } from \"../../domain/audit.js\";\nimport type { OutboxRow, SuppressionRow, ApiKeyRow, AuditRow } from \"./schema.js\";\n\n/** Row → domain mappers. Keep DB shape isolated from the domain. */\n\nexport function rowToMessage(r: OutboxRow): Message {\n return {\n id: r.id,\n idempotencyKey: r.idempotencyKey,\n state: r.state,\n recipientHmac: r.recipientHmac,\n recipientSealed: r.recipientSealed,\n bodySealed: r.bodySealed,\n subject: r.subject,\n templateId: r.templateId,\n templateVersion: r.templateVersion,\n provider: r.provider,\n metadata: r.metadata,\n attempts: r.attempts,\n nextAttemptAt: r.nextAttemptAt,\n scheduledFor: r.scheduledFor,\n providerMessageId: r.providerMessageId,\n lastError: r.lastError,\n createdAt: r.createdAt,\n updatedAt: r.updatedAt,\n };\n}\n\nexport function rowToSuppression(r: SuppressionRow): SuppressionEntry {\n return {\n recipientHmac: r.recipientHmac,\n reason: r.reason,\n createdBy: r.createdBy,\n createdAt: r.createdAt,\n note: r.note ?? undefined,\n };\n}\n\nexport function rowToApiKey(r: ApiKeyRow): ApiKey {\n return {\n id: r.id,\n label: r.label,\n keyHash: r.keyHash,\n scopes: r.scopes,\n expiresAt: r.expiresAt,\n revokedAt: r.revokedAt,\n createdAt: r.createdAt,\n lastUsedAt: r.lastUsedAt,\n };\n}\n\nexport function rowToAuditEvent(r: AuditRow): AuditEvent {\n return {\n id: r.id,\n messageId: r.messageId,\n eventType: r.eventType as AuditEvent[\"eventType\"],\n actor: r.actor,\n detail: r.detail ?? null,\n at: r.at,\n };\n}\n","import { and, eq, or, lte, gte, lt, isNull, inArray, asc, desc, sql } from \"drizzle-orm\";\nimport type {\n OutboxRepository,\n SuppressionRepository,\n AuditRepository,\n ApiKeyRepository,\n WebhookEventRepository,\n NewMessage,\n MessageStatePatch,\n ListMessagesQuery,\n NewApiKey,\n} from \"../../ports/repositories.js\";\nimport type { Message, Sealed } from \"../../domain/message.js\";\nimport type { SuppressionEntry, SuppressionReason } from \"../../domain/suppression.js\";\nimport type { ApiKey } from \"../../domain/api-key.js\";\nimport type { AuditEvent, NewAuditEvent } from \"../../domain/audit.js\";\nimport type { WebhookEvent } from \"../../domain/webhook.js\";\nimport type { OutpostDb } from \"./db.js\";\nimport { outbox, suppressions, auditEvents, apiKeys, webhookEvents } from \"./schema.js\";\nimport { rowToMessage, rowToSuppression, rowToApiKey, rowToAuditEvent } from \"./mappers.js\";\n\n/** Tombstone written into PII columns on redaction (TDR §3.9). */\nconst REDACTED: Sealed = { alg: \"redacted\", ciphertext: \"\" };\n\nexport class DrizzleOutboxRepository implements OutboxRepository {\n constructor(private readonly db: OutpostDb) {}\n\n async insert(msg: NewMessage): Promise<Message> {\n const [row] = await this.db\n .insert(outbox)\n .values({\n idempotencyKey: msg.idempotencyKey,\n state: msg.state,\n recipientHmac: msg.recipientHmac,\n recipientSealed: msg.recipientSealed,\n bodySealed: msg.bodySealed,\n subject: msg.subject,\n templateId: msg.templateId,\n templateVersion: msg.templateVersion,\n provider: msg.provider,\n metadata: msg.metadata,\n scheduledFor: msg.scheduledFor,\n nextAttemptAt: msg.nextAttemptAt,\n })\n .returning();\n return rowToMessage(row!);\n }\n\n async findById(id: string): Promise<Message | null> {\n const [row] = await this.db.select().from(outbox).where(eq(outbox.id, id)).limit(1);\n return row ? rowToMessage(row) : null;\n }\n\n async findByIdempotencyKey(key: string): Promise<Message | null> {\n const [row] = await this.db\n .select()\n .from(outbox)\n .where(eq(outbox.idempotencyKey, key))\n .limit(1);\n return row ? rowToMessage(row) : null;\n }\n\n async findByProviderMessageId(providerMessageId: string): Promise<Message | null> {\n const [row] = await this.db\n .select()\n .from(outbox)\n .where(eq(outbox.providerMessageId, providerMessageId))\n .limit(1);\n return row ? rowToMessage(row) : null;\n }\n\n async list(query: ListMessagesQuery): Promise<Message[]> {\n const conds = [];\n if (query.state) conds.push(eq(outbox.state, query.state));\n if (query.recipientHmac) conds.push(eq(outbox.recipientHmac, query.recipientHmac));\n if (query.provider) conds.push(eq(outbox.provider, query.provider));\n if (query.createdAfter) conds.push(gte(outbox.createdAt, query.createdAfter));\n if (query.createdBefore) conds.push(lt(outbox.createdAt, query.createdBefore));\n\n const rows = await this.db\n .select()\n .from(outbox)\n .where(conds.length ? and(...conds) : undefined)\n .orderBy(desc(outbox.createdAt))\n .limit(query.limit ?? 50)\n .offset(query.offset ?? 0);\n return rows.map(rowToMessage);\n }\n\n /**\n * Atomic claim using `FOR UPDATE SKIP LOCKED` so concurrent send workers\n * never grab the same row (TDR §6). Only `queued` rows whose `next_attempt_at`\n * has passed and whose `scheduled_for` (if any) has arrived are eligible.\n */\n async claimBatchForSending(limit: number, now: Date, reclaimBefore: Date): Promise<Message[]> {\n return this.db.transaction(async (tx) => {\n const rows = await tx\n .select()\n .from(outbox)\n .where(\n or(\n and(\n eq(outbox.state, \"queued\"),\n lte(outbox.nextAttemptAt, now),\n or(isNull(outbox.scheduledFor), lte(outbox.scheduledFor, now)),\n ),\n // Reclaim abandoned `sending` rows past their lease.\n and(eq(outbox.state, \"sending\"), lt(outbox.updatedAt, reclaimBefore)),\n ),\n )\n .orderBy(asc(outbox.nextAttemptAt))\n .limit(limit)\n .for(\"update\", { skipLocked: true });\n\n if (rows.length === 0) return [];\n const ids = rows.map((r) => r.id);\n await tx\n .update(outbox)\n .set({ state: \"sending\", updatedAt: now })\n .where(inArray(outbox.id, ids));\n return rows.map((r) => rowToMessage({ ...r, state: \"sending\" }));\n });\n }\n\n async updateState(id: string, patch: MessageStatePatch): Promise<void> {\n const set: Partial<typeof outbox.$inferInsert> = { state: patch.state, updatedAt: new Date() };\n if (patch.attempts !== undefined) set.attempts = patch.attempts;\n if (patch.nextAttemptAt !== undefined) set.nextAttemptAt = patch.nextAttemptAt;\n if (patch.providerMessageId !== undefined) set.providerMessageId = patch.providerMessageId;\n if (patch.lastError !== undefined) set.lastError = patch.lastError;\n await this.db.update(outbox).set(set).where(eq(outbox.id, id));\n }\n\n async claimTerminalForPurge(olderThan: Date, limit: number): Promise<Message[]> {\n const rows = await this.db\n .select()\n .from(outbox)\n .where(\n and(\n inArray(outbox.state, [\"delivered\", \"bounced\", \"complained\", \"failed\", \"suppressed\"]),\n lt(outbox.updatedAt, olderThan),\n // Skip rows already redacted (idempotent purge).\n sql`${outbox.bodySealed}->>'alg' <> 'redacted'`,\n ),\n )\n .orderBy(asc(outbox.updatedAt))\n .limit(limit);\n return rows.map(rowToMessage);\n }\n\n async redactBatch(ids: readonly string[]): Promise<number> {\n if (ids.length === 0) return 0;\n const rows = await this.db\n .update(outbox)\n .set({ recipientSealed: REDACTED, bodySealed: REDACTED, updatedAt: new Date() })\n .where(inArray(outbox.id, [...ids]))\n .returning({ id: outbox.id });\n return rows.length;\n }\n\n async deleteBatch(ids: readonly string[]): Promise<number> {\n if (ids.length === 0) return 0;\n const rows = await this.db\n .delete(outbox)\n .where(inArray(outbox.id, [...ids]))\n .returning({ id: outbox.id });\n return rows.length;\n }\n}\n\nexport class DrizzleSuppressionRepository implements SuppressionRepository {\n constructor(private readonly db: OutpostDb) {}\n\n async isSuppressed(recipientHmac: string): Promise<boolean> {\n const [row] = await this.db\n .select({ h: suppressions.recipientHmac })\n .from(suppressions)\n .where(eq(suppressions.recipientHmac, recipientHmac))\n .limit(1);\n return !!row;\n }\n\n async get(recipientHmac: string): Promise<SuppressionEntry | null> {\n const [row] = await this.db\n .select()\n .from(suppressions)\n .where(eq(suppressions.recipientHmac, recipientHmac))\n .limit(1);\n return row ? rowToSuppression(row) : null;\n }\n\n async add(entry: {\n recipientHmac: string;\n reason: SuppressionReason;\n createdBy: string;\n note?: string;\n }): Promise<SuppressionEntry> {\n const [row] = await this.db\n .insert(suppressions)\n .values({\n recipientHmac: entry.recipientHmac,\n reason: entry.reason,\n createdBy: entry.createdBy,\n note: entry.note ?? null,\n })\n // Idempotent: a repeat suppression keeps the original reason/timestamp.\n .onConflictDoNothing({ target: suppressions.recipientHmac })\n .returning();\n return row ? rowToSuppression(row) : (await this.get(entry.recipientHmac))!;\n }\n\n async remove(recipientHmac: string): Promise<boolean> {\n const rows = await this.db\n .delete(suppressions)\n .where(eq(suppressions.recipientHmac, recipientHmac))\n .returning({ h: suppressions.recipientHmac });\n return rows.length > 0;\n }\n\n async list(limit: number, offset: number): Promise<SuppressionEntry[]> {\n const rows = await this.db\n .select()\n .from(suppressions)\n .orderBy(desc(suppressions.createdAt))\n .limit(limit)\n .offset(offset);\n return rows.map(rowToSuppression);\n }\n}\n\nexport class DrizzleAuditRepository implements AuditRepository {\n constructor(private readonly db: OutpostDb) {}\n\n async append(event: NewAuditEvent): Promise<AuditEvent> {\n const [row] = await this.db\n .insert(auditEvents)\n .values({\n messageId: event.messageId,\n eventType: event.eventType,\n actor: event.actor,\n detail: event.detail ?? null,\n })\n .returning();\n return rowToAuditEvent(row!);\n }\n\n async listForMessage(messageId: string): Promise<AuditEvent[]> {\n const rows = await this.db\n .select()\n .from(auditEvents)\n .where(eq(auditEvents.messageId, messageId))\n .orderBy(asc(auditEvents.at));\n return rows.map(rowToAuditEvent);\n }\n\n async purgeOlderThan(cutoff: Date, batchSize: number): Promise<number> {\n let total = 0;\n for (;;) {\n // Delete in batches via a subselect of ids to keep locks short.\n const ids = await this.db\n .select({ id: auditEvents.id })\n .from(auditEvents)\n .where(lt(auditEvents.at, cutoff))\n .limit(batchSize);\n if (ids.length === 0) break;\n await this.db.delete(auditEvents).where(\n inArray(\n auditEvents.id,\n ids.map((r) => r.id),\n ),\n );\n total += ids.length;\n if (ids.length < batchSize) break;\n }\n return total;\n }\n}\n\nexport class DrizzleApiKeyRepository implements ApiKeyRepository {\n constructor(private readonly db: OutpostDb) {}\n\n async insert(key: NewApiKey): Promise<ApiKey> {\n const [row] = await this.db\n .insert(apiKeys)\n .values({\n label: key.label,\n keyHash: key.keyHash,\n scopes: [...key.scopes],\n expiresAt: key.expiresAt,\n })\n .returning();\n return rowToApiKey(row!);\n }\n\n async findByHash(keyHash: string): Promise<ApiKey | null> {\n const [row] = await this.db\n .select()\n .from(apiKeys)\n .where(eq(apiKeys.keyHash, keyHash))\n .limit(1);\n return row ? rowToApiKey(row) : null;\n }\n\n async findById(id: string): Promise<ApiKey | null> {\n const [row] = await this.db.select().from(apiKeys).where(eq(apiKeys.id, id)).limit(1);\n return row ? rowToApiKey(row) : null;\n }\n\n async list(): Promise<ApiKey[]> {\n const rows = await this.db.select().from(apiKeys).orderBy(desc(apiKeys.createdAt));\n return rows.map(rowToApiKey);\n }\n\n async revoke(id: string, at: Date): Promise<boolean> {\n const rows = await this.db\n .update(apiKeys)\n .set({ revokedAt: at })\n .where(and(eq(apiKeys.id, id), isNull(apiKeys.revokedAt)))\n .returning({ id: apiKeys.id });\n return rows.length > 0;\n }\n\n async touchLastUsed(id: string, at: Date): Promise<void> {\n await this.db.update(apiKeys).set({ lastUsedAt: at }).where(eq(apiKeys.id, id));\n }\n}\n\nexport class DrizzleWebhookEventRepository implements WebhookEventRepository {\n constructor(private readonly db: OutpostDb) {}\n\n async record(event: WebhookEvent): Promise<void> {\n await this.db.insert(webhookEvents).values({\n provider: event.provider,\n type: event.type,\n providerMessageId: event.providerMessageId,\n recipient: event.recipient ?? null,\n isHardBounce: event.isHardBounce ?? null,\n occurredAt: event.occurredAt ?? null,\n raw: event.raw,\n });\n }\n}\n"]}
|