ouisync.service

In-process embedding of the Ouisync service

  1"""In-process embedding of the Ouisync service"""
  2
  3import asyncio
  4import ctypes
  5
  6from ouisync.session import ErrorCode, dispatch_error
  7
  8from ._bindings import StatusCallback, bindings
  9
 10__all__ = ["Service", "init_log"]
 11
 12
 13class Service:
 14    """Manages the repositories and runs the sync protocol. It can be
 15    interacted with using a [Session][ouisync.session.Session] connected to
 16    the same config directory.
 17
 18    Note: to create a service, use `Service.start`.
 19    """
 20
 21    def __init__(self, handle: int):
 22        self._handle: int | None = handle
 23
 24    @classmethod
 25    async def start(
 26        cls,
 27        config_path,
 28        debug_label: str | None = None,
 29        local_endpoint: str | None = None,
 30    ) -> "Service":
 31        """Starts the service.
 32
 33        `config_path` is the path to the config directory of this service.
 34        If it doesn't exist, it's created automatically. The service requires
 35        both read and write access to it.
 36
 37        `debug_label` is an optional label used to distinguish multiple
 38        services running in the same process. Used mainly for testing and
 39        debugging the library itself.
 40
 41        `local_endpoint` is an optional endpoint the service listens on for
 42        local client connections. It's either a unix domain socket
 43        (`"unix:///path/to/socket"`, relative paths are resolved against the
 44        config dir) or a TCP endpoint with an auth key
 45        (`"tcp://127.0.0.1:12345?auth_key=<64 hex digits>"`, port 0 picks a
 46        random free port). If `None`, the endpoint from
 47        `<config_path>/local_endpoint.conf` is used, or the platform default
 48        if there is none. Either way the actual endpoint is written to
 49        `local_endpoint.conf` so that clients can find it.
 50        """
 51        error_code, handle = await _invoke(
 52            bindings().start_service,
 53            str(config_path).encode(),
 54            local_endpoint.encode() if local_endpoint is not None else None,
 55            debug_label.encode() if debug_label is not None else None,
 56        )
 57
 58        if error_code != ErrorCode.OK:
 59            # The handle must be released even if the service failed to start. The callback is
 60            # never invoked in that case.
 61            bindings().stop_service(handle, _noop_callback, None)
 62            raise dispatch_error(error_code)
 63
 64        return cls(handle)
 65
 66    async def stop(self):
 67        """Stops this service. Has no effect if the service has already been
 68        stopped."""
 69        handle = self._handle
 70        if handle is None:
 71            return
 72
 73        self._handle = None
 74
 75        error_code, _ = await _invoke(bindings().stop_service, handle)
 76
 77        if error_code != ErrorCode.OK:
 78            raise dispatch_error(error_code)
 79
 80
 81async def _invoke(func, *args):
 82    """Calls one of the `start_service`/`stop_service` native functions,
 83    appending the status callback and its (unused) context, and awaits its
 84    completion. Returns `(error_code, return_value)`."""
 85    loop = asyncio.get_running_loop()
 86    future: asyncio.Future = loop.create_future()
 87
 88    # The callback may be invoked from a thread other than this one, so it
 89    # must hand the result back to the event loop thread-safely. Kept alive
 90    # by this frame for as long as the native side may still call it.
 91    @StatusCallback
 92    def callback(_context: ctypes.c_void_p, error_code: int):
 93        loop.call_soon_threadsafe(_resolve, future, error_code)
 94
 95    return_value = func(*args, callback, None)
 96    error_code = ErrorCode(await future)
 97
 98    return error_code, return_value
 99
100
101@StatusCallback
102def _noop_callback(_context: ctypes.c_void_p, _error_code: int):
103    pass
104
105
106def _resolve(future: asyncio.Future, error_code: int):
107    if not future.done():
108        future.set_result(error_code)
109
110
111def init_log():
112    """Enables logging of Ouisync's internal messages.
113
114    Calling this function more than once has no effect. Currently there is
115    no way to disable the logging once it's been enabled.
116    """
117    bindings().init_log()
class Service:
14class Service:
15    """Manages the repositories and runs the sync protocol. It can be
16    interacted with using a [Session][ouisync.session.Session] connected to
17    the same config directory.
18
19    Note: to create a service, use `Service.start`.
20    """
21
22    def __init__(self, handle: int):
23        self._handle: int | None = handle
24
25    @classmethod
26    async def start(
27        cls,
28        config_path,
29        debug_label: str | None = None,
30        local_endpoint: str | None = None,
31    ) -> "Service":
32        """Starts the service.
33
34        `config_path` is the path to the config directory of this service.
35        If it doesn't exist, it's created automatically. The service requires
36        both read and write access to it.
37
38        `debug_label` is an optional label used to distinguish multiple
39        services running in the same process. Used mainly for testing and
40        debugging the library itself.
41
42        `local_endpoint` is an optional endpoint the service listens on for
43        local client connections. It's either a unix domain socket
44        (`"unix:///path/to/socket"`, relative paths are resolved against the
45        config dir) or a TCP endpoint with an auth key
46        (`"tcp://127.0.0.1:12345?auth_key=<64 hex digits>"`, port 0 picks a
47        random free port). If `None`, the endpoint from
48        `<config_path>/local_endpoint.conf` is used, or the platform default
49        if there is none. Either way the actual endpoint is written to
50        `local_endpoint.conf` so that clients can find it.
51        """
52        error_code, handle = await _invoke(
53            bindings().start_service,
54            str(config_path).encode(),
55            local_endpoint.encode() if local_endpoint is not None else None,
56            debug_label.encode() if debug_label is not None else None,
57        )
58
59        if error_code != ErrorCode.OK:
60            # The handle must be released even if the service failed to start. The callback is
61            # never invoked in that case.
62            bindings().stop_service(handle, _noop_callback, None)
63            raise dispatch_error(error_code)
64
65        return cls(handle)
66
67    async def stop(self):
68        """Stops this service. Has no effect if the service has already been
69        stopped."""
70        handle = self._handle
71        if handle is None:
72            return
73
74        self._handle = None
75
76        error_code, _ = await _invoke(bindings().stop_service, handle)
77
78        if error_code != ErrorCode.OK:
79            raise dispatch_error(error_code)

Manages the repositories and runs the sync protocol. It can be interacted with using a [Session][ouisync.session.Session] connected to the same config directory.

Note: to create a service, use Service.start.

Service(handle: int)
22    def __init__(self, handle: int):
23        self._handle: int | None = handle
@classmethod
async def start( cls, config_path, debug_label: str | None = None, local_endpoint: str | None = None) -> Service:
25    @classmethod
26    async def start(
27        cls,
28        config_path,
29        debug_label: str | None = None,
30        local_endpoint: str | None = None,
31    ) -> "Service":
32        """Starts the service.
33
34        `config_path` is the path to the config directory of this service.
35        If it doesn't exist, it's created automatically. The service requires
36        both read and write access to it.
37
38        `debug_label` is an optional label used to distinguish multiple
39        services running in the same process. Used mainly for testing and
40        debugging the library itself.
41
42        `local_endpoint` is an optional endpoint the service listens on for
43        local client connections. It's either a unix domain socket
44        (`"unix:///path/to/socket"`, relative paths are resolved against the
45        config dir) or a TCP endpoint with an auth key
46        (`"tcp://127.0.0.1:12345?auth_key=<64 hex digits>"`, port 0 picks a
47        random free port). If `None`, the endpoint from
48        `<config_path>/local_endpoint.conf` is used, or the platform default
49        if there is none. Either way the actual endpoint is written to
50        `local_endpoint.conf` so that clients can find it.
51        """
52        error_code, handle = await _invoke(
53            bindings().start_service,
54            str(config_path).encode(),
55            local_endpoint.encode() if local_endpoint is not None else None,
56            debug_label.encode() if debug_label is not None else None,
57        )
58
59        if error_code != ErrorCode.OK:
60            # The handle must be released even if the service failed to start. The callback is
61            # never invoked in that case.
62            bindings().stop_service(handle, _noop_callback, None)
63            raise dispatch_error(error_code)
64
65        return cls(handle)

Starts the service.

config_path is the path to the config directory of this service. If it doesn't exist, it's created automatically. The service requires both read and write access to it.

debug_label is an optional label used to distinguish multiple services running in the same process. Used mainly for testing and debugging the library itself.

local_endpoint is an optional endpoint the service listens on for local client connections. It's either a unix domain socket ("unix:///path/to/socket", relative paths are resolved against the config dir) or a TCP endpoint with an auth key ("tcp://127.0.0.1:12345?auth_key=<64 hex digits>", port 0 picks a random free port). If None, the endpoint from <config_path>/local_endpoint.conf is used, or the platform default if there is none. Either way the actual endpoint is written to local_endpoint.conf so that clients can find it.

async def stop(self):
67    async def stop(self):
68        """Stops this service. Has no effect if the service has already been
69        stopped."""
70        handle = self._handle
71        if handle is None:
72            return
73
74        self._handle = None
75
76        error_code, _ = await _invoke(bindings().stop_service, handle)
77
78        if error_code != ErrorCode.OK:
79            raise dispatch_error(error_code)

Stops this service. Has no effect if the service has already been stopped.

def init_log():
112def init_log():
113    """Enables logging of Ouisync's internal messages.
114
115    Calling this function more than once has no effect. Currently there is
116    no way to disable the logging once it's been enabled.
117    """
118    bindings().init_log()

Enables logging of Ouisync's internal messages.

Calling this function more than once has no effect. Currently there is no way to disable the logging once it's been enabled.