forked from hazelcast/hazelcast-go-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy_map.go
1694 lines (1520 loc) · 62.3 KB
/
proxy_map.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
/*
* Copyright (c) 2008-2023, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 hazelcast
import (
"context"
"fmt"
"strings"
"time"
"github.com/hazelcast/hazelcast-go-client/aggregate"
"github.com/hazelcast/hazelcast-go-client/internal/cb"
ihzerrors "github.com/hazelcast/hazelcast-go-client/internal/hzerrors"
"github.com/hazelcast/hazelcast-go-client/internal/proto"
"github.com/hazelcast/hazelcast-go-client/internal/proto/codec"
iproxy "github.com/hazelcast/hazelcast-go-client/internal/proxy"
"github.com/hazelcast/hazelcast-go-client/internal/serialization"
"github.com/hazelcast/hazelcast-go-client/nearcache"
"github.com/hazelcast/hazelcast-go-client/predicate"
"github.com/hazelcast/hazelcast-go-client/types"
)
/*
Map is a distributed map.
Hazelcast Go client enables you to perform operations like reading and writing from/to a Hazelcast Map with methods like Get and Put.
For details, see https://docs.hazelcast.com/imdg/latest/data-structures/map.html
# Listening for Map Events
To listen events of a map, you can use the AddListener, AddListenerWithKey, AddListenerWithPredicate and AddListenerWithPredicateAndKey methods.
The first method adds a listener to the map's all events. The others filter the events depending on a key and/or a predicate.
In all methods you specify whether you want to include value in the event or not.
You can pass a MapListener struct to these methods to add handlers to different event types. You can add different handlers to different event types
with a single MapListener struct. If you don't specify a handler in for an event type in MapListener struct, there will be no handler for that event.
In the example below, a listener for added and updated entry events is created. Entries only with key "somekey" and matching to predicate year > 2000 are considered:
entryListenerConfig := hazelcast.MapEntryListenerConfig{
Key: "somekey",
Predicate: predicate.Greater("year", 2000),
IncludeValue: true,
}
m, err := client.GetMap(ctx, "somemap")
// error checking is omitted.
subscriptionID, err := m.AddListenerWithPredicateAndKey(ctx, hazelcast.MapListener{
EntryAdded: func(event *hazelcast.EntryNotified) {
fmt.Println("Entry Added:", event.Value)
},
EntryRemoved: func(event *hazelcast.EntryNotified) {
fmt.Println("Entry Removed:", event.Value)
},
}, predicate.Greater("year", 2000), "somekey", true)
// error checking is omitted.
Adding an event listener returns a subscription ID, which you can later use to remove the listener:
err = m.RemoveListener(ctx, subscriptionID)
# Using Locks
You can lock entries in a Map.
When an entry is locked, only the owner of that lock can access that entry in the cluster until it is unlocked by the owner of force unlocked.
See https://docs.hazelcast.com/imdg/latest/data-structures/map.html#locking-maps for details.
Locks are reentrant.
The owner of a lock can acquire the lock again without waiting for the lock to be unlocked.
If the key is locked N times, it should be unlocked N times before another goroutine can acquire it.
Lock ownership in Hazelcast Go Client is explicit.
The first step to own a lock is creating a lock context, which is similar to a key.
The lock context is a regular context.Context which carry a special value that uniquely identifies the lock context in the cluster.
Once the lock context is created, it can be used to lock/unlock entries and used with any function that is lock aware, such as Put.
m, err := client.GetMap(ctx, "my-map")
lockCtx := m.NewLockContext(ctx)
// block acquiring the lock
err = m.Lock(lockCtx, "some-key")
// pass lock context to use the locked entry
err = m.Set(lockCtx, "some-key", "some-value")
// release the lock once done with it
err = m.Unlock(lockCtx, "some-key")
As mentioned before, lock context is a regular context.Context which carry a special lock ID.
You can pass any context.Context to any Map function, but in that case lock ownership between operations using the same hazelcast.Client instance is not possible.
# Using the Near Cache
Map entries in Hazelcast are partitioned across the cluster members.
Hazelcast clients do not have local data at all.
Suppose you read the key k a number of times from a Hazelcast client or k is owned by another member in your cluster.
Then each map.Get(k) will be a remote operation, which creates a lot of network trips.
If you have a data structure that is mostly read, then you should consider creating a local Near Cache, so that reads are sped up and less network traffic is created.
These benefits do not come for free. See the following trade-offs:
- Clients with a Near Cache has to hold the extra cached data, which increases memory consumption.
- If invalidation is enabled and entries are updated frequently, then invalidations will be costly.
- Near Cache breaks the strong consistency guarantees; you might be reading stale data.
Near Cache is highly recommended for data structures that are mostly read.
You must enable the Near Cache on the client, without the need to configure it on the server.
Note that Near Cache configuration is specific to the server or client itself.
A data structure on a server may not have Near Cache configured while the same data structure on a client may have Near Cache configured.
They also can have different Near Cache configurations.
If you are using the Near Cache, you should take into account that your hits to the keys in the Near Cache are not reflected as hits to the original keys on the primary members.
This has for example an impact on Map's maximum idle seconds or time-to-live seconds expiration.
Therefore, even though there is a hit on a key in Near Cache, your original key on the primary member may expire.
Note: Near Cache works only when you access data via map.Get(k).
Data returned using a predicate or an SQL query is not stored in the Near Cache.
Checkout the nearcache package for configuration options.
Warning: Storing keys in serialized form is required when the key cannot be compared for equality, such as slices.
That can be accomplished by setting SerializeKeys: true, shown in the example below:
ncc := nearcache.Config{
Name: "mymap*",
SerializeKeys: true
}
The following types cannot be used as keys without setting SerializeKeys==true:
- Maps
- Slices
- Structs with having at least one field with an incomparable type.
Following Map methods support the Near Cache:
- Clear
- ContainsKey
- Delete
- Evict
- EvictAll
- ExecuteOnKey
- ExecuteOnKeys
- Get
- GetAll
- LoadAllReplacing
- LoadAllWithoutReplacing
- LocalMapStats
- Put
- PutWithMaxIdle
- PutWithTTL
- PutWithTTLAndMaxIdle
- PutAll
- PutIfAbsent
- PutIfAbsentWithTTL
- PutIfAbsentWithTTLAndMaxIdle
- PutTransient
- PutTransientWithMaxIdle
- PutTransientWithTTL
- PutTransientWithTTLAndMaxIdle
- Remove
- RemoveIfSame
- RemoveAll
- Replace
- ReplaceIfSame
- Set
- SetWithTTL
- SetWithTTLAndMaxIdle
- TryPut
- TryPutWithTimeout
- TryRemove
- TryRemoveWithTimeout
*/
type Map struct {
*proxy
ncm nearCacheMap
hasNearCache bool
}
func newMap(p *proxy) *Map {
return &Map{proxy: p}
}
// NewLockContext augments the passed parent context with a unique lock ID.
// If passed context is nil, context.Background is used as the parent context.
// Deprecated: Use hazelcast.NewLockContext() instead.
func (m *Map) NewLockContext(ctx context.Context) context.Context {
return NewLockContext(ctx)
}
type MapListener struct {
EntryAdded func(event *EntryNotified)
EntryRemoved func(event *EntryNotified)
EntryUpdated func(event *EntryNotified)
EntryEvicted func(event *EntryNotified)
EntryExpired func(event *EntryNotified)
MapEvicted func(event *EntryNotified)
MapCleared func(event *EntryNotified)
EntryMerged func(event *EntryNotified)
EntryLoaded func(event *EntryNotified)
}
func (m *Map) prepareFlagsOfMapListener(listener MapListener) int32 {
var flags int32
if listener.EntryAdded != nil {
flagsSetOrClear(&flags, int32(EntryAdded), true)
}
if listener.EntryEvicted != nil {
flagsSetOrClear(&flags, int32(EntryEvicted), true)
}
if listener.EntryExpired != nil {
flagsSetOrClear(&flags, int32(EntryExpired), true)
}
if listener.EntryLoaded != nil {
flagsSetOrClear(&flags, int32(EntryLoaded), true)
}
if listener.EntryMerged != nil {
flagsSetOrClear(&flags, int32(EntryMerged), true)
}
if listener.EntryRemoved != nil {
flagsSetOrClear(&flags, int32(EntryRemoved), true)
}
if listener.EntryUpdated != nil {
flagsSetOrClear(&flags, int32(EntryUpdated), true)
}
if listener.MapCleared != nil {
flagsSetOrClear(&flags, int32(EntryAllCleared), true)
}
if listener.MapEvicted != nil {
flagsSetOrClear(&flags, int32(EntryAllEvicted), true)
}
return flags
}
func (m *Map) mapListenerEventHandler(listener MapListener) EntryNotifiedHandler {
return func(event *EntryNotified) {
switch event.EventType {
case EntryAdded:
listener.EntryAdded(event)
case EntryUpdated:
listener.EntryUpdated(event)
case EntryRemoved:
listener.EntryRemoved(event)
case EntryEvicted:
listener.EntryEvicted(event)
case EntryExpired:
listener.EntryExpired(event)
case EntryMerged:
listener.EntryMerged(event)
case EntryLoaded:
listener.EntryLoaded(event)
case EntryAllCleared:
listener.MapCleared(event)
case EntryAllEvicted:
listener.MapEvicted(event)
default:
m.logger.Warnf("Not a known map event type: %d", event.EventType)
}
}
}
// AddListener adds a continuous entry listener to this map.
func (m *Map) AddListener(ctx context.Context, listener MapListener, includeValue bool) (types.UUID, error) {
flags := m.prepareFlagsOfMapListener(listener)
return m.addEntryListener(ctx, flags, includeValue, nil, nil, m.mapListenerEventHandler(listener))
}
// AddListenerWithKey adds a continuous entry listener on a specific key to this map.
func (m *Map) AddListenerWithKey(ctx context.Context, listener MapListener, key interface{}, includeValue bool) (types.UUID, error) {
flags := m.prepareFlagsOfMapListener(listener)
return m.addEntryListener(ctx, flags, includeValue, key, nil, m.mapListenerEventHandler(listener))
}
// AddListenerWithPredicate adds a continuous entry listener to this map. Events are filtered by a predicate.
func (m *Map) AddListenerWithPredicate(ctx context.Context, listener MapListener, predicate predicate.Predicate, includeValue bool) (types.UUID, error) {
flags := m.prepareFlagsOfMapListener(listener)
return m.addEntryListener(ctx, flags, includeValue, nil, predicate, m.mapListenerEventHandler(listener))
}
// AddListenerWithPredicateAndKey adds a continuous entry listener on a specific key to this map. Events are filtered by a predicate.
func (m *Map) AddListenerWithPredicateAndKey(ctx context.Context, listener MapListener, predicate predicate.Predicate, key interface{}, includeValue bool) (types.UUID, error) {
flags := m.prepareFlagsOfMapListener(listener)
return m.addEntryListener(ctx, flags, includeValue, key, predicate, m.mapListenerEventHandler(listener))
}
// AddEntryListener adds a continuous entry listener to this map.
// Deprecated: In favor of AddListener, AddListenerWithKey, AddListenerWithPredicate,
// AddListenerWithPredicateAndKey methods.
func (m *Map) AddEntryListener(ctx context.Context, config MapEntryListenerConfig, handler EntryNotifiedHandler) (types.UUID, error) {
return m.addEntryListener(ctx, config.flags, config.IncludeValue, config.Key, config.Predicate, handler)
}
// AddIndex adds an index to this map for the specified entries so that queries can run faster.
func (m *Map) AddIndex(ctx context.Context, indexConfig types.IndexConfig) error {
return m.addIndex(ctx, indexConfig)
}
// AddInterceptor adds an interceptor for this map.
func (m *Map) AddInterceptor(ctx context.Context, interceptor interface{}) (string, error) {
if interceptorData, err := m.proxy.convertToData(interceptor); err != nil {
return "", err
} else {
request := codec.EncodeMapAddInterceptorRequest(m.name, interceptorData)
if response, err := m.invokeOnRandomTarget(ctx, request, nil); err != nil {
return "", err
} else {
return codec.DecodeMapAddInterceptorResponse(response), nil
}
}
}
// Aggregate runs the given aggregator and returns the result.
func (m *Map) Aggregate(ctx context.Context, agg aggregate.Aggregator) (interface{}, error) {
aggData, err := m.validateAndSerializeAggregate(agg)
if err != nil {
return nil, err
}
request := codec.EncodeMapAggregateRequest(m.name, aggData)
return m.aggregate(ctx, request, codec.DecodeMapAggregateResponse)
}
// AggregateWithPredicate runs the given aggregator and returns the result.
// The result is filtered with the given predicate.
func (m *Map) AggregateWithPredicate(ctx context.Context, agg aggregate.Aggregator, pred predicate.Predicate) (interface{}, error) {
aggData, err := m.validateAndSerializeAggregate(agg)
if err != nil {
return nil, err
}
predData, err := m.validateAndSerializePredicate(pred)
if err != nil {
return nil, err
}
request := codec.EncodeMapAggregateWithPredicateRequest(m.name, aggData, predData)
return m.aggregate(ctx, request, codec.DecodeMapAggregateWithPredicateResponse)
}
// Clear deletes all entries one by one and fires related events.
func (m *Map) Clear(ctx context.Context) error {
if m.hasNearCache {
return m.ncm.Clear(ctx, m)
}
return m.clearFromRemote(ctx)
}
// ContainsKey returns true if the map contains an entry with the given key.
func (m *Map) ContainsKey(ctx context.Context, key interface{}) (bool, error) {
if m.hasNearCache {
return m.ncm.ContainsKey(ctx, key, m)
}
return m.containsKeyFromRemote(ctx, key)
}
// ContainsValue returns true if the map contains an entry with the given value.
func (m *Map) ContainsValue(ctx context.Context, value interface{}) (bool, error) {
if valueData, err := m.validateAndSerialize(value); err != nil {
return false, err
} else {
request := codec.EncodeMapContainsValueRequest(m.name, valueData)
if response, err := m.invokeOnRandomTarget(ctx, request, nil); err != nil {
return false, err
} else {
return codec.DecodeMapContainsValueResponse(response), nil
}
}
}
// Delete removes the mapping for a key from this map if it is present.
// Unlike remove(object), this operation does not return the removed value, which avoids the serialization cost of
// the returned value. If the removed value will not be used, a delete operation is preferred over a remove
// operation for better performance.
func (m *Map) Delete(ctx context.Context, key interface{}) error {
if m.hasNearCache {
return m.ncm.Delete(ctx, m, key)
}
return m.deleteFromRemote(ctx, key)
}
// Evict evicts the mapping for a key from this map.
// Returns true if the key is evicted.
func (m *Map) Evict(ctx context.Context, key interface{}) (bool, error) {
if m.hasNearCache {
return m.ncm.Evict(ctx, m, key)
}
return m.evictFromRemote(ctx, key)
}
// EvictAll deletes all entries without firing related events.
func (m *Map) EvictAll(ctx context.Context) error {
if m.hasNearCache {
return m.ncm.EvictAll(ctx, m)
}
return m.evictAllFromRemote(ctx)
}
// ExecuteOnEntries applies the user defined EntryProcessor to all the entries in the map.
func (m *Map) ExecuteOnEntries(ctx context.Context, entryProcessor interface{}) ([]types.Entry, error) {
processorData, err := m.validateAndSerialize(entryProcessor)
if err != nil {
return nil, err
}
request := codec.EncodeMapExecuteOnAllKeysRequest(m.name, processorData)
resp, err := m.invokeOnRandomTarget(ctx, request, nil)
if err != nil {
return nil, err
}
pairs := codec.DecodeMapExecuteOnAllKeysResponse(resp)
kvPairs, err := m.convertPairsToEntries(pairs)
if err != nil {
return nil, err
}
return kvPairs, nil
}
// ExecuteOnKey applies the user defined EntryProcessor to the entry with the specified key in the map.
func (m *Map) ExecuteOnKey(ctx context.Context, entryProcessor interface{}, key interface{}) (interface{}, error) {
if m.hasNearCache {
return m.ncm.ExecuteOnKey(ctx, m, entryProcessor, key)
}
return m.executeOnKeyFromRemote(ctx, entryProcessor, key)
}
// ExecuteOnKeys applies the user defined EntryProcessor to the entries with the specified keys in the map.
func (m *Map) ExecuteOnKeys(ctx context.Context, entryProcessor interface{}, keys ...interface{}) ([]interface{}, error) {
if m.hasNearCache {
return m.ncm.ExecuteOnKeys(ctx, m, entryProcessor, keys)
}
return m.executeOnKeysFromRemote(ctx, entryProcessor, keys)
}
// ExecuteOnEntriesWithPredicate applies the user defined EntryProcessor to all the entries in the map which satisfies the predicate.
func (m *Map) ExecuteOnEntriesWithPredicate(ctx context.Context, entryProcessor interface{}, pred predicate.Predicate) ([]types.Entry, error) {
processorData, err := m.validateAndSerialize(entryProcessor)
if err != nil {
return nil, err
}
predData, err := m.validateAndSerializePredicate(pred)
if err != nil {
return nil, err
}
request := codec.EncodeMapExecuteWithPredicateRequest(m.name, processorData, predData)
resp, err := m.invokeOnRandomTarget(ctx, request, nil)
if err != nil {
return nil, err
}
pairs := codec.DecodeMapExecuteWithPredicateResponse(resp)
kvPairs, err := m.convertPairsToEntries(pairs)
if err != nil {
return nil, err
}
return kvPairs, nil
}
// Flush flushes all the local dirty entries.
func (m *Map) Flush(ctx context.Context) error {
request := codec.EncodeMapFlushRequest(m.name)
_, err := m.invokeOnRandomTarget(ctx, request, nil)
return err
}
// ForceUnlock releases the lock for the specified key regardless of the lock owner.
// It always successfully unlocks the key, never blocks, and returns immediately.
func (m *Map) ForceUnlock(ctx context.Context, key interface{}) error {
if keyData, err := m.validateAndSerialize(key); err != nil {
return err
} else {
refID := m.refIDGen.NextID()
request := codec.EncodeMapForceUnlockRequest(m.name, keyData, refID)
_, err = m.invokeOnKey(ctx, request, keyData)
return err
}
}
// Get returns the value for the specified key, or nil if this map does not contain this key.
// Warning: This method returns a clone of original value, modifying the returned value does not change the actual value in the map.
// One should put modified value back to make changes visible to all nodes.
func (m *Map) Get(ctx context.Context, key interface{}) (interface{}, error) {
if m.hasNearCache {
return m.ncm.Get(ctx, m, key)
}
keyData, err := m.validateAndSerialize(key)
if err != nil {
return nil, err
}
return m.getFromRemote(ctx, keyData)
}
func (m *Map) clearFromRemote(ctx context.Context) error {
request := codec.EncodeMapClearRequest(m.name)
_, err := m.invokeOnRandomTarget(ctx, request, nil)
return err
}
func (m *Map) containsKeyFromRemote(ctx context.Context, key interface{}) (bool, error) {
lid := iproxy.ExtractLockID(ctx)
keyData, err := m.validateAndSerialize(key)
if err != nil {
return false, err
}
request := codec.EncodeMapContainsKeyRequest(m.name, keyData, lid)
response, err := m.invokeOnKey(ctx, request, keyData)
if err != nil {
return false, err
}
return codec.DecodeMapContainsKeyResponse(response), nil
}
func (m *Map) evictFromRemote(ctx context.Context, key interface{}) (bool, error) {
keyData, err := m.validateAndSerialize(key)
if err != nil {
return false, err
}
lid := iproxy.ExtractLockID(ctx)
request := codec.EncodeMapEvictRequest(m.name, keyData, lid)
response, err := m.invokeOnKey(ctx, request, keyData)
if err != nil {
return false, err
}
return codec.DecodeMapEvictResponse(response), nil
}
func (m *Map) evictAllFromRemote(ctx context.Context) error {
request := codec.EncodeMapEvictAllRequest(m.name)
_, err := m.invokeOnRandomTarget(ctx, request, nil)
return err
}
func (m *Map) executeOnKeyFromRemote(ctx context.Context, entryProcessor interface{}, key interface{}) (interface{}, error) {
processorData, err := m.validateAndSerialize(entryProcessor)
if err != nil {
return nil, err
}
keyData, err := m.validateAndSerialize(key)
if err != nil {
return nil, err
}
lid := iproxy.ExtractLockID(ctx)
request := codec.EncodeMapExecuteOnKeyRequest(m.name, processorData, keyData, lid)
resp, err := m.invokeOnKey(ctx, request, keyData)
if err != nil {
return nil, err
}
return m.convertToObject(codec.DecodeMapExecuteOnKeyResponse(resp))
}
func (m *Map) executeOnKeysFromRemote(ctx context.Context, entryProcessor interface{}, keys []interface{}) ([]interface{}, error) {
if len(keys) == 0 {
return nil, nil
}
processorData, err := m.validateAndSerialize(entryProcessor)
if err != nil {
return nil, err
}
keysDataList, err := m.convertToDataList(keys)
if err != nil {
return nil, err
}
request := codec.EncodeMapExecuteOnKeysRequest(m.name, processorData, keysDataList)
resp, err := m.invokeOnRandomTarget(ctx, request, nil)
if err != nil {
return nil, err
}
pairs := codec.DecodeMapExecuteOnKeysResponse(resp)
return m.convertPairsToValues(pairs)
}
func (m *Map) getFromRemote(ctx context.Context, keyData serialization.Data) (interface{}, error) {
lid := iproxy.ExtractLockID(ctx)
request := codec.EncodeMapGetRequest(m.name, keyData, lid)
response, err := m.invokeOnKey(ctx, request, keyData)
if err != nil {
return nil, err
}
return m.convertToObject(codec.DecodeMapGetResponse(response))
}
func (m *Map) getAllFromRemote(ctx context.Context, keyCount int, partitionToKeys map[int32][]serialization.Data) ([]proto.Pair, error) {
futures := make([]cb.Future, 0, len(partitionToKeys))
for pid, ks := range partitionToKeys {
request := codec.EncodeMapGetAllRequest(m.name, ks)
fut := m.invoker.CB().TryContextFuture(ctx, func(ctx context.Context, attempt int) (interface{}, error) {
if attempt > 0 {
request = request.Copy()
}
return m.invokeOnPartition(ctx, request, pid)
})
futures = append(futures, fut)
}
result := make([]proto.Pair, 0, keyCount)
for _, fut := range futures {
fr, err := fut.Result()
if err != nil {
return nil, err
}
pairs := codec.DecodeMapGetAllResponse(fr.(*proto.ClientMessage))
result = append(result, pairs...)
}
return result, nil
}
func (m *Map) deleteFromRemote(ctx context.Context, key interface{}) error {
lid := iproxy.ExtractLockID(ctx)
keyData, err := m.validateAndSerialize(key)
if err != nil {
return err
}
request := codec.EncodeMapDeleteRequest(m.name, keyData, lid)
if _, err := m.invokeOnKey(ctx, request, keyData); err != nil {
return err
}
return nil
}
func (m *Map) loadAllFromRemote(ctx context.Context, replaceExisting bool, keys []interface{}) error {
var request *proto.ClientMessage
if len(keys) == 0 {
request = codec.EncodeMapLoadAllRequest(m.name, replaceExisting)
} else {
keyDatas, err := m.convertToDataList(keys)
if err != nil {
return err
}
request = codec.EncodeMapLoadGivenKeysRequest(m.name, keyDatas, replaceExisting)
}
_, err := m.invokeOnRandomTarget(ctx, request, nil)
return err
}
func (m *Map) putAllFromRemote(ctx context.Context, entries []types.Entry) error {
f := func(partitionID int32, entries []proto.Pair) cb.Future {
request := codec.EncodeMapPutAllRequest(m.name, entries, true)
now := time.Now()
return m.invoker.CB().TryContextFuture(ctx, func(ctx context.Context, attempt int) (interface{}, error) {
if attempt > 0 {
request = request.Copy()
}
if inv, err := m.invokeOnPartitionAsync(ctx, request, partitionID, now); err != nil {
return nil, err
} else {
return inv.GetWithContext(ctx)
}
})
}
return m.putAll(entries, f)
}
func (m *Map) putWithTTLFromRemote(ctx context.Context, key, value interface{}, ttl int64) (interface{}, error) {
lid := iproxy.ExtractLockID(ctx)
keyData, valueData, err := m.validateAndSerialize2(key, value)
if err != nil {
return false, err
}
request := codec.EncodeMapPutRequest(m.name, keyData, valueData, lid, ttl)
response, err := m.invokeOnKey(ctx, request, keyData)
if err != nil {
return nil, err
}
return m.convertToObject(codec.DecodeMapPutResponse(response))
}
func (m *Map) putWithMaxIdleFromRemote(ctx context.Context, key, value interface{}, ttl int64, maxIdle int64) (interface{}, error) {
lid := iproxy.ExtractLockID(ctx)
keyData, valueData, err := m.validateAndSerialize2(key, value)
if err != nil {
return false, err
}
request := codec.EncodeMapPutWithMaxIdleRequest(m.name, keyData, valueData, lid, ttl, maxIdle)
response, err := m.invokeOnKey(ctx, request, keyData)
if err != nil {
return nil, err
}
return m.convertToObject(codec.DecodeMapPutWithMaxIdleResponse(response))
}
func (m *Map) putTransientWithTTLFromRemote(ctx context.Context, key, value interface{}, ttl int64) error {
keyData, valueData, err := m.validateAndSerialize2(key, value)
if err != nil {
return err
}
lid := iproxy.ExtractLockID(ctx)
request := codec.EncodeMapPutTransientRequest(m.name, keyData, valueData, lid, ttl)
_, err = m.invokeOnKey(ctx, request, keyData)
return err
}
func (m *Map) putTransientWithTTLAndMaxIdleFromRemote(ctx context.Context, key interface{}, value interface{}, ttl int64, maxIdle int64) error {
keyData, valueData, err := m.validateAndSerialize2(key, value)
if err != nil {
return err
}
lid := iproxy.ExtractLockID(ctx)
request := codec.EncodeMapPutTransientWithMaxIdleRequest(m.name, keyData, valueData, lid, ttl, maxIdle)
_, err = m.invokeOnKey(ctx, request, keyData)
return err
}
func (m *Map) putIfAbsentWithTTLFromRemote(ctx context.Context, key interface{}, value interface{}, ttl int64) (interface{}, error) {
keyData, valueData, err := m.validateAndSerialize2(key, value)
if err != nil {
return nil, err
}
lid := iproxy.ExtractLockID(ctx)
request := codec.EncodeMapPutIfAbsentRequest(m.name, keyData, valueData, lid, ttl)
response, err := m.invokeOnKey(ctx, request, keyData)
if err != nil {
return nil, err
}
return m.convertToObject(codec.DecodeMapPutIfAbsentResponse(response))
}
func (m *Map) putIfAbsentWithTTLAndMaxIdleFromRemote(ctx context.Context, key interface{}, value interface{}, ttl time.Duration, maxIdle time.Duration) (interface{}, error) {
keyData, valueData, err := m.validateAndSerialize2(key, value)
if err != nil {
return nil, err
}
lid := iproxy.ExtractLockID(ctx)
request := codec.EncodeMapPutIfAbsentWithMaxIdleRequest(m.name, keyData, valueData, lid, ttl.Milliseconds(), maxIdle.Milliseconds())
response, err := m.invokeOnKey(ctx, request, keyData)
if err != nil {
return nil, err
}
return m.convertToObject(codec.DecodeMapPutIfAbsentWithMaxIdleResponse(response))
}
func (m *Map) removeFromRemote(ctx context.Context, key interface{}) (interface{}, error) {
lid := iproxy.ExtractLockID(ctx)
keyData, err := m.validateAndSerialize(key)
if err != nil {
return nil, err
}
request := codec.EncodeMapRemoveRequest(m.name, keyData, lid)
response, err := m.invokeOnKey(ctx, request, keyData)
if err != nil {
return nil, err
}
return m.convertToObject(codec.DecodeMapRemoveResponse(response))
}
func (m *Map) removeAllFromRemote(ctx context.Context, predicate predicate.Predicate) error {
predicateData, err := m.validateAndSerialize(predicate)
if err != nil {
return err
}
request := codec.EncodeMapRemoveAllRequest(m.name, predicateData)
_, err = m.invokeOnRandomTarget(ctx, request, nil)
return err
}
func (m *Map) replaceFromRemote(ctx context.Context, key interface{}, value interface{}) (interface{}, error) {
keyData, valueData, err := m.validateAndSerialize2(key, value)
if err != nil {
return nil, err
}
lid := iproxy.ExtractLockID(ctx)
request := codec.EncodeMapReplaceRequest(m.name, keyData, valueData, lid)
response, err := m.invokeOnKey(ctx, request, keyData)
if err != nil {
return nil, err
}
return m.convertToObject(codec.DecodeMapReplaceResponse(response))
}
func (m *Map) replaceIfSameFromRemote(ctx context.Context, key interface{}, oldValue interface{}, newValue interface{}) (bool, error) {
lid := iproxy.ExtractLockID(ctx)
keyData, oldValueData, newValueData, err := m.validateAndSerialize3(key, oldValue, newValue)
if err != nil {
return false, err
}
request := codec.EncodeMapReplaceIfSameRequest(m.name, keyData, oldValueData, newValueData, lid)
response, err := m.invokeOnKey(ctx, request, keyData)
if err != nil {
return false, err
}
return codec.DecodeMapReplaceIfSameResponse(response), nil
}
func (m *Map) removeIfSameFromRemote(ctx context.Context, key, value interface{}) (bool, error) {
lid := iproxy.ExtractLockID(ctx)
keyData, valueData, err := m.validateAndSerialize2(key, value)
if err != nil {
return false, err
}
request := codec.EncodeMapRemoveIfSameRequest(m.name, keyData, valueData, lid)
response, err := m.invokeOnKey(ctx, request, keyData)
if err != nil {
return false, err
}
return codec.DecodeMapRemoveIfSameResponse(response), nil
}
func (m *Map) setFromRemote(ctx context.Context, key, value interface{}, ttl int64) error {
lid := iproxy.ExtractLockID(ctx)
keyData, valueData, err := m.validateAndSerialize2(key, value)
if err != nil {
return err
}
request := codec.EncodeMapSetRequest(m.name, keyData, valueData, lid, ttl)
if _, err := m.invokeOnKey(ctx, request, keyData); err != nil {
return err
}
return nil
}
func (m *Map) setWithTTLAndMaxIdleFromRemote(ctx context.Context, key, value interface{}, ttl time.Duration, maxIdle time.Duration) error {
lid := iproxy.ExtractLockID(ctx)
keyData, valueData, err := m.validateAndSerialize2(key, value)
if err != nil {
return err
}
request := codec.EncodeMapSetWithMaxIdleRequest(m.name, keyData, valueData, lid, ttl.Milliseconds(), maxIdle.Milliseconds())
if _, err := m.invokeOnKey(ctx, request, keyData); err != nil {
return err
}
return nil
}
func (m *Map) tryRemoveFromRemote(ctx context.Context, key interface{}, timeout int64) (bool, error) {
lid := iproxy.ExtractLockID(ctx)
keyData, err := m.validateAndSerialize(key)
if err != nil {
return false, err
}
request := codec.EncodeMapTryRemoveRequest(m.name, keyData, lid, timeout)
response, err := m.invokeOnKey(ctx, request, keyData)
if err != nil {
return false, err
}
return codec.DecodeMapTryRemoveResponse(response), nil
}
func (m *Map) tryPutFromRemote(ctx context.Context, key interface{}, value interface{}, timeout int64) (bool, error) {
lid := iproxy.ExtractLockID(ctx)
keyData, valueData, err := m.validateAndSerialize2(key, value)
if err != nil {
return false, err
}
request := codec.EncodeMapTryPutRequest(m.name, keyData, valueData, lid, timeout)
response, err := m.invokeOnKey(ctx, request, keyData)
if err != nil {
return false, err
}
return codec.DecodeMapTryPutResponse(response), nil
}
// GetAll returns the entries for the given keys.
func (m *Map) GetAll(ctx context.Context, keys ...interface{}) ([]types.Entry, error) {
if len(keys) == 0 {
return nil, nil
}
if ctx == nil {
ctx = context.Background()
}
if m.hasNearCache {
return m.ncm.GetAll(ctx, m, keys)
}
return m.getAll(ctx, keys)
}
func (m *Map) getAll(ctx context.Context, keys []interface{}) ([]types.Entry, error) {
partitionToKeys, err := m.partitionToKeys(keys, false)
if err != nil {
return nil, err
}
pairs, err := m.getAllFromRemote(ctx, len(keys), partitionToKeys)
if err != nil {
return nil, err
}
return m.convertPairsToEntries(pairs)
}
// GetEntrySet returns a clone of the mappings contained in this map.
func (m *Map) GetEntrySet(ctx context.Context) ([]types.Entry, error) {
request := codec.EncodeMapEntrySetRequest(m.name)
if response, err := m.invokeOnRandomTarget(ctx, request, nil); err != nil {
return nil, err
} else {
return m.convertPairsToEntries(codec.DecodeMapEntrySetResponse(response))
}
}
// GetEntrySetWithPredicate returns a clone of the mappings contained in this map.
func (m *Map) GetEntrySetWithPredicate(ctx context.Context, predicate predicate.Predicate) ([]types.Entry, error) {
if predData, err := m.validateAndSerialize(predicate); err != nil {
return nil, err
} else {
request := codec.EncodeMapEntriesWithPredicateRequest(m.name, predData)
if response, err := m.invokeOnRandomTarget(ctx, request, nil); err != nil {
return nil, err
} else {
return m.convertPairsToEntries(codec.DecodeMapEntriesWithPredicateResponse(response))
}
}
}
// GetEntryView returns the SimpleEntryView for the specified key.
// If there is no entry view for the key, nil is returned.
func (m *Map) GetEntryView(ctx context.Context, key interface{}) (*types.SimpleEntryView, error) {
lid := iproxy.ExtractLockID(ctx)
if keyData, err := m.validateAndSerialize(key); err != nil {
return nil, err
} else {
request := codec.EncodeMapGetEntryViewRequest(m.name, keyData, lid)
if response, err := m.invokeOnKey(ctx, request, keyData); err != nil {
return nil, err
} else {
ev, maxIdle := codec.DecodeMapGetEntryViewResponse(response)
if ev == nil {
return nil, nil
}
// XXX: creating a new SimpleEntryView here in order to convert key, data and use maxIdle
deserializedKey, err := m.convertToObject(ev.Key.(serialization.Data))
if err != nil {
return nil, err
}
deserializedValue, err := m.convertToObject(ev.Value.(serialization.Data))
if err != nil {
return nil, err
}
newEntryView := types.NewSimpleEntryView(
deserializedKey,
deserializedValue,
ev.Cost,
ev.CreationTime,
ev.ExpirationTime,
ev.Hits,
ev.LastAccessTime,
ev.LastStoredTime,
ev.LastUpdateTime,
ev.Version,
ev.TTL,
maxIdle)
return newEntryView, nil
}
}
}
// GetKeySet returns keys contained in this map.
func (m *Map) GetKeySet(ctx context.Context) ([]interface{}, error) {
request := codec.EncodeMapKeySetRequest(m.name)
if response, err := m.invokeOnRandomTarget(ctx, request, nil); err != nil {
return nil, err
} else {
keyDatas := codec.DecodeMapKeySetResponse(response)
keys := make([]interface{}, len(keyDatas))
for i, keyData := range keyDatas {
if key, err := m.convertToObject(keyData); err != nil {
return nil, err
} else {
keys[i] = key
}
}
return keys, nil
}
}
// GetKeySetWithPredicate returns keys contained in this map.
func (m *Map) GetKeySetWithPredicate(ctx context.Context, predicate predicate.Predicate) ([]interface{}, error) {
if predicateData, err := m.validateAndSerializePredicate(predicate); err != nil {
return nil, err
} else {
request := codec.EncodeMapKeySetWithPredicateRequest(m.name, predicateData)
if response, err := m.invokeOnRandomTarget(ctx, request, nil); err != nil {
return nil, err
} else {
return m.convertToObjects(codec.DecodeMapKeySetWithPredicateResponse(response))
}
}
}
// GetValues returns a list clone of the values contained in this map.
func (m *Map) GetValues(ctx context.Context) ([]interface{}, error) {
request := codec.EncodeMapValuesRequest(m.name)
if response, err := m.invokeOnRandomTarget(ctx, request, nil); err != nil {
return nil, err
} else {
return m.convertToObjects(codec.DecodeMapValuesResponse(response))
}
}
// GetValuesWithPredicate returns a list clone of the values contained in this map.
func (m *Map) GetValuesWithPredicate(ctx context.Context, predicate predicate.Predicate) ([]interface{}, error) {
if predicateData, err := m.validateAndSerializePredicate(predicate); err != nil {
return nil, err
} else {
request := codec.EncodeMapValuesWithPredicateRequest(m.name, predicateData)
if response, err := m.invokeOnRandomTarget(ctx, request, nil); err != nil {
return nil, err
} else {
return m.convertToObjects(codec.DecodeMapValuesWithPredicateResponse(response))
}
}
}