Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
chore(email-service): Hexify send message endpoint (#1766)
Evan Hutnika59ea741c54a
diff --git a/js/app/packages/block-email/component/BaseInput.tsx b/js/app/packages/block-email/component/BaseInput.tsxindex f31e4d1a9a..3eb4051f3a 100644--- a/js/app/packages/block-email/component/BaseInput.tsx+++ b/js/app/packages/block-email/component/BaseInput.tsx@@ -51,7 +51,7 @@ import {useUnscheduleMessageMutation,} from '@queries/email/thread';import type {- MessageToSendDbId,+ ApiDraftOutputDbId,ApiMessage,} from '@service-email/generated/schemas';import { useEmail, useUserId } from '@core/context/user';@@ -320,7 +320,7 @@ export function BaseInput(props: {draft?: ApiMessage;preloadedBody?: string;preloadedHtml?: string;- sideEffectOnSend?: (newMessageId: MessageToSendDbId | null) => void;+ sideEffectOnSend?: (newMessageId: ApiDraftOutputDbId | null) => void;onMarkDone?: () => void;setShowReply?: Setter<boolean>;markdownDomRef?: (ref: HTMLDivElement) => void | HTMLDivElement;@@ -379,7 +379,7 @@ export function BaseInput(props: {const [showCc, setShowCc] = createSignal<boolean>();const [showBcc, setShowBcc] = createSignal<boolean>();const [savedDraftId, setSavedDraftId] = createSignal<- MessageToSendDbId | undefined+ ApiDraftOutputDbId | undefined>(props.draft?.db_id ??(undoReplySnapshot?.threadId === ctx.thread()?.db_id@@ -881,7 +881,6 @@ export function BaseInput(props: {subject: form().subject(),thread_db_id: currentThread?.db_id,to,- link_id: linkId!,},});diff --git a/js/app/packages/block-email/component/Compose.tsx b/js/app/packages/block-email/component/Compose.tsxindex 4adea122a7..727185f35a 100644--- a/js/app/packages/block-email/component/Compose.tsx+++ b/js/app/packages/block-email/component/Compose.tsx@@ -652,7 +652,6 @@ export function EmailCompose(props: EmailComposeProps) {sendMutation.mutate({message: {- link_id: currentLink.id,to: convertToContactInfoArray(recipients.to),cc:recipients.cc.length > 0@@ -667,7 +666,6 @@ export function EmailCompose(props: EmailComposeProps) {body_html: data.html,body_macro: data.raw,db_id: currentDraftID(),- send_time: sendTime,},});diff --git a/js/app/packages/block-email/component/EmailInput.tsx b/js/app/packages/block-email/component/EmailInput.tsxindex ec28db3966..bd81c305cd 100644--- a/js/app/packages/block-email/component/EmailInput.tsx+++ b/js/app/packages/block-email/component/EmailInput.tsx@@ -1,6 +1,6 @@import { useEmailContext } from '@block-email/component/EmailContext';import type {- MessageToSendDbId,+ ApiDraftOutputDbId,ApiMessage,} from '@service-email/generated/schemas';import { type Accessor, createMemo, type Setter, Show } from 'solid-js';@@ -24,7 +24,7 @@ export function EmailInput(props: EmailInputProps) {return decodedHtml;});- function afterSend(newMessageId: MessageToSendDbId | null) {+ function afterSend(newMessageId: ApiDraftOutputDbId | null) {// Refresh to get the new messagectx.query.refetch();diff --git a/js/app/packages/queries/email/thread.ts b/js/app/packages/queries/email/thread.tsindex 980ed1024d..1b852c4d03 100644--- a/js/app/packages/queries/email/thread.ts+++ b/js/app/packages/queries/email/thread.ts@@ -3,7 +3,7 @@ import { catchToResult, isErr, ok, throwOnErr } from '@core/util/maybeResult';import { optimisticUpdateSoupEntity } from '../soup/cache';import { emailClient } from '@service-email/client';import type {- MessageToSend,+ ApiDraftInput,SendMessageResponse,ApiThread as Thread,UpsertScheduledResponse,@@ -261,7 +261,7 @@ export function useArchiveThreadMutation(}));}-type SendMessageParams = { message: MessageToSend };+type SendMessageParams = { message: ApiDraftInput };/*** Mutation to send an email message.diff --git a/js/app/packages/service-clients/service-email/generated/client.ts b/js/app/packages/service-clients/service-email/generated/client.tsindex 8af0649c33..ee6633efba 100644--- a/js/app/packages/service-clients/service-email/generated/client.ts+++ b/js/app/packages/service-clients/service-email/generated/client.ts@@ -1370,7 +1370,7 @@ export const listLinks = async (};/**- * @summary Send an email message.+ * @summary Send a message.*/export type sendMessageResponse201 = {data: SendMessageResponse;@@ -1382,9 +1382,9 @@ export type sendMessageResponse400 = {status: 400;};-export type sendMessageResponse401 = {+export type sendMessageResponse404 = {data: ErrorResponse;- status: 401;+ status: 404;};export type sendMessageResponse500 = {@@ -1397,7 +1397,7 @@ export type sendMessageResponseSuccess = sendMessageResponse201 & {};export type sendMessageResponseError = (| sendMessageResponse400- | sendMessageResponse401+ | sendMessageResponse404| sendMessageResponse500) & {headers: Headers;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/attachmentToSend.ts b/js/app/packages/service-clients/service-email/generated/schemas/attachmentToSend.tsdeleted file mode 100644index 959d7dbdbc..0000000000--- a/js/app/packages/service-clients/service-email/generated/schemas/attachmentToSend.ts+++ /dev/null@@ -1,15 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * email_service- * OpenAPI spec version: 0.1.0- */--/**- * The attachment data we need to include when sending a message to a provider.- */-export interface AttachmentToSend {- content_type: string;- data: number[];- file_name: string;-}diff --git a/js/app/packages/service-clients/service-email/generated/schemas/index.ts b/js/app/packages/service-clients/service-email/generated/schemas/index.tsindex e6cae642b7..adfc458cac 100644--- a/js/app/packages/service-clients/service-email/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-email/generated/schemas/index.ts@@ -131,7 +131,6 @@ export * from './attachmentMimeType';export * from './attachmentProviderId';export * from './attachmentSfsId';export * from './attachmentSizeBytes';-export * from './attachmentToSend';export * from './backfillJob';export * from './backfillJobLinkId';export * from './backfillJobStatus';@@ -204,21 +203,6 @@ export * from './messageSentAt';export * from './messageSizeEstimate';export * from './messageSnippet';export * from './messageSubject';-export * from './messageToSend';-export * from './messageToSendAttachments';-export * from './messageToSendBcc';-export * from './messageToSendBodyHtml';-export * from './messageToSendBodyMacro';-export * from './messageToSendBodyText';-export * from './messageToSendCc';-export * from './messageToSendDbId';-export * from './messageToSendHeadersJson';-export * from './messageToSendProviderId';-export * from './messageToSendProviderThreadId';-export * from './messageToSendReplyingToId';-export * from './messageToSendSendTime';-export * from './messageToSendThreadDbId';-export * from './messageToSendTo';export * from './parsedMessage';export * from './parsedMessageBodyParsed';export * from './parsedMessageFrom';diff --git a/js/app/packages/service-clients/service-email/generated/schemas/messageToSend.ts b/js/app/packages/service-clients/service-email/generated/schemas/messageToSend.tsdeleted file mode 100644index b4db8c3c55..0000000000--- a/js/app/packages/service-clients/service-email/generated/schemas/messageToSend.ts+++ /dev/null@@ -1,39 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * email_service- * OpenAPI spec version: 0.1.0- */-import type { MessageToSendAttachments } from './messageToSendAttachments';-import type { MessageToSendBcc } from './messageToSendBcc';-import type { MessageToSendBodyHtml } from './messageToSendBodyHtml';-import type { MessageToSendBodyMacro } from './messageToSendBodyMacro';-import type { MessageToSendBodyText } from './messageToSendBodyText';-import type { MessageToSendCc } from './messageToSendCc';-import type { MessageToSendDbId } from './messageToSendDbId';-import type { MessageToSendHeadersJson } from './messageToSendHeadersJson';-import type { MessageToSendProviderId } from './messageToSendProviderId';-import type { MessageToSendProviderThreadId } from './messageToSendProviderThreadId';-import type { MessageToSendReplyingToId } from './messageToSendReplyingToId';-import type { MessageToSendSendTime } from './messageToSendSendTime';-import type { MessageToSendThreadDbId } from './messageToSendThreadDbId';-import type { MessageToSendTo } from './messageToSendTo';--export interface MessageToSend {- attachments?: MessageToSendAttachments;- bcc?: MessageToSendBcc;- body_html?: MessageToSendBodyHtml;- body_macro?: MessageToSendBodyMacro;- body_text?: MessageToSendBodyText;- cc?: MessageToSendCc;- db_id?: MessageToSendDbId;- headers_json?: MessageToSendHeadersJson;- link_id: string;- provider_id?: MessageToSendProviderId;- provider_thread_id?: MessageToSendProviderThreadId;- replying_to_id?: MessageToSendReplyingToId;- send_time?: MessageToSendSendTime;- subject: string;- thread_db_id?: MessageToSendThreadDbId;- to?: MessageToSendTo;-}diff --git a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendAttachments.ts b/js/app/packages/service-clients/service-email/generated/schemas/messageToSendAttachments.tsdeleted file mode 100644index 99659e6568..0000000000--- a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendAttachments.ts+++ /dev/null@@ -1,9 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * email_service- * OpenAPI spec version: 0.1.0- */-import type { AttachmentToSend } from './attachmentToSend';--export type MessageToSendAttachments = AttachmentToSend[] | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendBcc.ts b/js/app/packages/service-clients/service-email/generated/schemas/messageToSendBcc.tsdeleted file mode 100644index 20aebb7c61..0000000000--- a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendBcc.ts+++ /dev/null@@ -1,9 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * email_service- * OpenAPI spec version: 0.1.0- */-import type { ContactInfo } from './contactInfo';--export type MessageToSendBcc = ContactInfo[] | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendBodyHtml.ts b/js/app/packages/service-clients/service-email/generated/schemas/messageToSendBodyHtml.tsdeleted file mode 100644index 80eea20816..0000000000--- a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendBodyHtml.ts+++ /dev/null@@ -1,8 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * email_service- * OpenAPI spec version: 0.1.0- */--export type MessageToSendBodyHtml = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendBodyMacro.ts b/js/app/packages/service-clients/service-email/generated/schemas/messageToSendBodyMacro.tsdeleted file mode 100644index c806c6f605..0000000000--- a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendBodyMacro.ts+++ /dev/null@@ -1,8 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * email_service- * OpenAPI spec version: 0.1.0- */--export type MessageToSendBodyMacro = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendBodyText.ts b/js/app/packages/service-clients/service-email/generated/schemas/messageToSendBodyText.tsdeleted file mode 100644index 513fe5d56b..0000000000--- a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendBodyText.ts+++ /dev/null@@ -1,8 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * email_service- * OpenAPI spec version: 0.1.0- */--export type MessageToSendBodyText = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendCc.ts b/js/app/packages/service-clients/service-email/generated/schemas/messageToSendCc.tsdeleted file mode 100644index af370844a1..0000000000--- a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendCc.ts+++ /dev/null@@ -1,9 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * email_service- * OpenAPI spec version: 0.1.0- */-import type { ContactInfo } from './contactInfo';--export type MessageToSendCc = ContactInfo[] | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendDbId.ts b/js/app/packages/service-clients/service-email/generated/schemas/messageToSendDbId.tsdeleted file mode 100644index 2314d541eb..0000000000--- a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendDbId.ts+++ /dev/null@@ -1,8 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * email_service- * OpenAPI spec version: 0.1.0- */--export type MessageToSendDbId = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendHeadersJson.ts b/js/app/packages/service-clients/service-email/generated/schemas/messageToSendHeadersJson.tsdeleted file mode 100644index be045d0b4f..0000000000--- a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendHeadersJson.ts+++ /dev/null@@ -1,9 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * email_service- * OpenAPI spec version: 0.1.0- */-import type { Value } from './value';--export type MessageToSendHeadersJson = null | Value;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendProviderId.ts b/js/app/packages/service-clients/service-email/generated/schemas/messageToSendProviderId.tsdeleted file mode 100644index 5d8600f5e2..0000000000--- a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendProviderId.ts+++ /dev/null@@ -1,8 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * email_service- * OpenAPI spec version: 0.1.0- */--export type MessageToSendProviderId = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendProviderThreadId.ts b/js/app/packages/service-clients/service-email/generated/schemas/messageToSendProviderThreadId.tsdeleted file mode 100644index 109e42e1cd..0000000000--- a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendProviderThreadId.ts+++ /dev/null@@ -1,8 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * email_service- * OpenAPI spec version: 0.1.0- */--export type MessageToSendProviderThreadId = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendReplyingToId.ts b/js/app/packages/service-clients/service-email/generated/schemas/messageToSendReplyingToId.tsdeleted file mode 100644index 31af34d5a4..0000000000--- a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendReplyingToId.ts+++ /dev/null@@ -1,8 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * email_service- * OpenAPI spec version: 0.1.0- */--export type MessageToSendReplyingToId = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendSendTime.ts b/js/app/packages/service-clients/service-email/generated/schemas/messageToSendSendTime.tsdeleted file mode 100644index 598f99b07f..0000000000--- a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendSendTime.ts+++ /dev/null@@ -1,8 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * email_service- * OpenAPI spec version: 0.1.0- */--export type MessageToSendSendTime = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendThreadDbId.ts b/js/app/packages/service-clients/service-email/generated/schemas/messageToSendThreadDbId.tsdeleted file mode 100644index bc42a609f2..0000000000--- a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendThreadDbId.ts+++ /dev/null@@ -1,8 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * email_service- * OpenAPI spec version: 0.1.0- */--export type MessageToSendThreadDbId = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendTo.ts b/js/app/packages/service-clients/service-email/generated/schemas/messageToSendTo.tsdeleted file mode 100644index b19372efb8..0000000000--- a/js/app/packages/service-clients/service-email/generated/schemas/messageToSendTo.ts+++ /dev/null@@ -1,9 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * email_service- * OpenAPI spec version: 0.1.0- */-import type { ContactInfo } from './contactInfo';--export type MessageToSendTo = ContactInfo[] | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/sendMessageRequest.ts b/js/app/packages/service-clients/service-email/generated/schemas/sendMessageRequest.tsindex 898288bd95..7e78787b9f 100644--- a/js/app/packages/service-clients/service-email/generated/schemas/sendMessageRequest.ts+++ b/js/app/packages/service-clients/service-email/generated/schemas/sendMessageRequest.ts@@ -4,11 +4,12 @@* email_service* OpenAPI spec version: 0.1.0*/-import type { MessageToSend } from './messageToSend';+import type { ApiDraftInput } from './apiDraftInput';/**- * The request passed to send a message+ * Request body for sending a message (backward-compatible with `{ message: MessageToSend }`).*/export interface SendMessageRequest {- message: MessageToSend;+ /** The message content. */+ message: ApiDraftInput;}diff --git a/js/app/packages/service-clients/service-email/generated/schemas/sendMessageResponse.ts b/js/app/packages/service-clients/service-email/generated/schemas/sendMessageResponse.tsindex f080720d24..76cfa47958 100644--- a/js/app/packages/service-clients/service-email/generated/schemas/sendMessageResponse.ts+++ b/js/app/packages/service-clients/service-email/generated/schemas/sendMessageResponse.ts@@ -4,8 +4,12 @@* email_service* OpenAPI spec version: 0.1.0*/-import type { MessageToSend } from './messageToSend';+import type { ApiDraftOutput } from './apiDraftOutput';+/**+ * Response body for sending a message.+ */export interface SendMessageResponse {- message: MessageToSend;+ /** The created message. */+ message: ApiDraftOutput;}diff --git a/js/app/packages/service-clients/service-email/openapi.json b/js/app/packages/service-clients/service-email/openapi.jsonindex 5073813633..159b1da4bd 100644--- a/js/app/packages/service-clients/service-email/openapi.json+++ b/js/app/packages/service-clients/service-email/openapi.json@@ -1284,7 +1284,7 @@"/email/messages": {"post": {"tags": ["Messages"],- "summary": "Send an email message.",+ "summary": "Send a message.","operationId": "send_message","requestBody": {"content": {@@ -1317,7 +1317,7 @@}}},- "401": {+ "404": {"description": "","content": {"application/json": {@@ -3192,27 +3192,6 @@}}},- "AttachmentToSend": {- "type": "object",- "description": "The attachment data we need to include when sending a message to a provider.",- "required": ["file_name", "content_type", "data"],- "properties": {- "content_type": {- "type": "string"- },- "data": {- "type": "array",- "items": {- "type": "integer",- "format": "int32",- "minimum": 0- }- },- "file_name": {- "type": "string"- }- }- },"BackfillJob": {"type": "object","required": [@@ -3860,84 +3839,6 @@"type": "string","enum": ["Show", "Hide"]},- "MessageToSend": {- "type": "object",- "required": ["link_id", "subject"],- "properties": {- "attachments": {- "type": ["array", "null"],- "items": {- "$ref": "#/components/schemas/AttachmentToSend"- }- },- "bcc": {- "type": ["array", "null"],- "items": {- "$ref": "#/components/schemas/ContactInfo"- }- },- "body_html": {- "type": ["string", "null"]- },- "body_macro": {- "type": ["string", "null"]- },- "body_text": {- "type": ["string", "null"]- },- "cc": {- "type": ["array", "null"],- "items": {- "$ref": "#/components/schemas/ContactInfo"- }- },- "db_id": {- "type": ["string", "null"],- "format": "uuid"- },- "headers_json": {- "oneOf": [- {- "type": "null"- },- {- "$ref": "#/components/schemas/Value"- }- ]- },- "link_id": {- "type": "string",- "format": "uuid"- },- "provider_id": {- "type": ["string", "null"]- },- "provider_thread_id": {- "type": ["string", "null"]- },- "replying_to_id": {- "type": ["string", "null"],- "format": "uuid"- },- "send_time": {- "type": ["string", "null"],- "format": "date-time"- },- "subject": {- "type": "string"- },- "thread_db_id": {- "type": ["string", "null"],- "format": "uuid"- },- "to": {- "type": ["array", "null"],- "items": {- "$ref": "#/components/schemas/ContactInfo"- }- }- }- },"ParsedMessage": {"type": "object","required": [@@ -4061,20 +3962,23 @@},"SendMessageRequest": {"type": "object",- "description": "The request passed to send a message",+ "description": "Request body for sending a message (backward-compatible with `{ message: MessageToSend }`).","required": ["message"],"properties": {"message": {- "$ref": "#/components/schemas/MessageToSend"+ "$ref": "#/components/schemas/ApiDraftInput",+ "description": "The message content."}}},"SendMessageResponse": {"type": "object",+ "description": "Response body for sending a message.","required": ["message"],"properties": {"message": {- "$ref": "#/components/schemas/MessageToSend"+ "$ref": "#/components/schemas/ApiDraftOutput",+ "description": "The created message."}}},diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 310dfe0fed..747c8b08ba 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -5437,6 +5437,7 @@ version = "0.1.0"dependencies = ["aws-config","aws-sdk-s3",+ "aws-sdk-sqs","macro_env","macro_env_var","thiserror 2.0.17",@@ -9301,6 +9302,7 @@ dependencies = ["anyhow","aws-sdk-sqs","chrono",+ "email","futures","model","models_email",diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rsindex 03e4baeec5..8f1f1cf69c 100644--- a/rust/cloud-storage/ai_tools/src/tool_context.rs+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs@@ -24,7 +24,8 @@ pub type ToolScribe =pub type ToolFrecencyService = FrecencyQueryServiceImpl<FrecencyPgStorage>;/// Type alias for the email service implementation-pub type ToolEmailService = EmailServiceImpl<EmailPgRepo, ToolFrecencyService>;+pub type ToolEmailService =+ EmailServiceImpl<EmailPgRepo, ToolFrecencyService, email::domain::ports::NoOpEnqueuer>;/// Type alias for the comms/channels service implementationpub type ToolCommsService = ChannelServiceImpl<PgCommsRepo, PgUserRepo, FrecencyPgStorage>;diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rsindex 085f343b43..3e69047811 100644--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs@@ -192,8 +192,12 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar// Build soup service dependencieslet frecency_storage = FrecencyPgStorage::new(pool.clone());let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());- let email_service =- EmailServiceImpl::new(EmailPgRepo::new(pool.clone()), frecency_service.clone());+ let email_service = EmailServiceImpl::new(+ EmailPgRepo::new(pool.clone()),+ frecency_service.clone(),+ email::domain::ports::NoOpEnqueuer,+ 0,+ );let user_repo = PgUserRepo::new(pool.clone());let channels_service = ChannelServiceImpl::new(PgCommsRepo { pool: pool.clone() },diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rsindex a2218059e6..d28806c93c 100644--- a/rust/cloud-storage/document_cognition_service/src/main.rs+++ b/rust/cloud-storage/document_cognition_service/src/main.rs@@ -150,8 +150,12 @@ async fn main() -> anyhow::Result<()> {// Build soup servicelet frecency_storage = FrecencyPgStorage::new(db.clone());let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());- let email_service =- EmailServiceImpl::new(EmailPgRepo::new(db.clone()), frecency_service.clone());+ let email_service = EmailServiceImpl::new(+ EmailPgRepo::new(db.clone()),+ frecency_service.clone(),+ email::domain::ports::NoOpEnqueuer,+ 0,+ );let channels_service = ChannelServiceImpl::new(PgCommsRepo { pool: db.clone() },PgUserRepo::new(db.clone()),diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex 57f15a3fbd..f6bacefb68 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -59,10 +59,18 @@ type DssSoupState = SoupRouterState<SoupImpl<PgSoupRepo,FrecencyQueryServiceImpl<FrecencyPgStorage>,- EmailServiceImpl<EmailPgRepo, FrecencyQueryServiceImpl<FrecencyPgStorage>>,+ EmailServiceImpl<+ EmailPgRepo,+ FrecencyQueryServiceImpl<FrecencyPgStorage>,+ email::domain::ports::NoOpEnqueuer,+ >,ChannelServiceImpl<PgCommsRepo, PgUserRepo, FrecencyPgStorage>,>,- EmailServiceImpl<EmailPgRepo, FrecencyQueryServiceImpl<FrecencyPgStorage>>,+ EmailServiceImpl<+ EmailPgRepo,+ FrecencyQueryServiceImpl<FrecencyPgStorage>,+ email::domain::ports::NoOpEnqueuer,+ >,>;type SystemPropertiesService = SystemPropertiesServiceImpl<PgSystemPropertiesRepository>;diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex 9a748efcf1..2ffe4d14ed 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -202,8 +202,12 @@ async fn main() -> anyhow::Result<()> {let frecency_storage = FrecencyPgStorage::new(db.clone());let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());- let email_service =- EmailServiceImpl::new(EmailPgRepo::new(db.clone()), frecency_service.clone());+ let email_service = EmailServiceImpl::new(+ EmailPgRepo::new(db.clone()),+ frecency_service.clone(),+ email::domain::ports::NoOpEnqueuer,+ 0,+ );let system_properties_service =SystemPropertiesServiceImpl::new(PgSystemPropertiesRepository::new(db.clone()));let redis_multiplexed_conn = redis_clientdiff --git a/rust/cloud-storage/email/src/domain/models/draft.rs b/rust/cloud-storage/email/src/domain/models/draft.rsindex 9bc3066acf..6856d4005a 100644--- a/rust/cloud-storage/email/src/domain/models/draft.rs+++ b/rust/cloud-storage/email/src/domain/models/draft.rs@@ -37,6 +37,40 @@ pub struct CreateDraftInput {pub send_time: Option<DateTime<Utc>>,}+/// A draft input with all IDs resolved, ready for database insertion.+/// Created from `CreateDraftInput` after validation and ID generation.+#[derive(Debug, Clone)]+pub struct ResolvedDraftInput {+ /// The resolved message DB ID.+ pub db_id: Uuid,+ /// Provider message ID.+ pub provider_id: Option<String>,+ /// ID of the message this draft is replying to.+ pub replying_to_id: Option<Uuid>,+ /// Provider thread ID.+ pub provider_thread_id: Option<String>,+ /// The resolved thread DB ID.+ pub thread_db_id: Uuid,+ /// Subject line of the draft.+ pub subject: String,+ /// To recipients.+ pub to: Vec<ContactInfo>,+ /// Cc recipients.+ pub cc: Vec<ContactInfo>,+ /// Bcc recipients.+ pub bcc: Vec<ContactInfo>,+ /// Plain text body.+ pub body_text: Option<String>,+ /// HTML body (decoded).+ pub body_html: Option<String>,+ /// Macro-specific body format.+ pub body_macro: Option<String>,+ /// Headers JSON (e.g. Macro-In-Reply-To).+ pub headers_json: Option<JsonValue>,+ /// Scheduled send time.+ pub send_time: Option<DateTime<Utc>>,+}+/// Simplified message info used for validation queries.#[derive(Debug, Clone)]pub struct SimpleMessageInfo {diff --git a/rust/cloud-storage/email/src/domain/models/mod.rs b/rust/cloud-storage/email/src/domain/models/mod.rsindex 7c648e13b1..ef814654cc 100644--- a/rust/cloud-storage/email/src/domain/models/mod.rs+++ b/rust/cloud-storage/email/src/domain/models/mod.rs@@ -14,8 +14,8 @@ mod tests;pub use attachment::{Attachment, AttachmentDraft, AttachmentForwarded, MessageAttachment};pub use contact::{Contact, ContactInfo, RecipientType};pub use draft::{- CreateDraftInput, CreatedDraft, ParsedAddresses, SimpleMessageInfo, UpsertedContacts,- UpsertedRecipient,+ CreateDraftInput, CreatedDraft, ParsedAddresses, ResolvedDraftInput, SimpleMessageInfo,+ UpsertedContacts, UpsertedRecipient,};pub use error::EmailErr;pub use label::{Label, LabelListVisibility, LabelType, MessageLabel, MessageListVisibility};diff --git a/rust/cloud-storage/email/src/domain/ports.rs b/rust/cloud-storage/email/src/domain/ports.rsindex d1240df57a..4697ba1a59 100644--- a/rust/cloud-storage/email/src/domain/ports.rs+++ b/rust/cloud-storage/email/src/domain/ports.rs@@ -2,7 +2,8 @@ use crate::domain::models::{Attachment, AttachmentDraft, AttachmentForwarded, Contact, ContactInfo, CreateDraftInput,CreatedDraft, EmailErr, EmailThreadPreview, EnrichedEmailThreadPreview, GetEmailsRequest,Label, Link, MessageAttachment, MessageLabel, MessageRow, ParsedAddresses, PreviewCursorQuery,- RecipientType, SimpleMessageInfo, Thread, ThreadRow, UpsertedContacts, UserProvider,+ RecipientType, ResolvedDraftInput, SimpleMessageInfo, Thread, ThreadRow, UpsertedContacts,+ UserProvider,};use chrono::{DateTime, Utc};use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};@@ -14,6 +15,20 @@ use uuid::Uuid;/// Keyed map of message recipients grouped by message ID.pub type RecipientsByMessageId = HashMap<Uuid, Vec<(ContactInfo, RecipientType)>>;+/// Port for enqueuing email messages to be sent on a schedule.+pub trait EmailMessageEnqueuer: Send + Sync + 'static {+ /// Error type for enqueue operations.+ type Err: Send;++ /// Enqueue a message to be sent after an optional delay.+ fn enqueue_scheduled_message(+ &self,+ link_id: Uuid,+ message_id: Uuid,+ delay_seconds: Option<i32>,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;+}+pub trait EmailRepo: Send + Sync + 'static {type Err: Send;fn previews_for_view_cursor(@@ -123,19 +138,17 @@ pub trait EmailRepo: Send + Sync + 'static {addresses: ParsedAddresses,) -> impl Future<Output = Result<UpsertedContacts, Self::Err>> + Send;- /// Insert a draft message within a transaction, including thread insert (if new),+ /// Insert a message within a transaction, including thread insert (if new),/// recipients, scheduled message handling, thread metadata update, and user history./// If `new_thread` is Some, the thread is created inside the same transaction.- /// Returns the thread DB ID.- fn insert_draft_message(+ fn insert_message(&self,- input: &CreateDraftInput,- message_db_id: Uuid,- thread_db_id: Uuid,+ input: &ResolvedDraftInput,contacts: &UpsertedContacts,link_id: Uuid,new_thread: Option<ThreadRow>,- ) -> impl Future<Output = Result<Uuid, Self::Err>> + Send;+ is_draft: bool,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;}pub trait EmailService: Send + Sync + 'static {@@ -169,4 +182,28 @@ pub trait EmailService: Send + Sync + 'static {link: &Link,input: CreateDraftInput,) -> impl Future<Output = Result<CreatedDraft, EmailErr>> + Send;++ /// Send a message: persist it and enqueue for scheduled delivery.+ fn send_message(+ &self,+ link: &Link,+ input: CreateDraftInput,+ ) -> impl Future<Output = Result<CreatedDraft, EmailErr>> + Send;+}++/// No-op enqueuer for callers that don't need send capability.+#[derive(Clone)]+pub struct NoOpEnqueuer;++impl EmailMessageEnqueuer for NoOpEnqueuer {+ type Err = std::convert::Infallible;++ async fn enqueue_scheduled_message(+ &self,+ _link_id: Uuid,+ _message_id: Uuid,+ _delay_seconds: Option<i32>,+ ) -> Result<(), Self::Err> {+ Ok(())+ }}diff --git a/rust/cloud-storage/email/src/domain/service/draft.rs b/rust/cloud-storage/email/src/domain/service/draft.rsindex 7fc29935e0..eae50a16ee 100644--- a/rust/cloud-storage/email/src/domain/service/draft.rs+++ b/rust/cloud-storage/email/src/domain/service/draft.rs@@ -1,7 +1,7 @@use crate::domain::{models::{- CreateDraftInput, CreatedDraft, EmailErr, Link, ParsedAddresses, SimpleMessageInfo,- ThreadRow,+ CreateDraftInput, CreatedDraft, EmailErr, Link, ParsedAddresses, ResolvedDraftInput,+ SimpleMessageInfo, ThreadRow,},ports::EmailRepo,};@@ -12,17 +12,33 @@ use uuid::Uuid;use super::EmailServiceImpl;-impl<T, U> EmailServiceImpl<T, U>+impl<T, U, E> EmailServiceImpl<T, U, E>whereT: EmailRepo,U: FrecencyQueryService,+ E: crate::domain::ports::EmailMessageEnqueuer,anyhow::Error: From<T::Err>,{#[tracing::instrument(err, skip(self, link, input))]pub(crate) async fn create_draft_impl(+ &self,+ link: &Link,+ input: CreateDraftInput,+ ) -> Result<CreatedDraft, EmailErr> {+ self.prepare_and_insert_db_message(link, input, true).await+ }++ /// Shared pipeline for creating a draft or a sent message.+ ///+ /// Validates existing message / reply-to, decodes HTML body, upserts contacts,+ /// builds thread if needed, and inserts the message row via the repo layer.+ /// `is_draft` controls the `is_draft` flag persisted on the message row.+ #[tracing::instrument(err, skip(self, link, input))]+ pub(crate) async fn prepare_and_insert_db_message(&self,link: &Link,mut input: CreateDraftInput,+ is_draft: bool,) -> Result<CreatedDraft, EmailErr> {let link_id = link.id;@@ -52,30 +68,15 @@ where// Build new thread if one doesn't already existlet (thread_db_id, new_thread) = self.build_new_thread_if_needed(link_id, &input);- // Generate message ID once, before insert, so the response matches the DB+ // Resolve all IDs and build the insert-ready structlet message_db_id = input.db_id.unwrap_or_else(macro_uuid::generate_uuid_v7);- input.db_id = Some(message_db_id);-- let thread_db_id = self- .email_repo- .insert_draft_message(- &input,- message_db_id,- thread_db_id,- &contacts,- link_id,- new_thread,- )- .await- .map_err(anyhow::Error::from)?;- Ok(CreatedDraft {+ let resolved = ResolvedDraftInput {db_id: message_db_id,provider_id: input.provider_id,replying_to_id: input.replying_to_id,provider_thread_id: input.provider_thread_id,thread_db_id,- link_id,subject: input.subject,to: input.to,cc: input.cc,@@ -85,6 +86,29 @@ wherebody_macro: input.body_macro,headers_json: input.headers_json,send_time: input.send_time,+ };++ self.email_repo+ .insert_message(&resolved, &contacts, link_id, new_thread, is_draft)+ .await+ .map_err(anyhow::Error::from)?;++ Ok(CreatedDraft {+ db_id: resolved.db_id,+ provider_id: resolved.provider_id,+ replying_to_id: resolved.replying_to_id,+ provider_thread_id: resolved.provider_thread_id,+ thread_db_id: resolved.thread_db_id,+ link_id,+ subject: resolved.subject,+ to: resolved.to,+ cc: resolved.cc,+ bcc: resolved.bcc,+ body_text: resolved.body_text,+ body_html: resolved.body_html,+ body_macro: resolved.body_macro,+ headers_json: resolved.headers_json,+ send_time: resolved.send_time,})}diff --git a/rust/cloud-storage/email/src/domain/service/mod.rs b/rust/cloud-storage/email/src/domain/service/mod.rsindex 4ba21d8064..d549ec2177 100644--- a/rust/cloud-storage/email/src/domain/service/mod.rs+++ b/rust/cloud-storage/email/src/domain/service/mod.rs@@ -1,5 +1,6 @@mod draft;mod previews;+mod send;mod thread;use crate::domain::{@@ -7,7 +8,7 @@ use crate::domain::{CreateDraftInput, CreatedDraft, EmailErr, EnrichedEmailThreadPreview, GetEmailsRequest,Link, Thread,},- ports::{EmailRepo, EmailService},+ ports::{EmailMessageEnqueuer, EmailRepo, EmailService},};use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};use frecency::domain::ports::FrecencyQueryService;@@ -15,29 +16,41 @@ use models_pagination::{PaginatedCursor, SimpleSortMethod};use uuid::Uuid;#[derive(Clone)]-pub struct EmailServiceImpl<T, U> {+pub struct EmailServiceImpl<T, U, E> {email_repo: T,frecency_service: U,+ enqueuer: E,+ sent_undo_delay_secs: u32,}-impl<T, U> EmailServiceImpl<T, U>+impl<T, U, E> EmailServiceImpl<T, U, E>whereT: EmailRepo,U: FrecencyQueryService,+ E: EmailMessageEnqueuer,{- pub fn new(email_repo: T, frecency_service: U) -> EmailServiceImpl<T, U> {+ pub fn new(+ email_repo: T,+ frecency_service: U,+ enqueuer: E,+ sent_undo_delay_secs: u32,+ ) -> EmailServiceImpl<T, U, E> {EmailServiceImpl {email_repo,frecency_service,+ enqueuer,+ sent_undo_delay_secs,}}}-impl<T, U> EmailService for EmailServiceImpl<T, U>+impl<T, U, E> EmailService for EmailServiceImpl<T, U, E>whereT: EmailRepo,U: FrecencyQueryService,+ E: EmailMessageEnqueuer,anyhow::Error: From<T::Err>,+ anyhow::Error: From<E::Err>,{async fn get_email_thread_previews(&self,@@ -73,4 +86,12 @@ where) -> Result<CreatedDraft, EmailErr> {self.create_draft_impl(link, input).await}++ async fn send_message(+ &self,+ link: &Link,+ input: CreateDraftInput,+ ) -> Result<CreatedDraft, EmailErr> {+ self.send_message_impl(link, input).await+ }}diff --git a/rust/cloud-storage/email/src/domain/service/previews.rs b/rust/cloud-storage/email/src/domain/service/previews.rsindex ebd676b993..6785b1141e 100644--- a/rust/cloud-storage/email/src/domain/service/previews.rs+++ b/rust/cloud-storage/email/src/domain/service/previews.rs@@ -16,10 +16,11 @@ use uuid::Uuid;use super::EmailServiceImpl;-impl<T, U> EmailServiceImpl<T, U>+impl<T, U, E> EmailServiceImpl<T, U, E>whereT: EmailRepo,U: FrecencyQueryService,+ E: crate::domain::ports::EmailMessageEnqueuer,anyhow::Error: From<T::Err>,{#[tracing::instrument(err, skip(self, req))]diff --git a/rust/cloud-storage/email/src/domain/service/send.rs b/rust/cloud-storage/email/src/domain/service/send.rsnew file mode 100644index 0000000000..13b281ce0c--- /dev/null+++ b/rust/cloud-storage/email/src/domain/service/send.rs@@ -0,0 +1,41 @@+use chrono::Duration;++use crate::domain::{+ models::{CreateDraftInput, CreatedDraft, EmailErr, Link},+ ports::{EmailMessageEnqueuer, EmailRepo},+};+use frecency::domain::ports::FrecencyQueryService;++use super::EmailServiceImpl;++impl<T, U, E> EmailServiceImpl<T, U, E>+where+ T: EmailRepo,+ U: FrecencyQueryService,+ E: EmailMessageEnqueuer,+ anyhow::Error: From<T::Err>,+ anyhow::Error: From<E::Err>,+{+ #[tracing::instrument(err, skip(self, link, input))]+ pub(crate) async fn send_message_impl(+ &self,+ link: &Link,+ mut input: CreateDraftInput,+ ) -> Result<CreatedDraft, EmailErr> {+ let delay_secs = self.sent_undo_delay_secs;+ input.send_time = Some(chrono::Utc::now() + Duration::seconds(delay_secs as i64));++ let created = self+ .prepare_and_insert_db_message(link, input, false)+ .await?;++ // FE displays "Undo" button for delay_secs. Give extra time for round trip of cancel request+ let sqs_delay = delay_secs as i32 + 2;+ self.enqueuer+ .enqueue_scheduled_message(link.id, created.db_id, Some(sqs_delay))+ .await+ .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?;++ Ok(created)+ }+}diff --git a/rust/cloud-storage/email/src/domain/service/thread.rs b/rust/cloud-storage/email/src/domain/service/thread.rsindex 606b5eed05..08e47a6947 100644--- a/rust/cloud-storage/email/src/domain/service/thread.rs+++ b/rust/cloud-storage/email/src/domain/service/thread.rs@@ -11,10 +11,11 @@ use uuid::Uuid;use super::EmailServiceImpl;-impl<T, U> EmailServiceImpl<T, U>+impl<T, U, E> EmailServiceImpl<T, U, E>whereT: EmailRepo,U: FrecencyQueryService,+ E: crate::domain::ports::EmailMessageEnqueuer,anyhow::Error: From<T::Err>,{#[tracing::instrument(err, skip(self, receipt))]diff --git a/rust/cloud-storage/email/src/inbound/axum.rs b/rust/cloud-storage/email/src/inbound/axum.rsindex 7ba834da7d..21653ba277 100644--- a/rust/cloud-storage/email/src/inbound/axum.rs+++ b/rust/cloud-storage/email/src/inbound/axum.rs@@ -3,9 +3,11 @@ mod axum_impls;mod draft_router;mod get_thread_router;mod previews_router;+mod send_router;pub use api_types::*;pub use axum_impls::*;pub use draft_router::*;pub use get_thread_router::*;pub use previews_router::*;+pub use send_router::*;diff --git a/rust/cloud-storage/email/src/inbound/axum/api_types/mod.rs b/rust/cloud-storage/email/src/inbound/axum/api_types/mod.rsindex a218e1d83f..9f94ea4c32 100644--- a/rust/cloud-storage/email/src/inbound/axum/api_types/mod.rs+++ b/rust/cloud-storage/email/src/inbound/axum/api_types/mod.rs@@ -1,8 +1,10 @@mod draft;+mod send;pub use draft::{ApiDraftContactInfo, ApiDraftInput, ApiDraftOutput, CreateDraftRequest, CreateDraftResponse,};+pub use send::{SendMessageRequest, SendMessageResponse};mod label;mod message;mod preview;diff --git a/rust/cloud-storage/email/src/inbound/axum/api_types/send.rs b/rust/cloud-storage/email/src/inbound/axum/api_types/send.rsnew file mode 100644index 0000000000..b257ebede7--- /dev/null+++ b/rust/cloud-storage/email/src/inbound/axum/api_types/send.rs@@ -0,0 +1,61 @@+use serde::{Deserialize, Serialize};+use utoipa::ToSchema;++use crate::domain::models::{ContactInfo, CreateDraftInput};++use super::{ApiDraftInput, ApiDraftOutput};++/// Request body for sending a message (backward-compatible with `{ message: MessageToSend }`).+#[derive(Debug, Deserialize, ToSchema)]+pub struct SendMessageRequest {+ /// The message content.+ pub message: ApiDraftInput,+}++/// Response body for sending a message.+#[derive(Debug, Serialize, ToSchema)]+pub struct SendMessageResponse {+ /// The created message.+ pub message: ApiDraftOutput,+}++impl SendMessageRequest {+ /// Convert the API request into a domain `CreateDraftInput`.+ ///+ /// `send_time` is not set here — the service layer computes it from config.+ pub fn into_domain(self) -> CreateDraftInput {+ let msg = self.message;++ CreateDraftInput {+ db_id: msg.db_id,+ provider_id: msg.provider_id,+ replying_to_id: msg.replying_to_id,+ provider_thread_id: msg.provider_thread_id,+ thread_db_id: msg.thread_db_id,+ subject: msg.subject,+ to: msg+ .to+ .unwrap_or_default()+ .into_iter()+ .map(ContactInfo::from)+ .collect(),+ cc: msg+ .cc+ .unwrap_or_default()+ .into_iter()+ .map(ContactInfo::from)+ .collect(),+ bcc: msg+ .bcc+ .unwrap_or_default()+ .into_iter()+ .map(ContactInfo::from)+ .collect(),+ body_text: msg.body_text,+ body_html: msg.body_html,+ body_macro: msg.body_macro,+ headers_json: msg.headers_json,+ send_time: None,+ }+ }+}diff --git a/rust/cloud-storage/email/src/inbound/axum/axum_impls.rs b/rust/cloud-storage/email/src/inbound/axum/axum_impls.rsindex 09e8a13cbc..0d8aeb8b81 100644--- a/rust/cloud-storage/email/src/inbound/axum/axum_impls.rs+++ b/rust/cloud-storage/email/src/inbound/axum/axum_impls.rs@@ -3,7 +3,7 @@ use crate::{models::{EmailErr, Link, PreviewView},ports::EmailService,},- inbound::{ApiSortMethod, EmailPreviewState},+ inbound::{ApiSortMethod, EmailRouterState},};use axum::{RequestPartsExt, async_trait,@@ -103,7 +103,7 @@ impl IntoResponse for EmailLinkErr {#[async_trait]impl<S, U> FromRequestParts<S> for EmailLinkExtractor<U>where- EmailPreviewState<U>: FromRef<S>,+ EmailRouterState<U>: FromRef<S>,U: EmailService,S: Send + Sync + 'static,{@@ -115,7 +115,7 @@ whereuser_context,..}) = parts.extract_with_state(state).await?;- let res = <EmailPreviewState<U>>::from_ref(state)+ let res = <EmailRouterState<U>>::from_ref(state).inner.get_link_by_auth_id_and_macro_id(&user_context.fusion_user_id, macro_user_id).await?@@ -137,7 +137,7 @@ impl<U> Clone for OptionalEmailLinkExtractor<U> {#[async_trait]impl<S, U> FromRequestParts<S> for OptionalEmailLinkExtractor<U>where- EmailPreviewState<U>: FromRef<S>,+ EmailRouterState<U>: FromRef<S>,U: EmailService,S: Send + Sync + 'static,{@@ -149,7 +149,7 @@ whereuser_context,..}) = parts.extract_with_state(state).await?;- let res = <EmailPreviewState<U>>::from_ref(state)+ let res = <EmailRouterState<U>>::from_ref(state).inner.get_link_by_auth_id_and_macro_id(&user_context.fusion_user_id, macro_user_id).await?;diff --git a/rust/cloud-storage/email/src/inbound/axum/draft_router.rs b/rust/cloud-storage/email/src/inbound/axum/draft_router.rsindex d1d728edb1..e87b2b71b9 100644--- a/rust/cloud-storage/email/src/inbound/axum/draft_router.rs+++ b/rust/cloud-storage/email/src/inbound/axum/draft_router.rs@@ -1,35 +1,17 @@-use std::sync::Arc;--use axum::{- Extension, Json, Router, extract::State, http::StatusCode, response::IntoResponse,- routing::post,-};+use axum::{Json, Router, extract::State, http::StatusCode, response::IntoResponse, routing::post};+use axum_extra::extract::Cached;use model_error_response::ErrorResponse;use thiserror::Error;-use crate::domain::{- models::{EmailErr, Link},- ports::EmailService,-};--use super::api_types::{CreateDraftRequest, CreateDraftResponse};--/// State for the draft router, containing only the email service.-pub struct EmailDraftRouterState<T> {- /// The email service.- pub service: Arc<T>,-}+use crate::domain::{models::EmailErr, ports::EmailService};-impl<T> Clone for EmailDraftRouterState<T> {- fn clone(&self) -> Self {- Self {- service: self.service.clone(),- }- }-}+use super::{+ EmailLinkExtractor, EmailRouterState,+ api_types::{CreateDraftRequest, CreateDraftResponse},+};/// Create the draft router with a `POST /` handler.-pub fn draft_router<S, T>(state: EmailDraftRouterState<T>) -> Router<S>+pub fn draft_router<S, T>(state: EmailRouterState<T>) -> Router<S>whereS: Send + Sync + 'static,T: EmailService,@@ -99,12 +81,12 @@ impl From<EmailErr> for CreateDraftError {)]#[tracing::instrument(err, skip(state, link, body))]pub async fn create_draft_handler<T: EmailService>(- State(state): State<EmailDraftRouterState<T>>,- Extension(link): Extension<Link>,+ State(state): State<EmailRouterState<T>>,+ Cached(EmailLinkExtractor(link, _)): Cached<EmailLinkExtractor<T>>,Json(body): Json<CreateDraftRequest>,) -> Result<impl IntoResponse, CreateDraftError> {let input = body.into_domain();- let draft = state.service.create_draft(&link, input).await?;+ let draft = state.inner.create_draft(&link, input).await?;Ok((StatusCode::CREATED,diff --git a/rust/cloud-storage/email/src/inbound/axum/previews_router.rs b/rust/cloud-storage/email/src/inbound/axum/previews_router.rsindex 1ff1a76371..69c2bee080 100644--- a/rust/cloud-storage/email/src/inbound/axum/previews_router.rs+++ b/rust/cloud-storage/email/src/inbound/axum/previews_router.rs@@ -20,11 +20,11 @@ use crate::{},};-pub struct EmailPreviewState<T> {+pub struct EmailRouterState<T> {pub(crate) inner: Arc<T>,}-impl<T> Clone for EmailPreviewState<T> {+impl<T> Clone for EmailRouterState<T> {fn clone(&self) -> Self {Self {inner: Arc::clone(&self.inner),@@ -32,7 +32,7 @@ impl<T> Clone for EmailPreviewState<T> {}}-impl<T> EmailPreviewState<T>+impl<T> EmailRouterState<T>whereT: EmailService,{@@ -48,7 +48,7 @@ where}}-pub fn router<S, T>(state: EmailPreviewState<T>) -> Router<S>+pub fn router<S, T>(state: EmailRouterState<T>) -> Router<S>whereS: Send + Sync,T: EmailService,@@ -78,7 +78,7 @@ where)]#[tracing::instrument(skip(link, macro_user, service), fields(user_id=macro_user.macro_user_id.as_ref(), fusionauth_user_id=macro_user.user_context.fusion_user_id))]async fn cursor_handler<T: EmailService>(- State(service): State<EmailPreviewState<T>>,+ State(service): State<EmailRouterState<T>>,Cached(macro_user): Cached<MacroUserExtractor>,Cached(EmailLinkExtractor(link, _)): Cached<EmailLinkExtractor<T>>,PreviewViewPathExtractor(preview_view): PreviewViewPathExtractor,diff --git a/rust/cloud-storage/email/src/inbound/axum/send_router.rs b/rust/cloud-storage/email/src/inbound/axum/send_router.rsnew file mode 100644index 0000000000..61c7b0e22e--- /dev/null+++ b/rust/cloud-storage/email/src/inbound/axum/send_router.rs@@ -0,0 +1,97 @@+use axum::{Json, Router, extract::State, http::StatusCode, response::IntoResponse, routing::post};+use axum_extra::extract::Cached;+use model_error_response::ErrorResponse;+use thiserror::Error;++use crate::domain::{models::EmailErr, ports::EmailService};++use super::{+ EmailLinkExtractor, EmailRouterState,+ api_types::{SendMessageRequest, SendMessageResponse},+};++/// Create the send router with a `POST /` handler.+pub fn send_router<S, T>(state: EmailRouterState<T>) -> Router<S>+where+ S: Send + Sync + 'static,+ T: EmailService,+{+ Router::new()+ .route("/", post(send_message_handler::<T>))+ .with_state(state)+}++/// Errors from the send message handler.+#[derive(Debug, Error)]+pub enum SendMessageError {+ /// Validation error (bad request).+ #[error("{0}")]+ Validation(String),+ /// Not found.+ #[error("{0}")]+ NotFound(String),+ /// Internal error.+ #[error("Internal error")]+ Internal(EmailErr),+}++impl IntoResponse for SendMessageError {+ fn into_response(self) -> axum::response::Response {+ if matches!(self, SendMessageError::Internal(_)) {+ tracing::error!(error=?self, "send message error");+ }++ let status = match &self {+ SendMessageError::Validation(_) => StatusCode::BAD_REQUEST,+ SendMessageError::NotFound(_) => StatusCode::NOT_FOUND,+ SendMessageError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,+ };++ let message = self.to_string();+ (status, Json(ErrorResponse { message: &message })).into_response()+ }+}++impl From<EmailErr> for SendMessageError {+ fn from(err: EmailErr) -> Self {+ match &err {+ EmailErr::MessageNotFound(_) => SendMessageError::NotFound(err.to_string()),+ EmailErr::MessageAlreadySent(_)+ | EmailErr::CannotReplyToDraft+ | EmailErr::Base64DecodeError(_)+ | EmailErr::Utf8Error(_) => SendMessageError::Validation(err.to_string()),+ EmailErr::RepoErr(_) | EmailErr::Frecency(_) => SendMessageError::Internal(err),+ }+ }+}++/// Send a message.+#[utoipa::path(+ post,+ tag = "Messages",+ path = "/email/messages",+ operation_id = "send_message",+ request_body = SendMessageRequest,+ responses(+ (status = 201, body = SendMessageResponse),+ (status = 400, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip(state, link, body))]+pub async fn send_message_handler<T: EmailService>(+ State(state): State<EmailRouterState<T>>,+ Cached(EmailLinkExtractor(link, _)): Cached<EmailLinkExtractor<T>>,+ Json(body): Json<SendMessageRequest>,+) -> Result<impl IntoResponse, SendMessageError> {+ let input = body.into_domain();+ let created = state.inner.send_message(&link, input).await?;++ Ok((+ StatusCode::CREATED,+ Json(SendMessageResponse {+ message: created.into(),+ }),+ ))+}diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/draft.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/draft.rsindex ba7604eb0e..edda8a789e 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/draft.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/draft.rs@@ -1,5 +1,5 @@use super::{message, thread};-use crate::domain::models::{CreateDraftInput, ThreadRow, UpsertedContacts};+use crate::domain::models::{ResolvedDraftInput, ThreadRow, UpsertedContacts};use chrono::Utc;use sqlx::PgPool;use uuid::Uuid;@@ -9,22 +9,22 @@ use uuid::Uuid;/// thread metadata update, and user history./// Returns the thread DB ID.#[tracing::instrument(skip(pool, input, contacts, new_thread), err)]-pub(crate) async fn insert_draft_message(+pub(crate) async fn insert_message(pool: &PgPool,- input: &CreateDraftInput,- message_db_id: Uuid,- thread_db_id: Uuid,+ input: &ResolvedDraftInput,contacts: &UpsertedContacts,link_id: Uuid,new_thread: Option<ThreadRow>,-) -> Result<Uuid, sqlx::Error> {+ is_draft: bool,+) -> Result<(), sqlx::Error> {let mut tx = pool.begin().await?;- let thread_db_id = if let Some(thread) = new_thread {- thread::insert_thread(&mut tx, &thread, link_id).await?- } else {- thread_db_id- };+ let message_db_id = input.db_id;+ let thread_db_id = input.thread_db_id;++ if let Some(thread) = new_thread {+ thread::insert_thread(&mut tx, &thread, link_id).await?;+ }upsert_draft(&mut tx,@@ -33,6 +33,7 @@ pub(crate) async fn insert_draft_message(thread_db_id,contacts.from_contact_id,link_id,+ is_draft,).await?;@@ -45,17 +46,18 @@ pub(crate) async fn insert_draft_message(thread::upsert_user_history(&mut tx, link_id, thread_db_id).await?;tx.commit().await?;- Ok(thread_db_id)+ Ok(())}/// Upsert a draft message row.pub(crate) async fn upsert_draft(tx: &mut sqlx::PgConnection,- input: &CreateDraftInput,+ input: &ResolvedDraftInput,message_db_id: Uuid,thread_db_id: Uuid,from_contact_id: Option<Uuid>,link_id: Uuid,+ is_draft: bool,) -> Result<(), sqlx::Error> {let now = Utc::now();@@ -101,7 +103,7 @@ pub(crate) async fn upsert_draft(true, // is_readfalse, // is_starredfalse, // is_sent- true, // is_draft (always true for drafts)+ is_draft,input.body_text,input.body_html,input.body_macro,diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rsindex c3f7eef49c..6a8d5c653e 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs@@ -1,8 +1,8 @@use crate::domain::{models::{- Attachment, AttachmentDraft, AttachmentForwarded, Contact, ContactInfo, CreateDraftInput,- EmailThreadPreview, Label, Link, MessageAttachment, MessageLabel, MessageRow,- ParsedAddresses, PreviewCursorQuery, SimpleMessageInfo, ThreadRow, UpsertedContacts,+ Attachment, AttachmentDraft, AttachmentForwarded, Contact, ContactInfo, EmailThreadPreview,+ Label, Link, MessageAttachment, MessageLabel, MessageRow, ParsedAddresses,+ PreviewCursorQuery, ResolvedDraftInput, SimpleMessageInfo, ThreadRow, UpsertedContacts,UserProvider,},ports::{EmailRepo, RecipientsByMessageId},@@ -159,24 +159,14 @@ impl EmailRepo for EmailPgRepo {contact::upsert_contacts(&self.pool, link_id, addresses).await}- async fn insert_draft_message(+ async fn insert_message(&self,- input: &CreateDraftInput,- message_db_id: Uuid,- thread_db_id: Uuid,+ input: &ResolvedDraftInput,contacts: &UpsertedContacts,link_id: Uuid,new_thread: Option<ThreadRow>,- ) -> Result<Uuid, Self::Err> {- draft::insert_draft_message(- &self.pool,- input,- message_db_id,- thread_db_id,- contacts,- link_id,- new_thread,- )- .await+ is_draft: bool,+ ) -> Result<(), Self::Err> {+ draft::insert_message(&self.pool, input, contacts, link_id, new_thread, is_draft).await}}diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/draft.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/draft.rsindex 88ed520930..a9f5cd12f9 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/draft.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/draft.rs@@ -1,6 +1,6 @@use super::*;use crate::domain::models::{- ContactInfo, CreateDraftInput, ParsedAddresses, RecipientType, ThreadRow, UpsertedContacts,+ ContactInfo, ParsedAddresses, RecipientType, ResolvedDraftInput, ThreadRow, UpsertedContacts,UpsertedRecipient,};use chrono::Utc;@@ -339,12 +339,12 @@ async fn test_insert_draft_message_into_existing_thread(let from_contact_id = Uuid::parse_str("c0000001-0000-0000-0000-000000000001")?;let to_contact_id = Uuid::parse_str("c0000002-0000-0000-0000-000000000002")?;- let input = CreateDraftInput {- db_id: None,+ let input = ResolvedDraftInput {+ db_id: message_db_id,provider_id: None,replying_to_id: None,provider_thread_id: Some("provider-thread-2".to_string()),- thread_db_id: Some(thread_db_id),+ thread_db_id,subject: "Test draft".to_string(),to: vec![ContactInfo {email: "[email protected]".to_string(),@@ -369,19 +369,9 @@ async fn test_insert_draft_message_into_existing_thread(}],};- let returned_thread_id = repo- .insert_draft_message(- &input,- message_db_id,- thread_db_id,- &contacts,- link_id,- None,- )+ repo.insert_message(&input, &contacts, link_id, None, true).await?;- assert_eq!(returned_thread_id, thread_db_id);-// Verify the message was insertedlet msg = sqlx::query("SELECT thread_id, subject, is_draft, body_text FROM email_messages WHERE id = $1",@@ -436,12 +426,12 @@ async fn test_insert_draft_message_with_new_thread(pool: Pool<Postgres>) -> anyhlet message_db_id = Uuid::parse_str("dd000002-0000-0000-0000-000000000002")?;let from_contact_id = Uuid::parse_str("c0000001-0000-0000-0000-000000000001")?;- let input = CreateDraftInput {- db_id: None,+ let input = ResolvedDraftInput {+ db_id: message_db_id,provider_id: None,replying_to_id: None,provider_thread_id: None,- thread_db_id: None,+ thread_db_id: new_thread_id,subject: "Brand new thread draft".to_string(),to: vec![],cc: vec![],@@ -471,19 +461,9 @@ async fn test_insert_draft_message_with_new_thread(pool: Pool<Postgres>) -> anyhupdated_at: Utc::now(),};- let returned_thread_id = repo- .insert_draft_message(- &input,- message_db_id,- new_thread_id,- &contacts,- link_id,- Some(new_thread),- )+ repo.insert_message(&input, &contacts, link_id, Some(new_thread), true).await?;- assert_eq!(returned_thread_id, new_thread_id);-// Verify the thread was createdlet thread_link: Uuid = sqlx::query_scalar("SELECT link_id FROM email_threads WHERE id = $1").bind(new_thread_id)@@ -516,12 +496,12 @@ async fn test_insert_draft_message_with_scheduled_send(pool: Pool<Postgres>) ->let send_time =chrono::DateTime::parse_from_rfc3339("2025-06-01T12:00:00Z")?.with_timezone(&Utc);- let input = CreateDraftInput {- db_id: None,+ let input = ResolvedDraftInput {+ db_id: message_db_id,provider_id: None,replying_to_id: None,provider_thread_id: None,- thread_db_id: Some(thread_db_id),+ thread_db_id,subject: "Scheduled draft".to_string(),to: vec![],cc: vec![],@@ -538,15 +518,8 @@ async fn test_insert_draft_message_with_scheduled_send(pool: Pool<Postgres>) ->recipients: vec![],};- repo.insert_draft_message(- &input,- message_db_id,- thread_db_id,- &contacts,- link_id,- None,- )- .await?;+ repo.insert_message(&input, &contacts, link_id, None, true)+ .await?;// Verify the scheduled message was createdlet row =@@ -573,12 +546,12 @@ async fn test_insert_draft_message_upsert_existing(pool: Pool<Postgres>) -> anyh// Re-use the existing draft message ID (msg2)let message_db_id = Uuid::parse_str("ee000002-0000-0000-0000-000000000002")?;- let input = CreateDraftInput {- db_id: Some(message_db_id),+ let input = ResolvedDraftInput {+ db_id: message_db_id,provider_id: None,replying_to_id: Some(Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?),provider_thread_id: Some("provider-thread-1".to_string()),- thread_db_id: Some(thread_db_id),+ thread_db_id,subject: "Updated draft subject".to_string(),to: vec![],cc: vec![],@@ -595,15 +568,8 @@ async fn test_insert_draft_message_upsert_existing(pool: Pool<Postgres>) -> anyhrecipients: vec![],};- repo.insert_draft_message(- &input,- message_db_id,- thread_db_id,- &contacts,- link_id,- None,- )- .await?;+ repo.insert_message(&input, &contacts, link_id, None, true)+ .await?;// Verify the message was updated (not duplicated)let row = sqlx::query("SELECT subject, body_text FROM email_messages WHERE id = $1")@@ -637,12 +603,12 @@ async fn test_insert_draft_message_updates_thread_metadata(let message_db_id = Uuid::parse_str("dd000004-0000-0000-0000-000000000004")?;// Insert a macro draft (no provider_id, is_draft=true) into the thread- let input = CreateDraftInput {- db_id: None,+ let input = ResolvedDraftInput {+ db_id: message_db_id,provider_id: None,replying_to_id: None,provider_thread_id: None,- thread_db_id: Some(thread_db_id),+ thread_db_id,subject: "Metadata test draft".to_string(),to: vec![],cc: vec![],@@ -659,15 +625,8 @@ async fn test_insert_draft_message_updates_thread_metadata(recipients: vec![],};- repo.insert_draft_message(- &input,- message_db_id,- thread_db_id,- &contacts,- link_id,- None,- )- .await?;+ repo.insert_message(&input, &contacts, link_id, None, true)+ .await?;// Thread should now be inbox_visible because it has a macro draftlet row = sqlx::query("SELECT inbox_visible FROM email_threads WHERE id = $1")@@ -682,3 +641,54 @@ async fn test_insert_draft_message_updates_thread_metadata(Ok(())}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_insert_message_with_is_draft_false(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool.clone());++ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let thread_db_id = Uuid::parse_str("22222222-2222-2222-2222-222222222222")?;+ let message_db_id = Uuid::parse_str("dd000005-0000-0000-0000-000000000005")?;+ let from_contact_id = Uuid::parse_str("c0000001-0000-0000-0000-000000000001")?;++ let input = ResolvedDraftInput {+ db_id: message_db_id,+ provider_id: None,+ replying_to_id: None,+ provider_thread_id: None,+ thread_db_id,+ subject: "Sent message".to_string(),+ to: vec![],+ cc: vec![],+ bcc: vec![],+ body_text: Some("This is a sent message".to_string()),+ body_html: None,+ body_macro: None,+ headers_json: None,+ send_time: None,+ };++ let contacts = UpsertedContacts {+ from_contact_id: Some(from_contact_id),+ recipients: vec![],+ };++ repo.insert_message(&input, &contacts, link_id, None, false)+ .await?;++ // Verify the message was inserted with is_draft = false+ let row = sqlx::query("SELECT is_draft, is_sent FROM email_messages WHERE id = $1")+ .bind(message_db_id)+ .fetch_one(&pool)+ .await?;++ assert!(+ !row.get::<bool, _>("is_draft"),+ "Message should have is_draft = false"+ );++ Ok(())+}diff --git a/rust/cloud-storage/email_db_client/src/messages/insert.rs b/rust/cloud-storage/email_db_client/src/messages/insert.rsindex 57360feda6..57bb0c43a5 100644--- a/rust/cloud-storage/email_db_client/src/messages/insert.rs+++ b/rust/cloud-storage/email_db_client/src/messages/insert.rs@@ -1,14 +1,10 @@use crate::attachments::provider;use crate::messages::replying_to_id;-use crate::messages::scheduled::delete::delete_scheduled_message;-use crate::messages::scheduled::upsert::upsert_scheduled_message;-use crate::parse::service_to_db::{addresses_from_message, map_message_to_send_to_db};+use crate::parse::service_to_db::addresses_from_message;use crate::{contacts, labels, parse, threads};use anyhow::Context;-use chrono::Utc;use models_email::email::db::address::UpsertedRecipients;use models_email::email::service::message;-use models_email::service::message::ScheduledMessage;use sqlx::PgPool;use sqlx::types::Uuid;@@ -199,118 +195,3 @@ pub async fn insert_message(}}}--/// insert message that user created via macro frontend-#[tracing::instrument(skip(tx, service_message), err)]-pub async fn insert_message_to_send_db(- tx: &mut sqlx::PgConnection,- service_message: &mut message::MessageToSend,- send_time: Option<chrono::DateTime<Utc>>,- thread_id: Uuid,- from_contact_id: Option<Uuid>,- is_draft: bool,- // recipients need to be inserted ahead of time outside the tx, as they are shared- // across messages and can cause deadlocks if inserted within.- recipients: UpsertedRecipients,-) -> anyhow::Result<()> {- let message_db_id = service_message- .db_id- .unwrap_or_else(macro_uuid::generate_uuid_v7);-- let db_message_to_send = map_message_to_send_to_db(service_message, message_db_id, thread_id);-- // Insert the message into the database- sqlx::query!(- r#"- INSERT INTO email_messages (- id, provider_id, link_id, thread_id, provider_thread_id,- replying_to_id, subject, from_contact_id, sent_at,- has_attachments, is_read, is_starred, is_sent, is_draft,- body_text, body_html_sanitized, body_macro, headers_jsonb,- created_at, updated_at- )- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)- ON CONFLICT (id) DO UPDATE SET- id = EXCLUDED.id,- provider_id = EXCLUDED.provider_id,- thread_id = EXCLUDED.thread_id,- provider_thread_id = EXCLUDED.provider_thread_id,- replying_to_id = EXCLUDED.replying_to_id,- provider_history_id = EXCLUDED.provider_history_id,- subject = EXCLUDED.subject,- from_contact_id = EXCLUDED.from_contact_id,- sent_at = EXCLUDED.sent_at,- has_attachments = EXCLUDED.has_attachments,- is_read = EXCLUDED.is_read,- is_starred = EXCLUDED.is_starred,- is_sent = EXCLUDED.is_sent,- is_draft = EXCLUDED.is_draft,- body_text = EXCLUDED.body_text,- body_html_sanitized = EXCLUDED.body_html_sanitized,- body_macro = EXCLUDED.body_macro,- headers_jsonb = EXCLUDED.headers_jsonb,- updated_at = NOW()- "#,- message_db_id,- db_message_to_send.provider_id,- db_message_to_send.link_id,- thread_id,- db_message_to_send.provider_thread_id,- db_message_to_send.replying_to_id,- db_message_to_send.subject,- from_contact_id,- Utc::now(),- false,- true,- false,- false,- is_draft,- db_message_to_send.body_text,- db_message_to_send.body_html,- db_message_to_send.body_macro,- db_message_to_send.headers_json,- Utc::now(),- Utc::now()- )- .execute(&mut *tx)- .await?;-- service_message.db_id = Some(message_db_id);-- process_scheduled_message(tx, service_message, send_time, message_db_id).await?;-- contacts::upsert_message::upsert_message_recipients(tx, message_db_id, &recipients).await?;-- threads::update::update_thread_metadata(tx, thread_id, db_message_to_send.link_id).await?;-- Ok(())-}--// Handle scheduled message logic-async fn process_scheduled_message(- tx: &mut sqlx::PgConnection,- service_message: &message::MessageToSend,- send_time: Option<chrono::DateTime<Utc>>,- message_db_id: Uuid,-) -> anyhow::Result<()> {- if let Some(send_time) = send_time {- upsert_scheduled_message(- tx,- ScheduledMessage {- link_id: service_message.link_id,- message_id: message_db_id,- send_time,- sent: false,- processing: false,- },- )- .await- .context("Failed to insert scheduled message")?;- } else {- delete_scheduled_message(tx, service_message.link_id, message_db_id)- .await- .context("Failed to delete scheduled message")?;- }-- Ok(())-}diff --git a/rust/cloud-storage/email_db_client/src/parse/service_to_db.rs b/rust/cloud-storage/email_db_client/src/parse/service_to_db.rsindex cb168121ca..545fc0c2ea 100644--- a/rust/cloud-storage/email_db_client/src/parse/service_to_db.rs+++ b/rust/cloud-storage/email_db_client/src/parse/service_to_db.rs@@ -83,30 +83,6 @@ pub fn map_service_message_to_db(}}-#[tracing::instrument]-pub fn map_message_to_send_to_db(- service_msg: &mut message::MessageToSend,- message_id: Uuid,- thread_id: Uuid,-) -> db::message::MessageToSend {- db::message::MessageToSend {- db_id: Some(message_id),- provider_id: service_msg.provider_id.clone(),- provider_thread_id: service_msg.provider_thread_id.clone(),- replying_to_id: service_msg.replying_to_id,- thread_db_id: Some(thread_id),- link_id: service_msg.link_id,- subject: service_msg.subject.clone(),- to: service_msg.to.clone(),- cc: service_msg.cc.clone(),- bcc: service_msg.bcc.clone(),- body_text: mem::take(&mut service_msg.body_text),- body_html: mem::take(&mut service_msg.body_html),- body_macro: mem::take(&mut service_msg.body_macro),- headers_json: service_msg.headers_json.clone(),- }-}-#[tracing::instrument(skip(service_labels))]pub fn map_service_labels_to_provider_ids(service_labels: &[service::label::LabelInfo],diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.tomlindex 7d8bc12b06..92d2952022 100644--- a/rust/cloud-storage/email_service/Cargo.toml+++ b/rust/cloud-storage/email_service/Cargo.toml@@ -67,7 +67,7 @@ sfs_delete = []ammonia = "4.1.0"anyhow = { workspace = true }authentication_service_client = { path = "../authentication_service_client" }-macro_aws_config = { path = "../macro_aws_config", features = ["s3"] }+macro_aws_config = { path = "../macro_aws_config", features = ["s3", "sqs"] }aws-sdk-s3 = { workspace = true }aws-sdk-secretsmanager = { workspace = true }aws-sdk-sqs = { workspace = true }diff --git a/rust/cloud-storage/email_service/src/api/context.rs b/rust/cloud-storage/email_service/src/api/context.rsindex ec6262c0f3..7e33eefcc4 100644--- a/rust/cloud-storage/email_service/src/api/context.rs+++ b/rust/cloud-storage/email_service/src/api/context.rs@@ -2,7 +2,7 @@ use axum::extract::FromRef;use document_storage_service_client::DocumentStorageServiceClient;use email::{domain::service::EmailServiceImpl,- inbound::{EmailDraftRouterState, EmailPreviewState, EmailThreadRouterState},+ inbound::{EmailRouterState, EmailThreadRouterState},outbound::EmailPgRepo,};use email_service::config::Config;@@ -17,7 +17,8 @@ use std::sync::Arc;use system_properties::{PgSystemPropertiesRepository, SystemPropertiesServiceImpl};pub(crate) type EmailEntityAccessService = EntityAccessServiceImpl<PgAccessRepository>;-type EmailSvc = EmailServiceImpl<EmailPgRepo, FrecencyQueryServiceImpl<FrecencyPgStorage>>;+type EmailSvc =+ EmailServiceImpl<EmailPgRepo, FrecencyQueryServiceImpl<FrecencyPgStorage>, sqs_client::SQS>;#[derive(Clone, FromRef)]pub(crate) struct ApiContext {@@ -33,8 +34,7 @@ pub(crate) struct ApiContext {pub jwt_args: JwtValidationArgs,pub config: Arc<Config>,pub internal_auth_key: LocalOrRemoteSecret<InternalApiSecretKey>,- pub email_service: EmailPreviewState<EmailSvc>,+ pub email_service: EmailRouterState<EmailSvc>,pub entity_access_service: Arc<EmailEntityAccessService>,pub email_thread_state: EmailThreadRouterState<EmailSvc, EmailEntityAccessService>,- pub email_draft_state: EmailDraftRouterState<EmailSvc>,}diff --git a/rust/cloud-storage/email_service/src/api/email/drafts/create.rs b/rust/cloud-storage/email_service/src/api/email/drafts/create.rsdeleted file mode 100644index 14a1da19c1..0000000000--- a/rust/cloud-storage/email_service/src/api/email/drafts/create.rs+++ /dev/null@@ -1,215 +0,0 @@-use crate::api::context::ApiContext;-use crate::api::email::validation::{self, ValidationError};-use axum::extract::State;-use axum::http::StatusCode;-use axum::response::{IntoResponse, Response};-use axum::{Extension, Json};-use base64::Engine;-use base64::engine::general_purpose::URL_SAFE_NO_PAD;-use email_db_client::contacts::upsert_message::parse_and_upsert_message_contacts;-use email_db_client::messages::insert::insert_message_to_send_db;-use email_db_client::parse::service_to_db::addresses_from_message;-use email_db_client::user_history::upsert_user_history;-use macro_uuid::generate_uuid_v7;-use model::response::ErrorResponse;-use model::user::UserContext;-use models_email::email::db::address::UpsertedRecipients;-use models_email::service::link::Link;-use models_email::service::{message, thread};-use sqlx::PgPool;-use sqlx::types::chrono::{DateTime, Utc};-use strum_macros::AsRefStr;-use thiserror::Error;-use utoipa::ToSchema;--#[derive(Debug, Error, AsRefStr)]-pub enum CreateDraftError {- #[error("Validation error: {0}")]- Validation(#[from] ValidationError),-- #[error("Failed to insert draft")]- InsertError(#[from] anyhow::Error),-- #[error("A database transaction error occurred")]- TransactionError(#[from] sqlx::Error),-- #[error("Failed to decode base64 HTML body")]- Base64DecodeError(#[from] base64::DecodeError),-- #[error("Failed to convert decoded HTML body to UTF-8")]- Utf8Error(#[from] std::string::FromUtf8Error),-}--impl IntoResponse for CreateDraftError {- fn into_response(self) -> Response {- let status_code = match &self {- CreateDraftError::Validation(e) => e.status_code(),- CreateDraftError::Base64DecodeError(_) | CreateDraftError::Utf8Error(_) => {- StatusCode::BAD_REQUEST- }- CreateDraftError::InsertError(_) | CreateDraftError::TransactionError(_) => {- StatusCode::INTERNAL_SERVER_ERROR- }- };-- (status_code, self.to_string()).into_response()- }-}--/// The request passed to send a message-#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]-pub struct CreateDraftRequest {- pub draft: message::MessageToSend,- pub send_time: Option<DateTime<Utc>>,-}--#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]-pub struct CreateDraftResponse {- pub draft: message::MessageToSend,-}--/// Create a draft.-#[utoipa::path(- post,- tag = "Drafts",- path = "/email/drafts",- operation_id = "create_draft",- request_body = CreateDraftRequest,- responses(- (status = 201, body = CreateDraftResponse),- (status = 400, body = ErrorResponse),- (status = 401, body = ErrorResponse),- (status = 500, body = ErrorResponse),- )-)]-#[tracing::instrument(- skip(ctx, user_context, request_body),- fields(- user_id = user_context.user_id,- fusionauth_user_id = user_context.fusion_user_id- ),- err-)]-pub async fn handler(- State(ctx): State<ApiContext>,- user_context: Extension<UserContext>,- link: Extension<Link>,- Json(request_body): Json<CreateDraftRequest>,-) -> Result<Response, CreateDraftError> {- // falling back to old value for backwards compatability for now.- let send_time = request_body.send_time.or(request_body.draft.send_time);- let draft =- process_message_to_send(&ctx.db, &link, request_body.draft, send_time, true).await?;- Ok((StatusCode::CREATED, Json(CreateDraftResponse { draft })).into_response())-}--pub async fn process_message_to_send(- db: &PgPool,- link: &Link,- mut draft: message::MessageToSend,- send_time: Option<DateTime<Utc>>,- is_draft: bool,-) -> Result<message::MessageToSend, CreateDraftError> {- // TODO: Create api layer struct that doesn't have this value- draft.link_id = link.id;-- validation::validate_existing_message(db, &link.fusionauth_user_id, &mut draft).await?;-- validation::validate_replying_to_id(db, &mut draft, link).await?;-- let from_email = link.email_address.0.as_ref();-- // html comes in as a base64 encoded string, need to decode before inserting- if let Some(html_body) = draft.body_html {- let decoded_html = URL_SAFE_NO_PAD.decode(html_body.as_bytes())?;- let decoded_html_str = String::from_utf8(decoded_html)?;-- // Store the decoded HTML back into the message- draft.body_html = Some(decoded_html_str);- }-- // Parse and upsert contacts before starting the transaction to avoid deadlocks.- // Contacts are shared across messages so they must be inserted outside the transaction.- let addresses = addresses_from_message(&draft);- let recipients = parse_and_upsert_message_contacts(db, link.id, addresses)- .await- .map_err(CreateDraftError::InsertError)?;-- let mut tx = db.begin().await?;-- let result = insert_message_to_send(- &mut tx, &mut draft, send_time, is_draft, from_email, recipients,- )- .await;-- match result {- Ok(_) => {- tx.commit().await?;- Ok(draft)- }- Err(e) => {- if let Err(rollback_err) = tx.rollback().await {- tracing::error!(error=?rollback_err, "Failed to rollback transaction after draft insert failure");- }- Err(CreateDraftError::from(e))- }- }-}--#[tracing::instrument(skip(tx, recipients), err)]-async fn insert_message_to_send(- tx: &mut sqlx::PgConnection,- draft: &mut message::MessageToSend,- send_time: Option<DateTime<Utc>>,- is_draft: bool,- from_email: &str,- recipients: UpsertedRecipients,-) -> anyhow::Result<()> {- let link_id = draft.link_id;- let now: DateTime<Utc> = Utc::now();-- let thread_db_id = if let Some(id) = draft.thread_db_id {- id- } else {- // Generate thread ID in service layer before insertion- let thread_id = generate_uuid_v7();- let thread = thread::Thread {- db_id: thread_id,- provider_id: None,- link_id,- // if we're creating a thread with a sent message, it's not visible in the inbox- inbox_visible: false,- is_read: true,- latest_inbound_message_ts: None,- latest_outbound_message_ts: None,- latest_non_spam_message_ts: None,- created_at: now,- updated_at: now,- messages: Vec::new(),- };-- let new_id =- email_db_client::threads::insert::insert_thread(&mut *tx, &thread, link_id).await?;-- draft.thread_db_id = Some(new_id);- new_id- };-- let from_email_id =- email_db_client::contacts::get::fetch_id_by_email(tx, link_id, from_email).await?;-- insert_message_to_send_db(- tx,- draft,- send_time,- thread_db_id,- from_email_id,- is_draft,- recipients,- )- .await?;-- upsert_user_history(tx, link_id, thread_db_id).await?;-- Ok(())-}diff --git a/rust/cloud-storage/email_service/src/api/email/drafts/mod.rs b/rust/cloud-storage/email_service/src/api/email/drafts/mod.rsindex 35c37ec538..2898cf6124 100644--- a/rust/cloud-storage/email_service/src/api/email/drafts/mod.rs+++ b/rust/cloud-storage/email_service/src/api/email/drafts/mod.rs@@ -1,7 +1,5 @@pub(crate) mod add_attachment;pub(crate) mod add_forwarded_attachment;-#[allow(dead_code)]-pub(crate) mod create;pub(crate) mod delete;pub(crate) mod remove_attachment;pub(crate) mod remove_forwarded_attachment;@@ -14,7 +12,7 @@ use email::inbound::draft_router;pub fn router(state: ApiContext) -> Router<ApiContext> {Router::new()- .merge(draft_router(state.email_draft_state))+ .merge(draft_router(state.email_service.clone())).nest("/scheduled", scheduled::router()).route("/:id", delete(delete::handler)).route("/:id/attachments", post(add_attachment::handler))diff --git a/rust/cloud-storage/email_service/src/api/email/messages/mod.rs b/rust/cloud-storage/email_service/src/api/email/messages/mod.rsindex f68fed49fd..196a76c0ca 100644--- a/rust/cloud-storage/email_service/src/api/email/messages/mod.rs+++ b/rust/cloud-storage/email_service/src/api/email/messages/mod.rs@@ -1,9 +1,9 @@pub(crate) mod get;pub(crate) mod labels;-pub(crate) mod send;use axum::Router;use axum::routing::{get, patch, post};+use email::inbound::send_router;use crate::api::ApiContext;@@ -11,7 +11,7 @@ const BATCH_UPDATE_MESSAGE_LIMIT: usize = 10;pub fn router(state: ApiContext) -> Router<ApiContext> {Router::new()- .route("/", post(send::send_handler))+ .merge(send_router(state.email_service.clone())).route("/labels",patch(labels::handler).layer(axum::middleware::from_fn_with_state(diff --git a/rust/cloud-storage/email_service/src/api/email/messages/send.rs b/rust/cloud-storage/email_service/src/api/email/messages/send.rsdeleted file mode 100644index fbb9ca4c9f..0000000000--- a/rust/cloud-storage/email_service/src/api/email/messages/send.rs+++ /dev/null@@ -1,103 +0,0 @@-use crate::api::context::ApiContext;-use crate::api::email::drafts::create::{CreateDraftError, process_message_to_send};-use axum::extract::State;-use axum::http::StatusCode;-use axum::response::{IntoResponse, Response};-use axum::{Extension, Json};-use chrono::Duration;-use model::response::ErrorResponse;-use model::user::UserContext;-use models_email::email::service::message;-use models_email::service::link::Link;-use models_email::service::pubsub::ScheduledPubsubMessage;-use sqlx::types::chrono::Utc;-use strum_macros::AsRefStr;-use thiserror::Error;-use utoipa::ToSchema;-#[derive(Debug, Error, AsRefStr)]-pub enum SendMessageError {- #[error("Failed to create draft: {0}")]- DraftError(#[from] CreateDraftError),-- #[error("Failed to enqueue scheduled message: {0}")]- EnqueueError(#[from] anyhow::Error),-- #[error("Draft ID not found after creation")]- MissingDraftId,-}--impl IntoResponse for SendMessageError {- fn into_response(self) -> Response {- match self {- SendMessageError::DraftError(e) => e.into_response(),- SendMessageError::EnqueueError(_) | SendMessageError::MissingDraftId => (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "Internal server error",- }),- )- .into_response(),- }- }-}--/// The request passed to send a message-#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]-pub struct SendMessageRequest {- pub message: message::MessageToSend,-}--#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]-pub struct SendMessageResponse {- pub message: message::MessageToSend,-}--/// Send an email message.-#[utoipa::path(- post,- tag = "Messages",- path = "/email/messages",- operation_id = "send_message",- request_body = SendMessageRequest,-- responses(- (status = 201, body=SendMessageResponse),- (status = 400, body=ErrorResponse),- (status = 401, body=ErrorResponse),- (status = 500, body=ErrorResponse),- )-)]-#[tracing::instrument(skip(ctx, user_context, request_body), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id), err)]-pub async fn send_handler(- State(ctx): State<ApiContext>,- user_context: Extension<UserContext>,- link: Extension<Link>,- Json(request_body): Json<SendMessageRequest>,-) -> Result<Response, SendMessageError> {- let undo_delay_secs = ctx.config.sent_undo_delay_secs;- let send_time = Utc::now() + Duration::seconds(undo_delay_secs as i64);-- let draft =- process_message_to_send(&ctx.db, &link, request_body.message, Some(send_time), false)- .await?;-- let message_db_id = draft.db_id.ok_or(SendMessageError::MissingDraftId)?;-- let scheduled_message = ScheduledPubsubMessage {- link_id: link.id,- message_id: message_db_id,- };-- // small delay to give user more time to undo send- let delay_seconds = undo_delay_secs as i32 + 2;-- ctx.sqs_client- .enqueue_email_scheduled_message(scheduled_message, Some(delay_seconds))- .await?;-- Ok((- StatusCode::CREATED,- Json(SendMessageResponse { message: draft }),- )- .into_response())-}diff --git a/rust/cloud-storage/email_service/src/api/email/mod.rs b/rust/cloud-storage/email_service/src/api/email/mod.rsindex dcdd897ee0..ff9ec93a42 100644--- a/rust/cloud-storage/email_service/src/api/email/mod.rs+++ b/rust/cloud-storage/email_service/src/api/email/mod.rs@@ -14,7 +14,6 @@ pub(crate) mod messages;pub(crate) mod settings;pub(crate) mod sync;pub(crate) mod threads;-pub(crate) mod validation;pub fn router(state: ApiContext) -> Router<ApiContext> {Router::new()diff --git a/rust/cloud-storage/email_service/src/api/email/validation.rs b/rust/cloud-storage/email_service/src/api/email/validation.rsdeleted file mode 100644index bacbf12cc4..0000000000--- a/rust/cloud-storage/email_service/src/api/email/validation.rs+++ /dev/null@@ -1,141 +0,0 @@-use anyhow::Context;-use axum::http::StatusCode;-use models_email::service::link::Link;-use models_email::service::message::{MessageToSend, SimpleMessage};-use serde_json::json;-use sqlx::PgPool;-use strum_macros::AsRefStr;-use thiserror::Error;-use uuid::Uuid;--#[derive(Debug, Error, AsRefStr)]-pub enum ValidationError {- #[error("Message with id {0} not found")]- MessageNotFound(Uuid),-- #[error("Message with id {0} has already been sent")]- MessageAlreadySent(Uuid),-- #[error("Cannot reply to a draft")]- CannotReplyToDraft,-- #[error("Failed to get message from database")]- QueryError(#[from] anyhow::Error),-}--impl ValidationError {- pub fn status_code(&self) -> StatusCode {- match self {- ValidationError::MessageNotFound(_) => StatusCode::NOT_FOUND,- ValidationError::CannotReplyToDraft | ValidationError::MessageAlreadySent(_) => {- StatusCode::BAD_REQUEST- }- ValidationError::QueryError(_) => StatusCode::INTERNAL_SERVER_ERROR,- }- }-}--/// Validate draft request-pub async fn validate_replying_to_id(- db: &PgPool,- request_message: &mut MessageToSend,- link: &Link,-) -> Result<(), ValidationError> {- if let Some(replying_to_id) = request_message.replying_to_id {- // check if a draft already exists replying to this message, and if so, use its values- if let Some(existing_draft) = get_draft_replying_to_id(db, replying_to_id, &link.id).await?- {- request_message.db_id = Some(existing_draft.db_id);- request_message.thread_db_id = Some(existing_draft.thread_db_id);- request_message.provider_thread_id = existing_draft.provider_thread_id;- request_message.headers_json = existing_draft.headers_json;-- return Ok(());- }-- // ensure message we are replying to exists and is not a draft- let message_replying_to =- validate_reply_message(db, &replying_to_id, &link.fusionauth_user_id).await?;-- // set draft thread values based on the message we're replying to- request_message.thread_db_id = Some(message_replying_to.thread_db_id);- request_message.provider_thread_id = message_replying_to.provider_thread_id;-- // generate macro-in-reply-to header for email based on the replying_to_id of the draft. temporary- // solution that allows FE to determine the message the draft is replying to, until we have a- // dedicated field in the message table for replying_to_id- request_message.headers_json = Some(json!([{- "Macro-In-Reply-To": message_replying_to.db_id.to_string()- }]));- }-- Ok(())-}--/// Ensure message db_id does not belong to an already-sent message-pub async fn validate_existing_message(- db: &PgPool,- fusionauth_user_id: &str,- message_to_send: &mut MessageToSend,-) -> Result<(), ValidationError> {- if let Some(db_id) = message_to_send.db_id {- let db_message = email_db_client::messages::get_simple_messages::get_simple_message(- db,- &db_id,- fusionauth_user_id,- )- .await- .context("Failed to get message replying to")?- .ok_or(ValidationError::MessageNotFound(db_id))?;-- if db_message.is_sent || !db_message.is_draft {- return Err(ValidationError::MessageAlreadySent(db_id));- }-- message_to_send.thread_db_id = Some(db_message.thread_db_id);- // this might exist if the message being sent is part of an existing thread, or might not if- // the message being sent is the first message in the thread- message_to_send.provider_thread_id = db_message.provider_thread_id;- }-- Ok(())-}--/// Ensure message we are replying to exists and is not a draft-pub async fn validate_reply_message(- db: &PgPool,- replying_to_id: &Uuid,- fusionauth_user_id: &str,-) -> Result<SimpleMessage, ValidationError> {- let message_replying_to = email_db_client::messages::get_simple_messages::get_simple_message(- db,- replying_to_id,- fusionauth_user_id,- )- .await- .context("Failed to get message replying to")?- .ok_or(ValidationError::MessageNotFound(*replying_to_id))?;-- if message_replying_to.is_draft {- return Err(ValidationError::CannotReplyToDraft);- }-- Ok(message_replying_to)-}--/// Get the draft message that is replying to the message with the passed id.-pub async fn get_draft_replying_to_id(- db: &PgPool,- replying_to_id: Uuid,- link_id: &Uuid,-) -> Result<Option<SimpleMessage>, ValidationError> {- let existing_draft_ids =- email_db_client::messages::get_simple_messages::get_first_simple_message_draft(- db,- link_id,- replying_to_id,- )- .await- .context("Failed to search for existing draft")?;- Ok(existing_draft_ids)-}diff --git a/rust/cloud-storage/email_service/src/api/swagger.rs b/rust/cloud-storage/email_service/src/api/swagger.rsindex f245bb31f5..4e6c712ea4 100644--- a/rust/cloud-storage/email_service/src/api/swagger.rs+++ b/rust/cloud-storage/email_service/src/api/swagger.rs@@ -15,7 +15,6 @@ use crate::api::email::labels::create::CreateLabelResponse;use crate::api::email::labels::list::ListLabelsResponse;use crate::api::email::links::list::ListLinksResponse;use crate::api::email::messages::labels::{UpdateLabelBatchRequest, UpdateLabelBatchResponse};-use crate::api::email::messages::send::{SendMessageRequest, SendMessageResponse};use crate::api::email::settings::patch::{PatchSettingsRequest, PatchSettingsResponse};use crate::api::email::threads::archived::ArchiveThreadRequest;use crate::api::email::threads::labels::UpdateThreadLabelRequest;@@ -25,6 +24,7 @@ use ::email::inbound::{ApiDraftContactInfo, ApiDraftInput, ApiDraftOutput, ApiPaginatedThreadCursor, ApiSortMethod,ApiThread, CreateDraftRequest as HexCreateDraftRequest,CreateDraftResponse as HexCreateDraftResponse, GetPreviewsCursorParams, GetThreadResponse,+ SendMessageRequest as HexSendMessageRequest, SendMessageResponse as HexSendMessageResponse,};use model::response::EmptyResponse;use models_email::api::settings::Settings;@@ -34,7 +34,7 @@ use models_email::email::service::backfill::BackfillJob;use models_email::email::service::link::Link;use models_email::email::service::thread::{PreviewView, PreviewViewStandardLabel};use models_email::service::label::Label;-use models_email::service::message::{MessageToSend, ParsedMessage};+use models_email::service::message::ParsedMessage;use models_email::service::thread::ThreadPreviewCursor;use utoipa::OpenApi;@@ -63,7 +63,7 @@ use utoipa::OpenApi;email::messages::get::handler,email::messages::get::batch_handler,email::messages::labels::handler,- email::messages::send::send_handler,+ inbound::send_message_handler,email::threads::seen::seen_handler,email::threads::get::get_thread_messages_handler,email::threads::archived::archived_handler,@@ -106,10 +106,9 @@ use utoipa::OpenApi;// Message typesUpdateLabelBatchRequest,UpdateLabelBatchResponse,- SendMessageRequest,- SendMessageResponse,+ HexSendMessageRequest,+ HexSendMessageResponse,ParsedMessage,- MessageToSend,// Thread typesArchiveThreadRequest,UpdateThreadLabelRequest,diff --git a/rust/cloud-storage/email_service/src/main.rs b/rust/cloud-storage/email_service/src/main.rsindex 4726f1c453..7ce566e57e 100644--- a/rust/cloud-storage/email_service/src/main.rs+++ b/rust/cloud-storage/email_service/src/main.rs@@ -3,7 +3,7 @@ use anyhow::Context;use document_storage_service_client::DocumentStorageServiceClient;use email::{domain::service::EmailServiceImpl,- inbound::{EmailDraftRouterState, EmailPreviewState, EmailThreadRouterState},+ inbound::{EmailRouterState, EmailThreadRouterState},outbound::EmailPgRepo,};use email_service::config::EmailServiceCloudfrontSignerPrivateKey;@@ -67,9 +67,7 @@ async fn main() -> anyhow::Result<()> {.await.context("could not connect to db")?;- let gmail_queue_aws_config = macro_aws_config::get_macro_aws_config().await;-- let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(&gmail_queue_aws_config))+ let sqs_client = sqs_client::SQS::new(macro_aws_config::sqs_client().await).gmail_inbox_sync_queue(&config.gmail_inbox_sync_queue).gmail_inbox_sync_retry_queue(&config.gmail_inbox_sync_retry_queue).search_event_queue(&config.search_event_queue)@@ -125,9 +123,12 @@ async fn main() -> anyhow::Result<()> {JwtValidationArgs::new_with_secret_manager(config.environment, &secretsmanager_client).await?;- let email_service = EmailPreviewState::new(EmailServiceImpl::new(+ let sqs_client = Arc::new(sqs_client);+ let email_service = EmailRouterState::new(EmailServiceImpl::new(EmailPgRepo::new(db.clone()),FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(db.clone())),+ (*sqs_client).clone(),+ config.sent_undo_delay_secs,));let entity_access_service = Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(db.clone(),@@ -136,16 +137,12 @@ async fn main() -> anyhow::Result<()> {service: email_service.service(),access_service: entity_access_service.clone(),};- let email_draft_state = EmailDraftRouterState {- service: email_service.service(),- };-api::setup_and_serve(ApiContext {db,config: Arc::new(config),auth_service_client: Arc::new(auth_service_client),redis_client: Arc::new(redis_client),- sqs_client: Arc::new(sqs_client),+ sqs_client,sfs_client: Arc::new(sfs_client),gmail_client: Arc::new(gmail_client),s3_client: Arc::new(s3_client),@@ -156,7 +153,6 @@ async fn main() -> anyhow::Result<()> {email_service,entity_access_service,email_thread_state,- email_draft_state,}).await?;Ok(())diff --git a/rust/cloud-storage/macro_aws_config/Cargo.toml b/rust/cloud-storage/macro_aws_config/Cargo.tomlindex 1b13d89fee..3d48e9ccea 100644--- a/rust/cloud-storage/macro_aws_config/Cargo.toml+++ b/rust/cloud-storage/macro_aws_config/Cargo.toml@@ -6,6 +6,7 @@ version = "0.1.0"[features]s3 = ["dep:aws-sdk-s3"]+sqs = ["dep:aws-sdk-sqs"][dependencies]aws-config = { workspace = true }@@ -15,3 +16,4 @@ thiserror = { workspace = true }tracing = { workspace = true }url = { workspace = true }aws-sdk-s3 = { workspace = true, optional = true }+aws-sdk-sqs = { workspace = true, optional = true }diff --git a/rust/cloud-storage/macro_aws_config/src/lib.rs b/rust/cloud-storage/macro_aws_config/src/lib.rsindex c1cab2e089..e03625f19b 100644--- a/rust/cloud-storage/macro_aws_config/src/lib.rs+++ b/rust/cloud-storage/macro_aws_config/src/lib.rs@@ -19,6 +19,12 @@ pub async fn s3_client() -> aws_sdk_s3::Client {aws_sdk_s3::Client::from_conf(s3_config)}+/// Creates an SQS client+#[cfg(feature = "sqs")]+pub async fn sqs_client() -> aws_sdk_sqs::Client {+ aws_sdk_sqs::Client::new(&get_macro_aws_config().await)+}+/// Creates a aws_config to use./// If you provide `LOCAL_AWS_URL` environment variable we create a local aws/// config with test credentials.diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.json b/rust/cloud-storage/macro_db_client/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.jsonnew file mode 100644index 0000000000..d2b084cf10--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n 'TASK'::property_entity_type,\n u.property_definition_id,\n u.values\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::UUID[],\n $4::JSONB[]\n ) AS u(id, entity_id, property_definition_id, values)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET \n values = EXCLUDED.values,\n updated_at = NOW()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "UuidArray",+ "TextArray",+ "UuidArray",+ "JsonbArray"+ ]+ },+ "nullable": []+ },+ "hash": "1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.json b/rust/cloud-storage/macro_db_client/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.jsonnew file mode 100644index 0000000000..6d97183829--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n 'TASK'::property_entity_type,\n u.property_definition_id,\n NULL\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::UUID[]\n ) AS u(id, entity_id, property_definition_id)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "UuidArray",+ "TextArray",+ "UuidArray"+ ]+ },+ "nullable": []+ },+ "hash": "63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.json b/rust/cloud-storage/macro_db_client/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.jsonnew file mode 100644index 0000000000..9d717fa5f9--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT property_definition_id, values\n FROM entity_properties\n WHERE entity_id = $1\n AND entity_type = 'TASK'\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "property_definition_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "values",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ true+ ]+ },+ "hash": "9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.json b/rust/cloud-storage/macro_db_client/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.jsonnew file mode 100644index 0000000000..182e0858ba--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.json@@ -0,0 +1,18 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n u.entity_type::property_entity_type,\n u.property_definition_id,\n u.values\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::TEXT[],\n $4::UUID[],\n $5::JSONB[]\n ) AS u(id, entity_id, entity_type, property_definition_id, values)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET \n values = EXCLUDED.values,\n updated_at = NOW()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "UuidArray",+ "TextArray",+ "TextArray",+ "UuidArray",+ "JsonbArray"+ ]+ },+ "nullable": []+ },+ "hash": "f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069"+}diff --git a/rust/cloud-storage/soup/examples/ai_tools_cli.rs b/rust/cloud-storage/soup/examples/ai_tools_cli.rsindex f01c0eaa3d..dcc5ad737d 100644--- a/rust/cloud-storage/soup/examples/ai_tools_cli.rs+++ b/rust/cloud-storage/soup/examples/ai_tools_cli.rs@@ -52,7 +52,12 @@ async fn main() {// Create the email service with real database connectionslet email_repo = EmailPgRepo::new(pool.clone());- let email_service = EmailServiceImpl::new(email_repo, frecency_service.clone());+ let email_service = EmailServiceImpl::new(+ email_repo,+ frecency_service.clone(),+ email::domain::ports::NoOpEnqueuer,+ 0,+ );// Create the channels service with real database connectionslet comms_repo = PgCommsRepo { pool: pool.clone() };diff --git a/rust/cloud-storage/soup/src/domain/service/tests.rs b/rust/cloud-storage/soup/src/domain/service/tests.rsindex 7a0ae217a5..c30add8536 100644--- a/rust/cloud-storage/soup/src/domain/service/tests.rs+++ b/rust/cloud-storage/soup/src/domain/service/tests.rs@@ -63,6 +63,14 @@ impl EmailService for NoopEmailService {) -> Result<email::domain::models::CreatedDraft, EmailErr> {Err(EmailErr::RepoErr(anyhow::anyhow!("not implemented")))}++ async fn send_message(+ &self,+ _link: &email::domain::models::Link,+ _input: email::domain::models::CreateDraftInput,+ ) -> Result<email::domain::models::CreatedDraft, EmailErr> {+ Err(EmailErr::RepoErr(anyhow::anyhow!("not implemented")))+ }}struct NoopCommsService;diff --git a/rust/cloud-storage/soup/src/inbound/axum_router.rs b/rust/cloud-storage/soup/src/inbound/axum_router.rsindex 354c2cdbdd..c3c97c0c6e 100644--- a/rust/cloud-storage/soup/src/inbound/axum_router.rs+++ b/rust/cloud-storage/soup/src/inbound/axum_router.rs@@ -15,7 +15,7 @@ use email::{models::{Link, PreviewView},ports::EmailService,},- inbound::{EmailLinkErr, EmailLinkExtractor, EmailPreviewState},+ inbound::{EmailLinkErr, EmailLinkExtractor, EmailRouterState},};use item_filters::{EntityFilters, ast::ExpandErr};use macro_user_id::user_id::MacroUserIdStr;@@ -78,7 +78,7 @@ pub struct SoupPage {pub struct SoupRouterState<T, U> {service: Arc<T>,- email: EmailPreviewState<U>,+ email: EmailRouterState<U>,}impl<T, U> Clone for SoupRouterState<T, U> {@@ -90,7 +90,7 @@ impl<T, U> Clone for SoupRouterState<T, U> {}}-impl<T, U> FromRef<SoupRouterState<T, U>> for EmailPreviewState<U> {+impl<T, U> FromRef<SoupRouterState<T, U>> for EmailRouterState<U> {fn from_ref(input: &SoupRouterState<T, U>) -> Self {input.email.clone()}@@ -104,7 +104,7 @@ wherepub fn new(service: T, email: U) -> Self {SoupRouterState {service: Arc::new(service),- email: EmailPreviewState::new(email),+ email: EmailRouterState::new(email),}}diff --git a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rsindex fe04c14d80..1ad84f8eed 100644--- a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs+++ b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs@@ -107,6 +107,14 @@ impl EmailService for MockEmail {) -> Result<email::domain::models::CreatedDraft, EmailErr> {Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))}++ async fn send_message(+ &self,+ _link: &email::domain::models::Link,+ _input: email::domain::models::CreateDraftInput,+ ) -> Result<email::domain::models::CreatedDraft, EmailErr> {+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))+ }}fn mock_router() -> Router {@@ -187,6 +195,14 @@ impl EmailService for MockEmailLinkResult {) -> Result<email::domain::models::CreatedDraft, EmailErr> {Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))}++ async fn send_message(+ &self,+ _link: &email::domain::models::Link,+ _input: email::domain::models::CreateDraftInput,+ ) -> Result<email::domain::models::CreatedDraft, EmailErr> {+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))+ }}#[tokio::test]diff --git a/rust/cloud-storage/sqs_client/Cargo.toml b/rust/cloud-storage/sqs_client/Cargo.tomlindex 0b20161f2a..48866be586 100644--- a/rust/cloud-storage/sqs_client/Cargo.toml+++ b/rust/cloud-storage/sqs_client/Cargo.toml@@ -24,7 +24,7 @@ default = []document = []document_text_extractor = []-email = ["uuid", "models_email"]+email = ["uuid", "models_email", "dep:email"]gmail = ["model", "uuid"]organization_retention = []search = ["chrono", "model", "models_opensearch", "uuid", "futures"]@@ -36,6 +36,7 @@ upload_extractor = []anyhow = { workspace = true }aws-sdk-sqs = { workspace = true }chrono = { workspace = true, optional = true }+email = { path = "../email", features = ["ports"], optional = true }model = { path = "../model", optional = true }models_email = { path = "../models_email", optional = true }serde = { workspace = true }diff --git a/rust/cloud-storage/sqs_client/src/email.rs b/rust/cloud-storage/sqs_client/src/email.rsindex 4e17090dfc..8f1541d980 100644--- a/rust/cloud-storage/sqs_client/src/email.rs+++ b/rust/cloud-storage/sqs_client/src/email.rs@@ -1,4 +1,5 @@use crate::SQS;+use email::domain::ports::EmailMessageEnqueuer;use models_email::email::service::backfill::BackfillPubsubMessage;use models_email::email::service::pubsub::LinkManagerMessage;use models_email::service::pubsub::{SFSUploaderMessage, ScheduledPubsubMessage};@@ -106,6 +107,26 @@ impl SQS {}}+impl EmailMessageEnqueuer for SQS {+ type Err = anyhow::Error;++ async fn enqueue_scheduled_message(+ &self,+ link_id: Uuid,+ message_id: Uuid,+ delay_seconds: Option<i32>,+ ) -> Result<(), Self::Err> {+ self.enqueue_email_scheduled_message(+ ScheduledPubsubMessage {+ link_id,+ message_id,+ },+ delay_seconds,+ )+ .await+ }+}+#[tracing::instrument(skip(sqs_client))]pub async fn enqueue_link_manager_notification(sqs_client: &aws_sdk_sqs::Client,