forked from ariga/entcache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
driver.go
560 lines (507 loc) · 13.8 KB
/
driver.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
package entcache
import (
"context"
stdsql "database/sql"
"database/sql/driver"
"fmt"
"regexp"
"strings"
"sync/atomic"
"time"
_ "unsafe"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"github.com/mitchellh/hashstructure/v2"
)
type (
// Options wraps the basic configuration cache options.
Options struct {
// TTL defines the period of time that an Entry
// is valid in the cache.
TTL time.Duration
// Cache defines the GetAddDeleter (cache implementation)
// for holding the cache entries. If no cache implementation
// was provided, an LRU cache with no limit is used.
Cache AddGetDeleter
// Hash defines an optional Hash function for converting
// a query and its arguments to a cache key. If no Hash
// function was provided, the DefaultHash is used.
Hash func(query string, args []any) (Key, error)
// KeyHolderHash defines an optional Hash function for converting
// a query, its arguments, columns, values to a list of cache key. If no KeyHolderHash
// function was provided, the DefaultKeyHolderHash is used.
KeyHolderHash func(query string, args []any, columns []string, values [][]driver.Value) (<-chan Key, error)
// Logf function. If provided, the Driver will call it with
// errors that can not be handled.
Log func(...any)
}
// Option allows configuring the cache
// driver using functional options.
Option func(*Options)
// A Driver is an SQL cached client. Users should use the
// constructor below for creating new driver.
Driver struct {
dialect.Driver
*Options
stats Stats
}
)
var findTableNamesRe = regexp.MustCompile(
`(?i)(?:(?:from)(?:\s|\(|\")+((?:\.|\w*)+)(?:\s|\)|.?)+)`,
)
// NewDriver returns a new Driver an existing driver and optional
// configuration functions. For example:
//
// entcache.NewDriver(
// drv,
// entcache.TTL(time.Minute),
// entcache.Levels(
// NewLRU(256),
// NewRedis(redis.NewClient(&redis.Options{
// Addr: ":6379",
// })),
// )
// )
func NewDriver(drv dialect.Driver, opts ...Option) *Driver {
options := &Options{Hash: DefaultHash, KeyHolderHash: DefaultKeyHolderHash, Cache: NewLRU(0)}
for _, opt := range opts {
opt(options)
}
return &Driver{
Driver: drv,
Options: options,
}
}
// TTL configures the period of time that an Entry
// is valid in the cache.
func TTL(ttl time.Duration) Option {
return func(o *Options) {
o.TTL = ttl
}
}
// Hash configures an optional Hash function for
// converting a query and its arguments to a cache key.
func Hash(hash func(query string, args []any) (Key, error)) Option {
return func(o *Options) {
o.Hash = hash
}
}
// KeyHolderHash configures an optional KeyHolderHash function for
// converting a query, its arguments, columns, values to a cache key.
func KeyHolderHash(
keyHolderHash func(query string, args []any, columns []string, values [][]driver.Value) (<-chan Key, error),
) Option {
return func(o *Options) {
o.KeyHolderHash = keyHolderHash
}
}
// Levels configures the Driver to work with the given cache levels.
// For example, in process LRU cache and a remote Redis cache.
func Levels(levels ...AddGetDeleter) Option {
return func(o *Options) {
if len(levels) == 1 {
o.Cache = levels[0]
} else {
o.Cache = &multiLevel{levels: levels}
}
}
}
// ContextLevel configures the driver to work with context/request level cache.
// Users that use this option, should wraps the *http.Request context with the
// cache value as follows:
//
// ctx = entcache.NewContext(ctx)
//
// ctx = entcache.NewContext(ctx, entcache.NewLRU(128))
func ContextLevel() Option {
return func(o *Options) {
o.Cache = &contextLevel{}
}
}
func (d *Driver) getRecorderOnCloseFunc(
ctx context.Context,
query string,
args []any,
opts *ctxOptions,
) func([]string, [][]driver.Value) {
return func(columns []string, values [][]driver.Value) {
holderKeys, err := d.KeyHolderHash(query, args, columns, values)
if err != nil {
if d.Log != nil {
atomic.AddUint64(&d.stats.Errors, 1)
d.Log(
fmt.Sprintf(
"entcache: failed getting holder keys: %v",
err,
),
)
}
return
}
// add new key to holders
for holderKey := range holderKeys {
var newHolderValues *[][]Key
switch holder, err := d.Cache.Get(ctx, holderKey); {
case err == nil:
newHolderValues = &holder.Values
if len(*newHolderValues) != 1 {
// wrong key
continue
}
if opts.evict {
// evict related key
if err := d.Cache.Del(ctx, (*newHolderValues)[0]...); err != nil {
atomic.AddUint64(&d.stats.Errors, 1)
d.Log(
fmt.Sprintf(
"entcache: failed deleting %v holder: %v",
holderKey,
err,
),
)
}
vs := [][]Key{{opts.key}}
newHolderValues = &vs
} else {
(*newHolderValues)[0] = append((*newHolderValues)[0], opts.key)
}
case err == ErrNotFound:
vs := [][]Key{{opts.key}}
newHolderValues = &vs
default:
if d.Log != nil {
atomic.AddUint64(&d.stats.Errors, 1)
d.Log(
fmt.Sprintf(
"entcache: failed getting %v holder: %v",
holderKey,
err,
),
)
}
continue
}
if err := d.Cache.Add(
ctx,
holderKey,
&Entry{Values: *newHolderValues},
opts.ttl*2,
); err != nil && d.Log != nil {
atomic.AddUint64(&d.stats.Errors, 1)
d.Log(
fmt.Sprintf(
"entcache: failed storing holder %v in cache: %v",
holderKey,
err,
),
)
}
}
if err := d.Cache.Add(
ctx,
opts.key,
&Entry{Columns: columns, Values: values},
opts.ttl,
); err != nil && d.Log != nil {
atomic.AddUint64(&d.stats.Errors, 1)
d.Log(
fmt.Sprintf(
"entcache: failed storing entry %v in cache: %v",
opts.key,
err,
),
)
}
}
}
// Query implements the Querier interface for the driver. It falls back to the
// underlying wrapped driver in case of caching error.
//
// Note that, the driver does not synchronize identical queries that are executed
// concurrently. Hence, if 2 identical queries are executed at the ~same time, and
// there is no cache entry for them, the driver will execute both of them and the
// last successful one will be stored in the cache.
func (d *Driver) Query(ctx context.Context, query string, args, v any) error {
// Check if the given statement looks like a standard Ent query (e.g. SELECT).
// Custom queries (e.g. CTE) or statements that are prefixed with comments are
// not supported. This check is mainly necessary, because PostgreSQL and SQLite
// may execute insert statement like "INSERT ... RETURNING" using Driver.Query.
if !strings.HasPrefix(query, "SELECT") && !strings.HasPrefix(query, "select") {
return d.Driver.Query(ctx, query, args, v)
}
vr, ok := v.(*sql.Rows)
if !ok {
return fmt.Errorf("entcache: invalid type %T. expect *sql.Rows", v)
}
argv, ok := args.([]any)
if !ok {
return fmt.Errorf("entcache: invalid type %T. expect []interface{} for args", args)
}
opts, err := d.optionsFromContext(ctx, query, argv)
if err != nil {
if d.Log != nil {
atomic.AddUint64(&d.stats.Errors, 1)
d.Log(
fmt.Sprintf(
"entcache: failed getting options: %v",
err,
),
)
}
opts = ctxOptions{skip: true}
}
if opts.skip {
return d.Driver.Query(ctx, query, args, v)
}
if opts.evict {
if err := d.Cache.Del(ctx, opts.key); err != nil && d.Log != nil {
atomic.AddUint64(&d.stats.Errors, 1)
d.Log(
fmt.Sprintf(
"entcache: failed evicting %v cache entry: %v",
opts.key,
err,
),
)
}
}
atomic.AddUint64(&d.stats.Gets, 1)
switch e, err := d.Cache.Get(ctx, opts.key); {
case err == nil:
atomic.AddUint64(&d.stats.Hits, 1)
vr.ColumnScanner = &repeater{columns: e.Columns, values: e.Values}
case err == ErrNotFound:
if err := d.Driver.Query(ctx, query, args, vr); err != nil {
return err
}
vr.ColumnScanner = &recorder{
ColumnScanner: vr.ColumnScanner,
onClose: d.getRecorderOnCloseFunc(ctx, query, argv, &opts),
}
default:
if d.Log != nil {
atomic.AddUint64(&d.stats.Errors, 1)
d.Log(
fmt.Sprintf(
"entcache: failed getting %v cache entry: %v",
opts.key,
err,
),
)
}
return d.Driver.Query(ctx, query, args, v)
}
return nil
}
// Stats returns a copy of the cache statistics.
func (d *Driver) Stats() Stats {
return Stats{
Gets: atomic.LoadUint64(&d.stats.Gets),
Hits: atomic.LoadUint64(&d.stats.Hits),
Errors: atomic.LoadUint64(&d.stats.Errors),
}
}
// QueryContext calls QueryContext of the underlying driver, or fails if it is not supported.
// Note, this method is not part of the caching layer since Ent does not use it by default.
func (d *Driver) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) {
drv, ok := d.Driver.(interface {
QueryContext(context.Context, string, ...any) (*sql.Rows, error)
})
if !ok {
return nil, fmt.Errorf("Driver.QueryContext is not supported")
}
return drv.QueryContext(ctx, query, args...)
}
// ExecContext calls ExecContext of the underlying driver, or fails if it is not supported.
func (d *Driver) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) {
drv, ok := d.Driver.(interface {
ExecContext(context.Context, string, ...any) (sql.Result, error)
})
if !ok {
return nil, fmt.Errorf("Driver.ExecContext is not supported")
}
return drv.ExecContext(ctx, query, args...)
}
// optionsFromContext returns the injected options from the context, or its default value.
func (d *Driver) optionsFromContext(
ctx context.Context,
query string,
args []any,
) (ctxOptions, error) {
var opts ctxOptions
if c, ok := ctx.Value(ctxOptionsKey).(*ctxOptions); ok {
opts = *c
}
if opts.key == nil {
key, err := d.Hash(query, args)
if err != nil {
return opts, err
}
opts.key = key
}
if opts.ttl == 0 {
opts.ttl = d.TTL
}
return opts, nil
}
// DefaultHash provides the default implementation for converting
// a query and its argument to a cache key.
func DefaultHash(query string, args []any) (Key, error) {
key, err := hashstructure.Hash(struct {
Q string
A []any
}{
Q: query,
A: args,
}, hashstructure.FormatV2, nil)
if err != nil {
return nil, err
}
return key, nil
}
// DefaultKeyHolderHash provides the default implementation for converting
// a query, its argument, columns, values to a holder key.
func DefaultKeyHolderHash(
query string,
args []any,
columns []string,
values [][]driver.Value,
) (<-chan Key, error) {
c := make(chan Key)
firstTableName := ""
fromClauses := findTableNamesRe.FindStringSubmatch(query)
if len(fromClauses) == 2 {
firstTableName = fromClauses[1]
}
go func() {
defer close(c)
for i := range values {
rawKey := "(" + firstTableName + ")"
for k := range values[i] {
rawKey += fmt.Sprint(values[i][k])
}
key, err := hashstructure.Hash(rawKey, hashstructure.FormatV2, nil)
if err != nil {
continue
}
c <- key
}
}()
return c, nil
}
// Stats represents the cache statistics of the driver.
type Stats struct {
Gets uint64
Hits uint64
Errors uint64
}
// rawCopy copies the driver values by implementing
// the sql.Scanner interface.
type rawCopy struct {
values []driver.Value
}
func (c *rawCopy) Scan(src interface{}) error {
if b, ok := src.([]byte); ok {
b1 := make([]byte, len(b))
copy(b1, b)
src = b1
}
c.values[0] = src
c.values = c.values[1:]
return nil
}
// recorder represents an sql.Rows recorder that implements
// the entgo.io/ent/dialect/sql.ColumnScanner interface.
type recorder struct {
sql.ColumnScanner
values [][]driver.Value
columns []string
done bool
onClose func([]string, [][]driver.Value)
}
// Next wraps the underlying Next method
func (r *recorder) Next() bool {
hasNext := r.ColumnScanner.Next()
r.done = !hasNext
return hasNext
}
// Scan copies database values for future use (by the repeater)
// and assign them to the given destinations using the standard
// database/sql.convertAssign function.
func (r *recorder) Scan(dest ...any) error {
values := make([]driver.Value, len(dest))
args := make([]any, len(dest))
c := &rawCopy{values: values}
for i := range args {
args[i] = c
}
if err := r.ColumnScanner.Scan(args...); err != nil {
return err
}
for i := range values {
if err := convertAssign(dest[i], values[i]); err != nil {
return err
}
}
r.values = append(r.values, values)
return nil
}
// Columns wraps the underlying Column method and stores it in the recorder state.
// The repeater.Columns cannot be called if the recorder method was not called before.
// That means, raw scanning should be identical for identical queries.
func (r *recorder) Columns() ([]string, error) {
columns, err := r.ColumnScanner.Columns()
if err != nil {
return nil, err
}
r.columns = columns
return columns, nil
}
func (r *recorder) Close() error {
if err := r.ColumnScanner.Close(); err != nil {
return err
}
// If we did not encounter any error during iteration,
// and we scanned all rows, we store it on cache.
if err := r.ColumnScanner.Err(); err == nil || r.done {
r.onClose(r.columns, r.values)
}
return nil
}
// repeater repeats columns scanning from cache history.
type repeater struct {
columns []string
values [][]driver.Value
}
func (*repeater) Close() error {
return nil
}
func (*repeater) ColumnTypes() ([]*stdsql.ColumnType, error) {
return nil, fmt.Errorf("entcache.ColumnTypes is not supported")
}
func (r *repeater) Columns() ([]string, error) {
return r.columns, nil
}
func (*repeater) Err() error {
return nil
}
func (r *repeater) Next() bool {
return len(r.values) > 0
}
func (r *repeater) NextResultSet() bool {
return len(r.values) > 0
}
func (r *repeater) Scan(dest ...any) error {
if !r.Next() {
return stdsql.ErrNoRows
}
for i, src := range r.values[0] {
if err := convertAssign(dest[i], src); err != nil {
return err
}
}
r.values = r.values[1:]
return nil
}
//go:linkname convertAssign database/sql.convertAssign
func convertAssign(dest, src any) error