Skip to content

xmlrpc_extended.server

Core server classes and data types.


ThreadPoolXMLRPCServer

ThreadPoolXMLRPCServer

ThreadPoolXMLRPCServer(addr: tuple[str, int], requestHandler: type[SimpleXMLRPCRequestHandler] = LimitedXMLRPCRequestHandler, logRequests: bool = True, allow_none: bool = False, encoding: str | None = None, bind_and_activate: bool = True, use_builtin_types: bool = False, *, max_workers: int = max_workers, max_pending: int | None = max_pending, request_queue_size: int = request_queue_size, overload_policy: ServerOverloadPolicy | str = BLOCK, max_request_size: int = max_request_size, overload_fault_code: int = overload_fault_code, overload_fault_string: str = overload_fault_string, rpc_paths: tuple[str, ...] | None = None, connection_timeout: float | None = None)

Bases: SimpleXMLRPCServer

A drop-in XML-RPC server that dispatches requests through a thread pool.

Replaces SimpleXMLRPCServer's single-threaded request handling with a ThreadPoolExecutor and an explicit semaphore so that concurrency and pending request depth are both bounded.

The constructor is fully compatible with SimpleXMLRPCServer and adds keyword-only parameters for concurrency control, overload policy, and request size limiting.

Example
from xmlrpc_extended import ServerOverloadPolicy, ThreadPoolXMLRPCServer

server = ThreadPoolXMLRPCServer(
    ("127.0.0.1", 8000),
    max_workers=8,
    max_pending=16,
    overload_policy=ServerOverloadPolicy.HTTP_503,
    logRequests=False,
)
server.register_function(lambda a, b: a + b, "add")
server.serve_forever()

Initialise the server.

Parameters:

Name Type Description Default
addr tuple[str, int]

(host, port) tuple. Use port 0 to let the OS choose a free port (useful in tests).

required
requestHandler type[SimpleXMLRPCRequestHandler]

Request handler class. Defaults to LimitedXMLRPCRequestHandler which enforces max_request_size.

LimitedXMLRPCRequestHandler
logRequests bool

Whether to log each request to stderr.

True
allow_none bool

Whether None values are permitted in XML-RPC payloads.

False
encoding str | None

XML encoding; None defaults to UTF-8.

None
bind_and_activate bool

If False, skip binding and activating the socket (useful when supplying a pre-bound SO_REUSEPORT socket).

True
use_builtin_types bool

Map XML-RPC dateTime/base64 to Python built-in types.

False
max_workers int

Maximum number of requests executing concurrently in the thread pool. Must be ≥ 1.

max_workers
max_pending int | None

Maximum number of additional requests that may queue while all workers are busy. None (default) resolves to max_workers, giving total capacity of 2 × max_workers. Use 0 for fail-fast behaviour.

max_pending
request_queue_size int

OS-level TCP accept backlog size. Controls how many connections the kernel will hold before refusing new ones.

request_queue_size
overload_policy ServerOverloadPolicy | str

What to do when total capacity is exhausted. Accepts a ServerOverloadPolicy member or its string value ("block", "close", "fault", "http_503").

BLOCK
max_request_size int

Maximum accepted request body in bytes (default 1 MiB). Requests larger than this receive 413 Payload Too Large.

max_request_size
overload_fault_code int

XML-RPC fault code returned when overload_policy=FAULT.

overload_fault_code
overload_fault_string str

XML-RPC fault string returned when overload_policy=FAULT.

overload_fault_string
rpc_paths tuple[str, ...] | None

Accepted URL paths. None uses the stdlib defaults ("/" and "/RPC2"). All other paths return 404.

None
connection_timeout float | None

Per-connection socket read timeout in seconds. After a client socket is accepted, this timeout is applied so that a slow or stalled sender cannot hold a worker thread indefinitely. None (default) means no timeout (blocking I/O, matching the stdlib default).

None

Raises:

Type Description
ValueError

If max_workers < 1, max_pending < 0, request_queue_size < 1, max_request_size < 1, or connection_timeout is not None and is ≤ 0.

Source code in src/xmlrpc_extended/server.py
def __init__(
    self,
    addr: tuple[str, int],
    requestHandler: type[SimpleXMLRPCRequestHandler] = LimitedXMLRPCRequestHandler,
    logRequests: bool = True,  # noqa: N803 - stdlib compatibility
    allow_none: bool = False,
    encoding: str | None = None,
    bind_and_activate: bool = True,
    use_builtin_types: bool = False,
    *,
    max_workers: int = XMLRPCServerConfig.max_workers,
    max_pending: int | None = XMLRPCServerConfig.max_pending,
    request_queue_size: int = XMLRPCServerConfig.request_queue_size,
    overload_policy: ServerOverloadPolicy | str = ServerOverloadPolicy.BLOCK,
    max_request_size: int = XMLRPCServerConfig.max_request_size,
    overload_fault_code: int = XMLRPCServerConfig.overload_fault_code,
    overload_fault_string: str = XMLRPCServerConfig.overload_fault_string,
    rpc_paths: tuple[str, ...] | None = None,
    connection_timeout: float | None = None,
) -> None:
    """Initialise the server.

    Args:
        addr: ``(host, port)`` tuple.  Use port ``0`` to let the OS choose
            a free port (useful in tests).
        requestHandler: Request handler class.  Defaults to
            `LimitedXMLRPCRequestHandler` which enforces ``max_request_size``.
        logRequests: Whether to log each request to stderr.
        allow_none: Whether ``None`` values are permitted in XML-RPC payloads.
        encoding: XML encoding; ``None`` defaults to UTF-8.
        bind_and_activate: If ``False``, skip binding and activating the
            socket (useful when supplying a pre-bound `SO_REUSEPORT` socket).
        use_builtin_types: Map XML-RPC ``dateTime``/``base64`` to Python
            built-in types.
        max_workers: Maximum number of requests executing concurrently in the
            thread pool.  Must be ≥ 1.
        max_pending: Maximum number of additional requests that may queue
            while all workers are busy.  ``None`` (default) resolves to
            ``max_workers``, giving total capacity of ``2 × max_workers``.
            Use ``0`` for fail-fast behaviour.
        request_queue_size: OS-level TCP accept backlog size.  Controls how
            many connections the kernel will hold before refusing new ones.
        overload_policy: What to do when total capacity is exhausted.
            Accepts a `ServerOverloadPolicy` member or its string value
            (``"block"``, ``"close"``, ``"fault"``, ``"http_503"``).
        max_request_size: Maximum accepted request body in bytes (default 1 MiB).
            Requests larger than this receive ``413 Payload Too Large``.
        overload_fault_code: XML-RPC fault code returned when
            ``overload_policy=FAULT``.
        overload_fault_string: XML-RPC fault string returned when
            ``overload_policy=FAULT``.
        rpc_paths: Accepted URL paths.  ``None`` uses the stdlib defaults
            (``"/"`` and ``"/RPC2"``).  All other paths return ``404``.
        connection_timeout: Per-connection socket read timeout in seconds.
            After a client socket is accepted, this timeout is applied so
            that a slow or stalled sender cannot hold a worker thread
            indefinitely.  ``None`` (default) means no timeout (blocking
            I/O, matching the stdlib default).

    Raises:
        ValueError: If ``max_workers < 1``, ``max_pending < 0``,
            ``request_queue_size < 1``, ``max_request_size < 1``,
            or ``connection_timeout`` is not ``None`` and is ≤ 0.
    """
    normalized_policy = ServerOverloadPolicy(overload_policy)
    effective_pending = max_workers if max_pending is None else max_pending
    total_capacity = max_workers + effective_pending
    if max_workers < 1:
        raise ValueError("max_workers must be at least 1")
    if effective_pending < 0:
        raise ValueError("max_pending must be at least 0")
    if request_queue_size < 1:
        raise ValueError("request_queue_size must be at least 1")
    if max_request_size < 1:
        raise ValueError("max_request_size must be at least 1")
    if connection_timeout is not None and connection_timeout <= 0:
        raise ValueError("connection_timeout must be a positive number")

    self.request_queue_size = request_queue_size
    self._config = XMLRPCServerConfig(
        max_workers=max_workers,
        max_pending=effective_pending,
        request_queue_size=request_queue_size,
        overload_policy=normalized_policy,
        max_request_size=max_request_size,
        overload_fault_code=overload_fault_code,
        overload_fault_string=overload_fault_string,
        connection_timeout=connection_timeout,
    )
    self._capacity = threading.Semaphore(total_capacity)
    self._executor = ThreadPoolExecutor(max_workers=max_workers, thread_name_prefix="xmlrpc")
    self._executor_lock = threading.Lock()
    self._executor_closed = False
    self._stats = _StatsTracker()

    request_handler_class = self._build_request_handler(requestHandler, max_request_size, rpc_paths)
    try:
        super().__init__(
            addr,
            requestHandler=request_handler_class,
            logRequests=logRequests,
            allow_none=allow_none,
            encoding=encoding,
            bind_and_activate=bind_and_activate,
            use_builtin_types=use_builtin_types,
        )
    except Exception:
        self.shutdown_executor(wait=False)
        raise

stats

stats() -> ServerStats

Return a point-in-time snapshot of server activity counters.

Thread-safe; acquires the internal stats lock for the duration of the snapshot copy. Safe to call from any thread, including from registered RPC methods.

Returns:

Type Description
ServerStats

A ServerStats frozen dataclass with counters current at the

ServerStats

moment of the call.

Example
snap = server.stats()
print(f"active={snap.active} completed={snap.completed}")
Source code in src/xmlrpc_extended/server.py
def stats(self) -> ServerStats:
    """Return a point-in-time snapshot of server activity counters.

    Thread-safe; acquires the internal stats lock for the duration of
    the snapshot copy.  Safe to call from any thread, including from
    registered RPC methods.

    Returns:
        A `ServerStats` frozen dataclass with counters current at the
        moment of the call.

    Example:
        ```python
        snap = server.stats()
        print(f"active={snap.active} completed={snap.completed}")
        ```
    """
    return self._stats.snapshot()

submit_request

submit_request(request: Any, client_address: tuple[str, int]) -> None

Submit a request to the worker pool.

Source code in src/xmlrpc_extended/server.py
def submit_request(self, request: Any, client_address: tuple[str, int]) -> None:
    """Submit a request to the worker pool."""
    self._stats.record_submitted()
    self._executor.submit(self._process_request_worker, request, client_address)

ServerOverloadPolicy

ServerOverloadPolicy

Bases: str, Enum

How the server reacts when no worker capacity is available.

Members

BLOCK: Block the accept thread until a worker slot opens. No request is ever actively rejected; excess connections queue at the OS TCP backlog level. CLOSE: Close the connection immediately without sending a response. The client receives a connection-reset error. FAULT: Return an XML-RPC 200 OK response containing a fault element with the configured overload_fault_code and overload_fault_string. HTTP_503: Return an HTTP 503 Service Unavailable response with a Retry-After: 1 header.


ServerStats

ServerStats dataclass

ServerStats(active: int, queued: int, rejected_close: int, rejected_fault: int, rejected_503: int, completed: int, errored: int)

Immutable point-in-time snapshot of server activity counters.

Returned by ThreadPoolXMLRPCServer.stats(). All fields are non-negative integers. Counters (rejected_*, completed, errored) are cumulative since the server started.

Attributes:

Name Type Description
active int

Requests currently executing in worker threads.

queued int

Requests submitted to the thread pool but not yet started.

rejected_close int

Cumulative rejections via the CLOSE policy.

rejected_fault int

Cumulative rejections via the FAULT policy.

rejected_503 int

Cumulative rejections via the HTTP_503 policy.

completed int

Cumulative requests that finished (including those where the XML-RPC method raised an application exception — those are still sent as valid fault responses).

errored int

Cumulative requests that failed with a transport-level error (e.g. broken socket after partial write).


XMLRPCServerConfig

XMLRPCServerConfig dataclass

XMLRPCServerConfig(max_workers: int = 8, max_pending: int | None = None, request_queue_size: int = 64, overload_policy: ServerOverloadPolicy = BLOCK, max_request_size: int = 1048576, overload_fault_code: int = -32500, overload_fault_string: str = 'Server overloaded', connection_timeout: float | None = None)

Resolved, validated configuration for ThreadPoolXMLRPCServer.

Created internally from the constructor arguments. Access it via server.config to inspect the active settings.

Attributes:

Name Type Description
max_workers int

Maximum concurrent worker threads.

max_pending int | None

Maximum requests queued beyond the active pool (None in constructor resolves to max_workers here).

request_queue_size int

OS-level TCP accept backlog.

overload_policy ServerOverloadPolicy

Active overload policy enum member.

max_request_size int

Maximum body size in bytes.

overload_fault_code int

XML-RPC fault code for the FAULT policy.

overload_fault_string str

XML-RPC fault string for the FAULT policy.


LimitedXMLRPCRequestHandler

LimitedXMLRPCRequestHandler

Bases: SimpleXMLRPCRequestHandler

Request handler with a configurable maximum body size.

log_error

log_error(format: str, *args: object) -> None

Only emit error log lines when the server has logging enabled.

Source code in src/xmlrpc_extended/server.py
def log_error(self, format: str, *args: object) -> None:  # noqa: A002 - stdlib override
    """Only emit error log lines when the server has logging enabled."""
    if getattr(self.server, "logRequests", True):
        super().log_error(format, *args)