-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathJsonIndexManagerTest.cs
211 lines (183 loc) · 7.01 KB
/
JsonIndexManagerTest.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
using System.Diagnostics;
using System.Reactive.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using Bogus;
using DotJEM.AdvParsers;
using DotJEM.Json.Index2.Documents.Fields;
using DotJEM.Json.Index2.Management.Info;
using DotJEM.Json.Index2.Management.Observables;
using DotJEM.Json.Index2.Management.Snapshots;
using DotJEM.Json.Index2.Management.Snapshots.Zip;
using DotJEM.Json.Index2.Management.Source;
using DotJEM.Json.Index2.Snapshots;
using DotJEM.ObservableExtensions.InfoStreams;
using DotJEM.Web.Scheduler;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
namespace DotJEM.Json.Index2.Management.Test;
[TestFixture]
public class JsonIndexManagerTest
{
[Test, Explicit]
public async Task IndexWriterShouldNotBeDisposed()
{
using TestDirectory dir = new();
IJsonIndex index = new JsonIndexBuilder("Test")
.UsingSimpleFileStorage(dir.Info.CreateSubdirectory("index").FullName)
.WithFieldResolver(new FieldResolver("id", "type"))
.WithSnapshoting()
.Build();
IJsonDocumentSource source = new DummyDocumentSource();
IWebTaskScheduler scheduler = new WebTaskScheduler();
ISnapshotStrategy strategy = new ZipSnapshotStrategy(dir.Info.CreateSubdirectory("snapshot").FullName);
IJsonIndexSnapshotManager snapshots = new JsonIndexSnapshotManager(index, strategy, scheduler, "60h");
IJsonIndexManager manager = new JsonIndexManager(source, snapshots, index);
InfoStreamExceptionEvent? disposedEvent = null;
InfoStreamExceptionEvent? exceptionEvent = null;
manager.InfoStream
.OfType<InfoStreamExceptionEvent>()
.Where(@event => @event.Exception is ObjectDisposedException)
.Subscribe(@event =>
{
disposedEvent = @event;
});
manager.InfoStream
.OfType<InfoStreamExceptionEvent>()
.Where(@event => @event.Exception.Message != "Can't write to an existing snapshot.")
.Subscribe(@event =>
{
exceptionEvent = @event;
});
try
{
await manager.RunAsync();
Debug.WriteLine("TEST STARTED");
Stopwatch sw = Stopwatch.StartNew();
while (sw.Elapsed < 10.Minutes() && disposedEvent == null && exceptionEvent == null)
{
Task result = Random.Shared.Next(100) switch
{
(>= 0 and <= 50) => DoAfterDelay(manager.TakeSnapshotAsync, 1.Seconds()),
(> 50 and <= 100) => DoAfterDelay(manager.ResetIndexAsync, 1.Seconds()),
_ => Task.CompletedTask
};
await result;
}
async Task DoAfterDelay(Func<Task> action, TimeSpan? delay = null)
{
await Task.Delay(delay ?? Random.Shared.Next(1, 5).Seconds());
await action();
}
await manager.StopAsync();
}
catch (TaskCanceledException)
{
//Ignore.
}
finally
{
index.Close();
}
Assert.That(disposedEvent, Is.Null, () => disposedEvent?.Exception.ToString());
Assert.That(exceptionEvent, Is.Null, () => exceptionEvent?.Exception.ToString());
}
}
public class TestDirectory : IDisposable
{
public DirectoryInfo Info { get; }
public TestDirectory()
{
Info = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), $"TEST-{Guid.NewGuid():N}"));
Debug.WriteLine("TEST DIR: " + Info.FullName);
}
public void Dispose()
{
try
{
Info.Delete(true);
}
catch (Exception e)
{
}
}
~TestDirectory()
{
Dispose();
}
}
public class DummyDocumentSource : IJsonDocumentSource
{
private readonly DocumentChangesStream observable = new();
private readonly InfoStream<DummyDocumentSource> infoStream = new();
public IObservable<IJsonDocumentSourceEvent> DocumentChanges => observable;
public IObservableValue<bool> Initialized { get; } = new ObservableValue<bool>();
public IInfoStream InfoStream => infoStream;
private Faker faker = new Faker("en");
private long gen;
private Task? runningTask;
private CancellationTokenSource cancellationTokenSource = new ();
private readonly string area = "Test";
public async Task StartAsync()
{
infoStream.WriteJsonSourceEvent(JsonSourceEventType.Starting, area, $"Ingest starting for storageArea '{area}'.");
runningTask = Task.Run(async () =>
{
while (gen < 1_000_000 && !cancellationTokenSource.IsCancellationRequested)
{
if (!Initialized.Value)
{
infoStream.WriteJsonSourceEvent(JsonSourceEventType.Initializing, area, $"Initializing for storageArea '{area}'.");
RunLoop();
Initialized.Value = true;
infoStream.WriteJsonSourceEvent(JsonSourceEventType.Initialized, area, $"Initializing for storageArea '{area}'.");
}
else
{
infoStream.WriteJsonSourceEvent(JsonSourceEventType.Updating, area, $"Checking updates for storageArea '{area}'.");
RunLoop();
infoStream.WriteJsonSourceEvent(JsonSourceEventType.Updated, area, $"Done checking updates for storageArea '{area}'.");
}
observable.Publish(new JsonDocumentSourceDigestCompleted(area));
await Task.Delay(Random.Shared.Next(50, 250));
}
}, cancellationTokenSource.Token);
void RunLoop()
{
foreach (JObject json in Enumerable.Repeat(0, Random.Shared.Next(1, 100))
.Select(_ => Guid.NewGuid())
.Select(id => new
{
id,
type = "Test",
area,
time = DateTime.Now,
user = new
{
name = faker.Name.FirstName()
}
})
.Select(JObject.FromObject))
{
observable.Publish(new JsonDocumentCreated(area, json, 10, new GenerationInfo(gen++, 1_000_000)));
}
}
}
public async Task StopAsync()
{
cancellationTokenSource.Cancel();
if(runningTask != null)
await runningTask.ConfigureAwait(false);
runningTask = null;
cancellationTokenSource = new();
infoStream.WriteJsonSourceEvent(JsonSourceEventType.Stopped, area, $"Stopping for storageArea '{area}'.");
}
public void UpdateGeneration(string area, long generation)
{
gen = generation;
}
public async Task ResetAsync()
{
gen = 0;
}
}