forge
Explore
Log in

Don't you dare go Hollow

hezarfen_zeka

Clone
★ 0

0 watching0 forksPython1.9 MiBe01a4faAhmet Kaan Gümüş2 months ago25 commits

protocol.py943 lines, 32.3 KiBHistoryRawDownload
1"""`hab/2` kablo bicimi -- backend'in `src/ai/protocol.rs` dosyasinin Python karsiligi.
2
3OTORITE: `hezarfen_backend-main/src/ai/protocol.rs`. Burada gecen her alan adi
4orada gectigi gibi yazilmistir; bir alani yeniden adlandirmak sessizce her seyi
5bozar (`protocol.rs:422-424` testi tam bunu pinliyor).
6
7Cerceve bicimi (`protocol.rs:54-59`):
8 u32 big-endian uzunluk + o kadar bayt UTF-8 JSON.
9
10Akis disiplini (`protocol.rs:9-34`):
11 * Kontrol akisi: ilk *istemci* baslatimli cift yonlu akis. Servis bir `Hello`
12 yazar, backend bir `Greeting` yazar, akis omur boyu ACIK kalir. Kapanmasi
13 kayittan dusme sinyalidir; heartbeat cercevesi yoktur.
14 * Is: *sunucu* baslatimli her akis bir `Request` tasir, servis bir `Response`
15 yazar ve akis kapanir.
16 * API geri okumasi: servisin actigi (kontrol akisindan sonraki) her istemci
17 baslatimli akis bir `ApiRequest` tasir, backend bir `ApiResponse` yazar.
18 * Blob okumasi: ayni yon, bir `BlobRequest`; backend bir `BlobResponse`
19 BASLIK cercevesi yazar, `ok` ise tam `size` HAM bayt onu izler -- bunlar
20 cerceve DEGILDIR, dolayisiyla cerceve boyut kapagina tabi degildir
21 (`protocol.rs:26-31`).
22
23Uc istemci baslatimli sekil, zorunlu alaniyla ayirt edilir: `ApiRequest`'te
24`path`, `BlobRequest`'te `file`, `CapabilityRequest`'te `capability` vardir
25(`protocol.rs:34`, `server.rs:481-497`). Ilk ikisi okulun KENDI API'sini
26okur; ucuncusu backend'in bir operasyonunu kosturur -- ZEKA'nin veritabani
27erisimi olmadigi icin yazma yolu YALNIZCA budur.
28
29Okul kapsami (`protocol.rs:36-47`): her istek cercevesi okulunu tireli uuid ile
30adlandirir, her cevap onu yankilar. `Hello` KASITLI olarak okul tasimaz --
31filo tum okullar icin paylasilir. Varsayilan ya da geri dusme yoktur.
32
33Korelasyon kimligi yoktur (`protocol.rs:48-52`): QUIC akis kimlikleri zaten
34coklama yapar. `id` yalnizca iz kimligidir.
35"""
36
37from __future__ import annotations
38
39import asyncio
40import json
41import math
42import os
43import struct
44import time
45from dataclasses import dataclass, field
46from typing import Any
47
48# --- backend'den turetilen sabitler ----------------------------------------
49# Kopyalanmadi, TURETILDI: her birinin kaynak satiri yanindadir. Backend bu
50# degerleri degistirirse burasi sapar; sapmayi yakalayan sey `tests/` icindeki
51# sabit testleri ve `docs/BACKEND-GEREKSINIMLERI.md` icindeki sapma notudur.
52
53AI_PROTOCOL = "hab/2"
54"""`constant.rs:530` -- `pub const AI_PROTOCOL: &str = "hab/2";`
55
56DIKKAT: podcast ve Celebi servisleri `hab/1` kullaniyor ve bu YANLIS. Sürüm
57kapisi iki yerde birden reddeder: ALPN muzakeresi (TLS el sikismasinda) ve
58`protocol.rs:323` `protocol_matches`. ZEKA `hab/2` konusur.
59"""
60
61AI_ALPN = "hab/2"
62"""`constant.rs:531` -- `pub const AI_ALPN: &[u8] = b"hab/2";` Ayni dize."""
63
64AI_MAX_FRAME_BYTES = 8 * 1024 * 1024
65"""`constant.rs:536` -- tek bir cercevenin tavanı. Uzunluk oneki, govde
66ayrilmadan ONCE denetlenir; boylece kotu bir uzunluk bellek tuketemez."""
67
68AI_MAX_CONCURRENT_PER_WORKER = 64
69"""`constant.rs:547` -- backend `Hello.max_concurrent` degerini 1..=64 arasina
70kirpar."""
71
72AI_DEFAULT_CONCURRENT_PER_WORKER = 8
73"""`constant.rs:548` -- `max_concurrent` verilmezse kullanilan deger."""
74
75AI_IDLE_TIMEOUT_SECS = 30
76"""`constant.rs:554` -- QUIC bosta kalma zaman asimi."""
77
78AI_KEEPALIVE_SECS = 10
79"""`constant.rs:555` -- QUIC PING araligi; bosta kalma zaman asiminin cok
80altinda ki saglikli ama sessiz bir servis dusurulmesin."""
81
82AI_HANDSHAKE_TIMEOUT_SECS = 10
83"""`constant.rs:643` -- el sikisma tek cerceve gidis-donustur; kimliksiz bir
84baglanti dinleyiciyi sonsuza dek mesgul edemez."""
85
86AI_BLOB_WRITE_STALL_SECS = 30
87"""`constant.rs:563` -- blob govdesinin yazma basina ilerleme tavani. Aktarim
88kapagi DEGIL, TIKANMA kapagi."""
89
90AI_DEFAULT_REQUEST_TIMEOUT_SECS = 30
91"""`constant.rs:542` -- backend bir AI istegini terk etmeden once bekledigi
92varsayilan sure. Servis tarafinda yalnizca bilgi amaclidir; gercek sure her
93`Request` cercevesinin kendi `deadline_ms` alanindadir."""
94
95CERTIFICATE_PATH = "/ai/certificate"
96"""`src/web/ai.rs` -- `certificate_pem` + `fingerprint_sha256` doner."""
97
98DEADLINE_MARGIN_SECS = 0.25
99"""Kendi degerimiz: backend'in `deadline_ms` suresi dolmadan hemen once
100cevaplayabilmek icin butceden dusulen pay. Gec cevap yerine erken hata."""
101
102GREETING_TIMEOUT_SECS = 8.0
103"""Kendi degerimiz; backend'in `AI_HANDSHAKE_TIMEOUT_SECS` = 10 s degerinin
104altinda tutulur ki reddi biz gorelim, akis altimizdan kesilmesin."""
105
106AI_API_ALLOWLIST: tuple[str, ...] = (
107 "/auth/me",
108 "/users/me/profile",
109 "/users/{id}/profile",
110 "/notes",
111 "/notes/{id}",
112 "/course-notes",
113 "/course-notes/{id}",
114 "/course-notes/{id}/files",
115 "/homework",
116 "/homework/{id}",
117 "/homework/{id}/result",
118 "/homework/{id}/submission",
119 "/homework/report/{user}",
120 "/marks/me",
121 "/marks/{user}",
122 "/attendance/me",
123 "/attendance/{user}",
124 "/pomodoro/me",
125 "/pomodoro/{user}",
126)
127"""`constant.rs:656-676` -- AI servislerinin okuyabilecegi TEK yol kumesi.
128
129Reddet-varsayilan, segment segment eslesme (`ai/api.rs:39-60`): on-ek eslesmesi
130ve kuyruk joker'i YOKTUR. `/notes` asla `/notes/{id}/files` kabul etmez. Bu
131liste servislerin erisim kapsaminin ta kendisidir.
132
133Bu demet backend'in listesinin AYNASIDIR. Sapma testi: `tests/test_protocol.py`
134icindeki `test_allowlist_matches_backend_snapshot`.
135"""
136
137
138# --- hata kodlari ----------------------------------------------------------
139# Backend'in tel uzerinde dondurdugu, makine okunabilir, kararli kodlar.
140
141
142class RejectCode:
143 """`Greeting{type:"rejected"}` icindeki `code` degerleri (`protocol.rs:123-130`)."""
144
145 UNSUPPORTED_PROTOCOL = "unsupported_protocol"
146 UNAUTHORIZED = "unauthorized"
147 NO_CAPABILITIES = "no_capabilities"
148 MALFORMED = "malformed"
149
150
151class ApiErrorCode:
152 """`ApiResponse{outcome:"err"}` / `BlobResponse{status:"err"}` kodlari.
153
154 Kaynaklar: `ai/server.rs:75-99` (okul cozumleme), `ai/server.rs:719-731`
155 (yontem ve izin listesi), `ai/server.rs:709` (kullanici), `ai/server.rs:628`
156 ve `:650` (blob).
157 """
158
159 MALFORMED = "malformed"
160 UNKNOWN_SCHOOL = "unknown_school"
161 SCHOOL_SUSPENDED = "school_suspended"
162 UNAVAILABLE = "unavailable"
163 PATH_NOT_ALLOWED = "path_not_allowed"
164 METHOD_NOT_ALLOWED = "method_not_allowed"
165 UNKNOWN_USER = "unknown_user"
166 NOT_FOUND = "not_found"
167 FORBIDDEN = "forbidden"
168
169
170#: Yapilandirma degismeden yeniden denemenin anlamsiz oldugu red kodlari.
171#: Yine de CIKMIYORUZ (bkz. `bridge.py`): backend yeniden dagitilabilir.
172PERMANENT_REJECTS = (RejectCode.UNSUPPORTED_PROTOCOL, RejectCode.UNAUTHORIZED)
173
174#: Daha sonra denemeye deger red kodlari (`server.rs:75-81` gerekcesi).
175RETRYABLE_API_CODES = (ApiErrorCode.SCHOOL_SUSPENDED, ApiErrorCode.UNAVAILABLE)
176
177
178# --- istisnalar ------------------------------------------------------------
179
180
181class ProtocolError(Exception):
182 """Kablo seviyesinde bir sorun. `code` makine okunabilirdir."""
183
184 def __init__(self, code: str, message: str) -> None:
185 super().__init__(message)
186 self.code = code
187
188
189class FrameTooLarge(ProtocolError):
190 """Cerceve `AI_MAX_FRAME_BYTES` kapagini asiyor."""
191
192 def __init__(self, size: int) -> None:
193 super().__init__(
194 "frame_too_large",
195 f"{size} bayt, {AI_MAX_FRAME_BYTES} baytlik cerceve sinirini asiyor",
196 )
197 self.size = size
198
199
200class FrameMalformed(ProtocolError):
201 """Cerceve govdesi beklenen mesaj icin gecerli JSON degil."""
202
203 def __init__(self, message: str) -> None:
204 super().__init__(ApiErrorCode.MALFORMED, message)
205
206
207class HandshakeRejected(RuntimeError):
208 """`Greeting{type:"rejected"}` alindi."""
209
210 def __init__(self, code: str, message: str) -> None:
211 super().__init__(f"backend kaydi reddetti ({code}): {message}")
212 self.code = code
213 self.message = message
214
215 @property
216 def permanent(self) -> bool:
217 return self.code in PERMANENT_REJECTS
218
219
220class ApiRefused(Exception):
221 """Kopru seviyesinde red: `ApiResponse{outcome:"err"}`.
222
223 HTTP 404 bu DEGILDIR: router calisip cevap verdiyse o bir `ok`'tur ve
224 `status` alaninda tasinir (`protocol.rs:196-198`).
225 """
226
227 def __init__(self, code: str, message: str, school: str = "", request_id: str = "") -> None:
228 super().__init__(f"kopru istegi reddetti ({code}): {message}")
229 self.code = code
230 self.message = message
231 self.school = school
232 self.request_id = request_id
233
234 @property
235 def retryable(self) -> bool:
236 return self.code in RETRYABLE_API_CODES
237
238
239class BlobRefused(ApiRefused):
240 """`BlobResponse{status:"err"}`."""
241
242
243#: Yeniden denenmeye deger yetenek redleri. `timed_out` BURADA: yazinin
244#: dusup dusmedigi BILINMIYOR, o yuzden ayni cerceve taze kimlikle yeniden
245#: gonderilir -- `insight.*` yazmalari idempotenttir: ayni satir ayni
246#: degerlerle yeniden yazilir.
247RETRYABLE_CAPABILITY_CODES = ("unavailable", "school_suspended", "timed_out")
248
249
250class CapabilityRefused(ApiRefused):
251 """`CapabilityResponse{status:"err"}` — servisin actigi yetenek cagrisi."""
252
253 @property
254 def retryable(self) -> bool:
255 return self.code in RETRYABLE_CAPABILITY_CODES
256
257
258class CapabilityError(Exception):
259 """Yetenek isleyicisinin ele alinmis hatasi; `Response{status:"err"}` olur."""
260
261 def __init__(self, code: str, message: str) -> None:
262 super().__init__(message)
263 self.code = code
264
265
266# --- iz kimligi ------------------------------------------------------------
267
268_CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
269
270
271def new_trace_id() -> str:
272 """ULID uretir (48 bit zaman + 80 bit rastgelelik, Crockford base32).
273
274 Backend `id` alanini ULID diye belgeler (`protocol.rs:136`) ama dogrulamaz;
275 yine de ayni bicimde uretiyoruz ki iki tarafin loglari yan yana okunsun.
276 Harici bagimlilik eklememek icin elle yazildi.
277 """
278 value = (int(time.time() * 1000) << 80) | int.from_bytes(os.urandom(10), "big")
279 out = [""] * 26
280 for index in range(25, -1, -1):
281 out[index] = _CROCKFORD[value & 0x1F]
282 value >>= 5
283 return "".join(out)
284
285
286# --- cerceveleme -----------------------------------------------------------
287
288
289def encode_frame(obj: Any) -> bytes:
290 """Bir nesneyi tek bir uzunluk onekli JSON cerceveye cevir.
291
292 Boyut kapagi YAZARKEN de uygulanir (`protocol.rs:275-277`): sinirin ustunde
293 bir cerceve yazmak, karsi tarafin onu okuyamayacagi bir akis birakmaktir.
294 """
295 body = json.dumps(obj, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
296 if len(body) > AI_MAX_FRAME_BYTES:
297 raise FrameTooLarge(len(body))
298 return struct.pack(">I", len(body)) + body
299
300
301def decode_frame(data: bytes) -> Any:
302 """Tek bir tam cerceveyi (uzunluk oneki dahil) coz. Testler icin."""
303 if len(data) < 4:
304 raise FrameMalformed("cerceve 4 baytlik uzunluk onegini bile tasimiyor")
305 (length,) = struct.unpack(">I", data[:4])
306 if length > AI_MAX_FRAME_BYTES:
307 raise FrameTooLarge(length)
308 body = data[4 : 4 + length]
309 if len(body) != length:
310 raise FrameMalformed(f"{length} bayt vaat edildi, {len(body)} bayt var")
311 try:
312 return json.loads(body)
313 except ValueError as exc:
314 raise FrameMalformed(f"cerceve govdesi gecerli JSON degil: {exc}") from exc
315
316
317class FrameStream:
318 """Tek bir QUIC akisindan cerceve okuyan tampon.
319
320 `feed()` aioquic'in `StreamDataReceived` olayindan beslenir; `read_frame()`
321 bir tam cerceve, `read_exact()` ham bayt dondurur (blob govdesi icin).
322 """
323
324 def __init__(self) -> None:
325 self._buf = bytearray()
326 self._queue: asyncio.Queue[bytes | None] = asyncio.Queue()
327 self._eof = False
328
329 def feed(self, data: bytes, end: bool) -> None:
330 if data:
331 self._queue.put_nowait(data)
332 if end:
333 self._queue.put_nowait(None)
334
335 async def read_exact(self, n: int) -> bytes:
336 """Tam `n` bayt oku. Akis erken biterse `EOFError`.
337
338 Blob govdesi bu yoldan gelir: cerceve degil, ham bayt
339 (`protocol.rs:26-31`), dolayisiyla cerceve kapagina tabi degildir.
340 """
341 while len(self._buf) < n:
342 if self._eof:
343 raise EOFError("cerceve/govde tamamlanmadan akis bitti")
344 chunk = await self._queue.get()
345 if chunk is None:
346 self._eof = True
347 continue
348 self._buf.extend(chunk)
349 out = bytes(self._buf[:n])
350 del self._buf[:n]
351 return out
352
353 async def read_frame(self) -> Any:
354 header = await self.read_exact(4)
355 (length,) = struct.unpack(">I", header)
356 # Uzunluk, govde AYRILMADAN once denetlenir (`protocol.rs:286-289`).
357 if length > AI_MAX_FRAME_BYTES:
358 raise FrameTooLarge(length)
359 body = await self.read_exact(length)
360 try:
361 return json.loads(body)
362 except ValueError as exc:
363 raise FrameMalformed(f"cerceve govdesi gecerli JSON degil: {exc}") from exc
364
365
366# --- cerceve tipleri -------------------------------------------------------
367# Alan adlari birebir telde gecen adlardir. `to_wire()` cikti, `from_wire()`
368# giris; ikisi arasindaki gidis-donus testte pinlenir.
369
370
371def _require_str(raw: Any, name: str) -> str:
372 if not isinstance(raw, dict):
373 raise FrameMalformed("cerceve bir nesne degil")
374 value = raw.get(name)
375 if not isinstance(value, str) or not value:
376 raise FrameMalformed(f"'{name}' bos olmayan bir metin olmali")
377 return value
378
379
380def _optional_str(raw: dict, name: str) -> str | None:
381 value = raw.get(name)
382 if value is None:
383 return None
384 if not isinstance(value, str):
385 raise FrameMalformed(f"'{name}' metin ya da yok olmali")
386 return value
387
388
389@dataclass(frozen=True)
390class Hello:
391 """Servisin kontrol akisindaki acilis cercevesi (`protocol.rs:85-103`).
392
393 KASITLI olarak okul tasimaz: filo paylasimlidir, tek baglanti dagitimdaki
394 her okula hizmet eder ve her frame kendi okulunu adlandirir.
395 """
396
397 protocol: str
398 service: str
399 capabilities: tuple[str, ...]
400 token: str
401 max_concurrent: int | None = None
402
403 def to_wire(self) -> dict[str, Any]:
404 wire: dict[str, Any] = {
405 "protocol": self.protocol,
406 "service": self.service,
407 "capabilities": list(self.capabilities),
408 "token": self.token,
409 }
410 # `#[serde(default)]`: yoklugu varsayilan demektir (`protocol.rs:101`).
411 if self.max_concurrent is not None:
412 wire["max_concurrent"] = int(self.max_concurrent)
413 return wire
414
415 @staticmethod
416 def from_wire(raw: Any) -> "Hello":
417 protocol = _require_str(raw, "protocol")
418 service = _require_str(raw, "service")
419 caps = raw.get("capabilities")
420 if not isinstance(caps, list) or not all(isinstance(c, str) for c in caps):
421 raise FrameMalformed("'capabilities' metin listesi olmali")
422 token = _require_str(raw, "token")
423 max_concurrent = raw.get("max_concurrent")
424 if max_concurrent is not None and not isinstance(max_concurrent, int):
425 raise FrameMalformed("'max_concurrent' tamsayi ya da yok olmali")
426 return Hello(protocol, service, tuple(caps), token, max_concurrent)
427
428
429def build_hello(
430 service: str, capabilities: tuple[str, ...] | list[str], token: str, max_concurrent: int
431) -> dict[str, Any]:
432 """Kontrol akisina yazilacak `Hello` cercevesi. Protokol her zaman `hab/2`."""
433 clamped = max(1, min(int(max_concurrent), AI_MAX_CONCURRENT_PER_WORKER))
434 return Hello(AI_PROTOCOL, service, tuple(capabilities), token, clamped).to_wire()
435
436
437@dataclass(frozen=True)
438class Greeting:
439 """Backend'in kontrol akisi cevabi (`protocol.rs:106-119`).
440
441 Etiket alani `type`; degerler `welcome` / `rejected` (`protocol.rs:425-437`).
442 """
443
444 type: str
445 worker_id: str = ""
446 protocol: str = ""
447 code: str = ""
448 message: str = ""
449
450 @staticmethod
451 def from_wire(raw: Any) -> "Greeting":
452 if not isinstance(raw, dict):
453 raise FrameMalformed("greeting bir nesne degil")
454 kind = raw.get("type")
455 if kind == "welcome":
456 return Greeting(
457 "welcome",
458 worker_id=str(raw.get("worker_id", "")),
459 protocol=str(raw.get("protocol", "")),
460 )
461 if kind == "rejected":
462 return Greeting(
463 "rejected",
464 code=str(raw.get("code", RejectCode.MALFORMED)),
465 message=str(raw.get("message", "")),
466 )
467 raise FrameMalformed(f"bilinmeyen greeting type: {kind!r}")
468
469
470def parse_greeting(raw: Any) -> str:
471 """`Greeting`'i coz ve `worker_id` dondur; red ise `HandshakeRejected` firlat."""
472 greeting = Greeting.from_wire(raw)
473 if greeting.type == "rejected":
474 raise HandshakeRejected(greeting.code, greeting.message)
475 if greeting.protocol != AI_PROTOCOL:
476 # Backend hosgeldin dedi ama baska bir surum yankiladi: eslesmeyen bir
477 # surumle devam etmek, yanlis ayrisacak cerceveler yazmak demektir.
478 raise HandshakeRejected(
479 RejectCode.UNSUPPORTED_PROTOCOL,
480 f"backend '{greeting.protocol}' yankiladi, biz '{AI_PROTOCOL}' konusuyoruz",
481 )
482 return greeting.worker_id or "?"
483
484
485@dataclass(frozen=True)
486class Request:
487 """Backend'in sunucu baslatimli akista yazdigi tek is birimi
488 (`protocol.rs:134-148`)."""
489
490 id: str
491 school: str
492 capability: str
493 deadline_ms: int
494 payload: Any = None
495
496 @staticmethod
497 def from_wire(raw: Any) -> "Request":
498 if not isinstance(raw, dict):
499 raise FrameMalformed("istek cercevesi bir nesne degil")
500 request_id = _require_str(raw, "id")
501 school = _require_str(raw, "school")
502 capability = _require_str(raw, "capability")
503 deadline = raw.get("deadline_ms")
504 if isinstance(deadline, bool) or not isinstance(deadline, (int, float)):
505 raise FrameMalformed("'deadline_ms' sayi olmali")
506 if isinstance(deadline, float) and (math.isnan(deadline) or math.isinf(deadline)):
507 raise FrameMalformed("'deadline_ms' sonlu olmali")
508 return Request(request_id, school, capability, int(deadline), raw.get("payload"))
509
510 @property
511 def timeout_secs(self) -> float | None:
512 """Isleyiciye verilecek butce. Backend'in tavanindan pay dusulur."""
513 if self.deadline_ms <= 0:
514 return None
515 budget = self.deadline_ms / 1000.0
516 return max(budget - DEADLINE_MARGIN_SECS, budget * 0.5)
517
518
519def ok_response(request_id: str, school: str, payload: Any) -> dict[str, Any]:
520 """`Response{status:"ok"}` (`protocol.rs:155-161`). `school` YANKILANIR."""
521 return {"status": "ok", "id": request_id, "school": school, "payload": payload}
522
523
524def err_response(request_id: str, school: str, code: str, message: str) -> dict[str, Any]:
525 """`Response{status:"err"}` (`protocol.rs:162-169`). Ele alinmis hata; bir
526 servis istegin ortasinda olurse akisi birakir, bu cerceveyi yazmaz."""
527 return {
528 "status": "err",
529 "id": request_id,
530 "school": school,
531 "code": code,
532 "message": message,
533 }
534
535
536@dataclass(frozen=True)
537class ApiRequest:
538 """Servisin actigi akista okulun kendi API'sine yaptigi okuma
539 (`protocol.rs:174-194`)."""
540
541 id: str
542 school: str
543 path: str
544 query: str | None = None
545 on_behalf_of: str | None = None
546 method: str | None = None
547
548 def to_wire(self) -> dict[str, Any]:
549 wire: dict[str, Any] = {"id": self.id, "school": self.school, "path": self.path}
550 # Opsiyoneller `#[serde(default)]`; yoklari yazilmaz.
551 if self.query:
552 wire["query"] = self.query
553 if self.on_behalf_of:
554 wire["on_behalf_of"] = self.on_behalf_of
555 if self.method:
556 wire["method"] = self.method
557 return wire
558
559 @staticmethod
560 def from_wire(raw: Any) -> "ApiRequest":
561 path = _require_str(raw, "path")
562 return ApiRequest(
563 _require_str(raw, "id"),
564 _require_str(raw, "school"),
565 path,
566 _optional_str(raw, "query"),
567 _optional_str(raw, "on_behalf_of"),
568 _optional_str(raw, "method"),
569 )
570
571
572def build_api_request(
573 request_id: str,
574 school: str,
575 path: str,
576 query: str | None = None,
577 on_behalf_of: str | None = None,
578 method: str | None = None,
579) -> dict[str, Any]:
580 """`ApiRequest` cercevesi kur; kablonun kendi kurallarini burada uygula.
581
582 - `school` zorunludur; yoksa backend `malformed` doner (`server.rs:472`)
583 ama daha da onemlisi, YANLIS okulun verisini okuma ihtimali bu alanla
584 imkansiz kilinir (`protocol.rs:44-47`). Bu yuzden burada da zorunlu.
585 - `path` `/` ile baslamali ve `?` ICERMEMELI: query kendi alaninda gider ve
586 icinde `?` gecen bir yol izin listesinde ESLESMEZ (`ai/api.rs:29-31`).
587 - Yol izin listesinde olmali (`constant.rs:656-676`). Bunu burada
588 denetliyoruz ki izinsiz bir yol tele HIC cikmasin.
589 """
590 if not isinstance(school, str) or not school:
591 raise ApiRefused(ApiErrorCode.MALFORMED, "okul slug'i zorunlu; varsayilan yok")
592 if not isinstance(path, str) or not path.startswith("/") or "?" in path:
593 raise ApiRefused(
594 ApiErrorCode.MALFORMED,
595 f"yol / ile baslamali ve ? icermemeli (query ayri alanda gider): {path!r}",
596 school=school,
597 )
598 if method is not None and method.upper() != "GET":
599 # Kopru salt-okumadir (`server.rs:719-726`).
600 raise ApiRefused(
601 ApiErrorCode.METHOD_NOT_ALLOWED,
602 f"kopru yalnizca GET dagitir, istenen: {method!r}",
603 school=school,
604 )
605 if not path_allowed(path):
606 raise ApiRefused(
607 ApiErrorCode.PATH_NOT_ALLOWED,
608 f"'{path}' AI servislerinin okuyabildigi bir yol degil",
609 school=school,
610 )
611 return ApiRequest(
612 request_id,
613 school,
614 path,
615 query.lstrip("?") if query else None,
616 on_behalf_of or None,
617 method,
618 ).to_wire()
619
620
621@dataclass(frozen=True)
622class ApiResponse:
623 """Backend'in tek cevap cercevesi (`protocol.rs:199-221`).
624
625 Etiket alani `outcome` -- `status` DEGIL; `status` HTTP kodudur
626 (`protocol.rs:449-451`).
627 """
628
629 id: str
630 school: str
631 status: int
632 body: Any
633
634 @property
635 def ok(self) -> bool:
636 return 200 <= self.status < 300
637
638 @staticmethod
639 def from_wire(raw: Any) -> "ApiResponse":
640 if not isinstance(raw, dict):
641 raise ApiRefused(ApiErrorCode.MALFORMED, "api cevabi bir nesne degil")
642 outcome = raw.get("outcome")
643 school = str(raw.get("school", ""))
644 request_id = str(raw.get("id", ""))
645 if outcome == "err":
646 raise ApiRefused(
647 str(raw.get("code", "?")),
648 str(raw.get("message", "")),
649 school=school,
650 request_id=request_id,
651 )
652 if outcome != "ok":
653 raise ApiRefused(
654 ApiErrorCode.MALFORMED, f"bilinmeyen outcome: {outcome!r}", school=school
655 )
656 return ApiResponse(request_id, school, _coerce_status(raw.get("status", 0)), raw.get("body"))
657
658
659def parse_api_response(raw: Any) -> ApiResponse:
660 return ApiResponse.from_wire(raw)
661
662
663# ===========================================================================
664# Yetenek cagrisi -- servis backend'in bir operasyonunu BOYLE cagirir
665# ===========================================================================
666#
667# ZEKA'nin veritabani erisimi YOKTUR; hesapladigi satirlar backend'e bu
668# cerceveyle yazilir. `ApiRequest`'ten ayrimi `capability` alanidir ve YONU
669# terstir: `ApiRequest` okulun KENDI API'sini okur, bu cerceve backend'in
670# bir operasyonunu kosturur (yazma dahil).
671#
672# KIMLIK: `id` ULID'dir ve cevapta AYNEN doner; eslesme akis kimligiyle
673# kurulur, `id` yalniz loglarin yan yana okunmasi icindir (`protocol.rs:136`).
674
675
676@dataclass(frozen=True)
677class CapabilityRequest:
678 """Servisin actigi akista yazdigi tek yetenek cagrisi."""
679
680 id: str
681 capability: str
682 school: str
683 payload: dict[str, Any]
684
685 def to_wire(self) -> dict[str, Any]:
686 return {
687 "id": self.id,
688 "capability": self.capability,
689 "school": self.school,
690 "payload": self.payload,
691 }
692
693
694def build_capability_request(
695 request_id: str,
696 capability: str,
697 school: str,
698 payload: dict[str, Any] | None = None,
699) -> dict[str, Any]:
700 """`CapabilityRequest` cercevesi kur; kablonun kendi kurallarini uygula.
701
702 - `capability` zorunludur ve bos olamaz: adsiz bir cagri backend'de
703 `malformed` olur, burada ise tele hic cikmaz.
704 - `payload` bir NESNE olmali (dizi ya da null degil): her operasyonun
705 sozlesmesi bir sozluktur.
706 - `school` zorunludur ama BOS olabilir: deployment olcekli tek operasyon
707 (`insight.schools.list`) okul adlandirmaz ve backend onu cozmez.
708 """
709 if not isinstance(capability, str) or not capability.strip():
710 raise ApiRefused(ApiErrorCode.MALFORMED, "yetenek adi zorunlu")
711 if payload is None:
712 payload = {}
713 if not isinstance(payload, dict):
714 raise ApiRefused(
715 ApiErrorCode.MALFORMED,
716 f"payload bir nesne olmali, alinan: {type(payload).__name__}",
717 )
718 if not isinstance(school, str):
719 raise ApiRefused(ApiErrorCode.MALFORMED, "okul alani metin olmali")
720 return CapabilityRequest(request_id, capability.strip(), school, payload).to_wire()
721
722
723@dataclass(frozen=True)
724class CapabilityResponse:
725 """Backend'in yetenek cagrisina verdigi TEK cevap cercevesi.
726
727 Etiket alani `status` -- `ApiResponse`'un `outcome`'undan farkli, cunku
728 backend'in sunucu->istemci `Response` cercevesi de `status` kullanir;
729 ayni adi tasimak iki yonu yan yana okunur kilar.
730 """
731
732 status: str
733 id: str
734 school: str
735 payload: dict[str, Any] = field(default_factory=dict)
736 code: str = ""
737 message: str = ""
738
739 @property
740 def ok(self) -> bool:
741 return self.status == "ok"
742
743 @staticmethod
744 def from_wire(raw: Any) -> "CapabilityResponse":
745 if not isinstance(raw, dict):
746 raise FrameMalformed(f"yetenek cevabi nesne degil: {type(raw).__name__}")
747 status = _require_str(raw, "status")
748 if status not in ("ok", "err"):
749 raise FrameMalformed(f"bilinmeyen yetenek cevabi durumu: {status!r}")
750 payload = raw.get("payload")
751 if payload is None:
752 payload = {}
753 if not isinstance(payload, dict):
754 raise FrameMalformed("yetenek cevabinin payload'i nesne degil")
755 code = raw.get("code")
756 message = raw.get("message")
757 return CapabilityResponse(
758 status=status,
759 id=str(raw.get("id") or ""),
760 school=raw.get("school") if isinstance(raw.get("school"), str) else "",
761 payload=payload,
762 code=code if isinstance(code, str) else "",
763 message=message if isinstance(message, str) else "",
764 )
765
766 def raise_for_status(self, capability: str) -> dict[str, Any]:
767 """`ok` ise payload'i dondur; `err` ise `CapabilityRefused` firlat.
768
769 `status` ONCE okunur: reddi basari sayan bir yol, sessiz yazma
770 kaybinin ta kendisidir.
771 """
772 if self.ok:
773 return self.payload
774 raise CapabilityRefused(
775 self.code or "internal",
776 self.message or "backend yetenek cagrisini reddetti",
777 self.school,
778 self.id,
779 )
780
781
782def parse_capability_response(raw: Any) -> CapabilityResponse:
783 return CapabilityResponse.from_wire(raw)
784
785
786def _coerce_status(value: Any) -> int:
787 if isinstance(value, bool):
788 return int(value)
789 if isinstance(value, int):
790 return value
791 if isinstance(value, float):
792 if math.isnan(value) or math.isinf(value):
793 raise ApiRefused(ApiErrorCode.MALFORMED, f"status sayisal degil: {value!r}")
794 return int(value)
795 if isinstance(value, str):
796 try:
797 return int(value)
798 except ValueError as exc:
799 raise ApiRefused(
800 ApiErrorCode.MALFORMED, f"status sayisal degil: {value!r}"
801 ) from exc
802 raise ApiRefused(ApiErrorCode.MALFORMED, f"status sayisal degil: {value!r}")
803
804
805@dataclass(frozen=True)
806class BlobRequest:
807 """Bir ders notu dosyasinin BAYTLARINI okuma istegi (`protocol.rs:226-240`).
808
809 `ApiRequest`'ten zorunlu `file` alaniyla ayrilir. `on_behalf_of` pratikte
810 zorunludur: `ai` rolu hicbir dersi goremez, dolayisiyla onsuz her zaman
811 `forbidden` alinir (`protocol.rs:236-239`).
812 """
813
814 id: str
815 school: str
816 file: str
817 on_behalf_of: str | None = None
818
819 def to_wire(self) -> dict[str, Any]:
820 wire: dict[str, Any] = {"id": self.id, "school": self.school, "file": self.file}
821 if self.on_behalf_of:
822 wire["on_behalf_of"] = self.on_behalf_of
823 return wire
824
825 @staticmethod
826 def from_wire(raw: Any) -> "BlobRequest":
827 return BlobRequest(
828 _require_str(raw, "id"),
829 _require_str(raw, "school"),
830 _require_str(raw, "file"),
831 _optional_str(raw, "on_behalf_of"),
832 )
833
834
835def build_blob_request(
836 request_id: str, school: str, file_id: str, on_behalf_of: str | None = None
837) -> dict[str, Any]:
838 if not isinstance(school, str) or not school:
839 raise BlobRefused(ApiErrorCode.MALFORMED, "okul slug'i zorunlu; varsayilan yok")
840 if not isinstance(file_id, str) or not file_id:
841 raise BlobRefused(
842 ApiErrorCode.MALFORMED, "'file' bos olmayan bir metin olmali", school=school
843 )
844 return BlobRequest(request_id, school, file_id, on_behalf_of or None).to_wire()
845
846
847@dataclass(frozen=True)
848class BlobResponse:
849 """Blob akisini acan (ya da reddeden) BASLIK cercevesi (`protocol.rs:245-265`).
850
851 Etiket alani `status` -- `outcome` DEGIL; bir blob basliginda carpisacagi
852 bir HTTP kodu yoktur (`protocol.rs:509-511`).
853 `ok` ise bu cerceveden sonra tam `size` HAM bayt gelir, sonra FIN.
854 """
855
856 id: str
857 school: str
858 name: str
859 content_type: str
860 size: int
861
862 @staticmethod
863 def from_wire(raw: Any) -> "BlobResponse":
864 if not isinstance(raw, dict):
865 raise BlobRefused(ApiErrorCode.MALFORMED, "blob basligi bir nesne degil")
866 status = raw.get("status")
867 school = str(raw.get("school", ""))
868 request_id = str(raw.get("id", ""))
869 if status == "err":
870 raise BlobRefused(
871 str(raw.get("code", "?")),
872 str(raw.get("message", "")),
873 school=school,
874 request_id=request_id,
875 )
876 if status != "ok":
877 raise BlobRefused(
878 ApiErrorCode.MALFORMED, f"bilinmeyen blob status: {status!r}", school=school
879 )
880 size = raw.get("size")
881 if isinstance(size, bool) or not isinstance(size, int) or size < 0:
882 raise BlobRefused(
883 ApiErrorCode.MALFORMED, f"'size' negatif olmayan tamsayi olmali: {size!r}",
884 school=school,
885 )
886 return BlobResponse(
887 request_id,
888 school,
889 str(raw.get("name", "")),
890 str(raw.get("content_type", "application/octet-stream")),
891 size,
892 )
893
894
895def parse_blob_response(raw: Any) -> BlobResponse:
896 return BlobResponse.from_wire(raw)
897
898
899@dataclass
900class Blob:
901 """Bir blob okumasinin sonucu: baslik + ham baytlar."""
902
903 header: BlobResponse
904 data: bytes = field(repr=False, default=b"")
905
906
907# --- izin listesi eslesmesi ------------------------------------------------
908# `ai/api.rs:39-60` mantiginin birebir kopyasi: segment segment, on-ek YOK,
909# kuyruk joker'i YOK, `{x}` tam olarak bir BOS OLMAYAN segment.
910
911
912def route_template(path: str) -> str | None:
913 """Bu yolun eslestigi izin listesi SABLONU; somut yol degil.
914
915 Somut yol kayit kimligi tasir; log ve olcum etiketi olarak sablon kullanilir
916 (`ai/api.rs:24-28`).
917 """
918 if not isinstance(path, str) or not path.startswith("/") or "?" in path:
919 return None
920 for pattern in AI_API_ALLOWLIST:
921 if _pattern_matches(pattern, path):
922 return pattern
923 return None
924
925
926def path_allowed(path: str) -> bool:
927 """Bir AI servisi bu yolu GET edebilir mi?"""
928 return route_template(path) is not None
929
930
931def _pattern_matches(pattern: str, path: str) -> bool:
932 expected = pattern[1:].split("/")
933 actual = path[1:].split("/")
934 # Farkli segment sayisi = farkli rota. Sondaki `/` ayri bir yoldur.
935 if len(expected) != len(actual):
936 return False
937 for segment, given in zip(expected, actual):
938 if segment.startswith("{") and segment.endswith("}"):
939 if not given:
940 return False
941 elif segment != given:
942 return False
943 return True