Skip to content

client

client

Base client connecting an application to a running Nyx.

Standard library only, for Python 3.11+: clients live inside other applications (DCCs) that install this package without Nyx or Qt.

Subclass NyxClient for an application: fill default_namespace (e.g. with bpy) and, if the application is not safe to touch from other threads, override run_on_main_thread.

Attributes

LOGGER = logging.getLogger('nyx_bridge.client') module-attribute

Classes

NyxClient(name=None, address=None, token=None, reconnect=True, reconnect_delay=1.0)

Connects to a Nyx bridge server and runs the code it sends.

Two ways to run it:

  • serve_forever blocks the calling thread, which is then the thread executing the code. Meant for applications run in batch mode, where no event loop exists.
  • start_in_thread serves from a background thread and hands every execution to run_on_main_thread, which a subclass implements for its application.

Code runs in a namespace that persists for the lifetime of a connection, so variables of one execution are visible to the next. A script exposes its return value by assigning result.

Attributes:

Name Type Description
CLIENT_KIND

label telling the server what kind of application this is.

Initialize NyxClient.

Parameters:

Name Type Description Default
name str | None

name shown by the server. Derived from the kind and the process id if omitted.

None
address str | tuple[str, int] | None

host:port of the server. The environment is used if omitted, see protocol.find_server_address.

None
token str | None

server token, from the environment if omitted.

None
reconnect bool

connect again when the connection drops.

True
reconnect_delay float

seconds between connection attempts.

1.0
Source code in src/nyx_bridge/client.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def __init__(
    self,
    name: str | None = None,
    address: str | tuple[str, int] | None = None,
    token: str | None = None,
    reconnect: bool = True,
    reconnect_delay: float = 1.0,
) -> None:
    """Initialize NyxClient.

    Args:
        name (str | None): name shown by the server. Derived from the kind and the
            process id if omitted.
        address (str | tuple[str, int] | None): `host:port` of the server. The
            environment is used if omitted, see `protocol.find_server_address`.
        token (str | None): server token, from the environment if omitted.
        reconnect (bool): connect again when the connection drops.
        reconnect_delay (float): seconds between connection attempts.
    """
    self.name = name or f"{self.CLIENT_KIND}-{os.getpid()}"
    self._address = address
    self._token = token
    self._reconnect = reconnect
    self._reconnect_delay = reconnect_delay
    self._stop_event = threading.Event()
    self._sock: socket.socket | None = None
    self._namespace: dict[str, typing.Any] = {}
    self.client_id: str | None = None
    self.server_name: str | None = None
Attributes
CLIENT_KIND = 'python' class-attribute instance-attribute
HANDSHAKE_TIMEOUT = 10.0 class-attribute instance-attribute
client_id = None instance-attribute
is_connected property

bool: a handshaken connection is open.

name = name or f'{self.CLIENT_KIND}-{os.getpid()}' instance-attribute
server_name = None instance-attribute
Methods:
client_version()

str: version of the application. Override in subclasses.

Source code in src/nyx_bridge/client.py
80
81
82
def client_version(self) -> str:
    """str: version of the application. Override in subclasses."""
    return ""
connect()

Open one connection and handshake.

Raises:

Type Description
ConnectionError

nothing says where the server is.

OSError

the server can't be reached.

HandshakeError

the server refused the hello.

ProtocolError

the server broke the protocol.

Source code in src/nyx_bridge/client.py
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
157
158
159
160
161
162
def connect(self) -> None:
    """Open one connection and handshake.

    Raises:
        ConnectionError: nothing says where the server is.
        OSError: the server can't be reached.
        protocol.HandshakeError: the server refused the hello.
        protocol.ProtocolError: the server broke the protocol.
    """
    address = protocol.find_server_address(self._address, self._token)
    if address is None:
        raise ConnectionError(
            f"Unknown Nyx server address, set {protocol.ADDRESS_ENV_VAR}"
        )
    sock = socket.create_connection(
        (address.host, address.port), timeout=self.HANDSHAKE_TIMEOUT
    )
    try:
        protocol.send_message(
            sock,
            protocol.make_hello(
                address.token,
                self.name,
                self.CLIENT_KIND,
                self.client_version(),
            ),
        )
        reply = protocol.recv_message(sock)
        if reply["type"] == protocol.MessageType.ERROR:
            raise protocol.HandshakeError(reply.get("message", "Refused"))
        if reply["type"] != protocol.MessageType.ACK:
            raise protocol.ProtocolError(f"Unexpected reply: {reply['type']}")
        sock.settimeout(None)
    except BaseException:
        sock.close()
        raise

    self.client_id = reply.get("client_id")
    self.server_name = reply.get("server_name")
    self._namespace = dict(self.default_namespace())
    self._namespace.setdefault("__name__", "__nyx__")
    self._sock = sock
    LOGGER.info("Connected to %s as %s", self.server_name, self.name)
    self.on_connected()
default_namespace()

Names available to every execution, e.g. the application's modules.

Returns:

Type Description
dict[str, Any]

dict[str, Any]: names to put in a fresh namespace. Override in subclasses.

Source code in src/nyx_bridge/client.py
84
85
86
87
88
89
90
def default_namespace(self) -> dict[str, typing.Any]:
    """Names available to every execution, e.g. the application's modules.

    Returns:
        dict[str, Any]: names to put in a fresh namespace. Override in subclasses.
    """
    return {}
execute(code, mode=protocol.EXEC, args=None, request_id=None)

Run code in the persistent namespace. Never raises.

Output written to stdout and stderr while it runs is captured. In exec mode the value is what the code assigned to result, in eval mode the value of the expression.

Parameters:

Name Type Description Default
code str

source to run.

required
mode str

protocol.EXEC or protocol.EVAL.

EXEC
args dict | None

names to set in the namespace before running.

None
request_id str | None

id of the request being answered.

None

Returns:

Name Type Description
dict dict

result message, see protocol.make_result.

Source code in src/nyx_bridge/client.py
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
def execute(
    self,
    code: str,
    mode: str = protocol.EXEC,
    args: dict | None = None,
    request_id: str | None = None,
) -> dict:
    """Run code in the persistent namespace. Never raises.

    Output written to stdout and stderr while it runs is captured. In `exec` mode
    the value is what the code assigned to `result`, in `eval` mode the value of
    the expression.

    Args:
        code (str): source to run.
        mode (str): `protocol.EXEC` or `protocol.EVAL`.
        args (dict | None): names to set in the namespace before running.
        request_id (str | None): id of the request being answered.

    Returns:
        dict: result message, see `protocol.make_result`.
    """
    namespace = self._namespace
    namespace.update(args or {})
    stdout, stderr = io.StringIO(), io.StringIO()
    value, error, ok = None, None, True
    with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):
        try:
            if mode == protocol.EVAL:
                value = eval(compile(code, "<nyx>", "eval"), namespace)
            elif mode == protocol.EXEC:
                namespace.pop("result", None)
                exec(compile(code, "<nyx>", "exec"), namespace)
                value = namespace.get("result")
            else:
                raise ValueError(f"Unknown execution mode: {mode!r}")
        except (Exception, SystemExit) as err:
            ok, error = False, self._describe_error(err)
    return protocol.make_result(
        request_id,
        ok,
        value=protocol.to_jsonable(value),
        error=error,
        stdout=stdout.getvalue(),
        stderr=stderr.getvalue(),
    )
on_connected()

Called after the handshake. Override in subclasses.

Source code in src/nyx_bridge/client.py
107
108
def on_connected(self) -> None:
    """Called after the handshake. Override in subclasses."""
on_disconnected()

Called after the connection ended. Override in subclasses.

Source code in src/nyx_bridge/client.py
110
111
def on_disconnected(self) -> None:
    """Called after the connection ended. Override in subclasses."""
run_on_main_thread(func)

Run a function on the thread the application wants its API used from.

Called by the serving thread for every execution. The default runs it right there, which suits serve_forever on the main thread. Subclasses serving from a background thread override it to queue the call and wait for its result.

Parameters:

Name Type Description Default
func Callable[[], Any]

function to run.

required

Returns:

Name Type Description
Any Any

whatever the function returns.

Source code in src/nyx_bridge/client.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def run_on_main_thread(self, func: typing.Callable[[], typing.Any]) -> typing.Any:
    """Run a function on the thread the application wants its API used from.

    Called by the serving thread for every execution. The default runs it right
    there, which suits `serve_forever` on the main thread. Subclasses serving from
    a background thread override it to queue the call and wait for its result.

    Args:
        func (Callable[[], Any]): function to run.

    Returns:
        Any: whatever the function returns.
    """
    return func()
serve_forever(connect_timeout=None)

Connect and run what the server sends, until stopped or told to shut down.

Reconnects when the connection drops (if enabled). Runs on the calling thread.

Parameters:

Name Type Description Default
connect_timeout float | None

seconds to keep trying to reach the server, per attempt to connect. Forever if omitted.

None

Raises:

Type Description
ConnectionError

the server was not reached within connect_timeout.

HandshakeError

the server refused this client, retrying would not help.

Source code in src/nyx_bridge/client.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
def serve_forever(self, connect_timeout: float | None = None) -> None:
    """Connect and run what the server sends, until stopped or told to shut down.

    Reconnects when the connection drops (if enabled). Runs on the calling thread.

    Args:
        connect_timeout (float | None): seconds to keep trying to reach the
            server, per attempt to connect. Forever if omitted.

    Raises:
        ConnectionError: the server was not reached within `connect_timeout`.
        protocol.HandshakeError: the server refused this client, retrying would
            not help.
    """
    self._stop_event.clear()
    while not self._stop_event.is_set():
        self._connect_with_retry(connect_timeout)
        if not self.is_connected:
            break  # stopped while trying to connect
        try:
            # `stop` may have come in between connecting and here, when it had
            # no connection to close yet.
            if not self._stop_event.is_set():
                self._serve_connection()
        finally:
            self._close_socket()
            self.on_disconnected()
        if not self._reconnect:
            break
start_in_thread(connect_timeout=None)

Serve from a daemon thread.

Parameters:

Name Type Description Default
connect_timeout float | None

see serve_forever.

None

Returns:

Type Description
Thread

threading.Thread: running thread.

Source code in src/nyx_bridge/client.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
def start_in_thread(self, connect_timeout: float | None = None) -> threading.Thread:
    """Serve from a daemon thread.

    Args:
        connect_timeout (float | None): see `serve_forever`.

    Returns:
        threading.Thread: running thread.
    """
    thread = threading.Thread(
        target=self.serve_forever,
        args=(connect_timeout,),
        name=f"NyxClient-{self.name}",
        daemon=True,
    )
    thread.start()
    return thread
stop()

Stop serving and drop the connection. Safe to call from any thread.

Source code in src/nyx_bridge/client.py
212
213
214
215
def stop(self) -> None:
    """Stop serving and drop the connection. Safe to call from any thread."""
    self._stop_event.set()
    self._close_socket()