This repository has been archived by the owner on Oct 25, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.go
349 lines (283 loc) · 8.08 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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
// Copyright 2022 PGHQ. All Rights Reserved.
//
// Licensed under the GNU General Public License, Version 3 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package store
import (
"context"
"fmt"
"io/fs"
"os"
"reflect"
"time"
"github.com/dgraph-io/ristretto"
"github.com/pghq/go-tea/trail"
"github.com/pghq/go-store/provider"
"github.com/pghq/go-store/provider/pg"
)
type contextKey = struct{}
// Store an abstraction over database persistence
type Store struct {
db provider.Provider
cache *ristretto.Cache
}
// Begin a transaction
func (s Store) Begin(ctx context.Context, opts ...provider.TxOption) (Txn, error) {
span := trail.StartSpan(ctx, "Store.Begin")
defer span.Finish()
return begin(ctx, &s, opts...)
}
// Do execute callback in a transaction
func (s Store) Do(ctx context.Context, fn func(tx Txn) error, opts ...provider.TxOption) error {
span := trail.StartSpan(ctx, "Store.Do")
defer span.Finish()
tx, err := s.Begin(ctx, opts...)
if err != nil {
return trail.Stacktrace(err)
}
defer tx.rollback()
if err := fn(tx); err != nil {
return trail.Stacktrace(err)
}
return tx.commit()
}
// BatchQuery query
func (s Store) BatchQuery(ctx context.Context, query provider.BatchQuery, opts ...QueryOption) error {
span := trail.StartSpan(ctx, "Store.BatchQuery")
defer span.Finish()
conf := QueryConfig{}
for _, opt := range opts {
opt(&conf)
}
for _, item := range query {
cv, present := s.cache.Get(item.Spec.Id())
if present {
if err := hydrate(item.Value, cv); err != nil {
return trail.Stacktrace(err)
}
item.Skip = true
}
}
if err := s.db.Repository().BatchQuery(ctx, query); err != nil {
return trail.Stacktrace(err)
}
if conf.QueryTTL != 0 {
for _, item := range query {
if !item.Skip {
s.cache.SetWithTTL(item.Spec.Id(), item.Value, 1, conf.QueryTTL)
}
}
}
return nil
}
// One retrieve the first value matching the spec
func (s Store) One(ctx context.Context, spec provider.Spec, v interface{}, opts ...QueryOption) error {
span := trail.StartSpan(ctx, "Store.One")
defer span.Finish()
conf := QueryConfig{}
for _, opt := range opts {
opt(&conf)
}
cv, present := s.cache.Get(spec.Id())
span.Tags.Set("Store.CacheHit", fmt.Sprintf("%t", present))
if present {
return hydrate(v, cv)
}
if err := s.db.Repository().One(ctx, spec, v); err != nil {
return trail.Stacktrace(err)
}
if conf.QueryTTL != 0 {
s.cache.SetWithTTL(spec.Id(), v, 1, conf.QueryTTL)
}
return nil
}
// All retrieves a listing of values
func (s Store) All(ctx context.Context, spec provider.Spec, v interface{}, opts ...QueryOption) error {
span := trail.StartSpan(ctx, "Store.All")
defer span.Finish()
conf := QueryConfig{}
for _, opt := range opts {
opt(&conf)
}
cv, present := s.cache.Get(spec.Id())
span.Tags.Set("Store.CacheHit", fmt.Sprintf("%t", present))
if present {
return hydrate(v, cv)
}
if err := s.db.Repository().All(ctx, spec, v); err != nil {
return trail.Stacktrace(err)
}
if conf.QueryTTL != 0 {
s.cache.SetWithTTL(spec.Id(), v, 1, conf.QueryTTL)
}
return nil
}
// Add appends a value to the collection
func (s Store) Add(ctx context.Context, collection string, v interface{}) error {
span := trail.StartSpan(ctx, "Store.Add")
defer span.Finish()
return s.db.Repository().Add(ctx, collection, v)
}
// Edit updates value(s) in the collection
func (s Store) Edit(ctx context.Context, collection string, spec provider.Spec, v interface{}) error {
span := trail.StartSpan(ctx, "Store.Edit")
defer span.Finish()
return s.db.Repository().Edit(ctx, collection, spec, v)
}
// Remove deletes values(s) in the collection
func (s Store) Remove(ctx context.Context, collection string, spec provider.Spec) error {
span := trail.StartSpan(ctx, "Store.Remove")
defer span.Finish()
s.cache.Del(spec.Id())
return s.db.Repository().Remove(ctx, collection, spec)
}
// NewStore creates a new store instance
func NewStore(db provider.Provider) *Store {
s := Store{}
s.cache, _ = ristretto.NewCache(&ristretto.Config{
NumCounters: 1e7,
MaxCost: 1 << 30,
BufferItems: 64,
})
s.db = db
return &s
}
// New creates a new instance of the data store
func New(opts ...Option) (*Store, error) {
conf := Config{
DSN: os.Getenv("DATABASE_URL"),
}
for _, opt := range opts {
opt(&conf)
}
db, err := pg.New(conf.DSN, conf.Migration, conf.PgOptions...)
if err != nil {
return nil, trail.Stacktrace(err)
}
return NewStore(db), nil
}
// Txn A unit of work
type Txn struct {
ctx context.Context
uow provider.UnitOfWork
store *Store
root bool
done bool
}
// Context gets the context of the transaction
func (tx Txn) Context() context.Context {
return tx.ctx
}
// One retrieve the first value matching the spec
func (tx Txn) One(spec provider.Spec, v interface{}, opts ...QueryOption) error {
return tx.store.One(tx.Context(), spec, v, opts...)
}
// All retrieves a listing of values
func (tx Txn) All(spec provider.Spec, v interface{}, opts ...QueryOption) error {
return tx.store.All(tx.Context(), spec, v, opts...)
}
// Add appends a value to the collection
func (tx Txn) Add(collection string, v interface{}) error {
return tx.store.Add(tx.Context(), collection, v)
}
// Edit updates value(s) in the collection
func (tx Txn) Edit(collection string, spec provider.Spec, v interface{}) error {
return tx.store.Edit(tx.Context(), collection, spec, v)
}
// Remove deletes values(s) in the collection
func (tx Txn) Remove(collection string, spec provider.Spec) error {
return tx.store.Remove(tx.Context(), collection, spec)
}
// BatchQuery performs a batch query op within a transaction
func (tx Txn) BatchQuery(query provider.BatchQuery, opts ...QueryOption) error {
return tx.store.BatchQuery(tx.Context(), query, opts...)
}
// commit submit a unit of work
func (tx *Txn) commit() error {
if tx.done || !tx.root {
return nil
}
tx.done = true
return tx.uow.Commit(tx.Context())
}
// rollback cancel a unit of work
func (tx *Txn) rollback() {
if !tx.done && tx.root {
tx.done = true
tx.uow.Rollback(tx.Context())
}
}
// Config a configuration for the store
type Config struct {
DSN string
Migration fs.ReadDirFS
PgOptions []pg.Option
}
// Option A store configuration option
type Option func(conf *Config)
// WithMigration Use database migration
func WithMigration(fs fs.ReadDirFS) Option {
return func(conf *Config) {
conf.Migration = fs
}
}
// WithPg Use custom pg options
func WithPg(opts ...pg.Option) Option {
return func(conf *Config) {
conf.PgOptions = opts
}
}
// WithDSN Use dsn
func WithDSN(dsn string) Option {
return func(conf *Config) {
conf.DSN = dsn
}
}
// QueryConfig configuration for store queries
type QueryConfig struct {
QueryTTL time.Duration
}
// QueryOption for customizing store queries
type QueryOption func(conf *QueryConfig)
// QueryTTL custom duration of time to cache queries for
func QueryTTL(duration time.Duration) QueryOption {
return func(conf *QueryConfig) {
conf.QueryTTL = duration
}
}
// begin create instance of a read/write database transaction
func begin(ctx context.Context, store *Store, opts ...provider.TxOption) (Txn, error) {
if tx, ok := ctx.Value(contextKey{}).(Txn); ok {
tx.root = false
tx.ctx = context.WithValue(ctx, contextKey{}, tx)
return tx, nil
}
uow, err := store.db.Begin(ctx, opts...)
if err != nil {
return Txn{}, trail.Stacktrace(err)
}
tx := Txn{
uow: uow,
store: store,
root: true,
}
tx.ctx = context.WithValue(ctx, contextKey{}, tx)
return tx, nil
}
// hydrate Copies src value to destination
func hydrate(dst, src interface{}) error {
dv := reflect.Indirect(reflect.ValueOf(dst))
sv := reflect.Indirect(reflect.ValueOf(src))
if !dv.CanSet() || dv.Type() != sv.Type() {
return trail.NewError("bad hydration")
}
dv.Set(sv)
return nil
}