/
ledger_cache.go
50 lines (39 loc) · 1004 Bytes
/
ledger_cache.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package history
import (
"context"
"github.com/stellar/go/support/collections/set"
"github.com/stellar/go/support/errors"
)
// Queue adds `seq` to the load queue for the cache.
func (lc *LedgerCache) Queue(seq int32) {
lc.lock.Lock()
if lc.queued == nil {
lc.queued = set.Set[int32]{}
}
lc.queued.Add(seq)
lc.lock.Unlock()
}
// Load loads a batch of ledgers identified by `sequences`, using `q`,
// and populates the cache with the results
func (lc *LedgerCache) Load(ctx context.Context, q *Q) error {
lc.lock.Lock()
defer lc.lock.Unlock()
if len(lc.queued) == 0 {
return nil
}
sequences := make([]int32, 0, len(lc.queued))
for seq := range lc.queued {
sequences = append(sequences, seq)
}
var ledgers []Ledger
err := q.LedgersBySequence(ctx, &ledgers, sequences...)
if err != nil {
return errors.Wrap(err, "failed to load ledger batch")
}
lc.Records = map[int32]Ledger{}
for _, l := range ledgers {
lc.Records[l.Sequence] = l
}
lc.queued = nil
return nil
}