Repository navigation
Expand file tree
/
Copy pathdatabase.go
More file actions
executable file
·4135 lines (3948 loc) · 116 KB
/
Copy pathdatabase.go
File metadata and controls
executable file
·4135 lines (3948 loc) · 116 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
// database.go
package main
import (
"bytes"
"container/heap"
"container/list"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
)
type Database struct {
name string
path string
highestKey atomic.Uint64
nextPairTableID atomic.Uint32 // Contatore per i nuovi ID delle tabelle pair
// Fondo dell'ultima prenotazione di ID scritta su disco (getNewPairTableID).
pairTableIDReserved atomic.Uint32
pairTableReserveMu sync.Mutex
mainKeys *MainKeysTable
keyRecycle *RecycleTable // Righe di main_keys liberate da DELETE, riusate dal prossimo INSERT
keyFormat keyFormat
shardedKeys *shardedKeyStore
valuesTables sync.Map
recycleTables sync.Map
pairTables sync.Map // Cache per i nodi della TreeTable, ora indicizzata da uint32
fileManager *FileManager
pairTableCache *pairTableCache
payloadCache *payloadCache
mu sync.Mutex
pairMutationMu sync.Mutex // Serializza insert/delete sul trie dei pair, vedi setPairValue/deletePairValue
pairDir string // Path alla cartella /pairs
nextPairIDPath string // Path al file che memorizza il contatore
jumpDataPath string
jumpIndexPath string
jumpMu sync.Mutex
resources *ResourceMonitor
settingsMu sync.RWMutex
settings DatabaseConfig
settingsPersist func(DatabaseOverrides) error
branchCodec pairBranchCodec
adaptivePairs bool // adaptive per-node LIST/DENSE container enabled
pairListMaxBytes int // LIST densify byte budget
pairListMaxFillPct int // optional extra densify cap (% of capacity, 0 = off)
jumpDir string
nextJumpIDPath string
nextJumpID atomic.Uint32
// jumpIDReserved è il fondo dell'ultima prenotazione scritta su disco: gli
// ID sotto di esso si consegnano senza toccare il filesystem (jump_store.go).
jumpIDReserved atomic.Uint32
jumpReserveMu sync.Mutex
jumpDataFile *os.File // handle persistente, aperto una volta sola
jumpIndexFile *os.File
jumpDataEnd int64 // coda del file append-only, tenuta in memoria
jumpNodes *jumpCache
jumpStoreReady bool
jumpLegacyFiles bool // la cartella conteneva jump nel vecchio formato a file singolo
forkScheduler *ForkScheduler
predictStore *PredictionManager
recordStore *RecordManager
graphCache *graphCacheStore
graphTermMu sync.Mutex // Serializza contatori/grammi derivati dell'indice lessicale.
protocolProfiles *numericProfileStore
clusterMessenger *ClusterMessenger
jobs *microJobManager
reducers *ReducerRegistry
// closeOnce rende Close idempotente: spegnimento per segnale, EXIT dalla
// CLI e Engine.Close possono arrivare tutti sullo stesso database.
closeOnce sync.Once
closeErr error
}
type pairTableCache struct {
limit int
lru *list.List
mu sync.Mutex
entries map[uint32]*list.Element
}
type pairTableCacheEntry struct {
id uint32
table *PairTable
}
func newPairTableCache(limit int) *pairTableCache {
if limit <= 0 {
return nil
}
return &pairTableCache{
limit: limit,
lru: list.New(),
entries: make(map[uint32]*list.Element),
}
}
func (c *pairTableCache) OnPairTableOpen(table *PairTable) {
if c == nil || table == nil {
return
}
var victims []*PairTable
c.mu.Lock()
if elem, ok := c.entries[table.id]; ok {
c.lru.MoveToBack(elem)
} else {
elem = c.lru.PushBack(pairTableCacheEntry{id: table.id, table: table})
c.entries[table.id] = elem
}
victims = c.collectEvictionsLocked()
c.mu.Unlock()
for _, victim := range victims {
victim.ReleaseFile()
}
}
func (c *pairTableCache) OnPairTableClose(table *PairTable) {
if c == nil || table == nil {
return
}
c.mu.Lock()
if elem, ok := c.entries[table.id]; ok {
c.lru.Remove(elem)
delete(c.entries, table.id)
}
c.mu.Unlock()
}
func (c *pairTableCache) Touch(table *PairTable) {
if c == nil || table == nil {
return
}
c.mu.Lock()
if elem, ok := c.entries[table.id]; ok {
c.lru.MoveToBack(elem)
}
c.mu.Unlock()
}
func (c *pairTableCache) collectEvictionsLocked() []*PairTable {
if c == nil || c.limit <= 0 {
return nil
}
var victims []*PairTable
for c.lru.Len() > c.limit {
front := c.lru.Front()
if front == nil {
break
}
entry := front.Value.(pairTableCacheEntry)
c.lru.Remove(front)
delete(c.entries, entry.id)
victims = append(victims, entry.table)
}
return victims
}
// resolvePairTableLimit decide quanti descrittori il file manager può tenere
// aperti quando max_pair_tables non è configurato.
//
// La forma è "il limite meno un margine", ma il margine è *proporzionale*: era
// quello il difetto, non l'idea. Con una costante di 128 il calcolo funzionava
// col tipico soft limit Linux di 1024 e diventava patologico dove il limite è
// alto: su macOS (RLIMIT_NOFILE = kern.maxfilesperproc = 61440) concedeva 61312
// handle alle sole tabelle pair — tutti tranne 128 — senza lasciare niente a
// tabelle values e recycle, main_keys, jump store, socket TCP e runtime Go, e
// un'ingestione intensa arrivava a EMFILE ("too many open files") invece di
// sfrattare.
//
// Il margine non va allargato oltre il necessario: la cache di handle paga, e
// strozzarla costa molto più di quanto si risparmi, perché open(2) diventa in
// fretta la voce dominante di CPU (stessa trappola già registrata per il jump
// store). Misurato su image-sign-db, 12 immagini × 3600 costellazioni, macOS,
// soft limit 61440: con un tetto a 8192 le prime tre immagini costavano 13,3 s,
// 97,9 s e 156,9 s — 2135 s in totale, con degrado progressivo — contro 4,0 s e
// 6,6 s a budget pieno. Riservare un ottavo lascia qui 7 680 descrittori
// liberi, molti più di quanti ne servano fuori dal file manager, e
// openFileWithReclaim resta la rete di sicurezza se il conto non tornasse.
//
// Il tetto assoluto è solo una difesa contro rlimit patologici, non una
// manopola di tuning: va tenuto alto.
func resolvePairTableLimit(configured int) int {
if configured > 0 {
return configured
}
limit := fileDescriptorSoftLimit()
if limit <= 0 {
return defaultPairTableLimit
}
margin := limit / pairTableReserveDivisor
if margin < minPairTableReserve {
margin = minPairTableReserve
}
candidate := limit - margin
if candidate > maxPairTableLimit {
candidate = maxPairTableLimit
}
if candidate < minPairTableLimit {
candidate = minPairTableLimit
}
return candidate
}
const (
pairScanDefaultLimit = 256
pairScanMaxLimit = 4096
pairSummaryDefaultDepth = 1
pairSummaryDefaultBranchLimit = 32
pairSummaryMaxBranchLimit = 1024
defaultPairTableLimit = 1024
minPairTableLimit = 64
maxPairTableLimit = 65536
// Quota di RLIMIT_NOFILE lasciata fuori dal file manager — un ottavo — per
// socket, jump store, scritture transitorie e runtime. Vedi
// resolvePairTableLimit.
pairTableReserveDivisor = 8
// Il margine proporzionale non scende sotto questo valore sui limiti bassi.
minPairTableReserve = 128
maxJumpReloadAttempts = 8
// Quanti ID di tabella pair si prenotano per scrittura del contatore.
pairTableIDReservationChunk = 256
)
var errPairNotFound = errors.New("pair not found")
type PairScanResult struct {
Value []byte
Key uint64
}
type pairSummaryBranch struct {
Path []byte
Count int64
}
type PairSummaryResult struct {
Prefix []byte
TerminalCount int64
TotalPayloadBytes int64
MinPayloadBytes uint32
MaxPayloadBytes uint32
MinKey uint64
MaxKey uint64
MaxDepth int
SelfTerminal bool
Branches []pairSummaryBranch
}
type PairReduceResult struct {
Value []byte
Key uint64
Payload []byte
}
type forkTriePayload struct {
Path string `json:"path"`
Payload string `json:"payload"`
}
type forkTransferPayload struct {
Prefix string `json:"prefix,omitempty"`
Entries []forkTriePayload `json:"entries,omitempty"`
Predictions map[string][]PredictionEntry `json:"predictions,omitempty"`
}
const (
pairEntryKeyOffset = 1
pairEntryChildOffset = pairEntryKeyOffset + PairEntryKeySize
)
func entryHasTerminal(entry []byte) bool {
return len(entry) > 0 && (entry[0]&FlagIsTerminal) != 0
}
func entryIsHidden(entry []byte) bool {
return len(entry) > 0 && (entry[0]&FlagHidden) != 0
}
func entryHasChild(entry []byte) bool {
if len(entry) == 0 || (entry[0]&FlagHasChild) == 0 {
return false
}
return binary.BigEndian.Uint32(entry[pairEntryChildOffset:pairEntryChildOffset+PairEntryChildSize]) != 0
}
func entryChildID(entry []byte) uint32 {
if len(entry) < pairEntryChildOffset+PairEntryChildSize {
return 0
}
return binary.BigEndian.Uint32(entry[pairEntryChildOffset : pairEntryChildOffset+PairEntryChildSize])
}
func setEntryChild(entry []byte, childID uint32) {
if len(entry) < pairEntryChildOffset+PairEntryChildSize {
return
}
entry[0] |= FlagHasChild
entry[0] &^= FlagHasJump
binary.BigEndian.PutUint32(entry[pairEntryChildOffset:], childID)
}
func clearEntryChild(entry []byte) {
if len(entry) < pairEntryChildOffset+PairEntryChildSize {
return
}
entry[0] &^= FlagHasChild
for i := 0; i < PairEntryChildSize; i++ {
entry[pairEntryChildOffset+i] = 0
}
}
func entryHasJump(entry []byte) bool {
return len(entry) > 0 && (entry[0]&FlagHasJump) != 0
}
func entryJumpID(entry []byte) uint32 {
if len(entry) < pairEntryChildOffset+PairEntryChildSize {
return 0
}
return binary.BigEndian.Uint32(entry[pairEntryChildOffset : pairEntryChildOffset+PairEntryChildSize])
}
func setEntryJump(entry []byte, jumpID uint32) {
if len(entry) < pairEntryChildOffset+PairEntryChildSize {
return
}
entry[0] |= FlagHasJump
entry[0] &^= FlagHasChild
binary.BigEndian.PutUint32(entry[pairEntryChildOffset:], jumpID)
}
func clearEntryJump(entry []byte) {
if len(entry) < pairEntryChildOffset+PairEntryChildSize {
return
}
entry[0] &^= FlagHasJump
for i := 0; i < PairEntryChildSize; i++ {
entry[pairEntryChildOffset+i] = 0
}
}
func entryIsEmpty(entry []byte) bool {
if len(entry) == 0 {
return true
}
return (entry[0] & (FlagIsTerminal | FlagHasChild | FlagHasJump)) == 0
}
func setEntryTerminal(entry []byte, absKey uint64, hidden bool) {
if len(entry) < pairEntryKeyOffset+PairEntryKeySize {
return
}
entry[0] |= FlagIsTerminal
if hidden {
entry[0] |= FlagHidden
} else {
entry[0] &^= FlagHidden
}
var buf [8]byte
binary.BigEndian.PutUint64(buf[:], absKey)
copy(entry[pairEntryKeyOffset:pairEntryKeyOffset+PairEntryKeySize], buf[8-PairEntryKeySize:])
}
func clearEntryTerminal(entry []byte) {
if len(entry) < pairEntryKeyOffset+PairEntryKeySize {
return
}
entry[0] &^= FlagIsTerminal
entry[0] &^= FlagHidden
for i := 0; i < PairEntryKeySize; i++ {
entry[pairEntryKeyOffset+i] = 0
}
}
func (db *Database) nextChunk(key []byte, offset int) ([]byte, uint32, bool, error) {
if offset >= len(key) {
return nil, 0, true, fmt.Errorf("offset beyond key length")
}
end := offset + db.branchCodec.chunkBytes
if end > len(key) {
end = len(key)
}
chunk := key[offset:end]
index, err := db.branchCodec.branchIndexFromChunk(chunk)
if err != nil {
return nil, 0, false, err
}
return chunk, index, end == len(key), nil
}
func NewDatabase(name, path string, monitor *ResourceMonitor, cfg DatabaseConfig, maxPairTables int) (*Database, error) {
if err := os.MkdirAll(path, 0755); err != nil {
return nil, err
}
pairDir := filepath.Join(path, "pairs")
if err := os.MkdirAll(pairDir, 0755); err != nil {
return nil, err
}
jumpDir := filepath.Join(path, "pair_jumps")
if err := os.MkdirAll(jumpDir, 0755); err != nil {
return nil, err
}
keyFmt, err := resolveKeyFormat(path, cfg)
if err != nil {
return nil, err
}
// Resolve the pair-trie container format. The per-database marker
// (pairs/format.dat) is authoritative once written: it pins the stride and
// the adaptive flag so a database is always reopened with the same layout it
// was built with. A directory that already holds legacy (headerless) pair
// tables but no marker is refused — the operator must RESET_DB to rebuild it
// in the current format.
pairFmt, err := resolvePairFormat(pairDir, cfg)
if err != nil {
return nil, err
}
codec, err := newPairBranchCodec(pairFmt.stride)
if err != nil {
return nil, err
}
// Keep the recorded settings consistent with the format actually in use: the
// marker can legitimately differ from the supplied config on reopen.
effective := cfg
effective.PairIndexBytes = pairFmt.stride
effective.AdaptivePairIndex = pairFmt.adaptive
effective.PairListMaxBytes = pairFmt.listMaxBytes
effective.PairListMaxFillPercent = pairFmt.listMaxFillPct
effective.ShardedKeySlots = keyFmt.sharded
effective.KeySlotBits = keyFmt.slotBits
pairLimit := resolvePairTableLimit(maxPairTables)
fileManager := NewFileManager(pairLimit, monitor)
var mkt *MainKeysTable
if !keyFmt.sharded {
mkt, err = NewMainKeysTable(fileManager, filepath.Join(path, "main_keys.table"))
if err != nil {
fileManager.Close()
return nil, err
}
}
keepMainKeysOpen := false
defer func() {
if !keepMainKeysOpen {
if mkt != nil {
mkt.Close()
}
fileManager.Close()
}
}()
db := &Database{
name: name,
path: path,
pairDir: pairDir,
nextPairIDPath: filepath.Join(pairDir, "next_id.dat"),
mainKeys: mkt,
keyFormat: keyFmt,
payloadCache: newPayloadCacheFromConfig(cfg),
resources: monitor,
fileManager: fileManager,
pairTableCache: newPairTableCache(pairLimit),
settings: effective,
branchCodec: codec,
adaptivePairs: pairFmt.adaptive,
pairListMaxBytes: pairFmt.listMaxBytes,
pairListMaxFillPct: pairFmt.listMaxFillPct,
jumpDir: jumpDir,
jumpDataPath: filepath.Join(jumpDir, "jumps.bin"),
jumpIndexPath: filepath.Join(jumpDir, "index.bin"),
nextJumpIDPath: filepath.Join(jumpDir, "next_id.dat"),
forkScheduler: newForkScheduler(path),
jobs: newMicroJobManager(),
reducers: newReducerRegistry(),
}
db.predictStore = newPredictionManager(path)
db.recordStore = newRecordManager(filepath.Join(path, "records"))
db.graphCache = newGraphCacheStore(db, graphCacheConfigFromDatabaseConfig(effective))
db.protocolProfiles = newNumericProfileStore(filepath.Join(path, numericProfileFile))
db.clusterMessenger = newClusterMessenger(db.forkScheduler)
db.registerDefaultReducers()
if keyFmt.sharded {
db.shardedKeys, err = newShardedKeyStore(path, fileManager, keyFmt)
if err != nil {
return nil, err
}
}
// Carica il contatore degli ID delle tabelle pair
if err := db.loadNextPairTableID(); err != nil {
return nil, err
}
if err := db.loadNextJumpID(); err != nil {
return nil, err
}
if !keyFmt.sharded {
if err := db.loadHighestKey(); err != nil {
return nil, err
}
// La free list delle chiavi va aperta dopo loadHighestKey: se manca,
// viene seminata con le righe già cancellate.
keyRecyclePath := filepath.Join(path, "main_keys.recycle.table")
_, missing := os.Stat(keyRecyclePath)
keyRecycle, err := NewRecycleTable(fileManager, keyRecyclePath, RecycleKeyEntrySize)
if err != nil {
return nil, err
}
db.keyRecycle = keyRecycle
if os.IsNotExist(missing) {
if err := db.seedKeyRecycle(); err != nil {
keyRecycle.Close()
return nil, err
}
}
}
keepMainKeysOpen = true
return db, nil
}
func (db *Database) Path() string { return db.path }
func (db *Database) Name() string { return db.name }
// Close chiude tabelle, file manager, prediction store e messenger di questo
// database. È idempotente: le chiamate successive alla prima non fanno nulla e
// restituiscono lo stesso errore.
func (db *Database) Close() error {
if db == nil {
return nil
}
db.closeOnce.Do(func() {
db.closeErr = db.shutdown()
})
return db.closeErr
}
func (db *Database) shutdown() error {
var firstErr error
// Il maintainer della cache scrive nella trie come qualsiasi altro
// scrittore: va fermato e atteso *prima* che i file sotto di lui spariscano.
db.graphCache.CloseAndWait()
if db.shardedKeys != nil {
db.shardedKeys.Close()
} else {
if db.mainKeys != nil {
db.mainKeys.Close()
}
if db.keyRecycle != nil {
db.keyRecycle.Close()
}
}
db.valuesTables.Range(func(key, value interface{}) bool {
if table, ok := value.(interface{ Close() }); ok {
table.Close()
}
return true
})
db.recycleTables.Range(func(key, value interface{}) bool {
if table, ok := value.(interface{ Close() }); ok {
table.Close()
}
return true
})
db.pairTables.Range(func(key, value interface{}) bool {
if table, ok := value.(interface{ Close() }); ok {
table.Close()
}
return true
})
if db.fileManager != nil {
db.fileManager.Close()
}
db.closeJumpStore()
if db.predictStore != nil {
db.predictStore.Close()
}
if db.clusterMessenger != nil {
db.clusterMessenger.Stop()
}
return firstErr
}
// getValuesTable e getRecycleTable sono i gestori della cache delle tabelle.
func (db *Database) getValuesTable(size uint32, tableID uint32) (*ValuesTable, error) {
key := fmt.Sprintf("%d_%d", size, tableID)
if table, ok := db.valuesTables.Load(key); ok {
return table.(*ValuesTable), nil
}
db.mu.Lock()
defer db.mu.Unlock()
if table, ok := db.valuesTables.Load(key); ok {
return table.(*ValuesTable), nil
}
path := filepath.Join(db.path, fmt.Sprintf("values_%s.table", key))
newTable, err := NewValuesTable(db.fileManager, path, size)
if err != nil {
return nil, err
}
db.valuesTables.Store(key, newTable)
return newTable, nil
}
// todo: unificate getValuesTable and getRecycleTable
func (db *Database) getRecycleTable(size uint32) (*RecycleTable, error) {
key := size
if table, ok := db.recycleTables.Load(key); ok {
return table.(*RecycleTable), nil
}
db.mu.Lock()
defer db.mu.Unlock()
if table, ok := db.recycleTables.Load(key); ok {
return table.(*RecycleTable), nil
}
path := filepath.Join(db.path, fmt.Sprintf("values_%d.recycle.table", size))
newTable, err := NewRecycleTable(db.fileManager, path, ValueLocationIndexSize)
if err != nil {
return nil, err
}
db.recycleTables.Store(key, newTable)
return newTable, nil
}
// loadNextPairTableID carica dal disco il prossimo ID da usare per una nuova tabella pair.
func (db *Database) loadNextPairTableID() error {
data, err := os.ReadFile(db.nextPairIDPath)
if err != nil {
if os.IsNotExist(err) {
// Il file non esiste, partiamo da 1 (0 +-+ la root)
db.nextPairTableID.Store(1)
db.pairTableIDReserved.Store(1)
return nil
}
return err
}
if len(data) >= 4 {
stored := binary.BigEndian.Uint32(data)
db.nextPairTableID.Store(stored)
// Il file contiene il fondo dell'ultima prenotazione: sotto di esso gli
// ID sono bruciati, non liberi.
db.pairTableIDReserved.Store(stored)
}
return nil
}
// getNewPairTableID restituisce un nuovo ID univoco, prenotandoli a blocchi.
//
// Stessa regola di getNewJumpID: si persiste il fondo del blocco *prima* di
// consegnarne il primo ID, così un crash può solo bruciare ID mai usati. Una
// scrittura per ID costava un open+write+close per ogni nodo nuovo del trie.
func (db *Database) getNewPairTableID() (uint32, error) {
newID := db.nextPairTableID.Add(1) - 1
if newID < db.pairTableIDReserved.Load() {
return newID, nil
}
db.pairTableReserveMu.Lock()
defer db.pairTableReserveMu.Unlock()
if newID < db.pairTableIDReserved.Load() {
return newID, nil
}
target := newID + pairTableIDReservationChunk
buf := make([]byte, 4)
binary.BigEndian.PutUint32(buf, target)
if err := os.WriteFile(db.nextPairIDPath, buf, 0644); err != nil {
return 0, err
}
db.pairTableIDReserved.Store(target)
return newID, nil
}
// getPairTable ora accetta un uint32 ID.
func (db *Database) getPairTable(tableID uint32) (*PairTable, error) {
if table, ok := db.loadPairTable(tableID); ok {
if db.pairTableCache != nil {
db.pairTableCache.Touch(table)
}
return table, nil
}
db.mu.Lock()
defer db.mu.Unlock()
if table, ok := db.loadPairTable(tableID); ok {
if db.pairTableCache != nil {
db.pairTableCache.Touch(table)
}
return table, nil
}
// Il nome del file +-+ l'ID in esadecimale
path := filepath.Join(db.pairDir, fmt.Sprintf("%x.table", tableID))
newTable, err := NewPairTable(db.fileManager, db.pairTableCache, tableID, path, db.branchCodec.branchCount, db.adaptivePairs, db.pairListMaxBytes, db.pairListMaxFillPct)
if err != nil {
return nil, err
}
db.storePairTable(tableID, newTable)
if db.pairTableCache != nil {
db.pairTableCache.Touch(newTable)
}
return newTable, nil
}
func (db *Database) loadPairTable(tableID uint32) (*PairTable, bool) {
if table, ok := db.pairTables.Load(tableID); ok {
if pt, castOk := table.(*PairTable); castOk {
return pt, true
}
}
return nil, false
}
func (db *Database) storePairTable(tableID uint32, table *PairTable) {
db.pairTables.Store(tableID, table)
}
func (db *Database) closePairTable(tableID uint32, table *PairTable, deleteFile bool) error {
if table != nil {
table.Close()
}
if deleteFile {
path := filepath.Join(db.pairDir, fmt.Sprintf("%x.table", tableID))
return os.Remove(path)
}
return nil
}
func (db *Database) setPairValue(value []byte, absKey uint64, hidden bool) error {
if len(value) == 0 {
return fmt.Errorf("pair value cannot be empty")
}
if _, _, err := db.keyFormat.decode(absKey); err != nil {
return err
}
db.pairMutationMu.Lock()
defer db.pairMutationMu.Unlock()
return db.insertPairAt(0, value, 0, absKey, hidden)
}
func (db *Database) insertPairAt(tableID uint32, key []byte, offset int, absKey uint64, hidden bool) error {
table, err := db.getPairTable(tableID)
if err != nil {
return err
}
label := fmt.Sprintf("insert table=%d offset=%d", tableID, offset)
for retries := 0; retries < maxJumpReloadAttempts; retries++ {
branch, err := db.selectPairBranch(table, key, offset, label)
if err != nil {
return err
}
nextOffset := offset + len(branch.chunk)
entry := branch.entry
if nextOffset == len(key) {
// Chiave che finisce qui: si accende il terminale sull'entry e si
// lascia intatto un eventuale jump, che serve alle chiavi più
// lunghe che passano di qui.
setEntryTerminal(entry, absKey, hidden)
return table.WriteEntry(branch.index, entry)
}
if branch.jump != nil {
if err := db.insertThroughJump(tableID, table, branch.index, entry, key, nextOffset, absKey, hidden); err != nil {
if shouldRetryJump(err) {
continue
}
return err
}
return nil
}
if entryHasChild(entry) {
return db.insertPairAt(entryChildID(entry), key, nextOffset, absKey, hidden)
}
jumpID, err := db.createJump(key[nextOffset:], true, absKey, hidden, 0)
if err != nil {
return err
}
setEntryJump(entry, jumpID)
return table.WriteEntry(branch.index, entry)
}
return fmt.Errorf("jump reload limit exceeded (%s)", label)
}
func (db *Database) insertThroughJump(tableID uint32, parent *PairTable, branchIndex uint32, entry []byte, key []byte, offset int, absKey uint64, hidden bool) error {
jumpID := entryJumpID(entry)
node, err := db.loadJump(jumpID)
if err != nil {
return err
}
remainder := key[offset:]
common := longestCommonPrefix(node.Bytes, remainder)
if common == len(node.Bytes) {
offset += common
if offset == len(key) {
node.HasTerminal = true
node.HiddenTerminal = hidden
node.TerminalKey = absKey
return db.writeJump(node)
}
if node.NextTableID == 0 {
newID, err := db.getNewPairTableID()
if err != nil {
return err
}
node.NextTableID = newID
if err := db.writeJump(node); err != nil {
return err
}
}
return db.insertPairAt(node.NextTableID, key, offset, absKey, hidden)
}
if common > 0 {
return db.splitJumpWithCommonPrefix(node, common, remainder[common:], absKey, hidden)
}
childID, err := db.splitJumpIntoChild(parent, branchIndex, entry, node, common)
if err != nil {
return err
}
return db.insertPairAt(childID, key, offset+common, absKey, hidden)
}
func (db *Database) splitJumpWithCommonPrefix(node *JumpNode, common int, newTail []byte, absKey uint64, hidden bool) error {
if node == nil {
return fmt.Errorf("nil_jump_node")
}
if common <= 0 || common >= len(node.Bytes) {
return fmt.Errorf("invalid_common_prefix")
}
childID, err := db.getNewPairTableID()
if err != nil {
return err
}
oldTail := append([]byte{}, node.Bytes[common:]...)
if len(oldTail) == 0 {
return fmt.Errorf("invalid_jump_split_state")
}
if err := db.insertSuffixWithContinuation(
childID,
oldTail,
node.HasTerminal,
node.TerminalKey,
node.HiddenTerminal,
node.NextTableID,
); err != nil {
return err
}
if len(newTail) > 0 {
if err := db.insertSuffixWithContinuation(childID, newTail, true, absKey, hidden, 0); err != nil {
return err
}
}
node.Bytes = append([]byte{}, node.Bytes[:common]...)
node.NextTableID = childID
if len(newTail) == 0 {
node.HasTerminal = true
node.HiddenTerminal = hidden
node.TerminalKey = absKey
} else {
node.HasTerminal = false
node.HiddenTerminal = false
node.TerminalKey = 0
}
return db.writeJump(node)
}
func (db *Database) splitJumpIntoChild(parent *PairTable, branchIndex uint32, entry []byte, node *JumpNode, splitOffset int) (uint32, error) {
childID, err := db.getNewPairTableID()
if err != nil {
return 0, err
}
remaining := node.Bytes[splitOffset:]
if len(remaining) == 0 {
return 0, fmt.Errorf("invalid jump split state")
}
if err := db.insertSuffixWithContinuation(childID, remaining, node.HasTerminal, node.TerminalKey, node.HiddenTerminal, node.NextTableID); err != nil {
return 0, err
}
if err := db.deleteJump(node.ID); err != nil {
return 0, err
}
clearEntryJump(entry)
setEntryChild(entry, childID)
if err := parent.WriteEntry(branchIndex, entry); err != nil {
return 0, err
}
return childID, nil
}
func (db *Database) insertSuffixWithContinuation(tableID uint32, suffix []byte, hasTerminal bool, terminalKey uint64, terminalHidden bool, nextTableID uint32) error {
current := tableID
offset := 0
for {
table, err := db.getPairTable(current)
if err != nil {
return err
}
// Stessa scelta di ramo del lookup: se un ramo corto esiste già, la
// coda va infilata sotto quello e non su un ramo allineato accanto.
branch, err := db.selectPairBranch(table, suffix, offset, fmt.Sprintf("insert suffix table=%d offset=%d", current, offset))
if err != nil {
return err
}
entry := branch.entry
nextOffset := offset + len(branch.chunk)
if nextOffset == len(suffix) {
if hasTerminal {
setEntryTerminal(entry, terminalKey, terminalHidden)
}
if nextTableID != 0 {
setEntryChild(entry, nextTableID)
}
return table.WriteEntry(branch.index, entry)
}
if entryHasChild(entry) {
current = entryChildID(entry)
offset = nextOffset
continue
}
jumpID, err := db.createJump(suffix[nextOffset:], hasTerminal, terminalKey, terminalHidden, nextTableID)
if err != nil {
return err
}
setEntryJump(entry, jumpID)
return table.WriteEntry(branch.index, entry)
}
}
func longestCommonPrefix(a, b []byte) int {
minLen := len(a)
if len(b) < minLen {
minLen = len(b)
}
for i := 0; i < minLen; i++ {
if a[i] != b[i] {
return i
}
}
return minLen
}
func (db *Database) getPairValue(value []byte) (uint64, error) {
if len(value) == 0 {
return 0, fmt.Errorf("pair value cannot be empty")
}
return db.lookupPairAt(0, value, 0)
}
func (db *Database) lookupPairAt(tableID uint32, key []byte, offset int) (uint64, error) {
table, err := db.getPairTable(tableID)
if err != nil {
return 0, err
}
branch, err := db.selectPairBranch(table, key, offset, fmt.Sprintf("lookup table=%d offset=%d", tableID, offset))
if err != nil {
return 0, err
}
nextOffset := offset + len(branch.chunk)
if nextOffset == len(key) {
// La chiave finisce su questo ramo. Terminale, figlio e jump sono flag
// indipendenti, quindi il terminale dell'entry va letto prima di
// scendere: un jump accanto porta solo chiavi più lunghe.
if entryHasTerminal(branch.entry) {
return decodeAbsoluteKey(branch.entry), nil
}
return 0, errPairNotFound
}
if branch.jump != nil {
node := branch.jump
if !bytes.HasPrefix(key[nextOffset:], node.Bytes) {
return 0, errPairNotFound
}
childOffset := nextOffset + len(node.Bytes)
if childOffset == len(key) {
if node.HasTerminal {
return node.TerminalKey, nil
}
return 0, errPairNotFound
}
if node.NextTableID == 0 {
return 0, errPairNotFound
}
return db.lookupPairAt(node.NextTableID, key, childOffset)
}
if entryHasChild(branch.entry) {
return db.lookupPairAt(entryChildID(branch.entry), key, nextOffset)
}
return 0, errPairNotFound
}
// entryIsPopulated dice se un'entry porta davvero informazione: un ramo mai
// scritto si rilegge come entry azzerata, non come errore.
func entryIsPopulated(entry []byte) bool {
return !entryIsEmpty(entry)