-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathDistributedLocalCacheRegionStrategy.cs
928 lines (809 loc) · 24.9 KB
/
DistributedLocalCacheRegionStrategy.cs
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
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using NHibernate.Cache;
using NHibernate.Caches.StackExchangeRedis.Messages;
using StackExchange.Redis;
using static NHibernate.Caches.StackExchangeRedis.ConfigurationHelper;
namespace NHibernate.Caches.StackExchangeRedis
{
/// <summary>
/// A strategy that uses only a memory cache to store the values and uses Redis pubsub mechanism to synchronize
/// data between other local caches. The synchronization between caches is done by comparing the UTC <see cref="DateTime.Ticks"/>,
/// which represent when the operation was performed. When two operations have the same <see cref="DateTime.Ticks"/>, then the client
/// with the highest id wins. This strategy should be used only for regions that have few write operations and a high expiration time.
/// It is recommended to use <see cref="TwoLayerCacheRegionStrategy"/>, when the instances where the strategy would run are ofter restarted/recycled.
/// </summary>
public partial class DistributedLocalCacheRegionStrategy : AbstractRegionStrategy
{
private readonly int _clientId;
private readonly ISubscriber _subscriber;
private readonly RegionMemoryCacheBase _memoryCache;
private readonly ICacheLockValueProvider _lockValueProvider;
private readonly string _lockKeySuffix;
private readonly TimeSpan _lockAcquireTimeout;
private readonly TimeSpan _lockKeyTimeout;
private readonly RetryPolicy<string, Func<object>> _retryPolicy;
private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
private readonly object _lockLock = new object();
private readonly RedisChannel _synchronizationChannel;
private readonly TimeSpan _maxSynchronizationTime;
private readonly bool _usePipelining;
private long _lastClearTimestamp;
private int _lastClearClientId;
private long _version;
/// <inheritdoc />
public DistributedLocalCacheRegionStrategy(
IConnectionMultiplexer connectionMultiplexer,
RedisCacheRegionConfiguration configuration,
RegionMemoryCacheBase memoryCache,
IDictionary<string, string> properties)
: base(connectionMultiplexer, configuration, properties)
{
var lockConfiguration = configuration.LockConfiguration;
var acquireTimeout = lockConfiguration.AcquireTimeout;
var retryTimes = lockConfiguration.RetryTimes;
var maxRetryDelay = lockConfiguration.MaxRetryDelay;
var minRetryDelay = lockConfiguration.MinRetryDelay;
var lockRetryDelayProvider = lockConfiguration.RetryDelayProvider;
_usePipelining = GetBoolean("cache.region_strategy.distributed_local_cache.use_pipelining", properties, false);
Log.Debug("Use pipelining for region {0}: {1}", RegionName, _usePipelining);
_clientId = GetInteger("cache.region_strategy.distributed_local_cache.client_id", properties, Guid.NewGuid().GetHashCode());
Log.Debug("Client id for region {0}: {1}", RegionName, _clientId);
_maxSynchronizationTime = GetTimeSpanFromSeconds(
"cache.region_strategy.distributed_local_cache.max_synchronization_time", properties, TimeSpan.FromSeconds(10));
Log.Debug("Max synchronization time for region {0}: {1} seconds", RegionName, _maxSynchronizationTime.TotalSeconds);
_memoryCache = memoryCache;
_synchronizationChannel = string.Concat("{", configuration.RegionKey, "}@", "Synchronization");
_lockValueProvider = lockConfiguration.ValueProvider;
_lockKeySuffix = lockConfiguration.KeySuffix;
_lockAcquireTimeout = lockConfiguration.AcquireTimeout;
_lockKeyTimeout = lockConfiguration.KeyTimeout;
_retryPolicy = new RetryPolicy<string, Func<object>>(
retryTimes,
acquireTimeout,
() => lockRetryDelayProvider.GetValue(minRetryDelay, maxRetryDelay)
)
.ShouldRetry(s => s == null)
.OnFailure(OnFailedLock);
_subscriber = ConnectionMultiplexer.GetSubscriber();
ConnectionMultiplexer.ConnectionFailed += OnConnectionFailed;
ConnectionMultiplexer.ConnectionRestored += OnConnectionRestored;
ConnectionMultiplexer.ErrorMessage += OnErrorMessage;
_subscriber.Subscribe(_synchronizationChannel).OnMessage((Action<ChannelMessage>) OnSynchronizationMessage);
_subscriber.Subscribe(GetClientChannel(_clientId)).OnMessage((Action<ChannelMessage>) OnPrivateMessage);
}
/// <inheritdoc />
protected override string PutManyScript => null;
/// <inheritdoc />
protected override string LockManyScript => null;
/// <inheritdoc />
protected override string UnlockManyScript => null;
/// <inheritdoc />
protected override void ExecutePut(string cacheKey, object value)
{
TryPutLocal(cacheKey, value, DateTime.UtcNow.Ticks, _clientId, true);
}
/// <inheritdoc />
protected override void ExecutePutMany(object[] keys, object[] values)
{
for (var i = 0; i < keys.Length; i++)
{
Put(keys[i], values[i]);
}
}
/// <inheritdoc />
protected override Task ExecutePutManyAsync(object[] keys, object[] values, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<bool>(cancellationToken);
}
try
{
PutMany(keys, values);
return Task.CompletedTask;
}
catch (Exception ex)
{
return Task.FromException<bool>(ex);
}
}
/// <inheritdoc />
public override object Get(object key)
{
if (key == null)
{
return null;
}
var cacheKey = GetCacheKey(key);
return GetLocal(cacheKey);
}
/// <inheritdoc />
public override object[] GetMany(object[] keys)
{
if (keys == null)
{
throw new ArgumentNullException(nameof(keys));
}
var values = new object[keys.Length];
for (var i = 0; i < keys.Length; i++)
{
values[i] = Get(keys[i]);
}
return values;
}
/// <inheritdoc />
public override Task<object[]> GetManyAsync(object[] keys, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<object[]>(cancellationToken);
}
try
{
return Task.FromResult(GetMany(keys));
}
catch (Exception ex)
{
return Task.FromException<object[]>(ex);
}
}
/// <inheritdoc />
protected override bool ExecuteRemove(string cacheKey)
{
return TryRemoveLocal(cacheKey, DateTime.UtcNow.Ticks, _clientId, true);
}
/// <inheritdoc />
public override void Clear()
{
Log.Debug("Clearing region: '{0}'.", RegionKey);
TryClearLocal(DateTime.UtcNow.Ticks, _clientId, true);
}
/// <inheritdoc />
public override string Lock(object key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
var lockKey = GetLockKey(key);
Log.Debug("Locking key: '{0}'.", lockKey);
var lockValue = _lockValueProvider.GetValue();
using (var cacheLockValue = new CacheLockValue(lockValue))
{
object Context() => new KeyValuePair<string, CacheLockValue>(lockKey, cacheLockValue);
return _retryPolicy
.Execute(() =>
{
if (!LockLocal(lockKey, cacheLockValue))
{
Log.Debug("Failed to acquire lock for key '{0}' in the local cache, retrying...", lockKey);
return null; // Retry
}
cacheLockValue.Setup();
var subscriberCount = _subscriber.Publish(_synchronizationChannel, Serializer.Serialize(new CacheSynchronizationMessage
{
OperationType = OperationType.Lock,
Timestamp = DateTime.UtcNow.Ticks,
ClientId = _clientId,
Data = new LockData
{
LockKey = lockKey,
LockValue = lockValue
}
})) - 1;
if (subscriberCount == 0)
{
Log.Debug("Acquired lock for key '{0}', no other caches were involved.", lockKey);
// We are the only one subscribed
return cacheLockValue.Value;
}
Log.Debug("Waiting lock result from '{0}' other local caches.", subscriberCount);
IncreaseLock(cacheLockValue, subscriberCount);
if (!cacheLockValue.Semaphore.Wait(_lockAcquireTimeout) || cacheLockValue.Failed)
{
Log.Debug("Failed to acquire lock for key '{0}' from '{1}' other local caches, retrying...", lockKey, subscriberCount);
return null;
}
Log.Debug("Acquired lock for key '{0}', '{1}' other caches were involved.", lockKey, subscriberCount);
return cacheLockValue.Value;
}, Context);
}
}
/// <inheritdoc />
public override string LockMany(object[] keys)
{
if (keys == null)
{
throw new ArgumentNullException(nameof(keys));
}
var lockKeys = new string[keys.Length];
var lockValue = _lockValueProvider.GetValue();
for (var i = 0; i < keys.Length; i++)
{
lockKeys[i] = GetLockKey(keys[i]);
Log.Debug("Locking key: '{0}'.", lockKeys[i]);
}
using (var cacheLockValue = new CacheLockValue(lockValue))
{
object Context() => new KeyValuePair<string[], CacheLockValue>(lockKeys, cacheLockValue);
return _retryPolicy
.Execute(() =>
{
if (!LockManyLocal(lockKeys, cacheLockValue))
{
Log.Debug("Failed to acquire lock for '{0}' keys in the local cache, retrying...", lockKeys.Length);
return null; // Retry
}
cacheLockValue.Setup();
var subscriberCount = _subscriber.Publish(_synchronizationChannel, Serializer.Serialize(new CacheSynchronizationMessage
{
OperationType = OperationType.LockMany,
Timestamp = DateTime.UtcNow.Ticks,
ClientId = _clientId,
Data = new LockManyData
{
LockKeys = lockKeys,
LockValue = lockValue
}
})) - 1;
if (subscriberCount == 0)
{
Log.Debug("Acquired lock for '{0}' keys, no other caches were involved.", lockKeys.Length);
// We are the only one subscribed
return cacheLockValue.Value;
}
Log.Debug("Waiting lock result from '{0}' other local caches.", subscriberCount);
IncreaseLock(cacheLockValue, subscriberCount);
if (!cacheLockValue.Semaphore.Wait(_lockAcquireTimeout) || cacheLockValue.Failed)
{
Log.Debug("Failed to acquire lock for '{0}' keys from '{1}' other local caches, retrying...", lockKeys.Length, subscriberCount);
return null;
}
Log.Debug("Acquired lock for '{0}' keys, '{1}' other caches were involved.", lockKeys.Length, subscriberCount);
return cacheLockValue.Value;
}, Context);
}
}
/// <inheritdoc />
public override bool Unlock(object key, string lockValue)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
var lockKey = GetLockKey(key);
Log.Debug("Unlocking key: '{0}'.", lockKey);
return UnlockKey(lockKey, lockValue);
}
/// <inheritdoc />
public override int UnlockMany(object[] keys, string lockValue)
{
if (keys == null)
{
throw new ArgumentNullException(nameof(keys));
}
var lockKeys = new string[keys.Length];
for (var i = 0; i < keys.Length; i++)
{
lockKeys[i] = GetLockKey(keys[i]);
Log.Debug("Unlocking key: '{0}'.", lockKeys[i]);
}
return UnlockManyKeys(lockKeys, lockValue);
}
/// <inheritdoc />
public override void Validate()
{
}
private RedisChannel GetClientChannel(int clientId)
{
return $"{RegionKey}@{clientId}";
}
private void OnPrivateMessage(ChannelMessage obj)
{
var message = (LockResultMessage) Serializer.Deserialize(obj.Message);
ReleaseLock(message.LockKey, message.Success);
}
private void OnSynchronizationMessage(ChannelMessage channelMessage)
{
var message = (CacheSynchronizationMessage) Serializer.Deserialize(channelMessage.Message);
var timestamp = message.Timestamp;
var clientId = message.ClientId;
if (clientId == _clientId)
{
return;
}
switch (message.OperationType)
{
case OperationType.Put:
var putMessage = (PutData) message.Data;
TryPutLocal(putMessage.Key, putMessage.Value, timestamp, clientId, false);
break;
case OperationType.Remove:
TryRemoveLocal((string) message.Data, timestamp, clientId, false);
break;
case OperationType.Clear:
TryClearLocal(timestamp, clientId, false);
break;
case OperationType.Lock:
var lockData = (LockData) message.Data;
// Send the result to the client that triggered the lock
_subscriber.Publish(GetClientChannel(clientId), Serializer.Serialize(new LockResultMessage
{
LockKey = lockData.LockKey,
Success = LockLocal(lockData.LockKey, new CacheLockValue(lockData.LockValue))
}));
break;
case OperationType.LockMany:
var lockManyData = (LockManyData) message.Data;
// Send the result to the client that triggered the lock
_subscriber.Publish(GetClientChannel(clientId), Serializer.Serialize(new LockResultMessage
{
LockKey = lockManyData.LockKeys[0], // Is enough to send one key as the value is shared across all of them
Success = LockManyLocal(lockManyData.LockKeys, new CacheLockValue(lockManyData.LockValue))
}));
break;
case OperationType.Unlock:
var unlockData = (LockData) message.Data;
UnlockLocal(unlockData.LockKey, unlockData.LockValue);
break;
case OperationType.UnlockMany:
var unlockManyData = (LockManyData) message.Data;
UnlockManyLocal(unlockManyData.LockKeys, unlockManyData.LockValue);
break;
}
}
private bool UnlockKey(string lockKey, string lockValue)
{
Publish(Serializer.Serialize(new CacheSynchronizationMessage
{
OperationType = OperationType.Unlock,
ClientId = _clientId,
Timestamp = DateTime.UtcNow.Ticks,
Data = new LockData
{
LockKey = lockKey,
LockValue = lockValue
}
}));
return UnlockLocal(lockKey, lockValue);
}
private int UnlockManyKeys(string[] lockKeys, string lockValue)
{
Publish(Serializer.Serialize(new CacheSynchronizationMessage
{
OperationType = OperationType.UnlockMany,
ClientId = _clientId,
Timestamp = DateTime.UtcNow.Ticks,
Data = new LockManyData
{
LockKeys = lockKeys,
LockValue = lockValue
}
}));
return UnlockManyLocal(lockKeys, lockValue);
}
private int UnlockManyLocal(string[] lockKeys, string lockValue)
{
var result = 0;
foreach (var lockKey in lockKeys)
{
if (UnlockLocal(lockKey, lockValue))
{
result++;
}
}
return result;
}
private bool UnlockLocal(string lockKey, string lockValue)
{
var value = (CacheLockValue) _memoryCache.Get(lockKey);
if (value != null && value.Value == lockValue)
{
return _memoryCache.Remove(lockKey);
}
return false;
}
private bool LockManyLocal(string[] lockKeys, CacheLockValue lockValue)
{
foreach (var lockKey in lockKeys)
{
if (!LockLocal(lockKey, lockValue))
{
return false;
}
}
return true;
}
private bool LockLocal(string lockKey, CacheLockValue lockValue)
{
lock (_lockLock)
{
var value = (CacheLockValue) _memoryCache.Get(lockKey);
if (value != null && !value.Equals(lockValue))
{
return false;
}
_memoryCache.Put(lockKey, lockValue, _lockKeyTimeout);
return true;
}
}
private void ReleaseLock(string lockKey, bool success)
{
var cacheLockValue = (CacheLockValue) _memoryCache.Get(lockKey);
if (cacheLockValue == null)
{
return;
}
lock (cacheLockValue)
{
if (cacheLockValue.Failed)
{
return;
}
if (!success)
{
cacheLockValue.Failed = true;
cacheLockValue.Semaphore.Release();
}
cacheLockValue.RemainingLocks--;
Log.Debug("Remaining locks to acquire: '{0}'", cacheLockValue.RemainingLocks);
if (cacheLockValue.RemainingLocks == 0)
{
cacheLockValue.Semaphore.Release();
}
}
}
private void IncreaseLock(CacheLockValue cacheLockValue, long value)
{
lock (cacheLockValue)
{
if (cacheLockValue.Failed)
{
return;
}
cacheLockValue.RemainingLocks += value;
Log.Debug("Remaining locks to acquire: '{0}'", cacheLockValue.RemainingLocks);
if (cacheLockValue.RemainingLocks == 0)
{
cacheLockValue.Semaphore.Release();
}
}
}
private void OnFailedLock(int totalAttempts, long elapsedMs, Func<object> getDataFn)
{
var data = getDataFn();
var key = string.Empty;
switch (data)
{
case KeyValuePair<string, CacheLockValue> pair:
key = pair.Key;
UnlockKey(pair.Key, pair.Value.Value);
break;
case KeyValuePair<string[], CacheLockValue> pairMany:
key = string.Join(",", pairMany.Key);
UnlockManyKeys(pairMany.Key, pairMany.Value.Value);
break;
}
throw new CacheException("Unable to acquire cache lock: " +
$"region='{RegionName}', " +
$"keys='{key}', " +
$"total attempts='{totalAttempts}', " +
$"total acquiring time= '{elapsedMs}ms'");
}
private string GetLockKey(object key)
{
return $"{GetCacheKey(key)}{_lockKeySuffix}";
}
private object GetLocal(string key)
{
var cacheValue = (CacheValue) _memoryCache.Get(key);
if (cacheValue == null || _lastClearTimestamp > cacheValue.Timestamp)
{
return null;
}
// When the cache value was added with the same timestamp as the clear operation,
// we have to rely on the version in order to find out which operation was the last
// executed.
if (_lastClearTimestamp == cacheValue.Timestamp && cacheValue.Version != _version)
{
return null;
}
return cacheValue.Value;
}
private void OnConnectionRestored(object sender, ConnectionFailedEventArgs e)
{
Log.Error(e.Exception, "The connection to Redis is restored, clearing the local cache.");
// As we don't know if there was any message during the connection drop, we have to clear the local cache
TryClearLocal(DateTime.UtcNow.Ticks, _clientId, false);
}
private void OnConnectionFailed(object sender, ConnectionFailedEventArgs e)
{
Log.Error(e.Exception, "The connection to Redis was lost.");
}
private void OnErrorMessage(object sender, RedisErrorEventArgs e)
{
Log.Error("An error occurred while executing a Redis command: {0}", e.Message);
// As we don't know for which key the error occurred, we have to clear the local cache
TryClearLocal(DateTime.UtcNow.Ticks, _clientId, false);
}
private bool TryRemoveLocal(string cacheKey, long timestamp, int clientId, bool publish)
{
return ExecuteOperation(cacheKey, null, timestamp, clientId, publish, true);
}
private bool TryPutLocal(string cacheKey, object value, long timestamp, int clientId, bool publish)
{
return ExecuteOperation(cacheKey, value, timestamp, clientId, publish, false);
}
private bool ExecuteOperation(string cacheKey, object value, long timestamp, int clientId, bool publish, bool remove)
{
var message = publish
? Serializer.Serialize(new CacheSynchronizationMessage
{
OperationType = remove ? OperationType.Remove : OperationType.Put,
ClientId = _clientId,
Timestamp = timestamp,
Data = remove
? (object) cacheKey
: new PutData
{
Key = cacheKey,
Value = value
}
})
: null;
var cacheValue = (CacheValue) _memoryCache.Get(cacheKey);
if (cacheValue == null && TryPutLocal())
{
return !remove;
}
var lockValue = cacheValue.Lock;
lockValue.Wait();
try
{
if (!IsActionValid(timestamp, clientId))
{
return false;
}
cacheValue = (CacheValue) _memoryCache.Get(cacheKey);
// When a different thread calls TryPutLocal at the begining of the method
// and gets the lock before the current thread we have to retry to put as the lock
// value is not valid anymore
if (cacheValue == null && TryPutLocal()) // The key expired in the meantime
{
return !remove;
}
if (lockValue != cacheValue.Lock)
{
return ExecuteOperation(cacheKey, value, timestamp, clientId, publish, remove);
}
if (cacheValue.Timestamp == timestamp)
{
if (Log.IsDebugEnabled())
{
Log.Debug(
"The timestamp for the key '{0}' is equal to the current one... " +
"comparing the client id in order to determine who has a higher priority. ", cacheKey);
}
if (cacheValue.ClientId > clientId)
{
return false;
}
}
else if (cacheValue.Timestamp > timestamp)
{
return false;
}
if (cacheValue is RemovedCacheValue)
{
if (remove)
{
cacheValue.Timestamp = timestamp;
cacheValue.ClientId = clientId;
cacheValue.Version = _version;
}
else
{
cacheValue = new CacheValue(value, timestamp, clientId, _version, cacheValue.Lock);
}
}
else
{
if (remove)
{
cacheValue = new RemovedCacheValue(timestamp, clientId, _version, cacheValue.Lock);
}
else
{
cacheValue.Value = value;
cacheValue.Timestamp = timestamp;
cacheValue.ClientId = clientId;
cacheValue.Version = _version;
}
}
if (remove)
{
_memoryCache.Put(cacheKey, cacheValue, _maxSynchronizationTime);
}
else
{
_memoryCache.Put(cacheKey, cacheValue);
}
if (publish)
{
Publish(message);
}
return true;
}
finally
{
lockValue.Release();
}
bool TryPutLocal()
{
_writeLock.Wait();
try
{
cacheValue = (CacheValue) _memoryCache.Get(cacheKey);
if (cacheValue != null)
{
return false;
}
if (remove)
{
_memoryCache.Put(cacheKey, new RemovedCacheValue(timestamp, clientId, _version), _maxSynchronizationTime);
}
else
{
_memoryCache.Put(cacheKey, new CacheValue(value, timestamp, clientId, _version));
}
if (publish)
{
Publish(message);
}
return true;
}
finally
{
_writeLock.Release();
}
}
}
private void Publish(RedisValue message)
{
_subscriber.Publish(_synchronizationChannel, message, _usePipelining ? CommandFlags.FireAndForget : CommandFlags.None);
}
private Task PublishAsync(RedisValue message)
{
if (!_usePipelining)
{
return _subscriber.PublishAsync(_synchronizationChannel, message);
}
Publish(message);
return Task.CompletedTask;
}
private bool TryClearLocal(long timestamp, int clientId, bool publish)
{
var message = publish
? Serializer.Serialize(new CacheSynchronizationMessage
{
OperationType = OperationType.Clear,
ClientId = _clientId,
Timestamp = timestamp
})
: null;
_writeLock.Wait();
try
{
if (!IsActionValid(timestamp, clientId))
{
return false;
}
_lastClearTimestamp = timestamp;
_lastClearClientId = clientId;
_version++;
// Unfortunately we cannot clear the local cache as it can lead to an inconsistent
// state across local caches due to delays of synchronization messages.
if (publish)
{
Publish(message);
}
return true;
}
finally
{
_writeLock.Release();
}
}
private bool IsActionValid(long timestamp, long clientId)
{
if (_lastClearTimestamp == timestamp)
{
if (Log.IsDebugEnabled())
{
Log.Debug(
"The timestamp for the operation is equal to the last clear timestamp... " +
"comparing the client id in order to determine who has a higher priority. ");
}
if (_lastClearClientId > clientId)
{
return false;
}
}
else if (_lastClearTimestamp > timestamp)
{
return false;
}
return true;
}
private class CacheValue
{
public CacheValue(object value, long timestamp, int clientId, long version, SemaphoreSlim lockValue)
{
Value = value;
Timestamp = timestamp;
ClientId = clientId;
Version = version;
Lock = lockValue;
}
public CacheValue(object value, long timestamp, int clientId, long version)
: this(value, timestamp, clientId, version, new SemaphoreSlim(1, 1))
{
}
public object Value { get; set; }
public long Timestamp { get; set; }
public int ClientId { get; set; }
public long Version { get; set; }
public SemaphoreSlim Lock { get; }
}
private class RemovedCacheValue : CacheValue
{
public RemovedCacheValue(long timestamp, int clientId, long version, SemaphoreSlim lockValue)
: base(null, timestamp, clientId, version, lockValue)
{
}
public RemovedCacheValue(long timestamp, int clientId, long version)
: base(null, timestamp, clientId, version)
{
}
}
private class CacheLockValue : IEquatable<CacheLockValue>, IDisposable
{
public CacheLockValue(string value)
{
Value = value;
}
public void Setup()
{
Failed = false;
if (Semaphore == null)
{
Semaphore = new SemaphoreSlim(0, 1);
}
}
public string Value { get; }
public long RemainingLocks { get; set; }
public bool Failed { get; set; }
public SemaphoreSlim Semaphore { get; private set; }
public override bool Equals(object obj)
{
return obj?.GetType() == typeof(CacheLockValue) && Equals((CacheLockValue) obj);
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
public bool Equals(CacheLockValue other)
{
return string.Equals(Value, other?.Value);
}
public void Dispose()
{
Semaphore?.Dispose();
Semaphore = null;
}
}
}
}