diff --git a/Pilz.Net/Api/ApiServer.cs b/Pilz.Net/Api/ApiServer.cs index 7eda029..d7de09a 100644 --- a/Pilz.Net/Api/ApiServer.cs +++ b/Pilz.Net/Api/ApiServer.cs @@ -18,6 +18,7 @@ public class ApiServer(string apiUrl) : IApiServer protected DateTime lastRestartAttempt; protected SemaphoreSlim? semaphore; protected bool doListen; + protected bool isAutoRestarting; public event OnCheckAuthenticationEventHandler? OnCheckAuthentication; public event OnCheckContextEventHandler? OnCheckContext; @@ -89,10 +90,13 @@ public class ApiServer(string apiUrl) : IApiServer protected virtual bool AutoRestart(bool graceful) { + if (isAutoRestarting) + return true; + if (restartAttempts > MaxAutoRestartsPerMinute) { Log.Fatal("Reached maximum auto-restart attempts"); - Stop(); + Stop(false); return false; } @@ -102,7 +106,9 @@ public class ApiServer(string apiUrl) : IApiServer restartAttempts += 1; + isAutoRestarting = true; Restart(graceful); + isAutoRestarting = false; return true; } @@ -253,9 +259,11 @@ public class ApiServer(string apiUrl) : IApiServer // Check context Log.Info("Request retrived for " + context.Request.RawUrl); OnCheckContext?.Invoke(this, new(context)); + var success = false; try { CheckContext(context); + success = true; } catch (Exception ex) { @@ -268,12 +276,23 @@ public class ApiServer(string apiUrl) : IApiServer OnCheckContextCompleted?.Invoke(this, new(context)); } + // Try closing the request on fail + if (!success) + { + try + { + context.Response.Close(); + } + catch (Exception) + { + } + } + + FreeSlot(); + // Listen for new request if (!AllowMultipleRequests) - { - FreeSlot(); Receive(); - } } protected virtual void CheckContext(HttpListenerContext context)