@aglyn/plugins-outreach 1.15.2 → 1.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aglyn/plugins-outreach",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.16.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"homepage": "https://aglyn.com",
|
|
6
6
|
"repository": {
|
|
@@ -25,19 +25,19 @@
|
|
|
25
25
|
"./package.json": "./package.json"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@aglyn/aglyn": "1.
|
|
29
|
-
"@aglyn/shared-data-mdi": "1.
|
|
30
|
-
"@aglyn/shared-ui-email-campaigns": "1.
|
|
31
|
-
"@aglyn/shared-ui-jsx": "1.
|
|
32
|
-
"@aglyn/shared-ui-next": "1.
|
|
33
|
-
"@aglyn/shared-ui-snackstack": "1.
|
|
34
|
-
"@aglyn/shared-util-email": "1.
|
|
35
|
-
"@aglyn/shared-util-http": "1.
|
|
36
|
-
"@aglyn/shared-util-timestamp": "1.
|
|
37
|
-
"@aglyn/shared-util-tools": "1.
|
|
38
|
-
"@aglyn/tenant-data-admin": "1.
|
|
39
|
-
"@aglyn/tenant-feature-instance": "1.
|
|
40
|
-
"@aglyn/tenant-runtime": "1.
|
|
28
|
+
"@aglyn/aglyn": "1.16.0",
|
|
29
|
+
"@aglyn/shared-data-mdi": "1.16.0",
|
|
30
|
+
"@aglyn/shared-ui-email-campaigns": "1.16.0",
|
|
31
|
+
"@aglyn/shared-ui-jsx": "1.16.0",
|
|
32
|
+
"@aglyn/shared-ui-next": "1.16.0",
|
|
33
|
+
"@aglyn/shared-ui-snackstack": "1.16.0",
|
|
34
|
+
"@aglyn/shared-util-email": "1.16.0",
|
|
35
|
+
"@aglyn/shared-util-http": "1.16.0",
|
|
36
|
+
"@aglyn/shared-util-timestamp": "1.16.0",
|
|
37
|
+
"@aglyn/shared-util-tools": "1.16.0",
|
|
38
|
+
"@aglyn/tenant-data-admin": "1.16.0",
|
|
39
|
+
"@aglyn/tenant-feature-instance": "1.16.0",
|
|
40
|
+
"@aglyn/tenant-runtime": "1.16.0",
|
|
41
41
|
"@swc/helpers": "0.5.23"
|
|
42
42
|
},
|
|
43
43
|
"peerDependencies": {
|
|
@@ -40,6 +40,7 @@ import { noteOutreachMailboxReconnectRequired } from "./mailbox-notices.js";
|
|
|
40
40
|
import { stampRecordEmailReply } from "@aglyn/aglyn/plugin-manager/plugin-record-email-state";
|
|
41
41
|
import { fileOutreachEmail, fileOutreachNote, fileOutreachTask, markOutreachEmailDelivery } from "./timeline.js";
|
|
42
42
|
import { outreachUnsubscribeMailbox } from "./unsubscribe-link.js";
|
|
43
|
+
import { watchedEnrollmentsOfOrg } from "./watched-enrollments.js";
|
|
43
44
|
/*==========================================
|
|
44
45
|
* THE SYNC JOB (AGL-2981): every fifteen minutes, on the console.
|
|
45
46
|
*
|
|
@@ -147,10 +148,13 @@ const ENROLLMENT_HANDLED_MAX = 100;
|
|
|
147
148
|
const orgSnapshot = await firestore.collection('orgs').doc(orgId).get();
|
|
148
149
|
const org = orgSnapshot.exists ? orgSnapshot.data() : null;
|
|
149
150
|
if (!org || await deps.orgRefusal(orgId, org)) continue;
|
|
150
|
-
// Every enrollment the organization is still watching, read once per
|
|
151
|
-
//
|
|
152
|
-
|
|
153
|
-
const
|
|
151
|
+
// Every enrollment the organization is still watching, read once per run
|
|
152
|
+
// for every mailbox and the possible-reply step together, and again only
|
|
153
|
+
// after the run writes an enrollment (`./watched-enrollments`, AGL-4121).
|
|
154
|
+
const watched = watchedEnrollmentsOfOrg({
|
|
155
|
+
org: ()=>readWatchedEnrollmentDocs(firestore, orgId, context.nowMs),
|
|
156
|
+
mailbox: (mailboxId)=>readWatchedEnrollmentDocs(firestore, orgId, context.nowMs, mailboxId)
|
|
157
|
+
});
|
|
154
158
|
for (const mailbox of mailboxes){
|
|
155
159
|
if (deps.now() >= context.deadlineMs) break;
|
|
156
160
|
try {
|
|
@@ -159,7 +163,7 @@ const ENROLLMENT_HANDLED_MAX = 100;
|
|
|
159
163
|
mailbox,
|
|
160
164
|
report,
|
|
161
165
|
nowMs: context.nowMs,
|
|
162
|
-
|
|
166
|
+
watched
|
|
163
167
|
});
|
|
164
168
|
report.mailboxes += 1;
|
|
165
169
|
} catch (error) {
|
|
@@ -225,14 +229,15 @@ async function syncMailbox(deps, firestore, input) {
|
|
|
225
229
|
sequences: new Map(),
|
|
226
230
|
delta: emptyOutreachHealthDelta(),
|
|
227
231
|
report,
|
|
228
|
-
nowMs
|
|
232
|
+
nowMs,
|
|
233
|
+
touched: input.watched.touched
|
|
229
234
|
};
|
|
230
235
|
// The enrollments this mailbox is writing to, by thread and by address.
|
|
231
|
-
const watched = await
|
|
236
|
+
const watched = await input.watched.forMailbox(mailbox.id);
|
|
232
237
|
const byThread = new Map();
|
|
233
238
|
const byAddress = new Map();
|
|
234
239
|
const watchedEnrollments = [];
|
|
235
|
-
for (const doc of watched
|
|
240
|
+
for (const doc of watched){
|
|
236
241
|
var _enrollment_lastSentAtMs, _known_lastSentAtMs;
|
|
237
242
|
const enrollment = readStoredOutreachEnrollment(doc.id, doc.data());
|
|
238
243
|
if (!enrollment) continue;
|
|
@@ -304,6 +309,7 @@ async function syncMailbox(deps, firestore, input) {
|
|
|
304
309
|
if (address && !context.selfAddresses.includes(address)) {
|
|
305
310
|
var _byAddress_get;
|
|
306
311
|
const enrollment = (_byAddress_get = byAddress.get(address)) != null ? _byAddress_get : null;
|
|
312
|
+
context.touched();
|
|
307
313
|
await recordOutreachOptOut(deps, {
|
|
308
314
|
orgId,
|
|
309
315
|
email: address,
|
|
@@ -344,7 +350,7 @@ async function syncMailbox(deps, firestore, input) {
|
|
|
344
350
|
// the person writing to another of our mailboxes, or a colleague.
|
|
345
351
|
const leftover = inbound.filter(fresh).slice(0, POSSIBLE_REPLY_READS);
|
|
346
352
|
if (leftover.length) {
|
|
347
|
-
const enrollments = await input.
|
|
353
|
+
const enrollments = enrollmentsOf(await input.watched.forOrg());
|
|
348
354
|
for (const stub of leftover){
|
|
349
355
|
if (!fresh(stub)) continue;
|
|
350
356
|
const metadata = await context.client.getMessage(stub.id, {
|
|
@@ -436,9 +442,17 @@ async function syncMailbox(deps, firestore, input) {
|
|
|
436
442
|
});
|
|
437
443
|
}
|
|
438
444
|
}
|
|
439
|
-
/**
|
|
440
|
-
|
|
441
|
-
|
|
445
|
+
/**
|
|
446
|
+
* Every enrollment of an organization written to within the watch window,
|
|
447
|
+
* or, given a mailbox, that mailbox's: the narrow read a mailbox falls back
|
|
448
|
+
* to once the run has written an enrollment (`./watched-enrollments`).
|
|
449
|
+
*/ async function readWatchedEnrollmentDocs(firestore, orgId, nowMs, mailboxId) {
|
|
450
|
+
const enrollments = outreachOrgCollection(firestore, orgId, 'enrollments');
|
|
451
|
+
const query = mailboxId === undefined ? enrollments.where('lastSentAtMs', '>=', nowMs - OUTREACH_SYNC_WATCH_MS) : enrollments.where('mailboxId', '==', mailboxId).where('lastSentAtMs', '>=', nowMs - OUTREACH_SYNC_WATCH_MS);
|
|
452
|
+
return (await query.get()).docs;
|
|
453
|
+
}
|
|
454
|
+
/** The enrollments a set of watched documents holds, unreadable ones left out. */ function enrollmentsOf(docs) {
|
|
455
|
+
return docs.map((doc)=>readStoredOutreachEnrollment(doc.id, doc.data())).filter((enrollment)=>enrollment !== null);
|
|
442
456
|
}
|
|
443
457
|
/** The sequence an enrollment runs through, read once per run. */ async function sequenceOf(context, sequenceId) {
|
|
444
458
|
var _context_sequences_get;
|
|
@@ -490,6 +504,9 @@ async function syncMailbox(deps, firestore, input) {
|
|
|
490
504
|
});
|
|
491
505
|
const freshIds = decision.classifications.map((classification)=>classification.messageId).filter(Boolean);
|
|
492
506
|
if (!freshIds.length) return;
|
|
507
|
+
// Everything below may write this enrollment and, through an opt-out, the
|
|
508
|
+
// address's others in the organization.
|
|
509
|
+
context.touched();
|
|
493
510
|
// What they wrote, kept on the enrollment so the console can show it and
|
|
494
511
|
// answer it in the thread (AGL-4020) — every message of theirs among
|
|
495
512
|
// these, so a thread read whole also keeps a reply synced before they
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/runtime/sync-job.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { normalizeContactEmail } from '@aglyn/aglyn/app-utils/contacts'\nimport { isPublicMailboxDomain } from '@aglyn/aglyn/app-utils/crm'\nimport { emailAddressOf, emailExcerpt } from '@aglyn/aglyn/app-utils/email-text'\nimport { outreachMessageIdHeader } from '../engine/compose'\nimport { readOutreachDeliveryReport } from '../engine/delivery-status'\nimport { outreachEmailDomain } from '../engine/do-not-contact-domain'\nimport { outreachStoppedEntry } from '../engine/enrollment-activity'\nimport type { OutreachEnrollmentEvent } from '../engine/enrollment-state'\nimport { isOutreachGatewayBlock, outreachGatewayBlockDetail } from '../engine/gateway-block'\nimport { mergeOutreachInboundMessages, outreachInboundMessagesOf } from '../engine/manual-reply'\nimport {\n matchOutreachPossibleReply,\n outreachPossibleReplyNote,\n outreachPossibleReplyTitle,\n} from '../engine/possible-reply'\nimport { effectiveOutreachWindow, postponeOutreachForAutoReply } from '../engine/schedule'\nimport {\n decideOutreachThread,\n outreachAutoReplyEvidence,\n type OutreachMessageClassification,\n type OutreachThreadDecision,\n} from '../engine/thread-classification'\nimport { outreachHeader, outreachThreadMessageFromGmail, type OutreachThreadMessage } from '../engine/thread-message'\nimport { mailboxRef } from '../mailboxes/mailbox-credentials'\nimport {\n OUTREACH_COLLECTIONS,\n type OutreachEnrollment,\n type OutreachMailbox,\n type OutreachSequence,\n} from '../model/outreach.types'\nimport { addOutreachDoNotContact, addOutreachDoNotContactDomain } from '../storage/do-not-contact-store'\nimport {\n outreachEnrollmentLink,\n outreachOrgCollection,\n readStoredOutreachEnrollment,\n readStoredOutreachMailbox,\n readStoredOutreachSequence,\n} from '../storage/outreach-records'\nimport type { OutreachMailClient, OutreachMailSearch, OutreachMailStub } from '../transport/mail-client'\nimport { GmailTransportError, isReconnectRequired } from '../transport/gmail-errors'\nimport { creditOutreachReply } from './campaign-credit'\nimport { applyOutreachEvent, recordOutreachOptOut } from './enrollment-events'\nimport { creditOutreachGatewayDeliveries, recordOutreachGatewayBlock } from './gateway-ledger'\nimport { outreachMailboxSendingDomain } from '../storage/domain-intel-store'\nimport {\n applyOutreachMailboxHealth,\n emptyOutreachHealthDelta,\n type OutreachMailboxHealthDelta,\n} from './mailbox-health-store'\nimport { noteOutreachMailboxReconnectRequired } from './mailbox-notices'\nimport type { OutreachRuntimeDeps } from './runtime-deps'\nimport { stampRecordEmailReply } from '@aglyn/aglyn/plugin-manager/plugin-record-email-state'\nimport { fileOutreachEmail, fileOutreachNote, fileOutreachTask, markOutreachEmailDelivery } from './timeline'\nimport { outreachUnsubscribeMailbox } from './unsubscribe-link'\n\n/*==========================================\n * THE SYNC JOB (AGL-2981): every fifteen minutes, on the console.\n *\n * For each connected or paused mailbox, what came back since the last run —\n * read with `format=full`, turned into the engine's message shape and\n * classified by `decideOutreachThread`:\n *\n * - a REPLY stops the enrollment, files the message on the contact's\n * timeline (once per `Message-ID`, under the capture address's own id for\n * it) and gives the rep the task \"Reply from <name>\";\n * - every message the person wrote — a reply, an automatic answer, an\n * opt-out — is kept on the enrollment, its sender, time, threading ids\n * and trimmed text, for the console to show and answer (AGL-4020);\n * - an OUT-OF-OFFICE postpones the next step a working week from the reply;\n * - an OPT-OUT — a reply asking to be left alone, or a message to the\n * `+unsubscribe` address the `mailto:` names — puts the address on the\n * organization's do-not-contact list and off the site's `sales` topic,\n * and stops every open enrollment of it;\n * - a HARD BOUNCE stops the enrollment, files the address on the platform's\n * suppression list and the do-not-contact list — and, when its diagnostic\n * reads as the domain's mail gateway refusing the sender rather than one\n * address being unknown (`engine/gateway-block`, AGL-3244), files the\n * DOMAIN on the do-not-contact list too, and says so on the enrollment —\n * and counts the block on the gateway ledger (AGL-3326), under the\n * gateway the bounce's `Remote-MTA` names.\n *\n * And once the mail is read, every email step of a watched enrollment that\n * is a day old with no bounce against it is credited to the ledger as\n * delivered (`./gateway-ledger`): the silence that says a gateway let the\n * sender through.\n *\n * Every verdict a list takes is said on the record the person is as well\n * (AGL-3245): the lead and the contact carry `emailState` through the\n * platform's stamp, and a bounce or a complaint lands on the send's own\n * timeline entry, so a member reading the record sees what the runtime saw.\n *\n * Four reads find those, each narrowed by the provider rather than read in\n * full (`OutreachMailSearch`, AGL-3489):\n * the threads of this mailbox's enrollments that have new mail; delivery\n * reports outside those threads (a receiving server's own bounce), by\n * searching for the mail systems that send them; messages to the\n * unsubscribe address; and messages from the people this mailbox is\n * writing to, in a thread of their own.\n *\n * Then what is left of the new mail is read for POSSIBLE replies (AGL-4088,\n * `engine/possible-reply`): a person writing to another of the\n * organization's mailboxes, or a colleague at their company writing. Those\n * stop nothing; each files the task \"Possible reply from …\" for a person to\n * read.\n *\n * Every write it makes is idempotent — the do-not-contact list keeps its\n * first entry, a topic opt-out keeps its first moment, a timeline entry is\n * filed once per message — and the messages it handled are marked AFTER\n * their effects, on the enrollment and on the mailbox, so a run that dies\n * part-way repeats harmless work rather than skipping some. The mailbox's\n * health takes the run's bounces and complaints in one write at the end,\n * which is where it pauses itself.\n *==========================================*/\n\nexport { OUTREACH_SYNC_JOB_ID } from '../constants/runtime-jobs'\n\n/** The furthest back a run reads: a mailbox's first run, or one that fell behind. */\nexport const OUTREACH_SYNC_LOOKBACK_MS = 7 * 24 * 60 * 60_000\n\n/** How far a run reads back past the previous one, for mail Gmail indexed late. */\nexport const OUTREACH_SYNC_OVERLAP_MS = 2 * 60 * 60_000\n\n/** How long after its last send an enrollment's mail is still watched. */\nexport const OUTREACH_SYNC_WATCH_MS = 45 * 24 * 60 * 60_000\n\n/** The most pages of one search a run reads. */\nconst SEARCH_PAGES = 5\n/** Handled message ids a mailbox keeps, and an enrollment keeps. */\nconst MAILBOX_HANDLED_MAX = 500\n\n/** How far a quiet mailbox's window may lag before its document is moved anyway. */\nconst MAILBOX_SYNC_WINDOW_REFRESH_MS = 60 * 60_000\nconst ENROLLMENT_HANDLED_MAX = 100\n/** Addresses in one `from:` search. */\nconst FROM_CHUNK = 15\n/** Messages one mailbox's run reads for a possible reply (AGL-4088). */\nconst POSSIBLE_REPLY_READS = 60\n/** The headers a possible reply is judged by: who, what, and whether a machine sent it. */\nconst POSSIBLE_REPLY_HEADERS = ['From', 'Subject', 'Auto-Submitted', 'X-Autoreply', 'X-Autorespond', 'Precedence']\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport interface OutreachSyncReport {\n [key: string]: number\n mailboxes: number\n threads: number\n replies: number\n optOuts: number\n bounces: number\n /** Hard bounces that read as a gateway block, each filing its domain (AGL-3244). */\n gatewayBlocks: number\n /** Email steps a day old with no bounce, credited to the gateway ledger (AGL-3326). */\n deliveries: number\n postponed: number\n paused: number\n /** Messages filed as a possible reply for a person to read (AGL-4088). */\n possibleReplies: number\n}\n\ninterface SyncContext {\n deps: OutreachRuntimeDeps\n firestore: Firestore\n orgId: string\n mailbox: OutreachMailbox\n client: OutreachMailClient\n selfAddresses: string[]\n unsubscribeAddress: string | null\n sequences: Map<string, OutreachSequence | null>\n delta: OutreachMailboxHealthDelta\n report: OutreachSyncReport\n nowMs: number\n}\n\n/** Runs the sync job once — see the module note. */\nexport async function runOutreachSyncJob(\n deps: OutreachRuntimeDeps,\n context: { nowMs: number; deadlineMs: number },\n): Promise<OutreachSyncReport> {\n const firestore = deps.firestore()\n const report: OutreachSyncReport = {\n mailboxes: 0,\n threads: 0,\n replies: 0,\n optOuts: 0,\n bounces: 0,\n gatewayBlocks: 0,\n deliveries: 0,\n postponed: 0,\n paused: 0,\n possibleReplies: 0,\n }\n const all = await firestore.collectionGroup(OUTREACH_COLLECTIONS.mailboxes).get()\n const byOrg = new Map<string, OutreachMailbox[]>()\n for (const doc of all.docs) {\n const orgId = doc.ref.parent.parent?.id\n const mailbox = readStoredOutreachMailbox(doc.id, doc.data())\n if (!orgId || !mailbox || (mailbox.status !== 'connected' && mailbox.status !== 'paused')) continue\n byOrg.set(orgId, [...(byOrg.get(orgId) ?? []), mailbox])\n }\n for (const [orgId, mailboxes] of byOrg) {\n if (deps.now() >= context.deadlineMs) break\n const orgSnapshot = await firestore.collection('orgs').doc(orgId).get()\n const org = (orgSnapshot.exists ? orgSnapshot.data() : null) as Record<string, unknown> | null\n if (!org || (await deps.orgRefusal(orgId, org))) continue\n // Every enrollment the organization is still watching, read once per\n // run and only when a mailbox has mail left to match (AGL-4088).\n let orgWatched: Promise<OutreachEnrollment[]> | null = null\n const watchedInOrg = () => (orgWatched ??= readWatchedEnrollments(firestore, orgId, context.nowMs))\n for (const mailbox of mailboxes) {\n if (deps.now() >= context.deadlineMs) break\n try {\n await syncMailbox(deps, firestore, { orgId, mailbox, report, nowMs: context.nowMs, watchedInOrg })\n report.mailboxes += 1\n } catch (error) {\n // One mailbox's failure is its own; the next mailbox is read. A grant\n // Google refused is the mailbox's to reconnect.\n if (isReconnectRequired(error)) {\n await noteOutreachMailboxReconnectRequired(deps, {\n orgId,\n mailboxId: mailbox.id,\n errorCode: error instanceof GmailTransportError ? error.code : 'invalid_grant',\n nowMs: context.nowMs,\n })\n }\n console.error('[outreach] syncing a mailbox failed', error)\n }\n }\n }\n return report\n}\n\n/** Every stub a search finds, a few pages deep. */\nasync function search(client: OutreachMailClient, criteria: OutreachMailSearch): Promise<OutreachMailStub[]> {\n const found: OutreachMailStub[] = []\n let pageToken: string | null = null\n for (let page = 0; page < SEARCH_PAGES; page += 1) {\n const list = await client.searchMessages(criteria, { maxResults: 100, pageToken })\n found.push(...list.messages.filter((message) => message.id))\n pageToken = list.nextPageToken\n if (!pageToken) break\n }\n return found\n}\n\nasync function syncMailbox(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n input: {\n orgId: string\n mailbox: OutreachMailbox\n report: OutreachSyncReport\n nowMs: number\n watchedInOrg: () => Promise<OutreachEnrollment[]>\n },\n): Promise<void> {\n const { orgId, mailbox, report, nowMs } = input\n const opened = await deps.openMailbox(mailbox.id)\n if (opened.ok === false) {\n if (opened.reason !== 'not-configured') {\n await noteOutreachMailboxReconnectRequired(deps, {\n orgId,\n mailboxId: mailbox.id,\n errorCode: opened.reason,\n nowMs,\n })\n }\n return\n }\n const unsubscribe = outreachUnsubscribeMailbox(mailbox.email)\n const context: SyncContext = {\n deps,\n firestore,\n orgId,\n mailbox,\n client: opened.client,\n selfAddresses: [\n mailbox.email,\n mailbox.sendAs,\n ...(mailbox.sendAsOptions ?? []).map((option) => option.email),\n ].filter(Boolean),\n unsubscribeAddress: unsubscribe?.address ?? null,\n sequences: new Map(),\n delta: emptyOutreachHealthDelta(),\n report,\n nowMs,\n }\n\n // The enrollments this mailbox is writing to, by thread and by address.\n const watched = await outreachOrgCollection(firestore, orgId, 'enrollments')\n .where('mailboxId', '==', mailbox.id)\n .where('lastSentAtMs', '>=', nowMs - OUTREACH_SYNC_WATCH_MS)\n .get()\n const byThread = new Map<string, OutreachEnrollment>()\n const byAddress = new Map<string, OutreachEnrollment>()\n const watchedEnrollments: OutreachEnrollment[] = []\n for (const doc of watched.docs) {\n const enrollment = readStoredOutreachEnrollment(doc.id, doc.data())\n if (!enrollment) continue\n watchedEnrollments.push(enrollment)\n for (const threadId of enrollment.gmailThreadIds) byThread.set(threadId, enrollment)\n const known = byAddress.get(enrollment.email)\n if (!known || (enrollment.lastSentAtMs ?? 0) > (known.lastSentAtMs ?? 0)) byAddress.set(enrollment.email, enrollment)\n }\n\n const sinceMs = Math.max(Number(mailbox.sync?.throughMs) || 0, nowMs - OUTREACH_SYNC_LOOKBACK_MS) - OUTREACH_SYNC_OVERLAP_MS\n // Every message this run or an earlier one handled outside an enrollment's\n // thread; one message is handled once however many searches find it.\n const handled = new Set(mailbox.sync?.handledMessageIds ?? [])\n const newlyHandled: string[] = []\n const markHandled = (id: string) => {\n if (handled.has(id)) return\n handled.add(id)\n newlyHandled.push(id)\n }\n const fresh = (stub: OutreachMailStub) => !handled.has(stub.id) && !byThread.has(stub.threadId)\n\n // 1. The enrollments' own threads that have new mail.\n const inbound = await search(context.client, { afterMs: sinceMs, notFromSelf: true })\n for (const threadId of new Set(inbound.map((stub) => stub.threadId))) {\n const enrollment = byThread.get(threadId)\n if (!enrollment) continue\n const thread = await context.client.getFullThread(threadId)\n report.threads += 1\n await applyMessages(context, enrollment, thread.messages.map(outreachThreadMessageFromGmail))\n }\n\n // 2. Delivery reports outside those threads: a receiving server's bounce.\n for (const stub of await search(context.client, { afterMs: sinceMs, from: ['mailer-daemon', 'postmaster'] })) {\n if (!fresh(stub)) continue\n const message = outreachThreadMessageFromGmail(await context.client.getFullMessage(stub.id))\n const delivery = readOutreachDeliveryReport(message)\n if (delivery?.kind === 'hard') {\n for (const address of delivery.failedAddresses) {\n const enrollment = byAddress.get(address)\n if (enrollment) await applyMessages(context, enrollment, [message])\n }\n }\n markHandled(stub.id)\n }\n\n // 3. Messages to the unsubscribe address: whoever wrote asked to leave.\n if (unsubscribe) {\n for (const stub of await search(context.client, { afterMs: sinceMs, to: unsubscribe.address })) {\n if (handled.has(stub.id)) continue\n const metadata = await context.client.getMessage(stub.id, { metadataHeaders: ['From'] })\n const from = emailAddressOf(metadata.headers.find((header) => header.name.toLowerCase() === 'from')?.value ?? '')\n const address = normalizeContactEmail(from)\n if (address && !context.selfAddresses.includes(address)) {\n const enrollment = byAddress.get(address) ?? null\n await recordOutreachOptOut(deps, {\n orgId,\n email: address,\n source: 'unsubscribe',\n enrollment,\n hostIds: enrollment ? [enrollment.hostId] : [],\n detail: 'Wrote to the unsubscribe address.',\n nowMs,\n })\n report.optOuts += 1\n }\n markHandled(stub.id)\n }\n }\n\n // 4. The people this mailbox writes to, answering in a thread of their own.\n const addresses = [...byAddress.keys()]\n for (let start = 0; start < addresses.length; start += FROM_CHUNK) {\n const chunk = addresses.slice(start, start + FROM_CHUNK)\n for (const stub of await search(context.client, { afterMs: sinceMs, from: chunk })) {\n if (!fresh(stub)) continue\n const message = outreachThreadMessageFromGmail(await context.client.getFullMessage(stub.id))\n const enrollment = byAddress.get(normalizeContactEmail(emailAddressOf(message.from)) ?? '')\n if (enrollment) await applyMessages(context, enrollment, [message])\n markHandled(stub.id)\n }\n }\n\n // 4b. What is left of the new mail, read for a possible reply (AGL-4088):\n // the person writing to another of our mailboxes, or a colleague.\n const leftover = inbound.filter(fresh).slice(0, POSSIBLE_REPLY_READS)\n if (leftover.length) {\n const enrollments = await input.watchedInOrg()\n for (const stub of leftover) {\n if (!fresh(stub)) continue\n const metadata = await context.client.getMessage(stub.id, { metadataHeaders: POSSIBLE_REPLY_HEADERS })\n const headers = Object.fromEntries(metadata.headers.map((entry) => [entry.name, entry.value]))\n const header = (name: string) => outreachHeader({ headers }, name)\n const fromHeader = header('From')\n const sender = normalizeContactEmail(emailAddressOf(fromHeader))\n const subject = header('Subject')\n markHandled(stub.id)\n if (!sender || context.selfAddresses.includes(sender)) continue\n if (outreachAutoReplyEvidence({ headers, subject })) continue\n const match = matchOutreachPossibleReply(sender, { mailboxId: mailbox.id, enrollments })\n if (!match) continue\n const enrolled = match.enrollment\n try {\n await fileOutreachTask(deps, {\n orgId,\n hostId: enrolled.hostId,\n link: outreachEnrollmentLink(enrolled),\n dedupeKey: `possible-reply:${stub.id}`,\n title: outreachPossibleReplyTitle(fromHeader.replace(/<[^>]*>/, '').replace(/\"/g, '').trim(), sender),\n notes: outreachPossibleReplyNote({\n reason: match.reason,\n enrolledName: enrolled.contactName || enrolled.email,\n receivedBy: mailbox.sendAs || mailbox.email,\n excerpt: [subject && `Subject: ${subject}`, metadata.snippet].filter(Boolean).join('\\n'),\n }),\n kind: 'email',\n dueAtMs: nowMs,\n assigneeUid: mailbox.connectedByUid,\n })\n report.possibleReplies += 1\n } catch (error) {\n console.error('[outreach] the possible-reply task could not be filed', error)\n }\n }\n }\n\n // 5. What went through: a day of silence after a send is a delivery\n // (AGL-3326), judged on the enrollments as this run left them.\n try {\n report.deliveries += await creditOutreachGatewayDeliveries(firestore, {\n orgId,\n enrollments: watchedEnrollments,\n sendingDomain: outreachMailboxSendingDomain(mailbox),\n resolveMx: deps.resolveMx,\n nowMs,\n })\n } catch (error) {\n console.error('[outreach] the gateway ledger could not credit deliveries', error)\n }\n\n const paused = await applyOutreachMailboxHealth(deps, { orgId, mailboxId: mailbox.id, delta: context.delta })\n if (paused) report.paused += 1\n // The window is moved only when something was handled or an hour has\n // passed: a quiet mailbox re-reading an hour's window is a few list calls,\n // where rewriting every mailbox every run was a write per mailbox every\n // fifteen minutes with nothing in it (AGL-3932). The handled ids keep a\n // re-read from acting twice.\n if (newlyHandled.length || nowMs - (mailbox.sync?.throughMs ?? 0) >= MAILBOX_SYNC_WINDOW_REFRESH_MS) {\n await mailboxRef(firestore, orgId, mailbox.id).update({\n sync: {\n throughMs: nowMs,\n handledMessageIds: [...(mailbox.sync?.handledMessageIds ?? []), ...newlyHandled].slice(-MAILBOX_HANDLED_MAX),\n },\n })\n }\n}\n\n/** Every enrollment of an organization written to within the watch window. */\nasync function readWatchedEnrollments(firestore: Firestore, orgId: string, nowMs: number): Promise<OutreachEnrollment[]> {\n const snapshot = await outreachOrgCollection(firestore, orgId, 'enrollments')\n .where('lastSentAtMs', '>=', nowMs - OUTREACH_SYNC_WATCH_MS)\n .get()\n return snapshot.docs\n .map((doc) => readStoredOutreachEnrollment(doc.id, doc.data()))\n .filter((enrollment): enrollment is OutreachEnrollment => enrollment !== null)\n}\n\n/** The sequence an enrollment runs through, read once per run. */\nasync function sequenceOf(context: SyncContext, sequenceId: string): Promise<OutreachSequence | null> {\n if (!context.sequences.has(sequenceId)) {\n const snapshot = await outreachOrgCollection(context.firestore, context.orgId, 'sequences').doc(sequenceId).get()\n context.sequences.set(sequenceId, readStoredOutreachSequence(sequenceId, snapshot.exists ? snapshot.data() : undefined))\n }\n return context.sequences.get(sequenceId) ?? null\n}\n\n/** A message's `Message-ID` in header form, or `null` when it carries none. */\nconst messageIdOf = (message: OutreachThreadMessage) => outreachMessageIdHeader(outreachHeader(message, 'Message-ID'))\n\n/** A bounce's diagnostic with the recipient's address taken out of it. */\nexport function scrubbedOutreachDiagnostic(diagnostic: string | null, email: string): string | null {\n if (!diagnostic) return null\n const pattern = new RegExp(email.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), 'gi')\n return diagnostic.replace(pattern, 'the address')\n}\n\n/** Files a message the person wrote on their timeline. */\nasync function fileInbound(context: SyncContext, enrollment: OutreachEnrollment, message: OutreachThreadMessage) {\n const messageId = messageIdOf(message)\n if (!messageId) return\n await fileOutreachEmail(context.deps, {\n orgId: context.orgId,\n hostId: enrollment.hostId,\n link: outreachEnrollmentLink(enrollment),\n direction: 'inbound',\n subject: message.subject,\n from: emailAddressOf(message.from) ?? message.from,\n to: context.mailbox.sendAs || context.mailbox.email,\n messageId,\n inReplyTo: outreachMessageIdHeader(outreachHeader(message, 'In-Reply-To')),\n body: emailExcerpt(message.textBody ?? message.snippet ?? '', message.htmlBody ?? ''),\n atMs: message.internalDateMs,\n byUid: '',\n })\n}\n\n/**\n * What the new messages of one enrollment mean, done: the effects first,\n * each idempotent, then the event and the handled ids in one transaction.\n */\nasync function applyMessages(\n context: SyncContext,\n enrollment: OutreachEnrollment,\n messages: readonly OutreachThreadMessage[],\n): Promise<void> {\n const { deps, firestore, report, nowMs } = context\n const decision: OutreachThreadDecision = decideOutreachThread({\n messages,\n recipient: enrollment.email,\n handledMessageIds: enrollment.syncedMessageIds ?? [],\n selfAddresses: context.selfAddresses,\n unsubscribeAddress: context.unsubscribeAddress,\n threadSubject: enrollment.threadSubject,\n })\n const freshIds = decision.classifications.map((classification) => classification.messageId).filter(Boolean)\n if (!freshIds.length) return\n // What they wrote, kept on the enrollment so the console can show it and\n // answer it in the thread (AGL-4020) — every message of theirs among\n // these, so a thread read whole also keeps a reply synced before they\n // were kept.\n const inbound = outreachInboundMessagesOf(messages, {\n selfAddresses: context.selfAddresses,\n unsubscribeAddress: context.unsubscribeAddress,\n threadSubject: enrollment.threadSubject,\n })\n const decidedBy: OutreachMessageClassification | null = decision.decidedBy\n const decidingMessage = decidedBy ? messages.find((message) => message.id === decidedBy.messageId) ?? null : null\n const lastSentMessageId = enrollment.messageIds[enrollment.messageIds.length - 1] ?? null\n\n for (const classification of decision.classifications) {\n const aboutRecipient =\n !classification.bounce?.recipients.length || classification.bounce.recipients.includes(enrollment.email)\n if (classification.kind === 'hard_bounce' && aboutRecipient) {\n context.delta.bounces.push({ atMs: classification.atMs || nowMs, messageId: lastSentMessageId })\n }\n if (classification.complaint) {\n context.delta.complaintAtMs = Math.max(context.delta.complaintAtMs ?? 0, classification.atMs || nowMs)\n }\n }\n\n let event: OutreachEnrollmentEvent | null = null\n let postponedTo: number | null = null\n switch (decision.outcome) {\n case 'opted_out': {\n if (decidingMessage) await fileInbound(context, enrollment, decidingMessage)\n const complaint = decidedBy?.complaint === true\n await recordOutreachOptOut(deps, {\n orgId: context.orgId,\n email: enrollment.email,\n source: decidedBy?.evidence?.startsWith('To:') ? 'unsubscribe' : 'opt_out_reply',\n enrollment,\n hostIds: [enrollment.hostId],\n detail: decidedBy?.evidence ?? null,\n nowMs,\n complaint,\n })\n // A reply that called the email spam marks the send it answered\n // (AGL-3245), as the campaign webhook would mark a reported one.\n if (complaint) {\n await markOutreachEmailDelivery(deps, {\n orgId: context.orgId,\n messageId: lastSentMessageId,\n state: 'complained',\n atMs: decidedBy?.atMs || nowMs,\n detail: decidedBy?.evidence ?? null,\n })\n }\n report.optOuts += 1\n break\n }\n case 'replied': {\n if (decidingMessage) {\n await fileInbound(context, enrollment, decidingMessage)\n try {\n await fileOutreachTask(deps, {\n orgId: context.orgId,\n hostId: enrollment.hostId,\n link: outreachEnrollmentLink(enrollment),\n dedupeKey: `reply:${messageIdOf(decidingMessage) ?? decidingMessage.id}`,\n title: `Reply from ${enrollment.contactName || enrollment.email}`,\n notes: emailExcerpt(decidingMessage.textBody ?? decidingMessage.snippet ?? '', decidingMessage.htmlBody ?? '').slice(0, 500),\n kind: 'email',\n dueAtMs: nowMs,\n assigneeUid: context.mailbox.connectedByUid,\n })\n } catch (error) {\n console.error('[outreach] the reply task could not be filed', error)\n }\n }\n // A lead somebody wrote back to is being worked (AGL-3234): the record\n // system hears of the reply, and moves a lead nobody had worked to\n // Working (AGL-3080). Never throws.\n if (enrollment.target === 'lead' && enrollment.leadId && enrollment.email) {\n await stampRecordEmailReply({\n orgId: context.orgId,\n hostId: enrollment.hostId,\n emails: [enrollment.email],\n })\n }\n context.delta.replies += 1\n event = { type: 'reply', atMs: decidedBy?.atMs || nowMs, detail: decidedBy?.evidence ?? null }\n report.replies += 1\n // Once per enrollment (AGL-3254): a reply moves the status to\n // `replied`, and nothing is synced for it again.\n await creditOutreachReply(deps, { enrollment, atMs: event.atMs })\n break\n }\n case 'bounced': {\n const diagnostic = scrubbedOutreachDiagnostic(decidedBy?.bounce?.diagnostic ?? decidedBy?.bounce?.status ?? null, enrollment.email)\n await deps.suppressBouncedEmail({ email: enrollment.email, hostId: enrollment.hostId })\n await addOutreachDoNotContact(firestore, {\n orgId: context.orgId,\n email: enrollment.email,\n reason: 'hard_bounce',\n source: 'runtime',\n nowMs,\n enrollmentId: enrollment.id,\n sequenceId: enrollment.sequenceId,\n detail: diagnostic,\n })\n let detail = diagnostic\n // A gateway block is the domain's verdict on the sender (AGL-3244):\n // the domain is filed beside the address, and the enrollment says so.\n // Never a public mailbox provider's domain — Gmail refusing one\n // message on policy is not a reason to stop writing to Gmail.\n const domain = outreachEmailDomain(enrollment.email)\n const gateway = isOutreachGatewayBlock(decidedBy?.bounce ?? null)\n if (domain && !isPublicMailboxDomain(domain) && gateway) {\n await addOutreachDoNotContactDomain(firestore, {\n orgId: context.orgId,\n domain,\n reason: 'gateway_block',\n source: 'runtime',\n nowMs,\n enrollmentId: enrollment.id,\n sequenceId: enrollment.sequenceId,\n detail: diagnostic,\n })\n detail = outreachGatewayBlockDetail(domain, diagnostic)\n report.gatewayBlocks += 1\n }\n // The ledger learns the refusal (AGL-3326), whichever domain it was\n // at: a public provider refusing on policy is still that provider's\n // verdict on the sender, even though its domain is never listed.\n if (gateway) {\n await recordOutreachGatewayBlock(firestore, {\n orgId: context.orgId,\n email: enrollment.email,\n remoteMta: decidedBy?.bounce?.remoteMta ?? null,\n sendingDomain: outreachMailboxSendingDomain(context.mailbox),\n diagnostic,\n resolveMx: deps.resolveMx,\n nowMs,\n })\n }\n const bouncedAtMs = decidedBy?.atMs || nowMs\n // The record the person is says so too (AGL-3245): the verdict on the\n // lead and the contact, and the bounce on the send's own timeline\n // entry, so the record reads Sent, then Bounced.\n await deps.stampRecordEmailState({\n orgId: context.orgId,\n email: enrollment.email,\n state: {\n status: gateway ? 'blocked' : 'bounced',\n atMs: bouncedAtMs,\n source: 'sequence',\n detail: diagnostic,\n enrollmentId: enrollment.id,\n },\n })\n await markOutreachEmailDelivery(deps, {\n orgId: context.orgId,\n messageId: lastSentMessageId,\n state: 'bounced',\n atMs: bouncedAtMs,\n detail: diagnostic,\n })\n event = { type: 'bounce', atMs: bouncedAtMs, detail }\n report.bounces += 1\n break\n }\n case 'postpone': {\n const sequence = await sequenceOf(context, enrollment.sequenceId)\n postponedTo = postponeOutreachForAutoReply({\n nextDueAtMs: enrollment.nextDueAtMs,\n receivedAtMs: decidedBy?.atMs || nowMs,\n timeZone: context.mailbox.timezone,\n window: effectiveOutreachWindow(sequence?.settings.window, context.mailbox.window),\n random: deps.random,\n })\n break\n }\n default:\n break\n }\n\n const outcome = await applyOutreachEvent(firestore, {\n orgId: context.orgId,\n enrollmentId: enrollment.id,\n event,\n extra: (current) => {\n const extra: Record<string, unknown> = {\n syncedMessageIds: [...(current.syncedMessageIds ?? []), ...freshIds].slice(-ENROLLMENT_HANDLED_MAX),\n }\n if (inbound.length) extra['inboundMessages'] = mergeOutreachInboundMessages(current.inboundMessages, inbound)\n const waiting = current.status === 'active' || current.status === 'paused'\n if (postponedTo !== null && waiting && current.nextDueAtMs !== null && postponedTo > current.nextDueAtMs) {\n extra['nextDueAtMs'] = postponedTo\n }\n return extra\n },\n nowMs,\n })\n if (postponedTo !== null && outcome.enrollment?.nextDueAtMs === postponedTo) report.postponed += 1\n // The person's record says the sequence ended (AGL-3274), once, under the\n // reply that ended it — after the transaction moved the status, so a run\n // that reads the same reply again finds nothing to file. An opt-out's\n // line is `recordOutreachOptOut`'s, beside the lists it writes.\n if (event?.type === 'reply' && outcome.changed) {\n const sequence = await sequenceOf(context, enrollment.sequenceId)\n const entry = outreachStoppedEntry({\n enrollmentId: enrollment.id,\n sequenceName: sequence?.name ?? '',\n reason: 'replied',\n })\n await fileOutreachNote(deps, {\n orgId: context.orgId,\n hostId: enrollment.hostId,\n link: outreachEnrollmentLink(enrollment),\n dedupeKey: entry.dedupeKey,\n body: entry.body,\n atMs: event.atMs,\n })\n }\n // The run's own view of the enrollment moves with it, so a second message\n // of it in this run is judged against what this one did.\n if (outcome.enrollment) Object.assign(enrollment, outcome.enrollment)\n}\n"],"names":["normalizeContactEmail","isPublicMailboxDomain","emailAddressOf","emailExcerpt","outreachMessageIdHeader","readOutreachDeliveryReport","outreachEmailDomain","outreachStoppedEntry","isOutreachGatewayBlock","outreachGatewayBlockDetail","mergeOutreachInboundMessages","outreachInboundMessagesOf","matchOutreachPossibleReply","outreachPossibleReplyNote","outreachPossibleReplyTitle","effectiveOutreachWindow","postponeOutreachForAutoReply","decideOutreachThread","outreachAutoReplyEvidence","outreachHeader","outreachThreadMessageFromGmail","mailboxRef","OUTREACH_COLLECTIONS","addOutreachDoNotContact","addOutreachDoNotContactDomain","outreachEnrollmentLink","outreachOrgCollection","readStoredOutreachEnrollment","readStoredOutreachMailbox","readStoredOutreachSequence","GmailTransportError","isReconnectRequired","creditOutreachReply","applyOutreachEvent","recordOutreachOptOut","creditOutreachGatewayDeliveries","recordOutreachGatewayBlock","outreachMailboxSendingDomain","applyOutreachMailboxHealth","emptyOutreachHealthDelta","noteOutreachMailboxReconnectRequired","stampRecordEmailReply","fileOutreachEmail","fileOutreachNote","fileOutreachTask","markOutreachEmailDelivery","outreachUnsubscribeMailbox","OUTREACH_SYNC_JOB_ID","OUTREACH_SYNC_LOOKBACK_MS","OUTREACH_SYNC_OVERLAP_MS","OUTREACH_SYNC_WATCH_MS","SEARCH_PAGES","MAILBOX_HANDLED_MAX","MAILBOX_SYNC_WINDOW_REFRESH_MS","ENROLLMENT_HANDLED_MAX","FROM_CHUNK","POSSIBLE_REPLY_READS","POSSIBLE_REPLY_HEADERS","runOutreachSyncJob","deps","context","firestore","report","mailboxes","threads","replies","optOuts","bounces","gatewayBlocks","deliveries","postponed","paused","possibleReplies","all","collectionGroup","get","byOrg","Map","doc","docs","orgId","ref","parent","id","mailbox","data","status","set","now","deadlineMs","orgSnapshot","collection","org","exists","orgRefusal","orgWatched","watchedInOrg","readWatchedEnrollments","nowMs","syncMailbox","error","mailboxId","errorCode","code","console","search","client","criteria","found","pageToken","page","list","searchMessages","maxResults","push","messages","filter","message","nextPageToken","input","opened","openMailbox","ok","reason","unsubscribe","email","selfAddresses","sendAs","sendAsOptions","map","option","Boolean","unsubscribeAddress","address","sequences","delta","watched","where","byThread","byAddress","watchedEnrollments","enrollment","known","threadId","gmailThreadIds","lastSentAtMs","sinceMs","Math","max","Number","sync","throughMs","handled","Set","handledMessageIds","newlyHandled","markHandled","has","add","fresh","stub","inbound","afterMs","notFromSelf","thread","getFullThread","applyMessages","from","getFullMessage","delivery","kind","failedAddresses","to","metadata","getMessage","metadataHeaders","headers","find","header","name","toLowerCase","value","includes","source","hostIds","hostId","detail","addresses","keys","start","length","chunk","slice","leftover","enrollments","Object","fromEntries","entry","fromHeader","sender","subject","match","enrolled","link","dedupeKey","title","replace","trim","notes","enrolledName","contactName","receivedBy","excerpt","snippet","join","dueAtMs","assigneeUid","connectedByUid","sendingDomain","resolveMx","update","snapshot","sequenceOf","sequenceId","undefined","messageIdOf","scrubbedOutreachDiagnostic","diagnostic","pattern","RegExp","fileInbound","messageId","direction","inReplyTo","body","textBody","htmlBody","atMs","internalDateMs","byUid","outcome","decision","recipient","syncedMessageIds","threadSubject","freshIds","classifications","classification","decidedBy","decidingMessage","lastSentMessageId","messageIds","aboutRecipient","bounce","recipients","complaint","complaintAtMs","event","postponedTo","evidence","startsWith","state","target","leadId","emails","type","suppressBouncedEmail","enrollmentId","domain","gateway","remoteMta","bouncedAtMs","stampRecordEmailState","sequence","nextDueAtMs","receivedAtMs","timeZone","timezone","window","settings","random","extra","current","inboundMessages","waiting","changed","sequenceName","assign"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,qBAAqB,QAAQ,kCAAiC;AACvE,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,cAAc,EAAEC,YAAY,QAAQ,oCAAmC;AAChF,SAASC,uBAAuB,QAAQ,uBAAmB;AAC3D,SAASC,0BAA0B,QAAQ,+BAA2B;AACtE,SAASC,mBAAmB,QAAQ,qCAAiC;AACrE,SAASC,oBAAoB,QAAQ,mCAA+B;AAEpE,SAASC,sBAAsB,EAAEC,0BAA0B,QAAQ,6BAAyB;AAC5F,SAASC,4BAA4B,EAAEC,yBAAyB,QAAQ,4BAAwB;AAChG,SACEC,0BAA0B,EAC1BC,yBAAyB,EACzBC,0BAA0B,QACrB,8BAA0B;AACjC,SAASC,uBAAuB,EAAEC,4BAA4B,QAAQ,wBAAoB;AAC1F,SACEC,oBAAoB,EACpBC,yBAAyB,QAGpB,qCAAiC;AACxC,SAASC,cAAc,EAAEC,8BAA8B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M,KAAK;YAClE,IAAI4K,gBAAgB,QAAQ0B,WAAWF,QAAQR,WAAW,KAAK,QAAQhB,cAAcwB,QAAQR,WAAW,EAAE;gBACxGO,KAAK,CAAC,cAAc,GAAGvB;YACzB;YACA,OAAOuB;QACT;QACAvL;IACF;IACA,IAAIgK,gBAAgB,QAAQlB,EAAAA,sBAAAA,QAAQnG,UAAU,qBAAlBmG,oBAAoBkC,WAAW,MAAKhB,aAAapM,OAAOQ,SAAS,IAAI;IACjG,0EAA0E;IAC1E,yEAAyE;IACzE,sEAAsE;IACtE,gEAAgE;IAChE,IAAI2L,CAAAA,yBAAAA,MAAOQ,IAAI,MAAK,WAAWzB,QAAQ6C,OAAO,EAAE;;QAC9C,MAAMZ,WAAW,MAAMnD,WAAWlK,SAASiF,WAAWkF,UAAU;QAChE,MAAM1B,QAAQ9L,qBAAqB;YACjCoQ,cAAc9H,WAAW1D,EAAE;YAC3B2M,YAAY,WAAEb,4BAAAA,SAAU9F,IAAI,oBAAI;YAChCxD,QAAQ;QACV;QACA,MAAMhF,iBAAiBgB,MAAM;YAC3BqB,OAAOpB,QAAQoB,KAAK;YACpByG,QAAQ5C,WAAW4C,MAAM;YACzBkB,MAAMlL,uBAAuBoH;YAC7B+D,WAAWP,MAAMO,SAAS;YAC1B8B,MAAMrC,MAAMqC,IAAI;YAChBG,MAAMoB,MAAMpB,IAAI;QAClB;IACF;IACA,0EAA0E;IAC1E,yDAAyD;IACzD,IAAIG,QAAQnG,UAAU,EAAEsD,OAAO4F,MAAM,CAAClJ,YAAYmG,QAAQnG,UAAU;AACtE"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/runtime/sync-job.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { normalizeContactEmail } from '@aglyn/aglyn/app-utils/contacts'\nimport { isPublicMailboxDomain } from '@aglyn/aglyn/app-utils/crm'\nimport { emailAddressOf, emailExcerpt } from '@aglyn/aglyn/app-utils/email-text'\nimport { outreachMessageIdHeader } from '../engine/compose'\nimport { readOutreachDeliveryReport } from '../engine/delivery-status'\nimport { outreachEmailDomain } from '../engine/do-not-contact-domain'\nimport { outreachStoppedEntry } from '../engine/enrollment-activity'\nimport type { OutreachEnrollmentEvent } from '../engine/enrollment-state'\nimport { isOutreachGatewayBlock, outreachGatewayBlockDetail } from '../engine/gateway-block'\nimport { mergeOutreachInboundMessages, outreachInboundMessagesOf } from '../engine/manual-reply'\nimport {\n matchOutreachPossibleReply,\n outreachPossibleReplyNote,\n outreachPossibleReplyTitle,\n} from '../engine/possible-reply'\nimport { effectiveOutreachWindow, postponeOutreachForAutoReply } from '../engine/schedule'\nimport {\n decideOutreachThread,\n outreachAutoReplyEvidence,\n type OutreachMessageClassification,\n type OutreachThreadDecision,\n} from '../engine/thread-classification'\nimport { outreachHeader, outreachThreadMessageFromGmail, type OutreachThreadMessage } from '../engine/thread-message'\nimport { mailboxRef } from '../mailboxes/mailbox-credentials'\nimport {\n OUTREACH_COLLECTIONS,\n type OutreachEnrollment,\n type OutreachMailbox,\n type OutreachSequence,\n} from '../model/outreach.types'\nimport { addOutreachDoNotContact, addOutreachDoNotContactDomain } from '../storage/do-not-contact-store'\nimport {\n outreachEnrollmentLink,\n outreachOrgCollection,\n readStoredOutreachEnrollment,\n readStoredOutreachMailbox,\n readStoredOutreachSequence,\n} from '../storage/outreach-records'\nimport type { OutreachMailClient, OutreachMailSearch, OutreachMailStub } from '../transport/mail-client'\nimport { GmailTransportError, isReconnectRequired } from '../transport/gmail-errors'\nimport { creditOutreachReply } from './campaign-credit'\nimport { applyOutreachEvent, recordOutreachOptOut } from './enrollment-events'\nimport { creditOutreachGatewayDeliveries, recordOutreachGatewayBlock } from './gateway-ledger'\nimport { outreachMailboxSendingDomain } from '../storage/domain-intel-store'\nimport {\n applyOutreachMailboxHealth,\n emptyOutreachHealthDelta,\n type OutreachMailboxHealthDelta,\n} from './mailbox-health-store'\nimport { noteOutreachMailboxReconnectRequired } from './mailbox-notices'\nimport type { OutreachRuntimeDeps } from './runtime-deps'\nimport { stampRecordEmailReply } from '@aglyn/aglyn/plugin-manager/plugin-record-email-state'\nimport { fileOutreachEmail, fileOutreachNote, fileOutreachTask, markOutreachEmailDelivery } from './timeline'\nimport { outreachUnsubscribeMailbox } from './unsubscribe-link'\nimport { watchedEnrollmentsOfOrg, type WatchedEnrollments } from './watched-enrollments'\n\n/*==========================================\n * THE SYNC JOB (AGL-2981): every fifteen minutes, on the console.\n *\n * For each connected or paused mailbox, what came back since the last run —\n * read with `format=full`, turned into the engine's message shape and\n * classified by `decideOutreachThread`:\n *\n * - a REPLY stops the enrollment, files the message on the contact's\n * timeline (once per `Message-ID`, under the capture address's own id for\n * it) and gives the rep the task \"Reply from <name>\";\n * - every message the person wrote — a reply, an automatic answer, an\n * opt-out — is kept on the enrollment, its sender, time, threading ids\n * and trimmed text, for the console to show and answer (AGL-4020);\n * - an OUT-OF-OFFICE postpones the next step a working week from the reply;\n * - an OPT-OUT — a reply asking to be left alone, or a message to the\n * `+unsubscribe` address the `mailto:` names — puts the address on the\n * organization's do-not-contact list and off the site's `sales` topic,\n * and stops every open enrollment of it;\n * - a HARD BOUNCE stops the enrollment, files the address on the platform's\n * suppression list and the do-not-contact list — and, when its diagnostic\n * reads as the domain's mail gateway refusing the sender rather than one\n * address being unknown (`engine/gateway-block`, AGL-3244), files the\n * DOMAIN on the do-not-contact list too, and says so on the enrollment —\n * and counts the block on the gateway ledger (AGL-3326), under the\n * gateway the bounce's `Remote-MTA` names.\n *\n * And once the mail is read, every email step of a watched enrollment that\n * is a day old with no bounce against it is credited to the ledger as\n * delivered (`./gateway-ledger`): the silence that says a gateway let the\n * sender through.\n *\n * Every verdict a list takes is said on the record the person is as well\n * (AGL-3245): the lead and the contact carry `emailState` through the\n * platform's stamp, and a bounce or a complaint lands on the send's own\n * timeline entry, so a member reading the record sees what the runtime saw.\n *\n * Four reads find those, each narrowed by the provider rather than read in\n * full (`OutreachMailSearch`, AGL-3489):\n * the threads of this mailbox's enrollments that have new mail; delivery\n * reports outside those threads (a receiving server's own bounce), by\n * searching for the mail systems that send them; messages to the\n * unsubscribe address; and messages from the people this mailbox is\n * writing to, in a thread of their own.\n *\n * Then what is left of the new mail is read for POSSIBLE replies (AGL-4088,\n * `engine/possible-reply`): a person writing to another of the\n * organization's mailboxes, or a colleague at their company writing. Those\n * stop nothing; each files the task \"Possible reply from …\" for a person to\n * read.\n *\n * Every write it makes is idempotent — the do-not-contact list keeps its\n * first entry, a topic opt-out keeps its first moment, a timeline entry is\n * filed once per message — and the messages it handled are marked AFTER\n * their effects, on the enrollment and on the mailbox, so a run that dies\n * part-way repeats harmless work rather than skipping some. The mailbox's\n * health takes the run's bounces and complaints in one write at the end,\n * which is where it pauses itself.\n *==========================================*/\n\nexport { OUTREACH_SYNC_JOB_ID } from '../constants/runtime-jobs'\n\n/** The furthest back a run reads: a mailbox's first run, or one that fell behind. */\nexport const OUTREACH_SYNC_LOOKBACK_MS = 7 * 24 * 60 * 60_000\n\n/** How far a run reads back past the previous one, for mail Gmail indexed late. */\nexport const OUTREACH_SYNC_OVERLAP_MS = 2 * 60 * 60_000\n\n/** How long after its last send an enrollment's mail is still watched. */\nexport const OUTREACH_SYNC_WATCH_MS = 45 * 24 * 60 * 60_000\n\n/** The most pages of one search a run reads. */\nconst SEARCH_PAGES = 5\n/** Handled message ids a mailbox keeps, and an enrollment keeps. */\nconst MAILBOX_HANDLED_MAX = 500\n\n/** How far a quiet mailbox's window may lag before its document is moved anyway. */\nconst MAILBOX_SYNC_WINDOW_REFRESH_MS = 60 * 60_000\nconst ENROLLMENT_HANDLED_MAX = 100\n/** Addresses in one `from:` search. */\nconst FROM_CHUNK = 15\n/** Messages one mailbox's run reads for a possible reply (AGL-4088). */\nconst POSSIBLE_REPLY_READS = 60\n/** The headers a possible reply is judged by: who, what, and whether a machine sent it. */\nconst POSSIBLE_REPLY_HEADERS = ['From', 'Subject', 'Auto-Submitted', 'X-Autoreply', 'X-Autorespond', 'Precedence']\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport interface OutreachSyncReport {\n [key: string]: number\n mailboxes: number\n threads: number\n replies: number\n optOuts: number\n bounces: number\n /** Hard bounces that read as a gateway block, each filing its domain (AGL-3244). */\n gatewayBlocks: number\n /** Email steps a day old with no bounce, credited to the gateway ledger (AGL-3326). */\n deliveries: number\n postponed: number\n paused: number\n /** Messages filed as a possible reply for a person to read (AGL-4088). */\n possibleReplies: number\n}\n\ninterface SyncContext {\n deps: OutreachRuntimeDeps\n firestore: Firestore\n orgId: string\n mailbox: OutreachMailbox\n client: OutreachMailClient\n selfAddresses: string[]\n unsubscribeAddress: string | null\n sequences: Map<string, OutreachSequence | null>\n delta: OutreachMailboxHealthDelta\n report: OutreachSyncReport\n nowMs: number\n /**\n * Said before any write to an enrollment, so the run's held watched set is\n * read again rather than trusted (`./watched-enrollments`, AGL-4121).\n */\n touched: () => void\n}\n\n/** Runs the sync job once — see the module note. */\nexport async function runOutreachSyncJob(\n deps: OutreachRuntimeDeps,\n context: { nowMs: number; deadlineMs: number },\n): Promise<OutreachSyncReport> {\n const firestore = deps.firestore()\n const report: OutreachSyncReport = {\n mailboxes: 0,\n threads: 0,\n replies: 0,\n optOuts: 0,\n bounces: 0,\n gatewayBlocks: 0,\n deliveries: 0,\n postponed: 0,\n paused: 0,\n possibleReplies: 0,\n }\n const all = await firestore.collectionGroup(OUTREACH_COLLECTIONS.mailboxes).get()\n const byOrg = new Map<string, OutreachMailbox[]>()\n for (const doc of all.docs) {\n const orgId = doc.ref.parent.parent?.id\n const mailbox = readStoredOutreachMailbox(doc.id, doc.data())\n if (!orgId || !mailbox || (mailbox.status !== 'connected' && mailbox.status !== 'paused')) continue\n byOrg.set(orgId, [...(byOrg.get(orgId) ?? []), mailbox])\n }\n for (const [orgId, mailboxes] of byOrg) {\n if (deps.now() >= context.deadlineMs) break\n const orgSnapshot = await firestore.collection('orgs').doc(orgId).get()\n const org = (orgSnapshot.exists ? orgSnapshot.data() : null) as Record<string, unknown> | null\n if (!org || (await deps.orgRefusal(orgId, org))) continue\n // Every enrollment the organization is still watching, read once per run\n // for every mailbox and the possible-reply step together, and again only\n // after the run writes an enrollment (`./watched-enrollments`, AGL-4121).\n const watched = watchedEnrollmentsOfOrg({\n org: () => readWatchedEnrollmentDocs(firestore, orgId, context.nowMs),\n mailbox: (mailboxId) => readWatchedEnrollmentDocs(firestore, orgId, context.nowMs, mailboxId),\n })\n for (const mailbox of mailboxes) {\n if (deps.now() >= context.deadlineMs) break\n try {\n await syncMailbox(deps, firestore, { orgId, mailbox, report, nowMs: context.nowMs, watched })\n report.mailboxes += 1\n } catch (error) {\n // One mailbox's failure is its own; the next mailbox is read. A grant\n // Google refused is the mailbox's to reconnect.\n if (isReconnectRequired(error)) {\n await noteOutreachMailboxReconnectRequired(deps, {\n orgId,\n mailboxId: mailbox.id,\n errorCode: error instanceof GmailTransportError ? error.code : 'invalid_grant',\n nowMs: context.nowMs,\n })\n }\n console.error('[outreach] syncing a mailbox failed', error)\n }\n }\n }\n return report\n}\n\n/** Every stub a search finds, a few pages deep. */\nasync function search(client: OutreachMailClient, criteria: OutreachMailSearch): Promise<OutreachMailStub[]> {\n const found: OutreachMailStub[] = []\n let pageToken: string | null = null\n for (let page = 0; page < SEARCH_PAGES; page += 1) {\n const list = await client.searchMessages(criteria, { maxResults: 100, pageToken })\n found.push(...list.messages.filter((message) => message.id))\n pageToken = list.nextPageToken\n if (!pageToken) break\n }\n return found\n}\n\nasync function syncMailbox(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n input: {\n orgId: string\n mailbox: OutreachMailbox\n report: OutreachSyncReport\n nowMs: number\n watched: WatchedEnrollments<WatchedEnrollmentSnapshot>\n },\n): Promise<void> {\n const { orgId, mailbox, report, nowMs } = input\n const opened = await deps.openMailbox(mailbox.id)\n if (opened.ok === false) {\n if (opened.reason !== 'not-configured') {\n await noteOutreachMailboxReconnectRequired(deps, {\n orgId,\n mailboxId: mailbox.id,\n errorCode: opened.reason,\n nowMs,\n })\n }\n return\n }\n const unsubscribe = outreachUnsubscribeMailbox(mailbox.email)\n const context: SyncContext = {\n deps,\n firestore,\n orgId,\n mailbox,\n client: opened.client,\n selfAddresses: [\n mailbox.email,\n mailbox.sendAs,\n ...(mailbox.sendAsOptions ?? []).map((option) => option.email),\n ].filter(Boolean),\n unsubscribeAddress: unsubscribe?.address ?? null,\n sequences: new Map(),\n delta: emptyOutreachHealthDelta(),\n report,\n nowMs,\n touched: input.watched.touched,\n }\n\n // The enrollments this mailbox is writing to, by thread and by address.\n const watched = await input.watched.forMailbox(mailbox.id)\n const byThread = new Map<string, OutreachEnrollment>()\n const byAddress = new Map<string, OutreachEnrollment>()\n const watchedEnrollments: OutreachEnrollment[] = []\n for (const doc of watched) {\n const enrollment = readStoredOutreachEnrollment(doc.id, doc.data())\n if (!enrollment) continue\n watchedEnrollments.push(enrollment)\n for (const threadId of enrollment.gmailThreadIds) byThread.set(threadId, enrollment)\n const known = byAddress.get(enrollment.email)\n if (!known || (enrollment.lastSentAtMs ?? 0) > (known.lastSentAtMs ?? 0)) byAddress.set(enrollment.email, enrollment)\n }\n\n const sinceMs = Math.max(Number(mailbox.sync?.throughMs) || 0, nowMs - OUTREACH_SYNC_LOOKBACK_MS) - OUTREACH_SYNC_OVERLAP_MS\n // Every message this run or an earlier one handled outside an enrollment's\n // thread; one message is handled once however many searches find it.\n const handled = new Set(mailbox.sync?.handledMessageIds ?? [])\n const newlyHandled: string[] = []\n const markHandled = (id: string) => {\n if (handled.has(id)) return\n handled.add(id)\n newlyHandled.push(id)\n }\n const fresh = (stub: OutreachMailStub) => !handled.has(stub.id) && !byThread.has(stub.threadId)\n\n // 1. The enrollments' own threads that have new mail.\n const inbound = await search(context.client, { afterMs: sinceMs, notFromSelf: true })\n for (const threadId of new Set(inbound.map((stub) => stub.threadId))) {\n const enrollment = byThread.get(threadId)\n if (!enrollment) continue\n const thread = await context.client.getFullThread(threadId)\n report.threads += 1\n await applyMessages(context, enrollment, thread.messages.map(outreachThreadMessageFromGmail))\n }\n\n // 2. Delivery reports outside those threads: a receiving server's bounce.\n for (const stub of await search(context.client, { afterMs: sinceMs, from: ['mailer-daemon', 'postmaster'] })) {\n if (!fresh(stub)) continue\n const message = outreachThreadMessageFromGmail(await context.client.getFullMessage(stub.id))\n const delivery = readOutreachDeliveryReport(message)\n if (delivery?.kind === 'hard') {\n for (const address of delivery.failedAddresses) {\n const enrollment = byAddress.get(address)\n if (enrollment) await applyMessages(context, enrollment, [message])\n }\n }\n markHandled(stub.id)\n }\n\n // 3. Messages to the unsubscribe address: whoever wrote asked to leave.\n if (unsubscribe) {\n for (const stub of await search(context.client, { afterMs: sinceMs, to: unsubscribe.address })) {\n if (handled.has(stub.id)) continue\n const metadata = await context.client.getMessage(stub.id, { metadataHeaders: ['From'] })\n const from = emailAddressOf(metadata.headers.find((header) => header.name.toLowerCase() === 'from')?.value ?? '')\n const address = normalizeContactEmail(from)\n if (address && !context.selfAddresses.includes(address)) {\n const enrollment = byAddress.get(address) ?? null\n context.touched()\n await recordOutreachOptOut(deps, {\n orgId,\n email: address,\n source: 'unsubscribe',\n enrollment,\n hostIds: enrollment ? [enrollment.hostId] : [],\n detail: 'Wrote to the unsubscribe address.',\n nowMs,\n })\n report.optOuts += 1\n }\n markHandled(stub.id)\n }\n }\n\n // 4. The people this mailbox writes to, answering in a thread of their own.\n const addresses = [...byAddress.keys()]\n for (let start = 0; start < addresses.length; start += FROM_CHUNK) {\n const chunk = addresses.slice(start, start + FROM_CHUNK)\n for (const stub of await search(context.client, { afterMs: sinceMs, from: chunk })) {\n if (!fresh(stub)) continue\n const message = outreachThreadMessageFromGmail(await context.client.getFullMessage(stub.id))\n const enrollment = byAddress.get(normalizeContactEmail(emailAddressOf(message.from)) ?? '')\n if (enrollment) await applyMessages(context, enrollment, [message])\n markHandled(stub.id)\n }\n }\n\n // 4b. What is left of the new mail, read for a possible reply (AGL-4088):\n // the person writing to another of our mailboxes, or a colleague.\n const leftover = inbound.filter(fresh).slice(0, POSSIBLE_REPLY_READS)\n if (leftover.length) {\n const enrollments = enrollmentsOf(await input.watched.forOrg())\n for (const stub of leftover) {\n if (!fresh(stub)) continue\n const metadata = await context.client.getMessage(stub.id, { metadataHeaders: POSSIBLE_REPLY_HEADERS })\n const headers = Object.fromEntries(metadata.headers.map((entry) => [entry.name, entry.value]))\n const header = (name: string) => outreachHeader({ headers }, name)\n const fromHeader = header('From')\n const sender = normalizeContactEmail(emailAddressOf(fromHeader))\n const subject = header('Subject')\n markHandled(stub.id)\n if (!sender || context.selfAddresses.includes(sender)) continue\n if (outreachAutoReplyEvidence({ headers, subject })) continue\n const match = matchOutreachPossibleReply(sender, { mailboxId: mailbox.id, enrollments })\n if (!match) continue\n const enrolled = match.enrollment\n try {\n await fileOutreachTask(deps, {\n orgId,\n hostId: enrolled.hostId,\n link: outreachEnrollmentLink(enrolled),\n dedupeKey: `possible-reply:${stub.id}`,\n title: outreachPossibleReplyTitle(fromHeader.replace(/<[^>]*>/, '').replace(/\"/g, '').trim(), sender),\n notes: outreachPossibleReplyNote({\n reason: match.reason,\n enrolledName: enrolled.contactName || enrolled.email,\n receivedBy: mailbox.sendAs || mailbox.email,\n excerpt: [subject && `Subject: ${subject}`, metadata.snippet].filter(Boolean).join('\\n'),\n }),\n kind: 'email',\n dueAtMs: nowMs,\n assigneeUid: mailbox.connectedByUid,\n })\n report.possibleReplies += 1\n } catch (error) {\n console.error('[outreach] the possible-reply task could not be filed', error)\n }\n }\n }\n\n // 5. What went through: a day of silence after a send is a delivery\n // (AGL-3326), judged on the enrollments as this run left them.\n try {\n report.deliveries += await creditOutreachGatewayDeliveries(firestore, {\n orgId,\n enrollments: watchedEnrollments,\n sendingDomain: outreachMailboxSendingDomain(mailbox),\n resolveMx: deps.resolveMx,\n nowMs,\n })\n } catch (error) {\n console.error('[outreach] the gateway ledger could not credit deliveries', error)\n }\n\n const paused = await applyOutreachMailboxHealth(deps, { orgId, mailboxId: mailbox.id, delta: context.delta })\n if (paused) report.paused += 1\n // The window is moved only when something was handled or an hour has\n // passed: a quiet mailbox re-reading an hour's window is a few list calls,\n // where rewriting every mailbox every run was a write per mailbox every\n // fifteen minutes with nothing in it (AGL-3932). The handled ids keep a\n // re-read from acting twice.\n if (newlyHandled.length || nowMs - (mailbox.sync?.throughMs ?? 0) >= MAILBOX_SYNC_WINDOW_REFRESH_MS) {\n await mailboxRef(firestore, orgId, mailbox.id).update({\n sync: {\n throughMs: nowMs,\n handledMessageIds: [...(mailbox.sync?.handledMessageIds ?? []), ...newlyHandled].slice(-MAILBOX_HANDLED_MAX),\n },\n })\n }\n}\n\ntype WatchedEnrollmentSnapshot = FirebaseFirestore.QueryDocumentSnapshot\n\n/**\n * Every enrollment of an organization written to within the watch window,\n * or, given a mailbox, that mailbox's: the narrow read a mailbox falls back\n * to once the run has written an enrollment (`./watched-enrollments`).\n */\nasync function readWatchedEnrollmentDocs(\n firestore: Firestore,\n orgId: string,\n nowMs: number,\n mailboxId?: string,\n): Promise<WatchedEnrollmentSnapshot[]> {\n const enrollments = outreachOrgCollection(firestore, orgId, 'enrollments')\n const query =\n mailboxId === undefined\n ? enrollments.where('lastSentAtMs', '>=', nowMs - OUTREACH_SYNC_WATCH_MS)\n : enrollments.where('mailboxId', '==', mailboxId).where('lastSentAtMs', '>=', nowMs - OUTREACH_SYNC_WATCH_MS)\n return (await query.get()).docs\n}\n\n/** The enrollments a set of watched documents holds, unreadable ones left out. */\nfunction enrollmentsOf(docs: readonly WatchedEnrollmentSnapshot[]): OutreachEnrollment[] {\n return docs\n .map((doc) => readStoredOutreachEnrollment(doc.id, doc.data()))\n .filter((enrollment): enrollment is OutreachEnrollment => enrollment !== null)\n}\n\n/** The sequence an enrollment runs through, read once per run. */\nasync function sequenceOf(context: SyncContext, sequenceId: string): Promise<OutreachSequence | null> {\n if (!context.sequences.has(sequenceId)) {\n const snapshot = await outreachOrgCollection(context.firestore, context.orgId, 'sequences').doc(sequenceId).get()\n context.sequences.set(sequenceId, readStoredOutreachSequence(sequenceId, snapshot.exists ? snapshot.data() : undefined))\n }\n return context.sequences.get(sequenceId) ?? null\n}\n\n/** A message's `Message-ID` in header form, or `null` when it carries none. */\nconst messageIdOf = (message: OutreachThreadMessage) => outreachMessageIdHeader(outreachHeader(message, 'Message-ID'))\n\n/** A bounce's diagnostic with the recipient's address taken out of it. */\nexport function scrubbedOutreachDiagnostic(diagnostic: string | null, email: string): string | null {\n if (!diagnostic) return null\n const pattern = new RegExp(email.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), 'gi')\n return diagnostic.replace(pattern, 'the address')\n}\n\n/** Files a message the person wrote on their timeline. */\nasync function fileInbound(context: SyncContext, enrollment: OutreachEnrollment, message: OutreachThreadMessage) {\n const messageId = messageIdOf(message)\n if (!messageId) return\n await fileOutreachEmail(context.deps, {\n orgId: context.orgId,\n hostId: enrollment.hostId,\n link: outreachEnrollmentLink(enrollment),\n direction: 'inbound',\n subject: message.subject,\n from: emailAddressOf(message.from) ?? message.from,\n to: context.mailbox.sendAs || context.mailbox.email,\n messageId,\n inReplyTo: outreachMessageIdHeader(outreachHeader(message, 'In-Reply-To')),\n body: emailExcerpt(message.textBody ?? message.snippet ?? '', message.htmlBody ?? ''),\n atMs: message.internalDateMs,\n byUid: '',\n })\n}\n\n/**\n * What the new messages of one enrollment mean, done: the effects first,\n * each idempotent, then the event and the handled ids in one transaction.\n */\nasync function applyMessages(\n context: SyncContext,\n enrollment: OutreachEnrollment,\n messages: readonly OutreachThreadMessage[],\n): Promise<void> {\n const { deps, firestore, report, nowMs } = context\n const decision: OutreachThreadDecision = decideOutreachThread({\n messages,\n recipient: enrollment.email,\n handledMessageIds: enrollment.syncedMessageIds ?? [],\n selfAddresses: context.selfAddresses,\n unsubscribeAddress: context.unsubscribeAddress,\n threadSubject: enrollment.threadSubject,\n })\n const freshIds = decision.classifications.map((classification) => classification.messageId).filter(Boolean)\n if (!freshIds.length) return\n // Everything below may write this enrollment and, through an opt-out, the\n // address's others in the organization.\n context.touched()\n // What they wrote, kept on the enrollment so the console can show it and\n // answer it in the thread (AGL-4020) — every message of theirs among\n // these, so a thread read whole also keeps a reply synced before they\n // were kept.\n const inbound = outreachInboundMessagesOf(messages, {\n selfAddresses: context.selfAddresses,\n unsubscribeAddress: context.unsubscribeAddress,\n threadSubject: enrollment.threadSubject,\n })\n const decidedBy: OutreachMessageClassification | null = decision.decidedBy\n const decidingMessage = decidedBy ? messages.find((message) => message.id === decidedBy.messageId) ?? null : null\n const lastSentMessageId = enrollment.messageIds[enrollment.messageIds.length - 1] ?? null\n\n for (const classification of decision.classifications) {\n const aboutRecipient =\n !classification.bounce?.recipients.length || classification.bounce.recipients.includes(enrollment.email)\n if (classification.kind === 'hard_bounce' && aboutRecipient) {\n context.delta.bounces.push({ atMs: classification.atMs || nowMs, messageId: lastSentMessageId })\n }\n if (classification.complaint) {\n context.delta.complaintAtMs = Math.max(context.delta.complaintAtMs ?? 0, classification.atMs || nowMs)\n }\n }\n\n let event: OutreachEnrollmentEvent | null = null\n let postponedTo: number | null = null\n switch (decision.outcome) {\n case 'opted_out': {\n if (decidingMessage) await fileInbound(context, enrollment, decidingMessage)\n const complaint = decidedBy?.complaint === true\n await recordOutreachOptOut(deps, {\n orgId: context.orgId,\n email: enrollment.email,\n source: decidedBy?.evidence?.startsWith('To:') ? 'unsubscribe' : 'opt_out_reply',\n enrollment,\n hostIds: [enrollment.hostId],\n detail: decidedBy?.evidence ?? null,\n nowMs,\n complaint,\n })\n // A reply that called the email spam marks the send it answered\n // (AGL-3245), as the campaign webhook would mark a reported one.\n if (complaint) {\n await markOutreachEmailDelivery(deps, {\n orgId: context.orgId,\n messageId: lastSentMessageId,\n state: 'complained',\n atMs: decidedBy?.atMs || nowMs,\n detail: decidedBy?.evidence ?? null,\n })\n }\n report.optOuts += 1\n break\n }\n case 'replied': {\n if (decidingMessage) {\n await fileInbound(context, enrollment, decidingMessage)\n try {\n await fileOutreachTask(deps, {\n orgId: context.orgId,\n hostId: enrollment.hostId,\n link: outreachEnrollmentLink(enrollment),\n dedupeKey: `reply:${messageIdOf(decidingMessage) ?? decidingMessage.id}`,\n title: `Reply from ${enrollment.contactName || enrollment.email}`,\n notes: emailExcerpt(decidingMessage.textBody ?? decidingMessage.snippet ?? '', decidingMessage.htmlBody ?? '').slice(0, 500),\n kind: 'email',\n dueAtMs: nowMs,\n assigneeUid: context.mailbox.connectedByUid,\n })\n } catch (error) {\n console.error('[outreach] the reply task could not be filed', error)\n }\n }\n // A lead somebody wrote back to is being worked (AGL-3234): the record\n // system hears of the reply, and moves a lead nobody had worked to\n // Working (AGL-3080). Never throws.\n if (enrollment.target === 'lead' && enrollment.leadId && enrollment.email) {\n await stampRecordEmailReply({\n orgId: context.orgId,\n hostId: enrollment.hostId,\n emails: [enrollment.email],\n })\n }\n context.delta.replies += 1\n event = { type: 'reply', atMs: decidedBy?.atMs || nowMs, detail: decidedBy?.evidence ?? null }\n report.replies += 1\n // Once per enrollment (AGL-3254): a reply moves the status to\n // `replied`, and nothing is synced for it again.\n await creditOutreachReply(deps, { enrollment, atMs: event.atMs })\n break\n }\n case 'bounced': {\n const diagnostic = scrubbedOutreachDiagnostic(decidedBy?.bounce?.diagnostic ?? decidedBy?.bounce?.status ?? null, enrollment.email)\n await deps.suppressBouncedEmail({ email: enrollment.email, hostId: enrollment.hostId })\n await addOutreachDoNotContact(firestore, {\n orgId: context.orgId,\n email: enrollment.email,\n reason: 'hard_bounce',\n source: 'runtime',\n nowMs,\n enrollmentId: enrollment.id,\n sequenceId: enrollment.sequenceId,\n detail: diagnostic,\n })\n let detail = diagnostic\n // A gateway block is the domain's verdict on the sender (AGL-3244):\n // the domain is filed beside the address, and the enrollment says so.\n // Never a public mailbox provider's domain — Gmail refusing one\n // message on policy is not a reason to stop writing to Gmail.\n const domain = outreachEmailDomain(enrollment.email)\n const gateway = isOutreachGatewayBlock(decidedBy?.bounce ?? null)\n if (domain && !isPublicMailboxDomain(domain) && gateway) {\n await addOutreachDoNotContactDomain(firestore, {\n orgId: context.orgId,\n domain,\n reason: 'gateway_block',\n source: 'runtime',\n nowMs,\n enrollmentId: enrollment.id,\n sequenceId: enrollment.sequenceId,\n detail: diagnostic,\n })\n detail = outreachGatewayBlockDetail(domain, diagnostic)\n report.gatewayBlocks += 1\n }\n // The ledger learns the refusal (AGL-3326), whichever domain it was\n // at: a public provider refusing on policy is still that provider's\n // verdict on the sender, even though its domain is never listed.\n if (gateway) {\n await recordOutreachGatewayBlock(firestore, {\n orgId: context.orgId,\n email: enrollment.email,\n remoteMta: decidedBy?.bounce?.remoteMta ?? null,\n sendingDomain: outreachMailboxSendingDomain(context.mailbox),\n diagnostic,\n resolveMx: deps.resolveMx,\n nowMs,\n })\n }\n const bouncedAtMs = decidedBy?.atMs || nowMs\n // The record the person is says so too (AGL-3245): the verdict on the\n // lead and the contact, and the bounce on the send's own timeline\n // entry, so the record reads Sent, then Bounced.\n await deps.stampRecordEmailState({\n orgId: context.orgId,\n email: enrollment.email,\n state: {\n status: gateway ? 'blocked' : 'bounced',\n atMs: bouncedAtMs,\n source: 'sequence',\n detail: diagnostic,\n enrollmentId: enrollment.id,\n },\n })\n await markOutreachEmailDelivery(deps, {\n orgId: context.orgId,\n messageId: lastSentMessageId,\n state: 'bounced',\n atMs: bouncedAtMs,\n detail: diagnostic,\n })\n event = { type: 'bounce', atMs: bouncedAtMs, detail }\n report.bounces += 1\n break\n }\n case 'postpone': {\n const sequence = await sequenceOf(context, enrollment.sequenceId)\n postponedTo = postponeOutreachForAutoReply({\n nextDueAtMs: enrollment.nextDueAtMs,\n receivedAtMs: decidedBy?.atMs || nowMs,\n timeZone: context.mailbox.timezone,\n window: effectiveOutreachWindow(sequence?.settings.window, context.mailbox.window),\n random: deps.random,\n })\n break\n }\n default:\n break\n }\n\n const outcome = await applyOutreachEvent(firestore, {\n orgId: context.orgId,\n enrollmentId: enrollment.id,\n event,\n extra: (current) => {\n const extra: Record<string, unknown> = {\n syncedMessageIds: [...(current.syncedMessageIds ?? []), ...freshIds].slice(-ENROLLMENT_HANDLED_MAX),\n }\n if (inbound.length) extra['inboundMessages'] = mergeOutreachInboundMessages(current.inboundMessages, inbound)\n const waiting = current.status === 'active' || current.status === 'paused'\n if (postponedTo !== null && waiting && current.nextDueAtMs !== null && postponedTo > current.nextDueAtMs) {\n extra['nextDueAtMs'] = postponedTo\n }\n return extra\n },\n nowMs,\n })\n if (postponedTo !== null && outcome.enrollment?.nextDueAtMs === postponedTo) report.postponed += 1\n // The person's record says the sequence ended (AGL-3274), once, under the\n // reply that ended it — after the transaction moved the status, so a run\n // that reads the same reply again finds nothing to file. An opt-out's\n // line is `recordOutreachOptOut`'s, beside the lists it writes.\n if (event?.type === 'reply' && outcome.changed) {\n const sequence = await sequenceOf(context, enrollment.sequenceId)\n const entry = outreachStoppedEntry({\n enrollmentId: enrollment.id,\n sequenceName: sequence?.name ?? '',\n reason: 'replied',\n })\n await fileOutreachNote(deps, {\n orgId: context.orgId,\n hostId: enrollment.hostId,\n link: outreachEnrollmentLink(enrollment),\n dedupeKey: entry.dedupeKey,\n body: entry.body,\n atMs: event.atMs,\n })\n }\n // The run's own view of the enrollment moves with it, so a second message\n // of it in this run is judged against what this one did.\n if (outcome.enrollment) Object.assign(enrollment, outcome.enrollment)\n}\n"],"names":["normalizeContactEmail","isPublicMailboxDomain","emailAddressOf","emailExcerpt","outreachMessageIdHeader","readOutreachDeliveryReport","outreachEmailDomain","outreachStoppedEntry","isOutreachGatewayBlock","outreachGatewayBlockDetail","mergeOutreachInboundMessages","outreachInboundMessagesOf","matchOutreachPossibleReply","outreachPossibleReplyNote","outreachPossibleReplyTitle","effectiveOutreachWindow","postponeOutreachForAutoReply","decideOutreachThread","outreachAutoReplyEvidence","outreachHeader","outreachThreadMessageFromGmail","mailboxRef","OUTREACH_COLLECTIONS","addOutreachDoNotContact","addOutreachDoNotContactDomain","outreachEnrollmentLink","outreachOrgCollection","readStoredOutreachEnrollment","readStoredOutreachMailbox","readStoredOutreachSequence","GmailTransportError","isReconnectRequired","creditOutreachReply","applyOutreachEvent","recordOutreachOptOut","creditOutreachGatewayDeliveries","recordOutreachGatewayBlock","outreachMailboxSendingDomain","applyOutreachMailboxHealth","emptyOutreachHealthDelta","noteOutreachMailboxReconnectRequired","stampRecordEmailReply","fileOutreachEmail","fileOutreachNote","fileOutreachTask","markOutreachEmailDelivery","outreachUnsubscribeMailbox","watchedEnrollmentsOfOrg","OUTREACH_SYNC_JOB_ID","OUTREACH_SYNC_LOOKBACK_MS","OUTREACH_SYNC_OVERLAP_MS","OUTREACH_SYNC_WATCH_MS","SEARCH_PAGES","MAILBOX_HANDLED_MAX","MAILBOX_SYNC_WINDOW_REFRESH_MS","ENROLLMENT_HANDLED_MAX","FROM_CHUNK","POSSIBLE_REPLY_READS","POSSIBLE_REPLY_HEADERS","runOutreachSyncJob","deps","context","firestore","report","mailboxes","threads","replies","optOuts","bounces","gatewayBlocks","deliveries","postponed","paused","possibleReplies","all","collectionGroup","get","byOrg","Map","doc","docs","orgId","ref","parent","id","mailbox","data","status","set","now","deadlineMs","orgSnapshot","collection","org","exists","orgRefusal","watched","readWatchedEnrollmentDocs","nowMs","mailboxId","syncMailbox","error","errorCode","code","console","search","client","criteria","found","pageToken","page","list","searchMessages","maxResults","push","messages","filter","message","nextPageToken","input","opened","openMailbox","ok","reason","unsubscribe","email","selfAddresses","sendAs","sendAsOptions","map","option","Boolean","unsubscribeAddress","address","sequences","delta","touched","forMailbox","byThread","byAddress","watchedEnrollments","enrollment","known","threadId","gmailThreadIds","lastSentAtMs","sinceMs","Math","max","Number","sync","throughMs","handled","Set","handledMessageIds","newlyHandled","markHandled","has","add","fresh","stub","inbound","afterMs","notFromSelf","thread","getFullThread","applyMessages","from","getFullMessage","delivery","kind","failedAddresses","to","metadata","getMessage","metadataHeaders","headers","find","header","name","toLowerCase","value","includes","source","hostIds","hostId","detail","addresses","keys","start","length","chunk","slice","leftover","enrollments","enrollmentsOf","forOrg","Object","fromEntries","entry","fromHeader","sender","subject","match","enrolled","link","dedupeKey","title","replace","trim","notes","enrolledName","contactName","receivedBy","excerpt","snippet","join","dueAtMs","assigneeUid","connectedByUid","sendingDomain","resolveMx","update","query","undefined","where","sequenceOf","sequenceId","snapshot","messageIdOf","scrubbedOutreachDiagnostic","diagnostic","pattern","RegExp","fileInbound","messageId","direction","inReplyTo","body","textBody","htmlBody","atMs","internalDateMs","byUid","outcome","decision","recipient","syncedMessageIds","threadSubject","freshIds","classifications","classification","decidedBy","decidingMessage","lastSentMessageId","messageIds","aboutRecipient","bounce","recipients","complaint","complaintAtMs","event","postponedTo","evidence","startsWith","state","target","leadId","emails","type","suppressBouncedEmail","enrollmentId","domain","gateway","remoteMta","bouncedAtMs","stampRecordEmailState","sequence","nextDueAtMs","receivedAtMs","timeZone","timezone","window","settings","random","extra","current","inboundMessages","waiting","changed","sequenceName","assign"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,qBAAqB,QAAQ,kCAAiC;AACvE,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,cAAc,EAAEC,YAAY,QAAQ,oCAAmC;AAChF,SAASC,uBAAuB,QAAQ,uBAAmB;AAC3D,SAASC,0BAA0B,QAAQ,+BAA2B;AACtE,SAASC,mBAAmB,QAAQ,qCAAiC;AACrE,SAASC,oBAAoB,QAAQ,mCAA+B;AAEpE,SAASC,sBAAsB,EAAEC,0BAA0B,QAAQ,6BAAyB;AAC5F,SAASC,4BAA4B,EAAEC,yBAAyB,QAAQ,4BAAwB;AAChG,SACEC,0BAA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,OAAOpB,QAAQoB,KAAK;YACpBwG,QAAQ5C,WAAW4C,MAAM;YACzBoB,MAAMpL,uBAAuBoH;YAC7BiE,WAAWP,MAAMO,SAAS;YAC1BgC,MAAMvC,MAAMuC,IAAI;YAChBG,MAAMoB,MAAMpB,IAAI;QAClB;IACF;IACA,0EAA0E;IAC1E,yDAAyD;IACzD,IAAIG,QAAQvG,UAAU,EAAEwD,OAAO8F,MAAM,CAACtJ,YAAYuG,QAAQvG,UAAU;AACtE"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
/** The parts of a query document this reads. */
|
|
18
|
+
export interface WatchedEnrollmentDoc {
|
|
19
|
+
id: string;
|
|
20
|
+
get(field: string): unknown;
|
|
21
|
+
}
|
|
22
|
+
/** The two reads the cache stands in front of. */
|
|
23
|
+
export interface WatchedEnrollmentReads<D extends WatchedEnrollmentDoc> {
|
|
24
|
+
/** Every enrollment of the organization written to within the watch window. */
|
|
25
|
+
org(): Promise<D[]>;
|
|
26
|
+
/** The same, narrowed to one mailbox by the query itself. */
|
|
27
|
+
mailbox(mailboxId: string): Promise<D[]>;
|
|
28
|
+
}
|
|
29
|
+
export interface WatchedEnrollments<D extends WatchedEnrollmentDoc> {
|
|
30
|
+
/** One mailbox's watched enrollments, in the narrow query's order. */
|
|
31
|
+
forMailbox(mailboxId: string): Promise<D[]>;
|
|
32
|
+
/** The organization's watched enrollments. */
|
|
33
|
+
forOrg(): Promise<D[]>;
|
|
34
|
+
/** This run wrote an enrollment: a held set may no longer be current. */
|
|
35
|
+
touched(): void;
|
|
36
|
+
}
|
|
37
|
+
export declare function watchedEnrollmentsOfOrg<D extends WatchedEnrollmentDoc>(reads: WatchedEnrollmentReads<D>): WatchedEnrollments<D>;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ /*==========================================
|
|
17
|
+
* AN ORGANIZATION'S WATCHED ENROLLMENTS, READ ONCE PER SYNC RUN (AGL-4121)
|
|
18
|
+
*
|
|
19
|
+
* The sync job needs the watched enrollments twice over: each mailbox reads
|
|
20
|
+
* its own (`mailboxId ==` within the watch window), and the possible-reply
|
|
21
|
+
* step reads the whole organization's (AGL-4088). With six mailboxes and a
|
|
22
|
+
* couple of hundred people in sequences, that was every watched enrollment
|
|
23
|
+
* read twice every fifteen minutes, and it grew with each send.
|
|
24
|
+
*
|
|
25
|
+
* The organization's set is a superset of each mailbox's, read with the same
|
|
26
|
+
* window and in the same order, so one read answers both. The subset is the
|
|
27
|
+
* same documents in the same order the narrow query returns: both are
|
|
28
|
+
* ordered by `lastSentAtMs` and then by path, and filtering keeps that order.
|
|
29
|
+
*
|
|
30
|
+
* A held set is only as fresh as the run's own writes allow. A mailbox's sync
|
|
31
|
+
* can change another mailbox's enrollments — an opt-out stops every open
|
|
32
|
+
* enrollment of the address in the organization — so any step that writes an
|
|
33
|
+
* enrollment calls `touched()`, and after that:
|
|
34
|
+
*
|
|
35
|
+
* - the next mailbox reads its own with the narrow query, exactly as before;
|
|
36
|
+
* - the next possible-reply read re-reads the organization's set, so it is at
|
|
37
|
+
* least as fresh as the single lazy read it replaces.
|
|
38
|
+
*
|
|
39
|
+
* A quiet run (no reply, bounce or opt-out, which is nearly every run) reads
|
|
40
|
+
* the set once. Nothing reads it at all until a mailbox has opened, as
|
|
41
|
+
* before: a run whose mailboxes cannot be opened reads no enrollments.
|
|
42
|
+
*==========================================*/ /** The parts of a query document this reads. */ export function watchedEnrollmentsOfOrg(reads) {
|
|
43
|
+
let held = null;
|
|
44
|
+
let stale = false;
|
|
45
|
+
const readOrg = async ()=>{
|
|
46
|
+
const docs = await reads.org();
|
|
47
|
+
held = docs;
|
|
48
|
+
stale = false;
|
|
49
|
+
return docs;
|
|
50
|
+
};
|
|
51
|
+
return {
|
|
52
|
+
async forMailbox (mailboxId) {
|
|
53
|
+
if (held && stale) return reads.mailbox(mailboxId);
|
|
54
|
+
const docs = held != null ? held : await readOrg();
|
|
55
|
+
return docs.filter((doc)=>doc.get('mailboxId') === mailboxId);
|
|
56
|
+
},
|
|
57
|
+
async forOrg () {
|
|
58
|
+
return held && !stale ? held : readOrg();
|
|
59
|
+
},
|
|
60
|
+
touched () {
|
|
61
|
+
stale = true;
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
//# sourceMappingURL=watched-enrollments.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/runtime/watched-enrollments.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * AN ORGANIZATION'S WATCHED ENROLLMENTS, READ ONCE PER SYNC RUN (AGL-4121)\n *\n * The sync job needs the watched enrollments twice over: each mailbox reads\n * its own (`mailboxId ==` within the watch window), and the possible-reply\n * step reads the whole organization's (AGL-4088). With six mailboxes and a\n * couple of hundred people in sequences, that was every watched enrollment\n * read twice every fifteen minutes, and it grew with each send.\n *\n * The organization's set is a superset of each mailbox's, read with the same\n * window and in the same order, so one read answers both. The subset is the\n * same documents in the same order the narrow query returns: both are\n * ordered by `lastSentAtMs` and then by path, and filtering keeps that order.\n *\n * A held set is only as fresh as the run's own writes allow. A mailbox's sync\n * can change another mailbox's enrollments — an opt-out stops every open\n * enrollment of the address in the organization — so any step that writes an\n * enrollment calls `touched()`, and after that:\n *\n * - the next mailbox reads its own with the narrow query, exactly as before;\n * - the next possible-reply read re-reads the organization's set, so it is at\n * least as fresh as the single lazy read it replaces.\n *\n * A quiet run (no reply, bounce or opt-out, which is nearly every run) reads\n * the set once. Nothing reads it at all until a mailbox has opened, as\n * before: a run whose mailboxes cannot be opened reads no enrollments.\n *==========================================*/\n\n/** The parts of a query document this reads. */\nexport interface WatchedEnrollmentDoc {\n id: string\n get(field: string): unknown\n}\n\n/** The two reads the cache stands in front of. */\nexport interface WatchedEnrollmentReads<D extends WatchedEnrollmentDoc> {\n /** Every enrollment of the organization written to within the watch window. */\n org(): Promise<D[]>\n /** The same, narrowed to one mailbox by the query itself. */\n mailbox(mailboxId: string): Promise<D[]>\n}\n\nexport interface WatchedEnrollments<D extends WatchedEnrollmentDoc> {\n /** One mailbox's watched enrollments, in the narrow query's order. */\n forMailbox(mailboxId: string): Promise<D[]>\n /** The organization's watched enrollments. */\n forOrg(): Promise<D[]>\n /** This run wrote an enrollment: a held set may no longer be current. */\n touched(): void\n}\n\nexport function watchedEnrollmentsOfOrg<D extends WatchedEnrollmentDoc>(\n reads: WatchedEnrollmentReads<D>,\n): WatchedEnrollments<D> {\n let held: D[] | null = null\n let stale = false\n const readOrg = async (): Promise<D[]> => {\n const docs = await reads.org()\n held = docs\n stale = false\n return docs\n }\n return {\n async forMailbox(mailboxId) {\n if (held && stale) return reads.mailbox(mailboxId)\n const docs = held ?? (await readOrg())\n return docs.filter((doc) => doc.get('mailboxId') === mailboxId)\n },\n async forOrg() {\n return held && !stale ? held : readOrg()\n },\n touched() {\n stale = true\n },\n }\n}\n"],"names":["watchedEnrollmentsOfOrg","reads","held","stale","readOrg","docs","org","forMailbox","mailboxId","mailbox","filter","doc","get","forOrg","touched"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;4CA0B4C,GAE5C,8CAA8C,GAuB9C,OAAO,SAASA,wBACdC,KAAgC;IAEhC,IAAIC,OAAmB;IACvB,IAAIC,QAAQ;IACZ,MAAMC,UAAU;QACd,MAAMC,OAAO,MAAMJ,MAAMK,GAAG;QAC5BJ,OAAOG;QACPF,QAAQ;QACR,OAAOE;IACT;IACA,OAAO;QACL,MAAME,YAAWC,SAAS;YACxB,IAAIN,QAAQC,OAAO,OAAOF,MAAMQ,OAAO,CAACD;YACxC,MAAMH,OAAOH,eAAAA,OAAS,MAAME;YAC5B,OAAOC,KAAKK,MAAM,CAAC,CAACC,MAAQA,IAAIC,GAAG,CAAC,iBAAiBJ;QACvD;QACA,MAAMK;YACJ,OAAOX,QAAQ,CAACC,QAAQD,OAAOE;QACjC;QACAU;YACEX,QAAQ;QACV;IACF;AACF"}
|