@alexsun-top/opencode-chat-room 0.7.7 → 0.8.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/CHANGELOG.md +32 -0
- package/LICENSE +21 -0
- package/README.md +45 -36
- package/README.zh-CN.md +50 -41
- package/dist/cli.js +2696 -365
- package/package.json +14 -4
- package/packages/chat-room-channeld/README.md +242 -0
- package/packages/chat-room-channeld/dist/feishu-adapter.js +499 -0
- package/packages/chat-room-channeld/dist/mock-adapter.js +295 -0
- package/packages/chat-room-channeld/src/adapter.ts +475 -0
- package/packages/chat-room-channeld/src/cli.ts +124 -0
- package/packages/chat-room-channeld/src/config.ts +207 -0
- package/packages/chat-room-channeld/src/delivery.ts +158 -0
- package/packages/chat-room-channeld/src/feishu-adapter.ts +473 -0
- package/packages/chat-room-channeld/src/framing.ts +128 -0
- package/packages/chat-room-channeld/src/host-helpers.ts +41 -0
- package/packages/chat-room-channeld/src/host.ts +509 -0
- package/packages/chat-room-channeld/src/ingest-gate.ts +108 -0
- package/packages/chat-room-channeld/src/log.ts +26 -0
- package/packages/chat-room-channeld/src/mock-adapter.ts +206 -0
- package/packages/chat-room-channeld/src/protocol.ts +75 -0
- package/packages/chat-room-channeld/src/published.ts +37 -0
- package/packages/chat-room-channeld/src/rules.ts +127 -0
- package/packages/chat-room-channeld/src/state.ts +485 -0
- package/packages/chat-room-channeld/src/stats.ts +167 -0
- package/plugin.ts +22 -5
- package/server/addressing-routes.ts +130 -0
- package/server/assets/NOTICE.txt +2 -2
- package/server/assets/SHIKI-LICENSE +22 -0
- package/server/assets/base.css +9 -1
- package/server/assets/chat/announcements.js +5 -2
- package/server/assets/chat/clipboard.js +30 -0
- package/server/assets/chat/copy-action.js +48 -0
- package/server/assets/chat/diagram-viewer.js +253 -0
- package/server/assets/chat/doc-preview.js +149 -12
- package/server/assets/chat/events.js +25 -4
- package/server/assets/chat/files.js +26 -5
- package/server/assets/chat/forward.js +69 -0
- package/server/assets/chat/history-loader.js +3 -1
- package/server/assets/chat/index.js +11 -1
- package/server/assets/chat/join-requests.js +6 -3
- package/server/assets/chat/locales/de.js +7 -2
- package/server/assets/chat/locales/es.js +7 -2
- package/server/assets/chat/locales/fr.js +7 -2
- package/server/assets/chat/locales/it.js +7 -2
- package/server/assets/chat/locales/ja.js +7 -2
- package/server/assets/chat/locales/ko.js +7 -2
- package/server/assets/chat/markdown-footnotes.js +115 -0
- package/server/assets/chat/markdown.js +65 -113
- package/server/assets/chat/messages.js +6 -3
- package/server/assets/chat/palette.js +33 -16
- package/server/assets/chat/pwa.js +2 -0
- package/server/assets/chat/questions.js +5 -0
- package/server/assets/chat/replies.js +7 -1
- package/server/assets/chat/resource-format.js +74 -0
- package/server/assets/chat/rooms.js +3 -0
- package/server/assets/chat/shiki.js +87 -0
- package/server/assets/chat/side-pane.js +143 -0
- package/server/assets/chat/state.js +63 -9
- package/server/assets/chat/system-messages.js +2 -0
- package/server/assets/chat/task-row.js +2 -1
- package/server/assets/chat/tasks.js +29 -2
- package/server/assets/chat/viewport.js +5 -0
- package/server/assets/code-highlight.css +20 -31
- package/server/assets/conversation.css +27 -2
- package/server/assets/diagram-viewer.css +141 -0
- package/server/assets/doc-preview.css +26 -6
- package/server/assets/responsive.css +87 -13
- package/server/assets/shiki.bundle.js +152 -0
- package/server/assets/tasks.css +1 -4
- package/server/channels.ts +314 -0
- package/server/chat-server.ts +36 -8
- package/server/chat.html +33 -5
- package/server/resource-routes.ts +3 -1
- package/server/sw.js +236 -4
- package/skills/chatroom/SKILL.md +1 -1
- package/src/agent/chatroom-skill.ts +8 -2
- package/src/center/center-client.ts +79 -1
- package/src/config/file-config.ts +34 -0
- package/src/rooms/resources.ts +2 -2
- package/src/runtime/v2-plugin.ts +8 -2
- package/src/runtime/watch.ts +41 -7
- package/src/state/sqlite-state.ts +67 -18
- package/src/state/store.ts +11 -5
- package/src/tui/app.mjs +10 -2
- package/src/tui/http.mjs +16 -2
- package/src/tui/info-app.mjs +24 -15
- package/src/tui/join-app.mjs +3 -3
- package/src/tui/main.mjs +1 -1
- package/src/tui/markdown.mjs +5 -3
- package/src/tui/mentions.mjs +3 -3
- package/src/tui/message-app.mjs +14 -11
- package/src/tui/palette-app.mjs +10 -7
- package/src/tui/reminder-app.mjs +14 -10
- package/src/tui/ui-content.mjs +3 -1
- package/server/assets/HIGHLIGHT-LICENSE +0 -29
- package/server/assets/highlight-10.7.3.min.js +0 -1358
|
@@ -0,0 +1,509 @@
|
|
|
1
|
+
import type { AccountConfig, ChannelConfig, RuleTarget } from "./config.ts";
|
|
2
|
+
import { AdapterProcess, type SendReceipt } from "./adapter.ts";
|
|
3
|
+
import { applyReceipt, notifyDeliveryResult, type DeliveryResultHandler } from "./delivery.ts";
|
|
4
|
+
import { parseTarget, startFailureReason, toEndpoint, validateTargets } from "./host-helpers.ts";
|
|
5
|
+
import { IngestGate, type IngestResult } from "./ingest-gate.ts";
|
|
6
|
+
import { log } from "./log.ts";
|
|
7
|
+
import type { Endpoint, IngestEvent } from "./protocol.ts";
|
|
8
|
+
import { matchRules, planPayload, sameEndpoint, targetKey } from "./rules.ts";
|
|
9
|
+
import { openState, type ChannelState, type DeliveryRow } from "./state.ts";
|
|
10
|
+
|
|
11
|
+
export type { IngestResult } from "./ingest-gate.ts";
|
|
12
|
+
|
|
13
|
+
export interface AdapterHandle {
|
|
14
|
+
start(): Promise<void>;
|
|
15
|
+
send(
|
|
16
|
+
deliveryId: string,
|
|
17
|
+
attemptId: string,
|
|
18
|
+
idempotencyKey: string,
|
|
19
|
+
target: Endpoint,
|
|
20
|
+
payload: unknown,
|
|
21
|
+
): Promise<SendReceipt>;
|
|
22
|
+
stop(): Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface SpawnAdapterContext {
|
|
26
|
+
onIngest(event: IngestEvent): Promise<{ duplicate: boolean; eventId?: string }>;
|
|
27
|
+
onExit(code: number | null, signal: NodeJS.Signals | null): void;
|
|
28
|
+
onUnavailable(reason: string): void;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export type SpawnAdapter = (account: AccountConfig, context: SpawnAdapterContext) => AdapterHandle;
|
|
32
|
+
|
|
33
|
+
export interface HostDeps {
|
|
34
|
+
stateFactory?: (path: string) => ChannelState;
|
|
35
|
+
spawnAdapter?: SpawnAdapter;
|
|
36
|
+
now?: () => number;
|
|
37
|
+
deliveryIntervalMs?: number;
|
|
38
|
+
onDeliveryResult?: DeliveryResultHandler;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function defaultSpawnAdapter(account: AccountConfig, context: SpawnAdapterContext): AdapterHandle {
|
|
42
|
+
return new AdapterProcess({ account, ...context });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export class ChannelHost {
|
|
46
|
+
readonly #config: ChannelConfig;
|
|
47
|
+
readonly #stateFactory: (path: string) => ChannelState;
|
|
48
|
+
readonly #spawnAdapter: SpawnAdapter;
|
|
49
|
+
readonly #now: () => number;
|
|
50
|
+
readonly #deliveryIntervalMs: number;
|
|
51
|
+
readonly #onDeliveryResult?: DeliveryResultHandler;
|
|
52
|
+
readonly #adapters = new Map<string, AdapterHandle>();
|
|
53
|
+
readonly #timers = new Map<string, ReturnType<typeof setTimeout>>();
|
|
54
|
+
readonly #inFlight = new Map<string, Set<string>>();
|
|
55
|
+
readonly #notified = new Set<string>();
|
|
56
|
+
readonly #active = new Set<Promise<void>>();
|
|
57
|
+
readonly #disabled = new Set<string>();
|
|
58
|
+
readonly #gate = new IngestGate((accountId, _event, _error) => {
|
|
59
|
+
this.#disableAccount(accountId, "ingest barrier limit reached");
|
|
60
|
+
});
|
|
61
|
+
#state?: ChannelState;
|
|
62
|
+
#running = false;
|
|
63
|
+
#starting = false;
|
|
64
|
+
#idleTimer?: ReturnType<typeof setInterval>;
|
|
65
|
+
#rejectionHandler?: (reason: unknown) => void;
|
|
66
|
+
|
|
67
|
+
constructor(config: ChannelConfig, deps: HostDeps = {}) {
|
|
68
|
+
this.#config = config;
|
|
69
|
+
this.#stateFactory = deps.stateFactory ?? openState;
|
|
70
|
+
this.#spawnAdapter = deps.spawnAdapter ?? defaultSpawnAdapter;
|
|
71
|
+
this.#now = deps.now ?? Date.now;
|
|
72
|
+
this.#deliveryIntervalMs = deps.deliveryIntervalMs ?? 200;
|
|
73
|
+
this.#onDeliveryResult = deps.onDeliveryResult;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Account ids whose adapter failed to start or exited; their queues stay paused. */
|
|
77
|
+
get disabledAccounts(): readonly string[] {
|
|
78
|
+
return [...this.#disabled];
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Read-only view for routes: unknown ids or platform mismatches are missing. */
|
|
82
|
+
targetStatus(platform: string, accountId: string): "ready" | "disabled" | "missing" {
|
|
83
|
+
const account = this.#config.accounts.find((item) => item.id === accountId);
|
|
84
|
+
if (!account || account.platform !== platform) return "missing";
|
|
85
|
+
return this.#disabled.has(accountId) ? "disabled" : "ready";
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async start(): Promise<void> {
|
|
89
|
+
if (this.#running) throw new Error("host is already running");
|
|
90
|
+
validateTargets(this.#config);
|
|
91
|
+
const state = this.#stateFactory(this.#config.stateFile);
|
|
92
|
+
this.#state = state;
|
|
93
|
+
this.#installRejectionGuard();
|
|
94
|
+
const configuredKeys = this.#config.accounts.map((account) => `${account.platform}/${account.id}`);
|
|
95
|
+
const abandoned = state.abandonUnconfiguredDeliveries(configuredKeys);
|
|
96
|
+
if (abandoned.length > 0) {
|
|
97
|
+
log.warn(`abandoned ${abandoned.length} deliveries for unconfigured accounts`);
|
|
98
|
+
for (const row of abandoned) {
|
|
99
|
+
notifyDeliveryResult(state, row.deliveryId, this.#onDeliveryResult, { notified: this.#notified });
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
const resumed = state.resumePausedDeliveries();
|
|
103
|
+
if (resumed > 0) log.info(`resumed ${resumed} paused deliveries`);
|
|
104
|
+
const recovered = state.recoverInFlightDeliveries();
|
|
105
|
+
if (recovered > 0) log.warn(`recovered ${recovered} stale in-flight deliveries`);
|
|
106
|
+
|
|
107
|
+
this.#running = true;
|
|
108
|
+
this.#starting = true;
|
|
109
|
+
const started: string[] = [];
|
|
110
|
+
const failures: { id: string; reason: string }[] = [];
|
|
111
|
+
const tasks = this.#config.accounts.map(async (account) => {
|
|
112
|
+
let adapter: AdapterHandle | undefined;
|
|
113
|
+
try {
|
|
114
|
+
adapter = this.#spawnAdapter(account, {
|
|
115
|
+
onIngest: (event) => this.ingest(event),
|
|
116
|
+
onExit: (code, signal) => this.#handleExit(account.id, code, signal),
|
|
117
|
+
onUnavailable: (reason) => this.#disableAccount(account.id, reason),
|
|
118
|
+
});
|
|
119
|
+
this.#adapters.set(account.id, adapter);
|
|
120
|
+
await adapter.start();
|
|
121
|
+
this.#schedule(account.id);
|
|
122
|
+
return { id: account.id };
|
|
123
|
+
} catch (error) {
|
|
124
|
+
const reason = startFailureReason(account.id, error);
|
|
125
|
+
this.#disabled.add(account.id);
|
|
126
|
+
log.error(`adapter ${account.id} failed to start: ${reason}`, { account: account.id });
|
|
127
|
+
if (adapter) {
|
|
128
|
+
try {
|
|
129
|
+
await adapter.stop();
|
|
130
|
+
} catch {
|
|
131
|
+
// The account is already marked disabled.
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return { id: account.id, reason };
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
const settled = await Promise.allSettled(tasks);
|
|
139
|
+
this.#starting = false;
|
|
140
|
+
settled.forEach((result, index) => {
|
|
141
|
+
const account = this.#config.accounts[index]!;
|
|
142
|
+
if (result.status === "fulfilled") {
|
|
143
|
+
const { id, reason } = result.value;
|
|
144
|
+
if (reason) failures.push({ id, reason });
|
|
145
|
+
else started.push(id);
|
|
146
|
+
} else {
|
|
147
|
+
const reason = result.reason instanceof Error ? result.reason.message : String(result.reason);
|
|
148
|
+
failures.push({ id: account.id, reason });
|
|
149
|
+
this.#disabled.add(account.id);
|
|
150
|
+
log.error(`adapter ${account.id} failed to start: ${reason}`, { account: account.id });
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
for (const account of this.#config.accounts) {
|
|
155
|
+
if (this.#disabled.has(account.id)) {
|
|
156
|
+
state.pauseAccountDeliveries(`${account.platform}/${account.id}`, "account disabled until restart");
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const usable = started.filter((accountId) => !this.#disabled.has(accountId));
|
|
161
|
+
if (usable.length === 0) {
|
|
162
|
+
this.#running = false;
|
|
163
|
+
this.#starting = false;
|
|
164
|
+
this.#clearIdle();
|
|
165
|
+
this.#removeRejectionGuard();
|
|
166
|
+
for (const timer of this.#timers.values()) clearTimeout(timer);
|
|
167
|
+
this.#timers.clear();
|
|
168
|
+
await this.#stopAdapters();
|
|
169
|
+
state.close();
|
|
170
|
+
this.#state = undefined;
|
|
171
|
+
this.#disabled.clear();
|
|
172
|
+
const detail = failures.map((failure) => `${failure.id}: ${failure.reason}`).join("; ");
|
|
173
|
+
throw new Error(`no adapters started${detail ? `: ${detail}` : ""}`);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
for (const failure of failures) {
|
|
177
|
+
log.warn(`account ${failure.id} disabled until restart; queued deliveries paused`, {
|
|
178
|
+
account: failure.id,
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
log.info(
|
|
182
|
+
`host started: ${usable.length} accounts, ${failures.length} disabled, ${this.#config.rules.length} rules`,
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async ingest(event: IngestEvent): Promise<IngestResult> {
|
|
187
|
+
return this.#gate.run(event.source.accountId, event, (item) => this.#processIngest(item));
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async #processIngest(event: IngestEvent): Promise<IngestResult> {
|
|
191
|
+
const state = this.#state;
|
|
192
|
+
if (!state) throw new Error("host is not running");
|
|
193
|
+
|
|
194
|
+
if (event.message) {
|
|
195
|
+
const endpoint = targetKey(event.message.endpoint);
|
|
196
|
+
if (state.findEcho(endpoint, event.message.nativeMessageId)) {
|
|
197
|
+
log.info("echo ingest skipped", { event: event.eventId });
|
|
198
|
+
return { duplicate: false, eventId: event.eventId };
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const result = state.commitIngest(event);
|
|
203
|
+
if (result.duplicate) {
|
|
204
|
+
log.info("duplicate ingest skipped", { event: result.existingEventId });
|
|
205
|
+
return { duplicate: true, eventId: result.existingEventId };
|
|
206
|
+
}
|
|
207
|
+
const stored: IngestEvent = { ...event, ingressSeq: result.ingressSeq };
|
|
208
|
+
log.info(`ingested ${stored.kind}`, { event: stored.eventId });
|
|
209
|
+
|
|
210
|
+
if (stored.kind === "message.forward_requested") {
|
|
211
|
+
const selected = stored.selectedMessage;
|
|
212
|
+
const reason = !selected
|
|
213
|
+
? "selectedMessage is required"
|
|
214
|
+
: !sameEndpoint(selected.endpoint, stored.source)
|
|
215
|
+
? "selectedMessage is outside the source room"
|
|
216
|
+
: undefined;
|
|
217
|
+
if (reason) {
|
|
218
|
+
log.warn(`forward rejected: ${reason}`, { event: stored.eventId });
|
|
219
|
+
return { duplicate: false, eventId: stored.eventId };
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const requestedTarget = stored.kind === "message.forward_requested" ? stored.requestedTarget : undefined;
|
|
224
|
+
for (const rule of matchRules(this.#config, stored)) {
|
|
225
|
+
const targets: RuleTarget[] = [];
|
|
226
|
+
const payloads: string[] = [];
|
|
227
|
+
for (const target of rule.to) {
|
|
228
|
+
const endpoint = toEndpoint(this.#config, rule.id, target);
|
|
229
|
+
if (requestedTarget && !sameEndpoint(endpoint, requestedTarget)) continue;
|
|
230
|
+
const plan = planPayload(rule, stored, endpoint);
|
|
231
|
+
if ("dropped" in plan) {
|
|
232
|
+
log.warn(
|
|
233
|
+
`rule ${rule.id}@${rule.version} dropped delivery to ${targetKey(endpoint)}: ${plan.dropped}`,
|
|
234
|
+
{ event: stored.eventId },
|
|
235
|
+
);
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
targets.push(target);
|
|
239
|
+
payloads.push(JSON.stringify(plan.payload));
|
|
240
|
+
}
|
|
241
|
+
if (targets.length === 0) continue;
|
|
242
|
+
const created = state.enqueueDeliveries(stored.eventId, rule, targets, payloads);
|
|
243
|
+
for (const delivery of created) {
|
|
244
|
+
const endpoint = parseTarget(delivery.target);
|
|
245
|
+
if (endpoint && this.#disabled.has(endpoint.accountId)) {
|
|
246
|
+
state.markDelivery(delivery.deliveryId, "paused", {
|
|
247
|
+
lastError: "account disabled until restart",
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
log.info(`delivery enqueued rule=${rule.id}@${rule.version}`, {
|
|
251
|
+
delivery: delivery.deliveryId,
|
|
252
|
+
event: stored.eventId,
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
return { duplicate: false, eventId: stored.eventId };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
async stop(): Promise<void> {
|
|
260
|
+
if (!this.#running && !this.#state) {
|
|
261
|
+
this.#clearIdle();
|
|
262
|
+
this.#removeRejectionGuard();
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
this.#running = false;
|
|
266
|
+
this.#starting = false;
|
|
267
|
+
this.#clearIdle();
|
|
268
|
+
for (const timer of this.#timers.values()) clearTimeout(timer);
|
|
269
|
+
this.#timers.clear();
|
|
270
|
+
await Promise.allSettled([...this.#active]);
|
|
271
|
+
await this.#stopAdapters();
|
|
272
|
+
this.#state?.close();
|
|
273
|
+
this.#state = undefined;
|
|
274
|
+
this.#adapters.clear();
|
|
275
|
+
this.#inFlight.clear();
|
|
276
|
+
this.#notified.clear();
|
|
277
|
+
this.#disabled.clear();
|
|
278
|
+
this.#removeRejectionGuard();
|
|
279
|
+
log.info("host stopped");
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
#schedule(accountId: string): void {
|
|
283
|
+
if (!this.#running || this.#disabled.has(accountId)) return;
|
|
284
|
+
const timer = setTimeout(() => {
|
|
285
|
+
this.#timers.delete(accountId);
|
|
286
|
+
if (!this.#running) return;
|
|
287
|
+
const task = this.#drainOnce(accountId)
|
|
288
|
+
.catch((error: unknown) => {
|
|
289
|
+
log.error(`delivery loop failed: ${error instanceof Error ? error.message : String(error)}`, {
|
|
290
|
+
account: accountId,
|
|
291
|
+
});
|
|
292
|
+
})
|
|
293
|
+
.finally(() => {
|
|
294
|
+
this.#active.delete(task);
|
|
295
|
+
this.#schedule(accountId);
|
|
296
|
+
});
|
|
297
|
+
this.#active.add(task);
|
|
298
|
+
}, this.#deliveryIntervalMs);
|
|
299
|
+
this.#timers.set(accountId, timer);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
async #drainOnce(accountId: string): Promise<void> {
|
|
303
|
+
if (!this.#running || this.#disabled.has(accountId)) return;
|
|
304
|
+
const state = this.#state;
|
|
305
|
+
const adapter = this.#adapters.get(accountId);
|
|
306
|
+
const account = this.#config.accounts.find((item) => item.id === accountId);
|
|
307
|
+
if (!state || !adapter || !account) return;
|
|
308
|
+
const accountKey = `${account.platform}/${account.id}`;
|
|
309
|
+
const row = state.nextPendingDelivery(accountKey, this.#now());
|
|
310
|
+
if (!row) return;
|
|
311
|
+
await this.#deliver(state, adapter, accountId, row);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
async #deliver(
|
|
315
|
+
state: ChannelState,
|
|
316
|
+
adapter: AdapterHandle,
|
|
317
|
+
accountId: string,
|
|
318
|
+
row: DeliveryRow,
|
|
319
|
+
): Promise<void> {
|
|
320
|
+
const target = parseTarget(row.target);
|
|
321
|
+
if (!target) {
|
|
322
|
+
state.markDelivery(row.deliveryId, "permanent", { lastError: `invalid target: ${row.target}` });
|
|
323
|
+
state.recordReceipt({
|
|
324
|
+
deliveryId: row.deliveryId,
|
|
325
|
+
attemptId: "invalid-target",
|
|
326
|
+
state: "permanent",
|
|
327
|
+
detail: `invalid target: ${row.target}`,
|
|
328
|
+
});
|
|
329
|
+
notifyDeliveryResult(state, row.deliveryId, this.#onDeliveryResult, { attemptId: "invalid-target", notified: this.#notified });
|
|
330
|
+
log.error(`invalid target ${row.target}`, { account: accountId, delivery: row.deliveryId });
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const attempt = row.attemptCount + 1;
|
|
335
|
+
const attemptId = `att-${row.deliveryId}-${attempt}`;
|
|
336
|
+
state.markDelivery(row.deliveryId, "in_flight", { attemptCount: attempt });
|
|
337
|
+
const inFlight = this.#inFlight.get(accountId) ?? new Set<string>();
|
|
338
|
+
this.#inFlight.set(accountId, inFlight);
|
|
339
|
+
inFlight.add(row.deliveryId);
|
|
340
|
+
|
|
341
|
+
// Start the barrier synchronously before send; the finally below releases it
|
|
342
|
+
// only after applyReceipt commits the receipt and echo mapping. Sends are serial per account.
|
|
343
|
+
this.#gate.begin(accountId);
|
|
344
|
+
try {
|
|
345
|
+
let receipt: SendReceipt;
|
|
346
|
+
try {
|
|
347
|
+
receipt = await adapter.send(
|
|
348
|
+
row.deliveryId,
|
|
349
|
+
attemptId,
|
|
350
|
+
row.idempotencyKey,
|
|
351
|
+
target,
|
|
352
|
+
JSON.parse(row.payload) as unknown,
|
|
353
|
+
);
|
|
354
|
+
} catch (error) {
|
|
355
|
+
receipt = { state: "unknown", detail: error instanceof Error ? error.message : String(error) };
|
|
356
|
+
} finally {
|
|
357
|
+
inFlight.delete(row.deliveryId);
|
|
358
|
+
}
|
|
359
|
+
applyReceipt(state, row, attemptId, accountId, receipt, this.#now());
|
|
360
|
+
notifyDeliveryResult(state, row.deliveryId, this.#onDeliveryResult, { attemptId, notified: this.#notified });
|
|
361
|
+
} finally {
|
|
362
|
+
await this.#gate.finish(accountId, (event) => this.#processIngest(event));
|
|
363
|
+
if (this.#disabled.has(accountId)) {
|
|
364
|
+
this.#pauseAccountDeliveries(accountId, "account disabled until restart");
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
#pauseAccountDeliveries(accountId: string, reason: string): void {
|
|
370
|
+
const state = this.#state;
|
|
371
|
+
const account = this.#config.accounts.find((item) => item.id === accountId);
|
|
372
|
+
if (!state || !account) return;
|
|
373
|
+
try {
|
|
374
|
+
const paused = state.pauseAccountDeliveries(`${account.platform}/${account.id}`, reason);
|
|
375
|
+
if (paused > 0) {
|
|
376
|
+
log.info(`paused ${paused} deliveries for disabled account`, { account: accountId });
|
|
377
|
+
}
|
|
378
|
+
} catch (error) {
|
|
379
|
+
this.#safeWarn(
|
|
380
|
+
`could not pause deliveries: ${error instanceof Error ? error.message : String(error)}`,
|
|
381
|
+
accountId,
|
|
382
|
+
);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
#disableAccount(accountId: string, reason: string): void {
|
|
387
|
+
if (this.#disabled.has(accountId)) return;
|
|
388
|
+
this.#disabled.add(accountId);
|
|
389
|
+
|
|
390
|
+
const timer = this.#timers.get(accountId);
|
|
391
|
+
if (timer) {
|
|
392
|
+
clearTimeout(timer);
|
|
393
|
+
this.#timers.delete(accountId);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
const state = this.#state;
|
|
397
|
+
const inFlight = this.#inFlight.get(accountId);
|
|
398
|
+
if (state && inFlight && inFlight.size > 0) {
|
|
399
|
+
for (const deliveryId of inFlight) {
|
|
400
|
+
try {
|
|
401
|
+
state.markDelivery(deliveryId, "unknown", { lastError: reason });
|
|
402
|
+
notifyDeliveryResult(state, deliveryId, this.#onDeliveryResult, { notified: this.#notified });
|
|
403
|
+
} catch (error) {
|
|
404
|
+
this.#safeWarn(
|
|
405
|
+
`could not mark delivery unknown: ${error instanceof Error ? error.message : String(error)}`,
|
|
406
|
+
accountId,
|
|
407
|
+
deliveryId,
|
|
408
|
+
);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
this.#inFlight.delete(accountId);
|
|
412
|
+
this.#safeWarn(`marked ${inFlight.size} in-flight deliveries unknown`, accountId);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
this.#pauseAccountDeliveries(accountId, reason);
|
|
416
|
+
|
|
417
|
+
try {
|
|
418
|
+
log.error(`account ${accountId} disabled: ${reason}`, { account: accountId });
|
|
419
|
+
} catch {
|
|
420
|
+
// Logging must not escape the disable path.
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
try {
|
|
424
|
+
const adapter = this.#adapters.get(accountId);
|
|
425
|
+
if (adapter) {
|
|
426
|
+
void adapter.stop().catch((error: unknown) => {
|
|
427
|
+
this.#safeWarn(
|
|
428
|
+
`adapter stop failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
429
|
+
accountId,
|
|
430
|
+
);
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
} catch (error) {
|
|
434
|
+
this.#safeWarn(
|
|
435
|
+
`adapter stop failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
436
|
+
accountId,
|
|
437
|
+
);
|
|
438
|
+
}
|
|
439
|
+
this.#maybeIdle();
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
#handleExit(accountId: string, code: number | null, signal: NodeJS.Signals | null): void {
|
|
443
|
+
try {
|
|
444
|
+
this.#disableAccount(accountId, `adapter exited (code=${code} signal=${signal})`);
|
|
445
|
+
} catch (error) {
|
|
446
|
+
this.#safeWarn(
|
|
447
|
+
`disable after adapter exit failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
448
|
+
accountId,
|
|
449
|
+
);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
#safeWarn(message: string, accountId: string, deliveryId?: string): void {
|
|
454
|
+
try {
|
|
455
|
+
log.warn(message, { account: accountId, delivery: deliveryId });
|
|
456
|
+
} catch {
|
|
457
|
+
// Never throw from a disable/exit path.
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
#maybeIdle(): void {
|
|
462
|
+
try {
|
|
463
|
+
if (!this.#running || this.#starting || this.#idleTimer) return;
|
|
464
|
+
if (!this.#config.accounts.every((account) => this.#disabled.has(account.id))) return;
|
|
465
|
+
log.warn("all accounts disabled; host idle until restart");
|
|
466
|
+
this.#idleTimer = setInterval(() => {}, 60_000);
|
|
467
|
+
} catch {
|
|
468
|
+
// Idle bookkeeping must not throw.
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
#clearIdle(): void {
|
|
473
|
+
if (!this.#idleTimer) return;
|
|
474
|
+
clearInterval(this.#idleTimer);
|
|
475
|
+
this.#idleTimer = undefined;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
#installRejectionGuard(): void {
|
|
479
|
+
if (this.#rejectionHandler) return;
|
|
480
|
+
this.#rejectionHandler = (reason: unknown) => {
|
|
481
|
+
try {
|
|
482
|
+
log.error(`unhandled rejection: ${reason instanceof Error ? reason.message : String(reason)}`);
|
|
483
|
+
} catch {
|
|
484
|
+
// Last resort: never throw from the process guard.
|
|
485
|
+
}
|
|
486
|
+
};
|
|
487
|
+
process.on("unhandledRejection", this.#rejectionHandler);
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
#removeRejectionGuard(): void {
|
|
491
|
+
const handler = this.#rejectionHandler;
|
|
492
|
+
if (!handler) return;
|
|
493
|
+
this.#rejectionHandler = undefined;
|
|
494
|
+
try {
|
|
495
|
+
process.off("unhandledRejection", handler);
|
|
496
|
+
} catch {
|
|
497
|
+
// Ignore a partially torn-down process.
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
async #stopAdapters(): Promise<void> {
|
|
502
|
+
await Promise.allSettled([...this.#adapters.values()].map((adapter) => adapter.stop()));
|
|
503
|
+
this.#adapters.clear();
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
export function createHost(config: ChannelConfig, deps: HostDeps = {}): ChannelHost {
|
|
508
|
+
return new ChannelHost(config, deps);
|
|
509
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { log } from "./log.ts";
|
|
2
|
+
import type { IngestEvent } from "./protocol.ts";
|
|
3
|
+
|
|
4
|
+
export interface IngestResult {
|
|
5
|
+
duplicate: boolean;
|
|
6
|
+
eventId?: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export type IngestProcessor = (event: IngestEvent) => Promise<IngestResult>;
|
|
10
|
+
export type OverflowHandler = (accountId: string, event: IngestEvent, error: Error) => void;
|
|
11
|
+
|
|
12
|
+
interface BufferedIngest {
|
|
13
|
+
event: IngestEvent;
|
|
14
|
+
resolve(result: IngestResult): void;
|
|
15
|
+
reject(error: Error): void;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface GateState {
|
|
19
|
+
sends: number;
|
|
20
|
+
draining: boolean;
|
|
21
|
+
queue: BufferedIngest[];
|
|
22
|
+
overflow?: Error;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export const MAX_BUFFERED_INGESTS = 100;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Serializes inbound ingest handling behind in-flight sends per account. A
|
|
29
|
+
* counter, not a boolean, keeps buffered events parked until every started send
|
|
30
|
+
* has settled. Overflow is reported to the owner, which disables the account.
|
|
31
|
+
*/
|
|
32
|
+
export class IngestGate {
|
|
33
|
+
readonly #onOverflow: OverflowHandler;
|
|
34
|
+
readonly #gates = new Map<string, GateState>();
|
|
35
|
+
|
|
36
|
+
constructor(onOverflow: OverflowHandler) {
|
|
37
|
+
this.#onOverflow = onOverflow;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
begin(accountId: string): void {
|
|
41
|
+
const gate = this.#gate(accountId);
|
|
42
|
+
gate.sends += 1;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async finish(accountId: string, process: IngestProcessor): Promise<void> {
|
|
46
|
+
const gate = this.#gates.get(accountId);
|
|
47
|
+
if (!gate) return;
|
|
48
|
+
gate.sends = Math.max(0, gate.sends - 1);
|
|
49
|
+
if (gate.sends > 0 || gate.draining) return;
|
|
50
|
+
|
|
51
|
+
gate.draining = true;
|
|
52
|
+
try {
|
|
53
|
+
while (gate.queue.length > 0) {
|
|
54
|
+
const item = gate.queue.shift()!;
|
|
55
|
+
try {
|
|
56
|
+
item.resolve(await process(item.event));
|
|
57
|
+
} catch (error) {
|
|
58
|
+
item.reject(error instanceof Error ? error : new Error(String(error)));
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
} finally {
|
|
62
|
+
gate.draining = false;
|
|
63
|
+
if (gate.sends === 0 && gate.queue.length === 0) this.#gates.delete(accountId);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async run(accountId: string, event: IngestEvent, process: IngestProcessor): Promise<IngestResult> {
|
|
68
|
+
const gate = this.#gates.get(accountId);
|
|
69
|
+
if (!gate || (!gate.draining && gate.sends === 0)) return process(event);
|
|
70
|
+
if (gate.overflow) throw gate.overflow;
|
|
71
|
+
if (gate.queue.length >= MAX_BUFFERED_INGESTS) {
|
|
72
|
+
const error = new Error(
|
|
73
|
+
`ingest buffer overflow for account ${accountId}; limit ${MAX_BUFFERED_INGESTS}; event ${event.eventId} dropped`,
|
|
74
|
+
) as Error & { code?: string };
|
|
75
|
+
error.code = "ingest_buffer_overflow";
|
|
76
|
+
gate.overflow = error;
|
|
77
|
+
try {
|
|
78
|
+
log.error(error.message, { account: accountId, event: event.eventId });
|
|
79
|
+
} catch {
|
|
80
|
+
// Logging must not break the overflow path.
|
|
81
|
+
}
|
|
82
|
+
try {
|
|
83
|
+
this.#onOverflow(accountId, event, error);
|
|
84
|
+
} catch (callbackError) {
|
|
85
|
+
try {
|
|
86
|
+
log.error(
|
|
87
|
+
`overflow handler failed: ${callbackError instanceof Error ? callbackError.message : String(callbackError)}`,
|
|
88
|
+
{ account: accountId },
|
|
89
|
+
);
|
|
90
|
+
} catch {
|
|
91
|
+
// Keep the overflow rejection.
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
return new Promise<IngestResult>((resolve, reject) => {
|
|
97
|
+
gate.queue.push({ event, resolve, reject });
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
#gate(accountId: string): GateState {
|
|
102
|
+
const existing = this.#gates.get(accountId);
|
|
103
|
+
if (existing) return existing;
|
|
104
|
+
const gate: GateState = { sends: 0, draining: false, queue: [] };
|
|
105
|
+
this.#gates.set(accountId, gate);
|
|
106
|
+
return gate;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export interface LogFields {
|
|
2
|
+
account?: string;
|
|
3
|
+
delivery?: string;
|
|
4
|
+
event?: string;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
function write(level: "INFO" | "WARN" | "ERROR", message: string, fields: LogFields = {}): void {
|
|
8
|
+
const parts = [new Date().toISOString(), level, message];
|
|
9
|
+
if (fields.account) parts.push(`account=${fields.account}`);
|
|
10
|
+
if (fields.delivery) parts.push(`delivery=${fields.delivery}`);
|
|
11
|
+
if (fields.event) parts.push(`event=${fields.event}`);
|
|
12
|
+
process.stderr.write(`${parts.join(" ")}\n`);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Logger for protocol hosts: stderr only, one line per event. */
|
|
16
|
+
export const log = {
|
|
17
|
+
info(message: string, fields?: LogFields): void {
|
|
18
|
+
write("INFO", message, fields);
|
|
19
|
+
},
|
|
20
|
+
warn(message: string, fields?: LogFields): void {
|
|
21
|
+
write("WARN", message, fields);
|
|
22
|
+
},
|
|
23
|
+
error(message: string, fields?: LogFields): void {
|
|
24
|
+
write("ERROR", message, fields);
|
|
25
|
+
},
|
|
26
|
+
};
|