From d656d41b900f8df5f934c7ce7bca312d6a59e220 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?dni=20=E2=9A=A1?= Date: Thu, 1 Aug 2024 15:09:58 +0200 Subject: [PATCH] fix: properly start/stop tasks (#28) * fix: properly start/stop tasks https://github.com/lnbits/lnbits/issues/2411 * types * nicer --- __init__.py | 38 ++++++++++++++++++++++++++++---------- views_api.py | 34 +++++----------------------------- 2 files changed, 33 insertions(+), 39 deletions(-) diff --git a/__init__.py b/__init__.py index d50998b..98a1fcc 100644 --- a/__init__.py +++ b/__init__.py @@ -2,12 +2,14 @@ from typing import List from fastapi import APIRouter +from loguru import logger from lnbits.db import Database from lnbits.helpers import template_renderer -from lnbits.tasks import catch_everything_and_restart +from lnbits.tasks import create_permanent_unique_task from .nostr.client.client import NostrClient +from .router import NostrRouter db = Database("ext_nostrclient") @@ -20,9 +22,11 @@ nostrclient_ext: APIRouter = APIRouter(prefix="/nostrclient", tags=["nostrclient"]) -scheduled_tasks: List[asyncio.Task] = [] +nostr_client: NostrClient = NostrClient() -nostr_client = NostrClient() +# we keep this in +all_routers: list[NostrRouter] = [] +scheduled_tasks: list[asyncio.Task] = [] def nostr_renderer(): @@ -34,11 +38,25 @@ def nostr_renderer(): from .views_api import * # noqa +async def nostrclient_stop(): + for task in scheduled_tasks: + try: + task.cancel() + except Exception as ex: + logger.warning(ex) + + for router in all_routers: + try: + await router.stop() + all_routers.remove(router) + except Exception as e: + logger.error(e) + + nostr_client.close() + + def nostrclient_start(): - loop = asyncio.get_event_loop() - task1 = loop.create_task(catch_everything_and_restart(init_relays)) - scheduled_tasks.append(task1) - task2 = loop.create_task(catch_everything_and_restart(subscribe_events)) - scheduled_tasks.append(task2) - task3 = loop.create_task(catch_everything_and_restart(check_relays)) - scheduled_tasks.append(task3) + task1 = create_permanent_unique_task("ext_nostrclient_init_relays", init_relays) + task2 = create_permanent_unique_task("ext_nostrclient_subscrive_events", subscribe_events) + task3 = create_permanent_unique_task("ext_nostrclient_check_relays", check_relays) + scheduled_tasks.extend([task1, task2, task3]) diff --git a/views_api.py b/views_api.py index a0ec45a..9e13af6 100644 --- a/views_api.py +++ b/views_api.py @@ -9,16 +9,13 @@ from lnbits.decorators import check_admin from lnbits.helpers import decrypt_internal_message, urlsafe_short_hash -from . import nostr_client, nostrclient_ext, scheduled_tasks +from . import all_routers, nostr_client, nostrclient_ext from .crud import add_relay, create_config, delete_relay, get_config, get_relays, update_config from .helpers import normalize_public_key from .models import Config, Relay, TestMessage, TestMessageResponse from .nostr.key import EncryptedDirectMessage, PrivateKey from .router import NostrRouter -# we keep this in -all_routers: list[NostrRouter] = [] - @nostrclient_ext.get("/api/v1/relays", dependencies=[Depends(check_admin)]) async def api_get_relays() -> List[Relay]: @@ -111,28 +108,6 @@ async def api_test_endpoint(data: TestMessage) -> TestMessageResponse: ) -@nostrclient_ext.delete( - "/api/v1", status_code=HTTPStatus.OK, dependencies=[Depends(check_admin)] -) -async def api_stop(): - for router in all_routers: - try: - await router.stop() - all_routers.remove(router) - except Exception as e: - logger.error(e) - - nostr_client.close() - - for scheduled_task in scheduled_tasks: - try: - scheduled_task.cancel() - except Exception as ex: - logger.warning(ex) - - return {"success": True} - - @nostrclient_ext.websocket("/api/v1/{id}") async def ws_relay(id: str, websocket: WebSocket) -> None: """Relay multiplexer: one client (per endpoint) <-> multiple relays""" @@ -184,13 +159,14 @@ async def ws_relay(id: str, websocket: WebSocket) -> None: @nostrclient_ext.get("/api/v1/config", dependencies=[Depends(check_admin)]) -async def api_get_relays() -> Config: +async def api_get_config() -> Config: config = await get_config() if not config: - await create_config() - + config = await create_config() + assert config, "Failed to create config" return config + @nostrclient_ext.put("/api/v1/config", dependencies=[Depends(check_admin)]) async def api_update_config( data: Config