-
Notifications
You must be signed in to change notification settings - Fork 230
Expand file tree
/
Copy pathprocess-ongoing-sequences.ts
More file actions
267 lines (251 loc) · 7.87 KB
/
process-ongoing-sequences.ts
File metadata and controls
267 lines (251 loc) · 7.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
import { Domain, Email } from "@courselit/common-models";
import OngoingSequenceModel, {
OngoingSequence,
} from "./model/ongoing-sequence";
import { logger } from "../logger";
import { sequenceBounceLimit } from "../constants";
import {
deleteOngoingSequence,
getDueOngoingSequences,
getSequence,
getUser,
removeRuleForBroadcast,
updateSequenceSentAt,
getDomain,
} from "./queries";
import { sendMail } from "../mail";
import { Liquid } from "liquidjs";
import { Worker } from "bullmq";
import redis from "../redis";
import mongoose from "mongoose";
import sequenceQueue from "./sequence-queue";
import EmailDelivery from "./model/email-delivery";
import { AdminSequence, InternalUser } from "@courselit/common-logic";
import { Email as EmailType, renderEmailToHtml } from "@courselit/email-editor";
import { getUnsubLink } from "../utils/get-unsub-link";
import { getSiteUrl } from "../utils/get-site-url";
import { jwtUtils } from "@courselit/utils";
const liquidEngine = new Liquid();
new Worker(
"sequence",
async (job) => {
const ongoingSequenceId = job.data;
try {
await processOngoingSequence(ongoingSequenceId);
} catch (err: any) {
logger.error(err);
}
},
{ connection: redis },
);
export async function processOngoingSequences(): Promise<void> {
if (!process.env.PIXEL_SIGNING_SECRET) {
throw new Error(
"PIXEL_SIGNING_SECRET environment variable is not defined",
);
}
// eslint-disable-next-line no-constant-condition
while (true) {
// eslint-disable-next-line no-console
console.log(
`Starting process of ongoing sequence at ${new Date().toDateString()}`,
);
const dueOngoingSequences = await getDueOngoingSequences();
for (const ongoingSequence of dueOngoingSequences) {
sequenceQueue.add("sequence", ongoingSequence.id);
}
await new Promise((resolve) => setTimeout(resolve, 60 * 1000));
}
}
async function processOngoingSequence(
ongoingSequenceId: mongoose.Types.ObjectId,
) {
const ongoingSequence =
await OngoingSequenceModel.findById(ongoingSequenceId);
if (!ongoingSequence) {
return;
}
const domain = await getDomain(ongoingSequence.domain);
if (
!domain ||
!domain.quota ||
!domain.quota.mail ||
!domain.settings?.mailingAddress
) {
console.log(`Invalid domain settings for "${domain.name}"`, domain); // eslint-disable-line no-console
return;
}
if (
domain.quota.mail.dailyCount >= domain.quota.mail.daily ||
domain.quota.mail.monthlyCount >= domain.quota.mail.monthly
) {
console.log(`Domain quota exceeded for "${domain.name}"`); // eslint-disable-line no-console
return;
}
const sequence = await getSequence(ongoingSequence.sequenceId);
const [user, creator] = await Promise.all([
getUser(ongoingSequence.userId),
sequence ? getUser(sequence.creatorId) : null,
]);
if (!sequence || !user || !creator) {
return await cleanUpResources(ongoingSequence);
}
const nextPublishedEmail = getNextPublishedEmail(sequence, ongoingSequence);
await attemptMailSending({
domain,
creator,
user,
sequence,
ongoingSequence,
email: nextPublishedEmail,
});
ongoingSequence.sentEmailIds.push(nextPublishedEmail.emailId);
await domain.incrementEmailCount();
const nextEmail = getNextPublishedEmail(sequence, ongoingSequence);
if (!nextEmail) {
return await cleanUpResources(ongoingSequence, true);
} else {
ongoingSequence.nextEmailScheduledTime = new Date(
ongoingSequence.nextEmailScheduledTime + nextEmail.delayInMillis,
).getTime();
await ongoingSequence.save();
}
}
function getNextPublishedEmail(
sequence: AdminSequence,
ongoingSequence: OngoingSequence,
) {
let nextPublishedEmail = null;
const sentEmailIdsSet = new Set(ongoingSequence.sentEmailIds);
for (const mailId of sequence.emailsOrder) {
const email = sequence.emails.find(
(email) => email.emailId === mailId && email.published,
);
if (email && !sentEmailIdsSet.has(email.emailId)) {
nextPublishedEmail = email;
break;
}
}
return nextPublishedEmail;
}
async function cleanUpResources(
ongoingSequence: OngoingSequence,
completed?: boolean,
) {
await deleteOngoingSequence(ongoingSequence.sequenceId);
if (completed) {
await updateSequenceReports(ongoingSequence.sequenceId);
}
}
async function updateSequenceReports(sequenceId: string) {
const remainingOngoingSequencesWithSameSequenceId: OngoingSequence[] =
await OngoingSequenceModel.find({
sequenceId,
});
if (remainingOngoingSequencesWithSameSequenceId.length === 0) {
const sequence = await getSequence(sequenceId);
if (!sequence) {
return;
}
if (sequence.type === "broadcast") {
await removeRuleForBroadcast(sequence.sequenceId);
await updateSequenceSentAt(sequence.sequenceId);
}
}
}
async function attemptMailSending({
creator,
user,
sequence,
ongoingSequence,
email,
domain,
}: {
creator: InternalUser;
user: InternalUser;
sequence: AdminSequence;
ongoingSequence: OngoingSequence;
email: Email;
domain: Domain;
}) {
const from = sequence.from
? `${sequence.from.name} <${creator.email}>`
: `${creator.email} <${creator.email}>`;
const to = user.email;
const subject = email.subject;
const unsubscribeLink = getUnsubLink(domain, user.unsubscribeToken);
const templatePayload = {
subscriber: {
email: user.email,
name: user.name,
tags: user.tags,
},
address: domain.settings.mailingAddress,
unsubscribe_link: unsubscribeLink,
};
if (!email.content) {
return;
}
// const content = email.content;
const pixelPayload = {
userId: user.userId,
sequenceId: ongoingSequence.sequenceId,
emailId: email.emailId,
};
const pixelToken = jwtUtils.generateToken(
pixelPayload,
process.env.PIXEL_SIGNING_SECRET,
"365d",
);
const pixelUrl = `${getSiteUrl(domain)}/api/pixel?d=${pixelToken}`;
const emailContentWithPixel: EmailType = {
content: [
...email.content.content,
{
blockType: "image",
settings: {
src: pixelUrl,
width: "1px",
height: "1px",
alt: "CourseLit Pixel",
},
},
],
style: email.content.style,
meta: email.content.meta,
};
const content = await liquidEngine.parseAndRender(
await renderEmailToHtml({
email: emailContentWithPixel,
}),
templatePayload,
);
try {
await sendMail({
from,
to,
subject,
html: content,
});
// @ts-ignore - Mongoose type compatibility issue
await EmailDelivery.create({
domain: (domain as any).id,
sequenceId: sequence.sequenceId,
userId: user.userId,
emailId: email.emailId,
});
} catch (err: any) {
ongoingSequence.retryCount++;
if (ongoingSequence.retryCount >= sequenceBounceLimit) {
sequence.report.sequence.failed = [
...sequence.report.sequence.failed,
ongoingSequence.userId,
];
await (sequence as any).save();
await deleteOngoingSequence(ongoingSequence.sequenceId);
} else {
await ongoingSequence.save();
}
throw err;
}
}