@@ -34,7 +34,7 @@ public CookieTracker(IConfiguration configuration, ILogger<CookieTracker> logger
3434 _timer = new PeriodicTimer ( TimeSpan . FromSeconds ( configuration . GetValue ( "CookieTracker:Period" , 30 ) ) ) ;
3535
3636 _databaseConnection = NpgsqlDataSource . Create ( CookieDatabaseContext . GetConnectionString ( configuration ) ) . CreateConnection ( ) ;
37- _databaseConnection . Open ( ) ;
37+ _databaseConnection . StateChange += InitConnection ;
3838 _databaseCommands = new Dictionary < DatabaseOperation , NpgsqlCommand >
3939 {
4040 [ DatabaseOperation . Create ] = GetInsertCommand ( _databaseConnection ) ,
@@ -87,12 +87,9 @@ public ulong Click(Ulid cookieId)
8787
8888 private async Task StartBakingAsync ( )
8989 {
90+ InitConnection ( null , new StateChangeEventArgs ( ConnectionState . Closed , ConnectionState . Closed ) ) ;
9091 DbCommand createCommand = _databaseCommands [ DatabaseOperation . Create ] ;
9192 DbCommand updateCommand = _databaseCommands [ DatabaseOperation . Update ] ;
92- foreach ( DbCommand command in _databaseCommands . Values )
93- {
94- await command . PrepareAsync ( ) ;
95- }
9693
9794 while ( await _timer . WaitForNextTickAsync ( ) )
9895 {
@@ -172,6 +169,28 @@ public async ValueTask DisposeAsync()
172169 _semaphore . Dispose ( ) ;
173170 }
174171
172+ private void InitConnection ( object ? sender , StateChangeEventArgs eventArgs )
173+ {
174+ if ( eventArgs . CurrentState is not ConnectionState . Closed and not ConnectionState . Broken )
175+ {
176+ return ;
177+ }
178+
179+ _semaphore . Wait ( ) ;
180+ try
181+ {
182+ _databaseConnection . Open ( ) ;
183+ foreach ( DbCommand command in _databaseCommands . Values )
184+ {
185+ command . Prepare ( ) ;
186+ }
187+ }
188+ finally
189+ {
190+ _semaphore . Release ( ) ;
191+ }
192+ }
193+
175194 private static NpgsqlCommand GetSelectCommand ( NpgsqlConnection connection )
176195 {
177196 NpgsqlCommand command = connection . CreateCommand ( ) ;
0 commit comments