-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMaxLogic.Cache.pas
More file actions
2104 lines (1851 loc) · 56 KB
/
MaxLogic.Cache.pas
File metadata and controls
2104 lines (1851 loc) · 56 KB
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
unit MaxLogic.Cache;
{$I fpc_delphimode.inc}
{$SCOPEDENUMS ON}
interface
uses
System.Classes, System.Diagnostics, System.Generics.Collections, System.Generics.Defaults, System.IOUtils,
System.SyncObjs, System.SysUtils,
MaxLogic.hash.xxHash, MaxLogic.PortableTimer, maxLogic.StrUtils;
type
EMaxCacheException = class(Exception);
EMaxCacheLoadException = class(EMaxCacheException);
EMaxCacheShutdown = class(EMaxCacheException);
EMaxCacheWaitTimeout = class(EMaxCacheException);
TMaxDependencyStamp = record
MTimeUtcMs: Int64;
SizeBytes: Int64;
Hash32: Cardinal;
HasHash: Boolean;
class function FromFile(const aFileName: string; const aIncludeHash: Boolean = False): TMaxDependencyStamp; static;
function Equals(const aOther: TMaxDependencyStamp): Boolean;
end;
IMaxCacheDependency = interface
['{1CB9C196-0DCC-4B88-A59B-62A0AEE0FC82}']
function IsStale(out aNewStamp: TMaxDependencyStamp): Boolean;
function GetStamp: TMaxDependencyStamp;
end;
TMaxFileDependency = class(TInterfacedObject, IMaxCacheDependency)
private
fAlwaysHashBelowBytes: Int64;
fFileName: string;
fForceHash: Boolean;
fStamp: TMaxDependencyStamp;
function ComputeStamp(const aIncludeHash: Boolean): TMaxDependencyStamp;
function ShouldHash(const aBaseStamp: TMaxDependencyStamp; const aForce: Boolean): Boolean;
public
constructor Create(const aFileName: string; const aAlwaysHashBelowBytes: Int64 = 51200; const aForceHash: Boolean = False);
function GetStamp: TMaxDependencyStamp;
function IsStale(out aNewStamp: TMaxDependencyStamp): Boolean;
property FileName: string read fFileName;
property ForceHash: Boolean read fForceHash;
end;
TMaxCacheKeySize = record
Namespace: string;
Key: string;
EstimatedBytes: Int64;
end;
TMaxCacheMetrics = record
NamespaceCount: Integer;
EntryCount: Integer;
EstimatedMemoryKB: Int64;
Hits: Int64;
Misses: Int64;
Loads: Int64;
LoadFailures: Int64;
InvalidationsDirect: Int64;
InvalidationsByTag: Int64;
EvictionsTtl: Int64;
EvictionsIdle: Int64;
EvictionsSize: Int64;
AvgLoadTimeMs: Double;
P95LoadTimeMs: Double;
TopTenKeysBySize: TArray<TMaxCacheKeySize>;
end;
TMaxNamespaceCacheMetrics = record
Namespace: string;
EntryCount: Integer;
EstimatedMemoryKB: Int64;
end;
TMaxCacheConfig = record
DefaultTtlMs: Integer;
DefaultIdleMs: Integer;
DefaultValidateIntervalMs: Integer;
MaxEntriesGlobal: Integer;
MaxBytesGlobal: Int64;
MaxEntriesPerNamespace: Integer;
MaxBytesPerNamespace: Int64;
MinFailCacheMs: Integer;
DefaultWaitTimeoutMs: Integer;
AlwaysHashBelowBytes: Integer;
SweepIntervalMs: Integer;
SweepBatchSize: Integer;
CaseSensitiveKeys: Boolean;
ReturnStaleOnFailure: Boolean;
class function Default: TMaxCacheConfig; static;
end;
TMaxCacheOptions = class
public
TtlMs: Integer;
IdleMs: Integer;
ValidateIntervalMs: Integer;
FailCacheMs: Integer;
SizeEstimateBytes: Integer;
Tags: TArray<string>;
Dependency: IMaxCacheDependency;
ReturnStaleOnFailure: Boolean;
constructor Create;
end;
IMaxCache = interface
['{9C9FA4E8-B650-485F-8F52-2E6B4C93320D}']
function GetOrCreate(const aNamespace, aKey: string; const aLoader: TFunc<IInterface>; const aOptions: TMaxCacheOptions = nil): IInterface;
procedure Invalidate(const aNamespace, aKey: string);
procedure InvalidateNamespace(const aNamespace: string);
procedure InvalidateByTag(const aScopedTag: string);
procedure InvalidateMany(const aNamespace: string; const aKeys: array of string);
function TryGet(const aNamespace, aKey: string; out aValue: IInterface): Boolean;
function GetMetrics: TMaxCacheMetrics;
function GetNamespaceMetrics(const aNamespace: string): TMaxNamespaceCacheMetrics;
procedure Shutdown;
end;
TMaxCache = class(TInterfacedObject, IMaxCache)
public
class function New(const aConfig: TMaxCacheConfig): IMaxCache; overload; static;
class function New: IMaxCache; overload; static;
class function ScopedTag(const aNamespace, aTag: string): string; static;
public
constructor Create(const aConfig: TMaxCacheConfig);
destructor Destroy; override;
function GetOrCreate(const aNamespace, aKey: string; const aLoader: TFunc<IInterface>; const aOptions: TMaxCacheOptions = nil): IInterface;
procedure Invalidate(const aNamespace, aKey: string);
procedure InvalidateNamespace(const aNamespace: string);
procedure InvalidateByTag(const aScopedTag: string);
procedure InvalidateMany(const aNamespace: string; const aKeys: array of string);
function TryGet(const aNamespace, aKey: string; out aValue: IInterface): Boolean;
function GetMetrics: TMaxCacheMetrics;
function GetNamespaceMetrics(const aNamespace: string): TMaxNamespaceCacheMetrics;
procedure Shutdown;
private
type
TMaxCacheEntryState = (Empty, Loading, Ready, Failed, Obsolete);
TMaxCacheEntry = class
private
fRefCount: Integer;
public
EntrySync: TObject;
State: TMaxCacheEntryState;
Value: IInterface;
CreatedAtMs: Int64;
LastAccessMs: Int64;
ExpiresAtMs: Int64;
IdleExpiresAtMs: Int64;
NextValidateMs: Int64;
ValidateIntervalMs: Integer;
IsValidating: Integer;
WasInvalidated: Integer;
Dependency: IMaxCacheDependency;
Stamp: TMaxDependencyStamp;
Tags: TArray<string>;
SizeEstimateBytes: Int64;
RetryAtMs: Int64;
FailCacheMs: Integer;
ReturnStaleOnFailure: Boolean;
TtlMs: Integer;
IdleMs: Integer;
LastLoadTimeMs: Integer;
LastErrorMsg: string;
LastErrorClassName: string;
constructor Create;
destructor Destroy; override;
procedure AddRef;
procedure Release;
end;
TMaxNamespaceBucket = class
public
Lock: TLightweightMREW;
Items: TDictionary<string, TMaxCacheEntry>;
constructor Create(const aComparer: IEqualityComparer<string>);
destructor Destroy; override;
end;
TMaxTagRef = record
Namespace: string;
Key: string;
end;
private
const
cTagRefSep = #31;
cScopedTagSep = '|';
cGlobalTagPrefix = 'global:';
cMinSweepIntervalMs = 1;
cLoadTimeBoundsCount = 7;
cHistogramBucketCount = cLoadTimeBoundsCount + 1;
cLoadTimeBounds: array[0..cLoadTimeBoundsCount - 1] of Integer = (1, 5, 10, 50, 100, 500, 1000);
private
fConfig: TMaxCacheConfig;
fComparer: IEqualityComparer<string>;
fNamespacesLock: TLightweightMREW;
fNamespaces: TDictionary<string, TMaxNamespaceBucket>;
fTagIndexLock: TLightweightMREW;
fTagIndex: TDictionary<string, TDictionary<string, Byte>>;
fHits: Int64;
fMisses: Int64;
fLoads: Int64;
fLoadFailures: Int64;
fInvalidationsDirect: Int64;
fInvalidationsByTag: Int64;
fEvictionsTtl: Int64;
fEvictionsIdle: Int64;
fEvictionsSize: Int64;
fTotalLoadTimeMs: Int64;
fLoadTimeHistogram: array[0..cHistogramBucketCount - 1] of Int64;
fIsShuttingDown: Integer;
fSweeper: TPortableTimer;
fSweepRunning: Integer;
private
class function NowMs: Int64; static;
class function ClampNonNegative(const aValue: Integer): Integer; static;
class function ReadInt64(var aValue: Int64): Int64; static; inline;
class procedure WriteInt64(var aTarget: Int64; const aValue: Int64); static; inline;
function GetOrCreateBucket(const aNamespace: string): TMaxNamespaceBucket;
function TryGetBucket(const aNamespace: string): TMaxNamespaceBucket;
function TryGetEntry(const aBucket: TMaxNamespaceBucket; const aKey: string): TMaxCacheEntry;
procedure MarkEntryInvalidated(const aEntry: TMaxCacheEntry; const aClearValue: Boolean; out aTags: TArray<string>);
function RemoveEntryIfSame(const aBucket: TMaxNamespaceBucket; const aKey: string; const aEntry: TMaxCacheEntry): Boolean;
function TryBeginLoad(
const aKey: string;
const aBucket: TMaxNamespaceBucket;
const aNowMs: Int64;
const aForceLoad: Boolean;
out aEntry: TMaxCacheEntry): Boolean;
procedure WaitForEntry(const aEntry: TMaxCacheEntry);
procedure EnsureNotShuttingDown;
function IsExpired(const aEntry: TMaxCacheEntry; const aNowMs: Int64; out aEvictKind: Integer): Boolean;
procedure TouchEntry(const aEntry: TMaxCacheEntry; const aNowMs: Int64);
function ValidateDependency(const aEntry: TMaxCacheEntry; const aNowMs: Int64): Boolean;
procedure RegisterTags(const aNamespace, aKey: string; const aTags: TArray<string>);
procedure UnregisterTags(const aNamespace, aKey: string; const aTags: TArray<string>);
function GetTagRefsCopy(const aScopedTag: string): TArray<TMaxTagRef>;
procedure RecordLoadTimeMs(const aElapsedMs: Integer);
class function EstimateP95Ms(const aHistogram: array of Int64): Double; static;
procedure SweeperTimer(aSender: TObject);
procedure SweepTick;
procedure SweepBucket(const aNamespace: string; const aBucket: TMaxNamespaceBucket; const aNowMs: Int64; var aRemaining: Integer);
procedure EnforceSizeCaps(const aNamespace: string; const aBucket: TMaxNamespaceBucket; const aNowMs: Int64; var aRemaining: Integer);
procedure EnforceGlobalSizeCaps(const aBucketPairs: TArray<TPair<string, TMaxNamespaceBucket>>; var aRemaining: Integer);
function InvalidateInternal(const aNamespace, aKey: string; const aCountDirectMetric: Boolean): Boolean;
procedure InvalidateNamespaceInternal(const aNamespace: string; const aCountDirectMetric: Boolean);
end;
{$IFDEF UNITTESTS}
type
TMaxCacheTagRegisterHook = reference to procedure(const aNamespace, aKey: string; const aTags: TArray<string>);
TMaxCacheBeforeInvalidateRemoveHook = reference to procedure(const aNamespace, aKey: string; const aTags: TArray<string>);
procedure MaxCache_SetTagRegisterHook(const aHook: TMaxCacheTagRegisterHook);
procedure MaxCache_ClearTagRegisterHook;
procedure MaxCache_SetBeforeInvalidateRemoveHook(const aHook: TMaxCacheBeforeInvalidateRemoveHook);
procedure MaxCache_ClearBeforeInvalidateRemoveHook;
{$ENDIF}
implementation
{$IFDEF UNITTESTS}
var
gTagRegisterHook: TMaxCacheTagRegisterHook;
gBeforeInvalidateRemoveHook: TMaxCacheBeforeInvalidateRemoveHook;
procedure MaxCache_SetTagRegisterHook(const aHook: TMaxCacheTagRegisterHook);
begin
gTagRegisterHook := aHook;
end;
procedure MaxCache_ClearTagRegisterHook;
begin
gTagRegisterHook := nil;
end;
procedure MaxCache_SetBeforeInvalidateRemoveHook(const aHook: TMaxCacheBeforeInvalidateRemoveHook);
begin
gBeforeInvalidateRemoveHook := aHook;
end;
procedure MaxCache_ClearBeforeInvalidateRemoveHook;
begin
gBeforeInvalidateRemoveHook := nil;
end;
{$ENDIF}
{ TMaxDependencyStamp }
class function TMaxDependencyStamp.FromFile(const aFileName: string; const aIncludeHash: Boolean): TMaxDependencyStamp;
var
lDt: TDateTime;
lBytes: TBytes;
begin
Result.MTimeUtcMs := 0;
Result.SizeBytes := -1;
Result.Hash32 := 0;
Result.HasHash := False;
if (aFileName = '') or (not TFile.Exists(aFileName)) then
Exit;
Result.SizeBytes := TFile.GetSize(aFileName);
lDt := TFile.GetLastWriteTimeUtc(aFileName);
Result.MTimeUtcMs := Round(lDt * 86400000.0);
if aIncludeHash then
begin
lBytes := TFile.ReadAllBytes(aFileName);
if Length(lBytes) = 0 then
Result.Hash32 := xxHash32(nil, 0, 0)
else
Result.Hash32 := xxHash32(@lBytes[0], Length(lBytes), 0);
Result.HasHash := True;
end;
end;
function TMaxDependencyStamp.Equals(const aOther: TMaxDependencyStamp): Boolean;
begin
if MTimeUtcMs <> aOther.MTimeUtcMs then
Exit(False);
if SizeBytes <> aOther.SizeBytes then
Exit(False);
if HasHash and aOther.HasHash and (Hash32 <> aOther.Hash32) then
Exit(False);
Result := True;
end;
{ TMaxFileDependency }
constructor TMaxFileDependency.Create(const aFileName: string; const aAlwaysHashBelowBytes: Int64; const aForceHash: Boolean);
begin
inherited Create;
fFileName := aFileName;
fAlwaysHashBelowBytes := aAlwaysHashBelowBytes;
fForceHash := aForceHash;
fStamp.MTimeUtcMs := 0;
fStamp.SizeBytes := -1;
fStamp.Hash32 := 0;
fStamp.HasHash := False;
end;
function TMaxFileDependency.ShouldHash(const aBaseStamp: TMaxDependencyStamp; const aForce: Boolean): Boolean;
begin
if aForce then
Exit(True);
if (aBaseStamp.SizeBytes >= 0) and (aBaseStamp.SizeBytes <= fAlwaysHashBelowBytes) then
Exit(True);
if not fStamp.Equals(aBaseStamp) then
Exit(True);
Result := False;
end;
function TMaxFileDependency.ComputeStamp(const aIncludeHash: Boolean): TMaxDependencyStamp;
begin
Result := TMaxDependencyStamp.FromFile(fFileName, aIncludeHash);
end;
function TMaxFileDependency.GetStamp: TMaxDependencyStamp;
var
lBase: TMaxDependencyStamp;
lIncludeHash: Boolean;
begin
lBase := ComputeStamp(False);
lIncludeHash := fForceHash or ((lBase.SizeBytes >= 0) and (lBase.SizeBytes <= fAlwaysHashBelowBytes));
if lIncludeHash then
fStamp := ComputeStamp(True)
else
fStamp := lBase;
Result := fStamp;
end;
function TMaxFileDependency.IsStale(out aNewStamp: TMaxDependencyStamp): Boolean;
var
lBase: TMaxDependencyStamp;
lIncludeHash: Boolean;
begin
lBase := ComputeStamp(False);
lIncludeHash := ShouldHash(lBase, fForceHash);
if lIncludeHash then
aNewStamp := ComputeStamp(True)
else
aNewStamp := lBase;
Result := not fStamp.Equals(aNewStamp);
end;
{ TMaxCacheConfig }
class function TMaxCacheConfig.Default: TMaxCacheConfig;
begin
Result.DefaultTtlMs := 0;
Result.DefaultIdleMs := 0;
Result.DefaultValidateIntervalMs := 0;
Result.MaxEntriesGlobal := 0;
Result.MaxBytesGlobal := 0;
Result.MaxEntriesPerNamespace := 0;
Result.MaxBytesPerNamespace := 0;
Result.MinFailCacheMs := 500;
Result.DefaultWaitTimeoutMs := 30000;
Result.AlwaysHashBelowBytes := 51200;
Result.SweepIntervalMs := 10000;
Result.SweepBatchSize := 200;
Result.CaseSensitiveKeys := True;
Result.ReturnStaleOnFailure := False;
end;
{ TMaxCacheOptions }
constructor TMaxCacheOptions.Create;
begin
inherited Create;
TtlMs := 0;
IdleMs := 0;
ValidateIntervalMs := 0;
FailCacheMs := 0;
SizeEstimateBytes := 0;
Tags := [];
Dependency := nil;
ReturnStaleOnFailure := False;
end;
{ TMaxCache.TMaxCacheEntry }
constructor TMaxCache.TMaxCacheEntry.Create;
begin
inherited Create;
fRefCount := 1;
EntrySync := TObject.Create;
State := TMaxCacheEntryState.Empty;
Value := nil;
CreatedAtMs := 0;
LastAccessMs := 0;
ExpiresAtMs := 0;
IdleExpiresAtMs := 0;
NextValidateMs := 0;
ValidateIntervalMs := 0;
IsValidating := 0;
WasInvalidated := 0;
Dependency := nil;
Stamp.MTimeUtcMs := 0;
Stamp.SizeBytes := -1;
Stamp.Hash32 := 0;
Stamp.HasHash := False;
Tags := [];
SizeEstimateBytes := 0;
RetryAtMs := 0;
FailCacheMs := 0;
ReturnStaleOnFailure := False;
TtlMs := 0;
IdleMs := 0;
LastLoadTimeMs := 0;
LastErrorMsg := '';
LastErrorClassName := '';
end;
destructor TMaxCache.TMaxCacheEntry.Destroy;
begin
EntrySync.Free;
inherited Destroy;
end;
procedure TMaxCache.TMaxCacheEntry.AddRef;
begin
TInterlocked.Increment(fRefCount);
end;
procedure TMaxCache.TMaxCacheEntry.Release;
begin
if TInterlocked.Decrement(fRefCount) = 0 then
Free;
end;
{ TMaxCache.TMaxNamespaceBucket }
constructor TMaxCache.TMaxNamespaceBucket.Create(const aComparer: IEqualityComparer<string>);
begin
inherited Create;
Items := TDictionary<string, TMaxCacheEntry>.Create(aComparer);
end;
destructor TMaxCache.TMaxNamespaceBucket.Destroy;
var
lEntry: TMaxCacheEntry;
begin
for lEntry in Items.Values do
lEntry.Release;
Items.Free;
inherited Destroy;
end;
{ TMaxCache }
class function TMaxCache.New(const aConfig: TMaxCacheConfig): IMaxCache;
begin
Result := TMaxCache.Create(aConfig);
end;
class function TMaxCache.New: IMaxCache;
begin
Result := TMaxCache.Create(TMaxCacheConfig.Default);
end;
class function TMaxCache.ScopedTag(const aNamespace, aTag: string): string;
begin
if aTag.StartsWith(cGlobalTagPrefix, True) then
Exit(aTag);
if aTag.IndexOf(cScopedTagSep) >= 0 then
raise EMaxCacheException.Create('Tag must be unscoped (no "|") unless it starts with global:');
Result := aNamespace + cScopedTagSep + aTag;
end;
constructor TMaxCache.Create(const aConfig: TMaxCacheConfig);
var
lInterval: Integer;
begin
inherited Create;
fConfig := aConfig;
if fConfig.CaseSensitiveKeys then
fComparer := TFastCaseAwareComparer.Ordinal
else
fComparer := TFastCaseAwareComparer.OrdinalIgnoreCase;
fNamespaces := TDictionary<string, TMaxNamespaceBucket>.Create(fComparer);
fTagIndex := TDictionary<string, TDictionary<string, Byte>>.Create(fComparer);
fHits := 0;
fMisses := 0;
fLoads := 0;
fLoadFailures := 0;
fInvalidationsDirect := 0;
fInvalidationsByTag := 0;
fEvictionsTtl := 0;
fEvictionsIdle := 0;
fEvictionsSize := 0;
fTotalLoadTimeMs := 0;
FillChar(fLoadTimeHistogram, SizeOf(fLoadTimeHistogram), 0);
fIsShuttingDown := 0;
fSweeper := nil;
fSweepRunning := 0;
lInterval := ClampNonNegative(fConfig.SweepIntervalMs);
if lInterval < cMinSweepIntervalMs then
lInterval := cMinSweepIntervalMs;
if (fConfig.SweepIntervalMs > 0) and (fConfig.SweepBatchSize > 0) then
begin
fSweeper := TPortableTimer.Create;
fSweeper.SchedulingMode := tmFixedDelay;
fSweeper.OnTimer := SweeperTimer;
fSweeper.Start(Cardinal(lInterval));
end;
end;
destructor TMaxCache.Destroy;
var
lBucket: TMaxNamespaceBucket;
lSet: TDictionary<string, Byte>;
begin
Shutdown;
if fSweeper <> nil then
begin
fSweeper.Stop;
fSweeper.Free;
fSweeper := nil;
end;
fNamespacesLock.BeginWrite;
try
for lBucket in fNamespaces.Values do
lBucket.Free;
fNamespaces.Free;
fNamespaces := nil;
finally
fNamespacesLock.EndWrite;
end;
fTagIndexLock.BeginWrite;
try
if fTagIndex <> nil then
begin
for lSet in fTagIndex.Values do
lSet.Free;
fTagIndex.Free;
end;
fTagIndex := nil;
finally
fTagIndexLock.EndWrite;
end;
inherited Destroy;
end;
class function TMaxCache.NowMs: Int64;
begin
Result := (TStopwatch.GetTimeStamp * 1000) div TStopwatch.Frequency;
end;
class function TMaxCache.ClampNonNegative(const aValue: Integer): Integer;
begin
if aValue < 0 then
Exit(0);
Result := aValue;
end;
class function TMaxCache.ReadInt64(var aValue: Int64): Int64;
begin
{$IFDEF CPUX86}
Result := TInterlocked.CompareExchange(aValue, 0, 0);
{$ELSE}
Result := aValue;
{$ENDIF}
end;
class procedure TMaxCache.WriteInt64(var aTarget: Int64; const aValue: Int64);
begin
{$IFDEF CPUX86}
TInterlocked.Exchange(aTarget, aValue);
{$ELSE}
aTarget := aValue;
{$ENDIF}
end;
procedure TMaxCache.EnsureNotShuttingDown;
begin
if TInterlocked.CompareExchange(fIsShuttingDown, 0, 0) <> 0 then
raise EMaxCacheShutdown.Create('Cache is shutting down');
end;
function TMaxCache.TryGetBucket(const aNamespace: string): TMaxNamespaceBucket;
begin
Result := nil;
fNamespacesLock.BeginRead;
try
fNamespaces.TryGetValue(aNamespace, Result);
finally
fNamespacesLock.EndRead;
end;
end;
function TMaxCache.GetOrCreateBucket(const aNamespace: string): TMaxNamespaceBucket;
begin
Result := TryGetBucket(aNamespace);
if Result <> nil then
Exit;
fNamespacesLock.BeginWrite;
try
if not fNamespaces.TryGetValue(aNamespace, Result) then
begin
Result := TMaxNamespaceBucket.Create(fComparer);
fNamespaces.Add(aNamespace, Result);
end;
finally
fNamespacesLock.EndWrite;
end;
end;
function TMaxCache.TryGetEntry(const aBucket: TMaxNamespaceBucket; const aKey: string): TMaxCacheEntry;
begin
Result := nil;
aBucket.Lock.BeginRead;
try
if aBucket.Items.TryGetValue(aKey, Result) then
Result.AddRef
else
Result := nil;
finally
aBucket.Lock.EndRead;
end;
end;
procedure TMaxCache.MarkEntryInvalidated(const aEntry: TMaxCacheEntry; const aClearValue: Boolean; out aTags: TArray<string>);
begin
aTags := [];
TMonitor.Enter(aEntry.EntrySync);
try
aTags := aEntry.Tags;
aEntry.WasInvalidated := 1;
aEntry.State := TMaxCacheEntryState.Obsolete;
if aClearValue then
aEntry.Value := nil;
TMonitor.PulseAll(aEntry.EntrySync);
finally
TMonitor.Exit(aEntry.EntrySync);
end;
end;
function TMaxCache.RemoveEntryIfSame(const aBucket: TMaxNamespaceBucket; const aKey: string; const aEntry: TMaxCacheEntry): Boolean;
var
lCurrent: TMaxCacheEntry;
begin
Result := False;
aBucket.Lock.BeginWrite;
try
if aBucket.Items.TryGetValue(aKey, lCurrent) and (lCurrent = aEntry) then
begin
aBucket.Items.Remove(aKey);
Result := True;
end;
finally
aBucket.Lock.EndWrite;
end;
end;
function TMaxCache.IsExpired(const aEntry: TMaxCacheEntry; const aNowMs: Int64; out aEvictKind: Integer): Boolean;
var
lExpiresAt: Int64;
lIdleExpiresAt: Int64;
begin
aEvictKind := 0;
lExpiresAt := ReadInt64(aEntry.ExpiresAtMs);
if (lExpiresAt > 0) and (aNowMs >= lExpiresAt) then
begin
aEvictKind := 1;
Exit(True);
end;
lIdleExpiresAt := ReadInt64(aEntry.IdleExpiresAtMs);
if (lIdleExpiresAt > 0) and (aNowMs >= lIdleExpiresAt) then
begin
aEvictKind := 2;
Exit(True);
end;
Result := False;
end;
procedure TMaxCache.TouchEntry(const aEntry: TMaxCacheEntry; const aNowMs: Int64);
begin
WriteInt64(aEntry.LastAccessMs, aNowMs);
if aEntry.IdleMs > 0 then
WriteInt64(aEntry.IdleExpiresAtMs, aNowMs + aEntry.IdleMs);
end;
function TMaxCache.ValidateDependency(const aEntry: TMaxCacheEntry; const aNowMs: Int64): Boolean;
var
lShouldValidate: Boolean;
lNewStamp: TMaxDependencyStamp;
lIsStale: Boolean;
lNext: Int64;
begin
if aEntry.Dependency = nil then
Exit(True);
if aEntry.ValidateIntervalMs = 0 then
lShouldValidate := True
else
lShouldValidate := (aNowMs >= ReadInt64(aEntry.NextValidateMs));
if not lShouldValidate then
Exit(True);
if TInterlocked.CompareExchange(aEntry.IsValidating, 1, 0) <> 0 then
Exit(True); // another thread validates; optimistic
try
// Another thread may have completed validation between our first check and winning the CAS.
// Re-check "due" under the entry monitor to guarantee at most one validation per interval.
TMonitor.Enter(aEntry.EntrySync);
try
if aEntry.ValidateIntervalMs = 0 then
lShouldValidate := True
else
lShouldValidate := (aNowMs >= ReadInt64(aEntry.NextValidateMs));
finally
TMonitor.Exit(aEntry.EntrySync);
end;
if not lShouldValidate then
Exit(True);
lIsStale := False;
try
lIsStale := aEntry.Dependency.IsStale(lNewStamp);
except
lIsStale := True;
end;
TMonitor.Enter(aEntry.EntrySync);
try
if aEntry.ValidateIntervalMs = 0 then
lNext := aNowMs
else
lNext := aNowMs + aEntry.ValidateIntervalMs;
WriteInt64(aEntry.NextValidateMs, lNext);
if lIsStale and (aEntry.State = TMaxCacheEntryState.Ready) then
aEntry.State := TMaxCacheEntryState.Obsolete;
finally
TMonitor.Exit(aEntry.EntrySync);
end;
Result := not lIsStale;
finally
TInterlocked.Exchange(aEntry.IsValidating, 0);
end;
end;
procedure TMaxCache.WaitForEntry(const aEntry: TMaxCacheEntry);
var
lTimeout: Integer;
lRetryAt: Int64;
lFailCacheMs: Integer;
begin
lTimeout := fConfig.DefaultWaitTimeoutMs;
if lTimeout <= 0 then
lTimeout := 30000;
lRetryAt := 0;
lFailCacheMs := 0;
TMonitor.Enter(aEntry.EntrySync);
try
if aEntry.State <> TMaxCacheEntryState.Loading then
Exit;
if not TMonitor.Wait(aEntry.EntrySync, lTimeout) then
begin
if aEntry.State = TMaxCacheEntryState.Loading then
begin
aEntry.State := TMaxCacheEntryState.Failed;
aEntry.LastErrorMsg := 'Timed out waiting for cache entry load';
aEntry.LastErrorClassName := EMaxCacheWaitTimeout.ClassName;
lFailCacheMs := aEntry.FailCacheMs;
if lFailCacheMs < fConfig.MinFailCacheMs then
lFailCacheMs := fConfig.MinFailCacheMs;
aEntry.FailCacheMs := lFailCacheMs;
lRetryAt := NowMs + lFailCacheMs;
WriteInt64(aEntry.RetryAtMs, lRetryAt);
TMonitor.PulseAll(aEntry.EntrySync);
raise EMaxCacheWaitTimeout.Create('Timed out waiting for cache entry load');
end;
end;
finally
TMonitor.Exit(aEntry.EntrySync);
end;
end;
function TMaxCache.TryBeginLoad(
const aKey: string;
const aBucket: TMaxNamespaceBucket;
const aNowMs: Int64;
const aForceLoad: Boolean;
out aEntry: TMaxCacheEntry): Boolean;
var
lEntry: TMaxCacheEntry;
begin
aEntry := nil;
Result := False;
aBucket.Lock.BeginWrite;
try
if not aBucket.Items.TryGetValue(aKey, lEntry) then
begin
lEntry := TMaxCacheEntry.Create;
lEntry.State := TMaxCacheEntryState.Loading;
WriteInt64(lEntry.CreatedAtMs, aNowMs);
WriteInt64(lEntry.LastAccessMs, aNowMs);
aBucket.Items.Add(aKey, lEntry);
lEntry.AddRef;
aEntry := lEntry;
Exit(True);
end;
lEntry.AddRef;
aEntry := lEntry;
if lEntry.State = TMaxCacheEntryState.Loading then
Exit(False);
if lEntry.State = TMaxCacheEntryState.Failed then
begin
if aNowMs < ReadInt64(lEntry.RetryAtMs) then
Exit(False);
end;
if (not aForceLoad) and (lEntry.State = TMaxCacheEntryState.Ready) then
Exit(False);
lEntry.State := TMaxCacheEntryState.Loading;
Result := True;
finally
aBucket.Lock.EndWrite;
end;
end;
procedure TMaxCache.RegisterTags(const aNamespace, aKey: string; const aTags: TArray<string>);
var
lTag: string;
lScoped: string;
lRefKey: string;
lSet: TDictionary<string, Byte>;
begin
if Length(aTags) = 0 then
Exit;
lRefKey := aNamespace + cTagRefSep + aKey;
fTagIndexLock.BeginWrite;
try
for lTag in aTags do
begin
lScoped := ScopedTag(aNamespace, lTag);
if not fTagIndex.TryGetValue(lScoped, lSet) then
begin
lSet := TDictionary<string, Byte>.Create(fComparer);
fTagIndex.Add(lScoped, lSet);
end;
lSet.AddOrSetValue(lRefKey, 0);
end;
finally
fTagIndexLock.EndWrite;
end;
end;
procedure TMaxCache.UnregisterTags(const aNamespace, aKey: string; const aTags: TArray<string>);
var
lTag: string;
lScoped: string;
lRefKey: string;
lSet: TDictionary<string, Byte>;
begin
if Length(aTags) = 0 then
Exit;
lRefKey := aNamespace + cTagRefSep + aKey;
fTagIndexLock.BeginWrite;
try
for lTag in aTags do
begin
lScoped := ScopedTag(aNamespace, lTag);
if fTagIndex.TryGetValue(lScoped, lSet) then
begin
lSet.Remove(lRefKey);
if lSet.Count = 0 then
begin
fTagIndex.Remove(lScoped);
lSet.Free;
end;
end;
end;
finally
fTagIndexLock.EndWrite;
end;
end;
function TMaxCache.GetTagRefsCopy(const aScopedTag: string): TArray<TMaxTagRef>;
var
lSet: TDictionary<string, Byte>;
lRefKey: string;
lSepPos: Integer;
lIdx: Integer;
begin
Result := [];
fTagIndexLock.BeginRead;
try
if not fTagIndex.TryGetValue(aScopedTag, lSet) then
Exit;
SetLength(Result, lSet.Count);
lIdx := 0;
for lRefKey in lSet.Keys do
begin
lSepPos := lRefKey.IndexOf(cTagRefSep);
if lSepPos > 0 then
begin
Result[lIdx].Namespace := lRefKey.Substring(0, lSepPos);
Result[lIdx].Key := lRefKey.Substring(lSepPos + 1);
Inc(lIdx);
end;
end;
if lIdx <> Length(Result) then
SetLength(Result, lIdx);
finally
fTagIndexLock.EndRead;
end;
end;
procedure TMaxCache.RecordLoadTimeMs(const aElapsedMs: Integer);