@terreno/comms 57.0.0-beta.1 → 57.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,5 @@
1
1
  import {APIError, logger} from "@terreno/api";
2
+ import {DateTime} from "luxon";
2
3
 
3
4
  import {
4
5
  ConsoleMailProvider,
@@ -8,11 +9,18 @@ import {
8
9
  } from "./adapters/console";
9
10
  import {CommsMessage} from "./models/commsMessage";
10
11
  import {PushToken} from "./models/pushToken";
12
+ import type {CommsMessageAttempt, CommsMessageDocument} from "./modelTypes";
11
13
  import type {
12
14
  CheckVerificationOptions,
15
+ CommsChannel,
16
+ CommsHookContext,
17
+ CommsHookMessage,
18
+ CommsMessageStatus,
13
19
  CommsOptions,
20
+ DeliveryEvent,
14
21
  MailMessage,
15
22
  MailProvider,
23
+ OptOutEvent,
16
24
  PushMessage,
17
25
  PushProvider,
18
26
  SendPushToUserMessage,
@@ -26,6 +34,9 @@ import type {
26
34
 
27
35
  const CHANNEL_NOT_CONFIGURED_TITLE = "Comms channel not configured";
28
36
  const REDACTED_RECIPIENT = "[redacted]";
37
+ const DEFAULT_RETAIN_PAYLOAD_DAYS = 30;
38
+ const CANCELLED_ERROR = "Cancelled by beforeSend";
39
+ const HOOK_THREW = "hook-threw";
29
40
 
30
41
  const throwUnconfiguredChannel = (): never => {
31
42
  throw new APIError({status: 501, title: CHANNEL_NOT_CONFIGURED_TITLE});
@@ -33,6 +44,19 @@ const throwUnconfiguredChannel = (): never => {
33
44
 
34
45
  const isProduction = (): boolean => process.env.NODE_ENV === "production";
35
46
 
47
+ const providerThrowResult = (error: unknown): SendResult => ({
48
+ accepted: false,
49
+ error: error instanceof Error ? error.message : "Provider send failed",
50
+ errorClass: "transient",
51
+ errorCode: "provider-throw",
52
+ });
53
+
54
+ const isTransientFailure = (result: SendResult): boolean =>
55
+ !result.accepted && result.errorClass === "transient";
56
+
57
+ const isPermanentPushFailure = (result: SendResult): boolean =>
58
+ result.isPermanentFailure === true || result.errorClass === "permanent";
59
+
36
60
  export class CommsService {
37
61
  private readonly options: CommsOptions;
38
62
  private readonly consoleMail = new ConsoleMailProvider();
@@ -44,6 +68,46 @@ export class CommsService {
44
68
  this.options = options ?? {};
45
69
  }
46
70
 
71
+ async recordDeliveryEvent(event: DeliveryEvent): Promise<void> {
72
+ const onDeliveryEvent = this.options.onDeliveryEvent;
73
+ await this.invokeHook(
74
+ onDeliveryEvent ? (): Promise<void> => onDeliveryEvent(event) : undefined,
75
+ "onDeliveryEvent"
76
+ );
77
+ if (this.options.logMessages === false || !event.providerMessageId) {
78
+ return;
79
+ }
80
+ try {
81
+ const row = await CommsMessage.findOneOrNone({providerMessageId: event.providerMessageId});
82
+ if (!row) {
83
+ logger.warn(`[comms] No CommsMessage for delivery event ${event.providerMessageId}`);
84
+ return;
85
+ }
86
+ if (event.status === "opened") {
87
+ return;
88
+ }
89
+ row.status = event.status;
90
+ if (event.errorClass) {
91
+ row.errorClass = event.errorClass;
92
+ }
93
+ if (event.errorCode) {
94
+ row.errorCode = event.errorCode;
95
+ }
96
+ await row.save();
97
+ } catch (error: unknown) {
98
+ logger.warn(`[comms] Failed to apply delivery event: ${String(error)}`);
99
+ }
100
+ }
101
+
102
+ async recordOptOut(event: OptOutEvent): Promise<void> {
103
+ const onOptOut = this.options.onOptOut;
104
+ await this.invokeHook(onOptOut ? (): Promise<void> => onOptOut(event) : undefined, "onOptOut");
105
+ }
106
+
107
+ async clearExpiredPayloads(): Promise<number> {
108
+ return CommsMessage.clearExpiredPayloads();
109
+ }
110
+
47
111
  private recipientForLog(recipient: string | string[]): string {
48
112
  if (this.options.redactRecipients !== false) {
49
113
  return REDACTED_RECIPIENT;
@@ -51,38 +115,400 @@ export class CommsService {
51
115
  return Array.isArray(recipient) ? recipient.join(",") : recipient;
52
116
  }
53
117
 
118
+ private retainPayloadDays(): number {
119
+ return this.options.retainPayloadDays ?? DEFAULT_RETAIN_PAYLOAD_DAYS;
120
+ }
121
+
122
+ private async invokeHook(
123
+ hook: (() => Promise<void>) | undefined,
124
+ label: string
125
+ ): Promise<string | undefined> {
126
+ if (!hook) {
127
+ return undefined;
128
+ }
129
+ try {
130
+ await hook();
131
+ return undefined;
132
+ } catch (error: unknown) {
133
+ const message = `[comms] ${label} hook failed: ${String(error)}`;
134
+ logger.error(message);
135
+ return HOOK_THREW;
136
+ }
137
+ }
138
+
139
+ private appendHookError(
140
+ hookErrors: Record<string, string[]>,
141
+ label: string,
142
+ error: string | undefined
143
+ ): void {
144
+ if (!error) {
145
+ return;
146
+ }
147
+ const existing = hookErrors[label] ?? [];
148
+ existing.push(error);
149
+ hookErrors[label] = existing;
150
+ }
151
+
152
+ private async applyBeforeSend(
153
+ context: CommsHookContext,
154
+ hookErrors: Record<string, string[]>
155
+ ): Promise<{cancel: boolean; message: CommsHookMessage}> {
156
+ const beforeSend = this.options.beforeSend;
157
+ if (!beforeSend) {
158
+ return {cancel: false, message: context.message};
159
+ }
160
+ try {
161
+ const result = await beforeSend(context);
162
+ if (!result) {
163
+ return {cancel: false, message: context.message};
164
+ }
165
+ return {
166
+ cancel: result.cancel === true,
167
+ message: result.message ?? context.message,
168
+ };
169
+ } catch (error: unknown) {
170
+ this.appendHookError(hookErrors, "beforeSend", HOOK_THREW);
171
+ logger.error(`[comms] beforeSend hook failed: ${String(error)}`);
172
+ return {cancel: false, message: context.message};
173
+ }
174
+ }
175
+
176
+ private defaultPayload(message: CommsHookMessage, channel: CommsChannel): unknown {
177
+ if (channel === "mail") {
178
+ const mail = message as MailMessage;
179
+ return {
180
+ dynamicTemplateData: mail.dynamicTemplateData,
181
+ from: mail.from,
182
+ html: mail.html,
183
+ replyTo: mail.replyTo,
184
+ subject: mail.subject,
185
+ templateId: mail.templateId,
186
+ text: mail.text,
187
+ to: mail.to,
188
+ };
189
+ }
190
+ if (channel === "sms") {
191
+ const sms = message as SmsMessage;
192
+ return {body: sms.body, to: sms.to};
193
+ }
194
+ if (channel === "push") {
195
+ const push = message as PushMessage;
196
+ return {
197
+ badge: push.badge,
198
+ body: push.body,
199
+ data: push.data,
200
+ sound: push.sound,
201
+ title: push.title,
202
+ };
203
+ }
204
+ return {channel: (message as StartVerificationOptions).channel};
205
+ }
206
+
207
+ private resolvePayload(context: CommsHookContext, hookErrors: Record<string, string[]>): unknown {
208
+ if (this.retainPayloadDays() <= 0) {
209
+ return undefined;
210
+ }
211
+ const payload = this.defaultPayload(context.message, context.channel);
212
+ const redactPayload = this.options.redactPayload;
213
+ if (!redactPayload) {
214
+ return payload;
215
+ }
216
+ try {
217
+ return redactPayload(context, payload);
218
+ } catch (error: unknown) {
219
+ this.appendHookError(hookErrors, "redactPayload", HOOK_THREW);
220
+ logger.error(`[comms] redactPayload hook failed: ${String(error)}`);
221
+ return undefined;
222
+ }
223
+ }
224
+
225
+ private payloadExpiresAt(): Date | undefined {
226
+ const days = this.retainPayloadDays();
227
+ if (days <= 0) {
228
+ return undefined;
229
+ }
230
+ return DateTime.utc().plus({days}).toJSDate();
231
+ }
232
+
233
+ private cloneHookErrors(hookErrors: Record<string, string[]>): Record<string, string[]> {
234
+ return Object.fromEntries(
235
+ Object.entries(hookErrors).map(([key, values]) => [key, [...values]])
236
+ );
237
+ }
238
+
239
+ private cloneContext(
240
+ context: CommsHookContext,
241
+ overrides: Partial<CommsHookContext> = {}
242
+ ): CommsHookContext {
243
+ return {...context, ...overrides};
244
+ }
245
+
246
+ private resultsByToken(tokens: string[], results: SendResult[]): Map<string, SendResult> {
247
+ const missingResult: SendResult = {
248
+ accepted: false,
249
+ error: "Provider returned no result for token",
250
+ };
251
+ return new Map(tokens.map((token, index) => [token, results[index] ?? missingResult]));
252
+ }
253
+
254
+ private attemptFromResult(provider: string, result: SendResult): CommsMessageAttempt {
255
+ return {
256
+ at: DateTime.utc().toJSDate(),
257
+ error: result.error,
258
+ errorClass: result.errorClass,
259
+ errorCode: result.errorCode,
260
+ provider,
261
+ providerMessageId: result.providerMessageId,
262
+ };
263
+ }
264
+
54
265
  private async logResult({
266
+ attempts,
55
267
  channel,
268
+ context,
269
+ hookErrors,
56
270
  metadata,
271
+ omitPayload,
57
272
  provider,
58
273
  result,
274
+ status,
59
275
  subject,
276
+ templateId,
60
277
  to,
61
278
  userId,
62
279
  }: {
63
- channel: "mail" | "push" | "sms" | "verification";
280
+ attempts: CommsMessageAttempt[];
281
+ channel: CommsChannel;
282
+ context: CommsHookContext;
283
+ hookErrors: Record<string, string[]>;
64
284
  metadata?: Record<string, unknown>;
285
+ omitPayload?: boolean;
65
286
  provider: string;
66
287
  result: SendResult;
288
+ status: CommsMessageStatus;
67
289
  subject?: string;
290
+ templateId?: string;
68
291
  to: string | string[];
69
292
  userId?: string;
70
- }): Promise<void> {
293
+ }): Promise<CommsMessageDocument | null> {
71
294
  if (this.options.logMessages === false) {
72
- return;
295
+ return null;
73
296
  }
74
297
 
75
- await CommsMessage.logSend({
298
+ const payload = omitPayload ? undefined : this.resolvePayload(context, hookErrors);
299
+ const lastAttempt = attempts[attempts.length - 1];
300
+ const mergedMetadata = {
301
+ ...result.metadata,
302
+ ...metadata,
303
+ ...(Object.keys(hookErrors).length > 0 ? {hookErrors} : {}),
304
+ };
305
+
306
+ const logged = await CommsMessage.logSend({
307
+ attemptCount: attempts.length,
308
+ attempts,
76
309
  channel,
77
310
  error: result.error,
78
- metadata,
311
+ errorClass: result.errorClass,
312
+ errorCode: result.errorCode,
313
+ lastAttemptAt: lastAttempt?.at,
314
+ metadata: mergedMetadata,
315
+ payload,
316
+ payloadExpiresAt: payload === undefined ? undefined : this.payloadExpiresAt(),
79
317
  provider,
80
318
  providerMessageId: result.providerMessageId,
81
- status: result.accepted ? "sent" : "failed",
319
+ status,
82
320
  subject,
321
+ templateId,
83
322
  to: this.recipientForLog(to),
84
323
  userId,
85
324
  });
325
+ if (logged) {
326
+ context.messageId = String(logged._id);
327
+ }
328
+ return logged;
329
+ }
330
+
331
+ private async patchHookErrors(
332
+ logged: CommsMessageDocument | null,
333
+ hookErrors: Record<string, string[]>
334
+ ): Promise<void> {
335
+ if (!logged || Object.keys(hookErrors).length === 0) {
336
+ return;
337
+ }
338
+ logged.metadata = {...logged.metadata, hookErrors};
339
+ logged.markModified("metadata");
340
+ await logged.save().catch((error: unknown) => {
341
+ logger.warn(`[comms] Failed to record hook errors: ${String(error)}`);
342
+ });
343
+ }
344
+
345
+ private async notifyOutcomeHooks(
346
+ context: CommsHookContext,
347
+ result: SendResult,
348
+ hookErrors: Record<string, string[]>
349
+ ): Promise<void> {
350
+ if (result.accepted) {
351
+ const onSend = this.options.onSend;
352
+ this.appendHookError(
353
+ hookErrors,
354
+ "onSend",
355
+ await this.invokeHook(
356
+ onSend ? (): Promise<void> => onSend(context, result) : undefined,
357
+ "onSend"
358
+ )
359
+ );
360
+ return;
361
+ }
362
+
363
+ const onError = this.options.onError;
364
+ this.appendHookError(
365
+ hookErrors,
366
+ "onError",
367
+ await this.invokeHook(
368
+ onError ? (): Promise<void> => onError(context, result) : undefined,
369
+ "onError"
370
+ )
371
+ );
372
+ }
373
+
374
+ private async retryOnce<T extends SendResult>(
375
+ context: CommsHookContext,
376
+ firstResult: T,
377
+ retry: () => Promise<T>,
378
+ hookErrors: Record<string, string[]>
379
+ ): Promise<{attempts: SendResult[]; result: T}> {
380
+ if (!isTransientFailure(firstResult)) {
381
+ return {attempts: [firstResult], result: firstResult};
382
+ }
383
+ context.isRetry = true;
384
+ context.attempt = 2;
385
+ const onRetry = this.options.onRetry;
386
+ this.appendHookError(
387
+ hookErrors,
388
+ "onRetry",
389
+ await this.invokeHook(
390
+ onRetry ? (): Promise<void> => onRetry(context, firstResult) : undefined,
391
+ "onRetry"
392
+ )
393
+ );
394
+ const secondResult = await retry();
395
+ return {attempts: [firstResult, secondResult], result: secondResult};
396
+ }
397
+
398
+ private async persistRetry(
399
+ logged: CommsMessageDocument | null,
400
+ context: CommsHookContext,
401
+ hookErrors: Record<string, string[]>,
402
+ provider: string,
403
+ result: SendResult
404
+ ): Promise<CommsMessageDocument | null> {
405
+ if (!logged) {
406
+ return null;
407
+ }
408
+ const payload = this.resolvePayload(context, hookErrors);
409
+ return CommsMessage.appendAttempt({
410
+ attempt: this.attemptFromResult(provider, result),
411
+ error: result.error,
412
+ errorClass: result.errorClass,
413
+ errorCode: result.errorCode,
414
+ id: logged._id,
415
+ metadata: Object.keys(hookErrors).length > 0 ? {hookErrors} : undefined,
416
+ payload,
417
+ payloadExpiresAt: payload === undefined ? undefined : this.payloadExpiresAt(),
418
+ providerMessageId: result.providerMessageId,
419
+ status: result.accepted ? "sent" : "failed",
420
+ });
421
+ }
422
+
423
+ private async finalizeWithRetry({
424
+ context,
425
+ first,
426
+ hookErrors,
427
+ logFields,
428
+ provider,
429
+ retry,
430
+ }: {
431
+ context: CommsHookContext;
432
+ first: SendResult;
433
+ hookErrors: Record<string, string[]>;
434
+ logFields: {
435
+ channel: CommsChannel;
436
+ metadata?: Record<string, unknown>;
437
+ subject?: string;
438
+ templateId?: string;
439
+ to: string | string[];
440
+ userId?: string;
441
+ };
442
+ provider: string;
443
+ retry: () => Promise<SendResult>;
444
+ }): Promise<SendResult> {
445
+ const logged = await this.logResult({
446
+ attempts: [this.attemptFromResult(provider, first)],
447
+ channel: logFields.channel,
448
+ context,
449
+ hookErrors,
450
+ metadata: logFields.metadata,
451
+ provider,
452
+ result: first,
453
+ status: first.accepted ? "sent" : "failed",
454
+ subject: logFields.subject,
455
+ templateId: logFields.templateId,
456
+ to: logFields.to,
457
+ userId: logFields.userId,
458
+ });
459
+ const retried = await this.retryOnce(context, first, retry, hookErrors);
460
+ let finalLogged = logged;
461
+ if (retried.attempts.length > 1) {
462
+ finalLogged =
463
+ (await this.persistRetry(logged, context, hookErrors, provider, retried.result)) ?? logged;
464
+ }
465
+ await this.notifyOutcomeHooks(context, retried.result, hookErrors);
466
+ await this.patchHookErrors(finalLogged, hookErrors);
467
+ return retried.result;
468
+ }
469
+
470
+ private cancelledResult(): SendResult {
471
+ return {
472
+ accepted: false,
473
+ error: CANCELLED_ERROR,
474
+ errorClass: "permanent",
475
+ errorCode: "before-send-cancel",
476
+ };
477
+ }
478
+
479
+ private async sendMailOnce(provider: MailProvider, message: MailMessage): Promise<SendResult> {
480
+ try {
481
+ return await provider.sendMail(message);
482
+ } catch (error: unknown) {
483
+ return providerThrowResult(error);
484
+ }
485
+ }
486
+
487
+ private async sendSmsOnce(provider: SmsProvider, message: SmsMessage): Promise<SendResult> {
488
+ try {
489
+ return await provider.sendSms(message);
490
+ } catch (error: unknown) {
491
+ return providerThrowResult(error);
492
+ }
493
+ }
494
+
495
+ private async sendPushOnce(provider: PushProvider, message: PushMessage): Promise<SendResult[]> {
496
+ try {
497
+ return await provider.sendPush(message);
498
+ } catch (error: unknown) {
499
+ return message.tokens.map(() => providerThrowResult(error));
500
+ }
501
+ }
502
+
503
+ private async startVerificationOnce(
504
+ provider: VerificationProvider,
505
+ options: StartVerificationOptions
506
+ ): Promise<SendResult> {
507
+ try {
508
+ return await provider.startVerification(options);
509
+ } catch (error: unknown) {
510
+ return providerThrowResult(error);
511
+ }
86
512
  }
87
513
 
88
514
  private mailProvider(): MailProvider {
@@ -129,65 +555,111 @@ export class CommsService {
129
555
  return this.consoleVerification;
130
556
  }
131
557
 
132
- async sendMail(message: MailMessage): Promise<SendResult> {
133
- const provider = this.mailProvider();
134
- const resolvedMessage = {
558
+ private applyMailDefaults(message: MailMessage): MailMessage {
559
+ return {
135
560
  ...message,
136
561
  from: message.from ?? this.options.defaultFrom,
137
562
  };
563
+ }
138
564
 
139
- try {
140
- const result = await provider.sendMail(resolvedMessage);
565
+ async sendMail(message: MailMessage): Promise<SendResult> {
566
+ const provider = this.mailProvider();
567
+ const hookErrors: Record<string, string[]> = {};
568
+ const context: CommsHookContext = {
569
+ attempt: 1,
570
+ channel: "mail",
571
+ isRetry: false,
572
+ message: this.applyMailDefaults(message),
573
+ provider: provider.id,
574
+ };
575
+ const before = await this.applyBeforeSend(context, hookErrors);
576
+ const activeMessage = this.applyMailDefaults(before.message as MailMessage);
577
+ context.message = activeMessage;
578
+ if (before.cancel) {
579
+ const result = this.cancelledResult();
141
580
  await this.logResult({
581
+ attempts: [this.attemptFromResult(provider.id, result)],
142
582
  channel: "mail",
583
+ context,
584
+ hookErrors,
143
585
  provider: provider.id,
144
586
  result,
145
- subject: message.subject,
146
- to: message.to,
587
+ status: "cancelled",
588
+ subject: activeMessage.subject,
589
+ templateId: activeMessage.templateId,
590
+ to: activeMessage.to,
147
591
  });
148
592
  return result;
149
- } catch (error: unknown) {
150
- await this.logResult({
151
- channel: "mail",
152
- provider: provider.id,
153
- result: {accepted: false, error: "Provider send failed"},
154
- subject: message.subject,
155
- to: message.to,
156
- });
157
- throw error;
158
593
  }
594
+
595
+ const first = await this.sendMailOnce(provider, activeMessage);
596
+ return this.finalizeWithRetry({
597
+ context,
598
+ first,
599
+ hookErrors,
600
+ logFields: {
601
+ channel: "mail",
602
+ metadata: first.metadata,
603
+ subject: activeMessage.subject,
604
+ templateId: activeMessage.templateId,
605
+ to: activeMessage.to,
606
+ },
607
+ provider: provider.id,
608
+ retry: (): Promise<SendResult> => this.sendMailOnce(provider, activeMessage),
609
+ });
159
610
  }
160
611
 
161
612
  async sendSms(message: SmsMessage): Promise<SendResult> {
162
613
  const provider = this.smsProvider();
163
-
164
- try {
165
- const result = await provider.sendSms(message);
614
+ const hookErrors: Record<string, string[]> = {};
615
+ const context: CommsHookContext = {
616
+ attempt: 1,
617
+ channel: "sms",
618
+ isRetry: false,
619
+ message,
620
+ provider: provider.id,
621
+ };
622
+ const before = await this.applyBeforeSend(context, hookErrors);
623
+ const activeMessage = before.message as SmsMessage;
624
+ context.message = activeMessage;
625
+ if (before.cancel) {
626
+ const result = this.cancelledResult();
166
627
  await this.logResult({
628
+ attempts: [this.attemptFromResult(provider.id, result)],
167
629
  channel: "sms",
630
+ context,
631
+ hookErrors,
168
632
  provider: provider.id,
169
633
  result,
170
- to: message.to,
634
+ status: "cancelled",
635
+ to: activeMessage.to,
171
636
  });
172
637
  return result;
173
- } catch (error: unknown) {
174
- await this.logResult({
175
- channel: "sms",
176
- provider: provider.id,
177
- result: {accepted: false, error: "Provider send failed"},
178
- to: message.to,
179
- });
180
- throw error;
181
638
  }
639
+
640
+ const first = await this.sendSmsOnce(provider, activeMessage);
641
+ return this.finalizeWithRetry({
642
+ context,
643
+ first,
644
+ hookErrors,
645
+ logFields: {
646
+ channel: "sms",
647
+ to: activeMessage.to,
648
+ },
649
+ provider: provider.id,
650
+ retry: (): Promise<SendResult> => this.sendSmsOnce(provider, activeMessage),
651
+ });
182
652
  }
183
653
 
184
654
  async sendPushToUser(message: SendPushToUserMessage): Promise<SendResult[]> {
185
655
  const provider = this.pushProvider();
656
+ const hookErrors: Record<string, string[]> = {};
186
657
  const tokens = await PushToken.find({active: true, userId: message.userId});
187
658
  if (tokens.length === 0) {
188
659
  return [];
189
660
  }
190
661
 
662
+ const tokenDocs = new Map(tokens.map((token) => [token.token, token]));
191
663
  const providerMessage: PushMessage = {
192
664
  badge: message.badge,
193
665
  body: message.body,
@@ -196,98 +668,234 @@ export class CommsService {
196
668
  title: message.title,
197
669
  tokens: tokens.map((token) => token.token),
198
670
  };
199
- let results: SendResult[];
200
- try {
201
- results = await provider.sendPush(providerMessage);
202
- } catch (error: unknown) {
671
+ const context: CommsHookContext = {
672
+ attempt: 1,
673
+ channel: "push",
674
+ isRetry: false,
675
+ message: providerMessage,
676
+ provider: provider.id,
677
+ userId: String(message.userId),
678
+ };
679
+ const before = await this.applyBeforeSend(context, hookErrors);
680
+ const activeMessage = before.message as PushMessage;
681
+ context.message = activeMessage;
682
+ if (before.cancel) {
683
+ const result = this.cancelledResult();
203
684
  await Promise.all(
204
685
  tokens.map(
205
- (token): Promise<void> =>
686
+ (token): Promise<CommsMessageDocument | null> =>
206
687
  this.logResult({
688
+ attempts: [this.attemptFromResult(provider.id, result)],
207
689
  channel: "push",
690
+ context: this.cloneContext(context),
691
+ hookErrors,
208
692
  provider: provider.id,
209
- result: {accepted: false, error: "Provider send failed"},
693
+ result,
694
+ status: "cancelled",
210
695
  to: token.token,
211
696
  userId: String(message.userId),
212
697
  })
213
698
  )
214
699
  );
215
- throw error;
700
+ return tokens.map(() => result);
216
701
  }
217
702
 
218
- const normalizedResults = tokens.map(
219
- (_token, index): SendResult =>
220
- results[index] ?? {
221
- accepted: false,
222
- error: "Provider returned no result for token",
223
- }
703
+ const sendTokens = activeMessage.tokens;
704
+ if (sendTokens.length === 0) {
705
+ return [];
706
+ }
707
+
708
+ const firstByToken = this.resultsByToken(
709
+ sendTokens,
710
+ await this.sendPushOnce(provider, activeMessage)
224
711
  );
712
+ const loggedByToken = new Map<string, CommsMessageDocument | null>();
225
713
  await Promise.all(
226
- tokens.map(async (token, index): Promise<void> => {
227
- const result = normalizedResults[index] as SendResult;
228
- await this.logResult({
714
+ sendTokens.map(async (tokenValue): Promise<void> => {
715
+ const result = firstByToken.get(tokenValue) as SendResult;
716
+ const tokenContext = this.cloneContext(context);
717
+ const logged = await this.logResult({
718
+ attempts: [this.attemptFromResult(provider.id, result)],
229
719
  channel: "push",
720
+ context: tokenContext,
721
+ hookErrors,
230
722
  provider: provider.id,
231
723
  result,
232
- to: token.token,
724
+ status: result.accepted ? "sent" : "failed",
725
+ to: tokenValue,
233
726
  userId: String(message.userId),
234
727
  });
235
- if (!result.accepted && result.isPermanentFailure) {
236
- token.active = false;
237
- await token.save();
728
+ loggedByToken.set(tokenValue, logged);
729
+ })
730
+ );
731
+
732
+ const retryTokens = sendTokens.filter((tokenValue) =>
733
+ isTransientFailure(firstByToken.get(tokenValue) as SendResult)
734
+ );
735
+ const retryTokenSet = new Set(retryTokens);
736
+ const beforeRetryHookErrors = this.cloneHookErrors(hookErrors);
737
+ const finalByToken = new Map(firstByToken);
738
+ const retryContext = this.cloneContext(context, {attempt: 2, isRetry: true});
739
+ if (retryTokens.length > 0) {
740
+ const onRetry = this.options.onRetry;
741
+ const firstTransient = firstByToken.get(retryTokens[0] as string) as SendResult;
742
+ this.appendHookError(
743
+ hookErrors,
744
+ "onRetry",
745
+ await this.invokeHook(
746
+ onRetry ? (): Promise<void> => onRetry(retryContext, firstTransient) : undefined,
747
+ "onRetry"
748
+ )
749
+ );
750
+ const retryByToken = this.resultsByToken(
751
+ retryTokens,
752
+ await this.sendPushOnce(provider, {...activeMessage, tokens: retryTokens})
753
+ );
754
+ await Promise.all(
755
+ retryTokens.map(async (tokenValue): Promise<void> => {
756
+ const retryResult = retryByToken.get(tokenValue) as SendResult;
757
+ finalByToken.set(tokenValue, retryResult);
758
+ const tokenHookErrors = this.cloneHookErrors(beforeRetryHookErrors);
759
+ if (hookErrors.onRetry) {
760
+ tokenHookErrors.onRetry = [...hookErrors.onRetry];
761
+ }
762
+ const logged = loggedByToken.get(tokenValue) ?? null;
763
+ const appended = await this.persistRetry(
764
+ logged,
765
+ this.cloneContext(retryContext, {
766
+ messageId: logged ? String(logged._id) : undefined,
767
+ }),
768
+ tokenHookErrors,
769
+ provider.id,
770
+ retryResult
771
+ );
772
+ if (appended) {
773
+ loggedByToken.set(tokenValue, appended);
774
+ }
775
+ })
776
+ );
777
+ }
778
+
779
+ await Promise.all(
780
+ sendTokens.map(async (tokenValue): Promise<void> => {
781
+ const result = finalByToken.get(tokenValue) as SendResult;
782
+ const tokenHookErrors = this.cloneHookErrors(beforeRetryHookErrors);
783
+ if (retryTokenSet.has(tokenValue) && hookErrors.onRetry) {
784
+ tokenHookErrors.onRetry = [...hookErrors.onRetry];
785
+ }
786
+ const logged = loggedByToken.get(tokenValue) ?? null;
787
+ const didRetry = retryTokenSet.has(tokenValue);
788
+ await this.notifyOutcomeHooks(
789
+ this.cloneContext(context, {
790
+ attempt: didRetry ? 2 : 1,
791
+ isRetry: didRetry,
792
+ messageId: logged ? String(logged._id) : undefined,
793
+ }),
794
+ result,
795
+ tokenHookErrors
796
+ );
797
+ await this.patchHookErrors(logged, tokenHookErrors);
798
+ const tokenDoc = tokenDocs.get(tokenValue);
799
+ if (tokenDoc && !result.accepted && isPermanentPushFailure(result)) {
800
+ tokenDoc.active = false;
801
+ await tokenDoc.save();
238
802
  }
239
803
  })
240
804
  );
241
805
 
242
- return normalizedResults;
806
+ return sendTokens.map((tokenValue) => finalByToken.get(tokenValue) as SendResult);
243
807
  }
244
808
 
245
809
  async startVerification(options: StartVerificationOptions): Promise<SendResult> {
246
810
  const provider = this.verificationProvider();
247
- try {
248
- const result = await provider.startVerification(options);
811
+ const hookErrors: Record<string, string[]> = {};
812
+ const context: CommsHookContext = {
813
+ attempt: 1,
814
+ channel: "verification",
815
+ isRetry: false,
816
+ message: options,
817
+ provider: provider.id,
818
+ };
819
+ const before = await this.applyBeforeSend(context, hookErrors);
820
+ const activeOptions = before.message as StartVerificationOptions;
821
+ context.message = activeOptions;
822
+ if (before.cancel) {
823
+ const result = this.cancelledResult();
249
824
  await this.logResult({
825
+ attempts: [this.attemptFromResult(provider.id, result)],
250
826
  channel: "verification",
251
- metadata: {verificationChannel: options.channel},
827
+ context,
828
+ hookErrors,
829
+ metadata: {verificationChannel: activeOptions.channel},
252
830
  provider: provider.id,
253
831
  result,
254
- to: options.to,
832
+ status: "cancelled",
833
+ to: activeOptions.to,
255
834
  });
256
835
  return result;
257
- } catch (error: unknown) {
258
- await this.logResult({
259
- channel: "verification",
260
- metadata: {verificationChannel: options.channel},
261
- provider: provider.id,
262
- result: {accepted: false, error: "Provider send failed"},
263
- to: options.to,
264
- });
265
- throw error;
266
836
  }
837
+
838
+ const first = await this.startVerificationOnce(provider, activeOptions);
839
+ return this.finalizeWithRetry({
840
+ context,
841
+ first,
842
+ hookErrors,
843
+ logFields: {
844
+ channel: "verification",
845
+ metadata: {verificationChannel: activeOptions.channel},
846
+ to: activeOptions.to,
847
+ },
848
+ provider: provider.id,
849
+ retry: (): Promise<SendResult> => this.startVerificationOnce(provider, activeOptions),
850
+ });
267
851
  }
268
852
 
269
853
  async checkVerification(options: CheckVerificationOptions): Promise<VerificationResult> {
270
854
  const provider = this.verificationProvider();
855
+ const hookErrors: Record<string, string[]> = {};
856
+ const context: CommsHookContext = {
857
+ attempt: 1,
858
+ channel: "verification",
859
+ isRetry: false,
860
+ message: {channel: "sms", to: options.to},
861
+ provider: provider.id,
862
+ };
271
863
  try {
272
864
  const result = await provider.checkVerification(options);
273
- await this.logResult({
865
+ const loggedResult: SendResult = {
866
+ accepted: result.valid,
867
+ ...(result.valid ? {} : {error: result.error ?? "Verification check failed"}),
868
+ };
869
+ const logged = await this.logResult({
870
+ attempts: [this.attemptFromResult(provider.id, loggedResult)],
274
871
  channel: "verification",
872
+ context,
873
+ hookErrors,
874
+ omitPayload: true,
275
875
  provider: provider.id,
276
- result: {
277
- accepted: result.valid,
278
- ...(result.valid ? {} : {error: result.error ?? "Verification check failed"}),
279
- },
876
+ result: loggedResult,
877
+ status: loggedResult.accepted ? "sent" : "failed",
280
878
  to: options.to,
281
879
  });
880
+ await this.notifyOutcomeHooks(context, loggedResult, hookErrors);
881
+ await this.patchHookErrors(logged, hookErrors);
282
882
  return result;
283
883
  } catch (error: unknown) {
284
- await this.logResult({
884
+ const loggedResult = providerThrowResult(error);
885
+ const logged = await this.logResult({
886
+ attempts: [this.attemptFromResult(provider.id, loggedResult)],
285
887
  channel: "verification",
888
+ context,
889
+ hookErrors,
890
+ omitPayload: true,
286
891
  provider: provider.id,
287
- result: {accepted: false, error: "Provider check failed"},
892
+ result: loggedResult,
893
+ status: "failed",
288
894
  to: options.to,
289
895
  });
290
- throw error;
896
+ await this.notifyOutcomeHooks(context, loggedResult, hookErrors);
897
+ await this.patchHookErrors(logged, hookErrors);
898
+ return {error: loggedResult.error, valid: false};
291
899
  }
292
900
  }
293
901
  }