@artenx/dshb 0.1.55 → 0.1.57
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/lib/client.js +497 -6
- package/lib/client.js.map +1 -1
- package/lib/core/index.js +9 -2
- package/lib/core/index.js.map +1 -1
- package/lib/core/routes.js +4 -0
- package/lib/core/routes.js.map +1 -1
- package/lib/core/sync/coordinator.js +54 -26
- package/lib/core/sync/coordinator.js.map +1 -1
- package/lib/core/sync/internal-routes.js +36 -5
- package/lib/core/sync/internal-routes.js.map +1 -1
- package/lib/core/sync/node-sync.js +2 -4
- package/lib/core/sync/node-sync.js.map +1 -1
- package/lib/core/sync/offline-archive.js +1 -1
- package/lib/core/sync/offline-routes.js +1 -1
- package/lib/core/sync/remote-helper.js +6 -4
- package/lib/core/sync/remote-helper.js.map +1 -1
- package/lib/core/sync/session-open-routes.js +1 -1
- package/lib/core/sync/session-routes.js +1 -1
- package/lib/core/sync/session-sync.js +1 -1
- package/lib/core/workspace-bindings.js +62 -24
- package/lib/core/workspace-bindings.js.map +1 -1
- package/lib/{session-sync-Bsv3Qnof.js → session-sync-DrilvkP1.js} +16 -3
- package/lib/{session-sync-Bsv3Qnof.js.map → session-sync-DrilvkP1.js.map} +1 -1
- package/package.json +1 -1
|
@@ -3,7 +3,7 @@ import { syncRecordKey } from "./model.js";
|
|
|
3
3
|
import { SyncNodeManifestError } from "./node-sync.js";
|
|
4
4
|
import { SyncPeerNotFoundError } from "./peer-manager.js";
|
|
5
5
|
import { SYNC_SESSION_BUNDLE_OBJECTS_CAPABILITY, SYNC_SESSION_EVENT_TAIL_CAPABILITY, SYNC_SESSION_OBJECT_STREAM_CAPABILITY } from "./protocol.js";
|
|
6
|
-
import { c as planSessionTransfers, f as syncSessionEntryKey, h as validateSyncSessionManifest, m as validateSyncSessionBundle, n as SyncSessionError, o as makeSyncSessionBundle, u as sessionEventListDigest } from "../../session-sync-
|
|
6
|
+
import { c as planSessionTransfers, f as syncSessionEntryKey, h as validateSyncSessionManifest, m as validateSyncSessionBundle, n as SyncSessionError, o as makeSyncSessionBundle, u as sessionEventListDigest } from "../../session-sync-DrilvkP1.js";
|
|
7
7
|
import { SyncHostKeyChallengeError } from "./host-key.js";
|
|
8
8
|
import { SyncSessionDeltaPrefixError, SyncSshProbeError } from "./ssh-transport.js";
|
|
9
9
|
import { n as selectionIncludesNode, r as selectionIncludesSession, t as resolveSyncSelection } from "../../selection-BABQH1Rt.js";
|
|
@@ -134,55 +134,82 @@ function mergeSessionSkipped(...reports) {
|
|
|
134
134
|
* (例如对端正被活跃使用的会话:边抓取边推进,快照必然落后)。剔除的条目
|
|
135
135
|
* 由调用方计入 skippedSessions 并留待下次同步;对端仍在活跃的会话经远端
|
|
136
136
|
* 会话通道(wss)实时展示,不依赖内容同步。
|
|
137
|
+
*
|
|
138
|
+
* 缺失条目还有一类确定性来源:导出端体积超限(session-payload-too-large)
|
|
139
|
+
* 或 cwd 不匹配(workspace-cwd-mismatch)的会话会进 skipped 报告而不是
|
|
140
|
+
* entries。这类条目按「单条跳过」处理(remoteSkipped),保留同批其余条目;
|
|
141
|
+
* 否则一个永远导不出去的会话会把整批会话一起饿死——每次同步都重复发生,
|
|
142
|
+
* 没有自愈路径。
|
|
137
143
|
*/
|
|
138
|
-
function
|
|
144
|
+
function skippedSessionIdsOf(skipped) {
|
|
145
|
+
return new Set(skipped.map((item) => item.sessionId));
|
|
146
|
+
}
|
|
147
|
+
function partitionStaleSessionEntries(expectedEntries, selectedEntries, skippedSessionIds) {
|
|
139
148
|
const expected = new Map(expectedEntries.map((entry) => [syncSessionEntryKey(entry), entry]));
|
|
140
149
|
const selected = new Map(selectedEntries.map((entry) => [syncSessionEntryKey(entry), entry]));
|
|
141
150
|
const retained = [];
|
|
142
151
|
const stale = [];
|
|
143
|
-
|
|
144
|
-
|
|
152
|
+
let remoteSkipped = 0;
|
|
153
|
+
if (selected.size !== selectedEntries.length) {
|
|
154
|
+
for (const key of expected.keys()) stale.push({
|
|
145
155
|
key,
|
|
146
156
|
fields: "entry-missing",
|
|
147
157
|
detail: ""
|
|
148
158
|
});
|
|
149
|
-
for (const key of selected.keys())
|
|
159
|
+
for (const key of selected.keys()) stale.push({
|
|
150
160
|
key,
|
|
151
161
|
fields: "unexpected-entry",
|
|
152
162
|
detail: ""
|
|
153
163
|
});
|
|
154
164
|
return {
|
|
155
165
|
retained: [],
|
|
156
|
-
stale
|
|
166
|
+
stale,
|
|
167
|
+
remoteSkipped
|
|
157
168
|
};
|
|
158
169
|
}
|
|
170
|
+
for (const key of selected.keys()) if (!expected.has(key)) stale.push({
|
|
171
|
+
key,
|
|
172
|
+
fields: "unexpected-entry",
|
|
173
|
+
detail: ""
|
|
174
|
+
});
|
|
175
|
+
if (stale.length > 0) return {
|
|
176
|
+
retained: [],
|
|
177
|
+
stale,
|
|
178
|
+
remoteSkipped
|
|
179
|
+
};
|
|
159
180
|
for (const [key, expectedEntry] of expected) {
|
|
160
181
|
const metadata = expectedEntry.metadata;
|
|
161
182
|
const currentEntry = selected.get(key);
|
|
162
|
-
|
|
163
|
-
|
|
183
|
+
if (!currentEntry) {
|
|
184
|
+
if (skippedSessionIds?.has(String(metadata.localEntityId))) remoteSkipped += 1;
|
|
185
|
+
else stale.push({
|
|
186
|
+
key,
|
|
187
|
+
fields: "entry-missing",
|
|
188
|
+
detail: ""
|
|
189
|
+
});
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
const current = currentEntry.metadata;
|
|
193
|
+
const eventSummary = currentEntry.eventDelta ? {
|
|
164
194
|
eventCount: currentEntry.eventDelta.fullEventCount,
|
|
165
195
|
eventDigest: currentEntry.eventDelta.fullEventDigest,
|
|
166
196
|
inheritedEventCount: currentEntry.inheritedEventCount
|
|
167
|
-
} : currentEntry
|
|
197
|
+
} : currentEntry.events ? {
|
|
168
198
|
eventCount: currentEntry.events.length,
|
|
169
199
|
eventDigest: sessionEventListDigest(currentEntry.events),
|
|
170
200
|
inheritedEventCount: currentEntry.inheritedEventCount
|
|
171
201
|
} : void 0;
|
|
172
202
|
const hasExpectedEventSummary = expectedEntry.eventCount !== void 0 || expectedEntry.eventDigest !== void 0 || expectedEntry.inheritedEventCount !== void 0;
|
|
173
203
|
const expectedWorkspace = metadata.workspaceOrigin;
|
|
174
|
-
const currentWorkspace = current
|
|
204
|
+
const currentWorkspace = current.workspaceOrigin;
|
|
175
205
|
const mismatches = [];
|
|
176
|
-
if (
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
if (expectedWorkspace?.originInstanceId !== currentWorkspace?.originInstanceId || expectedWorkspace?.originEntityId !== currentWorkspace?.originEntityId) mismatches.push("workspaceOrigin");
|
|
184
|
-
if (hasExpectedEventSummary && (!eventSummary || eventSummary.eventCount !== expectedEntry.eventCount || eventSummary.eventDigest !== expectedEntry.eventDigest || eventSummary.inheritedEventCount !== expectedEntry.inheritedEventCount)) mismatches.push("eventSummary");
|
|
185
|
-
}
|
|
206
|
+
if (current.localEntityId !== metadata.localEntityId) mismatches.push("localEntityId");
|
|
207
|
+
if (compareSyncRevision(current.revision, metadata.revision) !== 0) mismatches.push("revision");
|
|
208
|
+
if (current.contentDigest !== metadata.contentDigest) mismatches.push("contentDigest");
|
|
209
|
+
if (current.stateDigest !== metadata.stateDigest) mismatches.push("stateDigest");
|
|
210
|
+
if (Boolean(current.deleted) !== Boolean(metadata.deleted)) mismatches.push("deleted");
|
|
211
|
+
if (expectedWorkspace?.originInstanceId !== currentWorkspace?.originInstanceId || expectedWorkspace?.originEntityId !== currentWorkspace?.originEntityId) mismatches.push("workspaceOrigin");
|
|
212
|
+
if (hasExpectedEventSummary && (!eventSummary || eventSummary.eventCount !== expectedEntry.eventCount || eventSummary.eventDigest !== expectedEntry.eventDigest || eventSummary.inheritedEventCount !== expectedEntry.inheritedEventCount)) mismatches.push("eventSummary");
|
|
186
213
|
if (mismatches.length > 0) {
|
|
187
214
|
const detail = current && hasExpectedEventSummary ? ` expected(eventCount=${expectedEntry.eventCount}, inherited=${expectedEntry.inheritedEventCount}, digest=${expectedEntry.eventDigest}) actual(${eventSummary ? `eventCount=${eventSummary.eventCount}, inherited=${eventSummary.inheritedEventCount}, digest=${eventSummary.eventDigest}` : "no-events"})` : "";
|
|
188
215
|
stale.push({
|
|
@@ -192,11 +219,12 @@ function partitionStaleSessionEntries(expectedEntries, selectedEntries) {
|
|
|
192
219
|
});
|
|
193
220
|
continue;
|
|
194
221
|
}
|
|
195
|
-
|
|
222
|
+
retained.push(currentEntry);
|
|
196
223
|
}
|
|
197
224
|
return {
|
|
198
225
|
retained,
|
|
199
|
-
stale
|
|
226
|
+
stale,
|
|
227
|
+
remoteSkipped
|
|
200
228
|
};
|
|
201
229
|
}
|
|
202
230
|
function sessionEventPrefixesFor(selectedEntries, receiverEntries) {
|
|
@@ -366,7 +394,7 @@ var SyncCoordinator = class {
|
|
|
366
394
|
let fetched = validateSyncSessionBundle(await this.retryTransport(signal, () => this.transport.fetchSessionEntries(peer.id, chunkKeys, remoteManifest.digest, prefixes, useObjectStream)));
|
|
367
395
|
this.throwIfStopped(signal);
|
|
368
396
|
if (fetched.instanceId !== remoteManifest.instanceId) throw new SyncCoordinatorError("protocol-invalid", "远端会话内容与 manifest 实例不一致");
|
|
369
|
-
const pullPartition = partitionStaleSessionEntries(chunkManifest, fetched.entries);
|
|
397
|
+
const pullPartition = partitionStaleSessionEntries(chunkManifest, fetched.entries, skippedSessionIdsOf(fetched.skipped));
|
|
370
398
|
staleSessionCount += pullPartition.stale.length;
|
|
371
399
|
remoteSkippedReports.push(fetched.skipped);
|
|
372
400
|
if (pullPartition.stale.length > 0) fetched = {
|
|
@@ -387,7 +415,7 @@ var SyncCoordinator = class {
|
|
|
387
415
|
if (!(error instanceof SyncSessionError && error.code === "session-delta-prefix")) throw error;
|
|
388
416
|
const fullRemoteEntries = validateSyncSessionBundle(await this.retryTransport(signal, () => this.transport.fetchSessionEntries(peer.id, chunkKeys, remoteManifest.digest, void 0, false)));
|
|
389
417
|
if (fullRemoteEntries.instanceId !== remoteManifest.instanceId) throw new SyncCoordinatorError("protocol-invalid", "远端会话内容与 manifest 实例不一致");
|
|
390
|
-
const pullRetryPartition = partitionStaleSessionEntries(chunkManifest, fullRemoteEntries.entries);
|
|
418
|
+
const pullRetryPartition = partitionStaleSessionEntries(chunkManifest, fullRemoteEntries.entries, skippedSessionIdsOf(fullRemoteEntries.skipped));
|
|
391
419
|
staleSessionCount += pullRetryPartition.stale.length;
|
|
392
420
|
remoteSkippedReports.push(fullRemoteEntries.skipped);
|
|
393
421
|
fullRemoteEntries.entries = pullRetryPartition.retained;
|
|
@@ -422,7 +450,7 @@ var SyncCoordinator = class {
|
|
|
422
450
|
deferredObjects: useObjectStream
|
|
423
451
|
});
|
|
424
452
|
this.throwIfStopped(signal);
|
|
425
|
-
const pushPartition = partitionStaleSessionEntries(chunkManifest, exported.entries);
|
|
453
|
+
const pushPartition = partitionStaleSessionEntries(chunkManifest, exported.entries, skippedSessionIdsOf(exported.skipped));
|
|
426
454
|
staleSessionCount += pushPartition.stale.length;
|
|
427
455
|
if (pushPartition.stale.length > 0) exported = {
|
|
428
456
|
...exported,
|
|
@@ -443,7 +471,7 @@ var SyncCoordinator = class {
|
|
|
443
471
|
sharedObjects: wireBundle.objects !== void 0,
|
|
444
472
|
deferredObjects: false
|
|
445
473
|
});
|
|
446
|
-
const pushRetryPartition = partitionStaleSessionEntries(chunkManifest, fullLocalEntries.entries);
|
|
474
|
+
const pushRetryPartition = partitionStaleSessionEntries(chunkManifest, fullLocalEntries.entries, skippedSessionIdsOf(fullLocalEntries.skipped));
|
|
447
475
|
staleSessionCount += pushRetryPartition.stale.length;
|
|
448
476
|
fullLocalEntries.entries = pushRetryPartition.retained;
|
|
449
477
|
const skippedReport = firstChunk ? mergeSessionSkipped(localManifest.skipped, fullLocalEntries.skipped) : fullLocalEntries.skipped;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"coordinator.js","names":[],"sources":["../../../src/core/sync/coordinator.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\nimport { SyncNodeManifestError, type SyncNodeApplyResult, type SyncNodeEntry, type SyncNodeService } from './node-sync.js'\nimport { SyncHostKeyChallengeError } from './host-key.js'\nimport { compareSyncRevision } from './revision.js'\nimport { syncRecordKey, type SyncCatalog, type SyncPeer } from './model.js'\nimport { SyncPeerManager, SyncPeerNotFoundError } from './peer-manager.js'\nimport type { SyncStateStore } from './stores.js'\nimport { SyncSessionDeltaPrefixError, SyncSshProbeError, SyncSshTransport } from './ssh-transport.js'\nimport {\n makeSyncSessionBundle,\n planSessionTransfers,\n SyncSessionError,\n SyncSessionService,\n sessionEventListDigest,\n syncSessionEntryKey,\n validateSyncSessionBundle,\n validateSyncSessionManifest,\n} from './session-sync.js'\nimport type {\n SyncSessionApplyResult,\n SyncSessionBundle,\n SyncSessionEntry,\n SyncSessionEventPrefix,\n SyncSessionObject,\n SyncSessionManifest,\n SyncSessionManifestEntry,\n} from './session-sync.js'\nimport { SYNC_CATALOG_CAPABILITY, SYNC_SESSION_BUNDLE_OBJECTS_CAPABILITY, SYNC_SESSION_EVENT_TAIL_CAPABILITY, SYNC_SESSION_MANIFEST_CAPABILITY, SYNC_SESSION_OBJECT_STREAM_CAPABILITY } from './protocol.js'\nimport { resolveSyncSelection, selectionIncludesNode, selectionIncludesSession } from './selection.js'\n\nconst EMPTY_APPLY_RESULT: SyncNodeApplyResult = { created: 0, updated: 0, deleted: 0, pendingRemoval: 0, skipped: 0 }\nconst TRANSPORT_RETRY_DELAY_MS = 250\n// 会话分批交换的目标批体积与单批 key 数上限:目标值 ≈ JSON.parse 后对象图的\n// 堆占用仍远小于宿主堆上限(桌面端约 1.4GB);单批 key 上限限制批内的\n// 条目数,避免 manifest 条目本身过大。\nconst SESSION_CHUNK_TARGET_BYTES = 12 * 1024 * 1024\nconst SESSION_CHUNK_MAX_KEYS = 8\n\nexport interface NodeTransferPlan {\n toLocal: SyncNodeEntry[]\n toRemote: SyncNodeEntry[]\n skipped: number\n}\n\nexport interface SyncRunSummary {\n peerId: string\n direction: SyncPeer['direction']\n startedAt: string\n finishedAt: string\n remoteInstanceId: string\n imported: number\n exported: number\n skipped: number\n pendingRemoval: number\n importedSessions: number\n exportedSessions: number\n skippedSessions: number\n}\n\nexport class SyncCoordinatorError extends Error {\n constructor(readonly code: string, message: string) {\n super(message)\n this.name = 'SyncCoordinatorError'\n }\n}\n\nfunction addCount(result: SyncNodeApplyResult): number {\n return result.created + result.updated + result.deleted\n}\n\nfunction manifestDigest(entries: readonly SyncNodeEntry[]): string {\n const versions = entries\n .map((entry) => ({\n key: syncRecordKey('node', entry.metadata),\n revision: entry.metadata.revision,\n contentDigest: entry.metadata.contentDigest,\n deleted: Boolean(entry.metadata.deleted),\n }))\n .sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0)\n return `sha256:${createHash('sha256').update(JSON.stringify(versions)).digest('hex')}`\n}\n\nexport function planNodeTransfers(\n direction: SyncPeer['direction'],\n localEntries: readonly SyncNodeEntry[],\n remoteEntries: readonly SyncNodeEntry[],\n): NodeTransferPlan {\n const toLocal: SyncNodeEntry[] = []\n const toRemote: SyncNodeEntry[] = []\n if (direction === 'pull') return { toLocal: [...remoteEntries], toRemote, skipped: 0 }\n\n const localByKey = new Map(localEntries.map((entry) => [syncRecordKey('node', entry.metadata), entry]))\n const remoteByKey = new Map(remoteEntries.map((entry) => [syncRecordKey('node', entry.metadata), entry]))\n const keys = new Set([...localByKey.keys(), ...remoteByKey.keys()])\n let skipped = 0\n\n for (const key of keys) {\n const local = localByKey.get(key)\n const remote = remoteByKey.get(key)\n if (!local) {\n toLocal.push(remote!)\n continue\n }\n if (!remote) {\n toRemote.push(local)\n continue\n }\n\n const comparison = compareSyncRevision(local.metadata.revision, remote.metadata.revision)\n if (comparison > 0) {\n toRemote.push(local)\n } else if (comparison < 0) {\n toLocal.push(remote)\n } else if (\n local.metadata.contentDigest === remote.metadata.contentDigest &&\n Boolean(local.metadata.deleted) === Boolean(remote.metadata.deleted)\n ) {\n skipped += 1\n } else {\n throw new SyncCoordinatorError('revision-conflict', 'Equal node revisions contain different content')\n }\n }\n return { toLocal, toRemote, skipped }\n}\n\nfunction mapFailure(error: unknown): SyncCoordinatorError {\n if (error instanceof SyncCoordinatorError) return error\n if (error instanceof SyncPeerNotFoundError) return new SyncCoordinatorError('peer-not-found', '同步节点已不存在')\n if (error instanceof SyncHostKeyChallengeError) {\n const code = error.decision === 'changed' ? 'host-key-changed' : 'host-key-untrusted'\n return new SyncCoordinatorError(code, error.message)\n }\n if (error instanceof SyncSshProbeError) {\n const messages: Record<string, string> = {\n auth: 'SSH 认证失败',\n network: 'SSH 节点不可达',\n timeout: 'SSH 连接超时',\n hostkey: 'SSH 主机密钥校验失败',\n helper: '远端同步 helper 不可用',\n protocol: '同步协议不兼容',\n }\n const baseMsg = messages[error.category] ?? 'SSH 同步失败'\n const detail = (error as Error & { detail?: string }).detail\n return new SyncCoordinatorError(`ssh-${error.category}`, detail ? `${baseMsg}:${detail}` : baseMsg)\n }\n if (error instanceof SyncNodeManifestError) return new SyncCoordinatorError('manifest-invalid', '节点 manifest 校验失败')\n if (error instanceof SyncSessionError) {\n return new SyncCoordinatorError(error.code.startsWith('session-') ? error.code : `session-${error.code}`, error.message)\n }\n return new SyncCoordinatorError('sync-failed', '同步作业失败')\n}\n\nfunction resultCount(result: SyncNodeApplyResult): { applied: number; skipped: number; pendingRemoval: number } {\n return {\n applied: addCount(result),\n skipped: result.skipped,\n pendingRemoval: result.pendingRemoval,\n }\n}\n\nfunction emptySessionResult(): SyncSessionApplyResult {\n return { created: 0, updated: 0, archived: 0, deleted: 0, skipped: 0, unmapped: 0 }\n}\n\nfunction sessionResultCount(result: SyncSessionApplyResult): number {\n return result.created + result.updated + result.deleted\n}\n\nfunction addSessionResults(target: SyncSessionApplyResult, delta: SyncSessionApplyResult): SyncSessionApplyResult {\n return {\n created: target.created + delta.created,\n updated: target.updated + delta.updated,\n archived: target.archived + delta.archived,\n deleted: target.deleted + delta.deleted,\n skipped: target.skipped + delta.skipped,\n unmapped: target.unmapped + delta.unmapped,\n }\n}\n\nfunction mergeSessionSkipped(...reports: Array<readonly { sessionId: string; reason: string }[]>): Array<{ sessionId: string; reason: string }> {\n const merged = new Map<string, { sessionId: string; reason: string }>()\n for (const report of reports) {\n for (const entry of report) merged.set(JSON.stringify([entry.sessionId, entry.reason]), entry)\n }\n return [...merged.values()]\n}\n\n/**\n * 把内容快照与 manifest 清单比对,剔除了「manifest 之后发生变化」的条目\n * (例如对端正被活跃使用的会话:边抓取边推进,快照必然落后)。剔除的条目\n * 由调用方计入 skippedSessions 并留待下次同步;对端仍在活跃的会话经远端\n * 会话通道(wss)实时展示,不依赖内容同步。\n */\nfunction partitionStaleSessionEntries(\n expectedEntries: readonly SyncSessionManifestEntry[],\n selectedEntries: readonly SyncSessionEntry[],\n): { retained: SyncSessionEntry[]; stale: Array<{ key: string; fields: string; detail: string }> } {\n const expected = new Map(expectedEntries.map((entry) => [syncSessionEntryKey(entry), entry]))\n const selected = new Map(selectedEntries.map((entry) => [syncSessionEntryKey(entry), entry]))\n const retained: SyncSessionEntry[] = []\n const stale: Array<{ key: string; fields: string; detail: string }> = []\n if (selected.size !== selectedEntries.length || selected.size !== expected.size) {\n for (const [key, expectedEntry] of expected) {\n if (!selected.has(key)) stale.push({ key, fields: 'entry-missing', detail: '' })\n }\n for (const key of selected.keys()) {\n if (!expected.has(key)) stale.push({ key, fields: 'unexpected-entry', detail: '' })\n }\n return { retained: [], stale }\n }\n for (const [key, expectedEntry] of expected) {\n const metadata = expectedEntry.metadata\n const currentEntry = selected.get(key)\n const current = currentEntry?.metadata\n const eventSummary = currentEntry?.eventDelta\n ? {\n eventCount: currentEntry.eventDelta.fullEventCount,\n eventDigest: currentEntry.eventDelta.fullEventDigest,\n inheritedEventCount: currentEntry.inheritedEventCount,\n }\n : currentEntry?.events\n ? {\n eventCount: currentEntry.events.length,\n eventDigest: sessionEventListDigest(currentEntry.events),\n inheritedEventCount: currentEntry.inheritedEventCount,\n }\n : undefined\n const hasExpectedEventSummary = expectedEntry.eventCount !== undefined || expectedEntry.eventDigest !== undefined ||\n expectedEntry.inheritedEventCount !== undefined\n const expectedWorkspace = metadata.workspaceOrigin\n const currentWorkspace = current?.workspaceOrigin\n const mismatches: string[] = []\n if (!current) mismatches.push('entry-missing')\n else {\n if (current.localEntityId !== metadata.localEntityId) mismatches.push('localEntityId')\n if (compareSyncRevision(current.revision, metadata.revision) !== 0) mismatches.push('revision')\n if (current.contentDigest !== metadata.contentDigest) mismatches.push('contentDigest')\n if (current.stateDigest !== metadata.stateDigest) mismatches.push('stateDigest')\n if (Boolean(current.deleted) !== Boolean(metadata.deleted)) mismatches.push('deleted')\n if (expectedWorkspace?.originInstanceId !== currentWorkspace?.originInstanceId ||\n expectedWorkspace?.originEntityId !== currentWorkspace?.originEntityId) mismatches.push('workspaceOrigin')\n if (hasExpectedEventSummary && (!eventSummary || eventSummary.eventCount !== expectedEntry.eventCount ||\n eventSummary.eventDigest !== expectedEntry.eventDigest || eventSummary.inheritedEventCount !== expectedEntry.inheritedEventCount)) {\n mismatches.push('eventSummary')\n }\n }\n if (mismatches.length > 0) {\n const detail = current && hasExpectedEventSummary\n ? ` expected(eventCount=${expectedEntry.eventCount}, inherited=${expectedEntry.inheritedEventCount}, digest=${expectedEntry.eventDigest})` +\n ` actual(${eventSummary ? `eventCount=${eventSummary.eventCount}, inherited=${eventSummary.inheritedEventCount}, digest=${eventSummary.eventDigest}` : 'no-events'})`\n : ''\n stale.push({ key, fields: mismatches.join(','), detail })\n continue\n }\n if (currentEntry) retained.push(currentEntry)\n }\n return { retained, stale }\n}\n\nfunction sessionEventPrefixesFor(\n selectedEntries: readonly SyncSessionManifestEntry[],\n receiverEntries: readonly SyncSessionManifestEntry[],\n): SyncSessionEventPrefix[] {\n const receiverByKey = new Map(receiverEntries.map((entry) => [syncSessionEntryKey(entry), entry]))\n const prefixes: SyncSessionEventPrefix[] = []\n for (const selected of selectedEntries) {\n if (selected.branchId || selected.metadata.deleted) continue\n const receiver = receiverByKey.get(syncSessionEntryKey(selected))\n if (!receiver || receiver.branchId || receiver.metadata.deleted || receiver.eventCount === undefined ||\n receiver.eventDigest === undefined || receiver.inheritedEventCount === undefined) continue\n prefixes.push({\n key: syncSessionEntryKey(selected),\n eventCount: receiver.eventCount,\n eventDigest: receiver.eventDigest,\n inheritedEventCount: receiver.inheritedEventCount,\n })\n }\n return prefixes\n}\n\nexport class SyncCoordinator {\n private readonly inFlight = new Map<string, { promise: Promise<SyncRunSummary>; controller: AbortController }>()\n\n constructor(\n private readonly peers: SyncPeerManager,\n private readonly state: SyncStateStore,\n private readonly nodes: SyncNodeService,\n private readonly transport: SyncSshTransport,\n private readonly now: () => number = Date.now,\n private readonly sessions?: SyncSessionService,\n ) {}\n\n run(peerId: string): Promise<SyncRunSummary> {\n const active = this.inFlight.get(peerId)\n if (active) return active.promise\n const controller = new AbortController()\n const run = this.execute(peerId, controller.signal)\n this.inFlight.set(peerId, { promise: run, controller })\n void run.then(() => this.clear(peerId, run), () => this.clear(peerId, run))\n return run\n }\n\n /**\n * 手动停止运行中的同步:在最近的安全边界(批次之间)中止。\n * 返回是否确有运行中的作业。中止后丢弃本对端未完成的 journal 批次\n * (未应用条目不落地、重启不回放),水位保持不变,状态记为 stopped。\n */\n stop(peerId: string): boolean {\n const active = this.inFlight.get(peerId)\n if (!active) return false\n active.controller.abort()\n // 立即关闭该对端的活跃 SSH 通道:等待中的 readFrames 随即返回,\n // 不必等空闲超时(沙箱代理冻结场景下可能长达 60s)。\n try {\n this.transport.stopActiveSessions(peerId)\n } catch {}\n return true\n }\n\n /** 是否已手动停止:错误分类与收尾路径共用。 */\n private stopped(error: unknown): boolean {\n return error instanceof SyncCoordinatorError && error.code === 'stopped'\n }\n\n private throwIfStopped(signal: AbortSignal): void {\n if (signal.aborted) throw new SyncCoordinatorError('stopped', '同步已被手动停止')\n }\n\n /** 进度错误消息必须满足校验器限制(≤256、无控制字符),否则收尾写失败会卡住状态。 */\n private progressMessage(text: string): string {\n return text.replace(/[\\u0000-\\u001f\\u007f]/g, ' ').slice(0, 256)\n }\n\n private async execute(peerId: string, signal: AbortSignal): Promise<SyncRunSummary> {\n const peer = await this.peers.get(peerId)\n if (!peer) throw new SyncCoordinatorError('peer-not-found', '同步节点已不存在')\n if (!peer.enabled) throw new SyncCoordinatorError('peer-disabled', '此同步节点已停用')\n if (signal.aborted) throw new SyncCoordinatorError('stopped', '同步已被手动停止')\n\n const startedAt = new Date(this.now()).toISOString()\n this.peers.updateProgress(peer.id, {\n lastRunAt: startedAt,\n lastRunStatus: 'running',\n lastErrorCode: undefined,\n lastErrorMessage: undefined,\n })\n\n try {\n if (peer.syncSessions && peer.mode !== 'metadata' && !this.sessions) {\n throw new SyncCoordinatorError('sessions-unavailable', '会话同步服务不可用')\n }\n const remoteNodeManifest = await this.retryTransport(signal, () => this.transport.fetchNodeManifest(peer.id))\n if (remoteNodeManifest.protocolVersion !== 1 || remoteNodeManifest.instanceId === this.state.instanceId()) {\n throw new SyncCoordinatorError('protocol-invalid', '同步 peer 协议版本或实例身份无效')\n }\n const remoteEntries = this.nodes.validateManifest(remoteNodeManifest.records)\n const localManifest = await this.nodes.exportManifest()\n const localEntries = this.nodes.validateManifest(localManifest.records)\n let catalog: SyncCatalog = {\n protocolVersion: 1,\n instanceId: remoteNodeManifest.instanceId,\n nodes: [],\n workspaces: [],\n sessions: [],\n }\n if (peer.mode === 'metadata' && peer.syncSessions) {\n // 元数据同步:只拉目录(节点/工作区/会话列表),不交换会话内容;\n // 点击同步来的会话时经远端会话通道(wss)实时操作远端 DSH。\n if (!remoteNodeManifest.capabilities?.includes(SYNC_CATALOG_CAPABILITY)) {\n throw new SyncCoordinatorError('metadata-catalog-unavailable', '目标同步节点需要升级以支持元数据同步')\n }\n catalog = await this.retryTransport(signal, () => this.transport.fetchCatalog(peer.id))\n if (catalog.instanceId !== remoteNodeManifest.instanceId) {\n throw new SyncCoordinatorError('protocol-invalid', '节点与目录清单的实例身份不一致')\n }\n } else if (peer.selection?.mode === 'selected' && peer.syncSessions &&\n (peer.selection.workspaces.length > 0 || peer.selection.sessions.length > 0)) {\n if (!remoteNodeManifest.capabilities?.includes(SYNC_CATALOG_CAPABILITY)) {\n throw new SyncCoordinatorError('selection-catalog-unavailable', '目标同步节点需要升级以支持自选范围')\n }\n catalog = await this.retryTransport(signal, () => this.transport.fetchCatalog(peer.id))\n if (catalog.instanceId !== remoteNodeManifest.instanceId) {\n throw new SyncCoordinatorError('protocol-invalid', '节点与目录清单的实例身份不一致')\n }\n }\n const selection = resolveSyncSelection(peer.mode === 'metadata' ? undefined : peer.selection, catalog)\n // 节点配置交换:全量模式恒开(会话导入依赖节点/工作区映射);元数据模式\n // 可由「同步工作节点」关闭——关闭后仅校验对端身份并拉取目录。\n const syncNodes = peer.mode !== 'metadata' || peer.syncNodes !== false\n // 节点配置固定从远端拉取(同步语义简化后方向仅作用于会话内容交换)。\n const fullNodePlan: NodeTransferPlan = syncNodes ? planNodeTransfers('pull', localEntries, remoteEntries) : { toLocal: [], toRemote: [], skipped: 0 }\n const plan = !syncNodes || selection.all ? fullNodePlan : {\n ...fullNodePlan,\n toLocal: fullNodePlan.toLocal.filter((entry) => selectionIncludesNode(entry.metadata, selection)),\n toRemote: fullNodePlan.toRemote.filter((entry) => selectionIncludesNode(entry.metadata, selection)),\n }\n\n const localResult = plan.toLocal.length > 0\n ? await this.nodes.applyManifest(plan.toLocal, peer.name, 'peer')\n : EMPTY_APPLY_RESULT\n const remoteResult = plan.toRemote.length > 0\n ? await this.retryTransport(signal, () => this.transport.applyNodeManifest(peer.id, plan.toRemote, localManifest.instanceId))\n : EMPTY_APPLY_RESULT\n const localCounts = resultCount(localResult)\n const remoteCounts = resultCount(remoteResult)\n let importedSessions = 0\n let exportedSessions = 0\n let skippedSessions = 0\n let staleSessionCount = 0\n let digest = manifestDigest(remoteEntries)\n if (peer.mode === 'metadata' && peer.syncSessions) {\n // 每次同步实时拉取目录并报告计数;会话内容交换整体跳过。\n } else if (peer.syncSessions) {\n const sessionService = this.sessions!\n let plan: ReturnType<typeof planSessionTransfers>\n let remoteSkipped = 0\n let remoteSessionDigest = ''\n let localSessionDigest = ''\n let localInstanceId = ''\n let sessionLocalResult = emptySessionResult()\n let sessionRemoteResult = emptySessionResult()\n if (remoteNodeManifest.capabilities?.includes(SYNC_SESSION_MANIFEST_CAPABILITY)) {\n const remoteManifest = validateSyncSessionManifest(\n await this.retryTransport(signal, () => this.transport.fetchSessionManifest(peer.id)),\n )\n if (remoteManifest.instanceId !== remoteNodeManifest.instanceId) {\n throw new SyncCoordinatorError('protocol-invalid', '节点与会话 manifest 的实例身份不一致')\n }\n const localManifest = await sessionService.exportManifest()\n const fullSessionPlan = planSessionTransfers(peer.direction, localManifest.entries, remoteManifest.entries)\n plan = selection.all ? fullSessionPlan : {\n ...fullSessionPlan,\n toLocal: fullSessionPlan.toLocal.filter((entry) => selectionIncludesSession(entry.metadata, selection)),\n toRemote: fullSessionPlan.toRemote.filter((entry) => selectionIncludesSession(entry.metadata, selection)),\n }\n remoteSessionDigest = remoteManifest.digest\n localSessionDigest = localManifest.digest\n localInstanceId = localManifest.instanceId\n const useEventDeltas = remoteNodeManifest.capabilities.includes(SYNC_SESSION_EVENT_TAIL_CAPABILITY)\n const useSharedObjects = remoteNodeManifest.capabilities.includes(SYNC_SESSION_BUNDLE_OBJECTS_CAPABILITY)\n const useObjectStream = remoteNodeManifest.capabilities.includes(SYNC_SESSION_OBJECT_STREAM_CAPABILITY)\n const remoteSkippedReports: Array<readonly { sessionId: string; reason: string }[]> = [remoteManifest.skipped]\n\n // 分批交换:首次同步(或长时间未同步后)plan 可能包含全部会话,一次性\n // fetch/export/apply 会让两端同时把整包内容驻留堆内(桌面端 1.4GB 堆\n // OOM 崩溃的根因,2026-11-01 崩溃日志)。按观测到的单 key 体积自适应\n // 分批:每批 fetch → 断言 → apply,批间释放内存;小计划(≤ 单批上限)\n // 仍只发一次请求,行为与旧实现一致。\n\n // 拉取方向(远端 → 本地)\n if (plan.toLocal.length > 0) {\n let perKeyBytes = 0\n let firstChunk = true\n let cursor = 0\n const keys = plan.toLocal.map(syncSessionEntryKey)\n while (cursor < keys.length) {\n const take = perKeyBytes > 0\n ? Math.max(1, Math.min(SESSION_CHUNK_MAX_KEYS, Math.floor(SESSION_CHUNK_TARGET_BYTES / perKeyBytes)))\n : SESSION_CHUNK_MAX_KEYS\n const chunkKeys = keys.slice(cursor, cursor + take)\n cursor += chunkKeys.length\n const chunkKeySet = new Set(chunkKeys)\n const chunkManifest = plan.toLocal.filter((entry) => chunkKeySet.has(syncSessionEntryKey(entry)))\n const prefixes = useEventDeltas ? sessionEventPrefixesFor(chunkManifest, localManifest.entries) : []\n this.throwIfStopped(signal)\n let fetched = validateSyncSessionBundle(await this.retryTransport(signal, () =>\n this.transport.fetchSessionEntries(peer.id, chunkKeys, remoteManifest.digest, prefixes, useObjectStream),\n ))\n this.throwIfStopped(signal)\n if (fetched.instanceId !== remoteManifest.instanceId) {\n throw new SyncCoordinatorError('protocol-invalid', '远端会话内容与 manifest 实例不一致')\n }\n const pullPartition = partitionStaleSessionEntries(chunkManifest, fetched.entries)\n staleSessionCount += pullPartition.stale.length\n remoteSkippedReports.push(fetched.skipped)\n if (pullPartition.stale.length > 0) {\n fetched = { ...fetched, entries: pullPartition.retained }\n }\n if (useObjectStream) {\n // 带外对象:bundle 里 deferred 描述符的载荷经对象流 RPC 拉到本地\n // 收件箱(磁盘流式,内存 O(帧)),随后 applyBundle 按摘要水合。\n const deferredObjects = fetched.entries.flatMap((entry) => (entry.objects ?? []).filter((object) => object.deferred === true))\n if (deferredObjects.length > 0) {\n await this.retryTransport(signal, async () => {\n await sessionService.ingestObjectStream(this.transport.fetchSessionObjects(peer.id, deferredObjects))\n })\n }\n }\n const applySkipped = firstChunk ? mergeSessionSkipped(remoteManifest.skipped, fetched.skipped) : fetched.skipped\n try {\n const applied = await sessionService.applyBundle(\n makeSyncSessionBundle(remoteManifest.instanceId, fetched.entries, applySkipped),\n peer.name,\n peer.id,\n )\n sessionLocalResult = addSessionResults(sessionLocalResult, applied)\n } catch (error) {\n if (!(error instanceof SyncSessionError && error.code === 'session-delta-prefix')) throw error\n // 回退拉全量内容:不带 deferred 标记,载荷内联(与既有回退语义一致,\n // 且不依赖已入库的收件箱对象)。\n const fullRemoteEntries = validateSyncSessionBundle(await this.retryTransport(signal, () =>\n this.transport.fetchSessionEntries(peer.id, chunkKeys, remoteManifest.digest, undefined, false),\n ))\n if (fullRemoteEntries.instanceId !== remoteManifest.instanceId) {\n throw new SyncCoordinatorError('protocol-invalid', '远端会话内容与 manifest 实例不一致')\n }\n const pullRetryPartition = partitionStaleSessionEntries(chunkManifest, fullRemoteEntries.entries)\n staleSessionCount += pullRetryPartition.stale.length\n remoteSkippedReports.push(fullRemoteEntries.skipped)\n fullRemoteEntries.entries = pullRetryPartition.retained\n const applied = await sessionService.applyBundle(\n makeSyncSessionBundle(\n remoteManifest.instanceId,\n fullRemoteEntries.entries,\n firstChunk ? mergeSessionSkipped(remoteManifest.skipped, fullRemoteEntries.skipped) : fullRemoteEntries.skipped,\n ),\n peer.name,\n peer.id,\n )\n sessionLocalResult = addSessionResults(sessionLocalResult, applied)\n fetched = fullRemoteEntries\n }\n const chunkBytes = Buffer.byteLength(JSON.stringify(fetched), 'utf8')\n if (chunkKeys.length > 0) perKeyBytes = Math.max(perKeyBytes, Math.ceil(chunkBytes / chunkKeys.length))\n firstChunk = false\n }\n } else if (remoteManifest.skipped.length > 0) {\n const applied = await sessionService.applyBundle(\n makeSyncSessionBundle(remoteManifest.instanceId, [], remoteManifest.skipped),\n peer.name,\n peer.id,\n )\n sessionLocalResult = addSessionResults(sessionLocalResult, applied)\n }\n remoteSkipped = mergeSessionSkipped(...remoteSkippedReports).length\n\n // 推送方向(本地 → 远端)\n if (plan.toRemote.length > 0) {\n const keys = plan.toRemote.map(syncSessionEntryKey)\n let perKeyBytes = 0\n let firstChunk = true\n let cursor = 0\n while (cursor < keys.length) {\n const take = perKeyBytes > 0\n ? Math.max(1, Math.min(SESSION_CHUNK_MAX_KEYS, Math.floor(SESSION_CHUNK_TARGET_BYTES / perKeyBytes)))\n : SESSION_CHUNK_MAX_KEYS\n const chunkKeys = keys.slice(cursor, cursor + take)\n cursor += chunkKeys.length\n const chunkKeySet = new Set(chunkKeys)\n const chunkManifest = plan.toRemote.filter((entry) => chunkKeySet.has(syncSessionEntryKey(entry)))\n const prefixes = useEventDeltas ? sessionEventPrefixesFor(chunkManifest, remoteManifest.entries) : []\n this.throwIfStopped(signal)\n let exported = await sessionService.exportEntries(\n chunkKeys,\n localManifest.digest,\n prefixes,\n { sharedObjects: useSharedObjects, deferredObjects: useObjectStream },\n )\n this.throwIfStopped(signal)\n const pushPartition = partitionStaleSessionEntries(chunkManifest, exported.entries)\n staleSessionCount += pushPartition.stale.length\n if (pushPartition.stale.length > 0) {\n exported = { ...exported, entries: pushPartition.retained }\n }\n const wireSkipped = firstChunk ? mergeSessionSkipped(localManifest.skipped, exported.skipped) : exported.skipped\n let wireBundle = exported.objects !== undefined\n ? makeSyncSessionBundle(exported.instanceId, exported.entries, wireSkipped, exported.objects)\n : makeSyncSessionBundle(exported.instanceId, exported.entries, wireSkipped)\n if (useObjectStream) {\n // 带外对象:先把 deferred 载荷推送进对端收件箱(磁盘流式,\n // 内存 O(帧)),再发 bundle;对端 apply 时按摘要水合。\n const deferredObjects = ((wireBundle.objects ?? wireBundle.entries.flatMap((entry) => entry.objects ?? [])) as SyncSessionObject[])\n .filter((object) => object.deferred === true)\n if (deferredObjects.length > 0) {\n await this.retryTransport(signal, () =>\n this.transport.pushSessionObjects(peer.id, sessionService.streamObjects(deferredObjects)),\n )\n }\n }\n try {\n const applied = await this.retryTransport(signal, () =>\n this.transport.applySessionBundle(peer.id, wireBundle, localInstanceId),\n )\n sessionRemoteResult = addSessionResults(sessionRemoteResult, applied)\n } catch (error) {\n if (!(error instanceof SyncSessionDeltaPrefixError)) throw error\n // 回退推全量内容:不带 deferred 标记,载荷内联。\n const fullLocalEntries = await sessionService.exportEntries(\n chunkKeys,\n localManifest.digest,\n [],\n { sharedObjects: wireBundle.objects !== undefined, deferredObjects: false },\n )\n const pushRetryPartition = partitionStaleSessionEntries(chunkManifest, fullLocalEntries.entries)\n staleSessionCount += pushRetryPartition.stale.length\n fullLocalEntries.entries = pushRetryPartition.retained\n const skippedReport = firstChunk ? mergeSessionSkipped(localManifest.skipped, fullLocalEntries.skipped) : fullLocalEntries.skipped\n wireBundle = fullLocalEntries.objects !== undefined\n ? makeSyncSessionBundle(fullLocalEntries.instanceId, fullLocalEntries.entries, skippedReport, fullLocalEntries.objects)\n : makeSyncSessionBundle(fullLocalEntries.instanceId, fullLocalEntries.entries, skippedReport)\n const applied = await this.retryTransport(signal, () =>\n this.transport.applySessionBundle(peer.id, wireBundle, localInstanceId),\n )\n sessionRemoteResult = addSessionResults(sessionRemoteResult, applied)\n }\n const chunkBytes = Buffer.byteLength(JSON.stringify(wireBundle), 'utf8')\n if (chunkKeys.length > 0) perKeyBytes = Math.max(perKeyBytes, Math.ceil(chunkBytes / chunkKeys.length))\n firstChunk = false\n }\n }\n } else {\n this.throwIfStopped(signal)\n const remoteBundle = validateSyncSessionBundle(await this.retryTransport(signal, () => this.transport.fetchSessionBundle(peer.id)))\n this.throwIfStopped(signal)\n if (remoteBundle.instanceId !== remoteNodeManifest.instanceId) {\n throw new SyncCoordinatorError('protocol-invalid', '节点与会话 manifest 的实例身份不一致')\n }\n const localBundle = await sessionService.exportBundle()\n plan = planSessionTransfers(peer.direction, localBundle.entries, remoteBundle.entries)\n remoteSkipped = remoteBundle.skipped.length\n remoteSessionDigest = remoteBundle.digest\n localSessionDigest = localBundle.digest\n localInstanceId = localBundle.instanceId\n if (plan.toLocal.length > 0 || remoteSkipped > 0) {\n sessionLocalResult = await sessionService.applyBundle(\n makeSyncSessionBundle(remoteBundle.instanceId, plan.toLocal, remoteBundle.skipped),\n peer.name,\n peer.id,\n )\n }\n if (plan.toRemote.length > 0) {\n sessionRemoteResult = await this.retryTransport(signal, () =>\n this.transport.applySessionBundle(\n peer.id,\n makeSyncSessionBundle(localBundle.instanceId, plan.toRemote, localBundle.skipped),\n localInstanceId,\n ),\n )\n }\n }\n importedSessions = sessionResultCount(sessionLocalResult)\n exportedSessions = sessionResultCount(sessionRemoteResult)\n skippedSessions = plan.skipped + sessionLocalResult.skipped + sessionRemoteResult.skipped + staleSessionCount\n digest = `sha256:${createHash('sha256').update(`${digest}\\0${remoteSessionDigest}\\0${localSessionDigest}`).digest('hex')}`\n }\n const finishedAt = new Date(this.now()).toISOString()\n const summary: SyncRunSummary = {\n peerId,\n direction: peer.direction,\n startedAt,\n finishedAt,\n remoteInstanceId: remoteNodeManifest.instanceId,\n imported: localCounts.applied,\n exported: remoteCounts.applied,\n skipped: plan.skipped + localCounts.skipped + remoteCounts.skipped + skippedSessions,\n pendingRemoval: localCounts.pendingRemoval + remoteCounts.pendingRemoval,\n importedSessions,\n exportedSessions,\n skippedSessions,\n }\n\n // 成功路径的进度写也不得抛出(否则 promise 拒绝被路由吞掉,状态卡 running)。\n try {\n this.peers.updateProgress(peer.id, {\n lastRunAt: finishedAt,\n lastRunStatus: 'succeeded',\n lastSuccessAt: finishedAt,\n lastManifestDigest: digest,\n watermark: digest,\n lastErrorCode: undefined,\n lastErrorMessage: undefined,\n lastResult: {\n imported: summary.imported,\n exported: summary.exported,\n skipped: summary.skipped,\n pendingRemoval: summary.pendingRemoval,\n importedSessions,\n exportedSessions,\n skippedSessions,\n ...(staleSessionCount > 0 ? { staleSkippedSessions: staleSessionCount } : {}),\n ...(peer.mode === 'metadata' && peer.syncSessions ? {\n catalogNodes: catalog.nodes.length,\n catalogWorkspaces: catalog.workspaces.length,\n catalogSessions: catalog.sessions.length,\n } : {}),\n },\n })\n } catch {}\n return summary\n } catch (error) {\n if (this.stopped(error)) {\n // 手动停止:丢弃本对端未完成的 journal 批次(进行中的批不再落地、\n // 重启不回放),水位保持不变,状态记为 stopped。\n let discarded = 0\n try {\n discarded = this.sessions?.discardPendingBatches(peerId) ?? 0\n } catch {}\n const finishedAt = new Date(this.now()).toISOString()\n // 进度写失败不得遮蔽停止本身(校验器曾拒绝 stopped 值导致状态卡 running)。\n try {\n this.peers.updateProgress(peer.id, {\n lastRunAt: finishedAt,\n lastRunStatus: 'stopped',\n lastErrorCode: 'stopped',\n lastErrorMessage: discarded > 0 ? `已停止:丢弃 ${discarded} 个未完成批次,已完成的会话保留` : '已停止:已完成的会话保留',\n })\n } catch {}\n const summary: SyncRunSummary = {\n peerId,\n direction: peer.direction,\n startedAt,\n finishedAt,\n remoteInstanceId: '',\n imported: 0,\n exported: 0,\n skipped: 0,\n pendingRemoval: 0,\n importedSessions: 0,\n exportedSessions: 0,\n skippedSessions: 0,\n }\n return summary\n }\n const failure = mapFailure(error)\n if (!(error instanceof SyncCoordinatorError) && !(error instanceof SyncSshProbeError) && !(error instanceof SyncSessionError) && !(error instanceof SyncNodeManifestError) && !(error instanceof SyncHostKeyChallengeError) && !(error instanceof SyncPeerNotFoundError)) {\n failure.message = `${failure.message}:${error instanceof Error ? error.message : String(error)}`\n }\n try {\n this.peers.updateProgress(peer.id, {\n lastRunAt: new Date(this.now()).toISOString(),\n lastRunStatus: 'failed',\n lastErrorCode: failure.code,\n lastErrorMessage: this.progressMessage(failure.message),\n })\n } catch {}\n throw failure\n }\n }\n\n private clear(peerId: string, run: Promise<SyncRunSummary>): void {\n if (this.inFlight.get(peerId)?.promise === run) this.inFlight.delete(peerId)\n }\n\n private async retryTransport<T>(signal: AbortSignal, operation: () => Promise<T>): Promise<T> {\n this.throwIfStopped(signal)\n try {\n return await operation()\n } catch (error) {\n if (signal.aborted) throw new SyncCoordinatorError('stopped', '同步已被手动停止')\n if (!(error instanceof SyncSshProbeError) || !['network', 'timeout', 'helper'].includes(error.category)) throw error\n this.throwIfStopped(signal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5F,KAAK,eAAe,MAAM;EAC1B,IAAI;GACF,OAAO,MAAM,UAAU;EACzB,SAAS,OAAO;GACd,IAAI,OAAO,SAAS,MAAM,IAAI,qBAAqB,WAAW,UAAU;GACxE,IAAI,EAAE,iBAAiB,sBAAsB,CAAC;IAAC;IAAW;IAAW;GAAQ,CAAC,CAAC,SAAS,MAAM,QAAQ,GAAG,MAAM;GAC/G,KAAK,eAAe,MAAM;GAC1B,MAAM,IAAI,SAAS,YAAY,WAAW,SAAS,wBAAwB,CAAC;GAC5E,KAAK,eAAe,MAAM;GAC1B,OAAO,UAAU;EACnB;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"coordinator.js","names":[],"sources":["../../../src/core/sync/coordinator.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\nimport { SyncNodeManifestError, type SyncNodeApplyResult, type SyncNodeEntry, type SyncNodeService } from './node-sync.js'\nimport { SyncHostKeyChallengeError } from './host-key.js'\nimport { compareSyncRevision } from './revision.js'\nimport { syncRecordKey, type SyncCatalog, type SyncPeer } from './model.js'\nimport { SyncPeerManager, SyncPeerNotFoundError } from './peer-manager.js'\nimport type { SyncStateStore } from './stores.js'\nimport { SyncSessionDeltaPrefixError, SyncSshProbeError, SyncSshTransport } from './ssh-transport.js'\nimport {\n makeSyncSessionBundle,\n planSessionTransfers,\n SyncSessionError,\n SyncSessionService,\n sessionEventListDigest,\n syncSessionEntryKey,\n validateSyncSessionBundle,\n validateSyncSessionManifest,\n} from './session-sync.js'\nimport type {\n SyncSessionApplyResult,\n SyncSessionBundle,\n SyncSessionEntry,\n SyncSessionEventPrefix,\n SyncSessionObject,\n SyncSessionManifest,\n SyncSessionManifestEntry,\n} from './session-sync.js'\nimport { SYNC_CATALOG_CAPABILITY, SYNC_SESSION_BUNDLE_OBJECTS_CAPABILITY, SYNC_SESSION_EVENT_TAIL_CAPABILITY, SYNC_SESSION_MANIFEST_CAPABILITY, SYNC_SESSION_OBJECT_STREAM_CAPABILITY } from './protocol.js'\nimport { resolveSyncSelection, selectionIncludesNode, selectionIncludesSession } from './selection.js'\n\nconst EMPTY_APPLY_RESULT: SyncNodeApplyResult = { created: 0, updated: 0, deleted: 0, pendingRemoval: 0, skipped: 0 }\nconst TRANSPORT_RETRY_DELAY_MS = 250\n// 会话分批交换的目标批体积与单批 key 数上限:目标值 ≈ JSON.parse 后对象图的\n// 堆占用仍远小于宿主堆上限(桌面端约 1.4GB);单批 key 上限限制批内的\n// 条目数,避免 manifest 条目本身过大。\nconst SESSION_CHUNK_TARGET_BYTES = 12 * 1024 * 1024\nconst SESSION_CHUNK_MAX_KEYS = 8\n\nexport interface NodeTransferPlan {\n toLocal: SyncNodeEntry[]\n toRemote: SyncNodeEntry[]\n skipped: number\n}\n\nexport interface SyncRunSummary {\n peerId: string\n direction: SyncPeer['direction']\n startedAt: string\n finishedAt: string\n remoteInstanceId: string\n imported: number\n exported: number\n skipped: number\n pendingRemoval: number\n importedSessions: number\n exportedSessions: number\n skippedSessions: number\n}\n\nexport class SyncCoordinatorError extends Error {\n constructor(readonly code: string, message: string) {\n super(message)\n this.name = 'SyncCoordinatorError'\n }\n}\n\nfunction addCount(result: SyncNodeApplyResult): number {\n return result.created + result.updated + result.deleted\n}\n\nfunction manifestDigest(entries: readonly SyncNodeEntry[]): string {\n const versions = entries\n .map((entry) => ({\n key: syncRecordKey('node', entry.metadata),\n revision: entry.metadata.revision,\n contentDigest: entry.metadata.contentDigest,\n deleted: Boolean(entry.metadata.deleted),\n }))\n .sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0)\n return `sha256:${createHash('sha256').update(JSON.stringify(versions)).digest('hex')}`\n}\n\nexport function planNodeTransfers(\n direction: SyncPeer['direction'],\n localEntries: readonly SyncNodeEntry[],\n remoteEntries: readonly SyncNodeEntry[],\n): NodeTransferPlan {\n const toLocal: SyncNodeEntry[] = []\n const toRemote: SyncNodeEntry[] = []\n if (direction === 'pull') return { toLocal: [...remoteEntries], toRemote, skipped: 0 }\n\n const localByKey = new Map(localEntries.map((entry) => [syncRecordKey('node', entry.metadata), entry]))\n const remoteByKey = new Map(remoteEntries.map((entry) => [syncRecordKey('node', entry.metadata), entry]))\n const keys = new Set([...localByKey.keys(), ...remoteByKey.keys()])\n let skipped = 0\n\n for (const key of keys) {\n const local = localByKey.get(key)\n const remote = remoteByKey.get(key)\n if (!local) {\n toLocal.push(remote!)\n continue\n }\n if (!remote) {\n toRemote.push(local)\n continue\n }\n\n const comparison = compareSyncRevision(local.metadata.revision, remote.metadata.revision)\n if (comparison > 0) {\n toRemote.push(local)\n } else if (comparison < 0) {\n toLocal.push(remote)\n } else if (\n local.metadata.contentDigest === remote.metadata.contentDigest &&\n Boolean(local.metadata.deleted) === Boolean(remote.metadata.deleted)\n ) {\n skipped += 1\n } else {\n throw new SyncCoordinatorError('revision-conflict', 'Equal node revisions contain different content')\n }\n }\n return { toLocal, toRemote, skipped }\n}\n\nfunction mapFailure(error: unknown): SyncCoordinatorError {\n if (error instanceof SyncCoordinatorError) return error\n if (error instanceof SyncPeerNotFoundError) return new SyncCoordinatorError('peer-not-found', '同步节点已不存在')\n if (error instanceof SyncHostKeyChallengeError) {\n const code = error.decision === 'changed' ? 'host-key-changed' : 'host-key-untrusted'\n return new SyncCoordinatorError(code, error.message)\n }\n if (error instanceof SyncSshProbeError) {\n const messages: Record<string, string> = {\n auth: 'SSH 认证失败',\n network: 'SSH 节点不可达',\n timeout: 'SSH 连接超时',\n hostkey: 'SSH 主机密钥校验失败',\n helper: '远端同步 helper 不可用',\n protocol: '同步协议不兼容',\n }\n const baseMsg = messages[error.category] ?? 'SSH 同步失败'\n const detail = (error as Error & { detail?: string }).detail\n return new SyncCoordinatorError(`ssh-${error.category}`, detail ? `${baseMsg}:${detail}` : baseMsg)\n }\n if (error instanceof SyncNodeManifestError) return new SyncCoordinatorError('manifest-invalid', '节点 manifest 校验失败')\n if (error instanceof SyncSessionError) {\n return new SyncCoordinatorError(error.code.startsWith('session-') ? error.code : `session-${error.code}`, error.message)\n }\n return new SyncCoordinatorError('sync-failed', '同步作业失败')\n}\n\nfunction resultCount(result: SyncNodeApplyResult): { applied: number; skipped: number; pendingRemoval: number } {\n return {\n applied: addCount(result),\n skipped: result.skipped,\n pendingRemoval: result.pendingRemoval,\n }\n}\n\nfunction emptySessionResult(): SyncSessionApplyResult {\n return { created: 0, updated: 0, archived: 0, deleted: 0, skipped: 0, unmapped: 0 }\n}\n\nfunction sessionResultCount(result: SyncSessionApplyResult): number {\n return result.created + result.updated + result.deleted\n}\n\nfunction addSessionResults(target: SyncSessionApplyResult, delta: SyncSessionApplyResult): SyncSessionApplyResult {\n return {\n created: target.created + delta.created,\n updated: target.updated + delta.updated,\n archived: target.archived + delta.archived,\n deleted: target.deleted + delta.deleted,\n skipped: target.skipped + delta.skipped,\n unmapped: target.unmapped + delta.unmapped,\n }\n}\n\nfunction mergeSessionSkipped(...reports: Array<readonly { sessionId: string; reason: string }[]>): Array<{ sessionId: string; reason: string }> {\n const merged = new Map<string, { sessionId: string; reason: string }>()\n for (const report of reports) {\n for (const entry of report) merged.set(JSON.stringify([entry.sessionId, entry.reason]), entry)\n }\n return [...merged.values()]\n}\n\n/**\n * 把内容快照与 manifest 清单比对,剔除了「manifest 之后发生变化」的条目\n * (例如对端正被活跃使用的会话:边抓取边推进,快照必然落后)。剔除的条目\n * 由调用方计入 skippedSessions 并留待下次同步;对端仍在活跃的会话经远端\n * 会话通道(wss)实时展示,不依赖内容同步。\n *\n * 缺失条目还有一类确定性来源:导出端体积超限(session-payload-too-large)\n * 或 cwd 不匹配(workspace-cwd-mismatch)的会话会进 skipped 报告而不是\n * entries。这类条目按「单条跳过」处理(remoteSkipped),保留同批其余条目;\n * 否则一个永远导不出去的会话会把整批会话一起饿死——每次同步都重复发生,\n * 没有自愈路径。\n */\nfunction skippedSessionIdsOf(skipped: ReadonlyArray<{ sessionId: string; reason: string }>): Set<string> {\n return new Set(skipped.map((item) => item.sessionId))\n}\n\nfunction partitionStaleSessionEntries(\n expectedEntries: readonly SyncSessionManifestEntry[],\n selectedEntries: readonly SyncSessionEntry[],\n skippedSessionIds?: ReadonlySet<string>,\n): { retained: SyncSessionEntry[]; stale: Array<{ key: string; fields: string; detail: string }>; remoteSkipped: number } {\n const expected = new Map(expectedEntries.map((entry) => [syncSessionEntryKey(entry), entry]))\n const selected = new Map(selectedEntries.map((entry) => [syncSessionEntryKey(entry), entry]))\n const retained: SyncSessionEntry[] = []\n const stale: Array<{ key: string; fields: string; detail: string }> = []\n let remoteSkipped = 0\n if (selected.size !== selectedEntries.length) {\n for (const key of expected.keys()) stale.push({ key, fields: 'entry-missing', detail: '' })\n for (const key of selected.keys()) stale.push({ key, fields: 'unexpected-entry', detail: '' })\n return { retained: [], stale, remoteSkipped }\n }\n for (const key of selected.keys()) {\n if (!expected.has(key)) stale.push({ key, fields: 'unexpected-entry', detail: '' })\n }\n // 快照里出现了 manifest 之外的条目:清单已整体过期,按批剔除(瞬时性,\n // 下次同步会重新拉 manifest,不会永久卡住)。\n if (stale.length > 0) return { retained: [], stale, remoteSkipped }\n for (const [key, expectedEntry] of expected) {\n const metadata = expectedEntry.metadata\n const currentEntry = selected.get(key)\n if (!currentEntry) {\n if (skippedSessionIds?.has(String(metadata.localEntityId))) remoteSkipped += 1\n else stale.push({ key, fields: 'entry-missing', detail: '' })\n continue\n }\n const current = currentEntry.metadata\n const eventSummary = currentEntry.eventDelta\n ? {\n eventCount: currentEntry.eventDelta.fullEventCount,\n eventDigest: currentEntry.eventDelta.fullEventDigest,\n inheritedEventCount: currentEntry.inheritedEventCount,\n }\n : currentEntry.events\n ? {\n eventCount: currentEntry.events.length,\n eventDigest: sessionEventListDigest(currentEntry.events),\n inheritedEventCount: currentEntry.inheritedEventCount,\n }\n : undefined\n const hasExpectedEventSummary = expectedEntry.eventCount !== undefined || expectedEntry.eventDigest !== undefined ||\n expectedEntry.inheritedEventCount !== undefined\n const expectedWorkspace = metadata.workspaceOrigin\n const currentWorkspace = current.workspaceOrigin\n const mismatches: string[] = []\n if (current.localEntityId !== metadata.localEntityId) mismatches.push('localEntityId')\n if (compareSyncRevision(current.revision, metadata.revision) !== 0) mismatches.push('revision')\n if (current.contentDigest !== metadata.contentDigest) mismatches.push('contentDigest')\n if (current.stateDigest !== metadata.stateDigest) mismatches.push('stateDigest')\n if (Boolean(current.deleted) !== Boolean(metadata.deleted)) mismatches.push('deleted')\n if (expectedWorkspace?.originInstanceId !== currentWorkspace?.originInstanceId ||\n expectedWorkspace?.originEntityId !== currentWorkspace?.originEntityId) mismatches.push('workspaceOrigin')\n if (hasExpectedEventSummary && (!eventSummary || eventSummary.eventCount !== expectedEntry.eventCount ||\n eventSummary.eventDigest !== expectedEntry.eventDigest || eventSummary.inheritedEventCount !== expectedEntry.inheritedEventCount)) {\n mismatches.push('eventSummary')\n }\n if (mismatches.length > 0) {\n const detail = current && hasExpectedEventSummary\n ? ` expected(eventCount=${expectedEntry.eventCount}, inherited=${expectedEntry.inheritedEventCount}, digest=${expectedEntry.eventDigest})` +\n ` actual(${eventSummary ? `eventCount=${eventSummary.eventCount}, inherited=${eventSummary.inheritedEventCount}, digest=${eventSummary.eventDigest}` : 'no-events'})`\n : ''\n stale.push({ key, fields: mismatches.join(','), detail })\n continue\n }\n retained.push(currentEntry)\n }\n return { retained, stale, remoteSkipped }\n}\n\nfunction sessionEventPrefixesFor(\n selectedEntries: readonly SyncSessionManifestEntry[],\n receiverEntries: readonly SyncSessionManifestEntry[],\n): SyncSessionEventPrefix[] {\n const receiverByKey = new Map(receiverEntries.map((entry) => [syncSessionEntryKey(entry), entry]))\n const prefixes: SyncSessionEventPrefix[] = []\n for (const selected of selectedEntries) {\n if (selected.branchId || selected.metadata.deleted) continue\n const receiver = receiverByKey.get(syncSessionEntryKey(selected))\n if (!receiver || receiver.branchId || receiver.metadata.deleted || receiver.eventCount === undefined ||\n receiver.eventDigest === undefined || receiver.inheritedEventCount === undefined) continue\n prefixes.push({\n key: syncSessionEntryKey(selected),\n eventCount: receiver.eventCount,\n eventDigest: receiver.eventDigest,\n inheritedEventCount: receiver.inheritedEventCount,\n })\n }\n return prefixes\n}\n\nexport class SyncCoordinator {\n private readonly inFlight = new Map<string, { promise: Promise<SyncRunSummary>; controller: AbortController }>()\n\n constructor(\n private readonly peers: SyncPeerManager,\n private readonly state: SyncStateStore,\n private readonly nodes: SyncNodeService,\n private readonly transport: SyncSshTransport,\n private readonly now: () => number = Date.now,\n private readonly sessions?: SyncSessionService,\n ) {}\n\n run(peerId: string): Promise<SyncRunSummary> {\n const active = this.inFlight.get(peerId)\n if (active) return active.promise\n const controller = new AbortController()\n const run = this.execute(peerId, controller.signal)\n this.inFlight.set(peerId, { promise: run, controller })\n void run.then(() => this.clear(peerId, run), () => this.clear(peerId, run))\n return run\n }\n\n /**\n * 手动停止运行中的同步:在最近的安全边界(批次之间)中止。\n * 返回是否确有运行中的作业。中止后丢弃本对端未完成的 journal 批次\n * (未应用条目不落地、重启不回放),水位保持不变,状态记为 stopped。\n */\n stop(peerId: string): boolean {\n const active = this.inFlight.get(peerId)\n if (!active) return false\n active.controller.abort()\n // 立即关闭该对端的活跃 SSH 通道:等待中的 readFrames 随即返回,\n // 不必等空闲超时(沙箱代理冻结场景下可能长达 60s)。\n try {\n this.transport.stopActiveSessions(peerId)\n } catch {}\n return true\n }\n\n /** 是否已手动停止:错误分类与收尾路径共用。 */\n private stopped(error: unknown): boolean {\n return error instanceof SyncCoordinatorError && error.code === 'stopped'\n }\n\n private throwIfStopped(signal: AbortSignal): void {\n if (signal.aborted) throw new SyncCoordinatorError('stopped', '同步已被手动停止')\n }\n\n /** 进度错误消息必须满足校验器限制(≤256、无控制字符),否则收尾写失败会卡住状态。 */\n private progressMessage(text: string): string {\n return text.replace(/[\\u0000-\\u001f\\u007f]/g, ' ').slice(0, 256)\n }\n\n private async execute(peerId: string, signal: AbortSignal): Promise<SyncRunSummary> {\n const peer = await this.peers.get(peerId)\n if (!peer) throw new SyncCoordinatorError('peer-not-found', '同步节点已不存在')\n if (!peer.enabled) throw new SyncCoordinatorError('peer-disabled', '此同步节点已停用')\n if (signal.aborted) throw new SyncCoordinatorError('stopped', '同步已被手动停止')\n\n const startedAt = new Date(this.now()).toISOString()\n this.peers.updateProgress(peer.id, {\n lastRunAt: startedAt,\n lastRunStatus: 'running',\n lastErrorCode: undefined,\n lastErrorMessage: undefined,\n })\n\n try {\n if (peer.syncSessions && peer.mode !== 'metadata' && !this.sessions) {\n throw new SyncCoordinatorError('sessions-unavailable', '会话同步服务不可用')\n }\n const remoteNodeManifest = await this.retryTransport(signal, () => this.transport.fetchNodeManifest(peer.id))\n if (remoteNodeManifest.protocolVersion !== 1 || remoteNodeManifest.instanceId === this.state.instanceId()) {\n throw new SyncCoordinatorError('protocol-invalid', '同步 peer 协议版本或实例身份无效')\n }\n const remoteEntries = this.nodes.validateManifest(remoteNodeManifest.records)\n const localManifest = await this.nodes.exportManifest()\n const localEntries = this.nodes.validateManifest(localManifest.records)\n let catalog: SyncCatalog = {\n protocolVersion: 1,\n instanceId: remoteNodeManifest.instanceId,\n nodes: [],\n workspaces: [],\n sessions: [],\n }\n if (peer.mode === 'metadata' && peer.syncSessions) {\n // 元数据同步:只拉目录(节点/工作区/会话列表),不交换会话内容;\n // 点击同步来的会话时经远端会话通道(wss)实时操作远端 DSH。\n if (!remoteNodeManifest.capabilities?.includes(SYNC_CATALOG_CAPABILITY)) {\n throw new SyncCoordinatorError('metadata-catalog-unavailable', '目标同步节点需要升级以支持元数据同步')\n }\n catalog = await this.retryTransport(signal, () => this.transport.fetchCatalog(peer.id))\n if (catalog.instanceId !== remoteNodeManifest.instanceId) {\n throw new SyncCoordinatorError('protocol-invalid', '节点与目录清单的实例身份不一致')\n }\n } else if (peer.selection?.mode === 'selected' && peer.syncSessions &&\n (peer.selection.workspaces.length > 0 || peer.selection.sessions.length > 0)) {\n if (!remoteNodeManifest.capabilities?.includes(SYNC_CATALOG_CAPABILITY)) {\n throw new SyncCoordinatorError('selection-catalog-unavailable', '目标同步节点需要升级以支持自选范围')\n }\n catalog = await this.retryTransport(signal, () => this.transport.fetchCatalog(peer.id))\n if (catalog.instanceId !== remoteNodeManifest.instanceId) {\n throw new SyncCoordinatorError('protocol-invalid', '节点与目录清单的实例身份不一致')\n }\n }\n const selection = resolveSyncSelection(peer.mode === 'metadata' ? undefined : peer.selection, catalog)\n // 节点配置交换:全量模式恒开(会话导入依赖节点/工作区映射);元数据模式\n // 可由「同步工作节点」关闭——关闭后仅校验对端身份并拉取目录。\n const syncNodes = peer.mode !== 'metadata' || peer.syncNodes !== false\n // 节点配置固定从远端拉取(同步语义简化后方向仅作用于会话内容交换)。\n const fullNodePlan: NodeTransferPlan = syncNodes ? planNodeTransfers('pull', localEntries, remoteEntries) : { toLocal: [], toRemote: [], skipped: 0 }\n const plan = !syncNodes || selection.all ? fullNodePlan : {\n ...fullNodePlan,\n toLocal: fullNodePlan.toLocal.filter((entry) => selectionIncludesNode(entry.metadata, selection)),\n toRemote: fullNodePlan.toRemote.filter((entry) => selectionIncludesNode(entry.metadata, selection)),\n }\n\n const localResult = plan.toLocal.length > 0\n ? await this.nodes.applyManifest(plan.toLocal, peer.name, 'peer')\n : EMPTY_APPLY_RESULT\n const remoteResult = plan.toRemote.length > 0\n ? await this.retryTransport(signal, () => this.transport.applyNodeManifest(peer.id, plan.toRemote, localManifest.instanceId))\n : EMPTY_APPLY_RESULT\n const localCounts = resultCount(localResult)\n const remoteCounts = resultCount(remoteResult)\n let importedSessions = 0\n let exportedSessions = 0\n let skippedSessions = 0\n let staleSessionCount = 0\n let digest = manifestDigest(remoteEntries)\n if (peer.mode === 'metadata' && peer.syncSessions) {\n // 每次同步实时拉取目录并报告计数;会话内容交换整体跳过。\n } else if (peer.syncSessions) {\n const sessionService = this.sessions!\n let plan: ReturnType<typeof planSessionTransfers>\n let remoteSkipped = 0\n let remoteSessionDigest = ''\n let localSessionDigest = ''\n let localInstanceId = ''\n let sessionLocalResult = emptySessionResult()\n let sessionRemoteResult = emptySessionResult()\n if (remoteNodeManifest.capabilities?.includes(SYNC_SESSION_MANIFEST_CAPABILITY)) {\n const remoteManifest = validateSyncSessionManifest(\n await this.retryTransport(signal, () => this.transport.fetchSessionManifest(peer.id)),\n )\n if (remoteManifest.instanceId !== remoteNodeManifest.instanceId) {\n throw new SyncCoordinatorError('protocol-invalid', '节点与会话 manifest 的实例身份不一致')\n }\n const localManifest = await sessionService.exportManifest()\n const fullSessionPlan = planSessionTransfers(peer.direction, localManifest.entries, remoteManifest.entries)\n plan = selection.all ? fullSessionPlan : {\n ...fullSessionPlan,\n toLocal: fullSessionPlan.toLocal.filter((entry) => selectionIncludesSession(entry.metadata, selection)),\n toRemote: fullSessionPlan.toRemote.filter((entry) => selectionIncludesSession(entry.metadata, selection)),\n }\n remoteSessionDigest = remoteManifest.digest\n localSessionDigest = localManifest.digest\n localInstanceId = localManifest.instanceId\n const useEventDeltas = remoteNodeManifest.capabilities.includes(SYNC_SESSION_EVENT_TAIL_CAPABILITY)\n const useSharedObjects = remoteNodeManifest.capabilities.includes(SYNC_SESSION_BUNDLE_OBJECTS_CAPABILITY)\n const useObjectStream = remoteNodeManifest.capabilities.includes(SYNC_SESSION_OBJECT_STREAM_CAPABILITY)\n const remoteSkippedReports: Array<readonly { sessionId: string; reason: string }[]> = [remoteManifest.skipped]\n\n // 分批交换:首次同步(或长时间未同步后)plan 可能包含全部会话,一次性\n // fetch/export/apply 会让两端同时把整包内容驻留堆内(桌面端 1.4GB 堆\n // OOM 崩溃的根因,2026-11-01 崩溃日志)。按观测到的单 key 体积自适应\n // 分批:每批 fetch → 断言 → apply,批间释放内存;小计划(≤ 单批上限)\n // 仍只发一次请求,行为与旧实现一致。\n\n // 拉取方向(远端 → 本地)\n if (plan.toLocal.length > 0) {\n let perKeyBytes = 0\n let firstChunk = true\n let cursor = 0\n const keys = plan.toLocal.map(syncSessionEntryKey)\n while (cursor < keys.length) {\n const take = perKeyBytes > 0\n ? Math.max(1, Math.min(SESSION_CHUNK_MAX_KEYS, Math.floor(SESSION_CHUNK_TARGET_BYTES / perKeyBytes)))\n : SESSION_CHUNK_MAX_KEYS\n const chunkKeys = keys.slice(cursor, cursor + take)\n cursor += chunkKeys.length\n const chunkKeySet = new Set(chunkKeys)\n const chunkManifest = plan.toLocal.filter((entry) => chunkKeySet.has(syncSessionEntryKey(entry)))\n const prefixes = useEventDeltas ? sessionEventPrefixesFor(chunkManifest, localManifest.entries) : []\n this.throwIfStopped(signal)\n let fetched = validateSyncSessionBundle(await this.retryTransport(signal, () =>\n this.transport.fetchSessionEntries(peer.id, chunkKeys, remoteManifest.digest, prefixes, useObjectStream),\n ))\n this.throwIfStopped(signal)\n if (fetched.instanceId !== remoteManifest.instanceId) {\n throw new SyncCoordinatorError('protocol-invalid', '远端会话内容与 manifest 实例不一致')\n }\n const pullPartition = partitionStaleSessionEntries(\n chunkManifest, fetched.entries, skippedSessionIdsOf(fetched.skipped))\n staleSessionCount += pullPartition.stale.length\n remoteSkippedReports.push(fetched.skipped)\n if (pullPartition.stale.length > 0) {\n fetched = { ...fetched, entries: pullPartition.retained }\n }\n if (useObjectStream) {\n // 带外对象:bundle 里 deferred 描述符的载荷经对象流 RPC 拉到本地\n // 收件箱(磁盘流式,内存 O(帧)),随后 applyBundle 按摘要水合。\n const deferredObjects = fetched.entries.flatMap((entry) => (entry.objects ?? []).filter((object) => object.deferred === true))\n if (deferredObjects.length > 0) {\n await this.retryTransport(signal, async () => {\n await sessionService.ingestObjectStream(this.transport.fetchSessionObjects(peer.id, deferredObjects))\n })\n }\n }\n const applySkipped = firstChunk ? mergeSessionSkipped(remoteManifest.skipped, fetched.skipped) : fetched.skipped\n try {\n const applied = await sessionService.applyBundle(\n makeSyncSessionBundle(remoteManifest.instanceId, fetched.entries, applySkipped),\n peer.name,\n peer.id,\n )\n sessionLocalResult = addSessionResults(sessionLocalResult, applied)\n } catch (error) {\n if (!(error instanceof SyncSessionError && error.code === 'session-delta-prefix')) throw error\n // 回退拉全量内容:不带 deferred 标记,载荷内联(与既有回退语义一致,\n // 且不依赖已入库的收件箱对象)。\n const fullRemoteEntries = validateSyncSessionBundle(await this.retryTransport(signal, () =>\n this.transport.fetchSessionEntries(peer.id, chunkKeys, remoteManifest.digest, undefined, false),\n ))\n if (fullRemoteEntries.instanceId !== remoteManifest.instanceId) {\n throw new SyncCoordinatorError('protocol-invalid', '远端会话内容与 manifest 实例不一致')\n }\n const pullRetryPartition = partitionStaleSessionEntries(\n chunkManifest, fullRemoteEntries.entries, skippedSessionIdsOf(fullRemoteEntries.skipped))\n staleSessionCount += pullRetryPartition.stale.length\n remoteSkippedReports.push(fullRemoteEntries.skipped)\n fullRemoteEntries.entries = pullRetryPartition.retained\n const applied = await sessionService.applyBundle(\n makeSyncSessionBundle(\n remoteManifest.instanceId,\n fullRemoteEntries.entries,\n firstChunk ? mergeSessionSkipped(remoteManifest.skipped, fullRemoteEntries.skipped) : fullRemoteEntries.skipped,\n ),\n peer.name,\n peer.id,\n )\n sessionLocalResult = addSessionResults(sessionLocalResult, applied)\n fetched = fullRemoteEntries\n }\n const chunkBytes = Buffer.byteLength(JSON.stringify(fetched), 'utf8')\n if (chunkKeys.length > 0) perKeyBytes = Math.max(perKeyBytes, Math.ceil(chunkBytes / chunkKeys.length))\n firstChunk = false\n }\n } else if (remoteManifest.skipped.length > 0) {\n const applied = await sessionService.applyBundle(\n makeSyncSessionBundle(remoteManifest.instanceId, [], remoteManifest.skipped),\n peer.name,\n peer.id,\n )\n sessionLocalResult = addSessionResults(sessionLocalResult, applied)\n }\n remoteSkipped = mergeSessionSkipped(...remoteSkippedReports).length\n\n // 推送方向(本地 → 远端)\n if (plan.toRemote.length > 0) {\n const keys = plan.toRemote.map(syncSessionEntryKey)\n let perKeyBytes = 0\n let firstChunk = true\n let cursor = 0\n while (cursor < keys.length) {\n const take = perKeyBytes > 0\n ? Math.max(1, Math.min(SESSION_CHUNK_MAX_KEYS, Math.floor(SESSION_CHUNK_TARGET_BYTES / perKeyBytes)))\n : SESSION_CHUNK_MAX_KEYS\n const chunkKeys = keys.slice(cursor, cursor + take)\n cursor += chunkKeys.length\n const chunkKeySet = new Set(chunkKeys)\n const chunkManifest = plan.toRemote.filter((entry) => chunkKeySet.has(syncSessionEntryKey(entry)))\n const prefixes = useEventDeltas ? sessionEventPrefixesFor(chunkManifest, remoteManifest.entries) : []\n this.throwIfStopped(signal)\n let exported = await sessionService.exportEntries(\n chunkKeys,\n localManifest.digest,\n prefixes,\n { sharedObjects: useSharedObjects, deferredObjects: useObjectStream },\n )\n this.throwIfStopped(signal)\n const pushPartition = partitionStaleSessionEntries(\n chunkManifest, exported.entries, skippedSessionIdsOf(exported.skipped))\n staleSessionCount += pushPartition.stale.length\n if (pushPartition.stale.length > 0) {\n exported = { ...exported, entries: pushPartition.retained }\n }\n const wireSkipped = firstChunk ? mergeSessionSkipped(localManifest.skipped, exported.skipped) : exported.skipped\n let wireBundle = exported.objects !== undefined\n ? makeSyncSessionBundle(exported.instanceId, exported.entries, wireSkipped, exported.objects)\n : makeSyncSessionBundle(exported.instanceId, exported.entries, wireSkipped)\n if (useObjectStream) {\n // 带外对象:先把 deferred 载荷推送进对端收件箱(磁盘流式,\n // 内存 O(帧)),再发 bundle;对端 apply 时按摘要水合。\n const deferredObjects = ((wireBundle.objects ?? wireBundle.entries.flatMap((entry) => entry.objects ?? [])) as SyncSessionObject[])\n .filter((object) => object.deferred === true)\n if (deferredObjects.length > 0) {\n await this.retryTransport(signal, () =>\n this.transport.pushSessionObjects(peer.id, sessionService.streamObjects(deferredObjects)),\n )\n }\n }\n try {\n const applied = await this.retryTransport(signal, () =>\n this.transport.applySessionBundle(peer.id, wireBundle, localInstanceId),\n )\n sessionRemoteResult = addSessionResults(sessionRemoteResult, applied)\n } catch (error) {\n if (!(error instanceof SyncSessionDeltaPrefixError)) throw error\n // 回退推全量内容:不带 deferred 标记,载荷内联。\n const fullLocalEntries = await sessionService.exportEntries(\n chunkKeys,\n localManifest.digest,\n [],\n { sharedObjects: wireBundle.objects !== undefined, deferredObjects: false },\n )\n const pushRetryPartition = partitionStaleSessionEntries(\n chunkManifest, fullLocalEntries.entries, skippedSessionIdsOf(fullLocalEntries.skipped))\n staleSessionCount += pushRetryPartition.stale.length\n fullLocalEntries.entries = pushRetryPartition.retained\n const skippedReport = firstChunk ? mergeSessionSkipped(localManifest.skipped, fullLocalEntries.skipped) : fullLocalEntries.skipped\n wireBundle = fullLocalEntries.objects !== undefined\n ? makeSyncSessionBundle(fullLocalEntries.instanceId, fullLocalEntries.entries, skippedReport, fullLocalEntries.objects)\n : makeSyncSessionBundle(fullLocalEntries.instanceId, fullLocalEntries.entries, skippedReport)\n const applied = await this.retryTransport(signal, () =>\n this.transport.applySessionBundle(peer.id, wireBundle, localInstanceId),\n )\n sessionRemoteResult = addSessionResults(sessionRemoteResult, applied)\n }\n const chunkBytes = Buffer.byteLength(JSON.stringify(wireBundle), 'utf8')\n if (chunkKeys.length > 0) perKeyBytes = Math.max(perKeyBytes, Math.ceil(chunkBytes / chunkKeys.length))\n firstChunk = false\n }\n }\n } else {\n this.throwIfStopped(signal)\n const remoteBundle = validateSyncSessionBundle(await this.retryTransport(signal, () => this.transport.fetchSessionBundle(peer.id)))\n this.throwIfStopped(signal)\n if (remoteBundle.instanceId !== remoteNodeManifest.instanceId) {\n throw new SyncCoordinatorError('protocol-invalid', '节点与会话 manifest 的实例身份不一致')\n }\n const localBundle = await sessionService.exportBundle()\n plan = planSessionTransfers(peer.direction, localBundle.entries, remoteBundle.entries)\n remoteSkipped = remoteBundle.skipped.length\n remoteSessionDigest = remoteBundle.digest\n localSessionDigest = localBundle.digest\n localInstanceId = localBundle.instanceId\n if (plan.toLocal.length > 0 || remoteSkipped > 0) {\n sessionLocalResult = await sessionService.applyBundle(\n makeSyncSessionBundle(remoteBundle.instanceId, plan.toLocal, remoteBundle.skipped),\n peer.name,\n peer.id,\n )\n }\n if (plan.toRemote.length > 0) {\n sessionRemoteResult = await this.retryTransport(signal, () =>\n this.transport.applySessionBundle(\n peer.id,\n makeSyncSessionBundle(localBundle.instanceId, plan.toRemote, localBundle.skipped),\n localInstanceId,\n ),\n )\n }\n }\n importedSessions = sessionResultCount(sessionLocalResult)\n exportedSessions = sessionResultCount(sessionRemoteResult)\n skippedSessions = plan.skipped + sessionLocalResult.skipped + sessionRemoteResult.skipped + staleSessionCount\n digest = `sha256:${createHash('sha256').update(`${digest}\\0${remoteSessionDigest}\\0${localSessionDigest}`).digest('hex')}`\n }\n const finishedAt = new Date(this.now()).toISOString()\n const summary: SyncRunSummary = {\n peerId,\n direction: peer.direction,\n startedAt,\n finishedAt,\n remoteInstanceId: remoteNodeManifest.instanceId,\n imported: localCounts.applied,\n exported: remoteCounts.applied,\n skipped: plan.skipped + localCounts.skipped + remoteCounts.skipped + skippedSessions,\n pendingRemoval: localCounts.pendingRemoval + remoteCounts.pendingRemoval,\n importedSessions,\n exportedSessions,\n skippedSessions,\n }\n\n // 成功路径的进度写也不得抛出(否则 promise 拒绝被路由吞掉,状态卡 running)。\n try {\n this.peers.updateProgress(peer.id, {\n lastRunAt: finishedAt,\n lastRunStatus: 'succeeded',\n lastSuccessAt: finishedAt,\n lastManifestDigest: digest,\n watermark: digest,\n lastErrorCode: undefined,\n lastErrorMessage: undefined,\n lastResult: {\n imported: summary.imported,\n exported: summary.exported,\n skipped: summary.skipped,\n pendingRemoval: summary.pendingRemoval,\n importedSessions,\n exportedSessions,\n skippedSessions,\n ...(staleSessionCount > 0 ? { staleSkippedSessions: staleSessionCount } : {}),\n ...(peer.mode === 'metadata' && peer.syncSessions ? {\n catalogNodes: catalog.nodes.length,\n catalogWorkspaces: catalog.workspaces.length,\n catalogSessions: catalog.sessions.length,\n } : {}),\n },\n })\n } catch {}\n return summary\n } catch (error) {\n if (this.stopped(error)) {\n // 手动停止:丢弃本对端未完成的 journal 批次(进行中的批不再落地、\n // 重启不回放),水位保持不变,状态记为 stopped。\n let discarded = 0\n try {\n discarded = this.sessions?.discardPendingBatches(peerId) ?? 0\n } catch {}\n const finishedAt = new Date(this.now()).toISOString()\n // 进度写失败不得遮蔽停止本身(校验器曾拒绝 stopped 值导致状态卡 running)。\n try {\n this.peers.updateProgress(peer.id, {\n lastRunAt: finishedAt,\n lastRunStatus: 'stopped',\n lastErrorCode: 'stopped',\n lastErrorMessage: discarded > 0 ? `已停止:丢弃 ${discarded} 个未完成批次,已完成的会话保留` : '已停止:已完成的会话保留',\n })\n } catch {}\n const summary: SyncRunSummary = {\n peerId,\n direction: peer.direction,\n startedAt,\n finishedAt,\n remoteInstanceId: '',\n imported: 0,\n exported: 0,\n skipped: 0,\n pendingRemoval: 0,\n importedSessions: 0,\n exportedSessions: 0,\n skippedSessions: 0,\n }\n return summary\n }\n const failure = mapFailure(error)\n if (!(error instanceof SyncCoordinatorError) && !(error instanceof SyncSshProbeError) && !(error instanceof SyncSessionError) && !(error instanceof SyncNodeManifestError) && !(error instanceof SyncHostKeyChallengeError) && !(error instanceof SyncPeerNotFoundError)) {\n failure.message = `${failure.message}:${error instanceof Error ? error.message : String(error)}`\n }\n try {\n this.peers.updateProgress(peer.id, {\n lastRunAt: new Date(this.now()).toISOString(),\n lastRunStatus: 'failed',\n lastErrorCode: failure.code,\n lastErrorMessage: this.progressMessage(failure.message),\n })\n } catch {}\n throw failure\n }\n }\n\n private clear(peerId: string, run: Promise<SyncRunSummary>): void {\n if (this.inFlight.get(peerId)?.promise === run) this.inFlight.delete(peerId)\n }\n\n private async retryTransport<T>(signal: AbortSignal, operation: () => Promise<T>): Promise<T> {\n this.throwIfStopped(signal)\n try {\n return await operation()\n } catch (error) {\n if (signal.aborted) throw new SyncCoordinatorError('stopped', '同步已被手动停止')\n if (!(error instanceof SyncSshProbeError) || !['network', 'timeout', 'helper'].includes(error.category)) throw error\n this.throwIfStopped(signal)\n await new Promise((resolve) => setTimeout(resolve, TRANSPORT_RETRY_DELAY_MS))\n this.throwIfStopped(signal)\n return operation()\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AA8BA,MAAM,qBAA0C;CAAE,SAAS;CAAG,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AI,CAAC,CAAC,CAAC,YAAY;KAC5C,eAAe;KACf,eAAe,QAAQ;KACvB,kBAAkB,KAAK,gBAAgB,QAAQ,OAAO;IACxD,CAAC;GACH,QAAQ,CAAC;GACT,MAAM;EACR;CACF;CAEA,MAAc,QAAgB,KAAoC;EAChE,IAAI,KAAK,SAAS,IAAI,MAAM,CAAC,EAAE,YAAY,KAAK,KAAK,SAAS,OAAO,MAAM;CAC7E;CAEA,MAAc,eAAkB,QAAqB,WAAyC;EAC5F,KAAK,eAAe,MAAM;EAC1B,IAAI;GACF,OAAO,MAAM,UAAU;EACzB,SAAS,OAAO;GACd,IAAI,OAAO,SAAS,MAAM,IAAI,qBAAqB,WAAW,UAAU;GACxE,IAAI,EAAE,iBAAiB,sBAAsB,CAAC;IAAC;IAAW;IAAW;GAAQ,CAAC,CAAC,SAAS,MAAM,QAAQ,GAAG,MAAM;GAC/G,KAAK,eAAe,MAAM;GAC1B,MAAM,IAAI,SAAS,YAAY,WAAW,SAAS,wBAAwB,CAAC;GAC5E,KAAK,eAAe,MAAM;GAC1B,OAAO,UAAU;EACnB;CACF;AACF"}
|
|
@@ -1,12 +1,43 @@
|
|
|
1
1
|
import { isLoopbackRequest } from "../../auth/loopback.js";
|
|
2
2
|
import { SyncNodeManifestError } from "./node-sync.js";
|
|
3
3
|
import { SYNC_CATALOG_CAPABILITY, SYNC_SESSION_BUNDLE_OBJECTS_CAPABILITY, SYNC_SESSION_EVENT_TAIL_CAPABILITY, SYNC_SESSION_MANIFEST_CAPABILITY, SYNC_SESSION_OBJECT_STREAM_CAPABILITY } from "./protocol.js";
|
|
4
|
-
import { n as SyncSessionError, p as validateObjectPayload } from "../../session-sync-
|
|
4
|
+
import { n as SyncSessionError, p as validateObjectPayload } from "../../session-sync-DrilvkP1.js";
|
|
5
5
|
import { t as exportSyncCatalog } from "../../catalog-B6Qvy7bH.js";
|
|
6
6
|
import { readFileSync } from "node:fs";
|
|
7
7
|
import { join } from "node:path";
|
|
8
8
|
//#region src/core/sync/internal-routes.ts
|
|
9
9
|
const MAX_APPLY_BODY_BYTES = 134217728;
|
|
10
|
+
/**
|
|
11
|
+
* 从 mirror 本地路径推导 DSH home(`<home>/dshb/mirrors/<node>/<slug>`)。
|
|
12
|
+
* 分隔符按两种平台形态识别('/' 与 '\'),Windows 镜像路径同样命中;
|
|
13
|
+
* 不含该标记时返回 undefined。
|
|
14
|
+
*/
|
|
15
|
+
function homeFromMirrorPath(localPath) {
|
|
16
|
+
const index = localPath.replaceAll("\\", "/").lastIndexOf("/dshb/mirrors/");
|
|
17
|
+
if (index <= 0) return void 0;
|
|
18
|
+
return localPath.slice(0, index);
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* 与 dsh-session-persistence-jsonl 的 projectKey 逐字符一致:路径分隔符
|
|
22
|
+
* ('/'、'\'、':')折叠为 '-',安全字符原样保留,其余字符转 '~XXXX' 十六
|
|
23
|
+
* 进制转义;去掉前导 '-' 后截断到 251 字符并包上 '--'。旧实现按 '/' 切分
|
|
24
|
+
* 拼接,POSIX 典型路径结果相同,但 Windows 路径(':' 与 '\' 相邻)永远对不上。
|
|
25
|
+
*/
|
|
26
|
+
function projectKey(cwd) {
|
|
27
|
+
let readable = "";
|
|
28
|
+
let separatorRun = false;
|
|
29
|
+
for (const ch of cwd) if (ch === "/" || ch === "\\" || ch === ":") {
|
|
30
|
+
if (!separatorRun) readable += "-";
|
|
31
|
+
separatorRun = true;
|
|
32
|
+
} else if (ch !== "~" && /^[A-Za-z0-9._-]$/.test(ch)) {
|
|
33
|
+
readable += ch;
|
|
34
|
+
separatorRun = false;
|
|
35
|
+
} else {
|
|
36
|
+
readable += `~${ch.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0")}`;
|
|
37
|
+
separatorRun = false;
|
|
38
|
+
}
|
|
39
|
+
return `--${(readable.replace(/^-+/, "") || "root").slice(0, 251)}--`;
|
|
40
|
+
}
|
|
10
41
|
function sendJson(res, status, body) {
|
|
11
42
|
res.writeHead(status, {
|
|
12
43
|
"content-type": "application/json",
|
|
@@ -357,7 +388,7 @@ function registerSyncInternalRoutes(ctx, state, nodeSync, sessionSync) {
|
|
|
357
388
|
const body = await readJsonBody(req);
|
|
358
389
|
const sessionId = typeof body?.sessionId === "string" ? body.sessionId : "";
|
|
359
390
|
const remotePath = typeof body?.remotePath === "string" ? body.remotePath : "";
|
|
360
|
-
if (
|
|
391
|
+
if (!/^session-[A-Za-z0-9._-]*$/.test(sessionId) || !remotePath.startsWith("/")) {
|
|
361
392
|
sendJson(res, 400, {
|
|
362
393
|
ok: false,
|
|
363
394
|
code: "session-request-invalid",
|
|
@@ -376,9 +407,9 @@ function registerSyncInternalRoutes(ctx, state, nodeSync, sessionSync) {
|
|
|
376
407
|
}
|
|
377
408
|
let payload;
|
|
378
409
|
for (const mapping of mappings) {
|
|
379
|
-
const home = mapping.localPath
|
|
380
|
-
if (home ===
|
|
381
|
-
const sessionDir = join(home, "sessions",
|
|
410
|
+
const home = homeFromMirrorPath(mapping.localPath);
|
|
411
|
+
if (home === void 0) continue;
|
|
412
|
+
const sessionDir = join(home, "sessions", projectKey(mapping.localPath), sessionId);
|
|
382
413
|
try {
|
|
383
414
|
const data = readFileSync(join(sessionDir, "session.v4.jsonl.zstd"));
|
|
384
415
|
if (data.length < 64) continue;
|