-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree.js
More file actions
2034 lines (1684 loc) · 60.4 KB
/
tree.js
File metadata and controls
2034 lines (1684 loc) · 60.4 KB
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright 2015, 2016 Netsend.
*
* This file is part of PerspectiveDB.
*
* PerspectiveDB is free software: you can redistribute it and/or modify it under the
* terms of the GNU Affero General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* PerspectiveDB is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along
* with PerspectiveDB. If not, see <https://www.gnu.org/licenses/>.
*/
/* jshint -W018, -W030, -W116 */
'use strict';
var stream = require('stream');
var Transform = stream.Transform;
var Writable = stream.Writable;
var util = require('util');
var async = require('async');
var BSON, bson = require('bson');
if (process.browser) {
BSON = new bson();
} else {
BSON = new bson.BSONPure.BSON();
}
var xtend = require('xtend');
var invalidItem = require('./invalid_item');
var noop = require('./noop');
var StreamTree = require('./_stream_tree');
var DSKEY = 0x01;
var IKEY = 0x02;
var HEADKEY = 0x03;
var VKEY = 0x04;
var USKEY = 0x05;
// head index value option masks
var CONFLICT = 0x01; // deprecated
var DELETE = 0x02;
// defined user store keys
// _composeUsKey(item.h.pe) => _composeVKey(item.h.v)
/**
* Tree
*
* Manage DAGs in a tree.
*
* @param {LevelUP.db} db database for persistent storage
* @param {String} name name of this tree, should not exceed 254 bytes
* @param {Object} [opts] object containing configurable parameters
*
* opts:
* vSize {Number, default 6} number of bytes used for the version. Should be:
* 0 < vSize <= 6
* iSize {Number, default 6} number of bytes used for i. Should be:
* 0 < iSize <= 6
* skipValidation {Boolean, default false} whether or not to check if new
* items connect
* log {Object, default console} log object that contains debug2, debug, info,
* notice, warning, err, crit and emerg functions. Uses console.log and
* console.error by default.
*/
function Tree(db, name, opts) {
if (typeof db !== 'object' || db === null) { throw new TypeError('db must be an object'); }
if (typeof name !== 'string') { throw new TypeError('name must be a string'); }
if (Buffer.byteLength(name) > 254) { throw new TypeError('name must not exceed 254 bytes'); }
if (opts == null) { opts = {}; }
if (typeof opts !== 'object' || Array.isArray(opts)) { throw new TypeError('opts must be an object'); }
if (opts.log != null && typeof opts.log !== 'object') { throw new TypeError('opts.log must be an object'); }
if (opts.vSize != null && typeof opts.vSize !== 'number') { throw new TypeError('opts.vSize must be a number'); }
if (opts.iSize != null && typeof opts.iSize !== 'number') { throw new TypeError('opts.iSize must be a number'); }
if (opts.skipValidation != null && typeof opts.skipValidation !== 'boolean') { throw new TypeError('opts.skipValidation must be a boolean'); }
opts.objectMode = true;
Writable.call(this, opts);
this.name = name;
this._db = db;
// partition db in a data store, i-, head-, v- and us-index
// see the keyspec for details
this._dsPrefix = Tree.getPrefixWithType(name, DSKEY);
this._idxIPrefix = Tree.getPrefixWithType(name, IKEY);
this._idxHeadPrefix = Tree.getPrefixWithType(name, HEADKEY);
this._idxVPrefix = Tree.getPrefixWithType(name, VKEY);
this._usPrefix = Tree.getPrefixWithType(name, USKEY);
// init _i
this._i = 0;
this._vSize = opts.vSize || 6;
this._iSize = opts.iSize || 6;
if (this._vSize < 0 || this._vSize > 6) { throw new TypeError('opts.vSize must be between 0 and 6'); }
if (this._iSize < 0 || this._iSize > 6) { throw new TypeError('opts.iSize must be between 0 and 6'); }
this._skipValidation = opts.skipValidation;
this._log = opts.log || {
emerg: console.error,
alert: console.error,
crit: console.error,
err: console.error,
warning: console.log,
notice: console.log,
info: console.log,
debug: console.log,
debug2: console.log,
getFileStream: noop,
getErrorStream: noop,
close: noop
};
}
util.inherits(Tree, Writable);
module.exports = Tree;
/**
* Create a key prefix for the database.
*
* @param {String} name name of the prefix
* @return {Buffer} corresponding prefix
*/
Tree.getPrefix = function getPrefix(name) {
if (typeof name !== 'string') { throw new TypeError('name must be a string'); }
if (Buffer.byteLength(name) > 254) { throw new TypeError('name must not exceed 254 bytes'); }
var namelen = Buffer.byteLength(name);
var prefix = new Buffer(1 + namelen + 1);
prefix[0] = namelen;
prefix.write(name, 1);
prefix[namelen + 1] = 0x00;
return prefix;
};
/**
* Create a key prefix for data store or an index. See keyspec for different key
* types.
*
* @param {String} name name of the prefix
* @param {Number} type valid subkey type
* @return {Buffer} corresponding prefix
*/
Tree.getPrefixWithType = function getPrefixWithType(name, type) {
if (typeof name !== 'string') { throw new TypeError('name must be a string'); }
if (Buffer.byteLength(name) > 254) { throw new TypeError('name must not exceed 254 bytes'); }
if (typeof type !== 'number') { throw new TypeError('type must be a number'); }
if (type < 0x01 || type > 0x05) { throw new TypeError('type must be in the subkey range of 0x01 to 0x05'); }
var p = Tree.getPrefix(name);
var pt = new Buffer(p.length + 1);
p.copy(pt);
pt[pt.length - 1] = type;
return pt;
};
/**
* Parse a key.
*
* @param {Buffer} key any valid type: dskey, ikey or headkey, vkey
* @param {Object} [opts] object containing configurable parameters
* @return {Object} containing the members name and type and depending on the
* type it can contain id, i and/or v.
*
*
* opts:
* decodeId {String} decode id as string with given encoding. Encoding must
* be either "hex", "utf8" or "base64". If not given a
* buffer will be returned.
* decodeV {String} decode v as string with given encoding. Encoding must be
* either "hex", "utf8" or "base64". If not given a number
* will be returned.
* decodeUs {String} decode pe as string with given encoding. Encoding must
* be either "hex", "utf8" or "base64". If not given a
* number will be returned.
*/
Tree.parseKey = function parseKey(key, opts) {
if (!Buffer.isBuffer(key)) { throw new TypeError('key must be a buffer'); }
if (opts == null) { opts = {}; }
if (typeof opts !== 'object' || Array.isArray(opts)) { throw new TypeError('opts must be an object'); }
var idDecode = opts.decodeId;
var vDecode = opts.decodeV;
var usDecode = opts.decodeUs;
var name, type, ret;
var offset, namelen, idend, nlen;
offset = 0;
namelen = key[offset++];
name = key.slice(offset, offset += namelen);
if (key[offset++] !== 0x00) { throw new Error('expected a null byte after name'); }
type = key[offset++];
if (type < 0x01 || type > 0x05) { throw new TypeError('key is of an unknown type'); }
ret = {
name: name,
type: type
};
switch (type) {
case DSKEY:
idend = offset;
while (key[idend++]) // find first null byte
;
idend--;
if (key[idend] !== 0x00) { throw new Error('expected a null byte after id'); }
ret.id = key.slice(offset, idend);
offset = ++idend; // skip null byte
if (ret.id && idDecode) { ret.id = ret.id.toString(idDecode); }
nlen = key[offset++];
if (!(nlen > 0)) { throw new Error('i must be at least one byte'); }
ret.i = key.readUIntBE(offset, nlen);
offset += nlen;
if (offset !== key.length) { throw new Error('expected no bytes after i'); }
break;
case IKEY:
nlen = key[offset++];
if (!(nlen > 0)) { throw new Error('i must be at least one byte'); }
ret.i = key.readUIntBE(offset, nlen);
offset += nlen;
if (offset !== key.length) { throw new Error('expected no bytes after i'); }
break;
case HEADKEY:
idend = offset;
while (key[idend++]) // find first null byte
;
idend--;
if (key[idend] !== 0x00) { throw new Error('expected a null byte'); }
ret.id = key.slice(offset, idend);
offset = ++idend; // skip null byte
if (ret.id && idDecode) { ret.id = ret.id.toString(idDecode); }
nlen = key[offset++];
if (!(nlen > 0)) { throw new Error('v must be at least one byte'); }
ret.v = vDecode ? key.slice(offset).toString(vDecode) : key.readUIntBE(offset, nlen);
offset += nlen;
if (offset !== key.length) { throw new Error('expected no bytes after v'); }
break;
case VKEY:
nlen = key[offset++];
if (!(nlen > 0)) { throw new Error('v must be at least one byte'); }
ret.v = vDecode ? key.slice(offset).toString(vDecode) : key.readUIntBE(offset, nlen);
offset += nlen;
if (offset !== key.length) { throw new Error('expected no bytes after v'); }
break;
case USKEY:
nlen = key[offset++];
if (!(nlen > 0)) { throw new Error('us must be at least one byte'); }
ret.us = key.slice(offset, offset += nlen);
if (key[offset++] !== 0x00) { throw new Error('expected a null byte'); }
if (ret.us && usDecode) { ret.us = ret.us.toString(usDecode); }
nlen = key[offset++];
if (!(nlen > 0)) { throw new Error('i must be at least one byte'); }
ret.i = key.readUIntBE(offset, nlen);
offset += nlen;
if (offset !== key.length) { throw new Error('expected no bytes after i'); }
break;
}
return ret;
};
/**
* Parse head index value.
*
* @param {Buffer} value value of a headkey
* @return {Object} containing the options and i
*/
Tree.parseHeadVal = function parseHeadVal(value) {
if (!Buffer.isBuffer(value)) { throw new TypeError('value must be a buffer'); }
var opts, ret;
var offset, nlen;
ret = {};
offset = 0;
// read option byte
opts = value.readUIntBE(offset++, 1);
if (opts & CONFLICT) {
ret.c = true;
}
if (opts & DELETE) {
ret.d = true;
}
nlen = value[offset++];
if (!(nlen > 0)) { throw new Error('i must be at least one byte'); }
ret.i = value.readUIntBE(offset, nlen);
offset += nlen;
if (offset !== value.length) { throw new Error('unexpected length of value'); }
return ret;
};
/**
* Get a range object with start and end points for the ikey index.
*
* @param {Object} [opts] object containing configurable parameters
* @return {Object} start and end buffer: { s: buffer, e: buffer }
*
* opts:
* minI {Number} minimum offset, valid lbeint
* maxI {Number} maximum value, valid lbeint
*/
Tree.prototype.getIKeyRange = function getIKeyRange(opts) {
if (opts == null) { opts = {}; }
if (typeof opts !== 'object' || Array.isArray(opts)) { throw new TypeError('opts must be an object'); }
opts = opts || {};
var minI, maxI;
if (opts.minI != null) {
if (typeof opts.minI !== 'number') { throw new TypeError('opts.minI must be a number'); }
minI = opts.minI;
}
if (opts.maxI != null) {
if (typeof opts.maxI !== 'number') { throw new TypeError('opts.maxI must be a number'); }
maxI = opts.maxI;
}
var prefix = this._idxIPrefix;
var slen = prefix.length;
var elen = prefix.length;
if (minI) {
slen += 1 + this._iSize;
}
if (maxI) {
elen += 1 + this._iSize;
} else {
elen += 1; // 0xff byte
}
var s = new Buffer(slen);
var e = new Buffer(elen);
var offset = 0;
// fill s
prefix.copy(s);
offset += prefix.length;
s.copy(e);
if (minI) {
s[offset] = this._iSize;
s.writeUIntBE(minI, offset + 1, this._iSize);
}
if (maxI) {
e[offset] = this._iSize;
e.writeUIntBE(maxI, offset + 1, this._iSize);
} else {
e[offset] = 0xff;
}
return { s: s, e: e };
};
/**
* Get a range object with start and end points for the vkey index.
*
* @return {Object} start and end buffer: { s: buffer, e: buffer }
*/
Tree.prototype.getVKeyRange = function getVKeyRange() {
var prefix = this._idxVPrefix;
var s = new Buffer(prefix.length);
var e = new Buffer(prefix.length + 1 + this._vSize + 1);
// fill s
prefix.copy(s);
prefix.copy(e);
var offset = 0;
offset += prefix.length;
e[offset] = this._vSize + 1;
offset++;
e.fill(0xff, offset);
return { s: s, e: e };
};
/**
* Create a new key that is incremented by one.
*
* @param {Buffer} key
* @return {Buffer} new key incremented by one
*/
Tree.incrementKey = function incrementKey(key) {
if (!Buffer.isBuffer(key)) { throw new TypeError('key must be a buffer'); }
var len = key.length;
var nkey = new Buffer(len);
key.copy(nkey);
while (len) {
++nkey[--len]; // increment operator returns 256 if incremented to 0
if (nkey[len]) {
len = 0; // finish
} else {
if (!len)
throw new Error('overflow');
}
}
return nkey;
};
/**
* Get a prefix range object with start and end points for the headkey index.
*
* @param {Buffer} prefix prefix to use
*/
Tree.prototype.getHeadKeyPrefixRange = function getHeadKeyPrefixRange(prefix) {
if (!Buffer.isBuffer(prefix)) { throw new TypeError('prefix must be a buffer'); }
// allocate a new buffer with enough space for the headkey prefix and the given prefix
var hprefix = this._idxHeadPrefix;
var s = new Buffer(hprefix.length + prefix.length);
// fill s
hprefix.copy(s);
var offset = hprefix.length;
prefix.copy(s, offset);
var e = Tree.incrementKey(s);
return { s: s, e: e };
};
/**
* Get a range object with start and end points for the headkey index.
*
* @param {Buffer} [id] optional id to prefix start and end
* @return {Object} start and end buffer: { s: buffer, e: buffer }
*/
Tree.prototype.getHeadKeyRange = function getHeadKeyRange(id) {
if (id && !Buffer.isBuffer(id)) { throw new TypeError('id must be a buffer if provided'); }
var prefix = this._idxHeadPrefix;
var len = prefix.length;
if (id) {
len += id.length + 1;
}
var s = new Buffer(len);
var e = new Buffer(len + 1);
var offset = 0;
// fill s
prefix.copy(s);
offset += prefix.length;
if (id) {
id.copy(s, offset);
offset += id.length;
s[offset++] = 0x00;
}
s.copy(e);
e[offset] = 0xff;
return { s: s, e: e };
};
/**
* Get a range object with start and end points for the dskey index.
*
* @param {Buffer} [id] optional id to prefix start and end
* @param {Object} [opts] object containing configurable parameters
* @return {Object} start and end buffer: { s: buffer, e: buffer }
*
* opts:
* id {Buffer|String|Object} id to prefix start and end, must be a buffer,
* string or implement "toString"
* minI {Number} minimum offset, valid lbeint (id required)
* maxI {Number} maximum value, valid lbeint (id required)
*/
Tree.prototype.getDsKeyRange = function getDsKeyRange(opts) {
if (opts == null) { opts = {}; }
if (typeof opts !== 'object' || Array.isArray(opts)) { throw new TypeError('opts must be an object'); }
var id = opts.id;
if (id != null && !Buffer.isBuffer(id)) {
id = new Buffer(Tree._ensureString(id));
}
var minI, maxI;
if (opts.minI != null) {
if (typeof opts.minI !== 'number') { throw new TypeError('opts.minI must be a number'); }
minI = opts.minI;
}
if (opts.maxI != null) {
if (typeof opts.maxI !== 'number') { throw new TypeError('opts.maxI must be a number'); }
maxI = opts.maxI;
}
var prefix = this._dsPrefix;
var slen = prefix.length;
var elen = prefix.length;
if (id) {
slen += id.length + 1;
elen += id.length + 1;
if (minI) {
slen += 1 + this._iSize;
}
if (maxI) {
elen += 1 + this._iSize;
}
}
var s = new Buffer(slen);
var e = new Buffer(elen + 1);
var offset = 0;
// fill s
prefix.copy(s);
offset += prefix.length;
if (id) {
id.copy(s, offset);
offset += id.length;
s[offset++] = 0x00;
s.copy(e);
if (minI) {
s[offset] = this._iSize;
s.writeUIntBE(minI, offset + 1, this._iSize);
}
if (maxI) {
e[offset] = this._iSize;
e.writeUIntBE(maxI, offset + 1, this._iSize);
offset += 1;
offset += this._iSize;
}
} else {
s.copy(e);
}
e[offset] = 0xff;
return { s: s, e: e };
};
/**
* Get all head versions of a given id.
*
* @param {Buffer} id id to find versions for
* @param {Function} cb First parameter will be an error object or null. Second
* parameter will be an array with version strings.
*/
Tree.prototype.getHeadVersions = function getHeadVersions(id, cb) {
if (!Buffer.isBuffer(id)) { throw new TypeError('id must be a buffer'); }
if (typeof cb !== 'function') { throw new TypeError('cb must be a function'); }
var r = this.getHeadKeyRange(id);
this._log.info('t:%s getHeadVersions range %j', this.name, r);
var it = this._db.createKeyStream({ gte: r.s, lt: r.e });
var result = [];
var that = this;
it.on('readable', function() {
var headKey = it.read();
if (!headKey) { // end of stream
cb(null, result);
return;
}
var key = Tree.parseKey(headKey, { decodeV: 'base64' });
that._log.debug('t:%s getHeadVersions iterate key %j', that.name, key);
result.push(key.v);
});
it.on('error', cb);
};
/**
* Get a stream that iterates over all heads in order of id. Both values and keys
* are emitted.
*
* @param {Object} [opts] object containing configurable parameters
* @return {stream.Readable}
*
* opts:
* id {Buffer|String|Object} id to prefix start and end, must be a buffer,
* string or implement "toString"
* prefix {Buffer|String|Object} prefix start and end, must be a buffer, string
* or implement "toString". mutually exclusive with id
* skipConflicts {Boolean, default false} whether to emit heads with the
* conflict bit set
* skipDeletes {Boolean, default false} whether to emit heads with the delete
* bit set
* reverse {Boolean, default false} whether to iterate in reverse
* limit {Number} whether to limit the maximum number of results
* bson {Boolean, default false} whether to BSON serialize the object or not
*/
Tree.prototype.createHeadReadStream = function createHeadReadStream(opts) {
if (opts != null && typeof opts !== 'object') { throw new TypeError('opts must be an object'); }
opts = xtend({
skipConflicts: false,
skipDeletes: false,
bson: false
}, opts);
var id = opts.id;
if (id != null && !Buffer.isBuffer(id)) {
id = new Buffer(Tree._ensureString(id));
}
var prefix = opts.prefix;
if (prefix != null && !Buffer.isBuffer(prefix)) {
prefix = new Buffer(Tree._ensureString(prefix));
}
if (opts.skipConflicts != null && typeof opts.skipConflicts !== 'boolean') { throw new TypeError('opts.skipConflicts must be a boolean'); }
if (opts.skipDeletes != null && typeof opts.skipDeletes !== 'boolean') { throw new TypeError('opts.skipDeletes must be a boolean'); }
if (opts.bson != null && typeof opts.bson !== 'boolean') { throw new TypeError('opts.bson must be a boolean'); }
var r;
if (prefix) {
r = this.getHeadKeyPrefixRange(prefix);
} else if (id) {
r = this.getHeadKeyRange(id);
} else {
r = this.getHeadKeyRange();
}
this._log.debug2('t:%s createHeadReadStream range %j', this.name, r);
opts = xtend(opts, {
gte: r.s,
lt: r.e
});
var that = this;
var transformer = new Transform({
objectMode: true,
transform: function(headIdx, encoding, cb2) {
var self = this;
var key = Tree.parseKey(headIdx.key, { decodeV: 'base64' });
var val = Tree.parseHeadVal(headIdx.value);
if (opts.skipConflicts && val.c) { cb2(); return; }
if (opts.skipDeletes && val.d) { cb2(); return; }
that._log.debug2('t:%s createHeadReadStream iterate key %j val %j', that.name, key, val);
that._db.get(that._composeDsKey(key.id, val.i), function(err, item) {
if (err) {
that._log.err('t:%s createHeadReadStream %s', that.name, err);
cb2(err);
return;
}
that._log.debug2('t:%s createHeadReadStream iterate item %j', that.name, item);
var value;
if (opts.bson) {
if (process.browser) {
value = BSON.serialize(item);
} else {
value = item;
}
} else {
if (process.browser) {
value = item;
} else {
value = BSON.deserialize(item);
}
}
self.push(value);
cb2();
});
}
});
return this._db.createReadStream(opts).pipe(transformer);
};
/**
* Get an iterator that iterates over all heads in order of id. Both values and
* keys are emitted.
*
* @param {Object} [opts] object containing configurable parameters
* @param {Function} iterator function(head, next) called with each head.
* signature: next(err, continue) if continue is false
* iteration will abort. if null or true, iteration
* will continue to the next head.
* @param {Function} cb First parameter will be an error object or null, second
* parameter will be the last iterator continue value.
*
* opts:
* id {Buffer|String|Object} id to prefix start and end, must be a buffer,
* string or implement "toString"
* prefix {Buffer|String|Object} prefix start and end, must be a buffer, string
* or implement "toString". mutually exclusive with id
* skipConflicts {Boolean, default false} whether to emit heads with the
* conflict bit set
* skipDeletes {Boolean, default false} whether to emit heads with the delete
* bit set
* bson {Boolean, default false} whether to BSON serialize the object or not
*/
Tree.prototype.getHeads = function getHeads(opts, iterator, cb) {
if (typeof opts === 'function') {
cb = iterator;
iterator = opts;
opts = null;
}
if (opts == null) { opts = {}; }
if (typeof opts !== 'object') { throw new TypeError('opts must be an object'); }
if (typeof iterator !== 'function') { throw new TypeError('iterator must be a function'); }
if (typeof cb !== 'function') { throw new TypeError('cb must be a function'); }
var contin, error;
var writable = new Writable({
objectMode: true,
write: function(head, encoding, cb2) {
iterator(head, function(err, cont) {
if (err) {
error = err;
// signal the end
writable.end();
cb2();
return;
}
if (cont != null && !cont) {
contin = false;
// signal the end
writable.end();
cb2();
return;
}
cb2();
});
}
});
this.createHeadReadStream(opts).pipe(writable).on('finish', function() {
cb(error, contin);
});
};
/**
* Get an item by version. A valid version is any number up to 48 bits.
*
* @param {Number|base64 String} version valid lbeint or base64 int
* @param {Object} [opts] object containing configurable parameters
* @param {Function} cb First parameter will be an error object or null. Second
* parameter will be an item if found.
*
* opts:
* bson {Boolean, default false} whether to BSON serialize the object or not
*/
Tree.prototype.getByVersion = function getByVersion(version, opts, cb) {
if (typeof opts === 'function') {
cb = opts;
opts = null;
}
if (typeof version !== 'number' && typeof version !== 'string') { throw new TypeError('version must be a number or a base64 string'); }
if (typeof cb !== 'function') { throw new TypeError('cb must be a function'); }
if (opts == null) { opts = {}; }
if (typeof opts !== 'object' || Array.isArray(opts)) { throw new TypeError('opts must be an object'); }
if (opts.bson != null && typeof opts.bson !== 'boolean') { throw new TypeError('opts.bson must be a boolean'); }
this._log.debug2('t:%s getByVersion %s', this.name, version);
var that = this;
this._getDsKeyByVersion(version, function(err, dsKey) {
if (err) { cb(err); return; }
if (!dsKey) {
cb(null, null);
return;
}
that._db.get(dsKey, function(err, item) {
if (err) { cb(err); return; }
var value;
if (opts.bson) {
if (process.browser) {
value = BSON.serialize(item);
} else {
value = item;
}
} else {
if (process.browser) {
value = item;
} else {
value = BSON.deserialize(item);
}
}
cb(null, value);
});
});
};
/**
* Get a readable stream over each item in the order of insertion into the tree.
*
* @param {Object} [opts] object containing configurable parameters
*
* opts:
* id {String|Object} limit to one specific DAG
* first {base64 String} first version, offset
* last {base64 String} last version
* excludeFirst {Boolean, default false} whether or not first should be
* excluded
* excludeLast {Boolean, default false} whether or not last should be
* excluded
* reverse {Boolean, default false} if true, starts with last version
* bson {Boolean, default false} whether to BSON serialize the object or not
*/
Tree.prototype.insertionOrderStream = function insertionOrderStream(opts) {
return new StreamTree(this, opts);
};
/**
* Get a stream over each item in the order of insertion into the tree. If tail is
* true, the returned stream will have an "end" method.
*
* @param {Object} [opts] object containing configurable parameters
*
* opts:
* id {String|Object} limit to one specific DAG
* first {base64 String} first version, offset
* last {base64 String} last version (mutually exclusive with tail)
* excludeFirst {Boolean, default false} whether or not first should be
* excluded
* excludeLast {Boolean, default false} whether or not last should be
* excluded (mutually exclusive with tail)
* reverse {Boolean, default false} if true, starts with last version (mutually
* exclusive with tail)
* limit {Number} whether to limit the maximum number of results
* bson {Boolean, default false} whether to BSON serialize the object or not
* tail {Boolean, default false} if true, keeps the stream open
* tailRetry {Number, default 1000} reopen readers every tailRetry ms
*/
Tree.prototype.createReadStream = function createReadStream(opts) {
if (opts == null) { opts = {}; }
if (typeof opts !== 'object' || Array.isArray(opts)) { throw new TypeError('opts must be an object'); }
if (opts.tail != null && typeof opts.tail !== 'boolean') { throw new TypeError('opts.tail must be a boolean'); }
if (opts.tailRetry != null && typeof opts.tailRetry !== 'number') { throw new TypeError('opts.tailRetry must be a number'); }
if (opts.tail) {
if (opts.last) { throw new Error('opts.last is mutually exclusive with opts.tail'); }
if (opts.excludeLast) { throw new Error('opts.excludeLast is mutually exclusive with opts.tail'); }
if (opts.reverse) { throw new Error('opts.reverse is mutually exclusive with opts.tail'); }
}
var first = opts.first;
var excludeFirst = opts.excludeFirst;
var that = this;
var timeout, ts, rs;
// create a new rs, pipe it to ts
function setupReader() {
that._log.debug2('t:%s createReadStream open reader: %j', that.name, opts);
rs = new StreamTree(that, {
id: opts.id,
first: first,
excludeFirst: excludeFirst,
bson: opts.bson
});
rs.once('end', function() {
// cleanup
rs.unpipe(ts);
that._log.debug2('t:%s createReadStream schedule next', that.name);
timeout = setTimeout(setupReader, opts.tailRetry || 1000);
});
rs.once('error', function(err) {
// since this is a retry tail, skip version not found errors, maybe the requested version will exist later
if (err.message === 'version not found') {
that._log.info('t:%s createReadStream unknown version requested', that.name);
} else {
that._log.err('t:%s createReadStream %j', that.name, err);
rs.emit('error', err);
}
});
rs.pipe(ts, { end: false });
}
if (opts.tail) {
// track last emitted version
ts = new Transform({
objectMode: true,
transform: function(obj, enc, cb) {
first = obj.h.v;
cb(null, obj);
}
});
setupReader();
// exclude first on subsequent iterations
excludeFirst = true;
// clear any scheduled timeout if end() is called
ts.on('finish', function() {
that._log.debug('t:%s createReadStream finished', that.name);
clearTimeout(timeout);
});
return ts;
} else {
return new StreamTree(that, opts);
}
};
/**
* Get last inserted version.
*
* @param {String} [decodeV] decode v as string with given encoding. Encoding
* must be either "hex", "utf8" or "base64". If not
* given a number will be returned.
* @param {Function} cb First parameter will be an error object or null. Second
* parameter will be a version or null.
*/
Tree.prototype.lastVersion = function lastVersion(decodeV, cb) {
if (typeof decodeV === 'function') {
cb = decodeV;
decodeV = null;
}
if (decodeV != null && typeof decodeV !== 'string') { throw new TypeError('decodeV must be a string'); }
if (typeof cb !== 'function') { throw new TypeError('cb must be a function'); }
// find the last version
var r = this.getIKeyRange();