SPB Git

Repository Public

run.ts 8.7 KB 163 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Vrai-Prix8 * File             : src/lib/cost/connectors/run.ts9 * Module           : lib10 * Repository       : https://git.spboucher.ai/vrai-prix11 * Created          : 2026-09-0812 * Last Modified    : 2026-09-0813 *14 * Author           : Simon-Pierre Boucher15 * Position         : Professor of Finance16 * Institution      : Université du Québec en Outaouais (UQO)17 * Organization     : SP Boucher18 * Website          : https://spboucher.ai19 * Git              : https://git.spboucher.ai20 *21 * Preferred Contact: contact@spboucher.ai22 * Development      : dev@spboucher.ai23 * Support          : support@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142/**43 * Orchestrateur d'un connecteur : discover → fetch (hash) → extract → normalize44 * → validate → persistance, avec journal structuré et statistiques de run.45 * Utilisé par scripts/cost-sync.ts (planificateur) et l'API admin.46 */47import type Database from "better-sqlite3";48import { getCostDb } from "../db";49import { CONNECTORS, type RunnableKey } from "./registry";50import { closeLabourPeriods, ensureConnectorSchema, finishRun, isSourceActive, lastSuccessfulSync, pushLog, saveIndex, saveLabour, savePrice, saveRawObservation, saveUnchangedMarker, startRun } from "./store";51import type { CanonicalObservation, RawDocument, RunLogEntry, RunOptions, RunStats } from "./types";52import { APCHQ_PARSER_VERSION } from "./apchq";53import { STATCAN_PARSER_VERSION } from "./statcan";54import { CCQ_PARSER_VERSION } from "./ccq";55import { RETAIL_PARSER_VERSION } from "./retail";5657const PARSER_VERSION: Record<RunnableKey, string> = { apchq: APCHQ_PARSER_VERSION, ccq: CCQ_PARSER_VERSION, statcan: STATCAN_PARSER_VERSION, canac: RETAIL_PARSER_VERSION, bmr: RETAIL_PARSER_VERSION, patrickmorin: RETAIL_PARSER_VERSION, rona: RETAIL_PARSER_VERSION, homedepot: RETAIL_PARSER_VERSION };5859/** Le connecteur est-il dû (fréquence nominale écoulée) ? */60export function isDue(key: RunnableKey, d: Database.Database = getCostDb()): boolean {61  const last = lastSuccessfulSync(key, d);62  if (!last) return true;63  return Date.now() - new Date(last).getTime() >= CONNECTORS[key].config.refreshDays * 86400000 - 3600000;64}6566export async function runConnector(key: RunnableKey, opts: RunOptions = {}): Promise<RunStats> {67  const d = opts.db ?? getCostDb();68  ensureConnectorSchema(d);69  const c = CONNECTORS[key];70  const run = startRun(key, d);71  const log = (e: RunLogEntry) => pushLog(run, e, opts.log);72  const ts = () => new Date().toISOString();73  if (!isSourceActive(key, d) && !opts.force) {74    run.status = "skipped";75    run.message = "source inactive (cost_sources.is_active = 0)";76    log({ connector: key, url: null, status: "skipped", duration: 0, observations: 0, validationErrors: 0, timestamp: ts(), message: run.message });77    return finishRun(run, d);78  }79  let docs: Awaited<ReturnType<typeof c.discover>> = [];80  try {81    docs = await c.discover({ ...opts, db: d, log });82    log({ connector: key, url: null, status: "ok", duration: 0, observations: docs.length, validationErrors: 0, timestamp: ts(), message: `${docs.length} document(s) découvert(s)` });83  } catch (e) {84    run.errors++;85    run.status = "error";86    run.message = `découverte échouée : ${(e as Error).message}`;87    log({ connector: key, url: null, status: "error", duration: 0, observations: 0, validationErrors: 0, timestamp: ts(), message: run.message });88    return finishRun(run, d);89  }90  const max = opts.maxPages ?? c.config.maxPages;91  const queue = docs.slice(0, max);92  const workers = Math.max(1, c.config.concurrency);93  let idx = 0;94  const worker = async () => {95    for (;;) {96      const i = idx++;97      if (i >= queue.length) return;98      const doc = queue[i];99      const t0 = Date.now();100      let raw: RawDocument | null = null;101      try {102        raw = await c.fetch(doc, { ...opts, db: d, log });103        run.pages++;104        if (raw.statusCode != null && raw.statusCode >= 400) {105          run.errors++;106          log({ connector: key, url: doc.url, status: "error", duration: Date.now() - t0, observations: 0, validationErrors: 0, timestamp: ts(), message: `HTTP ${raw.statusCode}` });107          continue;108        }109        if (raw.unchanged) {110          run.unchanged++;111          saveUnchangedMarker(key, raw, d);112          log({ connector: key, url: doc.url, status: "unchanged", duration: Date.now() - t0, observations: 0, validationErrors: 0, timestamp: ts() });113          continue;114        }115        const rawObs = await c.extract(raw, { ...opts, db: d, log });116        if (!rawObs.length) {117          const unavailable = key === "ccq" && !(raw.metadata.hasRateTable as boolean | undefined);118          if (unavailable) { run.status = "unavailable"; run.message = String(raw.metadata.incident ?? "aucune grille de taux détectable"); }119          else run.errors++;120          saveRawObservation(key, { externalId: null, sourceUrl: doc.url, retrievedAt: raw.fetchedAt, effectiveDate: null, title: String(raw.metadata.title ?? doc.title ?? ""), description: null, unit: null, price: null, regularPrice: null, salePrice: null, currency: "CAD", location: null, category: null, payload: { statusCode: raw.statusCode, unavailable } }, raw, "rejected", unavailable ? "source indisponible" : "aucune observation extraite (structure inattendue ou page sans prix)", PARSER_VERSION[key], d);121          log({ connector: key, url: doc.url, status: unavailable ? "unavailable" : "rejected", duration: Date.now() - t0, observations: 0, validationErrors: 1, timestamp: ts(), message: unavailable ? run.message : "aucune observation extraite" });122          continue;123        }124        const canon = await c.normalize(rawObs, raw, { ...opts, db: d, log });125        const { accepted, rejected } = c.validate(canon, { ...opts, db: d, log });126        run.observations += canon.length;127        const tx = d.transaction(() => {128          for (const o of accepted) persist(key, o, raw!, PARSER_VERSION[key], d);129          for (const r of rejected) saveRawObservation(key, rawOf(r.obs, raw!, doc.url), raw!, "rejected", r.reason, PARSER_VERSION[key], d);130        });131        tx();132        run.accepted += accepted.length;133        run.rejected += rejected.length;134        log({ connector: key, url: doc.url, status: accepted.length ? "ok" : "rejected", duration: Date.now() - t0, observations: accepted.length, validationErrors: rejected.length, timestamp: ts(), message: rejected.length ? rejected.slice(0, 3).map((r) => r.reason).join(" ; ") : undefined });135      } catch (e) {136        run.errors++;137        log({ connector: key, url: doc.url, status: "error", duration: Date.now() - t0, observations: 0, validationErrors: 0, timestamp: ts(), message: (e as Error).message });138      }139    }140  };141  await Promise.all(Array.from({ length: workers }, worker));142  if (key === "apchq" && run.accepted) closeLabourPeriods("apchq", d);143  if (run.status === "unavailable" && run.accepted === 0) return finishRun(run, d);144  return finishRun(run, d);145}146147function rawOf(o: CanonicalObservation, raw: RawDocument, url: string) {148  if (o.kind === "index") return { externalId: o.indexCode, sourceUrl: url, retrievedAt: raw.fetchedAt, effectiveDate: o.period, title: o.indexCode, description: null, unit: "index", price: o.value, regularPrice: null, salePrice: null, currency: "CAD", location: o.geography, category: "index", payload: {} };149  return o.raw;150}151152function persist(key: RunnableKey, o: CanonicalObservation, raw: RawDocument, parser: string, d: Database.Database): void {153  if (o.kind === "index") { saveIndex(o, d); return; }154  if (o.kind === "labour") {155    const rawId = saveRawObservation(key, o.raw, raw, "accepted", null, parser, d);156    saveLabour(key, o, rawId, d);157    return;158  }159  const rawId = saveRawObservation(key, o.raw, raw, "accepted", null, parser, d);160  const conf = Math.round(60 + (o.isRegularPrice ? 15 : 0) + (o.conversionFactor === 1 ? 10 : 5));161  savePrice(key, o, rawId, conf, false, null, d);162}163
Files main
Menu

Theme