@terreno/comms 57.2.0 → 57.4.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.
- package/README.md +58 -0
- package/dist/adapters/expoPush.d.ts +54 -0
- package/dist/adapters/expoPush.js +400 -0
- package/dist/adapters/sendgrid.d.ts +3 -0
- package/dist/adapters/sendgrid.js +7 -1
- package/dist/adapters/twilioSms.d.ts +36 -0
- package/dist/adapters/twilioSms.js +232 -0
- package/dist/adapters/twilioVerify.d.ts +44 -0
- package/dist/adapters/twilioVerify.js +212 -0
- package/dist/commsApp.d.ts +4 -1
- package/dist/commsApp.js +28 -2
- package/dist/commsQuery.d.ts +31 -0
- package/dist/commsQuery.js +135 -0
- package/dist/commsRetry.d.ts +12 -0
- package/dist/commsRetry.js +78 -0
- package/dist/commsService.d.ts +11 -4
- package/dist/commsService.js +224 -47
- package/dist/index.d.ts +3 -3
- package/dist/index.js +3 -1
- package/dist/routes/commsDashboard.d.ts +9 -0
- package/dist/routes/commsDashboard.js +412 -0
- package/dist/templates.d.ts +9 -0
- package/dist/templates.js +34 -1
- package/dist/types.d.ts +12 -0
- package/dist/webhooks/sendgridWebhooks.d.ts +10 -0
- package/dist/webhooks/sendgridWebhooks.js +250 -0
- package/dist/webhooks/twilioWebhooks.d.ts +11 -0
- package/dist/webhooks/twilioWebhooks.js +174 -0
- package/package.json +30 -9
- package/src/adapters/expoPush.test.ts +585 -0
- package/src/adapters/expoPush.ts +304 -0
- package/src/adapters/sendgrid.ts +8 -0
- package/src/adapters/twilioSms.test.ts +374 -0
- package/src/adapters/twilioSms.ts +237 -0
- package/src/adapters/twilioVerify.test.ts +207 -0
- package/src/adapters/twilioVerify.ts +227 -0
- package/src/commsApp.test.ts +13 -0
- package/src/commsApp.ts +38 -3
- package/src/commsQuery.test.ts +165 -0
- package/src/commsQuery.ts +163 -0
- package/src/commsRetry.ts +87 -0
- package/src/commsService.test.ts +128 -0
- package/src/commsService.ts +184 -20
- package/src/index.ts +9 -2
- package/src/routes/commsDashboard.test.ts +310 -0
- package/src/routes/commsDashboard.ts +324 -0
- package/src/templates.test.ts +63 -1
- package/src/templates.ts +47 -0
- package/src/tests/bunSetup.ts +8 -0
- package/src/types.ts +14 -0
- package/src/webhooks/sendgridWebhooks.test.ts +520 -0
- package/src/webhooks/sendgridWebhooks.ts +166 -0
- package/src/webhooks/twilioWebhooks.test.ts +352 -0
- package/src/webhooks/twilioWebhooks.ts +154 -0
- package/dist/routes/commsExplorer.d.ts +0 -7
- package/dist/routes/commsExplorer.js +0 -147
- package/src/routes/commsExplorer.ts +0 -114
package/src/commsApp.ts
CHANGED
|
@@ -1,14 +1,24 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
type AdminContribution,
|
|
3
|
+
APIError,
|
|
4
|
+
logger,
|
|
5
|
+
type TerrenoPlugin,
|
|
6
|
+
type WebhooksApp,
|
|
7
|
+
} from "@terreno/api";
|
|
2
8
|
import type express from "express";
|
|
3
9
|
|
|
4
10
|
import {CommsService} from "./commsService";
|
|
5
11
|
import {PushToken} from "./models/pushToken";
|
|
6
|
-
import {
|
|
12
|
+
import {addCommsDashboardRoutes} from "./routes/commsDashboard";
|
|
7
13
|
import {addPushTokenRoutes} from "./routes/pushTokens";
|
|
8
14
|
import type {CommsOptions} from "./types";
|
|
15
|
+
import {maybeRegisterSendGridCommsWebhooks} from "./webhooks/sendgridWebhooks";
|
|
16
|
+
import {maybeRegisterTwilioCommsWebhooks} from "./webhooks/twilioWebhooks";
|
|
9
17
|
|
|
10
18
|
export interface CommsAppOptions extends CommsOptions {
|
|
11
19
|
basePath?: string;
|
|
20
|
+
webhookPublicUrl?: string;
|
|
21
|
+
webhooks?: WebhooksApp;
|
|
12
22
|
}
|
|
13
23
|
|
|
14
24
|
let registeredCommsService: CommsService | undefined;
|
|
@@ -43,6 +53,31 @@ export class CommsApp implements TerrenoPlugin {
|
|
|
43
53
|
});
|
|
44
54
|
|
|
45
55
|
addPushTokenRoutes(app, {basePath: `${basePath}/pushTokens`, openApi});
|
|
46
|
-
|
|
56
|
+
addCommsDashboardRoutes(app, {basePath, openApi, service: this.service});
|
|
57
|
+
maybeRegisterTwilioCommsWebhooks({
|
|
58
|
+
basePath,
|
|
59
|
+
publicUrl: this.options.webhookPublicUrl,
|
|
60
|
+
service: this.service,
|
|
61
|
+
sms: this.options.sms,
|
|
62
|
+
webhooks: this.options.webhooks,
|
|
63
|
+
});
|
|
64
|
+
maybeRegisterSendGridCommsWebhooks({
|
|
65
|
+
basePath,
|
|
66
|
+
mail: this.options.mail,
|
|
67
|
+
service: this.service,
|
|
68
|
+
webhooks: this.options.webhooks,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
adminContribution(): AdminContribution {
|
|
73
|
+
return {
|
|
74
|
+
customScreens: [
|
|
75
|
+
{
|
|
76
|
+
displayName: "Comms Dashboard",
|
|
77
|
+
icon: "paper-plane",
|
|
78
|
+
name: "comms",
|
|
79
|
+
},
|
|
80
|
+
],
|
|
81
|
+
};
|
|
47
82
|
}
|
|
48
83
|
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import {describe, it} from "bun:test";
|
|
2
|
+
import {assert} from "chai";
|
|
3
|
+
import {DateTime} from "luxon";
|
|
4
|
+
import mongoose from "mongoose";
|
|
5
|
+
|
|
6
|
+
import {
|
|
7
|
+
buildCommsMessageMatch,
|
|
8
|
+
defaultStatsRange,
|
|
9
|
+
parseCommsListFilters,
|
|
10
|
+
parseCommsListPagination,
|
|
11
|
+
parseRetryManyLimit,
|
|
12
|
+
} from "./commsQuery";
|
|
13
|
+
|
|
14
|
+
describe("parseCommsListFilters", () => {
|
|
15
|
+
it("trims strings and drops blank or non-string values", () => {
|
|
16
|
+
const filters = parseCommsListFilters({
|
|
17
|
+
channel: " mail ",
|
|
18
|
+
errorClass: "",
|
|
19
|
+
provider: ["sendgrid"],
|
|
20
|
+
q: " ",
|
|
21
|
+
status: "failed",
|
|
22
|
+
to: 1234,
|
|
23
|
+
});
|
|
24
|
+
assert.equal(filters.channel, "mail");
|
|
25
|
+
assert.equal(filters.status, "failed");
|
|
26
|
+
assert.isUndefined(filters.errorClass);
|
|
27
|
+
assert.isUndefined(filters.provider);
|
|
28
|
+
assert.isUndefined(filters.q);
|
|
29
|
+
assert.isUndefined(filters.to);
|
|
30
|
+
});
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
describe("parseCommsListPagination", () => {
|
|
34
|
+
it("defaults to page 1 with a 20 row limit", () => {
|
|
35
|
+
assert.deepEqual(parseCommsListPagination({}), {limit: 20, page: 1, skip: 0});
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it("computes skip and clamps the limit to 100", () => {
|
|
39
|
+
assert.deepEqual(parseCommsListPagination({limit: "10", page: "3"}), {
|
|
40
|
+
limit: 10,
|
|
41
|
+
page: 3,
|
|
42
|
+
skip: 20,
|
|
43
|
+
});
|
|
44
|
+
assert.deepEqual(parseCommsListPagination({limit: "5000", page: "-4"}), {
|
|
45
|
+
limit: 100,
|
|
46
|
+
page: 1,
|
|
47
|
+
skip: 0,
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
describe("parseRetryManyLimit", () => {
|
|
53
|
+
it("falls back to the cap and clamps out-of-range values", () => {
|
|
54
|
+
assert.equal(parseRetryManyLimit(undefined), 100);
|
|
55
|
+
assert.equal(parseRetryManyLimit("not-a-number"), 100);
|
|
56
|
+
assert.equal(parseRetryManyLimit("250"), 100);
|
|
57
|
+
assert.equal(parseRetryManyLimit("0"), 1);
|
|
58
|
+
assert.equal(parseRetryManyLimit("25"), 25);
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
describe("defaultStatsRange", () => {
|
|
63
|
+
it("spans the trailing seven days", () => {
|
|
64
|
+
const {endDate, startDate} = defaultStatsRange();
|
|
65
|
+
assert.equal(Math.round(endDate.diff(startDate, "days").days), 7);
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
describe("buildCommsMessageMatch", () => {
|
|
70
|
+
it("always excludes soft-deleted rows", () => {
|
|
71
|
+
assert.deepEqual(buildCommsMessageMatch({}), {deleted: {$ne: true}});
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it("maps scalar filters straight through", () => {
|
|
75
|
+
const match = buildCommsMessageMatch({
|
|
76
|
+
channel: "mail",
|
|
77
|
+
errorClass: "transient",
|
|
78
|
+
errorCode: "timeout",
|
|
79
|
+
provider: "sendgrid",
|
|
80
|
+
status: "failed",
|
|
81
|
+
templateId: "welcome",
|
|
82
|
+
to: "a***@example.com",
|
|
83
|
+
});
|
|
84
|
+
assert.equal(match.channel, "mail");
|
|
85
|
+
assert.equal(match.errorClass, "transient");
|
|
86
|
+
assert.equal(match.errorCode, "timeout");
|
|
87
|
+
assert.equal(match.provider, "sendgrid");
|
|
88
|
+
assert.equal(match.status, "failed");
|
|
89
|
+
assert.equal(match.templateId, "welcome");
|
|
90
|
+
assert.equal(match.to, "a***@example.com");
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it("casts id filters and rejects malformed ones", () => {
|
|
94
|
+
const userId = new mongoose.Types.ObjectId().toString();
|
|
95
|
+
const retriedFromId = new mongoose.Types.ObjectId().toString();
|
|
96
|
+
const match = buildCommsMessageMatch({retriedFromId, userId});
|
|
97
|
+
assert.equal(String(match.userId), userId);
|
|
98
|
+
assert.equal(String(match.retriedFromId), retriedFromId);
|
|
99
|
+
|
|
100
|
+
assert.throws(() => buildCommsMessageMatch({userId: "nope"}), /Invalid userId/);
|
|
101
|
+
assert.throws(() => buildCommsMessageMatch({retriedFromId: "nope"}), /Invalid retriedFromId/);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it("builds created bounds from either end of the range", () => {
|
|
105
|
+
const startOnly = buildCommsMessageMatch({startDate: "2026-08-01T00:00:00.000Z"}) as {
|
|
106
|
+
created: {$gte?: Date; $lte?: Date};
|
|
107
|
+
};
|
|
108
|
+
assert.instanceOf(startOnly.created.$gte, Date);
|
|
109
|
+
assert.isUndefined(startOnly.created.$lte);
|
|
110
|
+
|
|
111
|
+
const endOnly = buildCommsMessageMatch({endDate: "2026-08-31T00:00:00.000Z"}) as {
|
|
112
|
+
created: {$gte?: Date; $lte?: Date};
|
|
113
|
+
};
|
|
114
|
+
assert.instanceOf(endOnly.created.$lte, Date);
|
|
115
|
+
assert.isUndefined(endOnly.created.$gte);
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
it("rejects invalid dates and inverted ranges", () => {
|
|
119
|
+
assert.throws(() => buildCommsMessageMatch({startDate: "yesterday"}), /Invalid startDate/);
|
|
120
|
+
assert.throws(() => buildCommsMessageMatch({endDate: "soon"}), /Invalid endDate/);
|
|
121
|
+
assert.throws(
|
|
122
|
+
() =>
|
|
123
|
+
buildCommsMessageMatch({
|
|
124
|
+
endDate: "2026-08-01T00:00:00.000Z",
|
|
125
|
+
startDate: "2026-08-31T00:00:00.000Z",
|
|
126
|
+
}),
|
|
127
|
+
/startDate must not be after endDate/
|
|
128
|
+
);
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
it("applies the default stats range only when both bounds are absent", () => {
|
|
132
|
+
const defaulted = buildCommsMessageMatch({}, {applyDefaultStatsRange: true}) as {
|
|
133
|
+
created: {$gte: Date; $lte: Date};
|
|
134
|
+
};
|
|
135
|
+
const spanDays = DateTime.fromJSDate(defaulted.created.$lte).diff(
|
|
136
|
+
DateTime.fromJSDate(defaulted.created.$gte),
|
|
137
|
+
"days"
|
|
138
|
+
).days;
|
|
139
|
+
assert.equal(Math.round(spanDays), 7);
|
|
140
|
+
|
|
141
|
+
const explicit = buildCommsMessageMatch(
|
|
142
|
+
{startDate: "2026-08-01T00:00:00.000Z"},
|
|
143
|
+
{applyDefaultStatsRange: true}
|
|
144
|
+
) as {created: {$gte: Date; $lte?: Date}};
|
|
145
|
+
assert.isUndefined(explicit.created.$lte);
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it("searches subject, error, and recipient, escaping regex metacharacters", () => {
|
|
149
|
+
const match = buildCommsMessageMatch({q: "a.b*c"}) as {
|
|
150
|
+
$or: Array<Record<string, {$regex: string}>>;
|
|
151
|
+
};
|
|
152
|
+
assert.lengthOf(match.$or, 3);
|
|
153
|
+
assert.equal(match.$or[0].subject.$regex, "a\\.b\\*c");
|
|
154
|
+
assert.equal(match.$or[1].error.$regex, "a\\.b\\*c");
|
|
155
|
+
assert.equal(match.$or[2].to.$regex, "a\\.b\\*c");
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
it("adds a last-4 suffix clause for redacted destinations", () => {
|
|
159
|
+
const match = buildCommsMessageMatch({q: "1234"}) as {
|
|
160
|
+
$or: Array<Record<string, {$regex: string}>>;
|
|
161
|
+
};
|
|
162
|
+
assert.lengthOf(match.$or, 4);
|
|
163
|
+
assert.equal(match.$or[3].to.$regex, "1234$");
|
|
164
|
+
});
|
|
165
|
+
});
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import {APIError} from "@terreno/api";
|
|
2
|
+
import {DateTime} from "luxon";
|
|
3
|
+
import mongoose from "mongoose";
|
|
4
|
+
|
|
5
|
+
export interface CommsListFilters {
|
|
6
|
+
channel?: string;
|
|
7
|
+
endDate?: string;
|
|
8
|
+
errorClass?: string;
|
|
9
|
+
errorCode?: string;
|
|
10
|
+
provider?: string;
|
|
11
|
+
q?: string;
|
|
12
|
+
retriedFromId?: string;
|
|
13
|
+
startDate?: string;
|
|
14
|
+
status?: string;
|
|
15
|
+
templateId?: string;
|
|
16
|
+
to?: string;
|
|
17
|
+
userId?: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface CommsListPagination {
|
|
21
|
+
limit: number;
|
|
22
|
+
page: number;
|
|
23
|
+
skip: number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const DEFAULT_LIMIT = 20;
|
|
27
|
+
const MAX_LIMIT = 100;
|
|
28
|
+
const DEFAULT_STATS_DAYS = 7;
|
|
29
|
+
|
|
30
|
+
const escapeRegex = (value: string): string => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
31
|
+
|
|
32
|
+
const queryString = (value: unknown): string | undefined => {
|
|
33
|
+
if (typeof value !== "string") {
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
const trimmed = value.trim();
|
|
37
|
+
return trimmed.length > 0 ? trimmed : undefined;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
export const parseCommsListFilters = (source: Record<string, unknown>): CommsListFilters => ({
|
|
41
|
+
channel: queryString(source.channel),
|
|
42
|
+
endDate: queryString(source.endDate),
|
|
43
|
+
errorClass: queryString(source.errorClass),
|
|
44
|
+
errorCode: queryString(source.errorCode),
|
|
45
|
+
provider: queryString(source.provider),
|
|
46
|
+
q: queryString(source.q),
|
|
47
|
+
retriedFromId: queryString(source.retriedFromId),
|
|
48
|
+
startDate: queryString(source.startDate),
|
|
49
|
+
status: queryString(source.status),
|
|
50
|
+
templateId: queryString(source.templateId),
|
|
51
|
+
to: queryString(source.to),
|
|
52
|
+
userId: queryString(source.userId),
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
export const parseCommsListPagination = (source: Record<string, unknown>): CommsListPagination => {
|
|
56
|
+
const page = Math.max(1, Number.parseInt(String(source.page ?? ""), 10) || 1);
|
|
57
|
+
const limit = Math.min(
|
|
58
|
+
MAX_LIMIT,
|
|
59
|
+
Math.max(1, Number.parseInt(String(source.limit ?? ""), 10) || DEFAULT_LIMIT)
|
|
60
|
+
);
|
|
61
|
+
return {limit, page, skip: (page - 1) * limit};
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
export const parseRetryManyLimit = (value: unknown): number => {
|
|
65
|
+
const parsed = Number.parseInt(String(value ?? ""), 10);
|
|
66
|
+
if (Number.isNaN(parsed)) {
|
|
67
|
+
return MAX_LIMIT;
|
|
68
|
+
}
|
|
69
|
+
return Math.min(MAX_LIMIT, Math.max(1, parsed));
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const parseIsoDate = (value: string, field: "startDate" | "endDate"): DateTime => {
|
|
73
|
+
const parsed = DateTime.fromISO(value, {zone: "utc"});
|
|
74
|
+
if (!parsed.isValid) {
|
|
75
|
+
throw new APIError({status: 400, title: `Invalid ${field} format`});
|
|
76
|
+
}
|
|
77
|
+
return parsed;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
/** @internal */
|
|
81
|
+
export const defaultStatsRange = (): {endDate: DateTime; startDate: DateTime} => {
|
|
82
|
+
const endDate = DateTime.utc();
|
|
83
|
+
return {endDate, startDate: endDate.minus({days: DEFAULT_STATS_DAYS})};
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
export const buildCommsMessageMatch = (
|
|
87
|
+
filters: CommsListFilters,
|
|
88
|
+
options?: {applyDefaultStatsRange?: boolean}
|
|
89
|
+
): Record<string, unknown> => {
|
|
90
|
+
const match: Record<string, unknown> & {created?: {$gte?: Date; $lte?: Date}} = {
|
|
91
|
+
deleted: {$ne: true},
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
if (filters.channel) {
|
|
95
|
+
match.channel = filters.channel;
|
|
96
|
+
}
|
|
97
|
+
if (filters.provider) {
|
|
98
|
+
match.provider = filters.provider;
|
|
99
|
+
}
|
|
100
|
+
if (filters.status) {
|
|
101
|
+
match.status = filters.status;
|
|
102
|
+
}
|
|
103
|
+
if (filters.errorClass) {
|
|
104
|
+
match.errorClass = filters.errorClass;
|
|
105
|
+
}
|
|
106
|
+
if (filters.errorCode) {
|
|
107
|
+
match.errorCode = filters.errorCode;
|
|
108
|
+
}
|
|
109
|
+
if (filters.templateId) {
|
|
110
|
+
match.templateId = filters.templateId;
|
|
111
|
+
}
|
|
112
|
+
if (filters.to) {
|
|
113
|
+
match.to = filters.to;
|
|
114
|
+
}
|
|
115
|
+
if (filters.userId) {
|
|
116
|
+
if (!mongoose.isValidObjectId(filters.userId)) {
|
|
117
|
+
throw new APIError({status: 400, title: "Invalid userId"});
|
|
118
|
+
}
|
|
119
|
+
match.userId = new mongoose.Types.ObjectId(filters.userId);
|
|
120
|
+
}
|
|
121
|
+
if (filters.retriedFromId) {
|
|
122
|
+
if (!mongoose.isValidObjectId(filters.retriedFromId)) {
|
|
123
|
+
throw new APIError({status: 400, title: "Invalid retriedFromId"});
|
|
124
|
+
}
|
|
125
|
+
match.retriedFromId = new mongoose.Types.ObjectId(filters.retriedFromId);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
let start = filters.startDate ? parseIsoDate(filters.startDate, "startDate") : undefined;
|
|
129
|
+
let end = filters.endDate ? parseIsoDate(filters.endDate, "endDate") : undefined;
|
|
130
|
+
if (options?.applyDefaultStatsRange && !start && !end) {
|
|
131
|
+
const range = defaultStatsRange();
|
|
132
|
+
start = range.startDate;
|
|
133
|
+
end = range.endDate;
|
|
134
|
+
}
|
|
135
|
+
if (start || end) {
|
|
136
|
+
match.created = {};
|
|
137
|
+
if (start) {
|
|
138
|
+
match.created.$gte = start.toJSDate();
|
|
139
|
+
}
|
|
140
|
+
if (end) {
|
|
141
|
+
match.created.$lte = end.toJSDate();
|
|
142
|
+
}
|
|
143
|
+
if (start && end && start.toMillis() > end.toMillis()) {
|
|
144
|
+
throw new APIError({status: 400, title: "startDate must not be after endDate"});
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if (filters.q) {
|
|
149
|
+
const escaped = escapeRegex(filters.q);
|
|
150
|
+
const clauses: Record<string, unknown>[] = [
|
|
151
|
+
{subject: {$options: "i", $regex: escaped}},
|
|
152
|
+
{error: {$options: "i", $regex: escaped}},
|
|
153
|
+
{to: {$options: "i", $regex: escaped}},
|
|
154
|
+
];
|
|
155
|
+
const last4 = filters.q.replace(/\s/g, "");
|
|
156
|
+
if (/^[A-Za-z0-9]{4}$/.test(last4)) {
|
|
157
|
+
clauses.push({to: {$options: "i", $regex: `${escapeRegex(last4)}$`}});
|
|
158
|
+
}
|
|
159
|
+
match.$or = clauses;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
return match;
|
|
163
|
+
};
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import {APIError} from "@terreno/api";
|
|
2
|
+
import {DateTime} from "luxon";
|
|
3
|
+
|
|
4
|
+
import type {CommsMessageDocument} from "./modelTypes";
|
|
5
|
+
import type {CommsChannel} from "./types";
|
|
6
|
+
|
|
7
|
+
const COMMS_RETRY_NOT_RETRYABLE = "comms-retry-not-retryable";
|
|
8
|
+
const COMMS_RETRY_PAYLOAD_EXPIRED = "comms-retry-payload-expired";
|
|
9
|
+
const COMMS_RETRY_CHANNEL_UNCONFIGURED = "comms-retry-channel-unconfigured";
|
|
10
|
+
|
|
11
|
+
export interface CommsRetryBlock {
|
|
12
|
+
code: string;
|
|
13
|
+
title: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const RETRYABLE_STATUSES = new Set(["bounced", "failed"]);
|
|
17
|
+
|
|
18
|
+
const isPayloadPresent = (message: CommsMessageDocument): boolean => {
|
|
19
|
+
if (message.payload === undefined || message.payload === null) {
|
|
20
|
+
return false;
|
|
21
|
+
}
|
|
22
|
+
if (message.payloadExpiresAt && DateTime.fromJSDate(message.payloadExpiresAt) <= DateTime.utc()) {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
return true;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export const evaluateRetryBlock = ({
|
|
29
|
+
isChannelConfigured,
|
|
30
|
+
message,
|
|
31
|
+
}: {
|
|
32
|
+
isChannelConfigured: (channel: CommsChannel) => boolean;
|
|
33
|
+
message: CommsMessageDocument;
|
|
34
|
+
}): CommsRetryBlock | undefined => {
|
|
35
|
+
if (message.channel === "verification") {
|
|
36
|
+
return {
|
|
37
|
+
code: COMMS_RETRY_NOT_RETRYABLE,
|
|
38
|
+
title: "Verification messages are not retryable",
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
if (!RETRYABLE_STATUSES.has(message.status)) {
|
|
42
|
+
return {
|
|
43
|
+
code: COMMS_RETRY_NOT_RETRYABLE,
|
|
44
|
+
title: "Only failed or bounced messages can be retried",
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
if (message.errorClass === "permanent") {
|
|
48
|
+
return {
|
|
49
|
+
code: COMMS_RETRY_NOT_RETRYABLE,
|
|
50
|
+
title: "Permanent failures cannot be retried",
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
if (!isPayloadPresent(message)) {
|
|
54
|
+
return {
|
|
55
|
+
code: COMMS_RETRY_PAYLOAD_EXPIRED,
|
|
56
|
+
title: "Retained payload is missing or expired",
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
if (!isChannelConfigured(message.channel)) {
|
|
60
|
+
return {
|
|
61
|
+
code: COMMS_RETRY_CHANNEL_UNCONFIGURED,
|
|
62
|
+
title: "Comms channel is not configured",
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
return undefined;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
export const throwRetryBlock = (block: CommsRetryBlock): never => {
|
|
69
|
+
throw new APIError({
|
|
70
|
+
code: block.code,
|
|
71
|
+
status: 400,
|
|
72
|
+
title: block.title,
|
|
73
|
+
});
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
export const serializeCommsMessage = (
|
|
77
|
+
message: CommsMessageDocument,
|
|
78
|
+
isChannelConfigured: (channel: CommsChannel) => boolean
|
|
79
|
+
): Record<string, unknown> => {
|
|
80
|
+
const json = message.toJSON() as Record<string, unknown>;
|
|
81
|
+
const block = evaluateRetryBlock({isChannelConfigured, message});
|
|
82
|
+
return {
|
|
83
|
+
...json,
|
|
84
|
+
retryable: !block,
|
|
85
|
+
retryDisabledReason: block?.title,
|
|
86
|
+
};
|
|
87
|
+
};
|
package/src/commsService.test.ts
CHANGED
|
@@ -709,6 +709,99 @@ describe("CommsService", () => {
|
|
|
709
709
|
const row = await CommsMessage.findExactlyOne({status: "cancelled"});
|
|
710
710
|
assert.equal(row.attemptCount, 1);
|
|
711
711
|
assert.equal((row.payload as {to?: string}).to, "person@example.com");
|
|
712
|
+
assert.equal(result.loggedMessageId, String(row._id));
|
|
713
|
+
});
|
|
714
|
+
|
|
715
|
+
it("passes the send option userId to mail and SMS beforeSend hooks", async (): Promise<void> => {
|
|
716
|
+
const seenUserIds: Array<string | undefined> = [];
|
|
717
|
+
const mailUserId = new mongoose.Types.ObjectId();
|
|
718
|
+
const smsUserId = new mongoose.Types.ObjectId();
|
|
719
|
+
const service = new CommsService({
|
|
720
|
+
beforeSend: async (context): Promise<undefined> => {
|
|
721
|
+
seenUserIds.push(context.userId);
|
|
722
|
+
return undefined;
|
|
723
|
+
},
|
|
724
|
+
mail: {
|
|
725
|
+
id: "user-aware-mail",
|
|
726
|
+
sendMail: async (): Promise<SendResult> => ({accepted: true}),
|
|
727
|
+
},
|
|
728
|
+
sms: {
|
|
729
|
+
id: "user-aware-sms",
|
|
730
|
+
sendSms: async (): Promise<SendResult> => ({accepted: true}),
|
|
731
|
+
},
|
|
732
|
+
});
|
|
733
|
+
|
|
734
|
+
await service.sendMail({subject: "Welcome", to: "person@example.com"}, {userId: mailUserId});
|
|
735
|
+
await service.sendSms({body: "Hello", to: "+15555550100"}, {userId: smsUserId});
|
|
736
|
+
|
|
737
|
+
assert.deepEqual(seenUserIds, [String(mailUserId), String(smsUserId)]);
|
|
738
|
+
const mailLog = await CommsMessage.findExactlyOne({channel: "mail"});
|
|
739
|
+
const smsLog = await CommsMessage.findExactlyOne({channel: "sms"});
|
|
740
|
+
assert.equal(String(mailLog.userId), String(mailUserId));
|
|
741
|
+
assert.equal(String(smsLog.userId), String(smsUserId));
|
|
742
|
+
});
|
|
743
|
+
|
|
744
|
+
it("preserves the original userId when retrying mail", async (): Promise<void> => {
|
|
745
|
+
const userId = new mongoose.Types.ObjectId();
|
|
746
|
+
const seenUserIds: Array<string | undefined> = [];
|
|
747
|
+
const service = new CommsService({
|
|
748
|
+
beforeSend: async (context): Promise<undefined> => {
|
|
749
|
+
seenUserIds.push(context.userId);
|
|
750
|
+
return undefined;
|
|
751
|
+
},
|
|
752
|
+
mail: {
|
|
753
|
+
id: "retry-user-aware-mail",
|
|
754
|
+
sendMail: async (): Promise<SendResult> => ({accepted: true}),
|
|
755
|
+
},
|
|
756
|
+
});
|
|
757
|
+
const original = await CommsMessage.create({
|
|
758
|
+
channel: "mail",
|
|
759
|
+
payload: {subject: "Retry me", to: "person@example.com"},
|
|
760
|
+
payloadExpiresAt: DateTime.utc().plus({days: 1}).toJSDate(),
|
|
761
|
+
provider: "retry-user-aware-mail",
|
|
762
|
+
status: "failed",
|
|
763
|
+
subject: "Retry me",
|
|
764
|
+
to: "person@example.com",
|
|
765
|
+
userId,
|
|
766
|
+
});
|
|
767
|
+
|
|
768
|
+
await service.retryMessage({messageId: String(original._id)});
|
|
769
|
+
|
|
770
|
+
assert.deepEqual(seenUserIds, [String(userId)]);
|
|
771
|
+
const retried = await CommsMessage.findExactlyOne({retriedFromId: original._id});
|
|
772
|
+
assert.equal(String(retried.userId), String(userId));
|
|
773
|
+
});
|
|
774
|
+
|
|
775
|
+
it("attaches loggedMessageId when beforeSend cancels a push send", async (): Promise<void> => {
|
|
776
|
+
const userId = new mongoose.Types.ObjectId();
|
|
777
|
+
await PushToken.upsert(
|
|
778
|
+
{token: "ExponentPushToken[cancel]"},
|
|
779
|
+
{
|
|
780
|
+
active: true,
|
|
781
|
+
lastSeenAt: DateTime.utc().toJSDate(),
|
|
782
|
+
platform: "ios",
|
|
783
|
+
userId,
|
|
784
|
+
}
|
|
785
|
+
);
|
|
786
|
+
let sendCount = 0;
|
|
787
|
+
const service = new CommsService({
|
|
788
|
+
beforeSend: async (): Promise<{cancel: boolean}> => ({cancel: true}),
|
|
789
|
+
push: {
|
|
790
|
+
id: "cancel-push",
|
|
791
|
+
sendPush: async (): Promise<SendResult[]> => {
|
|
792
|
+
sendCount += 1;
|
|
793
|
+
return [{accepted: true}];
|
|
794
|
+
},
|
|
795
|
+
},
|
|
796
|
+
});
|
|
797
|
+
|
|
798
|
+
const results = await service.sendPushToUser({body: "Hello", title: "Title", userId});
|
|
799
|
+
|
|
800
|
+
assert.equal(sendCount, 0);
|
|
801
|
+
assert.equal(results.length, 1);
|
|
802
|
+
assert.isFalse(results[0]?.accepted);
|
|
803
|
+
const row = await CommsMessage.findExactlyOne({channel: "push", status: "cancelled"});
|
|
804
|
+
assert.equal(results[0]?.loggedMessageId, String(row._id));
|
|
712
805
|
});
|
|
713
806
|
|
|
714
807
|
it("lets beforeSend replace the outbound message", async (): Promise<void> => {
|
|
@@ -1244,6 +1337,41 @@ describe("CommsService", () => {
|
|
|
1244
1337
|
warnSpy.mockRestore();
|
|
1245
1338
|
});
|
|
1246
1339
|
|
|
1340
|
+
it("rethrows when applying a delivery event fails to save", async (): Promise<void> => {
|
|
1341
|
+
const warnSpy = spyOn(logger, "warn");
|
|
1342
|
+
const service = new CommsService({
|
|
1343
|
+
mail: {
|
|
1344
|
+
id: "event-mail-save-fail",
|
|
1345
|
+
sendMail: async (): Promise<SendResult> => ({
|
|
1346
|
+
accepted: true,
|
|
1347
|
+
providerMessageId: "mail-save-fail",
|
|
1348
|
+
}),
|
|
1349
|
+
},
|
|
1350
|
+
});
|
|
1351
|
+
await service.sendMail({subject: "Welcome", to: "person@example.com"});
|
|
1352
|
+
const saveSpy = spyOn(CommsMessage.prototype, "save").mockImplementation(
|
|
1353
|
+
async (): Promise<never> => {
|
|
1354
|
+
throw new Error("save failed");
|
|
1355
|
+
}
|
|
1356
|
+
);
|
|
1357
|
+
let threw = false;
|
|
1358
|
+
try {
|
|
1359
|
+
await service.recordDeliveryEvent({
|
|
1360
|
+
channel: "mail",
|
|
1361
|
+
providerMessageId: "mail-save-fail",
|
|
1362
|
+
status: "delivered",
|
|
1363
|
+
});
|
|
1364
|
+
} catch (error: unknown) {
|
|
1365
|
+
threw = error instanceof Error && error.message === "save failed";
|
|
1366
|
+
}
|
|
1367
|
+
saveSpy.mockRestore();
|
|
1368
|
+
assert.isTrue(threw);
|
|
1369
|
+
assert.isTrue(
|
|
1370
|
+
warnSpy.mock.calls.some((call) => String(call[0]).includes("Failed to apply delivery event"))
|
|
1371
|
+
);
|
|
1372
|
+
warnSpy.mockRestore();
|
|
1373
|
+
});
|
|
1374
|
+
|
|
1247
1375
|
it("retries startVerification once on transient failure and never retries checkVerification", async (): Promise<void> => {
|
|
1248
1376
|
let startCalls = 0;
|
|
1249
1377
|
let checkCalls = 0;
|