Skip to content

: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.

feat(cdp): retire bounce opt-out write and surface suppression skips distinctly (#72500)

Meikel Ratzf33e71da5774
diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.ts
index 1c3a453f96c5..d48b6f6a566a 100644
--- a/nodejs/src/cdp/cdp-api.ts
+++ b/nodejs/src/cdp/cdp-api.ts
@@ -163,7 +163,6 @@ export class CdpApi {
services.hogFunctionMonitoringService,
services.capturedEventsService,
services.teamWorkflowsConfigService,
- services.recipientsManager,
new EmailTrackingCodeSigner(config.ENCRYPTION_SALT_KEYS, config.CDP_EMAIL_TRACKING_URL),
services.emailSuppressionService
)
diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
index cd74a25e7a18..e882acad8a5c 100644
--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
@@ -86,7 +86,7 @@ describe('HogFunctionHandler', () => {
mockHogFunctionExecutor
)
mockRecipientPreferencesService = {
- shouldSkipAction: jest.fn().mockResolvedValue(false),
+ shouldSkipAction: jest.fn().mockResolvedValue(null),
} as any
mockEmailValidationService = {
getSkipReason: jest.fn().mockResolvedValue(null),
@@ -372,8 +372,8 @@ describe('HogFunctionHandler', () => {
expect(calledConfig.mappings).toEqual([{ name: 'input mapping field' }])
})
- it('should skip execution if recipient preferences service returns true', async () => {
- ;(mockRecipientPreferencesService.shouldSkipAction as jest.Mock).mockResolvedValueOnce(true)
+ it('should skip execution and log an opt-out message when recipient preferences returns opted_out', async () => {
+ ;(mockRecipientPreferencesService.shouldSkipAction as jest.Mock).mockResolvedValueOnce('opted_out')
const invocationResult = createInvocationResult<CyclotronJobInvocationHogFlow>(invocation, {
queue: 'hog',
@@ -390,6 +390,39 @@ describe('HogFunctionHandler', () => {
expect(invocationResult.logs[0].message).toContain(
`[Action:function] Recipient has opted out, skipping message delivery.`
)
+ // Opt-out skips do not emit an app metric — no billable_invocation, no email_suppressed.
+ expect(invocationResult.metrics).toEqual([])
+ expect(mockFetch).not.toHaveBeenCalled()
+ })
+
+ // Guards the fix that split suppression from opt-out: previously both branches collapsed to a
+ // single "opted out" log with no metric, so a customer couldn't tell why a workflow send was
+ // skipped or measure suppression volume from the app-metrics view.
+ it('should skip execution, log a suppression message, and emit email_suppressed when recipient preferences returns suppressed', async () => {
+ ;(mockRecipientPreferencesService.shouldSkipAction as jest.Mock).mockResolvedValueOnce('suppressed')
+
+ const invocationResult = createInvocationResult<CyclotronJobInvocationHogFlow>(invocation, {
+ queue: 'hog',
+ queuePriority: 0,
+ })
+
+ const handlerResult = await hogFunctionHandler.execute({ invocation, action, result: invocationResult })
+
+ expect(handlerResult.nextAction?.id).toBe('exit')
+ expect(invocationResult.logs).toHaveLength(1)
+ expect(invocationResult.logs[0].message).toContain(
+ `[Action:function] Skipping send: recipient is on the suppression list.`
+ )
+ expect(invocationResult.metrics).toEqual([
+ {
+ team_id: team.id,
+ app_source_id: invocation.functionId,
+ instance_id: action.id,
+ metric_kind: 'email',
+ metric_name: 'email_suppressed',
+ count: 1,
+ },
+ ])
expect(mockFetch).not.toHaveBeenCalled()
})
@@ -485,7 +518,7 @@ describe('HogFunctionHandler', () => {
})
it('should not emit a billable_invocation metric when recipient opts out', async () => {
- ;(mockRecipientPreferencesService.shouldSkipAction as jest.Mock).mockResolvedValueOnce(true)
+ ;(mockRecipientPreferencesService.shouldSkipAction as jest.Mock).mockResolvedValueOnce('opted_out')
const invocationResult = createInvocationResult<CyclotronJobInvocationHogFlow>(invocation, {
queue: 'hog',
diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
index 64fa03d952fe..f88a37dec05e 100644
--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
@@ -124,23 +124,38 @@ export class HogFunctionHandler implements ActionHandler {
})
)
- const shouldSkip = await instrumentFn(
+ const skipReason = await instrumentFn(
{ key: 'hogFlow.action.hogFunction.recipientPreferences', sendException: false },
() => this.recipientPreferencesService.shouldSkipAction(hogFunctionInvocation, action)
)
- if (shouldSkip) {
+ if (skipReason) {
+ // Suppression and opt-out both short-circuit the send, but a customer reading the run
+ // log needs to know which one — the operator response is different (fix the recipient
+ // list vs. respect the unsubscribe). `email_suppressed` mirrors the metric name the
+ // send-time choke point in email.service.ts emits, so both entry points aggregate.
+ const message =
+ skipReason === 'suppressed'
+ ? `Skipping send: recipient is on the suppression list.`
+ : `Recipient has opted out, skipping message delivery.`
+ const metrics =
+ skipReason === 'suppressed'
+ ? [
+ {
+ team_id: hogFunctionInvocation.teamId,
+ app_source_id: hogFunctionInvocation.functionId,
+ instance_id: action.id,
+ metric_kind: 'email' as const,
+ metric_name: 'email_suppressed' as const,
+ count: 1,
+ },
+ ]
+ : []
return {
finished: true,
skipped: true,
invocation: hogFunctionInvocation,
- logs: [
- {
- level: 'info',
- timestamp: DateTime.now(),
- message: `Recipient has opted out, skipping message delivery.`,
- },
- ],
- metrics: [],
+ logs: [{ level: 'info', timestamp: DateTime.now(), message }],
+ metrics,
capturedPostHogEvents: [],
warehouseWebhookPayloads: [],
emailAssets: [],
diff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts
index c6f65cece14a..670fc344ba10 100644
--- a/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts
@@ -533,7 +533,7 @@ describe('EmailTrackingService', () => {
])
})
- it('inserts a suppressed row for a Permanent bounce webhook (dual-write with the opt-out path)', async () => {
+ it('inserts a suppressed row for a Permanent bounce webhook', async () => {
const hogFlow = await insertHogFlow(hub.postgres, new FixtureHogFlowBuilder().withTeamId(team.id).build())
const email = '[email protected]'
diff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.ts
index 8923d85b7bdd..84e4652a9a79 100644
--- a/nodejs/src/cdp/services/messaging/email-tracking.service.ts
+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.ts
@@ -12,7 +12,6 @@ import { logger } from '~/common/utils/logger'
import { CapturedEventsService } from '../captured-events/captured-events.service'
import { HogFlowManagerService } from '../hogflows/hogflow-manager.service'
import { HogFunctionManagerService } from '../managers/hog-function-manager.service'
-import { RecipientsManagerService } from '../managers/recipients-manager.service'
import { TeamWorkflowsConfigService } from '../managers/team-workflows-config.service'
import { HogFunctionMonitoringService } from '../monitoring/hog-function-monitoring.service'
import { EmailSuppressionService } from './email-suppression.service'
@@ -143,7 +142,6 @@ export class EmailTrackingService {
private hogFunctionMonitoringService: HogFunctionMonitoringService,
private capturedEventsService: CapturedEventsService,
private teamWorkflowsConfigService: TeamWorkflowsConfigService,
- private recipientsManager: RecipientsManagerService,
private trackingCodeSigner: EmailTrackingCodeSigner,
private emailSuppressionService: EmailSuppressionService
) {
@@ -316,7 +314,6 @@ export class EmailTrackingService {
body,
metrics,
logEntries,
- optOutRecipients,
transientBounceRecipients,
hardBounceRecipients,
deliveredRecipients,
@@ -340,7 +337,7 @@ export class EmailTrackingService {
})
}
- // Wrapped so a failure here doesn't skip the opt-out processing below.
+ // Wrapped so a failure here doesn't skip the suppression writes below.
try {
await this.trackLogs(
(logEntries || []).map((entry) => ({
@@ -356,39 +353,7 @@ export class EmailTrackingService {
emailTrackingErrorsCounter.inc({ error_type: 'track_logs_failed', source: 'ses' })
}
- // Collect all emails to opt out per team, then batch each team's opt-out in one query
- const emailsByTeam = new Map<number, string[]>()
- for (const { teamId: teamIdStr, emailAddresses } of optOutRecipients || []) {
- const teamId = teamIdStr ? parseInt(teamIdStr, 10) : NaN
- if (!teamId || isNaN(teamId)) {
- logger.error('[EmailTrackingService] handleSesWebhook: Missing or invalid teamId for opt-out', {
- teamIdStr,
- emailAddresses,
- })
- continue
- }
- const existing = emailsByTeam.get(teamId) ?? []
- existing.push(...emailAddresses)
- emailsByTeam.set(teamId, existing)
- }
-
- for (const [teamId, emails] of emailsByTeam) {
- try {
- await this.recipientsManager.optOut(teamId, emails)
- logger.info('[EmailTrackingService] Opted out recipients after a hard bounce', {
- teamId,
- emails,
- })
- } catch (error) {
- logger.error('[EmailTrackingService] Failed to opt out recipients', {
- teamId,
- emails,
- error,
- })
- }
- }
-
- // Feed soft bounces and successful deliveries into the suppression list. Wrapped so a
+ // Feed bounces and successful deliveries into the suppression list. Wrapped so a
// failure here never affects the webhook's 200 response to SNS. Deliveries are processed
// first so a delivery + bounce in the same batch nets out conservatively (count resets,
// then the fresh bounce re-counts from a clean slate).
@@ -409,9 +374,6 @@ export class EmailTrackingService {
)
}
}
- // Dual-write: hard bounces still go through the opt-out path above; here we also
- // mirror them into the suppression list so the unified deliverability view
- // includes them ahead of phase 2 (retiring the opt-out write).
for (const { teamId, emailAddresses, diagnostic } of hardBounceRecipients || []) {
const parsedTeamId = teamId ? parseInt(teamId, 10) : NaN
if (parsedTeamId && !isNaN(parsedTeamId)) {
diff --git a/nodejs/src/cdp/services/messaging/helpers/ses.test.ts b/nodejs/src/cdp/services/messaging/helpers/ses.test.ts
index 4497a09fb416..4801a165c6ed 100644
--- a/nodejs/src/cdp/services/messaging/helpers/ses.test.ts
+++ b/nodejs/src/cdp/services/messaging/helpers/ses.test.ts
@@ -220,7 +220,9 @@ describe('SesWebhookHandler', () => {
expect(result.metrics).toEqual([])
})
- it('still opts out recipients on a permanent bounce even for test sends', async () => {
+ it('does not suppress recipients on a permanent bounce for test sends', async () => {
+ // Editor "Run test" traffic must not be able to suppress a production address just by
+ // targeting a bad recipient — the isTest gate on suppressionAllowed blocks the write.
const testMail = {
...baseMail,
// isTest rides on the signed header code (preferred by the webhook); the short tag
@@ -243,13 +245,8 @@ describe('SesWebhookHandler', () => {
},
]
const result = await handler.handleWebhook({ body, headers: {} })
- // No metric or log entry recorded for the test send, but the hard bounce still triggers an opt-out
- // (pre-existing behavior, kept unchanged for backward compat).
expect(result.metrics).toEqual([])
expect(result.logEntries).toEqual([])
- expect(result.optOutRecipients).toEqual([{ teamId: '1', emailAddresses: ['[email protected]'] }])
- // Suppression writes are NOT populated for test sends — editor "Run test" traffic shouldn't be
- // able to suppress a production address just by targeting a bad recipient.
expect(result.hardBounceRecipients).toEqual([])
})
@@ -310,7 +307,7 @@ describe('SesWebhookHandler', () => {
])
})
- it('parses a raw Bounce event and returns opt-out recipients for permanent bounces', async () => {
+ it('parses a raw Bounce event and surfaces permanent bounces for suppression', async () => {
const body = [
{
eventType: 'Bounce',
@@ -329,14 +326,13 @@ describe('SesWebhookHandler', () => {
expect(result.status).toBe(200)
expect(result.metrics?.[0].metricName).toBe('email_bounced')
expect(result.metrics?.[0].distinctId).toBe('user-123')
- expect(result.optOutRecipients).toEqual([{ teamId: '1', emailAddresses: ['[email protected]'] }])
- // Dual-write: permanent bounces also surface for the suppression list with the diagnostic.
expect(result.hardBounceRecipients).toEqual([
{ teamId: '1', emailAddresses: ['[email protected]'], diagnostic: 'bad' },
])
+ expect(result.transientBounceRecipients).toEqual([])
})
- it('does not return opt-out recipients for transient bounces', async () => {
+ it('surfaces transient bounces for the soft-bounce counter, not the hard-bounce list', async () => {
const body = [
{
eventType: 'Bounce',
@@ -355,8 +351,7 @@ describe('SesWebhookHandler', () => {
expect(result.status).toBe(200)
expect(result.metrics?.[0].metricName).toBe('email_bounced')
expect(result.metrics?.[0].distinctId).toBe('user-123')
- expect(result.optOutRecipients).toEqual([])
- // Soft bounces are surfaced separately so the suppression list can count them.
+ expect(result.hardBounceRecipients).toEqual([])
expect(result.transientBounceRecipients).toEqual([
{ teamId: '1', emailAddresses: ['[email protected]'], diagnostic: 'temp' },
])
@@ -403,7 +398,7 @@ describe('SesWebhookHandler', () => {
]
const result = await handler.handleWebhook({ body, headers: {}, verifySignature: true })
expect(result.status).toBe(403)
- expect(result.optOutRecipients).toBeUndefined()
+ expect(result.hardBounceRecipients).toBeUndefined()
})
it('parses a raw Complaint event', async () => {
@@ -770,7 +765,6 @@ describe('SesWebhookHandler', () => {
})
const result = await restricted.handleWebhook({ body: envelope, headers: {}, verifySignature: false })
expect(result.status).toBe(403)
- expect(result.optOutRecipients).toBeUndefined()
expect(result.hardBounceRecipients).toBeUndefined()
})
@@ -787,7 +781,9 @@ describe('SesWebhookHandler', () => {
})
const result = await restricted.handleWebhook({ body: envelope, headers: {}, verifySignature: false })
expect(result.status).toBe(200)
- expect(result.optOutRecipients).toEqual([{ teamId: '1', emailAddresses: ['[email protected]'] }])
+ expect(result.hardBounceRecipients).toEqual([
+ { teamId: '1', emailAddresses: ['[email protected]'], diagnostic: 'bad' },
+ ])
})
it('empty allowlist means no restriction (dev/test backward compat)', async () => {
@@ -854,7 +850,6 @@ describe('SesWebhookHandler', () => {
expect(result.transientBounceRecipients).toEqual([])
expect(result.hardBounceRecipients).toEqual([])
expect(result.deliveredRecipients).toEqual([])
- expect(result.optOutRecipients).toEqual([])
// Metrics are unaffected — engagement signal is still emitted for the parsed events.
expect(result.metrics?.length).toBeGreaterThan(0)
})
diff --git a/nodejs/src/cdp/services/messaging/helpers/ses.ts b/nodejs/src/cdp/services/messaging/helpers/ses.ts
index fc54a2328ee2..58c3e5249b91 100644
--- a/nodejs/src/cdp/services/messaging/helpers/ses.ts
+++ b/nodejs/src/cdp/services/messaging/helpers/ses.ts
@@ -422,18 +422,14 @@ export class SesWebhookHandler {
level: SesEventLogLine['level']
message: string
}[]
- optOutRecipients?: {
- teamId?: string
- emailAddresses: string[]
- }[]
// Soft (Transient) bounces — fed into the suppression list's consecutive-bounce counter.
transientBounceRecipients?: {
teamId?: string
emailAddresses: string[]
diagnostic?: string
}[]
- // Hard (Permanent) bounces — mirrored into the suppression list alongside the existing
- // opt-out write, during the dual-write window before the opt-out path is retired.
+ // Hard (Permanent) bounces — recorded in the suppression list so future sends to the address
+ // are blocked. Suppression enforcement replaces the legacy opt-out-on-bounce write.
hardBounceRecipients?: {
teamId?: string
emailAddresses: string[]
@@ -523,10 +519,6 @@ export class SesWebhookHandler {
level: SesEventLogLine['level']
message: string
}[] = []
- const optOutRecipients: {
- teamId?: string
- emailAddresses: string[]
- }[] = []
const transientBounceRecipients: {
teamId?: string
emailAddresses: string[]
@@ -627,20 +619,15 @@ export class SesWebhookHandler {
const codeIsTrusted = parsedCode?.format === 'signed'
// Suppression writes (below) skip test sends — editor "Run test" traffic must not be
- // able to perturb production suppression state by targeting a bad recipient. The
- // pre-existing opt-out push stays ungated for backward compat.
+ // able to perturb production suppression state by targeting a bad recipient.
const suppressionAllowed = teamId && codeIsTrusted && !isTest
- // Opt out recipients on permanent bounces. Dual-write: also mirror into the suppression
- // list with the SMTP diagnostic so a unified deliverability view exists before the
- // opt-out path is retired (see phase 2 of the suppression rollout).
- if (teamId && codeIsTrusted && rec.eventType === 'Bounce' && rec.bounce.bounceType === 'Permanent') {
+ // Record permanent bounces in the suppression list so future sends to the address are
+ // blocked. The SMTP diagnostic is threaded through for operator visibility on the row.
+ if (suppressionAllowed && rec.eventType === 'Bounce' && rec.bounce.bounceType === 'Permanent') {
const emails = rec.bounce.bouncedRecipients.map((r) => r.emailAddress)
const diagnostic = rec.bounce.bouncedRecipients.find((r) => r.diagnosticCode)?.diagnosticCode
- optOutRecipients.push({ teamId, emailAddresses: emails })
- if (!isTest) {
- hardBounceRecipients.push({ teamId, emailAddresses: emails, diagnostic })
- }
+ hardBounceRecipients.push({ teamId, emailAddresses: emails, diagnostic })
}
// Count soft (Transient) bounces toward suppression. These are recipient-side failures
@@ -668,7 +655,6 @@ export class SesWebhookHandler {
body: { ok: true },
metrics,
logEntries,
- optOutRecipients,
transientBounceRecipients,
hardBounceRecipients,
deliveredRecipients,
diff --git a/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts b/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts
index 753f80b9e38f..3e39db4b725e 100644
--- a/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts
@@ -153,7 +153,7 @@ describe('RecipientPreferencesService', () => {
const result = await service.shouldSkipAction(invocation, action)
- expect(result).toBe(true)
+ expect(result).toBe('opted_out')
expect(mockRecipientsManagerGet).toHaveBeenCalledWith({
teamId: team.id,
identifier: '[email protected]',
@@ -177,7 +177,7 @@ describe('RecipientPreferencesService', () => {
const result = await service.shouldSkipAction(invocation, action)
- expect(result).toBe(false)
+ expect(result).toBeNull()
})
it('should return false if recipient has no preference', async () => {
@@ -191,7 +191,7 @@ describe('RecipientPreferencesService', () => {
const result = await service.shouldSkipAction(invocation, action)
- expect(result).toBe(false)
+ expect(result).toBeNull()
})
it('should return false if recipient is not found', async () => {
@@ -202,7 +202,7 @@ describe('RecipientPreferencesService', () => {
const result = await service.shouldSkipAction(invocation, action)
- expect(result).toBe(false)
+ expect(result).toBeNull()
expect(mockRecipientsManagerGet).toHaveBeenCalledWith({
teamId: team.id,
identifier: '[email protected]',
@@ -219,7 +219,7 @@ describe('RecipientPreferencesService', () => {
const result = await service.shouldSkipAction(invocation, action)
- expect(result).toBe(false)
+ expect(result).toBeNull()
expect(loggerSpy).toHaveBeenCalledWith(
'Failed to fetch recipient preferences for [email protected]:',
expect.any(Error)
@@ -251,7 +251,7 @@ describe('RecipientPreferencesService', () => {
const result = await service.shouldSkipAction(invocation, action)
- expect(result).toBe(true)
+ expect(result).toBe('opted_out')
expect(mockRecipientsManagerGetAllMarketingMessagingPreference).toHaveBeenCalledWith(recipient)
})
@@ -272,7 +272,7 @@ describe('RecipientPreferencesService', () => {
const result = await service.shouldSkipAction(invocation, action)
- expect(result).toBe(false)
+ expect(result).toBeNull()
// Transactional messages bypass the opt-out lookup entirely
expect(mockRecipientsManagerGet).not.toHaveBeenCalled()
}
@@ -292,7 +292,7 @@ describe('RecipientPreferencesService', () => {
const result = await service.shouldSkipAction(invocation, action)
- expect(result).toBe(true)
+ expect(result).toBe('opted_out')
expect(mockRecipientsManagerGetAllMarketingMessagingPreference).toHaveBeenCalledWith(recipient)
})
@@ -310,7 +310,7 @@ describe('RecipientPreferencesService', () => {
const result = await service.shouldSkipAction(invocation, action)
- expect(result).toBe(false)
+ expect(result).toBeNull()
expect(mockRecipientsManagerGetAllMarketingMessagingPreference).toHaveBeenCalledWith(recipient)
})
@@ -327,7 +327,7 @@ describe('RecipientPreferencesService', () => {
const result = await service.shouldSkipAction(invocation, action)
- expect(result).toBe(false)
+ expect(result).toBeNull()
expect(mockRecipientsManagerGetAllMarketingMessagingPreference).toHaveBeenCalledWith(recipient)
})
@@ -342,7 +342,7 @@ describe('RecipientPreferencesService', () => {
const result = await service.shouldSkipAction(invocation, action)
- expect(result).toBe(false)
+ expect(result).toBeNull()
expect(mockRecipientsManagerGetAllMarketingMessagingPreference).toHaveBeenCalledWith(recipient)
})
@@ -395,7 +395,7 @@ describe('RecipientPreferencesService', () => {
const result = await service.shouldSkipAction(invocation, action)
- expect(result).toBe(true)
+ expect(result).toBe('suppressed')
})
// A suppressed address placed in cc or bcc must still block the send, because SES
@@ -438,7 +438,7 @@ describe('RecipientPreferencesService', () => {
const result = await service.shouldSkipAction(invocation, action)
- expect(result).toBe(true)
+ expect(result).toBe('suppressed')
}
)
@@ -462,7 +462,7 @@ describe('RecipientPreferencesService', () => {
const result = await service.shouldSkipAction(invocation, action)
- expect(result).toBe(false)
+ expect(result).toBeNull()
})
})
})
@@ -501,7 +501,7 @@ describe('RecipientPreferencesService', () => {
const result = await service.shouldSkipAction(invocation, action)
- expect(result).toBe(true)
+ expect(result).toBe('opted_out')
expect(mockRecipientsManagerGet).toHaveBeenCalledWith({
teamId: team.id,
identifier: '+1234567890',
@@ -521,7 +521,7 @@ describe('RecipientPreferencesService', () => {
const result = await service.shouldSkipAction(invocation, action)
- expect(result).toBe(false)
+ expect(result).toBeNull()
})
it('should throw error if no SMS identifier is found', async () => {
@@ -547,7 +547,7 @@ describe('RecipientPreferencesService', () => {
const result = await service.shouldSkipAction(invocation, action)
- expect(result).toBe(true)
+ expect(result).toBe('opted_out')
expect(mockRecipientsManagerGetAllMarketingMessagingPreference).toHaveBeenCalledWith(recipient)
})
@@ -565,7 +565,7 @@ describe('RecipientPreferencesService', () => {
const result = await service.shouldSkipAction(invocation, action)
- expect(result).toBe(false)
+ expect(result).toBeNull()
expect(mockRecipientsManagerGetAllMarketingMessagingPreference).toHaveBeenCalledWith(recipient)
})
})
@@ -593,27 +593,30 @@ describe('RecipientPreferencesService', () => {
// Push is keyed by the recipient's distinct_id (from the triggering event), not an email/phone
// 'to' field — that is the identifier the device token was registered under.
it.each([
- ['opted out', 'OPTED_OUT', true],
- ['opted in', 'OPTED_IN', false],
- ] as const)('marketing push to a recipient %s of the category → skip=%s', async (_label, status, skip) => {
- const action = createPushAction('123e4567-e89b-12d3-a456-426614174000', 'marketing')
- const invocation = createFunctionStepInvocation(action)
- const recipient = createRecipient('distinct_id', {
- '123e4567-e89b-12d3-a456-426614174000': status,
- })
+ ['opted out', 'OPTED_OUT', 'opted_out'],
+ ['opted in', 'OPTED_IN', null],
+ ] as const)(
+ 'marketing push to a recipient %s of the category → skipReason=%s',
+ async (_label, status, expectedReason) => {
+ const action = createPushAction('123e4567-e89b-12d3-a456-426614174000', 'marketing')
+ const invocation = createFunctionStepInvocation(action)
+ const recipient = createRecipient('distinct_id', {
+ '123e4567-e89b-12d3-a456-426614174000': status,
+ })
- mockRecipientsManagerGet.mockResolvedValue(recipient)
- mockRecipientsManagerGetPreference.mockReturnValue(status)
- mockRecipientsManagerGetAllMarketingMessagingPreference.mockReturnValue('NO_PREFERENCE')
+ mockRecipientsManagerGet.mockResolvedValue(recipient)
+ mockRecipientsManagerGetPreference.mockReturnValue(status)
+ mockRecipientsManagerGetAllMarketingMessagingPreference.mockReturnValue('NO_PREFERENCE')
- const result = await service.shouldSkipAction(invocation, action)
+ const result = await service.shouldSkipAction(invocation, action)
- expect(result).toBe(skip)
- expect(mockRecipientsManagerGet).toHaveBeenCalledWith({
- teamId: team.id,
- identifier: 'distinct_id',
- })
- })
+ expect(result).toBe(expectedReason)
+ expect(mockRecipientsManagerGet).toHaveBeenCalledWith({
+ teamId: team.id,
+ identifier: 'distinct_id',
+ })
+ }
+ )
it('should return false for a transactional push without checking preferences', async () => {
const action = createPushAction('123e4567-e89b-12d3-a456-426614174000', 'transactional')
@@ -621,7 +624,7 @@ describe('RecipientPreferencesService', () => {
const result = await service.shouldSkipAction(invocation, action)
- expect(result).toBe(false)
+ expect(result).toBeNull()
expect(mockRecipientsManagerGet).not.toHaveBeenCalled()
})
@@ -643,7 +646,7 @@ describe('RecipientPreferencesService', () => {
const result = await service.shouldSkipAction(invocation, action)
- expect(result).toBe(true)
+ expect(result).toBe('opted_out')
expect(mockRecipientsManagerGet).toHaveBeenCalledWith({
teamId: team.id,
identifier: 'delivered-person',
@@ -670,7 +673,7 @@ describe('RecipientPreferencesService', () => {
const result = await service.shouldSkipAction(invocation, action)
- expect(result).toBe(false)
+ expect(result).toBeNull()
expect(mockRecipientsManagerGet).not.toHaveBeenCalled()
})
})
diff --git a/nodejs/src/cdp/services/messaging/recipient-preferences.service.ts b/nodejs/src/cdp/services/messaging/recipient-preferences.service.ts
index 080a4ae84d36..6ce834f21e01 100644
--- a/nodejs/src/cdp/services/messaging/recipient-preferences.service.ts
+++ b/nodejs/src/cdp/services/messaging/recipient-preferences.service.ts
@@ -9,6 +9,10 @@ type MessageFunctionActionType = 'function_email' | 'function_sms' | 'function_p
type MessageAction = Extract<HogFlowAction, { type: MessageFunctionActionType }>
+// Why the send was skipped, so callers can render a user-facing log/metric that names the actual
+// reason instead of collapsing suppression and opt-out into a single "opted out" message.
+export type RecipientSkipReason = 'suppressed' | 'opted_out'
+
// Split a comma-separated address list and, for each entry, extract the bare email from an RFC-822
// `"Name" <email@x>` form so it can be matched against normalized suppression identifiers.
const extractEmailsFromAddressList = (value: unknown): string[] => {
@@ -34,25 +38,25 @@ export class RecipientPreferencesService {
public async shouldSkipAction(
invocation: CyclotronJobInvocationHogFunction,
action: HogFlowAction
- ): Promise<boolean> {
+ ): Promise<RecipientSkipReason | null> {
if (!this.isSubjectToRecipientPreferences(action)) {
- return false
+ return null
}
// Suppression is a deliverability signal, not a messaging preference: an address that can't
// receive mail can't receive it regardless of category. So we check it even for
// transactional messages, and before the transactional opt-out bypass below.
if (await this.isRecipientSuppressed(invocation, action)) {
- return true
+ return 'suppressed'
}
// Transactional messages are not eligible for opt-outs, so they send regardless of
// whether the recipient has opted out of this category or of all marketing messaging.
if (action.config.message_category_type === 'transactional') {
- return false
+ return null
}
- return await this.isRecipientOptedOutOfAction(invocation, action)
+ return (await this.isRecipientOptedOutOfAction(invocation, action)) ? 'opted_out' : null
}
private async isRecipientSuppressed(