ravendb /Raven.Database/Storage/Voron/StorageActions/DocumentsStorageActions.cs

Language C# Lines 696
MD5 Hash 6de3c7ab17dad266510349a1985baadb
Repository https://github.com/nwendel/ravendb.git View Raw File
  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
using Raven.Abstractions;
using Raven.Abstractions.Data;
using Raven.Abstractions.Exceptions;
using Raven.Abstractions.Extensions;
using Raven.Abstractions.Logging;
using Raven.Abstractions.MEF;
using Raven.Abstractions.Util;
using Raven.Abstractions.Util.Streams;
using Raven.Database.Impl;
using Raven.Database.Plugins;
using Raven.Database.Storage.Voron.Impl;
using Raven.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Voron;
using Voron.Impl;
using Constants = Raven.Abstractions.Data.Constants;

namespace Raven.Database.Storage.Voron.StorageActions
{
	public class DocumentsStorageActions : StorageActionsBase, IDocumentStorageActions
	{
		private readonly Reference<WriteBatch> writeBatch;

		private readonly IUuidGenerator uuidGenerator;
		private readonly OrderedPartCollection<AbstractDocumentCodec> documentCodecs;
		private readonly IDocumentCacher documentCacher;

		private static readonly ILog logger = LogManager.GetCurrentClassLogger();
        private readonly Dictionary<Etag, Etag> etagTouches = new Dictionary<Etag, Etag>();
		private readonly TableStorage tableStorage;

		private readonly Index metadataIndex;

		public DocumentsStorageActions(IUuidGenerator uuidGenerator,
			OrderedPartCollection<AbstractDocumentCodec> documentCodecs,
			IDocumentCacher documentCacher,
			Reference<WriteBatch> writeBatch,
			Reference<SnapshotReader> snapshot,
            TableStorage tableStorage, 
            IBufferPool bufferPool)
			: base(snapshot, bufferPool)
		{
			this.uuidGenerator = uuidGenerator;
			this.documentCodecs = documentCodecs;
			this.documentCacher = documentCacher;
			this.writeBatch = writeBatch;
			this.tableStorage = tableStorage;

			metadataIndex = tableStorage.Documents.GetIndex(Tables.Documents.Indices.Metadata);
		}

		public IEnumerable<JsonDocument> GetDocumentsByReverseUpdateOrder(int start, int take)
		{
			if (start < 0)
				throw new ArgumentException("must have zero or positive value", "start");
			if (take < 0)
				throw new ArgumentException("must have zero or positive value", "take");
			if (take == 0) yield break;

			using (var iterator = tableStorage.Documents.GetIndex(Tables.Documents.Indices.KeyByEtag)
											.Iterate(Snapshot, writeBatch.Value))
			{
				int fetchedDocumentCount = 0;
				if (!iterator.Seek(Slice.AfterAllKeys))
					yield break;

				if (!iterator.Skip(-start))
					yield break;
				do
				{
					if (iterator.CurrentKey == null || iterator.CurrentKey.Equals(Slice.Empty))
						yield break;

					var key = GetKeyFromCurrent(iterator);

					var document = DocumentByKey(key, null);
					if (document == null) //precaution - should never be true
					{
						throw new InvalidDataException(string.Format("Possible data corruption - the key = '{0}' was found in the documents indice, but matching document was not found.", key));
					}

					yield return document;

					fetchedDocumentCount++;
				} while (iterator.MovePrev() && fetchedDocumentCount < take);
			}
		}

		public IEnumerable<KeyValuePair<string, Etag>> GetDocumentEtagsFromKeyByEtagIndice()
		{
			using (var iterator = tableStorage.Documents.GetIndex(Tables.Documents.Indices.KeyByEtag)
				.Iterate(Snapshot, writeBatch.Value))
			{
				if (!iterator.Seek(Slice.AfterAllKeys))
					yield break;
				do
				{
					if (iterator.CurrentKey == null || iterator.CurrentKey.Equals(Slice.Empty))
						continue;

					var key = GetKeyFromCurrent(iterator);
					var etag = Etag.Parse(iterator.CurrentKey.ToString());

					yield return new KeyValuePair<string, Etag>(key,etag);
				} while (iterator.MovePrev());
			}
		}

		public IEnumerable<KeyValuePair<string, Etag>> GetDocumentEtagsFromMetadata()
		{			
			using (var iterator = tableStorage.Documents.GetIndex(Tables.Documents.Indices.KeyByEtag)
				.Iterate(Snapshot, writeBatch.Value))
			{
				if (!iterator.Seek(Slice.AfterAllKeys))
					yield break;
				do
				{
					if (iterator.CurrentKey == null || iterator.CurrentKey.Equals(Slice.Empty))
						continue;

					var key = GetKeyFromCurrent(iterator);
					var documentMetadata = DocumentMetadataByKey(key, null);
					yield return new KeyValuePair<string, Etag>(key, documentMetadata.Etag);

				} while (iterator.MovePrev());
			}
		}


		public IEnumerable<JsonDocument> GetDocumentsAfter(Etag etag, int take, CancellationToken cancellationToken, long? maxSize = null, Etag untilEtag = null, TimeSpan? timeout = null)
		{
			if (take < 0)
				throw new ArgumentException("must have zero or positive value", "take");
			if (take == 0) yield break;

			if (string.IsNullOrEmpty(etag))
				throw new ArgumentNullException("etag");

			Stopwatch duration = null;
			if (timeout != null)
				duration = Stopwatch.StartNew();

			using (var iterator = tableStorage.Documents.GetIndex(Tables.Documents.Indices.KeyByEtag)
											.Iterate(Snapshot, writeBatch.Value))
			{
				if (!iterator.Seek(Slice.BeforeAllKeys))
				{
					yield break;
				}

				long fetchedDocumentTotalSize = 0;
				int fetchedDocumentCount = 0;

				do
				{
					cancellationToken.ThrowIfCancellationRequested();

					if (iterator.CurrentKey == null || iterator.CurrentKey.Equals(Slice.Empty))
						yield break;

					var docEtag = Etag.Parse(iterator.CurrentKey.ToString());

					if (!EtagUtil.IsGreaterThan(docEtag, etag)) continue;

					if (untilEtag != null && fetchedDocumentCount > 0)
					{
						if (EtagUtil.IsGreaterThan(docEtag, untilEtag))
							yield break;
					}

					var key = GetKeyFromCurrent(iterator);

					var document = DocumentByKey(key, null);
					if (document == null) //precaution - should never be true
					{
						throw new InvalidDataException(string.Format("Data corruption - the key = '{0}' was found in the documents indice, but matching document was not found", key));
					}

					if (!document.Etag.Equals(docEtag))
					{
						throw new InvalidDataException(string.Format("Data corruption - the etag for key ='{0}' is different between document and its indice",key));
					}

					fetchedDocumentTotalSize += document.SerializedSizeOnDisk;
					fetchedDocumentCount++;

					if (maxSize.HasValue && fetchedDocumentTotalSize >= maxSize)
					{
						yield return document;
						yield break;
					}

					yield return document;

					if (timeout != null)
					{
						if (duration.Elapsed > timeout.Value)
							yield break;
					}
				} while (iterator.MoveNext() && fetchedDocumentCount < take);
			}
		}

		private static string GetKeyFromCurrent(global::Voron.Trees.IIterator iterator)
		{
			string key;
			using (var currentDataStream = iterator.CreateReaderForCurrent().AsStream())
			{
				var keyBytes = currentDataStream.ReadData();
				key = Encoding.UTF8.GetString(keyBytes);
			}
			return key;
		}

		public IEnumerable<JsonDocument> GetDocumentsWithIdStartingWith(string idPrefix, int start, int take, string skipAfter)
		{
			if (string.IsNullOrEmpty(idPrefix))
				throw new ArgumentNullException("idPrefix");
			if (start < 0)
				throw new ArgumentException("must have zero or positive value", "start");
			if (take < 0)
				throw new ArgumentException("must have zero or positive value", "take");

			if (take == 0)
				yield break;

			using (var iterator = tableStorage.Documents.Iterate(Snapshot, writeBatch.Value))
			{
				iterator.RequiredPrefix = idPrefix.ToLowerInvariant();
				var seekStart = skipAfter == null ? iterator.RequiredPrefix : skipAfter.ToLowerInvariant();
				if (iterator.Seek(seekStart) == false || !iterator.Skip(start))
					yield break;

				if (skipAfter != null && !iterator.MoveNext())
					yield break; // move to the _next_ one
					

				var fetchedDocumentCount = 0;
				do
				{
					var key = iterator.CurrentKey.ToString();

					var fetchedDocument = DocumentByKey(key, null);
					if (fetchedDocument == null) continue;

					fetchedDocumentCount++;
					yield return fetchedDocument;
				} while (iterator.MoveNext() && fetchedDocumentCount < take);
			}
		}

		public long GetDocumentsCount()
		{
			return tableStorage.GetEntriesCount(tableStorage.Documents);
		}

		public JsonDocument DocumentByKey(string key, TransactionInformation transactionInformation)
		{
			if (string.IsNullOrEmpty(key))
			{
				logger.Debug("Document with empty key was not found");
				return null;
			}

			var lowerKey = CreateKey(key);
			if (!tableStorage.Documents.Contains(Snapshot, lowerKey, writeBatch.Value))
			{
				logger.Debug("Document with key='{0}' was not found", key);
				return null;
			}

			var metadataDocument = ReadDocumentMetadata(key);
			if (metadataDocument == null)
			{
				logger.Warn(string.Format("Metadata of document with key='{0} was not found, but the document itself exists.", key));
				return null;
			}

			var documentData = ReadDocumentData(key, metadataDocument.Etag, metadataDocument.Metadata);

			logger.Debug("DocumentByKey() by key ='{0}'", key);

			var docSize = tableStorage.Documents.GetDataSize(Snapshot, lowerKey);

			var metadataSize = metadataIndex.GetDataSize(Snapshot, lowerKey);

			return new JsonDocument
			{
				DataAsJson = documentData,
				Etag = metadataDocument.Etag,
				Key = metadataDocument.Key, //original key - with user specified casing, etc.
				Metadata = metadataDocument.Metadata,
				SerializedSizeOnDisk = docSize + metadataSize,
				LastModified = metadataDocument.LastModified
			};
		}

		public JsonDocumentMetadata DocumentMetadataByKey(string key, TransactionInformation transactionInformation)
		{
			if (string.IsNullOrEmpty(key))
				throw new ArgumentNullException("key");

			var lowerKey = CreateKey(key);

			if (tableStorage.Documents.Contains(Snapshot, lowerKey, writeBatch.Value))
				return ReadDocumentMetadata(key);

			logger.Debug("Document with key='{0}' was not found", key);
			return null;
		}

		public bool DeleteDocument(string key, Etag etag, out RavenJObject metadata, out Etag deletedETag)
		{
			if (string.IsNullOrEmpty(key))
				throw new ArgumentNullException("key");

			var loweredKey = CreateKey(key);
			
			if(etag != null)
				EnsureDocumentEtagMatch(loweredKey, etag, "DELETE");

			ushort? existingVersion;
			if (!tableStorage.Documents.Contains(Snapshot, loweredKey, writeBatch.Value, out existingVersion))
			{
				logger.Debug("Document with key '{0}' was not found, and considered deleted", key);
				metadata = null;
				deletedETag = null;
				return false;
			}

			if (!metadataIndex.Contains(Snapshot, loweredKey, writeBatch.Value)) //data exists, but metadata is not --> precaution, should never be true
			{
				var errorString = string.Format("Document with key '{0}' was found, but its metadata wasn't found --> possible data corruption", key);
				throw new InvalidDataException(errorString);
			}

			var existingEtag = EnsureDocumentEtagMatch(key, etag, "DELETE");
			var documentMetadata = ReadDocumentMetadata(key);
			metadata = documentMetadata.Metadata;

			deletedETag = etag != null ? existingEtag : documentMetadata.Etag;

			tableStorage.Documents.Delete(writeBatch.Value, loweredKey, existingVersion);
			metadataIndex.Delete(writeBatch.Value, loweredKey);

			tableStorage.Documents.GetIndex(Tables.Documents.Indices.KeyByEtag)
						  .Delete(writeBatch.Value, deletedETag);

			documentCacher.RemoveCachedDocument(loweredKey, etag);

			logger.Debug("Deleted document with key = '{0}'", key);

			return true;
		}

		public AddDocumentResult AddDocument(string key, Etag etag, RavenJObject data, RavenJObject metadata)
		{
			if (string.IsNullOrEmpty(key))
				throw new ArgumentNullException("key");

			if (key != null && Encoding.UTF8.GetByteCount(key) >= UInt16.MaxValue)
				throw new ArgumentException(string.Format("The dataKey must be a maximum of {0} bytes in Unicode, key is: '{1}'", UInt16.MaxValue, key), "key");

			Etag existingEtag;
			Etag newEtag;

			DateTime savedAt;
			var isUpdate = WriteDocumentData(key, etag, data, metadata, out newEtag, out existingEtag, out savedAt);

			logger.Debug("AddDocument() - {0} document with key = '{1}'", isUpdate ? "Updated" : "Added", key);

			return new AddDocumentResult
			{
				Etag = newEtag,
				PrevEtag = existingEtag,
				SavedAt = savedAt,
				Updated = isUpdate
			};
		}

		private bool PutDocumentMetadataInternal(string key, RavenJObject metadata, Etag newEtag, DateTime savedAt)
		{
			return WriteDocumentMetadata(new JsonDocumentMetadata
			{
				Key = key,
				Etag = newEtag,
				Metadata = metadata,
				LastModified = savedAt
			});
		}

		public void IncrementDocumentCount(int value)
		{
			//nothing to do here			
		}

		public AddDocumentResult InsertDocument(string key, RavenJObject data, RavenJObject metadata, bool overwriteExisting)
		{
			if (string.IsNullOrEmpty(key))
				throw new ArgumentNullException("key");

			if (!overwriteExisting && tableStorage.Documents.Contains(Snapshot, CreateKey(key), writeBatch.Value))
			{
				throw new ConcurrencyException(string.Format("InsertDocument() - overwriteExisting is false and document with key = '{0}' already exists", key));
			}

			return AddDocument(key, null, data, metadata);
		}

		public void TouchDocument(string key, out Etag preTouchEtag, out Etag afterTouchEtag)
		{
			if (string.IsNullOrEmpty(key))
				throw new ArgumentNullException("key");

			var lowerKey = CreateKey(key);

			if (!tableStorage.Documents.Contains(Snapshot, lowerKey, writeBatch.Value))
			{
				logger.Debug("Document with dataKey='{0}' was not found", key);
				preTouchEtag = null;
				afterTouchEtag = null;
				return;
			}

			var metadata = ReadDocumentMetadata(key);

			var newEtag = uuidGenerator.CreateSequentialUuid(UuidType.Documents);
			afterTouchEtag = newEtag;
			preTouchEtag = metadata.Etag;
			metadata.Etag = newEtag;

			WriteDocumentMetadata(metadata,shouldIgnoreConcurrencyExceptions:true);

			var keyByEtagIndex = tableStorage.Documents.GetIndex(Tables.Documents.Indices.KeyByEtag);

			keyByEtagIndex.Delete(writeBatch.Value, preTouchEtag);
			keyByEtagIndex.Add(writeBatch.Value, newEtag, lowerKey);
            etagTouches.Add(preTouchEtag, afterTouchEtag);

			logger.Debug("TouchDocument() - document with key = '{0}'", key);
		}

		public Etag GetBestNextDocumentEtag(Etag etag)
		{
			if (etag == null) throw new ArgumentNullException("etag");

			using (var iter = tableStorage.Documents.GetIndex(Tables.Documents.Indices.KeyByEtag)
													.Iterate(Snapshot, writeBatch.Value))
			{
				if (!iter.Seek(etag.ToString()) &&
					!iter.Seek(Slice.BeforeAllKeys)) //if parameter etag not found, scan from beginning. if empty --> return original etag
					return etag;

				do
				{
					var docEtag = Etag.Parse(iter.CurrentKey.ToString());
					
					if (EtagUtil.IsGreaterThan(docEtag, etag))
						return docEtag;
				} while (iter.MoveNext());
			}

			return etag; //if not found, return the original etag
		}

		private Etag EnsureDocumentEtagMatch(string key, Etag etag, string method)
		{
			var metadata = ReadDocumentMetadata(key);

			if (metadata == null)
				return Etag.InvalidEtag;

			var existingEtag = metadata.Etag;

           
			if (etag != null)
			{
                Etag next;
                while (etagTouches.TryGetValue(etag, out next))
                {
                    etag = next;
                }

				if (existingEtag != etag)
				{
					if (etag == Etag.Empty)
					{
						if (metadata.Metadata.ContainsKey(Constants.RavenDeleteMarker) &&
							metadata.Metadata.Value<bool>(Constants.RavenDeleteMarker))
						{
							return existingEtag;
						}
					}

					throw new ConcurrencyException(method + " attempted on document '" + key +
												   "' using a non current etag")
					{
						ActualETag = existingEtag,
						ExpectedETag = etag
					};
				}
			}

			return existingEtag;
		}

		//returns true if it was update operation
		private bool WriteDocumentMetadata(JsonDocumentMetadata metadata,bool shouldIgnoreConcurrencyExceptions = false)
		{
            var metadataStream = CreateStream();

			metadataStream.Write(metadata.Etag);
			metadataStream.Write(metadata.Key);

			if (metadata.LastModified.HasValue)
				metadataStream.Write(metadata.LastModified.Value.ToBinary());
			else
				metadataStream.Write((long)0);

			metadata.Metadata.WriteTo(metadataStream);

			metadataStream.Position = 0;

			var loweredKey = CreateKey(metadata.Key);

			ushort? existingVersion;
			var isUpdate = metadataIndex.Contains(Snapshot, loweredKey, writeBatch.Value, out existingVersion);
			metadataIndex.Add(writeBatch.Value, loweredKey, metadataStream, existingVersion, shouldIgnoreConcurrencyExceptions);

			return isUpdate;
		}

		private JsonDocumentMetadata ReadDocumentMetadata(string key)
		{
			var loweredKey = CreateKey(key);

			var metadataReadResult = metadataIndex.Read(Snapshot, loweredKey, writeBatch.Value);
			if (metadataReadResult == null)
				return null;

			using (var stream = metadataReadResult.Reader.AsStream())
			{
				stream.Position = 0;
				var etag = stream.ReadEtag();
				var originalKey = stream.ReadString();
				var lastModifiedDateTimeBinary = stream.ReadInt64();

				var existingCachedDocument = documentCacher.GetCachedDocument(loweredKey, etag);

				var metadata = existingCachedDocument != null ? existingCachedDocument.Metadata : stream.ToJObject();
			    var lastModified = DateTime.FromBinary(lastModifiedDateTimeBinary);

				return new JsonDocumentMetadata
				{
					Key = originalKey,
					Etag = etag,
					Metadata = metadata,
					LastModified = lastModified
				};
			}
		}

		private bool WriteDocumentData(string key, Etag etag, RavenJObject data, RavenJObject metadata, out Etag newEtag, out Etag existingEtag, out DateTime savedAt)
		{
			var keyByEtagDocumentIndex = tableStorage.Documents.GetIndex(Tables.Documents.Indices.KeyByEtag);
			var loweredKey = CreateKey(key);

			ushort? existingVersion;
			var isUpdate = tableStorage.Documents.Contains(Snapshot, loweredKey, writeBatch.Value, out existingVersion);
			existingEtag = null;

			if (isUpdate)
			{
				existingEtag = EnsureDocumentEtagMatch(loweredKey, etag, "PUT");
				keyByEtagDocumentIndex.Delete(writeBatch.Value, existingEtag);
			}
			else if (etag != null && etag != Etag.Empty)
			{
				throw new ConcurrencyException("PUT attempted on document '" + key +
													   "' using a non current etag (document deleted)")
				{
					ExpectedETag = etag
				};
			}

            var dataStream = CreateStream();

			using (var finalDataStream = documentCodecs.Aggregate((Stream) new UndisposableStream(dataStream),
				(current, codec) => codec.Encode(loweredKey, data, metadata, current)))
			{
				data.WriteTo(finalDataStream);
				finalDataStream.Flush();
			}
 
			dataStream.Position = 0;
			tableStorage.Documents.Add(writeBatch.Value, loweredKey, dataStream, existingVersion ?? 0); 

			newEtag = uuidGenerator.CreateSequentialUuid(UuidType.Documents);
			savedAt = SystemTime.UtcNow;

			var isUpdated = PutDocumentMetadataInternal(key, metadata, newEtag, savedAt);

			keyByEtagDocumentIndex.Add(writeBatch.Value, newEtag, loweredKey);

			return isUpdated;
		}

		private RavenJObject ReadDocumentData(string key, Etag existingEtag, RavenJObject metadata)
		{
			var loweredKey = CreateKey(key);

			var existingCachedDocument = documentCacher.GetCachedDocument(loweredKey, existingEtag);
			if (existingCachedDocument != null)
				return existingCachedDocument.Document;

			var documentReadResult = tableStorage.Documents.Read(Snapshot, loweredKey, writeBatch.Value);
			if (documentReadResult == null) //non existing document
				return null;

			using (var stream = documentReadResult.Reader.AsStream())
			{
				using (var decodedDocumentStream = documentCodecs.Aggregate(stream,
						(current, codec) => codec.Value.Decode(loweredKey, metadata, current)))
				{
					var documentData = decodedDocumentStream.ToJObject();

					documentCacher.SetCachedDocument(loweredKey, existingEtag, documentData, metadata, (int)stream.Length);

					return documentData;	
				}
			}
		}

		public DebugDocumentStats GetDocumentStatsVerySlowly()
		{
			var sp = Stopwatch.StartNew();
			var stat = new DebugDocumentStats { Total = GetDocumentsCount() };

			var documentsByEtag = tableStorage.Documents.GetIndex(Tables.Documents.Indices.KeyByEtag);
			using (var iterator = documentsByEtag.Iterate(Snapshot, writeBatch.Value))
			{
				if (!iterator.Seek(Slice.BeforeAllKeys))
				{
					stat.TimeToGenerate = sp.Elapsed;
					return stat;
				}

				do
				{
					var key = GetKeyFromCurrent(iterator);
                    var doc = DocumentByKey(key, null);
                    var size = doc.SerializedSizeOnDisk;
				    stat.TotalSize += size;
				    if (key.StartsWith("Raven/", StringComparison.OrdinalIgnoreCase))
				    {
                        stat.System++;
				        stat.SystemSize += size;
				    }
						

					var metadata = ReadDocumentMetadata(key);

					var entityName = metadata.Metadata.Value<string>(Constants.RavenEntityName);
				    if (string.IsNullOrEmpty(entityName))
				    {
                        stat.NoCollection++;
				        stat.NoCollectionSize += size;
				    }
				        
				    else
				    {
  
                        stat.IncrementCollection(entityName, size);
 				    }
						

					if (metadata.Metadata.ContainsKey(Constants.RavenDeleteMarker))
						stat.Tombstones++;

				}
				while (iterator.MoveNext());
                var sortedStat = stat.Collections.OrderByDescending(x => x.Value.Size).ToDictionary(x => x.Key, x => x.Value);
                stat.TimeToGenerate = sp.Elapsed;
			    stat.Collections = sortedStat;
                return stat;
			}
		}
	}
}
Back to Top