@sayedhfatimi/convex-email 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +290 -44
  2. package/dist/adapters/resend/inbound.d.ts.map +1 -1
  3. package/dist/adapters/resend/inbound.js +21 -5
  4. package/dist/adapters/resend/inbound.js.map +1 -1
  5. package/dist/adapters/resend/send.d.ts.map +1 -1
  6. package/dist/adapters/resend/send.js +9 -1
  7. package/dist/adapters/resend/send.js.map +1 -1
  8. package/dist/adapters/ses/inbound.d.ts.map +1 -1
  9. package/dist/adapters/ses/inbound.js +10 -3
  10. package/dist/adapters/ses/inbound.js.map +1 -1
  11. package/dist/adapters/ses/send.d.ts.map +1 -1
  12. package/dist/adapters/ses/send.js +4 -0
  13. package/dist/adapters/ses/send.js.map +1 -1
  14. package/dist/client/index.d.ts +20 -4
  15. package/dist/client/index.d.ts.map +1 -1
  16. package/dist/client/index.js +35 -20
  17. package/dist/client/index.js.map +1 -1
  18. package/dist/component/_generated/component.d.ts +2 -1
  19. package/dist/component/_generated/component.d.ts.map +1 -1
  20. package/dist/component/cleanup.d.ts +7 -0
  21. package/dist/component/cleanup.d.ts.map +1 -1
  22. package/dist/component/cleanup.js +141 -10
  23. package/dist/component/cleanup.js.map +1 -1
  24. package/dist/component/credentials.d.ts +11 -1
  25. package/dist/component/credentials.d.ts.map +1 -1
  26. package/dist/component/credentials.js +38 -3
  27. package/dist/component/credentials.js.map +1 -1
  28. package/dist/component/deliver.d.ts +13 -3
  29. package/dist/component/deliver.d.ts.map +1 -1
  30. package/dist/component/deliver.js +88 -36
  31. package/dist/component/deliver.js.map +1 -1
  32. package/dist/component/events.d.ts +15 -0
  33. package/dist/component/events.d.ts.map +1 -1
  34. package/dist/component/events.js +91 -31
  35. package/dist/component/events.js.map +1 -1
  36. package/dist/component/inbound.js +3 -3
  37. package/dist/component/inbound.js.map +1 -1
  38. package/dist/component/schema.d.ts +18 -4
  39. package/dist/component/schema.d.ts.map +1 -1
  40. package/dist/component/schema.js +22 -4
  41. package/dist/component/schema.js.map +1 -1
  42. package/dist/component/send.d.ts +5 -3
  43. package/dist/component/send.d.ts.map +1 -1
  44. package/dist/component/send.js +33 -15
  45. package/dist/component/send.js.map +1 -1
  46. package/dist/component/unsubscribe.d.ts.map +1 -1
  47. package/dist/component/unsubscribe.js +2 -1
  48. package/dist/component/unsubscribe.js.map +1 -1
  49. package/dist/component/webhooks.d.ts.map +1 -1
  50. package/dist/component/webhooks.js +3 -1
  51. package/dist/component/webhooks.js.map +1 -1
  52. package/dist/shared/readCapped.d.ts +2 -0
  53. package/dist/shared/readCapped.d.ts.map +1 -1
  54. package/dist/shared/readCapped.js +9 -0
  55. package/dist/shared/readCapped.js.map +1 -1
  56. package/package.json +1 -1
  57. package/src/adapters/resend/inbound.ts +20 -5
  58. package/src/adapters/resend/send.ts +10 -1
  59. package/src/adapters/ses/inbound.ts +9 -3
  60. package/src/adapters/ses/send.ts +4 -0
  61. package/src/client/index.ts +42 -21
  62. package/src/component/_generated/component.ts +2 -2
  63. package/src/component/cleanup.ts +158 -11
  64. package/src/component/credentials.ts +39 -5
  65. package/src/component/deliver.ts +104 -35
  66. package/src/component/events.ts +111 -41
  67. package/src/component/inbound.ts +3 -3
  68. package/src/component/schema.ts +22 -4
  69. package/src/component/send.ts +41 -12
  70. package/src/component/unsubscribe.ts +2 -1
  71. package/src/component/webhooks.ts +4 -2
  72. package/src/shared/readCapped.ts +9 -0
@@ -6,12 +6,16 @@ import { type MutationCtx, mutation } from "./_generated/server.js";
6
6
  const BATCH = 200;
7
7
  /** Attachment rows deleted per call, across all messages. */
8
8
  const ATTACHMENT_BUDGET = 1000;
9
+ /** Events deleted per call by a purge, across messages and orphans. */
10
+ const EVENT_BUDGET = 1000;
9
11
 
10
12
  /**
11
13
  * Outbound statuses whose bodies may go. `queued` and `sending` still need
12
14
  * theirs; `received` is inbound, which is driven from its `inbound` row.
13
15
  * Scanning these through an index (never filtering after the read) means a
14
- * pile of ineligible rows can never starve the rows behind them.
16
+ * pile of ineligible rows can never starve the rows behind them. A purge
17
+ * deletes messages in these statuses: a delivery still delayed after the
18
+ * retention period never resolves.
15
19
  */
16
20
  const PURGEABLE: Doc<"messages">["status"][] = [
17
21
  "test",
@@ -25,7 +29,7 @@ const PURGEABLE: Doc<"messages">["status"][] = [
25
29
  "rejected",
26
30
  ];
27
31
 
28
- type Budget = { messages: number; attachments: number };
32
+ type Budget = { messages: number; attachments: number; events: number };
29
33
 
30
34
  /**
31
35
  * Remove stored bodies and attachment files of messages older than
@@ -34,17 +38,27 @@ type Budget = { messages: number; attachments: number };
34
38
  * it). Attachments stored but never linked to a message and older than the
35
39
  * cut-off go too. Bounded per call: when `more` is true, call it again.
36
40
  * `removed` counts stored files deleted.
41
+ *
42
+ * With `purge`, the rows go as well: outbound messages in a final status not
43
+ * updated since the cut-off (with their events and attachments), handled
44
+ * inbound rows (with the message each one stored), and orphan events. Never
45
+ * `queued` or `sending` messages, inbound rows in any other state,
46
+ * suppressions or unsubscribes.
37
47
  */
38
48
  export const run = mutation({
39
- args: { olderThanMs: v.number() },
49
+ args: { olderThanMs: v.number(), purge: v.optional(v.boolean()) },
40
50
  returns: v.object({ removed: v.number(), more: v.boolean() }),
41
- handler: async (ctx, { olderThanMs }) => {
51
+ handler: async (ctx, { olderThanMs, purge }) => {
42
52
  if (!Number.isFinite(olderThanMs) || olderThanMs < 0) {
43
53
  throw new Error("olderThanMs must be a non-negative number");
44
54
  }
45
55
  const now = Date.now();
46
56
  const cutoff = now - olderThanMs;
47
- const budget: Budget = { messages: BATCH, attachments: ATTACHMENT_BUDGET };
57
+ const budget: Budget = {
58
+ messages: BATCH,
59
+ attachments: ATTACHMENT_BUDGET,
60
+ events: EVENT_BUDGET,
61
+ };
48
62
  let removed = 0;
49
63
  let more = false;
50
64
 
@@ -106,6 +120,7 @@ export const run = mutation({
106
120
  ) {
107
121
  const n = await purgeMessage(ctx, message, now, budget);
108
122
  if (n === null) {
123
+ stop = true;
109
124
  more = true;
110
125
  break;
111
126
  }
@@ -129,16 +144,154 @@ export const run = mutation({
129
144
  if (loose.length > looseLimit) more = true;
130
145
  removed += await deleteAttachments(ctx, loose.slice(0, looseLimit));
131
146
 
147
+ if (purge) {
148
+ // Only on a budget the passes above left intact; otherwise the next
149
+ // call gets to it.
150
+ if (!stop && budget.messages > 0 && budget.attachments > 0) {
151
+ const r = await purgeRows(ctx, cutoff, budget);
152
+ removed += r.removed;
153
+ if (r.more) more = true;
154
+ } else {
155
+ more = true;
156
+ }
157
+ }
158
+
132
159
  return { removed, more };
133
160
  },
134
161
  });
135
162
 
163
+ /**
164
+ * The purge passes, in order: final outbound messages, handled inbound
165
+ * rows, orphan events. A pass that runs out of budget mid-way ends the
166
+ * purge for this call.
167
+ */
168
+ async function purgeRows(
169
+ ctx: MutationCtx,
170
+ cutoff: number,
171
+ budget: Budget,
172
+ ): Promise<{ removed: number; more: boolean }> {
173
+ let removed = 0;
174
+ let more = false;
175
+
176
+ // Outbound, by the last time anything happened to the message.
177
+ for (const status of PURGEABLE) {
178
+ const limit = budget.messages;
179
+ if (limit <= 0) {
180
+ more = true;
181
+ break;
182
+ }
183
+ const rows = await ctx.db
184
+ .query("messages")
185
+ .withIndex("by_status_updatedAt", (q) =>
186
+ q.eq("status", status).lt("updatedAt", cutoff),
187
+ )
188
+ .take(limit + 1);
189
+ if (rows.length > limit) more = true;
190
+ for (const message of rows.slice(0, limit)) {
191
+ const n = await deleteMessage(ctx, message, budget);
192
+ if (n === null) return { removed, more: true };
193
+ removed += n;
194
+ }
195
+ }
196
+
197
+ // Inbound the app has handled. A duplicate row deletes only itself: the
198
+ // message belongs to the row that stored it.
199
+ const inboundLimit = budget.messages;
200
+ if (inboundLimit <= 0) return { removed, more: true };
201
+ const inbound = await ctx.db
202
+ .query("inbound")
203
+ .withIndex("by_state", (q) =>
204
+ q.eq("state", "handled").lt("_creationTime", cutoff),
205
+ )
206
+ .take(inboundLimit + 1);
207
+ if (inbound.length > inboundLimit) more = true;
208
+ for (const row of inbound.slice(0, inboundLimit)) {
209
+ const message = row.messageId ? await ctx.db.get(row.messageId) : null;
210
+ if (message && message.inboundId === row._id) {
211
+ const n = await deleteMessage(ctx, message, budget);
212
+ if (n === null) return { removed, more: true };
213
+ removed += n;
214
+ }
215
+ if (row.rawStorageId !== undefined) {
216
+ await ctx.storage.delete(row.rawStorageId);
217
+ removed += 1;
218
+ }
219
+ await ctx.db.delete(row._id);
220
+ }
221
+
222
+ // Orphan events, with what is left of the event budget.
223
+ const orphanLimit = budget.events;
224
+ const orphans = await ctx.db
225
+ .query("events")
226
+ .withIndex("by_orphan", (q) =>
227
+ q.eq("orphan", true).lt("_creationTime", cutoff),
228
+ )
229
+ .take(orphanLimit + 1);
230
+ if (orphans.length > orphanLimit) more = true;
231
+ for (const event of orphans.slice(0, orphanLimit)) {
232
+ await ctx.db.delete(event._id);
233
+ }
234
+ budget.events -= Math.min(orphans.length, orphanLimit);
235
+
236
+ return { removed, more };
237
+ }
238
+
136
239
  /** Returns files deleted, or null when the attachment budget is out. */
137
240
  async function purgeMessage(
138
241
  ctx: MutationCtx,
139
242
  message: Doc<"messages">,
140
243
  now: number,
141
244
  budget: Budget,
245
+ ): Promise<number | null> {
246
+ const removed = await deleteFiles(ctx, message, budget);
247
+ if (removed === null) return null;
248
+ await ctx.db.patch(message._id, {
249
+ htmlStorageId: undefined,
250
+ textStorageId: undefined,
251
+ bodiesPurgedAt: now,
252
+ });
253
+ budget.messages -= 1;
254
+ return removed;
255
+ }
256
+
257
+ /**
258
+ * Deletes a message with its events, attachments and bodies. Returns files
259
+ * deleted, or null when a budget runs out: events deleted by then stay
260
+ * deleted, and the row stays for the next call.
261
+ */
262
+ async function deleteMessage(
263
+ ctx: MutationCtx,
264
+ message: Doc<"messages">,
265
+ budget: Budget,
266
+ ): Promise<number | null> {
267
+ const events = await ctx.db
268
+ .query("events")
269
+ .withIndex("by_message", (q) => q.eq("messageId", message._id))
270
+ .take(budget.events + 1);
271
+ for (const event of events.slice(0, budget.events)) {
272
+ await ctx.db.delete(event._id);
273
+ }
274
+ if (events.length > budget.events) {
275
+ budget.events = 0;
276
+ return null;
277
+ }
278
+ budget.events -= events.length;
279
+ const removed = await deleteFiles(ctx, message, budget);
280
+ if (removed === null) return null;
281
+ await ctx.db.delete(message._id);
282
+ budget.messages -= 1;
283
+ return removed;
284
+ }
285
+
286
+ /**
287
+ * Deletes a message's attachments (rows and files) and stored bodies,
288
+ * leaving the row to the caller. Returns files deleted, or null, with
289
+ * nothing deleted, when the attachment budget is out.
290
+ */
291
+ async function deleteFiles(
292
+ ctx: MutationCtx,
293
+ message: Doc<"messages">,
294
+ budget: Budget,
142
295
  ): Promise<number | null> {
143
296
  const attachments = await ctx.db
144
297
  .query("attachments")
@@ -152,12 +305,6 @@ async function purgeMessage(
152
305
  await ctx.storage.delete(id);
153
306
  removed += 1;
154
307
  }
155
- await ctx.db.patch(message._id, {
156
- htmlStorageId: undefined,
157
- textStorageId: undefined,
158
- bodiesPurgedAt: now,
159
- });
160
- budget.messages -= 1;
161
308
  return removed;
162
309
  }
163
310
 
@@ -23,17 +23,51 @@ export function secretStrings(value: unknown, out: string[] = []): string[] {
23
23
  return out;
24
24
  }
25
25
 
26
- /** Adapter text may echo a credential back; scrub it before it is kept. */
26
+ const base64 = (s: string): string => {
27
+ let binary = "";
28
+ for (const byte of new TextEncoder().encode(s)) {
29
+ binary += String.fromCharCode(byte);
30
+ }
31
+ return btoa(binary);
32
+ };
33
+
34
+ /** Every form a secret is likely to take when an adapter echoes it back. */
35
+ function secretForms(secret: string): string[] {
36
+ if (secret.length < 8) return [secret];
37
+ const b64 = base64(secret).replace(/=+$/, "");
38
+ return [
39
+ secret,
40
+ b64,
41
+ b64.replace(/\+/g, "-").replace(/\//g, "_"),
42
+ encodeURIComponent(secret),
43
+ JSON.stringify(secret).slice(1, -1),
44
+ ];
45
+ }
46
+
47
+ /**
48
+ * Adapter text may echo a credential back, raw or encoded (base64, base64url,
49
+ * percent-encoded or JSON-escaped); scrub it before it is kept. Secrets under
50
+ * 8 characters are removed verbatim only: their encodings are too likely to
51
+ * match ordinary text.
52
+ */
27
53
  export function redact(text: string, secrets: string[]): string {
28
54
  let out = text;
29
- for (const secret of [...new Set(secrets)].sort(
30
- (a, b) => b.length - a.length,
31
- )) {
32
- out = out.split(secret).join("[redacted]");
55
+ const forms = [...new Set(secrets)].flatMap(secretForms);
56
+ for (const form of [...new Set(forms)].sort((a, b) => b.length - a.length)) {
57
+ if (form !== "") out = out.split(form).join("[redacted]");
33
58
  }
34
59
  return out;
35
60
  }
36
61
 
62
+ /**
63
+ * Error text fit to store: secrets scrubbed, one line (no stack frames) and
64
+ * no URL that carries a query string (it may be pre-signed).
65
+ */
66
+ export function cleanError(text: string, secrets: string[]): string {
67
+ const line = redact(text, secrets).split(/\r?\n/, 1)[0] ?? "";
68
+ return line.replace(/https?:\/\/[^\s?#"'<>]*\?[^\s"'<>]*/g, "[url]");
69
+ }
70
+
37
71
  /**
38
72
  * Call the app's credentials callback. Whatever it throws is dropped: its
39
73
  * message may carry a secret, so ours is the only text that escapes.
@@ -14,10 +14,11 @@ import {
14
14
  } from "./_generated/server.js";
15
15
  import {
16
16
  CREDENTIALS_FAILED,
17
+ cleanError,
17
18
  fetchCredentials,
18
- redact,
19
19
  secretStrings,
20
20
  } from "./credentials.js";
21
+ import { adoptOrphans } from "./events.js";
21
22
 
22
23
  /** Separate lanes so a newsletter cannot delay a sign-in email. */
23
24
  const pools: Record<Stream, Workpool> = {
@@ -116,6 +117,43 @@ export const markAmbiguous = internalMutation({
116
117
  },
117
118
  });
118
119
 
120
+ /** Stored when the provider accepted a message but its result could not be recorded. */
121
+ export const RECORD_FAILED =
122
+ "the provider may have accepted this message, but its result could not be recorded";
123
+
124
+ type Accepted = { providerId: string; rfcMessageId?: string };
125
+
126
+ /**
127
+ * The one place a provider's acceptance is recorded. Acts on a message still
128
+ * in flight (`queued`, `sending`) and on a `failed` one the provider never
129
+ * acknowledged (no `providerId`): an acceptance that arrives late wins over
130
+ * the failure recorded meanwhile. Returns whether it acted.
131
+ */
132
+ async function recordSent(
133
+ ctx: MutationCtx,
134
+ message: Doc<"messages">,
135
+ result: Accepted,
136
+ ): Promise<boolean> {
137
+ const inFlight = message.status === "queued" || message.status === "sending";
138
+ const unacknowledgedFailure =
139
+ message.status === "failed" && message.providerId === undefined;
140
+ if (!inFlight && !unacknowledgedFailure) return false;
141
+ await ctx.db.patch(message._id, {
142
+ status: "sent",
143
+ providerId: result.providerId,
144
+ ...(result.rfcMessageId ? { rfcMessageId: result.rfcMessageId } : {}),
145
+ error: undefined,
146
+ // A failure that turns out to be an acceptance is no longer in doubt.
147
+ ...(unacknowledgedFailure ? { deliveryAmbiguous: undefined } : {}),
148
+ updatedAt: Date.now(),
149
+ });
150
+ // Events that arrived before the provider id was recorded apply now; they
151
+ // need the message as patched, which carries the provider id.
152
+ const patched = await ctx.db.get(message._id);
153
+ if (patched) await adoptOrphans(ctx, patched);
154
+ return true;
155
+ }
156
+
119
157
  export const record = internalMutation({
120
158
  args: {
121
159
  messageId: v.id("messages"),
@@ -131,37 +169,66 @@ export const record = internalMutation({
131
169
  handler: async (ctx, { messageId, result }) => {
132
170
  const message = await ctx.db.get(messageId);
133
171
  if (!message) return null;
134
- if (message.status !== "sending" && message.status !== "queued") {
172
+ if (result.ok) {
173
+ await recordSent(ctx, message, result);
135
174
  return null;
136
175
  }
137
- const at = Date.now();
138
- if (result.ok) {
139
- await ctx.db.patch(messageId, {
140
- status: "sent",
141
- providerId: result.providerId,
142
- ...(result.rfcMessageId ? { rfcMessageId: result.rfcMessageId } : {}),
143
- updatedAt: at,
144
- });
145
- } else {
146
- await ctx.db.patch(messageId, {
147
- status: "failed",
148
- error: capError(result.error),
149
- updatedAt: at,
150
- });
176
+ if (message.status !== "sending" && message.status !== "queued") {
177
+ return null;
151
178
  }
179
+ await ctx.db.patch(messageId, {
180
+ status: "failed",
181
+ error: capError(result.error),
182
+ updatedAt: Date.now(),
183
+ });
152
184
  return null;
153
185
  },
154
186
  });
155
187
 
156
188
  /**
157
189
  * Terminal outcome of the job. A normal run settles the message itself
158
- * (`record`); this catches the runs that ended by throwing, i.e. a retryable
159
- * failure out of attempts, a credentials failure or a crash.
190
+ * (`record`). On success `run` returns the provider's result whenever the
191
+ * provider accepted, so an acceptance `run` could not record is recorded
192
+ * here; `null` means `run` settled the message itself (or found nothing to
193
+ * do), and it is left alone. A failure catches the runs that ended by
194
+ * throwing, i.e. a retryable failure out of attempts, a credentials failure
195
+ * or a crash.
160
196
  */
161
197
  export const finish = internalMutation({
162
198
  args: vOnCompleteArgs(v.object({ messageId: v.id("messages") })),
163
199
  handler: async (ctx, { context, result }) => {
164
- if (result.kind === "success") return null;
200
+ if (result.kind === "success") {
201
+ const accepted: unknown = result.returnValue;
202
+ if (typeof accepted !== "object" || accepted === null) return null;
203
+ const message = await ctx.db.get(context.messageId);
204
+ if (!message) return null;
205
+ const { providerId, rfcMessageId } = accepted as {
206
+ providerId?: unknown;
207
+ rfcMessageId?: unknown;
208
+ };
209
+ if (typeof providerId === "string") {
210
+ await recordSent(ctx, message, {
211
+ providerId,
212
+ ...(typeof rfcMessageId === "string" ? { rfcMessageId } : {}),
213
+ });
214
+ return null;
215
+ }
216
+ // The provider accepted, but there is nothing valid to record: never
217
+ // leave the message `sending`, and never let a plain retry resend it.
218
+ if (message.status !== "sending" && message.status !== "queued") {
219
+ return null;
220
+ }
221
+ console.error(
222
+ `[convex-email] message ${context.messageId}: the provider accepted it but its result could not be recorded`,
223
+ );
224
+ await ctx.db.patch(context.messageId, {
225
+ status: "failed",
226
+ deliveryAmbiguous: true,
227
+ error: RECORD_FAILED,
228
+ updatedAt: Date.now(),
229
+ });
230
+ return null;
231
+ }
165
232
  const message = await ctx.db.get(context.messageId);
166
233
  if (!message) return null;
167
234
  if (message.status !== "sending" && message.status !== "queued") {
@@ -173,7 +240,7 @@ export const finish = internalMutation({
173
240
  // The callback's own text is never stored, however it reached us.
174
241
  const error = thrown.includes(CREDENTIALS_FAILED)
175
242
  ? CREDENTIALS_FAILED
176
- : thrown;
243
+ : cleanError(thrown, []);
177
244
  await ctx.db.patch(context.messageId, {
178
245
  status: "failed",
179
246
  error: capError(error),
@@ -241,7 +308,7 @@ async function readText(ctx: ActionCtx, id: Id<"_storage"> | undefined) {
241
308
 
242
309
  export const run = internalAction({
243
310
  args: { messageId: v.id("messages") },
244
- handler: async (ctx, { messageId }): Promise<null> => {
311
+ handler: async (ctx, { messageId }): Promise<Accepted | null> => {
245
312
  const loaded: Loaded | null = await ctx.runQuery(internal.deliver.load, {
246
313
  messageId,
247
314
  });
@@ -338,14 +405,14 @@ export const run = internalAction({
338
405
  // whether the provider got the message, so it counts as ambiguous.
339
406
  await ctx.runMutation(internal.deliver.markAmbiguous, { messageId });
340
407
  throw new Error(
341
- redact(e instanceof Error ? e.message : String(e), secrets),
408
+ cleanError(e instanceof Error ? e.message : String(e), secrets),
342
409
  );
343
410
  }
344
411
  if (!result.ok && result.ambiguous) {
345
412
  await ctx.runMutation(internal.deliver.markAmbiguous, { messageId });
346
413
  }
347
414
  if (!result.ok) {
348
- const error = redact(result.error, secrets);
415
+ const error = cleanError(result.error, secrets);
349
416
  // Throwing hands the job back to the Workpool for another attempt.
350
417
  if (result.retryable) throw new Error(error);
351
418
  return await fail(error);
@@ -354,27 +421,29 @@ export const run = internalAction({
354
421
  // The provider has the message. From here nothing may throw, or Workpool
355
422
  // would rerun the action and send it again. A crash between the provider
356
423
  // call and `record` remains at-least-once (adapters add idempotency keys).
424
+ // The result goes back to Workpool too: `finish` records it if `record`
425
+ // could not, or marks the message failed and ambiguous.
426
+ const accepted = (): Accepted => ({
427
+ providerId: result.providerId,
428
+ rfcMessageId: result.rfcMessageId,
429
+ });
357
430
  const recordArgs = () => ({
358
431
  messageId,
359
- result: {
360
- ok: true as const,
361
- providerId: result.providerId,
362
- rfcMessageId: result.rfcMessageId,
363
- },
432
+ result: { ok: true as const, ...accepted() },
364
433
  });
365
434
  for (let attempt = 0; attempt < 3; attempt++) {
366
435
  try {
367
436
  await ctx.runMutation(internal.deliver.record, recordArgs());
368
- return null;
437
+ return accepted();
369
438
  } catch {
370
439
  // try again
371
440
  }
372
441
  }
373
- try {
374
- await ctx.scheduler.runAfter(0, internal.deliver.record, recordArgs());
375
- } catch {
376
- // Nothing more to do without risking a resend.
377
- }
378
- return null;
442
+ const { providerId } = accepted();
443
+ console.error(
444
+ "[convex-email] recording a provider acceptance failed; finish will settle it",
445
+ { messageId, providerId },
446
+ );
447
+ return accepted();
379
448
  },
380
449
  });
@@ -80,6 +80,108 @@ async function suppress(
80
80
  }
81
81
  }
82
82
 
83
+ /**
84
+ * Apply an event to the message it matched: the Message-ID, the status (by
85
+ * rank), suppression and the app's `onEvent`. The caller stores the event row.
86
+ */
87
+ export async function applyMatched(
88
+ ctx: MutationCtx,
89
+ config: Doc<"config"> | null,
90
+ message: Doc<"messages">,
91
+ event: NormalizedEvent,
92
+ ): Promise<void> {
93
+ const patch: Partial<Doc<"messages">> = {};
94
+ if (
95
+ event.rfcMessageId &&
96
+ event.rfcMessageId !== message.rfcMessageId &&
97
+ // Never trade a real Message-ID (has "@") for a bare provider id.
98
+ !(
99
+ event.rfcMessageId.includes("@") === false &&
100
+ message.rfcMessageId?.includes("@")
101
+ )
102
+ ) {
103
+ // SES's Send event names the Message-ID it actually used.
104
+ patch.rfcMessageId = event.rfcMessageId;
105
+ }
106
+ if (RANK[event.type] > RANK[message.status]) patch.status = event.type;
107
+ if (Object.keys(patch).length > 0) {
108
+ await ctx.db.patch(message._id, { ...patch, updatedAt: Date.now() });
109
+ }
110
+
111
+ const reason = suppressionReason(event);
112
+ if (reason) await suppress(ctx, message, event, reason);
113
+
114
+ if (config?.onEventHandle) {
115
+ const forApp: EventForApp = {
116
+ messageId: message._id,
117
+ type: event.type,
118
+ bounceType: event.bounceType,
119
+ at: event.at,
120
+ tags: message.tags,
121
+ };
122
+ // The app's handler arrives as a function handle string, which
123
+ // Workpool accepts in place of a reference.
124
+ const handler = config.onEventHandle as unknown as FunctionReference<
125
+ "mutation",
126
+ "internal",
127
+ EventForApp,
128
+ unknown
129
+ >;
130
+ await callbacks.enqueueMutation(ctx, handler, forApp);
131
+ }
132
+ }
133
+
134
+ /** Orphans adopted per recorded send; more than this for one id is not a real case. */
135
+ const MAX_ADOPT = 100;
136
+
137
+ /**
138
+ * Apply the events that arrived before this message's provider id was
139
+ * recorded (stored as orphans). Takes the message as it is after the id was
140
+ * recorded. Only orphans from an account-level route or the message's own
141
+ * tenant's route are adopted, the same rule `apply` matches by.
142
+ */
143
+ export async function adoptOrphans(
144
+ ctx: MutationCtx,
145
+ message: Doc<"messages">,
146
+ ): Promise<void> {
147
+ const { provider, providerId } = message;
148
+ if (provider === "raw" || providerId === undefined) return;
149
+ const config = await getConfig(ctx);
150
+ const orphans = await ctx.db
151
+ .query("events")
152
+ .withIndex("by_provider_providerId_orphan", (q) =>
153
+ q
154
+ .eq("provider", provider)
155
+ .eq("providerId", providerId)
156
+ .eq("orphan", true),
157
+ )
158
+ .take(MAX_ADOPT);
159
+ for (const orphan of orphans) {
160
+ if (orphan.tenant !== undefined && orphan.tenant !== message.tenant) {
161
+ continue;
162
+ }
163
+ await ctx.db.patch(orphan._id, {
164
+ messageId: message._id,
165
+ orphan: false,
166
+ recipients: undefined,
167
+ rfcMessageId: undefined,
168
+ });
169
+ // The previous event may have moved the status.
170
+ const current = await ctx.db.get(message._id);
171
+ if (!current) return;
172
+ await applyMatched(ctx, config, current, {
173
+ providerId: orphan.providerId,
174
+ providerEventId: orphan.providerEventId,
175
+ type: orphan.type,
176
+ bounceType: orphan.bounceType,
177
+ at: orphan.at,
178
+ detail: orphan.detail,
179
+ recipients: orphan.recipients ?? [],
180
+ rfcMessageId: orphan.rfcMessageId,
181
+ });
182
+ }
183
+ }
184
+
83
185
  export const apply = internalMutation({
84
186
  args: {
85
187
  provider: vProviderName,
@@ -125,7 +227,14 @@ export const apply = internalMutation({
125
227
  detail: event.detail,
126
228
  };
127
229
  if (!message) {
128
- await ctx.db.insert("events", { ...row, orphan: true });
230
+ // Possibly early: the send may not have recorded its provider id
231
+ // yet. Keep what `adoptOrphans` needs to apply it when it does.
232
+ await ctx.db.insert("events", {
233
+ ...row,
234
+ orphan: true,
235
+ recipients: event.recipients,
236
+ rfcMessageId: event.rfcMessageId,
237
+ });
129
238
  continue;
130
239
  }
131
240
  await ctx.db.insert("events", {
@@ -133,46 +242,7 @@ export const apply = internalMutation({
133
242
  messageId: message._id,
134
243
  orphan: false,
135
244
  });
136
-
137
- const patch: Partial<Doc<"messages">> = {};
138
- if (
139
- event.rfcMessageId &&
140
- event.rfcMessageId !== message.rfcMessageId &&
141
- // Never trade a real Message-ID (has "@") for a bare provider id.
142
- !(
143
- event.rfcMessageId.includes("@") === false &&
144
- message.rfcMessageId?.includes("@")
145
- )
146
- ) {
147
- // SES's Send event names the Message-ID it actually used.
148
- patch.rfcMessageId = event.rfcMessageId;
149
- }
150
- if (RANK[event.type] > RANK[message.status]) patch.status = event.type;
151
- if (Object.keys(patch).length > 0) {
152
- await ctx.db.patch(message._id, { ...patch, updatedAt: Date.now() });
153
- }
154
-
155
- const reason = suppressionReason(event);
156
- if (reason) await suppress(ctx, message, event, reason);
157
-
158
- if (config?.onEventHandle) {
159
- const forApp: EventForApp = {
160
- messageId: message._id,
161
- type: event.type,
162
- bounceType: event.bounceType,
163
- at: event.at,
164
- tags: message.tags,
165
- };
166
- // The app's handler arrives as a function handle string, which
167
- // Workpool accepts in place of a reference.
168
- const handler = config.onEventHandle as unknown as FunctionReference<
169
- "mutation",
170
- "internal",
171
- EventForApp,
172
- unknown
173
- >;
174
- await callbacks.enqueueMutation(ctx, handler, forApp);
175
- }
245
+ await applyMatched(ctx, config, message, event);
176
246
  }
177
247
  return null;
178
248
  },