-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathRavenEmbeddedPersistenceLifecycle.cs
More file actions
89 lines (74 loc) · 3.1 KB
/
RavenEmbeddedPersistenceLifecycle.cs
File metadata and controls
89 lines (74 loc) · 3.1 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
#nullable enable
namespace ServiceControl.Audit.Persistence.RavenDB
{
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using NServiceBus.Logging;
using Raven.Client.Documents;
using Raven.Client.Exceptions.Database;
using ServiceControl.RavenDB;
sealed class RavenEmbeddedPersistenceLifecycle(DatabaseConfiguration databaseConfiguration, IHostApplicationLifetime lifetime) : 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.LogsMode)
{
FindClrType = databaseConfiguration.FindClrType
};
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)
{
Log.Warn("Could not connect to database. Retrying in 500ms...", e);
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);
static readonly ILog Log = LogManager.GetLogger(typeof(RavenEmbeddedPersistenceLifecycle));
}
}