castle/__init__.py
padreug 8f35788e1a Adds task cleanup on extension shutdown
Implements a mechanism to cancel pending background tasks
when the extension is stopped. This ensures proper cleanup and
prevents potential issues with lingering tasks.
2025-11-02 01:41:34 +01:00

42 lines
1.1 KiB
Python

import asyncio
from fastapi import APIRouter
from loguru import logger
from .crud import db
from .tasks import wait_for_paid_invoices
from .views import castle_generic_router
from .views_api import castle_api_router
castle_ext: APIRouter = APIRouter(prefix="/castle", tags=["Castle"])
castle_ext.include_router(castle_generic_router)
castle_ext.include_router(castle_api_router)
castle_static_files = [
{
"path": "/castle/static",
"name": "castle_static",
}
]
scheduled_tasks: list[asyncio.Task] = []
def castle_stop():
"""Clean up background tasks on extension shutdown"""
for task in scheduled_tasks:
try:
task.cancel()
except Exception as ex:
logger.warning(ex)
def castle_start():
"""Initialize Castle extension background tasks"""
from lnbits.tasks import create_permanent_unique_task
task = create_permanent_unique_task("ext_castle", wait_for_paid_invoices)
scheduled_tasks.append(task)
__all__ = ["castle_ext", "castle_static_files", "db", "castle_start", "castle_stop"]