forked from apache/ignite
-
Notifications
You must be signed in to change notification settings - Fork 10
/
PlatformCacheTest.cs
1563 lines (1280 loc) · 57.7 KB
/
PlatformCacheTest.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
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 2019 GridGain Systems, Inc. and Contributors.
*
* Licensed under the GridGain Community Edition License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gridgain.com/products/software/community-edition/gridgain-community-edition-license
*
* 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.
*/
// ReSharper disable LoopVariableIsNeverChangedInsideLoop
namespace Apache.Ignite.Core.Tests.Cache.Platform
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Eviction;
using Apache.Ignite.Core.Cache.Expiry;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Cache.Store;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Datastream;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Log;
using Apache.Ignite.Core.Tests.Client.Cache;
using NUnit.Framework;
/// <summary>
/// Platform cache test.
/// </summary>
public sealed class PlatformCacheTest
{
/** */
private const string CacheName = "default";
/** */
private const int NearCacheMaxSize = 3;
/** */
private IIgnite _grid;
/** */
private IIgnite _grid2;
/** */
private IIgnite _client;
/** */
private ListLogger _logger;
/// <summary>
/// Fixture set up.
/// </summary>
[TestFixtureSetUp]
public void FixtureSetUp()
{
_logger = new ListLogger(new ConsoleLogger())
{
EnabledLevels = new[] {LogLevel.Error}
};
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
CacheConfiguration = new[]
{
new CacheConfiguration
{
NearConfiguration = new NearCacheConfiguration
{
EvictionPolicy = new FifoEvictionPolicy {MaxSize = NearCacheMaxSize},
},
PlatformCacheConfiguration = new PlatformCacheConfiguration(),
Name = CacheName,
QueryEntities = new[]
{
new QueryEntity(typeof(Foo))
}
}
},
IgniteInstanceName = "server1",
Logger = _logger
};
_grid = Ignition.Start(cfg);
var cfg2 = new IgniteConfiguration(cfg)
{
IgniteInstanceName = "server2"
};
_grid2 = Ignition.Start(cfg2);
var clientCfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
ClientMode = true,
IgniteInstanceName = "client",
IncludedEventTypes = new[] {EventType.CacheEntryCreated}
};
_client = Ignition.Start(clientCfg);
WaitForRebalance();
}
/// <summary>
/// Fixture tear down.
/// </summary>
[TestFixtureTearDown]
public void FixtureTearDown()
{
Ignition.StopAll(true);
}
/// <summary>
/// Test tear down.
/// </summary>
[TearDown]
public void TearDown()
{
_grid.GetCache<int, int>(CacheName).RemoveAll();
_logger.Clear();
}
/// <summary>
/// Tests that platform cache does not return same instance that we Put there:
/// there is always serialize-deserialize roundtrip, except on primary nodes.
/// </summary>
[Test]
public void TestPlatformCachePutGetReturnsNewObject(
[Values(CacheTestMode.ServerLocal, CacheTestMode.ServerRemote, CacheTestMode.Client)] CacheTestMode mode,
[Values(true, false)] bool primaryKey)
{
var cache = GetCache<int, Foo>(mode);
var key = TestUtils.GetKey(_grid, cache.Name, primaryKey: primaryKey);
var obj = new Foo(key);
cache[key] = obj;
var res1 = cache[key];
var res2 = cache[key];
// Returned object is Equal to the initial.
Assert.AreEqual(obj, res1);
// But not the same - new instance is stored in platform cache,
// except primary on servers - thread-local optimization avoids extra deserialization there.
if (primaryKey && mode == CacheTestMode.ServerLocal || !primaryKey && mode == CacheTestMode.ServerRemote)
{
Assert.AreSame(obj, res1);
}
else
{
Assert.AreNotSame(obj, res1);
}
// Repeated Get call returns same instance from platform cache.
Assert.AreSame(res1, res2);
}
/// <summary>
/// Tests that platform cache returns the same object on every get.
/// </summary>
[Test]
public void TestPlatformCacheRepeatedGetReturnsSameObjectReference(
[Values(CacheTestMode.ServerLocal, CacheTestMode.ServerRemote, CacheTestMode.Client)] CacheTestMode mode,
[Values(true, false)] bool primaryKey,
[Values(true, false)] bool localPut)
{
var cache = GetCache<int, Foo>(mode);
var key = TestUtils.GetKey(_grid, cache.Name, primaryKey: primaryKey);
var obj = new Foo(3);
if (localPut)
{
// Local put through the same cache instance: obj is in platform cache directly.
cache[key] = obj;
}
else
{
// Put through remote node: platform cache is updated only on Get.
var remoteCache = GetCache<int, Foo>(
mode == CacheTestMode.Client ? CacheTestMode.ServerRemote : CacheTestMode.Client);
remoteCache[key] = obj;
}
Assert.AreEqual(3, cache[key].Bar);
Assert.AreSame(cache[key], cache[key]);
}
/// <summary>
/// Tests that platform cache returns the same object on every get.
/// </summary>
[Test]
public void TestPlatformCacheRepeatedRemoteGetReturnsSameObjectReference(
[Values(CacheTestMode.ServerRemote, CacheTestMode.Client)] CacheTestMode mode,
[Values(true, false)] bool primaryKey)
{
var remoteCache = GetCache<int, Foo>(CacheTestMode.ServerLocal);
var localCache = GetCache<int, Foo>(mode);
var key = TestUtils.GetKey(_grid, remoteCache.Name, primaryKey: primaryKey);
remoteCache[key] = new Foo();
TestUtils.WaitForTrueCondition(() =>
{
Foo val;
return localCache.TryGet(key, out val) &&
ReferenceEquals(val, localCache.Get(key));
});
// Invalidate after get.
remoteCache[key] = new Foo(1);
TestUtils.WaitForTrueCondition(() =>
{
Foo val;
return localCache.TryGet(key, out val) &&
val.Bar == 1 &&
ReferenceEquals(val, localCache.Get(key));
});
}
/// <summary>
/// Tests that platform cache is updated from remote node after being populated with local Put call.
/// </summary>
[Test]
public void TestPlatformCacheUpdatesFromRemoteNode(
[Values(CacheTestMode.ServerLocal, CacheTestMode.ServerRemote, CacheTestMode.Client)] CacheTestMode mode1,
[Values(CacheTestMode.ServerLocal, CacheTestMode.ServerRemote, CacheTestMode.Client)] CacheTestMode mode2)
{
var cache1 = GetCache<int, int>(mode1);
var cache2 = GetCache<int, int>(mode2);
cache1[1] = 1;
cache2[1] = 2;
Assert.True(TestUtils.WaitForCondition(() => cache1[1] == 2, 300));
}
/// <summary>
/// Tests that platform cache is updated from another cache instance after being populated with local Put call.
/// </summary>
[Test]
public void TestPlatformCacheUpdatesFromAnotherLocalInstance()
{
var cache1 = _grid.GetCache<int, int>(CacheName);
var cache2 = _grid.GetCache<int, int>(CacheName);
cache1[1] = 1;
cache2.Replace(1, 2);
Assert.True(TestUtils.WaitForCondition(() => cache1[1] == 2, 300));
}
/// <summary>
/// Tests that platform cache is cleared from remote node after being populated with local Put call.
/// </summary>
[Test]
public void TestPlatformCacheRemoveFromRemoteNodeAfterLocalPut()
{
var localCache = _client.GetOrCreateNearCache<int, int>(CacheName, new NearCacheConfiguration());
var remoteCache = _grid.GetCache<int, int>(CacheName);
localCache[1] = 1;
remoteCache.Remove(1);
int unused;
Assert.True(TestUtils.WaitForCondition(() => !localCache.TryGet(1, out unused), 300));
}
/// <summary>
/// Tests that primary keys are always up-to-date in platform cache.
/// </summary>
[Test]
public void TestPrimaryKeyOnServerNodeIsAddedToPlatformCacheAfterRemotePut()
{
var clientCache = _client.GetCache<int, int>(CacheName);
var serverCache = _grid.GetCache<int, int>(CacheName);
var key = TestUtils.GetPrimaryKey(_grid, CacheName);
clientCache[key] = 2;
Assert.AreEqual(2, serverCache.LocalPeek(key, CachePeekMode.Platform));
clientCache[key] = 3;
Assert.AreEqual(3, serverCache.LocalPeek(key, CachePeekMode.Platform));
var nonPrimaryNodeCache = _grid2.GetCache<int, int>(CacheName);
Assert.AreEqual(0, nonPrimaryNodeCache.GetLocalSize(CachePeekMode.Platform));
}
/// <summary>
/// Tests that same platform cache can be used with different sets of generic type parameters.
/// </summary>
[Test]
public void TestSamePlatformCacheWithDifferentGenericTypeParameters()
{
var cfg = new CacheConfiguration(TestUtils.TestName)
{
NearConfiguration = new NearCacheConfiguration(),
PlatformCacheConfiguration = new PlatformCacheConfiguration()
};
var cache1 = _grid.CreateCache<int, int>(cfg);
var cache2 = _grid.GetCache<string, string>(cfg.Name);
var cache3 = _grid.GetCache<int, Foo>(cfg.Name);
var cache4 = _grid.GetCache<object, object>(cfg.Name);
cache1[1] = 1;
cache2["1"] = "1";
cache3[2] = new Foo(5);
Assert.AreEqual(cache4[1], 1);
Assert.AreEqual(cache4["1"], "1");
Assert.AreSame(cache4[2], cache3[2]);
}
/// <summary>
/// Tests that reference semantics is preserved on repeated get after generic parameters change.
/// </summary>
[Test]
public void TestRepeatedGetReturnsSameInstanceAfterGenericTypeParametersChange()
{
var cfg = new CacheConfiguration(TestUtils.TestName)
{
NearConfiguration = new NearCacheConfiguration(),
PlatformCacheConfiguration = new PlatformCacheConfiguration()
};
var cache1 = _grid.CreateCache<int, Foo>(cfg);
cache1[1] = new Foo(42);
cache1[2] = new Foo(43);
// Use different type parameters.
var cache2 = _grid.GetCache<int, string>(cfg.Name);
cache2[1] = "x";
// Check that platform cache still works for old entries.
Assert.Throws<InvalidCastException>(() => cache1.Get(1));
Assert.AreEqual(43, cache1[2].Bar);
Assert.AreSame(cache1[2], cache1[2]);
}
/// <summary>
/// Tests that cache data is invalidated in the existing cache instance after generic parameters change.
/// </summary>
[Test]
public void TestDataInvalidationAfterGenericTypeParametersChange()
{
var cacheName = TestUtils.TestName;
var cfg = new CacheConfiguration
{
Name = cacheName,
NearConfiguration = new NearCacheConfiguration(),
PlatformCacheConfiguration = new PlatformCacheConfiguration()
};
var cache = _client.CreateCache<int, int>(cfg, cfg.NearConfiguration);
cache[1] = 1;
var newCache = _client.GetOrCreateNearCache<int, object>(cacheName, cfg.NearConfiguration);
newCache[1] = 2;
Assert.AreEqual(2, cache[1]);
}
/// <summary>
/// Tests that error during Put does not affect correct data in platform cache.
/// </summary>
[Test]
public void TestFailedPutKeepsCorrectPlatformCacheValue(
[Values(CacheTestMode.ServerLocal, CacheTestMode.ServerRemote, CacheTestMode.Client)] CacheTestMode mode)
{
var cfg = new CacheConfiguration
{
Name = TestUtils.TestName,
NearConfiguration = new NearCacheConfiguration(),
PlatformCacheConfiguration = new PlatformCacheConfiguration(),
CacheStoreFactory = new FailingCacheStore(),
WriteThrough = true
};
var cache = GetIgnite(mode).CreateCache<int, Foo>(cfg, new NearCacheConfiguration(),
new PlatformCacheConfiguration());
// First write succeeds.
cache.Put(1, new Foo(1));
Assert.AreEqual(1, cache.LocalPeek(1, CachePeekMode.Platform).Bar);
// Special value causes write failure. Platform cache value is still correct.
Assert.Throws<CacheStoreException>(() => cache.Put(1, new Foo(FailingCacheStore.FailingValue)));
Assert.AreEqual(1, cache.LocalPeek(1, CachePeekMode.Platform).Bar);
}
/// <summary>
/// Tests that platform cache is updated/invalidated by SQL DML operations.
/// </summary>
[Test]
public void TestSqlUpdatesPlatformCache()
{
var cache = GetCache<int, Foo>(CacheTestMode.Client);
var value = new Foo(5);
cache[1] = value;
cache.Query(new SqlFieldsQuery("update Foo set Bar = 7 where Bar = 5"));
var res = cache[1];
Assert.AreEqual(7, res.Bar);
}
/// <summary>
/// Tests that eviction policy removes platform cache data for the key.
/// </summary>
[Test]
public void TestFifoEvictionPolicyRemovesPlatformCacheValue(
[Values(CacheTestMode.ServerLocal, CacheTestMode.ServerRemote, CacheTestMode.Client)] CacheTestMode mode)
{
var cache = GetCache<int, Foo>(mode);
TestEvictionPolicyRemovesPlatformCacheValue(mode, cache);
}
/// <summary>
/// Tests that eviction policy removes platform cache data for the key.
/// </summary>
[Test]
public void TestLruEvictionPolicyRemovesPlatformCacheValue(
[Values(CacheTestMode.ServerLocal, CacheTestMode.ServerRemote, CacheTestMode.Client)] CacheTestMode mode)
{
var cfg = new CacheConfiguration
{
Name = "lru-test-" + mode,
NearConfiguration = new NearCacheConfiguration
{
EvictionPolicy = new LruEvictionPolicy
{
MaxSize = NearCacheMaxSize,
BatchSize = 1
},
},
PlatformCacheConfiguration = new PlatformCacheConfiguration()
};
var ignite = GetIgnite(mode);
var cache = ignite.CreateCache<int, Foo>(cfg, cfg.NearConfiguration);
TestEvictionPolicyRemovesPlatformCacheValue(mode, cache);
}
/// <summary>
/// Tests that last N added entries are in platform cache, where N is MaxSize.
/// </summary>
[Test]
public void TestEvictionPolicyKeepsLastEntriesInPlatformCache(
[Values(true, false)] bool lruOrFifo,
[Values(true, false)] bool getOrCreate)
{
const int maxSize = 30;
var serverCache = _grid.CreateCache<int, Foo>(TestUtils.TestName);
var nearCfg = new NearCacheConfiguration
{
EvictionPolicy = lruOrFifo
? (IEvictionPolicy) new LruEvictionPolicy
{
MaxSize = maxSize
}
: new FifoEvictionPolicy
{
MaxSize = maxSize
}
};
var platformCfg = new PlatformCacheConfiguration();
var clientCache = getOrCreate
? _client.GetOrCreateNearCache<int, Foo>(serverCache.Name, nearCfg, platformCfg)
: _client.CreateNearCache<int, Foo>(serverCache.Name, nearCfg, platformCfg);
var keys = Enumerable.Range(1, maxSize * 5).ToList();
var nearKeys = keys.AsEnumerable().Reverse().Take(maxSize).ToArray();
keys.ForEach(k => serverCache.Put(k, new Foo(k)));
// Get from client to populate platform cache.
clientCache.GetAll(nearKeys);
Assert.AreEqual(nearKeys.Length, clientCache.GetLocalSize(CachePeekMode.Platform));
// Check that Get returns instance from platform cache.
foreach (var key in nearKeys)
{
Assert.AreSame(clientCache.LocalPeek(key, CachePeekMode.Platform), clientCache.Get(key));
}
// Check that GetAll returns instances from platform cache.
var all = clientCache.GetAll(nearKeys);
foreach (var entry in all)
{
Assert.AreSame(clientCache.LocalPeek(entry.Key, CachePeekMode.Platform), entry.Value);
}
}
/// <summary>
/// Tests that evicted entry is reloaded from Java after update from another node.
/// Eviction on Java side for non-local entry (not a primary key for this node) disconnects near cache notifier.
/// This test verifies that eviction on Java side causes eviction on .NET side, and does not cause stale data.
/// </summary>
[Test]
public void TestCacheGetFromEvictedEntryAfterUpdateFromAnotherNode()
{
var cfg = new CacheConfiguration
{
Name = TestUtils.TestName,
NearConfiguration = new NearCacheConfiguration
{
EvictionPolicy = new FifoEvictionPolicy
{
MaxSize = 1
}
},
PlatformCacheConfiguration = new PlatformCacheConfiguration()
};
var serverCache = _grid.CreateCache<int, int>(cfg);
var clientCache = _client.GetOrCreateNearCache<int, int>(cfg.Name, cfg.NearConfiguration);
clientCache[1] = 1;
clientCache[2] = 2;
serverCache[1] = 11;
Assert.AreEqual(11, clientCache[1]);
}
/// <summary>
/// Tests that scan query uses platform cache to pass values to <see cref="ScanQuery{TK,TV}.Filter"/> when possible.
/// </summary>
[Test]
public void TestScanQueryFilterUsesValueFromPlatformCache(
[Values(CacheTestMode.ServerLocal, CacheTestMode.ServerRemote, CacheTestMode.Client)] CacheTestMode mode)
{
var cache = GetCache<int, Foo>(mode);
const int count = 100;
cache.PutAll(Enumerable.Range(1, count).Select(x => new KeyValuePair<int, Foo>(x, new Foo(x))));
// Filter will check that value comes from native platform cache.
var filter = new ScanQueryPlatformCacheFilter
{
CacheName = cache.Name
};
var res = cache.Query(new ScanQuery<int, Foo>(filter));
Assert.AreEqual(count, res.Count());
}
/// <summary>
/// Tests that scan query falls back to deserialized value from Java when platform cache value is missing.
/// </summary>
[Test]
public void TestScanQueryFilterUsesFallbackValueWhenNotInPlatformCache(
[Values(CacheTestMode.ServerLocal, CacheTestMode.ServerRemote, CacheTestMode.Client)] CacheTestMode mode)
{
var cache = GetCache<int, Foo>(mode);
const int count = 100;
var data = Enumerable.Range(1, count).ToDictionary(x=> x, x => new Foo(x));
cache.PutAll(data);
// Filter will check that value does not come from native platform cache.
var filter = new ScanQueryNoPlatformCacheFilter
{
CacheName = cache.Name
};
// Clear platform cache using internal API.
foreach (var ignite in Ignition.GetAll())
{
var platformCache = ((Ignite) ignite).PlatformCacheManager.TryGetPlatformCache(BinaryUtils.GetCacheId(cache.Name));
if (platformCache != null)
{
platformCache.Clear();
}
}
var res = cache.Query(new ScanQuery<int, Foo>(filter));
Assert.AreEqual(count, res.Count());
}
/// <summary>
/// Tests that local scan query uses platform cache directly, avoiding Java roundtrip.
/// </summary>
[Test]
public void TestLocalScanQueryUsesKeysAndValuesFromPlatformCache([Values(true, false)] bool withFilter,
[Values(true, false)] bool withPartition)
{
var cache = GetCache<int, Foo>(CacheTestMode.ServerLocal);
cache.PutAll(Enumerable.Range(1, 100).ToDictionary(x => x, x => new Foo(x)));
var qry = new ScanQuery<int, Foo>
{
Local = true,
Filter = withFilter
? new ScanQueryPlatformCacheFilter
{
CacheName = cache.Name
}
: null,
Partition = withPartition
? _grid.GetAffinity(cache.Name).GetPartition(TestUtils.GetPrimaryKey(_grid, cache.Name))
: (int?) null
};
var res = cache.Query(qry);
foreach (var entry in res)
{
var localValue = cache.LocalPeek(entry.Key, CachePeekMode.Platform);
if (withPartition)
{
// Local scan with partition works directly through platform cache.
Assert.AreSame(entry.Value, localValue);
}
else
{
// Local scan without partition works through Java.
Assert.AreNotSame(entry.Value, localValue);
}
}
if (withPartition)
{
Assert.Throws<ObjectDisposedException>(() => res.GetAll());
}
}
/// <summary>
/// Tests that local scan query reserves the partition when <see cref="ScanQuery{TK,TV}.Partition"/> is set.
/// </summary>
[Test]
public void TestLocalScanQueryWithPartitionReservesPartitionAndReleasesItOnDispose()
{
var cache = GetCache<int, Foo>(CacheTestMode.ServerLocal);
var key = TestUtils.GetPrimaryKey(_grid, cache.Name);
var part = _grid.GetAffinity(cache.Name).GetPartition(key);
cache.PutAll(Enumerable.Range(1, 100).ToDictionary(x => x, x => new Foo(x)));
var qry = new ScanQuery<int, Foo>
{
Local = true,
Partition = part
};
Func<bool> isReserved = () => TestUtils.IsPartitionReserved(_grid, cache.Name, part);
Assert.IsFalse(isReserved());
// Full iteration.
using (var cursor = cache.Query(qry))
{
Assert.IsTrue(isReserved());
using (var enumerator = cursor.GetEnumerator())
{
Assert.IsTrue(isReserved());
while (enumerator.MoveNext())
{
Assert.IsTrue(isReserved());
}
Assert.IsFalse(isReserved());
}
Assert.IsFalse(isReserved());
}
Assert.IsFalse(isReserved());
// Partial iteration with LINQ.
using (var cursor = cache.Query(qry))
{
Assert.IsTrue(isReserved());
var item = cursor.FirstOrDefault();
Assert.IsNotNull(item);
// Released because LINQ disposes the iterator.
Assert.IsFalse(isReserved());
}
// Partial iteration.
using (var cursor = cache.Query(qry))
{
Assert.IsTrue(isReserved());
var moved = cursor.GetEnumerator().MoveNext();
Assert.IsTrue(moved);
Assert.IsTrue(isReserved());
}
Assert.IsFalse(isReserved());
// GetAll without using block.
using (var cursor = cache.Query(qry))
{
Assert.IsTrue(isReserved());
var res = cursor.GetAll();
Assert.IsNotEmpty(res);
Assert.IsFalse(isReserved());
}
// Exception in filter.
qry.Filter = new ScanQueryPlatformCacheFilter {FailKey = key};
using (var cursor = cache.Query(qry))
{
Assert.IsTrue(isReserved());
Assert.Throws<SecurityException>(() => cursor.GetAll());
Assert.IsFalse(isReserved());
}
}
/// <summary>
/// Tests that invalid <see cref="ScanQuery{TK,TV}.Partition"/> causes correct exception.
/// </summary>
[Test]
public void TestLocalScanQueryWithInvalidPartitionId()
{
var cache = GetCache<int, Foo>(CacheTestMode.ServerLocal);
var qry = new ScanQuery<int, Foo> {Local = true, Partition = 1024};
var ex = Assert.Throws<IgniteException>(() => cache.Query(qry));
Assert.AreEqual("Invalid partition number: 1024", ex.Message);
}
/// <summary>
/// Tests that local scan query throws an exception when <see cref="ScanQuery{TK,TV}.Partition"/> is specified,
/// but that partition can not be reserved (belongs to remote node).
/// </summary>
[Test]
public void TestLocalScanQueryWithPartitionThrowsOnRemoteKeys()
{
var cache = GetCache<int, Foo>(CacheTestMode.ServerLocal);
var partition = _grid2.GetAffinity(cache.Name)
.GetPrimaryPartitions(_grid2.GetCluster().GetLocalNode())
.First();
var qry = new ScanQuery<int, Foo>
{
Local = true,
Partition = partition
};
var ex = Assert.Throws<InvalidOperationException>(() => cache.Query(qry).GetAll());
Assert.AreEqual(
string.Format("Failed to reserve partition {0}, it does not belong to the local node.", partition),
ex.Message);
}
/// <summary>
/// Tests local scan query on client node.
/// </summary>
[Test]
public void TestLocalScanQueryFromClientNode()
{
var cache = _grid.CreateCache<int, Foo>(TestUtils.TestName);
cache.PutAll(Enumerable.Range(1, 100).ToDictionary(x => x, x => new Foo(x)));
var clientCache = _client.CreateNearCache<int, Foo>(cache.Name, new NearCacheConfiguration(),
new PlatformCacheConfiguration());
// Promote key to near cache.
clientCache.Get(2);
var res = clientCache.Query(new ScanQuery<int, Foo> {Local = true}).GetAll();
// Local scan on client node returns empty collection.
Assert.AreEqual(1, clientCache.GetLocalSize(CachePeekMode.Near));
Assert.AreEqual(1, clientCache.GetLocalSize(CachePeekMode.Platform));
Assert.IsEmpty(res);
}
/// <summary>
/// Tests that expiry policy functionality plays well with platform cache.
/// </summary>
[Test]
public void TestExpiryPolicyRemovesValuesFromPlatformCache(
[Values(CacheTestMode.ServerLocal, CacheTestMode.ServerRemote, CacheTestMode.Client)] CacheTestMode mode)
{
var cache = GetCache<int, Foo>(mode)
.WithExpiryPolicy(new ExpiryPolicy(TimeSpan.FromSeconds(0.2), null, null));
cache[1] = new Foo(1);
Assert.AreEqual(1, cache[1].Bar);
Assert.AreEqual(1, cache.LocalPeek(1, CachePeekMode.Platform).Bar);
Assert.AreEqual(1, cache.Count());
Foo _;
TestUtils.WaitForTrueCondition(() => !cache.TryLocalPeek(1, out _, CachePeekMode.Platform), 3000);
}
/// <summary>
/// Tests server-side platform cache binary mode.
/// </summary>
[Test]
public void TestKeepBinaryServer()
{
// Create server platform cache with binary mode enabled.
var cfg = new CacheConfiguration
{
Name = TestUtils.TestName,
NearConfiguration = new NearCacheConfiguration(),
PlatformCacheConfiguration = new PlatformCacheConfiguration
{
KeepBinary = true
}
};
var clientCache = _client.CreateCache<int, Foo>(cfg);
var serverCache = _grid2.GetCache<int, object>(cfg.Name);
Assert.IsTrue(serverCache.GetConfiguration().PlatformCacheConfiguration.KeepBinary);
// Put non-binary from client. There is no platform cache on client.
clientCache[1] = new Foo(2);
// Read from platform on server.
var res = (IBinaryObject) serverCache.LocalPeek(1, CachePeekMode.Platform);
Assert.AreEqual(2, res.GetField<int>("Bar"));
}
[Test]
public void TestMultithreadedConcurrentUpdates()
{
var localCache = GetCache<int, Foo>(CacheTestMode.Client);
var remoteCache = GetCache<int, Foo>(CacheTestMode.ServerRemote);
var cancel = false;
const int key = 1;
var id = 1;
remoteCache[1] = new Foo(id);
var localUpdater = Task.Factory.StartNew(() =>
{
// ReSharper disable once AccessToModifiedClosure
while (!cancel)
{
Interlocked.Increment(ref id);
localCache.Put(key, new Foo(id));
}
});
var remoteUpdater = Task.Factory.StartNew(() =>
{
// ReSharper disable once AccessToModifiedClosure
while (!cancel)
{
Interlocked.Increment(ref id);
remoteCache.Put(key, new Foo(id));
}
});
var localReader = Task.Factory.StartNew(() =>
{
// ReSharper disable once AccessToModifiedClosure
while (!cancel)
{
var cur = localCache[key].Bar;
Assert.GreaterOrEqual(id, cur);
}
});
Thread.Sleep(5000);
cancel = true;
Task.WaitAll(localUpdater, remoteUpdater, localReader);
// Get actual value with SQL to bypass caches.
// Actual value may not be equal to the latest id because two threads compete in Put calls.
var actualValue = (int) localCache.Query(new SqlFieldsQuery("select Bar from Foo")).GetAll()[0][0];
Assert.AreEqual(actualValue, localCache[key].Bar, "Local value");
Assert.AreEqual(actualValue, remoteCache[key].Bar, "Remote value");
}
/// <summary>
/// Tests GetAll operation.
/// </summary>
/// <param name="async"></param>
[Test]
public void TestGetAll([Values(true, false)] bool async)
{
var clientCache = GetCache<int, Foo>(CacheTestMode.Client);
var serverCache = GetCache<int, Foo>(CacheTestMode.ServerRemote);
// One entry is in platform cache, another is not.
clientCache[1] = new Foo(1);
serverCache[2] = new Foo(2);
var res = async
? clientCache.GetAllAsync(Enumerable.Range(1, 2)).Result
: clientCache.GetAll(Enumerable.Range(1, 2));
Assert.AreEqual(new[] {1, 2}, res.Select(x => x.Key));
// First entry is from platform cache.
Assert.AreSame(res.First().Value, clientCache.LocalPeek(1, CachePeekMode.Platform));
// Second entry is now in platform cache.
Assert.AreEqual(2, clientCache.LocalPeek(2, CachePeekMode.Platform).Bar);
}
/// <summary>
/// Tests LocalPeek / TryLocalPeek with platform platform cache.
/// </summary>
[Test]
public void TestLocalPeek()
{
var clientCache = GetCache<int, Foo>(CacheTestMode.Client);
var serverCache = GetCache<int, Foo>(CacheTestMode.ServerRemote);
// One entry is in client platform cache, another is not.
clientCache[1] = new Foo(1);
serverCache[2] = new Foo(2);
Foo foo;
Assert.IsTrue(clientCache.TryLocalPeek(1, out foo, CachePeekMode.Platform));
Assert.AreEqual(1, foo.Bar);
Assert.IsTrue(clientCache.TryLocalPeek(1, out foo, CachePeekMode.Platform | CachePeekMode.Near));
Assert.AreEqual(1, foo.Bar);
Assert.IsFalse(clientCache.TryLocalPeek(2, out foo, CachePeekMode.Platform));
Assert.IsFalse(clientCache.TryLocalPeek(2, out foo, CachePeekMode.Near));
Assert.IsFalse(clientCache.TryLocalPeek(2, out foo, CachePeekMode.All));
Assert.AreEqual(2, serverCache.LocalPeek(2, CachePeekMode.Platform).Bar);
Assert.AreEqual(2, serverCache.LocalPeek(2, CachePeekMode.Near).Bar);
Assert.AreSame(serverCache[2], serverCache.LocalPeek(2, CachePeekMode.Platform));
Assert.AreNotSame(serverCache[2], serverCache.LocalPeek(2, CachePeekMode.Near));
}
[Test]
public void TestContainsKey(
[Values(CacheTestMode.ServerLocal, CacheTestMode.ServerRemote, CacheTestMode.Client)] CacheTestMode mode,
[Values(true, false)] bool async)
{
var cache = GetCache<int, int>(mode);
var cache2 = GetCache<int, int>(CacheTestMode.ServerLocal);
var data = Enumerable.Range(1, 100).ToDictionary(x => x, x => x);
cache2.PutAll(data);
var act = async
? (Func<int, bool>) (k => cache.ContainsKeyAsync(k).Result)
: k => cache.ContainsKey(k);
foreach (var key in data.Keys)
{
Assert.IsTrue(act(key));
Assert.IsFalse(act(-key));
}
}