forked from BravoNatalie/migration-support-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmigration-repair.mjs
More file actions
206 lines (186 loc) · 6.41 KB
/
Copy pathmigration-repair.mjs
File metadata and controls
206 lines (186 loc) · 6.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
#!/usr/bin/env node
/**
* Storacha migration JSON repair tool.
*
* Subcommands:
* scan list shard entries missing pieceCID
* repiece download missing shards, compute pieceCID, checkpoint to SQLite
* patch apply checkpoint to migration JSON (fill pieceCID + rewrite sourceURL)
* validate assert every shard has pieceCID + roundabout sourceURL + sizeBytes>0
*/
import { writeFile } from 'node:fs/promises'
import { jsonStateAdapter } from './adapters/json-state-adapter.mjs'
import { sqliteStateAdapter } from './adapters/sqlite-state-adapter.mjs'
import { openCheckpointDb } from './checkpoint-db.mjs'
import { runRepiece } from './repiece-runner.mjs'
const DEFAULT_CONCURRENCY = 8
const ADAPTERS = {
json: jsonStateAdapter,
sqlite: sqliteStateAdapter,
}
function parseArgs(argv) {
const out = {}
for (let i = 0; i < argv.length; i++) {
const a = argv[i]
if (!a.startsWith('--')) continue
const key = a.slice(2)
const next = argv[i + 1]
if (next && !next.startsWith('--')) {
out[key] = next
i++
} else {
out[key] = true
}
}
return out
}
function usage() {
console.error(`Usage:
migration-repair.mjs scan --input <state.json|state.db> [--format json|sqlite] [--out missing.json]
migration-repair.mjs repiece --input <state.json|state.db> --db <checkpoint.sqlite> [--format json|sqlite] [--concurrency 8] [--limit N]
migration-repair.mjs patch --input <state.json|state.db> --db <checkpoint.sqlite> [--format json|sqlite] [--out patched.json]
migration-repair.mjs validate --input <state.json|state.db> [--format json|sqlite]
migration-repair.mjs manual --input <state.json|state.db> [--format json|sqlite] [--threshold-bytes 1073741824] [--out manual.json]`)
}
function resolveAdapter({ input, format }) {
const explicit = format && String(format).toLowerCase()
if (explicit) {
const adapter = ADAPTERS[explicit]
if (!adapter) {
throw new Error(`unsupported --format: ${format}`)
}
return adapter
}
if (!input) {
throw new Error('--input required')
}
const lowered = String(input).toLowerCase()
if (lowered.endsWith('.json')) return jsonStateAdapter
if (lowered.endsWith('.db') || lowered.endsWith('.sqlite') || lowered.endsWith('.sqlite3')) {
return sqliteStateAdapter
}
throw new Error(`unable to infer state format from ${input}; pass --format json or --format sqlite`)
}
function parsePositiveInteger(value, name) {
const parsed = Number(value)
if (!Number.isFinite(parsed) || parsed < 1) {
throw new Error(`invalid ${name}`)
}
return parsed
}
async function scan(adapter, { input, out }) {
if (!input) throw new Error('--input required')
const report = await adapter.scan(input, { includeMissing: Boolean(out) })
if (out) {
const serializableMissing = (report.missing ?? []).map((item) => ({
...item,
sizeBytes: Number(item.sizeBytes),
}))
await writeFile(out, JSON.stringify(serializableMissing, null, 2))
console.error(`Wrote ${out}`)
return
}
console.log(
JSON.stringify(
{
total: report.totalShardEntries,
withPiece: report.withPieceCID,
missing: report.uniqueMissingCids,
totalBytes: Number(report.totalBytesToDownload),
},
null,
2,
),
)
}
async function repiece(adapter, opts) {
const { input, db: dbPath, concurrency, limit: limitArg } = opts
if (!input || !dbPath) throw new Error('--input and --db required')
const maxConcurrency = concurrency ? parsePositiveInteger(concurrency, '--concurrency') : DEFAULT_CONCURRENCY
const maxItems = limitArg != null ? parsePositiveInteger(limitArg, '--limit') : Infinity
const checkpoint = openCheckpointDb(dbPath)
try {
const summary = await adapter.scan(input, { includeMissing: false })
await runRepiece({
checkpoint,
candidates: adapter.iterateRepairCandidates(input),
concurrency: maxConcurrency,
limit: maxItems,
summary: {
totalCandidates: summary.uniqueMissingCids,
totalBytes: summary.totalBytesToDownload,
},
})
} finally {
checkpoint.close()
}
}
async function patch(adapter, { input, db: dbPath, out }) {
if (!input || !dbPath) throw new Error('--input and --db required')
const checkpoint = openCheckpointDb(dbPath)
try {
const report = await adapter.patch(input, checkpoint, { out })
console.error(`Patched: ${report.patched}`)
console.error(`Moved shardsToStore → shards: ${report.movedToShards}`)
console.error(`Still missing: ${report.stillMissing}`)
if (report.outputPath) {
console.error(`Wrote ${report.outputPath}`)
} else if (report.inPlace) {
console.error(`Patched in place: ${input}`)
}
if (report.stillMissing > 0) process.exitCode = 2
} finally {
checkpoint.close()
}
}
async function validate(adapter, { input }) {
if (!input) throw new Error('--input required')
const report = await adapter.validate(input)
console.log(JSON.stringify(report, null, 2))
if (!report.migratable) process.exitCode = 1
}
async function manual(adapter, { input, 'threshold-bytes': thresholdArg, out }) {
if (!input) throw new Error('--input required')
const threshold = thresholdArg != null ? parsePositiveInteger(thresholdArg, '--threshold-bytes') : 1024 ** 3
const report = await adapter.manual(input, { thresholdBytes: threshold })
console.error(
`skippedUploads: ${report.skippedUploadsCount} (known size: ${report.skippedUploadsBytes} bytes — usually 0, schema has only CIDs)`,
)
console.error(
`largeRoots (>= ${(threshold / 1024 ** 3).toFixed(2)} GiB): ${report.largeRootsCount} (${(report.largeRootsBytes / 1024 ** 3).toFixed(2)} GiB)`,
)
if (out) {
await writeFile(out, JSON.stringify(report, null, 2))
console.error(`Wrote ${out}`)
} else {
console.log(JSON.stringify(report, null, 2))
}
}
const [, , sub, ...rest] = process.argv
const opts = parseArgs(rest)
try {
const adapter = sub ? resolveAdapter(opts) : null
switch (sub) {
case 'scan':
await scan(adapter, opts)
break
case 'repiece':
await repiece(adapter, opts)
break
case 'patch':
await patch(adapter, opts)
break
case 'validate':
await validate(adapter, opts)
break
case 'manual':
await manual(adapter, opts)
break
default:
usage()
process.exit(1)
}
} catch (err) {
console.error(`Error: ${err?.message || err}`)
process.exit(1)
}