forked from Level/classic-level
-
Notifications
You must be signed in to change notification settings - Fork 0
/
binding.cc
2170 lines (1801 loc) · 57.6 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>
#include <mutex>
/**
* Forward declarations.
*/
struct Database;
struct Iterator;
static void iterator_close_do (napi_env env, Iterator* iterator, napi_value cb);
static leveldb::Status threadsafe_open(const leveldb::Options &options,
bool multithreading,
Database &db_instance);
static leveldb::Status threadsafe_close(Database &db_instance);
/**
* Global declarations for multi-threaded access. These are not context-aware
* by definition and is specifically to allow for cross thread access to the
* single database handle.
*/
struct LevelDbHandle
{
leveldb::DB *db;
size_t open_handle_count;
};
static std::mutex handles_mutex;
// only access this when protected by the handles_mutex!
static std::map<std::string, LevelDbHandle> db_handles;
/**
* 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])
// TODO: consider using encoding options instead of type checking
#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_); \
} else { \
char* buf = 0; \
napi_typedarray_type type; \
napi_status status = napi_get_typedarray_info(env, from, &type, &to##Sz_, (void **)&buf, NULL, NULL); \
if (status != napi_ok || type != napi_typedarray_type::napi_uint8_array) { \
/* TODO: refactor so that we can napi_throw_type_error() here */ \
to##Sz_ = 0; \
to##Ch_ = new char[to##Sz_]; \
} else { \
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;
}
static napi_value CreateCodeError (napi_env env, const char* code, const char* msg) {
napi_value codeValue;
napi_create_string_utf8(env, code, strlen(code), &codeValue);
napi_value msgValue;
napi_create_string_utf8(env, msg, strlen(msg), &msgValue);
napi_value error;
napi_create_error(env, codeValue, msgValue, &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;
}
enum Encoding { buffer, utf8, view };
/**
* Returns internal Encoding enum matching the given encoding option.
*/
static Encoding GetEncoding (napi_env env, napi_value options, const char* option) {
napi_value value;
size_t copied;
char buf[2];
if (napi_get_named_property(env, options, option, &value) == napi_ok &&
napi_get_value_string_utf8(env, value, buf, 2, &copied) == napi_ok && copied == 1) {
// Value is either "buffer", "utf8" or "view" so we only have to read the first char
switch (buf[0]) {
case 'b': return Encoding::buffer;
case 'v': return Encoding::view;
}
}
return Encoding::utf8;
}
/**
* 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_);
}
/**
* Takes a Buffer, string or Uint8Array property 'name' from 'opts'.
* Returns null if the property does not exist.
*/
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);
// TODO: we can avoid a copy here
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.
*/
static std::vector<std::string> KeyArray (napi_env env, napi_value arr) {
uint32_t length;
std::vector<std::string> result;
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) {
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.data(), key.size()),
value_(value.data(), value.size()) {}
void ConvertByMode (napi_env env, Mode mode, const Encoding keyEncoding, const Encoding valueEncoding, napi_value& result) const {
if (mode == Mode::entries) {
napi_create_array_with_length(env, 2, &result);
napi_value keyElement;
napi_value valueElement;
Convert(env, &key_, keyEncoding, keyElement);
Convert(env, &value_, valueEncoding, valueElement);
napi_set_element(env, result, 0, keyElement);
napi_set_element(env, result, 1, valueElement);
} else if (mode == Mode::keys) {
Convert(env, &key_, keyEncoding, result);
} else {
Convert(env, &value_, valueEncoding, result);
}
}
static void Convert (napi_env env, const std::string* s, const Encoding encoding, napi_value& result) {
if (s == NULL) {
napi_get_undefined(env, &result);
} else if (encoding == Encoding::buffer || encoding == Encoding::view) {
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;
if (status_.IsNotFound()) {
argv = CreateCodeError(env, "LEVEL_NOT_FOUND", errMsg_);
} else if (status_.IsCorruption()) {
argv = CreateCodeError(env, "LEVEL_CORRUPTION", errMsg_);
} else if (status_.IsIOError()) {
if (strlen(errMsg_) > 15 && strncmp("IO error: lock ", errMsg_, 15) == 0) { // env_posix.cc
argv = CreateCodeError(env, "LEVEL_LOCKED", errMsg_);
} else if (strlen(errMsg_) > 19 && strncmp("IO error: LockFile ", errMsg_, 19) == 0) { // env_win.cc
argv = CreateCodeError(env, "LEVEL_LOCKED", errMsg_);
} else {
argv = CreateCodeError(env, "LEVEL_IO_ERROR", errMsg_);
}
} else {
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) {
threadsafe_close(*this);
}
}
leveldb::Status Open (const leveldb::Options& options,
const std::string &location,
bool multithreading) {
location_ = location;
return threadsafe_open(options, multithreading, *this);
}
void CloseDatabase () {
if (db_ != NULL) {
threadsafe_close(*this);
}
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_;
std::string location_;
// for separation of concerns the threadsafe functionality was kept at the global
// level and made a friend so it is explict where the threadsafe boundary exists
friend leveldb::Status threadsafe_open(const leveldb::Options &options,
bool multithreading,
Database &db_instance);
friend leveldb::Status threadsafe_close(Database &db_instance);
};
leveldb::Status threadsafe_open(const leveldb::Options &options,
bool multithreading,
Database &db_instance) {
// Bypass lock and handles if multithreading is disabled
if (!multithreading) {
return leveldb::DB::Open(options, db_instance.location_, &db_instance.db_);
}
std::unique_lock<std::mutex> lock(handles_mutex);
auto it = db_handles.find(db_instance.location_);
if (it == db_handles.end()) {
// Database not opened yet for this location, unless it was with
// multithreading disabled, in which case we're expected to fail here.
LevelDbHandle handle = {nullptr, 0};
leveldb::Status status = leveldb::DB::Open(options, db_instance.location_, &handle.db);
if (status.ok()) {
handle.open_handle_count++;
db_instance.db_ = handle.db;
db_handles[db_instance.location_] = handle;
}
return status;
}
++(it->second.open_handle_count);
db_instance.db_ = it->second.db;
return leveldb::Status::OK();
}
leveldb::Status threadsafe_close(Database &db_instance) {
std::unique_lock<std::mutex> lock(handles_mutex);
auto it = db_handles.find(db_instance.location_);
if (it == db_handles.end()) {
// Was not opened with multithreading enabled
delete db_instance.db_;
} else if (--(it->second.open_handle_count) == 0) {
delete it->second.db;
db_handles.erase(it);
}
// ensure db_ pointer is nullified in Database instance
db_instance.db_ = NULL;
return leveldb::Status::OK();
}
/**
* 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),
hasClosed_(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(hasClosed_);
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 Close () {
if (!hasClosed_) {
hasClosed_ = 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 {
// The lte and gte options take precedence over lt and gt respectively
if (lte_ != NULL) {
if (target.compare(*lte_) > 0) return true;
} else if (lt_ != NULL) {
if (target.compare(*lt_) >= 0) return true;
}
if (gte_ != NULL) {
if (target.compare(*gte_) < 0) return true;
} else if (gt_ != NULL) {
if (target.compare(*gt_) <= 0) return true;
}
return false;
}
Database* database_;
bool hasClosed_;
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 Encoding keyEncoding,
const Encoding valueEncoding,
const uint32_t highWaterMarkBytes)
: BaseIterator(database, reverse, lt, lte, gt, gte, limit, fillCache),
id_(id),
keys_(keys),
values_(values),
keyEncoding_(keyEncoding),
valueEncoding_(valueEncoding),
highWaterMarkBytes_(highWaterMarkBytes),
first_(true),
nexting_(false),
isClosing_(false),
closeWorker_(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();
cache_.reserve(size);
size_t bytesRead = 0;
leveldb::Slice empty;
while (true) {
if (!first_) Next();
else first_ = false;
if (!Valid() || !Increment()) break;
if (keys_ && values_) {
leveldb::Slice k = CurrentKey();
leveldb::Slice v = CurrentValue();
cache_.emplace_back(k, v);
bytesRead += k.size() + v.size();
} else if (keys_) {
leveldb::Slice k = CurrentKey();
cache_.emplace_back(k, empty);
bytesRead += k.size();
} else if (values_) {
leveldb::Slice v = CurrentValue();
cache_.emplace_back(empty, v);
bytesRead += v.size();
}
if (bytesRead > highWaterMarkBytes_ || cache_.size() >= size) {
return true;
}
}
return false;
}
const uint32_t id_;
const bool keys_;
const bool values_;
const Encoding keyEncoding_;
const Encoding valueEncoding_;
const uint32_t highWaterMarkBytes_;
bool first_;
bool nexting_;
bool isClosing_;
BaseWorker* closeWorker_;
std::vector<Entry> 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_;