"""Collecte quotidienne et relance horaire après échec, verrou interprocessus.""" import fcntl import json from datetime import datetime, timedelta, timezone import storage def status(): with storage.connect() as db: latest = db.execute("SELECT * FROM collections ORDER BY id DESC LIMIT 1").fetchone() good = db.execute("SELECT * FROM collections WHERE status='ok' ORDER BY id DESC LIMIT 1").fetchone() count = db.execute("SELECT count(*) FROM observations").fetchone()[0] return dict( latest=dict(latest) if latest else None, last_success=dict(good) if good else None, observations=count ) def collect(load=None, market=None, force=False): if load is None: import app def load(): return app.load_fuel_data(force=True) market = app.market_signal now = datetime.now(timezone.utc) day = now.astimezone(storage.PARIS).date().isoformat() storage.DB_PATH.parent.mkdir(parents=True, exist_ok=True) with (storage.DB_PATH.parent / "collection.lock").open("a") as lock: try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: return {"status": "busy", "count": 0} favorites = storage.list_entities("favorites") if not favorites: return {"status": "no_favorites", "count": 0} with storage.connect() as db: last = db.execute( "SELECT finished_at FROM collections WHERE status='ok' ORDER BY id DESC LIMIT 1" ).fetchone() if ( not force and last and datetime.fromisoformat(last[0]).astimezone(storage.PARIS).date().isoformat() == day ): return {"status": "skipped", "count": 0} db.execute( "UPDATE collections SET status='error', detail='Collecte précédente interrompue' WHERE status='running'" ) job = db.execute( "INSERT INTO collections(started_at,status) VALUES(?,'running')", (now.isoformat(),) ).lastrowid count, detail, outcome = 0, "", "ok" try: rows = load() if not rows: raise ValueError("Le flux national ne contient aucune station exploitable") selected = [ row for row in rows if any( storage.distance_km(f["lat"], f["lon"], row["lat"], row["lon"]) <= f["radius_km"] for f in favorites ) ] count = storage.record_observations(selected, now) # L'indisponibilité du pétrole ne doit pas annuler l'historique local. try: market_data = market() if market else {"trend": "unknown"} if market_data.get("trend") != "unknown" and market_data.get("date"): with storage.connect() as db: db.execute( "REPLACE INTO market_daily VALUES(?,?)", (market_data["date"], json.dumps(market_data)), ) except Exception as exc: detail = f"Prix locaux collectés ; pétrole indisponible ({type(exc).__name__})" if not selected: detail = "Aucune station dans les favoris actuels" except Exception as exc: outcome, detail = "error", f"{type(exc).__name__}: {str(exc)[:250]}" with storage.connect() as db: db.execute( "UPDATE collections SET finished_at=?, status=?, count=?, detail=? WHERE id=?", (datetime.now(timezone.utc).isoformat(), outcome, count, detail, job), ) # Fenêtre glissante suffisante pour une future validation ; limiter le volume. db.execute( "DELETE FROM observations WHERE day