GitHub

SocketServerService

API reference for SocketServerService.

A listening server: address is where it listens; run hands every connection to handler until interrupted. A handler's failure is logged ("Unhandled error in SocketServer"), not propagated.

Attributes

AttributeTypeDescription
address= address

Functions

__init__

__init__(address, accepted) -> None
ParameterTypeDescription
addressSocketAddress
acceptedAccepted
def __init__(self, address: SocketAddress, accepted: Accepted) -> None:
    self.address = address
    self._accepted = accepted

run

run[E, R = Never](handler) -> Effect[Never, SocketServerError, R]

Hands every accepted connection, as a Socket, to handler in a fiber of its own until interrupted; interrupting it interrupts the handlers still running. A handler's failure is logged ("Unhandled error in SocketServer"), not propagated. Never ends; pyfect's servers never fail it either (opening the server, where SocketServerError comes from, is the layer's work).

ParameterTypeDescription
handlerHandler[E, R]

Returns Effect[Never, SocketServerError, R]

def run[E, R = Never](self, handler: Handler[E, R]) -> Effect[Never, SocketServerError, R]:
    """Hands every accepted connection, as a ``Socket``, to ``handler``
    in a fiber of its own until interrupted; interrupting it interrupts
    the handlers still running. A handler's failure is logged
    ("Unhandled error in SocketServer"), not propagated. Never ends;
    pyfect's servers never fail it either (opening the server, where
    ``SocketServerError`` comes from, is the layer's work)."""
    accepted = self._accepted

    def serve(scope: CloseableScope) -> Effect[Never, Never, R]:
        def fork_taken():
            for incoming in accepted.take():
                fiber = yield from fork_in(incoming.handle(handler), scope)
                # The fiber owns the connection even if it is interrupted
                # before it starts, when the handler's own release never
                # gets registered.
                fiber.add_observer_unsafe(lambda _, i=incoming: i.release())

        # Taking and forking is one step: an interrupt between them would
        # drop the taken connections.
        hand_over = gen(fork_taken).uninterruptible()

        def loop():
            while True:
                yield from accepted.signal.wait(accepted.has_pending)
                yield from hand_over

        return gen(loop)

    def body():
        scope = CloseableScope()
        return (yield from serve(scope).ensuring(scope.close(Success(None))))

    return gen(body)