2026-11-16 13:43:09 +01:00
|
|
|
"""The background worker process (ADR-55): runs the round lifecycle every few seconds and, on the
|
|
|
|
|
simulated ledger, settles the confirmations that a real chain would bring (roadmap A4). The chain tasks
|
|
|
|
|
of phase B plug into `tick` too. A step that fails is logged and retried at the next tick: the lifecycle
|
|
|
|
|
keeps no state outside the database.
|
2026-11-16 12:00:57 +01:00
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
import logging
|
|
|
|
|
import signal
|
|
|
|
|
import threading
|
|
|
|
|
|
|
|
|
|
from django.core.management.base import BaseCommand
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
TICK_SECONDS = 5
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def tick() -> None:
|
2026-11-16 13:43:09 +01:00
|
|
|
"""One pass over everything the worker is responsible for."""
|
|
|
|
|
from django.conf import settings
|
|
|
|
|
|
2026-11-16 15:03:22 +01:00
|
|
|
from apps.lottery import console, lifecycle, simulation
|
2026-11-16 13:43:09 +01:00
|
|
|
|
2026-11-16 15:03:22 +01:00
|
|
|
console.beat() # WEB-31: proof of life, before the work that might fail
|
2026-11-16 13:43:09 +01:00
|
|
|
if settings.LEDGER_BACKEND == "simulated":
|
|
|
|
|
simulation.settle()
|
|
|
|
|
lifecycle.tick()
|
2026-11-16 12:00:57 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
class Command(BaseCommand):
|
|
|
|
|
help = "Run the background worker (round scheduler and chain tasks)."
|
|
|
|
|
|
|
|
|
|
def add_arguments(self, parser):
|
|
|
|
|
parser.add_argument("--once", action="store_true", help="Run a single tick and exit.")
|
|
|
|
|
|
|
|
|
|
def handle(self, *args, **options):
|
|
|
|
|
stop = threading.Event()
|
|
|
|
|
for signum in (signal.SIGTERM, signal.SIGINT):
|
|
|
|
|
signal.signal(signum, lambda *_: stop.set())
|
|
|
|
|
|
|
|
|
|
logger.info("worker started")
|
|
|
|
|
while not stop.is_set():
|
2026-11-16 13:43:09 +01:00
|
|
|
try:
|
|
|
|
|
tick()
|
|
|
|
|
except Exception: # a failed step leaves the round where it was; the next tick retries
|
|
|
|
|
logger.exception("worker tick failed")
|
|
|
|
|
if options["once"]:
|
|
|
|
|
raise
|
2026-11-16 12:00:57 +01:00
|
|
|
if options["once"]:
|
|
|
|
|
break
|
|
|
|
|
stop.wait(TICK_SECONDS)
|
|
|
|
|
logger.info("worker stopped")
|