This repository has been archived by the owner on Jun 11, 2023. It is now read-only.
forked from backblaze-b2-samples/multithreaded-downloader-js
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathMultiThread.js
159 lines (138 loc) · 4.5 KB
/
MultiThread.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
class MultiThread {
constructor (options) {
if (!window.ReadableStream && !window.WritableStream) {
throw Error('Web Streams are not yet supported in this browser.')
}
Object.assign(this, options)
this.onStart = this.onStart.bind(this) || function () {}
this.onFinish = this.onFinish.bind(this) || function () {}
this.onProgress = this.onProgress.bind(this) || function () {}
this.controller = new AbortController()
this.refreshTime = 1000
this.downloadQueue = []
this.currentRange = null
}
fetch (url, init) {
this.url = new URL(url)
this.requestHeaders = new Headers(init.headers)
return util.fetchRetry(this.url, {
method: 'HEAD',
mode: 'cors',
headers: this.requestHeaders,
signal: this.controller.signal
}).then(response => {
this.contentLength = util.getContentLength(response)
this.bytesWritten = 0
this.ranges = {
total: Math.ceil(this.contentLength / this.rangeSize),
started: 0,
finished: 0
}
const fileStream = streamSaver.createWriteStream(this.fileName, this.contentLength)
this.writer = fileStream.getWriter()
this.writer.writing = false
this.onStart({rangesTotal: this.ranges.total, contentLength: this.contentLength})
this.fetchRange()
this.writeNextRange()
for (let i = 1; i < this.threads; i++) {
this.tryFetch()
}
})
}
fetchRange () {
if (this.ranges.started < this.ranges.total) {
const start = this.ranges.started * this.rangeSize
const end = start + this.rangeSize - 1
const id = this.ranges.started++
let range = new Range({
id: id,
end: end,
start: start,
headers: this.headers,
onStart: this.onRangeStart,
onProgress: this.onRangeProgress,
onFinish: this.onRangeFinish
})
this.downloadQueue.push(range)
return range.fetch(this.url, {
headers: this.requestHeaders,
controller: this.controller
})
}
// No ranges left
return null
}
tryFetch () {
if (this.downloadQueue.length < this.threads) {
this.fetchRange()
} else {
console.log('waiting for slot in queue')
setTimeout(this.tryFetch.bind(this), this.refreshTime)
}
}
writeNextRange () {
let range = this.downloadQueue.find(item => item.id === this.ranges.finished)
if (range) {
// Move range from downloadQueue to this.currentRange
this.downloadQueue = this.downloadQueue.filter(item => item.id !== range.id)
this.currentRange = range
this.writeStream()
} else if (this.ranges.total === this.ranges.finished) {
console.log('finished')
} else {
console.warn('borked')
this.tryFetch()
return setTimeout(this.writeNextRange.bind(this), this.refreshTime)
}
}
writeStream () {
if (!this.currentRange || !this.currentRange.response) {
// Response not ready yet
return setTimeout(this.writeStream.bind(this), this.refreshTime)
}
if (!this.currentRange.response.body.locked) {
this.writer.writing = true
this.currentRange.reader = this.currentRange.response.body.getReader()
const pump = () => this.currentRange.reader.read().then(({done, value}) => {
this.currentRange.doneWriting = done
if (!this.currentRange.doneWriting) {
this.currentRange.bytesWritten += value.byteLength
this.bytesWritten += value.byteLength
this.writer.write(value)
this.onProgress({contentLength: this.contentLength, loaded: this.bytesWritten})
pump()
} else {
this.writer.writing = false
this.ranges.finished++
if (this.ranges.finished < this.ranges.total) {
this.writeNextRange()
this.tryFetch()
} else {
this.writer.close()
this.onFinish()
}
}
}).catch(error => {
if (!this.currentRange.doneWriting) {
console.error(`Range #${this.currentRange.id} failed: `, error)
this.currentRange.retry()
}
})
// Start reading
pump()
} else {
console.log(this.currentRange)
}
}
retryRangeById (id) {
const range = this.writeQueue.find(item => item.id === this.ranges.finished) || this.downloadQueue.find(item => item.id === this.ranges.finished)
range.retry()
}
cancel () {
this.controller.abort()
if (this.writer) {
this.writer.close()
}
return Promise.resolve()
}
}