-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
4059 lines (3452 loc) · 123 KB
/
client.go
File metadata and controls
4059 lines (3452 loc) · 123 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
package comet
import (
"bufio"
"context"
"encoding/binary"
"fmt"
"io"
"maps"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"unsafe"
"github.com/klauspost/compress/zstd"
)
// shardIndexPool reuses ShardIndex objects to reduce allocations
var shardIndexPool = sync.Pool{
New: func() any {
return &ShardIndex{
ConsumerOffsets: make(map[string]int64),
Files: make([]FileInfo, 0),
BinaryIndex: BinarySearchableIndex{
Nodes: make([]EntryIndexNode, 0),
},
}
},
}
// EntryPosition represents the location of an entry in the file system
// EntryPosition represents the location of an entry in the file system
type EntryPosition struct {
FileIndex int `json:"file_index"` // Index in the Files array
ByteOffset int64 `json:"byte_offset"` // Byte offset within the file
}
// EntryIndexMetadata represents a stored index node
type EntryIndexMetadata struct {
EntryNumber int64 `json:"entry_number"`
Position EntryPosition `json:"position"`
}
// WriteMode determines how data is written to disk
type WriteMode int
const (
WriteModeDirect WriteMode = iota // Direct I/O with O_SYNC
WriteModeBuffered // Standard buffered writes (fastest)
WriteModeFSync // Buffered writes + explicit fsync
// Constants for entry format
headerSize = 4 + 8 // uint32 size + uint64 timestamp
maxEntrySize = 128 * 1024 * 1024 // 128MB max entry size
)
// CompressionConfig controls compression behavior
type CompressionConfig struct {
MinCompressSize int `json:"min_compress_size"` // Minimum size to compress (bytes)
}
// IndexingConfig controls indexing behavior
type IndexingConfig struct {
BoundaryInterval int `json:"boundary_interval"` // Store boundary every N entries
MaxIndexEntries int `json:"max_index_entries"` // Max boundary entries per shard (0 = unlimited)
}
// StorageConfig controls file storage behavior
type StorageConfig struct {
MaxFileSize int64 `json:"max_file_size"` // Maximum size per file before rotation
CheckpointInterval time.Duration `json:"checkpoint_interval"` // Checkpoint interval
CheckpointEntries int `json:"checkpoint_entries"` // Checkpoint every N entries (default: 100000)
FlushInterval time.Duration `json:"flush_interval"` // Flush to OS cache interval (memory management, not durability)
FlushEntries int `json:"flush_entries"` // Flush to OS cache every N entries (memory management, not durability)
}
// ConcurrencyConfig controls multi-process behavior
type ConcurrencyConfig struct {
// Process-level shard ownership (simplifies multi-process coordination)
// When ProcessCount > 1, multi-process mode is automatically enabled
ProcessID int `json:"process_id"` // This process's ID (0-based)
ProcessCount int `json:"process_count"` // Total number of processes (0 = single-process)
SHMFile string `json:"shm_file"` // Shared memory file path (empty = os.TempDir()/comet-worker-slots-shm)
}
// Owns checks if this process owns a particular shard
func (c ConcurrencyConfig) Owns(shardID uint32) bool {
if c.ProcessCount <= 1 {
return true // Single process owns all shards
}
return int(shardID%uint32(c.ProcessCount)) == c.ProcessID
}
// IsMultiProcess returns true if running in multi-process mode
func (c ConcurrencyConfig) IsMultiProcess() bool {
return c.ProcessCount > 1
}
// RetentionConfig controls data retention policies
type RetentionConfig struct {
MaxAge time.Duration `json:"max_age"` // Delete files older than this
MaxBytes int64 `json:"max_bytes"` // Delete oldest files if total size exceeds
MaxTotalSize int64 `json:"max_total_size"` // Alias for MaxBytes for compatibility
MaxShardSize int64 `json:"max_shard_size"` // Maximum size per shard
CheckUnconsumed bool `json:"check_unconsumed"` // Protect unconsumed messages
ProtectUnconsumed bool `json:"protect_unconsumed"` // Alias for CheckUnconsumed
CleanupInterval time.Duration `json:"cleanup_interval"` // How often to run cleanup (0 = disabled)
FileGracePeriod time.Duration `json:"file_grace_period"` // Don't delete files newer than this
ForceDeleteAfter time.Duration `json:"force_delete_after"` // Force delete files older than this
SafetyMargin float64 `json:"safety_margin"` // Keep this fraction of space free (0.0-1.0)
MinFilesToRetain int `json:"min_files_to_retain"` // Always keep at least N files per shard
MinFilesToKeep int `json:"min_files_to_keep"` // Alias for MinFilesToRetain
}
// CometConfig represents the complete comet configuration
type CometConfig struct {
// Write mode
WriteMode WriteMode `json:"write_mode"`
// Compression settings
Compression CompressionConfig `json:"compression"`
// Indexing settings
Indexing IndexingConfig `json:"indexing"`
// Storage settings
Storage StorageConfig `json:"storage"`
// Concurrency settings
Concurrency ConcurrencyConfig `json:"concurrency"`
// Retention policy
Retention RetentionConfig `json:"retention"`
// Logging configuration
Log LogConfig `json:"log"`
// Reader settings
Reader ReaderConfig `json:"reader"`
}
// DefaultCometConfig returns sensible defaults optimized for logging workloads
func DefaultCometConfig() CometConfig {
maxFileSize := int64(256 << 20) // 256MB per file
cfg := CometConfig{
// Compression - optimized for logging workloads
Compression: CompressionConfig{
MinCompressSize: 4096, // Only compress entries >4KB to avoid latency hit on typical logs
},
// Indexing - memory efficient boundary tracking
Indexing: IndexingConfig{
BoundaryInterval: 100, // Store boundaries every 100 entries
MaxIndexEntries: 10000, // Limit index memory growth
},
// Storage - optimized for 256MB files
Storage: StorageConfig{
MaxFileSize: maxFileSize,
CheckpointInterval: 2 * time.Second, // Checkpoint every 2 seconds
CheckpointEntries: 100000, // Checkpoint every 100k entries
FlushEntries: 50000, // Flush every 50k entries (~5MB) - optimal for large batches
FlushInterval: 1 * time.Second, // Flush and make data visible every 1 second
},
// Concurrency - single-process mode by default
// Set ProcessCount > 1 for multi-process deployments (e.g., prefork mode)
Concurrency: ConcurrencyConfig{
ProcessID: 0, // Default to process 0
ProcessCount: 0, // 0 = single-process mode
},
// Retention - Keep 1 week of data by default
Retention: RetentionConfig{
MaxAge: 7 * 24 * time.Hour,
MaxBytes: 10 << 30, // 10GB max per shard
CheckUnconsumed: true, // Protect unconsumed data
CleanupInterval: 1 * time.Hour,
FileGracePeriod: 5 * time.Minute,
SafetyMargin: 0.1, // Keep 10% free
MinFilesToRetain: 2, // Always keep at least 2 files
},
// Logging
Log: LogConfig{
Level: func() string {
if os.Getenv("COMET_DEBUG") != "" && os.Getenv("COMET_DEBUG") != "0" && strings.ToLower(os.Getenv("COMET_DEBUG")) != "false" {
return "debug"
}
return "info"
}(),
},
}
if isFiberChild == envPreforkChildVal {
// We're in a Fiber worker - enable multi-process coordination
processID := GetProcessID() // Use default shared memory
if processID >= 0 {
cfg.Concurrency.ProcessID = processID
cfg.Concurrency.ProcessCount = runtime.NumCPU()
}
}
return cfg
}
// DeprecatedMultiProcessConfig creates a config for multi-process mode with N processes
func DeprecatedMultiProcessConfig(processID, processCount int) CometConfig {
cfg := DefaultCometConfig()
cfg.Concurrency.ProcessID = processID
cfg.Concurrency.ProcessCount = processCount
return cfg
}
// HighCompressionConfig returns a config optimized for compression ratio
func HighCompressionConfig() CometConfig {
cfg := DefaultCometConfig()
cfg.Compression.MinCompressSize = 512 // Compress smaller entries
return cfg
}
// HighThroughputConfig returns a config optimized for write throughput
func HighThroughputConfig() CometConfig {
cfg := DefaultCometConfig()
cfg.Storage.CheckpointInterval = 10 * time.Second // Less frequent checkpoints
cfg.Storage.CheckpointEntries = 200000 // Checkpoint every 200k entries (infrequent syncs)
cfg.Storage.FlushEntries = 100000 // Flush every 100k entries for large batch throughput
cfg.Compression.MinCompressSize = 1024 * 1024 // Only compress very large entries
cfg.Indexing.BoundaryInterval = 1000 // Less frequent index entries
// Reader config is set to defaults in DefaultReaderConfig()
return cfg
}
// OptimizedConfig returns a configuration optimized for a specific number of shards.
// Based on benchmarking, it adjusts file size and other parameters for optimal performance.
//
// Recommended shard counts:
// - 16 shards: Good for small deployments
// - 64 shards: Balanced performance
// - 256 shards: Optimal for high throughput (2.4M ops/sec)
//
// Example:
//
// config := comet.OptimizedConfig(256, 3072) // For 256 shards with 3GB memory budget
// client, err := comet.NewClient("/data", config)
func OptimizedConfig(shardCount int, memoryBudget int) CometConfig {
cfg := DefaultCometConfig()
// Calculate optimal file size based on 3GB memory budget
fileSizeMB := memoryBudget / shardCount
// Clamp file size to reasonable bounds
if fileSizeMB < 10 {
fileSizeMB = 10 // Minimum 10MB
} else if fileSizeMB > 1024 {
fileSizeMB = 1024 // Maximum 1GB
}
cfg.Storage.MaxFileSize = int64(fileSizeMB) << 20
// Use our benchmarked optimal values for flush and checkpoint
// These were proven to provide best performance in our tests
cfg.Storage.FlushEntries = 50_000 // Optimal for batch throughput
cfg.Storage.CheckpointEntries = 100_000 // Reduced from default, better for high throughput
// For high shard counts, reduce checkpoint time to avoid memory pressure
if shardCount >= 256 {
cfg.Storage.CheckpointInterval = 5 * time.Second // 5 seconds for many shards
}
return cfg
}
// validateConfig validates the configuration and sets defaults
func validateConfig(cfg *CometConfig) error {
if cfg.Storage.MaxFileSize <= 0 {
cfg.Storage.MaxFileSize = 256 << 20 // 256MB default
}
if cfg.Storage.CheckpointInterval <= 0 {
cfg.Storage.CheckpointInterval = 2 * time.Second // 2 seconds default
}
if cfg.Storage.CheckpointEntries <= 0 {
cfg.Storage.CheckpointEntries = 100000 // 100k entries default
}
if cfg.Storage.FlushEntries < 0 {
cfg.Storage.FlushEntries = 50000 // 50k entries default
}
// FlushEntries of 0 means no entry-based flushing (rely on buffer size)
// Validate constraint: checkpoint should be >= flush (if both are set)
if cfg.Storage.FlushEntries > 0 && cfg.Storage.CheckpointEntries < cfg.Storage.FlushEntries {
// Auto-adjust checkpoint to be at least 2x flush for efficiency
cfg.Storage.CheckpointEntries = cfg.Storage.FlushEntries * 2
}
if cfg.Compression.MinCompressSize < 0 {
cfg.Compression.MinCompressSize = 4096 // 4KB default
}
if cfg.Indexing.BoundaryInterval <= 0 {
cfg.Indexing.BoundaryInterval = 100 // Default interval
}
if cfg.Concurrency.ProcessCount < 0 {
return fmt.Errorf("process count cannot be negative")
}
if cfg.Concurrency.ProcessCount > 0 && (cfg.Concurrency.ProcessID < 0 || cfg.Concurrency.ProcessID >= cfg.Concurrency.ProcessCount) {
return fmt.Errorf("process ID %d is out of range [0, %d)", cfg.Concurrency.ProcessID, cfg.Concurrency.ProcessCount)
}
// Retention validation
if cfg.Retention.SafetyMargin < 0 || cfg.Retention.SafetyMargin > 1 {
cfg.Retention.SafetyMargin = 0.1 // Default 10%
}
if cfg.Retention.MinFilesToRetain < 1 {
cfg.Retention.MinFilesToRetain = 1
}
// Reader validation - use defaults from DefaultReaderConfig()
if cfg.Reader.MaxMappedFiles <= 0 {
cfg.Reader.MaxMappedFiles = 10
}
if cfg.Reader.MaxMemoryBytes <= 0 {
cfg.Reader.MaxMemoryBytes = 2 * 1024 * 1024 * 1024
}
if cfg.Reader.CleanupInterval <= 0 {
cfg.Reader.CleanupInterval = 5000
}
return nil
}
// ShardDiagnostics provides detailed diagnostics for a specific shard
// Fields ordered for optimal memory alignment
type ShardDiagnostics struct {
// 8-byte aligned fields first
WriteRate float64 `json:"write_rate_per_sec"`
ErrorRate float64 `json:"error_rate_per_sec"`
TotalEntries int64 `json:"total_entries"`
TotalBytes int64 `json:"total_bytes"`
FileRotateFailures int64 `json:"file_rotate_failures"`
ConsumerLags map[string]int64 `json:"consumer_lags"`
UnhealthyReasons []string `json:"unhealthy_reasons,omitempty"`
LastError string `json:"last_error,omitempty"`
// Time fields (24 bytes each)
LastWriteTime time.Time `json:"last_write_time"`
LastErrorTime time.Time `json:"last_error_time,omitempty"`
// Smaller fields last
ShardID uint32 `json:"shard_id"`
FileCount int `json:"file_count"`
IsHealthy bool `json:"is_healthy"`
// 3 bytes padding
}
// CometStats provides runtime statistics
type CometStats struct {
// Core metrics
TotalEntries int64 `json:"total_entries"`
TotalBytes int64 `json:"total_bytes"`
TotalCompressed int64 `json:"total_compressed"`
CompressedEntries int64 `json:"compressed_entries"`
SkippedCompression int64 `json:"skipped_compression"`
FileRotations int64 `json:"file_rotations"`
CompressionWaitNano int64 `json:"compression_wait_nano"`
ConsumerGroups int `json:"consumer_groups"`
ConsumerOffsets map[string]int64 `json:"consumer_offsets"`
WriteThroughput float64 `json:"write_throughput_mbps"`
CompressionRatio float64 `json:"compression_ratio"`
OpenReaders int64 `json:"open_readers"`
MaxLag int64 `json:"max_lag"`
FileCount int `json:"file_count"`
IndexSize int64 `json:"index_size"`
UptimeSeconds int64 `json:"uptime_seconds"`
// Production diagnostics (calculated on-the-fly)
WriteErrors int64 `json:"write_errors"`
ReadErrors int64 `json:"read_errors"`
TotalErrors int64 `json:"total_errors"`
WritesTotal int64 `json:"writes_total"`
ReadsTotal int64 `json:"reads_total"`
RecoveryAttempts int64 `json:"recovery_attempts"`
RecoverySuccesses int64 `json:"recovery_successes"`
AvgWriteLatencyNs int64 `json:"avg_write_latency_ns"`
GoroutineCount int `json:"goroutine_count"`
ConsumerLags map[string]int64 `json:"consumer_lags"`
TotalFileBytes int64 `json:"total_file_bytes"`
FailedWrites int64 `json:"failed_writes"`
FailedRotations int64 `json:"failed_rotations"`
SyncCount int64 `json:"sync_count"`
ErrorRate float64 `json:"error_rate_per_sec"`
WriteRate float64 `json:"write_rate_per_sec"`
ReadRate float64 `json:"read_rate_per_sec"`
}
// ClientMetrics tracks global client metrics
type ClientMetrics struct {
// Write metrics
WritesTotal atomic.Uint64
BytesWritten atomic.Uint64
WriteErrors atomic.Uint64
WriteLatencyNanos atomic.Uint64
CompressionSaves atomic.Uint64
CompressionSkipped atomic.Uint64
// Read metrics
ReadsTotal atomic.Uint64
BytesRead atomic.Uint64
ReadErrors atomic.Uint64
ConsumerLagTotal atomic.Uint64
// File metrics
FileRotations atomic.Uint64
FilesCreated atomic.Uint64
// Additional metrics
LastErrorNano atomic.Int64
TotalEntries atomic.Uint64
FilesDeleted atomic.Uint64
CheckpointsWritten atomic.Uint64
// Process coordination metrics
ShardConflicts atomic.Uint64
LockWaitNanos atomic.Uint64
RecoveryAttempts atomic.Uint64
RecoverySuccesses atomic.Uint64
// Index persistence errors
IndexPersistErrors atomic.Uint64
ErrorCount atomic.Uint64
// Consumer metrics
AckCount atomic.Uint64
ActiveConsumers atomic.Uint64
ConsumerTimeouts atomic.Uint64
ConsumerResets atomic.Uint64
// Retention metrics
RetentionRuns atomic.Uint64
FilesCleanedUp atomic.Uint64
BytesCleanedUp atomic.Uint64
RetentionErrors atomic.Uint64
RetentionSkipped atomic.Uint64
}
var (
isFiberChild = os.Getenv("FIBER_PREFORK_CHILD")
envPreforkChildVal = "1"
)
// MultiProcessConfig returns a configuration optimized for multi-process deployments.
// It automatically acquires a unique process ID and configures the client for multi-process mode.
// The process ID is automatically released when the client is closed.
func MultiProcessConfig(sharedMemoryFile ...string) CometConfig {
// Acquire process ID
processID := GetProcessID(sharedMemoryFile...)
if processID < 0 {
panic("failed to acquire process ID - all slots may be taken")
}
// Create multi-process config
config := DeprecatedMultiProcessConfig(processID, runtime.NumCPU())
// Set the shared memory file
if len(sharedMemoryFile) > 0 && sharedMemoryFile[0] != "" {
config.Concurrency.SHMFile = sharedMemoryFile[0]
}
return config
}
// Client implements a local file-based stream client with append-only storage
type Client struct {
dataDir string
config CometConfig
logger Logger
shards map[uint32]*Shard
metrics ClientMetrics
mu sync.RWMutex
closed bool
retentionWg sync.WaitGroup
stopCh chan struct{}
startTime time.Time
sharedMemoryFile string // For automatic process ID cleanup
// Multi-process optimization: cache owned shards per shard count
ownedShardsCache sync.Map // map[uint32][]uint32 - shardCount -> owned shard IDs
}
// isShardOwnedByProcess checks if this process owns a specific shard
// isShardOwnedByProcess removed - processes always own their shards exclusively
// Shard represents a single stream shard with its own files
// Fields ordered for optimal memory alignment (64-bit words first)
type Shard struct {
// 64-bit aligned fields first (8 bytes each)
readerCount int64 // Lock-free reader tracking
// Entry number tracking - critical for consistency:
// - nextEntryNumber: Next entry number to allocate. Incremented when entries
// are assigned numbers, before they're written anywhere.
// - lastWrittenEntryNumber: Last entry that has been written to the buffered
// writer. These entries are in OS buffers but NOT yet durable.
// - index.CurrentEntryNumber: Last entry that has been synced to disk and is
// durable. Only updated after fsync. This is what consumers can safely read.
nextEntryNumber int64 // Next entry number to allocate
lastWrittenEntryNumber int64 // Last entry written to OS buffers (not durable)
pendingWriteOffset int64 // Current write offset including pending writes
lastCheckpoint int64 // Unix nanoseconds of last checkpoint
lastIndexReload int64 // Unix nanoseconds when index was last reloaded from disk
// lastMmapCheck removed - processes own their shards exclusively
// Pointers (8 bytes each on 64-bit)
dataFile *os.File // Data file handle
writer *bufio.Writer // Buffered writer
compressor *zstd.Encoder // Compression engine
index *ShardIndex // Shard metadata
offsetMmap *ConsumerOffsetMmap // Memory-mapped consumer offset storage
// Lock files removed - processes own their shards exclusively
state *CometState // Unified memory-mapped state for all metrics and coordination
logger Logger // Logger for this shard
// Strings (24 bytes: ptr + len + cap)
indexPath string // Path to index file
statePath string // Path to unified state file
stateData []byte // Memory-mapped unified state data (slice header: 24 bytes)
// Mutex (platform-specific, often 24 bytes)
mu sync.RWMutex
writeMu sync.Mutex // Protects DirectWriter from concurrent writes
indexMu sync.Mutex // Protects index file writes
// Synchronization for background operations
wg sync.WaitGroup // Tracks background goroutines
stopFlush chan struct{} // Signal to stop periodic flush
// Smaller fields last
writesSinceCheckpoint int // 8 bytes
shardID uint32 // 4 bytes
// 4 bytes padding will be added automatically for 8-byte alignment
}
// EntryIndexNode represents a node in the binary searchable index
type EntryIndexNode struct {
EntryNumber int64 `json:"entry_number"` // Entry number this node covers
Position EntryPosition `json:"position"` // Position in files
}
// BinarySearchableIndex provides O(log n) entry lookups
type BinarySearchableIndex struct {
// Sorted slice of index nodes for binary search
Nodes []EntryIndexNode `json:"nodes"`
// Interval between indexed entries (default: 1000)
IndexInterval int `json:"index_interval"`
// Maximum number of nodes to keep (0 = unlimited)
MaxNodes int `json:"max_nodes"`
}
// ShardIndex tracks files and consumer offsets
// Fixed to use entry-based addressing instead of byte offsets
// Fields ordered for optimal memory alignment
type ShardIndex struct {
// 64-bit aligned fields first (8 bytes each)
CurrentEntryNumber int64 `json:"current_entry_number"` // Entry-based tracking (not byte offsets!)
CurrentWriteOffset int64 `json:"current_write_offset"` // Still track for file management
// Maps (8 bytes pointer each)
ConsumerOffsets map[string]int64 `json:"consumer_entry_offsets"` // Consumer tracking by entry number (not bytes!)
// Composite types
BinaryIndex BinarySearchableIndex `json:"binary_index"` // Binary searchable index for O(log n) lookups
// Slices (24 bytes: ptr + len + cap)
Files []FileInfo `json:"files"` // File management
// Strings (24 bytes: ptr + len + cap)
CurrentFile string `json:"current_file"`
// Smaller fields last
BoundaryInterval int `json:"boundary_interval"` // Store boundaries every N entries (4 bytes)
}
// FileInfo represents a data file in the shard
// Fields ordered for optimal memory alignment
type FileInfo struct {
// 64-bit aligned fields first (8 bytes each)
StartOffset int64 `json:"start_offset"` // Byte offset in virtual stream
EndOffset int64 `json:"end_offset"` // Last byte offset + 1
StartEntry int64 `json:"start_entry"` // First entry number
Entries int64 `json:"entries"` // Number of entries
// Time fields (24 bytes each on 64-bit due to location pointer)
StartTime time.Time `json:"start_time"` // File creation time
EndTime time.Time `json:"end_time"` // Last write time
// String last (will use remaining space efficiently)
Path string `json:"path"`
}
// NewMultiProcessClient creates a new comet client with automatic multi-process coordination.
// It uses the default shared memory file for process ID coordination.
// The process ID is automatically released when the client is closed.
//
// Example usage:
//
// client, err := comet.NewMultiProcessClient("./data")
// if err != nil {
// log.Fatal(err)
// }
// defer client.Close() // Automatically releases process ID
func NewMultiProcessClient(dataDir string, cfg ...CometConfig) (*Client, error) {
var config CometConfig
if len(cfg) > 0 && cfg[0].Concurrency.IsMultiProcess() {
// Use the provided multi-process config
config = cfg[0]
} else {
// Create a new multi-process config
var shmFile string
if len(cfg) > 0 && cfg[0].Concurrency.SHMFile != "" {
shmFile = cfg[0].Concurrency.SHMFile
}
if shmFile == "" {
config = MultiProcessConfig()
} else {
config = MultiProcessConfig(shmFile)
}
// Copy other settings from provided config
if len(cfg) > 0 {
providedCfg := cfg[0]
config.Compression = providedCfg.Compression
config.Indexing = providedCfg.Indexing
config.Storage = providedCfg.Storage
config.Retention = providedCfg.Retention
config.Reader = providedCfg.Reader
config.Log = providedCfg.Log
}
}
client, err := NewClient(dataDir, config)
if err != nil {
// Release process ID on failure
if config.Concurrency.SHMFile != "" {
ReleaseProcessID(config.Concurrency.SHMFile)
} else {
ReleaseProcessID()
}
return nil, err
}
// Mark that this client should auto-release the process ID
client.sharedMemoryFile = config.Concurrency.SHMFile
return client, nil
}
// NewClient creates a new comet client with custom configuration
func NewClient(dataDir string, config ...CometConfig) (*Client, error) {
cfg := DefaultCometConfig()
if len(config) > 0 {
cfg = config[0]
}
if cfg.Reader.MaxMemoryBytes == 0 && cfg.Reader.CleanupInterval == 0 && cfg.Reader.MaxMappedFiles == 0 {
cfg.Reader = ReaderConfigForStorage(cfg.Storage.MaxFileSize)
}
// Validate configuration
if err := validateConfig(&cfg); err != nil {
return nil, fmt.Errorf("invalid configuration: %w", err)
}
if err := os.MkdirAll(dataDir, 0755); err != nil {
return nil, fmt.Errorf("failed to create data directory: %w", err)
}
// Create logger based on config
logger := createLogger(cfg.Log)
c := &Client{
dataDir: dataDir,
config: cfg,
logger: logger,
shards: make(map[uint32]*Shard),
stopCh: make(chan struct{}),
startTime: time.Now(),
}
// Start retention manager if configured
c.startRetentionManager()
return c, nil
}
// Append adds entries to a stream shard (append-only semantics)
func (c *Client) Append(ctx context.Context, stream string, entries [][]byte) ([]MessageID, error) {
// Extract shard from stream name (e.g., "events:v1:shard:0042" -> 42)
shardID, err := parseShardFromStream(stream)
if err != nil {
return nil, fmt.Errorf("invalid stream name %s: %w", stream, err)
}
// Check process ownership for writes
if !c.config.Concurrency.Owns(shardID) {
return nil, fmt.Errorf("shard %d is not owned by process %d (assigned to process %d)",
shardID, c.config.Concurrency.ProcessID, int(shardID%uint32(c.config.Concurrency.ProcessCount)))
}
shard, err := c.getOrCreateShard(shardID)
if err != nil {
return nil, err
}
return shard.appendEntries(entries, &c.metrics, &c.config)
}
// Len returns the number of entries in a stream shard
func (c *Client) Len(ctx context.Context, stream string) (int64, error) {
shardID, err := parseShardFromStream(stream)
if err != nil {
return 0, fmt.Errorf("invalid stream name %s: %w", stream, err)
}
shard, err := c.getOrCreateShard(shardID)
if err != nil {
return 0, err
}
// Handle potential index rebuild in multi-process mode
if shard.state != nil && shard.checkIfRebuildNeeded() {
shard.mu.Lock()
needsRebuild := shard.checkIfRebuildNeeded()
shard.mu.Unlock()
if needsRebuild {
// Call rebuild without holding the lock to avoid deadlock
shard.lazyRebuildIndexIfNeeded(c.config, filepath.Join(c.dataDir, fmt.Sprintf("shard-%04d", shard.shardID)))
}
}
// Now get the length with read lock
shard.mu.RLock()
defer shard.mu.RUnlock()
// Return nextEntryNumber which tracks all assigned entries (both flushed and pending)
return shard.nextEntryNumber, nil
}
// Sync ensures all buffered data is durably written to disk
func (c *Client) Sync(ctx context.Context) error {
c.mu.RLock()
shards := make([]*Shard, 0, len(c.shards))
for _, shard := range c.shards {
shards = append(shards, shard)
}
c.mu.RUnlock()
for _, shard := range shards {
shard.mu.Lock()
// Flush and sync writer
if shard.writer != nil {
shard.writeMu.Lock()
err := shard.writer.Flush()
if err == nil && shard.dataFile != nil {
// Track sync latency
syncStart := time.Now()
err = shard.dataFile.Sync()
if err == nil && shard.state != nil {
syncDuration := time.Since(syncStart).Nanoseconds()
atomic.AddInt64(&shard.state.SyncLatencyNanos, syncDuration)
atomic.AddUint64(&shard.state.SyncCount, 1)
}
}
shard.writeMu.Unlock()
if err != nil {
shard.mu.Unlock()
return fmt.Errorf("failed to sync shard %d: %w", shard.shardID, err)
}
}
// Update index to reflect what's now persisted to disk
// CurrentEntryNumber should match nextEntryNumber after all pending writes are flushed
shard.index.CurrentEntryNumber = shard.nextEntryNumber
// Update CurrentWriteOffset and EndOffset to match actual file sizes
// This ensures GetShardStats() returns correct TotalBytes after sync
if shard.dataFile != nil {
if stat, err := shard.dataFile.Stat(); err == nil {
actualSize := stat.Size()
shard.index.CurrentWriteOffset = actualSize
shard.pendingWriteOffset = actualSize // Sync pending offset with actual file size
// Update current file EndOffset and Entries count
if len(shard.index.Files) > 0 {
current := &shard.index.Files[len(shard.index.Files)-1]
current.EndOffset = shard.index.CurrentWriteOffset
current.EndTime = time.Now()
// Calculate actual entry count for this file
current.Entries = shard.index.CurrentEntryNumber - current.StartEntry
}
}
}
// Force checkpoint
// Update mmap state while holding the lock
shard.updateMmapState()
shard.writesSinceCheckpoint = 0
shard.lastCheckpoint = time.Now().UnixNano()
shard.mu.Unlock()
// Persist the index - this will also update metrics
if err := shard.persistIndex(); err != nil {
return fmt.Errorf("failed to persist index for shard %d: %w", shard.shardID, err)
}
}
return nil
}
// loadExistingShard loads a shard that was created by another process
// getOrCreateShard returns an existing shard or creates a new one
// getShard retrieves an existing shard without creating it if it doesn't exist.
// Returns nil if the shard doesn't exist.
func (c *Client) getShard(shardID uint32) *Shard {
c.mu.RLock()
shard := c.shards[shardID]
c.mu.RUnlock()
return shard
}
// loadExistingShard loads a shard that already exists on disk without creating it
// This is a read-only operation used by consumers - it will NOT create directories or files
func (c *Client) loadExistingShard(shardID uint32) (*Shard, error) {
// Check if already loaded
c.mu.RLock()
if shard, exists := c.shards[shardID]; exists {
c.mu.RUnlock()
return shard, nil
}
c.mu.RUnlock()
// Check if shard directory exists
shardDir := filepath.Join(c.dataDir, fmt.Sprintf("shard-%04d", shardID))
if _, err := os.Stat(shardDir); os.IsNotExist(err) {
return nil, fmt.Errorf("shard %d does not exist on disk", shardID)
}
// Load the shard
c.mu.Lock()
defer c.mu.Unlock()
// Double-check after acquiring write lock
if shard, exists := c.shards[shardID]; exists {
return shard, nil
}
shard := &Shard{
shardID: shardID,
logger: c.logger.WithFields("shard", shardID),
indexPath: filepath.Join(shardDir, "index.bin"),
statePath: filepath.Join(shardDir, "comet.state"),
stopFlush: make(chan struct{}),
index: &ShardIndex{
CurrentEntryNumber: 0,
CurrentWriteOffset: 0,
BoundaryInterval: c.config.Indexing.BoundaryInterval,
ConsumerOffsets: make(map[string]int64),
Files: make([]FileInfo, 0),
BinaryIndex: BinarySearchableIndex{
IndexInterval: c.config.Indexing.BoundaryInterval,
MaxNodes: c.config.Indexing.MaxIndexEntries,
Nodes: make([]EntryIndexNode, 0),
},
},
nextEntryNumber: 0,
pendingWriteOffset: 0,
}
// Load existing index
if err := shard.loadIndex(); err != nil {
if !os.IsNotExist(err) {
return nil, fmt.Errorf("failed to load index for shard %d: %w", shardID, err)
}
}
// Always initialize state mmap (for both single and multi-process modes)
if err := shard.initCometStateMmap(); err != nil {
return nil, fmt.Errorf("failed to initialize state mmap: %w", err)
}
// Initialize consumer offset mmap
offsetMmap, err := NewConsumerOffsetMmap(shardDir, shardID)
if err != nil {
return nil, fmt.Errorf("failed to initialize consumer offset mmap: %w", err)
}
shard.offsetMmap = offsetMmap
// Add to shards map
c.shards[shardID] = shard
if c.logger != nil {
c.logger.Debug("Loaded existing shard from disk",
"shardID", shardID,
"currentEntry", shard.index.CurrentEntryNumber)
}
return shard, nil
}
func (c *Client) getOrCreateShard(shardID uint32) (*Shard, error) {
processID := os.Getpid()
if IsDebug() && c.logger != nil {
c.logger.Debug("TRACE: getOrCreateShard entry",
"shardID", shardID,
"pid", processID)
}
c.mu.RLock()
shard, exists := c.shards[shardID]
c.mu.RUnlock()
if exists {
if c.logger != nil && IsDebug() {
c.logger.Debug("getOrCreateShard: shard already exists in memory",
"shardID", shardID,
"pid", processID)
}
return shard, nil
}
if c.logger != nil {
c.logger.Debug("getOrCreateShard: creating new shard",
"shardID", shardID,
"pid", processID)
}
// For multi-process mode, we need to ensure only one process initializes the shard
shardDir := filepath.Join(c.dataDir, fmt.Sprintf("shard-%04d", shardID))
// Check if shard already exists and detect mode mismatch
if stat, err := os.Stat(shardDir); err == nil && stat.IsDir() {
// Since we now always use state files, we don't need to check for mode mismatches
// The state file will exist for both single and multi-process modes
}
// Create shard directory if it doesn't exist
if err := os.MkdirAll(shardDir, 0755); err != nil {
return nil, fmt.Errorf("failed to create shard directory: %w", err)
}
// Since processes own their shards exclusively, no init lock needed
c.mu.Lock()
defer c.mu.Unlock()
// Double-check after acquiring write lock
if shard, exists = c.shards[shardID]; exists {
return shard, nil
}
if c.logger != nil {
c.logger.Debug("getOrCreateShard: initializing new shard",
"shardID", shardID,
"pid", processID)
}
shard = &Shard{
shardID: shardID,
logger: c.logger.WithFields("shard", shardID),
indexPath: filepath.Join(shardDir, "index.bin"),
statePath: filepath.Join(shardDir, "comet.state"),
stopFlush: make(chan struct{}),
index: &ShardIndex{
CurrentEntryNumber: 0, // Explicitly initialize to prevent garbage values
CurrentWriteOffset: 0, // Explicitly initialize to prevent garbage values
BoundaryInterval: c.config.Indexing.BoundaryInterval,
ConsumerOffsets: make(map[string]int64),
Files: make([]FileInfo, 0),
BinaryIndex: BinarySearchableIndex{
IndexInterval: c.config.Indexing.BoundaryInterval,
MaxNodes: c.config.Indexing.MaxIndexEntries, // Use full limit for binary index
Nodes: make([]EntryIndexNode, 0),
},
},
lastCheckpoint: time.Now().UnixNano(),
}
// Initialize unified state (memory-mapped in multi-process mode, in-memory otherwise)
if err := shard.initCometState(); err != nil {
return nil, fmt.Errorf("failed to initialize unified state: %w", err)
}