Skip to content

server

server

Server side of the Nyx bridge: accepts clients and sends them code to run.

Everything here runs on plain threads and standard library sockets, no Qt. The crawler is synchronous, so a request just blocks its caller until the client answers. Never touch stage objects from the threads of this module.

Attributes

LOGGER = logging.getLogger(__name__) module-attribute

Classes

BridgeServer(name=None, host=protocol.DEFAULT_HOST, port=None, token=None, address_file=None)

TCP server clients connect to.

Nyx listens and the client applications connect out, so the side executing code never accepts connections. A client has to open with a hello carrying the server's token. Requests are then sent to its ClientSession.

Subclass it to change the class attributes and validate_client. To follow what happens to the server, add a listener, see add_listener.

Attributes:

Name Type Description
DEFAULT_PORT

first port tried when no port is requested

PORT_FALLBACK_COUNT

number of ports tried from the default one

HANDSHAKE_TIMEOUT

seconds a new connection has to send its hello

Initialize BridgeServer.

Parameters:

Name Type Description Default
name str | None

server name, the class name if omitted.

None
host str

interface to listen on. Keep it local: clients can have code run on them by whoever holds the token.

DEFAULT_HOST
port int | None

port to listen on. None tries DEFAULT_PORT and the ports after it, 0 lets the system choose, anything else is used as is.

None
token str | None

shared secret clients have to present, random if omitted.

None
address_file str | PathLike | None

file that tells clients where the server is. Written when the server starts and removed when it stops.

None
Source code in src/nyx_bridge/server.py
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
def __init__(
    self,
    name: str | None = None,
    host: str = protocol.DEFAULT_HOST,
    port: int | None = None,
    token: str | None = None,
    address_file: str | os.PathLike | None = None,
) -> None:
    """Initialize BridgeServer.

    Args:
        name (str | None): server name, the class name if omitted.
        host (str): interface to listen on. Keep it local: clients can have code
            run on them by whoever holds the token.
        port (int | None): port to listen on. None tries `DEFAULT_PORT` and the
            ports after it, 0 lets the system choose, anything else is used as is.
        token (str | None): shared secret clients have to present, random if
            omitted.
        address_file (str | os.PathLike | None): file that tells clients where
            the server is. Written when the server starts and removed when it
            stops.
    """
    self.address_file = address_file
    self.name = name or type(self).__name__
    self.host = host
    self.token = token or secrets.token_urlsafe(16)
    self._requested_port = port
    self._listener: socket.socket | None = None
    self._accept_thread: threading.Thread | None = None
    self._stop_event = threading.Event()
    self._clients: list[ClientSession] = []
    self._condition = threading.Condition()
    self._listeners: list[typing.Any] = []
    self._port = port
    if host not in ("127.0.0.1", "localhost", "::1"):
        LOGGER.warning("Bridge server %s is listening on %s", self.name, host)
Attributes
DEFAULT_PORT = protocol.DEFAULT_PORT class-attribute instance-attribute
HANDSHAKE_TIMEOUT = 5.0 class-attribute instance-attribute
PORT_FALLBACK_COUNT = 20 class-attribute instance-attribute
address_file = address_file instance-attribute
clients property

list[ClientSession]: connected clients.

host = host instance-attribute
is_running property

bool: the server accepts connections.

name = name or type(self).__name__ instance-attribute
port property

int | None: port the server listens on, the requested one before start.

token = token or secrets.token_urlsafe(16) instance-attribute
Methods:
__enter__()

Start the server.

Source code in src/nyx_bridge/server.py
330
331
332
333
def __enter__(self) -> typing.Self:
    """Start the server."""
    self.start()
    return self
__exit__(*exc_info)

Stop the server.

Source code in src/nyx_bridge/server.py
335
336
337
def __exit__(self, *exc_info) -> None:
    """Stop the server."""
    self.stop()
__repr__()

str: server with its name and address.

Source code in src/nyx_bridge/server.py
326
327
328
def __repr__(self) -> str:
    """str: server with its name and address."""
    return f"{type(self).__name__}({self.name!r}, {self.host}:{self.port})"
add_listener(listener)

Get told about what happens to the server.

A listener is any object with some of these methods, the others are skipped: on_server_started(server), on_server_stopped(server), on_client_connected(server, session) and on_client_disconnected(server, session).

They are called on the threads of the server, not on the one that added the listener, so they have to be quick and thread safe. A failing listener is logged and does not affect the server or the other listeners.

Parameters:

Name Type Description Default
listener Any

object to call, ignored if it is already added.

required
Source code in src/nyx_bridge/server.py
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
def add_listener(self, listener: typing.Any) -> None:
    """Get told about what happens to the server.

    A listener is any object with some of these methods, the others are skipped:
    `on_server_started(server)`, `on_server_stopped(server)`,
    `on_client_connected(server, session)` and
    `on_client_disconnected(server, session)`.

    They are called on the threads of the server, not on the one that added the
    listener, so they have to be quick and thread safe. A failing listener is
    logged and does not affect the server or the other listeners.

    Args:
        listener (Any): object to call, ignored if it is already added.
    """
    with self._condition:
        if listener not in self._listeners:
            self._listeners.append(listener)
find_clients(name=None, kind=None, client_id=None)

Find connected clients. Criteria left out match anything.

Parameters:

Name Type Description Default
name str | None

client name.

None
kind str | None

client kind.

None
client_id str | None

client id.

None

Returns:

Type Description
list[ClientSession]

list[ClientSession]: matching clients, in order of connection.

Source code in src/nyx_bridge/server.py
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
def find_clients(
    self,
    name: str | None = None,
    kind: str | None = None,
    client_id: str | None = None,
) -> list[ClientSession]:
    """Find connected clients. Criteria left out match anything.

    Args:
        name (str | None): client name.
        kind (str | None): client kind.
        client_id (str | None): client id.

    Returns:
        list[ClientSession]: matching clients, in order of connection.
    """
    return [
        session
        for session in self.clients
        if (name is None or session.name == name)
        and (kind is None or session.kind == kind)
        and (client_id is None or session.id == client_id)
    ]
remove_listener(listener)

Stop telling a listener about the server.

Parameters:

Name Type Description Default
listener Any

listener to remove, ignored if it is not added.

required
Source code in src/nyx_bridge/server.py
387
388
389
390
391
392
393
394
395
def remove_listener(self, listener: typing.Any) -> None:
    """Stop telling a listener about the server.

    Args:
        listener (Any): listener to remove, ignored if it is not added.
    """
    with self._condition:
        if listener in self._listeners:
            self._listeners.remove(listener)
start()

Start listening and accepting clients.

Raises:

Type Description
OSError

no port could be bound.

Source code in src/nyx_bridge/server.py
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
def start(self) -> None:
    """Start listening and accepting clients.

    Raises:
        OSError: no port could be bound.
    """
    if self.is_running:
        return
    self._listener = self._bind()
    self._port = self._listener.getsockname()[1]
    self._stop_event.clear()
    self._accept_thread = threading.Thread(
        target=self._accept_loop, name=f"BridgeServer-{self.name}", daemon=True
    )
    self._accept_thread.start()
    if self.address_file is not None:
        self._write_own_address_file()
    LOGGER.info(
        "Bridge server %s listening on %s:%s", self.name, self.host, self.port
    )
    self._notify("on_server_started")
stop()

Stop listening and disconnect every client.

Source code in src/nyx_bridge/server.py
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
def stop(self) -> None:
    """Stop listening and disconnect every client."""
    if not self.is_running:
        return
    self._stop_event.set()
    listener, self._listener = self._listener, None
    listener.close()
    if self._accept_thread is not None:
        self._accept_thread.join(timeout=2)
        self._accept_thread = None
    for session in self.clients:
        session.close()
    with self._condition:
        self._condition.notify_all()
    if self.address_file is not None:
        self._remove_own_address_file()
    LOGGER.info("Bridge server %s stopped", self.name)
    self._notify("on_server_stopped")
validate_client(hello)

Decide whether a client may connect, once its token has been checked.

Parameters:

Name Type Description Default
hello dict

hello message of the client.

required

Returns:

Type Description
str | None

str | None: reason to refuse the client, None to accept it.

Source code in src/nyx_bridge/server.py
356
357
358
359
360
361
362
363
364
365
def validate_client(self, hello: dict) -> str | None:
    """Decide whether a client may connect, once its token has been checked.

    Args:
        hello (dict): hello message of the client.

    Returns:
        str | None: reason to refuse the client, None to accept it.
    """
    return None
wait_for_client(name=None, kind=None, client_id=None, timeout=None)

Wait until a matching client is connected.

Parameters:

Name Type Description Default
name str | None

client name.

None
kind str | None

client kind.

None
client_id str | None

client id.

None
timeout float | None

seconds to wait, forever if None.

None

Raises:

Type Description
TimeoutError

no matching client within the timeout.

RuntimeError

the server was stopped while waiting.

Returns:

Name Type Description
ClientSession ClientSession

first matching client.

Source code in src/nyx_bridge/server.py
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
def wait_for_client(
    self,
    name: str | None = None,
    kind: str | None = None,
    client_id: str | None = None,
    timeout: float | None = None,
) -> ClientSession:
    """Wait until a matching client is connected.

    Args:
        name (str | None): client name.
        kind (str | None): client kind.
        client_id (str | None): client id.
        timeout (float | None): seconds to wait, forever if None.

    Raises:
        TimeoutError: no matching client within the timeout.
        RuntimeError: the server was stopped while waiting.

    Returns:
        ClientSession: first matching client.
    """

    def find() -> ClientSession | None:
        matches = [
            session
            for session in self._clients
            if (name is None or session.name == name)
            and (kind is None or session.kind == kind)
            and (client_id is None or session.id == client_id)
        ]
        return matches[0] if matches else None

    with self._condition:
        self._condition.wait_for(
            lambda: find() is not None or self._stop_event.is_set(), timeout
        )
        session = find()
    if session is not None:
        return session
    if self._stop_event.is_set():
        raise RuntimeError(f"Bridge server {self.name} was stopped")
    raise TimeoutError(
        f"No client (name={name!r}, kind={kind!r}) connected to {self.name} "
        f"within {timeout}s"
    )
write_address_file(path)

Write where this server listens, see protocol.write_address_file.

Parameters:

Name Type Description Default
path str | PathLike

file to write.

required
Source code in src/nyx_bridge/server.py
452
453
454
455
456
457
458
def write_address_file(self, path: str | os.PathLike) -> None:
    """Write where this server listens, see `protocol.write_address_file`.

    Args:
        path (str | os.PathLike): file to write.
    """
    protocol.write_address_file(path, self.host, self.port, self.token)

ClientDisconnected

Bases: ConnectionError

The client went away before it answered.

ClientSession(sock, client_id, name, kind, version, address)

A connected client, with the requests waiting for its answers.

Initialize ClientSession.

Parameters:

Name Type Description Default
sock socket

connection, already handshaken.

required
client_id str

id given to the client by the server.

required
name str

client name.

required
kind str

client kind, e.g. "blender".

required
version str

client application version.

required
address tuple

remote address of the connection.

required
Source code in src/nyx_bridge/server.py
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def __init__(
    self,
    sock: socket.socket,
    client_id: str,
    name: str,
    kind: str,
    version: str,
    address: tuple,
) -> None:
    """Initialize ClientSession.

    Args:
        sock (socket.socket): connection, already handshaken.
        client_id (str): id given to the client by the server.
        name (str): client name.
        kind (str): client kind, e.g. "blender".
        version (str): client application version.
        address (tuple): remote address of the connection.
    """
    self._sock = sock
    self._send_lock = threading.Lock()
    self._pending_lock = threading.Lock()
    self._pending: dict[str, concurrent.futures.Future] = {}
    self._request_ids = itertools.count(1)
    self._closed = threading.Event()
    self.id = client_id
    self.name = name
    self.kind = kind
    self.version = version
    self.address = address
Attributes
address = address instance-attribute
id = client_id instance-attribute
is_connected property

bool: the connection is open.

kind = kind instance-attribute
name = name instance-attribute
version = version instance-attribute
Methods:
__repr__()

str: client with its name and kind.

Source code in src/nyx_bridge/server.py
108
109
110
def __repr__(self) -> str:
    """str: client with its name and kind."""
    return f"ClientSession({self.name!r}, kind={self.kind!r}, id={self.id!r})"
close()

Drop the connection. Pending requests fail with ClientDisconnected.

Source code in src/nyx_bridge/server.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
def close(self) -> None:
    """Drop the connection. Pending requests fail with `ClientDisconnected`."""
    if self._closed.is_set():
        return
    self._closed.set()
    try:
        self._sock.shutdown(socket.SHUT_RDWR)
    except OSError:
        pass
    self._sock.close()
    with self._pending_lock:
        pending, self._pending = self._pending, {}
    for future in pending.values():
        if not future.done():
            future.set_exception(ClientDisconnected(f"{self.name} disconnected"))
execute(code, args=None, mode=protocol.EXEC, timeout=None)

Run code in the client and wait for the answer.

Parameters:

Name Type Description Default
code str

source to run.

required
args dict | None

names to set in the client's namespace first, has to be JSON serializable.

None
mode str

protocol.EXEC, the value is what the code assigned to result, or protocol.EVAL, the value of the expression.

EXEC
timeout float | None

seconds to wait for the answer, forever if None.

None

Raises:

Type Description
TypeError

args are not JSON serializable.

ClientDisconnected

the client is gone or went away while waiting.

TimeoutError

no answer within the timeout.

RemoteExecutionError

the code raised in the client.

Returns:

Name Type Description
ExecutionResult ExecutionResult

value and output.

Source code in src/nyx_bridge/server.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def execute(
    self,
    code: str,
    args: dict | None = None,
    mode: str = protocol.EXEC,
    timeout: float | None = None,
) -> ExecutionResult:
    """Run code in the client and wait for the answer.

    Args:
        code (str): source to run.
        args (dict | None): names to set in the client's namespace first, has to
            be JSON serializable.
        mode (str): `protocol.EXEC`, the value is what the code assigned to
            `result`, or `protocol.EVAL`, the value of the expression.
        timeout (float | None): seconds to wait for the answer, forever if None.

    Raises:
        TypeError: args are not JSON serializable.
        ClientDisconnected: the client is gone or went away while waiting.
        TimeoutError: no answer within the timeout.
        RemoteExecutionError: the code raised in the client.

    Returns:
        ExecutionResult: value and output.
    """
    request_id = str(next(self._request_ids))
    frame = protocol.encode_message(
        protocol.make_execute(request_id, code, mode, args)
    )
    reply = self._request(request_id, frame, timeout)
    if not reply.get("ok"):
        raise RemoteExecutionError(
            reply.get("error") or {},
            reply.get("stdout", ""),
            reply.get("stderr", ""),
        )
    return ExecutionResult(
        reply.get("value"), reply.get("stdout", ""), reply.get("stderr", "")
    )
ping(timeout=5.0)

Check the client answers.

Parameters:

Name Type Description Default
timeout float | None

seconds to wait for the pong.

5.0

Raises:

Type Description
ClientDisconnected

the client is gone.

TimeoutError

no answer within the timeout.

Source code in src/nyx_bridge/server.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
def ping(self, timeout: float | None = 5.0) -> None:
    """Check the client answers.

    Args:
        timeout (float | None): seconds to wait for the pong.

    Raises:
        ClientDisconnected: the client is gone.
        TimeoutError: no answer within the timeout.
    """
    request_id = f"ping-{next(self._request_ids)}"
    self._request(
        request_id, protocol.encode_message(protocol.make_ping(request_id)), timeout
    )
request_shutdown()

Ask the client to disconnect and stop serving.

Source code in src/nyx_bridge/server.py
173
174
175
176
177
178
def request_shutdown(self) -> None:
    """Ask the client to disconnect and stop serving."""
    try:
        self._send(protocol.encode_message(protocol.make_shutdown()))
    except ClientDisconnected:
        pass
run()

Read messages until the connection ends. Runs on the connection's thread.

Source code in src/nyx_bridge/server.py
196
197
198
199
200
201
202
203
204
205
206
def run(self) -> None:
    """Read messages until the connection ends. Runs on the connection's thread."""
    try:
        while True:
            self._dispatch(protocol.recv_message(self._sock))
    except protocol.ConnectionClosed as err:
        LOGGER.info("%s disconnected: %s", self.name, err)
    except (protocol.ProtocolError, OSError) as err:
        LOGGER.warning("Dropping %s: %s", self.name, err)
    finally:
        self.close()

ExecutionResult(value=None, stdout='', stderr='') dataclass

What a client answered to an execution.

Attributes:

Name Type Description
value Any

value of the code, JSON data (see protocol.to_jsonable)

stdout str

output written by the code

stderr str

error output written by the code

Attributes
stderr = '' class-attribute instance-attribute
stdout = '' class-attribute instance-attribute
value = None class-attribute instance-attribute
Methods:

RemoteExecutionError(error, stdout='', stderr='')

Bases: Exception

Code run by a client raised an exception.

Attributes:

Name Type Description
type_name

name of the exception class raised in the client

message

message of the exception

remote_traceback

traceback formatted by the client

stdout

output of the code before it failed

stderr

error output of the code before it failed

Initialize RemoteExecutionError.

Parameters:

Name Type Description Default
error dict

type, message and traceback sent by the client.

required
stdout str

output of the code.

''
stderr str

error output of the code.

''
Source code in src/nyx_bridge/server.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def __init__(self, error: dict, stdout: str = "", stderr: str = "") -> None:
    """Initialize RemoteExecutionError.

    Args:
        error (dict): `type`, `message` and `traceback` sent by the client.
        stdout (str): output of the code.
        stderr (str): error output of the code.
    """
    self.type_name = error.get("type", "Exception")
    self.message = error.get("message", "")
    self.remote_traceback = error.get("traceback", "")
    self.stdout = stdout
    self.stderr = stderr
    super().__init__(f"{self.type_name}: {self.message}")
Attributes
message = error.get('message', '') instance-attribute
remote_traceback = error.get('traceback', '') instance-attribute
stderr = stderr instance-attribute
stdout = stdout instance-attribute
type_name = error.get('type', 'Exception') instance-attribute
Methods: