github.com/ethersphere/bee/v2@v2.2.0/pkg/storer/internal/cache/export_test.go (about) 1 // Copyright 2022 The Swarm Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package cache 6 7 import ( 8 "context" 9 "fmt" 10 "time" 11 12 storage "github.com/ethersphere/bee/v2/pkg/storage" 13 "github.com/ethersphere/bee/v2/pkg/storer/internal/transaction" 14 "github.com/ethersphere/bee/v2/pkg/swarm" 15 ) 16 17 type ( 18 CacheEntry = cacheEntry 19 ) 20 21 var ( 22 ErrMarshalCacheEntryInvalidAddress = errMarshalCacheEntryInvalidAddress 23 ErrMarshalCacheEntryInvalidTimestamp = errMarshalCacheEntryInvalidTimestamp 24 ErrUnmarshalCacheEntryInvalidSize = errUnmarshalCacheEntryInvalidSize 25 ) 26 27 func ReplaceTimeNow(fn func() time.Time) func() { 28 now = fn 29 return func() { 30 now = time.Now 31 } 32 } 33 34 type CacheState struct { 35 Head swarm.Address 36 Tail swarm.Address 37 Size uint64 38 } 39 40 func (c *Cache) RemoveOldestMaxBatch(ctx context.Context, st transaction.Storage, count uint64, batchCnt int) error { 41 return c.RemoveOldest(ctx, st, count) 42 } 43 44 func (c *Cache) State(store storage.Reader) CacheState { 45 state := CacheState{} 46 state.Size = c.Size() 47 runner := swarm.ZeroAddress 48 49 err := store.Iterate( 50 storage.Query{ 51 Factory: func() storage.Item { return &cacheOrderIndex{} }, 52 ItemProperty: storage.QueryItemID, 53 }, 54 func(res storage.Result) (bool, error) { 55 _, addr, err := idFromKey(res.ID) 56 if err != nil { 57 return false, err 58 } 59 60 if state.Head.Equal(swarm.ZeroAddress) { 61 state.Head = addr 62 } 63 runner = addr 64 return false, nil 65 }, 66 ) 67 if err != nil { 68 panic(err) 69 } 70 state.Tail = runner 71 return state 72 } 73 74 func (c *Cache) IterateOldToNew( 75 st storage.Reader, 76 start, end swarm.Address, 77 iterateFn func(ch swarm.Address) (bool, error), 78 ) error { 79 runner := swarm.ZeroAddress 80 err := st.Iterate( 81 storage.Query{ 82 Factory: func() storage.Item { return &cacheOrderIndex{} }, 83 ItemProperty: storage.QueryItemID, 84 }, 85 func(res storage.Result) (bool, error) { 86 _, addr, err := idFromKey(res.ID) 87 if err != nil { 88 return false, err 89 } 90 91 if runner.Equal(swarm.ZeroAddress) { 92 if !addr.Equal(start) { 93 return false, fmt.Errorf("invalid cache order index key %s", res.ID) 94 } 95 } 96 runner = addr 97 return iterateFn(runner) 98 }, 99 ) 100 if err != nil { 101 return err 102 } 103 if !runner.Equal(end) { 104 return fmt.Errorf("invalid cache order index key %s", runner.String()) 105 } 106 107 return nil 108 }