-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathnanots.cpp
More file actions
2431 lines (2066 loc) · 82.9 KB
/
nanots.cpp
File metadata and controls
2431 lines (2066 loc) · 82.9 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
/* NANOTS */
#include "nanots.h"
std::mutex current_stream_tags_lok;
std::set<std::string> current_stream_tags;
// ---------------------------------------------------------------------------
// Epoch-Based Reclamation registry implementation
// ---------------------------------------------------------------------------
namespace {
int64_t _now_us() {
using namespace std::chrono;
return duration_cast<microseconds>(
steady_clock::now().time_since_epoch())
.count();
}
// Path-keyed table of registries. Both writers and iterators look up here
// at construction time. weak_ptr means entries naturally evaporate when the
// last writer and iterator on a file are destroyed.
std::mutex g_registry_table_mu;
std::map<std::string, std::weak_ptr<nanots_epoch_registry>> g_registry_table;
} // namespace
nanots_epoch_registry::Slot& nanots_epoch_registry::slot(uint32_t id) {
// The slot's address is stable once allocated (unique_ptr in a vector).
// We still take the lock so concurrent grows are safe.
std::lock_guard<std::mutex> g(_slots_mu);
return *_slots[id];
}
uint32_t nanots_epoch_registry::acquire_slot() {
std::lock_guard<std::mutex> g(_slots_mu);
// First try to reuse an INACTIVE slot.
for (size_t i = 0; i < _slots.size(); ++i) {
if (_slots[i]->epoch.load(std::memory_order_relaxed) == INACTIVE) {
// Mark acquired with a temporary 0 epoch; caller will overwrite via
// op_begin().
_slots[i]->epoch.store(0, std::memory_order_relaxed);
return static_cast<uint32_t>(i);
}
}
// No free slot; grow.
_slots.emplace_back(std::make_unique<Slot>());
_slots.back()->epoch.store(0, std::memory_order_relaxed);
return static_cast<uint32_t>(_slots.size() - 1);
}
void nanots_epoch_registry::release_slot(uint32_t id) {
std::lock_guard<std::mutex> g(_slots_mu);
if (id < _slots.size()) {
_slots[id]->epoch.store(INACTIVE, std::memory_order_release);
}
}
bool nanots_epoch_registry::can_recycle(uint64_t retired_epoch,
int64_t now_us) const {
std::lock_guard<std::mutex> g(_slots_mu);
for (const auto& slot_ptr : _slots) {
uint64_t e = slot_ptr->epoch.load(std::memory_order_acquire);
if (e == INACTIVE) continue;
if (e > retired_epoch) continue;
// Slot is at-or-before the retire. Check liveness via heartbeat.
int64_t hb = slot_ptr->heartbeat_us.load(std::memory_order_relaxed);
if (now_us - hb > NANOTS_HEARTBEAT_TIMEOUT_US) continue; // dead, ignore
return false; // active reader still pinning this retire
}
return true;
}
std::shared_ptr<nanots_epoch_registry>
nanots_epoch_registry::get_or_create(const std::string& file_path) {
std::lock_guard<std::mutex> g(g_registry_table_mu);
auto it = g_registry_table.find(file_path);
if (it != g_registry_table.end()) {
if (auto sp = it->second.lock()) return sp;
// weak_ptr expired; fall through and create a new one.
}
auto sp = std::make_shared<nanots_epoch_registry>();
g_registry_table[file_path] = sp;
return sp;
}
// ---------------------------------------------------------------------------
// nanots_slot_guard
// ---------------------------------------------------------------------------
nanots_slot_guard::nanots_slot_guard(
std::shared_ptr<nanots_epoch_registry> registry)
: _registry(std::move(registry)) {
if (_registry) {
_slot_id = _registry->acquire_slot();
op_begin(); // publish initial epoch + heartbeat
}
}
nanots_slot_guard::~nanots_slot_guard() { _release(); }
nanots_slot_guard::nanots_slot_guard(nanots_slot_guard&& other) noexcept
: _registry(std::move(other._registry)), _slot_id(other._slot_id) {
other._slot_id = UINT32_MAX;
}
nanots_slot_guard& nanots_slot_guard::operator=(
nanots_slot_guard&& other) noexcept {
if (this != &other) {
_release();
_registry = std::move(other._registry);
_slot_id = other._slot_id;
other._slot_id = UINT32_MAX;
}
return *this;
}
void nanots_slot_guard::op_begin() {
if (_slot_id == UINT32_MAX) return;
auto& s = _registry->slot(_slot_id);
uint64_t e = _registry->global_epoch_load();
s.epoch.store(e, std::memory_order_release);
s.heartbeat_us.store(_now_us(), std::memory_order_relaxed);
}
void nanots_slot_guard::_release() noexcept {
if (_slot_id != UINT32_MAX && _registry) {
_registry->release_slot(_slot_id);
_slot_id = UINT32_MAX;
}
_registry.reset();
}
// ---------------------------------------------------------------------------
static uint32_t _round_to_64k_boundary(uint32_t requested_size) {
const uint32_t BOUNDARY = 65536; // 64KB
if (requested_size == 0)
return BOUNDARY; // Minimum size is 64KB
// Round up to next multiple of 65536
return ((requested_size + BOUNDARY - 1) / BOUNDARY) * BOUNDARY;
}
static bool _validate_frame_header(const uint8_t* frame_p,
const uint8_t* expected_uuid,
uint32_t* flags_out,
uint32_t* size_out,
int64_t* sec_key_out) {
if (memcmp(frame_p + FRAME_UUID_OFFSET, expected_uuid, 16) != 0)
return false;
if (sec_key_out)
*sec_key_out = *(int64_t*)(frame_p + FRAME_SECKEY_OFFSET);
if (size_out)
*size_out = *(uint32_t*)(frame_p + FRAME_SIZE_OFFSET);
if (flags_out)
*flags_out = *(uint32_t*)(frame_p + FRAME_FLAGS_OFFSET);
return true;
}
static std::string _database_name(const std::string& file_name) {
return file_name.substr(0, file_name.find(".nts")) + ".db";
}
static void _free_block(nts_sqlite_conn& conn, int sb_id, int block_id) {
nts_sqlite_transaction(conn, true, [&](const nts_sqlite_conn& conn) {
auto stmt = conn.prepare("DELETE FROM segment_blocks WHERE id = ?");
stmt.bind(1, sb_id).exec_no_result();
stmt = conn.prepare("UPDATE blocks SET status = 'free' WHERE id = ?");
stmt.bind(1, block_id).exec_no_result();
});
}
static bool _is_valid_frame_at_index(uint8_t* block_p, uint32_t block_size,
int index, uint32_t n_valid_indexes,
const uint8_t* uuid) {
uint8_t* index_p = block_p + BLOCK_HEADER_SIZE + (index * INDEX_ENTRY_SIZE);
int64_t timestamp = *(int64_t*)(index_p + INDEX_ENTRY_TS_OFFSET);
uint64_t offset = *(uint64_t*)(index_p + INDEX_ENTRY_OFFSET_OFFSET);
// Skip zeroed entries
if (timestamp == 0 || offset == 0) {
return false;
}
// Check frame offset bounds
uint32_t index_region_end = BLOCK_HEADER_SIZE + ((n_valid_indexes + 1) * INDEX_ENTRY_SIZE);
if (offset < index_region_end || offset > block_size - FRAME_HEADER_SIZE) {
return false;
}
// Validate frame header
uint32_t frame_size = 0;
if (!_validate_frame_header(block_p + offset, uuid, nullptr, &frame_size, nullptr)) {
return false;
}
// Check if frame size fits within block
if (frame_size > block_size - offset - FRAME_HEADER_SIZE) {
return false;
}
return true;
}
static void _validate_blocks(const std::string& file_name) {
auto f = nts_file::open(file_name, "r+");
if (!f)
throw nanots_exception(NANOTS_EC_CANT_OPEN, "Unable to open file.", __FILE__, __LINE__);
uint32_t block_size = 0;
{
nts_memory_map mm(
filenum(f), 0, FILE_HEADER_BLOCK_SIZE,
nts_memory_map::NMM_PROT_READ | nts_memory_map::NMM_PROT_WRITE,
nts_memory_map::NMM_TYPE_FILE | nts_memory_map::NMM_SHARED);
uint8_t* hp = (uint8_t*)mm.map();
if (memcmp(hp + FILE_HEADER_MAGIC_OFFSET, NANOTS_FILE_MAGIC, NANOTS_FILE_MAGIC_LEN) != 0)
throw nanots_exception(NANOTS_EC_BAD_MAGIC, "Not a nanots v2 file (bad magic).", __FILE__, __LINE__);
uint16_t version = *(uint16_t*)(hp + FILE_HEADER_VERSION_OFFSET);
if (version != NANOTS_FORMAT_VERSION)
throw nanots_exception(NANOTS_EC_BAD_VERSION, "Unsupported nanots format version.", __FILE__, __LINE__);
block_size = *(uint32_t*)(hp + FILE_HEADER_BLOCK_SIZE_OFFSET);
}
auto db_name = _database_name(file_name);
nts_sqlite_conn conn(db_name, true, true);
std::vector<std::map<std::string, std::optional<std::string>>> rowsToProcess;
bool doneValidating = false;
while(!doneValidating) {
if(rowsToProcess.empty()) {
rowsToProcess = conn.exec(
"SELECT sb.id, sb.block_idx, sb.block_id, sb.uuid, s.stream_tag "
"FROM segment_blocks sb "
"JOIN segments s ON sb.segment_id = s.id "
"WHERE sb.end_timestamp = 0");
if(rowsToProcess.empty()) {
doneValidating = true;
continue;
}
} else {
auto row = rowsToProcess.back();
rowsToProcess.pop_back();
int sb_id = std::stoi(row["id"].value());
int block_id = std::stoi(row["block_id"].value());
int block_idx = std::stoi(row["block_idx"].value());
std::string uuid_hex = row["uuid"].value();
uint8_t uuid[16];
s_to_entropy_id(uuid_hex, uuid);
nts_memory_map mm(
filenum(f), FILE_HEADER_BLOCK_SIZE + (block_idx * block_size),
block_size,
nts_memory_map::NMM_PROT_READ | nts_memory_map::NMM_PROT_WRITE,
nts_memory_map::NMM_TYPE_FILE | nts_memory_map::NMM_SHARED);
uint8_t* block_p = (uint8_t*)mm.map();
auto valid_counter = (uint32_t*)(block_p + 8);
#ifdef _WIN32
uint32_t n_valid_indexes = *reinterpret_cast<volatile uint32_t*>(valid_counter);
_ReadWriteBarrier(); // compiler barrier (not mem)
#else
uint32_t n_valid_indexes = __atomic_load_n(valid_counter, std::memory_order_acquire);
#endif
if((n_valid_indexes * INDEX_ENTRY_SIZE) >= (block_size / 2) || n_valid_indexes == 0) {
_free_block(conn, sb_id, block_id);
rowsToProcess.clear();
continue;
}
// Find the last valid frame by searching backwards from the end
int last_valid = -1;
for (int i = n_valid_indexes - 1; i >= 0; i--) {
if (_is_valid_frame_at_index(block_p, block_size, i, n_valid_indexes, uuid)) {
last_valid = i;
break;
}
}
if(last_valid < 0) {
_free_block(conn, sb_id, block_id);
rowsToProcess.clear();
continue;
} else {
// Truncating corrupt block
*(uint32_t*)(block_p + 8) = last_valid + 1;
mm.flush(mm.map(), block_size, true);
nts_sqlite_transaction(conn, true, [&](const nts_sqlite_conn& conn) {
uint8_t* last_index_p =
block_p + BLOCK_HEADER_SIZE + (last_valid * INDEX_ENTRY_SIZE);
int64_t actual_last_timestamp = *(int64_t*)(last_index_p + INDEX_ENTRY_TS_OFFSET);
int64_t actual_last_sk = *(int64_t*)(last_index_p + INDEX_ENTRY_SECKEY_OFFSET);
auto stmt = conn.prepare(
"UPDATE segment_blocks SET end_timestamp = ?, end_secondary_key = ? "
"WHERE block_idx = ? AND uuid = ?");
stmt.bind(1, actual_last_timestamp)
.bind(2, actual_last_sk)
.bind(3, block_idx)
.bind(4, uuid_hex)
.exec_no_result();
});
}
}
}
}
static int _get_db_version(const nts_sqlite_conn& conn) {
auto result = conn.exec("PRAGMA user_version;");
if (result.empty())
throw nanots_exception(NANOTS_EC_SCHEMA, "Unable to query database version.", __FILE__, __LINE__);
auto row = result.front();
return std::stoi(row.begin()->second.value());
}
static void _set_db_version(const nts_sqlite_conn& conn, int version) {
conn.exec("PRAGMA user_version=" + std::to_string(version) + ";");
}
static void _upgrade_db(const nts_sqlite_conn& conn) {
auto current_version = _get_db_version(conn);
// v2-only build: any pre-v2 database is rejected. (Fresh DBs created by
// allocate() are stamped to version 2 below.)
if (current_version != 0 && current_version < 2) {
throw nanots_exception(NANOTS_EC_BAD_VERSION,
"Legacy nanots catalog (pre-v2) is not supported.",
__FILE__, __LINE__);
}
switch (current_version) {
case 0: {
nts_sqlite_transaction(
conn, true, [&](const nts_sqlite_conn& conn) { _set_db_version(conn, 2); });
}
[[fallthrough]];
default:
break;
};
}
static std::optional<block> _db_reclaim_oldest_used_block(
const nts_sqlite_conn& conn) {
// Find oldest finalized segment_block (end_timestamp != 0)
auto result = conn.exec(
"SELECT sb.block_id, b.idx, sb.id as segment_block_id, b.status "
"FROM segment_blocks sb "
"JOIN blocks b ON sb.block_id = b.id "
"WHERE sb.end_timestamp != 0 AND (b.status = 'used' OR b.status = 'reserved') "
"ORDER BY sb.end_timestamp ASC, b.reserved_at ASC "
"LIMIT 1");
if (result.empty())
return std::nullopt;
auto row = result.front();
int64_t block_id = std::stoll(row["block_id"].value());
int64_t segment_block_id = std::stoll(row["segment_block_id"].value());
// Delete the segment_block entry (trigger will clean up empty segments)
auto stmt = conn.prepare("DELETE FROM segment_blocks WHERE id = ?");
stmt.bind(1, segment_block_id).exec_no_result();
// Mark block as reserved
stmt = conn.prepare(
"UPDATE blocks SET status = 'reserved', reserved_at = CURRENT_TIMESTAMP "
"WHERE id = ?");
stmt.bind(1, block_id).exec_no_result();
return block{block_id, std::stoll(row["idx"].value())};
}
static std::optional<block> _db_get_free_block(const nts_sqlite_conn& conn) {
auto result =
conn.exec("SELECT id, idx FROM blocks WHERE status = 'free' LIMIT 1;");
if (result.empty())
return std::nullopt;
auto row = result.front();
int64_t block_id = std::stoll(row["id"].value());
auto stmt =
conn.prepare("UPDATE blocks SET status = 'reserved' WHERE id = ?");
stmt.bind(1, block_id).exec_no_result();
return block{block_id, std::stoll(row["idx"].value())};
}
// (Block acquisition logic moved to nanots_writer::_acquire_writable_block,
// which composes _db_get_free_block / _grow_blocks / _db_reclaim_oldest_used_block
// with the EBR limbo/ready machinery.)
static std::optional<segment> _db_create_segment(const nts_sqlite_conn& conn,
const std::string& stream_tag,
const std::string& metadata) {
auto stmt = conn.prepare(
"INSERT INTO segments (stream_tag, metadata) VALUES (?, ?)");
stmt.bind(1, stream_tag).bind(2, metadata).exec_no_result();
segment s;
s.id = std::stoll(conn.last_insert_id());
s.stream_tag = stream_tag;
s.metadata = metadata;
s.sequence = 0;
return s;
}
static std::optional<segment_block> _db_create_segment_block(
const nts_sqlite_conn& conn,
int64_t segment_id,
int64_t sequence,
int64_t block_id,
int64_t block_idx,
int64_t start_timestamp,
int64_t end_timestamp,
int64_t start_secondary_key,
int64_t end_secondary_key,
const uint8_t* uuid) {
auto stmt = conn.prepare(
"INSERT INTO segment_blocks ("
"segment_id, "
"sequence, "
"block_id, "
"block_idx, "
"start_timestamp, "
"end_timestamp, "
"start_secondary_key, "
"end_secondary_key, "
"uuid"
") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
auto hex_uuid = entropy_id_to_s(uuid);
stmt.bind(1, segment_id)
.bind(2, sequence)
.bind(3, block_id)
.bind(4, block_idx)
.bind(5, start_timestamp)
.bind(6, end_timestamp)
.bind(7, start_secondary_key)
.bind(8, end_secondary_key)
.bind(9, hex_uuid)
.exec_no_result();
struct segment_block sb;
sb.id = std::stoll(conn.last_insert_id());
sb.segment_id = segment_id;
sb.sequence = sequence;
sb.block_id = block_id;
sb.block_idx = block_idx;
sb.start_timestamp = start_timestamp;
sb.end_timestamp = end_timestamp;
sb.start_secondary_key = start_secondary_key;
sb.end_secondary_key = end_secondary_key;
memcpy(sb.uuid, uuid, 16);
return sb;
}
static void _db_finalize_block(const nts_sqlite_conn& conn,
int64_t segment_block_id,
int64_t timestamp,
int64_t secondary_key) {
auto stmt = conn.prepare(
"UPDATE segment_blocks SET end_timestamp = ?, end_secondary_key = ? "
"WHERE id = ?");
stmt.bind(1, timestamp)
.bind(2, secondary_key)
.bind(3, segment_block_id)
.exec_no_result();
}
static void _db_trans_finalize_reserved_blocks(const nts_sqlite_conn& conn) {
// Set status to 'used' for all blocks whose status is 'reserved' and
// reserved_at is older than 10 seconds.
auto query =
"UPDATE blocks SET status = 'used' WHERE status = 'reserved' AND "
"reserved_at < datetime('now', '-10 seconds');";
conn.exec(query);
}
static void _recycle_block(write_context& wctx, int64_t timestamp) {
uint8_t* p = (uint8_t*)wctx.mm.map();
// write the new timestamp
*(int64_t*)p = timestamp;
p += sizeof(int64_t);
uint32_t old_n_valid_indexes = *(uint32_t*)p;
// zero out the n_valid_indexes
auto valid_counter = (uint32_t*)p;
#ifdef _WIN32
std::atomic_thread_fence(std::memory_order_release);
*reinterpret_cast<volatile uint32_t*>(valid_counter) = 0;
#else
__atomic_store_n(valid_counter, 0, std::memory_order_release);
#endif
p += sizeof(uint32_t);
// zero out the reserved field
*(uint32_t*)p = 0;
p += sizeof(uint32_t);
memset(p, 0, INDEX_ENTRY_SIZE * old_n_valid_indexes);
// IMPORTANT: Sync immediately to ensure zeros are on disk
// This prevents seeing old index entries after a crash
wctx.mm.flush(wctx.mm.map(),
BLOCK_HEADER_SIZE + (INDEX_ENTRY_SIZE * old_n_valid_indexes),
true);
}
write_context::~write_context() {
std::lock_guard<std::mutex> g(current_stream_tags_lok);
std::string key = file_name + ":" + stream_tag;
current_stream_tags.erase(key);
if (last_timestamp && current_block) {
mm.flush(mm.map(), _block_size, true);
auto db_name = _database_name(file_name);
nts_sqlite_conn conn(db_name, true, true);
int64_t end_sk = last_secondary_key.value_or(NANOTS_SEC_KEY_UNSET);
nts_sqlite_transaction(conn, true, [&](const nts_sqlite_conn& conn) {
_db_finalize_block(conn, current_block->id, last_timestamp.value(), end_sk);
// This is a maintenance task that needs to be done periodically.
_db_trans_finalize_reserved_blocks(conn);
});
}
}
nanots_writer::nanots_writer(const std::string& file_name, bool auto_reclaim)
: _file_name(file_name),
_file_size(file_size(file_name)),
_file(nts_file::open(file_name, "r+")),
_file_header_mm(
filenum(_file),
0,
FILE_HEADER_BLOCK_SIZE,
nts_memory_map::NMM_PROT_READ | nts_memory_map::NMM_PROT_WRITE,
nts_memory_map::NMM_TYPE_FILE | nts_memory_map::NMM_SHARED),
_file_header_p((uint8_t*)_file_header_mm.map()),
_block_size(*(uint32_t*)(_file_header_p + FILE_HEADER_BLOCK_SIZE_OFFSET)),
_n_blocks(*(uint32_t*)(_file_header_p + FILE_HEADER_N_BLOCKS_OFFSET)),
_max_blocks(*(uint32_t*)(_file_header_p + FILE_HEADER_MAX_BLOCKS_OFFSET)),
_auto_reclaim(auto_reclaim),
_epoch(nanots_epoch_registry::get_or_create(file_name)) {
// Validate v2 magic + version up front. Legacy v1 files (which had
// block_size at offset 0) are rejected by design.
if (memcmp(_file_header_p + FILE_HEADER_MAGIC_OFFSET,
NANOTS_FILE_MAGIC, NANOTS_FILE_MAGIC_LEN) != 0)
throw nanots_exception(NANOTS_EC_BAD_MAGIC,
"Not a nanots v2 file (bad magic). Legacy v1 files are not supported.",
__FILE__, __LINE__);
uint16_t version = *(uint16_t*)(_file_header_p + FILE_HEADER_VERSION_OFFSET);
if (version != NANOTS_FORMAT_VERSION)
throw nanots_exception(NANOTS_EC_BAD_VERSION,
"Unsupported nanots format version.",
__FILE__, __LINE__);
if (_block_size < 4096 || _block_size > 1024 * 1024 * 1024)
throw nanots_exception(NANOTS_EC_INVALID_BLOCK_SIZE, "Invalid block size in file header.", __FILE__, __LINE__);
auto db_name = _database_name(_file_name);
nts_sqlite_conn db(db_name, true, true);
_upgrade_db(db);
_validate_blocks(_file_name);
}
std::optional<block> nanots_writer::_grow_blocks(const nts_sqlite_conn& conn) {
// Current physical block count comes from sqlite (authoritative).
auto count_rows = conn.exec("SELECT COUNT(*) AS c FROM blocks;");
int64_t current_count = std::stoll(count_rows.front()["c"].value());
// Honor the cap.
if (_max_blocks > 0 && current_count >= _max_blocks)
return std::nullopt;
// BoltDB-style: double the current count, capped at 1 GiB per grow.
// First-ever grow allocates exactly 1 block.
const int64_t cap_bytes = 1024LL * 1024LL * 1024LL;
int64_t cap_blocks = std::max<int64_t>(1, cap_bytes / _block_size);
int64_t to_add = (current_count == 0)
? 1
: std::min<int64_t>(current_count, cap_blocks);
// Don't exceed _max_blocks if one is set.
if (_max_blocks > 0)
to_add = std::min<int64_t>(to_add, int64_t(_max_blocks) - current_count);
if (to_add <= 0)
return std::nullopt;
// Extend the file. fallocate is idempotent on size — if a previous grow
// partially succeeded (file extended but sqlite rolled back), we just
// re-extend to the same or larger size, no harm done.
uint64_t new_size = FILE_HEADER_BLOCK_SIZE +
static_cast<uint64_t>(current_count + to_add) * _block_size;
if (fallocate(_file, new_size) < 0)
throw nanots_exception(NANOTS_EC_UNABLE_TO_ALLOCATE_FILE,
"Unable to grow file.", __FILE__, __LINE__);
_file_size = new_size;
// Insert new block rows. First one is 'reserved' (the caller's slot);
// the rest are 'free' for future writes.
auto stmt = conn.prepare("INSERT INTO blocks (idx, status) VALUES (?, ?)");
int64_t first_new_idx = current_count;
for (int64_t i = 0; i < to_add; i++) {
int64_t idx = current_count + i;
stmt.reset();
stmt.bind(1, idx).bind(2, std::string(i == 0 ? "reserved" : "free")).exec_no_result();
}
int64_t first_new_id = std::stoll(conn.last_insert_id()) - (to_add - 1);
return block{first_new_id, first_new_idx};
}
write_context nanots_writer::create_write_context(const std::string& stream_tag,
const std::string& metadata) {
std::string key = _file_name + ":" + stream_tag;
std::lock_guard<std::mutex> g(current_stream_tags_lok);
if(current_stream_tags.find(key) != current_stream_tags.end())
throw nanots_exception(NANOTS_EC_DUPLICATE_STREAM_TAG, "Only one current writer per active stream tag.", __FILE__, __LINE__);
write_context wctx;
wctx.metadata = metadata;
wctx.stream_tag = stream_tag;
wctx.file_name = _file_name;
wctx._block_size = _block_size;
// Segment creation is deferred to the first write(): only then do we know
// whether the caller intends this stream to carry a secondary key, which
// is recorded permanently on the segments row.
current_stream_tags.insert(key);
return wctx;
}
void nanots_writer::_scan_limbo() {
int64_t now = _now_us();
std::lock_guard<std::mutex> g(_limbo_mu);
// Front-of-deque ordering by retired_epoch is monotonic (every retire
// bumps global_epoch), so once the front is blocked, everything behind
// it is too.
while (!_limbo.empty()) {
const auto& front = _limbo.front();
if (!_epoch->can_recycle(front.retired_epoch, now)) break;
_ready.push_back(front);
_limbo.pop_front();
}
}
block nanots_writer::_acquire_writable_block(const nts_sqlite_conn& conn) {
// 1. Try the ready queue (limbo entries that have already cleared EBR).
{
std::lock_guard<std::mutex> g(_limbo_mu);
if (!_ready.empty()) {
auto e = _ready.front();
_ready.pop_front();
return block{e.block_id, e.block_idx};
}
}
// 2. Try a truly free block.
if (auto b = _db_get_free_block(conn)) {
return *b;
}
// 3. Growable: extend the file.
if (is_growable()) {
if (auto b = _grow_blocks(conn)) {
return *b;
}
}
// 4. Auto-reclaim: retire blocks into limbo and consume from ready.
if (_auto_reclaim) {
constexpr int MAX_RETRIES = 100;
for (int attempt = 0; attempt < MAX_RETRIES; ++attempt) {
// Cap check before retiring.
{
std::lock_guard<std::mutex> g(_limbo_mu);
if (_limbo.size() >= LIMBO_MAX_ENTRIES) {
throw nanots_exception(
NANOTS_EC_NO_FREE_BLOCKS,
"EBR limbo cap exceeded; pinned readers blocking reclaim.",
__FILE__, __LINE__);
}
}
// Retire one block (SQL: delete its segment_block, mark reserved).
auto victim = _db_reclaim_oldest_used_block(conn);
if (!victim) {
// Nothing finalized to retire (either no blocks at all, or every
// remaining block is still being actively written). Fall through
// to the throw below.
break;
}
uint64_t retired_epoch = _epoch->global_epoch_bump();
{
std::lock_guard<std::mutex> g(_limbo_mu);
_limbo.push_back({victim->id, victim->idx, retired_epoch});
}
// Try to migrate cleared entries to ready and consume one.
_scan_limbo();
{
std::lock_guard<std::mutex> g(_limbo_mu);
if (!_ready.empty()) {
auto e = _ready.front();
_ready.pop_front();
return block{e.block_id, e.block_idx};
}
}
// No ready block yet — readers haven't advanced their epochs. Yield
// briefly and retry.
std::this_thread::yield();
}
}
throw nanots_exception(NANOTS_EC_NO_FREE_BLOCKS, "Unable to get free block.",
__FILE__, __LINE__);
}
void nanots_writer::write(write_context& wctx,
const uint8_t* data,
size_t size,
uint32_t flags,
int64_t timestamp,
int64_t secondary_key) {
// Composite (timestamp, secondary_key) must be strictly greater than the
// previous frame's composite. When the caller doesn't pass a sec_key, the
// default is NANOTS_SEC_KEY_UNSET (= INT64_MIN); for a stream that never
// passes one this degenerates to "timestamp must strictly increase."
if (wctx.last_timestamp) {
int64_t last_ts = wctx.last_timestamp.value();
int64_t last_sk = wctx.last_secondary_key.value_or(NANOTS_SEC_KEY_UNSET);
bool composite_greater =
(timestamp > last_ts) ||
(timestamp == last_ts && secondary_key > last_sk);
if (!composite_greater) {
throw nanots_exception(
NANOTS_EC_NON_MONOTONIC_TIMESTAMP,
"Composite (timestamp, secondary_key) is not strictly greater than "
"the previous frame's composite.",
__FILE__, __LINE__);
}
}
if (size >
_block_size - (FRAME_HEADER_SIZE + INDEX_ENTRY_SIZE + BLOCK_HEADER_SIZE))
throw nanots_exception(NANOTS_EC_ROW_SIZE_TOO_BIG, "Frame size is too large. Use a much larger block size.", __FILE__, __LINE__);
// First write to this context: lazily create the segment row.
if (!wctx.current_segment) {
nts_sqlite_conn conn(_database_name(_file_name), true, true);
nts_sqlite_transaction(conn, true, [&](const nts_sqlite_conn& conn) {
wctx.current_segment = _db_create_segment(
conn, wctx.stream_tag, wctx.metadata);
if (!wctx.current_segment)
throw nanots_exception(NANOTS_EC_UNABLE_TO_CREATE_SEGMENT, "Unable to create segment.", __FILE__, __LINE__);
});
}
if (!wctx.current_block) {
nts_sqlite_conn conn(_database_name(_file_name), true, true);
// Acquire a physical block under EBR. The returned block is always safe
// to overwrite: it is either a freshly-free block, a newly-grown block,
// or a retired block that has cleared EBR safety. Block acquisition
// happens outside the transaction below because retiring may need
// multiple sub-transactions and yields while waiting on readers.
block phys = _acquire_writable_block(conn);
nts_sqlite_transaction(conn, true, [&](const nts_sqlite_conn& conn) {
uint8_t uuid[16];
generate_entropy_id(uuid);
wctx.current_block = _db_create_segment_block(
conn, wctx.current_segment->id, wctx.current_segment->sequence,
phys.id, phys.idx, timestamp, 0, secondary_key, 0, uuid);
if (!wctx.current_block)
throw nanots_exception(NANOTS_EC_UNABLE_TO_CREATE_SEGMENT_BLOCK, "Unable to create segment block.", __FILE__, __LINE__);
wctx.current_segment->sequence++;
});
wctx.file = nts_file::open(_file_name, "r+");
wctx.mm = nts_memory_map(
filenum(wctx.file),
FILE_HEADER_BLOCK_SIZE + (wctx.current_block->block_idx * _block_size),
_block_size,
nts_memory_map::NMM_PROT_READ | nts_memory_map::NMM_PROT_WRITE,
nts_memory_map::NMM_TYPE_FILE | nts_memory_map::NMM_SHARED);
_recycle_block(wctx, timestamp);
}
uint8_t* block_p = (uint8_t*)wctx.mm.map();
uint32_t n_valid_indexes = *(uint32_t*)(block_p + 8);
uint64_t index_end =
BLOCK_HEADER_SIZE + ((n_valid_indexes + 1) * INDEX_ENTRY_SIZE);
// Calculate padded frame size for 8-byte alignment (required for ARM compatibility)
uint32_t total_frame_size = (uint32_t)(FRAME_HEADER_SIZE + size);
uint32_t padded_frame_size = (total_frame_size + 7) & ~7; // Round up to multiple of 8
uint64_t new_block_ofs = (uint64_t)(_block_size - padded_frame_size);
if (n_valid_indexes > 0) {
uint8_t* last_index_p = block_p + BLOCK_HEADER_SIZE +
((n_valid_indexes - 1) * INDEX_ENTRY_SIZE);
uint64_t last_frame_offset = *(uint64_t*)(last_index_p + INDEX_ENTRY_OFFSET_OFFSET);
if (last_frame_offset >= padded_frame_size) {
uint64_t candidate_ofs = last_frame_offset - padded_frame_size;
new_block_ofs = (candidate_ofs >= index_end) ? candidate_ofs : index_end;
} else {
new_block_ofs = index_end; // Force rollover to new block
}
}
if (index_end >= new_block_ofs) {
nts_sqlite_conn conn(_database_name(_file_name), true, true);
wctx.mm.flush(wctx.mm.map(), _block_size, true);
int64_t end_sk = wctx.last_secondary_key.value_or(NANOTS_SEC_KEY_UNSET);
nts_sqlite_transaction(conn, true, [&](const nts_sqlite_conn& conn) {
_db_finalize_block(conn, wctx.current_block->id,
wctx.last_timestamp.value(), end_sk);
});
wctx.current_block = std::nullopt;
wctx.mm = nts_memory_map();
return write(wctx, data, size, flags, timestamp, secondary_key);
}
uint8_t* frame_p = block_p + new_block_ofs;
memcpy(frame_p + FRAME_UUID_OFFSET, wctx.current_block->uuid, 16);
*(int64_t*)(frame_p + FRAME_SECKEY_OFFSET) = secondary_key;
*(uint32_t*)(frame_p + FRAME_SIZE_OFFSET) = (uint32_t)size;
*(uint32_t*)(frame_p + FRAME_FLAGS_OFFSET) = flags;
memcpy(frame_p + FRAME_HEADER_SIZE, data, size);
uint8_t* index_p =
block_p + BLOCK_HEADER_SIZE + (n_valid_indexes * INDEX_ENTRY_SIZE);
*(int64_t*)(index_p + INDEX_ENTRY_TS_OFFSET) = timestamp;
*(int64_t*)(index_p + INDEX_ENTRY_SECKEY_OFFSET) = secondary_key;
*(uint64_t*)(index_p + INDEX_ENTRY_OFFSET_OFFSET) = new_block_ofs;
*(uint64_t*)(index_p + INDEX_ENTRY_RESERVED_OFFSET) = 0;
auto valid_counter = (uint32_t*)(block_p + 8);
#ifdef _WIN32
_InterlockedIncrement(reinterpret_cast<volatile long*>(valid_counter));
#else
__atomic_fetch_add(valid_counter, 1, std::memory_order_release);
#endif
wctx.last_timestamp = timestamp;
// Track the secondary key unconditionally so the composite monotonicity
// check on the next write has the right "last" value (including UNSET).
wctx.last_secondary_key = secondary_key;
}
void nanots_writer::free_blocks(const std::string& file_name,
const std::string& stream_tag,
int64_t start_timestamp,
int64_t start_secondary_key,
int64_t end_timestamp,
int64_t end_secondary_key) {
auto db_name = _database_name(file_name);
nts_sqlite_conn conn(db_name, true, true);
nts_sqlite_transaction(conn, true, [&](const nts_sqlite_conn& conn) {
// Find blocks fully contained in the composite window
// [(start_ts, start_sk), (end_ts, end_sk)]:
// block_start >= window_start:
// start_ts > ? OR (start_ts = ? AND start_sk >= ?)
// block_end <= window_end:
// end_ts < ? OR (end_ts = ? AND end_sk <= ?)
// Plus end_timestamp != 0 to skip the currently-open block.
auto stmt = conn.prepare(
"SELECT sb.id as segment_block_id, sb.block_id "
"FROM segment_blocks sb "
"JOIN segments s ON sb.segment_id = s.id "
"WHERE s.stream_tag = ? "
"AND (sb.start_timestamp > ? OR "
" (sb.start_timestamp = ? AND sb.start_secondary_key >= ?)) "
"AND (sb.end_timestamp < ? OR "
" (sb.end_timestamp = ? AND sb.end_secondary_key <= ?)) "
"AND sb.end_timestamp != 0");
auto blocks_to_delete =
stmt.bind(1, stream_tag)
.bind(2, start_timestamp).bind(3, start_timestamp).bind(4, start_secondary_key)
.bind(5, end_timestamp).bind(6, end_timestamp).bind(7, end_secondary_key)
.exec();
for (auto& block_row : blocks_to_delete) {
int64_t segment_block_id = std::stoll(block_row["segment_block_id"].value());
int64_t block_id = std::stoll(block_row["block_id"].value());
// Remove segment_block entry (trigger will clean up empty segments)
stmt = conn.prepare("DELETE FROM segment_blocks WHERE id = ?");
stmt.bind(1, segment_block_id).exec_no_result();
// Mark block as free
stmt = conn.prepare("UPDATE blocks SET status = 'free' WHERE id = ?");
stmt.bind(1, block_id).exec_no_result();
}
});
}
void nanots_writer::allocate_growable(const std::string& file_name,
uint32_t block_size,
uint32_t max_blocks) {
// Growable mode is signalled by n_blocks == 0 in the file header.
allocate(file_name, block_size, 0);
if (max_blocks > 0) {
auto f = nts_file::open(file_name, "r+");
nts_memory_map mm(
filenum(f), 0, 4096,
nts_memory_map::NMM_PROT_READ | nts_memory_map::NMM_PROT_WRITE,
nts_memory_map::NMM_TYPE_FILE | nts_memory_map::NMM_SHARED);
uint8_t* p = (uint8_t*)mm.map();
*(uint32_t*)(p + FILE_HEADER_MAX_BLOCKS_OFFSET) = max_blocks;
mm.flush(mm.map(), FILE_HEADER_USED_BYTES);
}
}
void nanots_writer::allocate(const std::string& file_name,
uint32_t block_size,
uint32_t n_blocks) {
// Windows MapViewOfFile() requires mapped regions to start and end on 64k
// boundaires. Our file header size is 65536, SO if the block size is a
// multiple of 65536 then block start and end on 64k boundaries.
block_size = _round_to_64k_boundary(block_size);
// n_blocks == 0 ⇒ growable mode: file starts at just the header and grows
// on demand. Otherwise pre-allocate the full file up front.
uint64_t file_size = FILE_HEADER_BLOCK_SIZE + static_cast<uint64_t>(n_blocks) * block_size;
{
auto f = nts_file::open(file_name, "w+");
if (fallocate(f, file_size) < 0)
throw nanots_exception(NANOTS_EC_UNABLE_TO_ALLOCATE_FILE, "Unable to allocate file.", __FILE__, __LINE__);
}
{
auto f = nts_file::open(file_name, "r+");
nts_memory_map mm(
filenum(f), 0, 4096,