@terreno/comms 57.0.0 → 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,12 +1,15 @@
1
- import {beforeEach, describe, it} from "bun:test";
2
- import {type APIError, isAPIError} from "@terreno/api";
1
+ import {beforeEach, describe, it, spyOn} from "bun:test";
2
+ import {type APIError, isAPIError, logger} from "@terreno/api";
3
3
  import {setupDb} from "@terreno/api/testing";
4
4
  import {assert} from "chai";
5
5
  import {DateTime} from "luxon";
6
6
  import mongoose from "mongoose";
7
7
  import {CommsService} from "./commsService";
8
+ import {CommsMessage} from "./models/commsMessage";
9
+ import {PushToken} from "./models/pushToken";
8
10
  import type {
9
11
  CheckVerificationOptions,
12
+ CommsHookContext,
10
13
  MailMessage,
11
14
  MailProvider,
12
15
  PushMessage,
@@ -15,8 +18,7 @@ import type {
15
18
  SmsProvider,
16
19
  StartVerificationOptions,
17
20
  VerificationProvider,
18
- } from "./index";
19
- import {CommsMessage, PushToken} from "./index";
21
+ } from "./types";
20
22
 
21
23
  const captureError = async (operation: () => Promise<unknown>): Promise<unknown> => {
22
24
  try {
@@ -312,28 +314,39 @@ describe("CommsService", () => {
312
314
  startVerification: throwProviderError,
313
315
  },
314
316
  });
315
- const operations = [
316
- (): Promise<unknown> => service.sendMail({subject: "Welcome", to: "person@example.com"}),
317
- (): Promise<unknown> => service.sendSms({body: "Hello", to: "+15555550100"}),
318
- (): Promise<unknown> => service.sendPushToUser({body: "Hello", title: "Title", userId}),
319
- (): Promise<unknown> => service.startVerification({channel: "sms", to: "+15555550100"}),
320
- (): Promise<unknown> => service.checkVerification({code: "654321", to: "+15555550100"}),
321
- (): Promise<unknown> =>
322
- service.startVerification({channel: "email", to: "person@example.com"}),
323
- (): Promise<unknown> => service.checkVerification({code: "123456", to: "person@example.com"}),
324
- ];
317
+ const mailResult = await service.sendMail({subject: "Welcome", to: "person@example.com"});
318
+ const smsResult = await service.sendSms({body: "Hello", to: "+15555550100"});
319
+ const pushResults = await service.sendPushToUser({body: "Hello", title: "Title", userId});
320
+ const smsStart = await service.startVerification({channel: "sms", to: "+15555550100"});
321
+ const smsCheck = await service.checkVerification({code: "654321", to: "+15555550100"});
322
+ const emailStart = await service.startVerification({
323
+ channel: "email",
324
+ to: "person@example.com",
325
+ });
326
+ const emailCheck = await service.checkVerification({
327
+ code: "123456",
328
+ to: "person@example.com",
329
+ });
325
330
 
326
- for (const operation of operations) {
327
- const error = await captureError(operation);
328
- assert.instanceOf(error, Error);
329
- }
331
+ assert.isFalse(mailResult.accepted);
332
+ assert.equal(mailResult.error, "Provider unavailable");
333
+ assert.equal(mailResult.errorClass, "transient");
334
+ assert.equal(mailResult.errorCode, "provider-throw");
335
+ assert.isFalse(smsResult.accepted);
336
+ assert.equal(smsResult.errorClass, "transient");
337
+ assert.isFalse(pushResults[0]?.accepted);
338
+ assert.isFalse(smsStart.accepted);
339
+ assert.isFalse(smsCheck.valid);
340
+ assert.isFalse(emailStart.accepted);
341
+ assert.isFalse(emailCheck.valid);
330
342
 
331
343
  assert.equal(await CommsMessage.countDocuments({status: "failed"}), 7);
332
344
  assert.equal(await CommsMessage.countDocuments({to: "[redacted]"}), 7);
333
345
  assert.equal(
334
346
  await CommsMessage.countDocuments({
335
347
  channel: "mail",
336
- error: "Provider send failed",
348
+ error: "Provider unavailable",
349
+ errorClass: "transient",
337
350
  provider: "throw-mail",
338
351
  status: "failed",
339
352
  }),
@@ -342,7 +355,8 @@ describe("CommsService", () => {
342
355
  assert.equal(
343
356
  await CommsMessage.countDocuments({
344
357
  channel: "verification",
345
- error: "Provider send failed",
358
+ error: "Provider unavailable",
359
+ errorClass: "transient",
346
360
  "metadata.verificationChannel": "sms",
347
361
  provider: "throw-verification",
348
362
  status: "failed",
@@ -352,7 +366,8 @@ describe("CommsService", () => {
352
366
  assert.equal(
353
367
  await CommsMessage.countDocuments({
354
368
  channel: "sms",
355
- error: "Provider send failed",
369
+ error: "Provider unavailable",
370
+ errorClass: "transient",
356
371
  provider: "throw-sms",
357
372
  status: "failed",
358
373
  }),
@@ -361,7 +376,8 @@ describe("CommsService", () => {
361
376
  assert.equal(
362
377
  await CommsMessage.countDocuments({
363
378
  channel: "push",
364
- error: "Provider send failed",
379
+ error: "Provider unavailable",
380
+ errorClass: "transient",
365
381
  provider: "throw-push",
366
382
  status: "failed",
367
383
  }),
@@ -370,7 +386,8 @@ describe("CommsService", () => {
370
386
  assert.equal(
371
387
  await CommsMessage.countDocuments({
372
388
  channel: "verification",
373
- error: "Provider send failed",
389
+ error: "Provider unavailable",
390
+ errorClass: "transient",
374
391
  "metadata.verificationChannel": "email",
375
392
  provider: "throw-verification",
376
393
  status: "failed",
@@ -380,7 +397,9 @@ describe("CommsService", () => {
380
397
  assert.equal(
381
398
  await CommsMessage.countDocuments({
382
399
  channel: "verification",
383
- error: "Provider check failed",
400
+ error: "Provider unavailable",
401
+ errorClass: "transient",
402
+ "metadata.verificationChannel": {$exists: false},
384
403
  provider: "throw-verification",
385
404
  status: "failed",
386
405
  }),
@@ -544,6 +563,106 @@ describe("CommsService", () => {
544
563
  }
545
564
  });
546
565
 
566
+ it("invokes onSend and onError hooks for every channel", async (): Promise<void> => {
567
+ const userId = new mongoose.Types.ObjectId();
568
+ await PushToken.upsert(
569
+ {token: "ExponentPushToken[hooks]"},
570
+ {
571
+ active: true,
572
+ lastSeenAt: DateTime.utc().toJSDate(),
573
+ platform: "ios",
574
+ userId,
575
+ }
576
+ );
577
+
578
+ const onSendChannels: string[] = [];
579
+ const onErrorChannels: string[] = [];
580
+ const service = new CommsService({
581
+ mail: {
582
+ id: "hook-mail",
583
+ sendMail: async (): Promise<SendResult> => ({accepted: true}),
584
+ },
585
+ onError: async (context): Promise<void> => {
586
+ onErrorChannels.push(context.channel);
587
+ },
588
+ onSend: async (context): Promise<void> => {
589
+ onSendChannels.push(context.channel);
590
+ },
591
+ push: {
592
+ id: "hook-push",
593
+ sendPush: async (): Promise<SendResult[]> => [{accepted: true}],
594
+ },
595
+ sms: {
596
+ id: "hook-sms",
597
+ sendSms: async (): Promise<SendResult> => ({accepted: true}),
598
+ },
599
+ verification: {
600
+ checkVerification: async (): Promise<{valid: boolean}> => ({error: "bad", valid: false}),
601
+ id: "hook-verification",
602
+ startVerification: async (): Promise<SendResult> => ({accepted: true}),
603
+ },
604
+ });
605
+
606
+ await service.sendMail({subject: "Welcome", to: "person@example.com"});
607
+ await service.sendSms({body: "Hello", to: "+15555550100"});
608
+ await service.sendPushToUser({body: "Hello", title: "Title", userId});
609
+ await service.startVerification({channel: "sms", to: "+15555550100"});
610
+ await service.checkVerification({code: "123456", to: "+15555550100"});
611
+
612
+ assert.deepEqual(onSendChannels, ["mail", "sms", "push", "verification"]);
613
+ assert.deepEqual(onErrorChannels, ["verification"]);
614
+ });
615
+
616
+ it("invokes onError once when push provider throws for multiple tokens", async (): Promise<void> => {
617
+ const userId = new mongoose.Types.ObjectId();
618
+ await PushToken.upsert(
619
+ {token: "ExponentPushToken[hooks-a]"},
620
+ {
621
+ active: true,
622
+ lastSeenAt: DateTime.utc().toJSDate(),
623
+ platform: "ios",
624
+ userId,
625
+ }
626
+ );
627
+ await PushToken.upsert(
628
+ {token: "ExponentPushToken[hooks-b]"},
629
+ {
630
+ active: true,
631
+ lastSeenAt: DateTime.utc().toJSDate(),
632
+ platform: "ios",
633
+ userId,
634
+ }
635
+ );
636
+
637
+ let onErrorCount = 0;
638
+ const service = new CommsService({
639
+ onError: async (): Promise<void> => {
640
+ onErrorCount += 1;
641
+ },
642
+ push: {
643
+ id: "throw-push",
644
+ sendPush: async (): Promise<never> => {
645
+ throw new Error("Provider unavailable");
646
+ },
647
+ },
648
+ });
649
+
650
+ const results = await service.sendPushToUser({body: "Hello", title: "Title", userId});
651
+ assert.lengthOf(results, 2);
652
+ assert.isFalse(results[0]?.accepted);
653
+ assert.equal(onErrorCount, 2);
654
+ assert.equal(
655
+ await CommsMessage.countDocuments({
656
+ channel: "push",
657
+ error: "Provider unavailable",
658
+ errorClass: "transient",
659
+ provider: "throw-push",
660
+ status: "failed",
661
+ }),
662
+ 2
663
+ );
664
+ });
665
+
547
666
  it("deactivates push tokens after permanent provider failures", async (): Promise<void> => {
548
667
  const userId = new mongoose.Types.ObjectId();
549
668
  const token = await PushToken.upsert(
@@ -567,4 +686,608 @@ describe("CommsService", () => {
567
686
  const updated = await PushToken.findExactlyOne({_id: token._id});
568
687
  assert.isFalse(updated.active);
569
688
  });
689
+
690
+ it("cancels a send from beforeSend without calling the provider", async (): Promise<void> => {
691
+ let sendCount = 0;
692
+ const service = new CommsService({
693
+ beforeSend: async (): Promise<{cancel: boolean}> => ({cancel: true}),
694
+ mail: {
695
+ id: "cancel-mail",
696
+ sendMail: async (): Promise<SendResult> => {
697
+ sendCount += 1;
698
+ return {accepted: true};
699
+ },
700
+ },
701
+ });
702
+
703
+ const result = await service.sendMail({subject: "Welcome", to: "person@example.com"});
704
+
705
+ assert.equal(sendCount, 0);
706
+ assert.isFalse(result.accepted);
707
+ assert.equal(result.errorCode, "before-send-cancel");
708
+ assert.equal(await CommsMessage.countDocuments({status: "cancelled"}), 1);
709
+ const row = await CommsMessage.findExactlyOne({status: "cancelled"});
710
+ assert.equal(row.attemptCount, 1);
711
+ assert.equal((row.payload as {to?: string}).to, "person@example.com");
712
+ });
713
+
714
+ it("lets beforeSend replace the outbound message", async (): Promise<void> => {
715
+ let delivered: MailMessage | undefined;
716
+ const service = new CommsService({
717
+ beforeSend: async (context) => ({
718
+ message: {
719
+ ...(context.message as MailMessage),
720
+ subject: "Quiet hours rewrite",
721
+ text: "rewritten",
722
+ },
723
+ }),
724
+ mail: {
725
+ id: "mutate-mail",
726
+ sendMail: async (message: MailMessage): Promise<SendResult> => {
727
+ delivered = message;
728
+ return {accepted: true};
729
+ },
730
+ },
731
+ });
732
+
733
+ await service.sendMail({subject: "Welcome", text: "original", to: "person@example.com"});
734
+
735
+ assert.equal(delivered?.subject, "Quiet hours rewrite");
736
+ assert.equal(delivered?.text, "rewritten");
737
+ const row = await CommsMessage.findExactlyOne({channel: "mail"});
738
+ assert.equal((row.payload as {subject?: string}).subject, "Quiet hours rewrite");
739
+ });
740
+
741
+ it("reapplies defaultFrom after beforeSend replaces the mail message", async (): Promise<void> => {
742
+ let delivered: MailMessage | undefined;
743
+ const service = new CommsService({
744
+ beforeSend: async (): Promise<{message: MailMessage}> => ({
745
+ message: {subject: "Quiet hours rewrite", text: "rewritten", to: "person@example.com"},
746
+ }),
747
+ defaultFrom: "sender@example.com",
748
+ mail: {
749
+ id: "default-from-mail",
750
+ sendMail: async (message: MailMessage): Promise<SendResult> => {
751
+ delivered = message;
752
+ return {accepted: true};
753
+ },
754
+ },
755
+ });
756
+
757
+ await service.sendMail({subject: "Welcome", to: "person@example.com"});
758
+
759
+ assert.equal(delivered?.from, "sender@example.com");
760
+ assert.equal(delivered?.subject, "Quiet hours rewrite");
761
+ });
762
+
763
+ it("retries only transient failures and records per-attempt error data", async (): Promise<void> => {
764
+ const calls: string[] = [];
765
+ const retryAttempts: number[] = [];
766
+ const service = new CommsService({
767
+ mail: {
768
+ id: "retry-mail",
769
+ sendMail: async (): Promise<SendResult> => {
770
+ calls.push("mail");
771
+ if (calls.length === 1) {
772
+ return {
773
+ accepted: false,
774
+ error: "Too many requests",
775
+ errorClass: "transient",
776
+ errorCode: "429",
777
+ };
778
+ }
779
+ return {accepted: true, providerMessageId: "mail-2"};
780
+ },
781
+ },
782
+ onRetry: async (context, result): Promise<void> => {
783
+ retryAttempts.push(context.attempt);
784
+ assert.equal(result.errorClass, "transient");
785
+ assert.equal(context.isRetry, true);
786
+ },
787
+ sms: {
788
+ id: "permanent-sms",
789
+ sendSms: async (): Promise<SendResult> => ({
790
+ accepted: false,
791
+ error: "Blocked",
792
+ errorClass: "permanent",
793
+ errorCode: "21610",
794
+ }),
795
+ },
796
+ });
797
+
798
+ const mailResult = await service.sendMail({subject: "Welcome", to: "person@example.com"});
799
+ const smsResult = await service.sendSms({body: "Hello", to: "+15555550100"});
800
+
801
+ assert.isTrue(mailResult.accepted);
802
+ assert.deepEqual(retryAttempts, [2]);
803
+ assert.equal(calls.length, 2);
804
+ assert.isFalse(smsResult.accepted);
805
+ assert.equal(smsResult.errorClass, "permanent");
806
+ const mailRow = await CommsMessage.findExactlyOne({channel: "mail"});
807
+ assert.equal(mailRow.attemptCount, 2);
808
+ assert.equal(mailRow.attempts[0]?.errorClass, "transient");
809
+ assert.equal(mailRow.attempts[0]?.errorCode, "429");
810
+ assert.equal(mailRow.attempts[1]?.providerMessageId, "mail-2");
811
+ const smsRow = await CommsMessage.findExactlyOne({channel: "sms"});
812
+ assert.equal(smsRow.attemptCount, 1);
813
+ assert.equal(smsRow.errorCode, "21610");
814
+ assert.equal(smsRow.errorClass, "permanent");
815
+ });
816
+
817
+ it("does not retry config or unclassified failures", async (): Promise<void> => {
818
+ let configCalls = 0;
819
+ let unclassifiedCalls = 0;
820
+ const retryAttempts: number[] = [];
821
+ const service = new CommsService({
822
+ mail: {
823
+ id: "config-mail",
824
+ sendMail: async (): Promise<SendResult> => {
825
+ configCalls += 1;
826
+ return {accepted: false, error: "Bad key", errorClass: "config", errorCode: "401"};
827
+ },
828
+ },
829
+ onRetry: async (_context, _result): Promise<void> => {
830
+ retryAttempts.push(1);
831
+ },
832
+ sms: {
833
+ id: "unclassified-sms",
834
+ sendSms: async (): Promise<SendResult> => {
835
+ unclassifiedCalls += 1;
836
+ return {accepted: false, error: "Unknown"};
837
+ },
838
+ },
839
+ });
840
+
841
+ await service.sendMail({subject: "Welcome", to: "person@example.com"});
842
+ await service.sendSms({body: "Hello", to: "+15555550100"});
843
+
844
+ assert.equal(configCalls, 1);
845
+ assert.equal(unclassifiedCalls, 1);
846
+ assert.lengthOf(retryAttempts, 0);
847
+ });
848
+
849
+ it("records throwing lifecycle hooks without changing the send outcome", async (): Promise<void> => {
850
+ const errorSpy = spyOn(logger, "error");
851
+ try {
852
+ const service = new CommsService({
853
+ beforeSend: async (): Promise<void> => {
854
+ throw new Error("beforeSend boom for person@example.com key=sg.secret");
855
+ },
856
+ mail: {
857
+ id: "hook-throw-mail",
858
+ sendMail: async (): Promise<SendResult> => ({accepted: true, providerMessageId: "ok"}),
859
+ },
860
+ onDeliveryEvent: async (): Promise<void> => {
861
+ throw new Error("onDeliveryEvent boom");
862
+ },
863
+ onError: async (): Promise<void> => {
864
+ throw new Error("onError boom");
865
+ },
866
+ onOptOut: async (): Promise<void> => {
867
+ throw new Error("onOptOut boom");
868
+ },
869
+ onRetry: async (): Promise<void> => {
870
+ throw new Error("onRetry boom");
871
+ },
872
+ onSend: async (): Promise<void> => {
873
+ throw new Error("onSend boom");
874
+ },
875
+ sms: {
876
+ id: "hook-throw-sms",
877
+ sendSms: async (): Promise<SendResult> => ({
878
+ accepted: false,
879
+ error: "rate limited",
880
+ errorClass: "transient",
881
+ errorCode: "429",
882
+ }),
883
+ },
884
+ });
885
+
886
+ const mailResult = await service.sendMail({subject: "Welcome", to: "person@example.com"});
887
+ const smsResult = await service.sendSms({body: "Hello", to: "+15555550100"});
888
+ await service.recordDeliveryEvent({
889
+ channel: "mail",
890
+ providerMessageId: "unrelated-delivery",
891
+ status: "delivered",
892
+ });
893
+ await service.recordOptOut({
894
+ channel: "sms",
895
+ provider: "hook-throw-sms",
896
+ reason: "sms-stop",
897
+ to: "+15555550100",
898
+ });
899
+
900
+ assert.isTrue(mailResult.accepted);
901
+ assert.isFalse(smsResult.accepted);
902
+ const mailRow = await CommsMessage.findExactlyOne({channel: "mail"});
903
+ assert.equal(mailRow.status, "sent");
904
+ assert.deepEqual(mailRow.metadata?.hookErrors, {
905
+ beforeSend: ["hook-threw"],
906
+ onSend: ["hook-threw"],
907
+ });
908
+ assert.notInclude(JSON.stringify(mailRow.metadata), "person@example.com");
909
+ assert.notInclude(JSON.stringify(mailRow.metadata), "sg.secret");
910
+ const smsRow = await CommsMessage.findExactlyOne({channel: "sms"});
911
+ assert.equal(smsRow.attemptCount, 2);
912
+ assert.deepEqual(smsRow.metadata?.hookErrors, {
913
+ beforeSend: ["hook-threw"],
914
+ onError: ["hook-threw"],
915
+ onRetry: ["hook-threw"],
916
+ });
917
+ assert.isTrue(errorSpy.mock.calls.some((call) => String(call[0]).includes("beforeSend")));
918
+ assert.isTrue(errorSpy.mock.calls.some((call) => String(call[0]).includes("onSend")));
919
+ assert.isTrue(errorSpy.mock.calls.some((call) => String(call[0]).includes("onRetry")));
920
+ assert.isTrue(errorSpy.mock.calls.some((call) => String(call[0]).includes("onError")));
921
+ assert.isTrue(
922
+ errorSpy.mock.calls.some((call) => String(call[0]).includes("onDeliveryEvent"))
923
+ );
924
+ assert.isTrue(errorSpy.mock.calls.some((call) => String(call[0]).includes("onOptOut")));
925
+ } finally {
926
+ errorSpy.mockRestore();
927
+ }
928
+ });
929
+
930
+ it("retains a redacted payload and clears it after retainPayloadDays", async (): Promise<void> => {
931
+ const service = new CommsService({
932
+ mail: {
933
+ id: "payload-mail",
934
+ sendMail: async (): Promise<SendResult> => ({accepted: true}),
935
+ },
936
+ redactPayload: (_context, payload): unknown => ({
937
+ ...(payload as Record<string, unknown>),
938
+ text: "[redacted-body]",
939
+ }),
940
+ retainPayloadDays: 30,
941
+ });
942
+
943
+ await service.sendMail({
944
+ subject: "Welcome",
945
+ text: "secret body",
946
+ to: "person@example.com",
947
+ });
948
+ const row = await CommsMessage.findExactlyOne({channel: "mail"});
949
+ assert.equal((row.payload as {text?: string}).text, "[redacted-body]");
950
+ assert.equal((row.payload as {subject?: string}).subject, "Welcome");
951
+ assert.isDefined(row.payloadExpiresAt);
952
+
953
+ row.payloadExpiresAt = DateTime.utc().minus({days: 1}).toJSDate();
954
+ await row.save();
955
+ assert.equal(await service.clearExpiredPayloads(), 1);
956
+ const cleared = await CommsMessage.findExactlyOne({channel: "mail"});
957
+ assert.isUndefined(cleared.payload);
958
+ assert.isUndefined(cleared.payloadExpiresAt);
959
+ assert.equal(cleared.status, "sent");
960
+ });
961
+
962
+ it("stores no payload when retainPayloadDays is 0", async (): Promise<void> => {
963
+ const service = new CommsService({
964
+ mail: {
965
+ id: "no-payload-mail",
966
+ sendMail: async (): Promise<SendResult> => ({accepted: true}),
967
+ },
968
+ retainPayloadDays: 0,
969
+ });
970
+
971
+ await service.sendMail({subject: "Welcome", text: "secret", to: "person@example.com"});
972
+ const row = await CommsMessage.findExactlyOne({channel: "mail"});
973
+ assert.isUndefined(row.payload);
974
+ assert.isUndefined(row.payloadExpiresAt);
975
+ });
976
+
977
+ it("retries only transient push tokens and deactivates permanent errorClass failures", async (): Promise<void> => {
978
+ const userId = new mongoose.Types.ObjectId();
979
+ const transientToken = await PushToken.upsert(
980
+ {token: "ExponentPushToken[transient]"},
981
+ {
982
+ active: true,
983
+ lastSeenAt: DateTime.utc().toJSDate(),
984
+ platform: "ios",
985
+ userId,
986
+ }
987
+ );
988
+ const permanentToken = await PushToken.upsert(
989
+ {token: "ExponentPushToken[permanent]"},
990
+ {
991
+ active: true,
992
+ lastSeenAt: DateTime.utc().toJSDate(),
993
+ platform: "android",
994
+ userId,
995
+ }
996
+ );
997
+ const retryTokens: string[] = [];
998
+ const service = new CommsService({
999
+ push: {
1000
+ id: "mixed-push",
1001
+ sendPush: async (message: PushMessage): Promise<SendResult[]> => {
1002
+ if (message.tokens.length === 1) {
1003
+ retryTokens.push(...message.tokens);
1004
+ return [{accepted: true, providerMessageId: "retry-ok"}];
1005
+ }
1006
+ return message.tokens.map((token) =>
1007
+ token.includes("permanent")
1008
+ ? {accepted: false, error: "Unregistered", errorClass: "permanent" as const}
1009
+ : {accepted: false, error: "Timeout", errorClass: "transient" as const}
1010
+ );
1011
+ },
1012
+ },
1013
+ });
1014
+
1015
+ const results = await service.sendPushToUser({body: "Hello", title: "Title", userId});
1016
+
1017
+ assert.equal(results.filter((result) => result.accepted).length, 1);
1018
+ assert.equal(results.filter((result) => !result.accepted).length, 1);
1019
+ assert.deepEqual(retryTokens, ["ExponentPushToken[transient]"]);
1020
+ const updatedTransient = await PushToken.findExactlyOne({_id: transientToken._id});
1021
+ const updatedPermanent = await PushToken.findExactlyOne({_id: permanentToken._id});
1022
+ assert.isTrue(updatedTransient.active);
1023
+ assert.isFalse(updatedPermanent.active);
1024
+ const retriedRow = await CommsMessage.findExactlyOne({providerMessageId: "retry-ok"});
1025
+ assert.equal(retriedRow.attemptCount, 2);
1026
+ });
1027
+
1028
+ it("maps push provider results by token after beforeSend reorders the batch", async (): Promise<void> => {
1029
+ const userId = new mongoose.Types.ObjectId();
1030
+ await PushToken.upsert(
1031
+ {token: "ExponentPushToken[first]"},
1032
+ {
1033
+ active: true,
1034
+ lastSeenAt: DateTime.utc().toJSDate(),
1035
+ platform: "ios",
1036
+ userId,
1037
+ }
1038
+ );
1039
+ await PushToken.upsert(
1040
+ {token: "ExponentPushToken[second]"},
1041
+ {
1042
+ active: true,
1043
+ lastSeenAt: DateTime.utc().toJSDate(),
1044
+ platform: "android",
1045
+ userId,
1046
+ }
1047
+ );
1048
+ let sentTokens: string[] = [];
1049
+ const service = new CommsService({
1050
+ beforeSend: async (context) => {
1051
+ const message = context.message as PushMessage;
1052
+ sentTokens = [...message.tokens].reverse();
1053
+ return {
1054
+ message: {
1055
+ ...message,
1056
+ tokens: sentTokens,
1057
+ },
1058
+ };
1059
+ },
1060
+ push: {
1061
+ id: "reorder-push",
1062
+ sendPush: async (message: PushMessage): Promise<SendResult[]> =>
1063
+ message.tokens.map((_token, index) =>
1064
+ index === 0
1065
+ ? {accepted: false, error: "Unregistered", errorClass: "permanent" as const}
1066
+ : {accepted: true, providerMessageId: "second-ok"}
1067
+ ),
1068
+ },
1069
+ redactRecipients: false,
1070
+ });
1071
+
1072
+ await service.sendPushToUser({body: "Hello", title: "Title", userId});
1073
+
1074
+ const sentFirst = sentTokens[0] as string;
1075
+ const sentSecond = sentTokens[1] as string;
1076
+ const deactivated = await PushToken.findExactlyOne({token: sentFirst});
1077
+ const stillActive = await PushToken.findExactlyOne({token: sentSecond});
1078
+ assert.isFalse(deactivated.active);
1079
+ assert.isTrue(stillActive.active);
1080
+ const failedRow = await CommsMessage.findExactlyOne({to: sentFirst});
1081
+ const sentRow = await CommsMessage.findExactlyOne({to: sentSecond});
1082
+ assert.equal(failedRow.errorClass, "permanent");
1083
+ assert.equal(sentRow.status, "sent");
1084
+ });
1085
+
1086
+ it("gives each push token its own outcome hook context", async (): Promise<void> => {
1087
+ const userId = new mongoose.Types.ObjectId();
1088
+ await PushToken.upsert(
1089
+ {token: "ExponentPushToken[keep]"},
1090
+ {
1091
+ active: true,
1092
+ lastSeenAt: DateTime.utc().toJSDate(),
1093
+ platform: "ios",
1094
+ userId,
1095
+ }
1096
+ );
1097
+ await PushToken.upsert(
1098
+ {token: "ExponentPushToken[retry]"},
1099
+ {
1100
+ active: true,
1101
+ lastSeenAt: DateTime.utc().toJSDate(),
1102
+ platform: "android",
1103
+ userId,
1104
+ }
1105
+ );
1106
+ const onSendCalls: Array<{
1107
+ attempt: number;
1108
+ isRetry: boolean;
1109
+ messageId?: string;
1110
+ }> = [];
1111
+ const service = new CommsService({
1112
+ onSend: async (context: CommsHookContext): Promise<void> => {
1113
+ onSendCalls.push({
1114
+ attempt: context.attempt,
1115
+ isRetry: context.isRetry,
1116
+ messageId: context.messageId,
1117
+ });
1118
+ },
1119
+ push: {
1120
+ id: "context-push",
1121
+ sendPush: async (message: PushMessage): Promise<SendResult[]> => {
1122
+ if (message.tokens.length === 1) {
1123
+ return [{accepted: true, providerMessageId: "retry-ok"}];
1124
+ }
1125
+ return message.tokens.map((token) =>
1126
+ token.includes("retry")
1127
+ ? {accepted: false, error: "Timeout", errorClass: "transient" as const}
1128
+ : {accepted: true, providerMessageId: "keep-ok"}
1129
+ );
1130
+ },
1131
+ },
1132
+ redactRecipients: false,
1133
+ });
1134
+
1135
+ await service.sendPushToUser({body: "Hello", title: "Title", userId});
1136
+
1137
+ const keepRow = await CommsMessage.findExactlyOne({to: "ExponentPushToken[keep]"});
1138
+ const retryRow = await CommsMessage.findExactlyOne({to: "ExponentPushToken[retry]"});
1139
+ const keepCall = onSendCalls.find((call) => call.messageId === String(keepRow._id));
1140
+ const retryCall = onSendCalls.find((call) => call.messageId === String(retryRow._id));
1141
+ assert.deepEqual(keepCall, {
1142
+ attempt: 1,
1143
+ isRetry: false,
1144
+ messageId: String(keepRow._id),
1145
+ });
1146
+ assert.deepEqual(retryCall, {
1147
+ attempt: 2,
1148
+ isRetry: true,
1149
+ messageId: String(retryRow._id),
1150
+ });
1151
+ });
1152
+
1153
+ it("retains mail and verification payloads in the IP shape", async (): Promise<void> => {
1154
+ const service = new CommsService({
1155
+ mail: {
1156
+ id: "shape-mail",
1157
+ sendMail: async (): Promise<SendResult> => ({accepted: true}),
1158
+ },
1159
+ sms: {
1160
+ id: "shape-sms",
1161
+ sendSms: async (): Promise<SendResult> => ({accepted: true}),
1162
+ },
1163
+ verification: {
1164
+ checkVerification: async (): Promise<{valid: boolean}> => ({valid: true}),
1165
+ id: "shape-verification",
1166
+ startVerification: async (): Promise<SendResult> => ({accepted: true}),
1167
+ },
1168
+ });
1169
+
1170
+ await service.sendMail({
1171
+ dynamicTemplateData: {name: "Ada"},
1172
+ from: "sender@example.com",
1173
+ html: "<p>Hi</p>",
1174
+ replyTo: "reply@example.com",
1175
+ subject: "Welcome",
1176
+ templateId: "d-welcome",
1177
+ text: "Hi",
1178
+ to: "person@example.com",
1179
+ });
1180
+ await service.sendSms({body: "Hello", to: "+15555550100"});
1181
+ await service.startVerification({channel: "sms", to: "+15555550100"});
1182
+ await service.checkVerification({code: "123456", to: "+15555550100"});
1183
+
1184
+ const mailRow = await CommsMessage.findExactlyOne({channel: "mail"});
1185
+ assert.deepEqual(mailRow.payload, {
1186
+ dynamicTemplateData: {name: "Ada"},
1187
+ from: "sender@example.com",
1188
+ html: "<p>Hi</p>",
1189
+ replyTo: "reply@example.com",
1190
+ subject: "Welcome",
1191
+ templateId: "d-welcome",
1192
+ text: "Hi",
1193
+ to: "person@example.com",
1194
+ });
1195
+ const smsRow = await CommsMessage.findExactlyOne({channel: "sms"});
1196
+ assert.deepEqual(smsRow.payload, {body: "Hello", to: "+15555550100"});
1197
+ const startRow = await CommsMessage.findExactlyOne({
1198
+ channel: "verification",
1199
+ "metadata.verificationChannel": "sms",
1200
+ });
1201
+ assert.deepEqual(startRow.payload, {channel: "sms"});
1202
+ const checkRow = await CommsMessage.findExactlyOne({
1203
+ channel: "verification",
1204
+ "metadata.verificationChannel": {$exists: false},
1205
+ });
1206
+ assert.isUndefined(checkRow.payload);
1207
+ });
1208
+
1209
+ it("updates a delivery log row from recordDeliveryEvent", async (): Promise<void> => {
1210
+ const warnSpy = spyOn(logger, "warn");
1211
+ const service = new CommsService({
1212
+ mail: {
1213
+ id: "event-mail",
1214
+ sendMail: async (): Promise<SendResult> => ({
1215
+ accepted: true,
1216
+ providerMessageId: "mail-delivered",
1217
+ }),
1218
+ },
1219
+ });
1220
+ await service.sendMail({subject: "Welcome", to: "person@example.com"});
1221
+ await service.recordDeliveryEvent({
1222
+ channel: "mail",
1223
+ errorClass: "permanent",
1224
+ errorCode: "bounce-500",
1225
+ providerMessageId: "mail-delivered",
1226
+ status: "bounced",
1227
+ });
1228
+ await service.recordDeliveryEvent({
1229
+ channel: "mail",
1230
+ providerMessageId: "mail-delivered",
1231
+ status: "opened",
1232
+ });
1233
+ await service.recordDeliveryEvent({
1234
+ channel: "mail",
1235
+ errorClass: "transient",
1236
+ providerMessageId: "missing-delivery",
1237
+ status: "failed",
1238
+ });
1239
+ const row = await CommsMessage.findExactlyOne({providerMessageId: "mail-delivered"});
1240
+ assert.equal(row.status, "bounced");
1241
+ assert.equal(row.errorCode, "bounce-500");
1242
+ assert.equal(row.errorClass, "permanent");
1243
+ assert.isTrue(warnSpy.mock.calls.some((call) => String(call[0]).includes("missing-delivery")));
1244
+ warnSpy.mockRestore();
1245
+ });
1246
+
1247
+ it("retries startVerification once on transient failure and never retries checkVerification", async (): Promise<void> => {
1248
+ let startCalls = 0;
1249
+ let checkCalls = 0;
1250
+ const service = new CommsService({
1251
+ verification: {
1252
+ checkVerification: async (): Promise<{valid: boolean}> => {
1253
+ checkCalls += 1;
1254
+ return {error: "bad", valid: false};
1255
+ },
1256
+ id: "retry-verification",
1257
+ startVerification: async (): Promise<SendResult> => {
1258
+ startCalls += 1;
1259
+ return {
1260
+ accepted: false,
1261
+ error: "Timeout",
1262
+ errorClass: "transient",
1263
+ errorCode: "429",
1264
+ };
1265
+ },
1266
+ },
1267
+ });
1268
+
1269
+ await service.startVerification({channel: "sms", to: "+15555550100"});
1270
+ await service.checkVerification({code: "123456", to: "+15555550100"});
1271
+
1272
+ assert.equal(startCalls, 2);
1273
+ assert.equal(checkCalls, 1);
1274
+ });
1275
+
1276
+ it("omits payload when redactPayload throws", async (): Promise<void> => {
1277
+ const service = new CommsService({
1278
+ mail: {
1279
+ id: "redact-throw-mail",
1280
+ sendMail: async (): Promise<SendResult> => ({accepted: true}),
1281
+ },
1282
+ redactPayload: (): unknown => {
1283
+ throw new Error("redact boom");
1284
+ },
1285
+ });
1286
+
1287
+ const result = await service.sendMail({subject: "Welcome", to: "person@example.com"});
1288
+ assert.isTrue(result.accepted);
1289
+ const row = await CommsMessage.findExactlyOne({channel: "mail"});
1290
+ assert.isUndefined(row.payload);
1291
+ assert.deepEqual(row.metadata?.hookErrors, {redactPayload: ["hook-threw"]});
1292
+ });
570
1293
  });