|
| 1 | +import asyncio |
| 2 | +import json |
| 3 | +import logging |
| 4 | +import os |
| 5 | +import sys |
| 6 | +import traceback |
| 7 | + |
| 8 | +import aiohttp |
| 9 | + |
| 10 | +# Import ld_eventsource from parent directory |
| 11 | +sys.path.insert(1, os.path.join(sys.path[0], '..')) |
| 12 | +from ld_eventsource.actions import Comment, Event, Fault # noqa: E402 |
| 13 | +from ld_eventsource.async_client import AsyncSSEClient # noqa: E402 |
| 14 | +from ld_eventsource.config.async_connect_strategy import \ |
| 15 | + AsyncConnectStrategy # noqa: E402 |
| 16 | +from ld_eventsource.config.error_strategy import ErrorStrategy # noqa: E402 |
| 17 | + |
| 18 | + |
| 19 | +def millis_to_seconds(t): |
| 20 | + return None if t is None else t / 1000 |
| 21 | + |
| 22 | + |
| 23 | +class AsyncStreamEntity: |
| 24 | + def __init__(self, options, http_session: aiohttp.ClientSession): |
| 25 | + self.options = options |
| 26 | + self.callback_url = options["callbackUrl"] |
| 27 | + self.log = logging.getLogger(options["tag"]) |
| 28 | + self.closed = False |
| 29 | + self.callback_counter = 0 |
| 30 | + self.sse = None |
| 31 | + self._http_session = http_session |
| 32 | + asyncio.create_task(self.run()) |
| 33 | + |
| 34 | + async def run(self): |
| 35 | + stream_url = self.options["streamUrl"] |
| 36 | + try: |
| 37 | + self.log.info('Opening stream from %s', stream_url) |
| 38 | + |
| 39 | + request_options = {} |
| 40 | + if self.options.get("readTimeoutMs") is not None: |
| 41 | + request_options["timeout"] = aiohttp.ClientTimeout( |
| 42 | + sock_read=millis_to_seconds(self.options.get("readTimeoutMs")) |
| 43 | + ) |
| 44 | + |
| 45 | + connect = AsyncConnectStrategy.http( |
| 46 | + url=stream_url, |
| 47 | + headers=self.options.get("headers"), |
| 48 | + aiohttp_request_options=request_options if request_options else None, |
| 49 | + ) |
| 50 | + sse = AsyncSSEClient( |
| 51 | + connect, |
| 52 | + initial_retry_delay=millis_to_seconds(self.options.get("initialDelayMs")), |
| 53 | + last_event_id=self.options.get("lastEventId"), |
| 54 | + error_strategy=ErrorStrategy.from_lambda( |
| 55 | + lambda _: ( |
| 56 | + ErrorStrategy.FAIL if self.closed else ErrorStrategy.CONTINUE, |
| 57 | + None, |
| 58 | + ) |
| 59 | + ), |
| 60 | + logger=self.log, |
| 61 | + ) |
| 62 | + self.sse = sse |
| 63 | + async for item in sse.all: |
| 64 | + if isinstance(item, Event): |
| 65 | + self.log.info('Received event from stream (%s)', item.event) |
| 66 | + await self.send_message( |
| 67 | + { |
| 68 | + 'kind': 'event', |
| 69 | + 'event': { |
| 70 | + 'type': item.event, |
| 71 | + 'data': item.data, |
| 72 | + 'id': item.last_event_id, |
| 73 | + }, |
| 74 | + } |
| 75 | + ) |
| 76 | + elif isinstance(item, Comment): |
| 77 | + self.log.info('Received comment from stream: %s', item.comment) |
| 78 | + await self.send_message({'kind': 'comment', 'comment': item.comment}) |
| 79 | + elif isinstance(item, Fault): |
| 80 | + if self.closed: |
| 81 | + break |
| 82 | + if item.error: |
| 83 | + self.log.info('Received error from stream: %s', item.error) |
| 84 | + await self.send_message({'kind': 'error', 'error': str(item.error)}) |
| 85 | + except Exception as e: |
| 86 | + self.log.info('Received error from stream: %s', e) |
| 87 | + self.log.info(traceback.format_exc()) |
| 88 | + await self.send_message({'kind': 'error', 'error': str(e)}) |
| 89 | + |
| 90 | + async def do_command(self, command: str) -> bool: |
| 91 | + self.log.info('Test service sent command: %s' % command) |
| 92 | + # currently we support no special commands |
| 93 | + return False |
| 94 | + |
| 95 | + async def send_message(self, message): |
| 96 | + if self.closed: |
| 97 | + return |
| 98 | + self.callback_counter += 1 |
| 99 | + callback_url = "%s/%d" % (self.callback_url, self.callback_counter) |
| 100 | + try: |
| 101 | + async with self._http_session.post( |
| 102 | + callback_url, |
| 103 | + data=json.dumps(message), |
| 104 | + headers={'Content-Type': 'application/json'}, |
| 105 | + ) as resp: |
| 106 | + if resp.status >= 300 and not self.closed: |
| 107 | + self.log.error('Callback request returned HTTP error %d', resp.status) |
| 108 | + except Exception as e: |
| 109 | + if not self.closed: |
| 110 | + self.log.error('Callback request failed: %s', e) |
| 111 | + |
| 112 | + async def close(self): |
| 113 | + self.closed = True |
| 114 | + if self.sse is not None: |
| 115 | + await self.sse.close() |
| 116 | + self.log.info('Test ended') |
0 commit comments