feat: add event watcher
This commit is contained in:
1 parent
c40e720163
commit
f0afb7ec5b
11 files changed
+176
-14
No files matched your search
@@ -1,17 +1,20 @@
|
||||
import asyncio
|
||||
import contextlib
|
||||
import json
|
||||
from collections.abc import Callable, Coroutine
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import asyncpg
|
||||
import uvloop
|
||||
|
||||
from dependencies.container import container
|
||||
from userbot import PyroClient
|
||||
from userbot.modules.capture import build_capture_context
|
||||
from userbot.modules.capture import CaptureContext, build_capture_context
|
||||
from userbot.modules.jobs import JobConsumer
|
||||
from utils.env import env
|
||||
from utils.logging import logger, setup_logging
|
||||
from utils.read.watches import WATCHES_CHANGED_CHANNEL
|
||||
from utils.storage import ContentAddressedStorage
|
||||
|
||||
setup_logging()
|
||||
@@ -69,21 +72,32 @@ async def _setup_capture(
|
||||
logger.info("[green]Capture context ready.[/]")
|
||||
|
||||
|
||||
async def _listen_policy_changes(
|
||||
async def _listen_changes(
|
||||
clients: list[PyroClient], tasks: set[asyncio.Task]
|
||||
) -> asyncpg.Connection:
|
||||
def on_change(
|
||||
_conn: asyncpg.Connection, _pid: int, _channel: str, _payload: str
|
||||
def reload(
|
||||
make_coro: Callable[[CaptureContext], Coroutine[Any, Any, None]],
|
||||
) -> None:
|
||||
for client in clients:
|
||||
if client.capture is None:
|
||||
continue
|
||||
task = asyncio.create_task(client.capture.reload_policies())
|
||||
task = asyncio.create_task(make_coro(client.capture))
|
||||
tasks.add(task)
|
||||
task.add_done_callback(tasks.discard)
|
||||
|
||||
def on_policy(
|
||||
_conn: asyncpg.Connection, _pid: int, _channel: str, _payload: str
|
||||
) -> None:
|
||||
reload(lambda capture: capture.reload_policies())
|
||||
|
||||
def on_watch(
|
||||
_conn: asyncpg.Connection, _pid: int, _channel: str, _payload: str
|
||||
) -> None:
|
||||
reload(lambda capture: capture.watches.refresh())
|
||||
|
||||
conn = await asyncpg.connect(dsn=env.db.connection_url)
|
||||
await conn.add_listener("policy_changed", on_change)
|
||||
await conn.add_listener("policy_changed", on_policy)
|
||||
await conn.add_listener(WATCHES_CHANGED_CHANNEL, on_watch)
|
||||
return conn
|
||||
|
||||
|
||||
@@ -122,7 +136,7 @@ async def runner() -> None:
|
||||
consumer_tasks.append(asyncio.create_task(consumer.run()))
|
||||
|
||||
if clients:
|
||||
listen_conn = await _listen_policy_changes(clients, reload_tasks)
|
||||
listen_conn = await _listen_changes(clients, reload_tasks)
|
||||
logger.info("[green]Userbot running.[/]")
|
||||
await asyncio.Event().wait()
|
||||
finally:
|
||||
|
||||
Reference in new issue
Block a user