Verified Commit 4cbd19a2 authored by Jakob Moser's avatar Jakob Moser
Browse files

Add client for JSON via Unix Socket wiring

parent c2666da6
Loading
Loading
Loading
Loading

poolpay/wire/Client.py

0 → 100644
+40 −0
Original line number Diff line number Diff line
import json
import socket
from collections.abc import Callable
from contextlib import AbstractContextManager
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Self

from poolpay.wire.Message import Message


@dataclass
class Client(AbstractContextManager):
    socket_path: Path
    _socket: socket.socket = field(init=False)

    def __enter__(self) -> Self:
        self._socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        self._socket.connect(str(self.socket_path.resolve()))
        return self

    def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
        self._socket.close()

    def send(self, message: Message) -> Message:
        """
        Send the given message to the server and returns the server's response.
        """
        self._socket.sendall((json.dumps(message) + "\n").encode("utf-8"))
        # TODO What if the response is longer than 1024 bytes?
        response = self._socket.recv(1024)
        return json.loads(response.decode("utf-8"))

    def on_receive_push(self, handle_message: Callable[[Message], None]) -> None:
        """
        Register a handler that is called whenever the client receives a push message from the server (i.e a message
        that is not a response to a previously sent message).
        """
        # TODO Handle receiving push messages
        raise NotImplementedError()
+3 −0
Original line number Diff line number Diff line
from typing import Any

type Message = dict[str, Any]
+0 −0

Empty file added.