-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdb_descriptor.cpp
More file actions
2103 lines (1891 loc) · 81.3 KB
/
Copy pathdb_descriptor.cpp
File metadata and controls
2103 lines (1891 loc) · 81.3 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
#include "core/background_error.h"
#include "core/platform.h"
#include "database/db_descriptor.h"
#include "database/db_settings.h"
#include "napi/helpers.h"
#include "transaction/transaction_handle.h"
#include "transaction_log/transaction_log_store_registry.h"
#include "rocksdb/convenience.h"
#include "rocksdb/listener.h"
#include "rocksdb/utilities/options_util.h"
#include <algorithm>
#include <memory>
#include <system_error>
#include <unordered_map>
namespace rocksdb_js {
// forward declarations
static void callJsCallback(napi_env env, napi_value jsCallback, void* context, void* data);
// Process-global monotonic source for DBDescriptor::vtEpoch. Starts at 1 so a
// valid epoch is never 0. 64-bit: never wraps in practice, so every descriptor
// open across the process lifetime gets a distinct VerificationTable identity.
static std::atomic<uint64_t> vtEpochCounter{1};
static uint64_t nextVtEpoch() {
return vtEpochCounter.fetch_add(1, std::memory_order_relaxed);
}
// A column family's persisted compression, recovered from the on-disk OPTIONS
// file so a cold open of one CF does not clobber the others (compression is
// per-CF).
struct PersistedCompression {
rocksdb::CompressionType compression;
rocksdb::CompressionType blobCompression;
rocksdb::CompressionOptions compressionOpts;
};
// Applies a compression algorithm (and optional level) to both the SST block
// compression and the blob-file compression of the given column family options.
static void applyCompression(
rocksdb::ColumnFamilyOptions& cfOptions,
rocksdb::CompressionType compression,
const std::optional<int>& level
) {
cfOptions.compression = compression;
// Large values are stored in blob files (enable_blob_files), which have their
// own compression that defaults to none; apply the same algorithm so the
// whole dataset is compressed, not just the inline (< min_blob_size) portion.
cfOptions.blob_compression_type = compression;
// An explicit request is "algorithm + optional level"; omitting the level
// means the algorithm's default. When applied over a CF that inherited a
// persisted level (e.g. cold-reopening a zstd-level-19 CF as zlib), that
// inherited level must NOT carry over — reset it to the default sentinel so
// the effective request matches what the API documents (and what the registry
// warm-reopen check compares against).
cfOptions.compression_opts.level =
level ? *level : rocksdb::CompressionOptions::kDefaultCompressionLevel;
}
/**
* Resolves `max_write_buffer_size_to_maintain` for a column family.
*
* Retained memtable history is a floor, not a cap — RocksDB trims down to this target and never
* below — and that memory is charged to the process-wide WriteBufferManager. A target the budget
* cannot hold is therefore a deadlock rather than backpressure: the budget fills with history that
* is never released, and a manager built with `allowStall` stalls every write to the database
* permanently.
*
* The derived default (`-1` → `maxWriteBufferNumber * writeBufferSize`) is dropped to 0 under any
* stalling manager. Deliberately coarse: the safe per-family bound is the budget divided by the
* live column-family count, which is not knowable here, so a comfortably-sized budget loses its
* history window too. The cost is that conflict checking reports "cannot determine"
* (`kTryAgain`) more often, which callers retry; the cost of the alternative is a hang.
*
* That cost was measured rather than assumed, which is why the coarse form is kept instead of a
* budget-aware clamp: it is ~zero whenever flushing is organic (driven by memtables filling), and
* only appears once flushes are frequent relative to transaction lifetime — at a forced 20ms
* cadence against 20ms+ transactions it roughly doubles attempts per commit, as history is what
* would otherwise resolve a non-conflicting transaction whose snapshot has already been flushed
* away. A clamp would only recover that regime.
*
* An explicit caller value is honored untouched — sizing it against the budget and the
* column-family count is then the caller's job.
*/
static int64_t resolveMaxWriteBufferSizeToMaintain(const DBOptions& options) {
if (options.maxWriteBufferSizeToMaintain >= 0) {
return options.maxWriteBufferSizeToMaintain;
}
DBSettings& settings = DBSettings::getInstance();
if (settings.getWriteBufferManagerSize() > 0 && settings.getWriteBufferManagerAllowStall()) {
return 0;
}
return options.maxWriteBufferSizeToMaintain;
}
rocksdb::ColumnFamilyOptions buildColumnFamilyOptions(
const DBOptions& options,
rocksdb::ColumnFamilyOptions cfOptions
) {
rocksdb::BlockBasedTableOptions tableOptions;
if (options.noBlockCache) {
tableOptions.no_block_cache = true;
} else {
tableOptions.block_cache = DBSettings::getInstance().getBlockCache();
}
cfOptions.enable_blob_files = true;
cfOptions.min_blob_size = 2048;
cfOptions.enable_blob_garbage_collection = true;
cfOptions.write_buffer_size = static_cast<size_t>(options.writeBufferSize);
cfOptions.max_write_buffer_number = options.maxWriteBufferNumber;
cfOptions.max_write_buffer_size_to_maintain = resolveMaxWriteBufferSizeToMaintain(options);
cfOptions.table_factory.reset(rocksdb::NewBlockBasedTableFactory(tableOptions));
return cfOptions;
}
// Reads each existing column family's persisted compression from the database's
// latest OPTIONS file into `result`, returning the RocksDB status. The OPTIONS
// file is the ONLY authoritative source for a CF's stored compression (RocksDB
// does not restore per-CF options on open), so callers must treat a non-OK
// status as fatal for an existing DB rather than falling back to defaults —
// doing so would open the non-target CFs with the base default and silently
// restamp their compression on the next OPTIONS write.
static rocksdb::Status loadPersistedCompression(
const std::string& path,
std::unordered_map<std::string, PersistedCompression>& result
) {
rocksdb::ConfigOptions configOptions;
// Be permissive: we only read compression fields, so unknown/unsupported
// options in the persisted file must not fail the load.
configOptions.ignore_unknown_options = true;
configOptions.ignore_unsupported_options = true;
rocksdb::DBOptions loadedDbOptions;
std::vector<rocksdb::ColumnFamilyDescriptor> loadedCfDescriptors;
rocksdb::Status status =
rocksdb::LoadLatestOptions(configOptions, path, &loadedDbOptions, &loadedCfDescriptors);
if (status.ok()) {
for (const auto& descriptor : loadedCfDescriptors) {
result[descriptor.name] = PersistedCompression{
descriptor.options.compression,
descriptor.options.blob_compression_type,
descriptor.options.compression_opts,
};
}
}
return status;
}
struct JobTracker final {
int columnFamilyCount = 0;
rocksdb::SequenceNumber flushedSequence = 0;
};
/**
* Shared state between the RocksDB `EventListener` and the `DBDescriptor`,
* created BEFORE `DB::Open` so background callbacks fired during open have a
* valid, race-free target even though the descriptor does not exist yet
* (HarperFast/rocksdb-js#754). The descriptor pointer is published under
* `mutex_` once construction succeeds, and every read takes the same lock — so
* there is no data race on the `weak_ptr`. (The previous design bound a shared
* `weak_ptr` object after open while background threads called `lock()` on that
* same object concurrently, which is undefined behavior.)
*
* A background error that latches before the descriptor is attached is stashed
* as `pendingError_` (the same JSON form `setLastError` stores) and transferred
* to the descriptor on publish, so an error during open still reaches
* `getLastError()` / the `'error'` event instead of being silently dropped.
*/
struct DBEventListenerState final {
// Flush callbacks: the attached descriptor, or null before attach / after close.
std::shared_ptr<DBDescriptor> lockDescriptor() {
std::lock_guard<std::mutex> lock(this->mutex_);
return this->descriptor_.lock();
}
// OnBackgroundError: route the serialized error to the descriptor when it is
// attached, else stash it for transfer on publish. Touches no N-API and never
// blocks, so it is safe on a RocksDB background thread.
void recordBackgroundError(std::string json) {
std::shared_ptr<DBDescriptor> desc;
{
std::lock_guard<std::mutex> lock(this->mutex_);
desc = this->descriptor_.lock();
if (!desc) {
this->pendingError_ = std::move(json);
return;
}
}
// setLastError stores + emits; call it outside our lock.
desc->setLastError(std::move(json));
}
// Publish the descriptor once open succeeds and flush any error captured
// during open. A concurrent recordBackgroundError therefore either stashes
// (observed before publish, drained here) or routes straight to the
// descriptor (after) — never lost.
void publishDescriptor(std::shared_ptr<DBDescriptor> descriptor) {
std::string pending;
{
std::lock_guard<std::mutex> lock(this->mutex_);
this->descriptor_ = descriptor;
pending.swap(this->pendingError_);
}
if (!pending.empty()) {
descriptor->setLastError(std::move(pending));
}
}
private:
std::mutex mutex_;
std::weak_ptr<DBDescriptor> descriptor_;
std::string pendingError_;
};
/**
* Custom event listener that handles flush completion events and notifies
* transaction log stores to track what has been flushed to the database.
*/
class TransactionLogEventListener : public rocksdb::EventListener {
public:
TransactionLogEventListener(std::shared_ptr<DBEventListenerState> state)
: state(std::move(state)) {}
void OnFlushBegin(rocksdb::DB* db, const rocksdb::FlushJobInfo& flush_info) override {
auto desc = this->state->lockDescriptor();
if (!desc) {
return;
}
// RocksDB can run flushes concurrently across background threads, so guard
// the shared jobTrackers map — concurrent std::unordered_map access is a
// data race.
std::lock_guard<std::mutex> jobLock(this->jobTrackersMutex);
// Track flush job by job_id, so we can determine when all the flushes have completed for
// With atomic flushes, there will be multiple flush events for each column family in the database
// We we want to flush at the beginning of the flush job (for first time job_id appears)
// And then we want to track the job so that we can determine when all the flushes have completed for
// the database job.
auto it = this->jobTrackers.find(flush_info.job_id);
if (it == this->jobTrackers.end()) {
// Create new entry
JobTracker tracker;
tracker.columnFamilyCount = 1;
rocksdb::SequenceNumber flushedSequence = flush_info.largest_seqno;
tracker.flushedSequence = flushedSequence;
this->jobTrackers[flush_info.job_id] = tracker;
DEBUG_LOG("%p TransactionLogEventListener::OnFlushBegin flushedSequence=%llu\n",
desc.get(), (unsigned long long)flushedSequence);
// Get stores from the registry
auto stores = TransactionLogStoreRegistry::GetStores(desc->path);
for (auto& store : stores) {
store->databaseFlushBegin(flushedSequence);
}
} else {
// Increment existing entry so we know how many column families are being flushed
it->second.columnFamilyCount++;
}
}
void OnFlushCompleted(rocksdb::DB* db, const rocksdb::FlushJobInfo& flush_info) override {
auto desc = this->state->lockDescriptor();
if (!desc) {
return;
}
rocksdb::SequenceNumber flushedSequence = flush_info.largest_seqno;
DEBUG_LOG("%p TransactionLogEventListener::OnFlushCompleted cf name=%s job id=%u flushedSequence=%llu\n",
desc.get(), flush_info.cf_name.c_str(), flush_info.job_id, (unsigned long long)flushedSequence);
// Guard the shared jobTrackers map — see OnFlushBegin.
std::lock_guard<std::mutex> jobLock(this->jobTrackersMutex);
// Track flush job by job_id
auto it = this->jobTrackers.find(flush_info.job_id);
if (it == this->jobTrackers.end()) {
DEBUG_LOG("%p TransactionLogEventListener::OnFlushCompleted unable to find job id=%d\n",
desc.get(), flush_info.job_id);
} else {
// we find the highest sequence number; this represents the overall sequence
// number for the flush job
if (flushedSequence > it->second.flushedSequence) {
it->second.flushedSequence = flushedSequence;
}
// Decrement existing entry until we have completed all the flush actions for the job
if (--it->second.columnFamilyCount == 0) {
// The last CF flush has completed for the job, now signal that the database flush is done
DEBUG_LOG("%p TransactionLogEventListener::OnFlushCompleted job completed name=%s job id=%d flushedSequence=%llu\n",
desc.get(), flush_info.cf_name.c_str(), flush_info.job_id, (unsigned long long)it->second.flushedSequence);
// Get stores from the registry
auto stores = TransactionLogStoreRegistry::GetStores(desc->path);
for (auto& store : stores) {
store->databaseFlushed(it->second.flushedSequence);
}
this->jobTrackers.erase(it); // cleanup
}
}
}
// Surfaces a RocksDB background error to JS (HarperFast/rocksdb-js#730).
// Serializes it to a JSON string and hands it to `setLastError`, which stores
// it (readable on demand via `db.getLastError()`) and emits the `'error'`
// event — both reconstruct the same `BackgroundError` from this string on the
// JS thread, so nothing N-API/env-bound is touched here. We do NOT suppress
// the error (leaving *bgError untouched) — the point is to surface it, not
// hide it. Runs on flush/compaction/write threads; storing a string and the
// thread-safe, asynchronous emit keep this cheap and non-blocking.
void OnBackgroundError(rocksdb::BackgroundErrorReason reason, rocksdb::Status* bgError) override {
if (bgError == nullptr) {
return;
}
// Route through the shared state (NOT the descriptor directly): an error
// latched during DB::Open, before the descriptor is attached, is stashed
// and transferred on publish rather than dropped (#754).
int severity = static_cast<int>(bgError->severity());
int reasonInt = static_cast<int>(reason);
this->state->recordBackgroundError(backgroundErrorToJson(
bgError->ToString(),
severity,
backgroundErrorSeverityName(severity),
backgroundErrorDisablesWrites(severity),
reasonInt,
backgroundErrorReasonName(reasonInt)
));
}
private:
std::shared_ptr<DBEventListenerState> state;
std::mutex jobTrackersMutex;
std::unordered_map<int, JobTracker> jobTrackers;
};
/**
* Creates a new database descriptor. This constructor is private. To create a
* new DBDescriptor, use `DBDescriptor::open()`.
*/
DBDescriptor::DBDescriptor(
const std::string& path,
const DBOptions& options,
const rocksdb::ColumnFamilyOptions& cfOptions,
std::shared_ptr<rocksdb::DB> db,
std::unordered_map<std::string, std::shared_ptr<ColumnFamilyDescriptor>>&& columns,
std::shared_ptr<rocksdb::Statistics> statistics
):
path(path),
vtEpoch(nextVtEpoch()),
mode(options.mode),
readOnly(options.readOnly),
cfOptions(cfOptions),
db(db),
columns(std::move(columns)),
statistics(statistics)
{}
/**
* Destroy the database descriptor and any resources associated to it
* (transactions, iterators, etc).
*/
DBDescriptor::~DBDescriptor() {
DEBUG_LOG("%p DBDescriptor::~DBDescriptor Closing \"%s\"\n", this, this->path.c_str());
this->close();
// Idempotent safety net, matching commitWorker/logWorker's own
// destructor shutdown.
this->parkTimeouts->shutdown();
}
/**
* Close the database descriptor and any resources associated with it
* (transactions, iterators, etc).
*/
void DBDescriptor::close() {
// check if already closing
if (!this->beginClose()) {
DEBUG_LOG("%p DBDescriptor::close Already closing \"%s\"\n", this, this->path.c_str());
return;
}
this->finishClose();
}
void DBDescriptor::finishClose() {
DEBUG_LOG("%p DBDescriptor::close Closing \"%s\" (mode=%s read-only=%s closables=%zu columns=%zu transactions=%zu)\n",
this, this->path.c_str(), this->mode == DBMode::Optimistic ? "optimistic" : "pessimistic", this->readOnly ? "true" : "false", this->closables.size(), this->columns.size(), this->transactions.size());
// Wait for all in-flight operations to complete before cleanup.
// The closing flag is already set, so new operations will fail with "Database is closing".
// Existing operations will decrement operationsInFlight and notify us when done.
DEBUG_LOG("%p DBDescriptor::close Waiting for %u in-flight operations \"%s\"\n", this, this->operationsInFlight.load(), this->path.c_str());
uint32_t current;
while ((current = this->operationsInFlight.load()) != 0) {
this->operationsInFlight.wait(current);
}
DEBUG_LOG("%p DBDescriptor::close All operations complete \"%s\"\n", this, this->path.c_str());
// Drain the commit pipeline before flushing so its data is included in
// the flush. The log lane feeds the commit lane, so it must drain first;
// its final tasks enqueue onto the still-running commit lane (or run
// inline once that lane stops).
this->logWorker.shutdown();
this->commitWorker.shutdown();
// Release any remaining per-env commit-completion tsfns. An in-flight
// commit pins this descriptor (state -> txnHandle -> dbHandle -> descriptor),
// so reaching here means no commit is in flight; only idle (unref'd) tsfns
// for still-living envs can remain, and those envs will issue no further
// commits to this descriptor. Queued completions already handed to a tsfn
// are still delivered (napi_tsfn_release, not abort).
{
std::lock_guard<std::mutex> lock(this->commitMutex);
for (auto& [env, completion] : this->commitCompletions) {
if (completion.tsfn) {
::napi_release_threadsafe_function(completion.tsfn, napi_tsfn_release);
}
}
this->commitCompletions.clear();
// Block any later registerCommitCompletion (a commit racing this close
// from another env) from re-creating a tsfn that would never be
// released; such commits fall back to the legacy libuv path.
this->commitCompletionsClosed = true;
}
// We want to ensure that all in-memory data is written to disk
this->flush();
// Trigger manual compaction on all column families to reclaim space from
// tombstones before closing
if (!this->readOnly && DBSettings::getInstance().getCompactOnClose()) {
// Snapshot under the columns mutex; a concurrent drop can erase from
// the map while we compact.
std::vector<std::shared_ptr<ColumnFamilyDescriptor>> pinnedColumns;
{
std::lock_guard<std::mutex> columnsLock(this->columnsMutex);
pinnedColumns.reserve(this->columns.size());
for (const auto& [name, columnDesc] : this->columns) {
pinnedColumns.push_back(columnDesc);
}
}
for (const auto& columnDesc : pinnedColumns) {
if (columnDesc && columnDesc->column) {
this->compactRange(columnDesc->column.get(), nullptr, nullptr);
}
}
}
// Wait for any outstanding (background threads) operations to complete.
// Note that this is not setting the RocksDB `close_db` flag since active
// references to the databases may still exist. Also, contrary to the
// suggestions of the documentation, this method alone does not seem to
// trigger a flush
rocksdb::WaitForCompactOptions options;
this->db->WaitForCompact(options);
std::unique_lock<std::mutex> txnsLock(this->txnsMutex);
// Close all handles that still exist and reset their descriptor references
for (auto it = this->closables.begin(); it != this->closables.end(); ) {
if (auto closable = it->second.lock()) {
// Remove from map before closing to avoid re-entrant detach() calls
it = this->closables.erase(it);
// Release mutex during close to avoid deadlocks
txnsLock.unlock();
closable->close();
txnsLock.lock();
} else {
// Handle was already GC'd, just remove the expired weak_ptr
it = this->closables.erase(it);
}
}
// Safety-net: cancel any VT locks still held by this DB after all
// TransactionHandles have been closed. Under normal operation the
// closable->close() calls above already call releaseIntent() + wake()
// for every transaction; this is a defensive final pass.
{
auto* vt = DBSettings::getInstance().getVerificationTableRaw();
if (vt) {
vt->cancelForDB(this->vtEpoch);
}
}
// A park can be registered on a foreign-dbId tracker (colliding VT slot;
// see the ParkTimeout header comment), so cancelForDB() above cannot be
// relied on to have woken everything this descriptor is waiting on.
// ParkTimeoutRegistry::shutdown() resolves whatever is left regardless.
this->parkTimeouts->shutdown();
// Unregister from transaction log store registry - this will clean up stores
// when the last descriptor for this path is closed
TransactionLogStoreRegistry::Unregister(this->path);
this->transactions.clear();
{
std::lock_guard<std::mutex> columnsLock(this->columnsMutex);
this->columns.clear();
}
this->events.releaseAll();
this->db.reset();
}
napi_status DBDescriptor::registerCommitCompletion(napi_env env, napi_threadsafe_function_call_js callJs, bool& closed) {
std::lock_guard<std::mutex> lock(this->commitMutex);
closed = this->commitCompletionsClosed;
if (closed) {
return napi_ok;
}
CommitCompletion& completion = this->commitCompletions[env];
if (completion.tsfn == nullptr) {
napi_value resourceName;
napi_status status = ::napi_create_string_utf8(env, "rocksdb.commit", NAPI_AUTO_LENGTH, &resourceName);
if (status != napi_ok) {
return status;
}
// Created ref'd (thread count 1 for the commit thread), which is what we
// want with a commit about to be dispatched.
status = ::napi_create_threadsafe_function(
env,
nullptr, // func: callJs does all the work
nullptr, // async_resource
resourceName,
0, // unlimited queue
1, // initial thread count: the commit thread
nullptr, // finalize data
nullptr, // finalize cb
nullptr, // context
callJs,
&completion.tsfn
);
if (status != napi_ok) {
this->commitCompletions.erase(env);
return status;
}
} else if (completion.pending == 0) {
// Waking from idle: keep the event loop alive until completion.
napi_status status = ::napi_ref_threadsafe_function(env, completion.tsfn);
if (status != napi_ok) {
return status;
}
}
completion.pending++;
return napi_ok;
}
bool DBDescriptor::dispatchCommitCompletion(napi_env env, void* state) {
std::lock_guard<std::mutex> lock(this->commitMutex);
auto it = this->commitCompletions.find(env);
if (it == this->commitCompletions.end() || it->second.tsfn == nullptr) {
// env was torn down / released; the caller drops the state.
return false;
}
napi_status status = ::napi_call_threadsafe_function(it->second.tsfn, state, napi_tsfn_nonblocking);
return status == napi_ok;
}
void DBDescriptor::finishCommitCompletion(napi_env env) {
std::lock_guard<std::mutex> lock(this->commitMutex);
auto it = this->commitCompletions.find(env);
if (it != this->commitCompletions.end() && --it->second.pending == 0 && it->second.tsfn != nullptr) {
// Idle: allow the event loop to exit.
::napi_unref_threadsafe_function(env, it->second.tsfn);
}
}
void DBDescriptor::releaseCommitCompletionsByEnv(napi_env env) {
std::lock_guard<std::mutex> lock(this->commitMutex);
auto it = this->commitCompletions.find(env);
if (it != this->commitCompletions.end()) {
if (it->second.tsfn != nullptr) {
// Queued completions are still delivered before the tsfn finalizes.
::napi_release_threadsafe_function(it->second.tsfn, napi_tsfn_release);
}
this->commitCompletions.erase(it);
}
}
uint64_t ParkTimeoutRegistry::schedule(
napi_env env,
unsigned timeoutMs,
napi_threadsafe_function tsfn,
std::shared_ptr<std::atomic<bool>> fired
) {
std::lock_guard<std::mutex> lock(this->mutex);
if (this->stopped) {
// Descriptor already closing: the caller must resolve inline without
// registering with the LockTracker at all (see the header comment).
return 0;
}
if (!this->threadStarted) {
try {
this->thread = std::thread([this]() { this->runLoop(); });
} catch (...) {
// Thread creation failed (e.g. thread/resource exhaustion): leave
// the flag false so the next park retries, and tell the caller to
// resolve inline now rather than register a park nothing will
// ever time out.
return 0;
}
this->threadStarted = true;
}
auto entry = std::make_unique<ParkTimeout>();
entry->id = this->nextId++;
entry->env = env;
entry->tsfn = tsfn;
entry->fired = std::move(fired);
uint64_t id = entry->id;
auto deadlineIt = this->deadlines.emplace(
std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs),
id
);
entry->deadlineIt = deadlineIt;
this->parks.emplace(id, std::move(entry));
if (deadlineIt == this->deadlines.begin()) {
// Only the new earliest deadline needs the loop re-armed (this also
// covers waking it out of the indefinite wait when `deadlines` was
// empty); any later one already fires within a wait it will take.
this->cv.notify_all();
}
return id;
}
std::unique_ptr<ParkTimeoutRegistry::ParkTimeout> ParkTimeoutRegistry::take(uint64_t id) {
auto it = this->parks.find(id);
if (it == this->parks.end()) {
return nullptr;
}
std::unique_ptr<ParkTimeout> owned = std::move(it->second);
this->deadlines.erase(owned->deadlineIt);
this->parks.erase(it);
return owned;
}
void ParkTimeoutRegistry::resolve(ParkTimeout& park) {
bool expected = false;
if (park.fired->compare_exchange_strong(expected, true)) {
// A closing tsfn (env teardown racing this resolve) must not be
// touched again -- napi_closing means Node may already be freeing it.
napi_status status = ::napi_call_threadsafe_function(park.tsfn, nullptr, napi_tsfn_nonblocking);
if (status == napi_ok) {
::napi_release_threadsafe_function(park.tsfn, napi_tsfn_release);
}
}
}
void ParkTimeoutRegistry::runLoop() {
setThreadName("rocksdb-park-timeout");
std::unique_lock<std::mutex> lock(this->mutex);
for (;;) {
if (this->stopped) {
return;
}
if (this->deadlines.empty()) {
this->cv.wait(lock);
continue;
}
auto now = std::chrono::steady_clock::now();
// Copy the deadline: wait_until releases the lock while parked, during
// which this entry can be erased (a real wake racing the timeout) and
// the map node freed -- a bound reference into it would be a read of
// freed memory once the wait re-checks time.
std::chrono::steady_clock::time_point earliest = this->deadlines.begin()->first;
if (earliest > now) {
this->cv.wait_until(lock, earliest);
continue;
}
// Fire while still holding the mutex, like dispatchCommitCompletion.
while (!this->deadlines.empty() && this->deadlines.begin()->first <= now) {
auto deadlineIt = this->deadlines.begin();
auto parkIt = this->parks.find(deadlineIt->second);
this->deadlines.erase(deadlineIt);
if (parkIt == this->parks.end()) {
continue;
}
std::unique_ptr<ParkTimeout> due = std::move(parkIt->second);
this->parks.erase(parkIt);
ParkTimeoutRegistry::resolve(*due);
}
}
}
void ParkTimeoutRegistry::fire(uint64_t id) {
std::lock_guard<std::mutex> lock(this->mutex);
std::unique_ptr<ParkTimeout> owned = this->take(id);
if (!owned) {
// Already claimed by the timeout thread, releaseByEnv, or shutdown.
return;
}
ParkTimeoutRegistry::resolve(*owned);
}
void ParkTimeoutRegistry::releaseByEnv(napi_env env) {
std::lock_guard<std::mutex> lock(this->mutex);
for (auto it = this->parks.begin(); it != this->parks.end();) {
if (it->second->env != env) {
++it;
continue;
}
// Mark fired first so neither the timeout thread nor a later real
// wake ever calls into the tsfn we're about to release -- the
// promise's env is gone, nothing is listening for the resolve.
bool expected = false;
it->second->fired->compare_exchange_strong(expected, true);
if (!expected) {
::napi_release_threadsafe_function(it->second->tsfn, napi_tsfn_release);
}
this->deadlines.erase(it->second->deadlineIt);
it = this->parks.erase(it);
}
}
void ParkTimeoutRegistry::shutdown() {
std::thread toJoin;
{
std::lock_guard<std::mutex> lock(this->mutex);
if (this->stopped && !this->threadStarted) {
// Already fully shut down (e.g. finishClose() already ran; this is
// the destructor's belt-and-suspenders call) -- nothing left to do.
return;
}
this->stopped = true;
if (this->threadStarted) {
toJoin = std::move(this->thread);
this->threadStarted = false;
}
// Resolve every park still pending, under the same mutex the other
// three methods serialize their tsfn calls on -- draining outside the
// lock would let a concurrent releaseByEnv for a dying env observe
// "nothing to cancel" while this is mid-call on that same env's tsfn,
// racing Node freeing it.
for (auto& entry : this->parks) {
ParkTimeoutRegistry::resolve(*entry.second);
}
this->parks.clear();
this->deadlines.clear();
}
// Notify + join outside the lock: the loop's cv.wait_until needs to
// re-acquire the mutex to observe `stopped` and return, so joining while
// still holding it would deadlock.
this->cv.notify_all();
if (toJoin.joinable()) {
toJoin.join();
}
}
ParkTimeoutRegistry::~ParkTimeoutRegistry() {
this->shutdown();
}
/**
* Registers a database resource to be closed when the descriptor is closed.
*
* Important: The closable must be same smart_ptr that is napi-wrapped and
* bound to the JavaScript class counterpart.
*/
void DBDescriptor::attach(std::shared_ptr<Closable> closable) {
std::lock_guard<std::mutex> lock(this->txnsMutex);
this->closables[closable.get()] = std::weak_ptr<Closable>(closable);
}
/**
* Unregisters a database resource from being closed when the descriptor is
* closed.
*/
void DBDescriptor::detach(std::shared_ptr<Closable> closable) {
std::lock_guard<std::mutex> lock(this->txnsMutex);
this->closables.erase(closable.get());
}
#define SET_DOUBLE_PROP(obj, name, value) \
do { \
napi_value jsValue; \
NAPI_STATUS_THROWS(::napi_create_double(env, value, &jsValue)); \
NAPI_STATUS_THROWS(::napi_set_named_property(env, obj, name, jsValue)); \
} while (0)
#define SET_INT64_PROP(obj, name, value) \
do { \
napi_value jsValue; \
NAPI_STATUS_THROWS(::napi_create_int64(env, value, &jsValue)); \
NAPI_STATUS_THROWS(::napi_set_named_property(env, obj, name, jsValue)); \
} while (0)
#define SET_HISTOGRAM_DATA_PROP(obj, name, histogram) \
do { \
rocksdb::HistogramData hist; \
this->statistics->histogramData(histogram, &hist); \
napi_value jsValue = buildHistogramDataObject(env, hist); \
NAPI_STATUS_THROWS(::napi_set_named_property(env, obj, name, jsValue)); \
} while (0)
napi_value buildHistogramDataObject(napi_env env, const rocksdb::HistogramData& hist) {
napi_value obj;
NAPI_STATUS_THROWS(::napi_create_object(env, &obj));
SET_DOUBLE_PROP(obj, "average", hist.average);
SET_INT64_PROP(obj, "count", hist.count);
SET_DOUBLE_PROP(obj, "max", hist.max);
SET_DOUBLE_PROP(obj, "median", hist.median);
SET_DOUBLE_PROP(obj, "min", hist.min);
SET_DOUBLE_PROP(obj, "percentile95", hist.percentile95);
SET_DOUBLE_PROP(obj, "percentile99", hist.percentile99);
SET_DOUBLE_PROP(obj, "standardDeviation", hist.standard_deviation);
SET_INT64_PROP(obj, "sum", hist.sum);
return obj;
}
napi_value DBDescriptor::getStat(napi_env env, const std::string& statName) {
if (!this->statistics) {
::napi_throw_error(env, nullptr, "Statistics are not enabled");
NAPI_RETURN_UNDEFINED();
}
for (const auto& [ticker, name] : rocksdb::TickersNameMap) {
if (name == statName) {
uint64_t value = this->statistics->getTickerCount(ticker);
napi_value result;
NAPI_STATUS_THROWS(::napi_create_int64(env, value, &result));
return result;
}
}
for (const auto& [histogram, name] : rocksdb::HistogramsNameMap) {
if (name == statName) {
rocksdb::HistogramData hist;
this->statistics->histogramData(histogram, &hist);
return buildHistogramDataObject(env, hist);
}
}
NAPI_RETURN_UNDEFINED();
}
bool DBDescriptor::getStats(napi_env env, bool all, napi_value* result) {
if (!this->statistics) {
return false;
}
#undef NAPI_STATUS_THROWS
#define NAPI_STATUS_THROWS(call) NAPI_STATUS_THROWS_RVAL(call, false)
NAPI_STATUS_THROWS(::napi_create_object(env, result));
if (all) {
// get all stats
for (const auto& [ticker, name] : rocksdb::TickersNameMap) {
napi_value value;
NAPI_STATUS_THROWS(::napi_create_int64(env, this->statistics->getTickerCount(ticker), &value));
napi_value key;
NAPI_STATUS_THROWS(::napi_create_string_utf8(env, name.c_str(), name.size(), &key));
NAPI_STATUS_THROWS(::napi_set_property(env, *result, key, value));
}
for (const auto& [histogram, name] : rocksdb::HistogramsNameMap) {
rocksdb::HistogramData hist;
this->statistics->histogramData(histogram, &hist);
napi_value key;
NAPI_STATUS_THROWS(::napi_create_string_utf8(env, name.c_str(), name.size(), &key));
napi_value value = buildHistogramDataObject(env, hist);
NAPI_STATUS_THROWS(::napi_set_property(env, *result, key, value));
}
} else {
// get essential stats
// block cache
SET_INT64_PROP(*result, "rocksdb.block.cache.hit", this->statistics->getTickerCount(rocksdb::Tickers::BLOCK_CACHE_HIT));
SET_INT64_PROP(*result, "rocksdb.block.cache.miss", this->statistics->getTickerCount(rocksdb::Tickers::BLOCK_CACHE_MISS));
SET_INT64_PROP(*result, "rocksdb.block.cache.data.hit", this->statistics->getTickerCount(rocksdb::Tickers::BLOCK_CACHE_DATA_HIT));
SET_INT64_PROP(*result, "rocksdb.block.cache.data.miss", this->statistics->getTickerCount(rocksdb::Tickers::BLOCK_CACHE_DATA_MISS));
SET_INT64_PROP(*result, "rocksdb.block.cache.index.hit", this->statistics->getTickerCount(rocksdb::Tickers::BLOCK_CACHE_INDEX_HIT));
SET_INT64_PROP(*result, "rocksdb.block.cache.index.miss", this->statistics->getTickerCount(rocksdb::Tickers::BLOCK_CACHE_INDEX_MISS));
SET_INT64_PROP(*result, "rocksdb.block.cache.filter.hit", this->statistics->getTickerCount(rocksdb::Tickers::BLOCK_CACHE_FILTER_HIT));
SET_INT64_PROP(*result, "rocksdb.block.cache.filter.miss", this->statistics->getTickerCount(rocksdb::Tickers::BLOCK_CACHE_FILTER_MISS));
// bloom filter
SET_INT64_PROP(*result, "rocksdb.bloom.filter.useful", this->statistics->getTickerCount(rocksdb::Tickers::BLOOM_FILTER_USEFUL));
SET_INT64_PROP(*result, "rocksdb.bloom.filter.full.positive", this->statistics->getTickerCount(rocksdb::Tickers::BLOOM_FILTER_FULL_POSITIVE));
SET_INT64_PROP(*result, "rocksdb.bloom.filter.full.true.positive", this->statistics->getTickerCount(rocksdb::Tickers::BLOOM_FILTER_FULL_TRUE_POSITIVE));
// iterators
SET_INT64_PROP(*result, "rocksdb.db.iter.bytes.read", this->statistics->getTickerCount(rocksdb::Tickers::ITER_BYTES_READ));
SET_INT64_PROP(*result, "rocksdb.number.reseeks.iteration", this->statistics->getTickerCount(rocksdb::Tickers::NUMBER_OF_RESEEKS_IN_ITERATION));
// keys
SET_INT64_PROP(*result, "rocksdb.number.keys.read", this->statistics->getTickerCount(rocksdb::Tickers::NUMBER_KEYS_READ));
SET_INT64_PROP(*result, "rocksdb.number.keys.written", this->statistics->getTickerCount(rocksdb::Tickers::NUMBER_KEYS_WRITTEN));
// values
SET_INT64_PROP(*result, "rocksdb.bytes.read", this->statistics->getTickerCount(rocksdb::Tickers::BYTES_READ));
SET_INT64_PROP(*result, "rocksdb.bytes.written", this->statistics->getTickerCount(rocksdb::Tickers::BYTES_WRITTEN));
// memtable
SET_INT64_PROP(*result, "rocksdb.memtable.hit", this->statistics->getTickerCount(rocksdb::Tickers::MEMTABLE_HIT));
SET_INT64_PROP(*result, "rocksdb.memtable.miss", this->statistics->getTickerCount(rocksdb::Tickers::MEMTABLE_MISS));
// transactions
SET_INT64_PROP(*result, "rocksdb.txn.overhead.mutex.prepare", this->statistics->getTickerCount(rocksdb::Tickers::TXN_PREPARE_MUTEX_OVERHEAD));
SET_INT64_PROP(*result, "rocksdb.txn.overhead.mutex.old.commit.map", this->statistics->getTickerCount(rocksdb::Tickers::TXN_OLD_COMMIT_MAP_MUTEX_OVERHEAD));
SET_INT64_PROP(*result, "rocksdb.txn.overhead.mutex.snapshot", this->statistics->getTickerCount(rocksdb::Tickers::TXN_SNAPSHOT_MUTEX_OVERHEAD));
// compaction
SET_INT64_PROP(*result, "rocksdb.compact.read.bytes", this->statistics->getTickerCount(rocksdb::Tickers::COMPACT_READ_BYTES));
SET_INT64_PROP(*result, "rocksdb.compact.write.bytes", this->statistics->getTickerCount(rocksdb::Tickers::COMPACT_WRITE_BYTES));
SET_INT64_PROP(*result, "rocksdb.compaction.cancelled", this->statistics->getTickerCount(rocksdb::Tickers::COMPACTION_CANCELLED));
SET_INT64_PROP(*result, "rocksdb.stall.micros", this->statistics->getTickerCount(rocksdb::Tickers::STALL_MICROS));
// errors & i/o
SET_INT64_PROP(*result, "rocksdb.no.file.errors", this->statistics->getTickerCount(rocksdb::Tickers::NO_FILE_ERRORS));
SET_INT64_PROP(*result, "rocksdb.read.amp.estimate.useful.bytes", this->statistics->getTickerCount(rocksdb::Tickers::READ_AMP_ESTIMATE_USEFUL_BYTES));
SET_INT64_PROP(*result, "rocksdb.read.amp.total.read.bytes", this->statistics->getTickerCount(rocksdb::Tickers::READ_AMP_TOTAL_READ_BYTES));
// histogram data
SET_HISTOGRAM_DATA_PROP(*result, "rocksdb.db.get.micros", rocksdb::Histograms::DB_GET);
SET_HISTOGRAM_DATA_PROP(*result, "rocksdb.db.write.micros", rocksdb::Histograms::DB_WRITE);
SET_HISTOGRAM_DATA_PROP(*result, "rocksdb.db.seek.micros", rocksdb::Histograms::DB_SEEK);
SET_HISTOGRAM_DATA_PROP(*result, "rocksdb.db.flush.micros", rocksdb::Histograms::FLUSH_TIME);
SET_HISTOGRAM_DATA_PROP(*result, "rocksdb.db.write.stall", rocksdb::Histograms::WRITE_STALL);
SET_HISTOGRAM_DATA_PROP(*result, "rocksdb.blobdb.value.size", rocksdb::Histograms::BLOB_DB_VALUE_SIZE);
SET_HISTOGRAM_DATA_PROP(*result, "rocksdb.sst.read.micros", rocksdb::Histograms::SST_READ_MICROS);
SET_HISTOGRAM_DATA_PROP(*result, "rocksdb.compaction.times.micros", rocksdb::Histograms::COMPACTION_TIME);
}
#undef NAPI_STATUS_THROWS
#define NAPI_STATUS_THROWS(call) NAPI_STATUS_THROWS_RVAL(call, nullptr)
return true;
}
/**
* Adds the callback to a queue to be executed mutually exclusive and if the
* lock is available, executes it immediately followed by any newly queued
* callbacks. Called by `db.withLock()`.
*/
void DBDescriptor::lockCall(
napi_env env,
std::string& key,
napi_value callback,
napi_deferred deferred,
std::shared_ptr<DBHandle> owner
) {
bool isNewLock = false;
this->lockEnqueueCallback(
env, // env
key, // key
callback, // callback
owner, // owner
false, // skipEnqueueIfNewLock
deferred, // deferred
&isNewLock // [out] isNewLock
);
if (!isNewLock) {
DEBUG_LOG("%p DBDescriptor::lockCall callback queued for key:", this);
DEBUG_LOG_KEY_LN(key);
return;
}
// lock found
std::unique_lock<std::mutex> locksMutex(this->locksMutex);
auto lockHandle = this->locks.find(key);
if (lockHandle == this->locks.end()) {
DEBUG_LOG("%p DBDescriptor::lockCall no lock found for key:", this);
DEBUG_LOG_KEY_LN(key);
return;
}
auto& handle = lockHandle->second;
// try to acquire the "lock" atomically
bool expected = false;
if (!handle->isRunning.compare_exchange_strong(expected, true)) {
// another callback is already running
DEBUG_LOG("%p DBDescriptor::lockCall another callback is already running for key:", this);
DEBUG_LOG_KEY_LN(key);
return;
}
// we now "own" the execution for this key
if (handle->threadsafeCallbacks.empty()) {
handle->isRunning.store(false);
DEBUG_LOG("%p DBDescriptor::lockCall no callbacks left, removing lock for key:", this);
DEBUG_LOG_KEY_LN(key);
// remove the empty lock handle from the map
this->locks.erase(key);
return;
}
LockCallback lockCallback = handle->threadsafeCallbacks.front();
handle->threadsafeCallbacks.pop();
napi_threadsafe_function threadsafeCallback = lockCallback.callback;
// release the mutex before calling the callback to avoid holding locks
// during callback execution
locksMutex.unlock();
if (!threadsafeCallback) {
DEBUG_LOG("%p DBDescriptor::lockCall threadsafe lock callback is null for key:", this);
DEBUG_LOG_KEY_LN(key);