@memberjunction/communication-engine 6.3.0-edge.1 → 6.3.0-edge.2
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 +203 -0
- package/dist/CommsActivityWorker.d.ts +130 -0
- package/dist/CommsActivityWorker.d.ts.map +1 -0
- package/dist/CommsActivityWorker.js +1054 -0
- package/dist/CommsActivityWorker.js.map +1 -0
- package/dist/DefaultCommunicationPrincipal.d.ts +62 -0
- package/dist/DefaultCommunicationPrincipal.d.ts.map +1 -0
- package/dist/DefaultCommunicationPrincipal.js +382 -0
- package/dist/DefaultCommunicationPrincipal.js.map +1 -0
- package/dist/Engine.d.ts +54 -1
- package/dist/Engine.d.ts.map +1 -1
- package/dist/Engine.js +123 -2
- package/dist/Engine.js.map +1 -1
- package/dist/LocalJsonCommunicationProvider.d.ts +133 -0
- package/dist/LocalJsonCommunicationProvider.d.ts.map +1 -0
- package/dist/LocalJsonCommunicationProvider.js +1337 -0
- package/dist/LocalJsonCommunicationProvider.js.map +1 -0
- package/dist/V2SendService.d.ts +293 -0
- package/dist/V2SendService.d.ts.map +1 -0
- package/dist/V2SendService.js +2035 -0
- package/dist/V2SendService.js.map +1 -0
- package/dist/compliance/ComplianceGate.d.ts +56 -0
- package/dist/compliance/ComplianceGate.d.ts.map +1 -0
- package/dist/compliance/ComplianceGate.js +452 -0
- package/dist/compliance/ComplianceGate.js.map +1 -0
- package/dist/compliance/JurisdictionResolver.d.ts +82 -0
- package/dist/compliance/JurisdictionResolver.d.ts.map +1 -0
- package/dist/compliance/JurisdictionResolver.js +249 -0
- package/dist/compliance/JurisdictionResolver.js.map +1 -0
- package/dist/compliance/index.d.ts +4 -0
- package/dist/compliance/index.d.ts.map +1 -0
- package/dist/compliance/index.js +4 -0
- package/dist/compliance/index.js.map +1 -0
- package/dist/compliance/rules/ConsentEvidenceRuleDriver.d.ts +22 -0
- package/dist/compliance/rules/ConsentEvidenceRuleDriver.d.ts.map +1 -0
- package/dist/compliance/rules/ConsentEvidenceRuleDriver.js +76 -0
- package/dist/compliance/rules/ConsentEvidenceRuleDriver.js.map +1 -0
- package/dist/compliance/rules/ConsentExpiryRuleDriver.d.ts +20 -0
- package/dist/compliance/rules/ConsentExpiryRuleDriver.d.ts.map +1 -0
- package/dist/compliance/rules/ConsentExpiryRuleDriver.js +70 -0
- package/dist/compliance/rules/ConsentExpiryRuleDriver.js.map +1 -0
- package/dist/compliance/rules/ConsentModelRuleDriver.d.ts +22 -0
- package/dist/compliance/rules/ConsentModelRuleDriver.d.ts.map +1 -0
- package/dist/compliance/rules/ConsentModelRuleDriver.js +65 -0
- package/dist/compliance/rules/ConsentModelRuleDriver.js.map +1 -0
- package/dist/compliance/rules/QuietHoursRuleDriver.d.ts +37 -0
- package/dist/compliance/rules/QuietHoursRuleDriver.d.ts.map +1 -0
- package/dist/compliance/rules/QuietHoursRuleDriver.js +144 -0
- package/dist/compliance/rules/QuietHoursRuleDriver.js.map +1 -0
- package/dist/compliance/rules/RequireDoubleOptInRuleDriver.d.ts +16 -0
- package/dist/compliance/rules/RequireDoubleOptInRuleDriver.d.ts.map +1 -0
- package/dist/compliance/rules/RequireDoubleOptInRuleDriver.js +40 -0
- package/dist/compliance/rules/RequireDoubleOptInRuleDriver.js.map +1 -0
- package/dist/compliance/rules/RuleParamUtils.d.ts +13 -0
- package/dist/compliance/rules/RuleParamUtils.d.ts.map +1 -0
- package/dist/compliance/rules/RuleParamUtils.js +51 -0
- package/dist/compliance/rules/RuleParamUtils.js.map +1 -0
- package/dist/compliance/rules/SenderIdentificationRuleDriver.d.ts +17 -0
- package/dist/compliance/rules/SenderIdentificationRuleDriver.d.ts.map +1 -0
- package/dist/compliance/rules/SenderIdentificationRuleDriver.js +64 -0
- package/dist/compliance/rules/SenderIdentificationRuleDriver.js.map +1 -0
- package/dist/compliance/rules/TrackingConsentRuleDriver.d.ts +23 -0
- package/dist/compliance/rules/TrackingConsentRuleDriver.d.ts.map +1 -0
- package/dist/compliance/rules/TrackingConsentRuleDriver.js +81 -0
- package/dist/compliance/rules/TrackingConsentRuleDriver.js.map +1 -0
- package/dist/compliance/rules/UnsubscribeHonorWindowRuleDriver.d.ts +21 -0
- package/dist/compliance/rules/UnsubscribeHonorWindowRuleDriver.d.ts.map +1 -0
- package/dist/compliance/rules/UnsubscribeHonorWindowRuleDriver.js +33 -0
- package/dist/compliance/rules/UnsubscribeHonorWindowRuleDriver.js.map +1 -0
- package/dist/compliance/rules/UnsubscribeMechanismRuleDriver.d.ts +19 -0
- package/dist/compliance/rules/UnsubscribeMechanismRuleDriver.d.ts.map +1 -0
- package/dist/compliance/rules/UnsubscribeMechanismRuleDriver.js +73 -0
- package/dist/compliance/rules/UnsubscribeMechanismRuleDriver.js.map +1 -0
- package/dist/compliance/rules/index.d.ts +10 -0
- package/dist/compliance/rules/index.d.ts.map +1 -0
- package/dist/compliance/rules/index.js +10 -0
- package/dist/compliance/rules/index.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +9 -9
|
@@ -0,0 +1,2035 @@
|
|
|
1
|
+
import { createHash, createHmac, randomUUID, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { BaseCommunicationPrincipal, BaseCommunicationSender, CommunicationEngineBase, Message, } from '@memberjunction/communication-types';
|
|
3
|
+
import { AuthorizationEvaluator, LogError, RunView } from '@memberjunction/core';
|
|
4
|
+
import { EscapeSQLString, IndexByUUID, MJGlobal, NormalizeUUID, UUIDSet, UUIDsEqual } from '@memberjunction/global';
|
|
5
|
+
import { CredentialEngine } from '@memberjunction/credentials';
|
|
6
|
+
import { ProcessedMessageServer } from './BaseProvider.js';
|
|
7
|
+
import { ComplianceGate } from './compliance/ComplianceGate.js';
|
|
8
|
+
import { JurisdictionResolver } from './compliance/JurisdictionResolver.js';
|
|
9
|
+
import { ComputeEndpointHash, NormalizeEndpointAddress, PrincipalRecordKey, } from './DefaultCommunicationPrincipal.js';
|
|
10
|
+
const DEFAULT_CHUNK_SIZE = 50; // recipients per queued comms.dispatch chunk when V2DispatchConfig.ChunkSize is unset
|
|
11
|
+
const DEFAULT_ASYNC_THRESHOLD = 100; // recipient count above which a send is queued in chunks, when V2DispatchConfig.AsyncThreshold is unset
|
|
12
|
+
/**
|
|
13
|
+
* Returns the hex HMAC-SHA256 of `trackingToken + ':' + targetUrl`. This is the `sig` parameter of
|
|
14
|
+
* a click-tracking link.
|
|
15
|
+
*/
|
|
16
|
+
export function ComputeTrackingSignature(trackingToken, targetUrl, secret) {
|
|
17
|
+
return createHmac('sha256', secret)
|
|
18
|
+
.update(`${trackingToken}:${targetUrl}`, 'utf8')
|
|
19
|
+
.digest('hex');
|
|
20
|
+
}
|
|
21
|
+
/** Checks a click-tracking signature in constant time. */
|
|
22
|
+
export function VerifyTrackingSignature(trackingToken, targetUrl, signature, secret) {
|
|
23
|
+
const expected = ComputeTrackingSignature(trackingToken, targetUrl, secret);
|
|
24
|
+
const a = Buffer.from(expected, 'utf8');
|
|
25
|
+
const b = Buffer.from(signature, 'utf8');
|
|
26
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* What an open-pixel signature signs in place of a click target. It is not an `http(s)` URL, so an
|
|
30
|
+
* open signature can never pass as a click signature for the same tracking token.
|
|
31
|
+
*/
|
|
32
|
+
const OPEN_PIXEL_SIGNATURE_SCOPE = 'open';
|
|
33
|
+
/**
|
|
34
|
+
* Returns the `sig` parameter of an open-pixel URL: the hex HMAC-SHA256 of
|
|
35
|
+
* `trackingToken + ':open'`. With it the `/comms/open` route can tell a pixel this system issued
|
|
36
|
+
* from a guessed token without reading the database.
|
|
37
|
+
*/
|
|
38
|
+
export function ComputeOpenPixelSignature(trackingToken, secret) {
|
|
39
|
+
return ComputeTrackingSignature(trackingToken, OPEN_PIXEL_SIGNATURE_SCOPE, secret);
|
|
40
|
+
}
|
|
41
|
+
/** Checks an open-pixel signature in constant time. */
|
|
42
|
+
export function VerifyOpenPixelSignature(trackingToken, signature, secret) {
|
|
43
|
+
return VerifyTrackingSignature(trackingToken, OPEN_PIXEL_SIGNATURE_SCOPE, signature, secret);
|
|
44
|
+
}
|
|
45
|
+
function buildCommsRouteUrl(baseUrl, subpath) {
|
|
46
|
+
let end = baseUrl.length;
|
|
47
|
+
while (end > 0 && baseUrl.charCodeAt(end - 1) === 47) {
|
|
48
|
+
end--;
|
|
49
|
+
}
|
|
50
|
+
const cleanBase = baseUrl.slice(0, end);
|
|
51
|
+
if (!cleanBase) {
|
|
52
|
+
return `/comms${subpath}`;
|
|
53
|
+
}
|
|
54
|
+
return cleanBase.endsWith('/comms')
|
|
55
|
+
? `${cleanBase}${subpath}`
|
|
56
|
+
: `${cleanBase}/comms${subpath}`;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Longest tracked link `RewriteLinksForTracking` will produce. The target travels inside the
|
|
60
|
+
* tracked link, so the tracked link is always the longer of the two. Past this length links fail
|
|
61
|
+
* in practice: some mail clients cap links near 2,000 characters, proxies reject long request
|
|
62
|
+
* lines, and `MJ: Communication Activities.TargetURL` holds 2,000 characters.
|
|
63
|
+
*/
|
|
64
|
+
export const MAX_TRACKED_LINK_LENGTH = 2000;
|
|
65
|
+
/**
|
|
66
|
+
* Rewrites every absolute `http(s)` link in `<a href>` tags to
|
|
67
|
+
* `<baseUrl>/comms/click/<trackingToken>?u=<target>&sig=<signature>`. Links listed in
|
|
68
|
+
* `excludedUrls` (the unsubscribe and preference-center links) are left as they are, and so is a
|
|
69
|
+
* link whose tracked form would be longer than `MAX_TRACKED_LINK_LENGTH`: it still works for the
|
|
70
|
+
* recipient, but its clicks are not recorded.
|
|
71
|
+
*/
|
|
72
|
+
export function RewriteLinksForTracking(html, trackingToken, secret, baseUrl = '', excludedUrls = []) {
|
|
73
|
+
const excluded = new Set(excludedUrls.filter(Boolean));
|
|
74
|
+
const lower = html.toLowerCase();
|
|
75
|
+
const out = [];
|
|
76
|
+
let pos = 0;
|
|
77
|
+
while (pos < html.length) {
|
|
78
|
+
const idx = lower.indexOf('<a', pos);
|
|
79
|
+
if (idx === -1) {
|
|
80
|
+
out.push(html.slice(pos));
|
|
81
|
+
break;
|
|
82
|
+
}
|
|
83
|
+
const afterTag = lower[idx + 2];
|
|
84
|
+
if (afterTag !== undefined && !/\s|>/.test(afterTag)) {
|
|
85
|
+
out.push(html.slice(pos, idx + 2));
|
|
86
|
+
pos = idx + 2;
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
const closeIdx = html.indexOf('>', idx + 2);
|
|
90
|
+
if (closeIdx === -1) {
|
|
91
|
+
out.push(html.slice(pos));
|
|
92
|
+
break;
|
|
93
|
+
}
|
|
94
|
+
out.push(html.slice(pos, idx));
|
|
95
|
+
const attrs = html.slice(idx + 2, closeIdx);
|
|
96
|
+
const updatedAttrs = attrs.replace(/\bhref\s*=\s*(["'])(https?:\/\/[^"']+)\1/i, (hrefMatch, quote, url) => {
|
|
97
|
+
const decodedUrl = url.replace(/&/gi, '&');
|
|
98
|
+
if (excluded.has(decodedUrl) || excluded.has(url)) {
|
|
99
|
+
return hrefMatch;
|
|
100
|
+
}
|
|
101
|
+
const sig = ComputeTrackingSignature(trackingToken, decodedUrl, secret);
|
|
102
|
+
const tracked = `${buildCommsRouteUrl(baseUrl, `/click/${trackingToken}`)}?u=${encodeURIComponent(decodedUrl)}&sig=${sig}`;
|
|
103
|
+
if (tracked.length > MAX_TRACKED_LINK_LENGTH) {
|
|
104
|
+
return hrefMatch;
|
|
105
|
+
}
|
|
106
|
+
return `href=${quote}${tracked}${quote}`;
|
|
107
|
+
});
|
|
108
|
+
out.push(`<a${updatedAttrs}>`);
|
|
109
|
+
pos = closeIdx + 1;
|
|
110
|
+
}
|
|
111
|
+
return out.join('');
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Adds the 1x1 open-tracking image (`<baseUrl>/comms/open/<trackingToken>.gif?sig=<signature>`)
|
|
115
|
+
* before `</body>`, or at the end when there is no body tag. The signature is left off when no
|
|
116
|
+
* `secret` is given; the route then has to look the token up before it records the open.
|
|
117
|
+
*/
|
|
118
|
+
export function InjectOpenPixel(html, trackingToken, baseUrl = '', secret = '') {
|
|
119
|
+
const signature = secret ? `?sig=${ComputeOpenPixelSignature(trackingToken, secret)}` : '';
|
|
120
|
+
const pixel = `<img src="${buildCommsRouteUrl(baseUrl, `/open/${trackingToken}.gif`)}${signature}" width="1" height="1" alt="" style="display:none;" />`;
|
|
121
|
+
if (/<\/body>/i.test(html)) {
|
|
122
|
+
return html.replace(/<\/body>/i, () => `${pixel}</body>`);
|
|
123
|
+
}
|
|
124
|
+
return `${html}${pixel}`;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Returns the SHA-256 hex digest of a snapshot's canonical JSON, used to detect a change to the
|
|
128
|
+
* protected elements.
|
|
129
|
+
*/
|
|
130
|
+
export function ComputeProtectedElementsHash(snapshot) {
|
|
131
|
+
const canonical = JSON.stringify({
|
|
132
|
+
From: snapshot.From,
|
|
133
|
+
To: snapshot.To,
|
|
134
|
+
ListUnsubscribe: snapshot.ListUnsubscribe ?? null,
|
|
135
|
+
ListUnsubscribePost: snapshot.ListUnsubscribePost ?? null,
|
|
136
|
+
FooterHTML: snapshot.FooterHTML ?? null,
|
|
137
|
+
FooterText: snapshot.FooterText ?? null,
|
|
138
|
+
LogID: snapshot.LogID,
|
|
139
|
+
});
|
|
140
|
+
return createHash('sha256').update(canonical, 'utf8').digest('hex');
|
|
141
|
+
}
|
|
142
|
+
/** How long senders, sender ancestry, sender template context and preferences are cached, in milliseconds. */
|
|
143
|
+
const CACHE_TTL_MS = 60_000;
|
|
144
|
+
/**
|
|
145
|
+
* The V2 send pipeline behind `CommunicationEngine.Send()`, `EvaluateEligibility()` and
|
|
146
|
+
* `ResolveEndpoints()`: resolves endpoints, runs the compliance gate, writes the log, adds the
|
|
147
|
+
* protected compliance elements and tracking, and dispatches inline or through the work queue. Use
|
|
148
|
+
* it through `CommunicationEngine.Instance`; the engine owns the configured instance.
|
|
149
|
+
*/
|
|
150
|
+
export class V2SendService {
|
|
151
|
+
constructor() {
|
|
152
|
+
this.config = {};
|
|
153
|
+
this.senderCache = new Map();
|
|
154
|
+
this.senderAncestryCache = new Map();
|
|
155
|
+
this.senderTemplateCtxCache = new Map();
|
|
156
|
+
this.preferenceCache = new Map();
|
|
157
|
+
}
|
|
158
|
+
/** Merges settings into the current configuration and clears the sender and preference caches. */
|
|
159
|
+
Configure(config) {
|
|
160
|
+
this.config = { ...this.config, ...config };
|
|
161
|
+
this.ClearCache();
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Drops the 60-second caches of senders, sender ancestry, sender template context and
|
|
165
|
+
* preferences. Call it after changing those rows when the change must apply at once.
|
|
166
|
+
*/
|
|
167
|
+
ClearCache() {
|
|
168
|
+
this.senderCache.clear();
|
|
169
|
+
this.senderAncestryCache.clear();
|
|
170
|
+
this.senderTemplateCtxCache.clear();
|
|
171
|
+
this.preferenceCache.clear();
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Resolves endpoints for principal records by calling each entity's principal driver. Returns a
|
|
175
|
+
* map keyed by `<EntityID lower-cased>:<RecordID>`.
|
|
176
|
+
*/
|
|
177
|
+
async ResolveEndpoints(records, channelID, contextUser) {
|
|
178
|
+
const out = new Map();
|
|
179
|
+
if (records.length === 0)
|
|
180
|
+
return out;
|
|
181
|
+
const byEntity = new Map();
|
|
182
|
+
for (const ref of records) {
|
|
183
|
+
const key = ref.EntityID.toLowerCase();
|
|
184
|
+
const list = byEntity.get(key) ?? [];
|
|
185
|
+
list.push(ref);
|
|
186
|
+
byEntity.set(key, list);
|
|
187
|
+
}
|
|
188
|
+
for (const group of byEntity.values()) {
|
|
189
|
+
const driver = this.getPrincipalDriver(group[0].EntityID);
|
|
190
|
+
if (!driver)
|
|
191
|
+
continue;
|
|
192
|
+
const resolved = await driver.ResolveEndpoints(group, channelID, contextUser);
|
|
193
|
+
for (const [k, v] of resolved.entries()) {
|
|
194
|
+
out.set(k, v);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return out;
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Runs the compliance gate for each recipient without sending or writing a log. Endpoint rows may
|
|
201
|
+
* be created as a side effect of endpoint resolution.
|
|
202
|
+
*/
|
|
203
|
+
async EvaluateEligibility(params, contextUser) {
|
|
204
|
+
const sender = await this.resolveSender(params.Envelope.SenderID, contextUser);
|
|
205
|
+
if (!sender) {
|
|
206
|
+
return {
|
|
207
|
+
Sendable: [],
|
|
208
|
+
Blocked: params.Recipients.map((r) => ({
|
|
209
|
+
Principal: r.Principal,
|
|
210
|
+
Reason: 'SenderNotFound',
|
|
211
|
+
Detail: 'No active sender found for envelope',
|
|
212
|
+
})),
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
const senderChain = await this.loadSenderAncestry(sender, contextUser);
|
|
216
|
+
const senderTemplateContext = await this.resolveSenderTemplateContext(senderChain, contextUser);
|
|
217
|
+
const preference = params.Envelope.PreferenceID
|
|
218
|
+
? await this.loadPreference(params.Envelope.PreferenceID, contextUser)
|
|
219
|
+
: undefined;
|
|
220
|
+
const principalRefs = params.Recipients.map((r) => r.Principal).filter((p) => Boolean(p));
|
|
221
|
+
const resolvedMap = await this.ResolveEndpoints(principalRefs, params.Envelope.ChannelID, contextUser);
|
|
222
|
+
const attrMap = await this.resolveAllAttributes(principalRefs, contextUser);
|
|
223
|
+
const jurMap = await this.resolveAllJurisdictions(principalRefs, contextUser);
|
|
224
|
+
const endpointIds = this.collectEndpointIds(resolvedMap, params.Recipients);
|
|
225
|
+
const endpointIdSet = new UUIDSet(endpointIds);
|
|
226
|
+
const adHocEndpointMap = await this.batchLoadAdHocEndpoints(params.Recipients, params.Envelope.ChannelID, contextUser);
|
|
227
|
+
for (const ep of adHocEndpointMap.values()) {
|
|
228
|
+
if (!endpointIdSet.Has(ep.ID)) {
|
|
229
|
+
endpointIdSet.Add(ep.ID);
|
|
230
|
+
endpointIds.push(ep.ID);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
const suppressions = await this.loadSuppressions(endpointIds, principalRefs, contextUser);
|
|
234
|
+
const prefMap = preference
|
|
235
|
+
? await this.loadPrincipalPreferences(principalRefs, preference.ID, senderChain, contextUser)
|
|
236
|
+
: new Map();
|
|
237
|
+
const gate = new ComplianceGate(new JurisdictionResolver());
|
|
238
|
+
const sendable = [];
|
|
239
|
+
const blocked = [];
|
|
240
|
+
const now = new Date();
|
|
241
|
+
for (const rec of params.Recipients) {
|
|
242
|
+
const endpoint = await this.pickEndpointForRecipient(rec, params.Envelope.ChannelID, resolvedMap, contextUser, adHocEndpointMap);
|
|
243
|
+
if (!endpoint) {
|
|
244
|
+
blocked.push({
|
|
245
|
+
Principal: rec.Principal,
|
|
246
|
+
Reason: 'NoEndpoint',
|
|
247
|
+
Detail: 'No communication endpoint resolved for recipient',
|
|
248
|
+
});
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
const key = rec.Principal ? PrincipalRecordKey(rec.Principal) : undefined;
|
|
252
|
+
const attrs = key ? attrMap.get(key) : undefined;
|
|
253
|
+
const jur = key ? jurMap.get(key) : null;
|
|
254
|
+
const pp = key ? prefMap.get(key) : undefined;
|
|
255
|
+
const endpointEntity = endpoint.EndpointEntity ??
|
|
256
|
+
adHocEndpointMap.get(endpoint.CommunicationEndpointID.toLowerCase()) ??
|
|
257
|
+
(await this.loadEndpointEntity(endpoint.CommunicationEndpointID, contextUser));
|
|
258
|
+
if (!endpointEntity) {
|
|
259
|
+
blocked.push({ Principal: rec.Principal, Endpoint: endpoint, Reason: 'EndpointNotFound' });
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
const gateResult = gate.Evaluate({
|
|
263
|
+
Sender: sender,
|
|
264
|
+
SenderAncestors: senderChain.slice(1).map((s) => s.ID),
|
|
265
|
+
Principal: rec.Principal,
|
|
266
|
+
Endpoint: endpointEntity,
|
|
267
|
+
Preference: preference,
|
|
268
|
+
MessageClass: params.Envelope.MessageClass,
|
|
269
|
+
ChannelID: params.Envelope.ChannelID,
|
|
270
|
+
PrincipalPreference: pp,
|
|
271
|
+
PrincipalAttributes: attrs,
|
|
272
|
+
Now: now,
|
|
273
|
+
}, {
|
|
274
|
+
Suppressions: suppressions,
|
|
275
|
+
RecipientJurisdiction: jur,
|
|
276
|
+
SenderJurisdiction: sender.JurisdictionID,
|
|
277
|
+
InstanceEnforcementMode: this.config.InstanceEnforcementMode,
|
|
278
|
+
});
|
|
279
|
+
if (gateResult.Decision === 'Blocked') {
|
|
280
|
+
blocked.push({
|
|
281
|
+
Principal: rec.Principal,
|
|
282
|
+
Endpoint: endpoint,
|
|
283
|
+
Reason: gateResult.Reason ?? 'Blocked',
|
|
284
|
+
Detail: gateResult.Detail,
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
else {
|
|
288
|
+
sendable.push({
|
|
289
|
+
Principal: rec.Principal,
|
|
290
|
+
Endpoint: endpoint,
|
|
291
|
+
Decision: gateResult.Decision,
|
|
292
|
+
DeferUntil: gateResult.DeferUntil,
|
|
293
|
+
Obligations: gateResult.Obligations,
|
|
294
|
+
AuditSnapshot: gateResult.AuditSnapshot,
|
|
295
|
+
SenderTemplateContext: senderTemplateContext,
|
|
296
|
+
PrincipalAttributes: attrs,
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
return { Sendable: sendable, Blocked: blocked };
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Sends to the recipients. Checks the sender, the caller's sender permission, the provider and
|
|
304
|
+
* (when the provider requires it) the verified sending domain; then either publishes
|
|
305
|
+
* `comms.dispatch` chunks or evaluates and dispatches inline.
|
|
306
|
+
*
|
|
307
|
+
* @param getProvider - Returns the provider instance for a provider name.
|
|
308
|
+
*/
|
|
309
|
+
async Send(params, contextUser, getProvider) {
|
|
310
|
+
let result;
|
|
311
|
+
let thrown;
|
|
312
|
+
try {
|
|
313
|
+
result = await this.sendUnrecorded(params, contextUser, getProvider);
|
|
314
|
+
return result;
|
|
315
|
+
}
|
|
316
|
+
catch (err) {
|
|
317
|
+
thrown = err;
|
|
318
|
+
throw err;
|
|
319
|
+
}
|
|
320
|
+
finally {
|
|
321
|
+
// Every exit of a positioned chunk counts toward its run: early pre-send refusals and thrown
|
|
322
|
+
// errors included, or one refused chunk would hold the run open forever. Recorded here and
|
|
323
|
+
// only here; a redelivered chunk updates its existing row instead of adding one.
|
|
324
|
+
if (params.CommunicationRunID && params.RunChunk) {
|
|
325
|
+
await this.RecordRunChunkDone(params.CommunicationRunID, params.RunChunk, DescribeChunkOutcome(params.Recipients.length, result, thrown), CommunicationEngineBase.Instance.ContextUser ?? contextUser);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
async sendUnrecorded(params, contextUser, getProvider) {
|
|
330
|
+
let sender;
|
|
331
|
+
try {
|
|
332
|
+
sender = await this.resolveSender(params.Envelope.SenderID, contextUser);
|
|
333
|
+
}
|
|
334
|
+
catch (err) {
|
|
335
|
+
return {
|
|
336
|
+
Success: false,
|
|
337
|
+
IsAsyncRun: false,
|
|
338
|
+
TotalCount: params.Recipients.length,
|
|
339
|
+
QueuedCount: 0,
|
|
340
|
+
BlockedCount: params.Recipients.length,
|
|
341
|
+
DeferredCount: 0,
|
|
342
|
+
ErrorMessage: err instanceof Error ? err.message : String(err),
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
if (!sender) {
|
|
346
|
+
return {
|
|
347
|
+
Success: false,
|
|
348
|
+
IsAsyncRun: false,
|
|
349
|
+
TotalCount: params.Recipients.length,
|
|
350
|
+
QueuedCount: 0,
|
|
351
|
+
BlockedCount: params.Recipients.length,
|
|
352
|
+
DeferredCount: 0,
|
|
353
|
+
ErrorMessage: 'Sender not found',
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
let senderPermCheck;
|
|
357
|
+
try {
|
|
358
|
+
senderPermCheck = await this.checkSenderPermission(sender, contextUser);
|
|
359
|
+
}
|
|
360
|
+
catch (err) {
|
|
361
|
+
return {
|
|
362
|
+
Success: false,
|
|
363
|
+
IsAsyncRun: false,
|
|
364
|
+
TotalCount: params.Recipients.length,
|
|
365
|
+
QueuedCount: 0,
|
|
366
|
+
BlockedCount: params.Recipients.length,
|
|
367
|
+
DeferredCount: 0,
|
|
368
|
+
ErrorMessage: err instanceof Error ? err.message : String(err),
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
if (!senderPermCheck.Allowed) {
|
|
372
|
+
return {
|
|
373
|
+
Success: false,
|
|
374
|
+
IsAsyncRun: false,
|
|
375
|
+
TotalCount: params.Recipients.length,
|
|
376
|
+
QueuedCount: 0,
|
|
377
|
+
BlockedCount: params.Recipients.length,
|
|
378
|
+
DeferredCount: 0,
|
|
379
|
+
ErrorMessage: senderPermCheck.ErrorMessage,
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
if (params.Envelope.MessageClass === 'Transactional') {
|
|
383
|
+
const authCheck = this.checkTransactionalAuthorization(contextUser);
|
|
384
|
+
if (!authCheck.Allowed) {
|
|
385
|
+
return {
|
|
386
|
+
Success: false,
|
|
387
|
+
IsAsyncRun: false,
|
|
388
|
+
TotalCount: params.Recipients.length,
|
|
389
|
+
QueuedCount: 0,
|
|
390
|
+
BlockedCount: params.Recipients.length,
|
|
391
|
+
DeferredCount: 0,
|
|
392
|
+
ErrorMessage: authCheck.ErrorMessage,
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
const providerPick = this.selectProvider(params.Envelope, sender);
|
|
397
|
+
if (!providerPick.Provider) {
|
|
398
|
+
return {
|
|
399
|
+
Success: false,
|
|
400
|
+
IsAsyncRun: false,
|
|
401
|
+
TotalCount: params.Recipients.length,
|
|
402
|
+
QueuedCount: 0,
|
|
403
|
+
BlockedCount: params.Recipients.length,
|
|
404
|
+
DeferredCount: 0,
|
|
405
|
+
ErrorMessage: providerPick.ErrorMessage,
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
const providerEntity = providerPick.Provider;
|
|
409
|
+
if (providerEntity.RequireVerifiedDomain) {
|
|
410
|
+
const verified = await this.verifySendingDomain(providerEntity.ID, sender.SendingDomain, sender.CredentialID, contextUser);
|
|
411
|
+
if (!verified) {
|
|
412
|
+
return {
|
|
413
|
+
Success: false,
|
|
414
|
+
IsAsyncRun: false,
|
|
415
|
+
TotalCount: params.Recipients.length,
|
|
416
|
+
QueuedCount: 0,
|
|
417
|
+
BlockedCount: params.Recipients.length,
|
|
418
|
+
DeferredCount: 0,
|
|
419
|
+
ErrorMessage: `Verified sending domain required for '${sender.SendingDomain ?? 'unknown'}'`,
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
let run;
|
|
424
|
+
if (params.CommunicationRunID) {
|
|
425
|
+
const rv = this.getRunView();
|
|
426
|
+
const existingRun = await rv.RunView({
|
|
427
|
+
EntityName: 'MJ: Communication Runs',
|
|
428
|
+
ExtraFilter: `ID='${EscapeSQLString(params.CommunicationRunID)}'`,
|
|
429
|
+
MaxRows: 1,
|
|
430
|
+
ResultType: 'entity_object',
|
|
431
|
+
}, contextUser);
|
|
432
|
+
if (!existingRun.Success) {
|
|
433
|
+
return {
|
|
434
|
+
Success: false,
|
|
435
|
+
IsAsyncRun: false,
|
|
436
|
+
TotalCount: params.Recipients.length,
|
|
437
|
+
QueuedCount: 0,
|
|
438
|
+
BlockedCount: 0,
|
|
439
|
+
DeferredCount: 0,
|
|
440
|
+
ErrorMessage: `Failed loading communication run '${params.CommunicationRunID}': ${existingRun.ErrorMessage ?? 'RunView failed'}`,
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
if (existingRun.Results.length === 0) {
|
|
444
|
+
return {
|
|
445
|
+
Success: false,
|
|
446
|
+
IsAsyncRun: false,
|
|
447
|
+
TotalCount: params.Recipients.length,
|
|
448
|
+
QueuedCount: 0,
|
|
449
|
+
BlockedCount: 0,
|
|
450
|
+
DeferredCount: 0,
|
|
451
|
+
ErrorMessage: `Communication run '${params.CommunicationRunID}' was not found`,
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
run = existingRun.Results[0];
|
|
455
|
+
}
|
|
456
|
+
else {
|
|
457
|
+
run = await CommunicationEngineBase.Instance.StartRun();
|
|
458
|
+
}
|
|
459
|
+
if (!run) {
|
|
460
|
+
return {
|
|
461
|
+
Success: false,
|
|
462
|
+
IsAsyncRun: false,
|
|
463
|
+
TotalCount: params.Recipients.length,
|
|
464
|
+
QueuedCount: 0,
|
|
465
|
+
BlockedCount: 0,
|
|
466
|
+
DeferredCount: 0,
|
|
467
|
+
ErrorMessage: 'Failed to create communication run',
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
const asyncThreshold = this.config.AsyncThreshold ?? DEFAULT_ASYNC_THRESHOLD;
|
|
471
|
+
const chunkSize = this.config.ChunkSize ?? DEFAULT_CHUNK_SIZE;
|
|
472
|
+
if (!params.CommunicationRunID && this.config.EnqueueWork && params.Recipients.length > asyncThreshold) {
|
|
473
|
+
const chunkCount = Math.ceil(params.Recipients.length / chunkSize);
|
|
474
|
+
const prepared = await this.prepareChunkedRun(run, chunkCount, params.Envelope.DeliveryGuarantee);
|
|
475
|
+
if (!prepared.Success) {
|
|
476
|
+
return {
|
|
477
|
+
Success: false,
|
|
478
|
+
CommunicationRunID: run.ID,
|
|
479
|
+
IsAsyncRun: false,
|
|
480
|
+
TotalCount: params.Recipients.length,
|
|
481
|
+
QueuedCount: 0,
|
|
482
|
+
BlockedCount: 0,
|
|
483
|
+
DeferredCount: 0,
|
|
484
|
+
ErrorMessage: prepared.ErrorMessage,
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
for (let i = 0; i < params.Recipients.length; i += chunkSize) {
|
|
488
|
+
const chunk = params.Recipients.slice(i, i + chunkSize);
|
|
489
|
+
// ActingUserID makes the worker run the chunk as the caller, not as its own system user,
|
|
490
|
+
// so principal lookups and permission checks keep the caller's row-level security.
|
|
491
|
+
await this.config.EnqueueWork('comms.dispatch', {
|
|
492
|
+
CommunicationRunID: run.ID,
|
|
493
|
+
Envelope: params.Envelope,
|
|
494
|
+
Payload: params.Payload,
|
|
495
|
+
Recipients: chunk,
|
|
496
|
+
ActingUserID: contextUser.ID,
|
|
497
|
+
RunChunk: { Index: i / chunkSize, Count: chunkCount },
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
return {
|
|
501
|
+
Success: true,
|
|
502
|
+
CommunicationRunID: run.ID,
|
|
503
|
+
IsAsyncRun: true,
|
|
504
|
+
TotalCount: params.Recipients.length,
|
|
505
|
+
QueuedCount: params.Recipients.length,
|
|
506
|
+
BlockedCount: 0,
|
|
507
|
+
DeferredCount: 0,
|
|
508
|
+
};
|
|
509
|
+
}
|
|
510
|
+
return this.executeInlineSend(params, sender, providerEntity, run, contextUser, getProvider);
|
|
511
|
+
}
|
|
512
|
+
/**
|
|
513
|
+
* Picks the provider for a send: the envelope's, else the sender's. With neither named, only an
|
|
514
|
+
* unambiguous choice is accepted: exactly one active, sending provider that supports the channel.
|
|
515
|
+
* Picking one of several would route mail through an account nobody chose.
|
|
516
|
+
*/
|
|
517
|
+
selectProvider(envelope, sender) {
|
|
518
|
+
const providers = CommunicationEngineBase.Instance.Providers;
|
|
519
|
+
const providerId = envelope.ProviderID ?? sender.CommunicationProviderID;
|
|
520
|
+
if (providerId) {
|
|
521
|
+
const named = providers.find((p) => UUIDsEqual(p.ID, providerId));
|
|
522
|
+
return named ? { Provider: named } : { ErrorMessage: 'Communication provider not found' };
|
|
523
|
+
}
|
|
524
|
+
const channelKey = NormalizeUUID(envelope.ChannelID);
|
|
525
|
+
const candidates = providers.filter((p) => p.Status === 'Active' &&
|
|
526
|
+
p.SupportsSending &&
|
|
527
|
+
p.MessageTypes.some((m) => NormalizeUUID(m.CommunicationBaseMessageTypeID) === channelKey));
|
|
528
|
+
if (candidates.length === 1) {
|
|
529
|
+
return { Provider: candidates[0] };
|
|
530
|
+
}
|
|
531
|
+
return {
|
|
532
|
+
ErrorMessage: candidates.length === 0
|
|
533
|
+
? 'Communication provider not found: no active sending provider supports this channel'
|
|
534
|
+
: `Ambiguous communication provider: ${candidates.length} active providers support this channel; set Envelope.ProviderID or the sender's CommunicationProviderID`,
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
async executeInlineSend(params, sender, providerEntity, run, contextUser, getProvider) {
|
|
538
|
+
const eligibility = await this.EvaluateEligibility({ Envelope: params.Envelope, Recipients: params.Recipients }, contextUser);
|
|
539
|
+
const outcomes = eligibility.Blocked.map((b) => ({
|
|
540
|
+
Principal: b.Principal,
|
|
541
|
+
Endpoint: b.Endpoint,
|
|
542
|
+
Status: 'Blocked',
|
|
543
|
+
Reason: b.Reason,
|
|
544
|
+
Detail: b.Detail,
|
|
545
|
+
}));
|
|
546
|
+
let queuedCount = 0;
|
|
547
|
+
let deferredCount = 0;
|
|
548
|
+
let dryRunCount = 0;
|
|
549
|
+
const provider = getProvider(providerEntity.Name);
|
|
550
|
+
const senderCredentials = await this.resolveSenderCredentials(sender, CommunicationEngineBase.Instance.ContextUser ?? contextUser);
|
|
551
|
+
const pmt = providerEntity.MessageTypes.find((m) => UUIDsEqual(m.CommunicationBaseMessageTypeID, params.Envelope.ChannelID)) ?? providerEntity.MessageTypes[0];
|
|
552
|
+
const scheduledAt = params.Envelope.ScheduledAt;
|
|
553
|
+
const scheduledInFuture = scheduledAt != null && scheduledAt.getTime() > Date.now();
|
|
554
|
+
// Only this chunk's endpoints: a run can hold every log of a 100k-recipient send.
|
|
555
|
+
const existingLogsByEndpoint = params.CommunicationRunID
|
|
556
|
+
? await this.batchLoadRunLogs(run.ID, eligibility.Sendable.map((s) => s.Endpoint.CommunicationEndpointID), CommunicationEngineBase.Instance.ContextUser ?? contextUser)
|
|
557
|
+
: undefined;
|
|
558
|
+
const deferredSaves = [];
|
|
559
|
+
for (let i = 0; i < eligibility.Sendable.length; i++) {
|
|
560
|
+
const target = eligibility.Sendable[i];
|
|
561
|
+
const rawRecipient = params.Recipients.find((r) => {
|
|
562
|
+
if (r.Principal && target.Principal) {
|
|
563
|
+
return PrincipalRecordKey(r.Principal) === PrincipalRecordKey(target.Principal);
|
|
564
|
+
}
|
|
565
|
+
if (!r.Principal && !target.Principal && r.Endpoint?.Address) {
|
|
566
|
+
const norm = NormalizeEndpointAddress(r.Endpoint.Address, params.Envelope.ChannelID);
|
|
567
|
+
return norm?.NormalizedValue === target.Endpoint.NormalizedValue;
|
|
568
|
+
}
|
|
569
|
+
return false;
|
|
570
|
+
});
|
|
571
|
+
if (target.Decision === 'Deferred' || scheduledInFuture) {
|
|
572
|
+
const deferUntil = target.DeferUntil && scheduledAt && scheduledInFuture
|
|
573
|
+
? (target.DeferUntil.getTime() > scheduledAt.getTime() ? target.DeferUntil : scheduledAt)
|
|
574
|
+
: (target.DeferUntil ?? (scheduledInFuture ? scheduledAt : undefined));
|
|
575
|
+
target.DeferUntil = deferUntil;
|
|
576
|
+
const deferredPayload = {
|
|
577
|
+
...params.Payload,
|
|
578
|
+
...rawRecipient?.PayloadOverride,
|
|
579
|
+
Headers: {
|
|
580
|
+
...(params.Payload?.Headers ?? {}),
|
|
581
|
+
...(rawRecipient?.PayloadOverride?.Headers ?? {}),
|
|
582
|
+
},
|
|
583
|
+
};
|
|
584
|
+
deferredSaves.push({ target, deferUntil, deferredPayload });
|
|
585
|
+
continue;
|
|
586
|
+
}
|
|
587
|
+
const outcome = await this.dispatchSingleRecipient(params, sender, providerEntity.ID, pmt, run.ID, target, rawRecipient?.PayloadOverride, provider, contextUser, senderCredentials, existingLogsByEndpoint);
|
|
588
|
+
if (outcome.Status === 'Sent' || outcome.Status === 'Queued') {
|
|
589
|
+
queuedCount++;
|
|
590
|
+
}
|
|
591
|
+
else if (outcome.Status === 'DryRun') {
|
|
592
|
+
dryRunCount++;
|
|
593
|
+
}
|
|
594
|
+
outcomes.push(outcome);
|
|
595
|
+
}
|
|
596
|
+
const LOG_BATCH_SIZE = 20;
|
|
597
|
+
for (let i = 0; i < deferredSaves.length; i += LOG_BATCH_SIZE) {
|
|
598
|
+
const batch = deferredSaves.slice(i, i + LOG_BATCH_SIZE);
|
|
599
|
+
const claims = await Promise.all(batch.map((item) => this.claimOrCreateV2Log(params, sender, providerEntity.ID, pmt?.ID, run.ID, item.target, 'Pending', contextUser, item.deferredPayload, existingLogsByEndpoint)));
|
|
600
|
+
for (let j = 0; j < batch.length; j++) {
|
|
601
|
+
const claim = claims[j];
|
|
602
|
+
if (!claim.Log) {
|
|
603
|
+
outcomes.push({
|
|
604
|
+
Principal: batch[j].target.Principal,
|
|
605
|
+
Endpoint: batch[j].target.Endpoint,
|
|
606
|
+
Status: 'Failed',
|
|
607
|
+
Reason: claim.FailureReason ?? 'LogCreationFailed',
|
|
608
|
+
Detail: claim.FailureDetail,
|
|
609
|
+
});
|
|
610
|
+
continue;
|
|
611
|
+
}
|
|
612
|
+
deferredCount++;
|
|
613
|
+
outcomes.push({
|
|
614
|
+
Principal: batch[j].target.Principal,
|
|
615
|
+
Endpoint: batch[j].target.Endpoint,
|
|
616
|
+
CommunicationLogID: claim.Log.ID,
|
|
617
|
+
Status: 'Deferred',
|
|
618
|
+
DeferUntil: batch[j].deferUntil,
|
|
619
|
+
});
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
// A run passed in belongs to the caller (a comms.dispatch chunk, a templated batch); ending it
|
|
623
|
+
// here would mark it finished while other chunks are still queued or sending. A positioned
|
|
624
|
+
// chunk is recorded by Send()'s finally, and the last one to finish ends the run.
|
|
625
|
+
if (!params.CommunicationRunID && !(await CommunicationEngineBase.Instance.EndRun(run))) {
|
|
626
|
+
LogError(`V2SendService: failed to finalize CommunicationRun ${run.ID}`);
|
|
627
|
+
}
|
|
628
|
+
return {
|
|
629
|
+
Success: true,
|
|
630
|
+
CommunicationRunID: run.ID,
|
|
631
|
+
IsAsyncRun: false,
|
|
632
|
+
TotalCount: params.Recipients.length,
|
|
633
|
+
QueuedCount: queuedCount,
|
|
634
|
+
BlockedCount: eligibility.Blocked.length,
|
|
635
|
+
DeferredCount: deferredCount,
|
|
636
|
+
DryRunCount: dryRunCount,
|
|
637
|
+
Outcomes: outcomes,
|
|
638
|
+
};
|
|
639
|
+
}
|
|
640
|
+
async dispatchSingleRecipient(params, sender, providerID, pmt, runID, target, override, provider, contextUser, senderCredentials, existingLogsByEndpoint, preclaimedLog) {
|
|
641
|
+
const claim = preclaimedLog
|
|
642
|
+
? { Log: preclaimedLog }
|
|
643
|
+
: await this.claimOrCreateV2Log(params, sender, providerID, pmt?.ID, runID, target, 'In-Progress', contextUser, undefined, existingLogsByEndpoint);
|
|
644
|
+
if (claim.AlreadySent) {
|
|
645
|
+
return {
|
|
646
|
+
Principal: target.Principal,
|
|
647
|
+
Endpoint: target.Endpoint,
|
|
648
|
+
CommunicationLogID: claim.Log?.ID,
|
|
649
|
+
Status: 'Sent',
|
|
650
|
+
};
|
|
651
|
+
}
|
|
652
|
+
if (!claim.Log) {
|
|
653
|
+
return {
|
|
654
|
+
Principal: target.Principal,
|
|
655
|
+
Endpoint: target.Endpoint,
|
|
656
|
+
Status: 'Failed',
|
|
657
|
+
Reason: claim.FailureReason ?? 'LogCreationFailed',
|
|
658
|
+
Detail: claim.FailureDetail,
|
|
659
|
+
};
|
|
660
|
+
}
|
|
661
|
+
const log = claim.Log;
|
|
662
|
+
const payload = {
|
|
663
|
+
...params.Payload,
|
|
664
|
+
...override,
|
|
665
|
+
Headers: {
|
|
666
|
+
...(params.Payload?.Headers ?? {}),
|
|
667
|
+
...(override?.Headers ?? {}),
|
|
668
|
+
},
|
|
669
|
+
};
|
|
670
|
+
const trackingToken = log.TrackingToken ?? randomUUID();
|
|
671
|
+
const unsubscribeToken = log.UnsubscribeToken ?? randomUUID();
|
|
672
|
+
const baseUrl = this.config.BaseTrackingURL ?? '';
|
|
673
|
+
const hmacSecret = this.config.TrackingHMACSecret ?? process.env.MJ_COMMS_HMAC_SECRET ?? '';
|
|
674
|
+
const obligations = this.enrichObligations(target.Obligations, baseUrl, unsubscribeToken);
|
|
675
|
+
const snapshot = Object.freeze({
|
|
676
|
+
From: sender.FromEmail ?? sender.FromPhone ?? '',
|
|
677
|
+
To: target.Endpoint.NormalizedValue,
|
|
678
|
+
ListUnsubscribe: obligations.RequireOneClickHeader && obligations.UnsubscribeURL
|
|
679
|
+
? `<${obligations.UnsubscribeURL}>`
|
|
680
|
+
: undefined,
|
|
681
|
+
ListUnsubscribePost: obligations.RequireOneClickHeader
|
|
682
|
+
? 'List-Unsubscribe=One-Click'
|
|
683
|
+
: undefined,
|
|
684
|
+
FooterHTML: this.buildComplianceFooterHTML(obligations),
|
|
685
|
+
FooterText: this.buildComplianceFooterText(obligations),
|
|
686
|
+
LogID: log.ID,
|
|
687
|
+
});
|
|
688
|
+
const expectedHash = ComputeProtectedElementsHash(snapshot);
|
|
689
|
+
const driver = target.Principal ? this.getPrincipalDriver(target.Principal.EntityID) : undefined;
|
|
690
|
+
const hookState = this.createMessageContext(params.Envelope, target, payload);
|
|
691
|
+
try {
|
|
692
|
+
if (driver && target.Principal) {
|
|
693
|
+
await driver.PreProcess([hookState.Context], contextUser);
|
|
694
|
+
await driver.PostProcess([hookState.Context], contextUser);
|
|
695
|
+
}
|
|
696
|
+
// Assert protected compliance elements were not tampered with by hooks
|
|
697
|
+
if (ComputeProtectedElementsHash(snapshot) !== expectedHash) {
|
|
698
|
+
throw new Error('Protected compliance elements failed SHA-256 integrity assertion after PostProcess');
|
|
699
|
+
}
|
|
700
|
+
const finalPayload = this.finalizePayload(payload, hookState, snapshot, obligations, params.Envelope, trackingToken, hmacSecret, baseUrl);
|
|
701
|
+
const enforcementMode = sender.EnforcementMode ?? this.config.InstanceEnforcementMode ?? 'Enforce';
|
|
702
|
+
if (enforcementMode === 'Enforce') {
|
|
703
|
+
const obligationError = this.validateBodyObligations(finalPayload, obligations);
|
|
704
|
+
if (obligationError) {
|
|
705
|
+
log.Status = 'Failed';
|
|
706
|
+
log.ErrorMessage = obligationError;
|
|
707
|
+
if (!(await log.Save())) {
|
|
708
|
+
LogError(`V2SendService: failed to save failed CommunicationLog ${log.ID}: ${log.LatestResult?.CompleteMessage ?? 'unknown error'}`);
|
|
709
|
+
}
|
|
710
|
+
return {
|
|
711
|
+
Principal: target.Principal,
|
|
712
|
+
Endpoint: target.Endpoint,
|
|
713
|
+
CommunicationLogID: log.ID,
|
|
714
|
+
Status: 'Blocked',
|
|
715
|
+
Reason: 'ObligationValidationFailed',
|
|
716
|
+
Detail: obligationError,
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
this.assertProtectedElementsIntact(finalPayload, snapshot);
|
|
721
|
+
const msg = new Message();
|
|
722
|
+
msg.MessageType = pmt;
|
|
723
|
+
msg.From = snapshot.From;
|
|
724
|
+
msg.FromName = sender.FromName ?? sender.Name;
|
|
725
|
+
msg.To = snapshot.To;
|
|
726
|
+
msg.Subject = finalPayload.Subject;
|
|
727
|
+
msg.Body = finalPayload.Body;
|
|
728
|
+
msg.HTMLBody = finalPayload.HTMLBody;
|
|
729
|
+
msg.Headers = finalPayload.Headers;
|
|
730
|
+
msg.DryRun = params.Envelope.DryRun;
|
|
731
|
+
msg.CorrelationLogID = log.ID;
|
|
732
|
+
msg.DisableProviderTracking = true;
|
|
733
|
+
const processed = new ProcessedMessageServer(msg);
|
|
734
|
+
processed.ProcessedSubject = finalPayload.Subject ?? '';
|
|
735
|
+
processed.ProcessedBody = finalPayload.Body ?? '';
|
|
736
|
+
processed.ProcessedHTMLBody = finalPayload.HTMLBody ?? '';
|
|
737
|
+
const sendRes = await provider.SendSingleMessage(processed, senderCredentials);
|
|
738
|
+
const isDryRun = Boolean(params.Envelope.DryRun) && sendRes.Success;
|
|
739
|
+
log.Status = sendRes.Success ? 'Complete' : 'Failed';
|
|
740
|
+
log.ProviderMessageID = sendRes.ProviderMessageID ?? log.ProviderMessageID;
|
|
741
|
+
log.ErrorMessage = sendRes.Error || null;
|
|
742
|
+
log.IsDryRun = isDryRun;
|
|
743
|
+
const saveErr = await this.saveLogAfterSend(log);
|
|
744
|
+
if (saveErr) {
|
|
745
|
+
// The provider has the message; the log does not say so. The log stays In-Progress, and a
|
|
746
|
+
// retry reports it OutcomeUnknown instead of sending again (at most once).
|
|
747
|
+
return {
|
|
748
|
+
Principal: target.Principal,
|
|
749
|
+
Endpoint: target.Endpoint,
|
|
750
|
+
CommunicationLogID: log.ID,
|
|
751
|
+
Status: 'Failed',
|
|
752
|
+
Reason: 'PostSendLogSaveFailed',
|
|
753
|
+
Detail: saveErr,
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
return {
|
|
757
|
+
Principal: target.Principal,
|
|
758
|
+
Endpoint: target.Endpoint,
|
|
759
|
+
CommunicationLogID: log.ID,
|
|
760
|
+
Status: isDryRun ? 'DryRun' : sendRes.Success ? 'Sent' : 'Failed',
|
|
761
|
+
Detail: sendRes.Error || undefined,
|
|
762
|
+
};
|
|
763
|
+
}
|
|
764
|
+
catch (err) {
|
|
765
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
766
|
+
log.Status = 'Failed';
|
|
767
|
+
log.ErrorMessage = detail;
|
|
768
|
+
if (!(await log.Save())) {
|
|
769
|
+
LogError(`V2SendService: failed to save Failed CommunicationLog ${log.ID}: ${log.LatestResult?.CompleteMessage ?? 'unknown error'}`);
|
|
770
|
+
}
|
|
771
|
+
return {
|
|
772
|
+
Principal: target.Principal,
|
|
773
|
+
Endpoint: target.Endpoint,
|
|
774
|
+
CommunicationLogID: log.ID,
|
|
775
|
+
Status: 'Failed',
|
|
776
|
+
Reason: 'DispatchException',
|
|
777
|
+
Detail: detail,
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
/**
|
|
782
|
+
* Saves a log after the provider call, retrying a bounded number of times: the message has
|
|
783
|
+
* already left, so losing this write is what turns a retry into a duplicate. Returns the last
|
|
784
|
+
* error, or `undefined` on success.
|
|
785
|
+
*/
|
|
786
|
+
async saveLogAfterSend(log) {
|
|
787
|
+
let lastError = 'unknown error';
|
|
788
|
+
for (let attempt = 1; attempt <= MAX_POST_SEND_SAVE_ATTEMPTS; attempt++) {
|
|
789
|
+
if (await log.Save()) {
|
|
790
|
+
return undefined;
|
|
791
|
+
}
|
|
792
|
+
lastError = log.LatestResult?.CompleteMessage ?? 'unknown error';
|
|
793
|
+
LogError(`V2SendService: failed to update CommunicationLog ${log.ID} after send (attempt ${attempt}/${MAX_POST_SEND_SAVE_ATTEMPTS}): ${lastError}`);
|
|
794
|
+
}
|
|
795
|
+
return lastError;
|
|
796
|
+
}
|
|
797
|
+
finalizePayload(payload, hookState, snapshot, obligations, envelope, trackingToken, hmacSecret, baseUrl) {
|
|
798
|
+
let html = `${hookState.HeaderHTML}${payload.HTMLBody ?? ''}${hookState.FooterHTML}`;
|
|
799
|
+
let text = `${hookState.HeaderText}${payload.Body ?? ''}${hookState.FooterText}`;
|
|
800
|
+
const hasHtml = html.trim().length > 0;
|
|
801
|
+
if (hasHtml && obligations.AllowClickTracking && envelope.TrackClicks !== false && hmacSecret) {
|
|
802
|
+
const excluded = [obligations.UnsubscribeURL, obligations.PreferenceCenterURL].filter((u) => Boolean(u));
|
|
803
|
+
html = RewriteLinksForTracking(html, trackingToken, hmacSecret, baseUrl, excluded);
|
|
804
|
+
}
|
|
805
|
+
if (hasHtml && snapshot.FooterHTML) {
|
|
806
|
+
html = `${html}${snapshot.FooterHTML}`;
|
|
807
|
+
}
|
|
808
|
+
if (snapshot.FooterText) {
|
|
809
|
+
text = `${text}${snapshot.FooterText}`;
|
|
810
|
+
}
|
|
811
|
+
if (hasHtml && obligations.AllowOpenPixel && envelope.TrackOpens !== false) {
|
|
812
|
+
html = InjectOpenPixel(html, trackingToken, baseUrl, hmacSecret);
|
|
813
|
+
}
|
|
814
|
+
const headers = {
|
|
815
|
+
...(payload.Headers ?? {}),
|
|
816
|
+
...hookState.CustomHeaders,
|
|
817
|
+
};
|
|
818
|
+
if (snapshot.ListUnsubscribe) {
|
|
819
|
+
headers['List-Unsubscribe'] = snapshot.ListUnsubscribe;
|
|
820
|
+
}
|
|
821
|
+
if (snapshot.ListUnsubscribePost) {
|
|
822
|
+
headers['List-Unsubscribe-Post'] = snapshot.ListUnsubscribePost;
|
|
823
|
+
}
|
|
824
|
+
return {
|
|
825
|
+
Subject: hookState.SubjectOverride ?? payload.Subject,
|
|
826
|
+
PreviewText: hookState.PreviewTextOverride ?? payload.PreviewText,
|
|
827
|
+
Body: text,
|
|
828
|
+
HTMLBody: hasHtml ? html : undefined,
|
|
829
|
+
Headers: headers,
|
|
830
|
+
};
|
|
831
|
+
}
|
|
832
|
+
createMessageContext(envelope, target, payload) {
|
|
833
|
+
const state = {
|
|
834
|
+
HeaderHTML: '',
|
|
835
|
+
FooterHTML: '',
|
|
836
|
+
HeaderText: '',
|
|
837
|
+
FooterText: '',
|
|
838
|
+
CustomHeaders: {},
|
|
839
|
+
SubjectOverride: undefined,
|
|
840
|
+
PreviewTextOverride: undefined,
|
|
841
|
+
Context: {},
|
|
842
|
+
};
|
|
843
|
+
const protectedHeaderNames = new Set([
|
|
844
|
+
'list-unsubscribe',
|
|
845
|
+
'list-unsubscribe-post',
|
|
846
|
+
'from',
|
|
847
|
+
'to',
|
|
848
|
+
]);
|
|
849
|
+
state.Context = {
|
|
850
|
+
Envelope: envelope,
|
|
851
|
+
Principal: target.Principal ?? { EntityID: '', RecordID: '' },
|
|
852
|
+
Endpoint: target.Endpoint,
|
|
853
|
+
Payload: payload,
|
|
854
|
+
AddContent(location, content) {
|
|
855
|
+
if (location === 'header') {
|
|
856
|
+
if (content.html)
|
|
857
|
+
state.HeaderHTML += content.html;
|
|
858
|
+
if (content.text)
|
|
859
|
+
state.HeaderText += content.text;
|
|
860
|
+
}
|
|
861
|
+
else {
|
|
862
|
+
if (content.html)
|
|
863
|
+
state.FooterHTML += content.html;
|
|
864
|
+
if (content.text)
|
|
865
|
+
state.FooterText += content.text;
|
|
866
|
+
}
|
|
867
|
+
},
|
|
868
|
+
SetHeader(name, value) {
|
|
869
|
+
if (!protectedHeaderNames.has(name.trim().toLowerCase())) {
|
|
870
|
+
state.CustomHeaders[name] = value;
|
|
871
|
+
}
|
|
872
|
+
},
|
|
873
|
+
RequestMutation(mutation) {
|
|
874
|
+
if (mutation.Subject !== undefined)
|
|
875
|
+
state.SubjectOverride = mutation.Subject;
|
|
876
|
+
if (mutation.PreviewText !== undefined)
|
|
877
|
+
state.PreviewTextOverride = mutation.PreviewText;
|
|
878
|
+
},
|
|
879
|
+
};
|
|
880
|
+
return state;
|
|
881
|
+
}
|
|
882
|
+
enrichObligations(obligations, baseUrl, unsubscribeToken) {
|
|
883
|
+
const unsubUrl = obligations.UnsubscribeURL ?? buildCommsRouteUrl(baseUrl, `/unsubscribe/${unsubscribeToken}`);
|
|
884
|
+
return {
|
|
885
|
+
...obligations,
|
|
886
|
+
UnsubscribeURL: unsubUrl,
|
|
887
|
+
};
|
|
888
|
+
}
|
|
889
|
+
buildComplianceFooterHTML(obligations) {
|
|
890
|
+
const parts = [];
|
|
891
|
+
if (obligations.RequireSenderPostalAddress && obligations.SenderPostalAddress) {
|
|
892
|
+
parts.push(`<span>${obligations.SenderPostalAddress}</span>`);
|
|
893
|
+
}
|
|
894
|
+
if (obligations.RequireFooterUnsubscribe && obligations.UnsubscribeURL) {
|
|
895
|
+
parts.push(`<a href="${obligations.UnsubscribeURL}">Unsubscribe</a>`);
|
|
896
|
+
}
|
|
897
|
+
if (parts.length === 0)
|
|
898
|
+
return undefined;
|
|
899
|
+
return `<div data-mj-compliance-footer="true">${parts.join(' | ')}</div>`;
|
|
900
|
+
}
|
|
901
|
+
buildComplianceFooterText(obligations) {
|
|
902
|
+
const parts = [];
|
|
903
|
+
if (obligations.RequireSenderPostalAddress && obligations.SenderPostalAddress) {
|
|
904
|
+
parts.push(obligations.SenderPostalAddress);
|
|
905
|
+
}
|
|
906
|
+
if (obligations.RequireFooterUnsubscribe && obligations.UnsubscribeURL) {
|
|
907
|
+
parts.push(`Unsubscribe: ${obligations.UnsubscribeURL}`);
|
|
908
|
+
}
|
|
909
|
+
if (parts.length === 0)
|
|
910
|
+
return undefined;
|
|
911
|
+
return `\n\n---\n${parts.join(' | ')}`;
|
|
912
|
+
}
|
|
913
|
+
getPrincipalDriver(entityID) {
|
|
914
|
+
const principal = CommunicationEngineBase.Instance.Principals.find((p) => p.Status === 'Active' && UUIDsEqual(p.EntityID, entityID));
|
|
915
|
+
const driverClass = principal?.DriverClass ?? 'DefaultCommunicationPrincipal';
|
|
916
|
+
return MJGlobal.Instance.ClassFactory.CreateInstance(BaseCommunicationPrincipal, driverClass);
|
|
917
|
+
}
|
|
918
|
+
async resolveSender(senderID, contextUser) {
|
|
919
|
+
const cacheKey = senderID ? senderID.toLowerCase() : '__default__';
|
|
920
|
+
const cached = this.senderCache.get(cacheKey);
|
|
921
|
+
if (cached && cached.expiresAt > Date.now()) {
|
|
922
|
+
return cached.value;
|
|
923
|
+
}
|
|
924
|
+
const rv = this.getRunView();
|
|
925
|
+
const filter = senderID
|
|
926
|
+
? `ID='${EscapeSQLString(senderID)}' AND Status='Active'`
|
|
927
|
+
: `IsDefault=1 AND Status='Active'`;
|
|
928
|
+
const res = await rv.RunView({
|
|
929
|
+
EntityName: 'MJ: Communication Senders',
|
|
930
|
+
ExtraFilter: filter,
|
|
931
|
+
ResultType: 'entity_object',
|
|
932
|
+
}, contextUser);
|
|
933
|
+
if (!res.Success) {
|
|
934
|
+
throw new Error(`Failed loading communication sender '${senderID ?? 'default'}': ${res.ErrorMessage ?? 'RunView failed'}`);
|
|
935
|
+
}
|
|
936
|
+
const found = res.Results.length > 0 ? res.Results[0] : undefined;
|
|
937
|
+
if (found) {
|
|
938
|
+
const expiresAt = Date.now() + CACHE_TTL_MS;
|
|
939
|
+
this.senderCache.set(cacheKey, { value: found, expiresAt });
|
|
940
|
+
this.senderCache.set(found.ID.toLowerCase(), { value: found, expiresAt });
|
|
941
|
+
}
|
|
942
|
+
return found;
|
|
943
|
+
}
|
|
944
|
+
async loadSenderAncestry(sender, contextUser) {
|
|
945
|
+
const cacheKey = sender.ID.toLowerCase();
|
|
946
|
+
const cached = this.senderAncestryCache.get(cacheKey);
|
|
947
|
+
if (cached && cached.expiresAt > Date.now()) {
|
|
948
|
+
return cached.value;
|
|
949
|
+
}
|
|
950
|
+
const chain = [sender];
|
|
951
|
+
const visited = new Set([sender.ID.toLowerCase()]);
|
|
952
|
+
let parentId = sender.ParentSenderID;
|
|
953
|
+
while (parentId && !visited.has(parentId.toLowerCase())) {
|
|
954
|
+
visited.add(parentId.toLowerCase());
|
|
955
|
+
const parent = await this.resolveSender(parentId, contextUser);
|
|
956
|
+
if (!parent)
|
|
957
|
+
break;
|
|
958
|
+
chain.push(parent);
|
|
959
|
+
parentId = parent.ParentSenderID;
|
|
960
|
+
}
|
|
961
|
+
this.senderAncestryCache.set(cacheKey, { value: chain, expiresAt: Date.now() + CACHE_TTL_MS });
|
|
962
|
+
return chain;
|
|
963
|
+
}
|
|
964
|
+
async resolveSenderTemplateContext(chain, contextUser) {
|
|
965
|
+
const cacheKey = chain[0].ID.toLowerCase();
|
|
966
|
+
const cached = this.senderTemplateCtxCache.get(cacheKey);
|
|
967
|
+
if (cached && cached.expiresAt > Date.now()) {
|
|
968
|
+
return cached.value;
|
|
969
|
+
}
|
|
970
|
+
const merged = {};
|
|
971
|
+
for (let i = chain.length - 1; i >= 0; i--) {
|
|
972
|
+
const s = chain[i];
|
|
973
|
+
if (s.TemplateContext) {
|
|
974
|
+
try {
|
|
975
|
+
Object.assign(merged, JSON.parse(s.TemplateContext));
|
|
976
|
+
}
|
|
977
|
+
catch {
|
|
978
|
+
// ignore malformed JSON
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
const senderType = CommunicationEngineBase.Instance.SenderTypes.find((st) => UUIDsEqual(st.ID, chain[0].CommunicationSenderTypeID));
|
|
983
|
+
if (senderType?.DriverClass) {
|
|
984
|
+
const driver = MJGlobal.Instance.ClassFactory.CreateInstance(BaseCommunicationSender, senderType.DriverClass);
|
|
985
|
+
if (driver) {
|
|
986
|
+
const extra = await driver.ResolveTemplateContext(chain[0], chain.slice(1), contextUser);
|
|
987
|
+
Object.assign(merged, extra);
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
this.senderTemplateCtxCache.set(cacheKey, { value: merged, expiresAt: Date.now() + CACHE_TTL_MS });
|
|
991
|
+
return merged;
|
|
992
|
+
}
|
|
993
|
+
async loadPreference(preferenceID, contextUser) {
|
|
994
|
+
const cacheKey = preferenceID.toLowerCase();
|
|
995
|
+
const cached = this.preferenceCache.get(cacheKey);
|
|
996
|
+
if (cached && cached.expiresAt > Date.now()) {
|
|
997
|
+
return cached.value;
|
|
998
|
+
}
|
|
999
|
+
const rv = this.getRunView();
|
|
1000
|
+
const res = await rv.RunView({
|
|
1001
|
+
EntityName: 'MJ: Communication Preferences',
|
|
1002
|
+
ExtraFilter: `ID='${EscapeSQLString(preferenceID)}'`,
|
|
1003
|
+
ResultType: 'entity_object',
|
|
1004
|
+
}, contextUser);
|
|
1005
|
+
if (!res.Success) {
|
|
1006
|
+
throw new Error(`Failed loading communication preference '${preferenceID}': ${res.ErrorMessage ?? 'RunView failed'}`);
|
|
1007
|
+
}
|
|
1008
|
+
if (res.Results.length === 0) {
|
|
1009
|
+
throw new Error(`Communication preference '${preferenceID}' was not found`);
|
|
1010
|
+
}
|
|
1011
|
+
this.preferenceCache.set(cacheKey, { value: res.Results[0], expiresAt: Date.now() + CACHE_TTL_MS });
|
|
1012
|
+
return res.Results[0];
|
|
1013
|
+
}
|
|
1014
|
+
async resolveAllAttributes(records, contextUser) {
|
|
1015
|
+
const out = new Map();
|
|
1016
|
+
if (records.length === 0)
|
|
1017
|
+
return out;
|
|
1018
|
+
const driver = this.getPrincipalDriver(records[0].EntityID);
|
|
1019
|
+
if (!driver)
|
|
1020
|
+
return out;
|
|
1021
|
+
return driver.ResolveAttributes(records, contextUser);
|
|
1022
|
+
}
|
|
1023
|
+
async resolveAllJurisdictions(records, contextUser) {
|
|
1024
|
+
const out = new Map();
|
|
1025
|
+
if (records.length === 0)
|
|
1026
|
+
return out;
|
|
1027
|
+
const driver = this.getPrincipalDriver(records[0].EntityID);
|
|
1028
|
+
if (!driver)
|
|
1029
|
+
return out;
|
|
1030
|
+
return driver.ResolveJurisdiction(records, contextUser);
|
|
1031
|
+
}
|
|
1032
|
+
collectEndpointIds(resolvedMap, recipients) {
|
|
1033
|
+
const ids = new Set();
|
|
1034
|
+
for (const list of resolvedMap.values()) {
|
|
1035
|
+
for (const ep of list)
|
|
1036
|
+
ids.add(ep.CommunicationEndpointID);
|
|
1037
|
+
}
|
|
1038
|
+
for (const r of recipients) {
|
|
1039
|
+
if (r.Endpoint?.CommunicationEndpointID) {
|
|
1040
|
+
ids.add(r.Endpoint.CommunicationEndpointID);
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
return Array.from(ids);
|
|
1044
|
+
}
|
|
1045
|
+
async batchLoadAdHocEndpoints(recipients, channelID, contextUser) {
|
|
1046
|
+
const out = new Map();
|
|
1047
|
+
const ids = new Set();
|
|
1048
|
+
const hashes = new Set();
|
|
1049
|
+
for (const rec of recipients) {
|
|
1050
|
+
if (rec.Endpoint?.CommunicationEndpointID) {
|
|
1051
|
+
ids.add(rec.Endpoint.CommunicationEndpointID);
|
|
1052
|
+
}
|
|
1053
|
+
else if (rec.Endpoint?.Address) {
|
|
1054
|
+
const norm = NormalizeEndpointAddress(rec.Endpoint.Address);
|
|
1055
|
+
if (norm) {
|
|
1056
|
+
hashes.add(ComputeEndpointHash(norm.NormalizedValue));
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
if (ids.size === 0 && hashes.size === 0) {
|
|
1061
|
+
return out;
|
|
1062
|
+
}
|
|
1063
|
+
const clauses = [];
|
|
1064
|
+
if (ids.size > 0) {
|
|
1065
|
+
const idList = Array.from(ids).map((id) => `'${EscapeSQLString(id)}'`).join(',');
|
|
1066
|
+
clauses.push(`ID IN (${idList})`);
|
|
1067
|
+
}
|
|
1068
|
+
if (hashes.size > 0) {
|
|
1069
|
+
const hashList = Array.from(hashes).map((h) => `'${EscapeSQLString(h)}'`).join(',');
|
|
1070
|
+
clauses.push(`(BaseMessageTypeID='${EscapeSQLString(channelID)}' AND ValueHash IN (${hashList}))`);
|
|
1071
|
+
}
|
|
1072
|
+
const rv = this.getRunView();
|
|
1073
|
+
const res = await rv.RunView({
|
|
1074
|
+
EntityName: 'MJ: Communication Endpoints',
|
|
1075
|
+
ExtraFilter: clauses.join(' OR '),
|
|
1076
|
+
ResultType: 'entity_object',
|
|
1077
|
+
}, contextUser);
|
|
1078
|
+
if (res.Success) {
|
|
1079
|
+
for (const ep of res.Results) {
|
|
1080
|
+
out.set(ep.ID.toLowerCase(), ep);
|
|
1081
|
+
if (ep.ValueHash) {
|
|
1082
|
+
out.set(`hash:${ep.ValueHash}`, ep);
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
return out;
|
|
1087
|
+
}
|
|
1088
|
+
async pickEndpointForRecipient(rec, channelID, resolvedMap, contextUser, adHocEndpointMap) {
|
|
1089
|
+
if (rec.Endpoint?.CommunicationEndpointID) {
|
|
1090
|
+
const entity = adHocEndpointMap?.get(rec.Endpoint.CommunicationEndpointID.toLowerCase()) ??
|
|
1091
|
+
(await this.loadEndpointEntity(rec.Endpoint.CommunicationEndpointID, contextUser));
|
|
1092
|
+
if (!entity)
|
|
1093
|
+
return undefined;
|
|
1094
|
+
return {
|
|
1095
|
+
CommunicationEndpointID: entity.ID,
|
|
1096
|
+
ChannelID: entity.BaseMessageTypeID,
|
|
1097
|
+
NormalizedValue: entity.NormalizedValue ?? '',
|
|
1098
|
+
ValueHash: entity.ValueHash,
|
|
1099
|
+
RawValue: entity.NormalizedValue ?? '',
|
|
1100
|
+
Domain: entity.Domain ?? undefined,
|
|
1101
|
+
EndpointEntity: entity,
|
|
1102
|
+
};
|
|
1103
|
+
}
|
|
1104
|
+
if (rec.Endpoint?.Address) {
|
|
1105
|
+
const norm = NormalizeEndpointAddress(rec.Endpoint.Address);
|
|
1106
|
+
if (!norm)
|
|
1107
|
+
return undefined;
|
|
1108
|
+
const hash = ComputeEndpointHash(norm.NormalizedValue);
|
|
1109
|
+
const cachedEp = adHocEndpointMap?.get(`hash:${hash}`);
|
|
1110
|
+
if (cachedEp) {
|
|
1111
|
+
return {
|
|
1112
|
+
CommunicationEndpointID: cachedEp.ID,
|
|
1113
|
+
ChannelID: cachedEp.BaseMessageTypeID,
|
|
1114
|
+
NormalizedValue: norm.NormalizedValue,
|
|
1115
|
+
ValueHash: hash,
|
|
1116
|
+
RawValue: norm.RawValue,
|
|
1117
|
+
Domain: norm.Domain,
|
|
1118
|
+
EndpointEntity: cachedEp,
|
|
1119
|
+
};
|
|
1120
|
+
}
|
|
1121
|
+
const rv = this.getRunView();
|
|
1122
|
+
const res = await rv.RunView({
|
|
1123
|
+
EntityName: 'MJ: Communication Endpoints',
|
|
1124
|
+
ExtraFilter: `BaseMessageTypeID='${EscapeSQLString(channelID)}' AND ValueHash='${EscapeSQLString(hash)}'`,
|
|
1125
|
+
ResultType: 'entity_object',
|
|
1126
|
+
}, contextUser);
|
|
1127
|
+
if (res.Success && res.Results.length > 0) {
|
|
1128
|
+
const ep = res.Results[0];
|
|
1129
|
+
return {
|
|
1130
|
+
CommunicationEndpointID: ep.ID,
|
|
1131
|
+
ChannelID: ep.BaseMessageTypeID,
|
|
1132
|
+
NormalizedValue: norm.NormalizedValue,
|
|
1133
|
+
ValueHash: hash,
|
|
1134
|
+
RawValue: norm.RawValue,
|
|
1135
|
+
Domain: norm.Domain,
|
|
1136
|
+
EndpointEntity: ep,
|
|
1137
|
+
};
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
if (rec.Principal) {
|
|
1141
|
+
return resolvedMap.get(PrincipalRecordKey(rec.Principal))?.[0];
|
|
1142
|
+
}
|
|
1143
|
+
return undefined;
|
|
1144
|
+
}
|
|
1145
|
+
async loadEndpointEntity(endpointID, contextUser) {
|
|
1146
|
+
const rv = this.getRunView();
|
|
1147
|
+
const res = await rv.RunView({
|
|
1148
|
+
EntityName: 'MJ: Communication Endpoints',
|
|
1149
|
+
ExtraFilter: `ID='${EscapeSQLString(endpointID)}'`,
|
|
1150
|
+
ResultType: 'entity_object',
|
|
1151
|
+
}, contextUser);
|
|
1152
|
+
return res.Success && res.Results.length > 0 ? res.Results[0] : undefined;
|
|
1153
|
+
}
|
|
1154
|
+
async loadSuppressions(endpointIds, principals, contextUser) {
|
|
1155
|
+
const clauses = [];
|
|
1156
|
+
if (endpointIds.length > 0) {
|
|
1157
|
+
const quoted = endpointIds.map((id) => `'${EscapeSQLString(id)}'`).join(',');
|
|
1158
|
+
clauses.push(`CommunicationEndpointID IN (${quoted})`);
|
|
1159
|
+
}
|
|
1160
|
+
if (principals.length > 0) {
|
|
1161
|
+
const quoted = principals.map((p) => `'${EscapeSQLString(p.RecordID)}'`).join(',');
|
|
1162
|
+
clauses.push(`RecordID IN (${quoted})`);
|
|
1163
|
+
}
|
|
1164
|
+
if (clauses.length === 0)
|
|
1165
|
+
return [];
|
|
1166
|
+
const rv = this.getRunView();
|
|
1167
|
+
const res = await rv.RunView({
|
|
1168
|
+
EntityName: 'MJ: Communication Suppressions',
|
|
1169
|
+
ExtraFilter: `Status='Active' AND (${clauses.join(' OR ')})`,
|
|
1170
|
+
ResultType: 'entity_object',
|
|
1171
|
+
}, contextUser);
|
|
1172
|
+
if (!res.Success) {
|
|
1173
|
+
throw new Error(`Failed loading communication suppressions: ${res.ErrorMessage ?? 'RunView failed'}`);
|
|
1174
|
+
}
|
|
1175
|
+
return res.Results;
|
|
1176
|
+
}
|
|
1177
|
+
/**
|
|
1178
|
+
* Loads each principal's choice for a preference across the whole sender chain (the sender, its
|
|
1179
|
+
* ancestors, and sender-less rows), the same reach suppressions have. See
|
|
1180
|
+
* {@link PickEffectivePrincipalPreference} for which row wins.
|
|
1181
|
+
*/
|
|
1182
|
+
async loadPrincipalPreferences(principals, preferenceID, senderChain, contextUser) {
|
|
1183
|
+
const out = new Map();
|
|
1184
|
+
if (principals.length === 0)
|
|
1185
|
+
return out;
|
|
1186
|
+
const quoted = principals.map((p) => `'${EscapeSQLString(p.RecordID)}'`).join(',');
|
|
1187
|
+
const senderIds = senderChain.map((s) => `'${EscapeSQLString(s.ID)}'`).join(',');
|
|
1188
|
+
const rv = this.getRunView();
|
|
1189
|
+
const res = await rv.RunView({
|
|
1190
|
+
EntityName: 'MJ: Communication Principal Preferences',
|
|
1191
|
+
ExtraFilter: `CommunicationPreferenceID='${EscapeSQLString(preferenceID)}' AND RecordID IN (${quoted}) AND (CommunicationSenderID IN (${senderIds}) OR CommunicationSenderID IS NULL)`,
|
|
1192
|
+
ResultType: 'entity_object',
|
|
1193
|
+
}, contextUser);
|
|
1194
|
+
if (!res.Success) {
|
|
1195
|
+
throw new Error(`Failed loading communication principal preferences: ${res.ErrorMessage ?? 'RunView failed'}`);
|
|
1196
|
+
}
|
|
1197
|
+
const byPrincipal = new Map();
|
|
1198
|
+
for (const pp of res.Results) {
|
|
1199
|
+
const key = `${pp.EntityID.toLowerCase()}:${pp.RecordID}`;
|
|
1200
|
+
byPrincipal.set(key, [...(byPrincipal.get(key) ?? []), pp]);
|
|
1201
|
+
}
|
|
1202
|
+
const chainIds = senderChain.map((s) => s.ID);
|
|
1203
|
+
for (const [key, rows] of byPrincipal) {
|
|
1204
|
+
const winner = PickEffectivePrincipalPreference(rows, chainIds);
|
|
1205
|
+
if (winner)
|
|
1206
|
+
out.set(key, winner);
|
|
1207
|
+
}
|
|
1208
|
+
return out;
|
|
1209
|
+
}
|
|
1210
|
+
checkTransactionalAuthorization(contextUser) {
|
|
1211
|
+
if (contextUser.Type === 'Owner') {
|
|
1212
|
+
return { Allowed: true };
|
|
1213
|
+
}
|
|
1214
|
+
const authorizations = CommunicationEngineBase.Instance.ProviderToUse?.Authorizations ?? [];
|
|
1215
|
+
const targetAuth = authorizations.find((a) => a.Name?.trim().toLowerCase() === 'communications: send transactional') ??
|
|
1216
|
+
authorizations.find((a) => a.Name?.trim().toLowerCase() === 'communications: admin');
|
|
1217
|
+
if (targetAuth && new AuthorizationEvaluator().UserCanExecuteWithAncestors(targetAuth, contextUser, authorizations)) {
|
|
1218
|
+
return { Allowed: true };
|
|
1219
|
+
}
|
|
1220
|
+
return {
|
|
1221
|
+
Allowed: false,
|
|
1222
|
+
ErrorMessage: 'Owner privileges or "Communications: Send Transactional" authorization required for Transactional sends',
|
|
1223
|
+
};
|
|
1224
|
+
}
|
|
1225
|
+
async checkSenderPermission(sender, contextUser) {
|
|
1226
|
+
const chain = await this.loadSenderAncestry(sender, contextUser);
|
|
1227
|
+
const ancestorIds = chain.slice(1).map((s) => `'${EscapeSQLString(s.ID)}'`);
|
|
1228
|
+
const filter = ancestorIds.length > 0
|
|
1229
|
+
? `CommunicationSenderID='${EscapeSQLString(sender.ID)}' OR (CommunicationSenderID IN (${ancestorIds.join(',')}) AND AppliesToChildSenders=1)`
|
|
1230
|
+
: `CommunicationSenderID='${EscapeSQLString(sender.ID)}'`;
|
|
1231
|
+
const rv = this.getRunView();
|
|
1232
|
+
const res = await rv.RunView({
|
|
1233
|
+
EntityName: 'MJ: Communication Sender Permissions',
|
|
1234
|
+
ExtraFilter: filter,
|
|
1235
|
+
ResultType: 'entity_object',
|
|
1236
|
+
}, contextUser);
|
|
1237
|
+
if (!res.Success) {
|
|
1238
|
+
return {
|
|
1239
|
+
Allowed: false,
|
|
1240
|
+
ErrorMessage: `Failed verifying sender permissions: ${res.ErrorMessage ?? 'RunView failed'}`,
|
|
1241
|
+
};
|
|
1242
|
+
}
|
|
1243
|
+
if (res.Results.length === 0) {
|
|
1244
|
+
// No ACL rows configured on sender chain — sender is unrestricted
|
|
1245
|
+
return { Allowed: true };
|
|
1246
|
+
}
|
|
1247
|
+
const userRoleIds = new UUIDSet((contextUser.UserRoles ?? []).map((ur) => ur.RoleID));
|
|
1248
|
+
const hasSend = res.Results.some((perm) => {
|
|
1249
|
+
if (perm.PermissionLevel !== 'Send' && perm.PermissionLevel !== 'Manage') {
|
|
1250
|
+
return false;
|
|
1251
|
+
}
|
|
1252
|
+
if (perm.UserID !== null && UUIDsEqual(perm.UserID, contextUser.ID)) {
|
|
1253
|
+
return true;
|
|
1254
|
+
}
|
|
1255
|
+
return perm.RoleID !== null && userRoleIds.Has(perm.RoleID);
|
|
1256
|
+
});
|
|
1257
|
+
if (!hasSend) {
|
|
1258
|
+
return {
|
|
1259
|
+
Allowed: false,
|
|
1260
|
+
ErrorMessage: `User lacks Send permission for sender '${sender.Name}'`,
|
|
1261
|
+
};
|
|
1262
|
+
}
|
|
1263
|
+
return { Allowed: true };
|
|
1264
|
+
}
|
|
1265
|
+
async verifySendingDomain(providerID, domain, credentialID, contextUser) {
|
|
1266
|
+
if (!domain)
|
|
1267
|
+
return false;
|
|
1268
|
+
const credClause = credentialID
|
|
1269
|
+
? `CredentialID='${EscapeSQLString(credentialID)}'`
|
|
1270
|
+
: `CredentialID IS NULL`;
|
|
1271
|
+
const rv = this.getRunView();
|
|
1272
|
+
const res = await rv.RunView({
|
|
1273
|
+
EntityName: 'MJ: Communication Sending Domains',
|
|
1274
|
+
ExtraFilter: `CommunicationProviderID='${EscapeSQLString(providerID)}' AND Domain='${EscapeSQLString(domain)}' AND ${credClause} AND Status='Verified'`,
|
|
1275
|
+
ResultType: 'simple',
|
|
1276
|
+
Fields: ['ID'],
|
|
1277
|
+
}, contextUser);
|
|
1278
|
+
return res.Success && res.Results.length > 0;
|
|
1279
|
+
}
|
|
1280
|
+
/**
|
|
1281
|
+
* Loads the run's existing logs for these endpoints only (one read per 200 endpoints, so a
|
|
1282
|
+
* normal chunk is one read). Returns `undefined` when a read fails; callers then look each log
|
|
1283
|
+
* up individually.
|
|
1284
|
+
*/
|
|
1285
|
+
async batchLoadRunLogs(runID, endpointIds, contextUser) {
|
|
1286
|
+
const map = new Map();
|
|
1287
|
+
const unique = [...new UUIDSet(endpointIds)];
|
|
1288
|
+
const rv = this.getRunView();
|
|
1289
|
+
for (let i = 0; i < unique.length; i += RUN_LOG_ENDPOINT_CHUNK) {
|
|
1290
|
+
const quoted = unique.slice(i, i + RUN_LOG_ENDPOINT_CHUNK).map((id) => `'${EscapeSQLString(id)}'`).join(',');
|
|
1291
|
+
const res = await rv.RunView({
|
|
1292
|
+
EntityName: 'MJ: Communication Logs',
|
|
1293
|
+
ExtraFilter: `CommunicationRunID='${EscapeSQLString(runID)}' AND CommunicationEndpointID IN (${quoted})`,
|
|
1294
|
+
ResultType: 'entity_object',
|
|
1295
|
+
}, contextUser);
|
|
1296
|
+
if (!res.Success) {
|
|
1297
|
+
return undefined;
|
|
1298
|
+
}
|
|
1299
|
+
for (const log of res.Results) {
|
|
1300
|
+
if (log.CommunicationEndpointID) {
|
|
1301
|
+
map.set(log.CommunicationEndpointID.toLowerCase(), log);
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
return map;
|
|
1306
|
+
}
|
|
1307
|
+
async claimOrCreateV2Log(params, sender, providerID, pmtID, runID, target, initialStatus, contextUser, deferredPayload, existingLogsByEndpoint) {
|
|
1308
|
+
if (!pmtID) {
|
|
1309
|
+
return { FailureReason: 'MissingProviderMessageType', FailureDetail: 'No provider message type found for channel' };
|
|
1310
|
+
}
|
|
1311
|
+
const findExisting = async () => {
|
|
1312
|
+
const rv = this.getRunView();
|
|
1313
|
+
const existingRes = await rv.RunView({
|
|
1314
|
+
EntityName: 'MJ: Communication Logs',
|
|
1315
|
+
ExtraFilter: `CommunicationRunID='${EscapeSQLString(runID)}' AND CommunicationEndpointID='${EscapeSQLString(target.Endpoint.CommunicationEndpointID)}'`,
|
|
1316
|
+
MaxRows: 1,
|
|
1317
|
+
ResultType: 'entity_object',
|
|
1318
|
+
}, contextUser);
|
|
1319
|
+
if (!existingRes.Success) {
|
|
1320
|
+
return { Success: false, ErrorMessage: existingRes.ErrorMessage ?? 'RunView failed' };
|
|
1321
|
+
}
|
|
1322
|
+
return { Success: true, Log: existingRes.Results[0] };
|
|
1323
|
+
};
|
|
1324
|
+
const handleExisting = async (existing) => {
|
|
1325
|
+
if (existing.Status === 'Complete' || Boolean(existing.ProviderMessageID)) {
|
|
1326
|
+
return { Log: existing, AlreadySent: true };
|
|
1327
|
+
}
|
|
1328
|
+
if (initialStatus === 'Pending') {
|
|
1329
|
+
return { Log: existing };
|
|
1330
|
+
}
|
|
1331
|
+
let reclaimStale = false;
|
|
1332
|
+
if (existing.Status === 'In-Progress') {
|
|
1333
|
+
if (!IsStaleInProgressLog(existing)) {
|
|
1334
|
+
return {
|
|
1335
|
+
FailureReason: 'LogAlreadyInProgress',
|
|
1336
|
+
FailureDetail: `CommunicationLog ${existing.ID} is already In-Progress without a ProviderMessageID`,
|
|
1337
|
+
};
|
|
1338
|
+
}
|
|
1339
|
+
const guarantee = await this.ResolveDeliveryGuarantee(params.Envelope, runID, sender, providerID, contextUser);
|
|
1340
|
+
if (guarantee !== 'At Least Once') {
|
|
1341
|
+
return {
|
|
1342
|
+
FailureReason: 'OutcomeUnknown',
|
|
1343
|
+
FailureDetail: `CommunicationLog ${existing.ID} has been In-Progress for over ${STALE_IN_PROGRESS_MINUTES} minutes without a ProviderMessageID. The provider may already have the message, and the delivery guarantee is ${guarantee}, so it was not resent.`,
|
|
1344
|
+
};
|
|
1345
|
+
}
|
|
1346
|
+
reclaimStale = true;
|
|
1347
|
+
}
|
|
1348
|
+
const claimed = await this.tryAtomicClaimLog(existing.ID, contextUser, reclaimStale);
|
|
1349
|
+
if (claimed.Result === 'claimed') {
|
|
1350
|
+
existing.Status = 'In-Progress';
|
|
1351
|
+
return { Log: existing };
|
|
1352
|
+
}
|
|
1353
|
+
if (claimed.Result === 'already-claimed') {
|
|
1354
|
+
return {
|
|
1355
|
+
FailureReason: 'LogAlreadyInProgress',
|
|
1356
|
+
FailureDetail: `CommunicationLog ${existing.ID} was claimed concurrently`,
|
|
1357
|
+
};
|
|
1358
|
+
}
|
|
1359
|
+
LogError(`V2SendService: could not claim CommunicationLog ${existing.ID}: ${claimed.Detail}`);
|
|
1360
|
+
return { FailureReason: 'LogClaimFailed', FailureDetail: claimed.Detail };
|
|
1361
|
+
};
|
|
1362
|
+
if (params.CommunicationRunID) {
|
|
1363
|
+
const preloaded = existingLogsByEndpoint?.get(target.Endpoint.CommunicationEndpointID.toLowerCase());
|
|
1364
|
+
if (preloaded) {
|
|
1365
|
+
return handleExisting(preloaded);
|
|
1366
|
+
}
|
|
1367
|
+
if (!existingLogsByEndpoint) {
|
|
1368
|
+
const lookup = await findExisting();
|
|
1369
|
+
if (!lookup.Success) {
|
|
1370
|
+
return { FailureReason: 'LogLookupFailed', FailureDetail: lookup.ErrorMessage };
|
|
1371
|
+
}
|
|
1372
|
+
if (lookup.Log) {
|
|
1373
|
+
return handleExisting(lookup.Log);
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
const md = CommunicationEngineBase.Instance.ProviderToUse;
|
|
1378
|
+
const bookkeepingUser = CommunicationEngineBase.Instance.ContextUser ?? contextUser;
|
|
1379
|
+
const log = await md.GetEntityObject('MJ: Communication Logs', bookkeepingUser);
|
|
1380
|
+
log.CommunicationRunID = runID;
|
|
1381
|
+
log.CommunicationProviderID = providerID;
|
|
1382
|
+
log.CommunicationProviderMessageTypeID = pmtID;
|
|
1383
|
+
log.CommunicationSenderID = sender.ID;
|
|
1384
|
+
log.CommunicationPreferenceID = params.Envelope.PreferenceID ?? null;
|
|
1385
|
+
log.CommunicationEndpointID = target.Endpoint.CommunicationEndpointID;
|
|
1386
|
+
log.RecipientAddress = target.Endpoint.NormalizedValue;
|
|
1387
|
+
log.EntityID = target.Principal?.EntityID ?? null;
|
|
1388
|
+
log.RecordID = target.Principal?.RecordID ?? null;
|
|
1389
|
+
log.MessageClass = params.Envelope.MessageClass;
|
|
1390
|
+
log.ScheduledAt = target.DeferUntil ?? params.Envelope.ScheduledAt ?? null;
|
|
1391
|
+
log.UnsubscribeToken = randomUUID();
|
|
1392
|
+
log.TrackingToken = randomUUID();
|
|
1393
|
+
log.Direction = 'Sending';
|
|
1394
|
+
log.Status = initialStatus;
|
|
1395
|
+
log.MessageDate = new Date();
|
|
1396
|
+
log.IsDryRun = Boolean(params.Envelope.DryRun);
|
|
1397
|
+
log.DeferredPayload = initialStatus === 'Pending' && deferredPayload ? JSON.stringify(deferredPayload) : null;
|
|
1398
|
+
log.CorrelationData = params.Envelope.CorrelationData ? JSON.stringify(params.Envelope.CorrelationData) : null;
|
|
1399
|
+
log.ComplianceDecision = JSON.stringify({
|
|
1400
|
+
Decision: target.Decision,
|
|
1401
|
+
Obligations: target.Obligations,
|
|
1402
|
+
...target.AuditSnapshot,
|
|
1403
|
+
});
|
|
1404
|
+
if (await log.Save()) {
|
|
1405
|
+
return { Log: log };
|
|
1406
|
+
}
|
|
1407
|
+
const saveErr = log.LatestResult?.CompleteMessage ?? 'Failed to save CommunicationLog';
|
|
1408
|
+
// Re-check for a concurrent winner on (CommunicationRunID, CommunicationEndpointID)
|
|
1409
|
+
const winner = await findExisting();
|
|
1410
|
+
if (winner.Success && winner.Log) {
|
|
1411
|
+
return handleExisting(winner.Log);
|
|
1412
|
+
}
|
|
1413
|
+
LogError(`V2SendService: ${saveErr}`);
|
|
1414
|
+
return { FailureReason: 'LogCreationFailed', FailureDetail: saveErr };
|
|
1415
|
+
}
|
|
1416
|
+
/**
|
|
1417
|
+
* Records that one chunk of a run has finished, as a `MJ: Communication Run Chunks` row, and ends
|
|
1418
|
+
* the run when every chunk is recorded.
|
|
1419
|
+
*
|
|
1420
|
+
* - A redelivered chunk finds its existing row (unique on run and chunk index) and is not counted
|
|
1421
|
+
* twice. A chunk that was refused (`Failed`) and later succeeds on a retry has its row updated.
|
|
1422
|
+
* - When the run's `ChunkCount` chunks are recorded, the run's `Status` becomes `Complete`, or
|
|
1423
|
+
* `Failed` if any chunk was refused, and `EndedAt` is set. Two chunks finishing together may
|
|
1424
|
+
* both write that same final state, which is harmless.
|
|
1425
|
+
* - Logs cannot be counted instead: blocked recipients write none, and recipients sharing an
|
|
1426
|
+
* address share one.
|
|
1427
|
+
*
|
|
1428
|
+
* Failures are logged and leave the run open; they never fail the chunk's send.
|
|
1429
|
+
*
|
|
1430
|
+
* @returns `true` when this call ended the run.
|
|
1431
|
+
*/
|
|
1432
|
+
async RecordRunChunkDone(runID, chunk, outcome, contextUser) {
|
|
1433
|
+
try {
|
|
1434
|
+
const recorded = await this.upsertRunChunk(runID, chunk, outcome, contextUser);
|
|
1435
|
+
if (!recorded)
|
|
1436
|
+
return false;
|
|
1437
|
+
return await this.endRunIfAllChunksRecorded(runID, chunk.Count, contextUser);
|
|
1438
|
+
}
|
|
1439
|
+
catch (err) {
|
|
1440
|
+
LogError(`V2SendService: failed recording chunk ${chunk.Index} of run ${runID}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1441
|
+
return false;
|
|
1442
|
+
}
|
|
1443
|
+
}
|
|
1444
|
+
/** Creates or updates the chunk's row. Returns false (already logged) when it could not be saved. */
|
|
1445
|
+
async upsertRunChunk(runID, chunk, outcome, contextUser) {
|
|
1446
|
+
const existing = await this.loadRunChunk(runID, chunk.Index, contextUser);
|
|
1447
|
+
if (existing) {
|
|
1448
|
+
if (existing.Status === 'Complete' || outcome.Status === 'Failed')
|
|
1449
|
+
return true;
|
|
1450
|
+
return this.saveRunChunk(existing, outcome, runID, chunk);
|
|
1451
|
+
}
|
|
1452
|
+
const md = CommunicationEngineBase.Instance.ProviderToUse;
|
|
1453
|
+
const row = await md.GetEntityObject('MJ: Communication Run Chunks', contextUser);
|
|
1454
|
+
row.CommunicationRunID = runID;
|
|
1455
|
+
row.ChunkIndex = chunk.Index;
|
|
1456
|
+
if (await this.saveRunChunk(row, outcome, runID, chunk))
|
|
1457
|
+
return true;
|
|
1458
|
+
// Lost a race with a concurrent redelivery of the same chunk: its row now exists.
|
|
1459
|
+
return (await this.loadRunChunk(runID, chunk.Index, contextUser)) !== undefined;
|
|
1460
|
+
}
|
|
1461
|
+
async saveRunChunk(row, outcome, runID, chunk) {
|
|
1462
|
+
row.Status = outcome.Status;
|
|
1463
|
+
row.RecipientCount = outcome.RecipientCount;
|
|
1464
|
+
row.ErrorMessage = outcome.ErrorMessage ?? null;
|
|
1465
|
+
row.CompletedAt = new Date();
|
|
1466
|
+
if (await row.Save())
|
|
1467
|
+
return true;
|
|
1468
|
+
LogError(`V2SendService: failed saving chunk ${chunk.Index} of run ${runID}: ${row.LatestResult?.CompleteMessage ?? 'unknown error'}`);
|
|
1469
|
+
return false;
|
|
1470
|
+
}
|
|
1471
|
+
async loadRunChunk(runID, chunkIndex, contextUser) {
|
|
1472
|
+
const res = await this.getRunView().RunView({
|
|
1473
|
+
EntityName: 'MJ: Communication Run Chunks',
|
|
1474
|
+
ExtraFilter: `CommunicationRunID='${EscapeSQLString(runID)}' AND ChunkIndex=${Math.trunc(chunkIndex)}`,
|
|
1475
|
+
MaxRows: 1,
|
|
1476
|
+
ResultType: 'entity_object',
|
|
1477
|
+
BypassCache: true,
|
|
1478
|
+
}, contextUser);
|
|
1479
|
+
if (!res.Success)
|
|
1480
|
+
throw new Error(res.ErrorMessage || 'Failed loading the communication run chunk');
|
|
1481
|
+
return res.Results[0];
|
|
1482
|
+
}
|
|
1483
|
+
/** Ends the run when every chunk is recorded. Returns true when this call changed the run. */
|
|
1484
|
+
async endRunIfAllChunksRecorded(runID, chunkCount, contextUser) {
|
|
1485
|
+
const rv = this.getRunView();
|
|
1486
|
+
const [runRes, chunksRes] = await rv.RunViews([
|
|
1487
|
+
{
|
|
1488
|
+
EntityName: 'MJ: Communication Runs',
|
|
1489
|
+
ExtraFilter: `ID='${EscapeSQLString(runID)}'`,
|
|
1490
|
+
MaxRows: 1,
|
|
1491
|
+
ResultType: 'entity_object',
|
|
1492
|
+
BypassCache: true,
|
|
1493
|
+
},
|
|
1494
|
+
{
|
|
1495
|
+
EntityName: 'MJ: Communication Run Chunks',
|
|
1496
|
+
ExtraFilter: `CommunicationRunID='${EscapeSQLString(runID)}'`,
|
|
1497
|
+
Fields: ['ID', 'Status'],
|
|
1498
|
+
ResultType: 'simple',
|
|
1499
|
+
IgnoreMaxRows: true,
|
|
1500
|
+
BypassCache: true,
|
|
1501
|
+
},
|
|
1502
|
+
], contextUser);
|
|
1503
|
+
if (!runRes.Success || !chunksRes.Success) {
|
|
1504
|
+
throw new Error(runRes.ErrorMessage || chunksRes.ErrorMessage || 'Failed loading run progress');
|
|
1505
|
+
}
|
|
1506
|
+
const run = runRes.Results[0];
|
|
1507
|
+
if (!run)
|
|
1508
|
+
throw new Error('run not found');
|
|
1509
|
+
const chunks = chunksRes.Results;
|
|
1510
|
+
const expected = run.ChunkCount ?? chunkCount;
|
|
1511
|
+
if (chunks.length < expected)
|
|
1512
|
+
return false;
|
|
1513
|
+
const finalStatus = chunks.some((c) => c.Status === 'Failed') ? 'Failed' : 'Complete';
|
|
1514
|
+
if (run.Status === finalStatus && run.EndedAt)
|
|
1515
|
+
return false;
|
|
1516
|
+
run.Status = finalStatus;
|
|
1517
|
+
run.EndedAt = run.EndedAt ?? new Date();
|
|
1518
|
+
if (run.ChunkCount == null)
|
|
1519
|
+
run.ChunkCount = expected;
|
|
1520
|
+
if (await run.Save())
|
|
1521
|
+
return true;
|
|
1522
|
+
throw new Error(run.LatestResult?.CompleteMessage || 'Failed ending the communication run');
|
|
1523
|
+
}
|
|
1524
|
+
/**
|
|
1525
|
+
* Stores the chunk count (and the envelope's delivery guarantee, when it sets one) on a run before
|
|
1526
|
+
* its chunks are queued, so the last chunk knows when the run is finished.
|
|
1527
|
+
*/
|
|
1528
|
+
async prepareChunkedRun(run, chunkCount, deliveryGuarantee) {
|
|
1529
|
+
run.ChunkCount = chunkCount;
|
|
1530
|
+
if (deliveryGuarantee)
|
|
1531
|
+
run.DeliveryGuarantee = deliveryGuarantee;
|
|
1532
|
+
if (await run.Save())
|
|
1533
|
+
return { Success: true };
|
|
1534
|
+
return {
|
|
1535
|
+
Success: false,
|
|
1536
|
+
ErrorMessage: `Failed to record the chunk count on communication run ${run.ID}: ${run.LatestResult?.CompleteMessage ?? 'unknown error'}`,
|
|
1537
|
+
};
|
|
1538
|
+
}
|
|
1539
|
+
/**
|
|
1540
|
+
* Resolves the delivery guarantee for a send: the envelope's, then the run's, then the sender's
|
|
1541
|
+
* and its ancestors' (nearest first), then the provider's, then {@link DEFAULT_DELIVERY_GUARANTEE}.
|
|
1542
|
+
* A lookup that fails resolves to At Most Once, the setting that never sends twice.
|
|
1543
|
+
*/
|
|
1544
|
+
async ResolveDeliveryGuarantee(envelope, runID, sender, providerID, contextUser) {
|
|
1545
|
+
if (envelope.DeliveryGuarantee)
|
|
1546
|
+
return envelope.DeliveryGuarantee;
|
|
1547
|
+
try {
|
|
1548
|
+
const runGuarantee = runID ? await this.loadRunDeliveryGuarantee(runID, contextUser) : null;
|
|
1549
|
+
const chain = await this.loadSenderAncestry(sender, contextUser);
|
|
1550
|
+
const provider = CommunicationEngineBase.Instance.Providers.find((p) => UUIDsEqual(p.ID, providerID));
|
|
1551
|
+
return PickDeliveryGuarantee([runGuarantee, ...chain.map((c) => c.DeliveryGuarantee), provider?.DeliveryGuarantee]);
|
|
1552
|
+
}
|
|
1553
|
+
catch (err) {
|
|
1554
|
+
LogError(`V2SendService: could not resolve the delivery guarantee; using At Most Once: ${err instanceof Error ? err.message : String(err)}`);
|
|
1555
|
+
return 'At Most Once';
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
1558
|
+
async loadRunDeliveryGuarantee(runID, contextUser) {
|
|
1559
|
+
const res = await this.getRunView().RunView({
|
|
1560
|
+
EntityName: 'MJ: Communication Runs',
|
|
1561
|
+
ExtraFilter: `ID='${EscapeSQLString(runID)}'`,
|
|
1562
|
+
Fields: ['ID', 'DeliveryGuarantee'],
|
|
1563
|
+
MaxRows: 1,
|
|
1564
|
+
ResultType: 'simple',
|
|
1565
|
+
}, contextUser);
|
|
1566
|
+
if (!res.Success)
|
|
1567
|
+
throw new Error(res.ErrorMessage || 'Failed loading the communication run');
|
|
1568
|
+
return res.Results[0]?.DeliveryGuarantee ?? null;
|
|
1569
|
+
}
|
|
1570
|
+
getRunView() {
|
|
1571
|
+
return RunView.FromMetadataProvider(CommunicationEngineBase.Instance.ProviderToUse);
|
|
1572
|
+
}
|
|
1573
|
+
/**
|
|
1574
|
+
* V1 gate: checks endpoint status and active suppressions for legacy SendSingleMessage / SendMessages callers.
|
|
1575
|
+
*/
|
|
1576
|
+
async CheckV1ComplianceGate(channelID, recipientAddress, messageClass, contextUser) {
|
|
1577
|
+
return this.CheckV1ComplianceGateBatch(channelID, [recipientAddress], messageClass, contextUser);
|
|
1578
|
+
}
|
|
1579
|
+
/**
|
|
1580
|
+
* Batched V1 gate: checks endpoint status and active suppressions across all recipient addresses
|
|
1581
|
+
* in at most two RunView calls instead of querying inside a per-recipient loop.
|
|
1582
|
+
*/
|
|
1583
|
+
async CheckV1ComplianceGateBatch(channelID, recipientAddresses, messageClass, contextUser) {
|
|
1584
|
+
const hashes = new Set();
|
|
1585
|
+
for (const raw of recipientAddresses) {
|
|
1586
|
+
const trimmed = raw.trim();
|
|
1587
|
+
if (!trimmed)
|
|
1588
|
+
continue;
|
|
1589
|
+
const norm = NormalizeEndpointAddress(trimmed, channelID);
|
|
1590
|
+
hashes.add(norm?.ValueHash ?? ComputeEndpointHash(trimmed.toLowerCase()));
|
|
1591
|
+
}
|
|
1592
|
+
if (hashes.size === 0) {
|
|
1593
|
+
return { Allowed: true };
|
|
1594
|
+
}
|
|
1595
|
+
const hashList = Array.from(hashes)
|
|
1596
|
+
.map((h) => `'${EscapeSQLString(h)}'`)
|
|
1597
|
+
.join(',');
|
|
1598
|
+
const rv = this.getRunView();
|
|
1599
|
+
const epRes = await rv.RunView({
|
|
1600
|
+
EntityName: 'MJ: Communication Endpoints',
|
|
1601
|
+
ExtraFilter: `BaseMessageTypeID='${EscapeSQLString(channelID)}' AND ValueHash IN (${hashList})`,
|
|
1602
|
+
ResultType: 'entity_object',
|
|
1603
|
+
}, contextUser);
|
|
1604
|
+
if (!epRes.Success) {
|
|
1605
|
+
return {
|
|
1606
|
+
Allowed: false,
|
|
1607
|
+
Reason: 'GateLookupFailed',
|
|
1608
|
+
Detail: epRes.ErrorMessage ?? 'Failed to query communication endpoints',
|
|
1609
|
+
};
|
|
1610
|
+
}
|
|
1611
|
+
if (epRes.Results.length === 0) {
|
|
1612
|
+
return { Allowed: true };
|
|
1613
|
+
}
|
|
1614
|
+
for (const endpoint of epRes.Results) {
|
|
1615
|
+
if (endpoint.Status === 'Hard Bounced' || endpoint.Status === 'Invalid' || endpoint.Status === 'Erased') {
|
|
1616
|
+
return {
|
|
1617
|
+
Allowed: false,
|
|
1618
|
+
Reason: endpoint.Status,
|
|
1619
|
+
Detail: `Blocked by endpoint status '${endpoint.Status}'`,
|
|
1620
|
+
};
|
|
1621
|
+
}
|
|
1622
|
+
if (endpoint.Status === 'Complained' && messageClass !== 'Transactional') {
|
|
1623
|
+
return {
|
|
1624
|
+
Allowed: false,
|
|
1625
|
+
Reason: 'Spam Complaint',
|
|
1626
|
+
Detail: `Blocked by endpoint status 'Complained'`,
|
|
1627
|
+
};
|
|
1628
|
+
}
|
|
1629
|
+
}
|
|
1630
|
+
const supRes = await this.loadV1Suppressions(epRes.Results.map((e) => e.ID), contextUser);
|
|
1631
|
+
if (!supRes.Suppressions) {
|
|
1632
|
+
return { Allowed: false, Reason: 'GateLookupFailed', Detail: supRes.ErrorMessage };
|
|
1633
|
+
}
|
|
1634
|
+
return this.evaluateV1Suppressions(supRes.Suppressions, messageClass);
|
|
1635
|
+
}
|
|
1636
|
+
/**
|
|
1637
|
+
* Active suppressions that reach these endpoints: those on the endpoint itself, and those on any
|
|
1638
|
+
* principal that has used it (through `MJ: Communication Endpoint Principals`), so a principal
|
|
1639
|
+
* that unsubscribed is not mailed at an address recorded under it. Fails closed on any read error.
|
|
1640
|
+
*/
|
|
1641
|
+
async loadV1Suppressions(endpointIds, contextUser) {
|
|
1642
|
+
const rv = this.getRunView();
|
|
1643
|
+
const epList = endpointIds.map((id) => `'${EscapeSQLString(id)}'`).join(',');
|
|
1644
|
+
const linkRes = await rv.RunView({
|
|
1645
|
+
EntityName: 'MJ: Communication Endpoint Principals',
|
|
1646
|
+
ExtraFilter: `CommunicationEndpointID IN (${epList})`,
|
|
1647
|
+
Fields: ['ID', 'EntityID', 'RecordID'],
|
|
1648
|
+
ResultType: 'simple',
|
|
1649
|
+
}, contextUser);
|
|
1650
|
+
if (!linkRes.Success) {
|
|
1651
|
+
return { ErrorMessage: linkRes.ErrorMessage ?? 'Failed to query communication endpoint principals' };
|
|
1652
|
+
}
|
|
1653
|
+
const clauses = [`CommunicationEndpointID IN (${epList})`];
|
|
1654
|
+
for (const link of linkRes.Results) {
|
|
1655
|
+
clauses.push(`(EntityID='${EscapeSQLString(link.EntityID)}' AND RecordID='${EscapeSQLString(link.RecordID)}')`);
|
|
1656
|
+
}
|
|
1657
|
+
const supRes = await rv.RunView({
|
|
1658
|
+
EntityName: 'MJ: Communication Suppressions',
|
|
1659
|
+
ExtraFilter: `Status='Active' AND (${clauses.join(' OR ')})`,
|
|
1660
|
+
ResultType: 'entity_object',
|
|
1661
|
+
}, contextUser);
|
|
1662
|
+
if (!supRes.Success) {
|
|
1663
|
+
return { ErrorMessage: supRes.ErrorMessage ?? 'Failed to query communication suppressions' };
|
|
1664
|
+
}
|
|
1665
|
+
return { Suppressions: supRes.Results };
|
|
1666
|
+
}
|
|
1667
|
+
evaluateV1Suppressions(suppressions, messageClass) {
|
|
1668
|
+
const nowMs = Date.now();
|
|
1669
|
+
for (const s of suppressions) {
|
|
1670
|
+
if (s.ExpiresAt && s.ExpiresAt.getTime() <= nowMs)
|
|
1671
|
+
continue;
|
|
1672
|
+
const alwaysBlocks = s.Reason === 'Hard Bounce' || s.Reason === 'Invalid Address';
|
|
1673
|
+
if (alwaysBlocks || messageClass !== 'Transactional') {
|
|
1674
|
+
return { Allowed: false, Reason: s.Reason, Detail: `Suppressed by ${s.Reason}` };
|
|
1675
|
+
}
|
|
1676
|
+
}
|
|
1677
|
+
return { Allowed: true };
|
|
1678
|
+
}
|
|
1679
|
+
validateBodyObligations(finalPayload, obligations) {
|
|
1680
|
+
if (obligations.RequireFooterUnsubscribe) {
|
|
1681
|
+
const unsubUrl = obligations.UnsubscribeURL?.trim();
|
|
1682
|
+
if (!unsubUrl) {
|
|
1683
|
+
return 'Missing required UnsubscribeURL for footer obligation';
|
|
1684
|
+
}
|
|
1685
|
+
const hasHtmlUnsub = finalPayload.HTMLBody ? finalPayload.HTMLBody.includes(unsubUrl) : false;
|
|
1686
|
+
const hasTextUnsub = finalPayload.Body ? finalPayload.Body.includes(unsubUrl) : false;
|
|
1687
|
+
if (finalPayload.HTMLBody && !hasHtmlUnsub) {
|
|
1688
|
+
return 'HTML body is missing required footer unsubscribe link';
|
|
1689
|
+
}
|
|
1690
|
+
if (!finalPayload.HTMLBody && !hasTextUnsub) {
|
|
1691
|
+
return 'Text body is missing required footer unsubscribe link';
|
|
1692
|
+
}
|
|
1693
|
+
}
|
|
1694
|
+
if (obligations.RequireSenderPostalAddress) {
|
|
1695
|
+
const postal = obligations.SenderPostalAddress?.trim();
|
|
1696
|
+
if (!postal) {
|
|
1697
|
+
return 'Missing required SenderPostalAddress for compliance footer obligation';
|
|
1698
|
+
}
|
|
1699
|
+
const hasHtmlPostal = finalPayload.HTMLBody ? finalPayload.HTMLBody.includes(postal) : false;
|
|
1700
|
+
const hasTextPostal = finalPayload.Body ? finalPayload.Body.includes(postal) : false;
|
|
1701
|
+
if (finalPayload.HTMLBody && !hasHtmlPostal) {
|
|
1702
|
+
return 'HTML body is missing required sender postal address';
|
|
1703
|
+
}
|
|
1704
|
+
if (!finalPayload.HTMLBody && !hasTextPostal) {
|
|
1705
|
+
return 'Text body is missing required sender postal address';
|
|
1706
|
+
}
|
|
1707
|
+
}
|
|
1708
|
+
return undefined;
|
|
1709
|
+
}
|
|
1710
|
+
assertProtectedElementsIntact(finalPayload, snapshot) {
|
|
1711
|
+
const headers = finalPayload.Headers ?? {};
|
|
1712
|
+
if (snapshot.ListUnsubscribe && headers['List-Unsubscribe'] !== snapshot.ListUnsubscribe) {
|
|
1713
|
+
throw new Error('Protected List-Unsubscribe header failed integrity check');
|
|
1714
|
+
}
|
|
1715
|
+
if (snapshot.ListUnsubscribePost && headers['List-Unsubscribe-Post'] !== snapshot.ListUnsubscribePost) {
|
|
1716
|
+
throw new Error('Protected List-Unsubscribe-Post header failed integrity check');
|
|
1717
|
+
}
|
|
1718
|
+
if (snapshot.FooterHTML && finalPayload.HTMLBody && !finalPayload.HTMLBody.includes(snapshot.FooterHTML)) {
|
|
1719
|
+
throw new Error('Protected compliance HTML footer failed integrity check');
|
|
1720
|
+
}
|
|
1721
|
+
if (snapshot.FooterText && !finalPayload.HTMLBody && finalPayload.Body && !finalPayload.Body.includes(snapshot.FooterText)) {
|
|
1722
|
+
throw new Error('Protected compliance text footer failed integrity check');
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
async resolveSenderCredentials(sender, contextUser) {
|
|
1726
|
+
if (!sender.CredentialID) {
|
|
1727
|
+
return undefined;
|
|
1728
|
+
}
|
|
1729
|
+
await CredentialEngine.Instance.Config(false, contextUser);
|
|
1730
|
+
const resolved = await CredentialEngine.Instance.GetCredential('', {
|
|
1731
|
+
credentialId: sender.CredentialID,
|
|
1732
|
+
contextUser,
|
|
1733
|
+
subsystem: 'Communication',
|
|
1734
|
+
});
|
|
1735
|
+
const values = { ...resolved.values };
|
|
1736
|
+
values.disableEnvironmentFallback = true;
|
|
1737
|
+
return values;
|
|
1738
|
+
}
|
|
1739
|
+
/**
|
|
1740
|
+
* Queries due `Pending` CommunicationLog rows (`ScheduledAt <= GETUTCDATE()`) created by
|
|
1741
|
+
* quiet-hours deferrals or future `Envelope.ScheduledAt`, re-evaluates compliance eligibility,
|
|
1742
|
+
* and dispatches each eligible message (or marks Failed / re-defers if still in quiet hours).
|
|
1743
|
+
*/
|
|
1744
|
+
async ProcessDueScheduledLogs(contextUser, getProvider, batchSize = 50) {
|
|
1745
|
+
const bookkeepingUser = CommunicationEngineBase.Instance.ContextUser ?? contextUser;
|
|
1746
|
+
const claimedLogs = await this.claimDueDeferredLogs(batchSize, bookkeepingUser);
|
|
1747
|
+
if (claimedLogs.length === 0) {
|
|
1748
|
+
return { Processed: 0, Sent: 0, Failed: 0, Redeferred: 0 };
|
|
1749
|
+
}
|
|
1750
|
+
let sent = 0;
|
|
1751
|
+
let failed = 0;
|
|
1752
|
+
let redeferred = 0;
|
|
1753
|
+
const providersById = IndexByUUID(CommunicationEngineBase.Instance.Providers, (p) => p.ID);
|
|
1754
|
+
const pmtsById = IndexByUUID(CommunicationEngineBase.Instance.Providers.flatMap((p) => p.MessageTypes), (m) => m.ID);
|
|
1755
|
+
const saveLogChecked = async (log, context) => {
|
|
1756
|
+
if (!(await log.Save())) {
|
|
1757
|
+
LogError(`V2SendService.ProcessDueScheduledLogs (${context}) failed to save log ${log.ID}: ${log.LatestResult?.CompleteMessage ?? 'unknown error'}`);
|
|
1758
|
+
}
|
|
1759
|
+
};
|
|
1760
|
+
for (const log of claimedLogs) {
|
|
1761
|
+
try {
|
|
1762
|
+
const payload = parseDeferredPayload(log.DeferredPayload);
|
|
1763
|
+
const dryRun = log.IsDryRun;
|
|
1764
|
+
const correlationData = parseCorrelationData(log.CorrelationData);
|
|
1765
|
+
if (!payload || !log.CommunicationSenderID || !log.RecipientAddress) {
|
|
1766
|
+
log.Status = 'Failed';
|
|
1767
|
+
log.ErrorMessage = 'Deferred log is missing payload, sender, or recipient address';
|
|
1768
|
+
log.DeferredPayload = null;
|
|
1769
|
+
await saveLogChecked(log, 'invalid-payload');
|
|
1770
|
+
failed++;
|
|
1771
|
+
continue;
|
|
1772
|
+
}
|
|
1773
|
+
const sender = await this.resolveSender(log.CommunicationSenderID, bookkeepingUser);
|
|
1774
|
+
const providerEntity = log.CommunicationProviderID
|
|
1775
|
+
? providersById.Get(log.CommunicationProviderID)
|
|
1776
|
+
: undefined;
|
|
1777
|
+
if (!sender || !providerEntity) {
|
|
1778
|
+
log.Status = 'Failed';
|
|
1779
|
+
log.ErrorMessage = 'Deferred log sender or provider no longer exists';
|
|
1780
|
+
log.DeferredPayload = null;
|
|
1781
|
+
await saveLogChecked(log, 'missing-sender-or-provider');
|
|
1782
|
+
failed++;
|
|
1783
|
+
continue;
|
|
1784
|
+
}
|
|
1785
|
+
const pmt = (log.CommunicationProviderMessageTypeID
|
|
1786
|
+
? pmtsById.Get(log.CommunicationProviderMessageTypeID)
|
|
1787
|
+
: undefined) ?? providerEntity.MessageTypes[0];
|
|
1788
|
+
const channelID = pmt?.CommunicationBaseMessageTypeID ?? '';
|
|
1789
|
+
if (!channelID) {
|
|
1790
|
+
log.Status = 'Failed';
|
|
1791
|
+
log.ErrorMessage = 'Unable to resolve channel for deferred communication log';
|
|
1792
|
+
log.DeferredPayload = null;
|
|
1793
|
+
await saveLogChecked(log, 'missing-channel');
|
|
1794
|
+
failed++;
|
|
1795
|
+
continue;
|
|
1796
|
+
}
|
|
1797
|
+
const envelope = {
|
|
1798
|
+
SenderID: sender.ID,
|
|
1799
|
+
ProviderID: providerEntity.ID,
|
|
1800
|
+
ChannelID: channelID,
|
|
1801
|
+
PreferenceID: log.CommunicationPreferenceID ?? undefined,
|
|
1802
|
+
MessageClass: log.MessageClass ?? 'Operational',
|
|
1803
|
+
DryRun: dryRun || undefined,
|
|
1804
|
+
CorrelationData: correlationData,
|
|
1805
|
+
};
|
|
1806
|
+
const recipient = {
|
|
1807
|
+
Principal: log.EntityID && log.RecordID ? { EntityID: log.EntityID, RecordID: log.RecordID } : undefined,
|
|
1808
|
+
Endpoint: { Address: log.RecipientAddress },
|
|
1809
|
+
};
|
|
1810
|
+
const eligibility = await this.EvaluateEligibility({ Envelope: envelope, Recipients: [recipient] }, bookkeepingUser);
|
|
1811
|
+
if (eligibility.Blocked.length > 0 || eligibility.Sendable.length === 0) {
|
|
1812
|
+
const block = eligibility.Blocked[0];
|
|
1813
|
+
log.Status = 'Failed';
|
|
1814
|
+
log.ErrorMessage = block?.Detail ?? block?.Reason ?? 'Blocked during scheduled dispatch';
|
|
1815
|
+
log.DeferredPayload = null;
|
|
1816
|
+
await saveLogChecked(log, 'eligibility-blocked');
|
|
1817
|
+
failed++;
|
|
1818
|
+
continue;
|
|
1819
|
+
}
|
|
1820
|
+
const target = eligibility.Sendable[0];
|
|
1821
|
+
if (target.Decision === 'Deferred' && target.DeferUntil) {
|
|
1822
|
+
log.Status = 'Pending';
|
|
1823
|
+
log.ScheduledAt = target.DeferUntil;
|
|
1824
|
+
await saveLogChecked(log, 'redefer');
|
|
1825
|
+
redeferred++;
|
|
1826
|
+
continue;
|
|
1827
|
+
}
|
|
1828
|
+
const provider = getProvider(providerEntity.Name);
|
|
1829
|
+
const senderCredentials = await this.resolveSenderCredentials(sender, bookkeepingUser);
|
|
1830
|
+
// Clear the stored body before dispatch so the rendered message is not kept on the log.
|
|
1831
|
+
log.DeferredPayload = null;
|
|
1832
|
+
const outcome = await this.dispatchSingleRecipient({
|
|
1833
|
+
CommunicationRunID: log.CommunicationRunID ?? undefined,
|
|
1834
|
+
Envelope: envelope,
|
|
1835
|
+
Payload: payload,
|
|
1836
|
+
Recipients: [recipient],
|
|
1837
|
+
}, sender, providerEntity.ID, pmt, log.CommunicationRunID ?? '', target, undefined, provider, bookkeepingUser, senderCredentials, undefined, log);
|
|
1838
|
+
if (outcome.Status === 'Sent' || outcome.Status === 'Queued') {
|
|
1839
|
+
sent++;
|
|
1840
|
+
}
|
|
1841
|
+
else if (outcome.Status !== 'DryRun') {
|
|
1842
|
+
failed++;
|
|
1843
|
+
}
|
|
1844
|
+
}
|
|
1845
|
+
catch (err) {
|
|
1846
|
+
log.Status = 'Failed';
|
|
1847
|
+
log.ErrorMessage = err instanceof Error ? err.message : String(err);
|
|
1848
|
+
await saveLogChecked(log, 'unexpected-error');
|
|
1849
|
+
failed++;
|
|
1850
|
+
}
|
|
1851
|
+
}
|
|
1852
|
+
return {
|
|
1853
|
+
Processed: claimedLogs.length,
|
|
1854
|
+
Sent: sent,
|
|
1855
|
+
Failed: failed,
|
|
1856
|
+
Redeferred: redeferred,
|
|
1857
|
+
};
|
|
1858
|
+
}
|
|
1859
|
+
/**
|
|
1860
|
+
* Claims a Pending or Failed log for sending with one conditional UPDATE, so two workers cannot
|
|
1861
|
+
* both win. With `reclaimStale` (delivery guarantee At Least Once) it may also take over a log
|
|
1862
|
+
* stuck In-Progress, with no ProviderMessageID, for longer than {@link STALE_IN_PROGRESS_MINUTES}.
|
|
1863
|
+
* There is no fallback: without `ExecuteSQL` a claim would be read-then-write, which cannot
|
|
1864
|
+
* exclude a concurrent sender, so the claim fails and nothing is sent.
|
|
1865
|
+
*/
|
|
1866
|
+
async tryAtomicClaimLog(logId, contextUser, reclaimStale = false) {
|
|
1867
|
+
const provider = CommunicationEngineBase.Instance.ProviderToUse;
|
|
1868
|
+
if (!isSqlCapableProvider(provider)) {
|
|
1869
|
+
return { Result: 'failed', Detail: 'Atomic log claim needs a provider with ExecuteSQL; refusing a non-atomic claim' };
|
|
1870
|
+
}
|
|
1871
|
+
const schema = provider.MJCoreSchemaName ?? '__mj';
|
|
1872
|
+
try {
|
|
1873
|
+
const rows = await provider.ExecuteSQL(
|
|
1874
|
+
// OUTPUT goes INTO a table variable: CommunicationLog has CodeGen's update trigger, and
|
|
1875
|
+
// SQL Server refuses a bare OUTPUT clause on a table with an enabled trigger.
|
|
1876
|
+
`DECLARE @Claimed TABLE (ID UNIQUEIDENTIFIER);
|
|
1877
|
+
UPDATE [${schema}].[CommunicationLog]
|
|
1878
|
+
SET Status = 'In-Progress', __mj_UpdatedAt = GETUTCDATE()
|
|
1879
|
+
OUTPUT INSERTED.ID INTO @Claimed
|
|
1880
|
+
WHERE ID = @p0
|
|
1881
|
+
AND (Status IN ('Pending', 'Failed')
|
|
1882
|
+
OR (@p1 = 1 AND Status = 'In-Progress' AND ProviderMessageID IS NULL
|
|
1883
|
+
AND __mj_UpdatedAt < DATEADD(MINUTE, -@p2, GETUTCDATE())));
|
|
1884
|
+
SELECT ID FROM @Claimed;`, [logId, reclaimStale ? 1 : 0, STALE_IN_PROGRESS_MINUTES], { isMutation: true, description: 'V2SendService.tryAtomicClaimLog' }, contextUser);
|
|
1885
|
+
return { Result: rows.length > 0 ? 'claimed' : 'already-claimed' };
|
|
1886
|
+
}
|
|
1887
|
+
catch (err) {
|
|
1888
|
+
return { Result: 'failed', Detail: err instanceof Error ? err.message : String(err) };
|
|
1889
|
+
}
|
|
1890
|
+
}
|
|
1891
|
+
async claimDueDeferredLogs(batchSize, bookkeepingUser) {
|
|
1892
|
+
const provider = CommunicationEngineBase.Instance.ProviderToUse;
|
|
1893
|
+
const rv = this.getRunView();
|
|
1894
|
+
if (isSqlCapableProvider(provider)) {
|
|
1895
|
+
const schema = provider.MJCoreSchemaName ?? '__mj';
|
|
1896
|
+
const claimedIds = await provider.ExecuteSQL(
|
|
1897
|
+
// OUTPUT INTO a table variable for the same trigger reason as tryAtomicClaimLog.
|
|
1898
|
+
`DECLARE @Claimed TABLE (ID UNIQUEIDENTIFIER);
|
|
1899
|
+
WITH Due AS (
|
|
1900
|
+
SELECT TOP (@p0) ID
|
|
1901
|
+
FROM [${schema}].[CommunicationLog]
|
|
1902
|
+
WHERE Status = 'Pending' AND ScheduledAt IS NOT NULL AND ScheduledAt <= GETUTCDATE() AND Direction = 'Sending'
|
|
1903
|
+
ORDER BY ScheduledAt ASC
|
|
1904
|
+
)
|
|
1905
|
+
UPDATE target
|
|
1906
|
+
SET Status = 'In-Progress', __mj_UpdatedAt = GETUTCDATE()
|
|
1907
|
+
OUTPUT INSERTED.ID INTO @Claimed
|
|
1908
|
+
FROM [${schema}].[CommunicationLog] target
|
|
1909
|
+
INNER JOIN Due ON target.ID = Due.ID;
|
|
1910
|
+
SELECT ID FROM @Claimed;`, [batchSize], { isMutation: true, description: 'V2SendService.claimDueDeferredLogs' }, bookkeepingUser);
|
|
1911
|
+
if (claimedIds.length === 0) {
|
|
1912
|
+
return [];
|
|
1913
|
+
}
|
|
1914
|
+
const idList = claimedIds.map((r) => `'${EscapeSQLString(r.ID)}'`).join(',');
|
|
1915
|
+
const loadedRes = await rv.RunView({
|
|
1916
|
+
EntityName: 'MJ: Communication Logs',
|
|
1917
|
+
ExtraFilter: `ID IN (${idList})`,
|
|
1918
|
+
OrderBy: 'ScheduledAt ASC',
|
|
1919
|
+
ResultType: 'entity_object',
|
|
1920
|
+
}, bookkeepingUser);
|
|
1921
|
+
if (!loadedRes.Success) {
|
|
1922
|
+
throw new Error(`Failed loading claimed deferred logs: ${loadedRes.ErrorMessage ?? 'RunView failed'}`);
|
|
1923
|
+
}
|
|
1924
|
+
return loadedRes.Results;
|
|
1925
|
+
}
|
|
1926
|
+
// Without ExecuteSQL two sweepers could both read-then-save the same due log and both send it.
|
|
1927
|
+
LogError('V2SendService.claimDueDeferredLogs: the provider has no ExecuteSQL, so due logs cannot be claimed atomically; none were sent');
|
|
1928
|
+
return [];
|
|
1929
|
+
}
|
|
1930
|
+
}
|
|
1931
|
+
/**
|
|
1932
|
+
* Minutes a log may stay In-Progress with no ProviderMessageID before it is treated as stuck: its
|
|
1933
|
+
* worker died, or saving the log failed after the provider call, so the send's outcome is unknown.
|
|
1934
|
+
*/
|
|
1935
|
+
const STALE_IN_PROGRESS_MINUTES = 15;
|
|
1936
|
+
/** Delivery guarantee used when no envelope, run, sender or provider sets one. */
|
|
1937
|
+
export const DEFAULT_DELIVERY_GUARANTEE = 'At Most Once';
|
|
1938
|
+
/** True when an In-Progress log with no ProviderMessageID has been stuck past the stale threshold. */
|
|
1939
|
+
export function IsStaleInProgressLog(log, now = Date.now()) {
|
|
1940
|
+
const updatedAtMs = log.__mj_UpdatedAt ? new Date(log.__mj_UpdatedAt).getTime() : NaN;
|
|
1941
|
+
return Number.isFinite(updatedAtMs) && now - updatedAtMs > STALE_IN_PROGRESS_MINUTES * 60_000;
|
|
1942
|
+
}
|
|
1943
|
+
/**
|
|
1944
|
+
* Returns the first delivery guarantee that is set, in precedence order (envelope, run, sender,
|
|
1945
|
+
* ancestor senders nearest first, provider), or {@link DEFAULT_DELIVERY_GUARANTEE}.
|
|
1946
|
+
*/
|
|
1947
|
+
export function PickDeliveryGuarantee(candidates) {
|
|
1948
|
+
for (const candidate of candidates) {
|
|
1949
|
+
if (candidate)
|
|
1950
|
+
return candidate;
|
|
1951
|
+
}
|
|
1952
|
+
return DEFAULT_DELIVERY_GUARANTEE;
|
|
1953
|
+
}
|
|
1954
|
+
/**
|
|
1955
|
+
* Picks the principal-preference row that governs a send, from rows for the sending sender, its
|
|
1956
|
+
* ancestors (`senderChainIds[0]` is the sender itself) and sender-less rows.
|
|
1957
|
+
*
|
|
1958
|
+
* - An opt-out anywhere in the chain wins: someone who opted out under a parent sender has not
|
|
1959
|
+
* opted back in just because a child sender sends.
|
|
1960
|
+
* - Otherwise the nearest row wins: the sender's own, then the closest ancestor, then sender-less.
|
|
1961
|
+
*/
|
|
1962
|
+
export function PickEffectivePrincipalPreference(rows, senderChainIds) {
|
|
1963
|
+
if (rows.length === 0)
|
|
1964
|
+
return undefined;
|
|
1965
|
+
const optOut = rows.find((r) => r.State === 'Opted Out');
|
|
1966
|
+
if (optOut)
|
|
1967
|
+
return optOut;
|
|
1968
|
+
const chainDepth = new Map();
|
|
1969
|
+
senderChainIds.forEach((id, index) => {
|
|
1970
|
+
const key = NormalizeUUID(id);
|
|
1971
|
+
if (!chainDepth.has(key))
|
|
1972
|
+
chainDepth.set(key, index);
|
|
1973
|
+
});
|
|
1974
|
+
const depth = (r) => {
|
|
1975
|
+
if (r.CommunicationSenderID === null)
|
|
1976
|
+
return senderChainIds.length;
|
|
1977
|
+
return chainDepth.get(NormalizeUUID(r.CommunicationSenderID)) ?? senderChainIds.length + 1;
|
|
1978
|
+
};
|
|
1979
|
+
return [...rows].sort((a, b) => depth(a) - depth(b))[0];
|
|
1980
|
+
}
|
|
1981
|
+
/** Attempts to record a send's result on its log before giving up (see `saveLogAfterSend`). */
|
|
1982
|
+
const MAX_POST_SEND_SAVE_ATTEMPTS = 3;
|
|
1983
|
+
/**
|
|
1984
|
+
* Describes a finished chunk from its send result. A chunk is `Failed` only when it was refused
|
|
1985
|
+
* before any recipient was processed (a pre-send check failed, or the send threw); a chunk whose
|
|
1986
|
+
* recipients were individually blocked or failed is still `Complete`.
|
|
1987
|
+
*/
|
|
1988
|
+
export function DescribeChunkOutcome(recipientCount, result, thrown) {
|
|
1989
|
+
if (thrown !== undefined) {
|
|
1990
|
+
return { Status: 'Failed', RecipientCount: recipientCount, ErrorMessage: thrown instanceof Error ? thrown.message : String(thrown) };
|
|
1991
|
+
}
|
|
1992
|
+
if (!result) {
|
|
1993
|
+
return { Status: 'Failed', RecipientCount: recipientCount, ErrorMessage: 'The chunk returned no result' };
|
|
1994
|
+
}
|
|
1995
|
+
// An inline chunk that reached its recipients always reports per-recipient Outcomes; a pre-send
|
|
1996
|
+
// refusal reports none (and counts every recipient as blocked), so the counts cannot be used here.
|
|
1997
|
+
const processed = (result.Outcomes?.length ?? 0) > 0;
|
|
1998
|
+
if (!result.Success && !processed) {
|
|
1999
|
+
return { Status: 'Failed', RecipientCount: recipientCount, ErrorMessage: result.ErrorMessage ?? 'The chunk was refused' };
|
|
2000
|
+
}
|
|
2001
|
+
return { Status: 'Complete', RecipientCount: recipientCount };
|
|
2002
|
+
}
|
|
2003
|
+
/** Endpoint IDs per `IN (...)` list when preloading a run's logs. */
|
|
2004
|
+
const RUN_LOG_ENDPOINT_CHUNK = 200;
|
|
2005
|
+
function isSqlCapableProvider(provider) {
|
|
2006
|
+
return (typeof provider === 'object' &&
|
|
2007
|
+
provider !== null &&
|
|
2008
|
+
'ExecuteSQL' in provider &&
|
|
2009
|
+
typeof provider.ExecuteSQL === 'function');
|
|
2010
|
+
}
|
|
2011
|
+
/** Reads a deferred log's stored message. Undefined when it is missing or not valid JSON. */
|
|
2012
|
+
function parseDeferredPayload(raw) {
|
|
2013
|
+
if (!raw)
|
|
2014
|
+
return undefined;
|
|
2015
|
+
try {
|
|
2016
|
+
const parsed = JSON.parse(raw);
|
|
2017
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : undefined;
|
|
2018
|
+
}
|
|
2019
|
+
catch {
|
|
2020
|
+
return undefined;
|
|
2021
|
+
}
|
|
2022
|
+
}
|
|
2023
|
+
/** Reads a log's caller correlation data back into the object the caller passed. */
|
|
2024
|
+
function parseCorrelationData(raw) {
|
|
2025
|
+
if (!raw)
|
|
2026
|
+
return undefined;
|
|
2027
|
+
try {
|
|
2028
|
+
const parsed = JSON.parse(raw);
|
|
2029
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : undefined;
|
|
2030
|
+
}
|
|
2031
|
+
catch {
|
|
2032
|
+
return undefined;
|
|
2033
|
+
}
|
|
2034
|
+
}
|
|
2035
|
+
//# sourceMappingURL=V2SendService.js.map
|