-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathrapidash.go
1032 lines (935 loc) · 28.6 KB
/
rapidash.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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package rapidash
import (
"context"
"database/sql"
"net"
"sort"
"strings"
"time"
"github.com/rs/xid"
"go.knocknote.io/rapidash/server"
"golang.org/x/xerrors"
)
type Coder interface {
Marshaler
Unmarshaler
}
type Marshaler interface {
EncodeRapidash(Encoder) error
}
type Unmarshaler interface {
DecodeRapidash(Decoder) error
}
type Rapidash struct {
cacheServer server.CacheServer
ignoreCaches map[string]struct{}
firstLevelCaches *FirstLevelCacheMap
secondLevelCaches *SecondLevelCacheMap
lastLevelCache *LastLevelCache
opt Option
}
type Selectors struct {
slcSelector *server.Selector
llcSelector *server.Selector
}
type CacheServerType int
const (
CacheServerTypeMemcached CacheServerType = iota
CacheServerTypeRedis
CacheServerTypeOnMemory
// DefaultTimeout is the default socket read/write timeout.
DefaultTimeout = 100 * time.Millisecond
// DefaultMaxIdleConns is the default maximum number of idle connections
// kept for any single address.
DefaultMaxIdleConns = 2
)
type LogModeType int
const (
LogModeConsole LogModeType = iota
LogModeJSON
LogModeServerDebug
)
type TableOption struct {
shardKey *string
server *string
expiration *time.Duration
lockExpiration *time.Duration
optimisticLock *bool
pessimisticLock *bool
}
func (o *TableOption) ShardKey() string {
if o.shardKey == nil {
return ""
}
return *o.shardKey
}
func (o *TableOption) Server() string {
if o.server == nil {
return ""
}
return *o.server
}
func (o *TableOption) Expiration() time.Duration {
if o.expiration == nil {
return 0
}
return *o.expiration
}
func (o *TableOption) LockExpiration() time.Duration {
if o.lockExpiration == nil {
return 0
}
return *o.lockExpiration
}
func (o *TableOption) OptimisticLock() bool {
if o.optimisticLock == nil {
return false
}
return *o.optimisticLock
}
func (o *TableOption) PessimisticLock() bool {
if o.pessimisticLock == nil {
return false
}
return *o.pessimisticLock
}
type LastLevelCacheOption struct {
lockExpiration time.Duration
expiration time.Duration
optimisticLock bool
pessimisticLock bool
tagOpt map[string]TagOption
}
type TagOption struct {
server string
expiration time.Duration
lockExpiration time.Duration
ignoreStash bool
optimisticLock *bool
pessimisticLock *bool
}
type QueryLog struct {
Command string `json:"command"`
Key string `json:"key"`
Hash uint32 `json:"hash"`
Type server.CacheKeyType `json:"type"`
Addr string `json:"addr"`
}
type Option struct {
serverType CacheServerType
serverAddrs []string
timeout time.Duration
maxIdleConnections int
maxRetryCount int
retryInterval time.Duration
logMode LogModeType
logEnabled bool
logServerAddr string
slcServerAddrs []string
slcLockExpiration time.Duration
slcExpiration time.Duration
slcOptimisticLock bool
slcPessimisticLock bool
slcIgnoreNewerCache bool
slcTableOpt map[string]TableOption
llcOpt *LastLevelCacheOption
llcServerAddrs []string
beforeCommitCallback func(*Tx, []*QueryLog) error
afterCommitSuccessCallback func(*Tx) error
afterCommitFailureCallback func(*Tx, []*QueryLog) error
}
func defaultOption() Option {
return Option{
serverType: CacheServerTypeMemcached,
timeout: DefaultTimeout,
maxIdleConnections: DefaultMaxIdleConns,
maxRetryCount: 3,
retryInterval: 30 * time.Millisecond,
logMode: LogModeConsole,
logEnabled: false,
slcLockExpiration: 0,
slcExpiration: 0,
slcOptimisticLock: true,
slcPessimisticLock: true,
slcIgnoreNewerCache: true,
slcTableOpt: map[string]TableOption{},
llcOpt: &LastLevelCacheOption{
tagOpt: map[string]TagOption{},
optimisticLock: true,
pessimisticLock: true,
},
}
}
type Connection interface {
QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)
ExecContext(context.Context, string, ...interface{}) (sql.Result, error)
}
type TxConnection interface {
Connection
Commit() error
Rollback() error
}
type PendingQuery struct {
*QueryLog
fn func() error
}
type Tx struct {
r *Rapidash
conn Connection
stash *Stash
id string
pendingQueries map[string]*PendingQuery
lockKeys []server.CacheKey
isDBCommitted bool
isCacheCommitted bool
beforeCommitCallback func([]*QueryLog) error
afterCommitSuccessCallback func() error
afterCommitFailureCallback func([]*QueryLog) error
}
type Stash struct {
oldKey map[string]struct{}
uniqueKeyToPrimaryKey map[string]server.CacheKey
keyToPrimaryKeys map[string][]server.CacheKey
primaryKeyToValue map[string]*StructValue
lastLevelCacheKeyToBytes map[string][]byte
casIDs map[string]uint64
}
func NewStash() *Stash {
return &Stash{
oldKey: map[string]struct{}{},
uniqueKeyToPrimaryKey: map[string]server.CacheKey{},
keyToPrimaryKeys: map[string][]server.CacheKey{},
primaryKeyToValue: map[string]*StructValue{},
lastLevelCacheKeyToBytes: map[string][]byte{},
casIDs: map[string]uint64{},
}
}
func (r *Rapidash) Begin(conns ...Connection) (*Tx, error) {
if len(conns) > 1 {
return nil, ErrBeginTransaction
}
var conn Connection
if len(conns) == 1 {
conn = conns[0]
}
return &Tx{
r: r,
conn: conn,
stash: NewStash(),
id: xid.New().String(),
pendingQueries: map[string]*PendingQuery{},
lockKeys: []server.CacheKey{},
}, nil
}
func (tx *Tx) ID() string {
return tx.id
}
func (tx *Tx) BeforeCommitCallback(callback func([]*QueryLog) error) {
tx.beforeCommitCallback = callback
}
func (tx *Tx) AfterCommitCallback(
successCallback func() error,
failureCallback func([]*QueryLog) error) {
tx.afterCommitSuccessCallback = successCallback
tx.afterCommitFailureCallback = failureCallback
}
func (tx *Tx) Create(key string, value Type) error {
if err := tx.CreateWithExpiration(key, value, 0); err != nil {
return xerrors.Errorf("failed to CreateWithExpiration: %w", err)
}
return nil
}
func (tx *Tx) CreateWithTag(tag, key string, value Type) error {
if err := tx.CreateWithTagAndExpiration(tag, key, value, 0); err != nil {
return xerrors.Errorf("failed to CreateWithTagAndExpiration: %w", err)
}
return nil
}
func (tx *Tx) CreateWithExpiration(key string, value Type, expiration time.Duration) error {
if err := tx.CreateWithTagAndExpiration("", key, value, expiration); err != nil {
return xerrors.Errorf("failed to CreateWithTagAndExpiration: %w", err)
}
return nil
}
func (tx *Tx) CreateWithTagAndExpiration(tag, key string, value Type, expiration time.Duration) error {
if tx.IsCommitted() {
return ErrAlreadyCommittedTransaction
}
if err := tx.r.lastLevelCache.Create(tx, tag, key, value, expiration); err != nil {
return xerrors.Errorf("failed to Create: %w", err)
}
return nil
}
func (tx *Tx) Find(key string, value Type) error {
if err := tx.FindWithTag("", key, value); err != nil {
return xerrors.Errorf("failed to FindWithTag: %w", err)
}
return nil
}
func (tx *Tx) FindWithTag(tag, key string, value Type) error {
if tx.IsCommitted() {
return ErrAlreadyCommittedTransaction
}
if err := tx.r.lastLevelCache.Find(tx, tag, key, value); err != nil {
return xerrors.Errorf("failed to Find: %w", err)
}
return nil
}
func (tx *Tx) Update(key string, value Type) error {
if err := tx.UpdateWithExpiration(key, value, 0); err != nil {
return xerrors.Errorf("failed to UpdateWithExpiration: %w", err)
}
return nil
}
func (tx *Tx) UpdateWithTag(tag, key string, value Type) error {
if err := tx.UpdateWithTagAndExpiration(tag, key, value, 0); err != nil {
return xerrors.Errorf("failed to UpdateWithTag: %w", err)
}
return nil
}
func (tx *Tx) UpdateWithExpiration(key string, value Type, expiration time.Duration) error {
if err := tx.UpdateWithTagAndExpiration("", key, value, expiration); err != nil {
return xerrors.Errorf("failed to UpdateWithTagAndExpiration: %w", err)
}
return nil
}
func (tx *Tx) UpdateWithTagAndExpiration(tag, key string, value Type, expiration time.Duration) error {
if tx.IsCommitted() {
return ErrAlreadyCommittedTransaction
}
if err := tx.r.lastLevelCache.Update(tx, tag, key, value, expiration); err != nil {
return xerrors.Errorf("failed to Update: %w", err)
}
return nil
}
func (tx *Tx) Delete(key string) error {
if err := tx.DeleteWithTag("", key); err != nil {
return xerrors.Errorf("failed to DeleteWithTag: %w", err)
}
return nil
}
func (tx *Tx) DeleteWithTag(tag, key string) error {
if tx.IsCommitted() {
return ErrAlreadyCommittedTransaction
}
if err := tx.r.lastLevelCache.Delete(tx, tag, key); err != nil {
return xerrors.Errorf("failed to Delete: %w", err)
}
return nil
}
func (tx *Tx) enabledIgnoreCacheIfExistsTable(builder *QueryBuilder) {
if _, exists := tx.r.ignoreCaches[builder.tableName]; exists {
builder.isIgnoreCache = true
}
}
func (tx *Tx) CreateByTable(tableName string, marshaler Marshaler) (int64, error) {
id, err := tx.CreateByTableContext(context.Background(), tableName, marshaler)
if err != nil {
return id, xerrors.Errorf("failed to CreateByTableContext: %w", err)
}
return id, nil
}
func (tx *Tx) CreateByTableContext(ctx context.Context, tableName string, marshaler Marshaler) (id int64, e error) {
if tx.IsCommitted() {
e = ErrAlreadyCommittedTransaction
return
}
if _, exists := tx.r.firstLevelCaches.get(tableName); exists {
e = xerrors.Errorf("%s is read only table. it doesn't support write query", tableName)
return
}
if c, exists := tx.r.secondLevelCaches.get(tableName); exists {
if _, exists := tx.r.ignoreCaches[tableName]; exists {
lastInsertID, err := c.CreateWithoutCache(ctx, tx, marshaler)
if err != nil {
e = xerrors.Errorf("failed to CreateWithoutCache: %w", err)
}
id = lastInsertID
return
}
lastInsertID, err := c.Create(ctx, tx, marshaler)
if err != nil {
e = xerrors.Errorf("failed to Create: %w", err)
return
}
id = lastInsertID
return
}
e = xerrors.Errorf("unknown table name %s", tableName)
return
}
func (tx *Tx) FindByQueryBuilder(builder *QueryBuilder, unmarshaler Unmarshaler) error {
if err := tx.FindByQueryBuilderContext(context.Background(), builder, unmarshaler); err != nil {
return xerrors.Errorf("failed to FindByQueryBuilderContext: %w", err)
}
return nil
}
func (tx *Tx) FindByQueryBuilderContext(ctx context.Context, builder *QueryBuilder, unmarshaler Unmarshaler) error {
if tx.IsCommitted() {
return ErrAlreadyCommittedTransaction
}
tx.enabledIgnoreCacheIfExistsTable(builder)
if c, exists := tx.r.firstLevelCaches.get(builder.tableName); exists {
if err := c.FindByQueryBuilder(builder, unmarshaler); err != nil {
return xerrors.Errorf("failed to FindByQueryBuilder of FirstLevelCache: %w", err)
}
return nil
}
if c, exists := tx.r.secondLevelCaches.get(builder.tableName); exists {
if tx.conn == nil {
return ErrConnectionOfTransaction
}
if err := c.FindByQueryBuilder(ctx, tx, builder, unmarshaler); err != nil {
return xerrors.Errorf("failed to FindByQueryBuilder of SecondLevelCache: %w", err)
}
return nil
}
return xerrors.Errorf("unknown table name %s", builder.tableName)
}
func (tx *Tx) CountByQueryBuilder(builder *QueryBuilder) (uint64, error) {
count, err := tx.CountByQueryBuilderContext(context.Background(), builder)
if err != nil {
return 0, xerrors.Errorf("failed to CountByQueryBuilderContext: %w", err)
}
return count, nil
}
func (tx *Tx) CountByQueryBuilderContext(ctx context.Context, builder *QueryBuilder) (uint64, error) {
if c, exists := tx.r.firstLevelCaches.get(builder.tableName); exists {
count, err := c.CountByQueryBuilder(builder)
if err != nil {
return 0, xerrors.Errorf("failed to CountByQueryBuilder of FirstLevelCache: %w", err)
}
return count, nil
}
if c, exists := tx.r.secondLevelCaches.get(builder.tableName); exists {
count, err := c.CountByQueryBuilder(ctx, tx, builder)
if err != nil {
return 0, xerrors.Errorf("failed to CountByQueryBuilder of SecondLevelCache: %w", err)
}
return count, nil
}
return 0, xerrors.Errorf("unknown table name %s", builder.tableName)
}
func (tx *Tx) FindAllByTable(tableName string, unmarshaler Unmarshaler) error {
if c, exists := tx.r.firstLevelCaches.get(tableName); exists {
if err := c.FindAll(unmarshaler); err != nil {
return xerrors.Errorf("failed to FindAll of FirstLevelCache: %w", err)
}
return nil
}
return xerrors.Errorf("unknown table name %s", tableName)
}
func (tx *Tx) UpdateByQueryBuilder(builder *QueryBuilder, updateMap map[string]interface{}) error {
if err := tx.UpdateByQueryBuilderContext(context.Background(), builder, updateMap); err != nil {
return xerrors.Errorf("failed to UpdateByQueryBuilderContext: %w", err)
}
return nil
}
func (tx *Tx) UpdateByQueryBuilderContext(ctx context.Context, builder *QueryBuilder, updateMap map[string]interface{}) error {
if tx.IsCommitted() {
return ErrAlreadyCommittedTransaction
}
tx.enabledIgnoreCacheIfExistsTable(builder)
if _, exists := tx.r.firstLevelCaches.get(builder.tableName); exists {
return xerrors.Errorf("%s is read only table. it doesn't support write query", builder.tableName)
}
if c, exists := tx.r.secondLevelCaches.get(builder.tableName); exists {
if tx.conn == nil {
return ErrConnectionOfTransaction
}
if err := c.UpdateByQueryBuilder(ctx, tx, builder, updateMap); err != nil {
return xerrors.Errorf("failed to UpdateByQueryBuilder: %w", err)
}
return nil
}
return xerrors.Errorf("unknown table name %s", builder.tableName)
}
func (tx *Tx) DeleteByQueryBuilder(builder *QueryBuilder) error {
if err := tx.DeleteByQueryBuilderContext(context.Background(), builder); err != nil {
return xerrors.Errorf("failed to DeleteByQueryBuilderContext: %w", err)
}
return nil
}
func (tx *Tx) DeleteByQueryBuilderContext(ctx context.Context, builder *QueryBuilder) error {
if tx.IsCommitted() {
return ErrAlreadyCommittedTransaction
}
tx.enabledIgnoreCacheIfExistsTable(builder)
if _, exists := tx.r.firstLevelCaches.get(builder.tableName); exists {
return xerrors.Errorf("%s is read only table. it doesn't support write query", builder.tableName)
}
if c, exists := tx.r.secondLevelCaches.get(builder.tableName); exists {
if tx.conn == nil {
return ErrConnectionOfTransaction
}
if err := c.DeleteByQueryBuilder(ctx, tx, builder); err != nil {
return xerrors.Errorf("failed to DeleteByQueryBuilder: %w", err)
}
return nil
}
return xerrors.Errorf("unknown table name %s", builder.tableName)
}
func (tx *Tx) IsCommitted() bool {
return tx.isDBCommitted || tx.isCacheCommitted
}
func (tx *Tx) execQuery(queries []*PendingQuery) []*PendingQuery {
failedQueries := []*PendingQuery{}
for _, query := range queries {
if err := query.fn(); err != nil {
failedQueries = append(failedQueries, query)
}
}
return failedQueries
}
func (tx *Tx) sortedPendingQueryKeys() []string {
keys := make([]string, len(tx.pendingQueries))
idx := 0
for k := range tx.pendingQueries {
keys[idx] = k
idx++
}
sort.Strings(keys)
return keys
}
func (tx *Tx) unlockAllKeys() error {
mergedErr := []string{}
for _, key := range tx.lockKeys {
log.Delete(tx.id, SLCServer, key)
if err := tx.r.cacheServer.Delete(key); err != nil {
mergedErr = append(mergedErr, err.Error())
}
}
if len(mergedErr) > 0 {
return xerrors.Errorf("%s: %w", strings.Join(mergedErr, ","), ErrUnlockCacheKeys)
}
return nil
}
func (tx *Tx) releaseValues() {
for _, value := range tx.stash.primaryKeyToValue {
value.Release()
}
tx.stash.primaryKeyToValue = make(map[string]*StructValue)
}
func (tx *Tx) commitBeforeProcess(queries []*PendingQuery) error {
if tx.beforeCommitCallback != nil {
totalQueries := make([]*QueryLog, len(queries))
for idx, query := range queries {
totalQueries[idx] = query.QueryLog
}
if err := tx.beforeCommitCallback(totalQueries); err != nil {
return xerrors.Errorf("failed to callback for BeforeCommit: %w", err)
}
} else if tx.r.opt.beforeCommitCallback != nil {
totalQueries := make([]*QueryLog, len(queries))
for idx, query := range queries {
totalQueries[idx] = query.QueryLog
}
if err := tx.r.opt.beforeCommitCallback(tx, totalQueries); err != nil {
return xerrors.Errorf("failed to callback for BeforeCommit: %w", err)
}
}
return nil
}
func (tx *Tx) commitAfterProcess(queries []*PendingQuery) error {
tx.isCacheCommitted = true
errs := []string{}
if err := tx.unlockAllKeys(); err != nil {
errs = append(errs, err.Error())
}
if len(queries) == 0 {
if tx.afterCommitSuccessCallback != nil {
if err := tx.afterCommitSuccessCallback(); err != nil {
errs = append(errs, err.Error())
}
} else if tx.r.opt.afterCommitSuccessCallback != nil {
if err := tx.r.opt.afterCommitSuccessCallback(tx); err != nil {
errs = append(errs, err.Error())
}
}
} else {
if tx.afterCommitFailureCallback != nil {
failureQueries := []*QueryLog{}
for _, query := range queries {
failureQueries = append(failureQueries, query.QueryLog)
}
if err := tx.afterCommitFailureCallback(failureQueries); err != nil {
errs = append(errs, err.Error())
}
} else if tx.r.opt.afterCommitFailureCallback != nil {
failureQueries := []*QueryLog{}
for _, query := range queries {
failureQueries = append(failureQueries, query.QueryLog)
}
if err := tx.r.opt.afterCommitFailureCallback(tx, failureQueries); err != nil {
errs = append(errs, err.Error())
}
}
}
if len(errs) > 0 {
return xerrors.Errorf("%s: %w", strings.Join(errs, ","), ErrCleanUpCache)
}
return nil
}
func (tx *Tx) commitCache() (e error) {
queries := []*PendingQuery{}
tx.releaseValues()
defer func() {
if err := tx.commitAfterProcess(queries); err != nil {
e = xerrors.Errorf("failed to run commit after process: %w", err)
}
}()
keys := tx.sortedPendingQueryKeys()
for _, key := range keys {
queries = append(queries, tx.pendingQueries[key])
}
if err := tx.commitBeforeProcess(queries); err != nil {
return xerrors.Errorf("failed to run commit before process: %w", err)
}
for i := 0; i < tx.r.opt.maxRetryCount-1; i++ {
queries = tx.execQuery(queries)
if len(queries) == 0 {
return nil
}
time.Sleep(tx.r.opt.retryInterval)
}
errs := []string{}
for _, query := range queries {
if err := query.fn(); err != nil {
errs = append(errs, err.Error())
}
}
if len(errs) > 0 {
return xerrors.Errorf("%s: %w", strings.Join(errs, ","), ErrCacheCommit)
}
return nil
}
func (tx *Tx) commitDB() error {
if tx.conn == nil {
return nil
}
txConn, ok := tx.conn.(TxConnection)
if !ok {
return nil
}
if err := txConn.Commit(); err != nil {
return xerrors.Errorf("failed to Commit for database: %w", err)
}
tx.isDBCommitted = true
return nil
}
func (tx *Tx) CommitCacheOnly() error {
if err := tx.commitCache(); err != nil {
return xerrors.Errorf("failed to Commit for cache: %w", err)
}
return nil
}
func (tx *Tx) CommitDBOnly() error {
if err := tx.commitDB(); err != nil {
return xerrors.Errorf("failed to Commit for database: %w", err)
}
return nil
}
func (tx *Tx) Commit() error {
if err := tx.commitDB(); err != nil {
return xerrors.Errorf("failed to Commit for database: %w", err)
}
if err := tx.commitCache(); err != nil {
return xerrors.Errorf("failed to Commit for cache: %w", err)
}
return nil
}
func (tx *Tx) rollbackCache() error {
tx.releaseValues()
if err := tx.unlockAllKeys(); err != nil {
return xerrors.Errorf("failed to unlock for all keys: %w", err)
}
return nil
}
func (tx *Tx) rollbackDB() error {
if tx.conn == nil {
return nil
}
txConn, ok := tx.conn.(TxConnection)
if !ok {
return nil
}
if err := txConn.Rollback(); err != nil {
return xerrors.Errorf("failed to Rollback for database: %w", err)
}
return nil
}
func (tx *Tx) RollbackCacheOnly() error {
if err := tx.rollbackCache(); err != nil {
return xerrors.Errorf("failed to Rollback for cache: %w", err)
}
return nil
}
func (tx *Tx) RollbackDBOnly() error {
if err := tx.rollbackDB(); err != nil {
return xerrors.Errorf("failed to Rollback for database: %w", err)
}
return nil
}
func (tx *Tx) Rollback() error {
if err := tx.rollbackDB(); err != nil {
return xerrors.Errorf("failed to Rollback for database: %w", err)
}
if err := tx.rollbackCache(); err != nil {
return xerrors.Errorf("failed to Rollback for cache: %w", err)
}
return nil
}
func (tx *Tx) RollbackCacheOnlyUnlessCommitted() error {
if !tx.isCacheCommitted {
if err := tx.rollbackCache(); err != nil {
return xerrors.Errorf("failed to rollback: %w", err)
}
return nil
}
return nil
}
func (tx *Tx) RollbackDBOnlyUnlessCommitted() error {
if !tx.isDBCommitted {
if err := tx.rollbackDB(); err != nil {
return xerrors.Errorf("failed to rollback: %w", err)
}
return nil
}
return nil
}
func (tx *Tx) RollbackUnlessCommitted() error {
if err := tx.RollbackDBOnlyUnlessCommitted(); err != nil {
return xerrors.Errorf("failed to rollback: %w", err)
}
if err := tx.RollbackCacheOnlyUnlessCommitted(); err != nil {
return xerrors.Errorf("failed to rollback: %w", err)
}
return nil
}
func (r *Rapidash) Recover(queries []*QueryLog) error {
mergedErr := []string{}
for _, query := range queries {
var serverAddr net.Addr
if query.Addr != "" {
addr, err := getAddr(query.Addr)
if err != nil {
return xerrors.Errorf("cannot get addr for recovery: %w", err)
}
serverAddr = addr
}
cacheKey := &CacheKey{
key: query.Key,
hash: query.Hash,
typ: query.Type,
addr: serverAddr,
}
if err := r.cacheServer.Delete(cacheKey); err != nil {
mergedErr = append(mergedErr, err.Error())
}
}
if len(mergedErr) > 0 {
return xerrors.Errorf("%s: %w", strings.Join(mergedErr, ","), ErrRecoverCache)
}
return nil
}
func (r *Rapidash) BeforeCommitCallback(callback func(*Tx, []*QueryLog) error) {
r.opt.beforeCommitCallback = callback
}
func (r *Rapidash) AfterCommitCallback(
successCallback func(*Tx) error,
failureCallback func(*Tx, []*QueryLog) error) {
r.opt.afterCommitSuccessCallback = successCallback
r.opt.afterCommitFailureCallback = failureCallback
}
// Ignore read/write to database without cache access
func (r *Rapidash) Ignore(conn *sql.DB, typ *Struct) error {
r.ignoreCaches[typ.tableName] = struct{}{}
if err := r.WarmUpSecondLevelCache(conn, typ); err != nil {
return xerrors.Errorf("cannot warm up SecondLevelCache. table is %s: %w", typ.tableName, err)
}
return nil
}
func (r *Rapidash) WarmUp(conn *sql.DB, typ *Struct, isReadOnly bool) error {
if isReadOnly {
if err := r.WarmUpFirstLevelCache(conn, typ); err != nil {
return xerrors.Errorf("cannot warm up FirstLevelCache: %w", err)
}
return nil
}
if err := r.WarmUpSecondLevelCache(conn, typ); err != nil {
return xerrors.Errorf("cannot warm up SecondLevelCache: %w", err)
}
return nil
}
func (r *Rapidash) WarmUpFirstLevelCache(conn *sql.DB, typ *Struct) error {
flc := NewFirstLevelCache(typ)
if err := flc.WarmUp(conn); err != nil {
return xerrors.Errorf("cannot warm up FirstLevelCache. table is %s: %w", typ.tableName, err)
}
r.firstLevelCaches.set(typ.tableName, flc)
return nil
}
func (r *Rapidash) tableOption(tableName string) TableOption {
opt := r.opt.slcTableOpt[tableName]
if opt.expiration == nil {
opt.expiration = &r.opt.slcExpiration
}
if opt.lockExpiration == nil {
opt.lockExpiration = &r.opt.slcLockExpiration
}
if opt.optimisticLock == nil {
opt.optimisticLock = &r.opt.slcOptimisticLock
}
if opt.pessimisticLock == nil {
opt.pessimisticLock = &r.opt.slcPessimisticLock
}
return opt
}
func (r *Rapidash) WarmUpSecondLevelCache(conn *sql.DB, typ *Struct) error {
slc := NewSecondLevelCache(typ, r.cacheServer, r.tableOption(typ.tableName))
if err := slc.WarmUp(conn); err != nil {
return xerrors.Errorf("cannot warm up SecondLevelCache. table is %s: %w", typ.tableName, err)
}
r.secondLevelCaches.set(typ.tableName, slc)
return nil
}
func (r *Rapidash) RemoveServers(servers ...string) error {
client := r.cacheServer.GetClient()
if err := client.RemoveSecondLevelCacheServers(servers...); err != nil {
return xerrors.Errorf("failed to remove second level cache servers: %w", err)
}
if err := client.RemoveLastLevelCacheServers(servers...); err != nil {
return xerrors.Errorf("failed to remove last level cache servers: %w", err)
}
return nil
}
func (r *Rapidash) RemoveSecondLevelCacheServers(servers ...string) error {
client := r.cacheServer.GetClient()
if err := client.RemoveSecondLevelCacheServers(servers...); err != nil {
return xerrors.Errorf("failed to remove second level cache servers: %w", err)
}
return nil
}
func (r *Rapidash) RemoveLastLevelCacheServers(servers ...string) error {
client := r.cacheServer.GetClient()
if err := client.RemoveLastLevelCacheServers(servers...); err != nil {
return xerrors.Errorf("failed to remove last level cache servers: %w", err)
}
return nil
}
func (r *Rapidash) AddServers(servers ...string) error {
client := r.cacheServer.GetClient()
if err := client.AddSecondLevelCacheServers(servers...); err != nil {
return xerrors.Errorf("failed to add second level cache servers: %w", err)
}
if err := client.AddLastLevelCacheServers(servers...); err != nil {
return xerrors.Errorf("failed to add last level cache servers: %w", err)
}
return nil
}
func (r *Rapidash) AddSecondLevelCacheServer(servers ...string) error {
client := r.cacheServer.GetClient()
if err := client.AddSecondLevelCacheServers(servers...); err != nil {
return xerrors.Errorf("failed to add second level cache servers: %w", err)
}
return nil
}
func (r *Rapidash) AddLastLevelCacheServer(servers ...string) error {
client := r.cacheServer.GetClient()
if err := client.AddLastLevelCacheServers(servers...); err != nil {
return xerrors.Errorf("failed to add last level cache servers: %w", err)
}
return nil
}
func (r *Rapidash) Flush() error {
if err := r.cacheServer.Flush(); err != nil {
return xerrors.Errorf("failed to flush cache server: %w", err)
}
return nil
}
func (r *Rapidash) setServer() error {
switch r.opt.serverType {
case CacheServerTypeMemcached:
s := &Selectors{}
if err := s.setSelector(r.opt.serverAddrs, r.opt.slcServerAddrs, r.opt.llcServerAddrs); err != nil {
return xerrors.Errorf("failed to set cache server selector: %w", err)
}
memcached := server.NewMemcachedBySelectors(s.slcSelector, s.llcSelector)
r.cacheServer = memcached
r.lastLevelCache = NewLastLevelCache(r.cacheServer, r.opt.llcOpt)
case CacheServerTypeRedis:
s := &Selectors{}
if err := s.setSelector(r.opt.serverAddrs, r.opt.slcServerAddrs, r.opt.llcServerAddrs); err != nil {
return xerrors.Errorf("failed to set cache server selector: %w", err)
}
redis := server.NewRedisBySelectors(s.slcSelector, s.llcSelector)
r.cacheServer = redis
r.lastLevelCache = NewLastLevelCache(r.cacheServer, r.opt.llcOpt)
case CacheServerTypeOnMemory:
}
if err := r.cacheServer.SetTimeout(r.opt.timeout); err != nil {
return xerrors.Errorf("failed to set timeout for cache server: %w", err)
}
if err := r.cacheServer.SetMaxIdleConnections(r.opt.maxIdleConnections); err != nil {
return xerrors.Errorf("failed to set max idle connections for cache server: %w", err)
}
return nil
}
func (r *Rapidash) setLogger() {
if !r.opt.logEnabled {
setNopLogger()
return
}
switch r.opt.logMode {
case LogModeConsole:
setConsoleLogger()
case LogModeJSON:
setJSONLogger()
case LogModeServerDebug:
}
}
func (s *Selectors) setSelector(serverAddrs, slcServerAddrs, llcServerAddrs []string) error {
if len(serverAddrs) > 0 {
slcSelector, err := server.NewSelector(serverAddrs...)
if err != nil {
return err
}
s.slcSelector = slcSelector
llcSelector, err := server.NewSelector(serverAddrs...)
if err != nil {
return err
}
s.llcSelector = llcSelector
}
if len(slcServerAddrs) > 0 {