@k2b/cloud 0.27.0 → 0.28.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.
Files changed (79) hide show
  1. package/package.json +2 -2
  2. package/src/ai/browser-code-contracts.ts +33 -63
  3. package/src/ai/browser.ts +1 -0
  4. package/src/ai/chat/blocks.tsx +16 -7
  5. package/src/ai/chat/live-turn.browser-harness.tsx +6 -3
  6. package/src/ai/chat/message-actions.tsx +123 -101
  7. package/src/ai/chat/message-utils.ts +30 -1
  8. package/src/ai/chat/messages.ts +198 -0
  9. package/src/ai/chat/presentation.tsx +66 -20
  10. package/src/ai/chat/tool-groups.ts +1 -1
  11. package/src/ai/chat/turn-error.ts +21 -0
  12. package/src/ai/chat/turn-view.tsx +55 -4
  13. package/src/ai/chat/user-message.tsx +19 -14
  14. package/src/ai/chat/visual-tools.tsx +1 -1
  15. package/src/ai/client/controller.ts +23 -6
  16. package/src/ai/code-mode-skill.ts +21 -25
  17. package/src/ai/code-runtime-tools.ts +5 -1
  18. package/src/ai/code-source-contracts.ts +2 -2
  19. package/src/ai/data-analysis-skill.ts +3 -3
  20. package/src/ai/default-tools.ts +15 -16
  21. package/src/ai/executor.ts +135 -59
  22. package/src/ai/index.ts +2 -0
  23. package/src/ai/open-tool-calls.ts +87 -0
  24. package/src/ai/routes.ts +6 -0
  25. package/src/ai/run-timeout.ts +4 -5
  26. package/src/ai/runtime.ts +8 -0
  27. package/src/ai/skill-seeds.ts +4 -4
  28. package/src/ai/store.ts +46 -14
  29. package/src/ai/system-prompt.ts +4 -21
  30. package/src/ai/turn-failure.ts +100 -0
  31. package/src/ai/turn-policy.ts +2 -1
  32. package/src/ai/types.ts +28 -1
  33. package/src/api/admin-outgoing-mail.ts +185 -5
  34. package/src/browser/FileChooser.tsx +11 -0
  35. package/src/browser/file-chooser-messages.ts +2 -0
  36. package/src/cli/admin/index.ts +3 -1
  37. package/src/cli/admin/notifications.ts +6 -0
  38. package/src/cli/admin/outgoing-mail.ts +104 -7
  39. package/src/contracts/outgoing-mail.ts +189 -1
  40. package/src/services/help/store.ts +2 -1
  41. package/src/services/index.ts +11 -1
  42. package/src/services/notifications/batches.ts +139 -79
  43. package/src/services/notifications/channels.ts +33 -13
  44. package/src/services/notifications/dispatcher.ts +57 -5
  45. package/src/services/notifications/email-frame.fixture.html +51 -0
  46. package/src/services/notifications/{email.ts → email-frame.ts} +12 -35
  47. package/src/services/notifications/email-mail.ts +101 -0
  48. package/src/services/notifications/index.ts +49 -36
  49. package/src/services/notifications/observability.ts +9 -1
  50. package/src/services/notifications/platform.ts +1 -1
  51. package/src/services/notifications/runtime.ts +9 -3
  52. package/src/services/outgoing-mail/admin.ts +84 -0
  53. package/src/services/outgoing-mail/attachments.ts +135 -0
  54. package/src/services/outgoing-mail/bulk.ts +11 -0
  55. package/src/services/outgoing-mail/dispatcher.ts +231 -0
  56. package/src/services/outgoing-mail/drain.ts +60 -0
  57. package/src/services/outgoing-mail/enqueue.ts +180 -0
  58. package/src/services/outgoing-mail/index.ts +103 -10
  59. package/src/services/outgoing-mail/message.ts +14 -0
  60. package/src/services/outgoing-mail/messages.ts +431 -0
  61. package/src/services/outgoing-mail/retention.ts +48 -0
  62. package/src/services/outgoing-mail/runtime.ts +72 -0
  63. package/src/services/outgoing-mail/send.ts +130 -0
  64. package/src/services/outgoing-mail/store.ts +115 -4
  65. package/src/services/outgoing-mail/sync.ts +39 -0
  66. package/src/services/outgoing-mail/transport.ts +5 -1
  67. package/src/services/pdf/markdown.ts +22 -4
  68. package/src/services/postgres.ts +15 -0
  69. package/src/services/settings/core-settings.ts +18 -0
  70. package/src/shared/ai-platform-prompt.ts +48 -4
  71. package/src/shared/markdown/extensions/links.ts +28 -20
  72. package/src/shared/markdown/index.ts +14 -5
  73. package/src/shared/markdown/shared.ts +0 -7
  74. package/src/ssr/GlobalAnnouncements.island.tsx +1 -1
  75. package/src/ssr/platform-messages.ts +1 -1
  76. package/src/styles/effects.css +15 -17
  77. package/src/styles/tokens.css +2 -0
  78. package/src/styles/utilities-markdown-editor.css +4 -39
  79. package/src/styles/utilities-markdown-table.css +14 -17
@@ -0,0 +1,101 @@
1
+ import { domainToASCII } from "node:url";
2
+ import type { ZodError } from "zod";
3
+ import { type MailMessage, MailMessageSchema, type MailRecord } from "../../contracts/outgoing-mail";
4
+ import { messageRecord, outgoingMailMessages } from "../outgoing-mail/messages";
5
+ import { sendMail } from "../outgoing-mail/send";
6
+ import { OutgoingMailError } from "../outgoing-mail/store";
7
+ import { prepareNotificationEmail } from "./email-frame";
8
+
9
+ export const notificationMailError = (error: unknown): Error & { code: string; retryable: boolean } => {
10
+ const code = error instanceof OutgoingMailError ? error.code : "mail_unavailable";
11
+ return Object.assign(new Error(error instanceof Error ? error.message : "Outgoing mail is unavailable."), {
12
+ code,
13
+ retryable: ["mail_unavailable", "backlog_full", "quota_exceeded", "attachment_storage_full"].includes(code),
14
+ });
15
+ };
16
+
17
+ export const normalizeNotificationMail = (to: string, subject: string) => {
18
+ const separator = to.lastIndexOf("@");
19
+ const domain = separator < 0 ? "" : to.slice(separator + 1);
20
+ // URL conversion can discard invalid address characters; leave those for validation.
21
+ const ascii = domain && !/[^\p{L}\p{N}\p{M}.-]/u.test(domain) ? domainToASCII(domain) : "";
22
+ return {
23
+ to: [ascii ? `${to.slice(0, separator + 1)}${ascii}` : to],
24
+ subject: subject
25
+ .replace(/[\r\n]+/g, " ")
26
+ .replace(/\0/g, "")
27
+ .trim()
28
+ .slice(0, 998),
29
+ };
30
+ };
31
+
32
+ export const notificationMailValidationError = (error: ZodError) =>
33
+ new OutgoingMailError(
34
+ "bad_input",
35
+ `Invalid notification email: ${error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ")}`,
36
+ 400,
37
+ );
38
+
39
+ const notificationMailMessage = async (
40
+ to: string,
41
+ subject: string,
42
+ body: { content?: string; rawHtml?: string },
43
+ key?: string,
44
+ ): Promise<MailMessage> => {
45
+ const parsed = MailMessageSchema.safeParse({
46
+ ...normalizeNotificationMail(to, subject),
47
+ ...(await prepareNotificationEmail(body)),
48
+ ...(key ? { key } : {}),
49
+ });
50
+ if (!parsed.success) throw notificationMailValidationError(parsed.error);
51
+ return parsed.data;
52
+ };
53
+
54
+ export const sendNotificationMail = async (
55
+ to: string,
56
+ subject: string,
57
+ body: { content?: string; rawHtml?: string },
58
+ key?: string,
59
+ signal?: AbortSignal,
60
+ ): Promise<MailRecord> => {
61
+ try {
62
+ return await sendMail("core", await notificationMailMessage(to, subject, body, key), signal, { trustedHtml: true });
63
+ } catch (error) {
64
+ throw notificationMailError(error);
65
+ }
66
+ };
67
+
68
+ export const notificationMailOutcome = async (record: MailRecord) => {
69
+ const row = await outgoingMailMessages.read(record.id, "core").catch(() => undefined);
70
+ const status = row?.status ?? record.status;
71
+ const errorCode = row?.error_code ?? (record.error ? "smtp_failed" : null);
72
+ const errorMessage = row?.error_message ?? row?.smtp_response ?? record.error ?? null;
73
+ if (status === "sent" || status === "bounced") return { status: "delivered" as const, outgoingMailId: record.id };
74
+ if (status === "failed" || status === "cancelled") {
75
+ throw Object.assign(new Error(errorMessage ?? `Outgoing mail ${status}.`), {
76
+ code: errorCode ?? "smtp_failed",
77
+ retryable: false,
78
+ outgoingMailId: record.id,
79
+ });
80
+ }
81
+ const next = row?.next_attempt_at ? new Date(row.next_attempt_at).getTime() - Date.now() : 60_000;
82
+ // Keep polling within the notification retry interval bounds.
83
+ const retryAfterMs = Number.isFinite(next) ? Math.min(5 * 60_000, Math.max(2_000, next)) : 60_000;
84
+ return { status: "pending" as const, outgoingMailId: record.id, retryAfterMs, errorMessage };
85
+ };
86
+
87
+ export const notificationMailOutcomeById = async (id: string) => {
88
+ const row = await outgoingMailMessages.read(id, "core").catch((error: unknown) => {
89
+ throw notificationMailError(error);
90
+ });
91
+ if (!row) {
92
+ // Retention may remove a settled mail before notification recovery. Its
93
+ // stored identity must never turn that recovery into another SMTP send.
94
+ throw Object.assign(new Error("Outgoing mail record is no longer available."), {
95
+ code: "smtp_failed",
96
+ retryable: false,
97
+ outgoingMailId: id,
98
+ });
99
+ }
100
+ return notificationMailOutcome(messageRecord(row));
101
+ };
@@ -4,7 +4,7 @@ import type { BoundNotificationDefinition, NotificationRecipientKind, Notificati
4
4
  import type { PaginationParams } from "../../contracts/shared";
5
5
  import { logger } from "../logging";
6
6
  import { escapeLikePattern } from "../postgres";
7
- import { sendEmail } from "./email";
7
+ import { notificationMailOutcome, sendNotificationMail } from "./email-mail";
8
8
  import "./browser";
9
9
  import { notificationObservability } from "./observability";
10
10
  import { sendTypedNotification, type TypedNotificationSendResult } from "./platform";
@@ -107,6 +107,26 @@ type DbNotificationRow = {
107
107
  sent_by_name: string | null;
108
108
  };
109
109
 
110
+ type LegacyMailRow = { id: string; type: NotificationType; recipient: string; subject: string; content: string; mail_generation: number };
111
+
112
+ const deliverLegacyMail = async (row: LegacyMailRow, body: { content?: string; rawHtml?: string }) => {
113
+ const key = `notification-message:${row.id}${row.mail_generation ? `:${row.mail_generation}` : ""}`;
114
+ try {
115
+ const record = await sendNotificationMail(row.recipient, row.subject, body, key);
116
+ await sql`UPDATE notifications.messages SET outgoing_mail_id = ${record.id}::uuid, sent_at = NULL, error = NULL
117
+ WHERE id = ${row.id}::uuid AND mail_generation = ${row.mail_generation}`;
118
+ const outcome = await notificationMailOutcome(record);
119
+ if (outcome.status === "pending") return "pending" as const;
120
+ await sql`UPDATE notifications.messages SET sent_at = now(), error = NULL
121
+ WHERE id = ${row.id}::uuid AND mail_generation = ${row.mail_generation}`;
122
+ return "sent" as const;
123
+ } catch (error) {
124
+ await sql`UPDATE notifications.messages SET sent_at = NULL, error = ${error instanceof Error ? error.message : String(error)}
125
+ WHERE id = ${row.id}::uuid AND mail_generation = ${row.mail_generation}`;
126
+ throw error;
127
+ }
128
+ };
129
+
110
130
  /**
111
131
  * Send a notification. Persists to DB, attempts delivery (if autoSend=true), updates sent_at/error.
112
132
  */
@@ -130,15 +150,11 @@ const sendLegacy = async (params: SendNotificationParams): Promise<SendNotificat
130
150
 
131
151
  // Attempt delivery
132
152
  try {
133
- if (type === "email") {
134
- await sendEmail(recipient, subject, { content, rawHtml });
135
- }
136
- await sql`UPDATE notifications.messages SET sent_at = now(), error = NULL WHERE id = ${id}`;
137
- return { id, status: "sent" };
153
+ const status = await deliverLegacyMail({ id, type, recipient, subject, content: dbContent, mail_generation: 0 }, { content, rawHtml });
154
+ return { id, status };
138
155
  } catch (e) {
139
156
  const error = e instanceof Error ? e.message : String(e);
140
157
  log.error("Failed to send", { type, recipient, error });
141
- await sql`UPDATE notifications.messages SET error = ${error} WHERE id = ${id}`;
142
158
  return { id, status: "error", error };
143
159
  }
144
160
  };
@@ -482,23 +498,26 @@ export const getById = async (id: string): Promise<NotificationMessage | null> =
482
498
  * Resend a notification (retry delivery).
483
499
  */
484
500
  export const resend = async (id: string): Promise<{ ok: true } | { ok: false; code: "not_found" | "delivery_failed"; error: string }> => {
485
- const notification = await getById(id);
486
- if (!notification) {
487
- return { ok: false, code: "not_found", error: "Notification not found" };
488
- }
489
-
501
+ const notification = await sql.begin(async (tx): Promise<(LegacyMailRow & { current_mail_status: string | null }) | undefined> => {
502
+ const [row] = await tx<(LegacyMailRow & { outgoing_mail_id: string | null; current_mail_status: string | null })[]>`
503
+ SELECT m.*, mail.status AS current_mail_status FROM notifications.messages m
504
+ LEFT JOIN outgoing_mail.messages mail ON mail.id = m.outgoing_mail_id
505
+ WHERE m.id = ${id}::uuid FOR UPDATE OF m
506
+ `;
507
+ if (!row || row.current_mail_status === "queued" || row.current_mail_status === "sending" || !row.outgoing_mail_id) return row;
508
+ const [updated] = await tx<LegacyMailRow[]>`
509
+ UPDATE notifications.messages SET mail_generation = mail_generation + 1, outgoing_mail_id = NULL, sent_at = NULL, error = NULL
510
+ WHERE id = ${id}::uuid RETURNING *
511
+ `;
512
+ return updated ? { ...updated, current_mail_status: null } : undefined;
513
+ });
514
+ if (!notification) return { ok: false, code: "not_found", error: "Notification not found" };
515
+ if (["queued", "sending"].includes(notification.current_mail_status ?? "")) return { ok: true };
490
516
  try {
491
- if (notification.type === "email") {
492
- await sendEmail(notification.recipient, notification.subject, {
493
- rawHtml: notification.content,
494
- });
495
- }
496
- await sql`UPDATE notifications.messages SET sent_at = now(), error = NULL WHERE id = ${id}`;
517
+ await deliverLegacyMail(notification, { rawHtml: notification.content });
497
518
  return { ok: true };
498
519
  } catch (e) {
499
- const error = e instanceof Error ? e.message : String(e);
500
- await sql`UPDATE notifications.messages SET error = ${error} WHERE id = ${id}`;
501
- return { ok: false, code: "delivery_failed", error };
520
+ return { ok: false, code: "delivery_failed", error: e instanceof Error ? e.message : String(e) };
502
521
  }
503
522
  };
504
523
 
@@ -535,7 +554,9 @@ export const update = async (
535
554
  subject = COALESCE(${data.subject ?? null}, subject),
536
555
  content = COALESCE(${data.content ?? null}, content),
537
556
  recipient = COALESCE(${data.recipient ?? null}, recipient),
538
- error = CASE WHEN ${clearError} THEN NULL ELSE error END
557
+ error = CASE WHEN ${clearError} THEN NULL ELSE error END,
558
+ mail_generation = CASE WHEN ${clearError} THEN mail_generation + 1 ELSE mail_generation END,
559
+ outgoing_mail_id = CASE WHEN ${clearError} THEN NULL ELSE outgoing_mail_id END
539
560
  WHERE id = ${id}
540
561
  `;
541
562
 
@@ -548,7 +569,7 @@ export const update = async (
548
569
  export const getPendingSystemCount = async (): Promise<number> => {
549
570
  const rows = await sql`
550
571
  SELECT COUNT(*)::int as count FROM notifications.messages
551
- WHERE sent_at IS NULL AND error IS NULL AND sent_by IS NULL
572
+ WHERE sent_at IS NULL AND error IS NULL AND sent_by IS NULL AND outgoing_mail_id IS NULL
552
573
  `;
553
574
  return rows[0]?.count ?? 0;
554
575
  };
@@ -563,10 +584,10 @@ export const sendAllPendingSystem = async (): Promise<{
563
584
  errors: { id: string; recipient: string; error: string }[];
564
585
  }> => {
565
586
  // Get all pending system notifications
566
- const rows = await sql`
567
- SELECT id, type, recipient, subject, content
587
+ const rows = await sql<LegacyMailRow[]>`
588
+ SELECT id, type, recipient, subject, content, mail_generation
568
589
  FROM notifications.messages
569
- WHERE sent_at IS NULL AND error IS NULL AND sent_by IS NULL
590
+ WHERE sent_at IS NULL AND error IS NULL AND sent_by IS NULL AND outgoing_mail_id IS NULL
570
591
  ORDER BY created_at ASC
571
592
  `;
572
593
 
@@ -575,21 +596,13 @@ export const sendAllPendingSystem = async (): Promise<{
575
596
  const errors: { id: string; recipient: string; error: string }[] = [];
576
597
 
577
598
  for (const row of rows) {
578
- const id = row.id as string;
579
- const type = row.type as NotificationType;
580
- const recipient = row.recipient as string;
581
- const subject = row.subject as string;
582
- const content = row.content as string;
599
+ const { id, recipient, content } = row;
583
600
 
584
601
  try {
585
- if (type === "email") {
586
- await sendEmail(recipient, subject, { rawHtml: content });
587
- }
588
- await sql`UPDATE notifications.messages SET sent_at = now(), error = NULL WHERE id = ${id}`;
602
+ if ((await deliverLegacyMail(row, { rawHtml: content })) === "pending") continue;
589
603
  sent++;
590
604
  } catch (e) {
591
605
  const error = e instanceof Error ? e.message : String(e);
592
- await sql`UPDATE notifications.messages SET error = ${error} WHERE id = ${id}`;
593
606
  failed++;
594
607
  errors.push({ id, recipient, error });
595
608
  }
@@ -1,4 +1,5 @@
1
1
  import { type SQL, sql } from "bun";
2
+ import type { MailStatus } from "../../contracts/outgoing-mail";
2
3
  import type { NotificationDeliveryStatus } from "../../contracts/user-notifications";
3
4
  import { escapeLikePattern, toPgTextArray } from "../postgres";
4
5
 
@@ -20,6 +21,8 @@ export type NotificationDeliveryObservabilityItem = {
20
21
  required: boolean;
21
22
  routePriority: number | null;
22
23
  status: NotificationDeliveryStatus;
24
+ outgoingMailId: string | null;
25
+ outgoingMailStatus: MailStatus | null;
23
26
  attemptCount: number;
24
27
  errorCode: string | null;
25
28
  errorMessage: string | null;
@@ -79,6 +82,8 @@ type DeliveryRow = {
79
82
  required: boolean;
80
83
  route_priority: number | null;
81
84
  status: NotificationDeliveryStatus;
85
+ outgoing_mail_id: string | null;
86
+ outgoing_mail_status: MailStatus | null;
82
87
  attempt_count: number;
83
88
  error_code: string | null;
84
89
  error_message: string | null;
@@ -168,11 +173,12 @@ const listDeliveries = async (input: {
168
173
  COALESCE(NULLIF(u.display_name, ''), NULLIF(u.uid, ''), e.recipient_email, e.recipient_key) AS recipient_label,
169
174
  COALESCE(NULLIF(u.mail, ''), NULLIF(u.uid, ''), e.recipient_email, e.recipient_key) AS recipient_reference,
170
175
  d.channel, d.destination_label, d.required, d.route_priority, d.status,
171
- d.attempt_count, d.error_code, d.error_message, d.created_at, d.updated_at, d.delivered_at
176
+ d.outgoing_mail_id, mail.status AS outgoing_mail_status, d.attempt_count, d.error_code, d.error_message, d.created_at, d.updated_at, d.delivered_at
172
177
  FROM notifications.deliveries d
173
178
  JOIN notifications.events e ON e.id = d.event_id
174
179
  JOIN notifications.definitions n ON n.id = e.definition_id
175
180
  LEFT JOIN auth.users u ON u.id = e.recipient_user_id
181
+ LEFT JOIN outgoing_mail.messages mail ON mail.id = d.outgoing_mail_id
176
182
  WHERE ${where}
177
183
  ORDER BY d.created_at DESC, d.id DESC
178
184
  LIMIT ${perPage} OFFSET ${offset}
@@ -196,6 +202,8 @@ const listDeliveries = async (input: {
196
202
  required: row.required,
197
203
  routePriority: row.route_priority,
198
204
  status: row.status,
205
+ outgoingMailId: row.outgoing_mail_id,
206
+ outgoingMailStatus: row.outgoing_mail_status,
199
207
  attemptCount: row.attempt_count,
200
208
  errorCode: row.error_code,
201
209
  errorMessage: row.error_message,
@@ -407,7 +407,7 @@ export const sendTypedNotification = async <
407
407
  if (persisted.prepared) {
408
408
  for (const deliveryId of persisted.requiredIds) {
409
409
  const result = await processNotificationDelivery(deliveryId);
410
- if (result.status === "retry") await enqueueNotificationDelivery(deliveryId, result.retryAfterMs);
410
+ if (result.status === "retry" || result.status === "pending") await enqueueNotificationDelivery(deliveryId, result.retryAfterMs);
411
411
  if (result.activatedIds?.length) await enqueueNotificationDeliveries(result.activatedIds);
412
412
  }
413
413
  await enqueueNotificationDeliveries(persisted.pendingIds);
@@ -3,7 +3,7 @@ import { lazySync } from "../../_internal/process-sync";
3
3
  import { logger, trace } from "../logging";
4
4
  import { createRuntimeLifecycle, createRuntimeTaskTracker, stopRuntimeJobs } from "../runtime-lifecycle";
5
5
 
6
- import { processNotificationDelivery, recoverNotificationDeliveries } from "./dispatcher";
6
+ import { processNotificationDelivery, reconcileNotificationMessages, recoverNotificationDeliveries } from "./dispatcher";
7
7
 
8
8
  type DeliveryMessage = { deliveryId: string };
9
9
 
@@ -58,10 +58,10 @@ const handleDelivery = async (context: JobContext<DeliveryMessage>): Promise<voi
58
58
  spanKey: trace.syncSpanKey("job", "cloud-notification-deliveries", context.jobId),
59
59
  attributes: { "cloud.notification.delivery_id": context.input.deliveryId },
60
60
  },
61
- () => processNotificationDelivery(context.input.deliveryId),
61
+ () => processNotificationDelivery(context.input.deliveryId, context.signal),
62
62
  );
63
63
  if (result.activatedIds?.length) await enqueueNotificationDeliveries(result.activatedIds);
64
- if (result.status === "retry") context.resubmit({ delayMs: result.retryAfterMs });
64
+ if (result.status === "retry" || result.status === "pending") context.resubmit({ delayMs: result.retryAfterMs });
65
65
  };
66
66
 
67
67
  type RuntimeOptions = { concurrency?: number; recoveryIntervalMs?: number };
@@ -79,6 +79,12 @@ const recover = (): Promise<void> => {
79
79
  } catch (error) {
80
80
  log.error("Delivery recovery failed", { error: error instanceof Error ? error.message : String(error) });
81
81
  }
82
+ // Message history must never hold back delivery recovery.
83
+ try {
84
+ await reconcileNotificationMessages();
85
+ } catch (error) {
86
+ log.error("Notification message reconciliation failed", { error: error instanceof Error ? error.message : String(error) });
87
+ }
82
88
  }) ?? Promise.resolve()
83
89
  ).finally(() => {
84
90
  recovery = undefined;
@@ -0,0 +1,84 @@
1
+ import { sql } from "bun";
2
+ import {
3
+ type AdminMailFilter,
4
+ type AdminMailRecord,
5
+ AdminMailRecordSchema,
6
+ type MailPage,
7
+ type MailPageParams,
8
+ } from "../../contracts/outgoing-mail";
9
+ import { audit } from "../audit";
10
+ import { cleanupMailAttachments, publishMailSettled } from "./dispatcher";
11
+ import { adminMessageRecord, type MessageRow, outgoingMailMessages } from "./messages";
12
+ import { type MailAuditContext, OutgoingMailError } from "./store";
13
+
14
+ const get = async (id: string): Promise<AdminMailRecord> => {
15
+ const record = await outgoingMailMessages.metadata(id);
16
+ if (!record) throw new OutgoingMailError("message_unknown", "Outgoing mail message does not exist.", 404);
17
+ return record;
18
+ };
19
+ const cancel = async (id: string, context: MailAuditContext): Promise<AdminMailRecord> => {
20
+ const row = await sql.begin(async (tx) => {
21
+ const [row] = await tx<MessageRow[]>`UPDATE outgoing_mail.messages SET status = 'cancelled', error_code = 'cancelled_by_admin',
22
+ error_message = 'Cancelled by an administrator.', next_attempt_at = NULL, updated_at = now() WHERE id = ${id}::uuid AND status = 'queued'
23
+ RETURNING *, created_at::text AS cursor_created_at`;
24
+ if (!row) {
25
+ if (!(await outgoingMailMessages.read(id, undefined, tx)))
26
+ throw new OutgoingMailError("message_unknown", "Outgoing mail message does not exist.", 404);
27
+ throw new OutgoingMailError("message_not_queued", "Only queued outgoing mail can be cancelled.", 409);
28
+ }
29
+ await audit.record(
30
+ {
31
+ ...context,
32
+ action: "outgoing_mail.message.cancel",
33
+ outcome: "allowed",
34
+ target: { type: "outgoing_mail_message", id },
35
+ metadata: { appId: row.app_id, profile: row.profile_key },
36
+ },
37
+ tx,
38
+ );
39
+ return row;
40
+ });
41
+ await cleanupMailAttachments(id).catch(() => {});
42
+ await publishMailSettled(id).catch(() => {});
43
+ return adminMessageRecord(row);
44
+ };
45
+ export const outgoingMailLog = {
46
+ get,
47
+ cancel,
48
+ async cancelBatch(batchId: string, context: MailAuditContext): Promise<{ batchId: string; cancelled: number }> {
49
+ const cancelled = await sql.begin(async (tx) => {
50
+ const apps = await tx<{ app_id: string }[]>`SELECT DISTINCT app_id FROM outgoing_mail.messages WHERE batch_id = ${batchId}::uuid`;
51
+ if (!apps.length) throw new OutgoingMailError("batch_unknown", "Outgoing mail batch does not exist.", 404);
52
+ const rows = await tx<{ id: string }[]>`UPDATE outgoing_mail.messages SET status = 'cancelled', error_code = 'cancelled_by_admin',
53
+ error_message = 'Cancelled by an administrator.', next_attempt_at = NULL, updated_at = now()
54
+ WHERE batch_id = ${batchId}::uuid AND status = 'queued' RETURNING id`;
55
+ await audit.record(
56
+ {
57
+ ...context,
58
+ action: "outgoing_mail.batch.cancel",
59
+ outcome: "allowed",
60
+ target: { type: "outgoing_mail_batch", id: batchId },
61
+ metadata: { appIds: apps.map((row) => row.app_id), count: rows.length },
62
+ },
63
+ tx,
64
+ );
65
+ return rows;
66
+ });
67
+ for (const row of cancelled) {
68
+ await cleanupMailAttachments(row.id).catch(() => {});
69
+ await publishMailSettled(row.id).catch(() => {});
70
+ }
71
+ return { batchId, cancelled: cancelled.length };
72
+ },
73
+ content: outgoingMailMessages.content,
74
+ list: async (filter: AdminMailFilter, page: MailPageParams): Promise<MailPage<AdminMailRecord>> => {
75
+ const result = await outgoingMailMessages.list(filter, page, true);
76
+ return {
77
+ ...result,
78
+ items: result.items.map((item) => {
79
+ // The metadata mapper deliberately omits content; validate its public boundary.
80
+ return AdminMailRecordSchema.parse(item);
81
+ }),
82
+ };
83
+ },
84
+ };
@@ -0,0 +1,135 @@
1
+ import { createHash } from "node:crypto";
2
+ import { type ObjectRef, StoreFullError } from "@k2b/sync";
3
+ import type { MailAttachment, MailRecord } from "../../contracts/outgoing-mail";
4
+ import { OutgoingMailError } from "./store";
5
+ import { mailAttachments } from "./sync";
6
+
7
+ export type UploadedAttachments = { metadata: MailRecord["attachments"]; refs: ObjectRef[] };
8
+ export const MAIL_ATTACHMENT_UPLOAD_MS = 60_000;
9
+ export const cancelMailStreams = (attachments: unknown = []): void => {
10
+ if (!Array.isArray(attachments)) return;
11
+ for (const attachment of attachments) {
12
+ if (
13
+ attachment &&
14
+ typeof attachment === "object" &&
15
+ "content" in attachment &&
16
+ attachment.content instanceof ReadableStream &&
17
+ !attachment.content.locked
18
+ )
19
+ void attachment.content.cancel().catch(() => {});
20
+ }
21
+ };
22
+ export const deleteMailObjects = async (refs: readonly ObjectRef[]): Promise<void> => {
23
+ // Sequential deletion bounds load even for a large attachment collection.
24
+ for (const ref of refs) await mailAttachments().delete({ tenantId: ref.tenantId, key: ref.key });
25
+ };
26
+ const contentStream = (content: MailAttachment["content"]): ReadableStream<Uint8Array> => {
27
+ if (content instanceof ReadableStream) return content;
28
+ if (content instanceof Blob) return content.stream();
29
+ return new ReadableStream({
30
+ start(controller) {
31
+ controller.enqueue(content);
32
+ controller.close();
33
+ },
34
+ });
35
+ };
36
+ export const uploadMailAttachments = async (
37
+ id: string,
38
+ attachments: readonly MailAttachment[],
39
+ limit: number,
40
+ uploadDeadline?: number,
41
+ ): Promise<UploadedAttachments> => {
42
+ const result: UploadedAttachments = { metadata: [], refs: [] };
43
+ let total = 0;
44
+ const controller = new AbortController();
45
+ // The caller's signal cancels the wait only. All attachments share one bounded upload.
46
+ if (uploadDeadline !== undefined && uploadDeadline <= Date.now() && attachments.length) {
47
+ cancelMailStreams(attachments);
48
+ throw new OutgoingMailError("mail_unavailable", "Attachment upload timed out.");
49
+ }
50
+ const timer = setTimeout(
51
+ () => controller.abort(new Error("Attachment upload timed out")),
52
+ uploadDeadline === undefined ? MAIL_ATTACHMENT_UPLOAD_MS : Math.max(0, uploadDeadline - Date.now()),
53
+ );
54
+ try {
55
+ for (const [index, attachment] of attachments.entries()) {
56
+ const hash = createHash("sha256");
57
+ let size = 0;
58
+ let exceeded = false;
59
+ const key = `${id}-${index}`;
60
+ try {
61
+ const stream = contentStream(attachment.content).pipeThrough(
62
+ new TransformStream<Uint8Array, Uint8Array>({
63
+ transform(chunk, output) {
64
+ total += chunk.byteLength;
65
+ size += chunk.byteLength;
66
+ if (total > limit) {
67
+ exceeded = true;
68
+ throw new OutgoingMailError("attachments_too_large", "Attachments exceed the profile's total byte limit.");
69
+ }
70
+ hash.update(chunk);
71
+ output.enqueue(chunk);
72
+ },
73
+ }),
74
+ { signal: controller.signal },
75
+ );
76
+ const ref = await mailAttachments().put({ tenantId: id, key, body: stream, signal: controller.signal });
77
+ result.refs.push(ref);
78
+ result.metadata.push({ filename: attachment.filename, contentType: attachment.contentType, size, sha256: hash.digest("hex") });
79
+ } catch (error) {
80
+ // A failed put can have written chunks before the final metadata was published.
81
+ await mailAttachments()
82
+ .delete({ tenantId: id, key })
83
+ .catch(() => {});
84
+ if (exceeded) throw new OutgoingMailError("attachments_too_large", "Attachments exceed the profile's total byte limit.");
85
+ if (
86
+ error instanceof StoreFullError ||
87
+ (error instanceof Error &&
88
+ /maximum bytes|maximum storage|insufficient (?:storage|resources)|storage resources|store.*full|resource limits exceeded/i.test(
89
+ error.message,
90
+ ))
91
+ )
92
+ throw new OutgoingMailError("attachment_storage_full", "Outgoing mail attachment storage is full.");
93
+ throw error;
94
+ }
95
+ }
96
+ return result;
97
+ } catch (error) {
98
+ await deleteMailObjects(result.refs).catch(() => {});
99
+ cancelMailStreams(attachments);
100
+ throw error;
101
+ } finally {
102
+ clearTimeout(timer);
103
+ controller.abort();
104
+ }
105
+ };
106
+
107
+ /** Verify before SMTP DATA; open a second, verified stream for nodemailer. */
108
+ export const verifyMailAttachment = async (
109
+ ref: ObjectRef,
110
+ metadata: MailRecord["attachments"][number],
111
+ signal?: AbortSignal,
112
+ ): Promise<void> => {
113
+ const object = await mailAttachments().get(ref, { signal });
114
+ if (!object) throw new OutgoingMailError("attachment_lost", "An outgoing mail attachment is missing or changed.");
115
+ const reader = object.body.getReader();
116
+ const hash = createHash("sha256");
117
+ let size = 0;
118
+ try {
119
+ while (true) {
120
+ const chunk = await reader.read();
121
+ if (chunk.done) break;
122
+ size += chunk.value.byteLength;
123
+ if (size > metadata.size) throw new Error("Attachment size mismatch");
124
+ hash.update(chunk.value);
125
+ }
126
+ if (size !== metadata.size || hash.digest("hex") !== metadata.sha256) throw new Error("Attachment digest mismatch");
127
+ } catch (error) {
128
+ if (signal?.aborted || (error instanceof Error && /stalled|timeout|timed out|connection/i.test(error.message)))
129
+ throw new Error("Attachment verification was interrupted.");
130
+ throw new OutgoingMailError("attachment_lost", "An outgoing mail attachment is missing or changed.");
131
+ } finally {
132
+ await reader.cancel().catch(() => {});
133
+ reader.releaseLock();
134
+ }
135
+ };
@@ -0,0 +1,11 @@
1
+ export const MAIL_RECOVERY_MS = 30_000;
2
+ export const mailSlotMs = (pacePerMinute: number): number => 60_000 / pacePerMinute;
3
+ export const mailBacklogFull = (queued: number, added: number, pacePerMinute: number): boolean =>
4
+ added > 0 && queued + added > pacePerMinute * 1440;
5
+ export const mailBatchId = (proposed: string, rows: readonly ({ batch_id: string | null } | undefined)[]): string => {
6
+ const previous = rows[0]?.batch_id;
7
+ return previous && rows.every((row) => row?.batch_id === previous) ? previous : proposed;
8
+ };
9
+ // Later submissions join a coalesced continuation, so long backoffs must not hide fresh mail.
10
+ export const mailNextDrainDelay = (now: number, slot: number, due: number): number =>
11
+ Math.min(MAIL_RECOVERY_MS, Math.max(0, Math.max(slot, due) - now));