Containerised macro-strategy dashboard: 4-panel web UI (indicators, portfolio, flash news, AI strategic log), MariaDB store, hourly ingestion jobs, OpenRouter-backed AI analysis. Ports the four prototype scripts in the parent dir (market_pulse, flash_news, trading212, strategic_log) into async services backed by a persistent DB and served via FastAPI + Jinja2 + HTMX. APScheduler runs as a separate compose service for crash-safety and easier restarts. Portfolio composition + position names come live from Trading 212; news per-ticker headlines reuse those names. Tone (NOVICE/INTERMEDIATE/ PRO) and analysis style (DRY/SPECULATIVE) are env-configurable and stored on each log row so historical entries show what produced them. Default model is deepseek/deepseek-v4-flash (overridable via env). Light/dark theme toggle, sans-serif for prose surfaces, monospace for data. Bearer-token auth, OpenRouter monthly cost cap, RSS feeds auto- disabled on consecutive failures. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
58 lines
2.1 KiB
Python
58 lines
2.1 KiB
Python
"""Shared job machinery: job_runs lifecycle, MariaDB advisory lock,
|
|
mock-mode short-circuits."""
|
|
from __future__ import annotations
|
|
|
|
from contextlib import asynccontextmanager
|
|
from typing import AsyncIterator
|
|
|
|
from sqlalchemy import text
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.db import get_session_factory, utcnow
|
|
from app.logging import get_logger
|
|
from app.models import JobRun
|
|
|
|
|
|
log = get_logger("jobs")
|
|
|
|
|
|
@asynccontextmanager
|
|
async def job_lifecycle(name: str) -> AsyncIterator[tuple[AsyncSession, JobRun]]:
|
|
"""Wraps a job invocation. Creates a JobRun row on entry; updates it on
|
|
exit. Failures are caught by the caller's try/except; this context only
|
|
handles the bookkeeping.
|
|
|
|
A MariaDB GET_LOCK(name, 0) is acquired to prevent concurrent runs of the
|
|
same job across processes. If the lock is busy, we skip the run."""
|
|
factory = get_session_factory()
|
|
async with factory() as session:
|
|
# Try lock; skip if held.
|
|
got = (await session.execute(
|
|
text("SELECT GET_LOCK(:n, 0)"), {"n": f"cassandra_{name}"}
|
|
)).scalar()
|
|
if not got:
|
|
log.warning("job.skipped_locked", name=name)
|
|
yield session, JobRun(name=name, started_at=utcnow(), status="skipped")
|
|
return
|
|
run = JobRun(name=name, started_at=utcnow(), status="running")
|
|
session.add(run)
|
|
await session.commit()
|
|
await session.refresh(run)
|
|
try:
|
|
yield session, run
|
|
run.status = run.status if run.status not in ("running",) else "success"
|
|
run.finished_at = utcnow()
|
|
await session.commit()
|
|
log.info("job.finished",
|
|
name=name, status=run.status, items=run.items_written)
|
|
except Exception as e:
|
|
run.status = "failed"
|
|
run.error = str(e)[:1000]
|
|
run.finished_at = utcnow()
|
|
await session.commit()
|
|
log.error("job.failed", name=name, error=str(e))
|
|
raise
|
|
finally:
|
|
await session.execute(text("SELECT RELEASE_LOCK(:n)"),
|
|
{"n": f"cassandra_{name}"})
|
|
await session.commit()
|