forked from Level/rocksdb
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
binding.cc
1645 lines (1271 loc) · 49.2 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 8
#include <assert.h>
#include <napi-macros.h>
#include <node_api.h>
#include <rocksdb/cache.h>
#include <rocksdb/comparator.h>
#include <rocksdb/convenience.h>
#include <rocksdb/db.h>
#include <rocksdb/env.h>
#include <rocksdb/filter_policy.h>
#include <rocksdb/merge_operator.h>
#include <rocksdb/options.h>
#include <rocksdb/slice.h>
#include <rocksdb/slice_transform.h>
#include <rocksdb/status.h>
#include <rocksdb/table.h>
#include <rocksdb/write_batch.h>
#include <iostream>
#include <memory>
#include <optional>
#include <set>
#include <string>
#include <thread>
#include <vector>
#include "max_rev_operator.h"
#include "util.h"
class NullLogger : public rocksdb::Logger {
public:
using rocksdb::Logger::Logv;
virtual void Logv(const char* format, va_list ap) override {}
virtual size_t GetLogFileSize() const override { return 0; }
};
struct Database;
class Iterator;
struct ColumnFamily {
rocksdb::ColumnFamilyHandle* handle;
rocksdb::ColumnFamilyDescriptor descriptor;
};
struct Closable {
virtual ~Closable() {}
virtual rocksdb::Status Close() = 0;
};
struct Database final {
Database(std::string location) : location(std::move(location)) {}
~Database() { assert(!db); }
rocksdb::Status Close() {
if (!db) {
return rocksdb::Status::OK();
}
std::set<Closable*> closables;
{
std::lock_guard<std::mutex> lock(mutex_);
closables = std::move(closables_);
}
for (auto closable : closables) {
closable->Close();
}
db->FlushWAL(true);
for (auto& [id, column] : columns) {
db->DestroyColumnFamilyHandle(column.handle);
}
columns.clear();
auto db2 = std::move(db);
return db2->Close();
}
void Attach(Closable* closable) {
std::lock_guard<std::mutex> lock(mutex_);
closables_.insert(closable);
}
void Detach(Closable* closable) {
std::lock_guard<std::mutex> lock(mutex_);
closables_.erase(closable);
}
const std::string location;
std::unique_ptr<rocksdb::DB> db;
std::map<int32_t, ColumnFamily> columns;
private:
mutable std::mutex mutex_;
std::set<Closable*> closables_;
};
enum BatchOp { Empty, Put, Delete, Merge, Data };
struct BatchEntry {
BatchOp op = BatchOp::Empty;
std::optional<std::string> key = std::nullopt;
std::optional<std::string> val = std::nullopt;
std::optional<ColumnFamily> column = std::nullopt;
};
struct BatchIterator : public rocksdb::WriteBatch::Handler {
BatchIterator(Database* database,
const bool keys,
const bool values,
const bool data,
const rocksdb::ColumnFamilyHandle* column,
const Encoding keyEncoding,
const Encoding valueEncoding)
: database_(database),
keys_(keys),
values_(values),
data_(data),
column_(column),
keyEncoding_(keyEncoding),
valueEncoding_(valueEncoding) {}
napi_status Iterate(napi_env env, const rocksdb::WriteBatch& batch, napi_value* result) {
cache_.reserve(batch.Count());
ROCKS_STATUS_RETURN_NAPI(batch.Iterate(this));
napi_value putStr;
NAPI_STATUS_RETURN(napi_create_string_utf8(env, "put", NAPI_AUTO_LENGTH, &putStr));
napi_value delStr;
NAPI_STATUS_RETURN(napi_create_string_utf8(env, "del", NAPI_AUTO_LENGTH, &delStr));
napi_value mergeStr;
NAPI_STATUS_RETURN(napi_create_string_utf8(env, "merge", NAPI_AUTO_LENGTH, &mergeStr));
napi_value dataStr;
NAPI_STATUS_RETURN(napi_create_string_utf8(env, "data", NAPI_AUTO_LENGTH, &dataStr));
napi_value nullVal;
NAPI_STATUS_RETURN(napi_get_null(env, &nullVal));
NAPI_STATUS_RETURN(napi_create_array_with_length(env, cache_.size() * 4, result));
for (size_t n = 0; n < cache_.size(); ++n) {
napi_value op;
if (cache_[n].op == BatchOp::Put) {
op = putStr;
} else if (cache_[n].op == BatchOp::Delete) {
op = delStr;
} else if (cache_[n].op == BatchOp::Merge) {
op = mergeStr;
} else if (cache_[n].op == BatchOp::Data) {
op = dataStr;
} else {
continue;
}
NAPI_STATUS_RETURN(napi_set_element(env, *result, n * 4 + 0, op));
napi_value key;
NAPI_STATUS_RETURN(Convert(env, cache_[n].key, keyEncoding_, key));
NAPI_STATUS_RETURN(napi_set_element(env, *result, n * 4 + 1, key));
napi_value val;
NAPI_STATUS_RETURN(Convert(env, cache_[n].val, valueEncoding_, val));
NAPI_STATUS_RETURN(napi_set_element(env, *result, n * 4 + 2, val));
// TODO (fix)
// napi_value column = cache_[n].column ? cache_[n].column->val : nullVal;
NAPI_STATUS_RETURN(napi_set_element(env, *result, n * 4 + 3, nullVal));
}
cache_.clear();
return napi_ok;
}
rocksdb::Status PutCF(uint32_t column_family_id, const rocksdb::Slice& key, const rocksdb::Slice& value) override {
if (column_ && column_->GetID() != column_family_id) {
return rocksdb::Status::OK();
}
BatchEntry entry = {BatchOp::Put};
if (keys_) {
entry.key = key.ToStringView();
}
if (values_) {
entry.val = value.ToStringView();
}
// if (database_ && database_->columns.find(column_family_id) != database_->columns.end()) {
// entry.column = database_->columns[column_family_id];
// }
cache_.push_back(entry);
return rocksdb::Status::OK();
}
rocksdb::Status DeleteCF(uint32_t column_family_id, const rocksdb::Slice& key) override {
if (column_ && column_->GetID() != column_family_id) {
return rocksdb::Status::OK();
}
BatchEntry entry = {BatchOp::Delete};
if (keys_) {
entry.key = key.ToStringView();
}
// if (database_ && database_->columns.find(column_family_id) != database_->columns.end()) {
// entry.column = database_->columns[column_family_id];
// }
cache_.push_back(entry);
return rocksdb::Status::OK();
}
rocksdb::Status MergeCF(uint32_t column_family_id, const rocksdb::Slice& key, const rocksdb::Slice& value) override {
if (column_ && column_->GetID() != column_family_id) {
return rocksdb::Status::OK();
}
BatchEntry entry = {BatchOp::Merge};
if (keys_) {
entry.key = key.ToStringView();
}
if (values_) {
entry.val = value.ToStringView();
}
// if (database_ && database_->columns.find(column_family_id) != database_->columns.end()) {
// entry.column = database_->columns[column_family_id];
// }
cache_.push_back(entry);
return rocksdb::Status::OK();
}
void LogData(const rocksdb::Slice& data) override {
if (!data_) {
return;
}
BatchEntry entry = {BatchOp::Data};
entry.val = data.ToStringView();
cache_.push_back(entry);
}
bool Continue() override { return true; }
private:
Database* database_;
const bool keys_;
const bool values_;
const bool data_;
const rocksdb::ColumnFamilyHandle* column_;
const Encoding keyEncoding_;
const Encoding valueEncoding_;
std::vector<BatchEntry> cache_;
};
struct BaseIterator : public Closable {
BaseIterator(Database* database,
rocksdb::ColumnFamilyHandle* column,
const bool reverse,
const std::optional<std::string>& lt,
const std::optional<std::string>& lte,
const std::optional<std::string>& gt,
const std::optional<std::string>& gte,
const int limit,
const bool fillCache,
bool tailing = false)
: database_(database), column_(column), reverse_(reverse), limit_(limit) {
if (lte) {
upper_bound_ = rocksdb::PinnableSlice();
*upper_bound_->GetSelf() = std::move(*lte) + '\0';
upper_bound_->PinSelf();
} else if (lt) {
upper_bound_ = rocksdb::PinnableSlice();
*upper_bound_->GetSelf() = std::move(*lt);
upper_bound_->PinSelf();
}
if (gte) {
lower_bound_ = rocksdb::PinnableSlice();
*lower_bound_->GetSelf() = std::move(*gte);
lower_bound_->PinSelf();
} else if (gt) {
lower_bound_ = rocksdb::PinnableSlice();
*lower_bound_->GetSelf() = std::move(*gt) + '\0';
lower_bound_->PinSelf();
}
rocksdb::ReadOptions readOptions;
if (upper_bound_) {
readOptions.iterate_upper_bound = &*upper_bound_;
}
if (lower_bound_) {
readOptions.iterate_lower_bound = &*lower_bound_;
}
readOptions.fill_cache = fillCache;
readOptions.async_io = true;
readOptions.adaptive_readahead = true;
readOptions.tailing = tailing;
iterator_.reset(database_->db->NewIterator(readOptions, column_));
if (reverse_) {
iterator_->SeekToLast();
} else {
iterator_->SeekToFirst();
}
database_->Attach(this);
}
virtual ~BaseIterator() {
if (iterator_) {
database_->Detach(this);
}
}
virtual void Seek(const rocksdb::Slice& target) {
assert(iterator_);
if ((upper_bound_ && target.compare(*upper_bound_) >= 0) || (lower_bound_ && target.compare(*lower_bound_) < 0)) {
// TODO (fix): Why is this required? Seek should handle it?
// https://github.com/facebook/rocksdb/issues/9904
iterator_->SeekToLast();
if (iterator_->Valid()) {
iterator_->Next();
}
} else if (reverse_) {
iterator_->SeekForPrev(target);
} else {
iterator_->Seek(target);
}
}
virtual rocksdb::Status Close() override {
if (iterator_) {
lower_bound_.reset();
upper_bound_.reset();
iterator_.reset();
database_->Detach(this);
}
return rocksdb::Status::OK();
}
bool Valid() const {
assert(iterator_);
return iterator_->Valid();
}
bool Increment() {
assert(iterator_);
return limit_ < 0 || ++count_ <= limit_;
}
void Next() {
assert(iterator_);
if (reverse_)
iterator_->Prev();
else
iterator_->Next();
}
rocksdb::Slice CurrentKey() const {
assert(iterator_);
return iterator_->key();
}
rocksdb::Slice CurrentValue() const {
assert(iterator_);
return iterator_->value();
}
rocksdb::Status Status() const {
assert(iterator_);
return iterator_->status();
}
Database* database_;
rocksdb::ColumnFamilyHandle* column_;
private:
int count_ = 0;
std::optional<rocksdb::PinnableSlice> lower_bound_;
std::optional<rocksdb::PinnableSlice> upper_bound_;
std::unique_ptr<rocksdb::Iterator> iterator_;
const bool reverse_;
const int limit_;
};
class Iterator final : public BaseIterator {
const bool keys_;
const bool values_;
const size_t highWaterMarkBytes_;
bool first_ = true;
const Encoding keyEncoding_;
const Encoding valueEncoding_;
public:
Iterator(Database* database,
rocksdb::ColumnFamilyHandle* column,
const bool reverse,
const bool keys,
const bool values,
const int limit,
const std::optional<std::string>& lt,
const std::optional<std::string>& lte,
const std::optional<std::string>& gt,
const std::optional<std::string>& gte,
const bool fillCache,
const size_t highWaterMarkBytes,
bool tailing = false,
Encoding keyEncoding = Encoding::Invalid,
Encoding valueEncoding = Encoding::Invalid)
: BaseIterator(database, column, reverse, lt, lte, gt, gte, limit, fillCache, tailing),
keys_(keys),
values_(values),
highWaterMarkBytes_(highWaterMarkBytes),
keyEncoding_(keyEncoding),
valueEncoding_(valueEncoding) {}
void Seek(const rocksdb::Slice& target) override {
first_ = true;
return BaseIterator::Seek(target);
}
static std::unique_ptr<Iterator> create(napi_env env, napi_value db, napi_value options) {
Database* database;
NAPI_STATUS_THROWS(napi_get_value_external(env, db, reinterpret_cast<void**>(&database)));
bool reverse = false;
NAPI_STATUS_THROWS(GetProperty(env, options, "reverse", reverse));
bool keys = true;
NAPI_STATUS_THROWS(GetProperty(env, options, "keys", keys));
bool values = true;
NAPI_STATUS_THROWS(GetProperty(env, options, "values", values));
bool tailing = false;
NAPI_STATUS_THROWS(GetProperty(env, options, "tailing", tailing));
bool fillCache = false;
NAPI_STATUS_THROWS(GetProperty(env, options, "fillCache", fillCache));
int32_t limit = -1;
NAPI_STATUS_THROWS(GetProperty(env, options, "limit", limit));
int32_t highWaterMarkBytes = 64 * 1024;
NAPI_STATUS_THROWS(GetProperty(env, options, "highWaterMarkBytes", highWaterMarkBytes));
std::optional<std::string> lt;
NAPI_STATUS_THROWS(GetProperty(env, options, "lt", lt));
std::optional<std::string> lte;
NAPI_STATUS_THROWS(GetProperty(env, options, "lte", lte));
std::optional<std::string> gt;
NAPI_STATUS_THROWS(GetProperty(env, options, "gt", gt));
std::optional<std::string> gte;
NAPI_STATUS_THROWS(GetProperty(env, options, "gte", gte));
rocksdb::ColumnFamilyHandle* column = database->db->DefaultColumnFamily();
NAPI_STATUS_THROWS(GetProperty(env, options, "column", column));
Encoding keyEncoding;
NAPI_STATUS_THROWS(GetProperty(env, options, "keyEncoding", keyEncoding));
Encoding valueEncoding;
NAPI_STATUS_THROWS(GetProperty(env, options, "valueEncoding", valueEncoding));
return std::make_unique<Iterator>(database, column, reverse, keys, values, limit, lt, lte, gt, gte, fillCache,
highWaterMarkBytes, tailing, keyEncoding, valueEncoding);
}
napi_value nextv(napi_env env, uint32_t count, napi_value callback) {
struct State {
std::vector<rocksdb::PinnableSlice> keys;
std::vector<rocksdb::PinnableSlice> values;
size_t count = 0;
bool finished = false;
};
runAsync<State>("iterator.nextv", env, callback,
[=](auto& state) {
state.keys.reserve(count);
state.values.reserve(count);
size_t bytesRead = 0;
while (true) {
if (!first_) {
Next();
} else {
first_ = false;
}
ROCKS_STATUS_RETURN(Status());
if (!Valid() || !Increment()) {
state.finished = true;
break;
}
if (keys_ && values_) {
rocksdb::PinnableSlice k;
k.PinSelf(CurrentKey());
bytesRead += k.size();
state.keys.push_back(std::move(k));
rocksdb::PinnableSlice v;
v.PinSelf(CurrentValue());
bytesRead += v.size();
state.values.push_back(std::move(v));
} else if (keys_) {
rocksdb::PinnableSlice k;
k.PinSelf(CurrentKey());
bytesRead += k.size();
state.keys.push_back(std::move(k));
} else if (values_) {
rocksdb::PinnableSlice v;
v.PinSelf(CurrentValue());
bytesRead += v.size();
state.values.push_back(std::move(v));
} else {
assert(false);
}
state.count += 1;
if (bytesRead > highWaterMarkBytes_ || state.count >= count) {
break;
}
}
return rocksdb::Status::OK();
},
[=](auto& state, auto env, auto& argv) {
argv.resize(2);
napi_value finished;
NAPI_STATUS_RETURN(napi_get_boolean(env, state.finished, &finished));
napi_value rows;
NAPI_STATUS_RETURN(napi_create_array(env, &rows));
for (size_t n = 0; n < state.count; n++) {
napi_value key;
napi_value val;
if (keys_ && values_) {
NAPI_STATUS_RETURN(Convert(env, std::move(state.keys[n]), keyEncoding_, key));
NAPI_STATUS_RETURN(Convert(env, std::move(state.values[n]), valueEncoding_, val));
} else if (keys_) {
NAPI_STATUS_RETURN(Convert(env, std::move(state.keys[n]), keyEncoding_, key));
NAPI_STATUS_RETURN(napi_get_undefined(env, &val));
} else if (values_) {
NAPI_STATUS_RETURN(napi_get_undefined(env, &key));
NAPI_STATUS_RETURN(Convert(env, std::move(state.values[n]), valueEncoding_, val));
} else {
assert(false);
}
NAPI_STATUS_RETURN(napi_set_element(env, rows, n * 2 + 0, key));
NAPI_STATUS_RETURN(napi_set_element(env, rows, n * 2 + 1, val));
}
NAPI_STATUS_RETURN(napi_create_object(env, &argv[1]));
NAPI_STATUS_RETURN(napi_set_named_property(env, argv[1], "rows", rows));
NAPI_STATUS_RETURN(napi_set_named_property(env, argv[1], "finished", finished));
return napi_ok;
});
return 0;
}
napi_value nextv(napi_env env, uint32_t count) {
napi_value finished;
NAPI_STATUS_THROWS(napi_get_boolean(env, false, &finished));
napi_value rows;
NAPI_STATUS_THROWS(napi_create_array(env, &rows));
size_t idx = 0;
size_t bytesRead = 0;
while (true) {
if (!first_) {
Next();
} else {
first_ = false;
}
ROCKS_STATUS_THROWS_NAPI(Status());
if (!Valid() || !Increment()) {
NAPI_STATUS_THROWS(napi_get_boolean(env, true, &finished));
break;
}
napi_value key;
napi_value val;
if (keys_ && values_) {
const auto k = CurrentKey();
const auto v = CurrentValue();
NAPI_STATUS_THROWS(Convert(env, &k, keyEncoding_, key));
NAPI_STATUS_THROWS(Convert(env, &v, valueEncoding_, val));
bytesRead += k.size() + v.size();
} else if (keys_) {
const auto k = CurrentKey();
NAPI_STATUS_THROWS(Convert(env, &k, keyEncoding_, key));
NAPI_STATUS_THROWS(napi_get_undefined(env, &val));
bytesRead += k.size();
} else if (values_) {
const auto v = CurrentValue();
NAPI_STATUS_THROWS(napi_get_undefined(env, &key));
NAPI_STATUS_THROWS(Convert(env, &v, valueEncoding_, val));
bytesRead += v.size();
} else {
assert(false);
}
NAPI_STATUS_THROWS(napi_set_element(env, rows, idx++, key));
NAPI_STATUS_THROWS(napi_set_element(env, rows, idx++, val));
if (bytesRead > highWaterMarkBytes_ || idx / 2 >= count) {
break;
}
}
napi_value ret;
NAPI_STATUS_THROWS(napi_create_object(env, &ret));
NAPI_STATUS_THROWS(napi_set_named_property(env, ret, "rows", rows));
NAPI_STATUS_THROWS(napi_set_named_property(env, ret, "finished", finished));
return ret;
}
};
/**
* 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* data) {
auto database = reinterpret_cast<Database*>(data);
// 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->Close();
}
}
static void FinalizeDatabase(napi_env env, void* data, void* hint) {
auto database = reinterpret_cast<Database*>(data);
if (database) {
napi_remove_env_cleanup_hook(env, env_cleanup_hook, database);
database->Close();
}
}
NAPI_METHOD(db_init) {
NAPI_ARGV(1);
Database* database = nullptr;
napi_valuetype type;
NAPI_STATUS_THROWS(napi_typeof(env, argv[0], &type));
napi_value result;
if (type == napi_string) {
std::string location;
size_t length = 0;
NAPI_STATUS_THROWS(napi_get_value_string_utf8(env, argv[0], nullptr, 0, &length));
location.resize(length, '\0');
NAPI_STATUS_THROWS(napi_get_value_string_utf8(env, argv[0], &location[0], length + 1, &length));
database = new Database(location);
napi_add_env_cleanup_hook(env, env_cleanup_hook, database);
NAPI_STATUS_THROWS(napi_create_external(env, database, FinalizeDatabase, nullptr, &result));
} else if (type == napi_bigint) {
int64_t value;
bool lossless;
NAPI_STATUS_THROWS(napi_get_value_bigint_int64(env, argv[0], &value, &lossless));
database = reinterpret_cast<Database*>(value);
NAPI_STATUS_THROWS(napi_create_external(env, database, nullptr, nullptr, &result));
// We should have an env_cleanup_hook for closing iterators...
} else {
NAPI_STATUS_THROWS(napi_invalid_arg);
}
return result;
}
NAPI_METHOD(db_get_handle) {
NAPI_ARGV(1);
Database* database;
NAPI_STATUS_THROWS(napi_get_value_external(env, argv[0], reinterpret_cast<void**>(&database)));
napi_value result;
NAPI_STATUS_THROWS(napi_create_bigint_int64(env, reinterpret_cast<intptr_t>(database), &result));
return result;
}
NAPI_METHOD(db_get_location) {
NAPI_ARGV(1);
Database* database;
NAPI_STATUS_THROWS(napi_get_value_external(env, argv[0], reinterpret_cast<void**>(&database)));
napi_value result;
NAPI_STATUS_THROWS(Convert(env, &database->location, Encoding::String, result));
return result;
}
NAPI_METHOD(db_query) {
NAPI_ARGV(2);
return Iterator::create(env, argv[0], argv[1])->nextv(env, std::numeric_limits<uint32_t>::max());
}
template <typename T, typename U>
napi_status InitOptions(napi_env env, T& columnOptions, const U& options) {
rocksdb::ConfigOptions configOptions;
uint64_t memtable_memory_budget = 256 * 1024 * 1024;
NAPI_STATUS_RETURN(GetProperty(env, options, "memtableMemoryBudget", memtable_memory_budget));
std::optional<std::string> compactionOpt;
NAPI_STATUS_RETURN(GetProperty(env, options, "compaction", compactionOpt));
if (compactionOpt) {
if (*compactionOpt == "universal") {
columnOptions.write_buffer_size = memtable_memory_budget / 4;
// merge two memtables when flushing to L0
columnOptions.min_write_buffer_number_to_merge = 2;
// this means we'll use 50% extra memory in the worst case, but will reduce
// write stalls.
columnOptions.max_write_buffer_number = 6;
// universal style compaction
columnOptions.compaction_style = rocksdb::kCompactionStyleUniversal;
columnOptions.compaction_options_universal.compression_size_percent = 80;
} else if (*compactionOpt == "level") {
columnOptions.write_buffer_size = static_cast<size_t>(memtable_memory_budget / 4);
// merge two memtables when flushing to L0
columnOptions.min_write_buffer_number_to_merge = 2;
// this means we'll use 50% extra memory in the worst case, but will reduce
// write stalls.
columnOptions.max_write_buffer_number = 6;
// start flushing L0->L1 as soon as possible. each file on level0 is
// (memtable_memory_budget / 2). This will flush level 0 when it's bigger than
// memtable_memory_budget.
columnOptions.level0_file_num_compaction_trigger = 2;
// doesn't really matter much, but we don't want to create too many files
columnOptions.target_file_size_base = memtable_memory_budget / 8;
// make Level1 size equal to Level0 size, so that L0->L1 compactions are fast
columnOptions.max_bytes_for_level_base = memtable_memory_budget;
// level style compaction
columnOptions.compaction_style = rocksdb::kCompactionStyleLevel;
// only compress levels >= 2
columnOptions.compression_per_level.resize(columnOptions.num_levels);
for (int i = 0; i < columnOptions.num_levels; ++i) {
if (i < 2) {
columnOptions.compression_per_level[i] = rocksdb::kNoCompression;
} else {
columnOptions.compression_per_level[i] = rocksdb::kZSTD;
}
}
} else {
return napi_invalid_arg;
}
}
bool compression = true;
NAPI_STATUS_RETURN(GetProperty(env, options, "compression", compression));
if (compression) {
columnOptions.compression = rocksdb::kZSTD;
columnOptions.compression_opts.max_dict_bytes = 16 * 1024;
columnOptions.compression_opts.zstd_max_train_bytes = 16 * 1024 * 100;
// TODO (perf): compression_opts.parallel_threads
}
std::optional<std::string> prefixExtractorOpt;
NAPI_STATUS_RETURN(GetProperty(env, options, "prefixExtractor", prefixExtractorOpt));
if (prefixExtractorOpt) {
ROCKS_STATUS_RETURN_NAPI(
rocksdb::SliceTransform::CreateFromString(configOptions, *prefixExtractorOpt, &columnOptions.prefix_extractor));
}
std::optional<std::string> comparatorOpt;
NAPI_STATUS_RETURN(GetProperty(env, options, "comparator", comparatorOpt));
if (comparatorOpt) {
ROCKS_STATUS_RETURN_NAPI(
rocksdb::Comparator::CreateFromString(configOptions, *comparatorOpt, &columnOptions.comparator));
}
std::optional<std::string> mergeOperatorOpt;
NAPI_STATUS_RETURN(GetProperty(env, options, "mergeOperator", mergeOperatorOpt));
if (mergeOperatorOpt) {
if (*mergeOperatorOpt == "maxRev") {
columnOptions.merge_operator = std::make_shared<MaxRevOperator>();
} else {
ROCKS_STATUS_RETURN_NAPI(
rocksdb::MergeOperator::CreateFromString(configOptions, *mergeOperatorOpt, &columnOptions.merge_operator));
}
}
std::optional<std::string> compactionPriority;
NAPI_STATUS_RETURN(GetProperty(env, options, "compactionPriority", compactionPriority));
if (compactionPriority) {
if (compactionPriority == "byCompensatedSize") {
columnOptions.compaction_pri = rocksdb::kByCompensatedSize;
} else if (compactionPriority == "oldestLargestSeqFirst") {
columnOptions.compaction_pri = rocksdb::kOldestLargestSeqFirst;
} else if (compactionPriority == "smallestSeqFirst") {
columnOptions.compaction_pri = rocksdb::kOldestSmallestSeqFirst;
} else if (compactionPriority == "overlappingRatio") {
columnOptions.compaction_pri = rocksdb::kMinOverlappingRatio;
} else if (compactionPriority == "roundRobin") {
columnOptions.compaction_pri = rocksdb::kRoundRobin;
} else {
// Throw?
}
}
uint32_t cacheSize = 8 << 20;
NAPI_STATUS_RETURN(GetProperty(env, options, "cacheSize", cacheSize));
rocksdb::BlockBasedTableOptions tableOptions;
if (cacheSize) {
tableOptions.block_cache = rocksdb::HyperClockCacheOptions(cacheSize, 0).MakeSharedCache();
NAPI_STATUS_RETURN(
GetProperty(env, options, "cacheIndexAndFilterBlocks", tableOptions.cache_index_and_filter_blocks));
} else {
tableOptions.no_block_cache = true;
tableOptions.cache_index_and_filter_blocks = false;
}
std::string optimize = "";
NAPI_STATUS_RETURN(GetProperty(env, options, "optimize", optimize));
if (optimize == "point-lookup") {
tableOptions.data_block_index_type = rocksdb::BlockBasedTableOptions::kDataBlockBinaryAndHash;
tableOptions.data_block_hash_table_util_ratio = 0.75;
tableOptions.filter_policy.reset(rocksdb::NewRibbonFilterPolicy(10, 1));
columnOptions.memtable_prefix_bloom_size_ratio = 0.02;
columnOptions.memtable_whole_key_filtering = true;
} else if (optimize == "range-lookup") {
// TODO?
} else {
tableOptions.filter_policy.reset(rocksdb::NewBloomFilterPolicy(10));
}
std::optional<std::string> filterPolicyOpt;
NAPI_STATUS_RETURN(GetProperty(env, options, "filterPolicy", filterPolicyOpt));
if (filterPolicyOpt) {
ROCKS_STATUS_RETURN_NAPI(
rocksdb::FilterPolicy::CreateFromString(configOptions, *filterPolicyOpt, &tableOptions.filter_policy));
}
NAPI_STATUS_RETURN(GetProperty(env, options, "blockSize", tableOptions.block_size));
NAPI_STATUS_RETURN(GetProperty(env, options, "blockRestartInterval", tableOptions.block_restart_interval));
tableOptions.checksum = rocksdb::kXXH3;
tableOptions.decouple_partitioned_filters = true;
NAPI_STATUS_RETURN(GetProperty(env, options, "decouplePartitionedFilters", tableOptions.block_restart_interval));
tableOptions.optimize_filters_for_memory = true;
NAPI_STATUS_RETURN(GetProperty(env, options, "optimizeFiltersForMemory", tableOptions.optimize_filters_for_memory));
columnOptions.table_factory.reset(rocksdb::NewBlockBasedTableFactory(tableOptions));
return napi_ok;
}
NAPI_METHOD(db_get_identity) {
NAPI_ARGV(1);
Database* database;
NAPI_STATUS_THROWS(napi_get_value_external(env, argv[0], reinterpret_cast<void**>(&database)));
std::string identity;
ROCKS_STATUS_THROWS_NAPI(database->db->GetDbIdentity(identity));
napi_value result;
NAPI_STATUS_THROWS(Convert(env, &identity, Encoding::String, result));
return result;
}
NAPI_METHOD(db_open) {
NAPI_ARGV(3);
Database* database;
NAPI_STATUS_THROWS(napi_get_value_external(env, argv[0], reinterpret_cast<void**>(&database)));
if (database->db) {
napi_value columns;
NAPI_STATUS_THROWS(napi_create_object(env, &columns));
for (auto& [id, column] : database->columns) {
napi_value val;
NAPI_STATUS_THROWS(napi_create_external(env, column.handle, nullptr, nullptr, &val));
NAPI_STATUS_THROWS(napi_set_named_property(env, columns, column.descriptor.name.c_str(), val));
}
return columns;
} else {
rocksdb::Options dbOptions;
const auto options = argv[1];
int parallelism = std::max<int>(1, std::thread::hardware_concurrency() / 2);
NAPI_STATUS_THROWS(GetProperty(env, options, "parallelism", parallelism));
dbOptions.IncreaseParallelism(parallelism);
uint32_t walTTL = 0;
NAPI_STATUS_THROWS(GetProperty(env, options, "walTTL", walTTL));
dbOptions.WAL_ttl_seconds = walTTL / 1e3;
uint32_t walSizeLimit = 0;
NAPI_STATUS_THROWS(GetProperty(env, options, "walSizeLimit", walSizeLimit));
dbOptions.WAL_size_limit_MB = walSizeLimit / 1e6;
uint32_t maxTotalWalSize = 0;
NAPI_STATUS_THROWS(GetProperty(env, options, "walTotalSizeLimit", walSizeLimit));
dbOptions.max_total_wal_size = maxTotalWalSize / 1e6;
bool walCompression = false;
NAPI_STATUS_THROWS(GetProperty(env, options, "walCompression", walCompression));
dbOptions.wal_compression =
walCompression ? rocksdb::CompressionType::kZSTD : rocksdb::CompressionType::kNoCompression;
dbOptions.avoid_unnecessary_blocking_io = true;
dbOptions.write_dbid_to_manifest = true;
dbOptions.create_missing_column_families = true;
dbOptions.fail_if_options_file_error = true;
NAPI_STATUS_THROWS(GetProperty(env, options, "createIfMissing", dbOptions.create_if_missing));
NAPI_STATUS_THROWS(GetProperty(env, options, "errorIfExists", dbOptions.error_if_exists));
NAPI_STATUS_THROWS(GetProperty(env, options, "pipelinedWrite", dbOptions.enable_pipelined_write));
// TODO (feat): dbOptions.listeners
std::string infoLogLevel;
NAPI_STATUS_THROWS(GetProperty(env, options, "infoLogLevel", infoLogLevel));
if (infoLogLevel.size() > 0) {
rocksdb::InfoLogLevel lvl = {};
if (infoLogLevel == "debug")
lvl = rocksdb::InfoLogLevel::DEBUG_LEVEL;
else if (infoLogLevel == "info")
lvl = rocksdb::InfoLogLevel::INFO_LEVEL;
else if (infoLogLevel == "warn")
lvl = rocksdb::InfoLogLevel::WARN_LEVEL;
else if (infoLogLevel == "error")
lvl = rocksdb::InfoLogLevel::ERROR_LEVEL;
else if (infoLogLevel == "fatal")
lvl = rocksdb::InfoLogLevel::FATAL_LEVEL;
else if (infoLogLevel == "header")
lvl = rocksdb::InfoLogLevel::HEADER_LEVEL;
else