dsh-multi-device-config-sync 1.5.0 → 1.6.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 +15 -7
- package/client.js +389 -65
- package/lib/plugins.js +25 -4
- package/lib/routes.js +74 -5
- package/lib/sync-install.js +39 -9
- package/locale/en.json +2 -2
- package/locale/zh.json +2 -2
- package/package.json +1 -1
- package/test/package.test.mjs +5 -2
- package/test/progress-client.test.mjs +225 -0
- package/test/progress-engine.test.mjs +235 -0
- package/test/progress-http.test.mjs +340 -0
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
/** The Host confirmation is the progress source. No routes, sleeps, sockets or real installer. */
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
import { undoStatus, validateBackup, WORK_DIR } from '../lib/backup.js'
|
|
6
|
+
import { declarationsFromManifest, installMissingPlugins, pluginInventory } from '../lib/plugins.js'
|
|
7
|
+
import { createRestoreSession } from '../lib/sync-install.js'
|
|
8
|
+
import { backupDocument, createReport, makeProfile, tempDir, TEST_GIST_ID, useProfile } from './harness.mjs'
|
|
9
|
+
|
|
10
|
+
const { check, finish } = createReport('Host restore progress')
|
|
11
|
+
const home = tempDir('dsh-restore-progress-')
|
|
12
|
+
process.env.HOME = process.env.USERPROFILE = process.env.DSH_HOME = home
|
|
13
|
+
process.env.PATH = join(home, 'no-executables')
|
|
14
|
+
for (const key of ['GITHUB_TOKEN', 'DSH_GITHUB_TOKEN', 'GH_TOKEN']) delete process.env[key]
|
|
15
|
+
globalThis.fetch = () => { throw new Error('unexpected network access') }
|
|
16
|
+
const ref = { id: TEST_GIST_ID }
|
|
17
|
+
const note = 'data/note.json', original = '{"hello":"world"}\n', reviewed = '{"reviewed":true}\n'
|
|
18
|
+
const readNote = profile => readFileSync(join(profile, note), 'utf8')
|
|
19
|
+
const checkStep = { stage: 'check' }, writeStep = { stage: 'write' }
|
|
20
|
+
const install = (files, processed, total, current) => ({ stage: 'install', files, processed, total, current })
|
|
21
|
+
function document(dependencies = {}, text = reviewed, extraFiles = []) {
|
|
22
|
+
const doc = backupDocument('sender', [{ path: note, lines: text.split('\n') }, ...extraFiles])
|
|
23
|
+
doc.files[0].json.dependencies = dependencies
|
|
24
|
+
return validateBackup(doc)
|
|
25
|
+
}
|
|
26
|
+
function gate() {
|
|
27
|
+
let open
|
|
28
|
+
const promise = new Promise(resolve => { open = resolve })
|
|
29
|
+
return { promise, open }
|
|
30
|
+
}
|
|
31
|
+
let serial = 0
|
|
32
|
+
async function scenario(label, run) {
|
|
33
|
+
const profile = makeProfile(join(home, 'profiles', `${++serial}`), { dependencies: {}, bundles: [] })
|
|
34
|
+
useProfile(profile, home)
|
|
35
|
+
let lookups = 0
|
|
36
|
+
const manager = { listPlugins: () => [], listBundles: () => [], installBundle: () => { throw new Error('unexpected install') } }
|
|
37
|
+
const session = createRestoreSession({ get pluginManager() { lookups++; return manager } })
|
|
38
|
+
try { await run({ profile, manager, session, lookups: () => lookups }); check(label, true) }
|
|
39
|
+
catch (error) { check(label, false, error.stack) }
|
|
40
|
+
finally { session.dispose() }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
await scenario('a held installer observes each real handoff; 3/3 precedes inventory verification, not a success verdict', async ({ profile, manager, session }) => {
|
|
44
|
+
const first = '@sample/one', second = 'dsh-profile-gist-sync', third = '@sample/three' // upstream is not the sync package itself
|
|
45
|
+
const url = 'https://example.invalid/third-party-source.tgz'
|
|
46
|
+
const events = [], snapshots = [], calls = [], visible = new Set(['preexisting'])
|
|
47
|
+
const inThird = gate(), releaseThird = gate(), inVerify = gate(), releaseVerify = gate()
|
|
48
|
+
manager.listPlugins = async () => {
|
|
49
|
+
if (events.at(-1)?.stage === 'verify') { inVerify.open(); await releaseVerify.promise }
|
|
50
|
+
return []
|
|
51
|
+
}
|
|
52
|
+
manager.listBundles = () => [...visible].map(name => ({ name, installed: true }))
|
|
53
|
+
manager.installBundle = async (spec, options) => {
|
|
54
|
+
calls.push({ spec, options, progressAtHandoff: events.at(-1) })
|
|
55
|
+
if (spec === url) { visible.add(first); return { application: 'applied', pendingBuilds: ['native-helper'] } }
|
|
56
|
+
if (spec === `${second}@1`) throw new Error('private diagnostic: installer offline')
|
|
57
|
+
inThird.open(); await releaseThird.promise
|
|
58
|
+
return { application: 'applied' } // manager says 'applied', but the inventory will still lack it
|
|
59
|
+
}
|
|
60
|
+
const plan = await session.preview(ref, document({
|
|
61
|
+
'dsh-profile-gist-sync-plus': '9', 'dsh-multi-device-config-sync': '9', preexisting: '1',
|
|
62
|
+
[first]: url, local: 'link:../private-path', [second]: '1', [third]: '1',
|
|
63
|
+
}))
|
|
64
|
+
const pending = session.confirm(plan.planId, true, event => {
|
|
65
|
+
events.push(event)
|
|
66
|
+
snapshots.push([readNote(profile), undoStatus()?.files ?? 0])
|
|
67
|
+
if (event.stage === 'install') throw new Error('subscriber disconnected')
|
|
68
|
+
})
|
|
69
|
+
const checkpoint = (reached, name) => Promise.race([
|
|
70
|
+
reached.promise, pending.then(() => { throw new Error(`confirmation finished before ${name}`) }),
|
|
71
|
+
])
|
|
72
|
+
let receipt
|
|
73
|
+
try {
|
|
74
|
+
await checkpoint(inThird, 'the third handoff')
|
|
75
|
+
assert.deepEqual(events.at(-1), install(1, 2, 3, third))
|
|
76
|
+
const other = []
|
|
77
|
+
await assert.rejects(session.confirm(plan.planId, true, event => other.push(event)), { code: 'stale-plan' })
|
|
78
|
+
assert.deepEqual(other, [], 'a second caller does not observe the first one’s job')
|
|
79
|
+
releaseThird.open()
|
|
80
|
+
await checkpoint(inVerify, 'the inventory recheck')
|
|
81
|
+
assert.deepEqual(events.at(-1), { stage: 'verify', files: 1, processed: 3, total: 3 })
|
|
82
|
+
assert.deepEqual(calls.map(call => call.progressAtHandoff), [install(1, 0, 3, first), install(1, 1, 3, second), install(1, 2, 3, third)])
|
|
83
|
+
} finally {
|
|
84
|
+
releaseThird.open(); releaseVerify.open()
|
|
85
|
+
receipt = await pending
|
|
86
|
+
}
|
|
87
|
+
assert.deepEqual(events.slice(0, 2), [checkStep, writeStep])
|
|
88
|
+
assert.deepEqual(snapshots.slice(0, 2), [[original, 0], [original, 0]], 'write starts before the file commit')
|
|
89
|
+
assert.ok(snapshots.slice(2).every(([text, count]) => text === reviewed && count === receipt.report.restored))
|
|
90
|
+
const meter = events.filter(event => event.stage === 'install')
|
|
91
|
+
assert.deepEqual(meter.filter(event => event.current !== null), calls.map(call => call.progressAtHandoff))
|
|
92
|
+
assert.deepEqual(meter.at(-1), install(1, 3, 3, null))
|
|
93
|
+
for (const event of meter) assert.deepEqual(Object.keys(event).sort(), ['current', 'files', 'processed', 'stage', 'total'])
|
|
94
|
+
assert.deepEqual(calls.map(call => call.spec), [url, `${second}@1`, `${third}@1`])
|
|
95
|
+
assert.ok(calls.every(call => !Object.hasOwn(call.options, 'approvedBuilds')))
|
|
96
|
+
assert.deepEqual(receipt.plugins.results.map(row => [row.name, row.outcome]), [[first, 'installed'], ['local', 'skipped'], [second, 'failed'], [third, 'failed']])
|
|
97
|
+
assert.deepEqual(receipt.plugins.results[0].pendingBuilds, ['native-helper'])
|
|
98
|
+
assert.equal(receipt.complete, false)
|
|
99
|
+
})
|
|
100
|
+
|
|
101
|
+
await scenario('the second inventory can add skips and remove work: only an approved item with its own result counts', async ({ profile, manager, session }) => {
|
|
102
|
+
const events = [], calls = [], installed = []
|
|
103
|
+
manager.listBundles = () => [...(readNote(profile) === original ? ['unreviewed-gap'] : ['now-present']), ...installed].map(name => ({ name, installed: true }))
|
|
104
|
+
manager.installBundle = spec => {
|
|
105
|
+
calls.push(spec); installed.push('attempted')
|
|
106
|
+
return { application: 'failed', error: { code: 'already-installed' } } // a real result for this handoff
|
|
107
|
+
}
|
|
108
|
+
const plan = await session.preview(ref, document({ 'now-present': '1', 'unreviewed-gap': '1', attempted: '1', manual: 'file:../manual' }))
|
|
109
|
+
assert.equal(plan.plugins.counts.installable, 2)
|
|
110
|
+
const receipt = await session.confirm(plan.planId, true, event => events.push(event))
|
|
111
|
+
assert.deepEqual(calls, ['attempted@1'])
|
|
112
|
+
assert.deepEqual(receipt.plugins.results.map(row => [row.name, row.outcome]), [['unreviewed-gap', 'skipped'], ['attempted', 'already-present'], ['manual', 'skipped']])
|
|
113
|
+
assert.deepEqual(events.filter(event => event.current != null), [install(1, 0, 2, 'attempted')])
|
|
114
|
+
assert.ok(events.filter(event => event.stage === 'install').every(event => event.total === 2 && event.processed <= 1))
|
|
115
|
+
assert.deepEqual(events.at(-1), { stage: 'verify', files: 1, processed: 1, total: 2 })
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
await scenario('an approved name skipped for a changed spec gets one result but the new source is never handed off', async ({ manager }) => {
|
|
119
|
+
const ctx = { pluginManager: manager }, events = [], calls = []
|
|
120
|
+
manager.installBundle = spec => { calls.push(spec) }
|
|
121
|
+
const declared = dependencies => declarationsFromManifest({ dependencies })
|
|
122
|
+
const review = await pluginInventory(ctx, declared({ changed: '1', 'became-present': '1' }))
|
|
123
|
+
const approved = new Map(review.missing.map(row => [row.name, row.installSpec]))
|
|
124
|
+
// Exercise the installer's eligibility recheck in isolation: the confirmation
|
|
125
|
+
// normally retains its immutable cloud declarations. A new spec is not consent.
|
|
126
|
+
manager.listBundles = () => [{ name: 'became-present', installed: true }]
|
|
127
|
+
const receipt = await installMissingPlugins(ctx, {
|
|
128
|
+
declarations: declared({ unchecked: '1', changed: '2', 'became-present': '1' }), approved,
|
|
129
|
+
progress: event => events.push(event),
|
|
130
|
+
})
|
|
131
|
+
assert.deepEqual(receipt.results.map(row => [row.name, row.outcome, row.message]), [['unchecked', 'skipped', 'stale-plan'], ['changed', 'skipped', 'stale-plan']])
|
|
132
|
+
assert.deepEqual(calls, [])
|
|
133
|
+
assert.deepEqual(events, [
|
|
134
|
+
{ stage: 'install', processed: 0, total: 2, current: null },
|
|
135
|
+
{ stage: 'install', processed: 1, total: 2, current: null },
|
|
136
|
+
{ stage: 'verify', processed: 1, total: 2 },
|
|
137
|
+
])
|
|
138
|
+
})
|
|
139
|
+
|
|
140
|
+
await scenario('zero changes and zero approvals: verify a real inventory, no install event or undo point', async ({ session, manager }) => {
|
|
141
|
+
const events = [], inventoryAt = [], calls = []
|
|
142
|
+
manager.installBundle = spec => { calls.push(spec) }
|
|
143
|
+
manager.listBundles = () => { inventoryAt.push(events.at(-1)?.stage); return [{ name: 'here', installed: true }] }
|
|
144
|
+
const plan = await session.preview(ref, document({ here: '1', manual: 'workspace:*' }, original))
|
|
145
|
+
const result = await session.confirm(plan.planId, true, event => events.push(event))
|
|
146
|
+
assert.deepEqual(events, [checkStep, writeStep, { stage: 'verify', files: 0 }])
|
|
147
|
+
assert.deepEqual(calls, [])
|
|
148
|
+
assert.equal(inventoryAt.at(-1), 'verify')
|
|
149
|
+
assert.equal(result.report.restored, 0)
|
|
150
|
+
assert.equal(result.report.undoDir, null)
|
|
151
|
+
assert.equal(undoStatus(), null)
|
|
152
|
+
assert.equal(result.complete, false, 'the unresolved declaration still needs attention')
|
|
153
|
+
})
|
|
154
|
+
|
|
155
|
+
await scenario('packages-only: all 3 items processed with zero file changes is not completion while a build is pending', async ({ session, manager }) => {
|
|
156
|
+
const events = [], names = [], options = []
|
|
157
|
+
manager.listBundles = () => names.map(name => ({ name, installed: true }))
|
|
158
|
+
manager.installBundle = (spec, opts) => {
|
|
159
|
+
names.push(spec.split('@')[0]); options.push(opts)
|
|
160
|
+
return { application: 'applied', pendingBuilds: names.length === 3 ? ['native-helper'] : [] }
|
|
161
|
+
}
|
|
162
|
+
const plan = await session.preview(ref, document({ one: '1', two: '1', three: '1' }, original))
|
|
163
|
+
const result = await session.confirm(plan.planId, true, event => events.push(event))
|
|
164
|
+
assert.deepEqual(events.at(-1), { stage: 'verify', files: 0, processed: 3, total: 3 })
|
|
165
|
+
assert.ok(events.filter(event => event.stage === 'install').every(event => event.files === 0))
|
|
166
|
+
assert.equal(result.report.restored, 0)
|
|
167
|
+
assert.equal(undoStatus(), null)
|
|
168
|
+
assert.equal(result.plugins.counts.missing, 0)
|
|
169
|
+
assert.equal(result.plugins.outcomeCounts.installed, 3)
|
|
170
|
+
assert.equal(result.complete, false)
|
|
171
|
+
assert.ok(options.every(opts => !Object.hasOwn(opts, 'approvedBuilds')))
|
|
172
|
+
})
|
|
173
|
+
|
|
174
|
+
await scenario('config committed but pre-install inventory unavailable: no invented outcomes or final verification', async ({ profile, session, manager }) => {
|
|
175
|
+
const events = []
|
|
176
|
+
manager.listPlugins = manager.listBundles = () => { if (readNote(profile) === reviewed) throw new Error('inventory unavailable'); return [] }
|
|
177
|
+
const plan = await session.preview(ref, document({ plugin: '1' }))
|
|
178
|
+
const result = await session.confirm(plan.planId, true, event => events.push(event))
|
|
179
|
+
assert.deepEqual(events, [checkStep, writeStep, install(1, 0, 1, null)])
|
|
180
|
+
assert.equal(result.report.restored, 1)
|
|
181
|
+
assert.equal(result.plugins.available, false)
|
|
182
|
+
assert.deepEqual(result.plugins.results, [])
|
|
183
|
+
assert.equal(result.complete, false)
|
|
184
|
+
})
|
|
185
|
+
|
|
186
|
+
for (const mode of ['config', 'local']) await scenario(`${mode}: synchronous, private write-receipt checks survive thrown or rejected deliveries, including a no-op`, async ({ session, profile, lookups }) => {
|
|
187
|
+
const doc = document(), events = [], bytesAt = [], again = []
|
|
188
|
+
const preview = () => mode === 'config' ? session.previewConfig(ref, doc) : session.previewLocal(doc)
|
|
189
|
+
const confirm = mode === 'config' ? session.confirmConfig : session.confirmLocal
|
|
190
|
+
const wrong = mode === 'config' ? session.confirmLocal : session.confirmConfig
|
|
191
|
+
const { planId } = preview()
|
|
192
|
+
assert.throws(() => wrong(planId, true, e => events.push(e)), { code: 'stale-plan' })
|
|
193
|
+
assert.throws(() => confirm(planId, 'true', e => events.push(e)), { code: 'invalid' })
|
|
194
|
+
assert.deepEqual(events, [])
|
|
195
|
+
const receipt = confirm(planId, true, e => {
|
|
196
|
+
events.push(e); bytesAt.push(readNote(profile))
|
|
197
|
+
if (e.stage === 'check') throw new Error('disconnected')
|
|
198
|
+
return e.stage === 'write' ? Promise.reject(new Error('async disconnection')) : new Promise(() => {})
|
|
199
|
+
})
|
|
200
|
+
assert.deepEqual(events, [checkStep, writeStep, { stage: 'verify', files: 1 }])
|
|
201
|
+
assert.deepEqual(bytesAt, [original, original, reviewed])
|
|
202
|
+
assert.equal(receipt.report.restored, 1, 'a synchronous receipt, not a Promise')
|
|
203
|
+
assert.deepEqual(Object.keys(receipt).sort(), mode === 'config' ? ['ref', 'report', 'restart', 'warnings'] : ['report'])
|
|
204
|
+
const unchanged = confirm(preview().planId, true, e => again.push(e))
|
|
205
|
+
assert.deepEqual(again, [checkStep, writeStep, { stage: 'verify', files: 0 }])
|
|
206
|
+
assert.equal(events.length, 3, 'the listener from the first call was not retained')
|
|
207
|
+
assert.equal(unchanged.report.undoDir, null)
|
|
208
|
+
assert.equal(unchanged.report.restored, 0)
|
|
209
|
+
assert.equal(lookups(), 0)
|
|
210
|
+
assert.equal(existsSync(join(profile, WORK_DIR, 'settings.json')), mode === 'config')
|
|
211
|
+
})
|
|
212
|
+
|
|
213
|
+
await scenario('rejected fingerprints and rolled-back writes do not emit commit/installation counts', async ({ session, profile, manager }) => {
|
|
214
|
+
const calls = [], stale = [], rollback = [], replay = []
|
|
215
|
+
manager.installBundle = spec => { calls.push(spec) }
|
|
216
|
+
const fresh = await session.preview(ref, document({ plugin: '1' }))
|
|
217
|
+
writeFileSync(join(profile, note), 'edited after preview')
|
|
218
|
+
await assert.rejects(session.confirm(fresh.planId, true, event => stale.push(event)), { code: 'stale-plan' })
|
|
219
|
+
assert.deepEqual(stale, [checkStep])
|
|
220
|
+
// Both paths are absent at preview. Writing the first fixture file makes it
|
|
221
|
+
// impossible to create the second file under it, after the note was overwritten.
|
|
222
|
+
const plan = await session.preview(ref, document({ plugin: '1' }, reviewed, [
|
|
223
|
+
{ path: 'data/conflict', lines: ['fixture file'] }, { path: 'data/conflict/note.json', lines: ['{}'] },
|
|
224
|
+
]))
|
|
225
|
+
await assert.rejects(session.confirm(plan.planId, true, event => rollback.push(event)), { code: 'unsafe-path' })
|
|
226
|
+
assert.deepEqual(rollback, [checkStep, writeStep])
|
|
227
|
+
assert.equal(readNote(profile), 'edited after preview')
|
|
228
|
+
assert.ok(!existsSync(join(profile, 'data/conflict')))
|
|
229
|
+
assert.equal(undoStatus(), null)
|
|
230
|
+
assert.deepEqual(calls, [])
|
|
231
|
+
await assert.rejects(session.confirm(plan.planId, true, event => replay.push(event)), { code: 'stale-plan' })
|
|
232
|
+
assert.deepEqual(replay, [])
|
|
233
|
+
})
|
|
234
|
+
|
|
235
|
+
process.exitCode = finish()
|
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
/** Exercise the registered restore handler over a real, disposable loopback socket. */
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import { once } from 'node:events'
|
|
4
|
+
import { readFileSync, readdirSync, writeFileSync } from 'node:fs'
|
|
5
|
+
import { request } from 'node:http'
|
|
6
|
+
import { join } from 'node:path'
|
|
7
|
+
import { json } from 'node:stream/consumers'
|
|
8
|
+
import {
|
|
9
|
+
backupDocument, createReport, makeProfile, serveHandler, stubGithub, tempDir,
|
|
10
|
+
TEST_GIST_ID as ID, TEST_TOKEN, useProfile,
|
|
11
|
+
} from './harness.mjs'
|
|
12
|
+
|
|
13
|
+
const { check, finish } = createReport('reviewed restore HTTP progress')
|
|
14
|
+
const home = tempDir('dpg-progress-http-')
|
|
15
|
+
useProfile(join(home, 'profiles', 'test'), home)
|
|
16
|
+
process.env.HOME = process.env.USERPROFILE = home
|
|
17
|
+
process.env.PATH = join(home, 'no-executables')
|
|
18
|
+
for (const key of ['DSH_GITHUB_TOKEN', 'GITHUB_TOKEN', 'GH_TOKEN']) delete process.env[key]
|
|
19
|
+
// Only node:http below talks to the ephemeral server. Even a fetch accidentally
|
|
20
|
+
// forwarded by the Gist stub cannot reach a real Gist, DSH instance, or registry.
|
|
21
|
+
const originalFetch = globalThis.fetch
|
|
22
|
+
globalThis.fetch = async () => { throw new Error('unexpected network access from restore fixture') }
|
|
23
|
+
const { BASE_PATH, registerRoutes } = await import('../lib/routes.js')
|
|
24
|
+
const { WORK_DIR } = await import('../lib/backup.js')
|
|
25
|
+
|
|
26
|
+
const NDJSON = 'application/x-ndjson'
|
|
27
|
+
const NOTE = 'data/note.json'
|
|
28
|
+
const REVIEWED = '{"revision":"reviewed"}'
|
|
29
|
+
const applied = { changed: true, application: 'applied' }
|
|
30
|
+
const modes = {
|
|
31
|
+
combined: ['sync/preview', 'sync/install'], config: ['config/preview', 'config/restore'], local: ['preview', 'restore'],
|
|
32
|
+
}
|
|
33
|
+
const receiptKeys = {
|
|
34
|
+
combined: ['complete', 'plugins', 'ref', 'report', 'restart', 'warnings'],
|
|
35
|
+
config: ['ref', 'report', 'restart', 'warnings'], local: ['report'],
|
|
36
|
+
}
|
|
37
|
+
function document(dependencies = {}, bundles = Object.keys(dependencies)) {
|
|
38
|
+
const doc = backupDocument('sender', [
|
|
39
|
+
{ path: NOTE, lines: [REVIEWED] },
|
|
40
|
+
{ path: 'cordis.yml', lines: ['plugins:', ' some-plugin: {}', ''] }, // identical: files must count writes, not candidates
|
|
41
|
+
])
|
|
42
|
+
Object.assign(doc.files[0].json, { dependencies, dsh: { profile: { bundles } } })
|
|
43
|
+
return doc
|
|
44
|
+
}
|
|
45
|
+
function deferred() {
|
|
46
|
+
let resolve
|
|
47
|
+
const promise = new Promise(done => { resolve = done })
|
|
48
|
+
return { promise, resolve }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const mime = res => res.headers['content-type']?.split(';')[0].trim().toLowerCase()
|
|
52
|
+
async function jsonReply(pending, status = 200) {
|
|
53
|
+
const res = await pending
|
|
54
|
+
assert.equal(mime(res), 'application/json')
|
|
55
|
+
const payload = await json(res)
|
|
56
|
+
assert.equal(res.statusCode, status, JSON.stringify(payload).slice(0, 300))
|
|
57
|
+
return payload
|
|
58
|
+
}
|
|
59
|
+
// Decode complete wire lines, never equate a TCP chunk with a JSON record.
|
|
60
|
+
// Yield before EOF: taking response.text()/joining chunks here would deadlock the barrier tests.
|
|
61
|
+
async function* frames(res) {
|
|
62
|
+
assert.equal(res.statusCode, 200)
|
|
63
|
+
assert.equal(mime(res), NDJSON)
|
|
64
|
+
res.setEncoding('utf8')
|
|
65
|
+
let pending = ''
|
|
66
|
+
for await (const chunk of res) {
|
|
67
|
+
pending += chunk
|
|
68
|
+
let end
|
|
69
|
+
while ((end = pending.indexOf('\n')) !== -1) {
|
|
70
|
+
const line = pending.slice(0, end)
|
|
71
|
+
pending = pending.slice(end + 1)
|
|
72
|
+
yield JSON.parse(line)
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
assert.equal(pending, '', 'unterminated NDJSON frame')
|
|
76
|
+
}
|
|
77
|
+
async function collect(pending, observe) {
|
|
78
|
+
const events = []
|
|
79
|
+
for await (const frame of frames(await pending)) { events.push(frame); await observe?.(frame) }
|
|
80
|
+
return events
|
|
81
|
+
}
|
|
82
|
+
function terminal(events, type) {
|
|
83
|
+
assert.ok(events.slice(0, -1).every(e => e.type === 'progress'), 'the terminal frame must be unique and last')
|
|
84
|
+
assert.equal(events.at(-1)?.type, type)
|
|
85
|
+
return events.at(-1)
|
|
86
|
+
}
|
|
87
|
+
async function refusal(pending, status, code) {
|
|
88
|
+
const res = await pending
|
|
89
|
+
const e = mime(res) === NDJSON ? terminal(await collect(res), 'error') : await jsonReply(res, status)
|
|
90
|
+
assert.equal(e.code, code)
|
|
91
|
+
assert.ok(typeof e.error === 'string' && e.error)
|
|
92
|
+
}
|
|
93
|
+
function receipt(result, mode, plan) {
|
|
94
|
+
assert.deepEqual(Object.keys(result).sort(), receiptKeys[mode], 'old unwrapped receipt')
|
|
95
|
+
assert.deepEqual(result.report.files, plan.preview.files)
|
|
96
|
+
assert.equal(result.report.restored, plan.preview.files.filter(f => f.status !== 'identical').length)
|
|
97
|
+
if (mode !== 'local') assert.deepEqual(result.ref, plan.ref)
|
|
98
|
+
}
|
|
99
|
+
function streamResult(events, mode, plan, approved = []) {
|
|
100
|
+
const { result } = terminal(events, 'result')
|
|
101
|
+
receipt(result, mode, plan)
|
|
102
|
+
const progress = events.slice(0, -1)
|
|
103
|
+
const stages = progress.map(e => e.stage).filter((s, i, all) => i === 0 || s !== all[i - 1])
|
|
104
|
+
assert.deepEqual(stages, ['check', 'write', ...(approved.length ? ['install'] : []), 'verify'])
|
|
105
|
+
let processed = 0
|
|
106
|
+
for (const e of progress) {
|
|
107
|
+
// Progress is display metadata, not a second channel for specs, logs, paths or backup bytes.
|
|
108
|
+
const allowed = ['type', 'stage']
|
|
109
|
+
if (e.stage === 'install' || e.stage === 'verify') {
|
|
110
|
+
allowed.push('files', 'processed', 'total')
|
|
111
|
+
assert.equal(e.files, result.report.restored)
|
|
112
|
+
if (e.stage === 'install' || e.processed !== undefined) {
|
|
113
|
+
assert.ok(Number.isSafeInteger(e.processed) && e.processed >= processed && e.processed <= approved.length)
|
|
114
|
+
processed = e.processed
|
|
115
|
+
}
|
|
116
|
+
if (e.stage === 'install' || e.total !== undefined) assert.equal(e.total, approved.length)
|
|
117
|
+
}
|
|
118
|
+
if (e.stage === 'install') {
|
|
119
|
+
allowed.push('current')
|
|
120
|
+
assert.ok(e.current === null || approved.includes(e.current), `not an approved package name: ${e.current}`)
|
|
121
|
+
}
|
|
122
|
+
assert.ok(Object.keys(e).every(k => allowed.includes(k)), JSON.stringify(e))
|
|
123
|
+
}
|
|
124
|
+
return result
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
let serial = 0
|
|
128
|
+
async function scenario(label, doc, run) {
|
|
129
|
+
const profile = makeProfile(join(home, 'profiles', `case-${++serial}`), { dependencies: { 'receiver-only': '1.0.0' }, bundles: [] })
|
|
130
|
+
useProfile(profile, home)
|
|
131
|
+
const repo = stubGithub({ gistId: ID, document: doc })
|
|
132
|
+
const manager = {
|
|
133
|
+
lookups: 0, calls: [], cancellations: [],
|
|
134
|
+
names: () => [], install: spec => { throw new Error(`unexpected fixture install: ${spec}`) },
|
|
135
|
+
listPlugins: () => [],
|
|
136
|
+
listBundles() { return this.names().map(name => ({ name, availability: 'profile', installed: true })) },
|
|
137
|
+
installBundle(spec, options) { this.calls.push({ spec, options }); return this.install(spec) },
|
|
138
|
+
cancelInstall(id) { this.cancellations.push(id); return { status: 'cancelled' } },
|
|
139
|
+
}
|
|
140
|
+
let handler
|
|
141
|
+
const webServer = { register(route) { handler = route.handler; return () => {} } }
|
|
142
|
+
const dispose = registerRoutes({ get(name) {
|
|
143
|
+
if (name === 'webServer') return webServer
|
|
144
|
+
if (name === 'pluginManager') { manager.lookups++; return manager }
|
|
145
|
+
} })
|
|
146
|
+
const disconnected = deferred()
|
|
147
|
+
const served = await serveHandler((req, res) => {
|
|
148
|
+
if (req.url.endsWith('/sync/install') && req.headers.accept === NDJSON) {
|
|
149
|
+
res.once('close', () => { if (!res.writableFinished) disconnected.resolve() })
|
|
150
|
+
}
|
|
151
|
+
handler(req, res)
|
|
152
|
+
})
|
|
153
|
+
const controller = new AbortController()
|
|
154
|
+
const post = (route, body, accept) => new Promise((resolve, reject) => {
|
|
155
|
+
const req = request(`${served.base}${BASE_PATH}/api/${route}`, {
|
|
156
|
+
method: 'POST', agent: false, signal: controller.signal,
|
|
157
|
+
headers: { 'content-type': 'application/json', ...(accept ? { accept } : {}) },
|
|
158
|
+
}, resolve)
|
|
159
|
+
req.once('error', reject)
|
|
160
|
+
req.end(JSON.stringify(body))
|
|
161
|
+
})
|
|
162
|
+
const preview = mode => jsonReply(post(modes[mode][0], mode === 'local' ? { reviewed: true, backup: doc } : { id: ID, token: TEST_TOKEN }))
|
|
163
|
+
const confirm = (mode, planId, accept) => post(modes[mode][1], { planId, confirm: true }, accept)
|
|
164
|
+
const releases = []
|
|
165
|
+
const barrier = () => {
|
|
166
|
+
const entered = deferred(), done = deferred()
|
|
167
|
+
releases.push(done.resolve)
|
|
168
|
+
return { entered: entered.promise, hold() { entered.resolve(); return done.promise }, release: done.resolve }
|
|
169
|
+
}
|
|
170
|
+
const gistReads = n => assert.deepEqual(repo.calls.map(c => [c.method, c.path]), Array.from({ length: n }, () => ['GET', `/gists/${ID}`]))
|
|
171
|
+
const note = () => readFileSync(join(profile, NOTE), 'utf8')
|
|
172
|
+
const undoPoints = () => readdirSync(join(profile, WORK_DIR, 'undo')).sort()
|
|
173
|
+
let timer
|
|
174
|
+
try {
|
|
175
|
+
await Promise.race([
|
|
176
|
+
run({ profile, doc, manager, post, preview, confirm, barrier, disconnected: disconnected.promise, note, undoPoints, gistReads }),
|
|
177
|
+
new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`timed out waiting for ${label}`)), 8_000) }),
|
|
178
|
+
])
|
|
179
|
+
check(label, true)
|
|
180
|
+
} catch (error) {
|
|
181
|
+
check(label, false, error.stack)
|
|
182
|
+
} finally {
|
|
183
|
+
clearTimeout(timer)
|
|
184
|
+
for (const release of releases) release()
|
|
185
|
+
controller.abort()
|
|
186
|
+
dispose()
|
|
187
|
+
const server = served.close()
|
|
188
|
+
const closed = once(server, 'close')
|
|
189
|
+
server.closeAllConnections()
|
|
190
|
+
try { await closed } finally { repo.restore() }
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const names = ['@fixture/first', 'fixture-rejected', 'fixture-unseen']
|
|
195
|
+
const late = 'fixture-initially-present'
|
|
196
|
+
const dependencies = Object.fromEntries([...names, late].map(name => [name, '1.2.3']))
|
|
197
|
+
const spec = name => `${name}@1.2.3`
|
|
198
|
+
const combined = document(dependencies, [...names, late, 'fixture-without-source'])
|
|
199
|
+
await scenario('live 0/3 and 2/3, only approved names; final inventory can contradict installer success', combined, async t => {
|
|
200
|
+
const { manager } = t
|
|
201
|
+
const first = t.barrier(), third = t.barrier()
|
|
202
|
+
const present = []
|
|
203
|
+
// The fourth package vanishes after the consent check. Now resolvable and missing,
|
|
204
|
+
// it still was not approved; the bundle with no source is never a target either.
|
|
205
|
+
manager.names = () => [...present, ...(t.note() !== REVIEWED ? [late] : [])]
|
|
206
|
+
manager.install = async target => {
|
|
207
|
+
if (target === spec(names[0])) { await first.hold(); present.push(names[0]); return applied }
|
|
208
|
+
if (target === spec(names[1])) throw new Error('fixture installation refused')
|
|
209
|
+
if (target === spec(names[2])) { await third.hold(); return applied } // absent in final inventory!
|
|
210
|
+
throw new Error(`unapproved target: ${target}`)
|
|
211
|
+
}
|
|
212
|
+
const plan = await t.preview('combined')
|
|
213
|
+
assert.deepEqual(plan.plugins.missing.filter(p => p.resolvable).map(p => p.name), names)
|
|
214
|
+
assert.ok(plan.plugins.installed.includes(late))
|
|
215
|
+
const observed = []
|
|
216
|
+
const events = await collect(t.confirm('combined', plan.planId, NDJSON), async e => {
|
|
217
|
+
if (e.type !== 'progress' || e.stage !== 'install') return
|
|
218
|
+
const index = names.indexOf(e.current)
|
|
219
|
+
if (![0, 2].includes(index) || observed.includes(index)) return
|
|
220
|
+
const gate = index === 0 ? first : third
|
|
221
|
+
await gate.entered
|
|
222
|
+
assert.equal(t.note(), REVIEWED, 'file write finished before install')
|
|
223
|
+
assert.deepEqual([e.processed, e.total], [index, 3], 'failed attempts also count as processed')
|
|
224
|
+
observed.push(index)
|
|
225
|
+
gate.release() // the manager cannot finish until its current event is decoded at the client
|
|
226
|
+
})
|
|
227
|
+
assert.deepEqual(observed, [0, 2])
|
|
228
|
+
const result = streamResult(events, 'combined', plan, names)
|
|
229
|
+
for (const [i, name] of names.entries()) {
|
|
230
|
+
assert.ok(events.some(e => e.stage === 'install' && e.current === name && e.processed === i), `missing handoff: ${name}`)
|
|
231
|
+
}
|
|
232
|
+
assert.ok(events.some(e => e.processed === names.length && e.total === names.length), 'all three attempts were processed, not three successes')
|
|
233
|
+
assert.deepEqual(manager.calls.map(c => c.spec), names.map(spec))
|
|
234
|
+
assert.ok(manager.calls.every(c => !c.options?.approvedBuilds?.length))
|
|
235
|
+
assert.equal(result.complete, false)
|
|
236
|
+
assert.deepEqual(names.map(n => result.plugins.results.find(p => p.name === n)?.outcome), ['installed', 'failed', 'failed'])
|
|
237
|
+
assert.ok(result.plugins.missing.some(p => p.name === names[2]), 'last applied call never became present')
|
|
238
|
+
assert.ok(result.plugins.missing.some(p => p.name === late), 'new gap was not silently installed')
|
|
239
|
+
await refusal(t.confirm('combined', plan.planId, NDJSON), 409, 'stale-plan')
|
|
240
|
+
t.gistReads(1)
|
|
241
|
+
})
|
|
242
|
+
|
|
243
|
+
for (const mode of ['config', 'local']) {
|
|
244
|
+
await scenario(`${mode}: checked file writes and verification only; old JSON callers keep the receipt`, document({ 'fixture-missing': '1.2.3' }), async t => {
|
|
245
|
+
const plan = await t.preview(mode)
|
|
246
|
+
const events = await collect(t.confirm(mode, plan.planId, NDJSON))
|
|
247
|
+
const result = streamResult(events, mode, plan)
|
|
248
|
+
assert.ok(result.report.restored > 0)
|
|
249
|
+
assert.equal(t.note(), REVIEWED)
|
|
250
|
+
await refusal(t.confirm(mode, plan.planId, NDJSON), 409, 'stale-plan')
|
|
251
|
+
const again = await t.preview(mode)
|
|
252
|
+
receipt(await jsonReply(t.confirm(mode, again.planId)), mode, again)
|
|
253
|
+
if (mode === 'local') { // the original raw-backup operation is not a reviewed stream, even with this Accept
|
|
254
|
+
const raw = await jsonReply(t.post('restore', { backup: t.doc, confirm: true }, NDJSON))
|
|
255
|
+
assert.deepEqual(Object.keys(raw), ['report'])
|
|
256
|
+
}
|
|
257
|
+
assert.equal(t.manager.lookups, 0, 'no inventory or installation for file-only restores')
|
|
258
|
+
t.gistReads(mode === 'config' ? 2 : 0)
|
|
259
|
+
})
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
await scenario('Accept opts into feedback, not extra authority: all three modes still require the reviewed request', document(), async t => {
|
|
263
|
+
const before = t.note()
|
|
264
|
+
for (const [mode, [, path]] of Object.entries(modes)) {
|
|
265
|
+
const { planId } = await t.preview(mode)
|
|
266
|
+
await refusal(t.post(path, { planId, confirm: 'true' }, NDJSON), 400, 'invalid')
|
|
267
|
+
const extra = mode === 'combined' ? { spec: 'not-approved@8.0.0' } : { backup: t.doc }
|
|
268
|
+
await refusal(t.post(path, { planId, confirm: true, ...extra }, NDJSON), 400, 'invalid')
|
|
269
|
+
}
|
|
270
|
+
assert.equal(t.note(), before)
|
|
271
|
+
assert.deepEqual(t.manager.calls, [])
|
|
272
|
+
t.gistReads(2)
|
|
273
|
+
})
|
|
274
|
+
|
|
275
|
+
await scenario('combined confirmations keep old JSON unless NDJSON is acceptable', document(), async t => {
|
|
276
|
+
for (const accept of [undefined, '*/*', `application/json, ${NDJSON};q=0`]) {
|
|
277
|
+
const plan = await t.preview('combined')
|
|
278
|
+
const result = await jsonReply(t.confirm('combined', plan.planId, accept))
|
|
279
|
+
receipt(result, 'combined', plan)
|
|
280
|
+
assert.equal(result.complete, true)
|
|
281
|
+
}
|
|
282
|
+
assert.deepEqual(t.manager.calls, [])
|
|
283
|
+
t.gistReads(3)
|
|
284
|
+
})
|
|
285
|
+
|
|
286
|
+
await scenario('write failure after progress ends in one coded error; it neither installs nor replays', document({ 'fixture-missing': '1.2.3' }), async t => {
|
|
287
|
+
const plan = await t.preview('combined')
|
|
288
|
+
const before = t.note()
|
|
289
|
+
writeFileSync(join(t.profile, WORK_DIR), 'cannot create undo snapshot here')
|
|
290
|
+
const events = await collect(t.confirm('combined', plan.planId, NDJSON))
|
|
291
|
+
const error = terminal(events, 'error')
|
|
292
|
+
assert.equal(error.code, 'other')
|
|
293
|
+
assert.ok(typeof error.error === 'string' && error.error)
|
|
294
|
+
assert.deepEqual([...new Set(events.slice(0, -1).map(e => e.stage))], ['check', 'write'])
|
|
295
|
+
assert.equal(t.note(), before)
|
|
296
|
+
await refusal(t.confirm('combined', plan.planId, NDJSON), 409, 'stale-plan')
|
|
297
|
+
assert.deepEqual(t.manager.calls, [])
|
|
298
|
+
t.gistReads(1)
|
|
299
|
+
})
|
|
300
|
+
|
|
301
|
+
const pair = ['fixture-held', 'fixture-next']
|
|
302
|
+
await scenario('reader disconnect keeps single-writer lock, finishes exactly once, and cannot replay', document(Object.fromEntries(pair.map(n => [n, '1.2.3']))), async t => {
|
|
303
|
+
const held = t.barrier(), rechecked = deferred()
|
|
304
|
+
const present = []
|
|
305
|
+
t.manager.names = () => { if (present.length === pair.length) rechecked.resolve(); return present }
|
|
306
|
+
t.manager.install = async target => {
|
|
307
|
+
if (target === spec(pair[0])) await held.hold()
|
|
308
|
+
present.push(target.split('@')[0])
|
|
309
|
+
return applied
|
|
310
|
+
}
|
|
311
|
+
const plan = await t.preview('combined')
|
|
312
|
+
const res = await t.confirm('combined', plan.planId, NDJSON)
|
|
313
|
+
for await (const e of frames(res)) {
|
|
314
|
+
if (e.stage === 'install' && e.current === pair[0]) {
|
|
315
|
+
await held.entered
|
|
316
|
+
res.destroy() // a real TCP disconnect, not an ignored local progress callback
|
|
317
|
+
break
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
await t.disconnected // server observed socket close before trying a concurrent writer
|
|
321
|
+
assert.equal(t.note(), REVIEWED)
|
|
322
|
+
const undo = t.undoPoints()
|
|
323
|
+
assert.equal(undo.length, 1)
|
|
324
|
+
const marker = '{"after":"disconnect"}'
|
|
325
|
+
writeFileSync(join(t.profile, NOTE), marker)
|
|
326
|
+
await refusal(t.post('undo', {}), 409, 'busy')
|
|
327
|
+
await refusal(t.confirm('combined', plan.planId, NDJSON), 409, 'busy')
|
|
328
|
+
assert.deepEqual(t.manager.calls.map(c => c.spec), [spec(pair[0])])
|
|
329
|
+
held.release()
|
|
330
|
+
await rechecked.promise // the second item and actual final inventory ran without a reader
|
|
331
|
+
await refusal(t.confirm('combined', plan.planId, NDJSON), 409, 'stale-plan')
|
|
332
|
+
assert.deepEqual(t.manager.calls.map(c => c.spec), pair.map(spec))
|
|
333
|
+
assert.deepEqual(t.manager.cancellations, [])
|
|
334
|
+
assert.deepEqual(t.undoPoints(), undo)
|
|
335
|
+
assert.equal(t.note(), marker, 'neither reconnect nor replay may repeat the file writes')
|
|
336
|
+
t.gistReads(1)
|
|
337
|
+
})
|
|
338
|
+
|
|
339
|
+
globalThis.fetch = originalFetch
|
|
340
|
+
process.exitCode = finish()
|