-
Notifications
You must be signed in to change notification settings - Fork 46
/
SharedEmbeddedServer.cs
78 lines (67 loc) · 2.71 KB
/
SharedEmbeddedServer.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
namespace ServiceControl.Audit.Persistence.Tests
{
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using Persistence.RavenDB;
using Raven.Client.ServerWide.Operations;
using TestHelper;
static class SharedEmbeddedServer
{
public static async Task<EmbeddedDatabase> GetInstance(CancellationToken cancellationToken = default)
{
if (embeddedDatabase != null)
{
return embeddedDatabase;
}
await semaphoreSlim.WaitAsync(cancellationToken);
try
{
if (embeddedDatabase != null)
{
return embeddedDatabase;
}
var dbPath = Path.Combine(TestContext.CurrentContext.WorkDirectory, "Tests", "AuditData");
var logPath = Path.Combine(TestContext.CurrentContext.WorkDirectory, "Logs", "Audit");
var logsMode = "Operations";
var serverUrl = $"http://localhost:{PortUtility.FindAvailablePort(33334)}";
embeddedDatabase = EmbeddedDatabase.Start(new DatabaseConfiguration("audit", 60, true, TimeSpan.FromMinutes(5), 120000, 5, 5, new ServerConfiguration(dbPath, serverUrl, logPath, logsMode)));
//make sure that the database is up
using var documentStore = await embeddedDatabase.Connect(cancellationToken);
var cleanupDatabases = new DirectoryInfo(dbPath)
.GetDirectories()
.Select(di => di.Name)
.Where(name => name.Length == 32)
.ToArray();
if (cleanupDatabases.Length > 0)
{
var cleanupOperation = new DeleteDatabasesOperation(new DeleteDatabasesOperation.Parameters { DatabaseNames = cleanupDatabases, HardDelete = true });
await documentStore.Maintenance.Server.SendAsync(cleanupOperation, CancellationToken.None);
}
return embeddedDatabase;
}
finally
{
semaphoreSlim.Release();
}
}
public static async Task Stop(CancellationToken cancellationToken = default)
{
await semaphoreSlim.WaitAsync(cancellationToken);
try
{
embeddedDatabase?.Dispose();
embeddedDatabase = null;
}
finally
{
semaphoreSlim.Release();
}
}
static EmbeddedDatabase embeddedDatabase;
static readonly SemaphoreSlim semaphoreSlim = new(1, 1);
}
}