-
Notifications
You must be signed in to change notification settings - Fork 402
/
iterator.go
787 lines (691 loc) · 21.1 KB
/
iterator.go
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
// Copyright (C) 2020 Storj Labs, Inc.
// See LICENSE for copying information.
package metabase
import (
"bytes"
"context"
"strings"
"cloud.google.com/go/spanner"
"github.com/zeebo/errs"
"storj.io/common/uuid"
"storj.io/storj/shared/tagsql"
)
// objectIterator enables iteration on objects in a bucket.
type objectsIterator struct {
adapter Adapter
projectID uuid.UUID
bucketName []byte
pending bool
prefix ObjectKey
prefixLimit ObjectKey
batchSize int
recursive bool
includeCustomMetadata bool
includeSystemMetadata bool
curIndex int
curRows tagsql.Rows
cursor ObjectsIteratorCursor // not relative to prefix
skipPrefix ObjectKey // relative to prefix
doNextQuery func(context.Context, *objectsIterator) (_ tagsql.Rows, err error)
// failErr is set when either scan or next query fails during iteration.
failErr error
}
// ObjectsIteratorCursor is the current location in an objects iterator.
type ObjectsIteratorCursor struct {
Key ObjectKey
Version Version
StreamID uuid.UUID
Inclusive bool
}
func iterateAllVersionsWithStatusDescending(ctx context.Context, adapter Adapter, opts IterateObjectsWithStatus, fn func(context.Context, ObjectsIterator) error) (err error) {
defer mon.Task()(&ctx)(&err)
it := &objectsIterator{
adapter: adapter,
projectID: opts.ProjectID,
bucketName: []byte(opts.BucketName),
pending: opts.Pending,
prefix: opts.Prefix,
prefixLimit: PrefixLimit(opts.Prefix),
batchSize: opts.BatchSize,
recursive: opts.Recursive,
includeCustomMetadata: opts.IncludeCustomMetadata,
includeSystemMetadata: opts.IncludeSystemMetadata,
curIndex: 0,
cursor: FirstIterateCursor(opts.Recursive, opts.Cursor, opts.Prefix),
doNextQuery: adapter.doNextQueryAllVersionsWithStatus,
}
// start from either the cursor or prefix, depending on which is larger
if LessObjectKey(it.cursor.Key, opts.Prefix) {
it.cursor.Key = opts.Prefix
it.cursor.Version = MaxVersion
it.cursor.Inclusive = true // TODO: we probably won't need this `Inclusive` handling, if we specify MaxVersion already
}
return iterate(ctx, it, fn)
}
func iterateAllVersionsWithStatusAscending(ctx context.Context, adapter Adapter, opts IterateObjectsWithStatus, fn func(context.Context, ObjectsIterator) error) (err error) {
defer mon.Task()(&ctx)(&err)
it := &objectsIterator{
adapter: adapter,
projectID: opts.ProjectID,
bucketName: []byte(opts.BucketName),
pending: opts.Pending,
prefix: opts.Prefix,
prefixLimit: PrefixLimit(opts.Prefix),
batchSize: opts.BatchSize,
recursive: opts.Recursive,
includeCustomMetadata: opts.IncludeCustomMetadata,
includeSystemMetadata: opts.IncludeSystemMetadata,
curIndex: 0,
cursor: FirstIterateCursor(opts.Recursive, opts.Cursor, opts.Prefix),
doNextQuery: adapter.doNextQueryAllVersionsWithStatusAscending,
}
// start from either the cursor or prefix, depending on which is larger
if LessObjectKey(it.cursor.Key, opts.Prefix) {
it.cursor.Key = opts.Prefix
it.cursor.Version = -1
it.cursor.Inclusive = true
}
return iterate(ctx, it, fn)
}
func iteratePendingObjectsByKey(ctx context.Context, adapter Adapter, opts IteratePendingObjectsByKey, fn func(context.Context, ObjectsIterator) error) (err error) {
defer mon.Task()(&ctx)(&err)
it := &objectsIterator{
adapter: adapter,
projectID: opts.ProjectID,
bucketName: []byte(opts.BucketName),
prefix: "",
prefixLimit: "",
batchSize: opts.BatchSize,
recursive: true,
includeCustomMetadata: true,
includeSystemMetadata: true,
pending: true,
curIndex: 0,
cursor: ObjectsIteratorCursor{
Key: opts.ObjectKey,
Version: MaxVersion, // TODO: this needs to come as an argument
StreamID: opts.Cursor.StreamID,
},
doNextQuery: adapter.doNextQueryPendingObjectsByKey,
}
return iterate(ctx, it, fn)
}
func iterate(ctx context.Context, it *objectsIterator, fn func(context.Context, ObjectsIterator) error) (err error) {
batchsizeLimit.Ensure(&it.batchSize)
it.curRows, err = it.doNextQuery(ctx, it)
if err != nil {
return err
}
it.cursor.Inclusive = false
defer func() {
if rowsErr := it.curRows.Err(); rowsErr != nil {
err = errs.Combine(err, rowsErr)
}
err = errs.Combine(err, it.failErr, it.curRows.Close())
}()
return fn(ctx, it)
}
// Next returns true if there was another item and copy it in item.
func (it *objectsIterator) Next(ctx context.Context, item *ObjectEntry) bool {
if it.recursive {
return it.next(ctx, item)
}
// TODO: implement this on the database side
// skip until we are past the prefix we returned before.
if it.skipPrefix != "" {
for strings.HasPrefix(string(item.ObjectKey), string(it.skipPrefix)) {
if !it.next(ctx, item) {
return false
}
}
it.skipPrefix = ""
} else {
ok := it.next(ctx, item)
if !ok {
return false
}
}
// should this be treated as a prefix?
p := strings.IndexByte(string(item.ObjectKey), Delimiter)
if p >= 0 {
it.skipPrefix = item.ObjectKey[:p+1]
*item = ObjectEntry{
IsPrefix: true,
ObjectKey: item.ObjectKey[:p+1],
Status: Prefix,
}
}
return true
}
// next returns true if there was another item and copy it in item.
func (it *objectsIterator) next(ctx context.Context, item *ObjectEntry) bool {
next := it.curRows.Next()
if !next {
if it.curIndex < it.batchSize {
return false
}
if it.curRows.Err() != nil {
return false
}
if !it.recursive {
afterPrefix := it.cursor.Key[len(it.prefix):]
p := bytes.IndexByte([]byte(afterPrefix), Delimiter)
if p >= 0 {
it.cursor.Key = it.prefix + PrefixLimit(afterPrefix[:p+1])
it.cursor.StreamID = uuid.UUID{}
it.cursor.Version = MaxVersion
}
}
rows, err := it.doNextQuery(ctx, it)
if err != nil {
it.failErr = errs.Combine(it.failErr, err)
return false
}
if closeErr := it.curRows.Close(); closeErr != nil {
it.failErr = errs.Combine(it.failErr, closeErr, rows.Close())
return false
}
it.curRows = rows
it.curIndex = 0
if !it.curRows.Next() {
return false
}
}
err := it.scanItem(item)
if err != nil {
it.failErr = errs.Combine(it.failErr, err)
return false
}
it.curIndex++
it.cursor.Key = it.prefix + item.ObjectKey
it.cursor.Version = item.Version
it.cursor.StreamID = item.StreamID
return true
}
func (p *PostgresAdapter) doNextQueryAllVersionsWithStatus(ctx context.Context, it *objectsIterator) (_ tagsql.Rows, err error) {
defer mon.Task()(&ctx)(&err)
cursorCompare := ">"
if it.cursor.Inclusive {
cursorCompare = ">="
}
statusFilter := `AND status <> ` + statusPending
if it.pending {
statusFilter = `AND status = ` + statusPending
}
if it.prefixLimit == "" {
querySelectFields := querySelectorFields("object_key", it)
return p.db.QueryContext(ctx, `
SELECT
`+querySelectFields+`
FROM objects
WHERE
(
(project_id, bucket_name, object_key) `+cursorCompare+` ($1, $2, $3)
OR (
(project_id, bucket_name, object_key) = ($1, $2, $3)
AND $4::INT8 `+cursorCompare+` version
)
)
AND (project_id, bucket_name) < ($1, $6)
`+statusFilter+`
AND (expires_at IS NULL OR expires_at > now())
ORDER BY project_id ASC, bucket_name ASC, object_key ASC, version DESC
LIMIT $5
`, it.projectID, it.bucketName,
[]byte(it.cursor.Key), int(it.cursor.Version),
it.batchSize,
nextBucket(it.bucketName),
)
}
fromSubstring := 1
if it.prefix != "" {
fromSubstring = len(it.prefix) + 1
}
querySelectFields := querySelectorFields("SUBSTRING(object_key FROM $7)", it)
return p.db.QueryContext(ctx, `
SELECT
`+querySelectFields+`
FROM objects
WHERE
(
(project_id, bucket_name, object_key) `+cursorCompare+` ($1, $2, $3)
OR (
(project_id, bucket_name, object_key) = ($1, $2, $3)
AND $4::INT8 `+cursorCompare+` version
)
)
AND (project_id, bucket_name, object_key) < ($1, $2, $5)
`+statusFilter+`
AND (expires_at IS NULL OR expires_at > now())
ORDER BY project_id ASC, bucket_name ASC, object_key ASC, version DESC
LIMIT $6
`, it.projectID, it.bucketName,
[]byte(it.cursor.Key), int(it.cursor.Version),
[]byte(it.prefixLimit),
it.batchSize,
fromSubstring,
)
}
func (s *SpannerAdapter) doNextQueryAllVersionsWithStatus(ctx context.Context, it *objectsIterator) (_ tagsql.Rows, err error) {
defer mon.Task()(&ctx)(&err)
cursorCompare := ">"
if it.cursor.Inclusive {
cursorCompare = ">="
}
statusFilter := `AND status <> ` + statusPending
if it.pending {
statusFilter = `AND status = ` + statusPending
}
if it.prefixLimit == "" {
querySelectFields := querySelectorFields("object_key", it)
rowIterator := s.client.Single().Query(ctx, spanner.Statement{
SQL: `
SELECT
` + querySelectFields + `
FROM objects
WHERE
project_id = @project_id
AND ` + TupleGreaterThanSQL([]string{"bucket_name", "object_key", "@cursor_version"}, []string{"@bucket_name", "@cursor_key", "version"}, it.cursor.Inclusive) + `
AND bucket_name < @next_bucket
` + statusFilter + `
AND (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)
ORDER BY project_id ASC, bucket_name ASC, object_key ASC, version DESC
LIMIT @batch_size
`,
Params: map[string]any{
"project_id": it.projectID,
"bucket_name": string(it.bucketName),
"cursor_key": []byte(it.cursor.Key),
"cursor_version": it.cursor.Version,
"batch_size": int64(it.batchSize),
"next_bucket": string(nextBucket(it.bucketName)),
},
})
return newSpannerRows(rowIterator), nil
}
fromSubstring := 1
if it.prefix != "" {
fromSubstring = len(it.prefix) + 1
}
querySelectFields := querySelectorFields("SUBSTR(object_key, @from_substring)", it)
rowIterator := s.client.Single().Query(ctx, spanner.Statement{
SQL: `
SELECT
` + querySelectFields + `
FROM objects
WHERE
project_id = @project_id
AND bucket_name = @bucket_name
AND (
object_key > @cursor_key
OR (object_key = @cursor_key AND @cursor_version ` + cursorCompare + ` version)
)
AND object_key < @prefix_limit
` + statusFilter + `
AND (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)
ORDER BY project_id ASC, bucket_name ASC, object_key ASC, version DESC
LIMIT @batch_size
`,
Params: map[string]any{
"project_id": it.projectID,
"bucket_name": string(it.bucketName),
"cursor_key": []byte(it.cursor.Key),
"cursor_version": it.cursor.Version,
"prefix_limit": []byte(it.prefixLimit),
"batch_size": int64(it.batchSize),
"from_substring": int64(fromSubstring),
},
})
return newSpannerRows(rowIterator), nil
}
func (p *PostgresAdapter) doNextQueryAllVersionsWithStatusAscending(ctx context.Context, it *objectsIterator) (_ tagsql.Rows, err error) {
defer mon.Task()(&ctx)(&err)
cursorCompare := ">"
if it.cursor.Inclusive {
cursorCompare = ">="
}
statusFilter := `AND status <> ` + statusPending
if it.pending {
statusFilter = `AND status = ` + statusPending
}
if it.prefixLimit == "" {
querySelectFields := querySelectorFields("object_key", it)
return p.db.QueryContext(ctx, `
SELECT
`+querySelectFields+`
FROM objects
WHERE
(project_id, bucket_name, object_key, version) `+cursorCompare+` ($1, $2, $3, $4)
AND (project_id, bucket_name) < ($1, $6)
`+statusFilter+`
AND (expires_at IS NULL OR expires_at > now())
ORDER BY (project_id, bucket_name, object_key, version) ASC
LIMIT $5
`, it.projectID, it.bucketName,
[]byte(it.cursor.Key), int(it.cursor.Version),
it.batchSize,
nextBucket(it.bucketName),
)
}
fromSubstring := 1
if it.prefix != "" {
fromSubstring = len(it.prefix) + 1
}
querySelectFields := querySelectorFields("SUBSTRING(object_key FROM $7)", it)
return p.db.QueryContext(ctx, `
SELECT
`+querySelectFields+`
FROM objects
WHERE
(project_id, bucket_name, object_key, version) `+cursorCompare+` ($1, $2, $3, $4)
AND (project_id, bucket_name, object_key) < ($1, $2, $5)
`+statusFilter+`
AND (expires_at IS NULL OR expires_at > now())
ORDER BY (project_id, bucket_name, object_key, version) ASC
LIMIT $6
`, it.projectID, it.bucketName,
[]byte(it.cursor.Key), int(it.cursor.Version),
[]byte(it.prefixLimit),
it.batchSize,
fromSubstring,
)
}
func (s *SpannerAdapter) doNextQueryAllVersionsWithStatusAscending(ctx context.Context, it *objectsIterator) (_ tagsql.Rows, err error) {
defer mon.Task()(&ctx)(&err)
cursorCompare := ">"
if it.cursor.Inclusive {
cursorCompare = ">="
}
statusFilter := `AND status <> ` + statusPending
if it.pending {
statusFilter = `AND status = ` + statusPending
}
if it.prefixLimit == "" {
querySelectFields := querySelectorFields("object_key", it)
rowIterator := s.client.Single().Query(ctx, spanner.Statement{
SQL: `
SELECT
` + querySelectFields + `
FROM objects
WHERE
project_id = @project_id
AND ` + TupleGreaterThanSQL([]string{"bucket_name", "object_key", "version"}, []string{"@bucket_name", "@cursor_key", "@cursor_version"}, it.cursor.Inclusive) + `
AND bucket_name < @next_bucket
` + statusFilter + `
AND (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)
ORDER BY project_id ASC, bucket_name ASC, object_key ASC, version ASC
LIMIT @batch_size
`,
Params: map[string]any{
"project_id": it.projectID,
"bucket_name": string(it.bucketName),
"cursor_key": []byte(it.cursor.Key),
"cursor_version": int64(it.cursor.Version),
"batch_size": int64(it.batchSize),
"next_bucket": string(nextBucket(it.bucketName)),
},
})
return newSpannerRows(rowIterator), nil
}
fromSubstring := 1
if it.prefix != "" {
fromSubstring = len(it.prefix) + 1
}
querySelectFields := querySelectorFields("SUBSTR(object_key, @from_substring)", it)
rowIterator := s.client.Single().Query(ctx, spanner.Statement{
SQL: `
SELECT
` + querySelectFields + `
FROM objects
WHERE
project_id = @project_id
AND bucket_name = @bucket_name
AND (
(object_key > @cursor_key)
OR (object_key = @cursor_key AND version ` + cursorCompare + ` @cursor_version)
)
AND object_key < @prefix_limit
` + statusFilter + `
AND (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)
ORDER BY project_id ASC, bucket_name ASC, object_key ASC, version ASC
LIMIT @batch_size
`,
Params: map[string]any{
"project_id": it.projectID,
"bucket_name": string(it.bucketName),
"cursor_key": []byte(it.cursor.Key),
"cursor_version": int64(it.cursor.Version),
"prefix_limit": []byte(it.prefixLimit),
"batch_size": int64(it.batchSize),
"from_substring": int64(fromSubstring),
},
})
return newSpannerRows(rowIterator), nil
}
// TupleGreaterThanSQL returns a constructed SQL expression equivalent to a
// tuple comparison (e.g. (tup1[0], tup1[1], ...) > (tup2[0], tup2[1], ...)).
//
// If orEqual is true, the returned expression will compare the tuples as
// "greater than or equal" (>=) instead of "greater than" (>).
//
// This is necessary because Spanner does not support comparison of tuples,
// except with equality (=).
//
// Example:
//
// (a, b, c) >= (d, e, f)
//
// becomes
//
// TupleGreaterThanSQL([]string{"a", "b", "c"}, []string{"d", "e", "f"}, true)
//
// which returns
//
// "((a > d) OR (a = d AND b > e) OR (a = d AND b = e AND c >= f))"
func TupleGreaterThanSQL(tup1, tup2 []string, orEqual bool) string {
if len(tup1) != len(tup2) {
panic("programming error: comparing tuples of different lengths")
}
if len(tup1) == 0 {
panic("programming error: comparing tuples of zero length")
}
comparator := " > "
if orEqual {
comparator = " >= "
}
var sb strings.Builder
if len(tup1) > 1 {
sb.WriteString("(")
}
for i := range tup1 {
sb.WriteString("(")
for j := 0; j < i; j++ {
sb.WriteString(tup1[j])
sb.WriteString(" = ")
sb.WriteString(tup2[j])
sb.WriteString(" AND ")
}
sb.WriteString(tup1[i])
if i == len(tup1)-1 {
sb.WriteString(comparator)
} else {
sb.WriteString(" > ")
}
sb.WriteString(tup2[i])
sb.WriteString(")")
if i < len(tup1)-1 {
sb.WriteString(" OR ")
}
}
if len(tup1) > 1 {
sb.WriteString(")")
}
return sb.String()
}
func querySelectorFields(objectKeyColumn string, it *objectsIterator) string {
querySelectFields := objectKeyColumn + `
,stream_id
,version
,status
,encryption`
if it.includeSystemMetadata {
querySelectFields += `
,created_at
,expires_at
,segment_count
,total_plain_size
,total_encrypted_size
,fixed_segment_size`
}
if it.includeCustomMetadata {
querySelectFields += `
,encrypted_metadata_nonce
,encrypted_metadata
,encrypted_metadata_encrypted_key`
}
return querySelectFields
}
// nextBucket returns the lexicographically next bucket.
func nextBucket(b []byte) []byte {
xs := make([]byte, len(b)+1)
copy(xs, b)
return xs
}
// doNextQuery executes query to fetch the next batch returning the rows.
func (p *PostgresAdapter) doNextQueryPendingObjectsByKey(ctx context.Context, it *objectsIterator) (_ tagsql.Rows, err error) {
defer mon.Task()(&ctx)(&err)
return p.db.QueryContext(ctx, `
SELECT
object_key, stream_id, version, status, encryption,
created_at, expires_at,
segment_count,
total_plain_size, total_encrypted_size, fixed_segment_size,
encrypted_metadata_nonce, encrypted_metadata, encrypted_metadata_encrypted_key
FROM objects
WHERE
(project_id, bucket_name, object_key) = ($1, $2, $3)
AND stream_id > $4::BYTEA
AND status = `+statusPending+`
ORDER BY stream_id ASC
LIMIT $5
`, it.projectID, it.bucketName,
[]byte(it.cursor.Key),
it.cursor.StreamID,
it.batchSize,
)
}
func (s *SpannerAdapter) doNextQueryPendingObjectsByKey(ctx context.Context, it *objectsIterator) (_ tagsql.Rows, err error) {
defer mon.Task()(&ctx)(&err)
rowIterator := s.client.Single().Query(ctx, spanner.Statement{
SQL: `
SELECT
object_key, stream_id, version, status, encryption,
created_at, expires_at,
segment_count,
total_plain_size, total_encrypted_size, fixed_segment_size,
encrypted_metadata_nonce, encrypted_metadata, encrypted_metadata_encrypted_key
FROM objects
WHERE
(project_id, bucket_name, object_key) = (@project_id, @bucket_name, @cursor_key)
AND stream_id > @stream_id
AND status = ` + statusPending + `
ORDER BY stream_id ASC
LIMIT @batch_size
`,
Params: map[string]any{
"project_id": it.projectID,
"bucket_name": string(it.bucketName),
"cursor_key": []byte(it.cursor.Key),
"stream_id": it.cursor.StreamID,
"batch_size": int64(it.batchSize),
},
})
return newSpannerRows(rowIterator), nil
}
// scanItem scans doNextQuery results into ObjectEntry.
func (it *objectsIterator) scanItem(item *ObjectEntry) (err error) {
item.IsPrefix = false
fields := []interface{}{
&item.ObjectKey,
&item.StreamID,
&item.Version,
&item.Status,
encryptionParameters{&item.Encryption},
}
if it.includeSystemMetadata {
fields = append(fields,
&item.CreatedAt,
&item.ExpiresAt,
&item.SegmentCount,
&item.TotalPlainSize,
&item.TotalEncryptedSize,
&item.FixedSegmentSize,
)
}
if it.includeCustomMetadata {
fields = append(fields,
&item.EncryptedMetadataNonce,
&item.EncryptedMetadata,
&item.EncryptedMetadataEncryptedKey,
)
}
err = it.curRows.Scan(fields...)
if err != nil {
return err
}
return nil
}
// PrefixLimit returns the object key that can be used in where clause for querying objects matching a prefix.
func PrefixLimit(a ObjectKey) ObjectKey {
if a == "" {
return ""
}
if a[len(a)-1] == 0xFF {
return a + "\x00"
}
key := []byte(a)
key[len(key)-1]++
return ObjectKey(key)
}
// LessObjectKey returns whether a < b.
func LessObjectKey(a, b ObjectKey) bool {
return bytes.Compare([]byte(a), []byte(b)) < 0
}
// FirstIterateCursor adjust the cursor for a non-recursive iteration.
// The cursor is non-inclusive and we need to adjust to handle prefix as cursor properly.
// We return the next possible key from the prefix.
func FirstIterateCursor(recursive bool, cursor IterateCursor, prefix ObjectKey) ObjectsIteratorCursor {
if recursive {
return ObjectsIteratorCursor{
Key: cursor.Key,
Version: cursor.Version,
}
}
// when the cursor does not match the prefix, we'll return the original cursor.
if !strings.HasPrefix(string(cursor.Key), string(prefix)) {
return ObjectsIteratorCursor{
Key: cursor.Key,
Version: cursor.Version,
}
}
// handle case where:
// prefix: x/y/
// cursor: x/y/z/w
// In this case, we want the skip prefix to be `x/y/z` + string('/' + 1).
cursorWithoutPrefix := cursor.Key[len(prefix):]
p := strings.IndexByte(string(cursorWithoutPrefix), Delimiter)
if p < 0 {
// The cursor is not a prefix, but instead a path inside the prefix,
// so we can use it directly.
return ObjectsIteratorCursor{
Key: cursor.Key,
Version: cursor.Version,
}
}
// return the next prefix given a scoped path
return ObjectsIteratorCursor{
Key: cursor.Key[:len(prefix)+p] + ObjectKey(Delimiter+1),
Version: MaxVersion,
Inclusive: true,
}
}