-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
152 lines (133 loc) · 3.42 KB
/
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
package main
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"budgetbridge/ynab"
"github.com/rs/zerolog/log"
)
type CachingClient struct {
client *ynab.Client
cache Cache
}
type Cache interface {
Open() error
Close() error
Get(key string, res interface{}) error
Set(key string, res interface{}) error
}
func (c *CachingClient) CreateTransactions(ctx context.Context, budgetID string, req ynab.CreateTransactionsRequest) (ynab.TransactionsResponse, error) {
return c.client.CreateTransactions(ctx, budgetID, req)
}
func (c *CachingClient) Transactions(ctx context.Context, req ynab.TransactionsRequest) (ynab.TransactionsResponse, error) {
return c.client.Transactions(ctx, req)
}
func (c *CachingClient) Budgets(ctx context.Context) (ynab.BudgetsResponse, error) {
cacheKey := "budgets"
var res ynab.BudgetsResponse
err := c.cache.Get(cacheKey, &res)
if errors.Is(err, errNotFound) {
res, err := c.client.Budgets(ctx)
if err != nil {
return res, fmt.Errorf("failed to fetch: %s", err)
}
if err := c.cache.Set(cacheKey, &res); err != nil {
return res, fmt.Errorf("failed to write to cache: %s", err)
}
return res, err
}
if err != nil {
// Some non-recoverable error.
return res, err
}
return res, nil
}
func (c *CachingClient) Categories(ctx context.Context, req ynab.CategoriesRequest) (ynab.CategoriesResponse, error) {
cacheKey := fmt.Sprintf("categories/%s", req.BudgetID)
var res ynab.CategoriesResponse
err := c.cache.Get(cacheKey, &res)
if errors.Is(err, errNotFound) {
res, err := c.client.Categories(ctx, req)
if err != nil {
return res, fmt.Errorf("failed to fetch: %s", err)
}
if err := c.cache.Set(cacheKey, &res); err != nil {
return res, fmt.Errorf("failed to write to cache: %s", err)
}
return res, err
}
if err != nil {
// Some non-recoverable error.
return res, err
}
return res, nil
}
var errNotFound error = errors.New("not found")
type FileCache struct {
path string
createMissing bool
cache map[string]json.RawMessage
}
func (c *FileCache) Open() error {
cache, err := c.loadFromDisk()
if err != nil && !os.IsNotExist(err) {
return err
}
if err != nil && c.createMissing {
log.Debug().Msg("init cache directory")
dir := filepath.Dir(c.path)
c.cache = make(map[string]json.RawMessage)
return os.MkdirAll(dir, os.ModePerm)
}
c.cache = cache
return nil
}
func (c *FileCache) Get(key string, res interface{}) error {
value, ok := c.cache[key]
if !ok {
log.Debug().Str("key", key).Msg("cache miss")
return errNotFound
}
if err := json.Unmarshal(value, res); err != nil {
return err
}
log.Debug().Str("key", key).Msg("cache hit")
return nil
}
func (c *FileCache) Set(key string, res interface{}) error {
var value json.RawMessage
value, err := json.Marshal(res)
if err != nil {
return err
}
c.cache[key] = value
return nil
}
func (c *FileCache) Close() error {
f, err := os.Create(c.path)
if err != nil {
return err
}
defer f.Close()
w := bufio.NewWriter(f)
defer w.Flush()
encoder := json.NewEncoder(w)
encoder.SetIndent("", " ")
return encoder.Encode(c.cache)
}
func (c *FileCache) loadFromDisk() (map[string]json.RawMessage, error) {
f, err := os.Open(c.path)
if err != nil {
return nil, err
}
defer f.Close()
var fullCache map[string]json.RawMessage
if err := json.NewDecoder(bufio.NewReader(f)).Decode(&fullCache); err != nil {
return nil, err
}
return fullCache, nil
}