bailinghub 0.9.2 → 0.9.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +6 -6
- package/README.md +6 -6
- package/docker-compose.images.yml +2 -2
- package/docs/CHANGELOG.en.md +12 -1
- package/docs/CHANGELOG.md +12 -1
- package/docs/CORE_RELIABILITY.en.md +22 -2
- package/docs/CORE_RELIABILITY.md +22 -2
- package/docs/IMPLEMENTATION_STATUS.en.md +19 -15
- package/docs/IMPLEMENTATION_STATUS.md +19 -15
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/OPERATIONS.en.md +13 -0
- package/docs/OPERATIONS.md +12 -0
- package/docs/README.en.md +3 -1
- package/docs/README.md +3 -1
- package/docs/RELEASE_NOTES_v0.9.3.en.md +51 -0
- package/docs/RELEASE_NOTES_v0.9.3.md +51 -0
- package/docs/TOOLS_DESIGN.md +1 -0
- package/docs/UPGRADE_v0.9.3.en.md +63 -0
- package/docs/UPGRADE_v0.9.3.md +63 -0
- package/package.json +1 -1
- package/scripts/check-doc-links.mjs +2 -0
- package/scripts/check-image-tags.sh +1 -1
- package/scripts/check-release-consistency.test.mjs +2 -2
- package/scripts/install.sh +1 -1
- package/scripts/publish-images.sh +1 -1
- package/scripts/release-audit.mjs +4 -0
- package/scripts/verify-github-repo.mjs +4 -0
- package/security/dependency-audit-exceptions.json +1 -1
- package/sql/067_delivery_dlq_replay.sql +10 -0
- package/sql/README.en.md +6 -0
- package/sql/README.md +6 -0
- package/src/adapters/llm/file.test.ts +59 -0
- package/src/adapters/llm/file.ts +11 -4
- package/src/app/agent-tool-invocations.test.ts +3 -1
- package/src/app/approval-continuations.test.ts +27 -1
- package/src/app/approval-continuations.ts +44 -3
- package/src/app/channels-attachments.test.ts +63 -0
- package/src/app/channels.ts +7 -4
- package/src/app/delivery-dlq-replay.mysql.test.ts +139 -0
- package/src/app/delivery-dlq-replay.test.ts +75 -0
- package/src/app/delivery-dlq-replay.ts +41 -0
- package/src/app/delivery.ts +3 -2
- package/src/app/kernel-notification-lifecycle.test.ts +49 -0
- package/src/app/kernel.ts +9 -0
- package/src/app/notification-outbound.test.ts +53 -0
- package/src/app/operational-metrics.test.ts +37 -1
- package/src/app/operational-metrics.ts +25 -2
- package/src/app/outbound.ts +13 -2
- package/src/app/runtime-lifecycle.test.ts +89 -0
- package/src/app/runtime-lifecycle.ts +20 -18
- package/src/app/tool-approvals.ts +2 -1
- package/src/core/contracts/delivery-replay.ts +41 -0
- package/src/core/contracts/tools-idempotency.test.ts +121 -5
- package/src/core/contracts/tools.ts +21 -11
- package/src/core/contracts/types.ts +2 -0
- package/src/core/observability/openmetrics.test.ts +28 -0
- package/src/core/observability/openmetrics.ts +91 -0
- package/src/core/platform/http-body.test.ts +185 -0
- package/src/core/platform/http-body.ts +58 -0
- package/src/core/runtime/finish-runtime.test.ts +2 -0
- package/src/core/runtime/finish-runtime.ts +10 -7
- package/src/core/runtime/notification-background-work.test.ts +50 -0
- package/src/core/runtime/notification-background-work.ts +101 -0
- package/src/core/state/delivery-replay.ts +19 -0
- package/src/core/state/state-codec.ts +1 -0
- package/src/core/state/state-contracts.ts +3 -0
- package/src/infrastructure/config/config-delivery-dlq-ledger.ts +36 -10
- package/src/infrastructure/config/configstore.ts +2 -1
- package/src/infrastructure/state/state-jsonl.ts +16 -1
- package/src/infrastructure/state/state-mysql.ts +27 -0
- package/src/modules/usage/background-work.test.ts +28 -0
- package/src/modules/usage/background-work.ts +43 -7
- package/src/modules/usage/billing-reconciliation.test.ts +16 -2
- package/src/modules/usage/billing-repository.ts +9 -0
- package/src/modules/usage/maintenance.test.ts +18 -2
- package/src/modules/usage/maintenance.ts +8 -0
- package/src/routes/admin-runtime.ts +14 -0
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ApprovalContinuation } from '../core/contracts/approval-continuation';
|
|
2
|
+
import type { BackgroundWorkMetricsSnapshot } from '../core/observability/openmetrics';
|
|
2
3
|
import type { RuntimeStateStore } from '../core/state/state-contracts';
|
|
3
4
|
import type { ApprovalLedgerContract, ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
4
5
|
import type { EngineRuntime } from './engine';
|
|
@@ -83,6 +84,29 @@ export async function continueApprovalDecisionFor(deps: ApprovalContinuationDeps
|
|
|
83
84
|
}
|
|
84
85
|
|
|
85
86
|
const passes = new WeakMap<ApprovalLedgerContract, Promise<number>>();
|
|
87
|
+
export interface ApprovalContinuationProgress { scanned: number; completed: number; pending: number; failed: number }
|
|
88
|
+
interface PassMetrics {
|
|
89
|
+
completed: number; failed: number; startedAt: string | null; completedAt: string | null; failedAt: string | null;
|
|
90
|
+
progress: ApprovalContinuationProgress;
|
|
91
|
+
}
|
|
92
|
+
const passMetrics = new WeakMap<ApprovalLedgerContract, PassMetrics>();
|
|
93
|
+
|
|
94
|
+
/** Read process-local maintenance state; never enumerate approval/job records. */
|
|
95
|
+
export function approvalContinuationMaintenanceSnapshotFor(
|
|
96
|
+
deps: Pick<ApprovalContinuationDeps, 'configStore' | 'stateStore'>,
|
|
97
|
+
nowMs = Date.now(),
|
|
98
|
+
): { work: BackgroundWorkMetricsSnapshot; progress?: ApprovalContinuationProgress } | undefined {
|
|
99
|
+
if (!supportsApprovalContinuations(deps)) return undefined;
|
|
100
|
+
const ledger = deps.configStore!.approvals, value = passMetrics.get(ledger), running = passes.has(ledger);
|
|
101
|
+
const startedAt = value?.startedAt ?? null;
|
|
102
|
+
return {
|
|
103
|
+
work: { kinds: [{ kind: 'approval-continuation', inFlight: running ? 1 : 0,
|
|
104
|
+
completed: value?.completed ?? 0, failed: value?.failed ?? 0,
|
|
105
|
+
oldestPendingAgeMs: running && startedAt ? Math.max(0, nowMs - Date.parse(startedAt)) : 0,
|
|
106
|
+
lastStartedAt: startedAt, lastCompletedAt: value?.completedAt ?? null, lastFailedAt: value?.failedAt ?? null }] },
|
|
107
|
+
...(value ? { progress: { ...value.progress } } : {}),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
86
110
|
|
|
87
111
|
/** Await from boot/tick. One pass per owner; no detached timers or swallowed shutdown work. */
|
|
88
112
|
export async function reconcileApprovalContinuationsFor(deps: ApprovalContinuationDeps, limit = 25): Promise<number> {
|
|
@@ -90,18 +114,35 @@ export async function reconcileApprovalContinuationsFor(deps: ApprovalContinuati
|
|
|
90
114
|
const ledger = deps.configStore!.approvals;
|
|
91
115
|
const active = passes.get(ledger);
|
|
92
116
|
if (active) return await active;
|
|
117
|
+
let metrics = passMetrics.get(ledger);
|
|
118
|
+
if (!metrics) {
|
|
119
|
+
metrics = { completed: 0, failed: 0, startedAt: null, completedAt: null, failedAt: null,
|
|
120
|
+
progress: { scanned: 0, completed: 0, pending: 0, failed: 0 } };
|
|
121
|
+
passMetrics.set(ledger, metrics);
|
|
122
|
+
}
|
|
123
|
+
const owner = metrics;
|
|
124
|
+
owner.startedAt = deps.now();
|
|
125
|
+
owner.progress = { scanned: 0, completed: 0, pending: 0, failed: 0 };
|
|
93
126
|
const work = (async () => {
|
|
94
127
|
const intents = await ledger.pendingContinuations!(limit);
|
|
95
128
|
let completed = 0;
|
|
96
129
|
for (const intent of intents) {
|
|
97
130
|
if (deps.isClosing?.()) break;
|
|
131
|
+
owner.progress.scanned++;
|
|
98
132
|
try {
|
|
99
133
|
const result = await continueApprovalDecisionFor(deps, intent.approval_id);
|
|
100
|
-
if (!result.pending) completed++;
|
|
101
|
-
} catch { /* Durable intent remains pending; later explicit pass retries it. */ }
|
|
134
|
+
if (!result.pending) { completed++; owner.progress.completed++; } else owner.progress.pending++;
|
|
135
|
+
} catch { owner.progress.failed++; /* Durable intent remains pending; later explicit pass retries it. */ }
|
|
102
136
|
}
|
|
103
137
|
return completed;
|
|
104
138
|
})();
|
|
105
139
|
passes.set(ledger, work);
|
|
106
|
-
try {
|
|
140
|
+
try {
|
|
141
|
+
const completed = await work;
|
|
142
|
+
owner.completed++; owner.completedAt = deps.now();
|
|
143
|
+
return completed;
|
|
144
|
+
} catch (error) {
|
|
145
|
+
owner.failed++; owner.failedAt = deps.now();
|
|
146
|
+
throw error;
|
|
147
|
+
} finally { if (passes.get(ledger) === work) passes.delete(ledger); }
|
|
107
148
|
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { channelSendFor } from './channels';
|
|
4
|
+
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
5
|
+
|
|
6
|
+
const config = { channels: { get: async () => ({ kind: 'wecom', enabled: true,
|
|
7
|
+
config: { corpid: 'synthetic', secret: 'synthetic', agentid: '1' } }) } } as unknown as ConfigStoreContract;
|
|
8
|
+
|
|
9
|
+
test('channel attachments: oversized declared bodies cancel before upload or message dispatch', async (t) => {
|
|
10
|
+
let pulls = 0;
|
|
11
|
+
let cancels = 0;
|
|
12
|
+
let calls = 0;
|
|
13
|
+
t.mock.method(globalThis, 'fetch', async (input: unknown) => {
|
|
14
|
+
assert.equal(String(input), 'https://synthetic.invalid/a.txt');
|
|
15
|
+
calls++;
|
|
16
|
+
return new Response(new ReadableStream<Uint8Array>({
|
|
17
|
+
pull(controller) { pulls++; controller.enqueue(new Uint8Array(1)); },
|
|
18
|
+
cancel() { cancels++; },
|
|
19
|
+
}, { highWaterMark: 0 }), { headers: { 'content-length': String(20 * 1024 * 1024 + 1) } });
|
|
20
|
+
});
|
|
21
|
+
const result = await channelSendFor(config, 'synthetic', 'recipient', { text: 'synthetic', files: [{ url: 'https://synthetic.invalid/a.txt' }] });
|
|
22
|
+
assert.equal(result.ok, false);
|
|
23
|
+
assert.match(result.error ?? '', /超过 20MB 上限/);
|
|
24
|
+
assert.equal(result.mayHaveCommitted, undefined);
|
|
25
|
+
assert.equal(calls, 1);
|
|
26
|
+
assert.equal(pulls, 0);
|
|
27
|
+
assert.equal(cancels, 1);
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
test('channel attachments: low declared length cannot bypass body limit or upload partial media', async (t) => {
|
|
31
|
+
let pulls = 0;
|
|
32
|
+
let cancels = 0;
|
|
33
|
+
let calls = 0;
|
|
34
|
+
const chunk = new Uint8Array(1024 * 1024);
|
|
35
|
+
t.mock.method(globalThis, 'fetch', async (input: unknown) => {
|
|
36
|
+
assert.equal(String(input), 'https://synthetic.invalid/a.png');
|
|
37
|
+
calls++;
|
|
38
|
+
return new Response(new ReadableStream<Uint8Array>({
|
|
39
|
+
pull(controller) { pulls++; controller.enqueue(pulls <= 20 ? chunk : new Uint8Array(1)); },
|
|
40
|
+
cancel() { cancels++; },
|
|
41
|
+
}, { highWaterMark: 0 }), { headers: { 'content-length': '1' } });
|
|
42
|
+
});
|
|
43
|
+
const result = await channelSendFor(config, 'synthetic', 'recipient', { images: ['https://synthetic.invalid/a.png'] });
|
|
44
|
+
assert.equal(result.ok, false);
|
|
45
|
+
assert.match(result.error ?? '', /超过 20MB 上限/);
|
|
46
|
+
assert.equal(calls, 1);
|
|
47
|
+
assert.equal(pulls, 21);
|
|
48
|
+
assert.equal(cancels, 1);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test('channel attachments: HTTP errors cancel promptly and keep original status', async (t) => {
|
|
52
|
+
let pulls = 0;
|
|
53
|
+
let cancels = 0;
|
|
54
|
+
t.mock.method(globalThis, 'fetch', async () => new Response(new ReadableStream<Uint8Array>({
|
|
55
|
+
pull(controller) { pulls++; controller.enqueue(new Uint8Array(1)); },
|
|
56
|
+
cancel() { cancels++; return new Promise<void>(() => undefined); },
|
|
57
|
+
}, { highWaterMark: 0 }), { status: 403 }));
|
|
58
|
+
const result = await channelSendFor(config, 'synthetic', 'recipient', { files: [{ url: 'https://synthetic.invalid/a.txt' }] });
|
|
59
|
+
assert.equal(result.ok, false);
|
|
60
|
+
assert.match(result.error ?? '', /HTTP 403/);
|
|
61
|
+
assert.equal(pulls, 0);
|
|
62
|
+
assert.equal(cancels, 1);
|
|
63
|
+
});
|
package/src/app/channels.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// 不建任何 job、不过 LLM、逐字送达——正式通知所见即所得;与「执行器拉取(wecom-notify)」那套解耦(内部告警不再走它)。
|
|
5
5
|
import { sendWecomText, sendWecomMedia, sendWecomCard, uploadWecomMedia, type WecomAccessTokenCache } from '../adapters/channels/wecom-api';
|
|
6
6
|
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
7
|
+
import { cancelResponseBody, readResponseBody, ResponseBodyLimitError } from '../core/platform/http-body';
|
|
7
8
|
|
|
8
9
|
export interface ChannelSendResult {
|
|
9
10
|
ok: boolean;
|
|
@@ -23,13 +24,15 @@ async function fetchBinary(url: string, maxBytes = 20 * 1024 * 1024): Promise<{
|
|
|
23
24
|
if (!/^https?:\/\//i.test(url)) return { error: 'URL 必须是 http(s)' };
|
|
24
25
|
try {
|
|
25
26
|
const r = await fetch(url, { signal: AbortSignal.timeout(20000) });
|
|
26
|
-
if (!r.ok) return { error: `拉取失败 HTTP ${r.status}` };
|
|
27
|
-
const ab = await r
|
|
27
|
+
if (!r.ok) { cancelResponseBody(r); return { error: `拉取失败 HTTP ${r.status}` }; }
|
|
28
|
+
const ab = await readResponseBody(r, maxBytes);
|
|
28
29
|
if (!ab.byteLength) return { error: '内容为空' };
|
|
29
|
-
if (ab.byteLength > maxBytes) return { error: `超过 ${Math.round(maxBytes / 1048576)}MB 上限` };
|
|
30
30
|
const mime = ((r.headers.get('content-type') || '').split(';')[0] || '').trim() || 'application/octet-stream';
|
|
31
31
|
return { buf: Buffer.from(ab), mime };
|
|
32
|
-
} catch (e) {
|
|
32
|
+
} catch (e) {
|
|
33
|
+
if (e instanceof ResponseBodyLimitError) return { error: `超过 ${Math.round(maxBytes / 1048576)}MB 上限` };
|
|
34
|
+
return { error: `拉取异常 ${String(e instanceof Error ? e.message : e).slice(0, 80)}` };
|
|
35
|
+
}
|
|
33
36
|
}
|
|
34
37
|
/** 给上传素材取个带扩展名的文件名(企微 media/upload 需要):优先 URL 末段,其次按 mime/类型兜底。 */
|
|
35
38
|
function fileNameFor(url: string, mime: string, kind: 'image' | 'file'): string {
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
4
|
+
import { readFile } from 'node:fs/promises';
|
|
5
|
+
import { resolve } from 'node:path';
|
|
6
|
+
import { pathToFileURL } from 'node:url';
|
|
7
|
+
import { createPool } from 'mysql2/promise';
|
|
8
|
+
import type { Job } from '../core/contracts/types';
|
|
9
|
+
import { DeliveryDlqLedger } from '../infrastructure/config/config-delivery-dlq-ledger';
|
|
10
|
+
import { MysqlStore } from '../infrastructure/state/state-mysql';
|
|
11
|
+
import { migrateBailingHubCoreSchema } from '../infrastructure/schema/core-schema-migrator';
|
|
12
|
+
import { classifyDeliveryDlq, replayExecutorDeliveryDlq } from './delivery-dlq-replay';
|
|
13
|
+
|
|
14
|
+
const enabled = process.env.BAILING_NOTIFICATION_TEST_MYSQL === '1';
|
|
15
|
+
const baselineRoot = process.env.BAILING_NOTIFICATION_BASELINE_ROOT;
|
|
16
|
+
const migrationName = '067_delivery_dlq_replay.sql';
|
|
17
|
+
|
|
18
|
+
async function fixture(upgrade = false) {
|
|
19
|
+
const database = `notification_acceptance_${randomUUID().replaceAll('-', '')}`;
|
|
20
|
+
const mysql = { host: '127.0.0.1', port: Number(process.env.BAILING_NOTIFICATION_TEST_MYSQL_PORT ?? 16307), user: 'root', password: '', database, connectionLimit: 8 };
|
|
21
|
+
const admin = createPool({ ...mysql, database: undefined });
|
|
22
|
+
await admin.query(`CREATE DATABASE \`${database}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`);
|
|
23
|
+
const pool = createPool({ ...mysql, timezone: 'Z' });
|
|
24
|
+
try {
|
|
25
|
+
if (upgrade) {
|
|
26
|
+
assert.ok(baselineRoot, 'explicit baseline root is required for upgrade acceptance');
|
|
27
|
+
const baseline = await import(pathToFileURL(resolve(baselineRoot, 'src/infrastructure/schema/core-schema-migrator.ts')).href);
|
|
28
|
+
await baseline.migrateBailingHubCoreSchema({ mysql, logger: { log() {}, warn() {} } });
|
|
29
|
+
} else await migrateBailingHubCoreSchema({ mysql, logger: { log() {}, warn() {} } });
|
|
30
|
+
const store = new MysqlStore(mysql, { get: async () => pool, close: async () => {} }); await store.init();
|
|
31
|
+
const ledger = new DeliveryDlqLedger(() => pool);
|
|
32
|
+
const stamp = new Date().toISOString();
|
|
33
|
+
const child: Job = { job_id: randomUUID(), request_id: `deliver-${randomUUID()}`, status: 'error', target: 'sms-notify',
|
|
34
|
+
profile: 'delivery', project: '', source: 'delivery', input: 'synthetic notification', input_preview: 'synthetic',
|
|
35
|
+
metadata: { to: 'synthetic-recipient', parent_job_id: 'synthetic-business-parent' }, created_at: stamp, updated_at: stamp };
|
|
36
|
+
const parent: Job = { ...child, job_id: randomUUID(), request_id: `business-${randomUUID()}`, source: 'business', target: 'llm' };
|
|
37
|
+
await store.createJob(child); await store.createJob(parent);
|
|
38
|
+
// Seed old-format rows even in fresh-schema tests to retain legacy coverage.
|
|
39
|
+
const [first]: any = await pool.query('INSERT INTO bz_delivery_dlq (parent_job_id,channel,recipient,content,error,resolved,created_at) VALUES (?,?,?,?,?,0,NOW())',
|
|
40
|
+
[child.job_id, child.target, 'synthetic-recipient', child.input, 'synthetic failure']);
|
|
41
|
+
const executorId = Number(first.insertId);
|
|
42
|
+
const [second]: any = await pool.query('INSERT INTO bz_delivery_dlq (parent_job_id,channel,recipient,content,error,resolved,created_at) VALUES (?,?,?,?,?,0,NOW())',
|
|
43
|
+
[parent.job_id, 'native-notify', 'synthetic-recipient', parent.input, 'synthetic failure']);
|
|
44
|
+
const nativeId = Number(second.insertId);
|
|
45
|
+
return { mysql, pool, store, ledger, child, parent, executorId, nativeId,
|
|
46
|
+
close: async () => { await pool.end(); await admin.query(`DROP DATABASE \`${database}\``); await admin.end(); } };
|
|
47
|
+
} catch (error) {
|
|
48
|
+
await pool.end(); await admin.query(`DROP DATABASE \`${database}\``); await admin.end(); throw error;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
test('MySQL v0.9.2 data upgrades to 067 once and preserves old native/executor records', { skip: !enabled || !baselineRoot }, async () => {
|
|
53
|
+
const h = await fixture(true);
|
|
54
|
+
try {
|
|
55
|
+
const [before]: any = await h.pool.query('SELECT id,parent_job_id,channel,recipient,content,error,resolved FROM bz_delivery_dlq ORDER BY id');
|
|
56
|
+
const upgrade = await migrateBailingHubCoreSchema({ mysql: h.mysql, logger: { log() {}, warn() {} } });
|
|
57
|
+
assert.deepEqual(upgrade.appliedFiles, [migrationName]);
|
|
58
|
+
const [after]: any = await h.pool.query('SELECT id,parent_job_id,channel,recipient,content,error,resolved FROM bz_delivery_dlq ORDER BY id');
|
|
59
|
+
assert.deepEqual(after, before);
|
|
60
|
+
assert.equal(await classifyDeliveryDlq((await h.ledger.get(h.executorId))!, h.store), 'executor_target');
|
|
61
|
+
assert.equal(await classifyDeliveryDlq((await h.ledger.get(h.nativeId))!, h.store), 'native_channel');
|
|
62
|
+
const [ledgerBefore]: any = await h.pool.query('SELECT filename,checksum_sha256 FROM bz_schema_migrations ORDER BY filename');
|
|
63
|
+
const second = await migrateBailingHubCoreSchema({ mysql: h.mysql, logger: { log() {}, warn() {} } });
|
|
64
|
+
assert.equal(second.appliedFiles.length, 0);
|
|
65
|
+
const [ledgerAfter]: any = await h.pool.query('SELECT filename,checksum_sha256 FROM bz_schema_migrations ORDER BY filename');
|
|
66
|
+
assert.deepEqual(ledgerAfter, ledgerBefore);
|
|
67
|
+
const checksum = createHash('sha256').update(await readFile(new URL('../../sql/067_delivery_dlq_replay.sql', import.meta.url))).digest('hex');
|
|
68
|
+
assert.equal(ledgerAfter.find((r: any) => r.filename === migrationName)?.checksum_sha256, checksum);
|
|
69
|
+
} finally { await h.close(); }
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
test('MySQL concurrent DLQ identity and notification admission have one winner', { skip: !enabled }, async () => {
|
|
73
|
+
const h = await fixture();
|
|
74
|
+
try {
|
|
75
|
+
const identities = await Promise.all(Array.from({ length: 8 }, () => h.ledger.ensureExecutorReplay(h.executorId, h.child.job_id)));
|
|
76
|
+
assert.equal(identities.filter(x => x?.created).length, 1);
|
|
77
|
+
const input = { dlq_id: h.executorId, replay_key: identities[0]!.key, job_id: h.child.job_id, request_id: h.child.request_id, target: h.child.target! };
|
|
78
|
+
const outcomes = await Promise.all(Array.from({ length: 8 }, () => h.store.requeueDeliveryJobOnce(input)));
|
|
79
|
+
assert.equal(outcomes.filter(x => x === 'queued').length, 1);
|
|
80
|
+
assert.equal(outcomes.filter(x => x === 'already_queued').length, 7);
|
|
81
|
+
assert.equal((await h.store.getJob(h.parent.job_id))?.status, 'error');
|
|
82
|
+
assert.equal((await h.store.getJob(h.child.job_id))?.delivery_replay_keys?.[String(h.executorId)], input.replay_key);
|
|
83
|
+
assert.ok(await h.store.claimNextJob(['sms-notify'], 'synthetic-executor', 1000));
|
|
84
|
+
assert.equal(await h.store.claimNextJob(['sms-notify'], 'synthetic-executor-2', 1000), null);
|
|
85
|
+
} finally { await h.close(); }
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
test('MySQL durable queued marker survives lost COMMIT/resolve replies and completed child retry', { skip: !enabled }, async () => {
|
|
89
|
+
const h = await fixture();
|
|
90
|
+
try {
|
|
91
|
+
const row = (await h.ledger.get(h.executorId))!;
|
|
92
|
+
const marker = await h.ledger.ensureExecutorReplay(h.executorId, h.child.job_id);
|
|
93
|
+
const faulty = new MysqlStore(h.mysql, { get: async () => ({ getConnection: async () => {
|
|
94
|
+
const conn = await h.pool.getConnection(); const commit = conn.commit.bind(conn);
|
|
95
|
+
conn.commit = async () => { conn.commit = commit; await commit(); throw new Error('synthetic queue COMMIT reply lost'); };
|
|
96
|
+
return conn;
|
|
97
|
+
} } as any), close: async () => {} }); await faulty.init();
|
|
98
|
+
await assert.rejects(faulty.requeueDeliveryJobOnce({ dlq_id: row.id, replay_key: marker!.key, job_id: h.child.job_id,
|
|
99
|
+
request_id: h.child.request_id, target: h.child.target! }), /COMMIT reply lost/);
|
|
100
|
+
assert.equal((await h.store.getJob(h.child.job_id))?.status, 'queued');
|
|
101
|
+
let failResolve = true;
|
|
102
|
+
const resolve = h.ledger.resolve.bind(h.ledger);
|
|
103
|
+
h.ledger.resolve = async id => { if (failResolve) { failResolve = false; throw new Error('synthetic resolve interruption'); } await resolve(id); };
|
|
104
|
+
await assert.rejects(replayExecutorDeliveryDlq((await h.ledger.get(row.id))!, h.ledger, h.store), /resolve interruption/);
|
|
105
|
+
await h.store.updateJob(h.child.job_id, { status: 'done', delivery_replay_keys: {} });
|
|
106
|
+
const restarted = new MysqlStore(h.mysql, { get: async () => h.pool, close: async () => {} }); await restarted.init();
|
|
107
|
+
assert.deepEqual(await replayExecutorDeliveryDlq((await h.ledger.get(row.id))!, h.ledger, restarted), { queued: false, duplicate: true });
|
|
108
|
+
assert.equal((await restarted.getJob(h.child.job_id))?.status, 'done');
|
|
109
|
+
assert.equal((await h.ledger.get(row.id))?.resolved, true);
|
|
110
|
+
} finally { await h.close(); }
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
test('MySQL executor replay rejects a business Job and mismatched recipient/content', { skip: !enabled }, async () => {
|
|
114
|
+
const h = await fixture();
|
|
115
|
+
try {
|
|
116
|
+
await h.pool.query("UPDATE bz_delivery_dlq SET delivery_kind='executor_target',notification_job_id=? WHERE id=?", [h.parent.job_id, h.nativeId]);
|
|
117
|
+
await assert.rejects(replayExecutorDeliveryDlq((await h.ledger.get(h.nativeId))!, h.ledger, h.store), /binding_conflict/);
|
|
118
|
+
await h.pool.query('UPDATE bz_delivery_dlq SET recipient=? WHERE id=?', ['wrong-recipient', h.executorId]);
|
|
119
|
+
await assert.rejects(replayExecutorDeliveryDlq((await h.ledger.get(h.executorId))!, h.ledger, h.store), /binding_conflict/);
|
|
120
|
+
assert.equal((await h.store.getJob(h.child.job_id))?.status, 'error');
|
|
121
|
+
assert.equal((await h.store.getJob(h.parent.job_id))?.status, 'error');
|
|
122
|
+
} finally { await h.close(); }
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
test('MySQL DLQ stores a UTF-8 byte-bounded long Chinese payload and replays the original full child', { skip: !enabled }, async () => {
|
|
126
|
+
const h = await fixture();
|
|
127
|
+
try {
|
|
128
|
+
const content = '汉'.repeat(60001);
|
|
129
|
+
await h.store.updateJob(h.child.job_id, { input: content });
|
|
130
|
+
await h.ledger.record({ parentJobId: h.child.job_id, channel: h.child.target!, recipient: 'synthetic-recipient', content,
|
|
131
|
+
error: 'synthetic failure', deliveryKind: 'executor_target', notificationJobId: h.child.job_id });
|
|
132
|
+
const [rows]: any = await h.pool.query('SELECT id FROM bz_delivery_dlq ORDER BY id DESC LIMIT 1');
|
|
133
|
+
const row = (await h.ledger.get(Number(rows[0].id)))!;
|
|
134
|
+
assert.equal(Buffer.byteLength(row.content), 60000);
|
|
135
|
+
assert.equal(await classifyDeliveryDlq(row, h.store), 'executor_target');
|
|
136
|
+
assert.equal((await replayExecutorDeliveryDlq(row, h.ledger, h.store)).queued, true);
|
|
137
|
+
assert.equal((await h.store.getJob(h.child.job_id))?.input, content);
|
|
138
|
+
} finally { await h.close(); }
|
|
139
|
+
});
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { mkdtemp, rm } from 'node:fs/promises';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import type { Job } from '../core/contracts/types';
|
|
7
|
+
import type { DeliveryDlqRecord } from '../core/contracts/delivery-replay';
|
|
8
|
+
import type { DeliveryDlqLedgerContract } from '../infrastructure/config/configstore';
|
|
9
|
+
import { JsonlStore } from '../infrastructure/state/state-jsonl';
|
|
10
|
+
import { classifyDeliveryDlq, replayExecutorDeliveryDlq } from './delivery-dlq-replay';
|
|
11
|
+
|
|
12
|
+
async function fixture() {
|
|
13
|
+
const dir = await mkdtemp(join(tmpdir(), 'notification-dlq-test-'));
|
|
14
|
+
const store = new JsonlStore(join(dir, 'jobs.jsonl')); await store.init();
|
|
15
|
+
const job: Job = { job_id: 'notification-child', request_id: 'deliver-business-parent', status: 'error',
|
|
16
|
+
target: 'sms-notify', source: 'delivery', profile: 'delivery', project: '', input_preview: 'fixture',
|
|
17
|
+
input: 'fixture content', metadata: { to: 'fixture-recipient', parent_job_id: 'business-parent' }, created_at: new Date().toISOString(), updated_at: new Date().toISOString() };
|
|
18
|
+
await store.createJob(job);
|
|
19
|
+
const row: DeliveryDlqRecord = { id: 1, parent_job_id: job.job_id, channel: job.target!, recipient: 'fixture-recipient', content: job.input!, resolved: false };
|
|
20
|
+
let failResolve = false;
|
|
21
|
+
const ledger = { get: async () => ({ ...row }), ensureExecutorReplay: async () => {
|
|
22
|
+
const created = !row.executor_replay_key;
|
|
23
|
+
row.delivery_kind = 'executor_target'; row.notification_job_id = job.job_id; row.executor_replay_key = 'delivery-dlq:1';
|
|
24
|
+
return { created, key: row.executor_replay_key };
|
|
25
|
+
}, resolve: async () => { if (failResolve) { failResolve = false; throw new Error('synthetic resolve loss'); } row.resolved = true; } } as unknown as DeliveryDlqLedgerContract;
|
|
26
|
+
return { store, job, row, ledger, failResolve: () => { failResolve = true; }, close: () => rm(dir, { recursive: true, force: true }) };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
test('executor DLQ replay admits one original notification child under concurrent requests', async () => {
|
|
30
|
+
const h = await fixture();
|
|
31
|
+
try {
|
|
32
|
+
assert.equal(await classifyDeliveryDlq(h.row, h.store), 'executor_target');
|
|
33
|
+
const replies = await Promise.all(Array.from({ length: 8 }, () => replayExecutorDeliveryDlq({ ...h.row }, h.ledger, h.store)));
|
|
34
|
+
assert.equal(replies.filter(x => x.queued).length, 1);
|
|
35
|
+
assert.equal((await h.store.getJob(h.job.job_id))?.status, 'queued');
|
|
36
|
+
assert.equal(await h.store.getJob('business-parent'), null);
|
|
37
|
+
assert.equal((await h.store.getJob(h.job.job_id))?.delivery_replay_keys?.['1'], 'delivery-dlq:1');
|
|
38
|
+
} finally { await h.close(); }
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test('lost resolve acknowledgement and completed child preserve the permanent replay marker', async () => {
|
|
42
|
+
const h = await fixture();
|
|
43
|
+
try {
|
|
44
|
+
h.failResolve();
|
|
45
|
+
await assert.rejects(replayExecutorDeliveryDlq({ ...h.row }, h.ledger, h.store), /resolve loss/);
|
|
46
|
+
await h.store.updateJob(h.job.job_id, { status: 'done', delivery_replay_keys: {} });
|
|
47
|
+
const restarted = new JsonlStore((h.store as any).path); await restarted.init();
|
|
48
|
+
const reply = await replayExecutorDeliveryDlq({ ...h.row }, h.ledger, restarted);
|
|
49
|
+
assert.deepEqual(reply, { queued: false, duplicate: true });
|
|
50
|
+
assert.equal((await restarted.getJob(h.job.job_id))?.status, 'done');
|
|
51
|
+
assert.equal(h.row.resolved, true);
|
|
52
|
+
} finally { await h.close(); }
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test('native business-parent DLQ remains native; executor wrong parent or payload cannot replay', async () => {
|
|
56
|
+
const h = await fixture();
|
|
57
|
+
try {
|
|
58
|
+
const parent = { ...h.job, job_id: 'business-parent', request_id: 'business', source: 'business', target: 'llm' };
|
|
59
|
+
await h.store.createJob(parent);
|
|
60
|
+
assert.equal(await classifyDeliveryDlq({ ...h.row, parent_job_id: parent.job_id, channel: 'wecom-main' }, h.store), 'native_channel');
|
|
61
|
+
assert.equal(await classifyDeliveryDlq({ ...h.row, parent_job_id: parent.job_id, channel: 'native-notify' }, h.store), 'native_channel');
|
|
62
|
+
await assert.rejects(classifyDeliveryDlq({ ...h.row, delivery_kind: 'executor_target', parent_job_id: parent.job_id }, h.store), /binding_conflict/);
|
|
63
|
+
await assert.rejects(replayExecutorDeliveryDlq({ ...h.row, content: 'changed' }, h.ledger, h.store), /binding_conflict/);
|
|
64
|
+
await assert.rejects(replayExecutorDeliveryDlq({ ...h.row, recipient: 'different' }, h.ledger, h.store), /binding_conflict/);
|
|
65
|
+
assert.equal((await h.store.getJob(h.job.job_id))?.status, 'error');
|
|
66
|
+
} finally { await h.close(); }
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test('old extension ports fail closed only for executor replay; native stays compatible', async () => {
|
|
70
|
+
const h = await fixture();
|
|
71
|
+
try {
|
|
72
|
+
await assert.rejects(replayExecutorDeliveryDlq(h.row, { get: h.ledger.get } as DeliveryDlqLedgerContract, h.store), /replay_unavailable/);
|
|
73
|
+
assert.equal(await classifyDeliveryDlq({ id: 9, channel: 'native', recipient: 'r', content: 'c', resolved: false }, h.store), 'native_channel');
|
|
74
|
+
} finally { await h.close(); }
|
|
75
|
+
});
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { isOriginalExecutorDelivery, type DeliveryDlqRecord } from '../core/contracts/delivery-replay';
|
|
2
|
+
import type { RuntimeStateStore } from '../core/state/state-contracts';
|
|
3
|
+
import type { DeliveryDlqLedgerContract } from '../infrastructure/config/configstore';
|
|
4
|
+
|
|
5
|
+
export class DeliveryReplayError extends Error {
|
|
6
|
+
constructor(readonly status: number, readonly code: string) { super(code); }
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export async function classifyDeliveryDlq(d: DeliveryDlqRecord, state: RuntimeStateStore): Promise<'native_channel' | 'executor_target'> {
|
|
10
|
+
if (d.delivery_kind === 'native_channel') return 'native_channel';
|
|
11
|
+
if (d.delivery_kind && d.delivery_kind !== 'executor_target') throw new DeliveryReplayError(409, 'delivery_dlq_binding_conflict');
|
|
12
|
+
const job = d.parent_job_id ? await state.getJob(d.notification_job_id || d.parent_job_id) : null;
|
|
13
|
+
if (isOriginalExecutorDelivery(d, job)) return 'executor_target';
|
|
14
|
+
// Legacy native records point to the business parent. Only an executor-shaped
|
|
15
|
+
// record is ambiguous; never redirect it to a native channel of the same name.
|
|
16
|
+
if (d.delivery_kind === 'executor_target' || d.notification_job_id || job?.source === 'delivery') throw new DeliveryReplayError(409, 'delivery_dlq_binding_conflict');
|
|
17
|
+
if (job && job.target !== d.channel) return 'native_channel';
|
|
18
|
+
if (d.channel.endsWith('-notify')) throw new DeliveryReplayError(409, 'delivery_dlq_binding_conflict');
|
|
19
|
+
return 'native_channel';
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export async function replayExecutorDeliveryDlq(d: DeliveryDlqRecord, ledger: DeliveryDlqLedgerContract, state: RuntimeStateStore): Promise<{ queued: boolean; duplicate: boolean }> {
|
|
23
|
+
if (!ledger.ensureExecutorReplay || !state.requeueDeliveryJobOnce) throw new DeliveryReplayError(503, 'delivery_dlq_replay_unavailable');
|
|
24
|
+
const jobId = d.notification_job_id || d.parent_job_id;
|
|
25
|
+
const job = jobId ? await state.getJob(jobId) : null;
|
|
26
|
+
if (!job || !isOriginalExecutorDelivery(d, job)) throw new DeliveryReplayError(409, 'delivery_dlq_binding_conflict');
|
|
27
|
+
const replay = await ledger.ensureExecutorReplay(d.id, job.job_id);
|
|
28
|
+
if (!replay) return { queued: false, duplicate: true };
|
|
29
|
+
const outcome = await state.requeueDeliveryJobOnce({ dlq_id: d.id, replay_key: replay.key,
|
|
30
|
+
job_id: job.job_id, request_id: job.request_id, target: job.target!,
|
|
31
|
+
isOriginalDelivery: async () => {
|
|
32
|
+
const current = await ledger.get(d.id);
|
|
33
|
+
return Boolean(current && !current.resolved && current.executor_replay_key === replay.key && isOriginalExecutorDelivery(current, job));
|
|
34
|
+
} });
|
|
35
|
+
if (outcome === 'in_flight') throw new DeliveryReplayError(409, 'delivery_notification_in_flight');
|
|
36
|
+
if (outcome === 'missing' || outcome === 'conflict') throw new DeliveryReplayError(409, 'delivery_dlq_binding_conflict');
|
|
37
|
+
// A lost resolve acknowledgement is safe: the permanent state marker is
|
|
38
|
+
// checked before any later admission, including after the child has completed.
|
|
39
|
+
await ledger.resolve(d.id);
|
|
40
|
+
return { queued: outcome === 'queued', duplicate: outcome === 'already_queued' };
|
|
41
|
+
}
|
package/src/app/delivery.ts
CHANGED
|
@@ -10,6 +10,7 @@ import type { Job } from '../core/contracts/types';
|
|
|
10
10
|
import type { AppConfig } from '../core/config/config';
|
|
11
11
|
import type { RuntimeStateStore } from '../core/state/state-contracts';
|
|
12
12
|
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
13
|
+
import { notificationBackgroundWorkFor } from '../core/runtime/notification-background-work';
|
|
13
14
|
|
|
14
15
|
export interface DeliveryDeps {
|
|
15
16
|
cfg: AppConfig;
|
|
@@ -55,7 +56,7 @@ export async function spawnDeliveryJobFor(deps: DeliveryDeps, parent: Job): Prom
|
|
|
55
56
|
await deps.stateStore.appendAudit({ ts: deps.now(), job_id: parent.job_id, request_id: parent.request_id, event: sent.ok ? 'channel_delivered' : 'channel_delivery_error', detail: { channel: channelName, to: recipient, ...(sent.ok ? {} : { error: sent.error }) } });
|
|
56
57
|
if (!sent.ok) {
|
|
57
58
|
void sendAlertWithDeps(outboundRuntime, `delivery_failed_${channelName}`, `渠道回流送达失败(${channelName} → ${recipient}):${String(sent.error ?? '未知').slice(0, 200)}。用户可能未收到结果,关联任务 ${parent.job_id}。`).catch(() => { /* 告警失败不阻塞 */ });
|
|
58
|
-
void deps.configStore
|
|
59
|
+
if (deps.configStore) void notificationBackgroundWorkFor(deps.stateStore).track('delivery-dlq', () => deps.configStore!.deliveryDlq.record({ parentJobId: parent.job_id, channel: channelName, recipient, content: String(text), error: String(sent.error ?? ''), deliveryKind: 'native_channel' }));
|
|
59
60
|
}
|
|
60
61
|
return;
|
|
61
62
|
}
|
|
@@ -153,7 +154,7 @@ export async function spawnDeliveryJobFor(deps: DeliveryDeps, parent: Job): Prom
|
|
|
153
154
|
await deps.stateStore.appendAudit({ ts: deps.now(), job_id: parent.job_id, request_id: parent.request_id, event: sent.ok ? 'channel_delivered' : 'channel_delivery_error', detail: { channel: channelName, to: single ? recipients[0] : `${recipients.length}人`, via: 'delivery', ...(sent.ok ? { thread_id: threadId ?? null } : { error: sent.error }) } });
|
|
154
155
|
if (!sent.ok) {
|
|
155
156
|
void sendAlertWithDeps(outboundRuntime, `delivery_failed_${channelName}`, `渠道送达失败(${channelName} → ${single ? recipients[0] : recipients.length + '人'}):${String(sent.error ?? '未知').slice(0, 200)}。收件人可能未收到,关联任务 ${parent.job_id}。`).catch(() => { /* 告警失败不阻塞 */ });
|
|
156
|
-
void deps.configStore
|
|
157
|
+
if (deps.configStore) void notificationBackgroundWorkFor(deps.stateStore).track('delivery-dlq', () => deps.configStore!.deliveryDlq.record({ parentJobId: parent.job_id, channel: channelName, recipient: recipients.join('|'), content: String(body), error: String(sent.error ?? ''), deliveryKind: 'native_channel' }));
|
|
157
158
|
}
|
|
158
159
|
return;
|
|
159
160
|
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { mkdtemp, writeFile, readFile, rm } from 'node:fs/promises';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { Readable } from 'node:stream';
|
|
7
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
8
|
+
import type { AppConfig } from '../core/config/config';
|
|
9
|
+
import { createBailingHubKernel } from './kernel';
|
|
10
|
+
|
|
11
|
+
test('Kernel close drains detached callback before resource release; timeout permits retry', async () => {
|
|
12
|
+
const dir = await mkdtemp(join(tmpdir(), 'kernel-notification-test-'));
|
|
13
|
+
const cfg: AppConfig = { root: process.cwd(), runtimeRoot: dir, env: 'development',
|
|
14
|
+
server: { host: '127.0.0.1', port: 0, token: 'synthetic-only' }, brand: { name: 'Synthetic' },
|
|
15
|
+
displayTz: 'Asia/Shanghai', displayTzLabel: '北京时间', auditRetentionDays: 0, alerts: null,
|
|
16
|
+
metrics: { enabled: false, token: '', scrapeTimeoutMs: 1000 }, bootstrapAdmin: null,
|
|
17
|
+
concurrency: 1, killSwitchFile: join(dir, '.paused'), claudeBin: 'synthetic-unused', defaultProfile: 'readonly', brainDir: join(dir, 'brain'),
|
|
18
|
+
state: { backend: 'jsonl', jsonlPath: join(dir, 'jobs.jsonl'), mysql: { host: '', port: 3306, database: '', user: '', password: '', connectionLimit: 2 } },
|
|
19
|
+
projects: {}, llmCredentials: {}, executor: { hubUrl: '', token: '', executorId: 'synthetic', targets: [], waitMs: 100, concurrency: 1, labels: [] } };
|
|
20
|
+
const job = { job_id: 'synthetic-notification-job', request_id: 'synthetic-notification-request', status: 'dispatched', target: 'synthetic-executor',
|
|
21
|
+
source: 'test', profile: 'readonly', project: '', input_preview: '', metadata: {}, callback_url: 'https://synthetic.invalid/callback',
|
|
22
|
+
created_at: new Date().toISOString(), updated_at: new Date().toISOString() };
|
|
23
|
+
await writeFile(cfg.state.jsonlPath, JSON.stringify({ kind: 'job', job }) + '\n');
|
|
24
|
+
const originalFetch = globalThis.fetch;
|
|
25
|
+
let started!: () => void, release!: () => void, completed = false;
|
|
26
|
+
const startedGate = new Promise<void>(resolve => { started = resolve; });
|
|
27
|
+
const gate = new Promise<void>(resolve => { release = resolve; });
|
|
28
|
+
globalThis.fetch = async () => { started(); await gate; completed = true; return new Response('', { status: 200 }); };
|
|
29
|
+
const kernel = createBailingHubKernel({ instanceKey: 'notification:test', config: cfg, bootstrapLocalAdmin: false });
|
|
30
|
+
try {
|
|
31
|
+
const req = Readable.from([Buffer.from(JSON.stringify({ job_id: job.job_id, ok: true, output: { text: 'synthetic result' } }))]) as IncomingMessage;
|
|
32
|
+
req.method = 'POST'; req.url = '/executor/result'; req.headers = { host: 'localhost', authorization: 'Bearer synthetic-only' };
|
|
33
|
+
let responseStatus = 0;
|
|
34
|
+
await kernel.handle(req, { writeHead(code: number) { responseStatus = code; }, end() {} } as unknown as ServerResponse, new URL('http://localhost/executor/result'));
|
|
35
|
+
await startedGate;
|
|
36
|
+
assert.equal(responseStatus, 200);
|
|
37
|
+
await assert.rejects(kernel.close(2), /notification background drain timed out/);
|
|
38
|
+
assert.equal(completed, false);
|
|
39
|
+
const pendingClose = kernel.close(1000);
|
|
40
|
+
release(); await pendingClose;
|
|
41
|
+
assert.equal(completed, true);
|
|
42
|
+
const records = (await readFile(cfg.state.jsonlPath, 'utf8')).trim().split('\n').map(line => JSON.parse(line));
|
|
43
|
+
assert.equal(records.filter(x => x.kind === 'job').at(-1).job.status, 'done');
|
|
44
|
+
assert.equal(records.filter(x => x.kind === 'audit' && x.entry.event === 'callback').length, 1);
|
|
45
|
+
await kernel.close(0);
|
|
46
|
+
} finally {
|
|
47
|
+
release(); await kernel.close(1000); globalThis.fetch = originalFetch; await rm(dir, { recursive: true, force: true });
|
|
48
|
+
}
|
|
49
|
+
});
|
package/src/app/kernel.ts
CHANGED
|
@@ -63,6 +63,7 @@ import { handleSendFor, type SendApiDeps } from '../routes/send';
|
|
|
63
63
|
import { handleWecomInboundFor, WecomRuntimeState, type WecomApiDeps } from '../routes/wecom';
|
|
64
64
|
import { WecomAccessTokenCache } from '../adapters/channels/wecom-api';
|
|
65
65
|
import { DemoDatasetService } from '../services/demo-dataset';
|
|
66
|
+
import { NotificationBackgroundWork, bindNotificationBackgroundWork } from '../core/runtime/notification-background-work';
|
|
66
67
|
|
|
67
68
|
const timezoneClaims = new Map<string, number>();
|
|
68
69
|
const MAX_KERNEL_CLOSE_DRAIN_MS = 10 * 60_000;
|
|
@@ -184,6 +185,11 @@ export function createBailingHubKernel(input: CreateBailingHubKernelInputV1): Ba
|
|
|
184
185
|
composition.cfgStore?.usage?.backgroundWork.setFailureReporter(kind => {
|
|
185
186
|
logger.warn?.(`[Kernel ${instanceKey}] usage background ${kind} failed; original durable evidence is retained`);
|
|
186
187
|
});
|
|
188
|
+
const notificationWork = new NotificationBackgroundWork();
|
|
189
|
+
bindNotificationBackgroundWork(composition.store, notificationWork);
|
|
190
|
+
notificationWork.setFailureReporter(kind => {
|
|
191
|
+
logger.warn?.(`[Kernel ${instanceKey}] notification background ${kind} failed`);
|
|
192
|
+
});
|
|
187
193
|
const demoDataset = composition.cfgStore ? new DemoDatasetService(composition.cfgStore, cfg.demoDataset) : null;
|
|
188
194
|
const runtimeHelpers = createRuntimeContextHelpers({
|
|
189
195
|
cfg,
|
|
@@ -258,6 +264,7 @@ export function createBailingHubKernel(input: CreateBailingHubKernelInputV1): Ba
|
|
|
258
264
|
isPaused,
|
|
259
265
|
auditFailures: edition.auditFailures,
|
|
260
266
|
logger,
|
|
267
|
+
notificationWork,
|
|
261
268
|
});
|
|
262
269
|
|
|
263
270
|
const runDeps: RunApiDeps = {
|
|
@@ -505,6 +512,8 @@ export function createBailingHubKernel(input: CreateBailingHubKernelInputV1): Ba
|
|
|
505
512
|
usageWork.beginDrain();
|
|
506
513
|
if (!await usageWork.drain(remainingDrainMs())) throw new Error(`Kernel ${instanceKey} usage background drain timed out`);
|
|
507
514
|
}
|
|
515
|
+
notificationWork.beginDrain();
|
|
516
|
+
if (!await notificationWork.drain(remainingDrainMs())) throw new Error(`Kernel ${instanceKey} notification background drain timed out`);
|
|
508
517
|
targetRegistry.bindStore(null);
|
|
509
518
|
wecomRuntimeState.dispose();
|
|
510
519
|
wecomAccessTokenCache.dispose();
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import type { AppConfig } from '../core/config/config';
|
|
4
|
+
import type { Job } from '../core/contracts/types';
|
|
5
|
+
import type { RuntimeStateStore } from '../core/state/state-contracts';
|
|
6
|
+
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
7
|
+
import { notificationBackgroundWorkFor } from '../core/runtime/notification-background-work';
|
|
8
|
+
import { finishJob } from '../core/runtime/finish-runtime';
|
|
9
|
+
import { approvalDepsForStores } from './tool-approvals';
|
|
10
|
+
import { spawnDeliveryJobFor } from './delivery';
|
|
11
|
+
import { outboundRuntimeDepsFor, sendAlertWithDeps } from './outbound';
|
|
12
|
+
|
|
13
|
+
const cfg = { server: { token: 'synthetic-only' }, brand: { name: 'Synthetic' }, alerts: null } as AppConfig;
|
|
14
|
+
const now = () => new Date().toISOString();
|
|
15
|
+
const job: Job = { job_id: 'fixture', request_id: 'fixture', status: 'done', source: 'test', profile: 'fixture', project: '',
|
|
16
|
+
input_preview: '', created_at: now(), updated_at: now(), result: { text: 'synthetic' }, metadata: {} };
|
|
17
|
+
|
|
18
|
+
for (const kind of ['delivery', 'approval', 'alert'] as const) test(`notification tracker retains innermost detached ${kind} webhook`, async () => {
|
|
19
|
+
const originalFetch = globalThis.fetch;
|
|
20
|
+
let release!: () => void, started!: () => void;
|
|
21
|
+
const gate = new Promise<void>(resolve => { release = resolve; });
|
|
22
|
+
const startedGate = new Promise<void>(resolve => { started = resolve; });
|
|
23
|
+
globalThis.fetch = async () => { started(); await gate; return new Response('', { status: 200 }); };
|
|
24
|
+
const state = { appendAudit: async () => {} } as unknown as RuntimeStateStore;
|
|
25
|
+
const work = notificationBackgroundWorkFor(state);
|
|
26
|
+
try {
|
|
27
|
+
if (kind === 'delivery') await spawnDeliveryJobFor({ cfg, configStore: null, stateStore: state, now, sleep: async () => {} },
|
|
28
|
+
{ ...job, dispatch: { delivery: { type: 'webhook', url: 'https://synthetic.invalid/delivery' } } });
|
|
29
|
+
if (kind === 'approval') {
|
|
30
|
+
const approvals = approvalDepsForStores({ approvals: {} } as ConfigStoreContract, state, job, { name: 'fixture' } as any,
|
|
31
|
+
{ approval: { type: 'business_webhook', url: 'https://synthetic.invalid/approval' } }, { provider: 'fixture', allow: ['*'] }, cfg, now, async () => {});
|
|
32
|
+
await approvals!.notify(1, { tool: 'fixture', scope: 'fixture', risk: 'high', policy: 'always', reason: 'fixture', method: 'POST', path: '/', args_hash: 'fixture', args_json: '{}' });
|
|
33
|
+
}
|
|
34
|
+
if (kind === 'alert') await sendAlertWithDeps(outboundRuntimeDepsFor({ cfg: { ...cfg, alerts: { type: 'webhook', url: 'https://synthetic.invalid/alert', cooldown_min: 0 } },
|
|
35
|
+
configStore: null, stateStore: state, now, sleep: async () => {} }), 'fixture', 'synthetic');
|
|
36
|
+
await startedGate;
|
|
37
|
+
work.beginDrain(); assert.equal(await work.drain(1), false);
|
|
38
|
+
release(); assert.equal(await work.drain(100), true);
|
|
39
|
+
} finally { release(); await work.drain(100); globalThis.fetch = originalFetch; }
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test('finish tracks a DLQ insertion through drain and reports a failed insert', async () => {
|
|
43
|
+
const state = { updateJob: async (_id: string, patch: Partial<Job>) => ({ ...job, ...patch }), appendAudit: async () => {} };
|
|
44
|
+
const work = notificationBackgroundWorkFor(state);
|
|
45
|
+
const failures: string[] = []; work.setFailureReporter(kind => failures.push(kind));
|
|
46
|
+
let release!: () => void;
|
|
47
|
+
const gate = new Promise<void>(resolve => { release = resolve; });
|
|
48
|
+
await finishJob({ ...job, source: 'delivery', target: 'sms-notify' }, { status: 'error' }, { store: state, now,
|
|
49
|
+
fireCallback: async () => {}, spawnDeliveryJob: async () => {}, sendAlert: async () => {},
|
|
50
|
+
deliveryDlq: { async record() { await gate; throw new Error('private SQL error'); } } });
|
|
51
|
+
assert.equal(await work.drain(1), false); release(); assert.equal(await work.drain(100), true);
|
|
52
|
+
assert.ok(failures.includes('delivery-dlq'));
|
|
53
|
+
});
|