try improve sensitive error handling

This commit is contained in:
2025-02-03 14:43:51 +01:00
parent 49b5ebddb1
commit 9ff34c44b2

View File

@@ -60,26 +60,34 @@ public class ApiServer(string apiUrl) : IApiServer
} }
public virtual void Stop() public virtual void Stop()
{
Stop(true);
}
public virtual void Stop(bool graceful)
{ {
Log.Info("Stopping listener"); Log.Info("Stopping listener");
doListen = false; doListen = false;
httpListener.Stop(); if (graceful)
httpListener.Stop();
else
httpListener.Abort();
Thread.Sleep(StopDelay); Thread.Sleep(StopDelay);
httpListener.Close(); httpListener.Close();
Log.Info("Stopped listener"); Log.Info("Stopped listener");
} }
public virtual void Restart() public virtual void Restart(bool graceful)
{ {
Log.Info("Restarting listener"); Log.Info("Restarting listener");
Stop(); Stop(graceful);
httpListener = new(); httpListener = new();
semaphore?.Release(int.MaxValue); semaphore?.Release(int.MaxValue);
Start(); Start();
Log.Info("Restarted listener"); Log.Info("Restarted listener");
} }
protected virtual bool AutoRestart() protected virtual bool AutoRestart(bool graceful)
{ {
if (restartAttempts > MaxAutoRestartsPerMinute) if (restartAttempts > MaxAutoRestartsPerMinute)
{ {
@@ -94,7 +102,7 @@ public class ApiServer(string apiUrl) : IApiServer
restartAttempts += 1; restartAttempts += 1;
Restart(); Restart(graceful);
return true; return true;
} }
@@ -192,6 +200,10 @@ public class ApiServer(string apiUrl) : IApiServer
{ {
WaitForSlot(); WaitForSlot();
} }
catch (ObjectDisposedException)
{
return;
}
catch (Exception ex) catch (Exception ex)
{ {
Log.Fatal($"Too many concurent connections", ex); Log.Fatal($"Too many concurent connections", ex);
@@ -205,16 +217,17 @@ public class ApiServer(string apiUrl) : IApiServer
{ {
context = httpListener.EndGetContext(result); context = httpListener.EndGetContext(result);
} }
catch (ObjectDisposedException)
{
return;
}
catch (HttpListenerException ex) catch (HttpListenerException ex)
{ {
if (ex.ErrorCode == 995 || ex.ErrorCode == 64) if (ex.ErrorCode == 995 || ex.ErrorCode == 64)
{ {
Log.Fatal($"Fatal http error retriving context with code {ex.ErrorCode}", ex); Log.Fatal($"Fatal http error retriving context with code {ex.ErrorCode}", ex);
if (AutoRestart()) // Try restart the server and skip this context if (AutoRestart(false)) // Try restart the server and skip this context
{
FreeSlot();
return; return;
}
} }
else else
Log.Error($"Http error retriving context with code {ex.ErrorCode}", ex); Log.Error($"Http error retriving context with code {ex.ErrorCode}", ex);
@@ -255,9 +268,6 @@ public class ApiServer(string apiUrl) : IApiServer
OnCheckContextCompleted?.Invoke(this, new(context)); OnCheckContextCompleted?.Invoke(this, new(context));
} }
// Release slot
FreeSlot();
// Listen for new request // Listen for new request
if (!AllowMultipleRequests) if (!AllowMultipleRequests)
{ {