|
1 | 1 | package litestream |
2 | 2 |
|
3 | 3 | import ( |
4 | | - "encoding/binary" |
| 4 | + "context" |
| 5 | + "fmt" |
5 | 6 | "sync" |
6 | 7 |
|
7 | | - "golang.org/x/sync/singleflight" |
8 | | - |
| 8 | + "github.com/benbjohnson/litestream" |
9 | 9 | "github.com/superfly/ltx" |
10 | 10 | ) |
11 | 11 |
|
12 | 12 | type pageCache struct { |
13 | | - single singleflight.Group |
14 | | - pages map[uint32]cachedPage // +checklocks:mtx |
15 | | - size int |
16 | | - mtx sync.Mutex |
| 13 | + pages map[uint32]cachedPage // +checklocks:mtx |
| 14 | + size int |
| 15 | + mtx sync.Mutex |
17 | 16 | } |
18 | 17 |
|
19 | 18 | type cachedPage struct { |
20 | 19 | data []byte |
21 | 20 | txid ltx.TXID |
22 | 21 | } |
23 | 22 |
|
24 | | -func (c *pageCache) getOrFetch(pgno uint32, maxTXID ltx.TXID, fetch func() (any, error)) ([]byte, error) { |
25 | | - if c.size >= 0 { |
| 23 | +func (c *pageCache) getOrFetch(ctx context.Context, client ReplicaClient, pgno uint32, elem ltx.PageIndexElem) ([]byte, error) { |
| 24 | + if c.size > 0 { |
26 | 25 | c.mtx.Lock() |
27 | | - if c.pages == nil { |
28 | | - c.pages = map[uint32]cachedPage{} |
29 | | - } |
30 | 26 | page := c.pages[pgno] |
31 | 27 | c.mtx.Unlock() |
32 | 28 |
|
33 | | - if page.txid == maxTXID { |
| 29 | + if page.txid == elem.MaxTXID { |
34 | 30 | return page.data, nil |
35 | 31 | } |
36 | 32 | } |
37 | 33 |
|
38 | | - var key [12]byte |
39 | | - binary.LittleEndian.PutUint32(key[0:], pgno) |
40 | | - binary.LittleEndian.PutUint64(key[4:], uint64(maxTXID)) |
41 | | - v, err, _ := c.single.Do(string(key[:]), fetch) |
42 | | - |
| 34 | + h, data, err := litestream.FetchPage(ctx, client, elem.Level, elem.MinTXID, elem.MaxTXID, elem.Offset, elem.Size) |
43 | 35 | if err != nil { |
44 | | - return nil, err |
| 36 | + return nil, fmt.Errorf("fetch page: %w", err) |
| 37 | + } |
| 38 | + if pgno != h.Pgno { |
| 39 | + return nil, fmt.Errorf("fetch page: want %d, got %d", pgno, h.Pgno) |
45 | 40 | } |
46 | 41 |
|
47 | | - page := cachedPage{v.([]byte), maxTXID} |
48 | | - if c.size >= 0 { |
| 42 | + if c.size > 0 { |
49 | 43 | c.mtx.Lock() |
50 | | - c.evict(len(page.data)) |
51 | | - c.pages[pgno] = page |
| 44 | + if c.pages != nil { |
| 45 | + c.evict(len(data)) |
| 46 | + } else { |
| 47 | + c.pages = map[uint32]cachedPage{} |
| 48 | + } |
| 49 | + c.pages[pgno] = cachedPage{data, elem.MaxTXID} |
52 | 50 | c.mtx.Unlock() |
53 | 51 | } |
54 | | - return page.data, nil |
| 52 | + return data, nil |
55 | 53 | } |
56 | 54 |
|
57 | 55 | // +checklocks:c.mtx |
|
0 commit comments