-
-
Notifications
You must be signed in to change notification settings - Fork 177
/
binding.cc
2058 lines (1700 loc) · 52.7 KB
/
binding.cc
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
#define NAPI_VERSION 3
#include <napi-macros.h>
#include <node_api.h>
#include <assert.h>
#include <leveldb/db.h>
#include <leveldb/write_batch.h>
#include <leveldb/cache.h>
#include <leveldb/filter_policy.h>
#include <map>
#include <vector>
/**
* Forward declarations.
*/
struct Database;
struct Iterator;
static void iterator_end_do (napi_env env, Iterator* iterator, napi_value cb);
/**
* Macros.
*/
#define NAPI_DB_CONTEXT() \
Database* database = NULL; \
NAPI_STATUS_THROWS(napi_get_value_external(env, argv[0], (void**)&database));
#define NAPI_ITERATOR_CONTEXT() \
Iterator* iterator = NULL; \
NAPI_STATUS_THROWS(napi_get_value_external(env, argv[0], (void**)&iterator));
#define NAPI_BATCH_CONTEXT() \
Batch* batch = NULL; \
NAPI_STATUS_THROWS(napi_get_value_external(env, argv[0], (void**)&batch));
#define NAPI_RETURN_UNDEFINED() \
return 0;
#define NAPI_UTF8_NEW(name, val) \
size_t name##_size = 0; \
NAPI_STATUS_THROWS(napi_get_value_string_utf8(env, val, NULL, 0, &name##_size)) \
char* name = new char[name##_size + 1]; \
NAPI_STATUS_THROWS(napi_get_value_string_utf8(env, val, name, name##_size + 1, &name##_size)) \
name[name##_size] = '\0';
#define NAPI_ARGV_UTF8_NEW(name, i) \
NAPI_UTF8_NEW(name, argv[i])
#define LD_STRING_OR_BUFFER_TO_COPY(env, from, to) \
char* to##Ch_ = 0; \
size_t to##Sz_ = 0; \
if (IsString(env, from)) { \
napi_get_value_string_utf8(env, from, NULL, 0, &to##Sz_); \
to##Ch_ = new char[to##Sz_ + 1]; \
napi_get_value_string_utf8(env, from, to##Ch_, to##Sz_ + 1, &to##Sz_); \
to##Ch_[to##Sz_] = '\0'; \
} else if (IsBuffer(env, from)) { \
char* buf = 0; \
napi_get_buffer_info(env, from, (void **)&buf, &to##Sz_); \
to##Ch_ = new char[to##Sz_]; \
memcpy(to##Ch_, buf, to##Sz_); \
}
/*********************************************************************
* Helpers.
********************************************************************/
/**
* Returns true if 'value' is a string.
*/
static bool IsString (napi_env env, napi_value value) {
napi_valuetype type;
napi_typeof(env, value, &type);
return type == napi_string;
}
/**
* Returns true if 'value' is a buffer.
*/
static bool IsBuffer (napi_env env, napi_value value) {
bool isBuffer;
napi_is_buffer(env, value, &isBuffer);
return isBuffer;
}
/**
* Returns true if 'value' is an object.
*/
static bool IsObject (napi_env env, napi_value value) {
napi_valuetype type;
napi_typeof(env, value, &type);
return type == napi_object;
}
/**
* Create an error object.
*/
static napi_value CreateError (napi_env env, const char* str) {
napi_value msg;
napi_create_string_utf8(env, str, strlen(str), &msg);
napi_value error;
napi_create_error(env, NULL, msg, &error);
return error;
}
/**
* Returns true if 'obj' has a property 'key'.
*/
static bool HasProperty (napi_env env, napi_value obj, const char* key) {
bool has = false;
napi_has_named_property(env, obj, key, &has);
return has;
}
/**
* Returns a property in napi_value form.
*/
static napi_value GetProperty (napi_env env, napi_value obj, const char* key) {
napi_value value;
napi_get_named_property(env, obj, key, &value);
return value;
}
/**
* Returns a boolean property 'key' from 'obj'.
* Returns 'DEFAULT' if the property doesn't exist.
*/
static bool BooleanProperty (napi_env env, napi_value obj, const char* key,
bool DEFAULT) {
if (HasProperty(env, obj, key)) {
napi_value value = GetProperty(env, obj, key);
bool result;
napi_get_value_bool(env, value, &result);
return result;
}
return DEFAULT;
}
/**
* Returns a uint32 property 'key' from 'obj'.
* Returns 'DEFAULT' if the property doesn't exist.
*/
static uint32_t Uint32Property (napi_env env, napi_value obj, const char* key,
uint32_t DEFAULT) {
if (HasProperty(env, obj, key)) {
napi_value value = GetProperty(env, obj, key);
uint32_t result;
napi_get_value_uint32(env, value, &result);
return result;
}
return DEFAULT;
}
/**
* Returns a int32 property 'key' from 'obj'.
* Returns 'DEFAULT' if the property doesn't exist.
*/
static int Int32Property (napi_env env, napi_value obj, const char* key,
int DEFAULT) {
if (HasProperty(env, obj, key)) {
napi_value value = GetProperty(env, obj, key);
int result;
napi_get_value_int32(env, value, &result);
return result;
}
return DEFAULT;
}
/**
* Returns a string property 'key' from 'obj'.
* Returns empty string if the property doesn't exist.
*/
static std::string StringProperty (napi_env env, napi_value obj, const char* key) {
if (HasProperty(env, obj, key)) {
napi_value value = GetProperty(env, obj, key);
if (IsString(env, value)) {
size_t size = 0;
napi_get_value_string_utf8(env, value, NULL, 0, &size);
char* buf = new char[size + 1];
napi_get_value_string_utf8(env, value, buf, size + 1, &size);
buf[size] = '\0';
std::string result = buf;
delete [] buf;
return result;
}
}
return "";
}
static void DisposeSliceBuffer (leveldb::Slice slice) {
if (!slice.empty()) delete [] slice.data();
}
/**
* Convert a napi_value to a leveldb::Slice.
*/
static leveldb::Slice ToSlice (napi_env env, napi_value from) {
LD_STRING_OR_BUFFER_TO_COPY(env, from, to);
return leveldb::Slice(toCh_, toSz_);
}
/**
* Returns length of string or buffer
*/
static size_t StringOrBufferLength (napi_env env, napi_value value) {
size_t size = 0;
if (IsString(env, value)) {
napi_get_value_string_utf8(env, value, NULL, 0, &size);
} else if (IsBuffer(env, value)) {
char* buf;
napi_get_buffer_info(env, value, (void **)&buf, &size);
}
return size;
}
/**
* Takes a Buffer or string property 'name' from 'opts'.
* Returns null if the property does not exist or is zero-length.
*/
static std::string* RangeOption (napi_env env, napi_value opts, const char* name) {
if (HasProperty(env, opts, name)) {
napi_value value = GetProperty(env, opts, name);
if (StringOrBufferLength(env, value) > 0) {
LD_STRING_OR_BUFFER_TO_COPY(env, value, to);
std::string* result = new std::string(toCh_, toSz_);
delete [] toCh_;
return result;
}
}
return NULL;
}
/**
* Converts an array containing Buffer or string keys to a vector.
* Empty elements are skipped.
*/
static std::vector<std::string>* KeyArray (napi_env env, napi_value arr) {
uint32_t length;
std::vector<std::string>* result = new std::vector<std::string>();
if (napi_get_array_length(env, arr, &length) == napi_ok) {
result->reserve(length);
for (uint32_t i = 0; i < length; i++) {
napi_value element;
if (napi_get_element(env, arr, i, &element) == napi_ok &&
StringOrBufferLength(env, element) > 0) {
LD_STRING_OR_BUFFER_TO_COPY(env, element, to);
result->emplace_back(toCh_, toSz_);
delete [] toCh_;
}
}
}
return result;
}
/**
* Calls a function.
*/
static napi_status CallFunction (napi_env env,
napi_value callback,
const int argc,
napi_value* argv) {
napi_value global;
napi_get_global(env, &global);
return napi_call_function(env, global, callback, argc, argv, NULL);
}
/**
* Whether to yield entries, keys or values.
*/
enum Mode {
entries,
keys,
values
};
/**
* Helper struct for caching and converting a key-value pair to napi_values.
*/
struct Entry {
Entry (const leveldb::Slice* key, const leveldb::Slice* value) {
key_ = key != NULL ? new std::string(key->data(), key->size()) : NULL;
value_ = value != NULL ? new std::string(value->data(), value->size()) : NULL;
}
~Entry () {
if (key_ != NULL) delete key_;
if (value_ != NULL) delete value_;
}
// Not used yet.
void ConvertXX (napi_env env, Mode mode, bool keyAsBuffer, bool valueAsBuffer, napi_value* result) {
if (mode == Mode::entries) {
napi_create_array_with_length(env, 2, result);
napi_value valueElement;
napi_value keyElement;
Convert(env, key_, keyAsBuffer, &keyElement);
Convert(env, value_, valueAsBuffer, &valueElement);
napi_set_element(env, *result, 0, keyElement);
napi_set_element(env, *result, 1, valueElement);
} else if (mode == Mode::keys) {
Convert(env, key_, keyAsBuffer, result);
} else {
Convert(env, value_, valueAsBuffer, result);
}
}
static void Convert (napi_env env, const std::string* s, bool asBuffer, napi_value* result) {
if (s == NULL) {
napi_get_undefined(env, result);
} else if (asBuffer) {
napi_create_buffer_copy(env, s->size(), s->data(), NULL, result);
} else {
napi_create_string_utf8(env, s->data(), s->size(), result);
}
}
private:
std::string* key_;
std::string* value_;
};
/**
* Base worker class. Handles the async work. Derived classes can override the
* following virtual methods (listed in the order in which they're called):
*
* - DoExecute (abstract, worker pool thread): main work
* - HandleOKCallback (main thread): call JS callback on success
* - HandleErrorCallback (main thread): call JS callback on error
* - DoFinally (main thread): do cleanup regardless of success
*/
struct BaseWorker {
// Note: storing env is discouraged as we'd end up using it in unsafe places.
BaseWorker (napi_env env,
Database* database,
napi_value callback,
const char* resourceName)
: database_(database), errMsg_(NULL) {
NAPI_STATUS_THROWS_VOID(napi_create_reference(env, callback, 1, &callbackRef_));
napi_value asyncResourceName;
NAPI_STATUS_THROWS_VOID(napi_create_string_utf8(env, resourceName,
NAPI_AUTO_LENGTH,
&asyncResourceName));
NAPI_STATUS_THROWS_VOID(napi_create_async_work(env, callback,
asyncResourceName,
BaseWorker::Execute,
BaseWorker::Complete,
this, &asyncWork_));
}
virtual ~BaseWorker () {
delete [] errMsg_;
}
static void Execute (napi_env env, void* data) {
BaseWorker* self = (BaseWorker*)data;
// Don't pass env to DoExecute() because use of Node-API
// methods should generally be avoided in async work.
self->DoExecute();
}
bool SetStatus (leveldb::Status status) {
status_ = status;
if (!status.ok()) {
SetErrorMessage(status.ToString().c_str());
return false;
}
return true;
}
void SetErrorMessage(const char *msg) {
delete [] errMsg_;
size_t size = strlen(msg) + 1;
errMsg_ = new char[size];
memcpy(errMsg_, msg, size);
}
virtual void DoExecute () = 0;
static void Complete (napi_env env, napi_status status, void* data) {
BaseWorker* self = (BaseWorker*)data;
self->DoComplete(env);
self->DoFinally(env);
}
void DoComplete (napi_env env) {
napi_value callback;
napi_get_reference_value(env, callbackRef_, &callback);
if (status_.ok()) {
HandleOKCallback(env, callback);
} else {
HandleErrorCallback(env, callback);
}
}
virtual void HandleOKCallback (napi_env env, napi_value callback) {
napi_value argv;
napi_get_null(env, &argv);
CallFunction(env, callback, 1, &argv);
}
virtual void HandleErrorCallback (napi_env env, napi_value callback) {
napi_value argv = CreateError(env, errMsg_);
CallFunction(env, callback, 1, &argv);
}
virtual void DoFinally (napi_env env) {
napi_delete_reference(env, callbackRef_);
napi_delete_async_work(env, asyncWork_);
delete this;
}
void Queue (napi_env env) {
napi_queue_async_work(env, asyncWork_);
}
Database* database_;
private:
napi_ref callbackRef_;
napi_async_work asyncWork_;
leveldb::Status status_;
char *errMsg_;
};
/**
* Owns the LevelDB storage, cache, filter policy and iterators.
*/
struct Database {
Database ()
: db_(NULL),
blockCache_(NULL),
filterPolicy_(leveldb::NewBloomFilterPolicy(10)),
currentIteratorId_(0),
pendingCloseWorker_(NULL),
ref_(NULL),
priorityWork_(0) {}
~Database () {
if (db_ != NULL) {
delete db_;
db_ = NULL;
}
}
leveldb::Status Open (const leveldb::Options& options,
const char* location) {
return leveldb::DB::Open(options, location, &db_);
}
void CloseDatabase () {
delete db_;
db_ = NULL;
if (blockCache_) {
delete blockCache_;
blockCache_ = NULL;
}
}
leveldb::Status Put (const leveldb::WriteOptions& options,
leveldb::Slice key,
leveldb::Slice value) {
return db_->Put(options, key, value);
}
leveldb::Status Get (const leveldb::ReadOptions& options,
leveldb::Slice key,
std::string& value) {
return db_->Get(options, key, &value);
}
leveldb::Status Del (const leveldb::WriteOptions& options,
leveldb::Slice key) {
return db_->Delete(options, key);
}
leveldb::Status WriteBatch (const leveldb::WriteOptions& options,
leveldb::WriteBatch* batch) {
return db_->Write(options, batch);
}
uint64_t ApproximateSize (const leveldb::Range* range) {
uint64_t size = 0;
db_->GetApproximateSizes(range, 1, &size);
return size;
}
void CompactRange (const leveldb::Slice* start,
const leveldb::Slice* end) {
db_->CompactRange(start, end);
}
void GetProperty (const leveldb::Slice& property, std::string* value) {
db_->GetProperty(property, value);
}
const leveldb::Snapshot* NewSnapshot () {
return db_->GetSnapshot();
}
leveldb::Iterator* NewIterator (leveldb::ReadOptions* options) {
return db_->NewIterator(*options);
}
void ReleaseSnapshot (const leveldb::Snapshot* snapshot) {
return db_->ReleaseSnapshot(snapshot);
}
void AttachIterator (napi_env env, uint32_t id, Iterator* iterator) {
iterators_[id] = iterator;
IncrementPriorityWork(env);
}
void DetachIterator (napi_env env, uint32_t id) {
iterators_.erase(id);
DecrementPriorityWork(env);
}
void IncrementPriorityWork (napi_env env) {
napi_reference_ref(env, ref_, &priorityWork_);
}
void DecrementPriorityWork (napi_env env) {
napi_reference_unref(env, ref_, &priorityWork_);
if (priorityWork_ == 0 && pendingCloseWorker_ != NULL) {
pendingCloseWorker_->Queue(env);
pendingCloseWorker_ = NULL;
}
}
bool HasPriorityWork () const {
return priorityWork_ > 0;
}
leveldb::DB* db_;
leveldb::Cache* blockCache_;
const leveldb::FilterPolicy* filterPolicy_;
uint32_t currentIteratorId_;
BaseWorker *pendingCloseWorker_;
std::map< uint32_t, Iterator * > iterators_;
napi_ref ref_;
private:
uint32_t priorityWork_;
};
/**
* Base worker class for doing async work that defers closing the database.
*/
struct PriorityWorker : public BaseWorker {
PriorityWorker (napi_env env, Database* database, napi_value callback, const char* resourceName)
: BaseWorker(env, database, callback, resourceName) {
database_->IncrementPriorityWork(env);
}
virtual ~PriorityWorker () {}
void DoFinally (napi_env env) override {
database_->DecrementPriorityWork(env);
BaseWorker::DoFinally(env);
}
};
/**
* Owns a leveldb iterator.
*/
struct BaseIterator {
BaseIterator(Database* database,
const bool reverse,
std::string* lt,
std::string* lte,
std::string* gt,
std::string* gte,
const int limit,
const bool fillCache)
: database_(database),
hasEnded_(false),
didSeek_(false),
reverse_(reverse),
lt_(lt),
lte_(lte),
gt_(gt),
gte_(gte),
limit_(limit),
count_(0) {
options_ = new leveldb::ReadOptions();
options_->fill_cache = fillCache;
options_->snapshot = database->NewSnapshot();
dbIterator_ = database_->NewIterator(options_);
}
virtual ~BaseIterator () {
assert(hasEnded_);
if (lt_ != NULL) delete lt_;
if (gt_ != NULL) delete gt_;
if (lte_ != NULL) delete lte_;
if (gte_ != NULL) delete gte_;
delete options_;
}
bool DidSeek () const {
return didSeek_;
}
/**
* Seek to the first relevant key based on range options.
*/
void SeekToRange () {
didSeek_ = true;
if (!reverse_ && gte_ != NULL) {
dbIterator_->Seek(*gte_);
} else if (!reverse_ && gt_ != NULL) {
dbIterator_->Seek(*gt_);
if (dbIterator_->Valid() && dbIterator_->key().compare(*gt_) == 0) {
dbIterator_->Next();
}
} else if (reverse_ && lte_ != NULL) {
dbIterator_->Seek(*lte_);
if (!dbIterator_->Valid()) {
dbIterator_->SeekToLast();
} else if (dbIterator_->key().compare(*lte_) > 0) {
dbIterator_->Prev();
}
} else if (reverse_ && lt_ != NULL) {
dbIterator_->Seek(*lt_);
if (!dbIterator_->Valid()) {
dbIterator_->SeekToLast();
} else if (dbIterator_->key().compare(*lt_) >= 0) {
dbIterator_->Prev();
}
} else if (reverse_) {
dbIterator_->SeekToLast();
} else {
dbIterator_->SeekToFirst();
}
}
/**
* Seek manually (during iteration).
*/
void Seek (leveldb::Slice& target) {
didSeek_ = true;
if (OutOfRange(target)) {
return SeekToEnd();
}
dbIterator_->Seek(target);
if (dbIterator_->Valid()) {
int cmp = dbIterator_->key().compare(target);
if (reverse_ ? cmp > 0 : cmp < 0) {
Next();
}
} else {
SeekToFirst();
if (dbIterator_->Valid()) {
int cmp = dbIterator_->key().compare(target);
if (reverse_ ? cmp > 0 : cmp < 0) {
SeekToEnd();
}
}
}
}
void End () {
if (!hasEnded_) {
hasEnded_ = true;
delete dbIterator_;
dbIterator_ = NULL;
database_->ReleaseSnapshot(options_->snapshot);
}
}
bool Valid () const {
return dbIterator_->Valid() && !OutOfRange(dbIterator_->key());
}
bool Increment () {
return limit_ < 0 || ++count_ <= limit_;
}
void Next () {
if (reverse_) dbIterator_->Prev();
else dbIterator_->Next();
}
void SeekToFirst () {
if (reverse_) dbIterator_->SeekToLast();
else dbIterator_->SeekToFirst();
}
void SeekToLast () {
if (reverse_) dbIterator_->SeekToFirst();
else dbIterator_->SeekToLast();
}
void SeekToEnd () {
SeekToLast();
Next();
}
leveldb::Slice CurrentKey () const {
return dbIterator_->key();
}
leveldb::Slice CurrentValue () const {
return dbIterator_->value();
}
leveldb::Status Status () const {
return dbIterator_->status();
}
bool OutOfRange (const leveldb::Slice& target) const {
// TODO: benchmark to see if this is worth it
// if (upperBoundOnly && !reverse_) {
// return ((lt_ != NULL && target.compare(*lt_) >= 0) ||
// (lte_ != NULL && target.compare(*lte_) > 0));
// }
return ((lt_ != NULL && target.compare(*lt_) >= 0) ||
(lte_ != NULL && target.compare(*lte_) > 0) ||
(gt_ != NULL && target.compare(*gt_) <= 0) ||
(gte_ != NULL && target.compare(*gte_) < 0));
}
Database* database_;
bool hasEnded_;
private:
leveldb::Iterator* dbIterator_;
bool didSeek_;
const bool reverse_;
std::string* lt_;
std::string* lte_;
std::string* gt_;
std::string* gte_;
const int limit_;
int count_;
leveldb::ReadOptions* options_;
};
/**
* Extends BaseIterator for reading it from JS land.
*/
struct Iterator final : public BaseIterator {
Iterator (Database* database,
const uint32_t id,
const bool reverse,
const bool keys,
const bool values,
const int limit,
std::string* lt,
std::string* lte,
std::string* gt,
std::string* gte,
const bool fillCache,
const bool keyAsBuffer,
const bool valueAsBuffer,
const uint32_t highWaterMark)
: BaseIterator(database, reverse, lt, lte, gt, gte, limit, fillCache),
id_(id),
keys_(keys),
values_(values),
keyAsBuffer_(keyAsBuffer),
valueAsBuffer_(valueAsBuffer),
highWaterMark_(highWaterMark),
landed_(false),
nexting_(false),
isEnding_(false),
endWorker_(NULL),
ref_(NULL) {
}
~Iterator () {}
void Attach (napi_env env, napi_value context) {
napi_create_reference(env, context, 1, &ref_);
database_->AttachIterator(env, id_, this);
}
void Detach (napi_env env) {
database_->DetachIterator(env, id_);
if (ref_ != NULL) napi_delete_reference(env, ref_);
}
bool ReadMany (uint32_t size) {
cache_.clear();
size_t bytesRead = 0;
while (true) {
if (landed_) Next();
if (!Valid() || !Increment()) break;
if (keys_) {
leveldb::Slice slice = CurrentKey();
cache_.emplace_back(slice.data(), slice.size());
bytesRead += slice.size();
} else {
cache_.emplace_back("");
}
if (values_) {
leveldb::Slice slice = CurrentValue();
cache_.emplace_back(slice.data(), slice.size());
bytesRead += slice.size();
} else {
cache_.emplace_back("");
}
if (!landed_) {
landed_ = true;
return true;
}
if (bytesRead > highWaterMark_ || cache_.size() >= size * 2) {
return true;
}
}
return false;
}
const uint32_t id_;
const bool keys_;
const bool values_;
const bool keyAsBuffer_;
const bool valueAsBuffer_;
const uint32_t highWaterMark_;
bool landed_;
bool nexting_;
bool isEnding_;
BaseWorker* endWorker_;
std::vector<std::string> cache_;
private:
napi_ref ref_;
};
/**
* Hook for when the environment exits. This hook will be called after
* already-scheduled napi_async_work items have finished, which gives us
* the guarantee that no db operations will be in-flight at this time.
*/
static void env_cleanup_hook (void* arg) {
Database* database = (Database*)arg;
// Do everything that db_close() does but synchronously. We're expecting that GC
// did not (yet) collect the database because that would be a user mistake (not
// closing their db) made during the lifetime of the environment. That's different
// from an environment being torn down (like the main process or a worker thread)
// where it's our responsibility to clean up. Note also, the following code must
// be a safe noop if called before db_open() or after db_close().
if (database && database->db_ != NULL) {
std::map<uint32_t, Iterator*> iterators = database->iterators_;
std::map<uint32_t, Iterator*>::iterator it;
// TODO: does not do `napi_delete_reference(env, iterator->ref_)`. Problem?
for (it = iterators.begin(); it != iterators.end(); ++it) {
it->second->End();
}
// Having ended the iterators (and released snapshots) we can safely close.
database->CloseDatabase();
}
}
/**
* Runs when a Database is garbage collected.
*/
static void FinalizeDatabase (napi_env env, void* data, void* hint) {
if (data) {
Database* database = (Database*)data;
napi_remove_env_cleanup_hook(env, env_cleanup_hook, database);
if (database->ref_ != NULL) napi_delete_reference(env, database->ref_);
delete database;
}
}
/**
* Returns a context object for a database.
*/
NAPI_METHOD(db_init) {
Database* database = new Database();
napi_add_env_cleanup_hook(env, env_cleanup_hook, database);
napi_value result;
NAPI_STATUS_THROWS(napi_create_external(env, database,
FinalizeDatabase,
NULL, &result));
// Reference counter to prevent GC of database while priority workers are active
NAPI_STATUS_THROWS(napi_create_reference(env, result, 0, &database->ref_));
return result;
}
/**
* Worker class for opening a database.
* TODO: shouldn't this be a PriorityWorker?
*/
struct OpenWorker final : public BaseWorker {
OpenWorker (napi_env env,
Database* database,
napi_value callback,
const std::string& location,
const bool createIfMissing,
const bool errorIfExists,
const bool compression,
const uint32_t writeBufferSize,
const uint32_t blockSize,
const uint32_t maxOpenFiles,
const uint32_t blockRestartInterval,
const uint32_t maxFileSize)
: BaseWorker(env, database, callback, "leveldown.db.open"),
location_(location) {
options_.block_cache = database->blockCache_;
options_.filter_policy = database->filterPolicy_;
options_.create_if_missing = createIfMissing;
options_.error_if_exists = errorIfExists;
options_.compression = compression
? leveldb::kSnappyCompression
: leveldb::kNoCompression;
options_.write_buffer_size = writeBufferSize;
options_.block_size = blockSize;
options_.max_open_files = maxOpenFiles;
options_.block_restart_interval = blockRestartInterval;
options_.max_file_size = maxFileSize;
}
~OpenWorker () {}
void DoExecute () override {
SetStatus(database_->Open(options_, location_.c_str()));
}
leveldb::Options options_;
std::string location_;
};
/**
* Open a database.
*/
NAPI_METHOD(db_open) {
NAPI_ARGV(4);
NAPI_DB_CONTEXT();
NAPI_ARGV_UTF8_NEW(location, 1);
napi_value options = argv[2];
const bool createIfMissing = BooleanProperty(env, options, "createIfMissing", true);
const bool errorIfExists = BooleanProperty(env, options, "errorIfExists", false);
const bool compression = BooleanProperty(env, options, "compression", true);
const uint32_t cacheSize = Uint32Property(env, options, "cacheSize", 8 << 20);
const uint32_t writeBufferSize = Uint32Property(env, options , "writeBufferSize" , 4 << 20);
const uint32_t blockSize = Uint32Property(env, options, "blockSize", 4096);
const uint32_t maxOpenFiles = Uint32Property(env, options, "maxOpenFiles", 1000);
const uint32_t blockRestartInterval = Uint32Property(env, options,
"blockRestartInterval", 16);
const uint32_t maxFileSize = Uint32Property(env, options, "maxFileSize", 2 << 20);
database->blockCache_ = leveldb::NewLRUCache(cacheSize);
napi_value callback = argv[3];
OpenWorker* worker = new OpenWorker(env, database, callback, location,
createIfMissing, errorIfExists,
compression, writeBufferSize, blockSize,
maxOpenFiles, blockRestartInterval,
maxFileSize);
worker->Queue(env);