File: server.py

package info (click to toggle)
python-wyoming 1.8.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 376 kB
  • sloc: python: 3,025; makefile: 3
file content (211 lines) | stat: -rw-r--r-- 6,831 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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
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
163
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import asyncio
import sys
from abc import ABC, abstractmethod
from functools import partial
from pathlib import Path
from typing import Callable, Dict, Optional, Union
from urllib.parse import urlparse

from .event import Event, async_get_stdin, async_read_event, async_write_event


class AsyncEventHandler(ABC):
    """Base class for async Wyoming event handler."""

    def __init__(
        self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
    ) -> None:
        self.reader = reader
        self.writer = writer
        self._is_running = False

    @abstractmethod
    async def handle_event(self, event: Event) -> bool:
        """Handle an event. Returning false will disconnect the client."""
        return True

    async def write_event(self, event: Event) -> None:
        """Send an event to the client."""
        await async_write_event(event, self.writer)

    async def run(self) -> None:
        """Receive events until stopped or handle_event returns false."""
        self._is_running = True

        try:
            while self._is_running:
                event = await async_read_event(self.reader)
                if event is None:
                    break

                if not (await self.handle_event(event)):
                    break
        finally:
            await self.disconnect()

    async def disconnect(self) -> None:
        """Called when client disconnects."""

    async def stop(self) -> None:
        """Try to stop the event handler."""
        self._is_running = False
        self.writer.close()
        self.reader.feed_eof()


HandlerFactory = Callable[
    [asyncio.StreamReader, asyncio.StreamWriter], AsyncEventHandler
]


class AsyncServer(ABC):
    """Base class for async Wyoming server."""

    def __init__(self) -> None:
        self._handlers: Dict[asyncio.Task, AsyncEventHandler] = {}

    @abstractmethod
    async def run(self, handler_factory: HandlerFactory) -> None:
        """Start server and block while running."""

    @staticmethod
    def from_uri(uri: str) -> "AsyncServer":
        """Create server from URI."""
        result = urlparse(uri)

        if result.scheme == "unix":
            return AsyncUnixServer(result.path)

        if result.scheme == "tcp":
            if (result.hostname is None) or (result.port is None):
                raise ValueError("A port must be specified when using a 'tcp://' URI")

            return AsyncTcpServer(result.hostname, result.port)

        if result.scheme == "stdio":
            return AsyncStdioServer()

        raise ValueError("Only 'stdio://', 'unix://', or 'tcp://' are supported")

    async def _handler_callback(
        self,
        handler_factory: HandlerFactory,
        reader: asyncio.StreamReader,
        writer: asyncio.StreamWriter,
    ):
        handler = handler_factory(reader, writer)
        task = asyncio.create_task(handler.run(), name="wyoming event handler")
        self._handlers[task] = handler
        task.add_done_callback(lambda t: self._handlers.pop(t, None))

    async def start(self, handler_factory: HandlerFactory) -> None:
        """Start server without blocking."""

    async def stop(self) -> None:
        """Try to stop all event handlers."""
        await asyncio.gather(*(h.stop() for h in self._handlers.values()))


class AsyncStdioServer(AsyncServer):
    """Wyoming server over stdin/stdout."""

    async def run(self, handler_factory: HandlerFactory) -> None:
        """Start server and block while running."""
        reader = await async_get_stdin()

        # Get stdout writer.
        # NOTE: This will make print() non-blocking.
        loop = asyncio.get_running_loop()
        writer_transport, writer_protocol = await loop.connect_write_pipe(
            asyncio.streams.FlowControlMixin, sys.stdout
        )
        writer = asyncio.StreamWriter(writer_transport, writer_protocol, None, loop)

        handler = handler_factory(reader, writer)
        while True:
            event = await async_read_event(reader)
            if event is None:
                break

            if not (await handler.handle_event(event)):
                break


class AsyncTcpServer(AsyncServer):
    """Wyoming server over TCP."""

    def __init__(self, host: str, port: int) -> None:
        super().__init__()
        self.host = host
        self.port = port
        self._server: Optional[asyncio.AbstractServer] = None

    async def run(self, handler_factory: HandlerFactory) -> None:
        handler_callback = partial(self._handler_callback, handler_factory)
        self._server = await asyncio.start_server(
            handler_callback, host=self.host, port=self.port
        )

        await self._server.serve_forever()

    async def start(self, handler_factory: HandlerFactory) -> None:
        """Start server without blocking."""
        handler_callback = partial(self._handler_callback, handler_factory)
        self._server = await asyncio.start_server(
            handler_callback, host=self.host, port=self.port
        )

        await self._server.start_serving()

    async def stop(self) -> None:
        """Try to stop all event handlers."""
        await super().stop()

        if self._server is not None:
            self._server.close()


class AsyncUnixServer(AsyncServer):
    """Wyoming server over a Unix domain socket."""

    def __init__(self, socket_path: Union[str, Path]) -> None:
        super().__init__()
        self.socket_path = Path(socket_path)
        self._server: Optional[asyncio.AbstractServer] = None

    async def run(self, handler_factory: HandlerFactory) -> None:
        """Start server and block while running."""
        # Need to unlink socket file if it exists
        self.socket_path.unlink(missing_ok=True)

        handler_callback = partial(self._handler_callback, handler_factory)
        self._server = await asyncio.start_unix_server(
            handler_callback, path=self.socket_path
        )

        try:
            await self._server.serve_forever()
        finally:
            # Unlink when we're done
            self.socket_path.unlink(missing_ok=True)

    async def start(self, handler_factory: HandlerFactory) -> None:
        """Start server without blocking."""
        # Need to unlink socket file if it exists
        self.socket_path.unlink(missing_ok=True)

        handler_callback = partial(self._handler_callback, handler_factory)
        self._server = await asyncio.start_unix_server(
            handler_callback, path=self.socket_path
        )

        await self._server.start_serving()

    async def stop(self) -> None:
        """Try to stop all event handlers."""
        await super().stop()

        if self._server is not None:
            self._server.close()

        self.socket_path.unlink(missing_ok=True)