IISHKO: Telegram bot, Mini App and gateway
Initial public release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,295 @@
|
||||
from contextlib import closing
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
|
||||
from request_effort import InvalidEffort, read_effort
|
||||
_ID = re.compile(r"[a-z][a-z0-9_-]{0,47}\Z")
|
||||
_SAFE_RETRIES = frozenset(("upstream_throttled", "overloaded_error", "server_overloaded",
|
||||
"rate_limit_exceeded", "no_available_channel", "upstream_unavailable"))
|
||||
# Evidence a method can support. A response model echo proves identity only, so
|
||||
# it can never carry `operator_verified` (that would claim weights/provenance).
|
||||
_EVIDENCE_STATUS = {"none": ("unverified",),
|
||||
"response_model": ("identity_checked",),
|
||||
"tool_roundtrip": ("identity_checked", "operator_verified"),
|
||||
"official_route": ("operator_verified",),
|
||||
"signed_attestation": ("operator_verified",)}
|
||||
_EVIDENCE_FIELDS = frozenset(("status", "method", "checked_at", "reference"))
|
||||
|
||||
|
||||
def public_verification(verification):
|
||||
"""Project evidence for the public catalogue: method and timestamp only.
|
||||
|
||||
`reference` may name a private operator note, admin URL, or ticket that must
|
||||
never leave the registry, so it is deliberately not projected.
|
||||
"""
|
||||
return {"status": verification["status"], "method": verification["method"],
|
||||
"checked_at": verification["checked_at"]}
|
||||
|
||||
|
||||
class ProviderError(ValueError):
|
||||
def __init__(self, status, code, message):
|
||||
super().__init__(message)
|
||||
self.status, self.code, self.message = status, code, message
|
||||
|
||||
|
||||
def _read(db):
|
||||
con = sqlite3.connect(Path(db).resolve().as_uri() + "?mode=ro", uri=True, timeout=3)
|
||||
con.row_factory = sqlite3.Row
|
||||
con.execute("PRAGMA query_only=ON")
|
||||
return con
|
||||
|
||||
|
||||
def response_effort(payload):
|
||||
"""Read policy metadata only. The generation bytes remain unchanged."""
|
||||
try:
|
||||
return read_effort(payload)
|
||||
except InvalidEffort as error:
|
||||
raise ProviderError(400, "invalid_effort", str(error)) from None
|
||||
|
||||
|
||||
def safe_to_retry(status, raw):
|
||||
"""Only an explicit overload rejection, never a timeout/ambiguous transport."""
|
||||
if status not in (429, 503):
|
||||
return False
|
||||
try:
|
||||
body = json.loads(raw)
|
||||
error = body.get("error", {})
|
||||
return isinstance(error, dict) and (error.get("code") or error.get("type")) in _SAFE_RETRIES
|
||||
except (ValueError, TypeError, AttributeError, UnicodeDecodeError):
|
||||
return False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ProviderChoice:
|
||||
id: str
|
||||
channel_id: int
|
||||
model: str
|
||||
probe: bool = False
|
||||
|
||||
|
||||
class ProviderRegistry:
|
||||
def __init__(self, config=None, *, clock=time.monotonic):
|
||||
config = config or {}
|
||||
if not isinstance(config, dict) or type(config.get("pinning_enabled", False)) is not bool:
|
||||
raise ValueError("invalid provider configuration")
|
||||
self.pinning_enabled = config.get("pinning_enabled", False)
|
||||
self.clock = clock
|
||||
self._lock = threading.Lock()
|
||||
self._circuits = {}
|
||||
self._round = {}
|
||||
self._active = {}
|
||||
self.providers = []
|
||||
used_ids, used_channels = set(), set()
|
||||
entries = config.get("providers", [])
|
||||
if not isinstance(entries, list) or len(entries) > 128:
|
||||
raise ValueError("invalid provider list")
|
||||
for entry in entries:
|
||||
if not isinstance(entry, dict):
|
||||
raise ValueError("invalid provider entry")
|
||||
pid, name = entry.get("id"), entry.get("name")
|
||||
if not isinstance(pid, str) or not _ID.fullmatch(pid) or pid in used_ids:
|
||||
raise ValueError("invalid or duplicate provider id")
|
||||
if not isinstance(name, str) or not 1 <= len(name) <= 80:
|
||||
raise ValueError("invalid provider display name")
|
||||
channels, models = entry.get("channel_ids", []), entry.get("models", {})
|
||||
if not isinstance(channels, list) or len(channels) > 512 or any(type(v) is not int or v < 1 for v in channels):
|
||||
raise ValueError("invalid provider channel ids")
|
||||
if len(channels) != len(set(channels)) or used_channels.intersection(channels):
|
||||
raise ValueError("a channel cannot masquerade as independent reserve providers")
|
||||
if not isinstance(models, dict) or len(models) > 1024:
|
||||
raise ValueError("invalid provider models")
|
||||
clean_models = {}
|
||||
for model, capability in models.items():
|
||||
if not isinstance(model, str) or not 1 <= len(model) <= 256 or not isinstance(capability, dict):
|
||||
raise ValueError("invalid model capability")
|
||||
effort = capability.get("effort_levels")
|
||||
if effort is not None and (not isinstance(effort, list) or any(not isinstance(v, str) or not v or len(v) > 32 for v in effort)):
|
||||
raise ValueError("invalid effort levels")
|
||||
evidence = capability.get("verification", {})
|
||||
if not isinstance(evidence, dict):
|
||||
raise ValueError("invalid verification evidence")
|
||||
if not set(evidence) <= _EVIDENCE_FIELDS:
|
||||
raise ValueError("unknown verification evidence field")
|
||||
status = evidence.get("status", "unverified")
|
||||
method = evidence.get("method", "none")
|
||||
if status not in ("unverified", "identity_checked", "operator_verified"):
|
||||
raise ValueError("invalid verification status")
|
||||
if not isinstance(method, str) or method not in _EVIDENCE_STATUS:
|
||||
raise ValueError("invalid verification method")
|
||||
if status not in _EVIDENCE_STATUS[method]:
|
||||
raise ValueError("incoherent verification status and method")
|
||||
checked = evidence.get("checked_at")
|
||||
reference = evidence.get("reference")
|
||||
if status == "unverified":
|
||||
# Nothing was checked, so claiming a timestamp or a reference
|
||||
# would be fabricated evidence rather than a downgrade.
|
||||
if checked is not None or reference is not None:
|
||||
raise ValueError("unverified evidence cannot carry proof fields")
|
||||
elif (type(checked) is not int or checked <= 0
|
||||
or not isinstance(reference, str) or not reference.strip()
|
||||
or len(reference) > 200):
|
||||
raise ValueError("verification requires a timestamp and evidence reference")
|
||||
clean_models[model] = {"effort_levels": effort, "verification": {
|
||||
"status": status, "method": method, "checked_at": checked,
|
||||
# Kept privately for the operator; never projected publicly.
|
||||
"reference": reference}}
|
||||
priority = entry.get("priority", 0)
|
||||
if type(priority) is not int or not -10000 <= priority <= 10000:
|
||||
raise ValueError("invalid provider priority")
|
||||
concurrency = entry.get("max_inflight", 32)
|
||||
if type(concurrency) is not int or not 1 <= concurrency <= 4096 or type(entry.get("reserve", False)) is not bool:
|
||||
raise ValueError("invalid provider capacity")
|
||||
self.providers.append({"id": pid, "name": name, "channels": tuple(channels), "models": clean_models,
|
||||
"priority": priority, "reserve": entry.get("reserve", False),
|
||||
"max_inflight": concurrency})
|
||||
used_ids.add(pid)
|
||||
used_channels.update(channels)
|
||||
self.providers.sort(key=lambda p: (p["reserve"], -p["priority"], p["id"]))
|
||||
|
||||
@classmethod
|
||||
def from_file(cls, path):
|
||||
if not path:
|
||||
return cls()
|
||||
with open(path, encoding="utf-8") as source:
|
||||
return cls(json.load(source))
|
||||
|
||||
def _channels(self, con, provider, model, group):
|
||||
if not provider["channels"]:
|
||||
return []
|
||||
marks = ",".join("?" for _ in provider["channels"])
|
||||
rows = con.execute(
|
||||
'SELECT DISTINCT c.id,c.model_mapping FROM channels c JOIN abilities a ON a.channel_id=c.id '
|
||||
'WHERE c.status=1 AND a.enabled=1 AND a.model=? AND a."group"=? AND c.id IN (' + marks + ') ORDER BY c.id',
|
||||
(model, group, *provider["channels"])).fetchall()
|
||||
result = []
|
||||
for row in rows:
|
||||
try:
|
||||
mapping = json.loads(row["model_mapping"] or "{}")
|
||||
except (ValueError, TypeError):
|
||||
continue
|
||||
if not isinstance(mapping, dict) or mapping.get(model, model) != model:
|
||||
continue
|
||||
result.append(int(row["id"]))
|
||||
return result
|
||||
|
||||
def catalog(self, db, model, group="default"):
|
||||
result = []
|
||||
with closing(_read(db)) as con:
|
||||
for provider in self.providers:
|
||||
cap = provider["models"].get(model)
|
||||
if cap is None:
|
||||
continue
|
||||
channels = self._channels(con, provider, model, group)
|
||||
with self._lock:
|
||||
worst = 0
|
||||
for cid in channels:
|
||||
st = self._circuits.get((cid, model), {})
|
||||
worst = max(worst, st.get("until", 0))
|
||||
cooldown = max(0, int(worst - self.clock() + .999))
|
||||
busy = self._active.get(provider["id"], 0) >= provider["max_inflight"]
|
||||
levels = cap["effort_levels"]
|
||||
result.append({"id": provider["id"], "name": provider["name"],
|
||||
"available": bool(channels) and not cooldown and not busy and self.pinning_enabled,
|
||||
"reserve": provider["reserve"], "effort": None if levels is None else bool(levels),
|
||||
"effort_levels": levels or [], "verification": public_verification(cap["verification"]),
|
||||
"cooldown_seconds": cooldown})
|
||||
return {"model": model, "providers": result, "pinning_enabled": self.pinning_enabled,
|
||||
"identity_notice": "Model name checks detect mismatches; they do not prove original weights or vendor provenance."}
|
||||
|
||||
def choose(self, db, raw_key, model, *, pinned=None, effort=None, exclude=()):
|
||||
if not self.pinning_enabled:
|
||||
raise ProviderError(503, "provider_selection_unavailable", "Provider selection has not been enabled by the operator.")
|
||||
if pinned and (not isinstance(pinned, str) or not _ID.fullmatch(pinned)):
|
||||
raise ProviderError(400, "invalid_provider", "Invalid provider id.")
|
||||
with closing(_read(db)) as con:
|
||||
token = con.execute('SELECT t."group",u.role FROM tokens t JOIN users u ON u.id=t.user_id '
|
||||
'WHERE t.key=? AND t.deleted_at IS NULL AND t.status=1 AND u.status=1 AND u.deleted_at IS NULL',
|
||||
(raw_key,)).fetchall()
|
||||
if len(token) != 1 or int(token[0]["role"]) < 10:
|
||||
raise ProviderError(503, "provider_selection_unavailable", "This New API installation cannot safely pin the authenticated token.")
|
||||
group = token[0]["group"] or "default"
|
||||
known = False
|
||||
unsupported = False
|
||||
for provider in self.providers:
|
||||
if pinned and provider["id"] != pinned:
|
||||
continue
|
||||
cap = provider["models"].get(model)
|
||||
if cap is None:
|
||||
continue
|
||||
known = True
|
||||
if provider["id"] in exclude:
|
||||
continue
|
||||
if effort is not None and (cap["effort_levels"] is None or effort not in cap["effort_levels"]):
|
||||
unsupported = True
|
||||
continue
|
||||
channels = self._channels(con, provider, model, group)
|
||||
if not channels:
|
||||
continue
|
||||
with self._lock:
|
||||
if self._active.get(provider["id"], 0) >= provider["max_inflight"]:
|
||||
continue
|
||||
live = [cid for cid in channels
|
||||
if (lambda s: not s or s["failures"] < 3 or
|
||||
(s["until"] <= self.clock() and not s.get("probe"))
|
||||
)(self._circuits.get((cid, model)))]
|
||||
if not live:
|
||||
continue
|
||||
probe_chan = None
|
||||
for cid in live:
|
||||
s = self._circuits.get((cid, model))
|
||||
if s and s["failures"] >= 3 and s["until"] <= self.clock() and not s.get("probe"):
|
||||
s["probe"] = True
|
||||
probe_chan = cid
|
||||
break
|
||||
index = self._round.get(provider["id"], 0)
|
||||
self._round[provider["id"]] = index + 1
|
||||
self._active[provider["id"]] = self._active.get(provider["id"], 0) + 1
|
||||
chosen = probe_chan if probe_chan is not None else live[index % len(live)]
|
||||
return ProviderChoice(provider["id"], chosen, model, probe_chan is not None)
|
||||
if pinned and not known:
|
||||
raise ProviderError(400, "provider_model_unavailable", "The selected provider does not serve this exact model.")
|
||||
if unsupported:
|
||||
raise ProviderError(400, "effort_not_supported", "Effort support for this model/provider is unsupported or unverified.")
|
||||
raise ProviderError(503, "no_healthy_provider", "No healthy same-model provider is available. Retry later.")
|
||||
|
||||
def complete(self, choice, status, *, retry_after=0):
|
||||
with self._lock:
|
||||
self._active[choice.id] = max(0, self._active.get(choice.id, 0) - 1)
|
||||
key = (choice.channel_id, choice.model)
|
||||
if 200 <= status < 400:
|
||||
self._circuits.pop(key, None)
|
||||
return
|
||||
if status not in (401, 403, 404, 429, 500, 502, 503, 504):
|
||||
if choice.probe:
|
||||
self._circuits.pop(key, None)
|
||||
return
|
||||
state = self._circuits.setdefault(key, {"failures": 0, "until": 0})
|
||||
state["failures"] += 1
|
||||
state["probe"] = False
|
||||
if status in (401, 403, 404):
|
||||
state["failures"] = max(3, state["failures"])
|
||||
if state["failures"] >= 3:
|
||||
try:
|
||||
delay = max(15, min(120, int(retry_after)))
|
||||
except (ValueError, TypeError):
|
||||
delay = 15
|
||||
state["until"] = self.clock() + delay
|
||||
|
||||
def abandon(self, choice):
|
||||
"""Release cancellation without claiming provider success or replaying."""
|
||||
with self._lock:
|
||||
self._active[choice.id] = max(0, self._active.get(choice.id, 0) - 1)
|
||||
state = self._circuits.get((choice.channel_id, choice.model))
|
||||
if state and choice.probe:
|
||||
state["probe"] = False
|
||||
|
||||
@staticmethod
|
||||
def pinned_authorization(raw_key, choice):
|
||||
if not isinstance(raw_key, str) or not re.fullmatch(r"[A-Za-z0-9_]{1,256}", raw_key):
|
||||
raise ProviderError(503, "provider_selection_unavailable", "The token format cannot safely select a New API channel.")
|
||||
return "Bearer sk-" + raw_key + "-" + str(choice.channel_id)
|
||||
Reference in New Issue
Block a user