-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathremove-all-pieces.ts
More file actions
240 lines (208 loc) · 8.49 KB
/
Copy pathremove-all-pieces.ts
File metadata and controls
240 lines (208 loc) · 8.49 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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
/**
* CLI entrypoint for removing all pieces from a Data Set.
*
* Responsibilities:
* - Validate required CLI arguments (dataSet)
* - Initialize Synapse with CLI auth/env configuration
* - Prompt user for confirmation (unless --force is specified)
* - Wire up progress events to spinner output
* - Return aggregated results (or throw on failure)
*/
import { confirm, isCancel } from '@clack/prompts'
import pc from 'picocolors'
import pino from 'pino'
import { setIncompleteExitCode } from '../common/cli-errors.js'
import { type RemoveAllPiecesProgressEvents, removeAllPieces } from '../core/piece/index.js'
import { initializeSynapse } from '../core/synapse/index.js'
import { parseCLIAuth } from '../utils/cli-auth.js'
import { cancel, createSpinner, intro, isInteractive, outro } from '../utils/cli-helpers.js'
import { log } from '../utils/cli-logger.js'
import type { RmAllPiecesOptions, RmAllPiecesResult } from './types.js'
/**
* Run the remove all pieces process.
*
* @param options - CLI options including dataSet id and force flag
* @returns Aggregated removal results
*
* Behavior:
* - Requires `dataSet`; throws if missing/invalid
* - Uses CLI auth env/flags via parseCLIAuth
* - Prompts for confirmation unless --force is specified
* - Streams progress to spinner and exits with cancel on failure
* - Always calls cleanupSynapseService to close providers
*/
export async function runRmAllPieces(options: RmAllPiecesOptions): Promise<RmAllPiecesResult> {
intro(pc.bold('Filecoin Pin Remove All'))
const spinner = createSpinner()
// Initialize logger (silent for CLI output)
const logger = pino({
level: process.env.LOG_LEVEL || 'silent',
})
const { dataSet, force } = options
// Validate dataSet
if (!dataSet) {
spinner.stop(`${pc.red('✗')} DataSet ID is required`)
cancel('Remove cancelled')
throw new Error('DataSet ID is required')
}
const dataSetId = Number(dataSet)
if (!Number.isInteger(dataSetId) || dataSetId <= 0) {
spinner.stop(`${pc.red('✗')} DataSet ID must be a positive integer`)
cancel('Remove cancelled')
throw new Error('DataSet ID must be a positive integer')
}
try {
spinner.start('Initializing Synapse SDK...')
const authConfig = await parseCLIAuth(options)
const synapse = await initializeSynapse(authConfig, logger)
const network = synapse.chain.name
spinner.stop(`${pc.green('✓')} Connected to ${pc.bold(network)}`)
// Create storage context to fetch pieces
spinner.start('Fetching pieces from DataSet...')
const storage = await synapse.storage.createContext({ dataSetId: BigInt(dataSetId) })
// Get piece count for confirmation
const { pieces: allPieces } = await import('../core/data-set/get-data-set-pieces.js').then((m) =>
m.getDataSetPieces(synapse, BigInt(dataSetId), storage.provider.pdp?.serviceURL ?? '', { logger })
)
const { PieceStatus } = await import('../core/data-set/types.js')
const activePieces = allPieces.filter((p) => p.status === PieceStatus.ACTIVE)
const pendingRemovalPieces = allPieces.filter((p) => p.status === PieceStatus.PENDING_REMOVAL)
const pieceCount = activePieces.length
const pendingRemovalCount = pendingRemovalPieces.length
if (pendingRemovalCount > 0) {
spinner.stop(
`${pc.green('✓')} Found ${pc.bold(String(pieceCount))} active piece(s) in DataSet ${dataSetId} (${pendingRemovalCount} already pending removal)`
)
} else {
spinner.stop(`${pc.green('✓')} Found ${pc.bold(String(pieceCount))} piece(s) in DataSet ${dataSetId}`)
}
if (pieceCount === 0) {
if (pendingRemovalCount > 0) {
outro(`No active pieces to remove (${pendingRemovalCount} piece(s) already pending removal)`)
} else {
outro('No pieces to remove')
}
return {
dataSetId,
totalPieces: 0,
removedCount: 0,
failedCount: 0,
transactions: [],
}
}
// Confirmation prompt (unless --force is specified)
if (!force) {
if (!isInteractive()) {
spinner.stop(`${pc.red('✗')} Confirmation required. Use --force to skip in interactive mode`)
cancel('Remove cancelled')
throw new Error('Confirmation required for destructive operation')
}
log.line('')
log.line(pc.yellow(`⚠ WARNING: This will remove ALL ${pieceCount} piece(s) from DataSet ${dataSetId}`))
log.line(pc.yellow(' This action cannot be undone.'))
log.flush()
const shouldProceed = await confirm({
message: `Are you sure you want to remove all ${pieceCount} pieces?`,
initialValue: false,
})
if (isCancel(shouldProceed) || !shouldProceed) {
cancel('Remove cancelled by user')
// User declined the destructive confirmation: not a failure, but the
// removal did not happen. Signal "incomplete" (2) distinctly from both
// success (0) and a caught error (1), matching `data-set terminate`.
setIncompleteExitCode()
return {
dataSetId,
totalPieces: pieceCount,
removedCount: 0,
failedCount: 0,
transactions: [],
}
}
}
// Track removal progress
let currentPiece = 0
let totalPieces = pieceCount
const onProgress = (event: RemoveAllPiecesProgressEvents): void => {
switch (event.type) {
case 'removeAll:fetching':
spinner.message('Fetching pieces...')
break
case 'removeAll:fetched':
totalPieces = event.data.totalPieces
spinner.message(`Found ${totalPieces} pieces`)
break
case 'removeAll:removing':
currentPiece = event.data.current
spinner.message(`Removing piece ${currentPiece}/${totalPieces}...`)
break
case 'removeAll:removed':
spinner.message(`${pc.green('✓')} Removed ${event.data.current}/${totalPieces}`)
break
case 'removeAll:failed':
spinner.message(`${pc.red('✗')} Failed ${event.data.current}/${totalPieces}: ${event.data.error}`)
break
case 'removeAll:complete':
// Main flow will handle stopping the spinner
break
}
}
spinner.start('Removing pieces...')
const result = await removeAllPieces(storage, {
synapse,
logger,
onProgress,
waitForConfirmation: options.waitForConfirmation ?? false,
pieces: activePieces,
})
// Per-piece failures are collected by the core function rather than
// thrown, so surface them through the exit code here: any failed piece
// means the command failed (1), which takes precedence over incomplete.
if (result.failedCount > 0) {
process.exitCode = 1
}
// Time-out waiting for requested confirmation on one or more removals,
// leaving them unconfirmed. Signal that distinctly so scripts can tell it
// apart from both success (0) and a caught error (1).
const confirmationPending = options.waitForConfirmation === true && result.confirmedCount < result.removedCount
if (confirmationPending) {
setIncompleteExitCode()
}
// Ensure spinner is stopped before displaying results
const spinnerIcon = result.failedCount > 0 ? pc.red('✗') : pc.green('✓')
spinner.stop(
`${spinnerIcon} Removal complete: ${result.removedCount}/${result.totalPieces} succeeded, ${result.failedCount} failed`
)
// Display results
const resultLines = [
pc.gray(`Total Pieces: ${result.totalPieces}`),
pc.gray(`Removed: ${result.removedCount}`),
pc.gray(`Failed: ${result.failedCount}`),
pc.gray(`Network: ${network}`),
]
const failures = result.transactions.filter((t) => !t.success)
for (const f of failures) {
resultLines.push(pc.red(` ${f.pieceCid}: ${f.error ?? 'unknown error'}`))
}
log.spinnerSection('Results', resultLines)
if (result.failedCount > 0) {
outro(`Remove completed with ${result.failedCount} failure(s)`)
} else if (confirmationPending) {
outro('Remove submitted; confirmation still pending')
} else {
outro('Remove completed successfully')
}
return {
dataSetId,
totalPieces: result.totalPieces,
removedCount: result.removedCount,
failedCount: result.failedCount,
transactions: result.transactions,
}
} catch (error) {
spinner.stop(`${pc.red('✗')} Remove failed: ${error instanceof Error ? error.message : 'Unknown error'}`)
logger.error({ event: 'rm-all.failed', error }, 'Remove all failed')
cancel('Remove failed')
throw error
}
}