Module directory_server.health

Health check and monitoring HTTP server.

Provides endpoints for health checks and status monitoring.

Classes

class HealthCheckHandler (request, client_address, server)
Expand source code
class HealthCheckHandler(BaseHTTPRequestHandler):
    server_instance: DirectoryServer | None = None

    def log_message(self, format: str, *args: Any) -> None:
        pass

    def do_GET(self) -> None:  # noqa: N802
        if self.path == "/health":
            self._handle_health()
        elif self.path == "/status":
            self._handle_status()
        else:
            self.send_error(404)

    def _handle_health(self) -> None:
        if not self.server_instance:
            self.send_error(503)
            return

        try:
            is_healthy = self.server_instance.is_healthy()
            status_code = 200 if is_healthy else 503

            self.send_response(status_code)
            self.send_header("Content-Type", "application/json")
            self.end_headers()

            response = {"status": "healthy" if is_healthy else "unhealthy"}
            self.wfile.write(json.dumps(response).encode())
        except Exception as e:
            logger.error(f"Health check error: {e}")
            self.send_error(500)

    def _handle_status(self) -> None:
        if not self.server_instance:
            self.send_error(503)
            return

        try:
            stats = self.server_instance.get_detailed_stats()

            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()

            self.wfile.write(json.dumps(stats, default=str).encode())
        except Exception as e:
            logger.error(f"Status check error: {e}")
            self.send_error(500)

HTTP request handler base class.

The following explanation of HTTP serves to guide you through the code as well as to expose any misunderstandings I may have about HTTP (so you don't need to read the code to figure out I'm wrong :-).

HTTP (HyperText Transfer Protocol) is an extensible protocol on top of a reliable stream transport (e.g. TCP/IP). The protocol recognizes three parts to a request:

  1. One line identifying the request type and path
  2. An optional set of RFC-822-style headers
  3. An optional data part

The headers and data are separated by a blank line.

The first line of the request has the form

where is a (case-sensitive) keyword such as GET or POST, is a string containing path information for the request, and should be the string "HTTP/1.0" or "HTTP/1.1". is encoded using the URL encoding scheme (using %xx to signify the ASCII character with hex code xx).

The specification specifies that lines are separated by CRLF but for compatibility with the widest range of clients recommends servers also handle LF. Similarly, whitespace in the request line is treated sensibly (allowing multiple spaces between components and allowing trailing whitespace).

Similarly, for output, lines ought to be separated by CRLF pairs but most clients grok LF characters just fine.

If the first line of the request has the form

(i.e. is left out) then this is assumed to be an HTTP 0.9 request; this form has no optional headers and data part and the reply consists of just the data.

The reply form of the HTTP 1.x protocol again has three parts:

  1. One line giving the response code
  2. An optional set of RFC-822-style headers
  3. The data

Again, the headers and data are separated by a blank line.

The response code line has the form

where is the protocol version ("HTTP/1.0" or "HTTP/1.1"), is a 3-digit response code indicating success or failure of the request, and is an optional human-readable string explaining what the response code means.

This server parses the request and the headers, and then calls a function specific to the request type (). Specifically, a request SPAM will be handled by a method do_SPAM(). If no such method exists the server sends an error response to the client. If it exists, it is called with no arguments:

do_SPAM()

Note that the request name is case sensitive (i.e. SPAM and spam are different requests).

The various request details are stored in instance variables:

  • client_address is the client IP address in the form (host, port);

  • command, path and version are the broken-down request line;

  • headers is an instance of email.message.Message (or a derived class) containing the header information;

  • rfile is a file object open for reading positioned at the start of the optional input data part;

  • wfile is a file object open for writing.

IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING!

The first thing to be written must be the response line. Then follow 0 or more header lines, then a blank line, and then the actual data (if any). The meaning of the header lines depends on the command executed by the server; in most cases, when data is returned, there should be at least one header line of the form

Content-type: /

where and should be registered MIME types, e.g. "text/html" or "text/plain".

Ancestors

  • http.server.BaseHTTPRequestHandler
  • socketserver.StreamRequestHandler
  • socketserver.BaseRequestHandler

Class variables

var server_instance : DirectoryServer | None

The type of the None singleton.

Methods

def do_GET(self) ‑> None
Expand source code
def do_GET(self) -> None:  # noqa: N802
    if self.path == "/health":
        self._handle_health()
    elif self.path == "/status":
        self._handle_status()
    else:
        self.send_error(404)
def log_message(self, format: str, *args: Any) ‑> None
Expand source code
def log_message(self, format: str, *args: Any) -> None:
    pass

Log an arbitrary message.

This is used by all other logging functions. Override it if you have specific logging wishes.

The first argument, FORMAT, is a format string for the message to be logged. If the format string contains any % escapes requiring parameters, they should be specified as subsequent arguments (it's just like printf!).

The client ip and current date/time are prefixed to every message.

Unicode control characters are replaced with escaped hex before writing the output to stderr.

class HealthCheckServer (host: str = '127.0.0.1', port: int = 8080)
Expand source code
class HealthCheckServer:
    def __init__(self, host: str = "127.0.0.1", port: int = 8080):
        self.host = host
        self.port = port
        self.httpd: HTTPServer | None = None
        self.thread: Thread | None = None

    def start(self, server_instance: DirectoryServer) -> None:
        HealthCheckHandler.server_instance = server_instance

        self.httpd = HTTPServer((self.host, self.port), HealthCheckHandler)
        self.thread = Thread(target=self.httpd.serve_forever, daemon=True)
        self.thread.start()

        logger.info(f"Health check server started on {self.host}:{self.port}")

    def stop(self) -> None:
        if self.httpd:
            self.httpd.shutdown()
            self.httpd.server_close()  # Explicitly close the socket
            logger.info("Health check server stopped")

Methods

def start(self, server_instance: DirectoryServer) ‑> None
Expand source code
def start(self, server_instance: DirectoryServer) -> None:
    HealthCheckHandler.server_instance = server_instance

    self.httpd = HTTPServer((self.host, self.port), HealthCheckHandler)
    self.thread = Thread(target=self.httpd.serve_forever, daemon=True)
    self.thread.start()

    logger.info(f"Health check server started on {self.host}:{self.port}")
def stop(self) ‑> None
Expand source code
def stop(self) -> None:
    if self.httpd:
        self.httpd.shutdown()
        self.httpd.server_close()  # Explicitly close the socket
        logger.info("Health check server stopped")