Repository navigation
Expand file tree
/
Copy pathRavenEmbeddedPersistenceLifecycle.cs
More file actions
84 lines (70 loc) · 2.99 KB
/
Copy pathRavenEmbeddedPersistenceLifecycle.cs
File metadata and controls
84 lines (70 loc) · 2.99 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
#nullable enable
namespace ServiceControl.Audit.Persistence.RavenDB
{
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Raven.Client.Documents;
using Raven.Client.Exceptions.Database;
using ServiceControl.RavenDB;
sealed class RavenEmbeddedPersistenceLifecycle(DatabaseConfiguration databaseConfiguration, IHostApplicationLifetime lifetime, ILogger<RavenEmbeddedPersistenceLifecycle> logger) : IRavenPersistenceLifecycle, IRavenDocumentStoreProvider, IDisposable
{
public async ValueTask<IDocumentStore> GetDocumentStore(CancellationToken cancellationToken = default)
{
if (documentStore != null)
{
return documentStore;
}
try
{
await initializeSemaphore.WaitAsync(cancellationToken);
return documentStore ?? throw new InvalidOperationException("Document store is not available. Ensure `IRavenPersistenceLifecycle.Initialize` is invoked");
}
finally
{
initializeSemaphore.Release();
}
}
public async Task Initialize(CancellationToken cancellationToken = default)
{
try
{
await initializeSemaphore.WaitAsync(cancellationToken);
var serverConfig = databaseConfiguration.ServerConfiguration;
var embeddedConfig = new EmbeddedDatabaseConfiguration(serverConfig.ServerUrl, databaseConfiguration.Name, serverConfig.DbPath, serverConfig.LogPath, serverConfig.LogsMinLevel);
database = EmbeddedDatabase.Start(embeddedConfig, lifetime);
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
documentStore = await database.Connect(cancellationToken);
var databaseSetup = new DatabaseSetup(databaseConfiguration);
await databaseSetup.Execute(documentStore, cancellationToken);
return;
}
catch (DatabaseLoadTimeoutException e)
{
logger.LogWarning(e, "Connecting to the embedded RavenDB database timed out. Retrying in 500ms...");
await Task.Delay(500, cancellationToken);
}
}
}
finally
{
initializeSemaphore.Release();
}
}
public Task Stop(CancellationToken cancellationToken = default) => database!.Stop(cancellationToken);
public void Dispose()
{
documentStore?.Dispose();
database?.Dispose();
}
IDocumentStore? documentStore;
EmbeddedDatabase? database;
readonly SemaphoreSlim initializeSemaphore = new(1, 1);
}
}