:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(cdp): deliver transactional email attachments from a side table (#127986)
Michael Reichenbache6c4c38f8f57
diff --git a/nodejs/src/cdp/async-functions/send-email.ts b/nodejs/src/cdp/async-functions/send-email.tsindex 7b52a3be7edc..c50a70f45c27 100644--- a/nodejs/src/cdp/async-functions/send-email.ts+++ b/nodejs/src/cdp/async-functions/send-email.ts@@ -7,8 +7,9 @@ import { registerAsyncFunction } from '../async-function-registry'registerAsyncFunction('sendEmail', {execute: (args, context, result) => {+ const { attachments: _onlyAnAcceptedSendHasFiles, ...stepEmail } = args[0] ?? {}result.invocation.queueParameters = CyclotronInvocationQueueParametersEmailSchema.parse({- ...args[0],+ ...stepEmail,...acceptedSendEmailFields(context.invocation.state.send),type: 'email',})diff --git a/nodejs/src/cdp/cdp-api.serial.test.ts b/nodejs/src/cdp/cdp-api.serial.test.tsindex 1c9d3271da02..6d075614d7d6 100644--- a/nodejs/src/cdp/cdp-api.serial.test.ts+++ b/nodejs/src/cdp/cdp-api.serial.test.ts@@ -2,8 +2,10 @@import { createMockJobQueue } from '../../tests/helpers/mocks/job-queue.mock'import { mockFetch } from '../../tests/helpers/mocks/request.mock'+import { createHash } from 'crypto'import { Server } from 'http'import jwt from 'jsonwebtoken'+import { Pool } from 'pg'import supertest from 'supertest'import express from 'ultimate-express'@@ -41,6 +43,7 @@ import {transactionalEmailRequestsTotal,transactionalEmailStageDurationMs,} from './services/hogflows/transactional-email'+import { decodeInvocationGlobals } from './services/monitoring/hog-invocation-results.service'import { BASE_REDIS_KEY, HogWatcherState } from './services/monitoring/hog-watcher.service'import { compileHog } from './templates/compiler'import { HogFunctionInvocationGlobals, HogFunctionType } from './types'@@ -2220,6 +2223,26 @@ describe('CDP API', () => {tracking: { captureEngagement: true },}+ const FILE_CONTENT = 'c2VjcmV0LWZpbGU='+ const attachment = (overrides: Record<string, unknown> = {}) => ({+ filename: 'report.pdf',+ content: FILE_CONTENT,+ contentType: 'application/pdf',+ ...overrides,+ })+ const storedAttachments = async (filename: string): Promise<{ job_id: string; content: Buffer }[]> => {+ const pool = new Pool({ connectionString: hub.CYCLOTRON_NODE_DATABASE_URL })+ try {+ return (+ await pool.query('SELECT job_id, content FROM cyclotron_email_attachments WHERE filename = $1', [+ filename,+ ])+ ).rows+ } finally {+ await pool.end()+ }+ }+beforeEach(async () => {produceOutput = jest.spyOn(api['emailStatusService']['outputs'], 'produce')mockQueueInvocations = jest.fn().mockResolvedValue(undefined)@@ -2393,6 +2416,14 @@ describe('CDP API', () => {['transactional_email/send', { ...body, send: { ...codeSend, cc: ['[email protected]'] } }],['transactional_email/send', { ...body, send: { ...codeSend, cc: ['[email protected]'] } }],],+ [+ 'a changed file under the same name',+ ['transactional_email/send', { ...body, send: { ...codeSend, attachments: [attachment()] } }],+ [+ 'transactional_email/send',+ { ...body, send: { ...codeSend, attachments: [attachment({ content: 'b3RoZXI=' })] } },+ ],+ ],] as const)('rejects the key for a request with %s',async (_desc, [firstRoute, first], [route, payload]) => {@@ -2512,12 +2543,58 @@ describe('CDP API', () => {'more than 10 cc addresses',{ ...codeSend, cc: Array.from({ length: 11 }, (_, i) => `copy-${i}@example.com`) },],+ ['a file that is not base64', { ...codeSend, attachments: [attachment({ content: `${FILE_CONTENT}!` })] }],+ ['an empty file', { ...codeSend, attachments: [attachment({ content: '' })] }],+ [+ 'a file too long to check as base64',+ { ...codeSend, attachments: [attachment({ content: 'A'.repeat(4_500_000) })] },+ ],+ [+ 'a file type mailbox providers block',+ { ...codeSend, attachments: [attachment({ filename: 'setup.EXE' })] },+ ],+ ['a file type only SES refuses', { ...codeSend, attachments: [attachment({ filename: 'settings.reg' })] }],+ ['a file type only Gmail blocks', { ...codeSend, attachments: [attachment({ filename: 'disk.iso' })] }],+ [+ 'a filename with a path separator',+ { ...codeSend, attachments: [attachment({ filename: '../report.pdf' })] },+ ],+ [+ 'a filename with a line break',+ { ...codeSend, attachments: [attachment({ filename: 'report\r\n.pdf' })] },+ ],+ [+ 'a content type that is not a MIME type',+ { ...codeSend, attachments: [attachment({ contentType: 'pdf' })] },+ ],+ ['a content id in angle brackets', { ...codeSend, attachments: [attachment({ contentId: '<logo>' })] }],+ [+ 'a content id longer than SES accepts',+ { ...codeSend, attachments: [attachment({ contentId: 'x'.repeat(79) })] },+ ],+ [+ 'a content type longer than SES accepts',+ { ...codeSend, attachments: [attachment({ contentType: `application/${'x'.repeat(67)}` })] },+ ],+ ['a file field this version does not know', { ...codeSend, attachments: [attachment({ size: 11 })] }],+ ['more than 10 files', { ...codeSend, attachments: Array.from({ length: 11 }, () => attachment()) }],+ [+ 'files over 512 KB in total',+ {+ ...codeSend,+ attachments: [+ attachment({ content: Buffer.alloc(300 * 1024).toString('base64') }),+ attachment({ content: `${Buffer.alloc(213 * 1024).toString('base64')}${FILE_CONTENT}` }),+ ],+ },+ ],])('refuses a code send with %s', async (_desc, acceptedSend) => {const invalidBefore = await outcomeCount('invalid_request')const res = await sendAccepted(hogFlow.id, { ...body, send: acceptedSend })expect(res.status).toEqual(400)+ expect(JSON.stringify(res.body)).not.toContain(FILE_CONTENT.slice(0, 12))expect(await outcomeCount('invalid_request')).toEqual(invalidBefore + 1)expect(mockQueueInvocations).not.toHaveBeenCalled()})@@ -2554,6 +2631,65 @@ describe('CDP API', () => {expect(mockQueueInvocations).not.toHaveBeenCalled()})+ it('stores the files of a code send outside the queued run and its snapshot, and a replay stores none', async () => {+ const resultsOutputs = api['invocationResultsService'].invocationResultsRowsService['outputs']+ const produceResultRow = jest.spyOn(resultsOutputs, 'produce')+ const resultsEnabled = hub.HOG_INVOCATION_RESULTS_ENABLED+ hub.HOG_INVOCATION_RESULTS_ENABLED = true+ const filename = `report-${new UUIDT().toString()}.pdf`+ const keyed = {+ ...body,+ idempotency_key: `key-${new UUIDT().toString()}`,+ send: { ...codeSend, attachments: [attachment({ filename })] },+ }++ try {+ const first = await sendAccepted(hogFlow.id, keyed)+ const replay = await sendAccepted(hogFlow.id, keyed)++ expect(first.status).toEqual(202)+ expect(replay.body).toMatchObject({ invocation_id: first.body.invocation_id, replayed: true })+ expect(await storedAttachments(filename)).toEqual([+ { job_id: first.body.invocation_id, content: Buffer.from('secret-file') },+ ])+ const [invocation] = mockQueueInvocations.mock.calls[0][0]+ expect(invocation.state.send.attachments).toEqual([+ {+ filename,+ contentType: 'application/pdf',+ sizeBytes: 11,+ sha256: createHash('sha256').update('secret-file').digest('hex'),+ },+ ])+ expect(JSON.stringify(invocation)).not.toContain(FILE_CONTENT)+ const snapshots = produceResultRow.mock.calls.filter(([output]) => output === 'hog_invocation_results')+ expect(snapshots).not.toHaveLength(0)+ for (const [, message] of snapshots) {+ const row = parseJSON(String(message.value))+ const globals = JSON.stringify(await decodeInvocationGlobals(row.invocation_globals))+ expect(globals).toContain(filename)+ expect(globals).not.toContain(FILE_CONTENT)+ }+ } finally {+ hub.HOG_INVOCATION_RESULTS_ENABLED = resultsEnabled+ }+ })++ it('keeps the stored files when the queue insert fails, as the job may be queued already', async () => {+ mockQueueInvocations.mockRejectedValueOnce(new Error('queue down'))+ const filename = `report-${new UUIDT().toString()}.pdf`++ const res = await sendAccepted(hogFlow.id, {+ ...body,+ send: { ...codeSend, attachments: [attachment({ filename })] },+ })++ expect(res.status).toEqual(500)+ expect(await storedAttachments(filename)).toEqual([+ { job_id: expect.any(String), content: Buffer.from('secret-file') },+ ])+ })+it.each<[string, () => { payload: Record<string, unknown>; verify?: () => void }]>([['the team is over its email quota',diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.tsindex 2071adfc65f1..604149a1ce58 100644--- a/nodejs/src/cdp/cdp-api.ts+++ b/nodejs/src/cdp/cdp-api.ts@@ -57,12 +57,15 @@ import {AcceptedSend,AcceptedSendRequestSchema,CODE_SEND_TOKEN_CLAIMS,+ QueuedSend,TEMPLATE_SEND_TOKEN_CLAIMS,TransactionalEmailOutcome,TransactionalEmailRequest,TransactionalEmailRequestSchema,TransactionalEmailStageTimer,+ decodeAttachments,isRecipientFormatIssue,+ queuedSend,transactionalEmailRecipients,transactionalEmailRequestsTotal,} from './services/hogflows/transactional-email'@@ -71,6 +74,7 @@ import { JobQueue } from './services/job-queue/job-queue.interface'import { GroupsManagerService } from './services/managers/groups-manager.service'import { HogFunctionManagerService } from './services/managers/hog-function-manager.service'import { TeamWorkflowsConfigService } from './services/managers/team-workflows-config.service'+import { EmailAttachmentsService } from './services/messaging/email-attachments.service'import { EMAIL_QUEUE_PRIORITY, EmailQueuePriorityClass, cdpEmailQueuedTotal } from './services/messaging/email-priority'import { EmailStatusService } from './services/messaging/email-status.service'import { EmailSuppressionService } from './services/messaging/email-suppression.service'@@ -178,7 +182,8 @@ const ACCEPTED_SEND_FINGERPRINT_MARKER = 'accepted_send'const transactionalEmailFingerprint = (hogFlowId: string,- { to, distinct_id, variables, send }: TransactionalEmailRequest+ { to, distinct_id, variables }: TransactionalEmailRequest,+ send: QueuedSend | undefined): string => {const templateRequest = [hogFlowId, to, distinct_id, variables]return IdempotencyKeys.fingerprint(@@ -191,7 +196,7 @@ type CallerChosenSender = Partial<NonNullable<AcceptedSend['from']>>const withSenderTheCallerChose = ({from,...send-}: AcceptedSend): Omit<AcceptedSend, 'from'> & { from?: CallerChosenSender } => ({+}: QueuedSend): Omit<QueuedSend, 'from'> & { from?: CallerChosenSender } => ({...send,from: senderTheCallerChose(from),})@@ -236,6 +241,7 @@ export class CdpApi {private transactionalEmailJwt: ScopedServiceJwtprivate transactionalEmailIdempotencyKeys: IdempotencyKeysprivate emailSuppressionService: EmailSuppressionService+ private emailAttachmentsService: EmailAttachmentsServiceprivate emailValidationService: EmailValidationServiceprivate teamWorkflowsConfigService: TeamWorkflowsConfigServiceprivate emailStatusService: EmailStatusService@@ -253,6 +259,7 @@ export class CdpApi {this.hogFlowManager = services.hogFlowManagerthis.recipientTokensService = services.recipientTokensServicethis.emailSuppressionService = services.emailSuppressionService+ this.emailAttachmentsService = services.emailAttachmentsServicethis.emailValidationService = services.emailValidationServicethis.teamWorkflowsConfigService = services.teamWorkflowsConfigServicethis.hogExecutorAsync = services.hogExecutorAsync@@ -366,6 +373,7 @@ export class CdpApi {this.batchExportHogFunctionService.stop(),this.rerunJobManager?.disconnect() ?? Promise.resolve(),this.invocationResultsService.stop(),+ this.emailAttachmentsService.stop(),])}@@ -1288,8 +1296,10 @@ export class CdpApi {})const invocation = createHogFlowInvocation(triggerGlobals, hogFlow, filterGlobals)- if (send) {- invocation.state.send = send+ const files = decodeAttachments(send)+ const sendToQueue = send ? queuedSend(send, files) : undefined+ if (sendToQueue) {+ invocation.state.send = sendToQueue}// The run skips the trigger pipeline that counts runs for event-triggered workflows, so the email// worker counts it instead.@@ -1301,7 +1311,7 @@ export class CdpApi {invocation.queuePriority = EMAIL_QUEUE_PRIORITY[priorityClass]const idempotencyKeys = this.transactionalEmailIdempotencyKeys- const fingerprint = transactionalEmailFingerprint(hogFlow.id, parsed.data)+ const fingerprint = transactionalEmailFingerprint(hogFlow.id, parsed.data, sendToQueue)if (idempotencyKey) {// Checked before the quota, so a retry of a send that went out gets its answer even// when the team has hit its quota since.@@ -1341,6 +1351,10 @@ export class CdpApi {}return reply(refusal.outcome, refusal.status, { error: refusal.outcome })}+ if (files.length) {+ stages.start('files')+ await this.emailAttachmentsService.store(invocation.id, team.id, files)+ }stages.start('queue_insert')this.invocationResultsService.invocationResultsRowsService.queueLifecycleRow(invocation, 'running')try {diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.tsindex f2e268ea6873..f17f1840ab81 100644--- a/nodejs/src/cdp/cdp-services.ts+++ b/nodejs/src/cdp/cdp-services.ts@@ -35,6 +35,10 @@ import { IntegrationManagerService } from './services/managers/integration-managimport { PersonsManagerService } from './services/managers/persons-manager.service'import { RecipientsManagerService } from './services/managers/recipients-manager.service'import { TeamWorkflowsConfigService } from './services/managers/team-workflows-config.service'+import {+ EMAIL_ATTACHMENTS_MAX_CONNECTIONS,+ EmailAttachmentsService,+} from './services/messaging/email-attachments.service'import { EmailStatusService } from './services/messaging/email-status.service'import { EmailSuppressionService } from './services/messaging/email-suppression.service'import { EmailValidationService } from './services/messaging/email-validation.service'@@ -124,6 +128,7 @@ export interface CdpCoreServices {messageAssetsService: MessageAssetsService/** Buffers transactional email status rows. `invocationResultsService.flush()` produces them. */emailStatusService: EmailStatusService+ emailAttachmentsService: EmailAttachmentsService}export type CdpCoreServicesConfig = Pick<@@ -471,6 +476,10 @@ export function createCdpCoreServices(const teamEmailRateLimiter = deps.emailValidationValkey? new RateLimiterService(deps.emailValidationValkey, { name: 'team-email' }): null+ const emailAttachmentsService = new EmailAttachmentsService(+ config.CYCLOTRON_NODE_DATABASE_URL,+ EMAIL_ATTACHMENTS_MAX_CONNECTIONS+ )const emailService = new EmailService({sesAccessKeyId: config.SES_ACCESS_KEY_ID,@@ -495,7 +504,8 @@ export function createCdpCoreServices(workflowsActivationReporter,messageAssetsService,workflowEmailRateLimiter,- teamEmailRateLimiter+ teamEmailRateLimiter,+ emailAttachmentsService)const recipientTokensService = new RecipientTokensService(config.ENCRYPTION_SALT_KEYS, config.SITE_URL)const hogInputsService = new HogInputsService(deps.integrationManager, recipientTokensService, deps.encryptedFields)@@ -644,6 +654,7 @@ export function createCdpCoreServices(recipientTokensService,outputs,emailService,+ emailAttachmentsService,messageAssetsService,emailStatusService,}diff --git a/nodejs/src/cdp/consumers/cdp-base.consumer.ts b/nodejs/src/cdp/consumers/cdp-base.consumer.tsindex 62ed7859cec3..ddc4e8865226 100644--- a/nodejs/src/cdp/consumers/cdp-base.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-base.consumer.ts@@ -26,6 +26,7 @@ import { HogFunctionManagerService } from '../services/managers/hog-function-manimport { HogFunctionTemplateManagerService } from '../services/managers/hog-function-template-manager.service'import { PersonsManagerService } from '../services/managers/persons-manager.service'import { RecipientsManagerService } from '../services/managers/recipients-manager.service'+import { EmailAttachmentsService } from '../services/messaging/email-attachments.service'import { EmailService } from '../services/messaging/email.service'import { RecipientPreferencesService } from '../services/messaging/recipient-preferences.service'import { HogFunctionMonitoringService } from '../services/monitoring/hog-function-monitoring.service'@@ -73,6 +74,7 @@ export abstract class CdpConsumerBase<TConfig extends CdpConsumerBaseConfig = CdrecipientsManager: RecipientsManagerServiceemailService: EmailService+ emailAttachmentsService: EmailAttachmentsServicehogFunctionMonitoringService: HogFunctionMonitoringServiceworkflowsActivationReporter: WorkflowsActivationReportercdpUsageReporter: CdpUsageReporterService@@ -106,6 +108,7 @@ export abstract class CdpConsumerBase<TConfig extends CdpConsumerBaseConfig = Cdthis.recipientPreferencesService = services.recipientPreferencesServicethis.hogFlowExecutor = services.hogFlowExecutorthis.emailService = services.emailService+ this.emailAttachmentsService = services.emailAttachmentsServicethis.hogFunctionMonitoringService = services.hogFunctionMonitoringServicethis.workflowsActivationReporter = services.workflowsActivationReporterthis.cdpUsageReporter = services.cdpUsageReporter@@ -155,6 +158,7 @@ export abstract class CdpConsumerBase<TConfig extends CdpConsumerBaseConfig = Cd// Release the per-consumer conversion-watcher pool created in createCdpCoreServices, so// graceful shutdown frees its cyclotron connections like the other cyclotron pools do.await this.invocationResultsService.stop()+ await this.emailAttachmentsService.stop()logger.info('👍', `${this.name} - stopped!`)}diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.tsindex f7e2639d86c7..613c958d37e7 100644--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts@@ -50,6 +50,24 @@ export class CdpCyclotronWorkerHogFlow extends CdpCyclotronWorker {return [...canceledResults, ...executed]}+ protected override async queueInvocationResults(results: CyclotronJobInvocationResult[]): Promise<void> {+ await super.queueInvocationResults(results)+ await this.deleteAttachmentsOfFinishedSends(results)+ }++ private async deleteAttachmentsOfFinishedSends(results: CyclotronJobInvocationResult[]): Promise<void> {+ await Promise.all(+ results+ .filter(+ (result) =>+ result.finished &&+ (result.invocation.state as CyclotronJobInvocationHogFlow['state'] | null)?.send?.attachments+ ?.length+ )+ .map((result) => this.emailAttachmentsService.delete(result.invocation.id, result.invocation.teamId))+ )+ }+/*** Terminate an invocation as canceled through the normal result pipeline, so the* terminal lifecycle row, app metric, and run log all land. A bare cyclotrondiff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.tsindex 98640b5d993b..6a16e70f7845 100644--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.ts+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.ts@@ -1,6 +1,7 @@import { createMockJobQueue } from '~/tests/helpers/mocks/job-queue.mock'import { DateTime } from 'luxon'+import { Pool } from 'pg'import { HogFlow } from '~/cdp/schema/hogflow'import { InternalPersonWithDistinctId, PersonReadRepository } from '~/common/persons/repositories/person-repository'@@ -13,12 +14,14 @@ import { createTeam, createTestTeamFixture, getTeam } from '~/tests/helpers/sql'import { Hub, InternalPerson, Team } from '../../types'import { FixtureHogFlowBuilder } from '../_tests/builders/hogflow.builder'import { createHogFlowInvocationContext, hideHogFlowsFromReplica, insertHogFlow } from '../_tests/fixtures-hogflows'+import { attachmentMetadata, decodeAttachments } from '../services/hogflows/transactional-email'import {CyclotronJobInvocation,CyclotronJobInvocationHogFlow,CyclotronJobInvocationResult,HogFlowInvocationContext,} from '../types'+import { createInvocationResult } from '../utils/invocation-utils'import { CdpCyclotronWorkerHogFlow } from './cdp-cyclotron-worker-hogflow.consumer'jest.setTimeout(1000)@@ -691,6 +694,100 @@ describe('CdpCyclotronWorkerHogFlow', () => {expect((results[0].invocation as CyclotronJobInvocationHogFlow).hogFlow?.id).toBe(hogFlow.id)})+ describe('attachment files', () => {+ const files = decodeAttachments({+ tracking: { captureEngagement: false },+ attachments: [{ filename: 'report.pdf', content: Buffer.from([0x25, 0x00, 0xff]).toString('base64') }],+ })+ let assertPool: Pool++ beforeEach(() => {+ assertPool = new Pool({ connectionString: hub.CYCLOTRON_NODE_DATABASE_URL })+ })++ afterEach(async () => {+ await processor['emailAttachmentsService'].stop()+ await assertPool.end()+ })++ it.each([+ ['deletes the files of a run canceled before its email step', 'canceled', true, true, 0, 0, null],+ ['deletes the files of a run whose send finished', 'finished', true, true, 0, 0, null],+ [+ 'deletes the files of a finished send whose job row is completed',+ 'finished',+ true,+ true,+ 0,+ 0,+ 'completed',+ ],+ [+ 'keeps the files of a finished send whose job another worker now holds',+ 'finished',+ true,+ true,+ 1,+ 0,+ 'running',+ ],+ [+ 'keeps the files of a finished send whose result was not written',+ 'finished',+ true,+ false,+ 1,+ 0,+ null,+ ],+ ['keeps the files of a run rescheduled for a retry', 'rescheduled', true, true, 1, 0, null],+ ['leaves stored files alone for a run that lists none', 'finished', false, true, 1, 0, null],+ ["leaves another team's files under the same job id alone", 'finished', true, true, 1, 1, null],+ ] as const)(+ '%s',+ async (_name, outcome, listsFiles, resultWritten, rowsLeft, storedTeamOffset, jobStatus) => {+ const invocation = createSerializedHogFlowInvocation(hogFlows[0], {+ event: { distinct_id: 'distinct_person_1', properties: {} } as any,+ })+ ;(invocation.state as CyclotronJobInvocationHogFlow['state']).send = {+ content: { subject: 'Receipt', text: 'Thanks' },+ tracking: { captureEngagement: false },+ attachments: listsFiles ? attachmentMetadata(files) : undefined,+ }+ if (outcome === 'canceled') {+ invocation.cancelRequestedAt = DateTime.now()+ }+ jest.spyOn(processor['hogFlowExecutor'], 'execute').mockImplementation((item) =>+ Promise.resolve(createInvocationResult(item, {}, { finished: outcome === 'finished' }))+ )+ await processor['emailAttachmentsService'].store(+ invocation.id,+ hogFlows[0].team_id + storedTeamOffset,+ files+ )+ if (!resultWritten) {+ jobQueue.queueInvocationResults.mockRejectedValueOnce(new Error('connection terminated'))+ }+ if (jobStatus) {+ await assertPool.query(+ `INSERT INTO cyclotron_jobs (id, team_id, queue_name, status, priority, scheduled, created, last_transition)+ VALUES ($1, $2, 'hogflow', $3, 0, NOW(), NOW(), NOW())`,+ [invocation.id, hogFlows[0].team_id, jobStatus]+ )+ }++ const { backgroundTask } = await processor.processBatch([invocation])+ await backgroundTask.catch(() => undefined)++ const rows = await assertPool.query(+ 'SELECT id FROM cyclotron_email_attachments WHERE job_id = $1',+ [invocation.id]+ )+ expect(rows.rowCount).toBe(rowsLeft)+ }+ )+ })+it('terminates cancel-requested invocations without loading the flow, so cancel works for deleted flows', async () => {const invocation = createSerializedHogFlowInvocation(hogFlows[0], {event: {diff --git a/nodejs/src/cdp/schema/cyclotron.ts b/nodejs/src/cdp/schema/cyclotron.tsindex f70e69f8ab65..4a480d73759d 100644--- a/nodejs/src/cdp/schema/cyclotron.ts+++ b/nodejs/src/cdp/schema/cyclotron.ts@@ -149,6 +149,18 @@ export const CyclotronInvocationQueueParametersFetchSchema = z.object({export const MAX_WORKFLOW_EMAIL_SENDERS = 10+export const MAX_EMAIL_ATTACHMENTS = 10++export const EmailAttachmentMetadataSchema = z.object({+ filename: z.string(),+ contentType: z.string().optional(),+ contentId: z.string().optional(),+ sizeBytes: z.number().int().nonnegative(),+ sha256: z.string(),+})++export type EmailAttachmentMetadata = z.infer<typeof EmailAttachmentMetadataSchema>+export const CyclotronInvocationQueueParametersEmailSchema = z.object({type: z.literal('email'),to: z.object({@@ -171,6 +183,7 @@ export const CyclotronInvocationQueueParametersEmailSchema = z.object({// Emails authored through the API or MCP often carry html only.text: z.string().optional(),html: z.string(),+ attachments: z.array(EmailAttachmentMetadataSchema).max(MAX_EMAIL_ATTACHMENTS).optional(),})export const CyclotronInvocationQueueParametersSendPushNotificationSchema = z.object({diff --git a/nodejs/src/cdp/services/conversion-watchers/conversion-watchers.service.ts b/nodejs/src/cdp/services/conversion-watchers/conversion-watchers.service.tsindex 4c3aa8dd3bca..21cf7e346ea3 100644--- a/nodejs/src/cdp/services/conversion-watchers/conversion-watchers.service.ts+++ b/nodejs/src/cdp/services/conversion-watchers/conversion-watchers.service.ts@@ -1,6 +1,7 @@import { Pool } from 'pg'import { Counter, Gauge } from 'prom-client'+import { LazyPool } from '~/cdp/utils/lazy-pool'import { logger } from '~/common/utils/logger'import { captureException } from '~/common/utils/posthog'@@ -34,33 +35,22 @@ const INSERT_CHUNK_SIZE = 1000*/export class ConversionWatchersService {private queuedRows: ConversionWatcherRow[] = []- private pool: Pool | null = null- private stopped = false+ private readonly pool: LazyPoolprivate inFlight = new Set<Promise<unknown>>()// Owns its pool rather than taking one, mirroring the subscription matcher: the table lives in the// cyclotron database, which nothing else in the result-sink chain connects to. A process without// the connection string drops watchers via the failure counter rather than throwing, so processes// that never run workflows are unaffected.- constructor(- private readonly databaseUrl: string | undefined,- private readonly maxConnections?: number- ) {}-- // Built on first use, not in the constructor. Every CDP service set constructs this service, but- // only the ones that actually run workflows ever write a row — an eager pool would have every- // consumer, and every test that builds a service set, holding cyclotron connections it never uses.- private getPool(): Pool | null {- if (this.pool || this.stopped || !this.databaseUrl) {- return this.pool- }- this.pool = new Pool({ connectionString: this.databaseUrl, max: this.maxConnections })- // pg throws an uncaught exception if an idle client errors with no listener attached, which- // would take down the process for something this sink is allowed to drop.- this.pool.on('error', (err) => {+ constructor(databaseUrl: string | undefined, maxConnections?: number) {+ // Built on first use, not in the constructor. Every CDP service set constructs this service, but+ // only the ones that actually run workflows ever write a row — an eager pool would have every+ // consumer, and every test that builds a service set, holding cyclotron connections it never uses.+ this.pool = new LazyPool(databaseUrl, maxConnections, (err) => {+ // pg throws an uncaught exception if an idle client errors with no listener attached, which+ // would take down the process for something this sink is allowed to drop.logger.error('⚠️', 'Conversion watcher pool error', { err })})- return this.pool}// Idempotent: pg rejects a second end() with "Called end on pool more than once", and several@@ -69,14 +59,12 @@ export class ConversionWatchersService {public async stop(): Promise<void> {// Set first so a flush that has not started yet gets no pool and drops its rows through the// failure counter, rather than opening a connection this method is about to close.- this.stopped = true- // A flush that is already running holds a pool reference and awaits a query. Ending the pool- // under it would fail the work it has not finished, so wait for every one of them. Each- // operation reports its own failure, and shutdown must not re-raise that.- await Promise.all([...this.inFlight].map((operation) => operation.catch(() => {})))- const pool = this.pool- this.pool = null- await pool?.end()+ await this.pool.end(() =>+ // A flush that is already running holds a pool reference and awaits a query. Ending the pool+ // under it would fail the work it has not finished, so wait for every one of them. Each+ // operation reports its own failure, and shutdown must not re-raise that.+ Promise.all([...this.inFlight].map((operation) => operation.catch(() => {})))+ )}public queueInvocationResults(results: CyclotronJobInvocationResult[]): void {@@ -110,7 +98,7 @@ export class ConversionWatchersService {this.queuedRows = []gaugeConversionWatchersPending.set(0)- const pool = this.getPool()+ const pool = this.pool.get()if (!pool) {counterConversionWatchersFailed.inc(rows.length)logger.error('⚠️', 'Dropping conversion watchers: no cyclotron database configured', {diff --git a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.tsindex faf24792b7ea..2e968d2d1df2 100644--- a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts+++ b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts@@ -10,7 +10,7 @@ import {serializeResolverState,} from '../hogflows/batch-resolver.types'import { HogInvocationResultsService } from '../monitoring/hog-invocation-results.service'-import { CyclotronV2Janitor, JANITOR_POISON_PILL_ERROR_KIND } from './janitor'+import { CyclotronV2Janitor, EMAIL_ATTACHMENTS_MAX_AGE_MS, JANITOR_POISON_PILL_ERROR_KIND } from './janitor'import { CyclotronV2Manager } from './manager'import {CYCLOTRON_COUNTER_MAX,@@ -2830,5 +2830,73 @@ describe('Cyclotron V2', () => {await janitor.stop()})++ it('sweeps email attachment rows past the max age and keeps rows of jobs that still wait', async () => {+ const insertAttachment = async (id: string, createdAt: Date): Promise<void> => {+ await assertPool.query(+ `INSERT INTO cyclotron_email_attachments+ (id, job_id, team_id, position, filename, content, size_bytes, sha256, created_at)+ VALUES ($1, $2, 1, 0, 'report.pdf', 'bytes', 5, 'digest', $3)`,+ [id, uuidv7(), createdAt]+ )+ }+ const abandoned = uuidv7()+ const waiting = uuidv7()+ await insertAttachment(abandoned, new Date(Date.now() - EMAIL_ATTACHMENTS_MAX_AGE_MS - 60_000))+ await insertAttachment(waiting, new Date(Date.now() - EMAIL_ATTACHMENTS_MAX_AGE_MS + 3_600_000))++ const janitor = createJanitor()+ await janitor.runOnce()++ const remaining = await assertPool.query(+ `SELECT id FROM cyclotron_email_attachments WHERE id = ANY($1::uuid[])`,+ [[abandoned, waiting]]+ )+ expect(remaining.rows.map((r) => r.id)).toEqual([waiting])++ await janitor.stop()+ })++ it('sweeps expired email attachment rows around a row another sweep holds locked', async () => {+ const expiredAt = new Date(Date.now() - EMAIL_ATTACHMENTS_MAX_AGE_MS - 60_000)+ const locked = uuidv7()+ const free = uuidv7()+ for (const id of [locked, free]) {+ await assertPool.query(+ `INSERT INTO cyclotron_email_attachments+ (id, job_id, team_id, position, filename, content, size_bytes, sha256, created_at)+ VALUES ($1, $2, 1, 0, 'report.pdf', 'bytes', 5, 'digest', $3)`,+ [id, uuidv7(), expiredAt]+ )+ }+ const remainingRows = async (): Promise<string[]> =>+ (+ await assertPool.query(`SELECT id FROM cyclotron_email_attachments WHERE id = ANY($1::uuid[])`, [+ [locked, free],+ ])+ ).rows.map((r) => r.id)++ const janitor = createJanitor()+ const holder = await assertPool.connect()+ try {+ await holder.query('BEGIN')+ await holder.query('SELECT id FROM cyclotron_email_attachments WHERE id = $1 FOR UPDATE', [locked])++ let timer: NodeJS.Timeout | undefined+ const blocked = new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new Error('the sweep waited on the locked row')), 5_000)+ })+ await Promise.race([janitor.sweepEmailAttachments(), blocked]).finally(() => clearTimeout(timer))+ expect(await remainingRows()).toEqual([locked])+ } finally {+ await holder.query('ROLLBACK')+ holder.release()+ }++ await janitor.sweepEmailAttachments()+ expect(await remainingRows()).toEqual([])++ await janitor.stop()+ })})})diff --git a/nodejs/src/cdp/services/cyclotron-v2/janitor.ts b/nodejs/src/cdp/services/cyclotron-v2/janitor.tsindex aad8bf55d709..2c2c45891d4b 100644--- a/nodejs/src/cdp/services/cyclotron-v2/janitor.ts+++ b/nodejs/src/cdp/services/cyclotron-v2/janitor.ts@@ -7,6 +7,7 @@ import { captureException } from '~/common/utils/posthog'import { CYCLOTRON_INVOCATION_JOB_QUEUES, CyclotronJobInvocationHogFlow } from '../../types'import { v2JobToInvocation } from '../job-queue/job-queue-postgres-v2'+import { emailAttachmentOutcomesTotal } from '../messaging/email-attachments.service'import { HogInvocationResultsService } from '../monitoring/hog-invocation-results.service'import {CYCLOTRON_COUNTER_MAX,@@ -75,6 +76,18 @@ const conversionWatchersSweptCounter = new Counter({help: 'Expired conversion watcher rows deleted. These are runs that reached the end of their attribution window without converting.',})+export const EMAIL_ATTACHMENTS_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000++const emailAttachmentsTableBytesGauge = new Gauge({+ name: 'cdp_email_attachments_table_bytes',+ help: 'Total size of cyclotron_email_attachments on disk, with its TOAST data and indexes (pg_total_relation_size). Sampled by the janitor sweep.',+})++const emailAttachmentsRowsGauge = new Gauge({+ name: 'cdp_email_attachments_rows',+ help: 'Planner estimate (pg_class.reltuples) of the rows in cyclotron_email_attachments, one per file of a transactional email that waits to send. Sampled by the janitor sweep without a table scan.',+})+const queueDepthGauge = new Gauge({name: 'cdp_cyclotron_v2_queue_depth',help: 'Number of available jobs per queue',@@ -176,6 +189,7 @@ export class CyclotronV2Janitor {// sweep touches a different table and swallows its own errors, so running it up front keeps// expired watchers draining even while cyclotron cleanup is failing.await this.sweepExpiredConversionWatchers()+ await this.sweepEmailAttachments()const deletedCounts = await this.cleanupTerminalJobs()const deleted = Object.values(deletedCounts).reduce((a, b) => a + b, 0)@@ -530,6 +544,36 @@ export class CyclotronV2Janitor {}}+ async sweepEmailAttachments(): Promise<number> {+ try {+ const result = await this.pool.query(+ `DELETE FROM cyclotron_email_attachments+ WHERE id IN (+ SELECT id FROM cyclotron_email_attachments WHERE created_at < $1 LIMIT $2+ FOR UPDATE SKIP LOCKED+ )`,+ [new Date(Date.now() - EMAIL_ATTACHMENTS_MAX_AGE_MS), this.cleanupBatchSize]+ )+ const swept = result.rowCount ?? 0+ if (swept > 0) {+ emailAttachmentOutcomesTotal.inc({ outcome: 'swept' }, swept)+ logger.info('CyclotronV2Janitor swept email attachment rows', { count: swept })+ }+ const size = await this.pool.query<{ bytes: string; rows: string }>(+ `SELECT pg_total_relation_size('cyclotron_email_attachments') AS bytes,+ (SELECT GREATEST(reltuples, 0)::bigint FROM pg_class+ WHERE oid = 'cyclotron_email_attachments'::regclass) AS rows`+ )+ emailAttachmentsTableBytesGauge.set(Number(size.rows[0].bytes))+ emailAttachmentsRowsGauge.set(Number(size.rows[0].rows))+ return swept+ } catch (err) {+ logger.error('CyclotronV2Janitor email attachment sweep failed', { error: String(err) })+ captureException(err)+ return 0+ }+ }+async measureQueueDepths(): Promise<Map<string, number>> {const result = await this.pool.query<{ queue_name: string; count: string; oldest_due_age_ms: number }>(`SELECT queue_name, COUNT(*) as count,diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.tsindex 465e70a8ade0..ac505acf89cb 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts@@ -39,7 +39,7 @@ import { RecipientPreferencesService } from '../messaging/recipient-preferences.import { RecipientTokensService } from '../messaging/recipient-tokens.service'import { HogFlowExecutorService, createHogFlowInvocation } from './hogflow-executor.service'import { HogFlowFunctionsService } from './hogflow-functions.service'-import { AcceptedSend } from './transactional-email'+import { QueuedSend } from './transactional-email'// Mock before importing fetchjest.mock('~/common/utils/request', () => {@@ -3358,7 +3358,7 @@ describe('Hogflow Executor', () => {html: '',})- const codeSend = (): AcceptedSend => ({+ const codeSend = (): QueuedSend => ({content: { subject: 'Reset your password', html: '<p>Hi {{ variables.name }}</p>', text: 'Hi' },from: { integrationId, email: '[email protected]', name: 'Security' },replyTo: ['[email protected]', '[email protected]'],@@ -3367,6 +3367,13 @@ describe('Hogflow Executor', () => {tracking: { captureEngagement: true },})+ const attachmentFile = {+ filename: 'report.pdf',+ contentType: 'application/pdf',+ sizeBytes: 11,+ sha256: 'a1b2c3',+ }+it('should route email actions to the email queue', async () => {await insertEmailSetup('maildev')@@ -3602,13 +3609,13 @@ if (not res.success) { throw Error(res.error) }`,{name: 'a template send as the step renders it',step: storedStep,- send: (): AcceptedSend | undefined => undefined,+ send: (): QueuedSend | undefined => undefined,expected: () => ({ type: 'email', ...storedStep() }),},{name: 'a code send for a local template as the step renders it',step: storedStep,- send: (): AcceptedSend => ({ tracking: { captureEngagement: false } }),+ send: (): QueuedSend => ({ tracking: { captureEngagement: false } }),expected: () => ({ type: 'email', ...storedStep() }),},{@@ -3628,6 +3635,18 @@ if (not res.success) { throw Error(res.error) }`,html: '<p>Hi {{ variables.name }}</p>',}),},+ {+ name: 'a code send with the metadata of its files, which the email worker loads by job id',+ step: storedStep,+ send: (): QueuedSend => ({ tracking: { captureEngagement: false }, attachments: [attachmentFile] }),+ expected: () => ({ type: 'email', ...storedStep(), attachments: [attachmentFile] }),+ },+ {+ name: 'a step whose own email input lists files without them, because only an accepted send has files',+ step: () => ({ ...storedStep(), attachments: [attachmentFile] }),+ send: (): QueuedSend | undefined => undefined,+ expected: () => ({ type: 'email', ...storedStep() }),+ },])('hands the email queue $name', async ({ step, send, expected }) => {await insertEmailSetup('ses')const invocation = flowInvocation(emailFlow(step()))@@ -3642,7 +3661,7 @@ if (not res.success) { throw Error(res.error) }`,it.each([{name: 'fails a code-key step without an accepted send',- send: (): AcceptedSend | undefined => undefined,+ send: (): QueuedSend | undefined => undefined,sent: 0,},{ name: 'delivers a code-key step with an accepted send', send: codeSend, sent: 1 },diff --git a/nodejs/src/cdp/services/hogflows/transactional-email.ts b/nodejs/src/cdp/services/hogflows/transactional-email.tsindex cf0582f5f63b..2d2292ea514c 100644--- a/nodejs/src/cdp/services/hogflows/transactional-email.ts+++ b/nodejs/src/cdp/services/hogflows/transactional-email.ts@@ -1,7 +1,12 @@+import { createHash } from 'crypto'import { Counter, Histogram } from 'prom-client'import { z } from 'zod'-import { CyclotronInvocationQueueParametersEmailType } from '~/cdp/schema/cyclotron'+import {+ CyclotronInvocationQueueParametersEmailType,+ EmailAttachmentMetadata,+ MAX_EMAIL_ATTACHMENTS,+} from '~/cdp/schema/cyclotron'export const MAX_COPY_RECIPIENTS = 10@@ -14,6 +19,180 @@ const CopyRecipientsSchema = z.readonly().optional()+export const MAX_EMAIL_ATTACHMENTS_BYTES = 512 * 1024++const BLOCKED_ATTACHMENT_EXTENSIONS: ReadonlySet<string> = new Set([+ 'ade',+ 'adp',+ 'apk',+ 'app',+ 'appx',+ 'appxbundle',+ 'asp',+ 'bas',+ 'bat',+ 'cab',+ 'cer',+ 'chm',+ 'cmd',+ 'com',+ 'cpl',+ 'crt',+ 'csh',+ 'der',+ 'diagcab',+ 'diagcfg',+ 'diagpkg',+ 'dll',+ 'dmg',+ 'ex',+ 'ex_',+ 'exe',+ 'fxp',+ 'gadget',+ 'hlp',+ 'hta',+ 'img',+ 'inf',+ 'ins',+ 'iso',+ 'isp',+ 'its',+ 'jar',+ 'jnlp',+ 'js',+ 'jse',+ 'ksh',+ 'lib',+ 'lnk',+ 'mad',+ 'maf',+ 'mag',+ 'mam',+ 'maq',+ 'mar',+ 'mas',+ 'mat',+ 'mau',+ 'mav',+ 'maw',+ 'mda',+ 'mdb',+ 'mde',+ 'mdt',+ 'mdw',+ 'mdz',+ 'mjs',+ 'msc',+ 'msh',+ 'msh1',+ 'msh1xml',+ 'msh2',+ 'msh2xml',+ 'mshxml',+ 'msi',+ 'msix',+ 'msixbundle',+ 'msp',+ 'mst',+ 'nsh',+ 'ops',+ 'pcd',+ 'pif',+ 'plg',+ 'prf',+ 'prg',+ 'ps1',+ 'ps1xml',+ 'ps2',+ 'ps2xml',+ 'psc1',+ 'psc2',+ 'reg',+ 'scf',+ 'scr',+ 'sct',+ 'shb',+ 'shs',+ 'sys',+ 'tmp',+ 'url',+ 'vb',+ 'vbe',+ 'vbs',+ 'vhd',+ 'vps',+ 'vsmacros',+ 'vss',+ 'vst',+ 'vsw',+ 'vxd',+ 'ws',+ 'wsc',+ 'wsf',+ 'wsh',+ 'xll',+ 'xnk',+])++const BASE64_RE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/+const MAX_ATTACHMENT_BASE64_LENGTH = Math.ceil(MAX_EMAIL_ATTACHMENTS_BYTES / 3) * 4+const MIME_TYPE_RE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/i+const CONTROL_CHARACTER_RE = /[\x00-\x1F\x7F]/+const SES_ATTACHMENT_HEADER_MAX_LENGTH = 78++const AttachmentSchema = z+ .object({+ filename: z+ .string()+ .min(1)+ .max(255)+ .refine((name) => !/[\\/]/.test(name) && !CONTROL_CHARACTER_RE.test(name), {+ message: 'filename must not contain a path separator or a line break',+ })+ .refine(+ (name) => {+ const dot = name.lastIndexOf('.')+ return dot < 0 || !BLOCKED_ATTACHMENT_EXTENSIONS.has(name.slice(dot + 1).toLowerCase())+ },+ { message: 'mailbox providers block this file type' }+ ),+ content: z+ .string()+ .min(1, { message: 'content must not be empty' })+ .max(MAX_ATTACHMENT_BASE64_LENGTH, { message: 'attachments must be 512 KB or less in total' })+ .refine((content) => content.length <= MAX_ATTACHMENT_BASE64_LENGTH && BASE64_RE.test(content), {+ message: 'content must be base64',+ }),+ contentType: z+ .string()+ .max(SES_ATTACHMENT_HEADER_MAX_LENGTH)+ .regex(MIME_TYPE_RE, { message: 'contentType must be a MIME type' })+ .optional(),+ contentId: z+ .string()+ .min(1)+ .max(SES_ATTACHMENT_HEADER_MAX_LENGTH)+ .refine((id) => !/[<>]/.test(id) && !CONTROL_CHARACTER_RE.test(id), {+ message: 'contentId must not contain < or > or a line break',+ })+ .optional(),+ })+ .strict()+ .readonly()++const AttachmentsSchema = z+ .array(AttachmentSchema)+ .max(MAX_EMAIL_ATTACHMENTS)+ .refine(+ (files) =>+ files.reduce((total, file) => total + Buffer.byteLength(file.content, 'base64'), 0) <=+ MAX_EMAIL_ATTACHMENTS_BYTES,+ { message: 'attachments must be 512 KB or less in total' }+ )+ .readonly()+ .optional()+export const AcceptedSendSchema = z.object({content: z@@ -38,6 +217,7 @@ export const AcceptedSendSchema = zreplyTo: z.array(z.string()).readonly().optional(),cc: CopyRecipientsSchema,bcc: CopyRecipientsSchema,+ attachments: AttachmentsSchema,tracking: z.object({ captureEngagement: z.boolean() }).strict().readonly(),}).strict()@@ -45,8 +225,33 @@ export const AcceptedSendSchema = zexport type AcceptedSend = z.infer<typeof AcceptedSendSchema>+export type QueuedSend = Omit<AcceptedSend, 'attachments'> & { attachments?: readonly EmailAttachmentMetadata[] }++export type DecodedAttachment = EmailAttachmentMetadata & { content: Buffer }++export const decodeAttachments = (send: AcceptedSend | undefined): DecodedAttachment[] =>+ (send?.attachments ?? []).map(({ filename, content, contentType, contentId }) => {+ const bytes = Buffer.from(content, 'base64')+ return {+ filename,+ ...(contentType !== undefined && { contentType }),+ ...(contentId !== undefined && { contentId }),+ sizeBytes: bytes.length,+ sha256: createHash('sha256').update(bytes).digest('hex'),+ content: bytes,+ }+ })++export const attachmentMetadata = (files: DecodedAttachment[]): EmailAttachmentMetadata[] =>+ files.map(({ content: _content, ...metadata }) => metadata)++export const queuedSend = (send: AcceptedSend, files: DecodedAttachment[]): QueuedSend => {+ const { attachments, ...rest } = send+ return attachments === undefined ? rest : { ...rest, attachments: attachmentMetadata(files) }+}+export const acceptedSendEmailFields = (- send: AcceptedSend | undefined+ send: QueuedSend | undefined): Partial<CyclotronInvocationQueueParametersEmailType> => ({...(send?.content && {subject: send.content.subject,@@ -58,6 +263,7 @@ export const acceptedSendEmailFields = (...(send?.replyTo && { replyTo: send.replyTo.join(', ') }),...(send?.cc && { cc: send.cc.join(', ') }),...(send?.bcc && { bcc: send.bcc.join(', ') }),+ ...(send?.attachments && { attachments: send.attachments.map((file) => ({ ...file })) }),})// What Django sends to run a transactional email's workflow once.@@ -119,6 +325,7 @@ export const TRANSACTIONAL_EMAIL_STAGES = ['build','idempotency','checks',+ 'files','queue_insert','metrics_flush',] as const@@ -126,7 +333,7 @@ export type TransactionalEmailStage = (typeof TRANSACTIONAL_EMAIL_STAGES)[numberexport const transactionalEmailStageDurationMs = new Histogram({name: 'cdp_transactional_email_stage_duration_ms',- help: 'Milliseconds one transactional email request spends in each stage: auth (the JWT), validate (the body), load (the team and the workflow), build (the run and its idempotency fingerprint), idempotency (every Idempotency-Key call to Valkey), checks (suspension, pause, suppression, quota and MX), queue_insert (the email queue insert), metrics_flush (the hand-off of the result and status rows to the Kafka producer, without the wait for the broker), and total. A request records only the stages it reached, so a refusal shows in the stage that refused it.',+ help: 'Milliseconds one transactional email request spends in each stage: auth (the JWT), validate (the body), load (the team and the workflow), build (the run and its idempotency fingerprint), idempotency (every Idempotency-Key call to Valkey), checks (suspension, pause, suppression, quota and MX), files (the attachment rows written to the Cyclotron database), queue_insert (the email queue insert), metrics_flush (the hand-off of the result and status rows to the Kafka producer, without the wait for the broker), and total. A request records only the stages it reached, so a refusal shows in the stage that refused it.',labelNames: ['stage'],buckets: [1, 2.5, 5, 10, 25, 50, 100, 250, 500, 1_000, 2_500, 5_000, 10_000],})diff --git a/nodejs/src/cdp/services/messaging/email-attachments.service.ts b/nodejs/src/cdp/services/messaging/email-attachments.service.tsnew file mode 100644index 000000000000..a8f9f92fb37c--- /dev/null+++ b/nodejs/src/cdp/services/messaging/email-attachments.service.ts@@ -0,0 +1,149 @@+import { createHash } from 'crypto'+import { Counter, Histogram } from 'prom-client'++import { EmailAttachmentMetadata } from '~/cdp/schema/cyclotron'+import { LazyPool } from '~/cdp/utils/lazy-pool'+import { logger } from '~/common/utils/logger'+import { captureException } from '~/common/utils/posthog'++import type { DecodedAttachment } from '../hogflows/transactional-email'++export const EMAIL_ATTACHMENTS_MAX_CONNECTIONS = 5++export type EmailAttachmentOutcome = 'stored' | 'loaded' | 'missing' | 'deleted' | 'swept'++export const emailAttachmentOutcomesTotal = new Counter({+ name: 'cdp_email_attachment_outcomes_total',+ help: 'Transactional email attachment files by outcome: stored by the API, loaded by the email worker, missing when the worker found no matching rows and failed the send, deleted after a terminal send outcome, and swept by the janitor because no send outcome deleted them.',+ labelNames: ['outcome'],+})++export const emailAttachmentBytesPerSend = new Histogram({+ name: 'cdp_email_attachment_bytes_per_send',+ help: 'Total decoded bytes of the attachment files of one transactional email, observed when the API stores them.',+ buckets: [1_024, 8_192, 32_768, 65_536, 131_072, 262_144, 393_216, 524_288],+})++export const EMAIL_ATTACHMENTS_MISSING = 'attachments_missing'++export class EmailAttachmentsMissingError extends Error {+ constructor() {+ super(+ `${EMAIL_ATTACHMENTS_MISSING}: the attachment files of this email are no longer stored, so it was not sent without them.`+ )+ }+}++type AttachmentRow = {+ position: number+ filename: string+ content_type: string | null+ content_id: string | null+ content: Buffer+ sha256: string+}++export class EmailAttachmentsService {+ private readonly pool: LazyPool++ constructor(databaseUrl: string | undefined, maxConnections?: number) {+ this.pool = new LazyPool(databaseUrl, maxConnections, (err) => {+ logger.error('⚠️', 'Email attachments pool error', { error: err.message })+ })+ }++ public async store(jobId: string, teamId: number, files: DecodedAttachment[]): Promise<void> {+ const pool = this.pool.get()+ if (!pool) {+ throw new Error('Email attachments need CYCLOTRON_NODE_DATABASE_URL')+ }+ const values: unknown[] = []+ const placeholders = files.map((file, position) => {+ const offset = values.length+ values.push(+ jobId,+ teamId,+ position,+ file.filename,+ file.contentType ?? null,+ file.contentId ?? null,+ file.content,+ file.sizeBytes,+ file.sha256+ )+ return `(gen_random_uuid(), ${Array.from({ length: 9 }, (_, i) => `$${offset + i + 1}`).join(', ')})`+ })+ await pool.query(+ `INSERT INTO cyclotron_email_attachments+ (id, job_id, team_id, position, filename, content_type, content_id, content, size_bytes, sha256)+ VALUES ${placeholders.join(', ')}`,+ values+ )+ emailAttachmentOutcomesTotal.inc({ outcome: 'stored' }, files.length)+ emailAttachmentBytesPerSend.observe(files.reduce((total, file) => total + file.sizeBytes, 0))+ }++ public async load(+ jobId: string,+ teamId: number,+ expected: readonly EmailAttachmentMetadata[]+ ): Promise<DecodedAttachment[]> {+ const pool = this.pool.get()+ const rows = pool+ ? (+ await pool.query<AttachmentRow>(+ `SELECT position, filename, content_type, content_id, content, sha256+ FROM cyclotron_email_attachments WHERE job_id = $1 AND team_id = $2 ORDER BY position`,+ [jobId, teamId]+ )+ ).rows+ : []+ const matches =+ rows.length === expected.length &&+ rows.every(+ (row, i) =>+ row.position === i &&+ row.sha256 === expected[i].sha256 &&+ createHash('sha256').update(row.content).digest('hex') === expected[i].sha256+ )+ if (!matches) {+ emailAttachmentOutcomesTotal.inc({ outcome: 'missing' }, expected.length)+ logger.error('⚠️', 'Email attachment rows are missing or do not match the job', {+ job_id: jobId,+ expected: expected.length,+ found: rows.length,+ })+ throw new EmailAttachmentsMissingError()+ }+ emailAttachmentOutcomesTotal.inc({ outcome: 'loaded' }, rows.length)+ return rows.map((row, i) => ({ ...expected[i], content: row.content }))+ }++ public async delete(jobId: string, teamId: number): Promise<void> {+ try {+ const pool = this.pool.get()+ if (!pool) {+ return+ }+ const result = await pool.query(+ `DELETE FROM cyclotron_email_attachments+ WHERE job_id = $1 AND team_id = $2+ AND NOT EXISTS (+ SELECT 1 FROM cyclotron_jobs WHERE id = $1 AND status IN ('available', 'running')+ )`,+ [jobId, teamId]+ )+ emailAttachmentOutcomesTotal.inc({ outcome: 'deleted' }, result.rowCount ?? 0)+ } catch (err) {+ logger.warn('⚠️', 'Failed to delete email attachment rows', {+ job_id: jobId,+ error: err instanceof Error ? err.message : String(err),+ })+ captureException(err)+ }+ }++ public async stop(): Promise<void> {+ await this.pool.end()+ }+}diff --git a/nodejs/src/cdp/services/messaging/email.service.test.ts b/nodejs/src/cdp/services/messaging/email.service.test.tsindex d432e9d7b16b..2820f0c621e0 100644--- a/nodejs/src/cdp/services/messaging/email.service.test.ts+++ b/nodejs/src/cdp/services/messaging/email.service.test.ts@@ -2,6 +2,7 @@ import { mockFetch } from '~/tests/helpers/mocks/request.mock'import { MessageRejected, SendingPausedException, TooManyRequestsException } from '@aws-sdk/client-sesv2'import { DateTime } from 'luxon'+import { Pool } from 'pg'import { register } from 'prom-client'import { FixtureHogFlowBuilder } from '~/cdp/_tests/builders/hogflow.builder'@@ -12,6 +13,7 @@ import {CyclotronInvocationQueueParametersEmailType,} from '~/cdp/schema/cyclotron'import { TRANSACTIONAL_EMAIL_EVENT } from '~/cdp/services/hogflows/hogflow-sensitivity'+import { attachmentMetadata, decodeAttachments } from '~/cdp/services/hogflows/transactional-email'import { CyclotronJobInvocationHogFunction } from '~/cdp/types'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'@@ -27,6 +29,7 @@ import { Hub, Team } from '../../../types'import { RecipientsManagerService } from '../managers/recipients-manager.service'import { TeamWorkflowsConfigService } from '../managers/team-workflows-config.service'import { RateLimiterService } from '../rate-limiter/rate-limiter.service'+import { EmailAttachmentsService } from './email-attachments.service'import { selectEmailSenderIntegrationId } from './email-sender-selection'import { EmailStatusService } from './email-status.service'import { EmailSuppressionService, emailSuppressionConfigFromEnv } from './email-suppression.service'@@ -1387,6 +1390,122 @@ describe('EmailService', () => {})})+ describe('attachments', () => {+ let attachments: EmailAttachmentsService+ let assertPool: Pool+ const pdfBytes = Buffer.from([0x25, 0x50, 0x44, 0x46, 0x00, 0x9f, 0xff])+ const files = decodeAttachments({+ tracking: { captureEngagement: false },+ attachments: [+ {+ filename: 'report.pdf',+ content: pdfBytes.toString('base64'),+ contentType: 'application/pdf',+ },+ {+ filename: 'logo.png',+ content: Buffer.from('png bytes').toString('base64'),+ contentType: 'image/png',+ contentId: 'logo',+ },+ ],+ })++ beforeEach(() => {+ attachments = new EmailAttachmentsService(hub.CYCLOTRON_NODE_DATABASE_URL)+ service['emailAttachmentsService'] = attachments+ assertPool = new Pool({ connectionString: hub.CYCLOTRON_NODE_DATABASE_URL })+ invocation.id = new UUIDT().toString()+ invocation.queueParameters = createEmailParams({+ from: { integrationId: 1 },+ attachments: attachmentMetadata(files),+ })+ })++ afterEach(async () => {+ await attachments.stop()+ await assertPool.end()+ })++ it.each([+ ['on the first try', null],+ [+ 'on the retry after an SES throttle',+ () => sendEmailSpy.mockRejectedValueOnce(new ThrottlingException('Rate exceeded')),+ ],+ [+ 'on the retry after the attachment store fails to answer',+ () =>+ jest+ .spyOn(attachments, 'load')+ .mockRejectedValueOnce(new Error('timeout exceeded when trying to connect')),+ ],+ ])('delivers the files to SES as Base64 attachments %s', async (_name, failFirstTry) => {+ failFirstTry?.()+ sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })+ await attachments.store(invocation.id, team.id, files)++ let result = await service.executeSendEmail(invocation)+ if (failFirstTry) {+ expect(result.finished).toBe(false)+ expect(result.error).toBeUndefined()+ expect(result.invocation.queueScheduledAt!.toMillis()).toBeGreaterThan(Date.now())+ result = await service.executeSendEmail(result.invocation)+ }++ expect(result.finished).toBe(true)+ expect(result.error).toBeUndefined()+ const sentCommand = sendEmailSpy.mock.calls.at(-1)![0] as { input: any }+ expect(sentCommand.input.Content.Simple.Attachments).toEqual([+ {+ RawContent: pdfBytes,+ FileName: 'report.pdf',+ ContentType: 'application/pdf',+ ContentId: undefined,+ ContentDisposition: 'ATTACHMENT',+ ContentTransferEncoding: 'BASE64',+ },+ {+ RawContent: Buffer.from('png bytes'),+ FileName: 'logo.png',+ ContentType: 'image/png',+ ContentId: 'logo',+ ContentDisposition: 'INLINE',+ ContentTransferEncoding: 'BASE64',+ },+ ])+ })++ it.each([+ ['no row is stored', async () => {}],+ [+ 'the files under this job id belong to another team',+ async () => {+ await attachments.store(invocation.id, team.id + 1, files)+ },+ ],+ [+ 'a stored file does not match its checksum',+ async () => {+ await attachments.store(invocation.id, team.id, files)+ await assertPool.query(+ `UPDATE cyclotron_email_attachments SET content = 'other bytes' WHERE job_id = $1 AND position = 1`,+ [invocation.id]+ )+ },+ ],+ ])('fails the send as attachments_missing and sends nothing when %s', async (_name, arrange) => {+ sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })+ await arrange()++ const result = await service.executeSendEmail(invocation)++ expect(sendEmailSpy).not.toHaveBeenCalled()+ expect(result.finished).toBe(true)+ expect(result.error).toMatch(/^attachments_missing: /)+ })+ })+const sesAccepts = (): void => {sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })}diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.tsindex c6b38a090ddc..76e4b06c1216 100644--- a/nodejs/src/cdp/services/messaging/email.service.ts+++ b/nodejs/src/cdp/services/messaging/email.service.ts@@ -19,14 +19,20 @@ import { buildIntegerMatcher } from '~/common/config/matchers'import { logger } from '~/common/utils/logger'import { TRANSACTIONAL_EMAIL_EVENT } from '../hogflows/hogflow-sensitivity'+import type { DecodedAttachment } from '../hogflows/transactional-email'import { IntegrationManagerService } from '../managers/integration-manager.service'import { RecipientManagerRecipient, RecipientsManagerService } from '../managers/recipients-manager.service'import { TeamWorkflowsConfigService } from '../managers/team-workflows-config.service'import { WorkflowsActivationReporter } from '../monitoring/workflows-activation-reporter'import { RateLimiterService } from '../rate-limiter/rate-limiter.service'+import {+ EMAIL_ATTACHMENTS_MISSING,+ EmailAttachmentsMissingError,+ EmailAttachmentsService,+} from './email-attachments.service'import { getEmailQueuePriorityClass } from './email-priority'import { selectEmailSenderIntegrationId } from './email-sender-selection'-import { EmailStatusService, isTransactionalEmailSend } from './email-status.service'+import { EmailStatusReason, EmailStatusService, isTransactionalEmailSend } from './email-status.service'import { EmailSuppressionService, SuppressionCheckOptions } from './email-suppression.service'import {addTrackingToEmail,@@ -156,6 +162,17 @@ export class SESThrottleError extends Error {}}+class EmailAttachmentsUnavailableError extends Error {+ constructor(cause: unknown) {+ super('Could not load the attachment files of this email', { cause })+ this.name = 'EmailAttachmentsUnavailableError'+ }+}++function pickAttachmentLoadRetryDelayMs(tries: number): number {+ return Math.min(1_000 * tries + Math.floor(Math.random() * 1_000), 60_000)+}+class UnverifiedEmailDomainError extends Error {constructor() {super('The selected email integration domain is not verified')@@ -453,7 +470,8 @@ export class EmailService {private workflowsActivationReporter: Pick<WorkflowsActivationReporter, 'report'>,private messageAssetsService?: MessageAssetsService,private workflowEmailRateLimiter: RateLimiterService | null = null,- private teamEmailRateLimiter: RateLimiterService | null = null+ private teamEmailRateLimiter: RateLimiterService | null = null,+ private emailAttachmentsService: EmailAttachmentsService | null = null) {this.sesV2Client = this.sesConfig.sesRegion? new SESv2Client({@@ -495,9 +513,10 @@ export class EmailService {const integration = await this.integrationManager.get(integrationId)let success: boolean = false- let throttled: boolean = false+ let rescheduled: boolean = falselet assetRow: MessageAssetRow | null = nulllet trackingEnabled = true+ let failureReason: EmailStatusReason = 'provider_error'try {// Team-level kill switches: staff suspend all workflow email for a team whose sender@@ -776,12 +795,14 @@ export class EmailService {}: paramsWithReplyTo+ const files = await this.loadAttachments(invocation.id, invocation.teamId, params.attachments)+switch (integration.config.provider ?? 'ses') {case 'maildev':- await this.sendEmailWithMaildev(result, sendParams, from, trackingEnabled, isTest)+ await this.sendEmailWithMaildev(result, sendParams, from, trackingEnabled, isTest, files)breakcase 'ses':- await this.sendEmailWithSES(result, sendParams, from, trackingEnabled, isTest, queueWait)+ await this.sendEmailWithSES(result, sendParams, from, trackingEnabled, isTest, queueWait, files)breakcase 'unsupported':@@ -804,13 +825,30 @@ export class EmailService {// Treat as a transient delivery delay — reschedule rather than fail// the job. Our local bucket is the primary throttle; this path// catches the cases where SES disagrees with our estimate.- throttled = true+ rescheduled = trueresult.finished = falseresult.invocation.queueParameters = paramsresult.invocation.queueMetadata = invocation.queueMetadataresult.invocation.queueScheduledAt = DateTime.utc().plus({ milliseconds: error.retryAfterMs })addLog('warn', `SES rate-limited (${error.errorCode}); rescheduling email in ${error.retryAfterMs}ms`)+ } else if (error instanceof EmailAttachmentsUnavailableError) {+ const tries = (invocation.queueMetadata?.attachmentLoadTries ?? 0) + 1+ const retryDelayMs = pickAttachmentLoadRetryDelayMs(tries)+ rescheduled = true+ result.finished = false+ result.invocation.queueParameters = params+ result.invocation.queueMetadata = { ...invocation.queueMetadata, attachmentLoadTries: tries }+ result.invocation.queueScheduledAt = DateTime.utc().plus({ milliseconds: retryDelayMs })+ addLog('warn', `${error.message}; rescheduling email in ${retryDelayMs}ms`)+ logger.warn('⚠️', 'Failed to load email attachment rows', {+ job_id: invocation.id,+ tries,+ error: error.cause instanceof Error ? error.cause.message : String(error.cause),+ })} else {+ if (error instanceof EmailAttachmentsMissingError) {+ failureReason = EMAIL_ATTACHMENTS_MISSING+ }addLog('error', error.message)result.error = error.messageresult.emailSendResult = { status: 'failed', reason: error.message }@@ -825,7 +863,7 @@ export class EmailService {}}- if (throttled) {+ if (rescheduled) {// On throttle, skip both the VM-state push and the business-metric// emit. The eventual successful retry will produce `email_sent` and// push the success bit to the VM stack — pushing them now would@@ -874,7 +912,7 @@ export class EmailService {teamId: invocation.teamId,messageId: invocation.id,status: success ? 'sent' : 'failed',- reason: success ? undefined : 'provider_error',+ reason: success ? undefined : failureReason,})}}@@ -1186,13 +1224,35 @@ export class EmailService {return overrideEmail}+ private async loadAttachments(+ jobId: string,+ teamId: number,+ expected: CyclotronInvocationQueueParametersEmailType['attachments']+ ): Promise<DecodedAttachment[]> {+ if (!expected?.length) {+ return []+ }+ if (!this.emailAttachmentsService) {+ throw new EmailAttachmentsMissingError()+ }+ try {+ return await this.emailAttachmentsService.load(jobId, teamId, expected)+ } catch (error) {+ if (error instanceof EmailAttachmentsMissingError) {+ throw error+ }+ throw new EmailAttachmentsUnavailableError(error)+ }+ }+// Send email to local maildev instance for testing (DEBUG=1 only)private async sendEmailWithMaildev(result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>,params: CyclotronInvocationQueueParametersEmailType,from: { email: string; name: string },trackingEnabled: boolean,- isTest = false+ isTest = false,+ files: DecodedAttachment[] = []): Promise<void> {// This can timeout but there is no native timeout so we do our own oneconst mailOptions: SendMailOptions = {@@ -1223,6 +1283,15 @@ export class EmailService {if (replyToAddresses) {mailOptions.replyTo = replyToAddresses}+ if (files.length) {+ mailOptions.attachments = files.map((file) => ({+ filename: file.filename,+ content: file.content,+ contentType: file.contentType,+ cid: file.contentId,+ contentDisposition: file.contentId ? 'inline' : 'attachment',+ }))+ }const response = await mailDevTransport!.sendMail(mailOptions)@@ -1239,7 +1308,8 @@ export class EmailService {from: { email: string; name: string },trackingEnabled: boolean,isTest = false,- queueWait?: EmailQueueWait+ queueWait?: EmailQueueWait,+ files: DecodedAttachment[] = []): Promise<void> {if (!this.sesV2Client) {throw new Error('SES is not configured - set SES_REGION and AWS credentials')@@ -1334,6 +1404,16 @@ export class EmailService {): []sendEmailParams.Content.Simple.Headers = [...unsubscribeHeaders, trackingHeader, AUTO_SUBMITTED_HEADER]+ if (files.length) {+ sendEmailParams.Content.Simple.Attachments = files.map((file) => ({+ RawContent: file.content,+ FileName: file.filename,+ ContentType: file.contentType,+ ContentId: file.contentId,+ ContentDisposition: file.contentId ? 'INLINE' : 'ATTACHMENT',+ ContentTransferEncoding: 'BASE64',+ }))+ }}const replyToAddresses = parseAddressList(params.replyTo)diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.tsindex 62ee80fa99ca..1839c58db50d 100644--- a/nodejs/src/cdp/types.ts+++ b/nodejs/src/cdp/types.ts@@ -13,7 +13,7 @@ import {PersonPropertyFilter,Team,} from '../types'-import type { AcceptedSend } from './services/hogflows/transactional-email'+import type { QueuedSend } from './services/hogflows/transactional-email'import type { HogErrorClass } from './utils/hog-error-classification'export type HogBytecode = any[]@@ -432,7 +432,7 @@ export type CyclotronJobInvocationHogFunctionContext = {sensitive?: booleanactionStepCount?: numbercustomerTaskIdempotencyVersion?: 1- send?: AcceptedSend+ send?: QueuedSend}export type WorkflowStepResumeStatus = 'completed' | 'failed' | 'cancelled'@@ -579,7 +579,7 @@ export type HogFlowInvocationContext = {// conversions are counted by the matcher and never touch this flag.conversionCounted?: booleanvariables?: Record<string, any>- send?: AcceptedSend+ send?: QueuedSend// Sticky counter incremented by the rerun paginator on rehydration. Lets// the lifecycle row producer derive `attempts` / `is_retry` for hog flows// the same way it does for hog functions, so the `max_attempts` guard ondiff --git a/nodejs/src/cdp/utils/lazy-pool.ts b/nodejs/src/cdp/utils/lazy-pool.tsnew file mode 100644index 000000000000..d641f7291c6f--- /dev/null+++ b/nodejs/src/cdp/utils/lazy-pool.ts@@ -0,0 +1,29 @@+import { Pool } from 'pg'++export class LazyPool {+ private pool: Pool | null = null+ private ended = false++ constructor(+ private readonly databaseUrl: string | undefined,+ private readonly maxConnections: number | undefined,+ private readonly onError: (err: Error) => void+ ) {}++ public get(): Pool | null {+ if (this.pool || this.ended || !this.databaseUrl) {+ return this.pool+ }+ this.pool = new Pool({ connectionString: this.databaseUrl, max: this.maxConnections })+ this.pool.on('error', this.onError)+ return this.pool+ }++ public async end(drain?: () => Promise<unknown>): Promise<void> {+ this.ended = true+ await drain?.()+ const pool = this.pool+ this.pool = null+ await pool?.end()+ }+}