Skip to content

Commit

Permalink
fix: properly start/stop tasks (#28)
Browse files Browse the repository at this point in the history
* fix: properly start/stop tasks

lnbits/lnbits#2411

* types

* nicer
  • Loading branch information
dni authored Aug 1, 2024
1 parent 942d997 commit d656d41
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 39 deletions.
38 changes: 28 additions & 10 deletions __init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand All @@ -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():
Expand All @@ -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])
34 changes: 5 additions & 29 deletions views_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand Down Expand Up @@ -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"""
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit d656d41

Please sign in to comment.