]>
Commit | Line | Data |
---|---|---|
efda99c3 C |
1 | // From https://github.com/MinEduTDF/idb-chunk-store |
2 | // We use temporary IndexDB (all data are removed on destroy) to avoid RAM issues | |
3 | // Thanks @santiagogil and @Feross | |
4 | ||
5 | import { EventEmitter } from 'events' | |
6 | import Dexie from 'dexie' | |
7 | ||
8 | class ChunkDatabase extends Dexie { | |
9 | chunks: Dexie.Table<{ id: number, buf: Buffer }, number> | |
10 | ||
11 | constructor (dbname: string) { | |
12 | super(dbname) | |
13 | ||
14 | this.version(1).stores({ | |
15 | chunks: 'id' | |
16 | }) | |
17 | } | |
18 | } | |
19 | ||
20 | class ExpirationDatabase extends Dexie { | |
21 | databases: Dexie.Table<{ name: string, expiration: number }, number> | |
22 | ||
23 | constructor () { | |
24 | super('webtorrent-expiration') | |
25 | ||
26 | this.version(1).stores({ | |
27 | databases: 'name,expiration' | |
28 | }) | |
29 | } | |
30 | } | |
31 | ||
32 | export class PeertubeChunkStore extends EventEmitter { | |
33 | private static readonly BUFFERING_PUT_MS = 1000 | |
34 | private static readonly CLEANER_INTERVAL_MS = 1000 * 60 // 1 minute | |
35 | private static readonly CLEANER_EXPIRATION_MS = 1000 * 60 * 5 // 5 minutes | |
36 | ||
37 | chunkLength: number | |
38 | ||
9df52d66 | 39 | private pendingPut: { id: number, buf: Buffer, cb: (err?: Error) => void }[] = [] |
efda99c3 C |
40 | // If the store is full |
41 | private memoryChunks: { [ id: number ]: Buffer | true } = {} | |
42 | private databaseName: string | |
244b4ae3 B |
43 | private putBulkTimeout: any |
44 | private cleanerInterval: any | |
efda99c3 C |
45 | private db: ChunkDatabase |
46 | private expirationDB: ExpirationDatabase | |
47 | private readonly length: number | |
48 | private readonly lastChunkLength: number | |
49 | private readonly lastChunkIndex: number | |
50 | ||
244b4ae3 | 51 | constructor (chunkLength: number, opts: any) { |
efda99c3 C |
52 | super() |
53 | ||
54 | this.databaseName = 'webtorrent-chunks-' | |
55 | ||
56 | if (!opts) opts = {} | |
9df52d66 | 57 | if (opts.torrent?.infoHash) this.databaseName += opts.torrent.infoHash |
efda99c3 C |
58 | else this.databaseName += '-default' |
59 | ||
60 | this.setMaxListeners(100) | |
61 | ||
62 | this.chunkLength = Number(chunkLength) | |
63 | if (!this.chunkLength) throw new Error('First argument must be a chunk length') | |
64 | ||
65 | this.length = Number(opts.length) || Infinity | |
66 | ||
67 | if (this.length !== Infinity) { | |
68 | this.lastChunkLength = (this.length % this.chunkLength) || this.chunkLength | |
69 | this.lastChunkIndex = Math.ceil(this.length / this.chunkLength) - 1 | |
70 | } | |
71 | ||
72 | this.db = new ChunkDatabase(this.databaseName) | |
73 | // Track databases that expired | |
74 | this.expirationDB = new ExpirationDatabase() | |
75 | ||
76 | this.runCleaner() | |
77 | } | |
78 | ||
c199c427 | 79 | put (index: number, buf: Buffer, cb: (err?: Error) => void) { |
efda99c3 C |
80 | const isLastChunk = (index === this.lastChunkIndex) |
81 | if (isLastChunk && buf.length !== this.lastChunkLength) { | |
82 | return this.nextTick(cb, new Error('Last chunk length must be ' + this.lastChunkLength)) | |
83 | } | |
84 | if (!isLastChunk && buf.length !== this.chunkLength) { | |
85 | return this.nextTick(cb, new Error('Chunk length must be ' + this.chunkLength)) | |
86 | } | |
87 | ||
88 | // Specify we have this chunk | |
89 | this.memoryChunks[index] = true | |
90 | ||
91 | // Add it to the pending put | |
92 | this.pendingPut.push({ id: index, buf, cb }) | |
93 | // If it's already planned, return | |
94 | if (this.putBulkTimeout) return | |
95 | ||
96 | // Plan a future bulk insert | |
97 | this.putBulkTimeout = setTimeout(async () => { | |
98 | const processing = this.pendingPut | |
99 | this.pendingPut = [] | |
100 | this.putBulkTimeout = undefined | |
101 | ||
102 | try { | |
103 | await this.db.transaction('rw', this.db.chunks, () => { | |
104 | return this.db.chunks.bulkPut(processing.map(p => ({ id: p.id, buf: p.buf }))) | |
105 | }) | |
106 | } catch (err) { | |
107 | console.log('Cannot bulk insert chunks. Store them in memory.', { err }) | |
108 | ||
9df52d66 C |
109 | processing.forEach(p => { |
110 | this.memoryChunks[p.id] = p.buf | |
111 | }) | |
efda99c3 C |
112 | } finally { |
113 | processing.forEach(p => p.cb()) | |
114 | } | |
115 | }, PeertubeChunkStore.BUFFERING_PUT_MS) | |
116 | } | |
117 | ||
c199c427 | 118 | get (index: number, opts: any, cb: (err?: Error, buf?: Buffer) => void): void { |
efda99c3 C |
119 | if (typeof opts === 'function') return this.get(index, null, opts) |
120 | ||
121 | // IndexDB could be slow, use our memory index first | |
122 | const memoryChunk = this.memoryChunks[index] | |
b224ddd8 | 123 | if (memoryChunk === undefined) { |
244b4ae3 | 124 | const err = new Error('Chunk not found') as any |
b224ddd8 C |
125 | err['notFound'] = true |
126 | ||
127 | return process.nextTick(() => cb(err)) | |
128 | } | |
129 | ||
efda99c3 C |
130 | // Chunk in memory |
131 | if (memoryChunk !== true) return cb(null, memoryChunk) | |
132 | ||
133 | // Chunk in store | |
134 | this.db.transaction('r', this.db.chunks, async () => { | |
135 | const result = await this.db.chunks.get({ id: index }) | |
c4710631 | 136 | if (result === undefined) return cb(null, Buffer.alloc(0)) |
efda99c3 C |
137 | |
138 | const buf = result.buf | |
139 | if (!opts) return this.nextTick(cb, null, buf) | |
140 | ||
141 | const offset = opts.offset || 0 | |
142 | const len = opts.length || (buf.length - offset) | |
143 | return cb(null, buf.slice(offset, len + offset)) | |
144 | }) | |
145 | .catch(err => { | |
146 | console.error(err) | |
147 | return cb(err) | |
148 | }) | |
149 | } | |
150 | ||
c199c427 C |
151 | close (cb: (err?: Error) => void) { |
152 | return this.destroy(cb) | |
efda99c3 C |
153 | } |
154 | ||
c199c427 | 155 | async destroy (cb: (err?: Error) => void) { |
efda99c3 C |
156 | try { |
157 | if (this.pendingPut) { | |
158 | clearTimeout(this.putBulkTimeout) | |
159 | this.pendingPut = null | |
160 | } | |
161 | if (this.cleanerInterval) { | |
162 | clearInterval(this.cleanerInterval) | |
163 | this.cleanerInterval = null | |
164 | } | |
165 | ||
2efd32f6 | 166 | if (this.db) { |
c4710631 | 167 | this.db.close() |
2efd32f6 C |
168 | |
169 | await this.dropDatabase(this.databaseName) | |
170 | } | |
171 | ||
efda99c3 | 172 | if (this.expirationDB) { |
c4710631 | 173 | this.expirationDB.close() |
efda99c3 C |
174 | this.expirationDB = null |
175 | } | |
176 | ||
efda99c3 C |
177 | return cb() |
178 | } catch (err) { | |
179 | console.error('Cannot destroy peertube chunk store.', err) | |
180 | return cb(err) | |
181 | } | |
182 | } | |
183 | ||
184 | private runCleaner () { | |
185 | this.checkExpiration() | |
186 | ||
98ab5dc8 | 187 | this.cleanerInterval = setInterval(() => { |
efda99c3 C |
188 | this.checkExpiration() |
189 | }, PeertubeChunkStore.CLEANER_INTERVAL_MS) | |
190 | } | |
191 | ||
2efd32f6 C |
192 | private async checkExpiration () { |
193 | let databasesToDeleteInfo: { name: string }[] = [] | |
efda99c3 | 194 | |
2efd32f6 C |
195 | try { |
196 | await this.expirationDB.transaction('rw', this.expirationDB.databases, async () => { | |
197 | // Update our database expiration since we are alive | |
198 | await this.expirationDB.databases.put({ | |
199 | name: this.databaseName, | |
200 | expiration: new Date().getTime() + PeertubeChunkStore.CLEANER_EXPIRATION_MS | |
201 | }) | |
efda99c3 | 202 | |
2efd32f6 C |
203 | const now = new Date().getTime() |
204 | databasesToDeleteInfo = await this.expirationDB.databases.where('expiration').below(now).toArray() | |
205 | }) | |
206 | } catch (err) { | |
207 | console.error('Cannot update expiration of fetch expired databases.', err) | |
208 | } | |
efda99c3 | 209 | |
2efd32f6 C |
210 | for (const databaseToDeleteInfo of databasesToDeleteInfo) { |
211 | await this.dropDatabase(databaseToDeleteInfo.name) | |
212 | } | |
efda99c3 C |
213 | } |
214 | ||
2efd32f6 | 215 | private async dropDatabase (databaseName: string) { |
efda99c3 | 216 | const dbToDelete = new ChunkDatabase(databaseName) |
2efd32f6 | 217 | console.log('Destroying IndexDB database %s.', databaseName) |
efda99c3 | 218 | |
2efd32f6 C |
219 | try { |
220 | await dbToDelete.delete() | |
221 | ||
222 | await this.expirationDB.transaction('rw', this.expirationDB.databases, () => { | |
223 | return this.expirationDB.databases.where({ name: databaseName }).delete() | |
224 | }) | |
225 | } catch (err) { | |
226 | console.error('Cannot delete %s.', databaseName, err) | |
227 | } | |
efda99c3 C |
228 | } |
229 | ||
c199c427 | 230 | private nextTick <T> (cb: (err?: Error, val?: T) => void, err: Error, val?: T) { |
efda99c3 C |
231 | process.nextTick(() => cb(err, val), undefined) |
232 | } | |
233 | } |