/
store.go
268 lines (231 loc) 路 7.67 KB
/
store.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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package ledger
import (
"bytes"
"io/ioutil"
"time"
sErrors "github.com/johnstarich/sage/errors"
"github.com/johnstarich/sage/pipe"
"github.com/johnstarich/sage/prompter"
"github.com/johnstarich/sage/vcs"
"github.com/pkg/errors"
"go.uber.org/atomic"
"go.uber.org/zap"
)
const (
day = 24 * time.Hour
)
// Store enables ledger syncing both in memory and on disk
type Store struct {
*Ledger
file vcs.File
logger *zap.Logger
prompter prompter.Prompter
syncPromptRequest *atomic.Value
syncing *atomic.Bool
lastSyncErr *atomic.Error
syncFile func() error
syncLedger func(start, end time.Time, download downloader, processTxns txnMutator, ldg *Ledger, logger *zap.Logger, prompter prompter.Prompter) error
}
// NewStore creates a Ledger Store from the given file
func NewStore(file vcs.File, logger *zap.Logger) (*Store, error) {
ledgerBytes, err := file.Read()
if err != nil {
return nil, errors.Wrap(err, "Error reading ledger file")
}
r := ioutil.NopCloser(bytes.NewBuffer(ledgerBytes))
ldg, err := NewFromReader(r)
if err != nil {
return nil, err
}
store := &Store{
Ledger: ldg,
file: file,
logger: logger,
prompter: prompter.New(),
syncPromptRequest: &atomic.Value{},
syncing: atomic.NewBool(false),
lastSyncErr: atomic.NewError(nil),
syncFile: syncLedgerFile(ldg, file),
syncLedger: syncLedger,
}
go store.listenPromptRequests()
return store, nil
}
type downloader func(start, end time.Time, prompter prompter.Prompter) ([]Transaction, error)
type txnMutator func(txns []Transaction)
// StartSync asynchronously downloads and processes new transactions between the start and end dates
// If a partial failure occurs during the sync, writes to disk anyway
func (s *Store) StartSync(start, end time.Time, download downloader, processTxns txnMutator) {
if !s.startSync() {
// sync already running
return
}
go func() {
err := s.sync(start, end, download, processTxns)
s.stopSync(err)
}()
}
func (s *Store) sync(start, end time.Time, download downloader, processTxns txnMutator) error {
ledgerErr := s.syncLedger(start, end, download, processTxns, s.Ledger, s.logger, s.prompter)
if _, ok := ledgerErr.(Error); ledgerErr != nil && !ok {
return ledgerErr
}
if fileErr := s.syncFile(); fileErr != nil {
return errors.Wrap(fileErr, "Error writing ledger to disk")
}
// save partial errors only if there isn't a more important failure
return ledgerErr
}
func syncLedgerFile(ldg *Ledger, file vcs.File) func() error {
return func() error {
err := file.Write([]byte(ldg.String()))
return errors.Wrap(err, "Error writing ledger to disk")
}
}
func syncLedger(start, end time.Time, download downloader, processTxns txnMutator, ldg *Ledger, logger *zap.Logger, prompter prompter.Prompter) error {
if err := ldg.Validate(); err != nil {
return errors.Wrap(err, "Existing ledger is not valid")
}
const syncBuffer = 2 * day
duration := end.Sub(start)
duration += syncBuffer
const maxDownloadDuration = 30 * day // TODO move 30 day chunking logic into downloader?
var allTxns []Transaction
downloadStart := end.Add(-duration)
var errs sErrors.Errors
for downloadStart.Before(end) {
downloadEnd := min(end, downloadStart.Add(maxDownloadDuration))
logger.Info("Downloading txns...", zap.Time("start", downloadStart), zap.Time("end", downloadEnd))
txns, err := download(downloadStart, downloadEnd, prompter)
errs.AddErr(err)
allTxns = append(allTxns, txns...)
downloadStart = downloadEnd
}
if len(errs) == 0 {
logger.Info("Download succeeded!")
} else {
logger.Warn("Failed to download some transactions", zap.Error(errs))
}
// throw out extra transactions that were included by the institution responses
filteredTxns := make([]Transaction, 0, len(allTxns))
for _, t := range allTxns {
if t.Date.Before(start) {
continue
}
filteredTxns = append(filteredTxns, t)
}
allTxns = filteredTxns
processTxns(allTxns)
if err := ldg.AddTransactions(allTxns); err != nil {
logger.Warn("Failed to add transactions to ledger", zap.Error(err))
return err
}
logger.Info("Ledger successfully updated")
return errs.ErrOrNil()
}
func min(a, b time.Time) time.Time {
if a.Before(b) {
return a
}
return b
}
func (s *Store) startSync() (startedSync bool) {
return s.syncing.CAS(false, true)
}
func (s *Store) stopSync(err error) {
s.syncPromptRequest.Store((*prompter.Request)(nil))
s.syncing.Store(false)
s.lastSyncErr.Store(err)
if err != nil {
s.logger.Error("Error syncing", zap.Error(err))
}
}
// SyncStatus returns whether sync is running and the most recent sync error
func (s *Store) SyncStatus() (syncing bool, prompt *prompter.Request, lastSyncErr error) {
var req *prompter.Request
if promptReq, ok := s.syncPromptRequest.Load().(*prompter.Request); ok {
req = promptReq
}
return s.syncing.Load(), req, s.lastSyncErr.Load()
}
func currentDate() time.Time {
return time.Now().UTC().Round(day)
}
func (s *Store) listenPromptRequests() {
for {
req, ok := <-s.prompter.Requests()
if !ok {
return
}
s.syncPromptRequest.Store(&req)
}
}
func (s *Store) SubmitSyncPrompt(response prompter.Response) {
s.prompter.Respond(response)
}
// SyncRecent runs Sync for any new transactions since the last sync. Currently assumes last the last txn's date should be the start date.
func (s *Store) SyncRecent(download downloader, processTxns txnMutator) {
now := currentDate()
// TODO inline LastTransactionTime?
// TODO use smart first date selection on a per-account basis
lastTxnTime := s.Ledger.LastTransactionTime()
if lastTxnTime.IsZero() {
lastTxnTime = now.Add(-30 * day)
}
s.StartSync(lastTxnTime, now, download, processTxns)
}
// Resync runs Sync from the first date in the ledger until now
func (s *Store) Resync(download downloader, processTxns txnMutator) {
now := currentDate()
s.StartSync(s.Ledger.FirstTransactionTime(), now, download, processTxns)
}
// RenameAccount wraps ledger.RenameAccount and syncs changes to disk
func (s *Store) RenameAccount(oldName, newName, oldID, newID string) (int, error) {
updatedCount := s.Ledger.RenameAccount(oldName, newName, oldID, newID)
return updatedCount, s.syncFile()
}
// UpdateAccount wraps ledger.UpdateAccount and syncs changes to disk
func (s *Store) UpdateAccount(oldAccount, newAccount string) error {
return pipe.OpFuncs{
func() error { return s.Ledger.UpdateAccount(oldAccount, newAccount) },
s.syncFile,
}.Do()
}
// AddTransactions wraps ledger.AddTransactions and syncs changes to disk
func (s *Store) AddTransactions(txns []Transaction) error {
return pipe.OpFuncs{
func() error { return s.Ledger.AddTransactions(txns) },
s.syncFile,
}.Do()
}
// UpdateTransaction wraps ledger.UpdateTransaction and syncs changes to disk
func (s *Store) UpdateTransaction(id string, txn Transaction) error {
return pipe.OpFuncs{
func() error { return s.Ledger.UpdateTransaction(id, txn) },
s.syncFile,
}.Do()
}
// UpdateTransactions wraps ledger.UpdateTransactions and syncs changes to disk
func (s *Store) UpdateTransactions(txns map[string]Transaction) error {
var ledgerErrs, errs sErrors.Errors
for id, txn := range txns {
switch err := s.Ledger.UpdateTransaction(id, txn).(type) {
case Error:
ledgerErrs.AddErr(err)
default:
errs.AddErr(err)
}
}
return pipe.OpFuncs{
errs.ErrOrNil,
s.syncFile, // sync file even if there are validation errors
ledgerErrs.ErrOrNil, // return least critical errors last
}.Do()
}
// UpdateOpeningBalance wraps ledger.UpdateOpeningBalance and syncs changes to disk
func (s *Store) UpdateOpeningBalance(opening Transaction) error {
return pipe.OpFuncs{
func() error { return s.Ledger.UpdateOpeningBalance(opening) },
s.syncFile,
}.Do()
}