feat(forge): fondation multi-forges — connexions chiffrées, registre, client GitHub (P0/P1)

- Tables forge_connections/users/workspaces (+ membres, projets,
  états, audit) ; migration des anciennes bases avec portées
  (workspace_id, connection_id) par défaut (1, 1).
- Jetons chiffrés Fernet (KANBANTE_MASTER_KEY ou clé générée en
  base), jamais réaffichés.
- ForgeRegistry : connexion héritée créée depuis l'environnement,
  espace Principal, instantanés préfixés par connexion.
- GitHubClient complet (Bearer, pagination Link, étiquettes par
  nom, PATCH archived, branches via git/refs).
- Paramètres surchargeables en base (résolveur config, P3).
This commit is contained in:
Spark
2026-10-21 14:48:29 -04:00
parent f1a05279b6
commit 735d7cdfd0
11 changed files with 1403 additions and 79 deletions
+48 -8
View File
@@ -38,7 +38,18 @@ MAX_PAGES = 40 # hard stop: 40 * 50 = 2000 items per list
class GiteaClient:
"""Lightweight async Gitea API client for Kanbante."""
"""Lightweight async Gitea API client for Kanbante.
Since 0.24.0 this class is the reference implementation of
the forge protocol: GitHubClient subclasses it and overrides
the endpoints whose shape differs. ``api_suffix`` and
``auth_scheme`` are the two seams; ``key_prefix`` namespaces
the persisted snapshots per connection ("c<id>:").
"""
kind = "gitea"
api_suffix = "/api/v1"
auth_scheme = "token"
def __init__(
self,
@@ -51,11 +62,15 @@ class GiteaClient:
self.base_url = (base_url or settings.gitea_url).rstrip("/")
self.token = settings.gitea_token if token is None else token
self.cache_ttl = settings.cache_ttl if cache_ttl is None else cache_ttl
self.key_prefix = ""
self.connection_id = 1
self.connection_slug = "gitea"
headers = {"Accept": "application/json"}
headers.update(self._extra_headers())
if self.token:
headers["Authorization"] = f"token {self.token}"
headers["Authorization"] = f"{self.auth_scheme} {self.token}"
self.client = httpx.AsyncClient(
base_url=f"{self.base_url}/api/v1",
base_url=f"{self.base_url}{self.api_suffix}",
headers=headers,
timeout=15.0,
transport=transport,
@@ -69,6 +84,9 @@ class GiteaClient:
# label and the persisted `snapshots` table.
self._snapshot_times: dict[str, str] = {}
def _extra_headers(self) -> dict:
return {}
async def aclose(self) -> None:
await self.client.aclose()
@@ -120,6 +138,9 @@ class GiteaClient:
# ── Snapshots (chantier B, 0.22.0) ──────────────────────
def _prefixed(self, key: str) -> str:
return f"{self.key_prefix}{key}"
def _persist_snapshot(self, key: str, value: Any) -> None:
"""Write-through to the SQLite snapshots table.
@@ -129,7 +150,7 @@ class GiteaClient:
try:
from app import models
models.save_snapshot(key, value)
models.save_snapshot(self._prefixed(key), value)
import datetime
self._snapshot_times[key] = datetime.datetime.now(
@@ -157,12 +178,20 @@ class GiteaClient:
logger.warning("snapshot hydration failed: %s", exc)
return 0
stale_at = time.monotonic() - self.cache_ttl - 1.0
for key, (payload, updated_at) in snapshots.items():
count = 0
for stored_key, (payload, updated_at) in snapshots.items():
if self.key_prefix:
if not stored_key.startswith(self.key_prefix):
continue
key = stored_key[len(self.key_prefix):]
else:
key = stored_key
self._cache[key] = (stale_at, payload)
self._snapshot_times[key] = updated_at
if snapshots:
logger.info("hydrated %d snapshot(s) from SQLite", len(snapshots))
return len(snapshots)
count += 1
if count:
logger.info("hydrated %d snapshot(s) from SQLite", count)
return count
def latest_snapshot_at(self) -> str | None:
"""Freshest Gitea fetch time across tracked keys (UTC str)."""
@@ -487,6 +516,17 @@ class GiteaClient:
self._cache_clear()
return r.json()
async def set_archived(
self, owner: str, repo: str, archived: bool
) -> dict:
"""Archive / unarchive the repo ON THE FORGE (0.24.0, P4)."""
r = await self.client.put(
f"/repos/{owner}/{repo}", json={"archived": archived}
)
r.raise_for_status()
self._cache_clear()
return r.json()
async def create_branch(
self, owner: str, repo: str, new_branch: str, old_branch: str
) -> dict: