modelsaar 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- modelsaar/__init__.py +13 -0
- modelsaar/adapters/__init__.py +27 -0
- modelsaar/adapters/base.py +274 -0
- modelsaar/adapters/ollama.py +317 -0
- modelsaar/adapters/openai_compat.py +296 -0
- modelsaar/catalogue/__init__.py +72 -0
- modelsaar/catalogue/starter.yaml +435 -0
- modelsaar/cli.py +880 -0
- modelsaar/clientconfig/__init__.py +364 -0
- modelsaar/config.py +631 -0
- modelsaar/doctor.py +233 -0
- modelsaar/evaluation/__init__.py +1 -0
- modelsaar/evaluation/fixtures/tasks.jsonl +47 -0
- modelsaar/evaluation/harness.py +768 -0
- modelsaar/evaluation/judge.py +173 -0
- modelsaar/evaluation/sandbox.py +341 -0
- modelsaar/evaluation/scoring.py +233 -0
- modelsaar/learning.py +227 -0
- modelsaar/lifecycle.py +208 -0
- modelsaar/pipelines.py +439 -0
- modelsaar/probes.py +526 -0
- modelsaar/protocol/__init__.py +1 -0
- modelsaar/protocol/anthropic.py +401 -0
- modelsaar/protocol/decisions.py +229 -0
- modelsaar/protocol/openai.py +322 -0
- modelsaar/protocol/responses.py +560 -0
- modelsaar/protocol/sse.py +181 -0
- modelsaar/registry.py +229 -0
- modelsaar/responses_store.py +117 -0
- modelsaar/routing/__init__.py +1 -0
- modelsaar/routing/admission.py +359 -0
- modelsaar/routing/affinity.py +131 -0
- modelsaar/routing/cascade.py +53 -0
- modelsaar/routing/classifier.py +298 -0
- modelsaar/routing/decision.py +85 -0
- modelsaar/routing/eligibility.py +158 -0
- modelsaar/routing/requirements.py +290 -0
- modelsaar/routing/router.py +1026 -0
- modelsaar/routing/scoring.py +179 -0
- modelsaar/routing/tokens.py +114 -0
- modelsaar/runtime.py +82 -0
- modelsaar/security.py +63 -0
- modelsaar/server.py +1546 -0
- modelsaar/static/status.html +95 -0
- modelsaar/store.py +208 -0
- modelsaar/testing/__init__.py +1 -0
- modelsaar/testing/fakebackend.py +661 -0
- modelsaar-0.2.0.dist-info/METADATA +285 -0
- modelsaar-0.2.0.dist-info/RECORD +54 -0
- modelsaar-0.2.0.dist-info/WHEEL +5 -0
- modelsaar-0.2.0.dist-info/entry_points.txt +2 -0
- modelsaar-0.2.0.dist-info/licenses/LICENSE +202 -0
- modelsaar-0.2.0.dist-info/licenses/NOTICE +18 -0
- modelsaar-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""Transparent, configurable ranking of eligible deployments.
|
|
2
|
+
|
|
3
|
+
Each candidate gets a breakdown: expected quality (with evidence level and
|
|
4
|
+
uncertainty), latency cost, residency/load cost, overhead cost, and any
|
|
5
|
+
affinity/switching adjustment. The top candidate wins unless it is tied with
|
|
6
|
+
a cheaper candidate within the evidence's uncertainty, in which case the
|
|
7
|
+
lower-overhead option is preferred.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import math
|
|
13
|
+
import re
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from ..config import ProfileWeights, RoutingConfig
|
|
18
|
+
from ..registry import Deployment
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class Candidate:
|
|
23
|
+
deployment: Deployment
|
|
24
|
+
quality: float
|
|
25
|
+
uncertainty: float
|
|
26
|
+
evidence: str # measured:<n> | prior:<provenance> | uncalibrated
|
|
27
|
+
latency_cost: float
|
|
28
|
+
residency_cost: float
|
|
29
|
+
overhead_cost: float
|
|
30
|
+
affinity_adjust: float
|
|
31
|
+
score: float = 0.0
|
|
32
|
+
notes: list[str] = field(default_factory=list)
|
|
33
|
+
|
|
34
|
+
def as_dict(self) -> dict[str, Any]:
|
|
35
|
+
return {
|
|
36
|
+
"deployment": self.deployment.id,
|
|
37
|
+
"quality": round(self.quality, 3),
|
|
38
|
+
"uncertainty": round(self.uncertainty, 3),
|
|
39
|
+
"evidence": self.evidence,
|
|
40
|
+
"latency_cost": round(self.latency_cost, 3),
|
|
41
|
+
"residency_cost": round(self.residency_cost, 3),
|
|
42
|
+
"overhead_cost": round(self.overhead_cost, 3),
|
|
43
|
+
"affinity_adjust": round(self.affinity_adjust, 3),
|
|
44
|
+
"score": round(self.score, 4),
|
|
45
|
+
"notes": self.notes,
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
_SIZE_RX = re.compile(r"([\d.]+)\s*([bBmM])")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def param_count_b(dep: Deployment) -> float | None:
|
|
53
|
+
m = _SIZE_RX.search(dep.parameter_size or "")
|
|
54
|
+
if not m:
|
|
55
|
+
return None
|
|
56
|
+
n = float(m.group(1))
|
|
57
|
+
return n / 1000.0 if m.group(2).lower() == "m" else n
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def quality_estimate(dep: Deployment, task: str, cfg: RoutingConfig) -> tuple[float, float, str]:
|
|
61
|
+
"""Return (quality, uncertainty, evidence). Never presents a prior as a measurement."""
|
|
62
|
+
m = dep.measurements.get(task)
|
|
63
|
+
if m and m.quality is not None and m.samples > 0:
|
|
64
|
+
unc = min(0.5, 1.0 / (m.samples**0.5))
|
|
65
|
+
if str(m.source).startswith("learned"):
|
|
66
|
+
# Passive outcomes under an activated, holdout-checked policy: labelled as learned, never as a
|
|
67
|
+
# harness measurement.
|
|
68
|
+
return float(m.quality), unc, f"{m.source}:{m.samples}"
|
|
69
|
+
return float(m.quality), unc, f"measured:{m.samples}"
|
|
70
|
+
# fall back to "any task" measurement as weak evidence (harness measurements only)
|
|
71
|
+
anym = [x for x in dep.measurements.values() if x.quality is not None and x.samples > 0 and not str(x.source).startswith("learned")]
|
|
72
|
+
if anym:
|
|
73
|
+
q = sum(x.quality for x in anym) / len(anym) # type: ignore[misc]
|
|
74
|
+
return float(q), 0.3, f"measured-other-task:{sum(x.samples for x in anym)}"
|
|
75
|
+
if task in dep.quality_prior:
|
|
76
|
+
return float(dep.quality_prior[task]), 0.25, f"prior:{dep.quality_prior_provenance}"
|
|
77
|
+
if "general" in dep.quality_prior:
|
|
78
|
+
return float(dep.quality_prior["general"]), 0.3, f"prior-general:{dep.quality_prior_provenance}"
|
|
79
|
+
pb = param_count_b(dep)
|
|
80
|
+
if pb is not None:
|
|
81
|
+
# Labelled hypothesis, not a measurement: slightly favour larger checkpoints until measured.
|
|
82
|
+
return min(0.75, cfg.uncalibrated_prior + 0.05 * math.log10(1.0 + pb)), 0.35, "uncalibrated:size-heuristic"
|
|
83
|
+
return float(cfg.uncalibrated_prior), 0.35, "uncalibrated"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def latency_estimate_ms(dep: Deployment, task: str) -> tuple[float, str]:
|
|
87
|
+
m = dep.measurements.get(task)
|
|
88
|
+
if m and m.p50_ms:
|
|
89
|
+
return float(m.p50_ms), "measured"
|
|
90
|
+
anym = [x.p50_ms for x in dep.measurements.values() if x.p50_ms]
|
|
91
|
+
if anym:
|
|
92
|
+
return float(sum(anym) / len(anym)), "measured-other-task"
|
|
93
|
+
pb = param_count_b(dep)
|
|
94
|
+
if pb is not None:
|
|
95
|
+
# Rough heuristic only used for relative ordering: ~ linear in parameter count.
|
|
96
|
+
return 500.0 + 150.0 * pb, "size-heuristic"
|
|
97
|
+
return 3000.0, "unknown-default"
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def load_estimate_ms(dep: Deployment) -> tuple[float, str]:
|
|
101
|
+
for m in dep.measurements.values():
|
|
102
|
+
if m.load_ms:
|
|
103
|
+
return float(m.load_ms), "measured"
|
|
104
|
+
if dep.memory_gb_estimate:
|
|
105
|
+
return 800.0 * dep.memory_gb_estimate, "memory-heuristic"
|
|
106
|
+
return 8000.0, "unknown-default"
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def blended_quality(dep: Deployment, tasks: dict[str, float], cfg: RoutingConfig) -> tuple[float, float, str]:
|
|
110
|
+
"""Confidence-weighted blend over the candidate task labels (robust for ambiguous requests)."""
|
|
111
|
+
if not tasks:
|
|
112
|
+
return quality_estimate(dep, "conversation", cfg)
|
|
113
|
+
total = sum(tasks.values()) or 1.0
|
|
114
|
+
q = u = 0.0
|
|
115
|
+
evs: list[str] = []
|
|
116
|
+
for t, w in tasks.items():
|
|
117
|
+
qt, ut, et = quality_estimate(dep, t, cfg)
|
|
118
|
+
q += w * qt
|
|
119
|
+
u += w * ut
|
|
120
|
+
evs.append(f"{t}={et}")
|
|
121
|
+
top = max(tasks.items(), key=lambda kv: kv[1])[0]
|
|
122
|
+
_, _, top_ev = quality_estimate(dep, top, cfg)
|
|
123
|
+
ev = top_ev if len(tasks) == 1 else f"{top_ev} (blend: {', '.join(evs)})"
|
|
124
|
+
return q / total, u / total, ev
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def rank(
|
|
128
|
+
eligible: list[Deployment],
|
|
129
|
+
task: str,
|
|
130
|
+
weights: ProfileWeights,
|
|
131
|
+
cfg: RoutingConfig,
|
|
132
|
+
affinity_dep: str | None = None,
|
|
133
|
+
tasks: dict[str, float] | None = None,
|
|
134
|
+
) -> list[Candidate]:
|
|
135
|
+
if not eligible:
|
|
136
|
+
return []
|
|
137
|
+
lat = {d.id: latency_estimate_ms(d, task) for d in eligible}
|
|
138
|
+
load = {d.id: load_estimate_ms(d) for d in eligible}
|
|
139
|
+
max_lat = max(v[0] for v in lat.values()) or 1.0
|
|
140
|
+
max_load = max(v[0] for v in load.values()) or 1.0
|
|
141
|
+
max_mem = max((d.memory_gb_estimate or 0.0) for d in eligible) or 1.0
|
|
142
|
+
cands: list[Candidate] = []
|
|
143
|
+
for d in eligible:
|
|
144
|
+
q, unc, ev = blended_quality(d, tasks or {task: 1.0}, cfg)
|
|
145
|
+
lcost = lat[d.id][0] / max_lat
|
|
146
|
+
rcost = 0.0 if d.loaded else (load[d.id][0] / max_load)
|
|
147
|
+
ocost = (d.memory_gb_estimate or 0.0) / max_mem
|
|
148
|
+
aff = 0.0
|
|
149
|
+
notes = [f"latency:{lat[d.id][1]}", f"load:{load[d.id][1]}"]
|
|
150
|
+
if affinity_dep:
|
|
151
|
+
if d.id == affinity_dep:
|
|
152
|
+
aff = cfg.switching_penalty
|
|
153
|
+
notes.append("affinity: current deployment for this session")
|
|
154
|
+
else:
|
|
155
|
+
aff = -cfg.switching_penalty
|
|
156
|
+
notes.append("switching penalty applied (hysteresis)")
|
|
157
|
+
c = Candidate(d, q, unc, ev, lcost, rcost, ocost, aff, notes=notes)
|
|
158
|
+
c.score = (
|
|
159
|
+
weights.quality * q
|
|
160
|
+
- weights.latency * lcost
|
|
161
|
+
- weights.residency * rcost
|
|
162
|
+
- weights.overhead * ocost
|
|
163
|
+
+ aff
|
|
164
|
+
)
|
|
165
|
+
cands.append(c)
|
|
166
|
+
cands.sort(key=lambda c: c.score, reverse=True)
|
|
167
|
+
# Tie-break: candidates whose quality is within the evidence uncertainty of
|
|
168
|
+
# the best quality are "effectively tied"; among those prefer lower overhead.
|
|
169
|
+
best = cands[0]
|
|
170
|
+
# Measured evidence: tolerance follows sampling uncertainty. Priors: a fixed small band.
|
|
171
|
+
tol = best.uncertainty / 2 if best.evidence.startswith(("measured", "learned")) else 0.03
|
|
172
|
+
tied = [c for c in cands if abs(c.quality - best.quality) <= tol and abs(c.score - best.score) <= tol]
|
|
173
|
+
if len(tied) > 1:
|
|
174
|
+
cheapest = min(tied, key=lambda c: (c.residency_cost + c.latency_cost + c.overhead_cost - c.affinity_adjust))
|
|
175
|
+
if cheapest is not best:
|
|
176
|
+
cheapest.notes.append("tie-break: effectively tied on quality; lower overhead preferred")
|
|
177
|
+
cands.remove(cheapest)
|
|
178
|
+
cands.insert(0, cheapest)
|
|
179
|
+
return cands
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Token accounting.
|
|
2
|
+
|
|
3
|
+
Exact tokenization is used when the backend exposes it (vLLM ``/tokenize``).
|
|
4
|
+
Otherwise a *documented conservative estimate* is applied: ``chars/3`` plus
|
|
5
|
+
per-message, per-tool and per-image overheads, plus the requested output and
|
|
6
|
+
any applicable reasoning budget. The estimate is deliberately pessimistic so
|
|
7
|
+
that a deployment is never chosen whose context the real request would overflow.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import math
|
|
14
|
+
import re
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from ..config import TokenEstimateConfig
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class TokenBudget:
|
|
23
|
+
input_estimate: int
|
|
24
|
+
output_allowance: int
|
|
25
|
+
reasoning_allowance: int
|
|
26
|
+
images: int
|
|
27
|
+
method: str # "tokenize:<backend>+template-estimate" | "estimate:chars/3"
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def total(self) -> int:
|
|
31
|
+
return self.input_estimate + self.output_allowance + self.reasoning_allowance
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
_WIDE = re.compile(r"[\u0400-\u04FF\u0590-\u08FF\u0900-\u0DFF\u0E00-\u0E7F\u1100-\u11FF\u3000-\u30FF\u3400-\u9FFF\uAC00-\uD7AF\uF900-\uFAFF\uFF00-\uFFEF]")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _wide_count(text: str) -> int:
|
|
38
|
+
"""Characters from scripts where tokenizers spend ~1+ token per character."""
|
|
39
|
+
return len(_WIDE.findall(text))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _text_of(content: Any) -> tuple[str, int]:
|
|
43
|
+
"""Flatten message content to text; return (text, image_count)."""
|
|
44
|
+
if content is None:
|
|
45
|
+
return "", 0
|
|
46
|
+
if isinstance(content, str):
|
|
47
|
+
return content, 0
|
|
48
|
+
images = 0
|
|
49
|
+
parts: list[str] = []
|
|
50
|
+
if isinstance(content, list):
|
|
51
|
+
for p in content:
|
|
52
|
+
if not isinstance(p, dict):
|
|
53
|
+
parts.append(str(p))
|
|
54
|
+
continue
|
|
55
|
+
t = p.get("type")
|
|
56
|
+
if t in ("text", "input_text"):
|
|
57
|
+
parts.append(str(p.get("text", "")))
|
|
58
|
+
elif t in ("image_url", "input_image", "image"):
|
|
59
|
+
images += 1
|
|
60
|
+
elif t in ("input_audio", "audio", "video_url"):
|
|
61
|
+
parts.append("") # audio/video have their own requirement flags (video adds a token allowance)
|
|
62
|
+
else:
|
|
63
|
+
parts.append(json.dumps(p, ensure_ascii=False))
|
|
64
|
+
return "\n".join(parts), images
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def estimate_chat_tokens(body: dict[str, Any], cfg: TokenEstimateConfig, thinking_possible: bool) -> TokenBudget:
|
|
68
|
+
chars = 0
|
|
69
|
+
wide_chars = 0
|
|
70
|
+
images = 0
|
|
71
|
+
msgs = body.get("messages") or []
|
|
72
|
+
for m in msgs:
|
|
73
|
+
if not isinstance(m, dict):
|
|
74
|
+
continue
|
|
75
|
+
t, im = _text_of(m.get("content"))
|
|
76
|
+
w = _wide_count(t)
|
|
77
|
+
wide_chars += w
|
|
78
|
+
chars += len(t) - w
|
|
79
|
+
images += im
|
|
80
|
+
if m.get("tool_calls"):
|
|
81
|
+
chars += len(json.dumps(m["tool_calls"], ensure_ascii=False))
|
|
82
|
+
if m.get("reasoning_content"):
|
|
83
|
+
chars += len(str(m["reasoning_content"]))
|
|
84
|
+
if m.get("name"):
|
|
85
|
+
chars += len(str(m["name"]))
|
|
86
|
+
tools = body.get("tools") or []
|
|
87
|
+
tool_overhead = 0
|
|
88
|
+
for t in tools:
|
|
89
|
+
chars += len(json.dumps(t, ensure_ascii=False))
|
|
90
|
+
tool_overhead += cfg.tool_definition_overhead
|
|
91
|
+
rf = body.get("response_format")
|
|
92
|
+
if isinstance(rf, dict):
|
|
93
|
+
chars += len(json.dumps(rf, ensure_ascii=False))
|
|
94
|
+
latin_chars = chars
|
|
95
|
+
text_tokens = math.ceil(latin_chars / cfg.chars_per_token) + wide_chars # 1 token per non-Latin char (conservative)
|
|
96
|
+
videos = sum(1 for m in msgs if isinstance(m, dict) and isinstance(m.get("content"), list) for p in m["content"] if isinstance(p, dict) and p.get("type") == "video_url")
|
|
97
|
+
input_estimate = text_tokens + len(msgs) * cfg.per_message_overhead + tool_overhead + images * cfg.image_tokens + videos * cfg.video_tokens
|
|
98
|
+
input_estimate = math.ceil(input_estimate * (1 + cfg.safety_margin))
|
|
99
|
+
out = body.get("max_completion_tokens") or body.get("max_tokens") or cfg.default_max_output
|
|
100
|
+
if not isinstance(out, int) or out < 1:
|
|
101
|
+
out = cfg.default_max_output
|
|
102
|
+
reasoning = cfg.reasoning_budget if thinking_possible else 0
|
|
103
|
+
return TokenBudget(
|
|
104
|
+
input_estimate=input_estimate,
|
|
105
|
+
output_allowance=int(out),
|
|
106
|
+
reasoning_allowance=reasoning,
|
|
107
|
+
images=images,
|
|
108
|
+
method=f"estimate:chars/{cfg.chars_per_token:g}+overheads",
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def estimate_text_tokens(text: str, cfg: TokenEstimateConfig) -> int:
|
|
113
|
+
w = _wide_count(text)
|
|
114
|
+
return math.ceil(((len(text) - w) / cfg.chars_per_token + w) * (1 + cfg.safety_margin))
|
modelsaar/runtime.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Assemble a gateway from a Config: store, router, auth, app. Also a thread
|
|
2
|
+
runner used by tests and the demo."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import logging
|
|
7
|
+
import socket
|
|
8
|
+
import threading
|
|
9
|
+
import time
|
|
10
|
+
|
|
11
|
+
import uvicorn
|
|
12
|
+
|
|
13
|
+
from .config import Config
|
|
14
|
+
from .routing.router import Router
|
|
15
|
+
from .security import Auth
|
|
16
|
+
from .server import build_app
|
|
17
|
+
from .store import Store
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def build(cfg: Config, with_store: bool = True):
|
|
21
|
+
store = Store(cfg.resolve(cfg.server.state_db)) if with_store else None
|
|
22
|
+
router = Router(cfg, store)
|
|
23
|
+
auth = Auth(cfg)
|
|
24
|
+
app = build_app(cfg, router, auth, store)
|
|
25
|
+
return app, router, auth, store
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def configure_logging(level: str = "INFO") -> None:
|
|
29
|
+
logging.basicConfig(level=getattr(logging, level, logging.INFO), format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
|
30
|
+
# uvicorn access logs would contain paths only (never bodies), but keep them quiet by default.
|
|
31
|
+
logging.getLogger("uvicorn.access").setLevel(logging.WARNING)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def free_port(host: str = "127.0.0.1") -> int:
|
|
35
|
+
s = socket.socket()
|
|
36
|
+
s.bind((host, 0))
|
|
37
|
+
p = s.getsockname()[1]
|
|
38
|
+
s.close()
|
|
39
|
+
return p
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class GatewayThread:
|
|
43
|
+
"""Run the gateway in a background thread (real HTTP server, real sockets)."""
|
|
44
|
+
|
|
45
|
+
def __init__(self, cfg: Config, with_store: bool = True) -> None:
|
|
46
|
+
self.cfg = cfg
|
|
47
|
+
self.app, self.router, self.auth, self.store = build(cfg, with_store)
|
|
48
|
+
self._server: uvicorn.Server | None = None
|
|
49
|
+
self._thread: threading.Thread | None = None
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def url(self) -> str:
|
|
53
|
+
return f"http://{self.cfg.server.host}:{self.cfg.server.port}"
|
|
54
|
+
|
|
55
|
+
def start(self) -> str:
|
|
56
|
+
config = uvicorn.Config(self.app, host=self.cfg.server.host, port=self.cfg.server.port, log_level="error")
|
|
57
|
+
self._server = uvicorn.Server(config)
|
|
58
|
+
self._thread = threading.Thread(target=self._server.run, daemon=True)
|
|
59
|
+
self._thread.start()
|
|
60
|
+
deadline = time.time() + 15
|
|
61
|
+
while time.time() < deadline:
|
|
62
|
+
if self._server.started and self.app.state.gw.ready:
|
|
63
|
+
return self.url
|
|
64
|
+
time.sleep(0.02)
|
|
65
|
+
raise RuntimeError("gateway did not start in time")
|
|
66
|
+
|
|
67
|
+
def run(self, coro): # type: ignore[no-untyped-def]
|
|
68
|
+
"""Run a coroutine on the gateway's event loop from another thread (adapters are loop-bound)."""
|
|
69
|
+
import asyncio
|
|
70
|
+
|
|
71
|
+
loop = self.app.state.gw.loop
|
|
72
|
+
if loop is None:
|
|
73
|
+
raise RuntimeError("gateway loop not running")
|
|
74
|
+
return asyncio.run_coroutine_threadsafe(coro, loop).result()
|
|
75
|
+
|
|
76
|
+
def stop(self) -> None:
|
|
77
|
+
if self._server:
|
|
78
|
+
self._server.should_exit = True
|
|
79
|
+
if self._thread:
|
|
80
|
+
self._thread.join(timeout=10)
|
|
81
|
+
if self.store:
|
|
82
|
+
self.store.close()
|
modelsaar/security.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Authentication, caller scoping and log redaction."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import hmac
|
|
7
|
+
import re
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from .config import Config, read_keys
|
|
11
|
+
|
|
12
|
+
_SECRET_RX = re.compile(
|
|
13
|
+
r"(?i)(bearer\s+[a-z0-9_\-\.]{8,}|msk_[A-Za-z0-9_\-]{16,}|msa_[A-Za-z0-9_\-]{16,}|sk-[A-Za-z0-9]{8,}|"
|
|
14
|
+
r"(api[_-]?key|authorization|token)\s*[=:]\s*['\"]?[A-Za-z0-9_\-\.]{8,})"
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def redact(text: str) -> str:
|
|
19
|
+
return _SECRET_RX.sub("[REDACTED]", text)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Auth:
|
|
23
|
+
def __init__(self, cfg: Config) -> None:
|
|
24
|
+
self.cfg = cfg
|
|
25
|
+
self.api_keys = read_keys(cfg.resolve(cfg.server.api_keys_file))
|
|
26
|
+
self.admin_keys = read_keys(cfg.resolve(cfg.server.admin_key_file))
|
|
27
|
+
|
|
28
|
+
@staticmethod
|
|
29
|
+
def _bearer(headers: dict[str, str]) -> str | None:
|
|
30
|
+
h = headers.get("authorization") or headers.get("Authorization")
|
|
31
|
+
if not h:
|
|
32
|
+
# Some clients send x-api-key.
|
|
33
|
+
return headers.get("x-api-key")
|
|
34
|
+
parts = h.split(None, 1)
|
|
35
|
+
if len(parts) == 2 and parts[0].lower() == "bearer":
|
|
36
|
+
return parts[1].strip()
|
|
37
|
+
return None
|
|
38
|
+
|
|
39
|
+
@staticmethod
|
|
40
|
+
def _match(token: str, keys: list[str]) -> bool:
|
|
41
|
+
t = token.encode("utf-8", "surrogateescape")
|
|
42
|
+
return any(hmac.compare_digest(t, k.encode("utf-8")) for k in keys)
|
|
43
|
+
|
|
44
|
+
def caller(self, headers: dict[str, str]) -> str | None:
|
|
45
|
+
"""Return a stable caller id (hash of the key) or None if unauthenticated."""
|
|
46
|
+
tok = self._bearer(headers)
|
|
47
|
+
if not tok:
|
|
48
|
+
return None
|
|
49
|
+
if self._match(tok, self.api_keys) or self._match(tok, self.admin_keys):
|
|
50
|
+
return hashlib.sha256(tok.encode()).hexdigest()[:12]
|
|
51
|
+
return None
|
|
52
|
+
|
|
53
|
+
def is_admin(self, headers: dict[str, str]) -> bool:
|
|
54
|
+
tok = self._bearer(headers)
|
|
55
|
+
return bool(tok) and self._match(tok, self.admin_keys)
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def configured(self) -> bool:
|
|
59
|
+
return bool(self.api_keys) and bool(self.admin_keys)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def key_paths(cfg: Config) -> tuple[Path, Path]:
|
|
63
|
+
return cfg.resolve(cfg.server.api_keys_file), cfg.resolve(cfg.server.admin_key_file)
|