This repository has been archived by the owner on May 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
574 lines (505 loc) · 17.2 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
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
// SPDX-FileCopyrightText: 2021 Anders Rune Jensen
//
// SPDX-License-Identifier: LGPL-3.0-only
const Cache = require('hashlru')
const RAF = require('polyraf')
const Obv = require('obz')
const debounce = require('lodash.debounce')
const isBufferZero = require('is-buffer-zero')
const debug = require('debug')('async-append-only-log')
const fs = require('fs')
const mutexify = require('mutexify')
const {
deletedRecordErr,
nanOffsetErr,
negativeOffsetErr,
outOfBoundsOffsetErr,
delDuringCompactErr,
appendLargerThanBlockErr,
streamClosedErr,
appendTransactionWantsArrayErr,
} = require('./errors')
const Stream = require('./stream')
const Record = require('./record')
const Compaction = require('./compaction')
/**
* The "End of Block" is a special field used to mark the end of a block, and
* in practice it's like a Record header "length" field, with the value 0.
* In most cases, the end region of a block will have a larger length than this,
* but we want to guarantee there is at *least* this many bytes at the end.
*/
const EOB = {
SIZE: Record.HEADER_SIZE,
asNumber: 0,
}
const DEFAULT_BLOCK_SIZE = 65536
const DEFAULT_CODEC = { encode: (x) => x, decode: (x) => x }
const DEFAULT_WRITE_TIMEOUT = 250
const DEFAULT_VALIDATE = () => true
module.exports = function AsyncAppendOnlyLog(filename, opts) {
const cache = new Cache(1024) // This is potentially 64 MiB!
const raf = RAF(filename)
const blockSize = (opts && opts.blockSize) || DEFAULT_BLOCK_SIZE
const codec = (opts && opts.codec) || DEFAULT_CODEC
const writeTimeout = (opts && opts.writeTimeout) || DEFAULT_WRITE_TIMEOUT
const validateRecord = (opts && opts.validateRecord) || DEFAULT_VALIDATE
let self
const waitingLoad = []
const waitingDrain = new Map() // blockIndex -> []
const waitingFlushDelete = []
const blocksToBeWritten = new Map() // blockIndex -> { blockBuf, offset }
const blocksWithDeletables = new Map() // blockIndex -> blockBuf
let writingBlockIndex = -1
let latestBlockBuf = null
let latestBlockIndex = null
let nextOffsetInBlock = null
const since = Obv() // offset of last written record
let compaction = null
const compactionProgress = Obv().set(
Compaction.stateFileExists(filename)
? { done: false }
: { sizeDiff: 0, percent: 1, done: true }
)
const waitingCompaction = []
onLoad(function maybeResumeCompaction() {
if (Compaction.stateFileExists(filename)) {
compact(function onCompactDone(err) {
if (err) throw err
})
}
})()
raf.stat(function onRAFStatDone(err, stat) {
if (err) debug('failed to stat ' + filename, err)
const fileSize = stat ? stat.size : -1
if (fileSize <= 0) {
debug('empty file')
latestBlockBuf = Buffer.alloc(blockSize)
latestBlockIndex = 0
nextOffsetInBlock = 0
cache.set(0, latestBlockBuf)
since.set(-1)
while (waitingLoad.length) waitingLoad.shift()()
} else {
const blockStart = fileSize - blockSize
loadLatestBlock(blockStart, function onLoadedLatestBlock(err) {
if (err) throw err
debug('opened file, since: %d', since.value)
while (waitingLoad.length) waitingLoad.shift()()
})
}
})
function loadLatestBlock(blockStart, cb) {
raf.read(blockStart, blockSize, function onRAFReadLastDone(err, blockBuf) {
if (err) return cb(err)
getLastGoodRecord(
blockBuf,
blockStart,
function gotLastGoodRecord(err, offsetInBlock) {
if (err) return cb(err)
latestBlockBuf = blockBuf
latestBlockIndex = blockStart / blockSize
const recSize = Record.readSize(blockBuf, offsetInBlock)
nextOffsetInBlock = offsetInBlock + recSize
since.set(blockStart + offsetInBlock)
cb()
}
)
})
}
function getOffsetInBlock(offset) {
return offset % blockSize
}
function getBlockStart(offset) {
return offset - getOffsetInBlock(offset)
}
function getNextBlockStart(offset) {
return getBlockStart(offset) + blockSize
}
function getBlockIndex(offset) {
return getBlockStart(offset) / blockSize
}
const writeLock = mutexify()
function writeWithFSync(blockStart, blockBuf, successValue, cb) {
writeLock(function onWriteLockReleased(unlock) {
raf.write(blockStart, blockBuf, function onRAFWriteDone(err) {
if (err) return unlock(cb, err)
if (raf.fd) {
fs.fsync(raf.fd, function onFSyncDone(err) {
if (err) unlock(cb, err)
else unlock(cb, null, successValue)
})
} else unlock(cb, null, successValue)
})
})
}
function truncateWithFSync(newSize, cb) {
writeLock(function onWriteLockReleasedForTruncate(unlock) {
raf.del(newSize, Infinity, function onRAFDeleteDone(err) {
if (err) return unlock(cb, err)
if (raf.fd) {
fs.fsync(raf.fd, function onFSyncDoneForTruncate(err) {
if (err) unlock(cb, err)
else unlock(cb, null)
})
} else unlock(cb, null)
})
})
}
function fixBlock(blockBuf, badOffsetInBlock, blockStart, successValue, cb) {
debug('found invalid record at %d, fixing last block', badOffsetInBlock)
blockBuf.fill(0, badOffsetInBlock, blockSize)
writeWithFSync(blockStart, blockBuf, successValue, cb)
}
function getLastGoodRecord(blockBuf, blockStart, cb) {
let lastGoodOffset = 0
for (let offsetInRecord = 0; offsetInRecord < blockSize; ) {
const length = Record.readDataLength(blockBuf, offsetInRecord)
if (length === EOB.asNumber) break
const [dataBuf, recSize] = Record.read(blockBuf, offsetInRecord)
const isLengthCorrupt = offsetInRecord + recSize > blockSize
const isDataCorrupt = !validateRecord(dataBuf)
if (isLengthCorrupt || isDataCorrupt) {
fixBlock(blockBuf, offsetInRecord, blockStart, lastGoodOffset, cb)
return
}
lastGoodOffset = offsetInRecord
offsetInRecord += recSize
}
cb(null, lastGoodOffset)
}
function getBlock(offset, cb) {
const blockIndex = getBlockIndex(offset)
if (cache.has(blockIndex)) {
debug('getting offset %d from cache', offset)
const cachedBlockBuf = cache.get(blockIndex)
cb(null, cachedBlockBuf)
} else {
debug('getting offset %d from disc', offset)
const blockStart = getBlockStart(offset)
raf.read(blockStart, blockSize, function onRAFReadDone(err, blockBuf) {
cache.set(blockIndex, blockBuf)
cb(err, blockBuf)
})
}
}
function get(offset, cb) {
const logSize = latestBlockIndex * blockSize + nextOffsetInBlock
if (typeof offset !== 'number') return cb(nanOffsetErr(offset))
if (isNaN(offset)) return cb(nanOffsetErr(offset))
if (offset < 0) return cb(negativeOffsetErr(offset))
if (offset >= logSize) return cb(outOfBoundsOffsetErr(offset, logSize))
getBlock(offset, function gotBlock(err, blockBuf) {
if (err) return cb(err)
const [dataBuf] = Record.read(blockBuf, getOffsetInBlock(offset))
if (isBufferZero(dataBuf)) return cb(deletedRecordErr())
cb(null, codec.decode(dataBuf))
})
}
// nextOffset can take 3 values:
// -1: end of log
// 0: need a new block
// >0: next record within block
function getDataNextOffset(blockBuf, offset, asRaw = false) {
const offsetInBlock = getOffsetInBlock(offset)
const [dataBuf, recSize] = Record.read(blockBuf, offsetInBlock)
const nextLength = Record.readDataLength(blockBuf, offsetInBlock + recSize)
let nextOffset
if (nextLength === EOB.asNumber) {
if (getNextBlockStart(offset) > since.value) nextOffset = -1
else nextOffset = 0
} else {
nextOffset = offset + recSize
}
if (isBufferZero(dataBuf)) return [nextOffset, null, recSize]
else return [nextOffset, asRaw ? dataBuf : codec.decode(dataBuf), recSize]
}
function del(offset, cb) {
if (compaction) {
cb(delDuringCompactErr())
return
}
const blockIndex = getBlockIndex(offset)
if (blocksToBeWritten.has(blockIndex)) {
onDrain(function delAfterDrained() {
del(offset, cb)
})
return
}
if (blocksWithDeletables.has(blockIndex)) {
const blockBuf = blocksWithDeletables.get(blockIndex)
gotBlockForDelete(null, blockBuf)
} else {
getBlock(offset, gotBlockForDelete)
}
function gotBlockForDelete(err, blockBuf) {
if (err) return cb(err)
const actualBlockBuf = blocksWithDeletables.get(blockIndex) || blockBuf
Record.overwriteWithZeroes(actualBlockBuf, getOffsetInBlock(offset))
blocksWithDeletables.set(blockIndex, actualBlockBuf)
scheduleFlushDelete()
cb()
}
}
function hasNoSpaceFor(dataBuf, offsetInBlock) {
return offsetInBlock + Record.size(dataBuf) + EOB.SIZE > blockSize
}
const scheduleFlushDelete = debounce(flushDelete, writeTimeout)
function flushDelete() {
if (blocksWithDeletables.size === 0) {
for (const cb of waitingFlushDelete) cb()
waitingFlushDelete.length = 0
return
}
const blockIndex = blocksWithDeletables.keys().next().value
const blockStart = blockIndex * blockSize
const blockBuf = blocksWithDeletables.get(blockIndex)
blocksWithDeletables.delete(blockIndex)
blocksWithDeletables.set(-1, null) // indicate that flush is active
writeWithFSync(blockStart, blockBuf, null, function flushedDelete(err) {
blocksWithDeletables.delete(-1) // indicate that flush is not active
if (err) {
for (const cb of waitingFlushDelete) cb(err)
waitingFlushDelete.length = 0
return
}
flushDelete() // next
})
}
function onDeletesFlushed(cb) {
if (blocksWithDeletables.size === 0) cb()
else waitingFlushDelete.push(cb)
}
function appendSingle(data) {
let encodedData = codec.encode(data)
if (typeof encodedData === 'string') encodedData = Buffer.from(encodedData)
if (Record.size(encodedData) + EOB.SIZE > blockSize)
throw appendLargerThanBlockErr()
if (hasNoSpaceFor(encodedData, nextOffsetInBlock)) {
const nextBlockBuf = Buffer.alloc(blockSize)
latestBlockBuf = nextBlockBuf
latestBlockIndex += 1
nextOffsetInBlock = 0
debug("data doesn't fit current block, creating new")
}
Record.write(latestBlockBuf, nextOffsetInBlock, encodedData)
cache.set(latestBlockIndex, latestBlockBuf) // update cache
const offset = latestBlockIndex * blockSize + nextOffsetInBlock
blocksToBeWritten.set(latestBlockIndex, {
blockBuf: latestBlockBuf,
offset,
})
nextOffsetInBlock += Record.size(encodedData)
scheduleWrite()
debug('data inserted at offset %d', offset)
return offset
}
function append(data, cb) {
if (compaction) {
waitingCompaction.push(() => append(data, cb))
return
}
if (Array.isArray(data)) {
let offset = 0
for (let i = 0, length = data.length; i < length; ++i)
offset = appendSingle(data[i])
cb(null, offset)
} else cb(null, appendSingle(data))
}
function appendTransaction(dataArray, cb) {
if (!Array.isArray(dataArray)) {
return cb(appendTransactionWantsArrayErr())
}
if (compaction) {
waitingCompaction.push(() => appendTransaction(dataArray, cb))
return
}
let size = 0
const encodedDataArray = dataArray.map((data) => {
let encodedData = codec.encode(data)
if (typeof encodedData === 'string')
encodedData = Buffer.from(encodedData)
size += Record.size(encodedData)
return encodedData
})
size += EOB.SIZE
if (size > blockSize) return cb(appendLargerThanBlockErr())
if (nextOffsetInBlock + size > blockSize) {
// doesn't fit
const nextBlockBuf = Buffer.alloc(blockSize)
latestBlockBuf = nextBlockBuf
latestBlockIndex += 1
nextOffsetInBlock = 0
debug("data doesn't fit current block, creating new")
}
const offsets = []
for (const encodedData of encodedDataArray) {
Record.write(latestBlockBuf, nextOffsetInBlock, encodedData)
cache.set(latestBlockIndex, latestBlockBuf) // update cache
const offset = latestBlockIndex * blockSize + nextOffsetInBlock
offsets.push(offset)
blocksToBeWritten.set(latestBlockIndex, {
blockBuf: latestBlockBuf,
offset,
})
nextOffsetInBlock += Record.size(encodedData)
debug('data inserted at offset %d', offset)
}
scheduleWrite()
return cb(null, offsets)
}
const scheduleWrite = debounce(write, writeTimeout)
function write() {
if (blocksToBeWritten.size === 0) return
const blockIndex = blocksToBeWritten.keys().next().value
const blockStart = blockIndex * blockSize
const { blockBuf, offset } = blocksToBeWritten.get(blockIndex)
blocksToBeWritten.delete(blockIndex)
debug(
'writing block of size: %d, to offset: %d',
blockBuf.length,
blockIndex * blockSize
)
writingBlockIndex = blockIndex
writeWithFSync(blockStart, blockBuf, null, function onBlockWritten(err) {
const drainsBefore = (waitingDrain.get(blockIndex) || []).slice(0)
writingBlockIndex = -1
if (err) {
debug('failed to write block %d', blockIndex)
throw err
} else {
since.set(offset)
// write values to live streams
for (const stream of self.streams) {
if (stream.live) stream.liveResume()
}
debug(
'draining the waiting queue for %d, items: %d',
blockIndex,
drainsBefore.length
)
for (let i = 0; i < drainsBefore.length; ++i) drainsBefore[i]()
// the resumed streams might have added more to waiting
let drainsAfter = waitingDrain.get(blockIndex) || []
if (drainsBefore.length === drainsAfter.length)
waitingDrain.delete(blockIndex)
else if (drainsAfter.length === 0) waitingDrain.delete(blockIndex)
else
waitingDrain.set(
blockIndex,
waitingDrain.get(blockIndex).slice(drainsBefore.length)
)
write() // next!
}
})
}
function overwrite(blockIndex, blockBuf, cb) {
cache.set(blockIndex, blockBuf)
const blockStart = blockIndex * blockSize
writeWithFSync(blockStart, blockBuf, null, cb)
}
function truncate(newLatestBlockIndex, cb) {
if (newLatestBlockIndex >= latestBlockIndex) return cb(null, 0)
const size = (latestBlockIndex + 1) * blockSize
const newSize = (newLatestBlockIndex + 1) * blockSize
for (let i = newLatestBlockIndex + 1; i < latestBlockIndex; ++i) {
cache.remove(i)
}
truncateWithFSync(newSize, function onTruncateWithFSyncDone(err) {
if (err) return cb(err)
const blockStart = newSize - blockSize
loadLatestBlock(blockStart, function onTruncateLoadedLatestBlock(err) {
if (err) return cb(err)
const sizeDiff = size - newSize
cb(null, sizeDiff)
})
})
}
function compact(cb) {
if (compaction) {
debug('compaction already in progress')
waitingCompaction.push(cb)
return
}
onDrain(function startCompactAfterDrain() {
onDeletesFlushed(function startCompactAfterDeletes() {
compaction = new Compaction(self, (err, stats) => {
compaction = null
if (err) return cb(err)
compactionProgress.set({ ...stats, percent: 1, done: true })
for (const callback of waitingCompaction) callback()
waitingCompaction.length = 0
cb()
})
compaction.progress((stats) => {
compactionProgress.set({ ...stats, done: false })
})
})
})
}
function close(cb) {
onDrain(function closeAfterHavingDrained() {
onDeletesFlushed(function closeAfterDeletesFlushed() {
for (const stream of self.streams) stream.abort(streamClosedErr())
self.streams = []
raf.close(cb)
})
})
}
function onLoad(fn) {
return function waitForLogLoaded(...args) {
if (latestBlockBuf === null) waitingLoad.push(fn.bind(null, ...args))
else fn(...args)
}
}
function onDrain(fn) {
if (compaction) {
waitingCompaction.push(fn)
return
}
if (blocksToBeWritten.size === 0 && writingBlockIndex === -1) fn()
else {
const latestBlockIndex =
blocksToBeWritten.size > 0
? last(blocksToBeWritten.keys())
: writingBlockIndex
const drains = waitingDrain.get(latestBlockIndex) || []
drains.push(fn)
waitingDrain.set(latestBlockIndex, drains)
}
}
function last(iterable) {
let res = null
for (let x of iterable) res = x
return res
}
return (self = {
// Public API:
get: onLoad(get),
del: onLoad(del),
append: onLoad(append),
appendTransaction: onLoad(appendTransaction),
close: onLoad(close),
onDrain: onLoad(onDrain),
onDeletesFlushed: onLoad(onDeletesFlushed),
compact: onLoad(compact),
since,
compactionProgress,
stream(opts) {
const stream = new Stream(self, opts)
self.streams.push(stream)
return stream
},
// Internals needed by ./compaction.js:
filename,
blockSize,
overwrite,
truncate,
hasNoSpaceFor,
// Internals needed by ./stream.js:
onLoad,
getNextBlockStart,
getDataNextOffset,
getBlock,
streams: [],
})
}