| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package tkvtest |
| 6 |
|
| 7 |
import ( |
| 8 |
"context" |
| 9 |
"errors" |
| 10 |
"math/rand" |
| 11 |
"sync" |
| 12 |
|
| 13 |
"golang.org/x/exp/sumdb/internal/tkv" |
| 14 |
) |
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
type Mem struct { |
| 21 |
mu sync.RWMutex |
| 22 |
table map[string]string |
| 23 |
} |
| 24 |
|
| 25 |
|
| 26 |
type memTx struct { |
| 27 |
m *Mem |
| 28 |
writes []tkv.Write |
| 29 |
} |
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
var errRetry = errors.New("retry") |
| 34 |
|
| 35 |
|
| 36 |
func (m *Mem) ReadOnly(ctx context.Context, f func(context.Context, tkv.Transaction) error) error { |
| 37 |
tx := &memTx{m: m} |
| 38 |
for { |
| 39 |
err := func() error { |
| 40 |
m.mu.Lock() |
| 41 |
defer m.mu.Unlock() |
| 42 |
|
| 43 |
if err := f(ctx, tx); err != nil { |
| 44 |
return err |
| 45 |
} |
| 46 |
|
| 47 |
if rand.Intn(10) == 0 { |
| 48 |
return errRetry |
| 49 |
} |
| 50 |
return nil |
| 51 |
}() |
| 52 |
if err != errRetry { |
| 53 |
return err |
| 54 |
} |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
|
| 59 |
func (m *Mem) ReadWrite(ctx context.Context, f func(context.Context, tkv.Transaction) error) error { |
| 60 |
tx := &memTx{m: m} |
| 61 |
for { |
| 62 |
err := func() error { |
| 63 |
m.mu.Lock() |
| 64 |
defer m.mu.Unlock() |
| 65 |
|
| 66 |
tx.writes = []tkv.Write{} |
| 67 |
if err := f(ctx, tx); err != nil { |
| 68 |
return err |
| 69 |
} |
| 70 |
|
| 71 |
if rand.Intn(10) == 0 { |
| 72 |
return errRetry |
| 73 |
} |
| 74 |
if m.table == nil { |
| 75 |
m.table = make(map[string]string) |
| 76 |
} |
| 77 |
for _, w := range tx.writes { |
| 78 |
if w.Value == "" { |
| 79 |
delete(m.table, w.Key) |
| 80 |
} else { |
| 81 |
m.table[w.Key] = w.Value |
| 82 |
} |
| 83 |
} |
| 84 |
return nil |
| 85 |
}() |
| 86 |
if err != errRetry { |
| 87 |
return err |
| 88 |
} |
| 89 |
} |
| 90 |
} |
| 91 |
|
| 92 |
|
| 93 |
func (tx *memTx) ReadValues(ctx context.Context, keys []string) ([]string, error) { |
| 94 |
vals := make([]string, len(keys)) |
| 95 |
for i, key := range keys { |
| 96 |
vals[i] = tx.m.table[key] |
| 97 |
} |
| 98 |
return vals, nil |
| 99 |
} |
| 100 |
|
| 101 |
|
| 102 |
func (tx *memTx) ReadValue(ctx context.Context, key string) (string, error) { |
| 103 |
return tx.m.table[key], nil |
| 104 |
} |
| 105 |
|
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
func (tx *memTx) BufferWrites(list []tkv.Write) error { |
| 111 |
if tx.writes == nil { |
| 112 |
panic("BufferWrite on read-only transaction") |
| 113 |
} |
| 114 |
tx.writes = append(tx.writes, list...) |
| 115 |
return nil |
| 116 |
} |