|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from dataclasses import dataclass |
| 4 | +from typing import Any, Dict, List, Mapping, Optional |
| 5 | + |
| 6 | +import aiohttp |
| 7 | + |
| 8 | + |
| 9 | +class CozyHubError(RuntimeError): |
| 10 | + pass |
| 11 | + |
| 12 | + |
| 13 | +class CozyHubNoCompatibleArtifactError(CozyHubError): |
| 14 | + def __init__(self, message: str, *, debug: Optional[object] = None) -> None: |
| 15 | + super().__init__(message) |
| 16 | + self.debug = debug |
| 17 | + |
| 18 | + |
| 19 | +@dataclass(frozen=True) |
| 20 | +class CozyHubArtifact: |
| 21 | + label: str |
| 22 | + file_layout: str |
| 23 | + file_type: str |
| 24 | + quantization: str |
| 25 | + |
| 26 | + |
| 27 | +@dataclass(frozen=True) |
| 28 | +class CozyHubSnapshotFile: |
| 29 | + path: str |
| 30 | + size_bytes: int |
| 31 | + blake3: str |
| 32 | + url: Optional[str] |
| 33 | + |
| 34 | + |
| 35 | +@dataclass(frozen=True) |
| 36 | +class CozyHubResolveArtifactResult: |
| 37 | + repo_revision_seq: int |
| 38 | + snapshot_digest: str |
| 39 | + artifact: Optional[CozyHubArtifact] |
| 40 | + files: List[CozyHubSnapshotFile] |
| 41 | + |
| 42 | + |
| 43 | +class CozyHubV2Client: |
| 44 | + """ |
| 45 | + Cozy Hub v2 model APIs (resolve_artifact). |
| 46 | +
|
| 47 | + Endpoint: |
| 48 | + - POST /api/v1/repos/<org>/<repo>/resolve_artifact |
| 49 | +
|
| 50 | + Response (v1): |
| 51 | + - repo_revision_seq: number |
| 52 | + - snapshot_digest: hex |
| 53 | + - artifact: {label, file_layout, file_type, quantization} |
| 54 | + - snapshot_manifest: {version, files:[{path,size_bytes,blake3,url?}]} |
| 55 | + """ |
| 56 | + |
| 57 | + def __init__(self, base_url: str, token: Optional[str] = None, timeout_s: int = 30) -> None: |
| 58 | + self.base_url = base_url.rstrip("/") |
| 59 | + self.token = (token or "").strip() or None |
| 60 | + self.timeout_s = timeout_s |
| 61 | + |
| 62 | + def _headers(self) -> Dict[str, str]: |
| 63 | + h: Dict[str, str] = {"Content-Type": "application/json"} |
| 64 | + if self.token: |
| 65 | + h["Authorization"] = f"Bearer {self.token}" |
| 66 | + return h |
| 67 | + |
| 68 | + async def resolve_artifact( |
| 69 | + self, |
| 70 | + *, |
| 71 | + org: str, |
| 72 | + repo: str, |
| 73 | + tag: str, |
| 74 | + include_urls: bool, |
| 75 | + preferences: Mapping[str, Any], |
| 76 | + capabilities: Mapping[str, Any], |
| 77 | + ) -> CozyHubResolveArtifactResult: |
| 78 | + if not org or not repo: |
| 79 | + raise ValueError("org/repo required") |
| 80 | + tag = (tag or "").strip() or "latest" |
| 81 | + |
| 82 | + url = f"{self.base_url}/api/v1/repos/{org}/{repo}/resolve_artifact" |
| 83 | + payload = { |
| 84 | + "tag": tag, |
| 85 | + "include_urls": bool(include_urls), |
| 86 | + "preferences": dict(preferences), |
| 87 | + "capabilities": dict(capabilities), |
| 88 | + } |
| 89 | + |
| 90 | + timeout = aiohttp.ClientTimeout(total=self.timeout_s) |
| 91 | + async with aiohttp.ClientSession(timeout=timeout, headers=self._headers()) as session: |
| 92 | + async with session.post(url, json=payload) as resp: |
| 93 | + if resp.status == 409: |
| 94 | + try: |
| 95 | + data = await resp.json() |
| 96 | + except Exception: |
| 97 | + data = {} |
| 98 | + raise CozyHubNoCompatibleArtifactError( |
| 99 | + "no compatible artifact for worker", |
| 100 | + debug=data.get("debug") if isinstance(data, dict) else None, |
| 101 | + ) |
| 102 | + resp.raise_for_status() |
| 103 | + data = await resp.json() |
| 104 | + if not isinstance(data, dict): |
| 105 | + raise ValueError("unexpected response shape") |
| 106 | + |
| 107 | + return _parse_resolve_artifact_response(data, include_urls=include_urls) |
| 108 | + |
| 109 | + async def get_snapshot_manifest(self, *, org: str, repo: str, digest: str) -> List[CozyHubSnapshotFile]: |
| 110 | + """ |
| 111 | + Fetch a snapshot manifest by digest (already pinned). |
| 112 | +
|
| 113 | + Endpoint: |
| 114 | + - GET /api/v1/repos/<org>/<repo>/snapshots/<digest>/manifest |
| 115 | + """ |
| 116 | + if not org or not repo or not digest: |
| 117 | + raise ValueError("org/repo/digest required") |
| 118 | + url = f"{self.base_url}/api/v1/repos/{org}/{repo}/snapshots/{digest}/manifest" |
| 119 | + |
| 120 | + timeout = aiohttp.ClientTimeout(total=self.timeout_s) |
| 121 | + async with aiohttp.ClientSession(timeout=timeout, headers=self._headers()) as session: |
| 122 | + async with session.get(url) as resp: |
| 123 | + resp.raise_for_status() |
| 124 | + data = await resp.json() |
| 125 | + if not isinstance(data, dict): |
| 126 | + raise ValueError("unexpected response shape") |
| 127 | + |
| 128 | + manifest = data.get("files") |
| 129 | + if not isinstance(manifest, list): |
| 130 | + manifest = data.get("root_files") |
| 131 | + if not isinstance(manifest, list): |
| 132 | + raise ValueError("missing files list") |
| 133 | + out: List[CozyHubSnapshotFile] = [] |
| 134 | + for ent in manifest: |
| 135 | + if not isinstance(ent, dict): |
| 136 | + continue |
| 137 | + path = str(ent.get("path") or "").strip() |
| 138 | + if not path: |
| 139 | + continue |
| 140 | + out.append( |
| 141 | + CozyHubSnapshotFile( |
| 142 | + path=path, |
| 143 | + size_bytes=int(ent.get("size_bytes") or 0), |
| 144 | + blake3=str(ent.get("blake3") or "").strip().lower(), |
| 145 | + url=str(ent.get("url") or "").strip() or None, |
| 146 | + ) |
| 147 | + ) |
| 148 | + if not out: |
| 149 | + raise ValueError("empty files list") |
| 150 | + return out |
| 151 | + |
| 152 | + |
| 153 | +def _parse_resolve_artifact_response(data: Mapping[str, Any], *, include_urls: bool) -> CozyHubResolveArtifactResult: |
| 154 | + repo_revision_seq = int(data.get("repo_revision_seq") or 0) |
| 155 | + snapshot_digest = str(data.get("snapshot_digest") or "").strip() |
| 156 | + art = data.get("artifact") |
| 157 | + if not isinstance(art, dict): |
| 158 | + raise ValueError("missing artifact") |
| 159 | + artifact = CozyHubArtifact( |
| 160 | + label=str(art.get("label") or "").strip(), |
| 161 | + file_layout=str(art.get("file_layout") or "").strip(), |
| 162 | + file_type=str(art.get("file_type") or "").strip(), |
| 163 | + quantization=str(art.get("quantization") or "").strip(), |
| 164 | + ) |
| 165 | + if repo_revision_seq <= 0 or not snapshot_digest: |
| 166 | + raise ValueError("missing snapshot_digest/repo_revision_seq") |
| 167 | + if not artifact.label: |
| 168 | + raise ValueError("missing artifact.label") |
| 169 | + |
| 170 | + manifest = data.get("snapshot_manifest") |
| 171 | + if not isinstance(manifest, dict): |
| 172 | + raise ValueError("missing snapshot_manifest") |
| 173 | + files_raw = manifest.get("files") |
| 174 | + if not isinstance(files_raw, list): |
| 175 | + raise ValueError("missing snapshot_manifest.files") |
| 176 | + |
| 177 | + files: List[CozyHubSnapshotFile] = [] |
| 178 | + for ent in files_raw: |
| 179 | + if not isinstance(ent, dict): |
| 180 | + continue |
| 181 | + path = str(ent.get("path") or "").strip() |
| 182 | + if not path: |
| 183 | + continue |
| 184 | + size_bytes = int(ent.get("size_bytes") or 0) |
| 185 | + blake3_hex = str(ent.get("blake3") or "").strip().lower() |
| 186 | + url = str(ent.get("url") or "").strip() if include_urls else "" |
| 187 | + files.append( |
| 188 | + CozyHubSnapshotFile( |
| 189 | + path=path, |
| 190 | + size_bytes=size_bytes, |
| 191 | + blake3=blake3_hex, |
| 192 | + url=url or None, |
| 193 | + ) |
| 194 | + ) |
| 195 | + if not files: |
| 196 | + raise ValueError("empty snapshot file list") |
| 197 | + |
| 198 | + return CozyHubResolveArtifactResult( |
| 199 | + repo_revision_seq=repo_revision_seq, |
| 200 | + snapshot_digest=snapshot_digest, |
| 201 | + artifact=artifact, |
| 202 | + files=files, |
| 203 | + ) |
0 commit comments