-
Notifications
You must be signed in to change notification settings - Fork 550
/
Copy pathMainStoreOps.cs
1046 lines (896 loc) · 49.7 KB
/
MainStoreOps.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 (c) Microsoft Corporation.
// Licensed under the MIT license.
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Garnet.common;
using Tsavorite.core;
namespace Garnet.server
{
using MainStoreAllocator = SpanByteAllocator<StoreFunctions<SpanByte, SpanByte, SpanByteComparer, SpanByteRecordDisposer>>;
using MainStoreFunctions = StoreFunctions<SpanByte, SpanByte, SpanByteComparer, SpanByteRecordDisposer>;
using ObjectStoreAllocator = GenericAllocator<byte[], IGarnetObject, StoreFunctions<byte[], IGarnetObject, ByteArrayKeyComparer, DefaultRecordDisposer<byte[], IGarnetObject>>>;
using ObjectStoreFunctions = StoreFunctions<byte[], IGarnetObject, ByteArrayKeyComparer, DefaultRecordDisposer<byte[], IGarnetObject>>;
sealed partial class StorageSession : IDisposable
{
public GarnetStatus GET<TContext>(ref SpanByte key, ref SpanByte input, ref SpanByteAndMemory output, ref TContext context)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
{
long ctx = default;
var status = context.Read(ref key, ref input, ref output, ctx);
if (status.IsPending)
{
StartPendingMetrics();
CompletePendingForSession(ref status, ref output, ref context);
StopPendingMetrics();
}
if (status.Found)
{
incr_session_found();
return GarnetStatus.OK;
}
else
{
incr_session_notfound();
return GarnetStatus.NOTFOUND;
}
}
public unsafe GarnetStatus ReadWithUnsafeContext<TContext>(ArgSlice key, ref SpanByte input, ref SpanByteAndMemory output, long localHeadAddress, out bool epochChanged, ref TContext context)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>, IUnsafeContext
{
var _key = key.SpanByte;
long ctx = default;
epochChanged = false;
var status = context.Read(ref _key, ref Unsafe.AsRef(in input), ref output, ctx);
if (status.IsPending)
{
context.EndUnsafe();
StartPendingMetrics();
CompletePendingForSession(ref status, ref output, ref context);
StopPendingMetrics();
context.BeginUnsafe();
// Start read of pointers from beginning if epoch changed
if (HeadAddress == localHeadAddress)
{
context.EndUnsafe();
epochChanged = true;
}
}
else if (status.NotFound)
{
incr_session_notfound();
return GarnetStatus.NOTFOUND;
}
else
{
incr_session_found();
}
return GarnetStatus.OK;
}
public unsafe GarnetStatus GET<TContext>(ArgSlice key, out ArgSlice value, ref TContext context)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
{
int inputSize = sizeof(int) + RespInputHeader.Size;
byte* pbCmdInput = stackalloc byte[inputSize];
byte* pcurr = pbCmdInput;
*(int*)pcurr = inputSize - sizeof(int);
pcurr += sizeof(int);
(*(RespInputHeader*)pcurr).cmd = RespCommand.GET; // Proxy for "get value without RESP header"
(*(RespInputHeader*)pcurr).flags = 0;
var _key = key.SpanByte;
var _output = new SpanByteAndMemory { SpanByte = scratchBufferManager.ViewRemainingArgSlice().SpanByte };
var ret = GET(ref _key, ref Unsafe.AsRef<SpanByte>(pbCmdInput), ref _output, ref context);
value = default;
if (ret == GarnetStatus.OK)
{
if (!_output.IsSpanByte)
{
value = scratchBufferManager.FormatScratch(0, _output.AsReadOnlySpan());
_output.Memory.Dispose();
}
else
{
value = scratchBufferManager.CreateArgSlice(_output.Length);
}
}
return ret;
}
public unsafe GarnetStatus GET<TContext>(ArgSlice key, out MemoryResult<byte> value, ref TContext context)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
{
int inputSize = sizeof(int) + RespInputHeader.Size;
byte* pbCmdInput = stackalloc byte[inputSize];
byte* pcurr = pbCmdInput;
*(int*)pcurr = inputSize - sizeof(int);
pcurr += sizeof(int);
(*(RespInputHeader*)pcurr).cmd = RespCommand.GET; // Proxy for "get value without RESP header"
(*(RespInputHeader*)pcurr).flags = 0;
var _key = key.SpanByte;
var _output = new SpanByteAndMemory();
var ret = GET(ref _key, ref Unsafe.AsRef<SpanByte>(pbCmdInput), ref _output, ref context);
value = new MemoryResult<byte>(_output.Memory, _output.Length);
return ret;
}
public GarnetStatus GET<TObjectContext>(byte[] key, out GarnetObjectStoreOutput output, ref TObjectContext objectContext)
where TObjectContext : ITsavoriteContext<byte[], IGarnetObject, ObjectInput, GarnetObjectStoreOutput, long, ObjectSessionFunctions, ObjectStoreFunctions, ObjectStoreAllocator>
{
long ctx = default;
var status = objectContext.Read(key, out output, ctx);
if (status.IsPending)
{
StartPendingMetrics();
CompletePendingForObjectStoreSession(ref status, ref output, ref objectContext);
StopPendingMetrics();
}
if (status.Found)
{
incr_session_found();
return GarnetStatus.OK;
}
else
{
incr_session_notfound();
return GarnetStatus.NOTFOUND;
}
}
/// <summary>
/// GETDEL command - Gets the value corresponding to the given key and deletes the key.
/// </summary>
/// <param name="key">The key to get the value for.</param>
/// <param name="output">Span to allocate the output of the operation</param>
/// <param name="context">Basic Context of the store</param>
/// <returns> Operation status </returns>
public unsafe GarnetStatus GETDEL<TContext>(ArgSlice key, ref SpanByteAndMemory output, ref TContext context)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
{
var _key = key.SpanByte;
return GETDEL(ref _key, ref output, ref context);
}
/// <summary>
/// GETDEL command - Gets the value corresponding to the given key and deletes the key.
/// </summary>
/// <param name="key">The key to get the value for.</param>
/// <param name="output">Span to allocate the output of the operation</param>
/// <param name="context">Basic Context of the store</param>
/// <returns> Operation status </returns>
public unsafe GarnetStatus GETDEL<TContext>(ref SpanByte key, ref SpanByteAndMemory output, ref TContext context)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
{
// size data + header
int inputSize = sizeof(int) + RespInputHeader.Size;
byte* pbCmdInput = stackalloc byte[inputSize];
byte* pcurr = pbCmdInput;
*(int*)pbCmdInput = inputSize - sizeof(int);
pcurr += sizeof(int);
((RespInputHeader*)pcurr)->cmd = RespCommand.GETDEL;
((RespInputHeader*)pcurr)->flags = 0;
ref var input = ref SpanByte.Reinterpret(pbCmdInput);
var status = context.RMW(ref key, ref input, ref output);
Debug.Assert(output.IsSpanByte);
if (status.IsPending)
CompletePendingForSession(ref status, ref output, ref context);
return status.Found ? GarnetStatus.OK : GarnetStatus.NOTFOUND;
}
public unsafe GarnetStatus GETRANGE<TContext>(ref SpanByte key, int sliceStart, int sliceLength, ref SpanByteAndMemory output, ref TContext context)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
{
int inputSize = sizeof(int) + RespInputHeader.Size + sizeof(int) * 2;
byte* pbCmdInput = stackalloc byte[inputSize];
byte* pcurr = pbCmdInput;
*(int*)pcurr = inputSize - sizeof(int);
pcurr += sizeof(int);
(*(RespInputHeader*)(pcurr)).cmd = RespCommand.GETRANGE;
(*(RespInputHeader*)(pcurr)).flags = 0;
pcurr += RespInputHeader.Size;
*(int*)(pcurr) = sliceStart;
*(int*)(pcurr + 4) = sliceLength;
var status = context.Read(ref key, ref Unsafe.AsRef<SpanByte>(pbCmdInput), ref output);
if (status.IsPending)
{
StartPendingMetrics();
CompletePendingForSession(ref status, ref output, ref context);
StopPendingMetrics();
}
if (status.Found)
{
incr_session_found();
return GarnetStatus.OK;
}
else
{
incr_session_notfound();
return GarnetStatus.NOTFOUND;
}
}
/// <summary>
/// Returns the remaining time to live of a key that has a timeout.
/// </summary>
/// <typeparam name="TContext"></typeparam>
/// <typeparam name="TObjectContext"></typeparam>
/// <param name="key">The key to get the remaining time to live in the store.</param>
/// <param name="storeType">The store to operate on</param>
/// <param name="output">Span to allocate the output of the operation</param>
/// <param name="context">Basic Context of the store</param>
/// <param name="objectContext">Object Context of the store</param>
/// <param name="milliseconds">when true the command to execute is PTTL.</param>
/// <returns></returns>
public unsafe GarnetStatus TTL<TContext, TObjectContext>(ref SpanByte key, StoreType storeType, ref SpanByteAndMemory output, ref TContext context, ref TObjectContext objectContext, bool milliseconds = false)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
where TObjectContext : ITsavoriteContext<byte[], IGarnetObject, ObjectInput, GarnetObjectStoreOutput, long, ObjectSessionFunctions, ObjectStoreFunctions, ObjectStoreAllocator>
{
int inputSize = sizeof(int) + RespInputHeader.Size;
byte* pbCmdInput = stackalloc byte[inputSize];
byte* pcurr = pbCmdInput;
*(int*)pcurr = inputSize - sizeof(int);
pcurr += sizeof(int);
(*(RespInputHeader*)pcurr).cmd = milliseconds ? RespCommand.PTTL : RespCommand.TTL;
(*(RespInputHeader*)pcurr).flags = 0;
if (storeType == StoreType.Main || storeType == StoreType.All)
{
var status = context.Read(ref key, ref Unsafe.AsRef<SpanByte>(pbCmdInput), ref output);
if (status.IsPending)
{
StartPendingMetrics();
CompletePendingForSession(ref status, ref output, ref context);
StopPendingMetrics();
}
if (status.Found) return GarnetStatus.OK;
}
if ((storeType == StoreType.Object || storeType == StoreType.All) && !objectStoreBasicContext.IsNull)
{
var objInput = new ObjectInput
{
header = new RespInputHeader
{
cmd = milliseconds ? RespCommand.PTTL : RespCommand.TTL,
type = milliseconds ? GarnetObjectType.PTtl : GarnetObjectType.Ttl,
},
};
var keyBA = key.ToByteArray();
var objO = new GarnetObjectStoreOutput { spanByteAndMemory = output };
var status = objectContext.Read(ref keyBA, ref objInput, ref objO);
if (status.IsPending)
CompletePendingForObjectStoreSession(ref status, ref objO, ref objectContext);
if (status.Found)
{
output = objO.spanByteAndMemory;
return GarnetStatus.OK;
}
}
return GarnetStatus.NOTFOUND;
}
public GarnetStatus SET<TContext>(ref SpanByte key, ref SpanByte value, ref TContext context)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
{
context.Upsert(ref key, ref value);
return GarnetStatus.OK;
}
public unsafe GarnetStatus SET_Conditional<TContext>(ref SpanByte key, ref SpanByte input, ref TContext context)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
{
byte* pbOutput = stackalloc byte[8];
var o = new SpanByteAndMemory(pbOutput, 8);
var status = context.RMW(ref key, ref input, ref o);
if (status.IsPending)
{
StartPendingMetrics();
CompletePendingForSession(ref status, ref o, ref context);
StopPendingMetrics();
}
if (status.NotFound)
{
incr_session_notfound();
return GarnetStatus.NOTFOUND;
}
else
{
incr_session_found();
return GarnetStatus.OK;
}
}
public unsafe GarnetStatus SET_Conditional<TContext>(ref SpanByte key, ref SpanByte input, ref SpanByteAndMemory output, ref TContext context)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
{
var status = context.RMW(ref key, ref input, ref output);
if (status.IsPending)
{
StartPendingMetrics();
CompletePendingForSession(ref status, ref output, ref context);
StopPendingMetrics();
}
if (status.NotFound)
{
incr_session_notfound();
return GarnetStatus.NOTFOUND;
}
else
{
incr_session_found();
return GarnetStatus.OK;
}
}
public GarnetStatus SET<TContext>(ArgSlice key, ArgSlice value, ref TContext context)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
{
var _key = key.SpanByte;
var _value = value.SpanByte;
return SET(ref _key, ref _value, ref context);
}
public GarnetStatus SET<TObjectContext>(byte[] key, IGarnetObject value, ref TObjectContext objectContext)
where TObjectContext : ITsavoriteContext<byte[], IGarnetObject, ObjectInput, GarnetObjectStoreOutput, long, ObjectSessionFunctions, ObjectStoreFunctions, ObjectStoreAllocator>
{
objectContext.Upsert(key, value);
return GarnetStatus.OK;
}
public GarnetStatus SET<TContext>(ArgSlice key, Memory<byte> value, ref TContext context)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
{
var _key = key.SpanByte;
unsafe
{
fixed (byte* ptr = value.Span)
{
var _value = SpanByte.FromPinnedPointer(ptr, value.Length);
return SET(ref _key, ref _value, ref context);
}
}
}
public unsafe GarnetStatus SETEX<TContext>(ArgSlice key, ArgSlice value, ArgSlice expiryMs, ref TContext context)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
=> SETEX(key, value, TimeSpan.FromMilliseconds(NumUtils.BytesToLong(expiryMs.Length, expiryMs.ptr)), ref context);
public GarnetStatus SETEX<TContext>(ArgSlice key, ArgSlice value, TimeSpan expiry, ref TContext context)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
{
var _key = key.SpanByte;
var valueSB = scratchBufferManager.FormatScratch(sizeof(long), value).SpanByte;
valueSB.ExtraMetadata = DateTimeOffset.UtcNow.Ticks + expiry.Ticks;
return SET(ref _key, ref valueSB, ref context);
}
/// <summary>
/// APPEND command - appends value at the end of existing string
/// </summary>
/// <typeparam name="TContext">Context type</typeparam>
/// <param name="key">Key whose value is to be appended</param>
/// <param name="value">Value to be appended</param>
/// <param name="output">Length of updated value</param>
/// <param name="context">Store context</param>
/// <returns>Operation status</returns>
public unsafe GarnetStatus APPEND<TContext>(ArgSlice key, ArgSlice value, ref ArgSlice output, ref TContext context)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
{
var _key = key.SpanByte;
var _value = value.SpanByte;
var _output = new SpanByteAndMemory(output.SpanByte);
return APPEND(ref _key, ref _value, ref _output, ref context);
}
/// <summary>
/// APPEND command - appends value at the end of existing string
/// </summary>
/// <typeparam name="TContext">Context type</typeparam>
/// <param name="key">Key whose value is to be appended</param>
/// <param name="value">Value to be appended</param>
/// <param name="output">Length of updated value</param>
/// <param name="context">Store context</param>
/// <returns>Operation status</returns>
public unsafe GarnetStatus APPEND<TContext>(ref SpanByte key, ref SpanByte value, ref SpanByteAndMemory output, ref TContext context)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
{
int inputSize = sizeof(int) + RespInputHeader.Size + sizeof(int) + sizeof(long);
byte* pbCmdInput = stackalloc byte[inputSize];
byte* pcurr = pbCmdInput;
*(int*)pcurr = inputSize - sizeof(int);
pcurr += sizeof(int);
(*(RespInputHeader*)(pcurr)).cmd = RespCommand.APPEND;
(*(RespInputHeader*)(pcurr)).flags = 0;
pcurr += RespInputHeader.Size;
*(int*)pcurr = value.Length;
pcurr += sizeof(int);
*(long*)pcurr = (long)value.ToPointer();
var status = context.RMW(ref key, ref Unsafe.AsRef<SpanByte>(pbCmdInput), ref output);
if (status.IsPending)
{
StartPendingMetrics();
CompletePendingForSession(ref status, ref output, ref context);
StopPendingMetrics();
}
Debug.Assert(output.IsSpanByte);
return GarnetStatus.OK;
}
public GarnetStatus DELETE<TContext, TObjectContext>(ArgSlice key, StoreType storeType, ref TContext context, ref TObjectContext objectContext)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
where TObjectContext : ITsavoriteContext<byte[], IGarnetObject, ObjectInput, GarnetObjectStoreOutput, long, ObjectSessionFunctions, ObjectStoreFunctions, ObjectStoreAllocator>
{
var _key = key.SpanByte;
return DELETE(ref _key, storeType, ref context, ref objectContext);
}
public GarnetStatus DELETE<TContext, TObjectContext>(ref SpanByte key, StoreType storeType, ref TContext context, ref TObjectContext objectContext)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
where TObjectContext : ITsavoriteContext<byte[], IGarnetObject, ObjectInput, GarnetObjectStoreOutput, long, ObjectSessionFunctions, ObjectStoreFunctions, ObjectStoreAllocator>
{
var found = false;
if (storeType == StoreType.Main || storeType == StoreType.All)
{
var status = context.Delete(ref key);
Debug.Assert(!status.IsPending);
if (status.Found) found = true;
}
if (!objectStoreBasicContext.IsNull && (storeType == StoreType.Object || storeType == StoreType.All))
{
var keyBA = key.ToByteArray();
var status = objectContext.Delete(ref keyBA);
Debug.Assert(!status.IsPending);
if (status.Found) found = true;
}
return found ? GarnetStatus.OK : GarnetStatus.NOTFOUND;
}
public GarnetStatus DELETE<TContext, TObjectContext>(byte[] key, StoreType storeType, ref TContext context, ref TObjectContext objectContext)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
where TObjectContext : ITsavoriteContext<byte[], IGarnetObject, ObjectInput, GarnetObjectStoreOutput, long, ObjectSessionFunctions, ObjectStoreFunctions, ObjectStoreAllocator>
{
bool found = false;
if ((storeType == StoreType.Object || storeType == StoreType.All) && !objectStoreBasicContext.IsNull)
{
var status = objectContext.Delete(key);
Debug.Assert(!status.IsPending);
if (status.Found) found = true;
}
if (!found && (storeType == StoreType.Main || storeType == StoreType.All))
{
unsafe
{
fixed (byte* ptr = key)
{
var keySB = SpanByte.FromPinnedPointer(ptr, key.Length);
var status = context.Delete(ref keySB);
Debug.Assert(!status.IsPending);
if (status.Found) found = true;
}
}
}
return found ? GarnetStatus.OK : GarnetStatus.NOTFOUND;
}
public unsafe GarnetStatus RENAME(ArgSlice oldKeySlice, ArgSlice newKeySlice, StoreType storeType)
{
GarnetStatus returnStatus = GarnetStatus.NOTFOUND;
// If same name check return early.
if (oldKeySlice.ReadOnlySpan.SequenceEqual(newKeySlice.ReadOnlySpan))
return GarnetStatus.OK;
bool createTransaction = false;
if (txnManager.state != TxnState.Running)
{
createTransaction = true;
txnManager.SaveKeyEntryToLock(oldKeySlice, false, LockType.Exclusive);
txnManager.SaveKeyEntryToLock(newKeySlice, false, LockType.Exclusive);
txnManager.Run(true);
}
var context = txnManager.LockableContext;
var objectContext = txnManager.ObjectStoreLockableContext;
SpanByte oldKey = oldKeySlice.SpanByte;
if (storeType == StoreType.Main || storeType == StoreType.All)
{
try
{
SpanByte input = default;
var o = new SpanByteAndMemory();
var status = GET(ref oldKey, ref input, ref o, ref context);
if (status == GarnetStatus.OK)
{
Debug.Assert(!o.IsSpanByte);
var memoryHandle = o.Memory.Memory.Pin();
var ptrVal = (byte*)memoryHandle.Pointer;
RespReadUtils.ReadUnsignedLengthHeader(out var headerLength, ref ptrVal, ptrVal + o.Length);
// Find expiration time of the old key
var expireSpan = new SpanByteAndMemory();
var ttlStatus = TTL(ref oldKey, storeType, ref expireSpan, ref context, ref objectContext, true);
if (ttlStatus == GarnetStatus.OK && !expireSpan.IsSpanByte)
{
using var expireMemoryHandle = expireSpan.Memory.Memory.Pin();
var expirePtrVal = (byte*)expireMemoryHandle.Pointer;
RespReadUtils.TryRead64Int(out var expireTimeMs, ref expirePtrVal, expirePtrVal + expireSpan.Length, out var _);
// If the key has an expiration, set the new key with the expiration
if (expireTimeMs > 0)
{
SETEX(newKeySlice, new ArgSlice(ptrVal, headerLength), TimeSpan.FromMilliseconds(expireTimeMs), ref context);
}
else if (expireTimeMs == -1) // Its possible to have expireTimeMs as 0 (Key expired or will be expired now) or -2 (Key does not exist), in those cases we don't SET the new key
{
SpanByte newKey = newKeySlice.SpanByte;
var value = SpanByte.FromPinnedPointer(ptrVal, headerLength);
SET(ref newKey, ref value, ref context);
}
expireSpan.Memory.Dispose();
memoryHandle.Dispose();
o.Memory.Dispose();
// Delete the old key
DELETE(ref oldKey, StoreType.Main, ref context, ref objectContext);
returnStatus = GarnetStatus.OK;
}
}
}
finally
{
if (createTransaction)
txnManager.Commit(true);
}
}
if ((storeType == StoreType.Object || storeType == StoreType.All) && !objectStoreBasicContext.IsNull)
{
createTransaction = false;
if (txnManager.state != TxnState.Running)
{
txnManager.SaveKeyEntryToLock(oldKeySlice, true, LockType.Exclusive);
txnManager.SaveKeyEntryToLock(newKeySlice, true, LockType.Exclusive);
txnManager.Run(true);
createTransaction = true;
}
try
{
byte[] oldKeyArray = oldKeySlice.ToArray();
var status = GET(oldKeyArray, out var value, ref objectContext);
if (status == GarnetStatus.OK)
{
var valObj = value.garnetObject;
byte[] newKeyArray = newKeySlice.ToArray();
var expireSpan = new SpanByteAndMemory();
var ttlStatus = TTL(ref oldKey, StoreType.Object, ref expireSpan, ref context, ref objectContext, true);
if (ttlStatus == GarnetStatus.OK && !expireSpan.IsSpanByte)
{
using var expireMemoryHandle = expireSpan.Memory.Memory.Pin();
var expirePtrVal = (byte*)expireMemoryHandle.Pointer;
RespReadUtils.TryRead64Int(out var expireTimeMs, ref expirePtrVal, expirePtrVal + expireSpan.Length, out var _);
expireSpan.Memory.Dispose();
if (expireTimeMs > 0)
{
SET(newKeyArray, valObj, ref objectContext);
EXPIRE(newKeySlice, TimeSpan.FromMilliseconds(expireTimeMs), out _, StoreType.Object, ExpireOption.None, ref context, ref objectContext, true);
}
else if (expireTimeMs == -1) // Its possible to have expire as 0 or -2, in those cases we don't SET the new key
{
SET(newKeyArray, valObj, ref objectContext);
}
// Delete the old key
DELETE(oldKeyArray, StoreType.Object, ref context, ref objectContext);
returnStatus = GarnetStatus.OK;
}
}
}
finally
{
if (createTransaction)
txnManager.Commit(true);
}
}
return returnStatus;
}
/// <summary>
/// Returns if key is an existing one in the store.
/// </summary>
/// <typeparam name="TContext"></typeparam>
/// <typeparam name="TObjectContext"></typeparam>
/// <param name="key">The name of the key to use in the operation</param>
/// <param name="storeType">The store to operate on.</param>
/// <param name="context">Basic context for the main store.</param>
/// <param name="objectContext">Object context for the object store.</param>
/// <returns></returns>
public GarnetStatus EXISTS<TContext, TObjectContext>(ArgSlice key, StoreType storeType, ref TContext context, ref TObjectContext objectContext)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
where TObjectContext : ITsavoriteContext<byte[], IGarnetObject, ObjectInput, GarnetObjectStoreOutput, long, ObjectSessionFunctions, ObjectStoreFunctions, ObjectStoreAllocator>
{
GarnetStatus status = GarnetStatus.NOTFOUND;
if (storeType == StoreType.Main || storeType == StoreType.All)
{
var _key = key.SpanByte;
SpanByte input = default;
var _output = new SpanByteAndMemory { SpanByte = scratchBufferManager.ViewRemainingArgSlice().SpanByte };
status = GET(ref _key, ref input, ref _output, ref context);
if (status == GarnetStatus.OK)
{
if (!_output.IsSpanByte)
_output.Memory.Dispose();
return status;
}
}
if ((storeType == StoreType.Object || storeType == StoreType.All) && !objectStoreBasicContext.IsNull)
{
status = GET(key.ToArray(), out _, ref objectContext);
}
return status;
}
/// <summary>
/// Set a timeout on key
/// </summary>
/// <typeparam name="TContext"></typeparam>
/// <typeparam name="TObjectContext"></typeparam>
/// <param name="key">The key to set the timeout on.</param>
/// <param name="expiryMs">Milliseconds value for the timeout.</param>
/// <param name="timeoutSet">True when the timeout was properly set.</param>
/// <param name="storeType">The store to operate on.</param>
/// <param name="expireOption">>Flags to use for the operation.</param>
/// <param name="context">Basic context for the main store.</param>
/// <param name="objectStoreContext">Object context for the object store.</param>
/// <returns></returns>
public unsafe GarnetStatus EXPIRE<TContext, TObjectContext>(ArgSlice key, ArgSlice expiryMs, out bool timeoutSet, StoreType storeType, ExpireOption expireOption, ref TContext context, ref TObjectContext objectStoreContext)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
where TObjectContext : ITsavoriteContext<byte[], IGarnetObject, ObjectInput, GarnetObjectStoreOutput, long, ObjectSessionFunctions, ObjectStoreFunctions, ObjectStoreAllocator>
=> EXPIRE(key, TimeSpan.FromMilliseconds(NumUtils.BytesToLong(expiryMs.Length, expiryMs.ptr)), out timeoutSet, storeType, expireOption, ref context, ref objectStoreContext);
/// <summary>
/// Set a timeout on key.
/// </summary>
/// <typeparam name="TContext"></typeparam>
/// <typeparam name="TObjectContext"></typeparam>
/// <param name="key">The key to set the timeout on.</param>
/// <param name="expiry">The timespan value to set the expiration for.</param>
/// <param name="timeoutSet">True when the timeout was properly set.</param>
/// <param name="storeType">The store to operate on.</param>
/// <param name="expireOption">Flags to use for the operation.</param>
/// <param name="context">Basic context for the main store</param>
/// <param name="objectStoreContext">Object context for the object store</param>
/// <param name="milliseconds">When true the command executed is PEXPIRE, expire by default.</param>
/// <returns></returns>
public unsafe GarnetStatus EXPIRE<TContext, TObjectContext>(ArgSlice key, TimeSpan expiry, out bool timeoutSet, StoreType storeType, ExpireOption expireOption, ref TContext context, ref TObjectContext objectStoreContext, bool milliseconds = false)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
where TObjectContext : ITsavoriteContext<byte[], IGarnetObject, ObjectInput, GarnetObjectStoreOutput, long, ObjectSessionFunctions, ObjectStoreFunctions, ObjectStoreAllocator>
{
byte* pbCmdInput = stackalloc byte[sizeof(int) + sizeof(long) + RespInputHeader.Size + sizeof(byte)];
*(int*)pbCmdInput = sizeof(long) + RespInputHeader.Size;
((RespInputHeader*)(pbCmdInput + sizeof(int) + sizeof(long)))->cmd = milliseconds ? RespCommand.PEXPIRE : RespCommand.EXPIRE;
((RespInputHeader*)(pbCmdInput + sizeof(int) + sizeof(long)))->flags = 0;
*(pbCmdInput + sizeof(int) + sizeof(long) + RespInputHeader.Size) = (byte)expireOption;
ref var input = ref SpanByte.Reinterpret(pbCmdInput);
input.ExtraMetadata = DateTimeOffset.UtcNow.Ticks + expiry.Ticks;
var rmwOutput = stackalloc byte[ObjectOutputHeader.Size];
var output = new SpanByteAndMemory(SpanByte.FromPinnedPointer(rmwOutput, ObjectOutputHeader.Size));
timeoutSet = false;
bool found = false;
if (storeType == StoreType.Main || storeType == StoreType.All)
{
var _key = key.SpanByte;
var status = context.RMW(ref _key, ref input, ref output);
if (status.IsPending)
CompletePendingForSession(ref status, ref output, ref context);
if (status.Found) found = true;
}
if (!found && (storeType == StoreType.Object || storeType == StoreType.All) &&
!objectStoreBasicContext.IsNull)
{
var parseState = new SessionParseState();
ArgSlice[] parseStateBuffer = default;
var expireOptionLength = NumUtils.NumDigits((byte)expireOption);
var expireOptionPtr = stackalloc byte[expireOptionLength];
NumUtils.IntToBytes((byte)expireOption, expireOptionLength, ref expireOptionPtr);
expireOptionPtr -= expireOptionLength;
var expireOptionSlice = new ArgSlice(expireOptionPtr, expireOptionLength);
var extraMetadataLength = NumUtils.NumDigitsInLong(input.ExtraMetadata);
var extraMetadataPtr = stackalloc byte[extraMetadataLength];
NumUtils.LongToBytes(input.ExtraMetadata, extraMetadataLength, ref extraMetadataPtr);
extraMetadataPtr -= extraMetadataLength;
var extraMetadataSlice = new ArgSlice(extraMetadataPtr, extraMetadataLength);
parseState.InitializeWithArguments(ref parseStateBuffer, expireOptionSlice, extraMetadataSlice);
var objInput = new ObjectInput
{
header = new RespInputHeader
{
cmd = milliseconds ? RespCommand.PEXPIRE : RespCommand.EXPIRE,
type = GarnetObjectType.Expire,
},
parseState = parseState,
parseStateStartIdx = 0,
};
// Retry on object store
var objOutput = new GarnetObjectStoreOutput { spanByteAndMemory = output };
var keyBytes = key.ToArray();
var status = objectStoreContext.RMW(ref keyBytes, ref objInput, ref objOutput);
if (status.IsPending)
CompletePendingForObjectStoreSession(ref status, ref objOutput, ref objectStoreContext);
if (status.Found) found = true;
output = objOutput.spanByteAndMemory;
}
Debug.Assert(output.IsSpanByte);
if (found) timeoutSet = ((ObjectOutputHeader*)output.SpanByte.ToPointer())->result1 == 1;
return found ? GarnetStatus.OK : GarnetStatus.NOTFOUND;
}
public unsafe GarnetStatus PERSIST<TContext, TObjectContext>(ArgSlice key, StoreType storeType, ref TContext context, ref TObjectContext objectStoreContext)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
where TObjectContext : ITsavoriteContext<byte[], IGarnetObject, ObjectInput, GarnetObjectStoreOutput, long, ObjectSessionFunctions, ObjectStoreFunctions, ObjectStoreAllocator>
{
GarnetStatus status = GarnetStatus.NOTFOUND;
int inputSize = sizeof(int) + RespInputHeader.Size;
byte* pbCmdInput = stackalloc byte[inputSize];
byte* pcurr = pbCmdInput;
*(int*)pcurr = inputSize - sizeof(int);
pcurr += sizeof(int);
(*(RespInputHeader*)pcurr).cmd = RespCommand.PERSIST;
(*(RespInputHeader*)pcurr).flags = 0;
byte* pbOutput = stackalloc byte[8];
var o = new SpanByteAndMemory(pbOutput, 8);
if (storeType == StoreType.Main || storeType == StoreType.All)
{
var _key = key.SpanByte;
var _status = context.RMW(ref _key, ref Unsafe.AsRef<SpanByte>(pbCmdInput), ref o);
if (_status.IsPending)
CompletePendingForSession(ref _status, ref o, ref context);
Debug.Assert(o.IsSpanByte);
if (o.SpanByte.AsReadOnlySpan()[0] == 1)
status = GarnetStatus.OK;
}
if (status == GarnetStatus.NOTFOUND && (storeType == StoreType.Object || storeType == StoreType.All) && !objectStoreBasicContext.IsNull)
{
// Retry on object store
var objInput = new ObjectInput
{
header = new RespInputHeader
{
cmd = RespCommand.PERSIST,
type = GarnetObjectType.Persist,
},
};
var objO = new GarnetObjectStoreOutput { spanByteAndMemory = o };
var _key = key.ToArray();
var _status = objectStoreContext.RMW(ref _key, ref objInput, ref objO);
if (_status.IsPending)
CompletePendingForObjectStoreSession(ref _status, ref objO, ref objectStoreContext);
Debug.Assert(o.IsSpanByte);
if (o.SpanByte.AsReadOnlySpan().Slice(0, CmdStrings.RESP_RETURN_VAL_1.Length)
.SequenceEqual(CmdStrings.RESP_RETURN_VAL_1))
status = GarnetStatus.OK;
}
return status;
}
/// <summary>
/// For existing keys - overwrites part of the value at a specified offset (in-place if possible)
/// For non-existing keys - creates a new string with the value at a specified offset (padded with '\0's)
/// </summary>
/// <typeparam name="TContext"></typeparam>
/// <param name="key">The key for which to set the range</param>
/// <param name="value">The value to place at an offset</param>
/// <param name="offset">The offset at which to place the value</param>
/// <param name="output">The length of the updated string</param>
/// <param name="context">Basic context for the main store</param>
/// <returns></returns>
public unsafe GarnetStatus SETRANGE<TContext>(ArgSlice key, ArgSlice value, int offset, ref ArgSlice output, ref TContext context)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
{
var sbKey = key.SpanByte;
SpanByteAndMemory sbmOut = new(output.SpanByte);
// Total size + Offset size + New value size + Address of new value
int inputSize = sizeof(int) + sizeof(int) + sizeof(int) + sizeof(long);
byte* pbCmdInput = stackalloc byte[inputSize];
byte* pcurr = pbCmdInput;
*(int*)pcurr = inputSize - sizeof(int);
pcurr += sizeof(int);
(*(RespInputHeader*)(pcurr)).cmd = RespCommand.SETRANGE;
(*(RespInputHeader*)(pcurr)).flags = 0;
pcurr += RespInputHeader.Size;
*(int*)(pcurr) = offset;
pcurr += sizeof(int);
*(int*)pcurr = value.Length;
pcurr += sizeof(int);
*(long*)pcurr = (long)(value.ptr);
var status = context.RMW(ref sbKey, ref Unsafe.AsRef<SpanByte>(pbCmdInput), ref sbmOut);
if (status.IsPending)
CompletePendingForSession(ref status, ref sbmOut, ref context);
Debug.Assert(sbmOut.IsSpanByte);
output.length = sbmOut.Length;
return GarnetStatus.OK;
}
public GarnetStatus Increment<TContext>(ArgSlice key, ArgSlice input, ref ArgSlice output, ref TContext context)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
{
var _key = key.SpanByte;
var _input = input.SpanByte;
SpanByteAndMemory _output = new(output.SpanByte);
var status = context.RMW(ref _key, ref _input, ref _output);
if (status.IsPending)
CompletePendingForSession(ref status, ref _output, ref context);
Debug.Assert(_output.IsSpanByte);
output.length = _output.Length;
return GarnetStatus.OK;
}
public unsafe GarnetStatus Increment<TContext>(ArgSlice key, out long output, long increment, ref TContext context)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
{
var cmd = RespCommand.INCRBY;
if (increment < 0)
{
cmd = RespCommand.DECRBY;
increment = -increment;
}
var incrementNumDigits = NumUtils.NumDigitsInLong(increment);
var inputByteSize = RespInputHeader.Size + incrementNumDigits;
var input = stackalloc byte[inputByteSize];
((RespInputHeader*)input)->cmd = cmd;
((RespInputHeader*)input)->flags = 0;
var longOutput = input + RespInputHeader.Size;
NumUtils.LongToBytes(increment, incrementNumDigits, ref longOutput);
const int outputBufferLength = NumUtils.MaximumFormatInt64Length + 1;
byte* outputBuffer = stackalloc byte[outputBufferLength];
var _key = key.SpanByte;
var _input = SpanByte.FromPinnedPointer(input, inputByteSize);
var _output = new SpanByteAndMemory(outputBuffer, outputBufferLength);
var status = context.RMW(ref _key, ref _input, ref _output);
if (status.IsPending)
CompletePendingForSession(ref status, ref _output, ref context);
Debug.Assert(_output.IsSpanByte);
Debug.Assert(_output.Length == outputBufferLength);
output = NumUtils.BytesToLong(_output.Length, outputBuffer);
return GarnetStatus.OK;
}
public void WATCH(ArgSlice key, StoreType type)
{
txnManager.Watch(key, type);
txnManager.VerifyKeyOwnership(key, LockType.Shared);
}
public unsafe void WATCH(byte[] key, StoreType type)
{
fixed (byte* ptr = key)
{
WATCH(new ArgSlice(ptr, key.Length), type);
}
}
public unsafe GarnetStatus SCAN<TContext>(long cursor, ArgSlice match, long count, ref TContext context)
{
return GarnetStatus.OK;
}
public GarnetStatus GetKeyType<TContext, TObjectContext>(ArgSlice key, out string keyType, ref TContext context, ref TObjectContext objectContext)
where TContext : ITsavoriteContext<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
where TObjectContext : ITsavoriteContext<byte[], IGarnetObject, ObjectInput, GarnetObjectStoreOutput, long, ObjectSessionFunctions, ObjectStoreFunctions, ObjectStoreAllocator>
{
keyType = "string";
// Check if key exists in Main store
var status = EXISTS(key, StoreType.Main, ref context, ref objectContext);
// If key was not found in the main store then it is an object
if (status != GarnetStatus.OK && !objectStoreBasicContext.IsNull)
{
status = GET(key.ToArray(), out GarnetObjectStoreOutput output, ref objectContext);
if (status == GarnetStatus.OK)
{
if ((output.garnetObject as SortedSetObject) != null)
{
keyType = "zset";
}
else if ((output.garnetObject as ListObject) != null)
{
keyType = "list";
}