-
Notifications
You must be signed in to change notification settings - Fork 820
/
TimeSeriesStorage.cs
2761 lines (2261 loc) · 120 KB
/
TimeSeriesStorage.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
using System;
using System.Buffers;
using System.Buffers.Text;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using Raven.Client;
using Raven.Client.Documents.Changes;
using Raven.Client.Documents.Operations.TimeSeries;
using Raven.Server.Documents.Handlers;
using Raven.Server.Documents.Replication.ReplicationItems;
using Raven.Server.NotificationCenter.Notifications;
using Raven.Server.ServerWide.Context;
using Raven.Server.Smuggler.Documents;
using Raven.Server.Utils;
using Sparrow;
using Sparrow.Binary;
using Sparrow.Extensions;
using Sparrow.Json;
using Sparrow.Json.Parsing;
using Sparrow.Logging;
using Sparrow.Server;
using Sparrow.Server.Utils;
using Voron;
using Voron.Data.Tables;
using Voron.Impl;
namespace Raven.Server.Documents.TimeSeries
{
public unsafe class TimeSeriesStorage
{
public const int MaxSegmentSize = 2048;
public static readonly Slice AllTimeSeriesEtagSlice;
private static readonly Slice CollectionTimeSeriesEtagsSlice;
private static readonly Slice TimeSeriesKeysSlice;
private static readonly Slice PendingDeletionSegments;
private static readonly Slice DeletedRangesKey;
private static readonly Slice AllDeletedRangesEtagSlice;
private static readonly Slice CollectionDeletedRangesEtagsSlice;
internal static readonly TableSchema TimeSeriesSchema = new TableSchema
{
TableType = (byte)TableType.TimeSeries
};
private static readonly TableSchema DeleteRangesSchema = new TableSchema();
private readonly DocumentDatabase _documentDatabase;
private readonly DocumentsStorage _documentsStorage;
private HashSet<string> _tableCreated = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
public readonly TimeSeriesStats Stats;
public readonly TimeSeriesRollups Rollups;
static TimeSeriesStorage()
{
using (StorageEnvironment.GetStaticContext(out ByteStringContext ctx))
{
Slice.From(ctx, "AllTimeSeriesEtag", ByteStringType.Immutable, out AllTimeSeriesEtagSlice);
Slice.From(ctx, "CollectionTimeSeriesEtags", ByteStringType.Immutable, out CollectionTimeSeriesEtagsSlice);
Slice.From(ctx, "TimeSeriesKeys", ByteStringType.Immutable, out TimeSeriesKeysSlice);
Slice.From(ctx, "PendingDeletionSegments", ByteStringType.Immutable, out PendingDeletionSegments);
Slice.From(ctx, "DeletedRangesKey", ByteStringType.Immutable, out DeletedRangesKey);
Slice.From(ctx, "AllDeletedRangesEtag", ByteStringType.Immutable, out AllDeletedRangesEtagSlice);
Slice.From(ctx, "CollectionDeletedRangesEtags", ByteStringType.Immutable, out CollectionDeletedRangesEtagsSlice);
}
TimeSeriesSchema.DefineKey(new TableSchema.SchemaIndexDef
{
StartIndex = (int)TimeSeriesTable.TimeSeriesKey,
Count = 1,
Name = TimeSeriesKeysSlice,
IsGlobal = true
});
TimeSeriesSchema.DefineFixedSizeIndex(new TableSchema.FixedSizeSchemaIndexDef
{
StartIndex = (int)TimeSeriesTable.Etag,
Name = AllTimeSeriesEtagSlice,
IsGlobal = true
});
TimeSeriesSchema.DefineFixedSizeIndex(new TableSchema.FixedSizeSchemaIndexDef
{
StartIndex = (int)TimeSeriesTable.Etag,
Name = CollectionTimeSeriesEtagsSlice
});
DeleteRangesSchema.DefineKey(new TableSchema.SchemaIndexDef
{
StartIndex = (int)DeletedRangeTable.RangeKey,
Count = 1,
Name = DeletedRangesKey,
IsGlobal = true
});
DeleteRangesSchema.DefineFixedSizeIndex(new TableSchema.FixedSizeSchemaIndexDef
{
StartIndex = (int)DeletedRangeTable.Etag,
Name = AllDeletedRangesEtagSlice,
IsGlobal = true
});
DeleteRangesSchema.DefineFixedSizeIndex(new TableSchema.FixedSizeSchemaIndexDef
{
StartIndex = (int)DeletedRangeTable.Etag,
Name = CollectionDeletedRangesEtagsSlice
});
}
private readonly Logger _logger;
public TimeSeriesStorage(DocumentDatabase documentDatabase, Transaction tx)
{
_documentDatabase = documentDatabase;
_documentsStorage = documentDatabase.DocumentsStorage;
tx.CreateTree(TimeSeriesKeysSlice);
tx.CreateTree(DeletedRangesKey);
Stats = new TimeSeriesStats(this, tx);
Rollups = new TimeSeriesRollups(_documentDatabase);
_logger = LoggingSource.Instance.GetLogger<TimeSeriesStorage>(documentDatabase.Name);
}
public long PurgeSegmentsAndDeletedRanges(DocumentsOperationContext context, string collection, long upto, long numberOfEntriesToDelete)
{
var collectionName = _documentsStorage.GetCollection(collection, throwIfDoesNotExist: false);
if (collectionName == null)
return 0;
var deletedSegments = PurgeSegments(upto, context, collectionName, numberOfEntriesToDelete);
var deletedRanges = PurgeDeletedRanged(upto, context, collectionName, numberOfEntriesToDelete - deletedSegments);
return deletedRanges + deletedSegments;
}
private long PurgeDeletedRanged(in long upto, DocumentsOperationContext context, CollectionName collectionName, long numberOfEntriesToDelete)
{
var tableName = collectionName.GetTableName(CollectionTableType.TimeSeriesDeletedRanges);
var table = context.Transaction.InnerTransaction.OpenTable(DeleteRangesSchema, tableName);
if (table == null || table.NumberOfEntries == 0 || numberOfEntriesToDelete <= 0)
return 0;
return table.DeleteBackwardFrom(DeleteRangesSchema.FixedSizeIndexes[CollectionDeletedRangesEtagsSlice], upto, numberOfEntriesToDelete);
}
private long PurgeSegments(long upto, DocumentsOperationContext context, CollectionName collectionName, long numberOfEntriesToDelete)
{
var tableName = collectionName.GetTableName(CollectionTableType.TimeSeries);
var table = context.Transaction.InnerTransaction.OpenTable(TimeSeriesSchema, tableName);
if (table == null || table.NumberOfEntries == 0 || numberOfEntriesToDelete <= 0)
return 0;
var pendingDeletion = context.Transaction.InnerTransaction.CreateTree(PendingDeletionSegments);
var outdated = new List<Slice>();
var uniqueTimeSeries = new HashSet<Slice>(SliceComparer.Instance);
var hasMore = true;
var deletedCount = 0;
while (hasMore)
{
using (var it = pendingDeletion.MultiRead(collectionName.Name))
{
if (it.Seek(Slices.BeforeAllKeys) == false)
return deletedCount;
do
{
var etag = it.CurrentKey.CreateReader().ReadBigEndianInt64();
if (etag > upto)
{
hasMore = false;
break;
}
if (table.FindByIndex(TimeSeriesSchema.FixedSizeIndexes[CollectionTimeSeriesEtagsSlice], etag, out var reader))
{
var keyPtr = reader.Read((int)TimeSeriesTable.TimeSeriesKey, out int keySize);
using (Slice.From(context.Allocator, keyPtr, keySize, ByteStringType.Immutable, out var key))
{
var size = key.Size - sizeof(long);
using (Slice.External(context.Allocator, key, size, out var tsKey))
{
if (uniqueTimeSeries.Contains(tsKey) == false)
uniqueTimeSeries.Add(tsKey.Clone(context.Allocator));
}
}
}
if (table.DeleteByIndex(TimeSeriesSchema.FixedSizeIndexes[CollectionTimeSeriesEtagsSlice], etag))
deletedCount++;
outdated.Add(it.CurrentKey.Clone(context.Allocator));
hasMore = it.MoveNext();
} while (hasMore && outdated.Count < numberOfEntriesToDelete);
}
foreach (var etagSlice in outdated)
{
pendingDeletion.MultiDelete(collectionName.Name, etagSlice);
}
outdated.Clear();
foreach (var tsKey in uniqueTimeSeries)
{
if (table.SeekOnePrimaryKeyWithPrefix(tsKey, Slices.BeforeAllKeys, out _) == false)
{
using (Slice.External(context.Allocator, tsKey, tsKey.Size - 1, out var statsKey))
{
if (Stats.GetStats(context, statsKey).Count == 0)
Stats.DeleteStats(context, collectionName, statsKey);
}
}
}
uniqueTimeSeries.Clear();
}
return deletedCount;
}
public long GetNumberOfTimeSeriesDeletedRanges(DocumentsOperationContext context)
{
var fstIndex = DeleteRangesSchema.FixedSizeIndexes[AllDeletedRangesEtagSlice];
var fst = context.Transaction.InnerTransaction.FixedTreeFor(fstIndex.Name, sizeof(long));
return fst.NumberOfEntries;
}
public long GetNumberOfTimeSeriesPendingDeletionSegments(DocumentsOperationContext context)
{
var timeSeriesPurgeSegments = 0L;
foreach (DocumentsStorage.CollectionStats collection in _documentsStorage.GetCollections(context))
{
var pendingDeletion = context.Transaction.InnerTransaction.ReadTree(PendingDeletionSegments);
if (pendingDeletion == null)
continue;
using (Slice.From(context.Allocator, collection.Name, ByteStringType.Immutable, out var keySlice))
{
timeSeriesPurgeSegments += pendingDeletion.MultiCount(keySlice);
}
}
return timeSeriesPurgeSegments;
}
public class DeletionRangeRequest
{
public string DocumentId;
public string Collection;
public string Name;
public DateTime From;
public DateTime To;
public override string ToString()
{
return $"Deletion request for time-series {Name} in document {DocumentId} from {From} to {To}";
}
}
private string InsertDeletedRange(DocumentsOperationContext context, DeletionRangeRequest deletionRangeRequest, string remoteChangeVector = null)
{
var collection = deletionRangeRequest.Collection;
var documentId = deletionRangeRequest.DocumentId;
var from = deletionRangeRequest.From;
var to = deletionRangeRequest.To;
var name = deletionRangeRequest.Name;
var collectionName = _documentsStorage.ExtractCollectionName(context, collection);
var table = GetOrCreateDeleteRangesTable(context.Transaction.InnerTransaction, collectionName);
from = EnsureMillisecondsPrecision(from);
to = EnsureMillisecondsPrecision(to);
string changeVector;
long etag;
if (remoteChangeVector != null)
{
changeVector = remoteChangeVector;
etag = _documentsStorage.GenerateNextEtag();
}
else
{
(changeVector, etag) = GenerateChangeVector(context);
}
using (var sliceHolder = new TimeSeriesSliceHolder(context, documentId, name, collectionName.Name).WithEtag(etag))
using (table.Allocate(out var tvb))
using (Slice.From(context.Allocator, changeVector, out var cv))
{
tvb.Add(sliceHolder.TimeSeriesKeySlice);
tvb.Add(Bits.SwapBytes(etag));
tvb.Add(cv);
tvb.Add(sliceHolder.CollectionSlice);
tvb.Add(context.GetTransactionMarker());
tvb.Add(from.Ticks);
tvb.Add(to.Ticks);
table.Set(tvb);
}
return changeVector;
}
public string DeleteTimestampRange(DocumentsOperationContext context, DeletionRangeRequest deletionRangeRequest, string remoteChangeVector = null, bool updateMetadata = true)
{
deletionRangeRequest.From = EnsureMillisecondsPrecision(deletionRangeRequest.From);
deletionRangeRequest.To = EnsureMillisecondsPrecision(deletionRangeRequest.To);
InsertDeletedRange(context, deletionRangeRequest, remoteChangeVector);
var collection = deletionRangeRequest.Collection;
var documentId = deletionRangeRequest.DocumentId;
var from = deletionRangeRequest.From;
var to = deletionRangeRequest.To;
var name = deletionRangeRequest.Name;
var collectionName = _documentsStorage.ExtractCollectionName(context, collection);
var table = GetOrCreateTimeSeriesTable(context.Transaction.InnerTransaction, collectionName);
using (var slicer = new TimeSeriesSliceHolder(context, documentId, name))
{
var stats = Stats.GetStats(context, slicer);
if (stats == default || stats.Count == 0)
return null; // nothing to delete here
if (stats.End < from)
return null; // nothing to delete here
slicer.SetBaselineToKey(stats.Start > from ? stats.Start : from);
// first try to find the previous segment containing from value
if (table.SeekOneBackwardByPrimaryKeyPrefix(slicer.TimeSeriesPrefixSlice, slicer.TimeSeriesKeySlice, out var segmentValueReader) == false)
{
// or the first segment _after_ the from value
if (table.SeekOnePrimaryKeyWithPrefix(slicer.TimeSeriesPrefixSlice, slicer.TimeSeriesKeySlice, out segmentValueReader) == false)
return null;
}
var baseline = GetBaseline(segmentValueReader);
string changeVector = null;
var deleted = 0;
while (true)
{
if (TryDeleteRange(out var nextSegment) == false)
break;
if (nextSegment == null)
break;
baseline = nextSegment.Value;
}
if (deleted == 0)
return null; // nothing happened, the deletion request was out of date
context.Transaction.AddAfterCommitNotification(new TimeSeriesChange
{
ChangeVector = changeVector,
DocumentId = documentId,
Name = name,
Type = TimeSeriesChangeTypes.Delete,
From = from,
To = to,
CollectionName = collectionName.Name
});
return changeVector;
bool TryDeleteRange(out DateTime? next)
{
next = default;
if (baseline > to)
return false; // we got to the end
using (var holder = new TimeSeriesSegmentHolder(this, context, documentId, name, collectionName, baseline))
{
if (holder.LoadCurrentSegment() == false)
return false;
// we need to get the next segment before the actual remove, since it might lead to a split
next = BaselineOfNextSegment(slicer.TimeSeriesKeySlice, slicer.TimeSeriesPrefixSlice, table, baseline);
var readOnlySegment = holder.ReadOnlySegment;
var end = readOnlySegment.GetLastTimestamp(baseline);
if (baseline > end)
return false;
if (remoteChangeVector != null)
{
if (ChangeVectorUtils.GetConflictStatus(remoteChangeVector, holder.ReadOnlyChangeVector) == ConflictStatus.AlreadyMerged)
{
// the deleted range is older than this segment, so we don't touch this segment
return false;
}
}
if (readOnlySegment.NumberOfLiveEntries == 0)
return true; // nothing to delete here
var newSegment = new TimeSeriesValuesSegment(holder.SliceHolder.SegmentBuffer.Ptr, MaxSegmentSize);
var canDeleteEntireSegment = baseline >= from && end <= to; // entire segment can be deleted
var numberOfValues = canDeleteEntireSegment ? 0 : readOnlySegment.NumberOfValues;
newSegment.Initialize(numberOfValues);
// TODO: RavenDB-14851 manipulating segments as a whole must be done carefully in a distributed env
// if (baseline >= from && end <= to) // entire segment can be deleted
// {
// // update properly the start/end of the time-series
// holder.AddNewValue(baseline, new double[readOnlySegment.NumberOfValues], Slices.Empty.AsSpan(), ref newSegment, TimeSeriesValuesSegment.Dead);
// holder.AddNewValue(readOnlySegment.GetLastTimestamp(baseline), new double[readOnlySegment.NumberOfValues], Slices.Empty.AsSpan(), ref newSegment, TimeSeriesValuesSegment.Dead);
// holder.AppendDeadSegment(newSegment);
//
// removeOccurred = true;
// return true;
// }
var segmentChanged = false;
using (var enumerator = readOnlySegment.GetEnumerator(context.Allocator))
{
var state = new TimestampState[readOnlySegment.NumberOfValues];
Span<double> values = stackalloc double[readOnlySegment.NumberOfValues];
Span<double> emptyValues = stackalloc double[numberOfValues];
var tag = new TimeSeriesValuesSegment.TagPointer();
while (enumerator.MoveNext(out int ts, values, state, ref tag, out var status))
{
var current = baseline.AddMilliseconds(ts);
if (current > to && segmentChanged == false)
return false; // we can exit here earlier
if (current >= from && current <= to)
{
holder.AddNewValue(current, emptyValues, Slices.Empty.AsSpan(), ref newSegment, TimeSeriesValuesSegment.Dead);
segmentChanged = true;
deleted++;
continue;
}
holder.AddExistingValue(current, values, tag.AsSpan(), ref newSegment, status);
}
}
if (segmentChanged)
{
var count = holder.AppendExistingSegment(newSegment);
if (count == 0 && updateMetadata)
{
// this ts was completely deleted
RemoveTimeSeriesNameFromMetadata(context, slicer.DocId, slicer.Name);
}
changeVector = holder.ChangeVector;
}
return end < to;
}
}
}
}
private DateTime? BaselineOfNextSegment(Slice key, Slice prefix, Table table, DateTime baseline)
{
var offset = key.Size - sizeof(long);
*(long*)(key.Content.Ptr + offset) = Bits.SwapBytes(baseline.Ticks / 10_000);
foreach (var (_, tvh) in table.SeekByPrimaryKeyPrefix(prefix, key, 0))
{
return GetBaseline(tvh.Reader);
}
return null;
}
private static DateTime GetBaseline(TableValueReader reader)
{
var key = reader.Read((int)TimeSeriesTable.TimeSeriesKey, out int keySize);
var baselineMilliseconds = Bits.SwapBytes(
*(long*)(key + keySize - sizeof(long))
);
var ticks = baselineMilliseconds * 10_000;
var baseline = new DateTime(ticks);
return baseline;
}
public static void RemoveTimeSeriesNameFromMetadata(DocumentsOperationContext ctx, string docId, string tsName)
{
var storage = ctx.DocumentDatabase.DocumentsStorage;
var doc = storage.Get(ctx, docId);
if (doc == null)
return;
var tss = storage.TimeSeriesStorage;
if (tss.Stats.GetStats(ctx, docId, tsName).Count > 0)
return;
var data = doc.Data;
var flags = doc.Flags.Strip(DocumentFlags.FromClusterTransaction | DocumentFlags.Resolved);
BlittableJsonReaderArray tsNames = null;
if (doc.TryGetMetadata(out var metadata))
{
metadata.TryGet(Constants.Documents.Metadata.TimeSeries, out tsNames);
}
if (metadata == null || tsNames == null)
return;
var tsNamesList = new List<string>(tsNames.Length + 1);
for (var i = 0; i < tsNames.Length; i++)
{
var val = tsNames.GetStringByIndex(i);
if (val == null)
continue;
tsNamesList.Add(val);
}
var location = tsNames.BinarySearch(tsName, StringComparison.OrdinalIgnoreCase);
if (location < 0)
return;
tsNamesList.RemoveAt(location);
data.Modifications = new DynamicJsonValue(data);
metadata.Modifications = new DynamicJsonValue(metadata);
if (tsNamesList.Count == 0)
{
metadata.Modifications.Remove(Constants.Documents.Metadata.TimeSeries);
flags = flags.Strip(DocumentFlags.HasTimeSeries);
}
else
{
metadata.Modifications[Constants.Documents.Metadata.TimeSeries] = tsNamesList;
}
data.Modifications[Constants.Documents.Metadata.Key] = metadata;
using (data)
{
var newDocumentData = ctx.ReadObject(doc.Data, doc.Id, BlittableJsonDocumentBuilder.UsageMode.ToDisk);
storage.Put(ctx, doc.Id, null, newDocumentData, flags: flags,
nonPersistentFlags: NonPersistentDocumentFlags.ByTimeSeriesUpdate);
}
}
private static TimeSeriesValuesSegment TableValueToSegment(ref TableValueReader segmentValueReader, out DateTime baseline)
{
var segmentPtr = segmentValueReader.Read((int)TimeSeriesTable.Segment, out int segmentSize);
var segment = new TimeSeriesValuesSegment(segmentPtr, segmentSize);
Debug.Assert(segmentSize == segment.NumberOfBytes);
var key = segmentValueReader.Read((int)TimeSeriesTable.TimeSeriesKey, out int keySize);
var baselineMilliseconds = Bits.SwapBytes(
*(long*)(key + keySize - sizeof(long))
);
var ticks = baselineMilliseconds * 10_000;
baseline = new DateTime(ticks);
return segment;
}
public static DateTime EnsureMillisecondsPrecision(DateTime dt)
{
if (dt == DateTime.MinValue || dt == DateTime.MaxValue)
return dt;
var remainder = dt.Ticks % 10_000;
if (remainder != 0)
dt = dt.AddTicks(-remainder);
return dt;
}
public void DeleteAllTimeSeriesForDocument(DocumentsOperationContext context, string documentId, CollectionName collection)
{
// this will be called as part of document's delete
var table = GetOrCreateTimeSeriesTable(context.Transaction.InnerTransaction, collection);
using (DocumentIdWorker.GetSliceFromId(context, documentId, out Slice documentKeyPrefix, SpecialChars.RecordSeparator))
{
table.DeleteByPrimaryKeyPrefix(documentKeyPrefix);
Stats.DeleteByPrimaryKeyPrefix(context, collection, documentKeyPrefix);
Rollups.DeleteByPrimaryKeyPrefix(context, documentKeyPrefix);
}
}
public void DeleteTimeSeriesForDocument(DocumentsOperationContext context, string documentId, CollectionName collection, string name)
{
var table = GetOrCreateTimeSeriesTable(context.Transaction.InnerTransaction, collection);
using (var slicer = new TimeSeriesSliceHolder(context, documentId, name, collection.Name))
{
table.DeleteByPrimaryKeyPrefix(slicer.TimeSeriesPrefixSlice);
Stats.DeleteStats(context, collection, slicer.StatsKey);
Rollups.DeleteByPrimaryKeyPrefix(context, slicer.StatsKey);
RemoveTimeSeriesNameFromMetadata(context, slicer.DocId, slicer.Name);
}
}
public TimeSeriesReader GetReader(DocumentsOperationContext context, string documentId, string name, DateTime from, DateTime to, TimeSpan? offset = null)
{
return new TimeSeriesReader(context, documentId, name, from, to, offset);
}
public bool TryAppendEntireSegment(DocumentsOperationContext context, TimeSeriesReplicationItem item, string docId, LazyStringValue name, DateTime baseline)
{
var collectionName = _documentsStorage.ExtractCollectionName(context, item.Collection);
return TryAppendEntireSegment(context, item.Key, docId, name, collectionName, item.ChangeVector, item.Segment, baseline);
}
private bool TryAppendEntireSegment(
DocumentsOperationContext context,
Slice key,
string documentId,
string name,
CollectionName collectionName,
string changeVector,
TimeSeriesValuesSegment segment,
DateTime baseline)
{
var table = GetOrCreateTimeSeriesTable(context.Transaction.InnerTransaction, collectionName);
if (table.ReadByKey(key, out var tvr))
{
var existingChangeVector = DocumentsStorage.TableValueToChangeVector(context, (int)TimeSeriesTable.ChangeVector, ref tvr);
var status = ChangeVectorUtils.GetConflictStatus(changeVector, existingChangeVector);
if (status == ConflictStatus.AlreadyMerged)
return true; // nothing to do, we already have this
if (status == ConflictStatus.Update)
{
// TODO: RavenDB-14851 currently this is not working as expected, and cause values to disappear
// we can put the segment directly only if the incoming segment doesn't overlap with any existing one
// using (Slice.From(context.Allocator, dbId.Content.Ptr, dbId.Size - sizeof(long), ByteStringType.Immutable, out var prefix))
// {
// if (IsOverlapWithHigherSegment(prefix) == false)
// {
// var segmentReadOnlyBuffer = tvr.Read((int)TimeSeriesTable.Segment, out int size);
// var readOnlySegment = new TimeSeriesValuesSegment(segmentReadOnlyBuffer, size);
// Stats.UpdateCountOfExistingStats(context, documentId, name, collectionName, -readOnlySegment.NumberOfLiveEntries);
//
// AppendEntireSegment();
//
// return true;
// }
// }
}
return false;
}
return TryPutSegmentDirectly(context, key, documentId, name, collectionName, changeVector, segment, baseline);
}
public bool TryAppendEntireSegmentFromSmuggler(DocumentsOperationContext context, Slice key, CollectionName collectionName, TimeSeriesItem item)
{
// we will generate new change vector, so we pass null here
return TryPutSegmentDirectly(context, key, item.DocId, context.GetLazyStringForFieldWithCaching(item.Name), collectionName, null, item.Segment, item.Baseline);
}
private bool TryPutSegmentDirectly(
DocumentsOperationContext context,
Slice key,
string documentId,
string name,
CollectionName collectionName,
string changeVector,
TimeSeriesValuesSegment segment,
DateTime baseline)
{
if (IsOverlapping(context, key, collectionName, segment, baseline))
return false;
// if this segment isn't overlap with any other we can put it directly
ValidateSegment(segment);
var table = GetOrCreateTimeSeriesTable(context.Transaction.InnerTransaction, collectionName);
using (var holder = new TimeSeriesSegmentHolder(this, context, documentId, name, collectionName, fromReplicationChangeVector: changeVector, timeStamp: baseline))
{
var slicer = holder.SliceHolder;
Stats.UpdateStats(context, slicer, collectionName, segment, baseline, segment.NumberOfLiveEntries);
var newEtag = _documentsStorage.GenerateNextEtag();
changeVector ??= _documentsStorage.GetNewChangeVector(context, newEtag);
_documentDatabase.TimeSeriesPolicyRunner?.MarkSegmentForPolicy(context, slicer, baseline, changeVector, segment.NumberOfLiveEntries);
if (segment.NumberOfLiveEntries == 0)
{
MarkSegmentAsPendingDeletion(context, collectionName.Name, newEtag);
}
using (Slice.From(context.Allocator, changeVector, out Slice cv))
using (table.Allocate(out TableValueBuilder tvb))
{
tvb.Add(key);
tvb.Add(Bits.SwapBytes(newEtag));
tvb.Add(cv);
tvb.Add(segment.Ptr, segment.NumberOfBytes);
tvb.Add(slicer.CollectionSlice);
tvb.Add(context.GetTransactionMarker());
table.Set(tvb);
}
context.Transaction.AddAfterCommitNotification(new TimeSeriesChange
{
CollectionName = collectionName.Name,
ChangeVector = changeVector,
DocumentId = documentId,
Name = name,
Type = TimeSeriesChangeTypes.Put,
From = DateTime.MinValue,
To = DateTime.MaxValue
});
}
EnsureStatsAndDataIntegrity(context, documentId, name, segment, collectionName, baseline);
return true;
}
public bool EnsureNoOverlap(
DocumentsOperationContext context,
Slice key,
CollectionName collectionName,
TimeSeriesValuesSegment segment,
DateTime baseline)
{
var table = GetOrCreateTimeSeriesTable(context.Transaction.InnerTransaction, collectionName);
using (Slice.From(context.Allocator, key.Content.Ptr, key.Size - sizeof(long), ByteStringType.Immutable, out var prefix))
{
return (IsOverlapWithHigherSegment(prefix) || IsOverlapWithLowerSegment(prefix)) == false;
}
bool IsOverlapWithHigherSegment(Slice prefix)
{
var lastTimestamp = segment.GetLastTimestamp(baseline);
var nextSegmentBaseline = BaselineOfNextSegment(key, prefix, table, baseline);
return lastTimestamp >= nextSegmentBaseline;
}
bool IsOverlapWithLowerSegment(Slice prefix)
{
TableValueReader tvr;
using (Slice.From(context.Allocator, key.Content.Ptr, key.Size, ByteStringType.Immutable, out var lastKey))
{
*(long*)(lastKey.Content.Ptr + lastKey.Size - sizeof(long)) = Bits.SwapBytes(baseline.Ticks / 10_000);
if (table.SeekOneBackwardByPrimaryKeyPrefix(prefix, lastKey, out tvr, excludeValueFromSeek: true) == false)
{
return false;
}
}
var prevSegment = TableValueToSegment(ref tvr, out var prevBaseline);
var last = prevSegment.GetLastTimestamp(prevBaseline);
return last >= baseline;
}
}
public bool IsOverlapping(
DocumentsOperationContext context,
Slice key,
CollectionName collectionName,
TimeSeriesValuesSegment segment,
DateTime baseline)
{
var table = GetOrCreateTimeSeriesTable(context.Transaction.InnerTransaction, collectionName);
using (Slice.From(context.Allocator, key.Content.Ptr, key.Size - sizeof(long), ByteStringType.Immutable, out var prefix))
{
return IsOverlapWithHigherSegment(prefix) || IsOverlapWithLowerSegment(prefix);
}
bool IsOverlapWithHigherSegment(Slice prefix)
{
var lastTimestamp = segment.GetLastTimestamp(baseline);
var nextSegmentBaseline = BaselineOfNextSegment(key, prefix, table, baseline);
return lastTimestamp >= nextSegmentBaseline;
}
bool IsOverlapWithLowerSegment(Slice prefix)
{
var myLastTimestamp = segment.GetLastTimestamp(baseline);
TableValueReader tvr;
using (Slice.From(context.Allocator, key.Content.Ptr, key.Size, ByteStringType.Immutable, out var lastKey))
{
*(long*)(lastKey.Content.Ptr + lastKey.Size - sizeof(long)) = Bits.SwapBytes(myLastTimestamp.Ticks / 10_000);
if (table.SeekOneBackwardByPrimaryKeyPrefix(prefix, lastKey, out tvr) == false)
{
return false;
}
}
var prevSegment = TableValueToSegment(ref tvr, out var prevBaseline);
var last = prevSegment.GetLastTimestamp(prevBaseline);
return last >= baseline;
}
}
public class SegmentSummary
{
public string DocumentId;
public string Name;
public DateTime StartTime;
public int NumberOfEntries;
public int NumberOfLiveEntries;
public string ChangeVector;
public DynamicJsonValue ToJson()
{
var json = new DynamicJsonValue
{
[nameof(DocumentId)] = DocumentId,
[nameof(Name)] = Name,
[nameof(StartTime)] = StartTime,
[nameof(NumberOfEntries)] = NumberOfEntries,
[nameof(NumberOfLiveEntries)] = NumberOfLiveEntries,
[nameof(ChangeVector)] = ChangeVector,
};
return json;
}
}
public class TimeSeriesSegmentHolder : IDisposable
{
private readonly TimeSeriesStorage _tss;
private readonly DocumentsOperationContext _context;
public readonly TimeSeriesSliceHolder SliceHolder;
public readonly bool FromReplication;
public readonly bool FromSmuggler;
private readonly string _docId;
private readonly CollectionName _collection;
private readonly string _name;
private TableValueReader _tvr;
public long BaselineMilliseconds => BaselineDate.Ticks / 10_000;
public DateTime BaselineDate;
public TimeSeriesValuesSegment ReadOnlySegment;
public string ReadOnlyChangeVector;
private long _currentEtag;
private string _currentChangeVector;
public string ChangeVector => _currentChangeVector;
private AllocatedMemoryData _clonedReadonlySegment;
private TimeSeriesSegmentHolder(
TimeSeriesStorage tss,
DocumentsOperationContext context,
string docId,
string name,
CollectionName collection,
string fromReplicationChangeVector
)
{
_tss = tss;
_context = context;
_collection = collection;
_docId = docId;
_name = name;
FromReplication = fromReplicationChangeVector != null;
_tss.GenerateChangeVector(_context, fromReplicationChangeVector); // update the database change vector
}
public TimeSeriesSegmentHolder(
TimeSeriesStorage tss,
DocumentsOperationContext context,
string docId,
string name,
CollectionName collection,
DateTime timeStamp,
string fromReplicationChangeVector = null
) : this(tss, context, docId, name, collection, fromReplicationChangeVector)
{
SliceHolder = new TimeSeriesSliceHolder(_context, docId, name, _collection.Name).WithBaseline(timeStamp);
SliceHolder.CreateSegmentBuffer();
}
public TimeSeriesSegmentHolder(
TimeSeriesStorage tss,
DocumentsOperationContext context,
TimeSeriesSliceHolder allocator,
string docId,
string name,
CollectionName collection,
AppendOptions options
) : this(tss, context, docId, name, collection, options.ChangeVectorFromReplication)
{
FromSmuggler = options.FromSmuggler;
SliceHolder = allocator;
BaselineDate = allocator.CurrentBaseline;
allocator.CreateSegmentBuffer();
}
private void Initialize()
{
Debug.Assert(_tvr.Equals(default) == false);
var readOnlySegment = TableValueToSegment(ref _tvr, out BaselineDate);
// while appending or deleting, we might change the same segment.
// So we clone it.
Debug.Assert(_clonedReadonlySegment == null);
_clonedReadonlySegment = readOnlySegment.Clone(_context, out ReadOnlySegment);
ReadOnlyChangeVector = DocumentsStorage.TableValueToChangeVector(_context, (int)TimeSeriesTable.ChangeVector, ref _tvr);
SliceHolder.SetBaselineToKey(BaselineDate);
_countWasReduced = false;
}
public Table Table => _tss.GetOrCreateTimeSeriesTable(_context.Transaction.InnerTransaction, _collection);
private bool _countWasReduced;
private void ReduceCountBeforeAppend()
{
if (_countWasReduced)
return;
// we modified this segment so we need to reduce the original count
_countWasReduced = true;
_tss.Stats.UpdateCountOfExistingStats(_context, SliceHolder, _collection, -ReadOnlySegment.NumberOfLiveEntries);
}
public long AppendExistingSegment(TimeSeriesValuesSegment newValueSegment)
{
if (newValueSegment.RecomputeRequired)
newValueSegment = newValueSegment.Recompute(_context.Allocator);
(_currentChangeVector, _currentEtag) = _tss.GenerateChangeVector(_context);
ValidateSegment(newValueSegment);
if (newValueSegment.NumberOfLiveEntries == 0)
{
MarkSegmentAsPendingDeletion(_context, _collection.Name, _currentEtag);
}
var modifiedEntries = Math.Abs(newValueSegment.NumberOfLiveEntries - ReadOnlySegment.NumberOfLiveEntries);
ReduceCountBeforeAppend();
var count = _tss.Stats.UpdateStats(_context, SliceHolder, _collection, newValueSegment, BaselineDate, modifiedEntries);
using (Table.Allocate(out var tvb))
using (Slice.From(_context.Allocator, _currentChangeVector, out var cv))
{
tvb.Add(SliceHolder.TimeSeriesKeySlice);
tvb.Add(Bits.SwapBytes(_currentEtag));
tvb.Add(cv);
tvb.Add(newValueSegment.Ptr, newValueSegment.NumberOfBytes);
tvb.Add(SliceHolder.CollectionSlice);
tvb.Add(_context.GetTransactionMarker());
Table.Set(tvb);
}
EnsureStatsAndDataIntegrity(_context, _docId, _name, newValueSegment, _collection, BaselineDate);
return count;
}
private void AppendDeadSegment(TimeSeriesValuesSegment newValueSegment)
{
(_currentChangeVector, _currentEtag) = _tss.GenerateChangeVector(_context);
ValidateSegment(newValueSegment);
MarkSegmentAsPendingDeletion(_context, _collection.Name, _currentEtag);
ReduceCountBeforeAppend();
//TODO: unused code, check if the number of modified entries is correct
_tss.Stats.UpdateStats(_context, SliceHolder, _collection, newValueSegment, BaselineDate, ReadOnlySegment.NumberOfLiveEntries);
using (Table.Allocate(out var tvb))
{
tvb.Add(SliceHolder.TimeSeriesKeySlice);
tvb.Add(Bits.SwapBytes(_currentEtag));
tvb.Add(Slices.Empty); // we put empty slice in the change-vector, so it wouldn't replicate
tvb.Add(newValueSegment.Ptr, newValueSegment.NumberOfBytes);
tvb.Add(SliceHolder.CollectionSlice);
tvb.Add(_context.GetTransactionMarker());