-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiterator.go
More file actions
376 lines (332 loc) · 10 KB
/
iterator.go
File metadata and controls
376 lines (332 loc) · 10 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
package blobcache
import (
"errors"
"fmt"
"github.com/cockroachdb/pebble"
"github.com/miretskiy/blobcache/internal/index"
"github.com/miretskiy/dio/align"
)
// Iterator provides ordered iteration over cache entries using the global
// Pebble key index. Keys are yielded in user key order (lexicographic).
// Only live entries — present in the RAM index and not deleted — are visible.
//
// Concurrent writes, evictions, and compactions do not affect the iterator's
// view (Pebble snapshot isolation), though newly written keys may not be
// visible and evicted keys are filtered out via RAM index liveness checks.
//
// Must call Close() when done to release the Pebble snapshot.
type Iterator struct {
cache *Cache
snap *pebble.Snapshot
iter *pebble.Iterator
// Current position.
key []byte // current user key (copy)
hash Key // current 128-bit hash (decoded from value)
item index.Item // resolved by filterAndSet(), used by View()
valid bool
err error
// Read-ahead prefetch buffer — reused across View() calls.
// When the iterator detects sequential on-disk layout (next item
// contiguous in the same segment), it over-reads by readAheadFor()
// bytes so subsequent View() calls serve from the buffer.
prefetch BufferHandle // aligned buffer (or nil)
prefetchSeg uint32 // segment the buffer covers
prefetchOff int64 // start offset in segment
prefetchEnd int64 // end offset (prefetchOff + valid bytes)
// Stats for debugging and testing read-ahead effectiveness.
Stats IteratorStats
}
// IteratorStats tracks read-ahead effectiveness.
type IteratorStats struct {
PrefetchHits int64 // View() served from prefetch buffer
PrefetchMisses int64 // View() required a disk read
ReadAheadBytes int64 // total extra bytes read for prefetch
}
// NewIterator creates an iterator over all live keys in [lower, upper).
// Both bounds may be nil for unbounded iteration.
func (c *Cache) NewIterator(lower, upper []byte) (*Iterator, error) {
if c.keyIndex == nil {
return nil, errors.New("key index not available")
}
snap, iter, err := c.keyIndex.NewSnapshotIter(lower, upper)
if err != nil {
return nil, err
}
return &Iterator{
cache: c,
snap: snap,
iter: iter,
}, nil
}
// First positions the iterator at the first live key.
func (it *Iterator) First() bool {
if it.err != nil {
return false
}
if !it.iter.First() {
it.valid = false
it.err = it.iter.Error()
return false
}
return it.filterAndSet()
}
// Next advances the iterator to the next live key.
func (it *Iterator) Next() bool {
if it.err != nil {
return false
}
if !it.iter.Next() {
it.valid = false
it.err = it.iter.Error()
return false
}
return it.filterAndSet()
}
// SeekGE positions the iterator at the first live key >= target.
func (it *Iterator) SeekGE(target []byte) bool {
if it.err != nil {
return false
}
if !it.iter.SeekGE(it.cache.keyIndex.EncodeSeekKey(target)) {
it.valid = false
it.err = it.iter.Error()
return false
}
return it.filterAndSet()
}
// filterAndSet checks the current Pebble position against the RAM index
// for liveness. Skips dead/evicted keys by advancing the iterator.
func (it *Iterator) filterAndSet() bool {
for {
val, valErr := it.iter.ValueAndErr()
if valErr != nil {
it.valid = false
it.err = valErr
return false
}
userKey, h, ok := it.cache.keyIndex.DecodeEntry(it.iter.Key(), val)
if !ok {
// Corrupt entry — skip.
if !it.iter.Next() {
it.valid = false
it.err = it.iter.Error()
return false
}
continue
}
// Check RAM index for liveness.
item, found := it.cache.index.Get(h)
if found && !item.IsDeleted() {
it.key = userKey
it.hash = h
it.item = item
it.valid = true
return true
}
// Dead or evicted — advance.
if !it.iter.Next() {
it.valid = false
it.err = it.iter.Error()
return false
}
}
}
// View provides scoped access to the current entry's blob data.
// The data slice is valid only for the duration of fn.
// Returns false if the blob is no longer accessible (e.g., evicted between
// positioning and read).
//
// Unlike Cache.View(), this uses the index.Item already resolved by
// filterAndSet() — bypassing the bloom filter and index lookup (~200ns
// savings per key). When blobs are contiguous on disk, it reads ahead
// to serve subsequent calls from the prefetch buffer.
func (it *Iterator) View(fn func(data []byte)) bool {
if !it.valid {
return false
}
// 1. Try prefetch buffer hit.
if it.tryPrefetchHit(fn) {
it.Stats.PrefetchHits++
return true
}
it.Stats.PrefetchMisses++
// 2. Determine read-ahead from next entry.
// Always read enough to fully cover the next item so that the next
// View() call can be served from the prefetch buffer.
readExtra := 0
if nextItem, ok := it.peekNextItem(); ok {
if nextItem.SegmentID == it.item.SegmentID &&
nextItem.Offset == it.item.Offset+it.item.PhysicalLen {
// Cover the next item completely, plus adaptive read-ahead
// past it for the item after that.
nextLen := int(nextItem.PhysicalLen)
readExtra = nextLen + readAheadFor(nextLen)
}
}
// 3. Read from disk with optional read-ahead.
it.Stats.ReadAheadBytes += int64(readExtra)
return it.readAndServe(fn, readExtra)
}
// tryPrefetchHit checks if the current item's bytes are in the prefetch
// buffer. On hit, parses the record and calls fn. Returns false on miss.
func (it *Iterator) tryPrefetchHit(fn func(data []byte)) bool {
if it.prefetch.Bytes() == nil {
return false
}
if it.item.SegmentID != it.prefetchSeg {
return false
}
itemOff := int64(it.item.Offset)
itemEnd := itemOff + int64(it.item.PhysicalLen)
if itemOff < it.prefetchOff || itemEnd > it.prefetchEnd {
return false
}
// Hit — parse record from buffer.
buf := it.prefetch.Bytes()
lead := int(itemOff - it.prefetchOff)
rec := buf[lead : lead+int(it.item.PhysicalLen)]
verifyKey := it.key
if it.cache.TrustHash {
verifyKey = nil
}
// Pass no-op releaser: the prefetch buffer is owned by the iterator,
// not the caller. For compressed data, parseRecord allocates a
// separate decompression buffer with its own releaser.
data, rel, err := it.cache.archivist.parseRecord(
rec, it.item, verifyKey, Releaser{}, func() {})
if err != nil {
return false
}
defer rel.Release()
fn(data)
return true
}
// peekNextItem looks at the next Pebble entry and resolves its index.Item
// without advancing the iterator position. Returns false if there is no
// next entry or the next entry is dead/evicted.
func (it *Iterator) peekNextItem() (index.Item, bool) {
if !it.iter.Next() {
return index.Item{}, false
}
defer func() { it.iter.Prev() }()
val, valErr := it.iter.ValueAndErr()
if valErr != nil {
return index.Item{}, false
}
_, h, ok := it.cache.keyIndex.DecodeEntry(it.iter.Key(), val)
if !ok {
return index.Item{}, false
}
next, found := it.cache.index.Get(h)
if !found || next.IsDeleted() {
return index.Item{}, false
}
return next, true
}
// readAndServe reads the current item from disk with optional read-ahead,
// parses the record, calls fn, and stashes excess bytes in the prefetch
// buffer for subsequent View() calls.
func (it *Iterator) readAndServe(fn func(data []byte), readExtra int) bool {
a := it.cache.archivist
segID := it.item.SegmentID
// Hold segment lock during the I/O to prevent deletion mid-read.
shard := it.cache.index.SegmentLockShard(segID)
shard.RLock()
sf, err := a.getSegmentFile(segID)
if err != nil {
shard.RUnlock()
return false // TOCTOU: segment drained/compacted.
}
blobOff := int64(it.item.Offset)
blobLen := int(it.item.PhysicalLen)
readLen := blobLen + readExtra
var readOff int64
if a.IO.DirectIORead {
alignedOff, alignedLen := align.AlignRange(blobOff, readLen)
it.releasePrefetch()
it.prefetch = AcquireAlignedBuffer(int(alignedLen), int(alignedLen))
readOff = alignedOff
} else {
it.releasePrefetch()
it.prefetch = AcquireBuffer(readLen, readLen)
readOff = blobOff
}
buf := it.prefetch.Bytes()
n, err := a.sched.ReadAt(sf, buf, readOff)
shard.RUnlock()
// Verify we read enough for the current record.
lead := int(blobOff - readOff)
if err != nil || n < lead+blobLen {
it.releasePrefetch()
return false
}
// Update prefetch tracking (read-ahead bytes may be partial at EOF).
it.prefetchSeg = segID
it.prefetchOff = readOff
it.prefetchEnd = readOff + int64(n)
// Parse the record.
rec := buf[lead : lead+blobLen]
verifyKey := it.key
if it.cache.TrustHash {
verifyKey = nil
}
data, rel, err := a.parseRecord(rec, it.item, verifyKey, Releaser{}, func() {})
if err != nil {
it.err = fmt.Errorf("iterator read: %w", err)
return false
}
defer rel.Release()
fn(data)
return true
}
// releasePrefetch releases the prefetch buffer and resets tracking state.
func (it *Iterator) releasePrefetch() {
it.prefetch.Release()
it.prefetch = BufferHandle{}
it.prefetchSeg = 0
it.prefetchOff = 0
it.prefetchEnd = 0
}
// readAheadFor returns adaptive read-ahead bytes based on current blob size.
// Scales linearly with blob size (next blob is likely similar size), with a
// 64KB floor and 1MB cap.
func readAheadFor(blobSize int) int {
const (
minReadAhead = 64 << 10 // 64KB floor
maxReadAhead = 1 << 20 // 1MB cap
)
return max(minReadAhead, min(blobSize, maxReadAhead))
}
// Key returns the current user key. Only valid when Valid() returns true.
func (it *Iterator) Key() []byte {
return it.key
}
// HashKey returns the 128-bit hash of the current key.
func (it *Iterator) HashKey() Key {
return it.hash
}
// Valid returns true if the iterator is positioned at a valid entry.
func (it *Iterator) Valid() bool {
return it.valid
}
// Error returns any error encountered during iteration.
func (it *Iterator) Error() error {
return it.err
}
// Close releases the prefetch buffer, Pebble iterator, and snapshot.
func (it *Iterator) Close() error {
it.releasePrefetch()
var errs []error
if it.iter != nil {
if err := it.iter.Close(); err != nil {
errs = append(errs, err)
}
}
if it.snap != nil {
if err := it.snap.Close(); err != nil {
errs = append(errs, err)
}
}
it.valid = false
return errors.Join(errs...)
}