forked from couchbase/go-couchbase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
1214 lines (1016 loc) · 30.3 KB
/
client.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 couchbase provides a smart client for go.
Usage:
client, err := couchbase.Connect("http://myserver:8091/")
handleError(err)
pool, err := client.GetPool("default")
handleError(err)
bucket, err := pool.GetBucket("MyAwesomeBucket")
handleError(err)
...
or a shortcut for the bucket directly
bucket, err := couchbase.GetBucket("http://myserver:8091/", "default", "default")
in any case, you can specify authentication credentials using
standard URL userinfo syntax:
b, err := couchbase.GetBucket("http://bucketname:bucketpass@myserver:8091/",
"default", "bucket")
*/
package couchbase
import (
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"runtime"
"strings"
"sync"
"time"
"unsafe"
"github.com/couchbase/gomemcached"
"github.com/couchbase/gomemcached/client" // package name is 'memcached'
"github.com/couchbase/goutils/logging"
)
// Mutation Token
type MutationToken struct {
VBid uint16 // vbucket id
Guard uint64 // vbuuid
Value uint64 // sequence number
}
// Maximum number of times to retry a chunk of a bulk get on error.
var MaxBulkRetries = 5000
// If this is set to a nonzero duration, Do() and ViewCustom() will log a warning if the call
// takes longer than that.
var SlowServerCallWarningThreshold time.Duration
func slowLog(startTime time.Time, format string, args ...interface{}) {
if elapsed := time.Now().Sub(startTime); elapsed > SlowServerCallWarningThreshold {
pc, _, _, _ := runtime.Caller(2)
caller := runtime.FuncForPC(pc).Name()
logging.Infof("go-couchbase: "+format+" in "+caller+" took "+elapsed.String(), args...)
}
}
// Return true if error is KEY_ENOENT. Required by cbq-engine
func IsKeyEExistsError(err error) bool {
res, ok := err.(*gomemcached.MCResponse)
if ok && res.Status == gomemcached.KEY_EEXISTS {
return true
}
return false
}
// Return true if error is KEY_ENOENT. Required by cbq-engine
func IsKeyNoEntError(err error) bool {
res, ok := err.(*gomemcached.MCResponse)
if ok && res.Status == gomemcached.KEY_ENOENT {
return true
}
return false
}
// ClientOpCallback is called for each invocation of Do.
var ClientOpCallback func(opname, k string, start time.Time, err error)
// Do executes a function on a memcached connection to the node owning key "k"
//
// Note that this automatically handles transient errors by replaying
// your function on a "not-my-vbucket" error, so don't assume
// your command will only be executed only once.
func (b *Bucket) Do(k string, f func(mc *memcached.Client, vb uint16) error) (err error) {
if SlowServerCallWarningThreshold > 0 {
defer slowLog(time.Now(), "call to Do(%q)", k)
}
vb := b.VBHash(k)
maxTries := len(b.Nodes()) * 2
for i := 0; i < maxTries; i++ {
// We encapsulate the attempt within an anonymous function to allow
// "defer" statement to work as intended.
retry, err := func() (retry bool, err error) {
conn, pool, err := b.getConnectionToVBucket(vb)
if err != nil {
return
}
defer pool.Return(conn)
err = f(conn, uint16(vb))
if i, ok := err.(*gomemcached.MCResponse); ok {
st := i.Status
retry = st == gomemcached.NOT_MY_VBUCKET
}
return
}()
if retry {
b.Refresh()
} else {
return err
}
}
return fmt.Errorf("unable to complete action after %v attemps",
maxTries)
}
type GatheredStats struct {
Server string
Stats map[string]string
Err error
}
func getStatsParallel(sn string, b *Bucket, offset int, which string,
ch chan<- GatheredStats) {
pool := b.getConnPool(offset)
var gatheredStats GatheredStats
conn, err := pool.Get()
defer func() {
pool.Return(conn)
ch <- gatheredStats
}()
if err != nil {
gatheredStats = GatheredStats{Server: sn, Err: err}
} else {
sm, err := conn.StatsMap(which)
gatheredStats = GatheredStats{Server: sn, Stats: sm, Err: err}
}
}
// GetStats gets a set of stats from all servers.
//
// Returns a map of server ID -> map of stat key to map value.
func (b *Bucket) GetStats(which string) map[string]map[string]string {
rv := map[string]map[string]string{}
for server, gs := range b.GatherStats(which) {
if len(gs.Stats) > 0 {
rv[server] = gs.Stats
}
}
return rv
}
// GatherStats returns a map of server ID -> GatheredStats from all servers.
func (b *Bucket) GatherStats(which string) map[string]GatheredStats {
vsm := b.VBServerMap()
if vsm.ServerList == nil {
return nil
}
// Go grab all the things at once.
ch := make(chan GatheredStats, len(vsm.ServerList))
for i, sn := range vsm.ServerList {
go getStatsParallel(sn, b, i, which, ch)
}
// Gather the results
rv := map[string]GatheredStats{}
for range vsm.ServerList {
gs := <-ch
rv[gs.Server] = gs
}
return rv
}
func isAuthError(err error) bool {
estr := err.Error()
return strings.Contains(estr, "Auth failure")
}
func IsReadTimeOutError(err error) bool {
return strings.ContainsAny(err.Error(), "read tcp & i/o timeout")
}
// Errors that are not considered fatal for our fetch loop
func isConnError(err error) bool {
if err == io.EOF {
return true
}
estr := err.Error()
return strings.Contains(estr, "broken pipe") ||
strings.Contains(estr, "connection reset") ||
strings.Contains(estr, "connection refused") ||
strings.Contains(estr, "connection pool is closed")
}
func isOutOfBoundsError(err error) bool {
return strings.Contains(err.Error(), "Out of Bounds error")
}
func (b *Bucket) doBulkGet(vb uint16, keys []string, reqDeadline time.Time,
ch chan<- map[string]*gomemcached.MCResponse, ech chan<- error) {
if SlowServerCallWarningThreshold > 0 {
defer slowLog(time.Now(), "call to doBulkGet(%d, %d keys)", vb, len(keys))
}
rv := _STRING_MCRESPONSE_POOL.Get()
attempts := 0
done := false
for attempts < MaxBulkRetries && !done {
if len(b.VBServerMap().VBucketMap) < int(vb) {
//fatal
logging.Errorf("go-couchbase: vbmap smaller than requested vbucket number. vb %d vbmap len %d", vb, len(b.VBServerMap().VBucketMap))
err := fmt.Errorf("vbmap smaller than requested vbucket")
ech <- err
return
}
masterID := b.VBServerMap().VBucketMap[vb][0]
attempts++
if masterID < 0 {
// fatal
logging.Errorf("No master node available for vb %d", vb)
err := fmt.Errorf("No master node available for vb %d", vb)
ech <- err
return
}
// This stack frame exists to ensure we can clean up
// connection at a reasonable time.
err := func() error {
pool := b.getConnPool(masterID)
conn, err := pool.Get()
if err != nil {
if isAuthError(err) {
logging.Errorf(" Fatal Auth Error %v", err)
ech <- err
return err
} else if isConnError(err) {
// for a connection error, refresh right away
b.Refresh()
}
logging.Infof("Pool Get returned %v", err)
// retry
return nil
}
conn.SetReadDeadline(reqDeadline)
err = conn.GetBulk(vb, keys, rv)
conn.SetReadDeadline(time.Time{})
pool.Return(conn)
switch err.(type) {
case *gomemcached.MCResponse:
st := err.(*gomemcached.MCResponse).Status
if st == gomemcached.NOT_MY_VBUCKET {
b.Refresh()
// retry
err = nil
}
return err
case error:
if isOutOfBoundsError(err) {
// We got an out of bound error, retry the operation
return nil
} else if isConnError(err) {
logging.Errorf("Connection Error: %s. Refreshing bucket", err.Error())
b.Refresh()
// retry
return nil
}
ech <- err
ch <- rv
return err
}
done = true
return nil
}()
if err != nil {
return
}
}
if attempts == MaxBulkRetries {
ech <- fmt.Errorf("bulkget exceeded MaxBulkRetries for vbucket %d", vb)
}
ch <- rv
}
type vbBulkGet struct {
b *Bucket
ch chan<- map[string]*gomemcached.MCResponse
ech chan<- error
k uint16
keys []string
reqDeadline time.Time
wg *sync.WaitGroup
}
const _NUM_CHANNELS = 5
var _NUM_CHANNEL_WORKERS = (runtime.NumCPU() + 1) / 2
// Buffer 4k requests per worker
var _VB_BULK_GET_CHANNELS []chan *vbBulkGet
func InitBulkGet() {
_VB_BULK_GET_CHANNELS = make([]chan *vbBulkGet, _NUM_CHANNELS)
for i := 0; i < _NUM_CHANNELS; i++ {
channel := make(chan *vbBulkGet, 16*1024*_NUM_CHANNEL_WORKERS)
_VB_BULK_GET_CHANNELS[i] = channel
for j := 0; j < _NUM_CHANNEL_WORKERS; j++ {
go vbBulkGetWorker(channel)
}
}
}
func vbBulkGetWorker(ch chan *vbBulkGet) {
defer func() {
// Workers cannot panic and die
recover()
go vbBulkGetWorker(ch)
}()
for vbg := range ch {
vbDoBulkGet(vbg)
}
}
func vbDoBulkGet(vbg *vbBulkGet) {
defer vbg.wg.Done()
defer func() {
// Workers cannot panic and die
recover()
}()
vbg.b.doBulkGet(vbg.k, vbg.keys, vbg.reqDeadline, vbg.ch, vbg.ech)
}
var _ERR_CHAN_FULL = fmt.Errorf("Data request queue full, aborting query.")
func (b *Bucket) processBulkGet(kdm map[uint16][]string, reqDeadline time.Time,
ch chan<- map[string]*gomemcached.MCResponse, ech chan<- error) {
defer close(ch)
defer close(ech)
wg := &sync.WaitGroup{}
for k, keys := range kdm {
vbg := &vbBulkGet{
b: b,
ch: ch,
ech: ech,
k: k,
keys: keys,
reqDeadline: reqDeadline,
wg: wg,
}
wg.Add(1)
// Random int
// Right shift to avoid 8-byte alignment, and take low bits
c := (uintptr(unsafe.Pointer(vbg)) >> 4) % _NUM_CHANNELS
select {
case _VB_BULK_GET_CHANNELS[c] <- vbg:
// No-op
default:
// Buffer full, abandon the bulk get
ech <- _ERR_CHAN_FULL
wg.Add(-1)
}
}
// Wait for my vb bulk gets
wg.Wait()
}
type multiError []error
func (m multiError) Error() string {
if len(m) == 0 {
panic("Error of none")
}
return fmt.Sprintf("{%v errors, starting with %v}", len(m), m[0].Error())
}
// Convert a stream of errors from ech into a multiError (or nil) and
// send down eout.
//
// At least one send is guaranteed on eout, but two is possible, so
// buffer the out channel appropriately.
func errorCollector(ech <-chan error, eout chan<- error) {
defer func() { eout <- nil }()
var errs multiError
for e := range ech {
errs = append(errs, e)
}
if len(errs) > 0 {
eout <- errs
}
}
// Fetches multiple keys concurrently, with []byte values
//
// This is a wrapper around GetBulk which converts all values returned
// by GetBulk from raw memcached responses into []byte slices.
// Returns one document for duplicate keys
func (b *Bucket) GetBulkRaw(keys []string) (map[string][]byte, error) {
resp, keyCount, eout := b.getBulk(keys, time.Time{})
rv := make(map[string][]byte, len(keys))
for k, av := range resp {
rv[k] = av.Body
}
b.ReleaseGetBulkPools(keyCount, resp)
return rv, eout
}
// GetBulk fetches multiple keys concurrently.
//
// Unlike more convenient GETs, the entire response is returned in the
// map array for each key. Keys that were not found will not be included in
// the map.
func (b *Bucket) GetBulk(keys []string, reqDeadline time.Time) (map[string]*gomemcached.MCResponse, map[string]int, error) {
return b.getBulk(keys, reqDeadline)
}
func (b *Bucket) ReleaseGetBulkPools(keyCount map[string]int, rv map[string]*gomemcached.MCResponse) {
_STRING_KEYCOUNT_POOL.Put(keyCount)
_STRING_MCRESPONSE_POOL.Put(rv)
}
func (b *Bucket) getBulk(keys []string, reqDeadline time.Time) (map[string]*gomemcached.MCResponse, map[string]int, error) {
kdm := _VB_STRING_POOL.Get()
defer _VB_STRING_POOL.Put(kdm)
keyCount := _STRING_KEYCOUNT_POOL.Get()
for _, k := range keys {
v, ok := keyCount[k]
if !ok {
vb := uint16(b.VBHash(k))
a, ok1 := kdm[vb]
if !ok1 {
a = _STRING_POOL.Get()
}
kdm[vb] = append(a, k)
v = 0
}
keyCount[k] = v + 1
}
eout := make(chan error, 2)
// processBulkGet will own both of these channels and
// guarantee they're closed before it returns.
ch := make(chan map[string]*gomemcached.MCResponse)
ech := make(chan error)
go errorCollector(ech, eout)
go b.processBulkGet(kdm, reqDeadline, ch, ech)
var rv map[string]*gomemcached.MCResponse
for m := range ch {
if rv == nil {
rv = m
continue
}
for k, v := range m {
rv[k] = v
}
_STRING_MCRESPONSE_POOL.Put(m)
}
return rv, keyCount, <-eout
}
// WriteOptions is the set of option flags availble for the Write
// method. They are ORed together to specify the desired request.
type WriteOptions int
const (
// Raw specifies that the value is raw []byte or nil; don't
// JSON-encode it.
Raw = WriteOptions(1 << iota)
// AddOnly indicates an item should only be written if it
// doesn't exist, otherwise ErrKeyExists is returned.
AddOnly
// Persist causes the operation to block until the server
// confirms the item is persisted.
Persist
// Indexable causes the operation to block until it's availble via the index.
Indexable
// Append indicates the given value should be appended to the
// existing value for the given key.
Append
)
var optNames = []struct {
opt WriteOptions
name string
}{
{Raw, "raw"},
{AddOnly, "addonly"}, {Persist, "persist"},
{Indexable, "indexable"}, {Append, "append"},
}
// String representation of WriteOptions
func (w WriteOptions) String() string {
f := []string{}
for _, on := range optNames {
if w&on.opt != 0 {
f = append(f, on.name)
w &= ^on.opt
}
}
if len(f) == 0 || w != 0 {
f = append(f, fmt.Sprintf("0x%x", int(w)))
}
return strings.Join(f, "|")
}
// Error returned from Write with AddOnly flag, when key already exists in the bucket.
var ErrKeyExists = errors.New("key exists")
// General-purpose value setter.
//
// The Set, Add and Delete methods are just wrappers around this. The
// interpretation of `v` depends on whether the `Raw` option is
// given. If it is, v must be a byte array or nil. (A nil value causes
// a delete.) If `Raw` is not given, `v` will be marshaled as JSON
// before being written. It must be JSON-marshalable and it must not
// be nil.
func (b *Bucket) Write(k string, flags, exp int, v interface{},
opt WriteOptions) (err error) {
if ClientOpCallback != nil {
defer func(t time.Time) {
ClientOpCallback(fmt.Sprintf("Write(%v)", opt), k, t, err)
}(time.Now())
}
var data []byte
if opt&Raw == 0 {
data, err = json.Marshal(v)
if err != nil {
return err
}
} else if v != nil {
data = v.([]byte)
}
var res *gomemcached.MCResponse
err = b.Do(k, func(mc *memcached.Client, vb uint16) error {
if opt&AddOnly != 0 {
res, err = memcached.UnwrapMemcachedError(
mc.Add(vb, k, flags, exp, data))
if err == nil && res.Status != gomemcached.SUCCESS {
if res.Status == gomemcached.KEY_EEXISTS {
err = ErrKeyExists
} else {
err = res
}
}
} else if opt&Append != 0 {
res, err = mc.Append(vb, k, data)
} else if data == nil {
res, err = mc.Del(vb, k)
} else {
res, err = mc.Set(vb, k, flags, exp, data)
}
return err
})
if err == nil && (opt&(Persist|Indexable) != 0) {
err = b.WaitForPersistence(k, res.Cas, data == nil)
}
return err
}
func (b *Bucket) WriteWithMT(k string, flags, exp int, v interface{},
opt WriteOptions) (mt *MutationToken, err error) {
if ClientOpCallback != nil {
defer func(t time.Time) {
ClientOpCallback(fmt.Sprintf("WriteWithMT(%v)", opt), k, t, err)
}(time.Now())
}
var data []byte
if opt&Raw == 0 {
data, err = json.Marshal(v)
if err != nil {
return nil, err
}
} else if v != nil {
data = v.([]byte)
}
var res *gomemcached.MCResponse
err = b.Do(k, func(mc *memcached.Client, vb uint16) error {
if opt&AddOnly != 0 {
res, err = memcached.UnwrapMemcachedError(
mc.Add(vb, k, flags, exp, data))
if err == nil && res.Status != gomemcached.SUCCESS {
if res.Status == gomemcached.KEY_EEXISTS {
err = ErrKeyExists
} else {
err = res
}
}
} else if opt&Append != 0 {
res, err = mc.Append(vb, k, data)
} else if data == nil {
res, err = mc.Del(vb, k)
} else {
res, err = mc.Set(vb, k, flags, exp, data)
}
if len(res.Extras) >= 16 {
vbuuid := uint64(binary.BigEndian.Uint64(res.Extras[0:8]))
seqNo := uint64(binary.BigEndian.Uint64(res.Extras[8:16]))
mt = &MutationToken{VBid: vb, Guard: vbuuid, Value: seqNo}
}
return err
})
if err == nil && (opt&(Persist|Indexable) != 0) {
err = b.WaitForPersistence(k, res.Cas, data == nil)
}
return mt, err
}
// Set a value in this bucket with Cas and return the new Cas value
func (b *Bucket) Cas(k string, exp int, cas uint64, v interface{}) (uint64, error) {
return b.WriteCas(k, 0, exp, cas, v, 0)
}
// Set a value in this bucket with Cas without json encoding it
func (b *Bucket) CasRaw(k string, exp int, cas uint64, v interface{}) (uint64, error) {
return b.WriteCas(k, 0, exp, cas, v, Raw)
}
func (b *Bucket) WriteCas(k string, flags, exp int, cas uint64, v interface{},
opt WriteOptions) (newCas uint64, err error) {
if ClientOpCallback != nil {
defer func(t time.Time) {
ClientOpCallback(fmt.Sprintf("Write(%v)", opt), k, t, err)
}(time.Now())
}
var data []byte
if opt&Raw == 0 {
data, err = json.Marshal(v)
if err != nil {
return 0, err
}
} else if v != nil {
data = v.([]byte)
}
var res *gomemcached.MCResponse
err = b.Do(k, func(mc *memcached.Client, vb uint16) error {
res, err = mc.SetCas(vb, k, flags, exp, cas, data)
return err
})
if err == nil && (opt&(Persist|Indexable) != 0) {
err = b.WaitForPersistence(k, res.Cas, data == nil)
}
return res.Cas, err
}
// Extended CAS operation. These functions will return the mutation token, i.e vbuuid & guard
func (b *Bucket) CasWithMeta(k string, flags int, exp int, cas uint64, v interface{}) (uint64, *MutationToken, error) {
return b.WriteCasWithMT(k, flags, exp, cas, v, 0)
}
func (b *Bucket) CasWithMetaRaw(k string, flags int, exp int, cas uint64, v interface{}) (uint64, *MutationToken, error) {
return b.WriteCasWithMT(k, flags, exp, cas, v, Raw)
}
func (b *Bucket) WriteCasWithMT(k string, flags, exp int, cas uint64, v interface{},
opt WriteOptions) (newCas uint64, mt *MutationToken, err error) {
if ClientOpCallback != nil {
defer func(t time.Time) {
ClientOpCallback(fmt.Sprintf("Write(%v)", opt), k, t, err)
}(time.Now())
}
var data []byte
if opt&Raw == 0 {
data, err = json.Marshal(v)
if err != nil {
return 0, nil, err
}
} else if v != nil {
data = v.([]byte)
}
var res *gomemcached.MCResponse
err = b.Do(k, func(mc *memcached.Client, vb uint16) error {
res, err = mc.SetCas(vb, k, flags, exp, cas, data)
return err
})
if err != nil {
return 0, nil, err
}
// check for extras
if len(res.Extras) >= 16 {
vbuuid := uint64(binary.BigEndian.Uint64(res.Extras[0:8]))
seqNo := uint64(binary.BigEndian.Uint64(res.Extras[8:16]))
vb := b.VBHash(k)
mt = &MutationToken{VBid: uint16(vb), Guard: vbuuid, Value: seqNo}
}
if err == nil && (opt&(Persist|Indexable) != 0) {
err = b.WaitForPersistence(k, res.Cas, data == nil)
}
return res.Cas, mt, err
}
// Set a value in this bucket.
// The value will be serialized into a JSON document.
func (b *Bucket) Set(k string, exp int, v interface{}) error {
return b.Write(k, 0, exp, v, 0)
}
// Set a value in this bucket with with flags
func (b *Bucket) SetWithMeta(k string, flags int, exp int, v interface{}) (*MutationToken, error) {
return b.WriteWithMT(k, flags, exp, v, 0)
}
// SetRaw sets a value in this bucket without JSON encoding it.
func (b *Bucket) SetRaw(k string, exp int, v []byte) error {
return b.Write(k, 0, exp, v, Raw)
}
// Add adds a value to this bucket; like Set except that nothing
// happens if the key exists. The value will be serialized into a
// JSON document.
func (b *Bucket) Add(k string, exp int, v interface{}) (added bool, err error) {
err = b.Write(k, 0, exp, v, AddOnly)
if err == ErrKeyExists {
return false, nil
}
return (err == nil), err
}
// AddRaw adds a value to this bucket; like SetRaw except that nothing
// happens if the key exists. The value will be stored as raw bytes.
func (b *Bucket) AddRaw(k string, exp int, v []byte) (added bool, err error) {
err = b.Write(k, 0, exp, v, AddOnly|Raw)
if err == ErrKeyExists {
return false, nil
}
return (err == nil), err
}
// Add adds a value to this bucket; like Set except that nothing
// happens if the key exists. The value will be serialized into a
// JSON document.
func (b *Bucket) AddWithMT(k string, exp int, v interface{}) (added bool, mt *MutationToken, err error) {
mt, err = b.WriteWithMT(k, 0, exp, v, AddOnly)
if err == ErrKeyExists {
return false, mt, nil
}
return (err == nil), mt, err
}
// AddRaw adds a value to this bucket; like SetRaw except that nothing
// happens if the key exists. The value will be stored as raw bytes.
func (b *Bucket) AddRawWithMT(k string, exp int, v []byte) (added bool, mt *MutationToken, err error) {
mt, err = b.WriteWithMT(k, 0, exp, v, AddOnly|Raw)
if err == ErrKeyExists {
return false, mt, nil
}
return (err == nil), mt, err
}
// Append appends raw data to an existing item.
func (b *Bucket) Append(k string, data []byte) error {
return b.Write(k, 0, 0, data, Append|Raw)
}
// GetsRaw gets a raw value from this bucket including its CAS
// counter and flags.
func (b *Bucket) GetsRaw(k string) (data []byte, flags int,
cas uint64, err error) {
if ClientOpCallback != nil {
defer func(t time.Time) { ClientOpCallback("GetsRaw", k, t, err) }(time.Now())
}
err = b.Do(k, func(mc *memcached.Client, vb uint16) error {
res, err := mc.Get(vb, k)
if err != nil {
return err
}
cas = res.Cas
if len(res.Extras) >= 4 {
flags = int(binary.BigEndian.Uint32(res.Extras))
}
data = res.Body
return nil
})
return
}
// Gets gets a value from this bucket, including its CAS counter. The
// value is expected to be a JSON stream and will be deserialized into
// rv.
func (b *Bucket) Gets(k string, rv interface{}, caso *uint64) error {
data, _, cas, err := b.GetsRaw(k)
if err != nil {
return err
}
if caso != nil {
*caso = cas
}
return json.Unmarshal(data, rv)
}
// Get a value from this bucket.
// The value is expected to be a JSON stream and will be deserialized
// into rv.
func (b *Bucket) Get(k string, rv interface{}) error {
return b.Gets(k, rv, nil)
}
// GetRaw gets a raw value from this bucket. No marshaling is performed.
func (b *Bucket) GetRaw(k string) ([]byte, error) {
d, _, _, err := b.GetsRaw(k)
return d, err
}
// GetAndTouchRaw gets a raw value from this bucket including its CAS
// counter and flags, and updates the expiry on the doc.
func (b *Bucket) GetAndTouchRaw(k string, exp int) (data []byte,
cas uint64, err error) {
if ClientOpCallback != nil {
defer func(t time.Time) { ClientOpCallback("GetsRaw", k, t, err) }(time.Now())
}
err = b.Do(k, func(mc *memcached.Client, vb uint16) error {
res, err := mc.GetAndTouch(vb, k, exp)
if err != nil {
return err
}
cas = res.Cas
data = res.Body
return nil
})
return data, cas, err
}
// GetMeta returns the meta values for a key
func (b *Bucket) GetMeta(k string, flags *int, expiry *int, cas *uint64, seqNo *uint64) (err error) {
if ClientOpCallback != nil {
defer func(t time.Time) { ClientOpCallback("GetsMeta", k, t, err) }(time.Now())
}
err = b.Do(k, func(mc *memcached.Client, vb uint16) error {
res, err := mc.GetMeta(vb, k)
if err != nil {
return err
}
*cas = res.Cas
if len(res.Extras) >= 8 {
*flags = int(binary.BigEndian.Uint32(res.Extras[4:]))
}
if len(res.Extras) >= 12 {
*expiry = int(binary.BigEndian.Uint32(res.Extras[8:]))
}
if len(res.Extras) >= 20 {
*seqNo = uint64(binary.BigEndian.Uint64(res.Extras[12:]))
}
return nil
})
return err
}
// Delete a key from this bucket.
func (b *Bucket) Delete(k string) error {
return b.Write(k, 0, 0, nil, Raw)
}
// Incr increments the value at a given key by amt and defaults to def if no value present.
func (b *Bucket) Incr(k string, amt, def uint64, exp int) (val uint64, err error) {
if ClientOpCallback != nil {
defer func(t time.Time) { ClientOpCallback("Incr", k, t, err) }(time.Now())
}
var rv uint64
err = b.Do(k, func(mc *memcached.Client, vb uint16) error {
res, err := mc.Incr(vb, k, amt, def, exp)
if err != nil {
return err
}
rv = res
return nil
})
return rv, err
}
// Decr decrements the value at a given key by amt and defaults to def if no value present
func (b *Bucket) Decr(k string, amt, def uint64, exp int) (val uint64, err error) {
if ClientOpCallback != nil {
defer func(t time.Time) { ClientOpCallback("Decr", k, t, err) }(time.Now())
}
var rv uint64
err = b.Do(k, func(mc *memcached.Client, vb uint16) error {
res, err := mc.Decr(vb, k, amt, def, exp)
if err != nil {
return err
}
rv = res
return nil
})
return rv, err
}
// Wrapper around memcached.CASNext()
func (b *Bucket) casNext(k string, exp int, state *memcached.CASState) bool {
if ClientOpCallback != nil {
defer func(t time.Time) {
ClientOpCallback("casNext", k, t, state.Err)
}(time.Now())
}
keepGoing := false
state.Err = b.Do(k, func(mc *memcached.Client, vb uint16) error {
keepGoing = mc.CASNext(vb, k, exp, state)
return state.Err
})
return keepGoing && state.Err == nil
}
// An UpdateFunc is a callback function to update a document
type UpdateFunc func(current []byte) (updated []byte, err error)
// Return this as the error from an UpdateFunc to cancel the Update
// operation.
const UpdateCancel = memcached.CASQuit
// Update performs a Safe update of a document, avoiding conflicts by
// using CAS.
//
// The callback function will be invoked with the current raw document