import Inject from "@entity-access/entity-access/dist/di/di.js"; import SocialMailContext from "../../model/SocialMailContext.js"; import Workflow, { UniqueActivity } from "@entity-access/entity-access/dist/workflows/Workflow.js"; // import BroadcastEmailToMX from "../channel/BroadcastEmailToMX.js"; import DispatchEmailToMX from "./DispatchEmailToMX.js"; import Sql from "@entity-access/entity-access/dist/sql/Sql.js"; import EmailReferenceService from "../../smtp/services/EmailReferenceService.js"; import EmailPostReceiveService from "../../smtp/services/EmailPostReceiveService.js"; import DateTime from "@entity-access/entity-access/dist/types/DateTime.js"; import EmailRecipient from "../../model/entities/EmailRecipient.js"; import EmailAddressService from "../../services/EmailAddressService.js"; import { IMessageEnvelope } from "./IMessageEnvelope.js"; import sleep from "../../../common/sleep.js"; const pad = (n, max) => { if (n < 0) { return "-" + pad(-n, max); } const s: string = n.toString(); return s.padStart(max, "0"); }; const toHost = (x: string) => x.split("@",2).pop(); export default class PrepareEmailToSend extends Workflow { static taskGroup = "prepare"; static taskGroups = ["priority-prepare"]; async run() { let inputs: (IMessageEnvelope & { group?, maxPerSecond? })[] for(let i=0;i<5;i++) { inputs = await this.prepareMessage(i); if (inputs) { // we got the inputs break; } await sleep(500); } if(!inputs) { return; } await this.all(inputs.map((x) => this.runChild(DispatchEmailToMX, x, x.group ? { group: x.group, maxPerSecond: x.maxPerSecond } : void 0, x.priority > 0 ? "priority-send" : "send" ) )); await this.updateStatus(); return ""; } /** * We will compose an email and save it to the cloud after signing * @param db Database * @returns error */ @UniqueActivity async prepareMessage( attempt, @Inject db?: SocialMailContext, @Inject eas?: EmailAddressService ) { db.verifyFilters = false; db.raiseEvents = false; const email = await db.emails .where({ id: this.input , wid: this.id}, (x, p) => x.emailID === p.id && x.workflowID === p.wid && x.isNote === false ) .include((x) => [ x.senderEmail, x.recipients.forEach((er) => er.emailAddress.domain)]) .first(); if (email?.workflowID !== this.id) { // send has been cancelled. return; } if(!email.recipients?.length) { // save failed.. we should retry after some time... return; } if (email.status !== "scheduled") { return; } const mailbox = await eas.getHostedMailboxByID(email.senderID); const hostedDomain = await eas.getHostedDomainByID(mailbox.domainID); await db.emails.where(email, (x, p) => x.emailID === p.emailID) .update((x) => ({ dateUpdated: Sql.date.now()})); if (hostedDomain?.returnPath) { const { returnPath } = hostedDomain; const headers = JSON.parse(email.headers ??= "{}"); if(headers["Return-Path"] !== returnPath) { headers["Return-Path"] = returnPath; email.headers = JSON.stringify(headers); await db.emails.withKeys({ emailID: email.emailID }).update({ headers }); } } let maxPerSecond = void 0; let group = void 0; if (!mailbox.isExternal) { maxPerSecond = Number(hostedDomain.maxSendPerSecond ?? 0); group = `send-throttle-d-${mailbox.domainID}`; if (!maxPerSecond) { group = `send-throttle-mb-${mailbox.mailboxID}`; maxPerSecond = Number(mailbox.maxSendPerSecond ?? 0); } if (!maxPerSecond) { group = void 0; maxPerSecond = void 0; } } const dateSent = DateTime.now; const recipients = [] as EmailRecipient[]; for(const er of email.recipients) { const { emailAddressID } = er; const { senderID } = email; const highFailureRate = await db.mailboxContacts.where({ emailAddressID, senderID }, (x, p) => x.mailboxID === p.senderID && x.emailAddressID === p.emailAddressID && x.deliveryFailureRate > 0.5 ).some(); if (highFailureRate) { const { emailID } = er; await db.emailRecipients.withKeys({ emailAddressID, emailID}) .update({ status: "sent-failed", error: "Suppressed due to recent failures", dateSent }); continue; } recipients.push(er); } const outsiders = recipients .map((x) => ({ host: toHost(x.replyTo || x.emailAddress.emailAddress), recipientAddress: x.replyTo || x.emailAddress.emailAddress, from: mailbox.emailAddress.emailAddress, senderID: email.senderID, emailID: x.emailID, recipientAddressID: x.emailAddressID, external: mailbox.isExternal, maxPerSecond, priority: email.priority, doNotSendDR: email.doNotSendDR, group })); return outsiders; } @UniqueActivity async updateStatus( @Inject db?: SocialMailContext, @Inject ers?: EmailReferenceService, @Inject eps?: EmailPostReceiveService ) { const [sent] = await db.emails.where({ id: this.input}, (x, p) => x.emailID === p.id && x.status !== "published") .updateSelect((x) => ({ status: "sent", dateUpdated: Sql.date.now() })); const emailID = this.input; await ers.updateReferences({ emailID, silent: true }); await db.emails.statements.update({ stateReferencesUpdated: true}, { emailID }); // load recipients... await eps.executeAll(sent); } }