from anyio import create_memory_object_stream
from anyio import BrokenResourceError

class SSEConnection:
    def __init__(self):
        self._send, self._receive = create_memory_object_stream()
        self._closed = False

    async def send(self, msg: str):
        if self._closed:
            return
        
        try:
            await self._send.send(msg)
        except BrokenResourceError:
            self._closed = True

    async def close(self):
        if not self._closed:
            self._closed = True
            await self._send.aclose()

    async def receive(self):
        async for msg in self._receive:
            yield msg
