Skip to content

Commit

Permalink
Reopen the connection immediately after it's closed
Browse files Browse the repository at this point in the history
  • Loading branch information
OoLunar committed May 5, 2023
1 parent e49479a commit 1b7ae6d
Showing 1 changed file with 24 additions and 5 deletions.
29 changes: 24 additions & 5 deletions src/CookieTracker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public CookieTracker(IConfiguration configuration, ILogger<CookieTracker> logger
_timer = new PeriodicTimer(TimeSpan.FromSeconds(configuration.GetValue("CookieTracker:Period", 30)));

_databaseConnection = NpgsqlDataSource.Create(CookieDatabaseContext.GetConnectionString(configuration)).CreateConnection();
_databaseConnection.Open();
_databaseConnection.StateChange += InitConnection;
_databaseCommands = new Dictionary<DatabaseOperation, NpgsqlCommand>
{
[DatabaseOperation.Create] = GetInsertCommand(_databaseConnection),
Expand Down Expand Up @@ -87,12 +87,9 @@ public ulong Click(Ulid cookieId)

private async Task StartBakingAsync()
{
InitConnection(null, new StateChangeEventArgs(ConnectionState.Closed, ConnectionState.Closed));
DbCommand createCommand = _databaseCommands[DatabaseOperation.Create];
DbCommand updateCommand = _databaseCommands[DatabaseOperation.Update];
foreach (DbCommand command in _databaseCommands.Values)
{
await command.PrepareAsync();
}

while (await _timer.WaitForNextTickAsync())
{
Expand Down Expand Up @@ -172,6 +169,28 @@ public async ValueTask DisposeAsync()
_semaphore.Dispose();
}

private void InitConnection(object? sender, StateChangeEventArgs eventArgs)
{
if (eventArgs.CurrentState is not ConnectionState.Closed and not ConnectionState.Broken)
{
return;
}

_semaphore.Wait();
try
{
_databaseConnection.Open();
foreach (DbCommand command in _databaseCommands.Values)
{
command.Prepare();
}
}
finally
{
_semaphore.Release();
}
}

private static NpgsqlCommand GetSelectCommand(NpgsqlConnection connection)
{
NpgsqlCommand command = connection.CreateCommand();
Expand Down

0 comments on commit 1b7ae6d

Please sign in to comment.