Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : ORIX App Universe8 * File : src/lib/releases/sync.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/orix-spboucher-ai11 * Project Website : https://www.orixlab.dev12 * Created : 2026-11-2113 * Last Modified : 2026-11-2114 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243import { db, now, tx } from "../database/db";44import { audit } from "../audit";45import { listApps } from "../catalog";46import { getReleases, getRepo, isForgeAssetUrl, type FetchLike, type ForgeRelease } from "../git/spbgit";47import { parseTag } from "./version";4849export type SyncSummary = { repos: number; newReleases: number; updated: number; invalid: number; errors: { slug: string; error: string }[] };50export type SyncRun = { id: number; started_at: string; finished_at: string | null; trigger: string; ok: number | null; summary: string | null; error: string | null };5152const SHA = /^[0-9a-f]{64}$/;53const isDmg = (n: string) => /^[A-Za-z0-9][A-Za-z0-9 ._+()-]{0,150}\.dmg$/.test(n);5455/** Structural validation of a forge asset before it may even be proposed for approval. */56export function validateAsset(repo: string, a: { name: string; size: number; sha256: string; url: string }): string | null {57 if (!isDmg(a.name)) return "asset_name";58 if (!Number.isInteger(a.size) || a.size <= 0) return "empty_asset";59 if (!SHA.test(a.sha256 ?? "")) return "missing_checksum";60 if (!isForgeAssetUrl(a.url, repo)) return "foreign_url";61 return null;62}6364function upsertRelease(slug: string, repo: string, rel: ForgeRelease, s: SyncSummary): void {65 const v = parseTag(rel.tag);66 const dmgs = rel.assets.filter((a) => a.name.toLowerCase().endsWith(".dmg"));67 const d = db();68 if (dmgs.length === 0) {69 // A tag without a downloadable image is release history only (e.g. an iOS TestFlight build tag).70 const existed = !!d.prepare("SELECT 1 FROM releases WHERE slug = ? AND tag = ? AND asset_name = ''").get(slug, rel.tag);71 d.prepare(`INSERT INTO releases (slug, repo, tag, version, prerelease, tag_date, subject, asset_name, state, discovered_at)72 VALUES (?, ?, ?, ?, ?, ?, ?, '', 'note', ?) ON CONFLICT (slug, tag, asset_name) DO UPDATE SET subject = excluded.subject, tag_date = excluded.tag_date`)73 .run(slug, repo, rel.tag, v?.text ?? null, v?.pre ? 1 : 0, rel.date, rel.subject, now());74 if (!existed) s.newReleases++;75 return;76 }77 for (const a of dmgs) {78 const problem = v ? validateAsset(repo, a) : "unparsable_tag";79 const cur = d.prepare("SELECT id, state, sha256_declared, asset_size FROM releases WHERE slug = ? AND tag = ? AND asset_name = ?").get(slug, rel.tag, a.name) as80 { id: number; state: string; sha256_declared: string | null; asset_size: number | null } | undefined;81 if (!cur) {82 d.prepare(`INSERT INTO releases (slug, repo, tag, version, prerelease, tag_date, subject, asset_name, asset_size, sha256_declared, source_url, state, reason, discovered_at, checked_at)83 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)84 .run(slug, repo, rel.tag, v?.text ?? null, v?.pre ? 1 : 0, rel.date, rel.subject, a.name, a.size, a.sha256 ?? null, a.url, problem ? "invalid" : "validated", problem, now(), now());85 s.newReleases++; if (problem) s.invalid++;86 audit("release.discovered", { detail: { slug, tag: rel.tag, asset: a.name, state: problem ? "invalid" : "validated", reason: problem } });87 continue;88 }89 // An asset replaced on the forge after publication no longer matches what was approved: take it offline.90 const changed = cur.sha256_declared !== (a.sha256 ?? null) || cur.asset_size !== a.size;91 if (changed && (cur.state === "published" || cur.state === "held")) {92 d.prepare("UPDATE releases SET state = 'withdrawn', reason = 'asset_changed_upstream', checked_at = ? WHERE id = ?").run(now(), cur.id);93 audit("release.withdrawn.auto", { detail: { slug, tag: rel.tag, asset: a.name, reason: "asset_changed_upstream" } });94 s.updated++;95 } else if (changed || cur.state === "invalid" || cur.state === "discovered") {96 d.prepare("UPDATE releases SET asset_size = ?, sha256_declared = ?, source_url = ?, subject = ?, state = ?, reason = ?, checked_at = ? WHERE id = ? AND state IN ('discovered','validated','invalid')")97 .run(a.size, a.sha256 ?? null, a.url, rel.subject, problem ? "invalid" : "validated", problem, now(), cur.id);98 s.updated++; if (problem) s.invalid++;99 } else d.prepare("UPDATE releases SET checked_at = ? WHERE id = ?").run(now(), cur.id);100 }101}102103/**104 * Pulls repository metadata and releases of every catalog application that has a PUBLIC forge repository.105 * Discovery never publishes anything: a new image becomes `validated` at best and waits for an administrator.106 */107export async function runSync(opts: { trigger: "schedule" | "manual" | "webhook" | "cli"; only?: string; fetchImpl?: FetchLike; retries?: number; baseDelayMs?: number } ): Promise<{ runId: number; ok: boolean; summary: SyncSummary }> {108 const g = globalThis as typeof globalThis & { __orixSyncing?: boolean };109 if (g.__orixSyncing) throw new Error("a synchronization is already running");110 g.__orixSyncing = true;111 const runId = Number(db().prepare("INSERT INTO sync_runs (started_at, trigger) VALUES (?, ?)").run(now(), opts.trigger).lastInsertRowid);112 const s: SyncSummary = { repos: 0, newReleases: 0, updated: 0, invalid: 0, errors: [] };113 try {114 const targets = listApps({ all: true }).filter((r) => r.publish !== "archived" && r.app.repo.visibility === "public" && r.app.repo.name && (!opts.only || r.app.repo.name === opts.only || r.slug === opts.only));115 for (const { slug, app } of targets) {116 const repo = app.repo.name!;117 try {118 const o = { fetchImpl: opts.fetchImpl, retries: opts.retries, baseDelayMs: opts.baseDelayMs };119 const [meta, releases] = [await getRepo(repo, o), await getReleases(repo, o)];120 tx(() => {121 db().prepare("INSERT INTO repo_meta (slug, json, fetched_at) VALUES (?, ?, ?) ON CONFLICT (slug) DO UPDATE SET json = excluded.json, fetched_at = excluded.fetched_at").run(slug, JSON.stringify(meta), now());122 for (const rel of releases) upsertRelease(slug, repo, rel, s);123 });124 s.repos++;125 } catch (e) { s.errors.push({ slug, error: e instanceof Error ? e.message : String(e) }); }126 }127 const ok = s.errors.length === 0;128 db().prepare("UPDATE sync_runs SET finished_at = ?, ok = ?, summary = ?, error = ? WHERE id = ?").run(now(), ok ? 1 : 0, JSON.stringify(s), ok ? null : s.errors.map((e) => `${e.slug}: ${e.error}`).join("; ").slice(0, 2000), runId);129 return { runId, ok, summary: s };130 } catch (e) {131 db().prepare("UPDATE sync_runs SET finished_at = ?, ok = 0, error = ? WHERE id = ?").run(now(), (e instanceof Error ? e.message : String(e)).slice(0, 2000), runId);132 throw e;133 } finally { g.__orixSyncing = false; }134}135136export const recentRuns = (n = 20) => db().prepare("SELECT * FROM sync_runs ORDER BY id DESC LIMIT ?").all(n) as unknown as SyncRun[];137export const lastSuccess = () => (db().prepare("SELECT max(finished_at) AS t FROM sync_runs WHERE ok = 1").get() as { t: string | null }).t;138139/** Data is stale when no run succeeded for three scheduling periods (or ever). */140export function syncHealth(intervalMin: number, at = Date.now()): { last: string | null; stale: boolean } {141 const last = lastSuccess();142 return { last, stale: !last || at - Date.parse(last) > Math.max(intervalMin, 5) * 3 * 60_000 };143}144145export type RepoMeta = { head: string; lastPush: string | null; commitCount: number; tagCount: number; topLanguage?: string; license?: string };146export function repoMeta(slug: string): (RepoMeta & { fetchedAt: string }) | null {147 const r = db().prepare("SELECT json, fetched_at FROM repo_meta WHERE slug = ?").get(slug) as { json: string; fetched_at: string } | undefined;148 return r ? { ...(JSON.parse(r.json) as RepoMeta), fetchedAt: r.fetched_at } : null;149}150