-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·318 lines (272 loc) · 7.47 KB
/
index.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
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
#!/usr/bin/env node
const Promise = require('bluebird');
const fs = require('mz/fs');
const request = require('request-promise');
const sha1 = Promise.promisify(require('node-sha1'));
const atmpt = require('atmpt');
const c = require('template-colors');
const prettyBytes = require('pretty-bytes');
const prettyMs = require('pretty-ms');
const bitrate = require('bitrate');
const argv = require('yargs')
.describe('concurrency', 'max concurrent connections')
.describe('path', 'path on b2 container')
.describe('bucket', 'bucket on b2')
.describe('type', 'content-type for the file being uploaded')
.describe('account', 'b2 account')
.describe('key', 'b2 key')
.describe('silent', 'will not output to stderr')
.describe('attempts', 'max upload attempts')
.default('attempts', 30)
.default('type', 'raw')
.default('silent', false)
.default('concurrency', 20)
.default('chunk', 5000000)
.demandOption([
'path',
'bucket',
'account',
'key'
])
.argv;
let b2 = {};
let buffersQueue = [];
let bufferIndex = 1;
let scratchBuffer = [];
let stdinCompleted = false;
let completed = false;
let uploads = [];
let stdinPaused = false;
let concurrency = argv.concurrency;
let uploadedBytes = 0;
let uploadedParts = [];
let isLargeFile = false;
let isSmallFile = false;
const stdin = process.openStdin();
let b2authorized = b2authorize();
let b2uploadStarted = Promise.pending();
if (process.stdin.isTTY) {
console.error('- missing stdin stream');
process.exit();
}
function log (message) {
if (!argv.silent) {
console.log(String(message));
}
}
log(c`b2 upload started`.green.bold);
log(c`- concurrency = ${concurrency}.white.bold`.grey);
stdin.on('data', async chunk => {
scratchBuffer.push(chunk);
let scratchBufferSize = scratchBuffer.map(buffer => buffer.length).reduce((a, b) => a + b, 0);
if (scratchBufferSize > argv.chunk) {
if (bufferIndex === 1) {
isLargeFile = true;
log(c`- uploadtype = ${'largefile'}.white.bold`.grey);
uploadStart();
}
buffersQueue.push({
index: bufferIndex,
scratchBuffer
});
scratchBuffer = [];
bufferIndex++;
}
if (buffersQueue.length >= concurrency) {
stdinPaused = true;
process.stdin.pause();
}
});
stdin.on('end', async () => {
stdinCompleted = true;
if (scratchBuffer.length) {
let scratchBufferSize = scratchBuffer.map(buffer => buffer.length).reduce((a, b) => a + b, 0);
if (bufferIndex > 1 || scratchBufferSize > argv.chunk) {
buffersQueue.push({
index: bufferIndex,
scratchBuffer
});
} else {
isSmallFile = 1;
log(c`- uploadtype = ${'standard'}.white.bold`.grey);
uploadedBytes = scratchBufferSize;
b2uploadStarted.resolve();
await b2uploadFile(scratchBuffer);
completed = 1;
}
scratchBuffer = [];
}
});
function storePart(part) {
return new Promise(async (resolve, reject) => {
await uploadPart(part);
resolve();
});
}
(async () => {
await b2uploadStarted.promise;
while (!completed && (buffersQueue.length || uploads.length || !stdinCompleted)) {
if (uploads.length < concurrency && buffersQueue.length) {
let itemsToUpload = concurrency - uploads.length;
for (let i = 0; i < itemsToUpload && buffersQueue.length; i++) {
uploads.push(
storePart(buffersQueue.shift())
);
}
}
uploads = uploads.filter(upload => !upload.isResolved());
if (!uploads.length && !buffersQueue.length && stdinCompleted) {
completed = true;
} else {
await new Promise(resolve => setImmediate(resolve));
}
if (!stdinCompleted && stdinPaused && buffersQueue.length + uploads.length < concurrency) {
stdinPaused = false;
process.stdin.resume();
}
}
})().catch(console.error);
async function b2authorize () {
let {
apiUrl,
authorizationToken
} = await request.get({
url: 'https://api.backblazeb2.com/b2api/v2/b2_authorize_account',
auth: {
user: argv.account,
password: argv.key
},
json: true
});
log(c`- apiUrl = ${apiUrl}.white.bold\n`.grey);
b2.apiUrl = apiUrl;
b2.authorizationToken = authorizationToken;
}
async function b2startUpload ({path, type}) {
return await atmpt(async attempt => {
log(c`initiating upload`.green);
const {
fileId
} = await request.post({
url: `${b2.apiUrl}/b2api/v2/b2_start_large_file`,
headers: {
Authorization: b2.authorizationToken
},
json: {
fileName: path,
bucketId: argv.bucket,
contentType: type
}
});
b2.fileId = fileId;
}, {maxAttempts: argv.attempts, delay: attempt => attempt * 1000});
}
async function b2uploadPart (part) {
return await atmpt(async attempt => {
let buffer = Buffer.concat(part.scratchBuffer);
let bufferSha1 = await sha1(buffer);
let uploadUrlInfo = await request.post({
url: `${b2.apiUrl}/b2api/v2/b2_get_upload_part_url`,
headers: {
Authorization: b2.authorizationToken
},
json: {
fileId: b2.fileId
}
});
await request.post({
url: uploadUrlInfo.uploadUrl,
headers: {
Authorization: uploadUrlInfo.authorizationToken,
'X-Bz-Part-Number': part.index,
'X-Bz-Content-Sha1': bufferSha1,
},
body: buffer
});
uploadedParts.push({
index: part.index,
sha1: bufferSha1,
bytes: buffer.length
});
}, {maxAttempts: argv.attempts, delay: attempt => attempt * 1000});
}
async function b2uploadFile (scratchBuffer) {
return await atmpt(async attempt => {
await b2authorized;
let buffer = Buffer.concat(scratchBuffer);
let bufferSha1 = await sha1(buffer);
let uploadUrlInfo = await request.post({
url: `${b2.apiUrl}/b2api/v2/b2_get_upload_url`,
headers: {
Authorization: b2.authorizationToken
},
json: {
bucketId: argv.bucket
}
});
await request.post({
url: uploadUrlInfo.uploadUrl,
headers: {
Authorization: uploadUrlInfo.authorizationToken,
'X-Bz-Content-Sha1': bufferSha1,
'X-Bz-File-Name': argv.path,
'Content-Type': argv.type
},
body: buffer
});
}, {maxAttempts: argv.attempts, delay: attempt => attempt * 1000});
}
async function b2completeUpload () {
return await atmpt(async attempt => {
await request.post({
url: `${b2.apiUrl}/b2api/v2/b2_finish_large_file`,
headers: {
Authorization: b2.authorizationToken
},
json: {
fileId: b2.fileId,
partSha1Array: uploadedParts.sort((a, b) => a.index - b.index).map(part => part.sha1)
}
});
}, {maxAttempts: argv.attempts, delay: attempt => attempt * 1000});
}
async function uploadStart () {
await b2authorized;
await b2startUpload({
path: argv.path,
type: argv.type
});
b2uploadStarted.resolve();
}
async function uploadPart (part) {
logProgress();
await b2uploadPart(part);
logProgress();
}
async function uploadComplete () {
if (isLargeFile) {
await b2completeUpload();
}
}
function logProgress () {
uploadedBytes = uploadedParts.map(part => part.bytes).reduce((a, b) => a + b, 0);
if (process.stdout.clearLine && !argv.silent) {
process.stderr.moveCursor(0, -1);
process.stderr.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(c`parts uploaded = ${String(uploadedParts.length)}.bold.white, active = ${String(uploads.length)}.bold.white, uploaded ${prettyBytes(uploadedBytes)}.bold.white\n`.grey.toString());
}
}
(async () => {
while (!isSmallFile && !isLargeFile) {
await Promise.delay(10);
}
await b2uploadStarted.promise;
let startTime = new Date();
while (!completed) {
await Promise.delay(50);
}
await uploadComplete();
let duration = new Date() - startTime;
log(c`\n\nupload completed in ${prettyMs(duration)}.bold.white, at ${bitrate(uploadedBytes, duration/1000, 'mbps').toFixed(2)}.bold.white mb/s`.green.bold);
})().catch(console.error);