forge
Explore
Log in

Don't you dare go Hollow

hezarfen_rag

Clone
★ 0

0 watching0 forksPython2.4 MiB184b84dAhmet Kaan Gümüş2 months ago189 commits

contract.py775 lines, 29.6 KiBHistoryRawDownload
1"""Backend'in tel biçimi (hab/2 köprüsü + REST DTO'ları) — Python karşılığı.
2
3KAYNAK (bu depoda DEĞİŞTİRİLMEZ, yalnız okunur):
4 hezarfen_backend/src/ai/protocol.rs — hab/2 çerçeveleri
5 hezarfen_backend/src/ai/chat.rs — `chat.reply` yeteneği
6 hezarfen_backend/src/ai/rag.rs — `rag.index` yeteneği
7 hezarfen_backend/src/web/*.rs — REST uçları ve DTO'ları
8
9Backend'in kendi testi (`rag_payload_keys_are_the_documented_wire_names`) şunu
10söylüyor: *"Services in other languages match on these literals — a rename here
11silently breaks every one of them, so pin the encoding."* Biz o "başka dildeki
12servis"iz; bu yüzden burada da aynı sabitleme testle yapılır
13(`tests/unit/test_backend_sozlesme.py`).
14
15MİMARİ NOT — KÖPRÜ YÖNÜ TERS:
16Backend QUIC **sunucusudur**, AI servisleri ona **dial eder**. Yani bizim
17FastAPI servisimizi backend ÇAĞIRMAZ; biz bağlanır, `Hello` ile yeteneklerimizi
18duyurur ve backend'in açtığı akışlarda `Request` çerçevesi bekleriz. Mevcut
19`src/service/http_app.py` bu köprünün yerine geçmez — onun yanında durur
20(yerel geliştirme + backend dışı entegrasyonlar için).
21"""
22from __future__ import annotations
23
24import asyncio
25import json
26import struct
27from dataclasses import dataclass, field, asdict
28
29# --- yetenek adları (constant.rs) ---
30AI_CHAT_CAPABILITY = "chat.reply"
31AI_RAG_INDEX_CAPABILITY = "rag.index"
32AI_RAG_CHAT_CAPABILITY = "rag.chat" # RAG'e özel kutu (chatbot'tan AYRI)
33AI_RAG_SUMMARIZE_CAPABILITY = "rag.summarize" # kapsamı özetle (tek atımlık)
34AI_RAG_QUESTIONS_CAPABILITY = "rag.questions" # kapsamdan N soru üret (tek atımlık)
35AI_PROTOCOL = "hab/2"
36
37# --- taşıma sabitleri (el sıkışma + çerçeveleme) ---------------------------
38# Kaynak: `hezarfen_backend/src/constant.rs`. Değerler ZEKA'nın kanıtlanmış
39# istemcisiyle (`hezarfen_zeka/service/src/protocol.py`) BİREBİR aynıdır: aynı
40# backend, aynı tel. Burada olmalarının sebebi: tel biçiminin TEK evi burası
41# (`protocol.rs` + `constant.rs` karşılığı), taşıma ise yalnız bunları kullanır.
42AI_ALPN = "hab/2"
43"""`constant.rs:531` — TLS ALPN. Sürüm kapısı BURADA da reddeder: `hab/1`
44konuşan bir servis el sıkışmada elenir, kaydolamaz."""
45
46AI_MAX_FRAME_BYTES = 8 * 1024 * 1024
47"""`constant.rs:536` — tek çerçevenin tavanı. Uzunluk ÖNEKİ, gövde ayrılmadan
48ÖNCE denetlenir; kötü bir uzunluk bellek tüketemez (`protocol.rs:286-289`)."""
49
50AI_MAX_CONCURRENT_PER_WORKER = 64
51"""`constant.rs:547` — backend `Hello.max_concurrent`i 1..=64 arasına kırpar."""
52
53AI_IDLE_TIMEOUT_SECS = 30
54"""`constant.rs:554` — QUIC boşta kalma zaman aşımı."""
55
56AI_KEEPALIVE_SECS = 10
57"""`constant.rs:555` — PING aralığı: boşta kalma penceresinin çok altında ki
58sağlıklı ama sessiz bir servis düşürülmesin. Uygulama düzeyinde heartbeat
59ÇERÇEVESİ yoktur (`protocol.rs:13-14`)."""
60
61CERTIFICATE_PATH = "/ai/certificate"
62"""`src/web/ai.rs` — `certificate_pem` + `fingerprint_sha256` döner."""
63
64GREETING_TIMEOUT_SECS = 8.0
65"""Bizim değerimiz: backend'in el sıkışma penceresinin (10 s) ALTINDA tutulur ki
66reddi biz görelim, akış altımızdan kesilmesin."""
67
68PERMANENT_REJECTS = ("unauthorized", "unsupported_protocol")
69"""Yapılandırma/dağıtım değişmeden düzelmeyen retler (`server.rs:1030-1046`).
70Bekleme yine sürer — çıkmak yok — ama tavana çekilir: kalıcı bir redde gürültü
71yapmadan bekleriz ve sorun düzeldiğinde kendiliğinden bağlanırız."""
72
73# Backend'in kabul ettiği okul rolleri (domain/role.rs — `ai` ATANAMAZ).
74ASSIGNABLE_ROLES = ("parent", "student", "teacher", "manager", "admin")
75
76
77# --------------------------------------------------------------- chat.reply
78
79@dataclass
80class ChatTurn:
81 """Bir önceki mesaj. `role` KİMİN SÖYLEDİĞİ ("user"/"assistant")."""
82 role: str
83 content: str
84
85 def to_wire(self) -> dict:
86 return {"role": self.role, "content": self.content}
87
88
89@dataclass
90class ChatRequestPayload:
91 """Backend'in `chat.reply` için gönderdiği gövde.
92
93 DİKKAT — burada ÖĞRENCİ KİMLİĞİ YOK. Backend yalnız `asker_role` gönderiyor
94 ("the backend only forwards the role"). Yani servis hangi öğrencinin
95 sorduğunu BİLEMEZ; o öğrencinin notlarını çekemez, sınıf/ders kasası
96 izolasyonunu uygulayamaz. Kişiselleştirme bu sözleşmeyle MÜMKÜN DEĞİL.
97 Ayrıntı ve öneri: `docs/BACKEND-ENTEGRASYON.md`.
98 """
99 message: str
100 asker_role: str
101 history: list[ChatTurn] = field(default_factory=list)
102
103 @classmethod
104 def from_wire(cls, d: dict) -> "ChatRequestPayload":
105 return cls(message=d["message"], asker_role=d["asker_role"],
106 history=[ChatTurn(t["role"], t["content"])
107 for t in d.get("history", [])])
108
109 def to_wire(self) -> dict:
110 return {"message": self.message, "asker_role": self.asker_role,
111 "history": [t.to_wire() for t in self.history]}
112
113
114@dataclass
115class ChatReplyPayload:
116 """Servisin döndürdüğü gövde — **yalnız metin**.
117
118 DİKKAT: `citations`/`abstained`/`reason` için köprüde yer YOK. Bizim ürün
119 sözümüz ("her cümle kaynağa dayanır, atıfa tıklayınca sayfayı bulursun")
120 bu sözleşmeyle kullanıcıya ULAŞAMAZ. Geçici çözüm, atıfları metnin içine
121 okunabilir biçimde gömmektir; kalıcı çözüm sözleşme değişikliğidir.
122 """
123 text: str
124
125 def to_wire(self) -> dict:
126 return {"text": self.text}
127
128
129# ---------------------------------------------------------------- rag.index
130
131@dataclass
132class RagFile:
133 """Notun bir eki — **yalnız meta**. Baytlar `BlobRequest` ile ayrı gelir."""
134 id: str
135 name: str
136 content_type: str
137 size: int
138
139 def to_wire(self) -> dict:
140 return asdict(self)
141
142
143@dataclass
144class RagIndexPayload:
145 """Backend'in indekslenmesini istediği ders notu.
146
147 `author`: dosya baytları bu kullanıcı ADINA okunur (`on_behalf_of`) —
148 notun öğretmeni kendi dersini her zaman görebilir, `ai` görevlisi ise
149 HİÇBİR ZAMAN göremez.
150 """
151 course_note: str
152 course: str
153 author: str
154 title: str
155 content: str
156 files: list[RagFile] = field(default_factory=list)
157
158 @classmethod
159 def from_wire(cls, d: dict) -> "RagIndexPayload":
160 return cls(course_note=d["course_note"], course=d["course"],
161 author=d["author"], title=d["title"], content=d["content"],
162 files=[RagFile(**f) for f in d.get("files", [])])
163
164 def to_wire(self) -> dict:
165 return {"course_note": self.course_note, "course": self.course,
166 "author": self.author, "title": self.title,
167 "content": self.content,
168 "files": [f.to_wire() for f in self.files]}
169
170
171@dataclass
172class RagIndexReplyFile:
173 """İndekslenen TEK ekin backend'e geri bildirimi — `id` → `doc_id` eşleşmesi.
174
175 `id`: isteğin `RagFile.id`'si — **AYNI değer**. `doc_id`: o ekin indekste
176 kazandığı korpus kimliği (`<dosya sha256 ilk 12>`; bkz. ingest/canonical.py).
177 Backend bu eşleşmeyle `course_note_file.rag_doc_id`'yi doldurur; sonra bir
178 eki yeniden indekslerken/silerken hangi korpusu hedefleyeceğini bilir.
179 """
180 id: str
181 doc_id: str
182
183 @classmethod
184 def from_wire(cls, d: dict) -> "RagIndexReplyFile":
185 return cls(id=d["id"], doc_id=d["doc_id"])
186
187 def to_wire(self) -> dict:
188 return {"id": self.id, "doc_id": self.doc_id}
189
190
191@dataclass
192class RagIndexReply:
193 """Servisin `rag.index`'e döndürdüğü gövde — her ek için `id`→`doc_id`.
194
195 Backend bunu OKUR (isteği bir yanıt bekler): hangi gönderdiği `course_note_file`
196 id'sinin hangi korpus `doc_id`'sine karşılık geldiğini yalnız bu yanıttan öğrenir.
197 """
198 files: list[RagIndexReplyFile] = field(default_factory=list)
199
200 @classmethod
201 def from_wire(cls, d: dict) -> "RagIndexReply":
202 return cls(files=[RagIndexReplyFile.from_wire(f)
203 for f in d.get("files", [])])
204
205 def to_wire(self) -> dict:
206 return {"files": [f.to_wire() for f in self.files]}
207
208
209# ---------------------------------------------------------------- rag.chat
210# Backend'in RAG'e ÖZEL yeteneği (chatbot'un `chat.reply`'inden AYRI; otorite:
211# hezarfen_backend README `## AI bridge (QUIC)` → `### The rag.chat capability`).
212# `asker_role` AYRI bir alandır: servis rolü buradan okur (bkz. API-CONTRACT
213# §0.2(a) — eskiden `asker_role` → `role` eşlemesi YOKTU; artık `bridge/
214# dispatch.py` yapar).
215
216@dataclass
217class RagChatRequestPayload:
218 message: str
219 asker: str
220 asker_role: str
221 scope: list["RagScopePair"] = field(default_factory=list)
222 history: list[ChatTurn] = field(default_factory=list)
223
224 @classmethod
225 def from_wire(cls, d: dict) -> "RagChatRequestPayload":
226 return cls(message=d["message"], asker=str(d.get("asker") or ""),
227 asker_role=str(d.get("asker_role") or ""),
228 scope=[RagScopePair.from_wire(p) for p in d.get("scope", [])],
229 history=[ChatTurn(**t) for t in d.get("history", [])])
230
231 def to_wire(self) -> dict:
232 return {"message": self.message, "asker": self.asker,
233 "asker_role": self.asker_role,
234 "scope": [p.to_wire() for p in self.scope],
235 "history": [t.to_wire() for t in self.history]}
236
237
238@dataclass
239class RagCitation:
240 """`rag.chat` yanıtındaki tıklanabilir kaynak (backend `RagCitation`)."""
241 n: int
242 doc_id: str
243 pages: list = field(default_factory=list)
244 span_ids: list = field(default_factory=list)
245 ders: str | None = None
246
247 @classmethod
248 def from_wire(cls, d: dict) -> "RagCitation":
249 return cls(n=int(d.get("n") or 0), doc_id=str(d.get("doc_id") or ""),
250 pages=list(d.get("pages") or []),
251 span_ids=list(d.get("span_ids") or []),
252 ders=d.get("ders"))
253
254 def to_wire(self) -> dict:
255 return {"n": self.n, "doc_id": self.doc_id, "pages": list(self.pages),
256 "span_ids": list(self.span_ids), "ders": self.ders}
257
258
259@dataclass
260class RagChatReplyPayload:
261 text: str
262 abstained: bool = False
263 reason: str = ""
264 citations: list[RagCitation] = field(default_factory=list)
265
266 @classmethod
267 def from_wire(cls, d: dict) -> "RagChatReplyPayload":
268 return cls(text=str(d.get("text") or ""),
269 abstained=bool(d.get("abstained", False)),
270 reason=str(d.get("reason") or ""),
271 citations=[RagCitation.from_wire(c)
272 for c in d.get("citations", [])])
273
274 def to_wire(self) -> dict:
275 return {"text": self.text, "abstained": self.abstained,
276 "reason": self.reason,
277 "citations": [c.to_wire() for c in self.citations]}
278
279
280# ------------------------------------- rag.summarize + rag.questions (tek atım)
281# `rag.chat`'ten AYRI: iplik YOK, saklama YOK, SSE YOK. İstemci TEK bir
282# (ders, isteğe bağlı sınıf) + sayfa/span aralığı adlandırır ve YAPITı bekler
283# (bir özet / bir dizi alıştırma sorusu). Kapsam `rag.chat`teki çift listesi
284# DEĞİL, tek bir kapsam nesnesidir ve korpusu tam olarak o nesne seçer.
285
286@dataclass
287class RagScope:
288 """Özet/soru kapsamı — TEK korpusa adreslenir.
289
290 `sinif=None` = sınıfa bağlı OLMAYAN korpus (okul kulübü / etüt).
291 `pages`/`span_ids` boş olabilir; servis o zaman `empty_scope` ile
292 fail-closed reddeder. Normalde ikisinden yalnız BİRİ kullanılır.
293 """
294 ders: str
295 sinif: str | None = None
296 pages: list = field(default_factory=list)
297 span_ids: list = field(default_factory=list)
298 scope_label: str = ""
299
300 @classmethod
301 def from_wire(cls, d: dict) -> "RagScope":
302 s = d.get("sinif")
303 return cls(ders=str(d.get("ders") or ""),
304 sinif=(str(s) if s not in (None, "") else None),
305 pages=list(d.get("pages") or []),
306 span_ids=list(d.get("span_ids") or []),
307 scope_label=str(d.get("scope_label") or ""))
308
309 def to_wire(self) -> dict:
310 return {"sinif": self.sinif, "ders": self.ders,
311 "pages": list(self.pages), "span_ids": list(self.span_ids),
312 "scope_label": self.scope_label}
313
314
315@dataclass
316class RagSummarizeRequestPayload:
317 """Backend'in `rag.summarize` için gönderdiği gövde."""
318 scope: RagScope
319 asker: str = ""
320 asker_role: str = ""
321 # Backend'in çağıran için hesapladığı (sınıf, ders) grant'leri. Eski
322 # backend'ler bu alanı göndermez; boş liste legacy role alanlarına düşer.
323 scope_pairs: list = field(default_factory=list)
324
325 @classmethod
326 def from_wire(cls, d: dict) -> "RagSummarizeRequestPayload":
327 return cls(scope=RagScope.from_wire(d.get("scope") or {}),
328 asker=str(d.get("asker") or ""),
329 asker_role=str(d.get("asker_role") or ""),
330 scope_pairs=list(d.get("scope_pairs") or []))
331
332 def to_wire(self) -> dict:
333 return {"scope": self.scope.to_wire(), "asker": self.asker,
334 "asker_role": self.asker_role,
335 "scope_pairs": list(self.scope_pairs)}
336
337
338@dataclass
339class RagQuestionsRequestPayload:
340 """Backend'in `rag.questions` için gönderdiği gövde — `rag.summarize` + üç alan."""
341 scope: RagScope
342 asker: str = ""
343 asker_role: str = ""
344 n: int = 5
345 difficulty: str = "orta"
346 seed_question: str | None = None
347 # Eski çağıranların konumsal `n`/`difficulty`/`seed_question` kullanımı
348 # bozulmasın; yeni alan sonradan eklenmiştir.
349 scope_pairs: list = field(default_factory=list)
350
351 @classmethod
352 def from_wire(cls, d: dict) -> "RagQuestionsRequestPayload":
353 return cls(scope=RagScope.from_wire(d.get("scope") or {}),
354 asker=str(d.get("asker") or ""),
355 asker_role=str(d.get("asker_role") or ""),
356 scope_pairs=list(d.get("scope_pairs") or []),
357 n=int(d.get("n") or 5),
358 difficulty=str(d.get("difficulty") or "orta"),
359 seed_question=d.get("seed_question"))
360
361 def to_wire(self) -> dict:
362 return {"scope": self.scope.to_wire(), "asker": self.asker,
363 "asker_role": self.asker_role,
364 "scope_pairs": list(self.scope_pairs), "n": self.n,
365 "difficulty": self.difficulty, "seed_question": self.seed_question}
366
367
368@dataclass
369class RagSummaryCitation:
370 """`rag.summarize` yanıtındaki kanıt (backend `RagSummaryCitation`)."""
371 n: int
372 span_ids: list = field(default_factory=list)
373 pages: list = field(default_factory=list)
374
375 @classmethod
376 def from_wire(cls, d: dict) -> "RagSummaryCitation":
377 return cls(n=int(d.get("n") or 0),
378 span_ids=list(d.get("span_ids") or []),
379 pages=list(d.get("pages") or []))
380
381 def to_wire(self) -> dict:
382 return {"n": self.n, "span_ids": list(self.span_ids),
383 "pages": list(self.pages)}
384
385
386@dataclass
387class RagSummarizeReplyPayload:
388 """Servisin `rag.summarize`'e döndürdüğü gövde.
389
390 `from_wire` EKSİK opsiyonel anahtarlara TOLERANSLIDIR: servisin red
391 sözlükleri (`_refused`/`_budget_denied`/`_llm_unavailable`) bazı alanları
392 hiç taşımaz; katı bir ayrıştırma bu karelerde patlardı.
393 """
394 text: str = ""
395 abstained: bool = False
396 reason: str = ""
397 citations: list[RagSummaryCitation] = field(default_factory=list)
398 scope_pages: list = field(default_factory=list)
399 hierarchical: bool = False
400
401 @classmethod
402 def from_wire(cls, d: dict) -> "RagSummarizeReplyPayload":
403 return cls(text=str(d.get("text") or ""),
404 abstained=bool(d.get("abstained", False)),
405 reason=str(d.get("reason") or ""),
406 citations=[RagSummaryCitation.from_wire(c)
407 for c in (d.get("citations") or [])],
408 scope_pages=list(d.get("scope_pages") or []),
409 hierarchical=bool(d.get("hierarchical", False)))
410
411 def to_wire(self) -> dict:
412 return {"text": self.text, "abstained": self.abstained,
413 "reason": self.reason,
414 "citations": [c.to_wire() for c in self.citations],
415 "scope_pages": list(self.scope_pages),
416 "hierarchical": self.hierarchical}
417
418
419@dataclass
420class RagQuestion:
421 """`rag.questions` yanıtındaki tek soru.
422
423 Anahtarlar SERVİSİN kendi sözlüğüdür (`soru`/`cevap`/`zorluk`) — tıpkı
424 `rag.chat`in kendi sözlüğünü yansıtması gibi. Yeniden adlandırılmaz;
425 backend DTO'su (question/answer/difficulty) eşlemeyi kendi tarafında yapar.
426 """
427 soru: str
428 cevap: str
429 zorluk: str
430
431 @classmethod
432 def from_wire(cls, d: dict) -> "RagQuestion":
433 return cls(soru=str(d.get("soru") or ""),
434 cevap=str(d.get("cevap") or ""),
435 zorluk=str(d.get("zorluk") or ""))
436
437 def to_wire(self) -> dict:
438 return {"soru": self.soru, "cevap": self.cevap, "zorluk": self.zorluk}
439
440
441@dataclass
442class RagQuestionsReplyPayload:
443 """Servisin `rag.questions`'a döndürdüğü gövde.
444
445 Red sözlüğü yalnız `items`/`span_ids`/`pages` taşır (abstained/reason
446 atlanabilir) — `from_wire` bunu tolere eder.
447 """
448 items: list[RagQuestion] = field(default_factory=list)
449 abstained: bool = False
450 reason: str = ""
451 span_ids: list = field(default_factory=list)
452 pages: list = field(default_factory=list)
453
454 @classmethod
455 def from_wire(cls, d: dict) -> "RagQuestionsReplyPayload":
456 return cls(items=[RagQuestion.from_wire(i)
457 for i in (d.get("items") or [])],
458 abstained=bool(d.get("abstained", False)),
459 reason=str(d.get("reason") or ""),
460 span_ids=list(d.get("span_ids") or []),
461 pages=list(d.get("pages") or []))
462
463 def to_wire(self) -> dict:
464 return {"items": [i.to_wire() for i in self.items],
465 "abstained": self.abstained, "reason": self.reason,
466 "span_ids": list(self.span_ids), "pages": list(self.pages)}
467
468
469# ----------------------------------------------------- scope (sınıf/ders ÇİFTİ)
470
471@dataclass
472class RagScopePair:
473 """`rag.chat` kapsamı: bir (sınıf, ders) ÇİFTİ.
474
475 NEDEN ÇİFT (çapraz-çarpım güvenliği): eski biçim `role.sinif` + `role.ders_list`
476 idi ve bu iki alan bir KARTEZYEN ÇARPIMI ifade eder — `sinif="10"` +
477 `ders_list=["biyoloji","satranc"]` "10-biyoloji **VE** 10-satranç" demektir.
478 Oysa gerçek kapsam "10-biyoloji **VEYA** okul-satranç" olabilir; düzleştirme
479 (flatten) yanlış bir (sınıf,ders) grant'i AÇAR. Çift listesi her grant'i tek
480 tek taşır, böylece hiçbir çift yanlışlıkla açılmaz.
481
482 `sinif=None` = sınıfa bağlı OLMAYAN korpus (okul kulübü / etüt).
483 """
484 sinif: str | None
485 ders: str
486
487 @classmethod
488 def from_wire(cls, d: dict) -> "RagScopePair":
489 s = d.get("sinif")
490 return cls(sinif=(str(s) if s not in (None, "") else None), ders=d["ders"])
491
492 def to_wire(self) -> dict:
493 return {"sinif": self.sinif, "ders": self.ders}
494
495
496# ------------------------------------------------- servis -> backend okuma
497
498@dataclass
499class ApiRequest:
500 """Servisin backend'den veri OKUMA çerçevesi.
501
502 "That mirrors the REST API — the backend dispatches the path internally —
503 so a service asks for school data instead of being handed it."
504
505 `on_behalf_of` verilirse istek O KULLANICI olarak koşar (kendi yetkisiyle);
506 verilmezse servisin kendi (`ai`) kimliğiyle koşar ve `ai` çoğu şeyi göremez.
507 Öğrenci verisini çekmenin TEK yolu budur.
508 """
509 id: str
510 school: str
511 path: str
512 query: str | None = None
513 on_behalf_of: str | None = None
514 method: str | None = None # None -> GET
515
516 def to_wire(self) -> dict:
517 d = {"id": self.id, "school": self.school, "path": self.path}
518 for ad, deger in (("query", self.query), ("on_behalf_of", self.on_behalf_of),
519 ("method", self.method)):
520 if deger is not None:
521 d[ad] = deger
522 return d
523
524
525@dataclass
526class BlobRequest:
527 """Ek dosyanın baytlarını okuma çerçevesi (JSON'a sığmaz, ham akar)."""
528 id: str
529 school: str
530 file: str
531 on_behalf_of: str | None = None
532
533 def to_wire(self) -> dict:
534 d = {"id": self.id, "school": self.school, "file": self.file}
535 if self.on_behalf_of is not None:
536 d["on_behalf_of"] = self.on_behalf_of
537 return d
538
539
540class BlobReadRefused(Exception):
541 """A blob read that did not deliver bytes.
542
543 The backend's own refusal vocabulary (`protocol.rs::BlobResponse::Err`:
544 `not_found` for a file it does not have, `forbidden` for one the named
545 reader may not open, `module_disabled`, `unavailable`) plus the codes this
546 side raises before/after the wire (`too_large`, `blob_unavailable`,
547 `bad_header`, `unsupported_type`, `parse_failed`). Typed, never a bare
548 `Exception`: one refused attachment must not abort a whole index.
549 """
550
551 def __init__(self, code: str, message: str) -> None:
552 super().__init__(f"{code}: {message}")
553 self.code = code
554 self.message = message
555
556
557class ApiError(Exception):
558 """Köprü düzeyinde red (yol izinli değil, kullanıcı bilinmiyor).
559
560 Koşup 404 dönen bir API çağrısı hata DEĞİLDİR — o `outcome:"ok"` içinde
561 kendi durum koduyla gelir (backend'in kendi ifadesi).
562 """
563
564
565# ------------------------------------------- backend -> servis (hab/2 Request)
566
567class BridgeFrameError(Exception):
568 """Çerçeve okunamıyor (protocol.rs `FrameError::Malformed`)."""
569
570 def __init__(self, message: str, code: str = "malformed"):
571 super().__init__(f"{code}: {message}")
572 self.code = code
573 self.message = message
574
575
576@dataclass
577class BridgeRequest:
578 """Backend'in AÇTIĞI akışta okunan tek çalışma birimi (`protocol.rs::Request`).
579
580 Okul İKİ YÖNDE de taşınır: burada ZORUNLUDUR ve cevap onu AYNEN yazar.
581 Backend'in kendi kuralı: *"Every request frame names its school by its hyphenated uuid,
582 and every answer echoes it … A frame without a `school` is `malformed` …
583 there is no default and no fallback."* Bu yüzden `from_wire` okulsuz
584 çerçeveyi reddeder — varsayılan bir okul YOKTUR (bkz. guard/tenant.py).
585 """
586 id: str
587 school: str
588 capability: str
589 deadline_ms: int = 0
590 payload: dict = field(default_factory=dict)
591
592 @classmethod
593 def from_wire(cls, d: dict) -> "BridgeRequest":
594 if not isinstance(d, dict):
595 raise BridgeFrameError("çerçeve bir JSON nesnesi değil")
596 okul = d.get("school")
597 if okul is None or not str(okul).strip():
598 raise BridgeFrameError("`school` ZORUNLU (varsayılan/fallback yok)")
599 for ad in ("id", "capability"):
600 if not str(d.get(ad) or "").strip():
601 raise BridgeFrameError(f"`{ad}` zorunlu")
602 govde = d.get("payload")
603 return cls(id=str(d["id"]), school=str(okul),
604 capability=str(d["capability"]),
605 deadline_ms=int(d.get("deadline_ms") or 0),
606 payload=govde if isinstance(govde, dict) else {})
607
608 def to_wire(self) -> dict:
609 return {"id": self.id, "school": self.school,
610 "capability": self.capability, "deadline_ms": self.deadline_ms,
611 "payload": self.payload}
612
613
614@dataclass
615class BridgeResponse:
616 """Servisin tek cevabı (`protocol.rs::Response`). `school` İSTEĞİN AYNISI.
617
618 `status` "ok" ya da "err"; `err` bir *işlenmiş* hatadır (kötü girdi, model
619 reddi). Servis isteğin ortasında ölürse akış düşer — o taşıma hatasıdır,
620 buraya girmez."""
621 id: str
622 school: str
623 status: str = "ok"
624 payload: dict | None = None
625 code: str = ""
626 message: str = ""
627
628 @classmethod
629 def ok(cls, req: "BridgeRequest", payload: dict) -> "BridgeResponse":
630 return cls(id=req.id, school=req.school, status="ok", payload=payload)
631
632 @classmethod
633 def err(cls, req: "BridgeRequest", code: str,
634 message: str) -> "BridgeResponse":
635 return cls(id=req.id, school=req.school, status="err", code=code,
636 message=message)
637
638 def to_wire(self) -> dict:
639 if self.status == "ok":
640 return {"status": "ok", "id": self.id, "school": self.school,
641 "payload": self.payload if self.payload is not None else {}}
642 return {"status": "err", "id": self.id, "school": self.school,
643 "code": self.code, "message": self.message}
644
645
646def decode_api_response(frame: dict) -> tuple[int, object]:
647 """`ApiResponse` çerçevesini `(status, body)`'ye çevirir."""
648 if frame.get("outcome") == "err":
649 raise ApiError(f"{frame.get('code', '?')}: {frame.get('message', '')}")
650 return int(frame["status"]), frame.get("body")
651
652
653# ------------------------------------------------- çerçeveleme (protocol.rs)
654# `protocol.rs:267-304`: u32 big-endian uzunluk + o kadar bayt JSON. Çerçevenin
655# kendisi burada kurulur/çözülür; AKIŞ (kim açar, kim kapatır) taşımanın işi.
656
657
658def encode_frame(obj) -> bytes:
659 """Bir nesneyi tek uzunluk-önekli JSON çerçeveye çevir.
660
661 Boyut tavanı YAZARKEN de uygulanır (`protocol.rs:275-277`): sınırın üstünde
662 bir çerçeve yazmak, karşı tarafın okuyamayacağı bir akış bırakmaktır."""
663 body = json.dumps(obj, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
664 if len(body) > AI_MAX_FRAME_BYTES:
665 raise FrameTooLarge(len(body))
666 return struct.pack(">I", len(body)) + body
667
668
669class FrameTooLarge(BridgeFrameError):
670 """Çerçeve `AI_MAX_FRAME_BYTES` tavanını aşıyor."""
671
672 def __init__(self, size: int) -> None:
673 super().__init__(
674 f"{size} bayt, {AI_MAX_FRAME_BYTES} baytlık çerçeve sınırını aşıyor",
675 "frame_too_large")
676 self.size = size
677
678
679class HandshakeRejected(BridgeFrameError):
680 """`Greeting{type:"rejected"}` — backend kaydı reddetti.
681
682 `code` makine okunabilirdir: `unauthorized` / `unsupported_protocol` /
683 `no_capabilities` / `malformed` (`server.rs:1030-1046`)."""
684
685 def __init__(self, code: str, message: str) -> None:
686 super().__init__(message, code)
687
688 @property
689 def permanent(self) -> bool:
690 """Yeniden denemek tek başına düzeltir mi? Düzeltmez — ama beklemeyi
691 BIRAKMAYIZ (kalıcı rette tavana çekiliriz, çıkmayız)."""
692 return self.code in PERMANENT_REJECTS
693
694
695class FrameStream:
696 """Tek bir QUIC akışından çerçeve okuyan tampon.
697
698 `feed()` aioquic'in `StreamDataReceived` olayından beslenir; `read_frame()`
699 bir tam çerçeve döndürür. Akış çerçevenin ortasında biterse `EOFError`."""
700
701 def __init__(self) -> None:
702 self._buf = bytearray()
703 self._queue: asyncio.Queue[bytes | None] = asyncio.Queue()
704 self._eof = False
705
706 def feed(self, data: bytes, end: bool) -> None:
707 if data:
708 self._queue.put_nowait(data)
709 if end:
710 self._queue.put_nowait(None)
711
712 async def read_exact(self, n: int) -> bytes:
713 while len(self._buf) < n:
714 if self._eof:
715 raise EOFError("çerçeve tamamlanmadan akış bitti")
716 chunk = await self._queue.get()
717 if chunk is None:
718 self._eof = True
719 continue
720 self._buf.extend(chunk)
721 out = bytes(self._buf[:n])
722 del self._buf[:n]
723 return out
724
725 async def read_frame(self):
726 (length,) = struct.unpack(">I", await self.read_exact(4))
727 # Uzunluk, gövde AYRILMADAN önce denetlenir (`protocol.rs:286-289`).
728 if length > AI_MAX_FRAME_BYTES:
729 raise FrameTooLarge(length)
730 body = await self.read_exact(length)
731 try:
732 return json.loads(body)
733 except ValueError as exc:
734 raise BridgeFrameError(f"çerçeve gövdesi geçerli JSON değil: {exc}") from exc
735
736
737# ------------------------------------------------------ el sıkışma (kontrol)
738# `protocol.rs:85-119`: `Hello` servisten backend'e, `Greeting` backend'den
739# servise. `Hello` KASITLI olarak okul TAŞIMAZ: filo paylaşımlıdır, tek bağlantı
740# dağıtımdaki her okula hizmet eder ve her `Request` kendi okulunu adlandırır.
741
742
743def build_hello(service: str, capabilities, token: str,
744 max_concurrent: int) -> dict:
745 """Kontrol akışına yazılacak `Hello` çerçevesi. Protokol her zaman `hab/2`."""
746 return {
747 "protocol": AI_PROTOCOL,
748 "service": service,
749 "capabilities": list(capabilities),
750 "token": token,
751 "max_concurrent": max(1, min(int(max_concurrent),
752 AI_MAX_CONCURRENT_PER_WORKER)),
753 }
754
755
756def parse_greeting(raw) -> str:
757 """`Greeting`i çöz ve `worker_id` döndür; red ise `HandshakeRejected` atar.
758
759 Etiket alanı `type`, değerler `welcome`/`rejected` (`protocol.rs:106-119`).
760 `welcome` gelse bile YANKILANAN protokol denetlenir: eşleşmeyen bir sürümle
761 devam etmek, yanlış ayrışacak çerçeveler yazmak demektir."""
762 if not isinstance(raw, dict):
763 raise HandshakeRejected("malformed", "greeting bir nesne değil")
764 kind = raw.get("type")
765 if kind == "rejected":
766 raise HandshakeRejected(str(raw.get("code") or "malformed"),
767 str(raw.get("message") or ""))
768 if kind != "welcome":
769 raise HandshakeRejected("malformed", f"bilinmeyen greeting type: {kind!r}")
770 yankilanan = str(raw.get("protocol") or "")
771 if yankilanan != AI_PROTOCOL:
772 raise HandshakeRejected(
773 "unsupported_protocol",
774 f"backend '{yankilanan}' yankıladı, biz '{AI_PROTOCOL}' konuşuyoruz")
775 return str(raw.get("worker_id") or "?")