2021-12-13 00:20:48 +08:00
|
|
|
import asyncio
|
|
|
|
import logging
|
2022-01-09 23:59:53 +08:00
|
|
|
from typing import AsyncGenerator
|
2021-12-13 00:20:48 +08:00
|
|
|
|
2022-01-09 23:59:53 +08:00
|
|
|
import strawberry # noqa
|
2023-04-10 20:23:31 +08:00
|
|
|
from api.gql.notification.types import ActivityStreamType
|
|
|
|
from apps.common.channel import BroadcastEvent, Subscriber, broadcast
|
|
|
|
from apps.notification.models import ActivityStream
|
2021-12-13 00:20:48 +08:00
|
|
|
|
|
|
|
logging.basicConfig(level=logging.INFO)
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
@strawberry.type
|
|
|
|
class StreamSubscription:
|
|
|
|
@strawberry.subscription
|
2022-11-25 16:35:48 +08:00
|
|
|
async def latest_activity(self) -> AsyncGenerator[ActivityStreamType, None]: # noqa
|
2021-12-13 00:20:48 +08:00
|
|
|
subscriber: Subscriber
|
|
|
|
async with broadcast.subscribe(channel="activities") as subscriber:
|
|
|
|
logger.info("Subscribed")
|
|
|
|
event: BroadcastEvent
|
|
|
|
try:
|
|
|
|
async for event in subscriber:
|
|
|
|
logger.info(event)
|
|
|
|
yield event.message
|
|
|
|
finally:
|
|
|
|
logger.info("Unsubscribed")
|
|
|
|
|
|
|
|
@strawberry.subscription
|
2022-11-25 16:35:48 +08:00
|
|
|
async def stream_all(self) -> AsyncGenerator[ActivityStreamType, None]: # noqa
|
2021-12-13 00:20:48 +08:00
|
|
|
streams = await ActivityStream.all()
|
|
|
|
for stream in streams:
|
|
|
|
yield stream
|
|
|
|
await asyncio.sleep(1)
|