-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompaction.go
More file actions
323 lines (273 loc) · 7.63 KB
/
Copy pathcompaction.go
File metadata and controls
323 lines (273 loc) · 7.63 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
package storage
import (
"fmt"
"os"
"sort"
"sync"
"time"
)
type CompactionConfig struct {
// MinDirtyRatio is the minimum ratio of "dirty" (duplicate key) records
// before compaction is triggered (0.0-1.0). Default: 0.5
MinDirtyRatio float64
// MinCompactionInterval is the minimum time between compactions.
MinCompactionInterval time.Duration
// Enabled controls whether compaction runs.
Enabled bool
}
// DefaultCompactionConfig returns sensible defaults.
func DefaultCompactionConfig() CompactionConfig {
return CompactionConfig{
MinDirtyRatio: 0.5,
MinCompactionInterval: 5 * time.Minute,
Enabled: false, // Opt-in
}
}
// KeyIndex tracks the latest offset for each key.
// Used during compaction to determine which records to keep.
type KeyIndex struct {
mu sync.RWMutex
keys map[string]uint64 // key -> latest offset
offsets map[uint64]string // offset -> key (for reverse lookup)
}
func NewKeyIndex() *KeyIndex {
return &KeyIndex{
keys: make(map[string]uint64),
offsets: make(map[uint64]string),
}
}
// Update records that a key was seen at the given offset.
// Only updates if this is a newer offset for the key.
func (ki *KeyIndex) Update(key []byte, offset uint64) {
ki.mu.Lock()
defer ki.mu.Unlock()
keyStr := string(key)
if existing, ok := ki.keys[keyStr]; ok {
if offset > existing {
// Remove old offset mapping
delete(ki.offsets, existing)
ki.keys[keyStr] = offset
ki.offsets[offset] = keyStr
}
} else {
ki.keys[keyStr] = offset
ki.offsets[offset] = keyStr
}
}
// IsLatest returns true if the given offset is the latest occurrence of the key.
func (ki *KeyIndex) IsLatest(key []byte, offset uint64) bool {
ki.mu.RLock()
defer ki.mu.RUnlock()
latest, exists := ki.keys[string(key)]
if !exists {
return true // Unknown key, keep it
}
return latest == offset
}
func (ki *KeyIndex) GetLatest(key []byte) (uint64, bool) {
ki.mu.RLock()
defer ki.mu.RUnlock()
offset, ok := ki.keys[string(key)]
return offset, ok
}
// Size returns the number of unique keys.
func (ki *KeyIndex) Size() int {
ki.mu.RLock()
defer ki.mu.RUnlock()
return len(ki.keys)
}
// UniqueKeys returns all unique keys.
func (ki *KeyIndex) UniqueKeys() []string {
ki.mu.RLock()
defer ki.mu.RUnlock()
keys := make([]string, 0, len(ki.keys))
for k := range ki.keys {
keys = append(keys, k)
}
return keys
}
type CompactionStats struct {
RecordsScanned int
RecordsRetained int
RecordsRemoved int
BytesBefore uint64
BytesAfter uint64
Duration time.Duration
}
// Compactor handles log compaction for a single log.
type Compactor struct {
mu sync.Mutex
log *Log
config CompactionConfig
lastCompact time.Time
stats CompactionStats
}
func NewCompactor(log *Log, config CompactionConfig) *Compactor {
return &Compactor{
log: log,
config: config,
}
}
// ShouldCompact returns true if compaction should run.
func (c *Compactor) ShouldCompact() bool {
c.mu.Lock()
defer c.mu.Unlock()
if !c.config.Enabled {
return false
}
if time.Since(c.lastCompact) < c.config.MinCompactionInterval {
return false
}
// This is a lightweight check that just counts keys
keyIndex := NewKeyIndex()
duplicates := 0
total := 0
c.log.Scan(func(offset uint64, data []byte) error {
total++
record, err := UnmarshalRecord(data)
if err != nil || len(record.Key) == 0 {
return nil // Skip keyless records
}
if _, exists := keyIndex.GetLatest(record.Key); exists {
duplicates++
}
keyIndex.Update(record.Key, offset)
return nil
})
if total == 0 {
return false
}
dirtyRatio := float64(duplicates) / float64(total)
return dirtyRatio >= c.config.MinDirtyRatio
}
// Compact performs log compaction, retaining only the latest value per key.
// Records without keys are always retained.
func (c *Compactor) Compact() (*CompactionStats, error) {
c.mu.Lock()
defer c.mu.Unlock()
startTime := time.Now()
// Phase 1: Build key index by scanning all records
keyIndex := NewKeyIndex()
var bytesBeforeTotal uint64
err := c.log.Scan(func(offset uint64, data []byte) error {
bytesBeforeTotal += uint64(len(data))
record, err := UnmarshalRecord(data)
if err != nil || len(record.Key) == 0 {
return nil // Records without keys indexed at their offset
}
keyIndex.Update(record.Key, offset)
return nil
})
if err != nil {
return nil, fmt.Errorf("scan for key index: %w", err)
}
// Phase 2: Collect records to keep
type keepRecord struct {
offset uint64
data []byte
}
var recordsToKeep []keepRecord
recordsScanned := 0
var bytesAfter uint64
err = c.log.Scan(func(offset uint64, data []byte) error {
recordsScanned++
record, err := UnmarshalRecord(data)
if err != nil || len(record.Key) == 0 {
// Keep keyless records
recordsToKeep = append(recordsToKeep, keepRecord{offset, data})
bytesAfter += uint64(len(data))
return nil
}
// Keep only if this is the latest for the key
if keyIndex.IsLatest(record.Key, offset) {
recordsToKeep = append(recordsToKeep, keepRecord{offset, data})
bytesAfter += uint64(len(data))
}
return nil
})
if err != nil {
return nil, fmt.Errorf("scan for records to keep: %w", err)
}
sort.Slice(recordsToKeep, func(i, j int) bool {
return recordsToKeep[i].offset < recordsToKeep[j].offset
})
// Phase 3: Create new compacted log
compactedDir := c.log.Dir() + ".compacting"
if err := os.MkdirAll(compactedDir, 0755); err != nil {
return nil, fmt.Errorf("create compacted dir: %w", err)
}
compactedLog, err := NewLog(Config{
Dir: compactedDir,
MaxSegmentBytes: c.log.config.MaxSegmentBytes,
SyncWrites: c.log.config.SyncWrites,
})
if err != nil {
os.RemoveAll(compactedDir)
return nil, fmt.Errorf("create compacted log: %w", err)
}
// Records keep their original offsets so committed consumer offsets stay
// valid; gaps left by removed records start a new segment.
for _, rec := range recordsToKeep {
if _, err := compactedLog.AppendAt(rec.offset, rec.data); err != nil {
compactedLog.Close()
os.RemoveAll(compactedDir)
return nil, fmt.Errorf("write to compacted log: %w", err)
}
}
if err := compactedLog.Close(); err != nil {
os.RemoveAll(compactedDir)
return nil, fmt.Errorf("close compacted log: %w", err)
}
// Phase 4: Atomic swap
originalDir := c.log.Dir()
backupDir := originalDir + ".backup"
if err := c.log.Close(); err != nil {
os.RemoveAll(compactedDir)
return nil, fmt.Errorf("close original log: %w", err)
}
// Rename original to backup
if err := os.Rename(originalDir, backupDir); err != nil {
os.RemoveAll(compactedDir)
return nil, fmt.Errorf("backup original: %w", err)
}
// Rename compacted to original
if err := os.Rename(compactedDir, originalDir); err != nil {
// Try to restore backup
os.Rename(backupDir, originalDir)
return nil, fmt.Errorf("swap compacted: %w", err)
}
os.RemoveAll(backupDir)
// Reopen log
newLog, err := NewLog(c.log.config)
if err != nil {
return nil, fmt.Errorf("reopen log: %w", err)
}
c.log = newLog
c.lastCompact = time.Now()
stats := &CompactionStats{
RecordsScanned: recordsScanned,
RecordsRetained: len(recordsToKeep),
RecordsRemoved: recordsScanned - len(recordsToKeep),
BytesBefore: bytesBeforeTotal,
BytesAfter: bytesAfter,
Duration: time.Since(startTime),
}
c.stats = *stats
return stats, nil
}
func (c *Compactor) GetStats() CompactionStats {
c.mu.Lock()
defer c.mu.Unlock()
return c.stats
}
// SetEnabled enables or disables compaction.
func (c *Compactor) SetEnabled(enabled bool) {
c.mu.Lock()
defer c.mu.Unlock()
c.config.Enabled = enabled
}
func (c *Compactor) GetLog() *Log {
c.mu.Lock()
defer c.mu.Unlock()
return c.log
}