| 1 | from __future__ import annotations |
| 2 | |
| 3 | import asyncio |
| 4 | import json |
| 5 | import math |
| 6 | import struct |
| 7 | from typing import Any |
| 8 | |
| 9 | PROTOCOL = "hab/2" |
| 10 | MAX_FRAME_BYTES = 8 * 1024 * 1024 |
| 11 | PODCAST_REPORT_CAPABILITY = "podcast.report" |
| 12 | KEEPALIVE_SECS = 10 |
| 13 | IDLE_TIMEOUT_SECS = 30.0 |
| 14 | GREETING_TIMEOUT_SECS = 8.0 |
| 15 | CERTIFICATE_PATH = "/ai/certificate" |
| 16 | DEADLINE_MARGIN_SECS = 0.25 |
| 17 | API_TIMEOUT_SECS = 15.0 |
| 18 | |
| 19 | |
| 20 | class CapabilityError(Exception): |
| 21 | def __init__(self, code: str, message: str) -> None: |
| 22 | super().__init__(message) |
| 23 | self.code = code |
| 24 | |
| 25 | |
| 26 | PERMANENT_REJECTS = ("unsupported_protocol", "unauthorized") |
| 27 | |
| 28 | |
| 29 | class HandshakeRejected(RuntimeError): |
| 30 | def __init__(self, code: str, message: str) -> None: |
| 31 | super().__init__(f"backend kaydi reddetti ({code}): {message}") |
| 32 | self.code = code |
| 33 | |
| 34 | @property |
| 35 | def permanent(self) -> bool: |
| 36 | return self.code in PERMANENT_REJECTS |
| 37 | |
| 38 | |
| 39 | def encode_frame(obj: Any) -> bytes: |
| 40 | body = json.dumps(obj, ensure_ascii=False).encode("utf-8") |
| 41 | if len(body) > MAX_FRAME_BYTES: |
| 42 | raise CapabilityError("frame_too_large", f"{len(body)} bayt cerceve sinirini asiyor") |
| 43 | return struct.pack(">I", len(body)) + body |
| 44 | |
| 45 | |
| 46 | class FrameStream: |
| 47 | def __init__(self) -> None: |
| 48 | self._buf = bytearray() |
| 49 | self._queue: "asyncio.Queue[bytes | None]" = asyncio.Queue() |
| 50 | self._eof = False |
| 51 | |
| 52 | def feed(self, data: bytes, end: bool) -> None: |
| 53 | if data: |
| 54 | self._queue.put_nowait(data) |
| 55 | if end: |
| 56 | self._queue.put_nowait(None) |
| 57 | |
| 58 | async def _read_exact(self, n: int) -> bytes: |
| 59 | while len(self._buf) < n: |
| 60 | if self._eof: |
| 61 | raise EOFError("cerceve tamamlanmadan akis bitti") |
| 62 | chunk = await self._queue.get() |
| 63 | if chunk is None: |
| 64 | self._eof = True |
| 65 | continue |
| 66 | self._buf.extend(chunk) |
| 67 | out = bytes(self._buf[:n]) |
| 68 | del self._buf[:n] |
| 69 | return out |
| 70 | |
| 71 | async def read_frame(self) -> Any: |
| 72 | header = await self._read_exact(4) |
| 73 | (length,) = struct.unpack(">I", header) |
| 74 | if length > MAX_FRAME_BYTES: |
| 75 | raise CapabilityError("frame_too_large", f"{length} bayt cerceve sinirini asiyor") |
| 76 | body = await self._read_exact(length) |
| 77 | return json.loads(body) |
| 78 | |
| 79 | |
| 80 | def build_hello( |
| 81 | service: str, capabilities: list[str], token: str, max_concurrent: int |
| 82 | ) -> dict[str, Any]: |
| 83 | return { |
| 84 | "protocol": PROTOCOL, |
| 85 | "service": service, |
| 86 | "capabilities": list(capabilities), |
| 87 | "token": token, |
| 88 | "max_concurrent": max_concurrent, |
| 89 | } |
| 90 | |
| 91 | |
| 92 | def parse_greeting(greeting: Any) -> str: |
| 93 | if not isinstance(greeting, dict): |
| 94 | raise HandshakeRejected("malformed", "greeting bir nesne degil") |
| 95 | if greeting.get("type") == "welcome": |
| 96 | if greeting.get("protocol") != PROTOCOL: |
| 97 | raise HandshakeRejected( |
| 98 | "unsupported_protocol", f"beklenmeyen protokol: {greeting.get('protocol')}" |
| 99 | ) |
| 100 | return str(greeting.get("worker_id", "?")) |
| 101 | raise HandshakeRejected( |
| 102 | str(greeting.get("code", "?")), str(greeting.get("message", "")) |
| 103 | ) |
| 104 | |
| 105 | |
| 106 | def ok_response(request_id: str, school: str, payload: dict[str, Any]) -> dict[str, Any]: |
| 107 | return {"status": "ok", "id": request_id, "school": school, "payload": payload} |
| 108 | |
| 109 | |
| 110 | def err_response( |
| 111 | request_id: str, school: str, code: str, message: str |
| 112 | ) -> dict[str, Any]: |
| 113 | return { |
| 114 | "status": "err", |
| 115 | "id": request_id, |
| 116 | "school": school, |
| 117 | "code": code, |
| 118 | "message": message, |
| 119 | } |
| 120 | |
| 121 | |
| 122 | def parse_request(frame: Any) -> tuple[str, str, str, Any, float | None]: |
| 123 | if not isinstance(frame, dict): |
| 124 | raise CapabilityError("bad_request", "istek cercevesi bir nesne degil") |
| 125 | request_id = frame.get("id") |
| 126 | school = frame.get("school") |
| 127 | capability = frame.get("capability") |
| 128 | if not isinstance(request_id, str) or not isinstance(capability, str): |
| 129 | raise CapabilityError("bad_request", "'id' ve 'capability' metin olmali") |
| 130 | if not isinstance(school, str) or not school.strip(): |
| 131 | raise CapabilityError("bad_request", "'school' bos olmayan bir metin olmali") |
| 132 | deadline_ms = frame.get("deadline_ms") |
| 133 | timeout = None |
| 134 | if isinstance(deadline_ms, (int, float)) and not isinstance(deadline_ms, bool): |
| 135 | if deadline_ms > 0: |
| 136 | budget_secs = deadline_ms / 1000.0 |
| 137 | timeout = max(budget_secs - DEADLINE_MARGIN_SECS, budget_secs * 0.5) |
| 138 | return request_id, school, capability, frame.get("payload"), timeout |
| 139 | |
| 140 | API_ALLOWLIST = ( |
| 141 | "/auth/me", |
| 142 | "/users/me/profile", |
| 143 | "/users/{id}/profile", |
| 144 | "/notes", |
| 145 | "/notes/{id}", |
| 146 | "/homework", |
| 147 | "/homework/{id}", |
| 148 | "/homework/{id}/result", |
| 149 | "/homework/{id}/submission", |
| 150 | "/homework/report/{user}", |
| 151 | "/marks/me", |
| 152 | "/marks/{user}", |
| 153 | "/attendance/me", |
| 154 | "/attendance/{user}", |
| 155 | "/pomodoro/me", |
| 156 | "/pomodoro/{user}", |
| 157 | ) |
| 158 | |
| 159 | |
| 160 | class ApiRefused(Exception): |
| 161 | def __init__( |
| 162 | self, code: str, message: str, school: str = "", request_id: str = "" |
| 163 | ) -> None: |
| 164 | super().__init__(f"kopru istegi reddetti ({code}): {message}") |
| 165 | self.code = code |
| 166 | self.school = school |
| 167 | self.request_id = request_id |
| 168 | |
| 169 | |
| 170 | class ApiResponse: |
| 171 | def __init__(self, request_id: str, school: str, status: int, body: Any) -> None: |
| 172 | self.request_id = request_id |
| 173 | self.school = school |
| 174 | self.status = status |
| 175 | self.body = body |
| 176 | |
| 177 | @property |
| 178 | def ok(self) -> bool: |
| 179 | return 200 <= self.status < 300 |
| 180 | |
| 181 | |
| 182 | def build_api_request( |
| 183 | request_id: str, |
| 184 | school: str, |
| 185 | path: str, |
| 186 | query: str | None = None, |
| 187 | on_behalf_of: str | None = None, |
| 188 | method: str = "GET", |
| 189 | ) -> dict[str, Any]: |
| 190 | if not isinstance(school, str) or not school.strip(): |
| 191 | raise ApiRefused("malformed", "okul slug'i zorunlu; varsayilan yok") |
| 192 | if not isinstance(path, str) or not path.startswith("/") or "?" in path: |
| 193 | raise ApiRefused( |
| 194 | "bad_path", |
| 195 | f"yol / ile baslamali ve ? icermemeli (query ayri alanda gider): {path!r}", |
| 196 | school=school, |
| 197 | ) |
| 198 | request: dict[str, Any] = { |
| 199 | "id": request_id, |
| 200 | "school": school, |
| 201 | "path": path, |
| 202 | "method": method, |
| 203 | } |
| 204 | if query: |
| 205 | request["query"] = query.lstrip("?") |
| 206 | if on_behalf_of: |
| 207 | request["on_behalf_of"] = on_behalf_of |
| 208 | return request |
| 209 | |
| 210 | |
| 211 | def build_capability_call( |
| 212 | request_id: str, school: str, capability: str, payload: dict[str, Any] |
| 213 | ) -> dict[str, Any]: |
| 214 | if not isinstance(school, str) or not school.strip(): |
| 215 | raise CapabilityError("malformed", "okul slug'i zorunlu; varsayilan yok") |
| 216 | if not isinstance(capability, str) or not capability.strip(): |
| 217 | raise CapabilityError("malformed", "yetenek adi zorunlu") |
| 218 | return { |
| 219 | "id": request_id, |
| 220 | "school": school, |
| 221 | "capability": capability, |
| 222 | "payload": payload, |
| 223 | } |
| 224 | |
| 225 | |
| 226 | def parse_capability_response(frame: Any, request_id: str) -> dict[str, Any]: |
| 227 | if not isinstance(frame, dict): |
| 228 | raise CapabilityError("malformed", "yetenek cevabi bir nesne degil") |
| 229 | status_field = frame.get("status") |
| 230 | if status_field == "ok": |
| 231 | payload = frame.get("payload") |
| 232 | if not isinstance(payload, dict): |
| 233 | raise CapabilityError("malformed", "yetenek cevabinda 'payload' nesne degil") |
| 234 | return payload |
| 235 | if status_field == "err": |
| 236 | raise CapabilityError( |
| 237 | str(frame.get("code", "?")), str(frame.get("message", "")) |
| 238 | ) |
| 239 | raise CapabilityError("malformed", f"bilinmeyen cevap durumu: {status_field!r}") |
| 240 | |
| 241 | |
| 242 | def build_upload_request( |
| 243 | request_id: str, |
| 244 | school: str, |
| 245 | job_id: str, |
| 246 | name: str, |
| 247 | content_type: str, |
| 248 | size: int, |
| 249 | duration_secs: float | None = None, |
| 250 | ) -> dict[str, Any]: |
| 251 | if not isinstance(school, str) or not school.strip(): |
| 252 | raise CapabilityError("malformed", "okul slug'i zorunlu; varsayilan yok") |
| 253 | request: dict[str, Any] = { |
| 254 | "id": request_id, |
| 255 | "upload": True, |
| 256 | "school": school, |
| 257 | "job_id": job_id, |
| 258 | "name": name, |
| 259 | "content_type": content_type, |
| 260 | "size": int(size), |
| 261 | } |
| 262 | if duration_secs is not None: |
| 263 | request["duration_secs"] = float(duration_secs) |
| 264 | return request |
| 265 | |
| 266 | |
| 267 | def parse_upload_response(frame: Any) -> dict[str, Any]: |
| 268 | if not isinstance(frame, dict): |
| 269 | raise CapabilityError("malformed", "yukleme cevabi bir nesne degil") |
| 270 | status_field = frame.get("status") |
| 271 | if status_field == "ok": |
| 272 | key = frame.get("key") |
| 273 | if not isinstance(key, str) or not key: |
| 274 | raise CapabilityError("malformed", "yukleme cevabinda 'key' yok") |
| 275 | return frame |
| 276 | if status_field == "err": |
| 277 | raise CapabilityError( |
| 278 | str(frame.get("code", "?")), str(frame.get("message", "")) |
| 279 | ) |
| 280 | raise CapabilityError("malformed", f"bilinmeyen yukleme durumu: {status_field!r}") |
| 281 | |
| 282 | |
| 283 | def _coerce_status(value: Any) -> int: |
| 284 | if isinstance(value, bool): |
| 285 | return int(value) |
| 286 | if isinstance(value, int): |
| 287 | return value |
| 288 | if isinstance(value, float): |
| 289 | if math.isnan(value) or math.isinf(value): |
| 290 | raise ApiRefused("malformed", f"status sayisal degil: {value!r}") |
| 291 | return int(value) |
| 292 | if isinstance(value, str): |
| 293 | try: |
| 294 | return int(value) |
| 295 | except ValueError as exc: |
| 296 | raise ApiRefused("malformed", f"status sayisal degil: {value!r}") from exc |
| 297 | raise ApiRefused("malformed", f"status sayisal degil: {value!r}") |
| 298 | |
| 299 | |
| 300 | def parse_api_response(frame: Any) -> ApiResponse: |
| 301 | if not isinstance(frame, dict): |
| 302 | raise ApiRefused("malformed", "api cevabi bir nesne degil") |
| 303 | outcome = frame.get("outcome") |
| 304 | school = str(frame.get("school", "")) |
| 305 | request_id = str(frame.get("id", "")) |
| 306 | if outcome == "err": |
| 307 | raise ApiRefused( |
| 308 | str(frame.get("code", "?")), |
| 309 | str(frame.get("message", "")), |
| 310 | school=school, |
| 311 | request_id=request_id, |
| 312 | ) |
| 313 | if outcome != "ok": |
| 314 | raise ApiRefused("malformed", f"bilinmeyen outcome: {outcome!r}", school=school) |
| 315 | return ApiResponse( |
| 316 | request_id, |
| 317 | school, |
| 318 | _coerce_status(frame.get("status", 0)), |
| 319 | frame.get("body"), |
| 320 | ) |