Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/mortgage/scheduler.py10# Module : immoka11# Repository : https://git.spboucher.ai/immo-ka12# Created : 2026-08-2413# Last Modified : 2026-08-2414#15# =============================================================================16# AUTHOR & PROFESSIONAL AFFILIATION17# =============================================================================18#19# Author : Simon-Pierre Boucher20# Position : Professor of Finance21# Institution : Université du Québec en Outaouais (UQO)22# Department : Département des sciences administratives23# Organization : SP Boucher24#25# Website : https://spboucher.ai26# Git : https://git.spboucher.ai27#28# =============================================================================29# OFFICIAL CONTACT DIRECTORY30# =============================================================================31#32# General : info@spboucher.ai33# Professional : contact@spboucher.ai34# Direct : simon@spboucher.ai35# Research : research@spboucher.ai36# Development : dev@spboucher.ai37# Support : support@spboucher.ai38# Security/Admin : admin@spboucher.ai39# Notifications : notifications@spboucher.ai40#41# Preferred Contact: contact@spboucher.ai42#43# =============================================================================44# COPYRIGHT & INTELLECTUAL PROPERTY45# =============================================================================46#47# Copyright (c) 202648# Simon-Pierre Boucher49#50# All rights reserved where applicable.51#52# This file is governed by the applicable project license,53# copyright notices, institutional agreements and relevant law.54#55# Unless expressly authorized by the applicable license or56# rights holder, copying, redistribution, sublicensing,57# publication and commercial exploitation are not permitted.58#59# Existing third-party rights and notices remain unaffected.60#61# =============================================================================62# CONFIDENTIALITY & SECURITY63# =============================================================================64#65# Classification : Public66# Distribution : Public repository; use is governed by the project license67# Security Contact : admin@spboucher.ai68#69# Access to this source does not independently grant permission70# to redistribute or disclose confidential materials.71#72# Do not embed credentials, private keys, access tokens,73# certificates or confidential personal information.74#75# =============================================================================76# LICENSE & MAINTENANCE77# =============================================================================78#79# License : None specified (no license file in this repository)80# Maintainer : Simon-Pierre Boucher81# Technical Contact: dev@spboucher.ai82#83# =============================================================================84# END OF SP BOUCHER SOURCE HEADER85# =============================================================================8687# -----------------------------------------------------------------------------88# Immo-Ka — Agrégateur de maisons à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# mortgage/scheduler.py : orchestration de la collecte des taux.91# Pipeline : provider.fetch() -> validation -> enregistrement historisé.92# Retries avec backoff exponentiel, timeout par provider, logs structurés,93# santé par provider (provider_runs). Une panne d'un provider n'affecte94# jamais les autres ni le calculateur (dernière donnée valide conservée).95# -----------------------------------------------------------------------------96from __future__ import annotations9798import os99import time100import traceback101102import requests103104from . import store105from .providers import PROVIDERS106from .validate import validate_batch107108RETRIES = int(os.environ.get("IMMOKA_MORTGAGE_RETRIES", "3"))109BACKOFF_BASE_S = float(os.environ.get("IMMOKA_MORTGAGE_BACKOFF", "5"))110# Fréquence de collecte (minutes) — utilisée par watch() ci-dessous.111INTERVAL_MIN = int(os.environ.get("IMMOKA_MORTGAGE_INTERVAL_MIN", "180"))112113114def _log(**kw) -> None:115 print("[mortgage] " + " ".join(f"{k}={v}" for k, v in kw.items()),116 flush=True)117118119def run_provider(slug: str, con=None) -> dict:120 """Collecte UNE institution avec retries + backoff. Retourne le résumé."""121 if con is None:122 con = store.connect()123 cls = PROVIDERS[slug]124 t0 = time.time()125 products: list[dict] | None = None126 status, message = "success", ""127 for attempt in range(RETRIES):128 try:129 products = cls().fetch()130 break131 except requests.RequestException as exc:132 status, message = "http_error", str(exc)[:200]133 except Exception as exc: # noqa: BLE001 — parseur cassé, etc.134 status, message = "parser_error", str(exc)[:200]135 traceback.print_exc()136 if attempt < RETRIES - 1:137 time.sleep(BACKOFF_BASE_S * (2 ** attempt))138 duration_ms = int((time.time() - t0) * 1000)139 if products is None:140 store.log_run(con, slug, ok=False, status=status,141 duration_ms=duration_ms, message=message)142 _log(provider=slug, status=status, duration=f"{duration_ms}ms",143 message=message or "-")144 return {"provider": slug, "ok": False, "status": status,145 "message": message}146 valid, problems = validate_batch(products)147 if not valid:148 status = "empty" if not products else "validation_error"149 store.log_run(con, slug, ok=False, status=status,150 products=len(products), rejected=len(problems),151 duration_ms=duration_ms,152 message="; ".join(problems[:5]))153 _log(provider=slug, status=status, products=len(products),154 rejected=len(problems), duration=f"{duration_ms}ms")155 return {"provider": slug, "ok": False, "status": status,156 "problems": problems}157 res = store.record_observations(con, slug, valid)158 ok = True159 if problems or res["rejected"]:160 status = "success" # partiel : données saines enregistrées quand même161 store.log_run(con, slug, ok=ok, status=status, products=len(valid),162 changed=res["changed"],163 rejected=len(problems) + res["rejected"],164 duration_ms=duration_ms,165 message="; ".join((problems + res["rejected_details"])[:5]))166 _log(provider=slug, status=status, products=len(valid),167 changed=res["changed"], rejected=len(problems) + res["rejected"],168 duration=f"{duration_ms}ms")169 return {"provider": slug, "ok": True, "status": status,170 "products": len(valid), "changed": res["changed"],171 "rejected": len(problems) + res["rejected"]}172173174def run(only: list[str] | None = None) -> list[dict]:175 """Collecte toutes les institutions (ou celles listées). Séquentiel et176 poli — jamais de martèlement des sites bancaires."""177 con = store.connect()178 slugs = [s for s in sorted(PROVIDERS) if not only or s in only]179 results = [run_provider(s, con) for s in slugs]180 ok = sum(1 for r in results if r["ok"])181 _log(status="done", providers=len(results), ok=ok,182 failed=len(results) - ok)183 return results184185186def watch(interval_minutes: int | None = None) -> None:187 """Boucle autonome de collecte (défaut : IMMOKA_MORTGAGE_INTERVAL_MIN)."""188 minutes = interval_minutes or INTERVAL_MIN189 while True:190 try:191 run()192 except Exception: # noqa: BLE001 — la boucle ne meurt jamais193 traceback.print_exc()194 time.sleep(minutes * 60)195196197def maybe_run(min_age_minutes: int | None = None) -> None:198 """Collecte seulement si la dernière passe date de plus de199 `min_age_minutes` — appelé depuis la boucle watch d'ingest.py sans risque200 de sur-solliciter les banques."""201 age_min = min_age_minutes or INTERVAL_MIN202 con = store.connect()203 last = con.execute("SELECT MAX(ts) AS m FROM provider_runs").fetchone()204 if last and last["m"] and (time.time() - last["m"]) < age_min * 60:205 return206 run()207