dsh-plugin-syncer 0.0.0-stage → 0.2.1
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 +121 -2
- package/cordis.patch.yml +18 -0
- package/icon.svg +15 -0
- package/index.js +26 -0
- package/lib/apply.js +153 -0
- package/lib/config.js +101 -0
- package/lib/engine.js +625 -0
- package/lib/log.js +36 -0
- package/lib/merge.js +146 -0
- package/lib/snapshot.js +119 -0
- package/lib/token.js +37 -0
- package/lib/transport.js +283 -0
- package/lib/util.js +163 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +26 -4
package/lib/engine.js
ADDED
|
@@ -0,0 +1,625 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { createLogger } from './log.js'
|
|
4
|
+
import { normalizeConfig, stateDir as defaultStateDir, validateConfig } from './config.js'
|
|
5
|
+
import { createTransport } from './transport.js'
|
|
6
|
+
import { resolveToken } from './token.js'
|
|
7
|
+
import { installedVersion, readSnapshot } from './snapshot.js'
|
|
8
|
+
import { emptyDoc, mergeDocs, parseDoc, recordHash, recordOf } from './merge.js'
|
|
9
|
+
import { applyTarget } from './apply.js'
|
|
10
|
+
import { compareSemver, defaultDeviceId, ensureDir, isSemver, nowIso, readJson, sanitizeId, sha256, sleep, stableStringify, writeJson } from './util.js'
|
|
11
|
+
|
|
12
|
+
const MAX_BACKOFF_MS = 60 * 1000
|
|
13
|
+
const WAIT_FOR_PLUGIN_MS = 30_000
|
|
14
|
+
|
|
15
|
+
export class SyncEngine {
|
|
16
|
+
constructor(ctx, rawConfig, options = {}) {
|
|
17
|
+
this.ctx = ctx
|
|
18
|
+
this.cfg = normalizeConfig(rawConfig)
|
|
19
|
+
this.stateDir = options.stateDir || defaultStateDir()
|
|
20
|
+
this.profileDir = options.profileDir || ctx.get('profileContext')?.dir || ''
|
|
21
|
+
this.profileKey = sha256(this.profileDir || 'no-profile').slice(0, 10)
|
|
22
|
+
this.log = createLogger({
|
|
23
|
+
file: path.join(this.stateDir, `sync-${this.profileKey}.log`),
|
|
24
|
+
level: this.cfg.logLevel,
|
|
25
|
+
echo: (line) => {
|
|
26
|
+
try {
|
|
27
|
+
console.warn(line)
|
|
28
|
+
} catch {}
|
|
29
|
+
},
|
|
30
|
+
})
|
|
31
|
+
this.statusFile = path.join(this.stateDir, `status-${this.profileKey}.json`)
|
|
32
|
+
this.stateFile = path.join(this.stateDir, `state-${this.profileKey}.json`)
|
|
33
|
+
this.started = false
|
|
34
|
+
this.stopped = false
|
|
35
|
+
this.busy = false
|
|
36
|
+
this.scheduled = false
|
|
37
|
+
this.pendingRun = false
|
|
38
|
+
this.timer = null
|
|
39
|
+
this.watchTimer = null
|
|
40
|
+
this.failures = 0
|
|
41
|
+
this.transport = null
|
|
42
|
+
this.tokenInfo = { source: 'none' }
|
|
43
|
+
this.lastPushAt = null
|
|
44
|
+
this.lastPullAt = null
|
|
45
|
+
this.lastError = null
|
|
46
|
+
this.lastConflicts = []
|
|
47
|
+
this.lastSkipped = []
|
|
48
|
+
this.remoteShas = new Map()
|
|
49
|
+
this.remoteDocs = new Map()
|
|
50
|
+
this.pending = new Map()
|
|
51
|
+
// Entries whose remote version cannot be satisfied here. They stay frozen
|
|
52
|
+
// until the winning version changes or the local install catches up.
|
|
53
|
+
this.deferred = new Map()
|
|
54
|
+
this.doc = emptyDoc(sanitizeId(this.cfg.deviceId, ''))
|
|
55
|
+
this.watchers = []
|
|
56
|
+
this.configErrors = []
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// ---------------------------------------------------------------- lifecycle
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Create a timer with the HMR transaction context removed. Timers made while
|
|
63
|
+
* this plugin is being reconciled inherit the transaction's AsyncLocalStorage
|
|
64
|
+
* store, which makes every later hmr.runExclusive() call look nested and fail
|
|
65
|
+
* with "HMR transactions cannot be nested".
|
|
66
|
+
*/
|
|
67
|
+
freshTimer(fn, delayMs) {
|
|
68
|
+
const create = () => setTimeout(fn, Math.max(0, delayMs))
|
|
69
|
+
try {
|
|
70
|
+
const store = this.ctx.get('hmr')?.executing
|
|
71
|
+
if (store && typeof store.getStore === 'function' && store.getStore() && typeof store.exit === 'function') {
|
|
72
|
+
return store.exit(create)
|
|
73
|
+
}
|
|
74
|
+
} catch {}
|
|
75
|
+
return create()
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
start() {
|
|
79
|
+
if (this.started) return this.started = true
|
|
80
|
+
this.stopped = false
|
|
81
|
+
ensureDir(this.stateDir)
|
|
82
|
+
this.loadState()
|
|
83
|
+
if (this.cfg.deviceId) this.doc.deviceId = sanitizeId(this.cfg.deviceId, '')
|
|
84
|
+
if (!this.doc.deviceId || this.doc.deviceId === 'device') this.doc.deviceId = defaultDeviceId()
|
|
85
|
+
this.watchProfile()
|
|
86
|
+
this.schedule(500)
|
|
87
|
+
this.log.info('started', {
|
|
88
|
+
deviceId: this.doc.deviceId,
|
|
89
|
+
profile: this.profileDir,
|
|
90
|
+
provider: this.cfg.provider,
|
|
91
|
+
intervalSeconds: this.cfg.intervalSeconds,
|
|
92
|
+
})
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
stop() {
|
|
96
|
+
if (this.stopped) return
|
|
97
|
+
this.stopped = true
|
|
98
|
+
if (this.timer) clearTimeout(this.timer)
|
|
99
|
+
this.timer = null
|
|
100
|
+
if (this.watchTimer) clearTimeout(this.watchTimer)
|
|
101
|
+
this.watchTimer = null
|
|
102
|
+
for (const watcher of this.watchers) {
|
|
103
|
+
try {
|
|
104
|
+
watcher.close()
|
|
105
|
+
} catch {}
|
|
106
|
+
}
|
|
107
|
+
this.watchers = []
|
|
108
|
+
this.saveState()
|
|
109
|
+
this.log.info('stopped')
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
schedule(delayMs) {
|
|
113
|
+
if (this.stopped) return
|
|
114
|
+
if (this.timer) clearTimeout(this.timer)
|
|
115
|
+
this.scheduled = true
|
|
116
|
+
this.timer = this.freshTimer(() => {
|
|
117
|
+
this.timer = null
|
|
118
|
+
this.scheduled = false
|
|
119
|
+
void this.run('timer')
|
|
120
|
+
}, Math.max(0, delayMs))
|
|
121
|
+
this.timer.unref?.()
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
watchProfile() {
|
|
125
|
+
if (!this.profileDir) return
|
|
126
|
+
const names = new Set(['cordis.patch.yml', 'cordis.yml', 'package.json'])
|
|
127
|
+
try {
|
|
128
|
+
const watcher = fs.watch(this.profileDir, { persistent: false }, (_event, filename) => {
|
|
129
|
+
const name = filename ? String(filename) : ''
|
|
130
|
+
if (name && !names.has(name)) return
|
|
131
|
+
if (this.watchTimer) clearTimeout(this.watchTimer)
|
|
132
|
+
this.watchTimer = this.freshTimer(() => {
|
|
133
|
+
this.watchTimer = null
|
|
134
|
+
void this.run('profile change')
|
|
135
|
+
}, 2000)
|
|
136
|
+
this.watchTimer.unref?.()
|
|
137
|
+
})
|
|
138
|
+
this.watchers.push(watcher)
|
|
139
|
+
} catch (error) {
|
|
140
|
+
this.log.warn('could not watch the profile directory', { error: error.message })
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// ---------------------------------------------------------------- main loop
|
|
145
|
+
|
|
146
|
+
async run(reason) {
|
|
147
|
+
if (this.stopped) return
|
|
148
|
+
if (this.busy) {
|
|
149
|
+
this.pendingRun = true
|
|
150
|
+
return
|
|
151
|
+
}
|
|
152
|
+
this.busy = true
|
|
153
|
+
try {
|
|
154
|
+
await this.runOnce(reason)
|
|
155
|
+
this.failures = 0
|
|
156
|
+
this.lastError = null
|
|
157
|
+
} catch (error) {
|
|
158
|
+
this.failures += 1
|
|
159
|
+
this.lastError = { at: nowIso(), message: error?.message || String(error), code: error?.code || '' }
|
|
160
|
+
this.log.error('sync failed', { reason, message: error?.message || String(error), code: error?.code })
|
|
161
|
+
} finally {
|
|
162
|
+
this.busy = false
|
|
163
|
+
const rerun = this.pendingRun
|
|
164
|
+
this.pendingRun = false
|
|
165
|
+
this.saveState()
|
|
166
|
+
this.writeStatus()
|
|
167
|
+
if (this.lastError?.code === 'unconfigured' && !rerun) return
|
|
168
|
+
const delay = rerun ? 1500 : this.nextDelay()
|
|
169
|
+
this.schedule(delay)
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
nextDelay() {
|
|
174
|
+
const base = this.cfg.intervalSeconds * 1000
|
|
175
|
+
if (this.failures === 0) return base
|
|
176
|
+
return Math.min(base * 2 ** Math.min(this.failures, 6), MAX_BACKOFF_MS)
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async runOnce(reason) {
|
|
180
|
+
const validation = validateConfig(this.cfg)
|
|
181
|
+
this.configErrors = validation.problems
|
|
182
|
+
if (!validation.ok) {
|
|
183
|
+
const error = new Error(`not configured: ${validation.problems.join('; ')}`)
|
|
184
|
+
error.code = 'unconfigured'
|
|
185
|
+
throw error
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const { token, source } = resolveToken(this.cfg)
|
|
189
|
+
this.tokenInfo = { source }
|
|
190
|
+
this.transport = createTransport(this.cfg, token)
|
|
191
|
+
|
|
192
|
+
const scope = this.readScope()
|
|
193
|
+
this.scope = scope
|
|
194
|
+
this.pruneForeign()
|
|
195
|
+
const snapshot = readSnapshot(this.ctx, this.cfg, { ...scope, profileDir: this.profileDir })
|
|
196
|
+
this.lastSkipped = snapshot.skipped
|
|
197
|
+
let dirty = this.foldLocal(snapshot)
|
|
198
|
+
|
|
199
|
+
if (dirty || this.needsPublish()) {
|
|
200
|
+
await this.push(`local change from ${this.doc.deviceId}`)
|
|
201
|
+
dirty = false
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
await this.pull()
|
|
205
|
+
|
|
206
|
+
if (!this.ownDocSeen) {
|
|
207
|
+
this.pushedHash = null
|
|
208
|
+
await this.push(`publish snapshot from ${this.doc.deviceId}`)
|
|
209
|
+
dirty = false
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const docs = [{ deviceId: this.doc.deviceId, doc: this.doc }]
|
|
213
|
+
for (const [deviceId, doc] of this.remoteDocs) docs.push({ deviceId, doc })
|
|
214
|
+
const { winners, conflicts } = mergeDocs(docs)
|
|
215
|
+
this.rememberConflicts(conflicts)
|
|
216
|
+
await this.writeConflictFiles(conflicts)
|
|
217
|
+
this.reconcileDeferred(winners)
|
|
218
|
+
|
|
219
|
+
// A plugin installed or upgraded locally to a newer version must not stay
|
|
220
|
+
// frozen behind an older remote record that merely carries a higher
|
|
221
|
+
// revision. Bump the local record so every machine converges on the newer
|
|
222
|
+
// version (the other side updates through updatePlugins).
|
|
223
|
+
const snapshotById = new Map(snapshot.entries.map((entry) => [entry.id, entry]))
|
|
224
|
+
for (const [id, winner] of winners) {
|
|
225
|
+
const entry = snapshotById.get(id)
|
|
226
|
+
if (!entry || !isSemver(winner.version)) continue
|
|
227
|
+
const localVersion = installedVersion(this.profileDir, entry.name)
|
|
228
|
+
if (!isSemver(localVersion) || compareSemver(localVersion, winner.version) <= 0) continue
|
|
229
|
+
const prev = this.doc.entries[id]
|
|
230
|
+
this.doc.entries[id] = recordOf(entry, { rev: (Number(prev?.rev) || 0) + 1, origin: this.doc.deviceId })
|
|
231
|
+
dirty = true
|
|
232
|
+
this.log.info('local version is newer; republishing', { id, local: localVersion, remote: winner.version })
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
let applied = 0
|
|
236
|
+
for (const [id, winner] of winners) {
|
|
237
|
+
const local = this.doc.entries[id]
|
|
238
|
+
const localHash = local ? recordHash(local) : ''
|
|
239
|
+
const winnerHash = recordHash(winner)
|
|
240
|
+
if (winner.version && local && winner.version !== local.version) {
|
|
241
|
+
this.log.info('version drift seen', { id, remote: winner.version, local: local.version, origin: winner.origin })
|
|
242
|
+
}
|
|
243
|
+
if (
|
|
244
|
+
local &&
|
|
245
|
+
localHash === winnerHash &&
|
|
246
|
+
!this.pending.has(id) &&
|
|
247
|
+
!this.deferred.has(id) &&
|
|
248
|
+
this.versionSatisfied(winner)
|
|
249
|
+
) {
|
|
250
|
+
this.doc.entries[id] = this.mergeMeta(local, winner)
|
|
251
|
+
continue
|
|
252
|
+
}
|
|
253
|
+
if (this.deferred.has(id)) {
|
|
254
|
+
// Frozen until the local install matches the winning version; retrying
|
|
255
|
+
// the same config against a different plugin version is pointless.
|
|
256
|
+
if (!this.versionSatisfied(winner)) continue
|
|
257
|
+
this.deferred.delete(id)
|
|
258
|
+
}
|
|
259
|
+
if (!this.accepts(id, winner)) {
|
|
260
|
+
continue
|
|
261
|
+
}
|
|
262
|
+
const result = await this.applyWinner(winner)
|
|
263
|
+
this.doc.entries[id] = this.cloneRecord(winner)
|
|
264
|
+
dirty = true
|
|
265
|
+
|
|
266
|
+
if (result.status === 'unchanged' || result.status === 'applied') {
|
|
267
|
+
this.pending.delete(id)
|
|
268
|
+
applied += 1
|
|
269
|
+
this.log.info('applied remote change', { id, name: winner.name, status: result.status, origin: winner.origin })
|
|
270
|
+
} else if (result.status === 'missing') {
|
|
271
|
+
this.pending.delete(id)
|
|
272
|
+
this.log.warn('remote plugin is not available here', { id, name: winner.name, reason: result.reason })
|
|
273
|
+
this.doc.entries[id] = local ? this.cloneRecord(local) : this.cloneRecord(winner)
|
|
274
|
+
} else if (result.status === 'error') {
|
|
275
|
+
this.pending.set(id, { hash: winnerHash, at: nowIso(), reason: result.reason })
|
|
276
|
+
this.log.warn('could not apply remote change yet', { id, name: winner.name, reason: result.reason })
|
|
277
|
+
} else if (result.status === 'skipped') {
|
|
278
|
+
// Keep the local record: the remote version was not applied, so this
|
|
279
|
+
// machine still runs what it has. The desired version lives in the
|
|
280
|
+
// deferred entry and the remote document.
|
|
281
|
+
this.doc.entries[id] = local ? this.cloneRecord(local) : this.cloneRecord(winner)
|
|
282
|
+
this.deferred.set(id, { hash: winnerHash, version: winner.version || null, reason: result.reason, at: nowIso() })
|
|
283
|
+
this.log.warn('remote plugin version differs; kept the local setup', {
|
|
284
|
+
id,
|
|
285
|
+
name: winner.name,
|
|
286
|
+
reason: result.reason,
|
|
287
|
+
})
|
|
288
|
+
} else {
|
|
289
|
+
this.pending.set(id, { hash: winnerHash, at: nowIso(), reason: result.reason })
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
for (const [id, entry] of this.pending) {
|
|
294
|
+
const local = this.doc.entries[id]
|
|
295
|
+
if (local && recordHash(local) === entry.hash) this.pending.delete(id)
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
if (applied > 0) this.log.info('applied merged changes', { reason, applied })
|
|
299
|
+
if (dirty) await this.push(`merged changes (${reason})`)
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// ---------------------------------------------------------------- local side
|
|
303
|
+
|
|
304
|
+
readScope() {
|
|
305
|
+
const patchIds = new Set()
|
|
306
|
+
try {
|
|
307
|
+
const text = fs.readFileSync(path.join(this.profileDir, 'cordis.patch.yml'), 'utf8')
|
|
308
|
+
for (const match of text.matchAll(/^\s*-\s+id:\s*["']?([^"'\s#]+)["']?\s*$/gm)) patchIds.add(match[1])
|
|
309
|
+
} catch {}
|
|
310
|
+
return { patchIds }
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
isCore(record) {
|
|
314
|
+
return typeof record?.name === 'string' && record.name.startsWith('@deepseek-ai/')
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
accepts(id, record) {
|
|
318
|
+
if (!this.isCore(record)) return true
|
|
319
|
+
return this.scope?.patchIds?.has(id) === true
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
pruneForeign() {
|
|
323
|
+
for (const [id, record] of Object.entries(this.doc.entries)) {
|
|
324
|
+
if (this.isCore(record) && !this.scope?.patchIds?.has(id)) delete this.doc.entries[id]
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
foldLocal(snapshot) {
|
|
329
|
+
let changed = false
|
|
330
|
+
for (const entry of snapshot.entries) {
|
|
331
|
+
if (this.pending.has(entry.id) || this.deferred.has(entry.id)) continue
|
|
332
|
+
const prev = this.doc.entries[entry.id]
|
|
333
|
+
const next = recordOf(entry, { rev: prev ? (Number(prev.rev) || 0) + 1 : 1, origin: this.doc.deviceId })
|
|
334
|
+
if (!prev) {
|
|
335
|
+
this.doc.entries[entry.id] = next
|
|
336
|
+
changed = true
|
|
337
|
+
continue
|
|
338
|
+
}
|
|
339
|
+
const enabledDiff = (prev.enabled === true) !== entry.enabled
|
|
340
|
+
const configDiff = entry.enabled && recordHash(prev) !== recordHash(next)
|
|
341
|
+
if (enabledDiff || configDiff) {
|
|
342
|
+
this.doc.entries[entry.id] = next
|
|
343
|
+
changed = true
|
|
344
|
+
} else if (prev.name !== entry.name) {
|
|
345
|
+
prev.name = entry.name
|
|
346
|
+
changed = true
|
|
347
|
+
} else if (prev.version == null && entry.version) {
|
|
348
|
+
// One-time backfill: older documents predate version tracking. Attribute
|
|
349
|
+
// the observation to this device - the previous record may have been
|
|
350
|
+
// authored by another machine, whose installed version is unknown.
|
|
351
|
+
this.doc.entries[entry.id] = {
|
|
352
|
+
...prev,
|
|
353
|
+
version: entry.version,
|
|
354
|
+
source: entry.source || null,
|
|
355
|
+
rev: (Number(prev.rev) || 0) + 1,
|
|
356
|
+
at: nowIso(),
|
|
357
|
+
origin: this.doc.deviceId,
|
|
358
|
+
}
|
|
359
|
+
changed = true
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
if (changed) this.doc.updatedAt = nowIso()
|
|
363
|
+
return changed
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
localVersionOf(record) {
|
|
367
|
+
return installedVersion(this.profileDir, record?.name)
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
versionSatisfied(record) {
|
|
371
|
+
if (!record?.version) return true
|
|
372
|
+
const local = this.localVersionOf(record)
|
|
373
|
+
// Unreadable local version (path installs, non-package ids) cannot be
|
|
374
|
+
// compared; do not freeze the entry on a guess.
|
|
375
|
+
return !local || local === record.version
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
reconcileDeferred(winners) {
|
|
379
|
+
for (const id of [...this.deferred.keys()]) {
|
|
380
|
+
const item = this.deferred.get(id)
|
|
381
|
+
const winner = winners.get(id)
|
|
382
|
+
if (!winner || recordHash(winner) !== item.hash || this.versionSatisfied(winner)) {
|
|
383
|
+
this.deferred.delete(id)
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
async applyWinner(winner) {
|
|
389
|
+
const helpers = {
|
|
390
|
+
log: this.log,
|
|
391
|
+
installMissing: this.cfg.installMissing,
|
|
392
|
+
updatePlugins: this.cfg.updatePlugins,
|
|
393
|
+
profileDir: this.profileDir,
|
|
394
|
+
waitFor: (target) => this.waitForEntry(target),
|
|
395
|
+
}
|
|
396
|
+
const result = await applyTarget(this.ctx, winner, helpers)
|
|
397
|
+
return result
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
async waitForEntry({ id, name }, timeoutMs = WAIT_FOR_PLUGIN_MS) {
|
|
401
|
+
const editor = this.ctx.get('configEditor')
|
|
402
|
+
if (!editor) return undefined
|
|
403
|
+
const deadline = Date.now() + timeoutMs
|
|
404
|
+
let last
|
|
405
|
+
while (Date.now() < deadline) {
|
|
406
|
+
try {
|
|
407
|
+
const entries = editor.entries()
|
|
408
|
+
last =
|
|
409
|
+
entries.find((entry) => entry?.options?.id === id) ||
|
|
410
|
+
(name ? entries.find((entry) => entry?.options?.name === name) : undefined)
|
|
411
|
+
if (last) {
|
|
412
|
+
if (!last.fiber || last.fiber.state === 2) return last
|
|
413
|
+
}
|
|
414
|
+
} catch {}
|
|
415
|
+
await sleep(750)
|
|
416
|
+
}
|
|
417
|
+
return last
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
cloneRecord(rec) {
|
|
421
|
+
return JSON.parse(JSON.stringify(rec))
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
mergeMeta(local, winner) {
|
|
425
|
+
return { ...this.cloneRecord(winner), name: winner.name || local.name }
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
// ---------------------------------------------------------------- remote side
|
|
429
|
+
|
|
430
|
+
async push(reason) {
|
|
431
|
+
if (this.cfg.provider !== 'file' && !this.transportTokenOk()) return
|
|
432
|
+
const hash = this.hashDoc()
|
|
433
|
+
if (hash === this.pushedHash) return
|
|
434
|
+
this.doc.updatedAt = nowIso()
|
|
435
|
+
const text = JSON.stringify(this.doc, null, 2) + '\n'
|
|
436
|
+
if (Buffer.byteLength(text, 'utf8') > this.cfg.maxDocBytes) {
|
|
437
|
+
throw new Error(`local document exceeds maxDocBytes (${this.cfg.maxDocBytes})`)
|
|
438
|
+
}
|
|
439
|
+
const rel = `devices/${this.doc.deviceId}.json`
|
|
440
|
+
let sha = this.remoteShas.get(rel)
|
|
441
|
+
try {
|
|
442
|
+
sha = await this.transport.put(rel, text, { message: `dsh-sync: ${reason}`, sha })
|
|
443
|
+
} catch (error) {
|
|
444
|
+
// Gitee reports a stale blob sha as 400 ("Blob SHA does not match"), not
|
|
445
|
+
// 409, so a push interrupted mid-cycle (state saved before the new sha
|
|
446
|
+
// landed) would otherwise wedge forever. Re-read the remote sha and retry.
|
|
447
|
+
const staleSha =
|
|
448
|
+
error?.status === 400 && /Blob SHA does not match/i.test(String(error?.message || ''))
|
|
449
|
+
if (error?.code !== 'conflict' && !staleSha) throw error
|
|
450
|
+
const existing = await this.transport.get(rel)
|
|
451
|
+
sha = await this.transport.put(rel, text, { message: `dsh-sync: ${reason}`, sha: existing?.sha })
|
|
452
|
+
}
|
|
453
|
+
if (sha) this.remoteShas.set(rel, sha)
|
|
454
|
+
this.pushedHash = hash
|
|
455
|
+
this.lastPushAt = nowIso()
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
hashDoc() {
|
|
459
|
+
const clone = { ...this.doc }
|
|
460
|
+
delete clone.updatedAt
|
|
461
|
+
return sha256(JSON.stringify(clone, null, 2))
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
needsPublish() {
|
|
465
|
+
return this.hashDoc() !== this.pushedHash
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
transportTokenOk() {
|
|
469
|
+
return this.tokenInfo.source !== 'none'
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
async pull() {
|
|
473
|
+
const files = await this.transport.list('devices')
|
|
474
|
+
const seen = new Set()
|
|
475
|
+
this.ownDocSeen = false
|
|
476
|
+
for (const file of files) {
|
|
477
|
+
if (!file?.name?.endsWith('.json')) continue
|
|
478
|
+
const rel = `devices/${file.name}`
|
|
479
|
+
seen.add(rel)
|
|
480
|
+
const deviceId = sanitizeId(file.name.slice(0, -5), 'device')
|
|
481
|
+
if (deviceId === this.doc.deviceId) {
|
|
482
|
+
this.ownDocSeen = true
|
|
483
|
+
if (file.sha) this.remoteShas.set(rel, file.sha)
|
|
484
|
+
continue
|
|
485
|
+
}
|
|
486
|
+
// Fetch the document whenever it is not already in memory: after a reload
|
|
487
|
+
// the sha cache survives in state, but the parsed documents do not, and
|
|
488
|
+
// skipping the fetch would hide every remote change until the other
|
|
489
|
+
// machine happens to push again.
|
|
490
|
+
if (file.sha && this.remoteShas.get(rel) === file.sha && this.remoteDocs.has(deviceId)) continue
|
|
491
|
+
const got = await this.transport.get(rel)
|
|
492
|
+
if (!got) continue
|
|
493
|
+
const doc = parseDoc(got.text, deviceId)
|
|
494
|
+
if (!doc) {
|
|
495
|
+
this.log.warn('ignoring malformed or misnamed device document', { file: file.name })
|
|
496
|
+
continue
|
|
497
|
+
}
|
|
498
|
+
if (file.sha) this.remoteShas.set(rel, file.sha)
|
|
499
|
+
else if (got.sha) this.remoteShas.set(rel, got.sha)
|
|
500
|
+
this.remoteDocs.set(deviceId, doc)
|
|
501
|
+
}
|
|
502
|
+
for (const rel of [...this.remoteShas.keys()]) {
|
|
503
|
+
if (rel.startsWith('devices/') && !seen.has(rel)) this.remoteShas.delete(rel)
|
|
504
|
+
}
|
|
505
|
+
for (const deviceId of [...this.remoteDocs.keys()]) {
|
|
506
|
+
if (!seen.has(`devices/${deviceId}.json`)) this.remoteDocs.delete(deviceId)
|
|
507
|
+
}
|
|
508
|
+
this.lastPullAt = nowIso()
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
// ---------------------------------------------------------------- reporting
|
|
512
|
+
|
|
513
|
+
rememberConflicts(conflicts) {
|
|
514
|
+
this.lastConflicts = conflicts.map((conflict) => ({
|
|
515
|
+
id: conflict.id,
|
|
516
|
+
name: conflict.name,
|
|
517
|
+
at: conflict.winner.at,
|
|
518
|
+
winner: { deviceId: conflict.winner.deviceId, at: conflict.winner.at },
|
|
519
|
+
others: conflict.others.map((item) => ({ deviceId: item.deviceId, at: item.at })),
|
|
520
|
+
}))
|
|
521
|
+
if (conflicts.length > 0) this.log.warn('conflicting writes detected', { count: conflicts.length })
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
async writeConflictFiles(conflicts) {
|
|
525
|
+
if (conflicts.length === 0) return
|
|
526
|
+
const dir = path.join(this.stateDir, 'conflicts')
|
|
527
|
+
ensureDir(dir)
|
|
528
|
+
for (const conflict of conflicts) {
|
|
529
|
+
const payload = {
|
|
530
|
+
format: 'dsh-sync-conflict',
|
|
531
|
+
at: nowIso(),
|
|
532
|
+
deviceId: this.doc.deviceId,
|
|
533
|
+
id: conflict.id,
|
|
534
|
+
name: conflict.name,
|
|
535
|
+
winner: conflict.winner,
|
|
536
|
+
others: conflict.others,
|
|
537
|
+
}
|
|
538
|
+
const hash = sha256(stableStringify(payload)).slice(0, 16)
|
|
539
|
+
const file = path.join(dir, `${hash}.json`)
|
|
540
|
+
if (!fs.existsSync(file)) writeJson(file, payload)
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
writeStatus() {
|
|
545
|
+
const status = {
|
|
546
|
+
at: nowIso(),
|
|
547
|
+
configured: this.configErrors.length === 0,
|
|
548
|
+
configErrors: this.configErrors,
|
|
549
|
+
provider: this.cfg.provider,
|
|
550
|
+
target:
|
|
551
|
+
this.cfg.provider === 'file'
|
|
552
|
+
? this.cfg.dir
|
|
553
|
+
: `${this.cfg.owner}/${this.cfg.repo}@${this.cfg.branch}/${this.cfg.path}`,
|
|
554
|
+
deviceId: this.doc.deviceId,
|
|
555
|
+
profileDir: this.profileDir,
|
|
556
|
+
intervalSeconds: this.cfg.intervalSeconds,
|
|
557
|
+
tokenSource: this.tokenInfo.source,
|
|
558
|
+
lastPushAt: this.lastPushAt,
|
|
559
|
+
lastPullAt: this.lastPullAt,
|
|
560
|
+
lastError: this.lastError,
|
|
561
|
+
entries: Object.keys(this.doc.entries).length,
|
|
562
|
+
pending: [...this.pending].map(([id, item]) => ({ id, reason: item.reason, since: item.at })),
|
|
563
|
+
deferred: [...this.deferred].map(([id, item]) => ({
|
|
564
|
+
id,
|
|
565
|
+
version: item.version || null,
|
|
566
|
+
reason: item.reason,
|
|
567
|
+
since: item.at,
|
|
568
|
+
})),
|
|
569
|
+
remoteDevices: [...this.remoteDocs].map(([deviceId, doc]) => ({
|
|
570
|
+
deviceId,
|
|
571
|
+
updatedAt: doc.updatedAt || null,
|
|
572
|
+
entries: Object.keys(doc.entries || {}).length,
|
|
573
|
+
})),
|
|
574
|
+
conflicts: this.lastConflicts.slice(0, 5),
|
|
575
|
+
skipped: this.lastSkipped.slice(0, 10),
|
|
576
|
+
}
|
|
577
|
+
try {
|
|
578
|
+
writeJson(this.statusFile, status)
|
|
579
|
+
} catch (error) {
|
|
580
|
+
this.log.warn('could not write status file', { error: error.message })
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
// ---------------------------------------------------------------- persistence
|
|
585
|
+
|
|
586
|
+
loadState() {
|
|
587
|
+
const state = readJson(this.stateFile)
|
|
588
|
+
if (state && state.doc && typeof state.doc === 'object' && state.doc.format === 'dsh-sync-doc') {
|
|
589
|
+
this.doc = state.doc
|
|
590
|
+
if (!this.doc.entries || typeof this.doc.entries !== 'object') this.doc.entries = {}
|
|
591
|
+
}
|
|
592
|
+
if (state?.remoteShas && typeof state.remoteShas === 'object') {
|
|
593
|
+
this.remoteShas = new Map(Object.entries(state.remoteShas))
|
|
594
|
+
}
|
|
595
|
+
if (state?.pending && typeof state.pending === 'object') {
|
|
596
|
+
this.pending = new Map(Object.entries(state.pending))
|
|
597
|
+
}
|
|
598
|
+
if (state?.deferred && typeof state.deferred === 'object') {
|
|
599
|
+
this.deferred = new Map(Object.entries(state.deferred))
|
|
600
|
+
}
|
|
601
|
+
this.lastPushAt = state?.lastPushAt || null
|
|
602
|
+
this.lastPullAt = state?.lastPullAt || null
|
|
603
|
+
this.pushedHash = state?.pushedHash || null
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
saveState() {
|
|
607
|
+
try {
|
|
608
|
+
writeJson(this.stateFile, {
|
|
609
|
+
deviceId: this.doc.deviceId,
|
|
610
|
+
doc: this.doc,
|
|
611
|
+
remoteShas: Object.fromEntries(this.remoteShas),
|
|
612
|
+
pending: Object.fromEntries(this.pending),
|
|
613
|
+
deferred: Object.fromEntries(this.deferred),
|
|
614
|
+
lastPushAt: this.lastPushAt,
|
|
615
|
+
lastPullAt: this.lastPullAt,
|
|
616
|
+
pushedHash: this.pushedHash,
|
|
617
|
+
})
|
|
618
|
+
} catch (error) {
|
|
619
|
+
this.log.warn('could not persist sync state', { error: error.message })
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
|
package/lib/log.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
|
|
4
|
+
const LEVELS = { debug: 10, info: 20, warn: 30, error: 40 }
|
|
5
|
+
const MAX_LOG_BYTES = 1_000_000
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Append-only ndjson log with one rotation, so a stuck plugin cannot fill the
|
|
9
|
+
* disk. Never throw from logging: the sync loop must survive a bad log path.
|
|
10
|
+
*/
|
|
11
|
+
export function createLogger({ file, level = 'info', echo } = {}) {
|
|
12
|
+
const threshold = LEVELS[level] ?? LEVELS.info
|
|
13
|
+
|
|
14
|
+
function write(levelName, message, meta) {
|
|
15
|
+
if ((LEVELS[levelName] ?? LEVELS.info) < threshold) return
|
|
16
|
+
const entry = { t: new Date().toISOString(), level: levelName, msg: String(message) }
|
|
17
|
+
if (meta !== undefined) entry.meta = meta
|
|
18
|
+
try {
|
|
19
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
20
|
+
try {
|
|
21
|
+
if (fs.statSync(file).size > MAX_LOG_BYTES) fs.renameSync(file, file + '.1')
|
|
22
|
+
} catch {}
|
|
23
|
+
fs.appendFileSync(file, JSON.stringify(entry) + '\n', 'utf8')
|
|
24
|
+
} catch {}
|
|
25
|
+
if (levelName === 'error' || levelName === 'warn') {
|
|
26
|
+
echo?.(`[dsh-sync] ${levelName}: ${message}`)
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return {
|
|
31
|
+
debug: (msg, meta) => write('debug', msg, meta),
|
|
32
|
+
info: (msg, meta) => write('info', msg, meta),
|
|
33
|
+
warn: (msg, meta) => write('warn', msg, meta),
|
|
34
|
+
error: (msg, meta) => write('error', msg, meta),
|
|
35
|
+
}
|
|
36
|
+
}
|