@12-apps/messaging 0.0.0-stage → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ADOPTING.md +119 -0
- package/README.md +157 -2
- package/dist/channel-Cs_vLGl_.d.ts +293 -0
- package/dist/chunk-72TDAQUW.js +136 -0
- package/dist/chunk-72TDAQUW.js.map +1 -0
- package/dist/chunk-7QVYU63E.js +7 -0
- package/dist/chunk-7QVYU63E.js.map +1 -0
- package/dist/chunk-R3DKM2IV.js +42 -0
- package/dist/chunk-R3DKM2IV.js.map +1 -0
- package/dist/chunk-Y7MG2UDQ.js +36 -0
- package/dist/chunk-Y7MG2UDQ.js.map +1 -0
- package/dist/engine-DTnp2zUL.d.ts +431 -0
- package/dist/index.d.ts +97 -0
- package/dist/index.js +999 -0
- package/dist/index.js.map +1 -0
- package/dist/manifest/index.d.ts +36 -0
- package/dist/manifest/index.js +14 -0
- package/dist/manifest/index.js.map +1 -0
- package/dist/manifest/server.d.ts +21 -0
- package/dist/manifest/server.js +17 -0
- package/dist/manifest/server.js.map +1 -0
- package/dist/server/index.d.ts +78 -0
- package/dist/server/index.js +15 -0
- package/dist/server/index.js.map +1 -0
- package/dist/whatsapp/index.d.ts +180 -0
- package/dist/whatsapp/index.js +385 -0
- package/dist/whatsapp/index.js.map +1 -0
- package/package.json +90 -4
- package/prisma/messaging.prisma +140 -0
- package/prisma/migrations/20261114120000_messaging_connector/migration.sql +110 -0
- package/src/core/channel.ts +106 -0
- package/src/core/connections.ts +67 -0
- package/src/core/context.ts +28 -0
- package/src/core/engine.ts +64 -0
- package/src/core/errors.ts +53 -0
- package/src/core/hash.ts +6 -0
- package/src/core/inbound.ts +240 -0
- package/src/core/inbox.ts +139 -0
- package/src/core/memory-store.ts +273 -0
- package/src/core/ports.ts +129 -0
- package/src/core/prisma-store.ts +354 -0
- package/src/core/retention.ts +27 -0
- package/src/core/sender.ts +106 -0
- package/src/core/store.ts +217 -0
- package/src/core/types.ts +189 -0
- package/src/index.ts +54 -0
- package/src/manifest/index.ts +32 -0
- package/src/manifest/server.ts +18 -0
- package/src/server/index.ts +22 -0
- package/src/server/jobs.ts +99 -0
- package/src/server/webhook.ts +92 -0
- package/src/whatsapp/graph.ts +136 -0
- package/src/whatsapp/index.ts +64 -0
- package/src/whatsapp/opt-out.ts +26 -0
- package/src/whatsapp/parse.ts +200 -0
- package/src/whatsapp/signature.ts +52 -0
- package/src/whatsapp/signup.ts +115 -0
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import type { EngineContext } from "./context";
|
|
2
|
+
import { errorText } from "./errors";
|
|
3
|
+
import type { StoredConnection } from "./store";
|
|
4
|
+
import type {
|
|
5
|
+
ConversationState,
|
|
6
|
+
ConversationView,
|
|
7
|
+
InboundContent,
|
|
8
|
+
InboundMessageEvent,
|
|
9
|
+
MessageView,
|
|
10
|
+
NormalizedEvent,
|
|
11
|
+
OptOutEvent,
|
|
12
|
+
} from "./types";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* One normalized event, applied. The tenant is resolved HERE, from the
|
|
16
|
+
* event's channel account against the connections — never from the URL, which
|
|
17
|
+
* for a channel like WhatsApp is one callback shared by every tenant. An
|
|
18
|
+
* account nobody connected, or one revoked or in error, resolves to nobody:
|
|
19
|
+
* the event is dropped (the edge already answered 200, so the channel stops
|
|
20
|
+
* redelivering) and a tenant can never receive another tenant's traffic.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
export type EventOutcome =
|
|
24
|
+
| { kind: "dropped"; reason: "unknown-account" | "not-connected" }
|
|
25
|
+
| { kind: "duplicate" }
|
|
26
|
+
| { kind: "message"; conversationId: string; messageId: string }
|
|
27
|
+
| { kind: "opted-out"; conversationId: string }
|
|
28
|
+
| { kind: "receipt"; applied: boolean };
|
|
29
|
+
|
|
30
|
+
export async function handleEvent(ctx: EngineContext, channel: string, event: NormalizedEvent): Promise<EventOutcome> {
|
|
31
|
+
const connection = await ctx.config.store.findConnectionByAccount(channel, event.accountId);
|
|
32
|
+
if (!connection) return { kind: "dropped", reason: "unknown-account" };
|
|
33
|
+
if (connection.status !== "CONNECTED") return { kind: "dropped", reason: "not-connected" };
|
|
34
|
+
|
|
35
|
+
if (event.type === "message") return handleMessage(ctx, connection, event);
|
|
36
|
+
if (event.type === "opt_out") return handleOptOut(ctx, connection, event);
|
|
37
|
+
const applied = await ctx.config.store.applyReceipt({
|
|
38
|
+
tenantId: connection.tenantId,
|
|
39
|
+
channel,
|
|
40
|
+
externalId: event.externalId,
|
|
41
|
+
status: event.status,
|
|
42
|
+
at: event.at,
|
|
43
|
+
error: event.error,
|
|
44
|
+
});
|
|
45
|
+
return { kind: "receipt", applied };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The text a message row keeps, and the channel reference beside it. */
|
|
49
|
+
function columnsOf(content: InboundContent): { kind: InboundContent["kind"]; body: string | null; attachmentRef: string | null } {
|
|
50
|
+
switch (content.kind) {
|
|
51
|
+
case "TEXT":
|
|
52
|
+
return { kind: "TEXT", body: content.text, attachmentRef: null };
|
|
53
|
+
case "INTERACTIVE":
|
|
54
|
+
return { kind: "INTERACTIVE", body: content.title, attachmentRef: content.replyId };
|
|
55
|
+
case "AUDIO":
|
|
56
|
+
return { kind: "AUDIO", body: null, attachmentRef: content.mediaId };
|
|
57
|
+
default:
|
|
58
|
+
return { kind: "OTHER", body: null, attachmentRef: null };
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const later = (a: Date | null, b: Date): Date => (a && a > b ? a : b);
|
|
63
|
+
|
|
64
|
+
/** How many times a conversation write is re-decided after losing a compare-and-set. */
|
|
65
|
+
const MAX_WRITE_ATTEMPTS = 6;
|
|
66
|
+
|
|
67
|
+
async function handleMessage(
|
|
68
|
+
ctx: EngineContext,
|
|
69
|
+
connection: StoredConnection,
|
|
70
|
+
event: InboundMessageEvent,
|
|
71
|
+
): Promise<EventOutcome> {
|
|
72
|
+
const { store } = ctx.config;
|
|
73
|
+
if (await store.findMessageByExternalId(connection.channel, event.externalId)) return { kind: "duplicate" };
|
|
74
|
+
|
|
75
|
+
const columns = columnsOf(event.content);
|
|
76
|
+
const conversation = await openConversation(ctx, connection, event, columns.body !== null);
|
|
77
|
+
const inserted = await store.insertMessage({
|
|
78
|
+
conversationId: conversation.id,
|
|
79
|
+
tenantId: connection.tenantId,
|
|
80
|
+
channel: connection.channel,
|
|
81
|
+
direction: "INBOUND",
|
|
82
|
+
...columns,
|
|
83
|
+
options: null,
|
|
84
|
+
externalId: event.externalId,
|
|
85
|
+
deliveryStatus: "RECEIVED",
|
|
86
|
+
authorKind: "CONTACT",
|
|
87
|
+
staffUserId: null,
|
|
88
|
+
createdAt: event.sentAt,
|
|
89
|
+
});
|
|
90
|
+
if (!inserted.created) return { kind: "duplicate" };
|
|
91
|
+
// Stored, but nothing may be said: the contact opted out with this message,
|
|
92
|
+
// or this one was sent BEFORE their opt-out and only now got processed.
|
|
93
|
+
if (event.optOut || conversation.state === "OPTED_OUT") return { kind: "opted-out", conversationId: conversation.id };
|
|
94
|
+
|
|
95
|
+
await notifyHost(ctx, conversation, inserted.message);
|
|
96
|
+
return { kind: "message", conversationId: conversation.id, messageId: inserted.message.id };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Create the conversation, or bring an existing one up to this message.
|
|
101
|
+
*
|
|
102
|
+
* Every write to an existing row is a compare-and-set on what was read (its
|
|
103
|
+
* state and its two timestamps): a worker that lost the race re-reads and
|
|
104
|
+
* decides again, so a stale read can never put back a state another worker
|
|
105
|
+
* just changed — an opt-out above all.
|
|
106
|
+
*/
|
|
107
|
+
async function openConversation(
|
|
108
|
+
ctx: EngineContext,
|
|
109
|
+
connection: StoredConnection,
|
|
110
|
+
event: InboundMessageEvent,
|
|
111
|
+
carriesText: boolean,
|
|
112
|
+
): Promise<ConversationView> {
|
|
113
|
+
const { store } = ctx.config;
|
|
114
|
+
for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS; attempt += 1) {
|
|
115
|
+
const existing = await store.findConversation(connection.tenantId, connection.channel, event.contactId);
|
|
116
|
+
// A lost insert race answers a null: go again, and the winner's row is `existing`.
|
|
117
|
+
const result = existing
|
|
118
|
+
? await updateExisting(ctx, connection, existing, event, carriesText)
|
|
119
|
+
: await createFirst(ctx, connection, event, carriesText);
|
|
120
|
+
if (result) return result;
|
|
121
|
+
}
|
|
122
|
+
throw new Error(`conversation ${event.contactId} kept changing under this message; retry`);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** The first message of a contact opens the conversation; null when another worker's insert won. */
|
|
126
|
+
async function createFirst(
|
|
127
|
+
ctx: EngineContext,
|
|
128
|
+
connection: StoredConnection,
|
|
129
|
+
event: InboundMessageEvent,
|
|
130
|
+
carriesText: boolean,
|
|
131
|
+
): Promise<ConversationView | null> {
|
|
132
|
+
const state = event.optOut ? "OPTED_OUT" : "AGENT";
|
|
133
|
+
const created = await ctx.config.store.createConversation({
|
|
134
|
+
tenantId: connection.tenantId,
|
|
135
|
+
channel: connection.channel,
|
|
136
|
+
contactId: event.contactId,
|
|
137
|
+
contactName: event.contactName,
|
|
138
|
+
connectionId: connection.id,
|
|
139
|
+
state,
|
|
140
|
+
lastInboundAt: event.sentAt,
|
|
141
|
+
lastMessageAt: event.sentAt,
|
|
142
|
+
optedOutAt: event.optOut ? event.sentAt : null,
|
|
143
|
+
hasText: carriesText,
|
|
144
|
+
});
|
|
145
|
+
return created.state === state && created.lastInboundAt?.getTime() === event.sentAt.getTime() ? created : null;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Bring an existing conversation up to this message; null when the compare-and-set lost. */
|
|
149
|
+
async function updateExisting(
|
|
150
|
+
ctx: EngineContext,
|
|
151
|
+
connection: StoredConnection,
|
|
152
|
+
existing: ConversationView,
|
|
153
|
+
event: InboundMessageEvent,
|
|
154
|
+
carriesText: boolean,
|
|
155
|
+
): Promise<ConversationView | null> {
|
|
156
|
+
const state = await nextState(ctx, existing, event);
|
|
157
|
+
return ctx.config.store.updateConversation(
|
|
158
|
+
connection.tenantId,
|
|
159
|
+
existing.id,
|
|
160
|
+
{
|
|
161
|
+
// Left out when unchanged: the write never carries a state it did not decide.
|
|
162
|
+
...(state !== existing.state ? { state } : {}),
|
|
163
|
+
...(event.optOut ? { optedOutAt: later(existing.optedOutAt, event.sentAt) } : {}),
|
|
164
|
+
...(connection.id !== existing.connectionId ? { connectionId: connection.id } : {}),
|
|
165
|
+
lastInboundAt: later(existing.lastInboundAt, event.sentAt),
|
|
166
|
+
lastMessageAt: later(existing.lastMessageAt, event.sentAt),
|
|
167
|
+
...(event.contactName ? { contactName: event.contactName } : {}),
|
|
168
|
+
...(carriesText ? { hasText: true } : {}),
|
|
169
|
+
},
|
|
170
|
+
{ state: existing.state, lastInboundAt: existing.lastInboundAt, lastMessageAt: existing.lastMessageAt, optedOutAt: existing.optedOutAt },
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* An opt-out wins. A message re-opens a CLOSED conversation, and an OPTED_OUT
|
|
176
|
+
* one only when it was sent AFTER the opt-out (the message's own time, so a
|
|
177
|
+
* delivery processed late, out of order, never undoes it).
|
|
178
|
+
*/
|
|
179
|
+
async function nextState(ctx: EngineContext, conversation: ConversationView, event: InboundMessageEvent): Promise<ConversationState> {
|
|
180
|
+
if (event.optOut) return "OPTED_OUT";
|
|
181
|
+
if (conversation.state === "OPTED_OUT") {
|
|
182
|
+
if (conversation.optedOutAt && event.sentAt <= conversation.optedOutAt) return "OPTED_OUT";
|
|
183
|
+
} else if (conversation.state !== "CLOSED") {
|
|
184
|
+
return conversation.state;
|
|
185
|
+
}
|
|
186
|
+
// The type refuses OPTED_OUT; a JavaScript host that returns it anyway is read as the default.
|
|
187
|
+
const chosen = (await ctx.config.hooks?.reopenState?.(conversation)) as ConversationState | undefined;
|
|
188
|
+
return chosen && chosen !== "OPTED_OUT" ? chosen : "AGENT";
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
async function notifyHost(
|
|
192
|
+
ctx: EngineContext,
|
|
193
|
+
conversation: ConversationView,
|
|
194
|
+
message: MessageView,
|
|
195
|
+
): Promise<void> {
|
|
196
|
+
const hook = ctx.config.hooks?.onInboundMessage;
|
|
197
|
+
if (!hook) return;
|
|
198
|
+
try {
|
|
199
|
+
await hook({ conversation, message });
|
|
200
|
+
} catch (error) {
|
|
201
|
+
// The message is stored; a retry of the delivery would be a no-op, so the
|
|
202
|
+
// hook's failure is the host's to log and recover from, never a re-run.
|
|
203
|
+
ctx.config.logger.error(`messaging.inbound: onInboundMessage failed for ${conversation.id}: ${errorText(error)}`, { error });
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async function handleOptOut(ctx: EngineContext, connection: StoredConnection, event: OptOutEvent): Promise<EventOutcome> {
|
|
208
|
+
const { store } = ctx.config;
|
|
209
|
+
for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS; attempt += 1) {
|
|
210
|
+
const existing = await store.findConversation(connection.tenantId, connection.channel, event.contactId);
|
|
211
|
+
if (!existing) {
|
|
212
|
+
// No conversation yet: one is opened in OPTED_OUT, so a later send is refused.
|
|
213
|
+
const created = await store.createConversation({
|
|
214
|
+
tenantId: connection.tenantId,
|
|
215
|
+
channel: connection.channel,
|
|
216
|
+
contactId: event.contactId,
|
|
217
|
+
contactName: null,
|
|
218
|
+
connectionId: connection.id,
|
|
219
|
+
state: "OPTED_OUT",
|
|
220
|
+
lastInboundAt: null,
|
|
221
|
+
lastMessageAt: null,
|
|
222
|
+
optedOutAt: event.at,
|
|
223
|
+
hasText: false,
|
|
224
|
+
});
|
|
225
|
+
if (created.state === "OPTED_OUT") return { kind: "opted-out", conversationId: created.id };
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
const updated = await store.updateConversation(
|
|
229
|
+
connection.tenantId,
|
|
230
|
+
existing.id,
|
|
231
|
+
{
|
|
232
|
+
...(existing.state !== "OPTED_OUT" ? { state: "OPTED_OUT" as const } : {}),
|
|
233
|
+
optedOutAt: later(existing.optedOutAt, event.at),
|
|
234
|
+
},
|
|
235
|
+
{ state: existing.state, lastInboundAt: existing.lastInboundAt, lastMessageAt: existing.lastMessageAt, optedOutAt: existing.optedOutAt },
|
|
236
|
+
);
|
|
237
|
+
if (updated) return { kind: "opted-out", conversationId: existing.id };
|
|
238
|
+
}
|
|
239
|
+
throw new Error(`conversation ${event.contactId} kept changing under this opt-out; retry`);
|
|
240
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import type { EngineContext } from "./context";
|
|
2
|
+
import { errorText } from "./errors";
|
|
3
|
+
import { bodyHash } from "./hash";
|
|
4
|
+
import { handleEvent, type EventOutcome } from "./inbound";
|
|
5
|
+
import type { NormalizedEvent } from "./types";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The durable inbox: persist the raw delivery, ACK, then process in a job.
|
|
9
|
+
*
|
|
10
|
+
* Nothing is resolved before the row is written — not the tenant, not even
|
|
11
|
+
* whether the body parses — because the one thing a webhook must never do is
|
|
12
|
+
* lose a delivery to a bug in the code that reads it. The raw bytes are kept
|
|
13
|
+
* so a mapping bug can be replayed once fixed — until the retention sweep
|
|
14
|
+
* deletes them, with the conversation's text, past the retention window.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/** The job the engine enqueues per fresh delivery, by wire name. */
|
|
18
|
+
export const PROCESS_DELIVERY_JOB = "messaging.process-delivery";
|
|
19
|
+
|
|
20
|
+
/** Store one verified delivery and queue its processing. Redeliveries are stored once. */
|
|
21
|
+
export async function receiveDelivery(
|
|
22
|
+
ctx: EngineContext,
|
|
23
|
+
channel: string,
|
|
24
|
+
rawBody: string,
|
|
25
|
+
): Promise<{ deliveryId: string; fresh: boolean }> {
|
|
26
|
+
const { store, clock, enqueue, logger } = ctx.config;
|
|
27
|
+
const recorded = await store.recordDelivery({ channel, bodyHash: bodyHash(rawBody), rawBody, receivedAt: clock.now() });
|
|
28
|
+
if (recorded.fresh) {
|
|
29
|
+
const queued = await enqueue.enqueue(
|
|
30
|
+
PROCESS_DELIVERY_JOB,
|
|
31
|
+
{ deliveryId: recorded.id },
|
|
32
|
+
{ dedupeKey: `${PROCESS_DELIVERY_JOB}:${recorded.id}` },
|
|
33
|
+
);
|
|
34
|
+
// Never fatal: the row is stored, and the reconciliation sweep runs it.
|
|
35
|
+
if (!queued.enqueued) logger.warn(`messaging.inbox: delivery ${recorded.id} not queued (${queued.reason ?? "no reason"})`);
|
|
36
|
+
}
|
|
37
|
+
return { deliveryId: recorded.id, fresh: recorded.fresh };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** What processing one stored delivery did. */
|
|
41
|
+
export type DeliveryOutcome =
|
|
42
|
+
| { kind: "missing" }
|
|
43
|
+
| { kind: "already-processed" }
|
|
44
|
+
| { kind: "processed"; events: EventOutcome[] }
|
|
45
|
+
| { kind: "unreadable"; reason: string };
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Process one stored delivery. Every event handler is idempotent (messages
|
|
49
|
+
* dedupe on their channel id, receipts on their column), so a retry after a
|
|
50
|
+
* partial failure redoes nothing. A throw settles the row FAILED and is
|
|
51
|
+
* rethrown, so the job's own retry runs it again; a receipt that found no
|
|
52
|
+
* message to land on settles it FAILED too, left to the reconciliation sweep.
|
|
53
|
+
*/
|
|
54
|
+
export async function processDelivery(ctx: EngineContext, deliveryId: string): Promise<DeliveryOutcome> {
|
|
55
|
+
const { store, clock, logger } = ctx.config;
|
|
56
|
+
const row = await store.getDelivery(deliveryId);
|
|
57
|
+
if (!row) return { kind: "missing" };
|
|
58
|
+
if (row.state === "PROCESSED") return { kind: "already-processed" };
|
|
59
|
+
|
|
60
|
+
const adapter = ctx.adapters.get(row.channel);
|
|
61
|
+
let events: NormalizedEvent[];
|
|
62
|
+
try {
|
|
63
|
+
if (!adapter) throw new Error(`no adapter mounted for channel "${row.channel}"`);
|
|
64
|
+
events = adapter.parse(row.rawBody);
|
|
65
|
+
} catch (error) {
|
|
66
|
+
// The same bytes will never read differently: settle it, with the reason,
|
|
67
|
+
// rather than retry. The raw body stays for a replay until retention deletes it.
|
|
68
|
+
const reason = errorText(error);
|
|
69
|
+
logger.warn(`messaging.inbox: delivery ${deliveryId} unreadable: ${reason}`);
|
|
70
|
+
await store.settleDelivery(deliveryId, { state: "PROCESSED", error: `unreadable: ${reason}`, at: clock.now() });
|
|
71
|
+
return { kind: "unreadable", reason };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
try {
|
|
75
|
+
const outcomes: EventOutcome[] = [];
|
|
76
|
+
for (const event of events) outcomes.push(await handleEvent(ctx, row.channel, event));
|
|
77
|
+
// Inside the try: a throwing hook settles the row FAILED for the sweep.
|
|
78
|
+
await handOverUnclaimed(ctx, row.channel, events, outcomes);
|
|
79
|
+
// A receipt for a message nobody stored yet (it raced the sender's own
|
|
80
|
+
// write of the channel id) changed nothing: settle FAILED, not PROCESSED,
|
|
81
|
+
// so the reconciliation sweep applies it once the id exists.
|
|
82
|
+
const unapplied = outcomes.filter((outcome) => outcome.kind === "receipt" && !outcome.applied).length;
|
|
83
|
+
if (unapplied > 0) {
|
|
84
|
+
const error = `${unapplied} receipt(s) for a message not stored yet`;
|
|
85
|
+
logger.warn(`messaging.inbox: delivery ${deliveryId}: ${error}`);
|
|
86
|
+
await store.settleDelivery(deliveryId, { state: "FAILED", error, at: clock.now() });
|
|
87
|
+
} else {
|
|
88
|
+
await store.settleDelivery(deliveryId, { state: "PROCESSED", error: null, at: clock.now() });
|
|
89
|
+
}
|
|
90
|
+
return { kind: "processed", events: outcomes };
|
|
91
|
+
} catch (error) {
|
|
92
|
+
await store.settleDelivery(deliveryId, { state: "FAILED", error: errorText(error), at: clock.now() });
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* The events whose account nobody connected, handed to the host's
|
|
99
|
+
* `onUnclaimedEvents` (its own number on the shared app). Only `unknown-account`
|
|
100
|
+
* drops: a revoked or errored account is a tenant's, never the host's.
|
|
101
|
+
*/
|
|
102
|
+
async function handOverUnclaimed(
|
|
103
|
+
ctx: EngineContext,
|
|
104
|
+
channel: string,
|
|
105
|
+
events: readonly NormalizedEvent[],
|
|
106
|
+
outcomes: readonly EventOutcome[],
|
|
107
|
+
): Promise<void> {
|
|
108
|
+
const hook = ctx.config.hooks?.onUnclaimedEvents;
|
|
109
|
+
if (!hook) return;
|
|
110
|
+
const unclaimed = events.filter((_, index) => {
|
|
111
|
+
const outcome = outcomes[index];
|
|
112
|
+
return outcome?.kind === "dropped" && outcome.reason === "unknown-account";
|
|
113
|
+
});
|
|
114
|
+
if (unclaimed.length > 0) await hook(channel, unclaimed);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Re-run deliveries left unprocessed (a dead worker, a refused enqueue, a
|
|
119
|
+
* failure) once they are older than the job's own retry span. One delivery's
|
|
120
|
+
* failure never stops the batch.
|
|
121
|
+
*/
|
|
122
|
+
export async function reconcileInbox(ctx: EngineContext): Promise<{ retried: number; failed: number }> {
|
|
123
|
+
const { store, clock, logger, reconcileAfterMs, maxDeliveryAttempts, reconcileBatchSize } = ctx.config;
|
|
124
|
+
const due = await store.listRetryableDeliveries({
|
|
125
|
+
receivedBefore: new Date(clock.now().getTime() - reconcileAfterMs),
|
|
126
|
+
maxAttempts: maxDeliveryAttempts,
|
|
127
|
+
take: reconcileBatchSize,
|
|
128
|
+
});
|
|
129
|
+
let failed = 0;
|
|
130
|
+
for (const row of due) {
|
|
131
|
+
try {
|
|
132
|
+
await processDelivery(ctx, row.id);
|
|
133
|
+
} catch (error) {
|
|
134
|
+
failed += 1;
|
|
135
|
+
logger.warn(`messaging.inbox: delivery ${row.id} failed again: ${errorText(error)}`);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return { retried: due.length, failed };
|
|
139
|
+
}
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
import { DELIVERY_RANK, RECEIPT_COLUMN, type ConversationGuard, type MessagingStore, type StoredConnection } from "./store";
|
|
4
|
+
import type { ConnectionView, ConversationView, InboxDeliveryView, MessageView } from "./types";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* An in-memory {@link MessagingStore}, for a host's tests and this package's
|
|
8
|
+
* own. It enforces the migration's unique keys the way Postgres does, so a
|
|
9
|
+
* test that passes here exercises the same dedupe a database would.
|
|
10
|
+
*
|
|
11
|
+
* Not for production: it lives in one process and forgets on restart.
|
|
12
|
+
*/
|
|
13
|
+
export function createMemoryMessagingStore(): MessagingStore & { readonly dump: () => MemoryStoreDump } {
|
|
14
|
+
const tables: MemoryTables = {
|
|
15
|
+
deliveries: new Map(),
|
|
16
|
+
connections: new Map(),
|
|
17
|
+
conversations: new Map(),
|
|
18
|
+
messages: new Map(),
|
|
19
|
+
};
|
|
20
|
+
return {
|
|
21
|
+
...memoryInbox(tables),
|
|
22
|
+
...memoryConnections(tables),
|
|
23
|
+
...memoryConversations(tables),
|
|
24
|
+
...memoryMessages(tables),
|
|
25
|
+
purgeExpiredText: async (input) => purge(tables, input),
|
|
26
|
+
purgeExpiredDeliveries: async (input) => purgeDeliveries(tables, input),
|
|
27
|
+
dump: () => ({
|
|
28
|
+
deliveries: [...tables.deliveries.values()].map(copy),
|
|
29
|
+
connections: [...tables.connections.values()].map(copy),
|
|
30
|
+
conversations: [...tables.conversations.values()].map(copy),
|
|
31
|
+
messages: [...tables.messages.values()].map(copy),
|
|
32
|
+
}),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Everything the memory store holds, for a test to assert on. */
|
|
37
|
+
export interface MemoryStoreDump {
|
|
38
|
+
deliveries: StoredDelivery[];
|
|
39
|
+
connections: StoredConnection[];
|
|
40
|
+
conversations: ConversationView[];
|
|
41
|
+
messages: MessageView[];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
type StoredDelivery = InboxDeliveryView & { bodyHash: string };
|
|
45
|
+
|
|
46
|
+
interface MemoryTables {
|
|
47
|
+
deliveries: Map<string, StoredDelivery>;
|
|
48
|
+
connections: Map<string, StoredConnection>;
|
|
49
|
+
conversations: Map<string, ConversationView>;
|
|
50
|
+
messages: Map<string, MessageView>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const copy = <T extends object>(row: T): T => ({ ...row });
|
|
54
|
+
/** A copy of `row` without `key`: what a real select would not return. */
|
|
55
|
+
function without<T extends object, K extends keyof T>(row: T, key: K): Omit<T, K> {
|
|
56
|
+
return Object.fromEntries(Object.entries(row).filter(([name]) => name !== key)) as Omit<T, K>;
|
|
57
|
+
}
|
|
58
|
+
const deliveryView = (row: StoredDelivery): InboxDeliveryView => without(row, "bodyHash");
|
|
59
|
+
const connectionView = (row: StoredConnection): ConnectionView => without(row, "credentialSealed");
|
|
60
|
+
|
|
61
|
+
function memoryInbox({ deliveries }: MemoryTables) {
|
|
62
|
+
return {
|
|
63
|
+
async recordDelivery({ channel, bodyHash, rawBody, receivedAt }) {
|
|
64
|
+
const existing = [...deliveries.values()].find((row) => row.channel === channel && row.bodyHash === bodyHash);
|
|
65
|
+
if (existing) return { id: existing.id, fresh: false };
|
|
66
|
+
const id = randomUUID();
|
|
67
|
+
deliveries.set(id, { id, channel, bodyHash, rawBody, state: "PENDING", attempts: 0, error: null, receivedAt, processedAt: null });
|
|
68
|
+
return { id, fresh: true };
|
|
69
|
+
},
|
|
70
|
+
async getDelivery(id) {
|
|
71
|
+
const row = deliveries.get(id);
|
|
72
|
+
return row ? deliveryView(row) : null;
|
|
73
|
+
},
|
|
74
|
+
async settleDelivery(id, { state, error, at }) {
|
|
75
|
+
const row = deliveries.get(id);
|
|
76
|
+
if (row) deliveries.set(id, { ...row, state, error, processedAt: at, attempts: row.attempts + 1 });
|
|
77
|
+
},
|
|
78
|
+
async listRetryableDeliveries({ receivedBefore, maxAttempts, take }) {
|
|
79
|
+
return [...deliveries.values()]
|
|
80
|
+
.filter((row) => row.state !== "PROCESSED" && row.attempts < maxAttempts && row.receivedAt < receivedBefore)
|
|
81
|
+
.sort((a, b) => a.receivedAt.getTime() - b.receivedAt.getTime())
|
|
82
|
+
.slice(0, take)
|
|
83
|
+
.map(deliveryView);
|
|
84
|
+
},
|
|
85
|
+
} satisfies Partial<MessagingStore>;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function memoryConnections({ connections }: MemoryTables) {
|
|
89
|
+
const findConnectionByAccount = async (channel: string, externalAccountId: string) => {
|
|
90
|
+
const row = [...connections.values()].find(
|
|
91
|
+
(candidate) => candidate.channel === channel && candidate.externalAccountId === externalAccountId,
|
|
92
|
+
);
|
|
93
|
+
return row ? copy(row) : null;
|
|
94
|
+
};
|
|
95
|
+
return {
|
|
96
|
+
findConnectionByAccount,
|
|
97
|
+
async getConnection(tenantId, id) {
|
|
98
|
+
const row = connections.get(id);
|
|
99
|
+
return row && row.tenantId === tenantId ? copy(row) : null;
|
|
100
|
+
},
|
|
101
|
+
async listConnections(tenantId) {
|
|
102
|
+
return [...connections.values()].filter((row) => row.tenantId === tenantId).map(connectionView);
|
|
103
|
+
},
|
|
104
|
+
async saveConnection(input) {
|
|
105
|
+
// Read and write with no await between them: the check-and-set is atomic, as the database's unique key makes it.
|
|
106
|
+
const existing = [...connections.values()].find(
|
|
107
|
+
(candidate) => candidate.channel === input.channel && candidate.externalAccountId === input.externalAccountId,
|
|
108
|
+
);
|
|
109
|
+
if (existing && existing.tenantId !== input.tenantId && existing.status !== "REVOKED") return null;
|
|
110
|
+
const row: StoredConnection = {
|
|
111
|
+
id: existing?.id ?? randomUUID(),
|
|
112
|
+
...input,
|
|
113
|
+
status: "CONNECTED",
|
|
114
|
+
statusReason: null,
|
|
115
|
+
revokedAt: null,
|
|
116
|
+
};
|
|
117
|
+
connections.set(row.id, row);
|
|
118
|
+
return connectionView(row);
|
|
119
|
+
},
|
|
120
|
+
async setConnectionStatus(tenantId, id, patch) {
|
|
121
|
+
const row = connections.get(id);
|
|
122
|
+
if (!row || row.tenantId !== tenantId) return false;
|
|
123
|
+
connections.set(id, { ...row, ...patch });
|
|
124
|
+
return true;
|
|
125
|
+
},
|
|
126
|
+
} satisfies Partial<MessagingStore>;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function memoryConversations({ conversations }: MemoryTables) {
|
|
130
|
+
const findConversation = async (tenantId: string, channel: string, contactId: string) => {
|
|
131
|
+
const row = [...conversations.values()].find(
|
|
132
|
+
(candidate) => candidate.tenantId === tenantId && candidate.channel === channel && candidate.contactId === contactId,
|
|
133
|
+
);
|
|
134
|
+
return row ? copy(row) : null;
|
|
135
|
+
};
|
|
136
|
+
return {
|
|
137
|
+
findConversation,
|
|
138
|
+
async getConversation(tenantId, id) {
|
|
139
|
+
const row = conversations.get(id);
|
|
140
|
+
return row && row.tenantId === tenantId ? copy(row) : null;
|
|
141
|
+
},
|
|
142
|
+
async createConversation(input) {
|
|
143
|
+
const existing = await findConversation(input.tenantId, input.channel, input.contactId);
|
|
144
|
+
if (existing) return existing;
|
|
145
|
+
const row: ConversationView = {
|
|
146
|
+
id: randomUUID(),
|
|
147
|
+
...input,
|
|
148
|
+
optedOutAt: input.optedOutAt ?? null,
|
|
149
|
+
summary: null,
|
|
150
|
+
summaryUpdatedAt: null,
|
|
151
|
+
createdAt: new Date(),
|
|
152
|
+
};
|
|
153
|
+
conversations.set(row.id, row);
|
|
154
|
+
return copy(row);
|
|
155
|
+
},
|
|
156
|
+
async updateConversation(tenantId, id, patch, guard) {
|
|
157
|
+
const row = conversations.get(id);
|
|
158
|
+
if (!row || row.tenantId !== tenantId) return null;
|
|
159
|
+
// No await between this check and the write below: the compare-and-set is atomic.
|
|
160
|
+
if (guard && !matchesGuard(row, guard)) return null;
|
|
161
|
+
const next = { ...row, ...patch };
|
|
162
|
+
conversations.set(id, next);
|
|
163
|
+
return copy(next);
|
|
164
|
+
},
|
|
165
|
+
} satisfies Partial<MessagingStore>;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const sameTime = (a: Date | null, b: Date | null): boolean => (a === null || b === null ? a === b : a.getTime() === b.getTime());
|
|
169
|
+
|
|
170
|
+
const GUARDED_TIMES = ["lastInboundAt", "lastMessageAt", "optedOutAt"] as const;
|
|
171
|
+
|
|
172
|
+
function matchesGuard(row: ConversationView, guard: ConversationGuard): boolean {
|
|
173
|
+
if (guard.state !== undefined && row.state !== guard.state) return false;
|
|
174
|
+
if (guard.stateNot !== undefined && row.state === guard.stateNot) return false;
|
|
175
|
+
return GUARDED_TIMES.every((key) => {
|
|
176
|
+
const wanted = guard[key];
|
|
177
|
+
return wanted === undefined || sameTime(row[key], wanted);
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function memoryMessages({ messages }: MemoryTables) {
|
|
182
|
+
const findMessageByExternalId = async (channel: string, externalId: string) => {
|
|
183
|
+
const row = [...messages.values()].find((candidate) => candidate.channel === channel && candidate.externalId === externalId);
|
|
184
|
+
return row ? copy(row) : null;
|
|
185
|
+
};
|
|
186
|
+
return {
|
|
187
|
+
findMessageByExternalId,
|
|
188
|
+
async insertMessage(input) {
|
|
189
|
+
const existing = input.externalId === null ? null : await findMessageByExternalId(input.channel, input.externalId);
|
|
190
|
+
if (existing) return { created: false, message: existing };
|
|
191
|
+
const row: MessageView = {
|
|
192
|
+
id: randomUUID(),
|
|
193
|
+
...input,
|
|
194
|
+
transcript: null,
|
|
195
|
+
error: null,
|
|
196
|
+
sentAt: null,
|
|
197
|
+
deliveredAt: null,
|
|
198
|
+
readAt: null,
|
|
199
|
+
failedAt: null,
|
|
200
|
+
};
|
|
201
|
+
messages.set(row.id, row);
|
|
202
|
+
return { created: true, message: copy(row) };
|
|
203
|
+
},
|
|
204
|
+
async updateMessage(tenantId, id, patch) {
|
|
205
|
+
const row = messages.get(id);
|
|
206
|
+
if (!row || row.tenantId !== tenantId) return null;
|
|
207
|
+
const taken = patch.externalId === undefined ? null : await findMessageByExternalId(row.channel, patch.externalId);
|
|
208
|
+
if (taken && taken.id !== id) throw Object.assign(new Error("unique"), { code: "P2002" });
|
|
209
|
+
const next = { ...row, ...patch };
|
|
210
|
+
messages.set(id, next);
|
|
211
|
+
return copy(next);
|
|
212
|
+
},
|
|
213
|
+
async listMessages(tenantId, conversationId) {
|
|
214
|
+
return [...messages.values()]
|
|
215
|
+
.filter((row) => row.tenantId === tenantId && row.conversationId === conversationId)
|
|
216
|
+
.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime())
|
|
217
|
+
.map(copy);
|
|
218
|
+
},
|
|
219
|
+
async applyReceipt({ tenantId, channel, externalId, status, at, error }) {
|
|
220
|
+
const row = [...messages.values()].find(
|
|
221
|
+
(candidate) =>
|
|
222
|
+
candidate.tenantId === tenantId &&
|
|
223
|
+
candidate.channel === channel &&
|
|
224
|
+
candidate.externalId === externalId &&
|
|
225
|
+
candidate.direction === "OUTBOUND",
|
|
226
|
+
);
|
|
227
|
+
if (!row) return false;
|
|
228
|
+
const column = RECEIPT_COLUMN[status];
|
|
229
|
+
const stamp = row[column] === null;
|
|
230
|
+
const forward = DELIVERY_RANK[status] > DELIVERY_RANK[row.deliveryStatus];
|
|
231
|
+
messages.set(row.id, {
|
|
232
|
+
...row,
|
|
233
|
+
...(stamp ? { [column]: at, ...(error !== null ? { error } : {}) } : {}),
|
|
234
|
+
...(forward ? { deliveryStatus: status } : {}),
|
|
235
|
+
});
|
|
236
|
+
return true;
|
|
237
|
+
},
|
|
238
|
+
} satisfies Partial<MessagingStore>;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function purgeDeliveries(
|
|
242
|
+
{ deliveries }: MemoryTables,
|
|
243
|
+
{ cutoff, maxAttempts, take }: { cutoff: Date; maxAttempts: number; take: number },
|
|
244
|
+
): number {
|
|
245
|
+
const due = (match: (row: StoredDelivery) => boolean) =>
|
|
246
|
+
[...deliveries.values()]
|
|
247
|
+
.filter((row) => row.receivedAt < cutoff && match(row))
|
|
248
|
+
.sort((a, b) => a.receivedAt.getTime() - b.receivedAt.getTime())
|
|
249
|
+
.slice(0, take);
|
|
250
|
+
const rows = [...due((row) => row.state === "PROCESSED"), ...due((row) => row.state === "FAILED" && row.attempts >= maxAttempts)];
|
|
251
|
+
for (const row of rows) deliveries.delete(row.id);
|
|
252
|
+
return rows.length;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function purge({ conversations, messages }: MemoryTables, { cutoff, take }: { cutoff: Date; take: number }) {
|
|
256
|
+
const expired = (row: ConversationView) => row.lastMessageAt !== null && row.lastMessageAt < cutoff;
|
|
257
|
+
const due = [...conversations.values()]
|
|
258
|
+
.filter((row) => row.hasText && expired(row))
|
|
259
|
+
.sort((a, b) => a.lastMessageAt!.getTime() - b.lastMessageAt!.getTime())
|
|
260
|
+
.slice(0, take);
|
|
261
|
+
const ids = new Set(due.map((row) => row.id));
|
|
262
|
+
let purged = 0;
|
|
263
|
+
for (const row of messages.values()) {
|
|
264
|
+
if (!ids.has(row.conversationId) || row.createdAt > cutoff) continue;
|
|
265
|
+
messages.set(row.id, { ...row, body: null, options: null, transcript: null });
|
|
266
|
+
purged += 1;
|
|
267
|
+
}
|
|
268
|
+
for (const row of due) {
|
|
269
|
+
const current = conversations.get(row.id)!;
|
|
270
|
+
if (expired(current)) conversations.set(row.id, { ...current, hasText: false });
|
|
271
|
+
}
|
|
272
|
+
return { conversations: due.length, messages: purged };
|
|
273
|
+
}
|