Every public symbol, signatures, and edge cases.
Encode a JSON-serialisable payload as one framed line:
json.dumps(payload) + "\n", UTF-8 encoded, with ensure_ascii=False
and compact separators (",", ":").
Raises ValueError if the encoded payload itself somehow contains a
raw newline (would break framing).
Yield parsed objects from a readable binary stream. Reads one line at a time; blank lines are skipped; iteration stops on EOF.
Decode a single framed line (trailing newline optional).
Threaded Unix-domain-socket server.
| Parameter | Type | Default | Notes |
|---|---|---|---|
path |
str / PathLike |
— | Filesystem path for the socket. |
handler |
`Callable[[dict], dict | None]` | — |
mode |
int |
0o600 |
Permissions applied with chmod after bind. |
backlog |
int |
16 |
listen() backlog. |
Bind, chmod, listen, start a daemon accept-loop thread. Raises
RuntimeError if already started. Cleans up stale socket files
(socket node exists but nobody listening); raises FileExistsError
if the path is in use by a live server or is not a socket node.
Signal the accept loop, close the listening socket, join worker
threads (best-effort, up to timeout each), unlink the socket file.
with UnixServer(...) as srv: ... calls start() / stop().
- Returns
dict→ response is sent as one JSON line. - Returns
None→ no response (notification). - Raises
Exception→ server replies with{"error": str(exc), "type": type(exc).__name__}and continues serving.
Synchronous Unix-socket client.
| Parameter | Type | Default | Notes |
|---|---|---|---|
path |
str / PathLike |
— | Server socket path. |
timeout |
float |
5.0 |
Per-connection socket timeout (seconds). |
retries |
int |
3 |
Additional attempts after the first failure (4 total). |
retry_backoff |
float |
0.5 |
Initial backoff (seconds); doubles per retry. |
Send one JSON line, read one JSON line back. Raises
ConnectionError if the server closes the connection without
responding, or if all retry attempts fail.
Send one JSON line and close. Does not read a response.
Retries cover the connect step only — ConnectionRefusedError
and FileNotFoundError (and other OSError subclasses raised by
socket.connect()). Backoff schedule: 0.5s, 1.0s, 2.0s, …
(doubling). Once a connection succeeds, the subsequent sendall /
readline are not retried.
Named-pipe (FIFO) channel with JSON-line framing.
Constructor auto-creates the FIFO with mkfifo(path, mode) if
missing. Raises FileExistsError if the path exists and is not a
FIFO.
Open the FIFO in O_WRONLY | O_NONBLOCK mode, write one JSON line,
close. Raises BrokenPipeError if no reader is attached (kernel
returns ENXIO).
Open the FIFO blocking and return the next decoded message. Blocks until a writer attaches and sends one full JSON line.
Remove the FIFO from the filesystem (idempotent — no error if already gone).
Exclusive PID-file context manager.
- Creates the parent directory.
- Opens the file with
O_RDWR | O_CREAT, mode=0o600. - Takes
fcntl.flock(LOCK_EX | LOCK_NB). If another process holds the lock, raisesBlockingIOErrorimmediately. - Truncates and writes
f"{os.getpid()}\n", fsyncs. - On exit: releases the lock, removes the file, closes the fd.
Useful for sidecar daemons that must not run twice.
try:
with pidfile("/run/codechu/myapp/daemon.pid"):
run()
except BlockingIOError:
sys.exit("already running")