-
Notifications
You must be signed in to change notification settings - Fork 1
/
bos.js
212 lines (194 loc) · 7.51 KB
/
bos.js
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
const { uploadChunked } = require('swarm-chunked-upload')
const fs = require('fs')
const { Bee } = require('@ethersphere/bee-js')
const { Promises } = require('cafe-utility')
const axios = require('axios')
const chunkSize = 4096
const dataDir = 'data'
const beeUrl = 'http://127.0.0.1:1633'
const errorFile = 'errors.json'
const defaultFilename = 'The-Book-of-Swarm.pdf'
main()
function write(args) {
process.stdout.clearLine(0);
process.stdout.cursorTo(0);
process.stdout.write(args);
}
function calculateNumberOfChunks(size) {
const refSize = 32
let inputSize = size
let numChunks = 0
while (inputSize > 0) {
numChunks += 1
inputSize -= chunkSize
inputSize += refSize
}
return numChunks + 1 // plus the manifest chunk
}
async function main() {
const command = process.argv[2]
switch (command) {
case 'upload': await upload(); break
case 'check': await check(); break
case 'reupload': await reupload(); break
case 'recheck': await recheck(); break
}
}
function ensureDataDir() {
try {
fs.mkdirSync(dataDir)
} catch (e) {
}
}
async function upload(filename = defaultFilename) {
ensureDataDir()
const data = fs.readFileSync(filename)
const numChunks = calculateNumberOfChunks(data.length)
const dataDir = 'data'
let succesCount = 0
let errorCount = 0
const { bzzReference, context } = await uploadChunked(data, {
filename,
stamp: process.env.STAMP || '0000000000000000000000000000000000000000000000000000000000000000',
beeUrl,
deferred: false,
retries: 1,
onSuccessfulChunkUpload: async (chunk, context) => {
// console.log('✅', `${context.beeUrl}/chunks/${toHexString(chunk.address())}`)
const address = toHexString(chunk.address())
const outputFilename = `${dataDir}/${address}`
fs.writeFileSync(outputFilename, new Uint8Array([...chunk.span(), ...chunk.payload]))
succesCount++
write(`chunks: ${numChunks}, success: ${succesCount}, error: ${errorCount}\r`)
},
onFailedChunkUpload: async (chunk, context) => {
console.error('❌', `${context.beeUrl}/chunks/${toHexString(chunk.address())}`)
errorCount++
write(`chunks: ${numChunks}, success: ${succesCount}, error: ${errorCount}\r`)
}
})
console.log(`chunks: ${numChunks}, success: ${succesCount}, error: ${errorCount}\r`)
console.log('📦', `${context.beeUrl}/bzz/${toHexString(bzzReference)}/`)
}
async function isChunkRetrievable(hash) {
const response = await axios.get(`${beeUrl}/stewardship/${hash}?traverse=false`)
const isRetrievable = response.data.isRetrievable
return isRetrievable
}
async function reupload() {
const concurrency = 50
const stamp = process.env.STAMP || '0000000000000000000000000000000000000000000000000000000000000000'
const queue = Promises.makeAsyncQueue(concurrency)
const bee = new Bee(beeUrl)
const errorJSON = fs.readFileSync(errorFile)
const errorHashes = JSON.parse(errorJSON)
let succesCount = 0
let errorCount = 0
for (const item of errorHashes) {
queue.enqueue(async () => {
try {
const start = Date.now()
// const isRetrievable = await bee.isReferenceRetrievable(item)
const fileData = fs.readFileSync(`${dataDir}/${item}`)
const response = await bee.uploadChunk(stamp, fileData, { deferred: false })
const elapsed = Date.now() - start
if (item === response) {
const isRetrievable = await isChunkRetrievable(item)
if (!isRetrievable) {
throw "error"
}
succesCount++
console.log('✅', `${item}: ${elapsed}, chunks: ${errorHashes.length}, success: ${succesCount}, error: ${errorCount}`)
} else {
errorCount++
console.log('❌', `${item}: ${elapsed}, chunks: ${errorHashes.length}, success: ${succesCount}, error: ${errorCount}`)
// console.error(`content error: ${item}`)
console.debug({swarmData, fileData})
}
} catch (e) {
errorCount++
console.log('❌', `${item}: chunks: ${errorHashes.length}, success: ${succesCount}, error: ${errorCount}`)
console.error(`retrieve error: ${item}`)
}
// console.log(`chunks: ${numChunks}, success: ${succesCount}, error: ${errorCount}\r`)
})
}
await queue.drain()
}
async function checkItems(items) {
const concurrency = 50
const queue = Promises.makeAsyncQueue(concurrency)
const bee = new Bee(beeUrl)
let succesCount = 0
let errorCount = 0
const errors = []
const report = []
const numChunks = items.length
for (const item of items) {
queue.enqueue(async () => {
try {
const start = Date.now()
// const isRetrievable = await bee.isReferenceRetrievable(item)
const response = await axios.get(`${beeUrl}/stewardship/${item}?traverse=false`)
const isRetrievable = response.data.isRetrievable
if (!isRetrievable) {
console.debug(response.data)
throw "error"
}
const swarmData = await bee.downloadChunk(item)
const elapsed = Date.now() - start
const fileData = fs.readFileSync(`${dataDir}/${item}`)
if (bytesEqual(swarmData, fileData)) {
succesCount++
console.log('✅', `${item}: ${elapsed}, chunks: ${numChunks}, success: ${succesCount}, error: ${errorCount}`)
report.push([item, elapsed])
} else {
errorCount++
console.log('❌', `${item}: ${elapsed}, chunks: ${numChunks}, success: ${succesCount}, error: ${errorCount}`)
errors.push(item)
console.debug({swarmData, fileData})
}
} catch (e) {
console.error({e})
errorCount++
console.log('❌', `${item}: chunks: ${numChunks}, success: ${succesCount}, error: ${errorCount}`)
console.error(`retrieve error: ${item}`)
errors.push(item)
}
// console.log(`chunks: ${numChunks}, success: ${succesCount}, error: ${errorCount}\r`)
})
}
await queue.drain()
return {
report,
errors,
}
}
async function check() {
const dir = fs.readdirSync(dataDir)
const reportFile = 'report.csv'
const { report, errors } = await checkItems(dir)
console.log({errors})
fs.writeFileSync(errorFile, JSON.stringify(errors), { })
fs.writeFileSync(reportFile, report.map(([item, elapsed]) => `${item},${elapsed}\n`).join(''))
}
async function recheck() {
const errorJSON = fs.readFileSync(errorFile)
const errorChunks = JSON.parse(errorJSON)
const { report, errors } = await checkItems(errorChunks)
console.log({errors})
}
function bytesEqual(a, b) {
if (a.length !== b.length) {
return false
}
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false
}
}
return true
}
function toHexString(bytes) {
return bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '')
}