Skip to content

protocol

protocol

Wire protocol shared by the Nyx bridge server and its clients.

Standard library only, for Python 3.11+: clients living in other applications (DCCs) install this package, so it must have no dependencies.

Messages are JSON objects with a type key, sent over TCP with a 4-byte big-endian length prefix.

Attributes

ADDRESS_ENV_VAR = 'NYX_BRIDGE_ADDRESS' module-attribute

ADDRESS_FILE_ENV_VAR = 'NYX_BRIDGE_ADDRESS_FILE' module-attribute

Address = collections.namedtuple('Address', ['host', 'port', 'token']) module-attribute

DEFAULT_ADDRESS_FILE_NAME = 'bridge.json' module-attribute

DEFAULT_HOST = '127.0.0.1' module-attribute

DEFAULT_PORT = 47770 module-attribute

EVAL = 'eval' module-attribute

EXEC = 'exec' module-attribute

MAX_MESSAGE_SIZE = 64 * 1024 * 1024 module-attribute

PROTOCOL_VERSION = 1 module-attribute

TOKEN_ENV_VAR = 'NYX_BRIDGE_TOKEN' module-attribute

Classes

ConnectionClosed

Bases: ProtocolError

The peer closed the connection (or it broke) while reading.

HandshakeError

Bases: ProtocolError

The server refused the hello message.

MessageType

Values of the type key of messages.

Attributes
ACK = 'ack' class-attribute instance-attribute
ERROR = 'error' class-attribute instance-attribute
EXECUTE = 'execute' class-attribute instance-attribute
HELLO = 'hello' class-attribute instance-attribute
PING = 'ping' class-attribute instance-attribute
PONG = 'pong' class-attribute instance-attribute
RESULT = 'result' class-attribute instance-attribute
SHUTDOWN = 'shutdown' class-attribute instance-attribute

ProtocolError

Bases: Exception

Malformed message or a peer breaking the protocol.

Functions:

default_address_file_path()

Where Nyx writes its address file unless told otherwise.

The folder is the per-user data folder of the Nyx application, so a client on the same machine finds a running Nyx without any configuration.

Returns:

Type Description
Path

pathlib.Path: path of the file, which may not exist.

Source code in src/nyx_bridge/protocol.py
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
def default_address_file_path() -> pathlib.Path:
    """Where Nyx writes its address file unless told otherwise.

    The folder is the per-user data folder of the Nyx application, so a client on
    the same machine finds a running Nyx without any configuration.

    Returns:
        pathlib.Path: path of the file, which may not exist.
    """
    if sys.platform == "darwin":
        base = pathlib.Path.home() / "Library" / "Application Support" / "nyx"
    elif sys.platform == "win32":
        local = os.environ.get("LOCALAPPDATA") or pathlib.Path.home() / "AppData/Local"
        base = pathlib.Path(local) / "sowwic" / "nyx"
    else:
        data = os.environ.get("XDG_DATA_HOME") or pathlib.Path.home() / ".local/share"
        base = pathlib.Path(data) / "nyx"
    return base / DEFAULT_ADDRESS_FILE_NAME

encode_message(message)

Serialize a message and prefix it with its length.

Parameters:

Name Type Description Default
message dict

JSON serializable message.

required

Raises:

Type Description
TypeError

message can't be serialized to JSON.

ProtocolError

message is larger than MAX_MESSAGE_SIZE.

Returns:

Name Type Description
bytes bytes

frame to send.

Source code in src/nyx_bridge/protocol.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def encode_message(message: dict) -> bytes:
    """Serialize a message and prefix it with its length.

    Args:
        message (dict): JSON serializable message.

    Raises:
        TypeError: message can't be serialized to JSON.
        ProtocolError: message is larger than `MAX_MESSAGE_SIZE`.

    Returns:
        bytes: frame to send.
    """
    payload = json.dumps(message, separators=(",", ":")).encode("utf-8")
    if len(payload) > MAX_MESSAGE_SIZE:
        raise ProtocolError(f"Message too large: {len(payload)} bytes")
    return _HEADER.pack(len(payload)) + payload

find_server_address(address=None, token=None)

Work out where the server is.

Looked up in order: the arguments, NYX_BRIDGE_ADDRESS (host:port) with NYX_BRIDGE_TOKEN, then the file named by NYX_BRIDGE_ADDRESS_FILE, then the default address file of a running Nyx (see default_address_file_path).

Parameters:

Name Type Description Default
address str | tuple[str, int] | None

host:port or (host, port).

None
token str | None

token, taken from the environment if omitted.

None

Returns:

Type Description
Address | None

Address | None: None when nothing says where the server is.

Source code in src/nyx_bridge/protocol.py
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
def find_server_address(
    address: str | tuple[str, int] | None = None, token: str | None = None
) -> Address | None:
    """Work out where the server is.

    Looked up in order: the arguments, `NYX_BRIDGE_ADDRESS` (`host:port`) with
    `NYX_BRIDGE_TOKEN`, then the file named by `NYX_BRIDGE_ADDRESS_FILE`, then the
    default address file of a running Nyx (see `default_address_file_path`).

    Args:
        address (str | tuple[str, int] | None): `host:port` or (host, port).
        token (str | None): token, taken from the environment if omitted.

    Returns:
        Address | None: None when nothing says where the server is.
    """
    if address is None:
        address = os.environ.get(ADDRESS_ENV_VAR)
    if address:
        if isinstance(address, str):
            host, port = parse_address(address)
        else:
            host, port = address
        if token is None:
            token = os.environ.get(TOKEN_ENV_VAR, "")
        return Address(host, int(port), token)

    candidates = [os.environ.get(ADDRESS_FILE_ENV_VAR), default_address_file_path()]
    for address_file in candidates:
        if address_file and os.path.isfile(address_file):
            found = read_address_file(address_file)
            return found if token is None else found._replace(token=token)
    return None

make_ack(client_id, server_name)

Build the server's answer to an accepted hello.

Source code in src/nyx_bridge/protocol.py
166
167
168
169
170
171
172
173
def make_ack(client_id: str, server_name: str) -> dict:
    """Build the server's answer to an accepted hello."""
    return {
        "type": MessageType.ACK,
        "protocol_version": PROTOCOL_VERSION,
        "client_id": client_id,
        "server_name": server_name,
    }

make_error(message, request_id=None)

Build an error message, optionally answering a request.

Source code in src/nyx_bridge/protocol.py
176
177
178
179
180
181
def make_error(message: str, request_id: str | None = None) -> dict:
    """Build an error message, optionally answering a request."""
    error = {"type": MessageType.ERROR, "message": message}
    if request_id is not None:
        error["id"] = request_id
    return error

make_execute(request_id, code, mode=EXEC, args=None)

Build a request to run code in the client.

Source code in src/nyx_bridge/protocol.py
184
185
186
187
188
189
190
191
192
193
194
def make_execute(
    request_id: str, code: str, mode: str = EXEC, args: dict | None = None
) -> dict:
    """Build a request to run code in the client."""
    return {
        "type": MessageType.EXECUTE,
        "id": request_id,
        "code": code,
        "mode": mode,
        "args": args or {},
    }

make_hello(token, client_name, client_kind, client_version)

Build the message a client opens a connection with.

Source code in src/nyx_bridge/protocol.py
152
153
154
155
156
157
158
159
160
161
162
163
def make_hello(
    token: str, client_name: str, client_kind: str, client_version: str
) -> dict:
    """Build the message a client opens a connection with."""
    return {
        "type": MessageType.HELLO,
        "protocol_version": PROTOCOL_VERSION,
        "token": token,
        "client_name": client_name,
        "client_kind": client_kind,
        "client_version": client_version,
    }

make_ping(request_id)

Build a ping, answered by a pong with the same id.

Source code in src/nyx_bridge/protocol.py
220
221
222
def make_ping(request_id: str) -> dict:
    """Build a ping, answered by a pong with the same id."""
    return {"type": MessageType.PING, "id": request_id}

make_pong(request_id)

Build the answer to a ping.

Source code in src/nyx_bridge/protocol.py
225
226
227
def make_pong(request_id: str | None) -> dict:
    """Build the answer to a ping."""
    return {"type": MessageType.PONG, "id": request_id}

make_result(request_id, ok, value=None, error=None, stdout='', stderr='')

Build the answer to an execute request.

On failure error is {"type", "message", "traceback"}.

Source code in src/nyx_bridge/protocol.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
def make_result(
    request_id: str | None,
    ok: bool,
    value: typing.Any = None,
    error: dict | None = None,
    stdout: str = "",
    stderr: str = "",
) -> dict:
    """Build the answer to an execute request.

    On failure `error` is `{"type", "message", "traceback"}`.
    """
    return {
        "type": MessageType.RESULT,
        "id": request_id,
        "ok": ok,
        "value": value,
        "error": error,
        "stdout": stdout,
        "stderr": stderr,
    }

make_shutdown()

Build the message asking a client to disconnect and stop serving.

Source code in src/nyx_bridge/protocol.py
230
231
232
def make_shutdown() -> dict:
    """Build the message asking a client to disconnect and stop serving."""
    return {"type": MessageType.SHUTDOWN}

parse_address(text)

Split host:port.

Parameters:

Name Type Description Default
text str

address, a bare port means the default host.

required

Raises:

Type Description
ValueError

text is not an address.

Returns:

Type Description
tuple[str, int]

tuple[str, int]: host and port.

Source code in src/nyx_bridge/protocol.py
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
def parse_address(text: str) -> tuple[str, int]:
    """Split `host:port`.

    Args:
        text (str): address, a bare port means the default host.

    Raises:
        ValueError: text is not an address.

    Returns:
        tuple[str, int]: host and port.
    """
    host, separator, port = text.strip().rpartition(":")
    if not separator:
        host, port = DEFAULT_HOST, text.strip()
    return host or DEFAULT_HOST, int(port)

read_address_file(path)

Read a file written by write_address_file.

Parameters:

Name Type Description Default
path str | PathLike

address file.

required

Returns:

Name Type Description
Address Address

host, port and token.

Source code in src/nyx_bridge/protocol.py
303
304
305
306
307
308
309
310
311
312
313
314
def read_address_file(path: str | os.PathLike) -> Address:
    """Read a file written by `write_address_file`.

    Args:
        path (str | os.PathLike): address file.

    Returns:
        Address: host, port and token.
    """
    with open(path, encoding="utf-8") as address_file:
        data = json.load(address_file)
    return Address(data["host"], int(data["port"]), data.get("token", ""))

recv_message(sock)

Block until a whole message is read.

Parameters:

Name Type Description Default
sock socket

connected socket.

required

Raises:

Type Description
ConnectionClosed

connection closed or broken.

ProtocolError

invalid frame, size or payload.

TimeoutError

socket timeout expired.

Returns:

Name Type Description
dict dict

message.

Source code in src/nyx_bridge/protocol.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def recv_message(sock: socket.socket) -> dict:
    """Block until a whole message is read.

    Args:
        sock (socket.socket): connected socket.

    Raises:
        ConnectionClosed: connection closed or broken.
        ProtocolError: invalid frame, size or payload.
        TimeoutError: socket timeout expired.

    Returns:
        dict: message.
    """
    (size,) = _HEADER.unpack(_recv_exact(sock, _HEADER.size))
    if size > MAX_MESSAGE_SIZE:
        raise ProtocolError(f"Message too large: {size} bytes")
    payload = _recv_exact(sock, size)
    try:
        message = json.loads(payload.decode("utf-8"))
    except ValueError as err:
        raise ProtocolError(f"Invalid message payload: {err}") from err
    if not isinstance(message, dict) or not isinstance(message.get("type"), str):
        raise ProtocolError("Message has to be an object with a string `type`")
    return message

send_message(sock, message)

Send a message. Callers sharing a socket between threads have to lock.

Parameters:

Name Type Description Default
sock socket

connected socket.

required
message dict

JSON serializable message.

required
Source code in src/nyx_bridge/protocol.py
85
86
87
88
89
90
91
92
def send_message(sock: socket.socket, message: dict) -> None:
    """Send a message. Callers sharing a socket between threads have to lock.

    Args:
        sock (socket.socket): connected socket.
        message (dict): JSON serializable message.
    """
    sock.sendall(encode_message(message))

to_jsonable(value, _depth=0)

Convert a value to something JSON can carry.

Containers are converted item by item. Anything else that JSON can't carry, like an object of the application, becomes its repr.

Parameters:

Name Type Description Default
value Any

value to convert.

required

Returns:

Name Type Description
Any Any

JSON serializable value.

Source code in src/nyx_bridge/protocol.py
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
def to_jsonable(value: typing.Any, _depth: int = 0) -> typing.Any:
    """Convert a value to something JSON can carry.

    Containers are converted item by item. Anything else that JSON can't carry, like
    an object of the application, becomes its `repr`.

    Args:
        value (Any): value to convert.

    Returns:
        Any: JSON serializable value.
    """
    if value is None or isinstance(value, (bool, int, float, str)):
        return value
    if _depth < _MAX_JSON_DEPTH:
        if isinstance(value, (list, tuple, set, frozenset)):
            return [to_jsonable(item, _depth + 1) for item in value]
        if isinstance(value, dict):
            return {
                str(key): to_jsonable(item, _depth + 1) for key, item in value.items()
            }
    try:
        return repr(value)
    except Exception:
        return f"<unrepresentable {type(value).__name__}>"

write_address_file(path, host, port, token)

Write where a server listens, so clients on the machine can find it.

The file holds the token, so it is made readable by the owner only where possible.

Parameters:

Name Type Description Default
path str | PathLike

file to write.

required
host str

server host.

required
port int

server port.

required
token str

server token.

required
Source code in src/nyx_bridge/protocol.py
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
def write_address_file(
    path: str | os.PathLike, host: str, port: int, token: str
) -> None:
    """Write where a server listens, so clients on the machine can find it.

    The file holds the token, so it is made readable by the owner only where possible.

    Args:
        path (str | os.PathLike): file to write.
        host (str): server host.
        port (int): server port.
        token (str): server token.
    """
    with open(path, "w", encoding="utf-8") as address_file:
        json.dump({"host": host, "port": port, "token": token}, address_file)
    try:
        os.chmod(path, 0o600)
    except OSError:
        pass