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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
|
import type { EmailFromInstruction, EmailJob, EmailToInstruction } from "./job";
import * as TE from "fp-ts/lib/TaskEither";
import * as O from "fp-ts/lib/Option";
import { createTransport } from "nodemailer";
import { toError } from "fp-ts/lib/Either";
import { pipe } from "fp-ts/lib/function";
import {
ImapFlow,
type FetchMessageObject,
type FetchQueryObject,
type MailboxLockObject,
} from "imapflow";
import * as IO from "fp-ts/lib/IO";
import * as T from "fp-ts/lib/Task";
import { ConsoleLogger, type Logger } from "./logger";
interface ImapClientI {
fetchAll: (
range: string,
options: FetchQueryObject,
) => Promise<FetchMessageObject[]>;
connect: () => Promise<void>;
getMailboxLock: (mailbox: string) => Promise<MailboxLockObject>;
messageDelete: (
uids: number[],
opts: Record<string, any>,
) => Promise<boolean>;
logout: () => Promise<void>;
mailboxClose: () => Promise<void>;
}
type Email = {
from: string;
to: string;
subject: string;
text: string;
};
class ErrorWithLock extends Error {
lock: O.Option<MailboxLockObject>;
imap: O.Option<ImapClientI>;
constructor(message: string, lock?: MailboxLockObject, imap?: ImapClientI) {
super(message);
this.lock = O.fromNullable(lock);
this.imap = O.fromNullable(imap);
}
}
const ToErrorWithLock =
(lock?: MailboxLockObject, imap?: ImapClientI) => (error: unknown) =>
new ErrorWithLock(
error instanceof Error ? error.message : "Unknown error",
lock,
imap,
);
/**
* Generate a unique email.
* @param from is the email to send from.
* @param to is the email to send to.
* @returns an {@link Email}.
*/
type EmailGenerator = (
from: EmailFromInstruction,
to: EmailToInstruction,
) => IO.IO<Email>;
const generateEmail: EmailGenerator =
(from: EmailFromInstruction, to: EmailToInstruction) => () => ({
from: from.email,
to: to.email,
subject: [new Date().toISOString(), crypto.randomUUID()].join(" | "),
text: crypto.randomUUID(),
});
/**
* Get the transport layer for a mailbox to send a piece of mail.
* @param param0 is the mailbox to send from.
* @returns a function that takes an email and sends it.
*/
type GetSendEmail = (
from: EmailFromInstruction,
) => (email: Email) => TE.TaskEither<Error, Email>;
const getSendTransport: GetSendEmail = ({
username,
password,
server,
send_port,
}) => {
const transport = createTransport({
host: server,
port: send_port,
auth: {
user: username,
pass: password,
},
tls: {
rejectUnauthorized: false,
},
});
return (email: Email) =>
TE.tryCatch(
() =>
new Promise<Email>((resolve, reject) =>
transport.sendMail(email, (error) => {
if (error) {
reject(error);
} else {
resolve(email);
}
}),
),
toError,
);
};
/**
* Get an Imap client connected to a mailbox.
* @param param0 is the mailbox to read from.
* @returns a Right({@link ImapFlow}) if it connected, else an Left(error).
*/
type GetImapClient = (
to: EmailToInstruction,
) => TE.TaskEither<Error, ImapClientI>;
const getImap: GetImapClient = ({ username, password, server, read_port }) => {
const imap = new ImapFlow({
logger: false,
host: server,
port: read_port,
secure: true,
auth: {
user: username,
pass: password,
},
});
return TE.tryCatch(() => imap.connect().then(() => imap), toError);
};
/**
* @param imap is the Imap client to fetch messages from.
* @returns a Right({@link FetchMessageObject}[]) if successful, else a Left(error).
*/
const fetchMessages = (
imap: ImapClientI,
): TE.TaskEither<Error, FetchMessageObject[]> =>
TE.tryCatch(
() =>
imap.fetchAll("*", {
uid: true,
envelope: true,
headers: true,
bodyParts: ["text"],
}),
toError,
);
/**
* Curry a function to check if a message matches an email.
* @param email is the email to match.
* @returns a function that takes a message and returns true if it matches the email.
*/
type EmailMatcher = (email: Email) => (message: FetchMessageObject) => boolean;
const matchesEmail: EmailMatcher = (email) => (message) => {
const subjectMatches = email.subject === message.envelope?.subject;
const bodyMatches =
message.bodyParts?.get("text")?.toString().trim() === email.text.trim();
const headers = message.headers?.toLocaleString();
const fromMatches = headers.includes(`Return-Path: <${email.from}>`);
const toMatches = headers.includes(`Delivered-To: ${email.to}`);
return subjectMatches && bodyMatches && fromMatches && toMatches;
};
/**
* Find an email in the inbox.
* @param imap is the Imap client to search with.
* @param email is the email to search for.
* @param retries is the number of retries left.
* @param pollIntervalMs is the time to wait between retries.
* @returns a Right(number) if the email was found, else a Left(error).
*/
type FindEmailUidInInbox = (
imap: ImapClientI,
equalsEmail: (message: FetchMessageObject) => boolean,
retries: number,
pollIntervalMs: number,
logger?: Logger,
) => TE.TaskEither<Error, number>;
const findEmailUidInInbox: FindEmailUidInInbox = (
imap,
equalsEmail,
retries,
pollIntervalMs,
logger = ConsoleLogger,
) =>
pipe(
fetchMessages(imap),
TE.flatMap((messages) => {
const message = messages.find(equalsEmail);
if (message) {
return TE.right(message.uid);
}
return TE.left(new Error("Email message not found"));
}),
TE.fold(
(e) =>
pipe(
TE.fromIO(
logger.log(`failed to find email; ${retries} retries left.`),
),
TE.chain(() =>
retries === 0
? TE.left(e)
: T.delay(pollIntervalMs)(TE.right(null)),
),
TE.chain(() =>
findEmailUidInInbox(imap, equalsEmail, retries - 1, pollIntervalMs),
),
),
(s) =>
pipe(
s,
TE.of,
TE.tap(() => TE.fromIO(logger.log("Email succeeded"))),
),
),
);
export type EmailJobDependencies = {
generateEmailImpl: EmailGenerator;
getSendImpl: GetSendEmail;
getImapImpl: GetImapClient;
findEmailUidInInboxImpl: FindEmailUidInInbox;
matchesEmailImpl: EmailMatcher;
};
/**
* Perform an email job.
* @param job is the job to perform.
*/
export const perform = (
{ from, to, readRetry: { retries, interval } }: EmailJob,
{
generateEmailImpl = generateEmail,
getSendImpl = getSendTransport,
getImapImpl = getImap,
findEmailUidInInboxImpl = findEmailUidInInbox,
matchesEmailImpl = matchesEmail,
}: Partial<EmailJobDependencies> = {},
): TE.TaskEither<Error, boolean> =>
pipe(
// arrange.
TE.fromIO(generateEmailImpl(from, to)),
TE.bindTo("email"),
// act.
TE.tap(({ email }) =>
pipe(getSendImpl(from)(email), TE.mapLeft(ToErrorWithLock())),
),
TE.bind("imap", () => pipe(getImapImpl(to), TE.mapLeft(ToErrorWithLock()))),
TE.bind("mailboxLock", ({ imap }) =>
TE.tryCatch(
() => imap.getMailboxLock("INBOX"),
ToErrorWithLock(undefined, imap),
),
),
// "assert".
TE.bind("uid", ({ imap, email, mailboxLock }) =>
pipe(
findEmailUidInInboxImpl(
imap,
matchesEmailImpl(email),
retries,
interval,
),
TE.mapLeft(ToErrorWithLock(mailboxLock, imap)),
),
),
// cleanup.
TE.bind("deleted", ({ imap, uid, mailboxLock }) =>
TE.tryCatch(
() => imap.messageDelete([uid], { uid: true }),
ToErrorWithLock(mailboxLock, imap),
),
),
TE.fold(
(e) => {
if (O.isSome(e.lock)) {
e.lock.value.release();
}
if (O.isSome(e.imap)) {
const imap = e.imap.value;
return pipe(
TE.tryCatch(
() => imap.mailboxClose().then(() => imap.logout()),
toError,
),
TE.flatMap(() => TE.left(e)),
);
}
return TE.left(e);
},
({ mailboxLock, deleted, imap }) => {
mailboxLock.release();
return pipe(
TE.tryCatch(
() => imap.mailboxClose().then(() => imap.logout()),
toError,
),
TE.flatMap(() => TE.right(deleted)),
);
},
),
);
|