import threading import time class RequestLifecycleMiddleware: ALLOWED_DURING_SHUTDOWN = { ("GET", "/"), ("HEAD", "/"), ("GET", "/api/status"), ("GET", "/api/gps-test"), ("POST", "/scanner/stop"), ("POST", "/gps-test/stop"), } UNTRACKED_DURING_SHUTDOWN = { ("GET", "/"), ("HEAD", "/"), ("GET", "/api/status"), ("GET", "/api/gps-test"), } STATIC_PREFIXES = ( "/static/", "/reports/static/", ) def __init__(self, application): self.application = application self._condition = threading.Condition() self._shutdown_requested = False self._active_requests = 0 @property def shutdown_requested(self): with self._condition: return self._shutdown_requested @property def active_requests(self): with self._condition: return self._active_requests def begin_shutdown(self): with self._condition: self._shutdown_requested = True self._condition.notify_all() def wait_for_drain(self, timeout=None): deadline = ( None if timeout is None else time.monotonic() + timeout ) with self._condition: while self._active_requests: remaining = ( None if deadline is None else deadline - time.monotonic() ) if remaining is not None and remaining <= 0: return False self._condition.wait(remaining) return True def _is_allowed_during_shutdown(self, method, path): if (method, path) in self.ALLOWED_DURING_SHUTDOWN: return True if method not in ("GET", "HEAD"): return False return any( path.startswith(prefix) for prefix in self.STATIC_PREFIXES ) def _release_request(self): with self._condition: self._active_requests -= 1 self._condition.notify_all() def __call__(self, environ, start_response): method = environ.get("REQUEST_METHOD", "GET").upper() path = environ.get("PATH_INFO", "/") track_request = True with self._condition: if self._shutdown_requested: if not self._is_allowed_during_shutdown( method, path ): body = b"Application is shutting down.\n" start_response( "503 Service Unavailable", [ ("Content-Type", "text/plain; charset=utf-8"), ("Content-Length", str(len(body))), ("Retry-After", "5"), ("Cache-Control", "no-store"), ] ) return [body] if ( (method, path) in self.UNTRACKED_DURING_SHUTDOWN or ( method in ("GET", "HEAD") and any( path.startswith(prefix) for prefix in self.STATIC_PREFIXES ) ) ): track_request = False if track_request: self._active_requests += 1 if not track_request: return self.application( environ, start_response ) try: response = self.application( environ, start_response ) except BaseException: self._release_request() raise return _TrackedIterable( response, self._release_request ) class _TrackedIterable: def __init__(self, iterable, release): self._iterable = iterable self._iterator = iter(iterable) self._release = release self._closed = False def __iter__(self): return self def __next__(self): try: return next(self._iterator) except BaseException: self.close() raise def close(self): if self._closed: return self._closed = True try: close = getattr( self._iterable, "close", None ) if close is not None: close() finally: self._release()