-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbin.js
More file actions
executable file
·345 lines (323 loc) · 14.9 KB
/
Copy pathbin.js
File metadata and controls
executable file
·345 lines (323 loc) · 14.9 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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
#!/usr/bin/env node
import fs from 'node:fs'
import { Readable, Writable } from 'node:stream'
import { fetch, Agent } from 'undici'
import sade from 'sade'
import { S3Client, ListObjectsV2Command, HeadObjectCommand } from '@aws-sdk/client-s3'
import dotenv from 'dotenv'
import { Parse, Stringify } from 'ndjson-web'
import * as dagJSON from '@ipld/dag-json'
import { Parallel } from 'parallel-transform-web'
import retry from 'p-retry'
import * as Link from 'multiformats/link'
const pkg = JSON.parse(fs.readFileSync(new URL('./package.json', import.meta.url)).toString())
const cli = sade('sha256it')
const concurrency = 50
const dispatcher = new Agent({ headersTimeout: 900e3 })
dotenv.config({ path: './.env.local' })
cli
.version(pkg.version)
cli
.command('list')
.alias('ls')
.describe('List keys in a bucket. Note: expects env vars for ACCESS_KEY_ID and SECRET_ACCESS_KEY to be set.')
.option('-e, --endpoint', 'Bucket endpoint.')
.option('-r, --region', 'Bucket region.')
.option('-b, --bucket', 'Bucket name.')
.option('-p, --prefix', 'Key prefix.')
.option('-s, --start-after', 'Start listing after this key.')
.action(async (/** @type {Record<string, string|undefined>} */ options) => {
const accessKeyId = notNully(process.env, 'AWS_ACCESS_KEY_ID', 'missing environment variable')
const secretAccessKey = notNully(process.env, 'AWS_SECRET_ACCESS_KEY', 'missing environment variable')
const { endpoint } = options
const region = notNully(options, 'region', 'missing required option')
const bucket = notNully(options, 'bucket', 'missing required option')
const prefix = options.prefix ?? ''
const startAfter = options['start-after']
const s3 = new S3Client({ region, endpoint, credentials: { accessKeyId, secretAccessKey } })
/** @type {string|undefined} */
let token
await new ReadableStream({
async pull (controller) {
const cmd = new ListObjectsV2Command({ Bucket: bucket, Prefix: prefix, StartAfter: startAfter, MaxKeys: 1000, ContinuationToken: token })
const res = await s3.send(cmd)
for (const obj of res.Contents ?? []) {
if (!obj.Key || !obj.Key.endsWith('.car')) continue
controller.enqueue(`${JSON.stringify({ region, bucket, key: obj.Key })}\n`)
}
if (!res.IsTruncated) {
return controller.close()
}
token = res.NextContinuationToken
}
}).pipeTo(Writable.toWeb(process.stdout))
})
cli
.command('hash [key]')
.option('-e, --endpoint', 'Service endpoint.')
.option('-r, --region', 'Bucket region.')
.option('-b, --bucket', 'Bucket name.')
.action(async (/** @type {string|undefined} */ key, /** @type {Record<string, string|undefined>} */ options) => {
const endpoint = new URL(options.endpoint ?? notNully(process.env, 'HASH_SERVICE_ENDPOINT', 'missing required option'))
if (key) {
const region = notNully(options, 'region', 'missing required option')
const bucket = notNully(options, 'bucket', 'missing required option')
const { cid } = await hash(endpoint, region, bucket, key)
return console.log(dagJSON.stringify({ region, bucket, key, cid }))
}
const source = /** @type {ReadableStream<Uint8Array>} */ (Readable.toWeb(process.stdin))
await source
.pipeThrough(/** @type {Parse<{ region?: string, bucket?: string, key: string }>} */ (new Parse()))
.pipeThrough(new Parallel(concurrency, async item => {
const region = item.region ?? notNully(options, 'region', 'missing required option')
const bucket = item.bucket ?? notNully(options, 'bucket', 'missing required option')
const { key } = item
try {
const { cid } = await retry(() => hash(endpoint, region, bucket, key))
return { region, bucket, key, cid }
} catch (err) {
console.warn(`failed hash of ${region}/${bucket}/${key}`, err)
return { region, bucket, key, error: err.message }
}
}))
.pipeThrough(new Stringify(dagJSON.stringify))
.pipeTo(Writable.toWeb(process.stdout))
})
/**
* @param {URL} endpoint
* @param {string} region
* @param {string} bucket
* @param {string} key
* @returns {Promise<{ cid: import('multiformats').Link }>}
*/
const hash = async (endpoint, region, bucket, key) => {
const url = new URL(endpoint)
url.searchParams.set('region', region)
url.searchParams.set('bucket', bucket)
url.searchParams.set('key', key)
const res = await fetch(url, { dispatcher })
const text = await res.text()
if (!res.ok) throw new Error(`hash failed: ${text}`)
return dagJSON.parse(text)
}
cli.command('copy [key] [cid]')
.option('--root', 'DAG root CID (if not derivable from key).')
.option('-e, --endpoint', 'Service endpoint.')
.option('-r, --region', 'Bucket region.')
.option('-b, --bucket', 'Bucket name.')
.action(async (/** @type {string|undefined} */ key, /** @type {string|undefined} */ cidstr, /** @type {Record<string, string|undefined>} */ options) => {
const endpoint = new URL(options.endpoint ?? notNully(process.env, 'COPY_SERVICE_ENDPOINT', 'missing required option'))
if (key && cidstr) {
const region = notNully(options, 'region', 'missing required option')
const bucket = notNully(options, 'bucket', 'missing required option')
const root = options.root ? Link.parse(options.root) : bucketKeyToRootCID(key)
if (!root) throw new Error('missing required option: root')
const cid = Link.parse(cidstr)
try {
// @ts-expect-error
await copy(endpoint, region, bucket, key, cid, root)
return console.log(dagJSON.stringify({ region, bucket, key, cid, root }))
} catch (err) {
console.warn(`failed copy of ${region}/${bucket}/${key}`, err)
return console.log(dagJSON.stringify({ region, bucket, key, cid, root, error: err.message }))
}
}
const source = /** @type {ReadableStream<Uint8Array>} */ (Readable.toWeb(process.stdin))
await source
.pipeThrough(/** @type {Parse<{ region?: string, bucket?: string, key: string, cid: { '/': string }, root?: { '/': string } }|{ error: string }>} */ (new Parse()))
.pipeThrough(new Parallel(concurrency, async item => {
if ('error' in item) return { ...item, error: 'missing shard CID' }
const region = item.region ?? notNully(options, 'region', 'missing required option')
const bucket = item.bucket ?? notNully(options, 'bucket', 'missing required option')
const { key } = item
const cid = Link.parse(item.cid['/'])
const root = item.root
? Link.parse(item.root['/'])
: options.root
? Link.parse(options.root)
: bucketKeyToRootCID(key)
if (!root) throw new Error('missing required option: root')
try {
// @ts-expect-error
await retry(() => copy(endpoint, region, bucket, key, cid, root))
return { region, bucket, key, cid, root }
} catch (err) {
console.warn(`failed copy of ${region}/${bucket}/${key}`, err)
return { region, bucket, key, cid, root, error: err.message }
}
}))
.pipeThrough(new Stringify(dagJSON.stringify))
.pipeTo(Writable.toWeb(process.stdout))
})
/**
* @param {URL} endpoint
* @param {string} region
* @param {string} bucket
* @param {string} key
* @param {import('multiformats').Link} shard
* @param {import('multiformats').UnknownLink} root
*/
const copy = async (endpoint, region, bucket, key, shard, root) => {
const url = new URL(endpoint)
url.searchParams.set('region', region)
url.searchParams.set('bucket', bucket)
url.searchParams.set('key', key)
url.searchParams.set('shard', shard.toString())
url.searchParams.set('root', root.toString())
const res = await fetch(url, { dispatcher })
const text = await res.text()
if (!res.ok) throw new Error(`copy failed: ${text}`)
return dagJSON.parse(text)
}
/** @param {string} key */
const bucketKeyToRootCID = key => {
if (key.startsWith('complete/')) {
const cidstr = key.split('/').pop()?.replace('.car', '')
if (!cidstr) return
return cidstr ? Link.parse(cidstr) : undefined
}
}
/**
* @param {Record<string, string|undefined>} obj
* @param {string} key
*/
const notNully = (obj, key, msg = 'unexpected null value') => {
const value = obj[key]
if (!value) throw new Error(`${msg}: ${key}`)
return value
}
cli.command('head [carCid]')
.describe('Check head response for a car cid at a bucket endpoint')
.example('head bagbaieraaosiqlj4gia2lx35dl7ofqynk7xs47aijrnyrfwny6nea4i6srua -r auto -b carpark --endpoint https://<ACCOUNT_ID>.r2.cloudflarestorage.com')
.option('-e, --endpoint', 'Bucket endpoint. e.g https://<ACCOUNT_ID>.r2.cloudflarestorage.com')
.option('-r, --region', 'Bucket region', 'us-east-1') // "When using the S3 API, the region for an R2 bucket is auto. For compatibility with tools that do not allow you to specify a region, an empty value and us-east-1 will alias to the auto region."
.option('-b, --bucket', 'Bucket name.')
.action(async (/** @type {string|undefined} */ cidstr, /** @type {Record<string, string|undefined>} */ options) => {
const accessKeyId = notNully(process.env, 'DEST_ACCESS_KEY_ID', 'missing environment variable')
const secretAccessKey = notNully(process.env, 'DEST_SECRET_ACCESS_KEY', 'missing environment variable')
const endpoint = options.endpoint ?? notNully(process.env, 'DEST_ENDPOINT', 'missing required environment variable')
const region = options.region ?? notNully(process.env, 'DEST_REGION', 'missing required environment variable')
const bucket = notNully(options, 'bucket', 'missing required option')
const client = new S3Client({ region, endpoint, credentials: { accessKeyId, secretAccessKey }, })
if (cidstr) {
const cid = Link.parse(cidstr)
const res = await head(cid, bucket, region, client)
return console.log(dagJSON.stringify(res))
}
const source = /** @type {ReadableStream<Uint8Array>} */ (Readable.toWeb(process.stdin))
await source
.pipeThrough(/** @type {Parse<{ region?: string, bucket?: string, key: string, cid: { '/': string }, root?: { '/': string } }>} */ (new Parse()))
.pipeThrough(new Parallel(concurrency, item => {
const cid = Link.parse(item.cid['/'])
return head(cid, bucket, region, client)
}))
.pipeThrough(new Stringify(dagJSON.stringify))
.pipeTo(Writable.toWeb(process.stdout))
})
/**
* Check head response for car cid at the given bucket endpoint
* Flag error if status not 200 or content-length: 0
*
* public url access is not enabled on carpark, so we must provide auth
*
* @param {import('multiformats').UnknownLink} cid
* @param {string} bucket
* @param {string} region
* @param {S3Client} client
*/
async function head (cid, bucket, region, client) {
const key = `${cid}/${cid}.car`
try {
const cmd = new HeadObjectCommand({ Bucket: bucket, Key: key })
const res = await client.send(cmd)
const status = res.$metadata.httpStatusCode
if (status === 200) {
const length = res.ContentLength ?? 0
if (length > 0) {
return { cid, region, bucket, key, status, length }
}
console.warn(`error: ${region}/${bucket}/${key} - content-length: 0`)
return { cid, region, bucket, key, status, length, error: `content-length: 0` }
}
console.warn(`error: ${region}/${bucket}/${key} - http status: ${status}`)
return { cid, region, bucket, key, status, error: `http status: ${status}` }
} catch (err) {
console.warn(`error: ${region}/${bucket}/${key}`, err.message ?? err)
return { cid, region, bucket, key, error: err.message ?? err }
}
}
cli
.command('errors')
.describe('filter items that have an `error` property from the ndjson list')
.action(async () => {
const source = /** @type {ReadableStream<Uint8Array>} */ (Readable.toWeb(process.stdin))
await source
.pipeThrough(/** @type {Parse<{}|{ error: string }>} */ (new Parse()))
.pipeThrough(new TransformStream({
transform: (item, controller) => {
if (!('error' in item)) return
controller.enqueue(item)
}
}))
.pipeThrough(new Stringify(dagJSON.stringify))
.pipeTo(Writable.toWeb(process.stdout))
})
cli.command('index [key] [cid]')
.option('-e, --endpoint', 'Service endpoint.')
.option('-r, --region', 'Bucket region.')
.option('-b, --bucket', 'Bucket name.')
.action(async (/** @type {string|undefined} */ key, /** @type {string|undefined} */ cidstr, /** @type {Record<string, string|undefined>} */ options) => {
const endpoint = new URL(options.endpoint ?? notNully(process.env, 'INDEX_SERVICE_ENDPOINT', 'missing required option'))
if (key && cidstr) {
const region = notNully(options, 'region', 'missing required option')
const bucket = notNully(options, 'bucket', 'missing required option')
/** @type {import('multiformats').Link} */
const cid = Link.parse(cidstr)
try {
await index(endpoint, region, bucket, key, cid)
return console.log(dagJSON.stringify({ region, bucket, key, cid }))
} catch (err) {
console.warn(`failed index of ${region}/${bucket}/${key}`, err)
return console.log(dagJSON.stringify({ region, bucket, key, cid, error: err.message }))
}
}
const source = /** @type {ReadableStream<Uint8Array>} */ (Readable.toWeb(process.stdin))
await source
.pipeThrough(/** @type {Parse<{ region?: string, bucket?: string, key: string, cid: { '/': string }, root?: { '/': string } }|{ error: string }>} */ (new Parse()))
.pipeThrough(new Parallel(concurrency, async item => {
if ('error' in item) return { ...item, error: 'missing shard CID' }
const region = item.region ?? notNully(options, 'region', 'missing required option')
const bucket = item.bucket ?? notNully(options, 'bucket', 'missing required option')
const { key } = item
/** @type {import('multiformats').Link} */
const cid = Link.parse(item.cid['/'])
try {
await retry(() => index(endpoint, region, bucket, key, cid))
return { region, bucket, key, cid }
} catch (err) {
console.warn(`failed index of ${region}/${bucket}/${key}`, err)
return { region, bucket, key, cid, error: err.message }
}
}))
.pipeThrough(new Stringify(dagJSON.stringify))
.pipeTo(Writable.toWeb(process.stdout))
})
/**
* @param {URL} endpoint
* @param {string} region
* @param {string} bucket
* @param {string} key
* @param {import('multiformats').Link} shard
*/
const index = async (endpoint, region, bucket, key, shard) => {
const url = new URL(endpoint)
url.searchParams.set('region', region)
url.searchParams.set('bucket', bucket)
url.searchParams.set('key', key)
url.searchParams.set('shard', shard.toString())
const res = await fetch(url, { dispatcher })
const text = await res.text()
if (!res.ok) throw new Error(`index failed: ${text}`)
return dagJSON.parse(text)
}
cli.parse(process.argv)