@ddtcorex/dsh-maestro-core 0.15.0 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -7
- package/assets/icon.svg +4 -0
- package/cordis.patch.yml +0 -12
- package/lib/client.js +3 -1744
- package/lib/health-poller.js +1 -1
- package/lib/self-kill-guard.d.ts +25 -8
- package/lib/self-kill-guard.js +81 -27
- package/lib/types/client/config/components/BrandMark.d.ts +3 -3
- package/lib/types/client/index.d.ts.map +1 -1
- package/locale/en.json +6 -0
- package/package.json +9 -5
- package/src/client/config/components/BrandMark.tsx +3 -3
- package/src/client/index.tsx +0 -2
- package/src/host/health-poller.ts +1 -1
- package/src/host/self-kill-guard.ts +84 -26
- package/lib/sync/backup-config.d.ts +0 -55
- package/lib/sync/backup-config.js +0 -119
- package/lib/sync/backup-service.d.ts +0 -123
- package/lib/sync/backup-service.js +0 -486
- package/lib/sync/bidirectional.d.ts +0 -39
- package/lib/sync/bidirectional.js +0 -25
- package/lib/sync/cli.d.ts +0 -38
- package/lib/sync/cli.js +0 -528
- package/lib/sync/config.d.ts +0 -59
- package/lib/sync/config.js +0 -72
- package/lib/sync/fingerprint.d.ts +0 -29
- package/lib/sync/fingerprint.js +0 -65
- package/lib/sync/hashing.d.ts +0 -22
- package/lib/sync/hashing.js +0 -77
- package/lib/sync/index.d.ts +0 -6
- package/lib/sync/index.js +0 -619
- package/lib/sync/machine-id.d.ts +0 -29
- package/lib/sync/machine-id.js +0 -66
- package/lib/sync/merge.d.ts +0 -31
- package/lib/sync/merge.js +0 -86
- package/lib/sync/peer-host.d.ts +0 -22
- package/lib/sync/peer-host.js +0 -62
- package/lib/sync/process-runner.d.ts +0 -31
- package/lib/sync/process-runner.js +0 -161
- package/lib/sync/remote-agent.d.ts +0 -41
- package/lib/sync/remote-agent.js +0 -227
- package/lib/sync/remote-cache.d.ts +0 -18
- package/lib/sync/remote-cache.js +0 -60
- package/lib/sync/remote-manifest.d.ts +0 -33
- package/lib/sync/remote-manifest.js +0 -111
- package/lib/sync/s3-object-store.d.ts +0 -38
- package/lib/sync/s3-object-store.js +0 -126
- package/lib/sync/session-plan.d.ts +0 -29
- package/lib/sync/session-plan.js +0 -213
- package/lib/sync/sigv4.d.ts +0 -20
- package/lib/sync/sigv4.js +0 -57
- package/lib/sync/snapshot.d.ts +0 -16
- package/lib/sync/snapshot.js +0 -143
- package/lib/sync/ssh-mux.d.ts +0 -12
- package/lib/sync/ssh-mux.js +0 -48
- package/lib/sync/store-root.d.ts +0 -44
- package/lib/sync/store-root.js +0 -67
- package/lib/sync/sync-plan.d.ts +0 -24
- package/lib/sync/sync-plan.js +0 -366
- package/lib/sync/sync-service.d.ts +0 -181
- package/lib/sync/sync-service.js +0 -911
- package/lib/sync/sync-types.d.ts +0 -87
- package/lib/sync/sync-types.js +0 -1
- package/lib/sync/transport.d.ts +0 -75
- package/lib/sync/transport.js +0 -196
- package/lib/sync/tunnel-restore.d.ts +0 -77
- package/lib/sync/tunnel-restore.js +0 -142
- package/lib/sync/validation.d.ts +0 -12
- package/lib/sync/validation.js +0 -96
- package/lib/types/client/sync/R2SyncPanel.d.ts +0 -6
- package/lib/types/client/sync/R2SyncPanel.d.ts.map +0 -1
- package/lib/types/client/sync/SyncPanel.d.ts +0 -12
- package/lib/types/client/sync/SyncPanel.d.ts.map +0 -1
- package/lib/types/client/sync/confirm-dialog.d.ts +0 -43
- package/lib/types/client/sync/confirm-dialog.d.ts.map +0 -1
- package/lib/types/client/sync/index.d.ts +0 -10
- package/lib/types/client/sync/index.d.ts.map +0 -1
- package/lib/types/client/sync/ui.d.ts +0 -75
- package/lib/types/client/sync/ui.d.ts.map +0 -1
- package/lib/types/client/sync/use-backup.d.ts +0 -50
- package/lib/types/client/sync/use-backup.d.ts.map +0 -1
- package/lib/types/client/sync/use-sync.d.ts +0 -88
- package/lib/types/client/sync/use-sync.d.ts.map +0 -1
- package/src/client/sync/R2SyncPanel.tsx +0 -260
- package/src/client/sync/SyncPanel.tsx +0 -422
- package/src/client/sync/confirm-dialog.tsx +0 -202
- package/src/client/sync/index.tsx +0 -286
- package/src/client/sync/ui.tsx +0 -297
- package/src/client/sync/use-backup.ts +0 -207
- package/src/client/sync/use-sync.ts +0 -502
- package/src/host/sync/backup-config.ts +0 -158
- package/src/host/sync/backup-service.ts +0 -506
- package/src/host/sync/bidirectional.ts +0 -66
- package/src/host/sync/cli.ts +0 -530
- package/src/host/sync/config.ts +0 -96
- package/src/host/sync/fingerprint.ts +0 -83
- package/src/host/sync/hashing.ts +0 -91
- package/src/host/sync/index.ts +0 -697
- package/src/host/sync/machine-id.ts +0 -81
- package/src/host/sync/merge.ts +0 -99
- package/src/host/sync/peer-host.ts +0 -65
- package/src/host/sync/process-runner.ts +0 -177
- package/src/host/sync/remote-agent.ts +0 -223
- package/src/host/sync/remote-cache.ts +0 -68
- package/src/host/sync/remote-manifest.ts +0 -117
- package/src/host/sync/s3-object-store.ts +0 -144
- package/src/host/sync/session-plan.ts +0 -237
- package/src/host/sync/sigv4.ts +0 -81
- package/src/host/sync/snapshot.ts +0 -132
- package/src/host/sync/ssh-mux.ts +0 -55
- package/src/host/sync/store-root.ts +0 -83
- package/src/host/sync/sync-plan.ts +0 -366
- package/src/host/sync/sync-service.ts +0 -944
- package/src/host/sync/sync-types.ts +0 -102
- package/src/host/sync/transport.ts +0 -256
- package/src/host/sync/tunnel-restore.ts +0 -160
- package/src/host/sync/validation.ts +0 -104
|
@@ -1,123 +0,0 @@
|
|
|
1
|
-
import type { S3ObjectStore } from './s3-object-store.js';
|
|
2
|
-
import type { BackupTarget } from './backup-config.js';
|
|
3
|
-
export interface BackupManifestFile {
|
|
4
|
-
path: string;
|
|
5
|
-
sha256: string;
|
|
6
|
-
size: number;
|
|
7
|
-
blobKey: string;
|
|
8
|
-
}
|
|
9
|
-
export interface BackupManifest {
|
|
10
|
-
schema: 1;
|
|
11
|
-
hostId: string;
|
|
12
|
-
createdAt: string;
|
|
13
|
-
files: BackupManifestFile[];
|
|
14
|
-
}
|
|
15
|
-
export interface BackupPreview {
|
|
16
|
-
previewId: string;
|
|
17
|
-
revision: string;
|
|
18
|
-
expiresAt: string;
|
|
19
|
-
summary: {
|
|
20
|
-
identical: number;
|
|
21
|
-
missing: number;
|
|
22
|
-
addedBytes: number;
|
|
23
|
-
};
|
|
24
|
-
}
|
|
25
|
-
export interface BackupApplyResult {
|
|
26
|
-
ok: boolean;
|
|
27
|
-
revision: string;
|
|
28
|
-
committed: string[];
|
|
29
|
-
failures: SyncFailureLike[];
|
|
30
|
-
}
|
|
31
|
-
export interface SyncFailureLike {
|
|
32
|
-
phase: string;
|
|
33
|
-
code: string;
|
|
34
|
-
detail: string;
|
|
35
|
-
path?: string;
|
|
36
|
-
}
|
|
37
|
-
export declare class BackupService {
|
|
38
|
-
private readonly opts;
|
|
39
|
-
constructor(opts: {
|
|
40
|
-
localDsh: string;
|
|
41
|
-
storeRoot?: string;
|
|
42
|
-
store: S3ObjectStore;
|
|
43
|
-
target: BackupTarget;
|
|
44
|
-
previewDir: string;
|
|
45
|
-
cacheDir: string;
|
|
46
|
-
fs?: any;
|
|
47
|
-
});
|
|
48
|
-
/**
|
|
49
|
-
* The store may live outside the DSH home. Reads and writes of memory content map
|
|
50
|
-
* through the resolved root; sessions and sync state stay under the DSH home.
|
|
51
|
-
*/
|
|
52
|
-
private resolveStoreRoot;
|
|
53
|
-
private localPathForWirePath;
|
|
54
|
-
blobKey(sha: string): string;
|
|
55
|
-
/**
|
|
56
|
-
* A backup taken in the core-first release window would walk a root that does not
|
|
57
|
-
* exist yet, record zero memory files, and report `ok: true`. Refuse instead, with
|
|
58
|
-
* the same sentinel sync uses.
|
|
59
|
-
*/
|
|
60
|
-
assertStoreMigrated(): void;
|
|
61
|
-
listEligibleFiles(): string[];
|
|
62
|
-
readHeadManifest(): Promise<{
|
|
63
|
-
key: string;
|
|
64
|
-
manifest: BackupManifest;
|
|
65
|
-
} | null>;
|
|
66
|
-
private localHashes;
|
|
67
|
-
preview(fileList?: {
|
|
68
|
-
path: string;
|
|
69
|
-
sha256: string;
|
|
70
|
-
size: number;
|
|
71
|
-
}[]): Promise<BackupPreview>;
|
|
72
|
-
/**
|
|
73
|
-
* Backup apply — the ONLY bucket-mutation route (spec §5.5):
|
|
74
|
-
* 1. load the persisted preview (single-use, 60s TTL);
|
|
75
|
-
* 2. re-hash local (freshest) and compare against the current HEAD manifest;
|
|
76
|
-
* 3. PUT missing blobs (putIfAbsent — idempotent by content-addressing);
|
|
77
|
-
* 4. PUT a new immutable manifest (unique key);
|
|
78
|
-
* 5. CAS-advance HEAD (If-Match old etag / If-None-Match when absent).
|
|
79
|
-
* ok:true only after HEAD advances; blob PUTs are retry-safe.
|
|
80
|
-
*/
|
|
81
|
-
apply(req: {
|
|
82
|
-
previewId: string;
|
|
83
|
-
confirm: true;
|
|
84
|
-
}): Promise<BackupApplyResult>;
|
|
85
|
-
restorePreview(opts: {
|
|
86
|
-
mode: 'new-dir' | 'in-place';
|
|
87
|
-
}): Promise<{
|
|
88
|
-
previewId: string;
|
|
89
|
-
expiresAt: string;
|
|
90
|
-
mode: 'new-dir' | 'in-place';
|
|
91
|
-
summary: {
|
|
92
|
-
copied: number;
|
|
93
|
-
merged: number;
|
|
94
|
-
skipped: number;
|
|
95
|
-
conflicts: number;
|
|
96
|
-
};
|
|
97
|
-
}>;
|
|
98
|
-
restoreApply(req: {
|
|
99
|
-
previewId: string;
|
|
100
|
-
mode: 'new-dir' | 'in-place';
|
|
101
|
-
destDir?: string;
|
|
102
|
-
confirm: true;
|
|
103
|
-
}): Promise<BackupApplyResult>;
|
|
104
|
-
gcPreview(opts?: {
|
|
105
|
-
keepDaily?: number;
|
|
106
|
-
keepMonthly?: number;
|
|
107
|
-
}): Promise<{
|
|
108
|
-
retainedManifests: number;
|
|
109
|
-
trashManifests: number;
|
|
110
|
-
deletableBlobs: string[];
|
|
111
|
-
freedBytes: number;
|
|
112
|
-
previewId: string;
|
|
113
|
-
}>;
|
|
114
|
-
gcApply(req: {
|
|
115
|
-
previewId: string;
|
|
116
|
-
confirm: true;
|
|
117
|
-
}): Promise<{
|
|
118
|
-
ok: boolean;
|
|
119
|
-
deleted: number;
|
|
120
|
-
freedBytes: number;
|
|
121
|
-
}>;
|
|
122
|
-
private readManifestKey;
|
|
123
|
-
}
|
|
@@ -1,486 +0,0 @@
|
|
|
1
|
-
// src/host/backup-service.ts — R2/S3 backup engine (spec §5.4–§5.6, decision C).
|
|
2
|
-
//
|
|
3
|
-
// Layout: blobs/sha256/<sha> (immutable, content-addressed) + manifests/<ts>-<id>
|
|
4
|
-
// (immutable snapshot) + HEAD (CAS pointer). preview() is READ-ONLY: it compares
|
|
5
|
-
// the current eligible local hashes against the HEAD manifest (no object
|
|
6
|
-
// download, no upload). apply() is the only bucket-mutation route: PUT missing
|
|
7
|
-
// blobs (idempotent by sha) → PUT a fresh immutable manifest → CAS-advance HEAD.
|
|
8
|
-
// Restore and GC arrive in later tasks of the same module.
|
|
9
|
-
import * as nodeFs from 'node:fs';
|
|
10
|
-
import * as path from 'node:path';
|
|
11
|
-
import { randomBytes, createHash } from 'node:crypto';
|
|
12
|
-
import { normalizeEligiblePath } from './validation.js';
|
|
13
|
-
import { hashWirePaths } from './hashing.js';
|
|
14
|
-
import { localPathForWirePath, resolveStoreRoot } from './store-root.js';
|
|
15
|
-
import { loadIndex, saveIndex, probeIndex, matchesStat, statFingerprint } from './fingerprint.js';
|
|
16
|
-
const TTL_MS = 60_000;
|
|
17
|
-
export class BackupService {
|
|
18
|
-
opts;
|
|
19
|
-
constructor(opts) {
|
|
20
|
-
this.opts = opts;
|
|
21
|
-
}
|
|
22
|
-
/**
|
|
23
|
-
* The store may live outside the DSH home. Reads and writes of memory content map
|
|
24
|
-
* through the resolved root; sessions and sync state stay under the DSH home.
|
|
25
|
-
*/
|
|
26
|
-
resolveStoreRoot() {
|
|
27
|
-
return (this.opts.storeRoot ??
|
|
28
|
-
resolveStoreRoot({ env: { ...process.env, DSH_HOME: this.opts.localDsh } }).root);
|
|
29
|
-
}
|
|
30
|
-
localPathForWirePath(wirePath) {
|
|
31
|
-
return localPathForWirePath(wirePath, { storeRoot: this.resolveStoreRoot(), localDsh: this.opts.localDsh });
|
|
32
|
-
}
|
|
33
|
-
blobKey(sha) {
|
|
34
|
-
return `blobs/sha256/${sha}`;
|
|
35
|
-
}
|
|
36
|
-
/**
|
|
37
|
-
* A backup taken in the core-first release window would walk a root that does not
|
|
38
|
-
* exist yet, record zero memory files, and report `ok: true`. Refuse instead, with
|
|
39
|
-
* the same sentinel sync uses.
|
|
40
|
-
*/
|
|
41
|
-
assertStoreMigrated() {
|
|
42
|
-
const fsMod = this.opts.fs ?? nodeFs;
|
|
43
|
-
if (typeof fsMod.existsSync !== 'function')
|
|
44
|
-
return;
|
|
45
|
-
const storeRoot = this.resolveStoreRoot();
|
|
46
|
-
const exists = (p) => {
|
|
47
|
-
try {
|
|
48
|
-
return fsMod.existsSync(p);
|
|
49
|
-
}
|
|
50
|
-
catch {
|
|
51
|
-
return false;
|
|
52
|
-
}
|
|
53
|
-
};
|
|
54
|
-
if (!exists(storeRoot) && exists(path.join(this.opts.localDsh, 'maestro-memory'))) {
|
|
55
|
-
const error = new Error(`local store is still at ${path.join(this.opts.localDsh, 'maestro-memory')}; install the current build (its boot migration moves it to ${storeRoot}) before backing up`);
|
|
56
|
-
error.code = 'STORE_NOT_MIGRATED';
|
|
57
|
-
throw error;
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
listEligibleFiles() {
|
|
61
|
-
this.assertStoreMigrated();
|
|
62
|
-
const root = this.opts.localDsh;
|
|
63
|
-
const storeRoot = this.resolveStoreRoot();
|
|
64
|
-
const fsMod = this.opts.fs ?? nodeFs;
|
|
65
|
-
const out = [];
|
|
66
|
-
// `prefix` is the wire prefix of the directory being walked, so a store outside the
|
|
67
|
-
// DSH home still reports `maestro-memory/...` and passes normalization.
|
|
68
|
-
const walk = (dir, prefix = '') => {
|
|
69
|
-
let ents;
|
|
70
|
-
try {
|
|
71
|
-
ents = fsMod.readdirSync(dir, { withFileTypes: true });
|
|
72
|
-
}
|
|
73
|
-
catch {
|
|
74
|
-
return;
|
|
75
|
-
}
|
|
76
|
-
for (const ent of ents) {
|
|
77
|
-
const full = path.join(dir, ent.name);
|
|
78
|
-
if (typeof ent.isDirectory === 'function' && ent.isDirectory()) {
|
|
79
|
-
if (!['node_modules', '.git', '.supervisor', 'profiles'].includes(ent.name)) {
|
|
80
|
-
walk(full, prefix ? `${prefix}/${ent.name}` : ent.name);
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
else {
|
|
84
|
-
const rel = (prefix ? `${prefix}/${ent.name}` : ent.name).split(path.sep).join('/');
|
|
85
|
-
try {
|
|
86
|
-
normalizeEligiblePath(rel);
|
|
87
|
-
out.push(rel);
|
|
88
|
-
}
|
|
89
|
-
catch { }
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
};
|
|
93
|
-
try {
|
|
94
|
-
walk(storeRoot, 'maestro-memory');
|
|
95
|
-
// When the store sits inside the DSH home its files were already collected above,
|
|
96
|
-
// so sessions alone are walked from there.
|
|
97
|
-
walk(path.join(root, 'sessions'), 'sessions');
|
|
98
|
-
}
|
|
99
|
-
catch { }
|
|
100
|
-
return out.sort();
|
|
101
|
-
}
|
|
102
|
-
async readHeadManifest() {
|
|
103
|
-
const headKey = `${this.opts.target.prefix}HEAD`;
|
|
104
|
-
const head = await this.opts.store.head(this.opts.target.bucket, headKey);
|
|
105
|
-
if (!head)
|
|
106
|
-
return null;
|
|
107
|
-
const tmp = path.join(require('node:os').tmpdir(), `bk-head-${randomBytes(4).toString('hex')}`);
|
|
108
|
-
nodeFs.mkdirSync(tmp, { recursive: true });
|
|
109
|
-
try {
|
|
110
|
-
await this.opts.store.get(this.opts.target.bucket, headKey, tmp);
|
|
111
|
-
const headBody = JSON.parse(nodeFs.readFileSync(path.join(tmp, headKey), 'utf-8'));
|
|
112
|
-
await this.opts.store.get(this.opts.target.bucket, headBody.manifestKey, tmp);
|
|
113
|
-
const manifest = JSON.parse(nodeFs.readFileSync(path.join(tmp, headBody.manifestKey), 'utf-8'));
|
|
114
|
-
return { key: headBody.manifestKey, manifest };
|
|
115
|
-
}
|
|
116
|
-
finally {
|
|
117
|
-
try {
|
|
118
|
-
nodeFs.rmSync(tmp, { recursive: true, force: true });
|
|
119
|
-
}
|
|
120
|
-
catch { }
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
async localHashes() {
|
|
124
|
-
const fsMod = this.opts.fs ?? nodeFs;
|
|
125
|
-
const paths = this.listEligibleFiles();
|
|
126
|
-
const index = loadIndex(this.opts.cacheDir);
|
|
127
|
-
const stale = [];
|
|
128
|
-
const local = [];
|
|
129
|
-
for (const rel of paths) {
|
|
130
|
-
const full = this.localPathForWirePath(rel);
|
|
131
|
-
try {
|
|
132
|
-
const st = fsMod.statSync(full, { bigint: true });
|
|
133
|
-
const e = probeIndex(rel, index);
|
|
134
|
-
if (e && matchesStat(e, st))
|
|
135
|
-
local.push({ path: rel, sha256: e.sha256, size: e.size });
|
|
136
|
-
else
|
|
137
|
-
stale.push(rel);
|
|
138
|
-
}
|
|
139
|
-
catch {
|
|
140
|
-
stale.push(rel);
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
const hashed = await hashWirePaths(fsMod, { storeRoot: this.resolveStoreRoot(), localDsh: this.opts.localDsh }, stale);
|
|
144
|
-
for (const f of hashed) {
|
|
145
|
-
local.push({ path: f.path, sha256: f.sha256, size: f.size });
|
|
146
|
-
try {
|
|
147
|
-
const st = fsMod.statSync(this.localPathForWirePath(f.path), { bigint: true });
|
|
148
|
-
index.entries[f.path] = { ...statFingerprint(st), sha256: f.sha256 };
|
|
149
|
-
}
|
|
150
|
-
catch { }
|
|
151
|
-
}
|
|
152
|
-
if (hashed.length > 0)
|
|
153
|
-
saveIndex(this.opts.cacheDir, index);
|
|
154
|
-
return local.sort((a, b) => a.path.localeCompare(b.path));
|
|
155
|
-
}
|
|
156
|
-
async preview(fileList) {
|
|
157
|
-
// fileList override exists for tests; production uses the fresh local hashes.
|
|
158
|
-
const local = fileList ?? (await this.localHashes());
|
|
159
|
-
const prev = await this.readHeadManifest();
|
|
160
|
-
const prevByPath = new Map((prev?.manifest.files ?? []).map((f) => [f.path, f]));
|
|
161
|
-
let identical = 0;
|
|
162
|
-
let missing = 0;
|
|
163
|
-
let addedBytes = 0;
|
|
164
|
-
for (const f of local) {
|
|
165
|
-
const p = prevByPath.get(f.path);
|
|
166
|
-
if (p && p.sha256 === f.sha256)
|
|
167
|
-
identical++;
|
|
168
|
-
else {
|
|
169
|
-
missing++;
|
|
170
|
-
addedBytes += f.size;
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
const previewId = randomBytes(16).toString('hex');
|
|
174
|
-
const preview = {
|
|
175
|
-
previewId,
|
|
176
|
-
revision: createHash('sha256').update(JSON.stringify(local)).digest('hex').slice(0, 16),
|
|
177
|
-
expiresAt: new Date(Date.now() + TTL_MS).toISOString(),
|
|
178
|
-
summary: { identical, missing, addedBytes },
|
|
179
|
-
};
|
|
180
|
-
nodeFs.mkdirSync(this.opts.previewDir, { recursive: true, mode: 0o700 });
|
|
181
|
-
nodeFs.writeFileSync(path.join(this.opts.previewDir, `${previewId}.backup.json`), JSON.stringify(preview), 'utf-8');
|
|
182
|
-
return preview;
|
|
183
|
-
}
|
|
184
|
-
/**
|
|
185
|
-
* Backup apply — the ONLY bucket-mutation route (spec §5.5):
|
|
186
|
-
* 1. load the persisted preview (single-use, 60s TTL);
|
|
187
|
-
* 2. re-hash local (freshest) and compare against the current HEAD manifest;
|
|
188
|
-
* 3. PUT missing blobs (putIfAbsent — idempotent by content-addressing);
|
|
189
|
-
* 4. PUT a new immutable manifest (unique key);
|
|
190
|
-
* 5. CAS-advance HEAD (If-Match old etag / If-None-Match when absent).
|
|
191
|
-
* ok:true only after HEAD advances; blob PUTs are retry-safe.
|
|
192
|
-
*/
|
|
193
|
-
async apply(req) {
|
|
194
|
-
if (req.confirm !== true) {
|
|
195
|
-
throw Object.assign(new Error('backup apply requires confirm:true'), { phase: 'validate', code: 'CONFIRM_REQUIRED' });
|
|
196
|
-
}
|
|
197
|
-
const pvPath = path.join(this.opts.previewDir, `${req.previewId}.backup.json`);
|
|
198
|
-
let saved;
|
|
199
|
-
try {
|
|
200
|
-
saved = JSON.parse(nodeFs.readFileSync(pvPath, 'utf-8'));
|
|
201
|
-
}
|
|
202
|
-
catch {
|
|
203
|
-
throw Object.assign(new Error('backup preview not found or expired'), { phase: 'validate', code: 'STALE_PREVIEW' });
|
|
204
|
-
}
|
|
205
|
-
if (new Date(saved.expiresAt).getTime() <= Date.now()) {
|
|
206
|
-
try {
|
|
207
|
-
nodeFs.rmSync(pvPath, { force: true });
|
|
208
|
-
}
|
|
209
|
-
catch { }
|
|
210
|
-
throw Object.assign(new Error('backup preview expired'), { phase: 'validate', code: 'STALE_PREVIEW' });
|
|
211
|
-
}
|
|
212
|
-
const failures = [];
|
|
213
|
-
const committed = [];
|
|
214
|
-
let fresh;
|
|
215
|
-
try {
|
|
216
|
-
fresh = await this.preview();
|
|
217
|
-
}
|
|
218
|
-
catch (e) {
|
|
219
|
-
// The store is unreachable/broken: fail closed with a structured journal —
|
|
220
|
-
// apply must never throw a raw network error after the preview gate.
|
|
221
|
-
try {
|
|
222
|
-
nodeFs.rmSync(pvPath, { force: true });
|
|
223
|
-
}
|
|
224
|
-
catch { }
|
|
225
|
-
return { ok: false, revision: saved.revision, committed: [], failures: [{ phase: 'backup', code: 'PREVIEW_REFRESH_FAILED', detail: e?.message ?? String(e) }] };
|
|
226
|
-
}
|
|
227
|
-
const prev = await this.readHeadManifest();
|
|
228
|
-
const prevByPath = new Map((prev?.manifest.files ?? []).map((f) => [f.path, f]));
|
|
229
|
-
const localPaths = this.listEligibleFiles();
|
|
230
|
-
const files = [];
|
|
231
|
-
const fsMod = this.opts.fs ?? nodeFs;
|
|
232
|
-
for (const rel of localPaths) {
|
|
233
|
-
const prevFile = prevByPath.get(rel);
|
|
234
|
-
// Fast path: bytes already backed up under the same sha — reuse, skip read+PUT.
|
|
235
|
-
const index = loadIndex(this.opts.cacheDir);
|
|
236
|
-
const entry = probeIndex(rel, index);
|
|
237
|
-
let sha = null;
|
|
238
|
-
let size = 0;
|
|
239
|
-
if (entry && prevFile && entry.sha256 === prevFile.sha256) {
|
|
240
|
-
sha = entry.sha256;
|
|
241
|
-
size = entry.size;
|
|
242
|
-
}
|
|
243
|
-
if (sha === null) {
|
|
244
|
-
try {
|
|
245
|
-
const buf = fsMod.readFileSync(this.localPathForWirePath(rel));
|
|
246
|
-
const b = Buffer.isBuffer(buf) ? buf : Buffer.from(String(buf), 'utf-8');
|
|
247
|
-
sha = createHash('sha256').update(b).digest('hex');
|
|
248
|
-
size = b.length;
|
|
249
|
-
const key = `${this.opts.target.prefix}${this.blobKey(sha)}`;
|
|
250
|
-
try {
|
|
251
|
-
await this.opts.store.putIfAbsent(this.opts.target.bucket, key, b);
|
|
252
|
-
}
|
|
253
|
-
catch (e) {
|
|
254
|
-
failures.push({ phase: 'backup', code: 'UPLOAD_FAILED', detail: e?.message ?? String(e), path: rel });
|
|
255
|
-
continue;
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
catch (e) {
|
|
259
|
-
failures.push({ phase: 'backup', code: 'READ_FAILED', detail: e?.message ?? String(e), path: rel });
|
|
260
|
-
continue;
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
files.push({ path: rel, sha256: sha, size, blobKey: this.blobKey(sha) });
|
|
264
|
-
}
|
|
265
|
-
void fresh;
|
|
266
|
-
if (failures.length === 0) {
|
|
267
|
-
const ts = new Date().toISOString().replace(/[:.]/g, '-');
|
|
268
|
-
const manifest = { schema: 1, hostId: this.opts.target.hostId, createdAt: new Date().toISOString(), files };
|
|
269
|
-
const manifestKey = `${this.opts.target.prefix}manifests/${ts}-${randomBytes(4).toString('hex')}.json`;
|
|
270
|
-
try {
|
|
271
|
-
await this.opts.store.putIfAbsent(this.opts.target.bucket, manifestKey, Buffer.from(JSON.stringify(manifest)));
|
|
272
|
-
}
|
|
273
|
-
catch (e) {
|
|
274
|
-
failures.push({ phase: 'backup', code: 'MANIFEST_PUT_FAILED', detail: e?.message ?? String(e), path: manifestKey });
|
|
275
|
-
}
|
|
276
|
-
if (failures.length === 0) {
|
|
277
|
-
const headKey = `${this.opts.target.prefix}HEAD`;
|
|
278
|
-
const old = await this.opts.store.head(this.opts.target.bucket, headKey);
|
|
279
|
-
try {
|
|
280
|
-
await this.opts.store.putConditional(this.opts.target.bucket, headKey, Buffer.from(JSON.stringify({ manifestKey })), old ? { ifMatch: old.etag } : { ifNoneMatch: true });
|
|
281
|
-
committed.push(...files.map((f) => f.path));
|
|
282
|
-
}
|
|
283
|
-
catch (e) {
|
|
284
|
-
failures.push({ phase: 'backup', code: e?.code === 'CONCURRENT_MODIFICATION' ? 'CONCURRENT_MODIFICATION' : 'HEAD_UPDATE_FAILED', detail: e?.message ?? String(e), path: headKey });
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
try {
|
|
289
|
-
nodeFs.rmSync(pvPath, { force: true });
|
|
290
|
-
}
|
|
291
|
-
catch { }
|
|
292
|
-
return { ok: failures.length === 0, revision: saved.revision, committed, failures };
|
|
293
|
-
}
|
|
294
|
-
// ---- restore (spec §5.6): preview read-only; apply is the only mutation ----
|
|
295
|
-
async restorePreview(opts) {
|
|
296
|
-
const head = await this.readHeadManifest();
|
|
297
|
-
if (!head)
|
|
298
|
-
throw Object.assign(new Error('no backup to restore (no HEAD)'), { phase: 'restore', code: 'NO_BACKUP' });
|
|
299
|
-
const fsMod = this.opts.fs ?? nodeFs;
|
|
300
|
-
let copied = 0;
|
|
301
|
-
let merged = 0;
|
|
302
|
-
let skipped = 0;
|
|
303
|
-
let conflicts = 0;
|
|
304
|
-
for (const f of head.manifest.files) {
|
|
305
|
-
if (opts.mode === 'new-dir') {
|
|
306
|
-
copied++;
|
|
307
|
-
continue;
|
|
308
|
-
}
|
|
309
|
-
const full = this.localPathForWirePath(f.path);
|
|
310
|
-
let cur = null;
|
|
311
|
-
try {
|
|
312
|
-
cur = createHash('sha256').update(fsMod.readFileSync(full)).digest('hex');
|
|
313
|
-
}
|
|
314
|
-
catch { }
|
|
315
|
-
if (cur === f.sha256)
|
|
316
|
-
skipped++;
|
|
317
|
-
else if (cur === null)
|
|
318
|
-
copied++;
|
|
319
|
-
else
|
|
320
|
-
merged++;
|
|
321
|
-
}
|
|
322
|
-
const previewId = randomBytes(16).toString('hex');
|
|
323
|
-
const preview = { previewId, expiresAt: new Date(Date.now() + TTL_MS).toISOString(), mode: opts.mode, summary: { copied, merged, skipped, conflicts } };
|
|
324
|
-
nodeFs.writeFileSync(path.join(this.opts.previewDir, `${previewId}.restore.json`), JSON.stringify(preview), 'utf-8');
|
|
325
|
-
return preview;
|
|
326
|
-
}
|
|
327
|
-
async restoreApply(req) {
|
|
328
|
-
if (req.confirm !== true)
|
|
329
|
-
throw Object.assign(new Error('restore apply requires confirm:true'), { phase: 'validate', code: 'CONFIRM_REQUIRED' });
|
|
330
|
-
const pvPath = path.join(this.opts.previewDir, `${req.previewId}.restore.json`);
|
|
331
|
-
let saved;
|
|
332
|
-
try {
|
|
333
|
-
saved = JSON.parse(nodeFs.readFileSync(pvPath, 'utf-8'));
|
|
334
|
-
}
|
|
335
|
-
catch {
|
|
336
|
-
throw Object.assign(new Error('restore preview not found or expired'), { phase: 'validate', code: 'STALE_PREVIEW' });
|
|
337
|
-
}
|
|
338
|
-
if (saved.mode !== req.mode)
|
|
339
|
-
throw Object.assign(new Error('restore preview mode mismatch'), { phase: 'validate', code: 'DIRECTION_MISMATCH' });
|
|
340
|
-
const head = await this.readHeadManifest();
|
|
341
|
-
if (!head)
|
|
342
|
-
throw Object.assign(new Error('no backup to restore (no HEAD)'), { phase: 'restore', code: 'NO_BACKUP' });
|
|
343
|
-
const fsMod = this.opts.fs ?? nodeFs;
|
|
344
|
-
const tmp = path.join(require('node:os').tmpdir(), `restore-${randomBytes(4).toString('hex')}`);
|
|
345
|
-
nodeFs.mkdirSync(tmp, { recursive: true });
|
|
346
|
-
const failures = [];
|
|
347
|
-
const committed = [];
|
|
348
|
-
try {
|
|
349
|
-
for (const f of head.manifest.files) {
|
|
350
|
-
try {
|
|
351
|
-
// In place means "into the live store", which is the resolved root, not the
|
|
352
|
-
// DSH home. Getting this wrong recreates the legacy directory on restore.
|
|
353
|
-
const outFull = req.mode === 'new-dir'
|
|
354
|
-
? path.join(req.destDir ?? path.join(this.opts.localDsh, 'restored'), f.path)
|
|
355
|
-
: this.localPathForWirePath(f.path);
|
|
356
|
-
if (req.mode === 'in-place') {
|
|
357
|
-
try {
|
|
358
|
-
const cur = createHash('sha256').update(fsMod.readFileSync(outFull)).digest('hex');
|
|
359
|
-
if (cur === f.sha256)
|
|
360
|
-
continue; // byte-identical: skip
|
|
361
|
-
}
|
|
362
|
-
catch { }
|
|
363
|
-
}
|
|
364
|
-
const fullKey = `${this.opts.target.prefix}${f.blobKey}`;
|
|
365
|
-
await this.opts.store.get(this.opts.target.bucket, fullKey, tmp);
|
|
366
|
-
const staged = path.join(tmp, fullKey);
|
|
367
|
-
const buf = fsMod.readFileSync(staged);
|
|
368
|
-
if (createHash('sha256').update(buf).digest('hex') !== f.sha256) {
|
|
369
|
-
throw Object.assign(new Error('blob checksum mismatch'), { phase: 'restore', code: 'CHECKSUM_MISMATCH' });
|
|
370
|
-
}
|
|
371
|
-
// In-place: keep a timestamped backup of the target before overwrite.
|
|
372
|
-
if (req.mode === 'in-place' && fsMod.existsSync(outFull)) {
|
|
373
|
-
const bak = `${outFull}.bak.${Date.now()}.${randomBytes(4).toString('hex')}`;
|
|
374
|
-
fsMod.writeFileSync(bak, fsMod.readFileSync(outFull));
|
|
375
|
-
}
|
|
376
|
-
fsMod.mkdirSync(path.dirname(outFull), { recursive: true });
|
|
377
|
-
const tmpFile = `${outFull}.tmp.${randomBytes(4).toString('hex')}`;
|
|
378
|
-
fsMod.writeFileSync(tmpFile, buf);
|
|
379
|
-
try {
|
|
380
|
-
const fd = fsMod.openSync(tmpFile, 'r');
|
|
381
|
-
try {
|
|
382
|
-
fsMod.fsyncSync(fd);
|
|
383
|
-
}
|
|
384
|
-
finally {
|
|
385
|
-
fsMod.closeSync(fd);
|
|
386
|
-
}
|
|
387
|
-
}
|
|
388
|
-
catch { }
|
|
389
|
-
fsMod.renameSync(tmpFile, outFull);
|
|
390
|
-
committed.push(f.path);
|
|
391
|
-
}
|
|
392
|
-
catch (e) {
|
|
393
|
-
failures.push({ phase: 'restore', code: e?.code ?? 'RESTORE_FAILED', detail: e?.message ?? String(e), path: f.path });
|
|
394
|
-
}
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
finally {
|
|
398
|
-
try {
|
|
399
|
-
nodeFs.rmSync(tmp, { recursive: true, force: true });
|
|
400
|
-
}
|
|
401
|
-
catch { }
|
|
402
|
-
}
|
|
403
|
-
try {
|
|
404
|
-
nodeFs.rmSync(pvPath, { force: true });
|
|
405
|
-
}
|
|
406
|
-
catch { }
|
|
407
|
-
return { ok: failures.length === 0, revision: '', committed, failures };
|
|
408
|
-
}
|
|
409
|
-
// ---- retention GC (spec §5.7): preview read-only; apply deletes unreachable blobs ----
|
|
410
|
-
async gcPreview(opts = {}) {
|
|
411
|
-
const prefix = this.opts.target.prefix;
|
|
412
|
-
const all = (await this.opts.store.list(this.opts.target.bucket, `${prefix}manifests/`)).map((e) => e.key);
|
|
413
|
-
const byDay = new Map();
|
|
414
|
-
const byMonth = new Map();
|
|
415
|
-
for (const key of all) {
|
|
416
|
-
const head = await this.readManifestKey(key);
|
|
417
|
-
const d = head.createdAt;
|
|
418
|
-
const day = d.slice(0, 10);
|
|
419
|
-
const month = d.slice(0, 7);
|
|
420
|
-
const curDay = byDay.get(day);
|
|
421
|
-
if (!curDay || key > curDay)
|
|
422
|
-
byDay.set(day, key);
|
|
423
|
-
const curMonth = byMonth.get(month);
|
|
424
|
-
if (!curMonth || key > curMonth)
|
|
425
|
-
byMonth.set(month, key);
|
|
426
|
-
}
|
|
427
|
-
const keepDaily = opts.keepDaily ?? 30;
|
|
428
|
-
const keepMonthly = opts.keepMonthly ?? 12;
|
|
429
|
-
const days = [...byDay.keys()].sort().slice(-keepDaily);
|
|
430
|
-
const months = [...byMonth.keys()].sort().slice(-keepMonthly);
|
|
431
|
-
const retained = new Set();
|
|
432
|
-
for (const d of days)
|
|
433
|
-
retained.add(byDay.get(d));
|
|
434
|
-
for (const m of months)
|
|
435
|
-
retained.add(byMonth.get(m));
|
|
436
|
-
const reachable = new Set();
|
|
437
|
-
for (const key of retained) {
|
|
438
|
-
const m = await this.readManifestKey(key);
|
|
439
|
-
for (const f of m.files)
|
|
440
|
-
reachable.add(this.blobKey(f.sha256));
|
|
441
|
-
}
|
|
442
|
-
const allBlobs = (await this.opts.store.list(this.opts.target.bucket, `${prefix}blobs/`)).map((e) => e.key.replace(prefix, ''));
|
|
443
|
-
const deletable = allBlobs.filter((k) => !reachable.has(k));
|
|
444
|
-
let freedBytes = 0;
|
|
445
|
-
for (const k of deletable) {
|
|
446
|
-
const head = await this.opts.store.head(this.opts.target.bucket, `${prefix}${k}`);
|
|
447
|
-
freedBytes += head?.size ?? 0;
|
|
448
|
-
}
|
|
449
|
-
const previewId = randomBytes(16).toString('hex');
|
|
450
|
-
nodeFs.writeFileSync(path.join(this.opts.previewDir, `${previewId}.gc.json`), JSON.stringify({ previewId, deletable, freedBytes, ts: Date.now() }), 'utf-8');
|
|
451
|
-
return { retainedManifests: retained.size, trashManifests: all.length - retained.size, deletableBlobs: deletable, freedBytes, previewId };
|
|
452
|
-
}
|
|
453
|
-
async gcApply(req) {
|
|
454
|
-
if (req.confirm !== true)
|
|
455
|
-
throw Object.assign(new Error('gc apply requires confirm:true'), { phase: 'validate', code: 'CONFIRM_REQUIRED' });
|
|
456
|
-
const pvPath = path.join(this.opts.previewDir, `${req.previewId}.gc.json`);
|
|
457
|
-
let saved;
|
|
458
|
-
try {
|
|
459
|
-
saved = JSON.parse(nodeFs.readFileSync(pvPath, 'utf-8'));
|
|
460
|
-
}
|
|
461
|
-
catch {
|
|
462
|
-
throw Object.assign(new Error('gc preview not found or expired'), { phase: 'validate', code: 'STALE_PREVIEW' });
|
|
463
|
-
}
|
|
464
|
-
const prefix = this.opts.target.prefix;
|
|
465
|
-
await this.opts.store.deleteKeys(this.opts.target.bucket, saved.deletable.map((k) => `${prefix}${k}`));
|
|
466
|
-
try {
|
|
467
|
-
nodeFs.rmSync(pvPath, { force: true });
|
|
468
|
-
}
|
|
469
|
-
catch { }
|
|
470
|
-
return { ok: true, deleted: saved.deletable.length, freedBytes: saved.freedBytes };
|
|
471
|
-
}
|
|
472
|
-
async readManifestKey(key) {
|
|
473
|
-
const tmp = path.join(require('node:os').tmpdir(), `bk-mf-${randomBytes(4).toString('hex')}`);
|
|
474
|
-
nodeFs.mkdirSync(tmp, { recursive: true });
|
|
475
|
-
try {
|
|
476
|
-
await this.opts.store.get(this.opts.target.bucket, key, tmp);
|
|
477
|
-
return JSON.parse(nodeFs.readFileSync(path.join(tmp, key), 'utf-8'));
|
|
478
|
-
}
|
|
479
|
-
finally {
|
|
480
|
-
try {
|
|
481
|
-
nodeFs.rmSync(tmp, { recursive: true, force: true });
|
|
482
|
-
}
|
|
483
|
-
catch { }
|
|
484
|
-
}
|
|
485
|
-
}
|
|
486
|
-
}
|
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Bidirectional orchestration — one push-then-pull operation built from the
|
|
3
|
-
* existing per-direction preview/apply primitives.
|
|
4
|
-
*
|
|
5
|
-
* Each phase keeps the full safety contract (single-use preview, per-file
|
|
6
|
-
* CAS, fail closed); this module adds no new mutation route. The pull
|
|
7
|
-
* preview is minted only AFTER the push apply has landed, so it is exact.
|
|
8
|
-
* No auto-retry: the operator re-runs after reading the journal (union
|
|
9
|
-
* idempotence makes a re-run resume the unfinished phase).
|
|
10
|
-
*/
|
|
11
|
-
import type { SyncService, ApplyResult } from './sync-service.js';
|
|
12
|
-
import type { SyncScope, SyncPreview, SyncSummary, SyncFailure } from './sync-types.js';
|
|
13
|
-
export interface BidirectionalPreview {
|
|
14
|
-
/** Combined id — the push preview's id; the pull phase mints its own. */
|
|
15
|
-
previewId: string;
|
|
16
|
-
expiresAt: string;
|
|
17
|
-
/** Exact push plan. */
|
|
18
|
-
push: SyncPreview;
|
|
19
|
-
/** Pull plan projected BEFORE the push lands; recomputed exact at apply time. */
|
|
20
|
-
pullProjected: SyncPreview;
|
|
21
|
-
}
|
|
22
|
-
export interface BidirectionalResult {
|
|
23
|
-
ok: boolean;
|
|
24
|
-
push: ApplyResult;
|
|
25
|
-
/** Null when the push failed — pull never runs. */
|
|
26
|
-
pull: ApplyResult | null;
|
|
27
|
-
/** Final pull dry-run summary; all-skip means converged. Null when pull never ran. */
|
|
28
|
-
verification: SyncSummary | null;
|
|
29
|
-
committed: string[];
|
|
30
|
-
failures: SyncFailure[];
|
|
31
|
-
}
|
|
32
|
-
export declare function runBidirectionalPreview(svc: SyncService, opts: {
|
|
33
|
-
scope: SyncScope;
|
|
34
|
-
}): Promise<BidirectionalPreview>;
|
|
35
|
-
export declare function runBidirectionalApply(svc: SyncService, opts: {
|
|
36
|
-
previewId: string;
|
|
37
|
-
confirm: true;
|
|
38
|
-
scope: SyncScope;
|
|
39
|
-
}): Promise<BidirectionalResult>;
|
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
export async function runBidirectionalPreview(svc, opts) {
|
|
2
|
-
const push = await svc.preview({ direction: 'push', scope: opts.scope });
|
|
3
|
-
const pullProjected = await svc.preview({ direction: 'pull', scope: opts.scope });
|
|
4
|
-
return { previewId: push.previewId, expiresAt: push.expiresAt, push, pullProjected };
|
|
5
|
-
}
|
|
6
|
-
export async function runBidirectionalApply(svc, opts) {
|
|
7
|
-
if (opts.confirm !== true) {
|
|
8
|
-
throw Object.assign(new Error('bidirectional apply requires confirm:true'), { phase: 'validate', code: 'CONFIRM_REQUIRED' });
|
|
9
|
-
}
|
|
10
|
-
const push = await svc.apply({ previewId: opts.previewId, direction: 'push', confirm: true, scope: opts.scope });
|
|
11
|
-
if (!push.ok) {
|
|
12
|
-
return { ok: false, push, pull: null, verification: null, committed: [...push.committed], failures: [...push.failures] };
|
|
13
|
-
}
|
|
14
|
-
const pullPreview = await svc.preview({ direction: 'pull', scope: opts.scope });
|
|
15
|
-
const pull = await svc.apply({ previewId: pullPreview.previewId, direction: 'pull', confirm: true, scope: opts.scope });
|
|
16
|
-
const verify = await svc.preview({ direction: 'pull', scope: opts.scope });
|
|
17
|
-
return {
|
|
18
|
-
ok: pull.ok,
|
|
19
|
-
push,
|
|
20
|
-
pull,
|
|
21
|
-
verification: verify.summary,
|
|
22
|
-
committed: [...push.committed, ...pull.committed],
|
|
23
|
-
failures: [...push.failures, ...pull.failures],
|
|
24
|
-
};
|
|
25
|
-
}
|