github.com/ethersphere/bee/v2@v2.2.0/pkg/accesscontrol/kvs/mock/kvs.go (about) 1 // Copyright 2024 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 mock provides an in-memory key-value store implementation. 6 package mock 7 8 import ( 9 "context" 10 "encoding/hex" 11 "sync" 12 13 "github.com/ethersphere/bee/v2/pkg/accesscontrol/kvs" 14 "github.com/ethersphere/bee/v2/pkg/swarm" 15 ) 16 17 var lock = &sync.Mutex{} 18 var lockGetPut = &sync.Mutex{} 19 20 type single struct { 21 memoryMock map[string]map[string][]byte 22 } 23 24 var singleInMemorySwarm *single 25 26 func getInMemorySwarm() *single { 27 if singleInMemorySwarm == nil { 28 lock.Lock() 29 defer lock.Unlock() 30 if singleInMemorySwarm == nil { 31 singleInMemorySwarm = &single{ 32 memoryMock: make(map[string]map[string][]byte), 33 } 34 } 35 } 36 return singleInMemorySwarm 37 } 38 39 func getMemory() map[string]map[string][]byte { 40 ch := make(chan *single) 41 go func() { 42 ch <- getInMemorySwarm() 43 }() 44 mem := <-ch 45 return mem.memoryMock 46 } 47 48 type mockKeyValueStore struct { 49 address swarm.Address 50 } 51 52 var _ kvs.KeyValueStore = (*mockKeyValueStore)(nil) 53 54 func (m *mockKeyValueStore) Get(_ context.Context, key []byte) ([]byte, error) { 55 lockGetPut.Lock() 56 defer lockGetPut.Unlock() 57 mem := getMemory() 58 val := mem[m.address.String()][hex.EncodeToString(key)] 59 return val, nil 60 } 61 62 func (m *mockKeyValueStore) Put(_ context.Context, key []byte, value []byte) error { 63 lockGetPut.Lock() 64 defer lockGetPut.Unlock() 65 mem := getMemory() 66 if _, ok := mem[m.address.String()]; !ok { 67 mem[m.address.String()] = make(map[string][]byte) 68 } 69 mem[m.address.String()][hex.EncodeToString(key)] = value 70 return nil 71 } 72 73 func (m *mockKeyValueStore) Save(ctx context.Context) (swarm.Address, error) { 74 return m.address, nil 75 } 76 77 func New() kvs.KeyValueStore { 78 return &mockKeyValueStore{address: swarm.EmptyAddress} 79 } 80 81 func NewReference(address swarm.Address) kvs.KeyValueStore { 82 return &mockKeyValueStore{address: address} 83 }