-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathObjectBTreeFile.cs
More file actions
6858 lines (5774 loc) · 206 KB
/
ObjectBTreeFile.cs
File metadata and controls
6858 lines (5774 loc) · 206 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
#define ASSERT_LOCKS
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using Waher.Events;
using Waher.Persistence.Exceptions;
using Waher.Persistence.Files.Statistics;
using Waher.Persistence.Files.Storage;
using Waher.Persistence.Filters;
using Waher.Persistence.Serialization;
using Waher.Runtime.Collections;
using Waher.Runtime.Inventory;
using Waher.Runtime.Threading;
namespace Waher.Persistence.Files
{
/// <summary>
/// This class manages a binary file where objects are persisted in a B-tree.
/// </summary>
[DebuggerDisplay("{CollectionName}, Searches: {nrSearches}, Block Loads: {nrBlockLoads}, Block Saves: {nrBlockSaves}")]
public class ObjectBTreeFile : IDisposable
{
internal const int BlockHeaderSize = 14;
internal readonly MultiReadSingleWriteObject fileAccess;
private IndexBTreeFile[] indices = Array.Empty<IndexBTreeFile>();
private ChunkedList<IndexBTreeFile> indexList = new ChunkedList<IndexBTreeFile>();
private SortedDictionary<uint, bool> emptyBlocks = null;
private readonly GenericObjectSerializer genericSerializer;
private readonly FilesProvider provider;
private readonly FileOfBlocks file;
private readonly FileOfBlocks blobFile;
private readonly Encoding encoding;
private SortedDictionary<uint, byte[]> blocksToSave = null;
private ChunkedList<SaveRec> objectsToSave = null;
private ChunkedList<LoadRec> objectsToLoad = null;
private readonly object synchObject = new object();
private readonly IRecordHandler recordHandler;
private long lockToken = long.MinValue;
private ulong nrFullFileScans = 0;
private ulong nrSearches = 0;
private uint blocksAdded = 0;
private ulong nrBlockLoads = 0;
private ulong nrCacheLoads = 0;
private ulong nrBlockSaves = 0;
private ulong nrBlobBlockLoads = 0;
private ulong nrBlobBlockSaves = 0;
private ulong blockUpdateCounter = 0;
private readonly string fileName;
private readonly string collectionName;
private readonly string blobFileName;
private readonly int blockSize;
private readonly int blobBlockSize;
private readonly int inlineObjectSizeLimit;
private readonly int timeoutMilliseconds;
private readonly int id;
private uint blockLimit;
private uint blobBlockLimit;
private bool emptyRoot = false;
private Aes aes;
private byte[] aesKey;
private byte[] ivSeed;
private int ivSeedLen;
private readonly bool encrypted;
private readonly bool mainSynch;
private enum WriteOp
{
Insert,
Update,
Delete,
FindDelete
}
private class SaveRec
{
public object Object;
public ObjectSerializer Serializer;
public WriteOp Operation;
public ObjectCallback ObjectCallback;
public ObjectsCallback ObjectsCallback;
public void Raise(object Object)
{
if (!(this.ObjectCallback is null))
this.ObjectCallback(Object);
else if (!(this.ObjectsCallback is null))
this.ObjectsCallback(new object[] { Object });
}
public void Raise(IEnumerable<object> Objects)
{
if (!(this.ObjectCallback is null))
{
foreach (object Object in Objects)
this.ObjectCallback(Object);
}
else if (!(this.ObjectsCallback is null))
this.ObjectsCallback(Objects);
}
}
private class LoadRec
{
public Guid ObjectId;
public ObjectSerializer Serializer;
public EmbeddedObjectSetter Setter;
}
private ObjectBTreeFile(string FileName, string CollectionName, string BlobFileName, int BlockSize,
int BlobBlockSize, FilesProvider Provider, Encoding Encoding, int TimeoutMilliseconds, bool Encrypted,
IRecordHandler RecordHandler, MultiReadSingleWriteObject FileAccess)
{
this.provider = Provider;
this.id = Provider.GetNewFileId();
this.fileName = Path.GetFullPath(FileName);
this.collectionName = CollectionName;
this.blobFileName = string.IsNullOrEmpty(BlobFileName) ? string.Empty : Path.GetFullPath(BlobFileName);
this.blockSize = BlockSize;
this.blobBlockSize = BlobBlockSize;
this.inlineObjectSizeLimit = (BlockSize - BlockHeaderSize) / 2 - 4;
this.encoding = Encoding;
this.timeoutMilliseconds = TimeoutMilliseconds;
this.genericSerializer = new GenericObjectSerializer(Provider);
this.encrypted = Encrypted;
this.mainSynch = FileAccess is null;
this.fileAccess = FileAccess ?? new MultiReadSingleWriteObject(this, false);
if (RecordHandler is null)
this.recordHandler = new PrimaryRecords(this.inlineObjectSizeLimit);
else
this.recordHandler = RecordHandler;
if (this.encrypted)
{
this.aes = Aes.Create();
this.aes.BlockSize = 128;
this.aes.KeySize = 256;
this.aes.Mode = CipherMode.CBC;
this.aes.Padding = PaddingMode.None;
}
this.file = new FileOfBlocks(this.collectionName, FileName, this.blockSize);
if (string.IsNullOrEmpty(this.blobFileName))
{
this.blobFile = null;
this.blobBlockLimit = 0;
}
else
{
this.blobFile = new FileOfBlocks(this.collectionName, this.blobFileName, this.blobBlockSize);
this.blobBlockLimit = this.blobFile.BlockLimit;
}
}
/// <summary>
/// This class manages a binary file where objects are persisted in a B-tree.
/// </summary>
/// <param name="FileName">Name of binary file. File will be created if it does not exist. The class will require
/// unique read/write access to the file.</param>
/// <param name="CollectionName">Name of collection corresponding to the file.</param>
/// <param name="BlobFileName">Name of file in which BLOBs are stored.</param>
/// <param name="BlockSize">Size of a block in the B-tree. The size must be a power of two, and should be at least the same
/// size as a sector on the storage device. Smaller block sizes (2, 4 kB) are suitable for online transaction processing, where
/// a lot of updates to the database occurs. Larger block sizes (8, 16, 32 kB) are suitable for decision support systems.
/// The block sizes also limit the size of objects stored directly in the file. Objects larger than
/// <see cref="InlineObjectSizeLimit"/> bytes will be stored as BLOBs.</param>
/// <param name="BlobBlockSize">Size of a block in the BLOB file. The size must be a power of two. The BLOB file will consist
/// of a doubly linked list of blocks of this size.</param>
/// <param name="Provider">Reference to the files provider.</param>
/// <param name="Encoding">Encoding to use for text properties.</param>
/// <param name="TimeoutMilliseconds">Timeout, in milliseconds, to wait for access to the database layer.</param>
/// <param name="Encrypted">If the files should be encrypted or not.</param>
internal static Task<ObjectBTreeFile> Create(string FileName, string CollectionName, string BlobFileName, int BlockSize, int BlobBlockSize,
FilesProvider Provider, Encoding Encoding, int TimeoutMilliseconds, bool Encrypted)
{
return Create(FileName, CollectionName, BlobFileName, BlockSize, BlobBlockSize, Provider, Encoding, TimeoutMilliseconds, Encrypted, null, null);
}
/// <summary>
/// This class manages a binary file where objects are persisted in a B-tree.
/// </summary>
/// <param name="FileName">Name of binary file. File will be created if it does not exist. The class will require
/// unique read/write access to the file.</param>
/// <param name="CollectionName">Name of collection corresponding to the file.</param>
/// <param name="BlobFileName">Name of file in which BLOBs are stored.</param>
/// <param name="BlockSize">Size of a block in the B-tree. The size must be a power of two, and should be at least the same
/// size as a sector on the storage device. Smaller block sizes (2, 4 kB) are suitable for online transaction processing, where
/// a lot of updates to the database occurs. Larger block sizes (8, 16, 32 kB) are suitable for decision support systems.
/// The block sizes also limit the size of objects stored directly in the file. Objects larger than
/// <see cref="InlineObjectSizeLimit"/> bytes will be stored as BLOBs.</param>
/// <param name="BlobBlockSize">Size of a block in the BLOB file. The size must be a power of two. The BLOB file will consist
/// of a doubly linked list of blocks of this size.</param>
/// <param name="Provider">Reference to the files provider.</param>
/// <param name="Encoding">Encoding to use for text properties.</param>
/// <param name="TimeoutMilliseconds">Timeout, in milliseconds, to wait for access to the database layer.</param>
/// <param name="Encrypted">If the files should be encrypted or not.</param>
/// <param name="RecordHandler">Record handler to use.</param>
/// <param name="FileAccess">File Access synchronization object.</param>
internal static async Task<ObjectBTreeFile> Create(string FileName, string CollectionName, string BlobFileName, int BlockSize,
int BlobBlockSize, FilesProvider Provider, Encoding Encoding, int TimeoutMilliseconds, bool Encrypted,
IRecordHandler RecordHandler, MultiReadSingleWriteObject FileAccess)
{
FileOfBlocks.CheckBlockSize(BlockSize);
FileOfBlocks.CheckBlockSize(BlobBlockSize);
if (TimeoutMilliseconds <= 0)
throw new ArgumentOutOfRangeException("The timeout must be positive.", nameof(TimeoutMilliseconds));
ObjectBTreeFile Result = new ObjectBTreeFile(FileName, CollectionName, BlobFileName, BlockSize, BlobBlockSize, Provider,
Encoding, TimeoutMilliseconds, Encrypted, RecordHandler, FileAccess);
if (Result.encrypted)
await Result.EnsureKeys();
if (!Result.file.FilePreExisting || Result.file.Length == 0)
await Result.CreateFirstBlock();
Result.blockLimit = Result.file.BlockLimit;
return Result;
}
/// <summary>
/// Ensures cryptographic keys are loaded.
/// </summary>
internal async Task EnsureKeys()
{
if (this.aesKey is null || this.ivSeed is null)
{
KeyValuePair<byte[], byte[]> P = await this.provider.GetKeys(this.fileName, this.file.FilePreExisting);
this.aesKey = P.Key;
this.ivSeed = P.Value;
this.ivSeedLen = this.ivSeed.Length;
}
if (this.aes is null)
{
this.aes = Aes.Create();
this.aes.BlockSize = 128;
this.aes.KeySize = 256;
this.aes.Mode = CipherMode.CBC;
this.aes.Padding = PaddingMode.None;
}
}
/// <summary>
/// <see cref="IDisposable.Dispose"/>
/// </summary>
public void Dispose()
{
this.file?.Dispose();
if (!(this.indices is null))
{
foreach (IndexBTreeFile IndexFile in this.indices)
IndexFile.Dispose();
this.indices = null;
this.indexList = null;
}
this.blobFile?.Dispose();
this.provider.RemoveBlocks(this.id);
if (!(this.fileAccess is null))
{
if (!this.fileAccess.Disposed) // Object shared between object file and index files.
this.fileAccess.Dispose();
}
}
internal IRecordHandler RecordHandler => this.recordHandler;
internal GenericObjectSerializer GenericSerializer => this.genericSerializer;
internal MultiReadSingleWriteObject FileAccess => this.fileAccess;
/// <summary>
/// Identifier of the file.
/// </summary>
public int Id => this.id;
/// <summary>
/// Reference to files provider.
/// </summary>
public FilesProvider Provider => this.provider;
/// <summary>
/// Name of binary file.
/// </summary>
public string FileName => this.fileName;
/// <summary>
/// Name of corresponding collection name.
/// </summary>
public string CollectionName => this.collectionName;
/// <summary>
/// Name of file in which BLOBs are stored.
/// </summary>
public string BlobFileName => this.blobFileName;
/// <summary>
/// Encoding to use for text properties.
/// </summary>
public Encoding Encoding => this.encoding;
/// <summary>
/// Size of a block in the B-tree. The size must be a power of two, and should be at least the same
/// size as a sector on the storage device. Smaller block sizes (2, 4 kB) are suitable for online transaction processing, where
/// a lot of updates to the database occurs. Larger block sizes (8, 16, 32 kB) are suitable for decision support systems.
/// The block sizes also limit the size of objects stored directly in the file. Objects larger than
/// <see cref="InlineObjectSizeLimit"/> will be persisted as BLOBs, with the bulk of the object stored as separate files.
/// Smallest block size = 1024, largest block size = 65536.
/// </summary>
public int BlockSize => this.blockSize;
/// <summary>
/// Size of a block in the BLOB file. The size must be a power of two. The BLOB file will consist
/// of a doubly linked list of blocks of this size.
/// </summary>
public int BlobBlockSize => this.blobBlockSize;
/// <summary>
/// Maximum size of objects that are stored in-line. Larger objects will be stored as BLOBs.
/// </summary>
public int InlineObjectSizeLimit => this.inlineObjectSizeLimit;
/// <summary>
/// Timeout, in milliseconds, for database operations.
/// </summary>
public int TimeoutMilliseconds => this.timeoutMilliseconds;
/// <summary>
/// If the files should be encrypted or not.
/// </summary>
public bool Encrypted => this.encrypted;
internal GenericObjectSerializer GenericObjectSerializer => this.genericSerializer;
/// <summary>
/// Block limit
/// </summary>
internal uint BlockLimit => this.blockLimit;
/// <summary>
/// BLOB Block Limit
/// </summary>
internal uint BlobBlockLimit => this.blobBlockLimit;
/// <summary>
/// If the file is the main synchronization file of a collection (true) or a secondary file (false).
/// </summary>
internal bool MainSynch => this.mainSynch;
#region GUIDs for databases
/// <summary>
/// Creates a new GUID suitable for use in databases.
/// </summary>
/// <returns>New GUID.</returns>
public static Guid CreateDatabaseGUID()
{
return guidGenerator.CreateGuid();
}
private readonly static SequentialGuidGenerator guidGenerator = new SequentialGuidGenerator();
#endregion
#region Locks
/// <summary>
/// Waits until object ready for reading.
/// Each call to <see cref="BeginRead"/> must be followed by exactly one call to <see cref="EndRead"/>.
/// </summary>
/// <exception cref="TimeoutException">If read access could not be given within the <see cref="TimeoutMilliseconds"/> time.</exception>
public async Task BeginRead()
{
if (this.mainSynch)
{
if (!await this.fileAccess.TryBeginRead(this.timeoutMilliseconds))
throw new TimeoutException("Unable to get read access to " + this.collectionName);
this.lockToken = this.fileAccess.Token;
}
else
throw new InvalidOperationException("Secondary files are automatically locked with the primary file.");
}
/// <summary>
/// Waits, at most <paramref name="Timeout"/> milliseconds, until object ready for reading.
/// Each successful call to <see cref="TryBeginRead"/> must be followed by exactly one call to <see cref="EndRead"/>.
/// </summary>
/// <param name="Timeout">Timeout, in milliseconds.</param>
public async Task<bool> TryBeginRead(int Timeout)
{
if (this.mainSynch)
{
bool Result = await this.fileAccess.TryBeginRead(Timeout);
if (Result)
this.lockToken = this.fileAccess.Token;
return Result;
}
else
throw new InvalidOperationException("Secondary files are automatically locked with the primary file.");
}
/// <summary>
/// Waits until object ready for writing.
/// Each call to <see cref="BeginWrite"/> must be followed by exactly one call to <see cref="EndWrite"/>.
/// </summary>
/// <exception cref="TimeoutException">If write access could not be given within the <see cref="TimeoutMilliseconds"/> time.</exception>
public async Task BeginWrite()
{
if (this.mainSynch)
{
if (!await this.fileAccess.TryBeginWrite(this.timeoutMilliseconds))
throw new TimeoutException("Unable to get write access to " + this.collectionName);
this.lockToken = this.fileAccess.Token;
}
else
throw new InvalidOperationException("Secondary files are automatically locked with the primary file.");
}
/// <summary>
/// Waits, at most <paramref name="Timeout"/> milliseconds, until object ready for writing.
/// Each successful call to <see cref="TryBeginWrite"/> must be followed by exactly one call to <see cref="EndWrite"/>.
/// </summary>
/// <param name="Timeout">Timeout, in milliseconds.</param>
public async Task<bool> TryBeginWrite(int Timeout)
{
if (this.mainSynch)
{
bool Result = await this.fileAccess.TryBeginWrite(Timeout);
if (Result)
this.lockToken = this.fileAccess.Token;
return Result;
}
else
throw new InvalidOperationException("Secondary files are automatically locked with the primary file.");
}
/// <summary>
/// Ends a reading session of the object.
/// Must be called once for each call to <see cref="MultiReadSingleWriteObject.BeginRead"/> or successful call to
/// <see cref="MultiReadSingleWriteObject.TryBeginRead(int)"/>.
/// </summary>
/// <returns>Number of concurrent readers when returning from locked section of call.</returns>
public async Task<int> EndRead()
{
if (this.mainSynch)
{
int Result = await this.fileAccess.EndRead();
if (Result == 0)
await this.CheckPending();
return Result;
}
else
throw new InvalidOperationException("Secondary files are automatically locked with the primary file.");
}
/// <summary>
/// Ends a writing session of the object.
/// Must be called once for each call to <see cref="MultiReadSingleWriteObject.BeginWrite"/> or successful call to
/// <see cref="MultiReadSingleWriteObject.TryBeginWrite(int)"/>.
/// </summary>
public async Task EndWrite()
{
if (!this.mainSynch)
throw new InvalidOperationException("Secondary files are automatically locked with the primary file.");
if (!(this.indices is null))
{
foreach (IndexBTreeFile Index in this.indices)
await Index.EndWritePriv();
}
await this.EndWritePriv();
await this.CheckPending();
}
private async Task CheckPending()
{
ChunkedList<SaveRec> ToSave;
ChunkedList<LoadRec> ToLoad;
lock (this.synchObject)
{
ToSave = this.objectsToSave;
this.objectsToSave = null;
ToLoad = this.objectsToLoad;
this.objectsToLoad = null;
}
if (!(ToSave is null))
{
foreach (SaveRec Rec in ToSave)
{
switch (Rec.Operation)
{
case WriteOp.Insert:
await this.SaveNewObject(Rec.Object, Rec.Serializer, true, Rec.Raise);
break;
case WriteOp.Update:
await this.UpdateObject(Rec.Object, Rec.Serializer, true, Rec.Raise);
break;
case WriteOp.Delete:
await this.DeleteObject(Rec.Object, Rec.Serializer, true, Rec.Raise);
break;
case WriteOp.FindDelete:
if (Rec.Object is FindDeleteLazyRec FindDeleteLazyRec)
{
int Offset = FindDeleteLazyRec.Offset;
int MaxCount = FindDeleteLazyRec.MaxCount;
Filter Filter = FindDeleteLazyRec.Filter;
string[] SortOrder = FindDeleteLazyRec.SortOrder;
ObjectSerializer Serializer = FindDeleteLazyRec.Serializer;
if (Serializer is null)
await this.FindDelete(Offset, MaxCount, Filter, true, SortOrder, Rec.Raise);
else
{
if (await this.TryBeginWrite(0))
{
try
{
await this.FindDeleteLocked(FindDeleteLazyRec.T, Offset, MaxCount, Filter, Serializer, SortOrder);
}
finally
{
await this.EndWrite();
}
}
else if (Rec.ObjectCallback is null)
this.QueueForSave(FindDeleteLazyRec, Serializer, Rec.ObjectsCallback, Rec.Operation);
else
this.QueueForSave(FindDeleteLazyRec, Serializer, Rec.ObjectCallback, Rec.Operation);
}
}
break;
}
}
}
if (!(ToLoad is null))
{
foreach (LoadRec Rec in ToLoad)
Rec.Setter(await this.LoadObject(Rec.ObjectId, Rec.Serializer));
}
}
internal async Task EndWritePriv()
{
bool EmptyBlocks = !(this.emptyBlocks is null);
bool SaveBlocks = !(this.blocksToSave is null) && this.blocksToSave.Count > 0 && !this.provider.InBulkMode(this);
if (this.emptyRoot || EmptyBlocks || SaveBlocks)
{
try
{
if (this.emptyRoot)
{
this.emptyRoot = false;
byte[] Block = await this.LoadBlockLocked(0, true);
BinaryDeserializer Reader = new BinaryDeserializer(this.collectionName, this.encoding, Block, this.blockLimit);
BlockHeader Header = new BlockHeader(Reader);
uint BlockIndex;
while (Header.BytesUsed == 0 && (BlockIndex = Header.LastBlockIndex) != 0)
{
Block = await this.LoadBlockLocked(BlockIndex, true);
Reader.Restart(Block, 0);
Header = new BlockHeader(Reader);
this.RegisterEmptyBlockLocked(BlockIndex);
}
Array.Clear(Block, 10, 4);
this.QueueSaveBlockLocked(0, Block);
await this.UpdateParentLinksLocked(0, Block);
}
if (EmptyBlocks)
await this.RemoveEmptyBlocksLocked();
if (SaveBlocks)
await this.SaveUnsavedLocked();
}
finally
{
if (this.mainSynch)
await this.fileAccess.EndWrite();
}
}
else if (this.mainSynch)
await this.fileAccess.EndWrite();
}
private async Task SaveUnsavedLocked()
{
#if ASSERT_LOCKS
this.fileAccess.AssertWriting();
#endif
if (!(this.blocksToSave is null))
{
bool Changed = false;
foreach (KeyValuePair<uint, byte[]> Rec in this.blocksToSave)
{
await this.DoSaveBlockLocked(Rec.Key, Rec.Value);
Changed = true;
}
if (Changed)
{
this.blocksToSave.Clear();
this.blocksAdded = 0;
this.blockLimit = this.file.BlockLimit;
await this.file.FlushAsync();
}
}
}
#endregion
#region Blocks
private async Task<Tuple<uint, byte[]>> CreateNewBlockLocked()
{
#if ASSERT_LOCKS
this.fileAccess.AssertWriting();
#endif
byte[] Block = null;
uint BlockIndex = uint.MaxValue;
if (!(this.emptyBlocks is null))
{
foreach (uint BlockIndex2 in this.emptyBlocks.Keys)
{
this.emptyBlocks.Remove(BlockIndex2);
if (this.emptyBlocks.Count == 0)
this.emptyBlocks = null;
Block = await this.LoadBlockLocked(BlockIndex2, true);
BlockIndex = BlockIndex2;
Array.Clear(Block, 0, this.blockSize);
break;
}
}
if (Block is null)
{
Block = new byte[this.blockSize];
BlockIndex = this.blockLimit;
this.blocksAdded++;
this.blockLimit++;
}
this.QueueSaveBlockLocked(BlockIndex, Block);
return new Tuple<uint, byte[]>(BlockIndex, Block);
}
private async Task CreateFirstBlock()
{
if (this.mainSynch)
await this.BeginWrite();
try
{
await this.CreateNewBlockLocked();
}
finally
{
if (this.mainSynch)
await this.EndWrite();
}
}
/// <summary>
/// Clears the internal memory cache.
/// </summary>
public void ClearCache()
{
this.provider.RemoveBlocks(this.id);
}
/// <summary>
/// Loads a block from the file.
/// </summary>
/// <param name="BlockIndex">Index of block to load.</param>
/// <returns>Loaded block.</returns>
public async Task<byte[]> LoadBlock(uint BlockIndex)
{
bool NeedLock = this.lockToken != this.fileAccess.Token;
if (NeedLock)
await this.BeginRead();
try
{
return await this.LoadBlockLocked(BlockIndex, true);
}
finally
{
if (NeedLock)
await this.EndRead();
}
}
internal async Task<byte[]> LoadBlockLocked(uint BlockIndex, bool AddToCache)
{
#if ASSERT_LOCKS
this.fileAccess.AssertReadingOrWriting();
#endif
if (this.provider.TryGetBlock(this.id, BlockIndex, out byte[] Block))
{
this.nrCacheLoads++;
return Block;
}
if (!(this.blocksToSave is null) && this.blocksToSave.TryGetValue(BlockIndex, out Block))
{
this.nrCacheLoads++;
return Block;
}
Block = await this.file.LoadBlock(BlockIndex);
this.nrBlockLoads++;
if (this.encrypted)
{
using (ICryptoTransform Aes = this.aes.CreateDecryptor(this.aesKey, this.GetIV(((long)BlockIndex) * this.blockSize)))
{
Block = Aes.TransformFinalBlock(Block, 0, Block.Length);
}
}
if (AddToCache)
this.provider.AddBlockToCache(this.id, BlockIndex, Block);
return Block;
}
/// <summary>
/// Saves a block to the file.
/// </summary>
/// <param name="BlockIndex">Block index of block in file.</param>
/// <param name="Block">Block to save.</param>
/// <returns>Block to save.</returns>
public async Task SaveBlock(uint BlockIndex, byte[] Block)
{
await this.BeginWrite();
try
{
this.QueueSaveBlockLocked(BlockIndex, Block);
}
finally
{
await this.EndWrite();
}
}
internal void QueueSaveBlockLocked(uint BlockIndex, byte[] Block)
{
#if ASSERT_LOCKS
this.fileAccess.AssertWriting();
#endif
if (Block is null || Block.Length != this.blockSize)
throw Database.FlagForRepair(this.collectionName, "Block not of the correct block size.");
if (this.provider.TryGetBlock(this.id, BlockIndex, out byte[] PrevBlock) && PrevBlock != Block)
{
if (Array.Equals(PrevBlock, Block))
{
this.provider.AddBlockToCache(this.id, BlockIndex, Block); // Update to new reference.
return; // No need to save.
}
}
if (this.blocksToSave is null)
this.blocksToSave = new SortedDictionary<uint, byte[]>();
this.blocksToSave[BlockIndex] = Block;
this.blockUpdateCounter++;
this.provider.AddBlockToCache(this.id, BlockIndex, Block);
}
/// <summary>
/// This counter gets updated each time a block is updated in the file.
/// </summary>
internal ulong BlockUpdateCounter => this.blockUpdateCounter;
internal async Task DoSaveBlockLocked(uint BlockIndex, byte[] Block)
{
#if ASSERT_LOCKS
this.fileAccess.AssertWriting();
#endif
byte[] EncryptedBlock;
if (this.encrypted)
{
using (ICryptoTransform Aes = this.aes.CreateEncryptor(this.aesKey, this.GetIV(((long)BlockIndex) * this.blockSize)))
{
EncryptedBlock = Aes.TransformFinalBlock(Block, 0, Block.Length);
}
}
else
EncryptedBlock = (byte[])Block.Clone();
await this.file.SaveBlock(BlockIndex, EncryptedBlock);
this.nrBlockSaves++;
}
private byte[] GetIV(long Position)
{
byte[] Input = new byte[this.ivSeedLen + 8];
Buffer.BlockCopy(this.ivSeed, 0, Input, 0, this.ivSeedLen);
Buffer.BlockCopy(BitConverter.GetBytes(Position), 0, Input, this.ivSeedLen, 8);
byte[] Hash;
using (SHA1 Sha1 = SHA1.Create())
{
Hash = Sha1.ComputeHash(Input);
}
Array.Resize(ref Hash, 16);
return Hash;
}
private void RegisterEmptyBlockLocked(uint Block)
{
#if ASSERT_LOCKS
this.fileAccess.AssertWriting();
#endif
if (this.emptyBlocks is null)
this.emptyBlocks = new SortedDictionary<uint, bool>(new ReverseOrder());
this.emptyBlocks[Block] = true;
}
private class ReverseOrder : IComparer<uint>
{
public int Compare(uint x, uint y)
{
return y.CompareTo(x);
}
}
private async Task RemoveEmptyBlocksLocked()
{
#if ASSERT_LOCKS
this.fileAccess.AssertWriting();
#endif
if (!(this.emptyBlocks is null))
{
BinaryDeserializer Reader;
BlockHeader Header;
uint DestinationIndex;
uint SourceIndex;
byte[] Block;
uint PrevBlockIndex;
uint ParentBlockIndex;
foreach (uint BlockIndex in this.emptyBlocks.Keys)
{
DestinationIndex = BlockIndex;
SourceIndex = (uint)(this.file.BlockLimit + this.blocksAdded - 1);
if (DestinationIndex < SourceIndex)
{
PrevBlockIndex = SourceIndex;
Block = await this.LoadBlockLocked(SourceIndex, false);
this.blocksToSave?.Remove(SourceIndex);
this.provider.RemoveBlock(this.id, SourceIndex);
this.QueueSaveBlockLocked(DestinationIndex, Block);
await this.UpdateParentLinksLocked(BlockIndex, Block);
ParentBlockIndex = BitConverter.ToUInt32(Block, 10);
SourceIndex = ParentBlockIndex;
Block = await this.LoadBlockLocked(SourceIndex, true);
Reader = new BinaryDeserializer(this.collectionName, this.encoding, Block, this.blockLimit);
Header = new BlockHeader(Reader);
if (Header.LastBlockIndex == PrevBlockIndex)
Buffer.BlockCopy(BitConverter.GetBytes(BlockIndex), 0, Block, 6, 4);
else
{
await this.ForEachObject(Block, (Link, ObjectId, Pos, Len) =>
{
if (Link == PrevBlockIndex)
{
Buffer.BlockCopy(BitConverter.GetBytes(BlockIndex), 0, Block, Pos - 4, 4);
return false;
}
else
return true;
});
}
this.QueueSaveBlockLocked(SourceIndex, Block);
}
else
{
this.blocksToSave?.Remove(DestinationIndex);
this.provider.RemoveBlock(this.id, DestinationIndex);
if (SourceIndex != DestinationIndex)
{
this.blocksToSave?.Remove(SourceIndex);
this.provider.RemoveBlock(this.id, SourceIndex);
}
}
if (this.blocksAdded > 0)
this.blocksAdded--;
else
await this.file.Truncate(this.file.BlockLimit - 1);
this.blockLimit--;
}
this.emptyBlocks = null;
}
}
#endregion
#region BLOBs
internal async Task<byte[]> SaveBlobLocked(byte[] Bin)
{
#if ASSERT_LOCKS
this.fileAccess.AssertWriting();
#endif
if (this.blobFile is null)
throw new FileException("BLOBs not supported in this file.", this.fileName, this.collectionName);
BinaryDeserializer Reader = new BinaryDeserializer(this.collectionName, this.encoding, Bin, this.blockLimit);
this.recordHandler.SkipKey(Reader);
int KeySize = Reader.Position;
int Len = (int)await this.recordHandler.GetFullPayloadSize(Reader);
int HeaderSize = Reader.Position;
if (Len != Bin.Length - Reader.Position)
throw Database.FlagForRepair(this.collectionName, "Invalid serialization of object");
this.blobBlockLimit = this.blobFile.BlockLimit;
byte[] Result = new byte[HeaderSize + 4];
byte[] EncryptedBlock;
Buffer.BlockCopy(Bin, 0, Result, 0, HeaderSize);
Buffer.BlockCopy(BitConverter.GetBytes(this.blobBlockLimit), 0, Result, HeaderSize, 4);
byte[] Block = new byte[this.blobBlockSize];
int Left;
uint Prev = uint.MaxValue;
int Limit = this.blobBlockSize - KeySize - 8;
int Pos = HeaderSize;
uint BlobBlockIndex = this.blobFile.BlockLimit;
Buffer.BlockCopy(Bin, 0, Block, 0, KeySize);
Len += HeaderSize;
while (Pos < Len)
{
Buffer.BlockCopy(BitConverter.GetBytes(Prev), 0, Block, KeySize, 4);
Prev = this.blobBlockLimit;
Left = Len - Pos;