File size: 9,550 Bytes
2eafbc4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import asyncio
import json
from asyncio import StreamReader, StreamWriter
from json import JSONDecodeError
from typing import Optional, Tuple

from inference.core import logger
from inference.enterprise.stream_management.api.entities import (
    CommandContext,
    CommandResponse,
    InferencePipelineStatusResponse,
    ListPipelinesResponse,
    PipelineInitialisationRequest,
)
from inference.enterprise.stream_management.api.errors import (
    ConnectivityError,
    ProcessesManagerAuthorisationError,
    ProcessesManagerClientError,
    ProcessesManagerInternalError,
    ProcessesManagerInvalidPayload,
    ProcessesManagerNotFoundError,
    ProcessesManagerOperationError,
)
from inference.enterprise.stream_management.manager.entities import (
    ERROR_TYPE_KEY,
    PIPELINE_ID_KEY,
    REQUEST_ID_KEY,
    RESPONSE_KEY,
    STATUS_KEY,
    TYPE_KEY,
    CommandType,
    ErrorType,
    OperationStatus,
)
from inference.enterprise.stream_management.manager.errors import (
    CommunicationProtocolError,
    MalformedHeaderError,
    MalformedPayloadError,
    MessageToBigError,
    TransmissionChannelClosed,
)

BUFFER_SIZE = 16384
HEADER_SIZE = 4

ERRORS_MAPPING = {
    ErrorType.INTERNAL_ERROR.value: ProcessesManagerInternalError,
    ErrorType.INVALID_PAYLOAD.value: ProcessesManagerInvalidPayload,
    ErrorType.NOT_FOUND.value: ProcessesManagerNotFoundError,
    ErrorType.OPERATION_ERROR.value: ProcessesManagerOperationError,
    ErrorType.AUTHORISATION_ERROR.value: ProcessesManagerAuthorisationError,
}


class StreamManagerClient:
    @classmethod
    def init(
        cls,
        host: str,
        port: int,
        operations_timeout: Optional[float] = None,
        header_size: int = HEADER_SIZE,
        buffer_size: int = BUFFER_SIZE,
    ) -> "StreamManagerClient":
        return cls(
            host=host,
            port=port,
            operations_timeout=operations_timeout,
            header_size=header_size,
            buffer_size=buffer_size,
        )

    def __init__(
        self,
        host: str,
        port: int,
        operations_timeout: Optional[float],
        header_size: int,
        buffer_size: int,
    ):
        self._host = host
        self._port = port
        self._operations_timeout = operations_timeout
        self._header_size = header_size
        self._buffer_size = buffer_size

    async def list_pipelines(self) -> ListPipelinesResponse:
        command = {
            TYPE_KEY: CommandType.LIST_PIPELINES,
        }
        response = await self._handle_command(command=command)
        status = response[RESPONSE_KEY][STATUS_KEY]
        context = CommandContext(
            request_id=response.get(REQUEST_ID_KEY),
            pipeline_id=response.get(PIPELINE_ID_KEY),
        )
        pipelines = response[RESPONSE_KEY]["pipelines"]
        return ListPipelinesResponse(
            status=status,
            context=context,
            pipelines=pipelines,
        )

    async def initialise_pipeline(
        self, initialisation_request: PipelineInitialisationRequest
    ) -> CommandResponse:
        command = initialisation_request.dict(exclude_none=True)
        command[TYPE_KEY] = CommandType.INIT
        response = await self._handle_command(command=command)
        return build_response(response=response)

    async def terminate_pipeline(self, pipeline_id: str) -> CommandResponse:
        command = {
            TYPE_KEY: CommandType.TERMINATE,
            PIPELINE_ID_KEY: pipeline_id,
        }
        response = await self._handle_command(command=command)
        return build_response(response=response)

    async def pause_pipeline(self, pipeline_id: str) -> CommandResponse:
        command = {
            TYPE_KEY: CommandType.MUTE,
            PIPELINE_ID_KEY: pipeline_id,
        }
        response = await self._handle_command(command=command)
        return build_response(response=response)

    async def resume_pipeline(self, pipeline_id: str) -> CommandResponse:
        command = {
            TYPE_KEY: CommandType.RESUME,
            PIPELINE_ID_KEY: pipeline_id,
        }
        response = await self._handle_command(command=command)
        return build_response(response=response)

    async def get_status(self, pipeline_id: str) -> InferencePipelineStatusResponse:
        command = {
            TYPE_KEY: CommandType.STATUS,
            PIPELINE_ID_KEY: pipeline_id,
        }
        response = await self._handle_command(command=command)
        status = response[RESPONSE_KEY][STATUS_KEY]
        context = CommandContext(
            request_id=response.get(REQUEST_ID_KEY),
            pipeline_id=response.get(PIPELINE_ID_KEY),
        )
        report = response[RESPONSE_KEY]["report"]
        return InferencePipelineStatusResponse(
            status=status,
            context=context,
            report=report,
        )

    async def _handle_command(self, command: dict) -> dict:
        response = await send_command(
            host=self._host,
            port=self._port,
            command=command,
            header_size=self._header_size,
            buffer_size=self._buffer_size,
            timeout=self._operations_timeout,
        )
        if is_request_unsuccessful(response=response):
            dispatch_error(error_response=response)
        return response


async def send_command(
    host: str,
    port: int,
    command: dict,
    header_size: int,
    buffer_size: int,
    timeout: Optional[float] = None,
) -> dict:
    try:
        reader, writer = await establish_socket_connection(
            host=host, port=port, timeout=timeout
        )
        await send_message(
            writer=writer, message=command, header_size=header_size, timeout=timeout
        )
        data = await receive_message(
            reader, header_size=header_size, buffer_size=buffer_size, timeout=timeout
        )
        writer.close()
        await writer.wait_closed()
        return json.loads(data)
    except JSONDecodeError as error:
        raise MalformedPayloadError(
            f"Could not decode response. Cause: {error}"
        ) from error
    except (OSError, asyncio.TimeoutError) as errors:
        raise ConnectivityError(
            f"Could not communicate with Process Manager"
        ) from errors


async def establish_socket_connection(
    host: str, port: int, timeout: Optional[float] = None
) -> Tuple[StreamReader, StreamWriter]:
    return await asyncio.wait_for(asyncio.open_connection(host, port), timeout=timeout)


async def send_message(
    writer: StreamWriter,
    message: dict,
    header_size: int,
    timeout: Optional[float] = None,
) -> None:
    try:
        body = json.dumps(message).encode("utf-8")
        header = len(body).to_bytes(length=header_size, byteorder="big")
        payload = header + body
        writer.write(payload)
        await asyncio.wait_for(writer.drain(), timeout=timeout)
    except TypeError as error:
        raise MalformedPayloadError(f"Could not serialise message. Details: {error}")
    except OverflowError as error:
        raise MessageToBigError(
            f"Could not send message due to size overflow. Details: {error}"
        )
    except asyncio.TimeoutError as error:
        raise ConnectivityError(
            f"Could not communicate with Process Manager"
        ) from error
    except Exception as error:
        raise CommunicationProtocolError(
            f"Could not send message. Cause: {error}"
        ) from error


async def receive_message(
    reader: StreamReader,
    header_size: int,
    buffer_size: int,
    timeout: Optional[float] = None,
) -> bytes:
    header = await asyncio.wait_for(reader.read(header_size), timeout=timeout)
    if len(header) != header_size:
        raise MalformedHeaderError("Header size missmatch")
    payload_size = int.from_bytes(bytes=header, byteorder="big")
    received = b""
    while len(received) < payload_size:
        chunk = await asyncio.wait_for(reader.read(buffer_size), timeout=timeout)
        if len(chunk) == 0:
            raise TransmissionChannelClosed(
                "Socket was closed to read before payload was decoded."
            )
        received += chunk
    return received


def is_request_unsuccessful(response: dict) -> bool:
    return (
        response.get(RESPONSE_KEY, {}).get(STATUS_KEY, OperationStatus.FAILURE.value)
        != OperationStatus.SUCCESS.value
    )


def dispatch_error(error_response: dict) -> None:
    response_payload = error_response.get(RESPONSE_KEY, {})
    error_type = response_payload.get(ERROR_TYPE_KEY)
    error_class = response_payload.get("error_class", "N/A")
    error_message = response_payload.get("error_message", "N/A")
    logger.error(
        f"Error in ProcessesManagerClient. error_type={error_type} error_class={error_class} "
        f"error_message={error_message}"
    )
    if error_type in ERRORS_MAPPING:
        raise ERRORS_MAPPING[error_type](
            f"Error in ProcessesManagerClient. Error type: {error_type}. Details: {error_message}"
        )
    raise ProcessesManagerClientError(
        f"Error in ProcessesManagerClient. Error type: {error_type}. Details: {error_message}"
    )


def build_response(response: dict) -> CommandResponse:
    status = response[RESPONSE_KEY][STATUS_KEY]
    context = CommandContext(
        request_id=response.get(REQUEST_ID_KEY),
        pipeline_id=response.get(PIPELINE_ID_KEY),
    )
    return CommandResponse(
        status=status,
        context=context,
    )