evolcore 0.0.43-test.6 → 0.0.43-test.7
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 +48 -0
- package/bin/ecmsg.js +171 -54
- package/dist/agents/baseagent-availability.js +1 -1
- package/dist/agents/codex/app-server-client.js +22 -0
- package/dist/agents/codex-runner.js +69 -2
- package/dist/aun/msg/p2p.js +6 -1
- package/dist/channels/aun.js +234 -21
- package/dist/cli/agent-create.js +2 -2
- package/dist/cli/daemon-commands.js +6 -66
- package/dist/cli/daemon-lifecycle-client.js +61 -0
- package/dist/cli/ecmsg-gateway.js +35 -2
- package/dist/cli/events-command.js +73 -0
- package/dist/cli/index.js +31 -14
- package/dist/cli/invoke-command.js +182 -0
- package/dist/cli/managed-command-guard.js +6 -1
- package/dist/cli/restart-monitor.js +45 -47
- package/dist/cli/services-command.js +111 -0
- package/dist/cli/team-workspace-command.js +134 -0
- package/dist/cli/thread-command.js +6 -2
- package/dist/cli/watch-msg.js +1 -1
- package/dist/config/config-field-policy.js +2 -2
- package/dist/config/config-manager.js +0 -7
- package/dist/config/invoke-ipc-service.js +118 -0
- package/dist/config/schema-migration.js +6 -1
- package/dist/config-store.js +2 -1
- package/dist/core/agent-reload-coordinator.js +6 -4
- package/dist/core/agent-runtime.js +104 -10
- package/dist/core/auth/delegation-authorization.js +66 -0
- package/dist/core/auth/operation-catalog.js +20 -0
- package/dist/core/baseagent-loader.js +60 -130
- package/dist/core/channel-loader.js +10 -1
- package/dist/core/channel-runtime.js +4 -3
- package/dist/core/command/agent-control.js +1 -1
- package/dist/core/command/agent-storage-menu.js +1 -1
- package/dist/core/command/chatmode-config.js +2 -36
- package/dist/core/command/command-handler.js +53 -11
- package/dist/core/command/data-root-resolver.js +32 -23
- package/dist/core/command/eventcenter-menu.js +338 -0
- package/dist/core/command/menu-catalog.js +8 -0
- package/dist/core/command/menu-handler.js +198 -84
- package/dist/core/command/menu-protocol.js +60 -11
- package/dist/core/command/menu-query-batch.js +194 -0
- package/dist/core/command/slash-gate.js +1 -1
- package/dist/core/command/slash-handler.js +34 -42
- package/dist/core/command/team-workspace-bootstrap.js +350 -0
- package/dist/core/command/{pa-workspace-calendar.js → team-workspace-calendar.js} +7 -7
- package/dist/core/command/team-workspace-initializer.js +2 -0
- package/dist/core/command/{pa-workspace-items.js → team-workspace-items.js} +83 -68
- package/dist/core/command/team-workspace-job-store.js +88 -0
- package/dist/core/command/team-workspace-management-service.js +2 -0
- package/dist/core/command/team-workspace-management-store.js +96 -0
- package/dist/core/command/team-workspace-management.js +265 -0
- package/dist/core/command/team-workspace-members-menu.js +88 -0
- package/dist/core/command/team-workspace-store.js +612 -0
- package/dist/core/command/team-workspace-team.js +193 -0
- package/dist/core/daemon-control.js +8 -5
- package/dist/core/daemon-lifecycle.js +132 -73
- package/dist/core/handoff/runtime.js +3 -3
- package/dist/core/invoke/executors/index.js +13 -0
- package/dist/core/invoke/executors/media.js +283 -0
- package/dist/core/invoke/executors/text.js +198 -0
- package/dist/core/invoke/invoke-service.js +157 -0
- package/dist/core/invoke/style-router.js +48 -0
- package/dist/core/invoke/types.js +19 -0
- package/dist/core/ipc-registration.js +46 -7
- package/dist/core/memory/consolidation.js +7 -5
- package/dist/core/message/aun-ipc-sender.js +147 -17
- package/dist/core/message/im-renderer.js +28 -84
- package/dist/core/message/message-bridge.js +4 -0
- package/dist/core/message/message-utils.js +10 -2
- package/dist/core/message/peer-mode.js +7 -34
- package/dist/core/message/response-engine.js +157 -54
- package/dist/core/message/send-options.js +7 -4
- package/dist/core/message/send-routing.js +43 -5
- package/dist/core/ownership/owner-resolver.js +7 -0
- package/dist/core/permission/ec-command-parser.js +3 -2
- package/dist/core/permission/protected-paths.js +12 -2
- package/dist/core/permission/shell-environment.js +9 -0
- package/dist/core/session/session-file-health.js +243 -0
- package/dist/core/session/session-fs-store.js +2 -3
- package/dist/core/task/task-recovery-service.js +13 -2
- package/dist/core/thread/command-parser.js +9 -2
- package/dist/core/thread/thread-operation.js +21 -2
- package/dist/core/thread/thread-route.js +13 -2
- package/dist/directory/owner-directory-admission.js +40 -53
- package/dist/directory/owner-directory-cache.js +89 -113
- package/dist/directory/owner-directory-query-operation.js +8 -10
- package/dist/eck/kit-renderer.js +7 -5
- package/dist/ecweb/basic-settings-service.js +1 -1
- package/dist/ecweb/message-context-service.js +0 -4
- package/dist/ecweb/runtime/lifecycle.js +6 -2
- package/dist/ecweb/runtime/supervisor.js +19 -4
- package/dist/event-center/admission-materializer.js +114 -0
- package/dist/event-center/bus-gate.js +136 -0
- package/dist/event-center/bus-host.js +290 -0
- package/dist/event-center/bus-resolver.js +120 -0
- package/dist/event-center/center-config.js +100 -0
- package/dist/event-center/client-factory.js +50 -0
- package/dist/event-center/daemon.js +45 -0
- package/dist/event-center/directory-source.js +53 -0
- package/dist/event-center/dispatcher.js +157 -0
- package/dist/event-center/event-log.js +110 -0
- package/dist/event-center/index-generator.js +63 -0
- package/dist/event-center/ipc-operation.js +308 -0
- package/dist/event-center/ledger.js +52 -0
- package/dist/event-center/pack-loader.js +202 -0
- package/dist/event-center/pack-manager.js +85 -0
- package/dist/event-center/registry.js +238 -0
- package/dist/event-center/runtime.js +641 -0
- package/dist/event-center/script-runner.js +356 -0
- package/dist/event-center/types.js +35 -0
- package/dist/event-center/validation.js +413 -0
- package/dist/index.js +285 -99
- package/dist/ipc.js +66 -12
- package/dist/paths.js +20 -0
- package/dist/product.js +14 -0
- package/dist/proxy/manager.js +5 -1
- package/dist/proxy/service-supervisor.js +13 -4
- package/dist/response-system/engines/v1/index.js +0 -1
- package/dist/response-system/modes/single-session/index.js +1 -1
- package/dist/services/dispatcher.js +100 -0
- package/dist/services/idempotency.js +90 -0
- package/dist/services/identity.js +52 -0
- package/dist/services/index-generator.js +70 -0
- package/dist/services/index.js +449 -0
- package/dist/services/ipc-operation.js +458 -0
- package/dist/services/ledger.js +52 -0
- package/dist/services/message-log.js +112 -0
- package/dist/services/pack-manager.js +204 -0
- package/dist/services/reply.js +55 -0
- package/dist/services/router.js +95 -0
- package/dist/services/script-runner.js +422 -0
- package/dist/services/service-payload.js +70 -0
- package/dist/services/types.js +18 -0
- package/dist/services/validation.js +297 -0
- package/dist/trigger/application-service.js +18 -0
- package/dist/trigger/event-source.js +1 -1
- package/dist/trigger/ipc-service.js +3 -1
- package/dist/trigger/script-sandbox.js +118 -22
- package/dist/utils/cross-platform.js +24 -10
- package/dist/utils/evolcore-version.js +69 -27
- package/dist/utils/instance-registry.js +19 -13
- package/dist/utils/process-introspect.js +45 -9
- package/dist/utils/startup-trace.js +74 -37
- package/dist/utils/windows-shell-trust.js +80 -6
- package/kits/docs/INDEX.md +2 -2
- package/kits/docs/aun/ABILITY_CALLING.md +7 -14
- package/kits/docs/context-assembly.md +1 -1
- package/kits/docs/evolcore/INDEX.md +2 -0
- package/kits/docs/evolcore/ability.md +4 -0
- package/kits/docs/evolcore/aid.md +1 -1
- package/kits/docs/evolcore/event-center.md +207 -0
- package/kits/docs/evolcore/file-navigation.md +10 -264
- package/kits/docs/evolcore/fs.md +3 -2
- package/kits/docs/evolcore/group.md +1 -1
- package/kits/docs/evolcore/memory-architecture.md +2 -0
- package/kits/docs/evolcore/menu-protocol.md +21 -0
- package/kits/docs/evolcore/msg.md +15 -3
- package/kits/docs/evolcore/provider.md +3 -1
- package/kits/docs/evolcore/response.md +5 -5
- package/kits/docs/evolcore/services.md +277 -0
- package/kits/docs/evolcore/task.md +2 -0
- package/kits/docs/evolcore/team-workspace.md +41 -0
- package/kits/eck_manifest.json +26 -0
- package/kits/rules/02-navigation.md +10 -1
- package/kits/schemas/_meta.json +17 -6
- package/kits/schemas/agent-config.schema.19.json +5 -7
- package/kits/schemas/agent-config.schema.20.json +936 -0
- package/kits/schemas/relation-config.schema.12.json +2 -3
- package/kits/schemas/role-config.schema.2.json +4 -4
- package/kits/skills/.switches.json +1 -5
- package/kits/skills/ability/SKILL.md +56 -0
- package/kits/skills/ability/references/calling.md +56 -0
- package/kits/skills/{ec-ability → ability}/references/contract-checklist.md +1 -1
- package/kits/skills/{ec-ability → ability}/references/development.md +9 -33
- package/kits/skills/{ec-ability → ability}/references/management.md +2 -2
- package/kits/skills/{ec-ability → ability}/references/recovery.md +1 -1
- package/kits/skills/{ec-ability → ability}/references/runtime-protocol.md +2 -0
- package/kits/skills/ec-agent-create/SKILL.md +0 -1
- package/kits/skills/ec-service-proxy/SKILL.md +34 -5
- package/kits/skills/personal-assistant/SKILL.md +6 -6
- package/kits/skills/personal-assistant/references/02-bootstrap.md +4 -4
- package/kits/skills/personal-assistant/scripts/clean.mjs +4 -4
- package/kits/skills/personal-assistant/scripts/init.mjs +2 -2
- package/kits/skills/personal-assistant/scripts/pa.mjs +4 -4
- package/kits/templates/system-fragments/channel.md +3 -3
- package/kits/templates/system-fragments/commands.md +5 -3
- package/kits/templates/system-fragments/reply.md +0 -5
- package/kits/templates/system-fragments/thread.md +10 -8
- package/package.json +3 -5
- package/dist/cli/pa-workspace-command.js +0 -225
- package/dist/core/command/pa-workspace-store.js +0 -468
- package/dist/core/relation/pa-team.js +0 -132
- package/kits/docs/evolcore/pa-workspace.md +0 -51
- package/kits/skills/aid-ability/SKILL.md +0 -244
- package/kits/skills/ec-ability/SKILL.md +0 -67
- package/kits/skills/ec-ability/references/workflows.md +0 -15
|
@@ -3,7 +3,7 @@ import path from 'path';
|
|
|
3
3
|
import { spawn } from 'child_process';
|
|
4
4
|
import { isDevMode, resolvePaths } from '../../paths.js';
|
|
5
5
|
import { SERVICE_HEALTH_INTERVALS, SERVICE_RESTART_BACKOFF_MS, SERVICE_RESTART_MAX_ATTEMPTS, SERVICE_RESTART_WINDOW_MS, SERVICE_STARTUP_TIMEOUT_MS, } from '../../config/daemon-services.js';
|
|
6
|
-
import { WEB_PACKAGE_NAME } from '../../product.js';
|
|
6
|
+
import { RUNTIME_HOME_ENV, WEB_PACKAGE_NAME } from '../../product.js';
|
|
7
7
|
import { resolveGlobalPkgAsync } from '../../utils/npm-ops.js';
|
|
8
8
|
import { ecwebVersionRequirementError, resolveEcwebLaunchCommand } from './launch.js';
|
|
9
9
|
import * as platform from '../../utils/cross-platform.js';
|
|
@@ -11,6 +11,7 @@ import { getProcessStartTimeAsync } from '../../utils/process-introspect.js';
|
|
|
11
11
|
import { matchesEcwebInstanceHealth, parseEcwebInstanceRecord } from '../../contracts/ecweb-instance.js';
|
|
12
12
|
import { sanitizeMenuLogValue } from '../../core/command/menu-protocol.js';
|
|
13
13
|
import { stopEcwebProcess } from './lifecycle.js';
|
|
14
|
+
import { sanitizeServiceEnvironment } from '../../core/permission/shell-environment.js';
|
|
14
15
|
const INSTANCE_FILE_RE = /^(?:ecweb|watch-web)-\d+\.json$/;
|
|
15
16
|
function sleep(ms) {
|
|
16
17
|
return new Promise(resolve => setTimeout(resolve, ms));
|
|
@@ -125,7 +126,7 @@ async function probe(record, timeoutMs) {
|
|
|
125
126
|
* ECWeb's own stale-instance cleanup, and daemon startup.
|
|
126
127
|
*/
|
|
127
128
|
export function createEcwebSupervisor(options) {
|
|
128
|
-
const settleInitialHealth = options.startupTrace?.startTask('daemon.ecwebHealthReady');
|
|
129
|
+
const settleInitialHealth = options.startupTrace?.startTask('daemon.ecwebHealthReady', undefined, { initialPhase: 'waiting' });
|
|
129
130
|
let healthConfig = options.health;
|
|
130
131
|
let failureThreshold = Math.max(1, healthConfig?.failureThreshold ?? options.failureThreshold ?? 3);
|
|
131
132
|
let desiredPort = options.port;
|
|
@@ -139,6 +140,7 @@ export function createEcwebSupervisor(options) {
|
|
|
139
140
|
let failureCount = 0;
|
|
140
141
|
let lastHealthFailure = '未发现有效的 ECWeb 实例注册';
|
|
141
142
|
let healthy = false;
|
|
143
|
+
let checkedAt;
|
|
142
144
|
let startInFlight = null;
|
|
143
145
|
let childStartedAt = 0;
|
|
144
146
|
let childIdentityStartedAt = null;
|
|
@@ -260,6 +262,7 @@ export function createEcwebSupervisor(options) {
|
|
|
260
262
|
child = null;
|
|
261
263
|
childIdentityStartedAt = null;
|
|
262
264
|
healthy = false;
|
|
265
|
+
checkedAt = undefined;
|
|
263
266
|
return;
|
|
264
267
|
}
|
|
265
268
|
await stopTrackedProcess({ pid: current.pid, startedAt: current.startedAt }, onTiming);
|
|
@@ -268,6 +271,7 @@ export function createEcwebSupervisor(options) {
|
|
|
268
271
|
child = null;
|
|
269
272
|
childIdentityStartedAt = null;
|
|
270
273
|
healthy = false;
|
|
274
|
+
checkedAt = undefined;
|
|
271
275
|
};
|
|
272
276
|
const spawnEcweb = async () => {
|
|
273
277
|
if (stopping || !desiredEnabled || runtimeMode !== 'managed')
|
|
@@ -339,8 +343,8 @@ export function createEcwebSupervisor(options) {
|
|
|
339
343
|
stdio: ['ignore', childLogFd, childLogFd, 'ipc'],
|
|
340
344
|
windowsHide: platform.isWindows,
|
|
341
345
|
env: {
|
|
342
|
-
...process.env,
|
|
343
|
-
|
|
346
|
+
...sanitizeServiceEnvironment(process.env),
|
|
347
|
+
[RUNTIME_HOME_ENV]: root,
|
|
344
348
|
EVOLCORE_ECWEB_SUPERVISED: '1',
|
|
345
349
|
},
|
|
346
350
|
});
|
|
@@ -377,6 +381,7 @@ export function createEcwebSupervisor(options) {
|
|
|
377
381
|
childStartedAt = 0;
|
|
378
382
|
childIdentityStartedAt = null;
|
|
379
383
|
healthy = false;
|
|
384
|
+
checkedAt = Date.now();
|
|
380
385
|
if (!expectedExit) {
|
|
381
386
|
if (active?.pid === spawned.pid)
|
|
382
387
|
active = null;
|
|
@@ -418,6 +423,7 @@ export function createEcwebSupervisor(options) {
|
|
|
418
423
|
if (!desiredEnabled || runtimeMode !== 'managed')
|
|
419
424
|
return;
|
|
420
425
|
healthy = instance !== null;
|
|
426
|
+
checkedAt = Date.now();
|
|
421
427
|
if (instance) {
|
|
422
428
|
launchRequested = false;
|
|
423
429
|
cancelRecovery();
|
|
@@ -539,6 +545,7 @@ export function createEcwebSupervisor(options) {
|
|
|
539
545
|
return;
|
|
540
546
|
}
|
|
541
547
|
// Give an independently started ECWeb time to publish its instance record.
|
|
548
|
+
settleInitialHealth?.phase?.('waiting', 'existing ECWeb instance');
|
|
542
549
|
const existing = await waitForHealthyInstance(1_500);
|
|
543
550
|
if (stopping) {
|
|
544
551
|
if (existing)
|
|
@@ -547,12 +554,14 @@ export function createEcwebSupervisor(options) {
|
|
|
547
554
|
}
|
|
548
555
|
if (existing) {
|
|
549
556
|
healthy = true;
|
|
557
|
+
checkedAt = Date.now();
|
|
550
558
|
hasBeenReady = true;
|
|
551
559
|
await setActiveFromEntry(existing, false);
|
|
552
560
|
options.logger.info(`✓ ECWeb supervisor 接管现有实例 (PID: ${existing.record.pid}, 端口: ${existing.record.port})`);
|
|
553
561
|
settleInitialHealth?.('ok');
|
|
554
562
|
}
|
|
555
563
|
else {
|
|
564
|
+
settleInitialHealth?.phase?.('running');
|
|
556
565
|
failureCount = failureThreshold;
|
|
557
566
|
launchRequested = 'manual';
|
|
558
567
|
await check();
|
|
@@ -594,6 +603,7 @@ export function createEcwebSupervisor(options) {
|
|
|
594
603
|
child = null;
|
|
595
604
|
active = null;
|
|
596
605
|
healthy = false;
|
|
606
|
+
checkedAt = undefined;
|
|
597
607
|
}
|
|
598
608
|
else if (enabledChanged || portChanged || modeChanged) {
|
|
599
609
|
await killActive();
|
|
@@ -637,10 +647,15 @@ export function createEcwebSupervisor(options) {
|
|
|
637
647
|
// Report the latest supervised state; status reads must not run tasklist.
|
|
638
648
|
const running = active !== null;
|
|
639
649
|
const ready = running && healthy && active.port === desiredPort;
|
|
650
|
+
const health = desiredEnabled && runtimeMode === 'managed' && checkedAt !== undefined ? healthy : null;
|
|
640
651
|
return {
|
|
641
652
|
enabled: desiredEnabled,
|
|
642
653
|
port: desiredPort,
|
|
643
654
|
state: !desiredEnabled ? 'disabled' : ready ? 'ready' : failureCount >= failureThreshold ? 'failed' : 'starting',
|
|
655
|
+
healthy: health,
|
|
656
|
+
hasProbe: runtimeMode === 'managed',
|
|
657
|
+
endpointHealth: health === null ? 'unknown' : health ? 'healthy' : 'unhealthy',
|
|
658
|
+
...(health === null ? {} : { checkedAt }),
|
|
644
659
|
...(running ? { pid: active.pid } : {}),
|
|
645
660
|
};
|
|
646
661
|
},
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { AID_PATTERN } from './validation.js';
|
|
4
|
+
function aid(value) {
|
|
5
|
+
return typeof value === 'string' && AID_PATTERN.test(value) ? value : undefined;
|
|
6
|
+
}
|
|
7
|
+
function identityAid(value) {
|
|
8
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
9
|
+
return undefined;
|
|
10
|
+
return aid(value.aid);
|
|
11
|
+
}
|
|
12
|
+
function readContactSnapshot(agentDir, selfAid) {
|
|
13
|
+
let raw;
|
|
14
|
+
try {
|
|
15
|
+
raw = JSON.parse(fs.readFileSync(path.join(agentDir, 'directory', 'contacts.json'), 'utf8'));
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
return { error: error instanceof Error && 'code' in error && error.code === 'ENOENT' ? 'contacts_snapshot_missing' : 'contacts_snapshot_unreadable' };
|
|
19
|
+
}
|
|
20
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
21
|
+
return { error: 'contacts_snapshot_invalid' };
|
|
22
|
+
const record = raw;
|
|
23
|
+
const entries = [];
|
|
24
|
+
if (Array.isArray(record.entries)) {
|
|
25
|
+
for (const item of record.entries) {
|
|
26
|
+
if (!item || typeof item !== 'object' || Array.isArray(item))
|
|
27
|
+
continue;
|
|
28
|
+
const value = item;
|
|
29
|
+
const entryAid = aid(value.aid);
|
|
30
|
+
if (!entryAid)
|
|
31
|
+
continue;
|
|
32
|
+
const scopeRaw = value.agent_scope;
|
|
33
|
+
const agentScope = scopeRaw && typeof scopeRaw === 'object' && !Array.isArray(scopeRaw)
|
|
34
|
+
? { mode: scopeRaw.mode, agentAids: scopeRaw.agent_aids }
|
|
35
|
+
: undefined;
|
|
36
|
+
entries.push({ aid: entryAid, ...(agentScope ? { agentScope } : {}) });
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const blocked = new Set();
|
|
40
|
+
const blockedRaw = record.blocked_aids ?? record.blockedAids;
|
|
41
|
+
if (Array.isArray(blockedRaw)) {
|
|
42
|
+
for (const item of blockedRaw) {
|
|
43
|
+
const blockedAid = typeof item === 'string'
|
|
44
|
+
? aid(item)
|
|
45
|
+
: item && typeof item === 'object' && !Array.isArray(item) ? aid(item.target_id) : undefined;
|
|
46
|
+
if (blockedAid)
|
|
47
|
+
blocked.add(blockedAid);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const owner = identityAid(record.owner);
|
|
51
|
+
const personalAssistant = identityAid(record.personal_assistant);
|
|
52
|
+
if (!owner && entries.length === 0 && !personalAssistant)
|
|
53
|
+
return { error: 'contacts_snapshot_empty' };
|
|
54
|
+
return { owner, personalAssistant, entries, blocked };
|
|
55
|
+
}
|
|
56
|
+
function admittedAids(snapshot, selfAid) {
|
|
57
|
+
const result = new Set();
|
|
58
|
+
for (const candidate of [selfAid, snapshot.owner, snapshot.personalAssistant]) {
|
|
59
|
+
// The current contact admission treats the local Agent and the resolved
|
|
60
|
+
// Owner identity as always reachable; event deny rules can still narrow them.
|
|
61
|
+
if (candidate)
|
|
62
|
+
result.add(candidate);
|
|
63
|
+
}
|
|
64
|
+
for (const entry of snapshot.entries) {
|
|
65
|
+
if (snapshot.blocked.has(entry.aid))
|
|
66
|
+
continue;
|
|
67
|
+
if (entry.agentScope?.mode === 'selected') {
|
|
68
|
+
const selected = Array.isArray(entry.agentScope.agentAids) ? entry.agentScope.agentAids : [];
|
|
69
|
+
if (!selected.includes(selfAid))
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
result.add(entry.aid);
|
|
73
|
+
}
|
|
74
|
+
return [...result].sort();
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Materialize the SDK allowlist from the current contacts snapshot. Empty
|
|
78
|
+
* event allow rules mean the contact admission set; a non-empty rule narrows
|
|
79
|
+
* that set. Deny always wins. Temporary grants and other authorization stores
|
|
80
|
+
* are deliberately not consulted here.
|
|
81
|
+
*/
|
|
82
|
+
export function materializeAllowlist(config, agentDir, selfAid, registeredEvents) {
|
|
83
|
+
const snapshot = readContactSnapshot(agentDir, selfAid);
|
|
84
|
+
if ('error' in snapshot) {
|
|
85
|
+
return { allowlist: explicitAllowlist(config), degraded: true, admittedAids: [], reason: snapshot.error };
|
|
86
|
+
}
|
|
87
|
+
const base = new Set(admittedAids(snapshot, selfAid));
|
|
88
|
+
const allowlist = {};
|
|
89
|
+
const events = registeredEvents === undefined
|
|
90
|
+
? Object.keys(config.allowlist)
|
|
91
|
+
: [...new Set(registeredEvents)];
|
|
92
|
+
for (const event of events) {
|
|
93
|
+
const entry = config.allowlist[event] ?? {
|
|
94
|
+
allow: { publish: [], subscribe: [] },
|
|
95
|
+
deny: { publish: [], subscribe: [] },
|
|
96
|
+
};
|
|
97
|
+
const publishAllow = entry.allow.publish.length > 0 ? entry.allow.publish : [...base];
|
|
98
|
+
const subscribeAllow = entry.allow.subscribe.length > 0 ? entry.allow.subscribe : [...base];
|
|
99
|
+
const publish = publishAllow.filter(candidate => base.has(candidate) && !entry.deny.publish.includes(candidate));
|
|
100
|
+
const subscribe = subscribeAllow.filter(candidate => base.has(candidate) && !entry.deny.subscribe.includes(candidate));
|
|
101
|
+
allowlist[event] = { publish_aids: [...new Set(publish)].sort(), subscribe_aids: [...new Set(subscribe)].sort() };
|
|
102
|
+
}
|
|
103
|
+
return { allowlist, degraded: false, admittedAids: [...base] };
|
|
104
|
+
}
|
|
105
|
+
function explicitAllowlist(config) {
|
|
106
|
+
const result = {};
|
|
107
|
+
for (const [event, entry] of Object.entries(config.allowlist)) {
|
|
108
|
+
result[event] = {
|
|
109
|
+
publish_aids: entry.allow.publish.filter(aid => !entry.deny.publish.includes(aid)),
|
|
110
|
+
subscribe_aids: entry.allow.subscribe.filter(aid => !entry.deny.subscribe.includes(aid)),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
return result;
|
|
114
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
const facadeGates = new WeakMap();
|
|
2
|
+
const coreGates = new WeakMap();
|
|
3
|
+
/** Wrap the SDK's remote request handler when its runtime service map is available. */
|
|
4
|
+
export function installEventBusRequestGate(facadeValue, busAid, gate) {
|
|
5
|
+
if (!facadeValue || typeof facadeValue !== 'object')
|
|
6
|
+
return false;
|
|
7
|
+
const facade = facadeValue;
|
|
8
|
+
if (typeof facade.start !== 'function' || !(facade.buses instanceof Map))
|
|
9
|
+
return false;
|
|
10
|
+
let state = facadeGates.get(facade);
|
|
11
|
+
if (!state) {
|
|
12
|
+
const originalStart = facade.start;
|
|
13
|
+
state = { originalStart, gates: new Map() };
|
|
14
|
+
facadeGates.set(facade, state);
|
|
15
|
+
facade.start = function (...args) {
|
|
16
|
+
const started = state.originalStart.apply(this, args);
|
|
17
|
+
const aid = typeof args[0] === 'string' ? args[0] : '';
|
|
18
|
+
const nextGate = state.gates.get(aid);
|
|
19
|
+
if (aid && nextGate)
|
|
20
|
+
installCoreGate(this.buses?.get(aid)?.service, nextGate);
|
|
21
|
+
return started;
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
state.gates.set(busAid, gate);
|
|
25
|
+
return installCoreGate(facade.buses.get(busAid)?.service, gate);
|
|
26
|
+
}
|
|
27
|
+
function installCoreGate(service, gate) {
|
|
28
|
+
if (!service || typeof service.handle !== 'function')
|
|
29
|
+
return false;
|
|
30
|
+
const existing = coreGates.get(service);
|
|
31
|
+
if (existing) {
|
|
32
|
+
existing.gate = gate;
|
|
33
|
+
return true;
|
|
34
|
+
}
|
|
35
|
+
const originalHandle = service.handle;
|
|
36
|
+
const state = { originalHandle, gate };
|
|
37
|
+
coreGates.set(service, state);
|
|
38
|
+
service.handle = async function (senderAid, request, ...rest) {
|
|
39
|
+
await state.gate(senderAid, request, this);
|
|
40
|
+
return state.originalHandle.call(this, senderAid, request, ...rest);
|
|
41
|
+
};
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
44
|
+
export function evaluateEventBusRequest(senderAid, request, materialized, service) {
|
|
45
|
+
const operation = typeof request.op === 'string' ? request.op : 'unknown';
|
|
46
|
+
const deny = (reason, event, action) => ({
|
|
47
|
+
allowed: false, operation, reason, ...(event ? { event } : {}), ...(action ? { action } : {}),
|
|
48
|
+
});
|
|
49
|
+
const admitted = new Set(materialized.admittedAids);
|
|
50
|
+
if (operation === 'unsubscribe')
|
|
51
|
+
return { allowed: true, operation };
|
|
52
|
+
if (operation === 'catalog' || operation === 'stats') {
|
|
53
|
+
return admitted.has(senderAid) ? { allowed: true, operation } : deny('contact_admission');
|
|
54
|
+
}
|
|
55
|
+
if (operation === 'publish') {
|
|
56
|
+
const event = typeof request.event_name === 'string' ? request.event_name : undefined;
|
|
57
|
+
if (!event)
|
|
58
|
+
return { allowed: true, operation };
|
|
59
|
+
return isAllowed(materialized, event, 'publish', senderAid)
|
|
60
|
+
? { allowed: true, operation, action: 'publish', event }
|
|
61
|
+
: deny('event_rule', event, 'publish');
|
|
62
|
+
}
|
|
63
|
+
if (operation === 'authorize') {
|
|
64
|
+
if (request.auth_mode !== undefined && request.auth_mode !== 'allowlist')
|
|
65
|
+
return deny('unsupported_auth_mode');
|
|
66
|
+
const scope = requestScope(request);
|
|
67
|
+
if (!scope)
|
|
68
|
+
return { allowed: true, operation };
|
|
69
|
+
for (const item of scope) {
|
|
70
|
+
if (!isAllowed(materialized, item.event, item.action, senderAid))
|
|
71
|
+
return deny('event_rule', item.event, item.action);
|
|
72
|
+
}
|
|
73
|
+
return { allowed: true, operation };
|
|
74
|
+
}
|
|
75
|
+
if (operation === 'subscribe') {
|
|
76
|
+
const events = stringList(request.events);
|
|
77
|
+
if (!events)
|
|
78
|
+
return { allowed: true, operation };
|
|
79
|
+
for (const event of events) {
|
|
80
|
+
if (!isAllowed(materialized, event, 'subscribe', senderAid))
|
|
81
|
+
return deny('event_rule', event, 'subscribe');
|
|
82
|
+
}
|
|
83
|
+
return { allowed: true, operation };
|
|
84
|
+
}
|
|
85
|
+
if (operation === 'renew') {
|
|
86
|
+
const leaseId = typeof request.lease_id === 'string' ? request.lease_id : '';
|
|
87
|
+
const leases = service?.leases;
|
|
88
|
+
const lease = leaseId ? leases?.get(leaseId) : undefined;
|
|
89
|
+
if (!admitted.has(senderAid))
|
|
90
|
+
return deny('contact_admission');
|
|
91
|
+
if (!lease?.scope)
|
|
92
|
+
return { allowed: true, operation };
|
|
93
|
+
if (lease.aid !== senderAid || lease.auth_mode === 'credential')
|
|
94
|
+
return deny('lease_scope');
|
|
95
|
+
for (const item of lease.scope) {
|
|
96
|
+
if ((item.action !== 'publish' && item.action !== 'subscribe')
|
|
97
|
+
|| typeof item.event_name !== 'string'
|
|
98
|
+
|| !isAllowed(materialized, item.event_name, item.action, senderAid)) {
|
|
99
|
+
return deny('event_rule', item.event_name, item.action === 'publish' || item.action === 'subscribe' ? item.action : undefined);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return { allowed: true, operation };
|
|
103
|
+
}
|
|
104
|
+
return deny('unsupported_operation');
|
|
105
|
+
}
|
|
106
|
+
function isAllowed(materialized, event, action, aid) {
|
|
107
|
+
const entry = materialized.allowlist[event];
|
|
108
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry))
|
|
109
|
+
return false;
|
|
110
|
+
const list = entry[action === 'publish' ? 'publish_aids' : 'subscribe_aids'];
|
|
111
|
+
return Array.isArray(list) && list.includes(aid);
|
|
112
|
+
}
|
|
113
|
+
function stringList(value) {
|
|
114
|
+
if (!Array.isArray(value) || value.some(item => typeof item !== 'string'))
|
|
115
|
+
return undefined;
|
|
116
|
+
return value;
|
|
117
|
+
}
|
|
118
|
+
function requestScope(request) {
|
|
119
|
+
if (Array.isArray(request.scope)) {
|
|
120
|
+
const scope = [];
|
|
121
|
+
for (const value of request.scope) {
|
|
122
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
123
|
+
return undefined;
|
|
124
|
+
const item = value;
|
|
125
|
+
if (typeof item.event_name !== 'string' || (item.action !== 'publish' && item.action !== 'subscribe'))
|
|
126
|
+
return undefined;
|
|
127
|
+
scope.push({ event: item.event_name, action: item.action });
|
|
128
|
+
}
|
|
129
|
+
return scope.length ? scope : undefined;
|
|
130
|
+
}
|
|
131
|
+
const events = stringList(request.events);
|
|
132
|
+
const actions = stringList(request.actions);
|
|
133
|
+
if (!events || !actions || actions.some(action => action !== 'publish' && action !== 'subscribe'))
|
|
134
|
+
return undefined;
|
|
135
|
+
return events.flatMap(event => actions.map(action => ({ event, action: action })));
|
|
136
|
+
}
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 单个 agent 的事件中心 Bus 宿主:专用 slot client + fastaun EventService。
|
|
3
|
+
* 移植自旧 src/aun/event-bus/bus-host.ts(配置源改为事件包合并目录 + center.json 白名单):
|
|
4
|
+
* - apply(config):写路径(center.json 变更/白名单变更),成功 ⇒ running;失败抛错且配置不变。
|
|
5
|
+
* - ensureRunning(config):生命周期入口,失败转后台自愈(指数退避,DEVICE_CONFLICT 固定间隔)。
|
|
6
|
+
* - SDK 失租后 binding 自行关闭且门面不感知,用定时探测兜底。
|
|
7
|
+
*/
|
|
8
|
+
import { logger } from '../utils/logger.js';
|
|
9
|
+
import { EVENT_CENTER_BUS_SLOT, EventCenterError, errorCode, errorMessage, } from './types.js';
|
|
10
|
+
import { installEventBusRequestGate } from './bus-gate.js';
|
|
11
|
+
function withTimeout(promise, ms, code) {
|
|
12
|
+
let timer;
|
|
13
|
+
return Promise.race([
|
|
14
|
+
promise,
|
|
15
|
+
new Promise((_, reject) => {
|
|
16
|
+
timer = setTimeout(() => reject(new EventCenterError(code, `timed out after ${ms}ms`)), ms);
|
|
17
|
+
timer.unref?.();
|
|
18
|
+
}),
|
|
19
|
+
]).finally(() => { if (timer)
|
|
20
|
+
clearTimeout(timer); });
|
|
21
|
+
}
|
|
22
|
+
export class BusHost {
|
|
23
|
+
options;
|
|
24
|
+
handle;
|
|
25
|
+
statusValue = 'stopped';
|
|
26
|
+
detail = null;
|
|
27
|
+
config;
|
|
28
|
+
probeTimer;
|
|
29
|
+
retryTimer;
|
|
30
|
+
retryDelay = 0;
|
|
31
|
+
generation = 0;
|
|
32
|
+
op = Promise.resolve();
|
|
33
|
+
closed = false;
|
|
34
|
+
gateInstalledValue = false;
|
|
35
|
+
constructor(options) {
|
|
36
|
+
this.options = options;
|
|
37
|
+
}
|
|
38
|
+
get status() { return this.statusValue; }
|
|
39
|
+
get statusDetail() { return this.detail; }
|
|
40
|
+
get gateInstalled() { return this.gateInstalledValue; }
|
|
41
|
+
/** Retry capability detection without restarting the Bus. */
|
|
42
|
+
refreshGate() {
|
|
43
|
+
if (!this.options.requestGate || !this.handle)
|
|
44
|
+
return false;
|
|
45
|
+
this.gateInstalledValue = installEventBusRequestGate(this.handle.client.EventService, this.options.aid, this.options.requestGate);
|
|
46
|
+
return this.gateInstalledValue;
|
|
47
|
+
}
|
|
48
|
+
/** 串行化所有生命周期操作。 */
|
|
49
|
+
serial(action) {
|
|
50
|
+
const next = this.op.then(action, action);
|
|
51
|
+
this.op = next.catch(() => { });
|
|
52
|
+
return next;
|
|
53
|
+
}
|
|
54
|
+
setStatus(status, detail = null) {
|
|
55
|
+
if (this.statusValue !== status || this.detail !== detail) {
|
|
56
|
+
logger.info(`[EventCenter] ${this.options.aid} bus ${this.statusValue} → ${status}${detail ? ` (${detail})` : ''}`);
|
|
57
|
+
}
|
|
58
|
+
this.statusValue = status;
|
|
59
|
+
this.detail = detail;
|
|
60
|
+
}
|
|
61
|
+
/** 写路径:同步生效或失败(失败不改变当前运行配置)。 */
|
|
62
|
+
apply(config) {
|
|
63
|
+
return this.serial(async () => {
|
|
64
|
+
if (this.closed)
|
|
65
|
+
throw new EventCenterError('BUS_UNAVAILABLE', 'event center bus host is closed');
|
|
66
|
+
if (!config || Object.keys(config.catalog).length === 0) {
|
|
67
|
+
await this.stopInner();
|
|
68
|
+
this.config = undefined;
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
if (this.statusValue === 'running' && this.handle) {
|
|
72
|
+
await this.handle.client.EventService.updateConfig(this.options.aid, config);
|
|
73
|
+
this.config = config;
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
// 未运行(stopped / 自愈中):同步启动一次,成功后接管。
|
|
77
|
+
this.clearRetry();
|
|
78
|
+
await this.startInner(config, true);
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
/** 生命周期入口:失败转后台自愈。 */
|
|
82
|
+
ensureRunning(config) {
|
|
83
|
+
return this.serial(async () => {
|
|
84
|
+
// close() 置 closed 是为了让调用方显式停用;但 EventRuntime.close() 之后
|
|
85
|
+
// 同一个 BusHost 实例会被 reload 复用(registry.reload = remove + ensureStarted)。
|
|
86
|
+
// 不在这里复位,reload 后 Bus 永远起不来,且重试链被 closed 短路,
|
|
87
|
+
// 表现为 publish/subscribe 都在、Bus 却停在 stopped/conflict。
|
|
88
|
+
if (this.closed) {
|
|
89
|
+
this.closed = false;
|
|
90
|
+
this.generation++;
|
|
91
|
+
}
|
|
92
|
+
this.config = config;
|
|
93
|
+
if (this.statusValue === 'running')
|
|
94
|
+
return;
|
|
95
|
+
try {
|
|
96
|
+
await this.startInner(config, false);
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
this.scheduleRetry(error);
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
async stats(params = {}) {
|
|
104
|
+
if (this.statusValue !== 'running' || !this.handle)
|
|
105
|
+
return null;
|
|
106
|
+
return await this.handle.client.EventService.stats(this.options.aid, params);
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* The SDK currently exposes subscriber counts through stats but not the AID
|
|
110
|
+
* list. Read the in-process service snapshot when the SDK facade exposes it;
|
|
111
|
+
* callers must handle unavailable as a normal capability result.
|
|
112
|
+
*/
|
|
113
|
+
subscribers() {
|
|
114
|
+
if (this.statusValue !== 'running' || !this.handle)
|
|
115
|
+
return { available: false, subscribers: [], reason: 'bus_not_running' };
|
|
116
|
+
const facade = this.handle.client.EventService;
|
|
117
|
+
const service = facade.buses?.get?.(this.options.aid)?.service;
|
|
118
|
+
if (!service?.subscriptions)
|
|
119
|
+
return { available: false, subscribers: [], reason: 'sdk_subscriber_details_unavailable' };
|
|
120
|
+
try {
|
|
121
|
+
service.pruneSubscriptions?.();
|
|
122
|
+
}
|
|
123
|
+
catch { /* stats remains usable if pruning is private/unavailable */ }
|
|
124
|
+
const subscribers = [];
|
|
125
|
+
for (const sub of service.subscriptions.values()) {
|
|
126
|
+
const aid = typeof sub.aid === 'string' ? sub.aid : '';
|
|
127
|
+
const event = typeof sub.event === 'string' ? sub.event : '';
|
|
128
|
+
if (!aid || !event)
|
|
129
|
+
continue;
|
|
130
|
+
const lease = typeof sub.leaseId === 'string' ? service.leases?.get(sub.leaseId) : undefined;
|
|
131
|
+
const expiresAt = typeof lease?.expires_at === 'number' ? lease.expires_at : undefined;
|
|
132
|
+
subscribers.push({ aid, event, ...(typeof sub.leaseId === 'string' ? { leaseId: sub.leaseId } : {}), ...(expiresAt !== undefined ? { expiresAt } : {}), active: expiresAt === undefined || expiresAt > Date.now() });
|
|
133
|
+
}
|
|
134
|
+
subscribers.sort((a, b) => a.event.localeCompare(b.event) || a.aid.localeCompare(b.aid));
|
|
135
|
+
return { available: true, subscribers };
|
|
136
|
+
}
|
|
137
|
+
stop() {
|
|
138
|
+
return this.serial(async () => {
|
|
139
|
+
await this.stopInner();
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
async close() {
|
|
143
|
+
this.closed = true;
|
|
144
|
+
await this.stop();
|
|
145
|
+
}
|
|
146
|
+
async startInner(config, strict) {
|
|
147
|
+
const generation = ++this.generation;
|
|
148
|
+
const previousStatus = this.statusValue;
|
|
149
|
+
const previousDetail = this.detail;
|
|
150
|
+
this.setStatus('starting');
|
|
151
|
+
const aid = this.options.aid;
|
|
152
|
+
try {
|
|
153
|
+
await withTimeout((async () => {
|
|
154
|
+
if (!this.handle)
|
|
155
|
+
this.handle = await this.options.createClient(aid, EVENT_CENTER_BUS_SLOT);
|
|
156
|
+
const service = this.handle.client.EventService;
|
|
157
|
+
// 配置唯一真源是包目录+center.json;SDK state.load 会覆盖 start 参数,因此 load 返回同一份配置。
|
|
158
|
+
const current = this.config ?? config;
|
|
159
|
+
this.refreshGate();
|
|
160
|
+
await service.start(aid, {
|
|
161
|
+
catalog: current.catalog,
|
|
162
|
+
allowlist: current.allowlist,
|
|
163
|
+
state: {
|
|
164
|
+
load: () => ({ service_aid: aid, catalog: current.catalog, allowlist: current.allowlist, issued_grants: [], paused_cids: [] }),
|
|
165
|
+
save: () => { },
|
|
166
|
+
},
|
|
167
|
+
});
|
|
168
|
+
this.refreshGate();
|
|
169
|
+
await service.updateConfig(aid, config);
|
|
170
|
+
})(), this.options.startTimeoutMs ?? 10_000, 'BUS_UNAVAILABLE');
|
|
171
|
+
}
|
|
172
|
+
catch (error) {
|
|
173
|
+
if (generation === this.generation) {
|
|
174
|
+
await this.releaseClient();
|
|
175
|
+
const code = errorCode(error);
|
|
176
|
+
const conflict = code === 'DEVICE_CONFLICT';
|
|
177
|
+
if (strict) {
|
|
178
|
+
this.setStatus(previousStatus === 'starting' ? 'stopped' : previousStatus, previousDetail);
|
|
179
|
+
if (previousStatus !== 'running' && previousStatus !== 'stopped')
|
|
180
|
+
this.scheduleRetry(error);
|
|
181
|
+
}
|
|
182
|
+
else {
|
|
183
|
+
this.setStatus(conflict ? 'conflict' : 'error', `${code}: ${errorMessage(error)}`);
|
|
184
|
+
}
|
|
185
|
+
throw new EventCenterError(conflict ? 'BUS_CONFLICT' : 'BUS_UNAVAILABLE', conflict ? 'another instance of this agent already hosts the event bus' : `event bus unavailable: ${errorMessage(error)}`, { retryable: !conflict });
|
|
186
|
+
}
|
|
187
|
+
throw error;
|
|
188
|
+
}
|
|
189
|
+
this.config = config;
|
|
190
|
+
this.retryDelay = 0;
|
|
191
|
+
this.setStatus('running');
|
|
192
|
+
this.startProbe();
|
|
193
|
+
}
|
|
194
|
+
async stopInner() {
|
|
195
|
+
this.generation++;
|
|
196
|
+
this.clearRetry();
|
|
197
|
+
this.stopProbe();
|
|
198
|
+
if (this.handle && (this.statusValue === 'running' || this.statusValue === 'lease_lost')) {
|
|
199
|
+
const service = this.handle.client.EventService;
|
|
200
|
+
try {
|
|
201
|
+
await withTimeout(service.drain(this.options.aid), 2_000, 'TIMEOUT');
|
|
202
|
+
}
|
|
203
|
+
catch { }
|
|
204
|
+
try {
|
|
205
|
+
await service.close(this.options.aid);
|
|
206
|
+
}
|
|
207
|
+
catch { }
|
|
208
|
+
}
|
|
209
|
+
await this.releaseClient();
|
|
210
|
+
this.setStatus('stopped');
|
|
211
|
+
}
|
|
212
|
+
async releaseClient() {
|
|
213
|
+
const handle = this.handle;
|
|
214
|
+
this.handle = undefined;
|
|
215
|
+
this.gateInstalledValue = false;
|
|
216
|
+
if (handle) {
|
|
217
|
+
try {
|
|
218
|
+
await handle.close();
|
|
219
|
+
}
|
|
220
|
+
catch (error) {
|
|
221
|
+
logger.warn(`[EventCenter] ${this.options.aid} bus client close failed: ${errorMessage(error)}`);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
/** binding 是否仍持有实例租约。优先读 SDK 内部状态,读不到时用 stats 探测。 */
|
|
226
|
+
async leaseAlive() {
|
|
227
|
+
const service = this.handle?.client.EventService;
|
|
228
|
+
const running = service?.buses?.get?.(this.options.aid)?.binding?.running;
|
|
229
|
+
if (typeof running === 'boolean')
|
|
230
|
+
return running;
|
|
231
|
+
try {
|
|
232
|
+
await this.handle.client.EventService.stats(this.options.aid, {});
|
|
233
|
+
return true;
|
|
234
|
+
}
|
|
235
|
+
catch {
|
|
236
|
+
return false;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
startProbe() {
|
|
240
|
+
this.stopProbe();
|
|
241
|
+
const generation = this.generation;
|
|
242
|
+
this.probeTimer = setInterval(() => {
|
|
243
|
+
void this.serial(async () => {
|
|
244
|
+
if (generation !== this.generation || this.statusValue !== 'running' || !this.handle)
|
|
245
|
+
return;
|
|
246
|
+
if (await this.leaseAlive())
|
|
247
|
+
return;
|
|
248
|
+
this.stopProbe();
|
|
249
|
+
this.setStatus('lease_lost', 'SERVICE_LEASE_LOST');
|
|
250
|
+
this.scheduleRetry(new EventCenterError('SERVICE_LEASE_LOST', 'event bus lease lost'));
|
|
251
|
+
});
|
|
252
|
+
}, this.options.probeIntervalMs ?? 15_000);
|
|
253
|
+
this.probeTimer.unref?.();
|
|
254
|
+
}
|
|
255
|
+
stopProbe() {
|
|
256
|
+
if (this.probeTimer)
|
|
257
|
+
clearInterval(this.probeTimer);
|
|
258
|
+
this.probeTimer = undefined;
|
|
259
|
+
}
|
|
260
|
+
clearRetry() {
|
|
261
|
+
if (this.retryTimer)
|
|
262
|
+
clearTimeout(this.retryTimer);
|
|
263
|
+
this.retryTimer = undefined;
|
|
264
|
+
}
|
|
265
|
+
scheduleRetry(error) {
|
|
266
|
+
if (this.closed || !this.config)
|
|
267
|
+
return;
|
|
268
|
+
this.clearRetry();
|
|
269
|
+
const conflict = errorCode(error) === 'DEVICE_CONFLICT' || (error instanceof EventCenterError && error.code === 'BUS_CONFLICT');
|
|
270
|
+
const max = this.options.maxBackoffMs ?? 60_000;
|
|
271
|
+
this.retryDelay = conflict
|
|
272
|
+
? (this.options.conflictRetryMs ?? 60_000)
|
|
273
|
+
: Math.min(max, this.retryDelay ? this.retryDelay * 2 : 1_000);
|
|
274
|
+
const generation = this.generation;
|
|
275
|
+
this.retryTimer = setTimeout(() => {
|
|
276
|
+
this.retryTimer = undefined;
|
|
277
|
+
void this.serial(async () => {
|
|
278
|
+
if (this.closed || generation !== this.generation || this.statusValue === 'running')
|
|
279
|
+
return;
|
|
280
|
+
try {
|
|
281
|
+
await this.startInner(this.config, false);
|
|
282
|
+
}
|
|
283
|
+
catch (retryError) {
|
|
284
|
+
this.scheduleRetry(retryError);
|
|
285
|
+
}
|
|
286
|
+
});
|
|
287
|
+
}, this.retryDelay);
|
|
288
|
+
this.retryTimer.unref?.();
|
|
289
|
+
}
|
|
290
|
+
}
|