| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"log" |
| 6 |
"sync" |
| 7 |
) |
| 8 |
|
| 9 |
func newDistributedStorage() *distributedStorage { |
| 10 |
return &distributedStorage{ |
| 11 |
records: make(map[string][]byte), |
| 12 |
} |
| 13 |
} |
| 14 |
|
| 15 |
type distributedStorage struct { |
| 16 |
sync.RWMutex |
| 17 |
records map[string][]byte |
| 18 |
} |
| 19 |
|
| 20 |
func (d *distributedStorage) Get(_ context.Context, key string) ([]byte, bool) { |
| 21 |
d.RLock() |
| 22 |
defer d.RUnlock() |
| 23 |
|
| 24 |
log.Printf("Getting key %s from the distributed storage\n", key) |
| 25 |
value, ok := d.records[key] |
| 26 |
return value, ok |
| 27 |
} |
| 28 |
|
| 29 |
func (d *distributedStorage) Set(_ context.Context, key string, value []byte) { |
| 30 |
d.Lock() |
| 31 |
defer d.Unlock() |
| 32 |
|
| 33 |
log.Printf("Writing key %s to the distributed storage\n", key) |
| 34 |
d.records[key] = value |
| 35 |
} |
| 36 |
|
| 37 |
func (d *distributedStorage) GetBatch(_ context.Context, keys []string) map[string][]byte { |
| 38 |
d.RLock() |
| 39 |
defer d.RUnlock() |
| 40 |
|
| 41 |
records := make(map[string][]byte) |
| 42 |
for _, key := range keys { |
| 43 |
log.Printf("Getting key %s from the distributed storage\n", key) |
| 44 |
if value, ok := d.records[key]; ok { |
| 45 |
records[key] = value |
| 46 |
} |
| 47 |
} |
| 48 |
return records |
| 49 |
} |
| 50 |
|
| 51 |
func (d *distributedStorage) SetBatch(_ context.Context, records map[string][]byte) { |
| 52 |
d.Lock() |
| 53 |
defer d.Unlock() |
| 54 |
|
| 55 |
for key, value := range records { |
| 56 |
log.Printf("Writing key %s to the distributed storage\n", key) |
| 57 |
d.records[key] = value |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
func (d *distributedStorage) Delete(_ context.Context, key string) { |
| 62 |
d.Lock() |
| 63 |
defer d.Unlock() |
| 64 |
|
| 65 |
log.Printf("Deleting key %s from the distributed storage\n", key) |
| 66 |
delete(d.records, key) |
| 67 |
} |
| 68 |
|
| 69 |
func (d *distributedStorage) DeleteBatch(_ context.Context, keys []string) { |
| 70 |
d.Lock() |
| 71 |
defer d.Unlock() |
| 72 |
|
| 73 |
for _, key := range keys { |
| 74 |
log.Printf("Deleting key %s from the distributed storage\n", key) |
| 75 |
delete(d.records, key) |
| 76 |
} |
| 77 |
} |