| 1 |
import asyncio |
| 2 |
import json |
| 3 |
import os |
| 4 |
import sys |
| 5 |
from abc import ABC, abstractmethod |
| 6 |
from dataclasses import dataclass, field |
| 7 |
from typing import Any, BinaryIO, Dict, Iterable, Optional |
| 8 |
|
| 9 |
from .version import __version__ |
| 10 |
|
| 11 |
_TYPE = "type" |
| 12 |
_DATA = "data" |
| 13 |
_DATA_LENGTH = "data_length" |
| 14 |
_PAYLOAD_LENGTH = "payload_length" |
| 15 |
_NEWLINE = "\n".encode() |
| 16 |
_VERSION = "version" |
| 17 |
_VERSION_NUMBER = __version__ |
| 18 |
|
| 19 |
|
| 20 |
@dataclass |
| 21 |
class Event: |
| 22 |
type: str |
| 23 |
data: Dict[str, Any] = field(default_factory=dict) |
| 24 |
payload: Optional[bytes] = None |
| 25 |
|
| 26 |
def to_dict(self) -> Dict[str, Any]: |
| 27 |
return {_TYPE: self.type, _DATA: self.data} |
| 28 |
|
| 29 |
@staticmethod |
| 30 |
def from_dict(event_dict: Dict[str, Any]) -> "Event": |
| 31 |
return Event(type=event_dict["type"], data=event_dict.get("data", {})) |
| 32 |
|
| 33 |
|
| 34 |
class Eventable(ABC): |
| 35 |
@abstractmethod |
| 36 |
def event(self) -> Event: |
| 37 |
pass |
| 38 |
|
| 39 |
@staticmethod |
| 40 |
@abstractmethod |
| 41 |
def is_type(event_type: str) -> bool: |
| 42 |
pass |
| 43 |
|
| 44 |
def to_dict(self) -> Dict[str, Any]: |
| 45 |
return self.event().data |
| 46 |
|
| 47 |
@staticmethod |
| 48 |
@abstractmethod |
| 49 |
def from_event(event: Event) -> "Eventable": |
| 50 |
pass |
| 51 |
|
| 52 |
|
| 53 |
async def async_get_stdin( |
| 54 |
loop: Optional[asyncio.AbstractEventLoop] = None, |
| 55 |
) -> asyncio.StreamReader: |
| 56 |
"""Get StreamReader for stdin.""" |
| 57 |
if loop is None: |
| 58 |
loop = asyncio.get_running_loop() |
| 59 |
|
| 60 |
reader = asyncio.StreamReader() |
| 61 |
await loop.connect_read_pipe( |
| 62 |
lambda: asyncio.StreamReaderProtocol(reader), sys.stdin |
| 63 |
) |
| 64 |
|
| 65 |
return reader |
| 66 |
|
| 67 |
|
| 68 |
async def async_get_stdout( |
| 69 |
loop: Optional[asyncio.AbstractEventLoop] = None, |
| 70 |
) -> asyncio.StreamWriter: |
| 71 |
"""Get StreamWriter for stdout.""" |
| 72 |
if loop is None: |
| 73 |
loop = asyncio.get_running_loop() |
| 74 |
|
| 75 |
writer_transport, writer_protocol = await loop.connect_write_pipe( |
| 76 |
lambda: asyncio.streams.FlowControlMixin(loop=loop), |
| 77 |
os.fdopen(sys.stdout.fileno(), "wb"), |
| 78 |
) |
| 79 |
return asyncio.streams.StreamWriter(writer_transport, writer_protocol, None, loop) |
| 80 |
|
| 81 |
|
| 82 |
async def async_read_event(reader: asyncio.StreamReader) -> Optional[Event]: |
| 83 |
try: |
| 84 |
json_line = await reader.readline() |
| 85 |
if not json_line: |
| 86 |
return None |
| 87 |
|
| 88 |
event_dict = json.loads(json_line) |
| 89 |
data_length = event_dict.get(_DATA_LENGTH) |
| 90 |
if (data_length is not None) and (data_length > 0): |
| 91 |
# Merge data |
| 92 |
data_bytes = await reader.readexactly(data_length) |
| 93 |
data_dict = event_dict.get(_DATA, {}) |
| 94 |
data_dict.update(json.loads(data_bytes)) |
| 95 |
event_dict[_DATA] = data_dict |
| 96 |
|
| 97 |
payload_length = event_dict.get(_PAYLOAD_LENGTH) |
| 98 |
|
| 99 |
payload: Optional[bytes] = None |
| 100 |
if (payload_length is not None) and (payload_length > 0): |
| 101 |
payload = await reader.readexactly(payload_length) |
| 102 |
|
| 103 |
return Event( |
| 104 |
type=event_dict[_TYPE], data=event_dict.get(_DATA, {}), payload=payload |
| 105 |
) |
| 106 |
except (KeyboardInterrupt, ValueError): |
| 107 |
pass |
| 108 |
|
| 109 |
return None |
| 110 |
|
| 111 |
|
| 112 |
async def async_write_event(event: Event, writer: asyncio.StreamWriter): |
| 113 |
event_dict: Dict[str, Any] = event.to_dict() |
| 114 |
event_dict[_VERSION] = _VERSION_NUMBER |
| 115 |
|
| 116 |
data_dict = event_dict.pop(_DATA, None) |
| 117 |
data_bytes: Optional[bytes] = None |
| 118 |
if data_dict: |
| 119 |
data_bytes = json.dumps(data_dict, ensure_ascii=False).encode("utf-8") |
| 120 |
event_dict[_DATA_LENGTH] = len(data_bytes) |
| 121 |
|
| 122 |
if event.payload: |
| 123 |
event_dict[_PAYLOAD_LENGTH] = len(event.payload) |
| 124 |
|
| 125 |
json_line = json.dumps(event_dict, ensure_ascii=False) |
| 126 |
|
| 127 |
try: |
| 128 |
writer.writelines((json_line.encode(), _NEWLINE)) |
| 129 |
|
| 130 |
if data_bytes: |
| 131 |
writer.write(data_bytes) |
| 132 |
|
| 133 |
if event.payload: |
| 134 |
writer.write(event.payload) |
| 135 |
|
| 136 |
await writer.drain() |
| 137 |
except KeyboardInterrupt: |
| 138 |
pass |
| 139 |
|
| 140 |
|
| 141 |
async def async_write_events(events: Iterable[Event], writer: asyncio.StreamWriter): |
| 142 |
try: |
| 143 |
await asyncio.gather(*(async_write_event(event, writer) for event in events)) |
| 144 |
except KeyboardInterrupt: |
| 145 |
pass |
| 146 |
|
| 147 |
|
| 148 |
def read_event(reader: Optional[BinaryIO] = None) -> Optional[Event]: |
| 149 |
if reader is None: |
| 150 |
reader = sys.stdin.buffer |
| 151 |
|
| 152 |
try: |
| 153 |
json_line = reader.readline() |
| 154 |
|
| 155 |
if not json_line: |
| 156 |
return None |
| 157 |
|
| 158 |
event_dict = json.loads(json_line) |
| 159 |
data_length = event_dict.get(_DATA_LENGTH) |
| 160 |
if (data_length is not None) and (data_length > 0): |
| 161 |
# Merge data |
| 162 |
data_bytes = reader.read(data_length) |
| 163 |
while len(data_bytes) < data_length: |
| 164 |
chunk = reader.read(data_length - len(data_bytes)) |
| 165 |
if not chunk: |
| 166 |
# Stream closed before all data was read |
| 167 |
return None |
| 168 |
data_bytes += chunk |
| 169 |
|
| 170 |
data_dict = event_dict.get(_DATA, {}) |
| 171 |
data_dict.update(json.loads(data_bytes)) |
| 172 |
event_dict[_DATA] = data_dict |
| 173 |
|
| 174 |
payload_length = event_dict.get(_PAYLOAD_LENGTH) |
| 175 |
|
| 176 |
payload: Optional[bytes] = None |
| 177 |
if (payload_length is not None) and (payload_length > 0): |
| 178 |
payload = reader.read(payload_length) |
| 179 |
while len(payload) < payload_length: |
| 180 |
chunk = reader.read(payload_length - len(payload)) |
| 181 |
if not chunk: |
| 182 |
# Stream closed before all data was read |
| 183 |
return None |
| 184 |
payload += chunk |
| 185 |
|
| 186 |
return Event( |
| 187 |
type=event_dict[_TYPE], data=event_dict.get(_DATA, {}), payload=payload |
| 188 |
) |
| 189 |
except (KeyboardInterrupt, ValueError): |
| 190 |
pass |
| 191 |
|
| 192 |
return None |
| 193 |
|
| 194 |
|
| 195 |
def write_event(event: Event, writer: Optional[BinaryIO] = None): |
| 196 |
if writer is None: |
| 197 |
writer = sys.stdout.buffer |
| 198 |
|
| 199 |
event_dict: Dict[str, Any] = event.to_dict() |
| 200 |
event_dict[_VERSION] = _VERSION_NUMBER |
| 201 |
|
| 202 |
data_dict = event_dict.pop(_DATA, None) |
| 203 |
data_bytes: Optional[bytes] = None |
| 204 |
if data_dict: |
| 205 |
data_bytes = json.dumps(data_dict, ensure_ascii=False).encode("utf-8") |
| 206 |
event_dict[_DATA_LENGTH] = len(data_bytes) |
| 207 |
|
| 208 |
if event.payload: |
| 209 |
event_dict[_PAYLOAD_LENGTH] = len(event.payload) |
| 210 |
|
| 211 |
json_line = json.dumps(event_dict, ensure_ascii=False) |
| 212 |
|
| 213 |
try: |
| 214 |
writer.writelines((json_line.encode(), _NEWLINE)) |
| 215 |
|
| 216 |
if data_bytes: |
| 217 |
writer.write(data_bytes) |
| 218 |
|
| 219 |
if event.payload: |
| 220 |
writer.write(event.payload) |
| 221 |
|
| 222 |
writer.flush() |
| 223 |
except KeyboardInterrupt: |
| 224 |
pass |