The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
import { Injectable, Logger } from '@nestjs/common';
import { In } from 'typeorm';
import { isDefined } from 'twenty-shared/utils';
import { v4 } from 'uuid';
import { CampaignDeliveryWorkspaceEntity } from 'src/modules/emailing/standard-objects/campaign-delivery.workspace-entity';
import { SEND_CAMPAIGN_EMAIL_BATCH_JOB } from 'src/engine/core-modules/emailing-domain/constants/send-campaign-email-batch-job.constant';
import { CAMPAIGN_DELIVERY_CLAIM_TTL_MS } from 'src/engine/core-modules/emailing-domain/constants/campaign-delivery-claim-ttl-ms.constant';
import { CAMPAIGN_DELIVERY_STATE } from 'src/engine/core-modules/emailing-domain/constants/campaign-delivery-state.constant';
import { CAMPAIGN_FAILURE_REASON } from 'src/engine/core-modules/emailing-domain/constants/campaign-failure-reason.constant';
import { CAMPAIGN_SEND_RETRY_BACKOFF } from 'src/engine/core-modules/emailing-domain/constants/campaign-send-retry-backoff.constant';
import { CAMPAIGN_SEND_RETRY_LIMIT } from 'src/engine/core-modules/emailing-domain/constants/campaign-send-retry-limit.constant';
import { CAMPAIGN_SKIP_REASON } from 'src/engine/core-modules/emailing-domain/constants/campaign-skip-reason.constant';
import { CLAIMABLE_CAMPAIGN_DELIVERY_STATES } from 'src/engine/core-modules/emailing-domain/constants/claimable-campaign-delivery-states.constant';
import { SEND_SLOT_RETRY } from 'src/engine/core-modules/emailing-domain/constants/send-slot-retry.constant';
import { type SendCampaignEmailBatchJobData } from 'src/engine/core-modules/emailing-domain/types/send-campaign-email-batch-job-data.type';
import { type SendSlotRefusal } from 'src/engine/core-modules/emailing-domain/types/send-slot-refusal.type';
import { applyReplacementTags } from 'src/engine/core-modules/emailing-domain/utils/apply-replacement-tags.util';
import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { CampaignSendSlotService } from 'src/modules/emailing/services/campaign-send-slot.service';
import { CampaignVariableService } from 'src/modules/emailing/services/campaign-variable.service';
import { EmailBillingService } from 'src/modules/emailing/services/email-billing.service';
import { EmailingDomainSenderService } from 'src/modules/emailing/services/emailing-domain-sender.service';
import { MessageCampaignLifecycleService } from 'src/modules/emailing/services/message-campaign-lifecycle.service';
import { MessageCampaignStatisticsService } from 'src/modules/emailing/services/message-campaign-statistics.service';
import { MessageCampaignWorkspaceEntity } from 'src/modules/emailing/standard-objects/message-campaign.workspace-entity';
import { type EmailingDomainEmailTemplate } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-email-template.type';
import { type CampaignDeliverySettlement } from 'src/modules/emailing/types/campaign-delivery-settlement.type';
import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';
import { CampaignTrackingContentService } from 'src/modules/emailing/services/campaign-tracking-content.service';
import { buildCampaignBatchReplacements } from 'src/modules/emailing/utils/build-campaign-batch-replacements.util';
import { buildCampaignThreadExternalId } from 'src/modules/emailing/utils/build-campaign-thread-external-id.util';
import { getCampaignDeliveryTableName } from 'src/modules/emailing/utils/get-campaign-delivery-table-name.util';
import { buildCampaignDeliverySettleQuery } from 'src/modules/emailing/utils/build-campaign-delivery-settle-query.util';
import { compileCampaignBatchTemplate } from 'src/modules/emailing/utils/compile-campaign-batch-template.util';
import { chunkRecipientsToAdmissibleSize } from 'src/modules/emailing/utils/chunk-recipients-to-admissible-size.util';
import { computeSendSlotBackoffMs } from 'src/modules/emailing/utils/compute-send-slot-backoff-ms.util';
import { resolveCampaignBatchSettlements } from 'src/modules/emailing/utils/resolve-campaign-batch-settlements.util';
import { resolveCampaignSendFailure } from 'src/modules/emailing/utils/resolve-campaign-send-failure.util';
import { MessageChannelMessageAssociationWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-channel-message-association.workspace-entity';
import { MessageWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message.workspace-entity';
import { buildOutboundThreadingHeaders } from 'src/modules/messaging/message-outbound-manager/utils/build-outbound-threading-headers.util';
import { PersonWorkspaceEntity } from 'src/modules/person/standard-objects/person.workspace-entity';
type BatchRecipient = SendCampaignEmailBatchJobData['recipients'][number];
@Injectable()
export class MessageCampaignBatchDeliveryService {
private readonly logger = new Logger(
MessageCampaignBatchDeliveryService.name,
);
constructor(
@InjectMessageQueue(MessageQueue.campaignSendQueue)
private readonly messageQueueService: MessageQueueService,
private readonly workspaceOrmManager: WorkspaceOrmManager,
private readonly emailingDomainSenderService: EmailingDomainSenderService,
private readonly emailBillingService: EmailBillingService,
private readonly campaignVariableService: CampaignVariableService,
private readonly campaignTrackingContentService: CampaignTrackingContentService,
private readonly exceptionHandlerService: ExceptionHandlerService,
private readonly messageCampaignLifecycleService: MessageCampaignLifecycleService,
private readonly messageCampaignStatisticsService: MessageCampaignStatisticsService,
private readonly campaignSendSlotService: CampaignSendSlotService,
) {}
async processSendBatchJob(
data: SendCampaignEmailBatchJobData,
): Promise<void> {
const { workspaceId, campaignId } = data;
await this.workspaceOrmManager.executeInWorkspaceContext(async () => {
const campaign =
await this.messageCampaignLifecycleService.findRunningCampaign(
campaignId,
);
const claimToken = v4();
const claimedDeliveryIds = await this.claimBatch({
deliveryIds: data.recipients.map((recipient) => recipient.messageId),
claimToken,
});
if (claimedDeliveryIds.length === 0) {
return;
}
const claimedDeliveryIdSet = new Set(claimedDeliveryIds);
const claimedRecipients = data.recipients.filter((recipient) =>
claimedDeliveryIdSet.has(recipient.messageId),
);
try {
await this.processClaimedBatch({
data,
campaign,
claimToken,
claimedRecipients,
});
} finally {
await this.requeueClaimsNeverHandedToProvider({
claimToken,
});
}
await this.messageCampaignStatisticsService
.scheduleRefresh({ workspaceId, campaignId })
.catch((error) => {
this.logger.error(
`Campaign ${campaignId} could not schedule a statistics refresh: ${
error instanceof Error ? error.message : String(error)
}`,
);
});
await this.messageCampaignLifecycleService.finalizeCampaignIfComplete({
workspaceId,
campaignId,
});
}, buildSystemAuthContext(workspaceId));
}
private async processClaimedBatch({
data,
campaign,
claimToken,
claimedRecipients,
}: {
data: SendCampaignEmailBatchJobData;
campaign: MessageCampaignWorkspaceEntity | null;
claimToken: string;
claimedRecipients: BatchRecipient[];
}): Promise<void> {
const { workspaceId } = data;
if (!isDefined(campaign)) {
await this.settleWholeBatchAs({
claimToken,
recipients: claimedRecipients,
state: CAMPAIGN_DELIVERY_STATE.SKIPPED,
skipReason: CAMPAIGN_SKIP_REASON.CAMPAIGN_CANCELED,
});
return;
}
// Suppressed recipients are resolved before the slots are asked for, so a
// batch full of unsubscribed addresses does not spend send capacity that
// the recipients it actually has could have used. This only sizes the
// charge: the sender resolves suppression again at the handoff, and anyone
// who unsubscribes in between is dropped there. That leaves the batch
// having paid for a slot it did not use, which costs throughput rather than
// mailing someone who opted out.
const blockedAddresses =
await this.emailingDomainSenderService.findBlockedRecipientAddresses({
workspaceId,
sendKind: 'MARKETING',
emailAddresses: claimedRecipients.map((recipient) => recipient.email),
unsubscribeTopicId: campaign.unsubscribeTopicId ?? undefined,
});
const deliverableRecipientCount = claimedRecipients.filter(
(recipient) =>
!blockedAddresses.has(recipient.email.trim().toLowerCase()),
).length;
const sendRefusal =
deliverableRecipientCount === 0
? null
: await this.emailBillingService.findEmailSendRefusal({
workspaceId,
spenders: { userWorkspaceId: data.userWorkspaceId },
emailCount: deliverableRecipientCount,
});
if (isDefined(sendRefusal)) {
await this.settleWholeBatchAs({
claimToken,
recipients: claimedRecipients,
state: CAMPAIGN_DELIVERY_STATE.SKIPPED,
skipReason: CAMPAIGN_SKIP_REASON.OUT_OF_CREDITS,
});
return;
}
const sendSlotRefusal =
deliverableRecipientCount === 0
? null
: await this.campaignSendSlotService.findSendSlotRefusal({
workspaceId,
requestedSlotCount: deliverableRecipientCount,
});
if (isDefined(sendSlotRefusal)) {
await this.deferRateLimitedBatch({
data,
claimToken,
claimedRecipients,
sendSlotRefusal,
});
return;
}
const campaignStillRunning =
await this.messageCampaignLifecycleService.findRunningCampaign(
data.campaignId,
);
if (!isDefined(campaignStillRunning)) {
await this.settleWholeBatchAs({
claimToken,
recipients: claimedRecipients,
state: CAMPAIGN_DELIVERY_STATE.SKIPPED,
skipReason: CAMPAIGN_SKIP_REASON.CAMPAIGN_CANCELED,
});
return;
}
await this.deliverBatch({
data,
campaign: campaignStillRunning,
claimToken,
claimedRecipients,
});
}
private async deferRateLimitedBatch({
data,
claimToken,
claimedRecipients,
sendSlotRefusal,
}: {
data: SendCampaignEmailBatchJobData;
claimToken: string;
claimedRecipients: BatchRecipient[];
sendSlotRefusal: SendSlotRefusal;
}): Promise<void> {
const attemptCount = (data.rateLimitedAttemptCount ?? 0) + 1;
if (attemptCount > SEND_SLOT_RETRY.attemptLimit) {
await this.settleWholeBatchAs({
claimToken,
recipients: claimedRecipients,
state: CAMPAIGN_DELIVERY_STATE.FAILED,
failureReason: CAMPAIGN_FAILURE_REASON.RATE_LIMITED,
});
return;
}
await this.settleWholeBatchAs({
claimToken,
recipients: claimedRecipients,
state: CAMPAIGN_DELIVERY_STATE.QUEUED,
});
// A workspace whose limit is below this batch can never admit it whole, so
// re-queueing the same size would defer until the attempt limit and fail
// recipients the provider would have taken. Split it to what fits instead.
const chunks = chunkRecipientsToAdmissibleSize({
recipients: claimedRecipients,
limitValue: sendSlotRefusal.limitValue,
});
const delay = computeSendSlotBackoffMs({
attemptCount,
retryDelayMs: sendSlotRefusal.retryDelayMs,
windowMs: sendSlotRefusal.windowMs,
});
// A split batch starts its own retry budget: it was never refused at this
// size, and inheriting the count would fail it early.
const requeuedAttemptCount = chunks.length > 1 ? 0 : attemptCount;
await this.messageQueueService.bulkAdd<SendCampaignEmailBatchJobData>(
SEND_CAMPAIGN_EMAIL_BATCH_JOB,
chunks.map((chunk) => ({
data: {
...data,
recipients: chunk,
rateLimitedAttemptCount: requeuedAttemptCount,
},
workspaceId: data.workspaceId,
isWorkspaceJob: true,
})),
{
delay,
retryLimit: CAMPAIGN_SEND_RETRY_LIMIT,
backoff: CAMPAIGN_SEND_RETRY_BACKOFF,
},
);
}
private async deliverBatch({
data,
campaign,
claimToken,
claimedRecipients,
}: {
data: SendCampaignEmailBatchJobData;
campaign: MessageCampaignWorkspaceEntity;
claimToken: string;
claimedRecipients: BatchRecipient[];
}): Promise<void> {
const { workspaceId, campaignId, emailingDomainId } = data;
const { template, plainTextSourceHtml, campaignVariables } =
await compileCampaignBatchTemplate({
subjectTemplate: campaign.subject ?? '',
bodyTemplate: campaign.bodyTemplate ?? '',
});
const personRepository =
this.workspaceOrmManager.getRepositoryWithoutPermissionChecks(
PersonWorkspaceEntity,
);
const people = await personRepository.find({
where: {
id: In(claimedRecipients.map((recipient) => recipient.personId)),
},
});
const personById = new Map(people.map((person) => [person.id, person]));
const replacementsByDeliveryId = new Map<string, Record<string, string>>();
for (const recipient of claimedRecipients) {
const variables =
await this.campaignVariableService.buildVariablesForPerson(
workspaceId,
personById.get(recipient.personId) ?? null,
);
replacementsByDeliveryId.set(
recipient.messageId,
buildCampaignBatchReplacements({ campaignVariables, variables }),
);
}
const trackedBatch = await this.campaignTrackingContentService
.prepareBatch({
workspaceId,
emailingDomainId,
template,
plainTextSourceHtml,
campaignVariables,
recipients: claimedRecipients.map((recipient) => ({
deliveryId: recipient.messageId,
email: recipient.email,
replacements: replacementsByDeliveryId.get(recipient.messageId) ?? {},
})),
})
.catch((error) => {
this.exceptionHandlerService.captureExceptions([error], {
additionalData: { workspaceId, campaignId },
});
this.logger.warn(
`Campaign ${campaignId} of workspace ${workspaceId} is sending a batch without tracking: ${error}`,
);
return { template, replacementsByDeliveryId };
});
const fromAddress = campaign.fromAddress?.primaryEmail ?? '';
const providerOutcome = await this.emailingDomainSenderService
.sendEmailBatch({
workspaceId,
emailingDomainId,
sendKind: 'MARKETING',
from: fromAddress,
template: trackedBatch.template,
recipients: claimedRecipients.map((recipient) => ({
email: recipient.email,
replacements:
trackedBatch.replacementsByDeliveryId.get(recipient.messageId) ??
{},
headers: buildOutboundThreadingHeaders({
threadExternalId: buildCampaignThreadExternalId({
messageId: recipient.messageId,
fromAddress,
}),
}),
})),
unsubscribeTopicId: campaign.unsubscribeTopicId ?? undefined,
})
.catch(async (error) => {
const { shouldRetry } = await this.recordBatchFailure({
campaignId,
claimToken,
claimedRecipients,
error,
});
if (shouldRetry) {
throw error;
}
return null;
});
if (!isDefined(providerOutcome)) {
return;
}
const settlements = resolveCampaignBatchSettlements({
claimedRecipients,
outcome: providerOutcome,
});
const headerMessageIdByDeliveryId = new Map<string, string>();
for (const entry of providerOutcome.entries) {
const recipient = claimedRecipients[entry.recipientIndex];
if (isDefined(recipient) && isDefined(entry.headerMessageId)) {
headerMessageIdByDeliveryId.set(
recipient.messageId,
entry.headerMessageId,
);
}
}
try {
await this.settleDeliveredBatch({
data,
claimToken,
settlements,
template,
replacementsByDeliveryId,
headerMessageIdByDeliveryId,
});
} catch (error) {
await this.settleClaimsAlreadyHandedToProvider({
workspaceId,
claimToken,
settlements,
});
throw error;
}
}
private async settleDeliveredBatch({
data,
claimToken,
settlements,
template,
replacementsByDeliveryId,
headerMessageIdByDeliveryId,
}: {
data: SendCampaignEmailBatchJobData;
claimToken: string;
settlements: CampaignDeliverySettlement[];
template: EmailingDomainEmailTemplate;
replacementsByDeliveryId: Map<string, Record<string, string>>;
headerMessageIdByDeliveryId: Map<string, string>;
}): Promise<void> {
const { workspaceId, campaignId, userWorkspaceId } = data;
const settledDeliveryIds = await this.settleClaimedBatch({
workspaceId,
claimToken,
settlements,
});
const sentSettlements = settlements.filter(
(settlement) =>
settlement.state === CAMPAIGN_DELIVERY_STATE.SENT &&
settledDeliveryIds.has(settlement.deliveryId) &&
isDefined(settlement.providerMessageId),
);
for (const settlement of sentSettlements) {
const providerMessageId = settlement.providerMessageId ?? '';
await this.recordSentMessage({
deliveryId: settlement.deliveryId,
providerMessageId,
headerMessageId:
headerMessageIdByDeliveryId.get(settlement.deliveryId) ??
providerMessageId,
template,
replacements: replacementsByDeliveryId.get(settlement.deliveryId) ?? {},
});
}
const sentDeliveryIds = sentSettlements.map(
(settlement) => settlement.deliveryId,
);
await this.emailBillingService
.billSentEmails({
workspaceId,
sentEmailCount: sentDeliveryIds.length,
spenders: { userWorkspaceId },
})
.catch((error) => {
this.logger.error(
`Campaign ${campaignId} delivered ${sentDeliveryIds.length} message(s) but failed to bill them: ${
error instanceof Error ? error.message : String(error)
}`,
);
});
}
private async recordSentMessage({
deliveryId,
providerMessageId,
headerMessageId,
template,
replacements,
}: {
deliveryId: string;
providerMessageId: string;
headerMessageId: string;
template: EmailingDomainEmailTemplate;
replacements: Record<string, string>;
}): Promise<void> {
const messageRepository =
this.workspaceOrmManager.getRepositoryWithoutPermissionChecks(
MessageWorkspaceEntity,
{ shouldSkipEventEmission: true },
);
await messageRepository.update(deliveryId, {
headerMessageId,
subject: applyReplacementTags(template.subject, replacements),
text: applyReplacementTags(template.text, replacements),
});
const associationRepository =
this.workspaceOrmManager.getRepositoryWithoutPermissionChecks(
MessageChannelMessageAssociationWorkspaceEntity,
{ shouldSkipEventEmission: true },
);
await associationRepository.update(
{ messageId: deliveryId },
{ messageExternalId: providerMessageId },
);
}
private async recordBatchFailure({
campaignId,
claimToken,
claimedRecipients,
error,
}: {
campaignId: string;
claimToken: string;
claimedRecipients: BatchRecipient[];
error: unknown;
}): Promise<{ shouldRetry: boolean }> {
const { state, skipReason, failureReason, shouldRetry } =
resolveCampaignSendFailure(error);
await this.settleWholeBatchAs({
claimToken,
recipients: claimedRecipients,
state: shouldRetry ? CAMPAIGN_DELIVERY_STATE.QUEUED : state,
skipReason,
failureReason,
});
this.logger.warn(
`Campaign ${campaignId} batch of ${claimedRecipients.length} failed: ${
error instanceof Error ? error.message : String(error)
}`,
);
return { shouldRetry };
}
private async claimBatch({
deliveryIds,
claimToken,
}: {
deliveryIds: string[];
claimToken: string;
}): Promise<string[]> {
const { generatedMaps: claimedDeliveries } = await this.workspaceOrmManager
.getRepositoryWithoutPermissionChecks(CampaignDeliveryWorkspaceEntity, {
shouldSkipEventEmission: true,
})
.update(
{ id: In(deliveryIds), state: In(CLAIMABLE_CAMPAIGN_DELIVERY_STATES) },
{
state: CAMPAIGN_DELIVERY_STATE.SENDING,
claimToken,
claimExpiresAt: new Date(Date.now() + CAMPAIGN_DELIVERY_CLAIM_TTL_MS),
},
);
return claimedDeliveries.map((delivery) => delivery.id);
}
private async settleWholeBatchAs({
claimToken,
recipients,
state,
skipReason = null,
failureReason = null,
}: {
claimToken: string;
recipients: BatchRecipient[];
state: CampaignDeliveryWorkspaceEntity['state'];
skipReason?: CampaignDeliveryWorkspaceEntity['skipReason'];
failureReason?: CampaignDeliveryWorkspaceEntity['failureReason'];
}): Promise<void> {
if (recipients.length === 0) {
return;
}
await this.workspaceOrmManager
.getRepositoryWithoutPermissionChecks(CampaignDeliveryWorkspaceEntity, {
shouldSkipEventEmission: true,
})
.update(
{
id: In(recipients.map((recipient) => recipient.messageId)),
claimToken,
},
{
state,
skipReason,
failureReason,
claimToken: null,
claimExpiresAt: null,
},
);
}
private async settleClaimedBatch({
workspaceId,
claimToken,
settlements,
}: {
workspaceId: string;
claimToken: string;
settlements: CampaignDeliverySettlement[];
}): Promise<Set<string>> {
if (settlements.length === 0) {
return new Set();
}
const { sql, parameters } = buildCampaignDeliverySettleQuery({
campaignDeliveryTableName: getCampaignDeliveryTableName(workspaceId),
claimToken,
settlements,
});
const settledRows = await this.workspaceOrmManager
.getRepositoryWithoutPermissionChecks(CampaignDeliveryWorkspaceEntity, {
shouldSkipEventEmission: true,
})
.executeRaw<{ id: string }>(sql, parameters);
return new Set(settledRows.map((row) => row.id));
}
private async requeueClaimsNeverHandedToProvider({
claimToken,
}: {
claimToken: string;
}): Promise<void> {
await this.workspaceOrmManager
.getRepositoryWithoutPermissionChecks(CampaignDeliveryWorkspaceEntity, {
shouldSkipEventEmission: true,
})
.update(
{ claimToken },
{
state: CAMPAIGN_DELIVERY_STATE.QUEUED,
claimToken: null,
claimExpiresAt: null,
},
);
}
// Settling threw after the provider had already taken the batch, so the rows
// still hold their claim. The rows the provider accepted are settled first:
// whatever is left claimed after this is re-queued by the finally block, and
// only recipients the provider never delivered to may safely go back.
private async settleClaimsAlreadyHandedToProvider({
workspaceId,
claimToken,
settlements,
}: {
workspaceId: string;
claimToken: string;
settlements: CampaignDeliverySettlement[];
}): Promise<void> {
const isAcceptedByProvider = (settlement: CampaignDeliverySettlement) =>
settlement.state === CAMPAIGN_DELIVERY_STATE.SENT;
// Keeps the provider message id, which is what later delivery and bounce
// webhooks match on; the reason records that billing and the message rows
// never ran for them.
await this.settleClaimedBatch({
workspaceId,
claimToken,
settlements: settlements
.filter(isAcceptedByProvider)
.map((settlement) => ({
...settlement,
failureReason: CAMPAIGN_FAILURE_REASON.SETTLEMENT_LOST,
})),
});
await this.settleClaimedBatch({
workspaceId,
claimToken,
settlements: settlements.filter(
(settlement) => !isAcceptedByProvider(settlement),
),
});
}
}