/
PersistedEventsStorage.cs
632 lines (553 loc) · 16 KB
/
PersistedEventsStorage.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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Net.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Linq;
using System.Linq;
using Raven.Abstractions.Logging;
using Rhino.Events.Data;
using Rhino.Events.Impl;
namespace Rhino.Events.Storage
{
public class PersistedEventsStorage : IDisposable
{
private static readonly ILog log = LogManager.GetCurrentClassLogger();
private readonly PersistedOptions options;
private const long DoesNotExists = -1;
private const long Deleted = -2;
private readonly IStreamSource streamSource;
private readonly string dataPath = "data.events";
private readonly string offsetsPath = "data.offsets";
private readonly Task writerTask;
private readonly ManualResetEventSlim hasItems = new ManualResetEventSlim(false);
private readonly ConcurrentQueue<WriteState> itemsToWrite = new ConcurrentQueue<WriteState>();
private readonly CancellationTokenSource cts = new CancellationTokenSource();
private readonly JsonDataCache<PersistedEvent> cache;
private readonly ReaderWriterLockSlim compactionLock = new ReaderWriterLockSlim();
private readonly ConcurrentDictionary<string, StreamInformation> idToPos = new ConcurrentDictionary<string, StreamInformation>(StringComparer.InvariantCultureIgnoreCase);
private readonly ConcurrentQueue<Stream> cachedReadStreams = new ConcurrentQueue<Stream>();
private BinaryWriter binaryWriter;
private Stream file;
private long lastWriteSnapshotCount;
private DateTime lastWriteSnapshotTime;
private long eventsCount;
private long deleteCount;
private DateTime lastWrite;
bool hadWrites;
private volatile bool disposed;
private volatile Exception corruptingException;
private class WriteState : PersistedEvent
{
public readonly TaskCompletionSource<object> TaskCompletionSource = new TaskCompletionSource<object>();
}
public PersistedEventsStorage(PersistedOptions options)
{
cache = new JsonDataCache<PersistedEvent>(options);
this.options = options;
streamSource = options.StreamSource;
file = streamSource.OpenReadWrite(dataPath);
ReadAllFromDisk();
binaryWriter = new BinaryWriter(file, Encoding.UTF8, leaveOpen: true);
writerTask = Task.Factory.StartNew(() =>
{
try
{
WriteToDisk();
}
catch (Exception e)
{
corruptingException = e;
}
});
}
private void ReadAllFromDisk()
{
file.Position = ReadOffsets(Path.GetFileName(streamSource.GetLatestName(dataPath)));
while (true)
{
using (var reader = new BinaryReader(file, Encoding.UTF8, leaveOpen: true))
{
var itemPos = file.Position;
PersistedEvent persistedEvent;
try
{
persistedEvent = ReadPersistedEvent(reader);
eventsCount++;
}
catch (EndOfStreamException)
{
lastWriteSnapshotCount = eventsCount;
lastWriteSnapshotTime = DateTime.UtcNow;
return;
}
catch (Exception e)
{
log.WarnException("Error during initial events read, file corrupted", e);
if (options.AllowRecovery == false)
throw;
file.SetLength(itemPos);
log.Warn("Recovered from corrupted file by truncating file to last known good position: " + itemPos);
return;
}
switch (persistedEvent.State)
{
case EventState.Event:
case EventState.Snapshot:
idToPos.AddOrUpdate(persistedEvent.Id, s => new StreamInformation
{
LastPosition = itemPos,
StreamLength = 1
}, (s, information) => new StreamInformation
{
LastPosition = itemPos,
StreamLength = information.StreamLength + 1
});
break;
case EventState.Delete:
deleteCount++;
var streamInformation = new StreamInformation
{
LastPosition = Deleted,
StreamLength = 0
};
idToPos.AddOrUpdate(persistedEvent.Id, s => streamInformation, (s, information) =>
{
deleteCount += information.StreamLength;
return streamInformation;
});
break;
default:
throw new ArgumentOutOfRangeException(persistedEvent.State.ToString());
}
}
}
}
public IEnumerable<EventData> Read(string id)
{
AssertValidState();
StreamInformation previous;
Stream stream;
compactionLock.EnterReadLock();
try
{
if (idToPos.TryGetValue(id, out previous) == false)
return null;
if(cachedReadStreams.TryDequeue(out stream) == false)
{
stream = streamSource.OpenRead(dataPath);
}
}
finally
{
compactionLock.ExitReadLock();
}
return ReadInternal(stream, previous.LastPosition).Select(x => new EventData
{
Data = x.Data,
State = x.State,
Metadata = x.Metadata
});
}
private void AssertValidState()
{
var exception = corruptingException;
if (exception != null)
throw new InvalidOperationException("Instance state corrupted, can't read", exception);
if (disposed)
throw new ObjectDisposedException("PersistedEventsStorage");
}
private IEnumerable<PersistedEvent> ReadInternal(Stream stream, long previous)
{
try
{
foreach (var p in ReadFromCache(previous))
{
previous = p.Previous;
yield return p;
}
using (var reader = new BinaryReader(stream, leaveOpen: true, encoding: Encoding.UTF8))
{
while (true)
{
foreach (var p in ReadFromCache(previous))
{
previous = p.Previous;
yield return p;
}
if (previous == DoesNotExists || previous == Deleted)
yield break;
var itemPos = previous;
stream.Position = previous;
var persistedEvent = ReadPersistedEvent(reader);
previous = persistedEvent.Previous;
cache.Set(itemPos, persistedEvent);
yield return persistedEvent;
}
}
}
finally
{
cachedReadStreams.Enqueue(stream);
}
}
private static void WriteItem(PersistedEvent item, BinaryWriter binaryWriter)
{
binaryWriter.Write(item.Id);
binaryWriter.Write(item.Previous);
binaryWriter.Write(item.StreamLength);
binaryWriter.Write((int)item.State);
item.Metadata.WriteTo(new BsonWriter(binaryWriter));
item.Data.WriteTo(new BsonWriter(binaryWriter));
}
private static PersistedEvent ReadPersistedEvent(BinaryReader reader)
{
var id = reader.ReadString();
long previous = reader.ReadInt64();
var len = reader.ReadInt32();
var state = (EventState)reader.ReadInt32();
var metadata = (JObject)JToken.ReadFrom(new BsonReader(reader));
var data = (JObject)JToken.ReadFrom(new BsonReader(reader));
return new PersistedEvent
{
Id = id,
Data = data,
Metadata = metadata,
Previous = previous,
State = state,
StreamLength = len
};
}
private IEnumerable<PersistedEvent> ReadFromCache(long previous)
{
if (previous == DoesNotExists || previous == Deleted)
yield break;
var persistedEvent = cache.Get(previous);
while (persistedEvent != null)
{
if (previous == DoesNotExists || previous == Deleted)
yield break;
previous = persistedEvent.Previous;
yield return persistedEvent;
persistedEvent = cache.Get(previous);
}
}
private void WriteToDisk()
{
var tasksToNotify = new List<Action<Exception>>();
while (true)
{
if (cts.IsCancellationRequested)
{
FlushToDisk(tasksToNotify, closing: true);
return;
}
WriteState item;
if (hadWrites)
{
if ((DateTime.UtcNow - lastWrite) > options.MaxTimeToWaitForFlush)
{
// we have to flush to disk now, because we have writes and nothing else is forthcoming
// or we have so many writes, that we need to flush to clear the buffers
FlushToDisk(tasksToNotify);
continue;
}
}
if (itemsToWrite.TryDequeue(out item) == false)
{
if (hadWrites)
{
FlushToDisk(tasksToNotify);
}
else
{
if (deleteCount > (eventsCount / 4)) // we have > 25% wasted space
{
// we waited enough time to be pretty sure we are idle
// and can run compaction without too much problems.
if (hasItems.Wait(options.IdleTime, cts.Token) == false)
{
Compact();
continue;
}
}
else
{
hasItems.Wait(cts.Token);
}
hasItems.Reset();
}
continue;
}
StreamInformation info;
idToPos.TryGetValue(item.Id, out info);
var prevPos = info == null ? DoesNotExists : info.LastPosition;
var currentPos = file.Position;
var persistedEvent = new PersistedEvent
{
Id = item.Id,
Data = item.Data,
State = item.State,
Previous = prevPos,
Metadata = item.Metadata
};
WriteItem(persistedEvent, binaryWriter);
var action = CreateCompletionAction(tasksToNotify, item, currentPos);
tasksToNotify.Add(action);
hadWrites = true;
}
}
public void Compact()
{
var newPositions = new Dictionary<string, StreamInformation>(StringComparer.InvariantCultureIgnoreCase);
var newFilePath = dataPath + ".compacting";
streamSource.DeleteIfExists(newFilePath);
using (var newFile = streamSource.OpenReadWrite(newFilePath))
using (var newWriter = new BinaryWriter(newFile))
using (var current = streamSource.OpenRead(dataPath))
using (var reader = new BinaryReader(current))
{
while (true)
{
PersistedEvent persistedEvent;
try
{
persistedEvent = ReadPersistedEvent(reader);
}
catch (EndOfStreamException)
{
break;
}
StreamInformation value;
if (idToPos.TryGetValue(persistedEvent.Id, out value) == false)
continue;
if (value.LastPosition == Deleted || value.LastPosition == DoesNotExists)
continue;
StreamInformation information;
if (newPositions.TryGetValue(persistedEvent.Id, out information) == false)
{
information =new StreamInformation
{
LastPosition = DoesNotExists,
StreamLength = 0
};
}
persistedEvent.Previous = information.LastPosition;
newPositions[persistedEvent.Id] = new StreamInformation
{
LastPosition = newFile.Position,
StreamLength = persistedEvent.StreamLength
};
WriteItem(persistedEvent, newWriter);
}
streamSource.Flush(newFile);
compactionLock.EnterWriteLock();
try
{
newFile.Close();
streamSource.DeleteOnClose(dataPath);
Stream result;
while (cachedReadStreams.TryDequeue(out result))
{
result.Dispose();
}
binaryWriter.Dispose();
file.Dispose();
streamSource.RenameToLatest(newFilePath, dataPath);
file = streamSource.OpenReadWrite(dataPath);
binaryWriter = new BinaryWriter(file, Encoding.UTF8, leaveOpen: true);
streamSource.DeleteIfExists("data.offsets");
FlushOffsets();
idToPos.Clear();
foreach (var val in newPositions)
{
idToPos[val.Key] = val.Value;
}
}
finally
{
compactionLock.ExitWriteLock();
}
}
}
public long DeleteCount
{
get { return deleteCount; }
}
public long EventsCount
{
get { return eventsCount; }
}
private Action<Exception> CreateCompletionAction(List<Action<Exception>> tasksToNotify, WriteState item, long currentPos)
{
return exception =>
{
if (exception == null)
{
HandleFlushSuccessful(item, currentPos);
}
else
{
item.TaskCompletionSource.SetException(exception);
}
};
}
private void HandleFlushSuccessful(WriteState item, long currentPos)
{
switch (item.State)
{
case EventState.Event:
case EventState.Snapshot:
idToPos.AddOrUpdate(item.Id, s => new StreamInformation
{
LastPosition = currentPos,
StreamLength = 1
}, (s, l) => new StreamInformation
{
LastPosition = currentPos,
StreamLength = l.StreamLength + 1
});
break;
case EventState.Delete:
var streamInformation = new StreamInformation
{
LastPosition = Deleted,
StreamLength = 0
};
idToPos.AddOrUpdate(item.Id, s => streamInformation, (s, l) =>
{
deleteCount += l.StreamLength;
return streamInformation;
});
break;
default:
throw new ArgumentOutOfRangeException(item.State.ToString());
}
item.TaskCompletionSource.SetResult(null);
}
private void FlushToDisk(ICollection<Action<Exception>> tasksToNotify, bool closing = false)
{
try
{
streamSource.Flush(file);
eventsCount += tasksToNotify.Count;
foreach (var taskCompletionSource in tasksToNotify)
{
taskCompletionSource(null);
}
}
catch (Exception e)
{
foreach (var taskCompletionSource in tasksToNotify)
{
taskCompletionSource(e);
}
throw;
}
finally
{
tasksToNotify.Clear();
lastWrite = DateTime.UtcNow;
hadWrites = false;
}
if (closing ||
(eventsCount - lastWriteSnapshotCount) > options.WritesBetweenOffsetSnapshots ||
(eventsCount > lastWriteSnapshotCount) && (DateTime.UtcNow - lastWriteSnapshotTime) > options.MinTimeForOffsetSnapshots)
{
FlushOffsets();
}
}
private long ReadOffsets(string currentFileName)
{
long position;
if (streamSource.Exists(offsetsPath) == false)
return 0;
using (var offsets = streamSource.OpenRead(offsetsPath))
using(var reader = new BinaryReader(offsets))
{
var fileName = reader.ReadString();
if(fileName != currentFileName)
{
// wrong file, skipping
streamSource.DeleteOnClose(offsetsPath);
return 0;
}
position = reader.ReadInt64();
while (true)
{
string key;
try
{
key = reader.ReadString();
}
catch (EndOfStreamException)
{
break;
}
var pos = reader.ReadInt64();
var count = reader.ReadInt32();
idToPos[key] = new StreamInformation
{
LastPosition = pos,
StreamLength = count
};
}
}
return position;
}
private void FlushOffsets()
{
lastWriteSnapshotCount = eventsCount;
lastWriteSnapshotTime = DateTime.UtcNow;
using(var offsets = streamSource.OpenReadWrite( offsetsPath + ".new"))
using(var writer = new BinaryWriter(offsets))
{
writer.Write(Path.GetFileName(streamSource.GetLatestName(dataPath)));
writer.Write(file.Position);
foreach (var streamInformation in idToPos)
{
writer.Write(streamInformation.Key);
writer.Write(streamInformation.Value.LastPosition);
writer.Write(streamInformation.Value.StreamLength);
}
writer.Flush();
}
streamSource.DeleteOnClose(offsetsPath);
streamSource.RenameToLatest(offsetsPath + ".new", offsetsPath);
}
public Task EnqueueAsync(string id, EventState state, JObject data, JObject metadata)
{
AssertValidState();
var item = new WriteState
{
Data = data,
State = state,
Metadata = metadata,
Id = id
};
itemsToWrite.Enqueue(item);
hasItems.Set();
return item.TaskCompletionSource.Task;
}
public void Dispose()
{
var e = new ExceptionAggregator();
e.Execute(cts.Cancel);
e.Execute(writerTask.Wait);
e.Execute(binaryWriter.Dispose);
e.Execute(file.Dispose);
e.Execute(cache.Dispose);
e.Execute(hasItems.Dispose);
foreach (var cachedReadStream in cachedReadStreams)
{
e.Execute(cachedReadStream.Dispose);
}
e.ThrowIfNeeded();
disposed = true;
}
}
}