Line data Source code
1 : // Copyright 2023 The LevelDB-Go and Pebble Authors. All rights reserved. Use
2 : // of this source code is governed by a BSD-style license that can be found in
3 : // the LICENSE file.
4 :
5 : package pebble
6 :
7 : import (
8 : "context"
9 : "fmt"
10 : "slices"
11 :
12 : "github.com/cockroachdb/errors"
13 : "github.com/cockroachdb/pebble/internal/base"
14 : "github.com/cockroachdb/pebble/internal/invariants"
15 : "github.com/cockroachdb/pebble/internal/keyspan"
16 : "github.com/cockroachdb/pebble/internal/keyspan/keyspanimpl"
17 : "github.com/cockroachdb/pebble/internal/manifest"
18 : "github.com/cockroachdb/pebble/internal/treeprinter"
19 : "github.com/cockroachdb/pebble/objstorage"
20 : "github.com/cockroachdb/pebble/objstorage/remote"
21 : "github.com/cockroachdb/pebble/sstable"
22 : )
23 :
24 : const (
25 : // In skip-shared iteration mode, keys in levels greater than
26 : // sharedLevelsStart (i.e. lower in the LSM) are skipped. Keys
27 : // in sharedLevelsStart are returned iff they are not in a
28 : // shared file.
29 : sharedLevelsStart = remote.SharedLevelsStart
30 :
31 : // In skip-external iteration mode, keys in levels greater
32 : // than externalSkipStart are skipped. Keys in
33 : // externalSkipStart are returned iff they are not in an
34 : // external file.
35 : externalSkipStart = 6
36 : )
37 :
38 : // ErrInvalidSkipSharedIteration is returned by ScanInternal if it was called
39 : // with a shared file visitor function, and a file in a shareable level (i.e.
40 : // level >= sharedLevelsStart) was found to not be in shared storage according
41 : // to objstorage.Provider, or not shareable for another reason such as for
42 : // containing keys newer than the snapshot sequence number.
43 : var ErrInvalidSkipSharedIteration = errors.New("pebble: cannot use skip-shared iteration due to non-shareable files in lower levels")
44 :
45 : // SharedSSTMeta represents an sstable on shared storage that can be ingested
46 : // by another pebble instance. This struct must contain all fields that are
47 : // required for a Pebble instance to ingest a foreign sstable on shared storage,
48 : // including constructing any relevant objstorage.Provider / remoteobjcat.Catalog
49 : // data structures, as well as creating virtual FileMetadatas.
50 : //
51 : // Note that the Pebble instance creating and returning a SharedSSTMeta might
52 : // not be the one that created the underlying sstable on shared storage to begin
53 : // with; it's possible for a Pebble instance to reshare an sstable that was
54 : // shared to it.
55 : type SharedSSTMeta struct {
56 : // Backing is the shared object underlying this SST. Can be attached to an
57 : // objstorage.Provider.
58 : Backing objstorage.RemoteObjectBackingHandle
59 :
60 : // Smallest and Largest internal keys for the overall bounds. The kind and
61 : // SeqNum of these will reflect what is physically present on the source Pebble
62 : // instance's view of the sstable; it's up to the ingesting instance to set the
63 : // sequence number in the trailer to match the read-time sequence numbers
64 : // reserved for the level this SST is being ingested into. The Kind is expected
65 : // to remain unchanged by the ingesting instance.
66 : //
67 : // Note that these bounds could be narrower than the bounds of the underlying
68 : // sstable; ScanInternal is expected to truncate sstable bounds to the user key
69 : // bounds passed into that method.
70 : Smallest, Largest InternalKey
71 :
72 : // SmallestRangeKey and LargestRangeKey are internal keys that denote the
73 : // range key bounds of this sstable. Must lie within [Smallest, Largest].
74 : SmallestRangeKey, LargestRangeKey InternalKey
75 :
76 : // SmallestPointKey and LargestPointKey are internal keys that denote the
77 : // point key bounds of this sstable. Must lie within [Smallest, Largest].
78 : SmallestPointKey, LargestPointKey InternalKey
79 :
80 : // Level denotes the level at which this file was present at read time.
81 : // For files visited by ScanInternal, this value will only be 5 or 6.
82 : Level uint8
83 :
84 : // Size contains an estimate of the size of this sstable.
85 : Size uint64
86 :
87 : // fileNum at time of creation in the creator instance. Only used for
88 : // debugging/tests.
89 : fileNum base.FileNum
90 : }
91 :
92 2 : func (s *SharedSSTMeta) cloneFromFileMeta(f *fileMetadata) {
93 2 : *s = SharedSSTMeta{
94 2 : Smallest: f.Smallest.Clone(),
95 2 : Largest: f.Largest.Clone(),
96 2 : SmallestRangeKey: f.SmallestRangeKey.Clone(),
97 2 : LargestRangeKey: f.LargestRangeKey.Clone(),
98 2 : SmallestPointKey: f.SmallestPointKey.Clone(),
99 2 : LargestPointKey: f.LargestPointKey.Clone(),
100 2 : Size: f.Size,
101 2 : fileNum: f.FileNum,
102 2 : }
103 2 : }
104 :
105 : type sharedByLevel []SharedSSTMeta
106 :
107 2 : func (s sharedByLevel) Len() int { return len(s) }
108 0 : func (s sharedByLevel) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
109 2 : func (s sharedByLevel) Less(i, j int) bool { return s[i].Level < s[j].Level }
110 :
111 : type pcIterPos int
112 :
113 : const (
114 : pcIterPosCur pcIterPos = iota
115 : pcIterPosNext
116 : )
117 :
118 : // pointCollapsingIterator is an internalIterator that collapses point keys and
119 : // returns at most one point internal key for each user key. Merges and
120 : // SingleDels are not supported and result in a panic if encountered. Point keys
121 : // deleted by rangedels are considered shadowed and not exposed.
122 : //
123 : // Only used in ScanInternal to return at most one internal key per user key.
124 : type pointCollapsingIterator struct {
125 : iter keyspan.InterleavingIter
126 : pos pcIterPos
127 : comparer *base.Comparer
128 : merge base.Merge
129 : err error
130 : seqNum base.SeqNum
131 : // The current position of `iter`. Always owned by the underlying iter.
132 : iterKV *base.InternalKV
133 : // The last saved key. findNextEntry and similar methods are expected to save
134 : // the current value of iterKey to savedKey if they're iterating away from the
135 : // current key but still need to retain it. See comments in findNextEntry on
136 : // how this field is used.
137 : //
138 : // At the end of a positioning call:
139 : // - if pos == pcIterPosNext, iterKey is pointing to the next user key owned
140 : // by `iter` while savedKey is holding a copy to our current key.
141 : // - If pos == pcIterPosCur, iterKey is pointing to an `iter`-owned current
142 : // key, and savedKey is either undefined or pointing to a version of the
143 : // current key owned by this iterator (i.e. backed by savedKeyBuf).
144 : savedKey InternalKey
145 : savedKeyBuf []byte
146 : // If fixedSeqNum is non-zero, all emitted points are verified to have this
147 : // fixed sequence number.
148 : fixedSeqNum base.SeqNum
149 : }
150 :
151 2 : func (p *pointCollapsingIterator) Span() *keyspan.Span {
152 2 : return p.iter.Span()
153 2 : }
154 :
155 : // SeekPrefixGE implements the InternalIterator interface.
156 : func (p *pointCollapsingIterator) SeekPrefixGE(
157 : prefix, key []byte, flags base.SeekGEFlags,
158 0 : ) *base.InternalKV {
159 0 : p.resetKey()
160 0 : p.iterKV = p.iter.SeekPrefixGE(prefix, key, flags)
161 0 : p.pos = pcIterPosCur
162 0 : if p.iterKV == nil {
163 0 : return nil
164 0 : }
165 0 : return p.findNextEntry()
166 : }
167 :
168 : // SeekGE implements the InternalIterator interface.
169 2 : func (p *pointCollapsingIterator) SeekGE(key []byte, flags base.SeekGEFlags) *base.InternalKV {
170 2 : p.resetKey()
171 2 : p.iterKV = p.iter.SeekGE(key, flags)
172 2 : p.pos = pcIterPosCur
173 2 : if p.iterKV == nil {
174 2 : return nil
175 2 : }
176 2 : return p.findNextEntry()
177 : }
178 :
179 : // SeekLT implements the InternalIterator interface.
180 0 : func (p *pointCollapsingIterator) SeekLT(key []byte, flags base.SeekLTFlags) *base.InternalKV {
181 0 : panic("unimplemented")
182 : }
183 :
184 2 : func (p *pointCollapsingIterator) resetKey() {
185 2 : p.savedKey.UserKey = p.savedKeyBuf[:0]
186 2 : p.savedKey.Trailer = 0
187 2 : p.iterKV = nil
188 2 : p.pos = pcIterPosCur
189 2 : }
190 :
191 2 : func (p *pointCollapsingIterator) verifySeqNum(kv *base.InternalKV) *base.InternalKV {
192 2 : if !invariants.Enabled {
193 0 : return kv
194 0 : }
195 2 : if p.fixedSeqNum == 0 || kv == nil || kv.Kind() == InternalKeyKindRangeDelete {
196 2 : return kv
197 2 : }
198 0 : if kv.SeqNum() != p.fixedSeqNum {
199 0 : panic(fmt.Sprintf("expected foreign point key to have seqnum %d, got %d", p.fixedSeqNum, kv.SeqNum()))
200 : }
201 0 : return kv
202 : }
203 :
204 : // findNextEntry is called to return the next key. p.iter must be positioned at the
205 : // start of the first user key we are interested in.
206 2 : func (p *pointCollapsingIterator) findNextEntry() *base.InternalKV {
207 2 : p.saveKey()
208 2 : // Saves a comparison in the fast path
209 2 : firstIteration := true
210 2 : for p.iterKV != nil {
211 2 : // NB: p.savedKey is either the current key (iff p.iterKV == firstKey),
212 2 : // or the previous key.
213 2 : if !firstIteration && !p.comparer.Equal(p.iterKV.K.UserKey, p.savedKey.UserKey) {
214 2 : p.saveKey()
215 2 : continue
216 : }
217 2 : firstIteration = false
218 2 : if s := p.iter.Span(); s != nil && s.CoversAt(p.seqNum, p.iterKV.SeqNum()) {
219 2 : // All future keys for this user key must be deleted.
220 2 : if p.savedKey.Kind() == InternalKeyKindSingleDelete {
221 0 : panic("cannot process singledel key in point collapsing iterator")
222 : }
223 : // Fast forward to the next user key.
224 2 : p.saveKey()
225 2 : p.iterKV = p.iter.Next()
226 2 : for p.iterKV != nil && p.savedKey.SeqNum() >= p.iterKV.SeqNum() && p.comparer.Equal(p.iterKV.K.UserKey, p.savedKey.UserKey) {
227 2 : p.iterKV = p.iter.Next()
228 2 : }
229 2 : continue
230 : }
231 2 : switch p.savedKey.Kind() {
232 2 : case InternalKeyKindSet, InternalKeyKindDelete, InternalKeyKindSetWithDelete, InternalKeyKindDeleteSized:
233 2 : // Note that we return SETs directly, even if they would otherwise get
234 2 : // compacted into a Del to turn into a SetWithDelete. This is a fast
235 2 : // path optimization that can break SINGLEDEL determinism. To lead to
236 2 : // consistent SINGLEDEL behaviour, this iterator should *not* be used for
237 2 : // a keyspace where SINGLEDELs could be in use. If this iterator observes
238 2 : // a SINGLEDEL as the first internal key for a user key, it will panic.
239 2 : //
240 2 : // As p.value is a lazy value owned by the child iterator, we can thread
241 2 : // it through without loading it into p.valueBuf.
242 2 : //
243 2 : // TODO(bilal): We can even avoid saving the key in this fast path if
244 2 : // we are in a block where setHasSamePrefix = false in a v3 sstable,
245 2 : // guaranteeing that there's only one internal key for each user key.
246 2 : // Thread this logic through the sstable iterators and/or consider
247 2 : // collapsing (ha) this logic into the sstable iterators that are aware
248 2 : // of blocks and can determine user key changes without doing key saves
249 2 : // or comparisons.
250 2 : p.pos = pcIterPosCur
251 2 : return p.verifySeqNum(p.iterKV)
252 0 : case InternalKeyKindSingleDelete:
253 0 : // Panic, as this iterator is not expected to observe single deletes.
254 0 : panic("cannot process singledel key in point collapsing iterator")
255 0 : case InternalKeyKindMerge:
256 0 : // Panic, as this iterator is not expected to observe merges.
257 0 : panic("cannot process merge key in point collapsing iterator")
258 2 : case InternalKeyKindRangeDelete:
259 2 : // These are interleaved by the interleaving iterator ahead of all points.
260 2 : // We should pass them as-is, but also account for any points ahead of
261 2 : // them.
262 2 : p.pos = pcIterPosCur
263 2 : return p.verifySeqNum(p.iterKV)
264 0 : default:
265 0 : panic(fmt.Sprintf("unexpected kind: %d", p.iterKV.Kind()))
266 : }
267 : }
268 1 : p.resetKey()
269 1 : return nil
270 : }
271 :
272 : // First implements the InternalIterator interface.
273 1 : func (p *pointCollapsingIterator) First() *base.InternalKV {
274 1 : p.resetKey()
275 1 : p.iterKV = p.iter.First()
276 1 : p.pos = pcIterPosCur
277 1 : if p.iterKV == nil {
278 0 : return nil
279 0 : }
280 1 : return p.findNextEntry()
281 : }
282 :
283 : // Last implements the InternalIterator interface.
284 0 : func (p *pointCollapsingIterator) Last() *base.InternalKV {
285 0 : panic("unimplemented")
286 : }
287 :
288 2 : func (p *pointCollapsingIterator) saveKey() {
289 2 : if p.iterKV == nil {
290 1 : p.savedKey = InternalKey{UserKey: p.savedKeyBuf[:0]}
291 1 : return
292 1 : }
293 2 : p.savedKeyBuf = append(p.savedKeyBuf[:0], p.iterKV.K.UserKey...)
294 2 : p.savedKey = InternalKey{UserKey: p.savedKeyBuf, Trailer: p.iterKV.K.Trailer}
295 : }
296 :
297 : // Next implements the InternalIterator interface.
298 2 : func (p *pointCollapsingIterator) Next() *base.InternalKV {
299 2 : switch p.pos {
300 2 : case pcIterPosCur:
301 2 : p.saveKey()
302 2 : if p.iterKV != nil && p.iterKV.Kind() == InternalKeyKindRangeDelete {
303 2 : // Step over the interleaved range delete and process the very next
304 2 : // internal key, even if it's at the same user key. This is because a
305 2 : // point for that user key has not been returned yet.
306 2 : p.iterKV = p.iter.Next()
307 2 : break
308 : }
309 : // Fast forward to the next user key.
310 2 : kv := p.iter.Next()
311 2 : // p.iterKV.SeqNum() >= key.SeqNum() is an optimization that allows us to
312 2 : // use p.iterKV.SeqNum() < key.SeqNum() as a sign that the user key has
313 2 : // changed, without needing to do the full key comparison.
314 2 : for kv != nil && p.savedKey.SeqNum() >= kv.SeqNum() &&
315 2 : p.comparer.Equal(p.savedKey.UserKey, kv.K.UserKey) {
316 2 : kv = p.iter.Next()
317 2 : }
318 2 : if kv == nil {
319 2 : // There are no keys to return.
320 2 : p.resetKey()
321 2 : return nil
322 2 : }
323 2 : p.iterKV = kv
324 0 : case pcIterPosNext:
325 0 : p.pos = pcIterPosCur
326 : }
327 2 : if p.iterKV == nil {
328 2 : p.resetKey()
329 2 : return nil
330 2 : }
331 2 : return p.findNextEntry()
332 : }
333 :
334 : // NextPrefix implements the InternalIterator interface.
335 0 : func (p *pointCollapsingIterator) NextPrefix(succKey []byte) *base.InternalKV {
336 0 : panic("unimplemented")
337 : }
338 :
339 : // Prev implements the InternalIterator interface.
340 0 : func (p *pointCollapsingIterator) Prev() *base.InternalKV {
341 0 : panic("unimplemented")
342 : }
343 :
344 : // Error implements the InternalIterator interface.
345 2 : func (p *pointCollapsingIterator) Error() error {
346 2 : if p.err != nil {
347 0 : return p.err
348 0 : }
349 2 : return p.iter.Error()
350 : }
351 :
352 : // Close implements the InternalIterator interface.
353 2 : func (p *pointCollapsingIterator) Close() error {
354 2 : return p.iter.Close()
355 2 : }
356 :
357 : // SetBounds implements the InternalIterator interface.
358 0 : func (p *pointCollapsingIterator) SetBounds(lower, upper []byte) {
359 0 : p.resetKey()
360 0 : p.iter.SetBounds(lower, upper)
361 0 : }
362 :
363 0 : func (p *pointCollapsingIterator) SetContext(ctx context.Context) {
364 0 : p.iter.SetContext(ctx)
365 0 : }
366 :
367 : // DebugTree is part of the InternalIterator interface.
368 0 : func (p *pointCollapsingIterator) DebugTree(tp treeprinter.Node) {
369 0 : n := tp.Childf("%T(%p)", p, p)
370 0 : p.iter.DebugTree(n)
371 0 : }
372 :
373 : // String implements the InternalIterator interface.
374 0 : func (p *pointCollapsingIterator) String() string {
375 0 : return p.iter.String()
376 0 : }
377 :
378 : var _ internalIterator = &pointCollapsingIterator{}
379 :
380 : // IteratorLevelKind is used to denote whether the current ScanInternal iterator
381 : // is unknown, belongs to a flushable, or belongs to an LSM level type.
382 : type IteratorLevelKind int8
383 :
384 : const (
385 : // IteratorLevelUnknown indicates an unknown LSM level.
386 : IteratorLevelUnknown IteratorLevelKind = iota
387 : // IteratorLevelLSM indicates an LSM level.
388 : IteratorLevelLSM
389 : // IteratorLevelFlushable indicates a flushable (i.e. memtable).
390 : IteratorLevelFlushable
391 : )
392 :
393 : // IteratorLevel is used with scanInternalIterator to surface additional iterator-specific info where possible.
394 : // Note: this is struct is only provided for point keys.
395 : type IteratorLevel struct {
396 : Kind IteratorLevelKind
397 : // FlushableIndex indicates the position within the flushable queue of this level.
398 : // Only valid if kind == IteratorLevelFlushable.
399 : FlushableIndex int
400 : // The level within the LSM. Only valid if Kind == IteratorLevelLSM.
401 : Level int
402 : // Sublevel is only valid if Kind == IteratorLevelLSM and Level == 0.
403 : Sublevel int
404 : }
405 :
406 : // scanInternalIterator is an iterator that returns all internal keys, including
407 : // tombstones. For instance, an InternalKeyKindDelete would be returned as an
408 : // InternalKeyKindDelete instead of the iterator skipping over to the next key.
409 : // Internal keys within a user key are collapsed, eg. if there are two SETs, the
410 : // one with the higher sequence is returned. Useful if an external user of Pebble
411 : // needs to observe and rebuild Pebble's history of internal keys, such as in
412 : // node-to-node replication. For use with {db,snapshot}.ScanInternal().
413 : //
414 : // scanInternalIterator is expected to ignore point keys deleted by range
415 : // deletions, and range keys shadowed by a range key unset or delete, however it
416 : // *must* return the range delete as well as the range key unset/delete that did
417 : // the shadowing.
418 : type scanInternalIterator struct {
419 : ctx context.Context
420 : db *DB
421 : opts scanInternalOptions
422 : comparer *base.Comparer
423 : merge Merge
424 : iter internalIterator
425 : readState *readState
426 : version *version
427 : rangeKey *iteratorRangeKeyState
428 : pointKeyIter internalIterator
429 : iterKV *base.InternalKV
430 : alloc *iterAlloc
431 : newIters tableNewIters
432 : newIterRangeKey keyspanimpl.TableNewSpanIter
433 : seqNum base.SeqNum
434 : iterLevels []IteratorLevel
435 : mergingIter *mergingIter
436 :
437 : // boundsBuf holds two buffers used to store the lower and upper bounds.
438 : // Whenever the InternalIterator's bounds change, the new bounds are copied
439 : // into boundsBuf[boundsBufIdx]. The two bounds share a slice to reduce
440 : // allocations. opts.LowerBound and opts.UpperBound point into this slice.
441 : boundsBuf [2][]byte
442 : boundsBufIdx int
443 : }
444 :
445 : // truncateExternalFile truncates an External file's [SmallestUserKey,
446 : // LargestUserKey] fields to [lower, upper). A ExternalFile is
447 : // produced that is suitable for external consumption by other Pebble
448 : // instances.
449 : //
450 : // truncateSharedFile reads the file to try to create the smallest
451 : // possible bounds. Here, we blindly truncate them. This may mean we
452 : // include this SST in iterations it isn't really needed in. Since we
453 : // don't expect External files to be long-lived in the pebble
454 : // instance, We think this is OK.
455 : //
456 : // TODO(ssd) 2024-01-26: Potentially de-duplicate with
457 : // truncateSharedFile.
458 : func (d *DB) truncateExternalFile(
459 : ctx context.Context,
460 : lower, upper []byte,
461 : level int,
462 : file *fileMetadata,
463 : objMeta objstorage.ObjectMetadata,
464 1 : ) (*ExternalFile, error) {
465 1 : cmp := d.cmp
466 1 : sst := &ExternalFile{
467 1 : Level: uint8(level),
468 1 : ObjName: objMeta.Remote.CustomObjectName,
469 1 : Locator: objMeta.Remote.Locator,
470 1 : HasPointKey: file.HasPointKeys,
471 1 : HasRangeKey: file.HasRangeKeys,
472 1 : Size: file.Size,
473 1 : SyntheticPrefix: slices.Clone(file.SyntheticPrefixAndSuffix.Prefix()),
474 1 : SyntheticSuffix: slices.Clone(file.SyntheticPrefixAndSuffix.Suffix()),
475 1 : }
476 1 :
477 1 : needsLowerTruncate := cmp(lower, file.Smallest.UserKey) > 0
478 1 : if needsLowerTruncate {
479 1 : sst.StartKey = slices.Clone(lower)
480 1 : } else {
481 1 : sst.StartKey = slices.Clone(file.Smallest.UserKey)
482 1 : }
483 :
484 1 : cmpUpper := cmp(upper, file.Largest.UserKey)
485 1 : needsUpperTruncate := cmpUpper < 0
486 1 : if needsUpperTruncate {
487 0 : sst.EndKey = slices.Clone(upper)
488 0 : sst.EndKeyIsInclusive = false
489 1 : } else {
490 1 : sst.EndKey = slices.Clone(file.Largest.UserKey)
491 1 : sst.EndKeyIsInclusive = !file.Largest.IsExclusiveSentinel()
492 1 : }
493 :
494 1 : if cmp(sst.StartKey, sst.EndKey) > 0 {
495 0 : return nil, base.AssertionFailedf("pebble: invalid external file bounds after truncation [%q, %q)", sst.StartKey, sst.EndKey)
496 0 : }
497 :
498 1 : if cmp(sst.StartKey, sst.EndKey) == 0 && !sst.EndKeyIsInclusive {
499 0 : return nil, base.AssertionFailedf("pebble: invalid external file bounds after truncation [%q, %q)", sst.StartKey, sst.EndKey)
500 0 : }
501 :
502 1 : return sst, nil
503 : }
504 :
505 : // truncateSharedFile truncates a shared file's [Smallest, Largest] fields to
506 : // [lower, upper), potentially opening iterators on the file to find keys within
507 : // the requested bounds. A SharedSSTMeta is produced that is suitable for
508 : // external consumption by other Pebble instances. If shouldSkip is true, this
509 : // file does not contain any keys in [lower, upper) and can be skipped.
510 : //
511 : // TODO(bilal): If opening iterators and doing reads in this method is too
512 : // inefficient, consider producing non-tight file bounds instead.
513 : func (d *DB) truncateSharedFile(
514 : ctx context.Context,
515 : lower, upper []byte,
516 : level int,
517 : file *fileMetadata,
518 : objMeta objstorage.ObjectMetadata,
519 2 : ) (sst *SharedSSTMeta, shouldSkip bool, err error) {
520 2 : cmp := d.cmp
521 2 : sst = &SharedSSTMeta{}
522 2 : sst.cloneFromFileMeta(file)
523 2 : sst.Level = uint8(level)
524 2 : sst.Backing, err = d.objProvider.RemoteObjectBacking(&objMeta)
525 2 : if err != nil {
526 0 : return nil, false, err
527 0 : }
528 2 : needsLowerTruncate := cmp(lower, file.Smallest.UserKey) > 0
529 2 : needsUpperTruncate := cmp(upper, file.Largest.UserKey) < 0 || (cmp(upper, file.Largest.UserKey) == 0 && !file.Largest.IsExclusiveSentinel())
530 2 : // Fast path: file is entirely within [lower, upper).
531 2 : if !needsLowerTruncate && !needsUpperTruncate {
532 2 : return sst, false, nil
533 2 : }
534 :
535 : // We will need to truncate file bounds in at least one direction. Open all
536 : // relevant iterators.
537 2 : iters, err := d.newIters(ctx, file, &IterOptions{
538 2 : LowerBound: lower,
539 2 : UpperBound: upper,
540 2 : layer: manifest.Level(level),
541 2 : }, internalIterOpts{}, iterPointKeys|iterRangeDeletions|iterRangeKeys)
542 2 : if err != nil {
543 0 : return nil, false, err
544 0 : }
545 2 : defer iters.CloseAll()
546 2 : iter := iters.point
547 2 : rangeDelIter := iters.rangeDeletion
548 2 : rangeKeyIter := iters.rangeKey
549 2 : if rangeDelIter != nil {
550 2 : rangeDelIter = keyspan.Truncate(cmp, rangeDelIter, base.UserKeyBoundsEndExclusive(lower, upper))
551 2 : }
552 2 : if rangeKeyIter != nil {
553 2 : rangeKeyIter = keyspan.Truncate(cmp, rangeKeyIter, base.UserKeyBoundsEndExclusive(lower, upper))
554 2 : }
555 : // Check if we need to truncate on the left side. This means finding a new
556 : // LargestPointKey and LargestRangeKey that is >= lower.
557 2 : if needsLowerTruncate {
558 2 : sst.SmallestPointKey.UserKey = sst.SmallestPointKey.UserKey[:0]
559 2 : sst.SmallestPointKey.Trailer = 0
560 2 : kv := iter.SeekGE(lower, base.SeekGEFlagsNone)
561 2 : foundPointKey := kv != nil
562 2 : if kv != nil {
563 2 : sst.SmallestPointKey.CopyFrom(kv.K)
564 2 : }
565 2 : if rangeDelIter != nil {
566 2 : if span, err := rangeDelIter.SeekGE(lower); err != nil {
567 0 : return nil, false, err
568 2 : } else if span != nil && (len(sst.SmallestPointKey.UserKey) == 0 || base.InternalCompare(cmp, span.SmallestKey(), sst.SmallestPointKey) < 0) {
569 2 : sst.SmallestPointKey.CopyFrom(span.SmallestKey())
570 2 : foundPointKey = true
571 2 : }
572 : }
573 2 : if !foundPointKey {
574 2 : // There are no point keys in the span we're interested in.
575 2 : sst.SmallestPointKey = InternalKey{}
576 2 : sst.LargestPointKey = InternalKey{}
577 2 : }
578 2 : sst.SmallestRangeKey.UserKey = sst.SmallestRangeKey.UserKey[:0]
579 2 : sst.SmallestRangeKey.Trailer = 0
580 2 : if rangeKeyIter != nil {
581 2 : span, err := rangeKeyIter.SeekGE(lower)
582 2 : switch {
583 0 : case err != nil:
584 0 : return nil, false, err
585 2 : case span != nil:
586 2 : sst.SmallestRangeKey.CopyFrom(span.SmallestKey())
587 2 : default:
588 2 : // There are no range keys in the span we're interested in.
589 2 : sst.SmallestRangeKey = InternalKey{}
590 2 : sst.LargestRangeKey = InternalKey{}
591 : }
592 : }
593 : }
594 : // Check if we need to truncate on the right side. This means finding a new
595 : // LargestPointKey and LargestRangeKey that is < upper.
596 2 : if needsUpperTruncate {
597 2 : sst.LargestPointKey.UserKey = sst.LargestPointKey.UserKey[:0]
598 2 : sst.LargestPointKey.Trailer = 0
599 2 : kv := iter.SeekLT(upper, base.SeekLTFlagsNone)
600 2 : foundPointKey := kv != nil
601 2 : if kv != nil {
602 2 : sst.LargestPointKey.CopyFrom(kv.K)
603 2 : }
604 2 : if rangeDelIter != nil {
605 2 : if span, err := rangeDelIter.SeekLT(upper); err != nil {
606 0 : return nil, false, err
607 2 : } else if span != nil && (len(sst.LargestPointKey.UserKey) == 0 || base.InternalCompare(cmp, span.LargestKey(), sst.LargestPointKey) > 0) {
608 2 : sst.LargestPointKey.CopyFrom(span.LargestKey())
609 2 : foundPointKey = true
610 2 : }
611 : }
612 2 : if !foundPointKey {
613 2 : // There are no point keys in the span we're interested in.
614 2 : sst.SmallestPointKey = InternalKey{}
615 2 : sst.LargestPointKey = InternalKey{}
616 2 : }
617 2 : sst.LargestRangeKey.UserKey = sst.LargestRangeKey.UserKey[:0]
618 2 : sst.LargestRangeKey.Trailer = 0
619 2 : if rangeKeyIter != nil {
620 2 : span, err := rangeKeyIter.SeekLT(upper)
621 2 : switch {
622 0 : case err != nil:
623 0 : return nil, false, err
624 2 : case span != nil:
625 2 : sst.LargestRangeKey.CopyFrom(span.LargestKey())
626 2 : default:
627 2 : // There are no range keys in the span we're interested in.
628 2 : sst.SmallestRangeKey = InternalKey{}
629 2 : sst.LargestRangeKey = InternalKey{}
630 : }
631 : }
632 : }
633 : // Set overall bounds based on {Smallest,Largest}{Point,Range}Key.
634 2 : switch {
635 2 : case len(sst.SmallestRangeKey.UserKey) == 0:
636 2 : sst.Smallest = sst.SmallestPointKey
637 2 : case len(sst.SmallestPointKey.UserKey) == 0:
638 2 : sst.Smallest = sst.SmallestRangeKey
639 2 : default:
640 2 : sst.Smallest = sst.SmallestPointKey
641 2 : if base.InternalCompare(cmp, sst.SmallestRangeKey, sst.SmallestPointKey) < 0 {
642 2 : sst.Smallest = sst.SmallestRangeKey
643 2 : }
644 : }
645 2 : switch {
646 2 : case len(sst.LargestRangeKey.UserKey) == 0:
647 2 : sst.Largest = sst.LargestPointKey
648 2 : case len(sst.LargestPointKey.UserKey) == 0:
649 2 : sst.Largest = sst.LargestRangeKey
650 2 : default:
651 2 : sst.Largest = sst.LargestPointKey
652 2 : if base.InternalCompare(cmp, sst.LargestRangeKey, sst.LargestPointKey) > 0 {
653 2 : sst.Largest = sst.LargestRangeKey
654 2 : }
655 : }
656 : // On rare occasion, a file might overlap with [lower, upper) but not actually
657 : // have any keys within those bounds. Skip such files.
658 2 : if len(sst.Smallest.UserKey) == 0 {
659 2 : return nil, true, nil
660 2 : }
661 2 : sst.Size, err = d.fileCache.estimateSize(file, sst.Smallest.UserKey, sst.Largest.UserKey)
662 2 : if err != nil {
663 0 : return nil, false, err
664 0 : }
665 : // On occasion, estimateSize gives us a low estimate, i.e. a 0 file size. This
666 : // can cause panics in places where we divide by file sizes. Correct for it
667 : // here.
668 2 : if sst.Size == 0 {
669 2 : sst.Size = 1
670 2 : }
671 2 : return sst, false, nil
672 : }
673 :
674 : func scanInternalImpl(
675 : ctx context.Context, lower, upper []byte, iter *scanInternalIterator, opts *scanInternalOptions,
676 2 : ) error {
677 2 : if opts.visitSharedFile != nil && (lower == nil || upper == nil) {
678 0 : panic("lower and upper bounds must be specified in skip-shared iteration mode")
679 : }
680 2 : if opts.visitSharedFile != nil && opts.visitExternalFile != nil {
681 0 : return base.AssertionFailedf("cannot provide both a shared-file and external-file visitor")
682 0 : }
683 :
684 : // Before starting iteration, check if any files in levels sharedLevelsStart
685 : // and below are *not* shared. Error out if that is the case, as skip-shared
686 : // iteration will not produce a consistent point-in-time view of this range
687 : // of keys. For files that are shared, call visitSharedFile with a truncated
688 : // version of that file.
689 2 : cmp := iter.comparer.Compare
690 2 : provider := iter.db.ObjProvider()
691 2 : seqNum := iter.seqNum
692 2 : current := iter.version
693 2 : if current == nil {
694 2 : current = iter.readState.current
695 2 : }
696 :
697 2 : if opts.visitSharedFile != nil || opts.visitExternalFile != nil {
698 2 : if provider == nil {
699 0 : panic("expected non-nil Provider in skip-shared iteration mode")
700 : }
701 :
702 2 : firstLevelWithRemote := opts.skipLevelForOpts()
703 2 : for level := firstLevelWithRemote; level < numLevels; level++ {
704 2 : files := current.Levels[level].Iter()
705 2 : for f := files.SeekGE(cmp, lower); f != nil && cmp(f.Smallest.UserKey, upper) < 0; f = files.Next() {
706 2 : if cmp(lower, f.Largest.UserKey) == 0 && f.Largest.IsExclusiveSentinel() {
707 0 : continue
708 : }
709 :
710 2 : var objMeta objstorage.ObjectMetadata
711 2 : var err error
712 2 : objMeta, err = provider.Lookup(fileTypeTable, f.FileBacking.DiskFileNum)
713 2 : if err != nil {
714 0 : return err
715 0 : }
716 :
717 : // We allow a mix of files at the first level.
718 2 : if level != firstLevelWithRemote {
719 2 : if !objMeta.IsShared() && !objMeta.IsExternal() {
720 0 : return errors.Wrapf(ErrInvalidSkipSharedIteration, "file %s is not shared or external", objMeta.DiskFileNum)
721 0 : }
722 : }
723 :
724 2 : if objMeta.IsShared() && opts.visitSharedFile == nil {
725 0 : return errors.Wrapf(ErrInvalidSkipSharedIteration, "shared file is present but no shared file visitor is defined")
726 0 : }
727 :
728 2 : if objMeta.IsExternal() && opts.visitExternalFile == nil {
729 1 : return errors.Wrapf(ErrInvalidSkipSharedIteration, "external file is present but no external file visitor is defined")
730 1 : }
731 :
732 2 : if !base.Visible(f.LargestSeqNum, seqNum, base.SeqNumMax) {
733 1 : return errors.Wrapf(ErrInvalidSkipSharedIteration, "file %s contains keys newer than snapshot", objMeta.DiskFileNum)
734 1 : }
735 :
736 2 : if level != firstLevelWithRemote && (!objMeta.IsShared() && !objMeta.IsExternal()) {
737 0 : return errors.Wrapf(ErrInvalidSkipSharedIteration, "file %s is not shared or external", objMeta.DiskFileNum)
738 0 : }
739 :
740 2 : if objMeta.IsShared() {
741 2 : var sst *SharedSSTMeta
742 2 : var skip bool
743 2 : sst, skip, err = iter.db.truncateSharedFile(ctx, lower, upper, level, f, objMeta)
744 2 : if err != nil {
745 0 : return err
746 0 : }
747 2 : if skip {
748 2 : continue
749 : }
750 2 : if err = opts.visitSharedFile(sst); err != nil {
751 0 : return err
752 0 : }
753 1 : } else if objMeta.IsExternal() {
754 1 : sst, err := iter.db.truncateExternalFile(ctx, lower, upper, level, f, objMeta)
755 1 : if err != nil {
756 0 : return err
757 0 : }
758 1 : if err := opts.visitExternalFile(sst); err != nil {
759 0 : return err
760 0 : }
761 : }
762 :
763 : }
764 : }
765 : }
766 :
767 2 : for valid := iter.seekGE(lower); valid && iter.error() == nil; valid = iter.next() {
768 2 : key := iter.unsafeKey()
769 2 :
770 2 : if opts.rateLimitFunc != nil {
771 0 : if err := opts.rateLimitFunc(key, iter.lazyValue()); err != nil {
772 0 : return err
773 0 : }
774 : }
775 :
776 2 : switch key.Kind() {
777 2 : case InternalKeyKindRangeKeyDelete, InternalKeyKindRangeKeyUnset, InternalKeyKindRangeKeySet:
778 2 : if opts.visitRangeKey != nil {
779 2 : span := iter.unsafeSpan()
780 2 : // NB: The caller isn't interested in the sequence numbers of these
781 2 : // range keys. Rather, the caller wants them to be in trailer order
782 2 : // _after_ zeroing of sequence numbers. Copy span.Keys, sort it, and then
783 2 : // call visitRangeKey.
784 2 : keysCopy := make([]keyspan.Key, len(span.Keys))
785 2 : for i := range span.Keys {
786 2 : keysCopy[i].CopyFrom(span.Keys[i])
787 2 : keysCopy[i].Trailer = base.MakeTrailer(0, span.Keys[i].Kind())
788 2 : }
789 2 : keyspan.SortKeysByTrailer(keysCopy)
790 2 : if err := opts.visitRangeKey(span.Start, span.End, keysCopy); err != nil {
791 0 : return err
792 0 : }
793 : }
794 2 : case InternalKeyKindRangeDelete:
795 2 : if opts.visitRangeDel != nil {
796 2 : rangeDel := iter.unsafeRangeDel()
797 2 : if err := opts.visitRangeDel(rangeDel.Start, rangeDel.End, rangeDel.LargestSeqNum()); err != nil {
798 0 : return err
799 0 : }
800 : }
801 2 : default:
802 2 : if opts.visitPointKey != nil {
803 2 : var info IteratorLevel
804 2 : if len(iter.mergingIter.heap.items) > 0 {
805 2 : mergingIterIdx := iter.mergingIter.heap.items[0].index
806 2 : info = iter.iterLevels[mergingIterIdx]
807 2 : } else {
808 0 : info = IteratorLevel{Kind: IteratorLevelUnknown}
809 0 : }
810 2 : val := iter.lazyValue()
811 2 : if err := opts.visitPointKey(key, val, info); err != nil {
812 0 : return err
813 0 : }
814 : }
815 : }
816 : }
817 :
818 2 : return nil
819 : }
820 :
821 2 : func (opts *scanInternalOptions) skipLevelForOpts() int {
822 2 : if opts.visitSharedFile != nil {
823 2 : return sharedLevelsStart
824 2 : }
825 1 : if opts.visitExternalFile != nil {
826 1 : return externalSkipStart
827 1 : }
828 1 : return numLevels
829 : }
830 :
831 : // constructPointIter constructs a merging iterator and sets i.iter to it.
832 : func (i *scanInternalIterator) constructPointIter(
833 : category sstable.Category, memtables flushableList, buf *iterAlloc,
834 2 : ) error {
835 2 : // Merging levels and levels from iterAlloc.
836 2 : mlevels := buf.mlevels[:0]
837 2 : levels := buf.levels[:0]
838 2 :
839 2 : // We compute the number of levels needed ahead of time and reallocate a slice if
840 2 : // the array from the iterAlloc isn't large enough. Doing this allocation once
841 2 : // should improve the performance.
842 2 : numMergingLevels := len(memtables)
843 2 : numLevelIters := 0
844 2 :
845 2 : current := i.version
846 2 : if current == nil {
847 2 : current = i.readState.current
848 2 : }
849 2 : numMergingLevels += len(current.L0SublevelFiles)
850 2 : numLevelIters += len(current.L0SublevelFiles)
851 2 :
852 2 : skipStart := i.opts.skipLevelForOpts()
853 2 : for level := 1; level < len(current.Levels); level++ {
854 2 : if current.Levels[level].Empty() {
855 2 : continue
856 : }
857 2 : if level > skipStart {
858 2 : continue
859 : }
860 2 : numMergingLevels++
861 2 : numLevelIters++
862 : }
863 :
864 2 : if numMergingLevels > cap(mlevels) {
865 1 : mlevels = make([]mergingIterLevel, 0, numMergingLevels)
866 1 : }
867 2 : if numLevelIters > cap(levels) {
868 1 : levels = make([]levelIter, 0, numLevelIters)
869 1 : }
870 : // TODO(bilal): Push these into the iterAlloc buf.
871 2 : var rangeDelMiter keyspanimpl.MergingIter
872 2 : rangeDelIters := make([]keyspan.FragmentIterator, 0, numMergingLevels)
873 2 : rangeDelLevels := make([]keyspanimpl.LevelIter, 0, numLevelIters)
874 2 :
875 2 : i.iterLevels = make([]IteratorLevel, numMergingLevels)
876 2 : mlevelsIndex := 0
877 2 :
878 2 : // Next are the memtables.
879 2 : for j := len(memtables) - 1; j >= 0; j-- {
880 2 : mem := memtables[j]
881 2 : mlevels = append(mlevels, mergingIterLevel{
882 2 : iter: mem.newIter(&i.opts.IterOptions),
883 2 : })
884 2 : i.iterLevels[mlevelsIndex] = IteratorLevel{
885 2 : Kind: IteratorLevelFlushable,
886 2 : FlushableIndex: j,
887 2 : }
888 2 : mlevelsIndex++
889 2 : if rdi := mem.newRangeDelIter(&i.opts.IterOptions); rdi != nil {
890 2 : rangeDelIters = append(rangeDelIters, rdi)
891 2 : }
892 : }
893 :
894 : // Next are the file levels: L0 sub-levels followed by lower levels.
895 2 : levelsIndex := len(levels)
896 2 : mlevels = mlevels[:numMergingLevels]
897 2 : levels = levels[:numLevelIters]
898 2 : rangeDelLevels = rangeDelLevels[:numLevelIters]
899 2 : i.opts.IterOptions.snapshotForHideObsoletePoints = i.seqNum
900 2 : i.opts.IterOptions.Category = category
901 2 : addLevelIterForFiles := func(files manifest.LevelIterator, level manifest.Layer) {
902 2 : li := &levels[levelsIndex]
903 2 : rli := &rangeDelLevels[levelsIndex]
904 2 :
905 2 : li.init(
906 2 : i.ctx, i.opts.IterOptions, i.comparer, i.newIters, files, level,
907 2 : internalIterOpts{})
908 2 : mlevels[mlevelsIndex].iter = li
909 2 : rli.Init(i.ctx, keyspan.SpanIterOptions{RangeKeyFilters: i.opts.RangeKeyFilters},
910 2 : i.comparer.Compare, tableNewRangeDelIter(i.newIters), files, level,
911 2 : manifest.KeyTypePoint)
912 2 : rangeDelIters = append(rangeDelIters, rli)
913 2 :
914 2 : levelsIndex++
915 2 : mlevelsIndex++
916 2 : }
917 :
918 2 : for j := len(current.L0SublevelFiles) - 1; j >= 0; j-- {
919 2 : i.iterLevels[mlevelsIndex] = IteratorLevel{
920 2 : Kind: IteratorLevelLSM,
921 2 : Level: 0,
922 2 : Sublevel: j,
923 2 : }
924 2 : addLevelIterForFiles(current.L0SublevelFiles[j].Iter(), manifest.L0Sublevel(j))
925 2 : }
926 : // Add level iterators for the non-empty non-L0 levels.
927 2 : for level := 1; level < numLevels; level++ {
928 2 : if current.Levels[level].Empty() {
929 2 : continue
930 : }
931 :
932 2 : if level > skipStart {
933 2 : continue
934 : }
935 2 : i.iterLevels[mlevelsIndex] = IteratorLevel{Kind: IteratorLevelLSM, Level: level}
936 2 : levIter := current.Levels[level].Iter()
937 2 : if level == skipStart {
938 2 : nonRemoteFiles := make([]*manifest.FileMetadata, 0)
939 2 : for f := levIter.First(); f != nil; f = levIter.Next() {
940 2 : meta, err := i.db.objProvider.Lookup(fileTypeTable, f.FileBacking.DiskFileNum)
941 2 : if err != nil {
942 0 : return err
943 0 : }
944 2 : if (meta.IsShared() && i.opts.visitSharedFile != nil) ||
945 2 : (meta.IsExternal() && i.opts.visitExternalFile != nil) {
946 2 : // Skip this file.
947 2 : continue
948 : }
949 1 : nonRemoteFiles = append(nonRemoteFiles, f)
950 : }
951 2 : levSlice := manifest.NewLevelSliceKeySorted(i.db.cmp, nonRemoteFiles)
952 2 : levIter = levSlice.Iter()
953 : }
954 :
955 2 : addLevelIterForFiles(levIter, manifest.Level(level))
956 : }
957 :
958 2 : buf.merging.init(&i.opts.IterOptions, &InternalIteratorStats{}, i.comparer.Compare, i.comparer.Split, mlevels...)
959 2 : buf.merging.snapshot = i.seqNum
960 2 : rangeDelMiter.Init(i.comparer, keyspan.VisibleTransform(i.seqNum), new(keyspanimpl.MergingBuffers), rangeDelIters...)
961 2 :
962 2 : if i.opts.includeObsoleteKeys {
963 1 : iiter := &keyspan.InterleavingIter{}
964 1 : iiter.Init(i.comparer, &buf.merging, &rangeDelMiter,
965 1 : keyspan.InterleavingIterOpts{
966 1 : LowerBound: i.opts.LowerBound,
967 1 : UpperBound: i.opts.UpperBound,
968 1 : })
969 1 : i.pointKeyIter = iiter
970 2 : } else {
971 2 : pcIter := &pointCollapsingIterator{
972 2 : comparer: i.comparer,
973 2 : merge: i.merge,
974 2 : seqNum: i.seqNum,
975 2 : }
976 2 : pcIter.iter.Init(i.comparer, &buf.merging, &rangeDelMiter, keyspan.InterleavingIterOpts{
977 2 : LowerBound: i.opts.LowerBound,
978 2 : UpperBound: i.opts.UpperBound,
979 2 : })
980 2 : i.pointKeyIter = pcIter
981 2 : }
982 2 : i.iter = i.pointKeyIter
983 2 : return nil
984 : }
985 :
986 : // constructRangeKeyIter constructs the range-key iterator stack, populating
987 : // i.rangeKey.rangeKeyIter with the resulting iterator. This is similar to
988 : // Iterator.constructRangeKeyIter, except it doesn't handle batches and ensures
989 : // iterConfig does *not* elide unsets/deletes.
990 2 : func (i *scanInternalIterator) constructRangeKeyIter() error {
991 2 : // We want the bounded iter from iterConfig, but not the collapsing of
992 2 : // RangeKeyUnsets and RangeKeyDels.
993 2 : i.rangeKey.rangeKeyIter = i.rangeKey.iterConfig.Init(
994 2 : i.comparer, i.seqNum, i.opts.LowerBound, i.opts.UpperBound,
995 2 : nil /* hasPrefix */, nil /* prefix */, true, /* internalKeys */
996 2 : &i.rangeKey.rangeKeyBuffers.internal)
997 2 :
998 2 : // Next are the flushables: memtables and large batches.
999 2 : if i.readState != nil {
1000 2 : for j := len(i.readState.memtables) - 1; j >= 0; j-- {
1001 2 : mem := i.readState.memtables[j]
1002 2 : // We only need to read from memtables which contain sequence numbers older
1003 2 : // than seqNum.
1004 2 : if logSeqNum := mem.logSeqNum; logSeqNum >= i.seqNum {
1005 2 : continue
1006 : }
1007 2 : if rki := mem.newRangeKeyIter(&i.opts.IterOptions); rki != nil {
1008 2 : i.rangeKey.iterConfig.AddLevel(rki)
1009 2 : }
1010 : }
1011 : }
1012 :
1013 2 : current := i.version
1014 2 : if current == nil {
1015 2 : current = i.readState.current
1016 2 : }
1017 : // Next are the file levels: L0 sub-levels followed by lower levels.
1018 : //
1019 : // Add file-specific iterators for L0 files containing range keys. This is less
1020 : // efficient than using levelIters for sublevels of L0 files containing
1021 : // range keys, but range keys are expected to be sparse anyway, reducing the
1022 : // cost benefit of maintaining a separate L0Sublevels instance for range key
1023 : // files and then using it here.
1024 : //
1025 : // NB: We iterate L0's files in reverse order. They're sorted by
1026 : // LargestSeqNum ascending, and we need to add them to the merging iterator
1027 : // in LargestSeqNum descending to preserve the merging iterator's invariants
1028 : // around Key InternalKeyTrailer order.
1029 2 : iter := current.RangeKeyLevels[0].Iter()
1030 2 : for f := iter.Last(); f != nil; f = iter.Prev() {
1031 2 : spanIter, err := i.newIterRangeKey(i.ctx, f, i.opts.SpanIterOptions())
1032 2 : if err != nil {
1033 0 : return err
1034 0 : }
1035 2 : i.rangeKey.iterConfig.AddLevel(spanIter)
1036 : }
1037 : // Add level iterators for the non-empty non-L0 levels.
1038 2 : skipStart := i.opts.skipLevelForOpts()
1039 2 : for level := 1; level < len(current.RangeKeyLevels); level++ {
1040 2 : if current.RangeKeyLevels[level].Empty() {
1041 2 : continue
1042 : }
1043 2 : if level > skipStart {
1044 2 : continue
1045 : }
1046 2 : li := i.rangeKey.iterConfig.NewLevelIter()
1047 2 : spanIterOpts := i.opts.SpanIterOptions()
1048 2 : levIter := current.RangeKeyLevels[level].Iter()
1049 2 : if level == skipStart {
1050 2 : nonRemoteFiles := make([]*manifest.FileMetadata, 0)
1051 2 : for f := levIter.First(); f != nil; f = levIter.Next() {
1052 2 : meta, err := i.db.objProvider.Lookup(fileTypeTable, f.FileBacking.DiskFileNum)
1053 2 : if err != nil {
1054 0 : return err
1055 0 : }
1056 2 : if (meta.IsShared() && i.opts.visitSharedFile != nil) ||
1057 2 : (meta.IsExternal() && i.opts.visitExternalFile != nil) {
1058 2 : // Skip this file.
1059 2 : continue
1060 : }
1061 0 : nonRemoteFiles = append(nonRemoteFiles, f)
1062 : }
1063 2 : levSlice := manifest.NewLevelSliceKeySorted(i.db.cmp, nonRemoteFiles)
1064 2 : levIter = levSlice.Iter()
1065 : }
1066 2 : li.Init(i.ctx, spanIterOpts, i.comparer.Compare, i.newIterRangeKey, levIter,
1067 2 : manifest.Level(level), manifest.KeyTypeRange)
1068 2 : i.rangeKey.iterConfig.AddLevel(li)
1069 : }
1070 2 : return nil
1071 : }
1072 :
1073 : // seekGE seeks this iterator to the first key that's greater than or equal
1074 : // to the specified user key.
1075 2 : func (i *scanInternalIterator) seekGE(key []byte) bool {
1076 2 : i.iterKV = i.iter.SeekGE(key, base.SeekGEFlagsNone)
1077 2 : return i.iterKV != nil
1078 2 : }
1079 :
1080 : // unsafeKey returns the unsafe InternalKey at the current position. The value
1081 : // is nil if the iterator is invalid or exhausted.
1082 2 : func (i *scanInternalIterator) unsafeKey() *InternalKey {
1083 2 : return &i.iterKV.K
1084 2 : }
1085 :
1086 : // lazyValue returns a value pointer to the value at the current iterator
1087 : // position. Behaviour undefined if unsafeKey() returns a Range key or Rangedel
1088 : // kind key.
1089 2 : func (i *scanInternalIterator) lazyValue() LazyValue {
1090 2 : return i.iterKV.V
1091 2 : }
1092 :
1093 : // unsafeRangeDel returns a range key span. Behaviour undefined if UnsafeKey returns
1094 : // a non-rangedel kind.
1095 2 : func (i *scanInternalIterator) unsafeRangeDel() *keyspan.Span {
1096 2 : type spanInternalIterator interface {
1097 2 : Span() *keyspan.Span
1098 2 : }
1099 2 : return i.pointKeyIter.(spanInternalIterator).Span()
1100 2 : }
1101 :
1102 : // unsafeSpan returns a range key span. Behaviour undefined if UnsafeKey returns
1103 : // a non-rangekey type.
1104 2 : func (i *scanInternalIterator) unsafeSpan() *keyspan.Span {
1105 2 : return i.rangeKey.iiter.Span()
1106 2 : }
1107 :
1108 : // next advances the iterator in the forward direction, and returns the
1109 : // iterator's new validity state.
1110 2 : func (i *scanInternalIterator) next() bool {
1111 2 : i.iterKV = i.iter.Next()
1112 2 : return i.iterKV != nil
1113 2 : }
1114 :
1115 : // error returns an error from the internal iterator, if there's any.
1116 2 : func (i *scanInternalIterator) error() error {
1117 2 : return i.iter.Error()
1118 2 : }
1119 :
1120 : // close closes this iterator, and releases any pooled objects.
1121 2 : func (i *scanInternalIterator) close() error {
1122 2 : if err := i.iter.Close(); err != nil {
1123 0 : return err
1124 0 : }
1125 2 : if i.readState != nil {
1126 2 : i.readState.unref()
1127 2 : }
1128 2 : if i.version != nil {
1129 1 : i.version.Unref()
1130 1 : }
1131 2 : if i.rangeKey != nil {
1132 2 : i.rangeKey.PrepareForReuse()
1133 2 : *i.rangeKey = iteratorRangeKeyState{
1134 2 : rangeKeyBuffers: i.rangeKey.rangeKeyBuffers,
1135 2 : }
1136 2 : iterRangeKeyStateAllocPool.Put(i.rangeKey)
1137 2 : i.rangeKey = nil
1138 2 : }
1139 2 : if alloc := i.alloc; alloc != nil {
1140 2 : for j := range i.boundsBuf {
1141 2 : if cap(i.boundsBuf[j]) >= maxKeyBufCacheSize {
1142 0 : alloc.boundsBuf[j] = nil
1143 2 : } else {
1144 2 : alloc.boundsBuf[j] = i.boundsBuf[j]
1145 2 : }
1146 : }
1147 2 : *alloc = iterAlloc{
1148 2 : keyBuf: alloc.keyBuf[:0],
1149 2 : boundsBuf: alloc.boundsBuf,
1150 2 : prefixOrFullSeekKey: alloc.prefixOrFullSeekKey[:0],
1151 2 : }
1152 2 : iterAllocPool.Put(alloc)
1153 2 : i.alloc = nil
1154 : }
1155 2 : return nil
1156 : }
1157 :
1158 2 : func (i *scanInternalIterator) initializeBoundBufs(lower, upper []byte) {
1159 2 : buf := i.boundsBuf[i.boundsBufIdx][:0]
1160 2 : if lower != nil {
1161 2 : buf = append(buf, lower...)
1162 2 : i.opts.LowerBound = buf
1163 2 : } else {
1164 1 : i.opts.LowerBound = nil
1165 1 : }
1166 2 : if upper != nil {
1167 2 : buf = append(buf, upper...)
1168 2 : i.opts.UpperBound = buf[len(buf)-len(upper):]
1169 2 : } else {
1170 1 : i.opts.UpperBound = nil
1171 1 : }
1172 2 : i.boundsBuf[i.boundsBufIdx] = buf
1173 2 : i.boundsBufIdx = 1 - i.boundsBufIdx
1174 : }
|