datapi-selfheal 0.3.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.
selfheal_api/server.py ADDED
@@ -0,0 +1,1480 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import csv
5
+ import hmac
6
+ import importlib
7
+ import io
8
+ import json
9
+ import logging
10
+ import os
11
+ import re
12
+ import signal
13
+ import threading
14
+ import time
15
+ import uuid
16
+ from collections import OrderedDict
17
+ from collections.abc import Callable, Mapping
18
+ from http import HTTPStatus
19
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
20
+ from pathlib import Path
21
+ from typing import Any
22
+ from urllib.parse import parse_qs, urlparse
23
+
24
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
25
+
26
+ from selfheal_api import server_hosted
27
+ from selfheal_api.autoheal import AutoHealWorker, HostedAutoHealRunner
28
+ from selfheal_api.billing import (
29
+ BillingStore,
30
+ StripeAPI,
31
+ handle_stripe_webhook,
32
+ )
33
+ from selfheal_api.dashboard import DashboardSnapshot, render_dashboard_html
34
+ from selfheal_api.github_app import (
35
+ GitHubAppAuth,
36
+ InstallationRegistry,
37
+ handle_github_webhook,
38
+ )
39
+ from selfheal_api.github_app import (
40
+ verify_webhook_signature as verify_webhook_signature,
41
+ )
42
+ from selfheal_api.ledger import DriftLedger
43
+ from selfheal_api.metrics import compute_remediation_metrics
44
+ from selfheal_api.notifier import (
45
+ AlertNotifier,
46
+ CompositeAlertNotifier,
47
+ DriftAlert,
48
+ EmailAlertNotifier,
49
+ PagerDutyNotifier,
50
+ SignedWebhookNotifier,
51
+ UrllibSlackNotifier,
52
+ )
53
+ from selfheal_api.server_hosted import HostedStateStore
54
+ from sentinel.detector import detect_drift
55
+ from sentinel.guard import DriftDeduplicator, compute_drift_fingerprint
56
+ from sentinel.llm_fallback import AnthropicSchemaMappingProvider
57
+ from synthesizer.patcher import PatchPlan, build_patch_plan
58
+ from synthesizer.zod_emitter import synthesize_zod_preprocessor
59
+
60
+ _logger = logging.getLogger("selfheal_api.server")
61
+
62
+ SERVER_VERSION = "0.2.0"
63
+ _ORG_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
64
+ _REQUEST_ID_RE = re.compile(r"^[A-Za-z0-9-]{1,64}$")
65
+
66
+
67
+ def _sanitize_csv_cell(value: str) -> str:
68
+ """Neutralize CSV formula injection for spreadsheet consumers."""
69
+ if value and value[0] in ("=", "+", "-", "@", "\t", "\r"):
70
+ return f"'{value}"
71
+ return value
72
+
73
+
74
+ def _parse_model_specs(raw: Any) -> list[str]:
75
+ if raw is None:
76
+ return []
77
+ if isinstance(raw, str):
78
+ return [part.strip() for part in raw.split(",") if part.strip()]
79
+ if isinstance(raw, list):
80
+ specs: list[str] = []
81
+ for item in raw:
82
+ if not isinstance(item, str):
83
+ raise ValueError("model_specs entries must be strings")
84
+ specs.extend(part.strip() for part in item.split(",") if part.strip())
85
+ return specs
86
+ raise ValueError("model_specs must be a list of strings or comma-separated string")
87
+
88
+
89
+ class TenantConfig(BaseModel):
90
+ model_config = ConfigDict(frozen=True)
91
+
92
+ webhook_secret: str = ""
93
+ api_secret: str = ""
94
+ stripe_webhook_secret: str = ""
95
+ github_webhook_secret: str = ""
96
+ max_requests_per_minute: int = Field(default=60, ge=1)
97
+ max_llm_calls_per_tenant: int = Field(default=20, ge=0)
98
+ max_fingerprints: int = Field(default=1024, ge=1)
99
+ enable_llm_fallback: bool = False
100
+
101
+
102
+ class ServerConfig(BaseModel):
103
+ model_config = ConfigDict(frozen=True)
104
+
105
+ host: str = "0.0.0.0"
106
+ port: int = Field(default=8080, ge=0, le=65535)
107
+ webhook_secret: str = ""
108
+ api_secret: str = ""
109
+ stripe_webhook_secret: str = ""
110
+ github_webhook_secret: str = ""
111
+ max_requests_per_minute: int = Field(default=60, ge=1)
112
+ max_llm_calls_per_tenant: int = Field(default=20, ge=0)
113
+ tenants: dict[str, TenantConfig] = Field(default_factory=dict)
114
+ allow_unregistered_tenants: bool = True
115
+ allow_admin_read_bypass: bool = False
116
+ include_zod_adapter: bool = True
117
+ max_body_bytes: int = Field(default=1_048_576, ge=1024)
118
+ db_path: str = ":memory:"
119
+ retention_days: int = Field(default=0, ge=0)
120
+ model_specs: list[str] = Field(default_factory=list)
121
+ slack_webhook_url: str = ""
122
+ alert_webhook_url: str = ""
123
+ alert_webhook_secret: str = ""
124
+
125
+ @field_validator("model_specs", mode="before")
126
+ @classmethod
127
+ def _validate_model_specs(cls, value: Any) -> list[str]:
128
+ return _parse_model_specs(value)
129
+
130
+ def default_tenant_config(self) -> TenantConfig:
131
+ opts: dict[str, Any] = {
132
+ "webhook_secret": self.webhook_secret,
133
+ "max_requests_per_minute": self.max_requests_per_minute,
134
+ "max_llm_calls_per_tenant": self.max_llm_calls_per_tenant,
135
+ }
136
+ return TenantConfig(**opts)
137
+
138
+
139
+ class DriftWebhookRequest(BaseModel):
140
+ model_config = ConfigDict(extra="forbid")
141
+
142
+ model: str = Field(min_length=1, max_length=128)
143
+ payload: dict[str, Any] | str
144
+ include_zod_adapter: bool | None = None
145
+
146
+
147
+ class TokenBucketRateLimiter:
148
+ """Thread-safe per-tenant token-bucket rate limiter."""
149
+
150
+ def __init__(
151
+ self,
152
+ max_requests_per_minute: int,
153
+ clock: Callable[[], float] = time.monotonic,
154
+ ) -> None:
155
+ if max_requests_per_minute < 1:
156
+ raise ValueError("max_requests_per_minute must be >= 1")
157
+ self._capacity = float(max_requests_per_minute)
158
+ self._tokens = float(max_requests_per_minute)
159
+ self._refill_rate = max_requests_per_minute / 60.0
160
+ self._clock = clock
161
+ self._last_refill = self._clock()
162
+ self._lock = threading.Lock()
163
+
164
+ def allow(self) -> bool:
165
+ with self._lock:
166
+ now = self._clock()
167
+ elapsed = max(0.0, now - self._last_refill)
168
+ self._tokens = min(
169
+ self._capacity, self._tokens + elapsed * self._refill_rate
170
+ )
171
+ self._last_refill = now
172
+ if self._tokens >= 1.0:
173
+ self._tokens -= 1.0
174
+ return True
175
+ return False
176
+
177
+ def update_limit(self, max_requests_per_minute: int) -> None:
178
+ if max_requests_per_minute < 1:
179
+ raise ValueError("max_requests_per_minute must be >= 1")
180
+ with self._lock:
181
+ old_capacity = self._capacity
182
+ new_capacity = float(max_requests_per_minute)
183
+ if new_capacity != old_capacity:
184
+ self._capacity = new_capacity
185
+ self._refill_rate = max_requests_per_minute / 60.0
186
+ if new_capacity > old_capacity:
187
+ self._tokens = min(
188
+ self._capacity,
189
+ self._tokens + (new_capacity - old_capacity),
190
+ )
191
+ else:
192
+ self._tokens = min(self._tokens, self._capacity)
193
+
194
+
195
+ class TenantState:
196
+ """Isolated per-tenant runtime state (deduplicator, rate limiter, LLM cap)."""
197
+
198
+ def __init__(
199
+ self,
200
+ org_id: str,
201
+ config: TenantConfig,
202
+ *,
203
+ pinned: bool = False,
204
+ ) -> None:
205
+ self.org_id = org_id
206
+ self.config = config
207
+ self.pinned = pinned
208
+ self.deduplicator = DriftDeduplicator(max_fingerprints=config.max_fingerprints)
209
+ self.rate_limiter = TokenBucketRateLimiter(
210
+ max_requests_per_minute=config.max_requests_per_minute
211
+ )
212
+ self.mapping_provider: AnthropicSchemaMappingProvider | None = (
213
+ AnthropicSchemaMappingProvider(max_calls=config.max_llm_calls_per_tenant)
214
+ if config.enable_llm_fallback
215
+ else None
216
+ )
217
+
218
+ def apply_limits(self, max_requests_per_minute: int, max_llm_calls: int) -> None:
219
+ """Apply updated plan limits immediately to this tenant's runtime state."""
220
+ self.rate_limiter.update_limit(max_requests_per_minute)
221
+ if self.mapping_provider is not None:
222
+ self.mapping_provider.set_max_calls(max_llm_calls)
223
+
224
+
225
+ class TenantRegistry:
226
+ """Thread-safe registry maintaining strict per-org_id isolation."""
227
+
228
+ def __init__(self, config: ServerConfig, max_tenants: int = 4096) -> None:
229
+ if max_tenants < 1:
230
+ raise ValueError("max_tenants must be >= 1")
231
+ self._config = config
232
+ self._max_tenants = max_tenants
233
+ self._lock = threading.Lock()
234
+ self._pinned: dict[str, TenantState] = {
235
+ org_id: TenantState(org_id=org_id, config=tenant_cfg, pinned=True)
236
+ for org_id, tenant_cfg in config.tenants.items()
237
+ }
238
+ self._dynamic: OrderedDict[str, TenantState] = OrderedDict()
239
+
240
+ def get_or_create(self, org_id: str) -> TenantState | None:
241
+ with self._lock:
242
+ pinned = self._pinned.get(org_id)
243
+ if pinned is not None:
244
+ return pinned
245
+ existing = self._dynamic.get(org_id)
246
+ if existing is not None:
247
+ self._dynamic.move_to_end(org_id)
248
+ return existing
249
+ if not self._config.allow_unregistered_tenants:
250
+ return None
251
+ dynamic_cap = self._max_tenants - len(self._pinned)
252
+ if dynamic_cap <= 0:
253
+ return None
254
+ while len(self._dynamic) >= dynamic_cap:
255
+ self._dynamic.popitem(last=False)
256
+ state = TenantState(
257
+ org_id=org_id,
258
+ config=self._config.default_tenant_config(),
259
+ pinned=False,
260
+ )
261
+ self._dynamic[org_id] = state
262
+ return state
263
+
264
+ def get_tenant(self, org_id: str) -> TenantState | None:
265
+ with self._lock:
266
+ pinned = self._pinned.get(org_id)
267
+ if pinned is not None:
268
+ return pinned
269
+ return self._dynamic.get(org_id)
270
+
271
+ def list_org_ids(self) -> list[str]:
272
+ with self._lock:
273
+ return sorted(set(self._pinned.keys()) | set(self._dynamic.keys()))
274
+
275
+
276
+ class SelfHealHTTPServer(ThreadingHTTPServer):
277
+ allow_reuse_address = True
278
+ daemon_threads = True
279
+
280
+ def __init__(
281
+ self,
282
+ server_address: tuple[str, int],
283
+ RequestHandlerClass: type[BaseHTTPRequestHandler],
284
+ config: ServerConfig,
285
+ registry: TenantRegistry,
286
+ model_registry: Mapping[str, type[BaseModel]],
287
+ billing_store: BillingStore | None = None,
288
+ installation_registry: InstallationRegistry | None = None,
289
+ drift_ledger: DriftLedger | None = None,
290
+ notifier: AlertNotifier | None = None,
291
+ hosted_store: HostedStateStore | None = None,
292
+ github_app_slug: str | None = None,
293
+ state_secret: str = "",
294
+ github_app_auth: Any | None = None,
295
+ stripe_api: Any | None = None,
296
+ stripe_price_ids: dict[str, str] | None = None,
297
+ public_base_url: str = "http://127.0.0.1:8080",
298
+ jobs_token: str = "",
299
+ email_notifier: Any | None = None,
300
+ auto_heal_worker: AutoHealWorker | None = None,
301
+ ) -> None:
302
+ self.config = config
303
+ self.registry = registry
304
+ self.model_registry: dict[str, type[BaseModel]] = dict(model_registry)
305
+ self.billing_store = billing_store or BillingStore()
306
+ self.installation_registry = installation_registry or InstallationRegistry()
307
+ self.drift_ledger = drift_ledger or DriftLedger()
308
+ self.notifier = notifier
309
+ self.hosted_store = hosted_store or HostedStateStore()
310
+ self.github_app_slug = github_app_slug
311
+ self.state_secret = state_secret
312
+ self.github_app_auth = github_app_auth
313
+ self.stripe_api = stripe_api
314
+ self.stripe_price_ids = stripe_price_ids or {}
315
+ self.public_base_url = public_base_url.rstrip("/")
316
+ self.jobs_token = jobs_token
317
+ self.email_notifier = email_notifier
318
+ self.auto_heal_worker = auto_heal_worker
319
+ super().__init__(server_address, RequestHandlerClass)
320
+
321
+
322
+ class SelfHealRequestHandler(BaseHTTPRequestHandler):
323
+ server: SelfHealHTTPServer
324
+ timeout = 10.0
325
+
326
+ def _verify_read_secret(self, secret: str, org_id: str) -> bool:
327
+ auth_hdr = self.headers.get("Authorization", "").strip()
328
+ if auth_hdr.startswith("Bearer ") and hmac.compare_digest(
329
+ auth_hdr[7:].strip(), secret
330
+ ):
331
+ return True
332
+ sig_hdr = (
333
+ self.headers.get("X-Hub-Signature-256")
334
+ or self.headers.get("X-SelfHeal-Signature")
335
+ or ""
336
+ )
337
+ return verify_webhook_signature(secret, org_id.encode("utf-8"), sig_hdr)
338
+
339
+ def _authorize_tenant_read(self, org_id: str) -> bool:
340
+ is_multi_tenant = (
341
+ len(self.server.config.tenants) > 0
342
+ or not self.server.config.allow_unregistered_tenants
343
+ )
344
+ server_secret = (
345
+ self.server.config.api_secret or self.server.config.webhook_secret
346
+ )
347
+ tenant = self.server.registry.get_tenant(org_id)
348
+
349
+ if tenant is not None:
350
+ tenant_secret = (
351
+ tenant.config.api_secret or tenant.config.webhook_secret
352
+ )
353
+ if tenant.pinned or tenant.config.api_secret:
354
+ if tenant_secret:
355
+ return self._verify_read_secret(tenant_secret, org_id)
356
+ if is_multi_tenant:
357
+ if self.server.config.allow_admin_read_bypass and server_secret:
358
+ return self._verify_read_secret(server_secret, org_id)
359
+ return False
360
+ return not server_secret or self._verify_read_secret(
361
+ server_secret, org_id
362
+ )
363
+
364
+ # Unpinned dynamic tenant without its own api_secret
365
+ if is_multi_tenant:
366
+ if self.server.config.allow_admin_read_bypass and server_secret:
367
+ return self._verify_read_secret(server_secret, org_id)
368
+ return False
369
+ if not server_secret:
370
+ return True
371
+ return self._verify_read_secret(server_secret, org_id)
372
+
373
+ # Unknown / unconfigured tenant
374
+ if is_multi_tenant:
375
+ if self.server.config.allow_admin_read_bypass and server_secret:
376
+ return self._verify_read_secret(server_secret, org_id)
377
+ return False
378
+ if not server_secret:
379
+ return True
380
+ return self._verify_read_secret(server_secret, org_id)
381
+
382
+ def log_message(self, format: str, *args: Any) -> None:
383
+ _logger.info("%s - %s", self.address_string(), format % args)
384
+
385
+ def _get_request_id(self) -> str:
386
+ cached: str | None = getattr(self, "_request_id", None)
387
+ if cached is not None:
388
+ return cached
389
+ raw_hdr = self.headers.get("X-Request-Id", "").strip()
390
+ if raw_hdr and _REQUEST_ID_RE.match(raw_hdr):
391
+ request_id = raw_hdr
392
+ else:
393
+ request_id = uuid.uuid4().hex[:16]
394
+ self._request_id = request_id
395
+ return request_id
396
+
397
+ def _send_json(
398
+ self,
399
+ status: HTTPStatus,
400
+ payload: dict[str, Any],
401
+ extra_headers: Mapping[str, str] | None = None,
402
+ ) -> None:
403
+ body = json.dumps(payload).encode("utf-8")
404
+ self.send_response(status.value)
405
+ self.send_header("Content-Type", "application/json; charset=utf-8")
406
+ self.send_header("Content-Length", str(len(body)))
407
+ self.send_header("X-Request-Id", self._get_request_id())
408
+ self.send_header("X-Content-Type-Options", "nosniff")
409
+ self.send_header("Cache-Control", "no-store")
410
+ if extra_headers:
411
+ for k, v in extra_headers.items():
412
+ self.send_header(k, v)
413
+ self.end_headers()
414
+ self.wfile.write(body)
415
+
416
+ def _send_html(self, status: HTTPStatus, html_body: str) -> None:
417
+ body = html_body.encode("utf-8")
418
+ self.send_response(status.value)
419
+ self.send_header("Content-Type", "text/html; charset=utf-8")
420
+ self.send_header("Content-Length", str(len(body)))
421
+ self.send_header("X-Request-Id", self._get_request_id())
422
+ self.send_header("X-Content-Type-Options", "nosniff")
423
+ self.send_header("X-Frame-Options", "DENY")
424
+ self.send_header(
425
+ "Content-Security-Policy",
426
+ "default-src 'none'; style-src 'unsafe-inline'",
427
+ )
428
+ self.end_headers()
429
+ self.wfile.write(body)
430
+
431
+ def _send_text(
432
+ self,
433
+ status: HTTPStatus,
434
+ text_body: str,
435
+ content_type: str = "text/plain; charset=utf-8",
436
+ extra_headers: Mapping[str, str] | None = None,
437
+ ) -> None:
438
+ body = text_body.encode("utf-8")
439
+ self.send_response(status.value)
440
+ self.send_header("Content-Type", content_type)
441
+ self.send_header("Content-Length", str(len(body)))
442
+ self.send_header("X-Request-Id", self._get_request_id())
443
+ if extra_headers:
444
+ for k, v in extra_headers.items():
445
+ self.send_header(k, v)
446
+ self.end_headers()
447
+ self.wfile.write(body)
448
+
449
+ def _format_prometheus_metrics(self) -> str:
450
+ tenants_active = len(self.server.registry.list_org_ids())
451
+ installations_active = len(self.server.installation_registry.list_org_ids())
452
+ subscriptions_active = len(self.server.billing_store.list_org_ids())
453
+ totals = self.server.drift_ledger.global_totals()
454
+ lines = [
455
+ "# HELP selfheal_tenants_active Number of active tenant states",
456
+ "# TYPE selfheal_tenants_active gauge",
457
+ f"selfheal_tenants_active {tenants_active}",
458
+ "# HELP selfheal_installations_active Number of active GitHub installations",
459
+ "# TYPE selfheal_installations_active gauge",
460
+ f"selfheal_installations_active {installations_active}",
461
+ "# HELP selfheal_subscriptions_active Number of active billing subscriptions",
462
+ "# TYPE selfheal_subscriptions_active gauge",
463
+ f"selfheal_subscriptions_active {subscriptions_active}",
464
+ "# HELP selfheal_drift_events_total Total drift webhook events recorded",
465
+ "# TYPE selfheal_drift_events_total counter",
466
+ f"selfheal_drift_events_total {totals['total_events']}",
467
+ "# HELP selfheal_drifted_events_total Total drift events with detected drift",
468
+ "# TYPE selfheal_drifted_events_total counter",
469
+ f"selfheal_drifted_events_total {totals['drifted_events']}",
470
+ "# HELP selfheal_prs_opened_total Total remediation PRs opened",
471
+ "# TYPE selfheal_prs_opened_total counter",
472
+ f"selfheal_prs_opened_total {totals['prs_opened']}",
473
+ ]
474
+ try:
475
+ runs = self.server.hosted_store.list_all_repair_runs(limit=1000)
476
+ events = self.server.drift_ledger.list_events(limit=1000)
477
+ rm = compute_remediation_metrics(runs, events)
478
+ except Exception: # noqa: BLE001 - metrics must never 500
479
+ _logger.exception("remediation metrics rollup failed")
480
+ rm = None
481
+ if rm is not None:
482
+ lines.extend(
483
+ [
484
+ "# HELP selfheal_repair_runs_total Auto-heal runs by status",
485
+ "# TYPE selfheal_repair_runs_total counter",
486
+ f"selfheal_repair_runs_total{{status=\"pr_opened\"}} {rm.pr_opened}",
487
+ f"selfheal_repair_runs_total{{status=\"escalated\"}} {rm.escalated}",
488
+ f"selfheal_repair_runs_total{{status=\"failed\"}} {rm.failed}",
489
+ f"selfheal_repair_runs_total{{status=\"reverted\"}} {rm.reverted}",
490
+ "# HELP selfheal_patch_correctness_ratio Verified patches / decided runs",
491
+ "# TYPE selfheal_patch_correctness_ratio gauge",
492
+ "selfheal_patch_correctness_ratio "
493
+ f"{rm.patch_correctness if rm.patch_correctness is not None else 'NaN'}",
494
+ "# HELP selfheal_regression_rate_ratio Reverted PRs / opened PRs",
495
+ "# TYPE selfheal_regression_rate_ratio gauge",
496
+ "selfheal_regression_rate_ratio "
497
+ f"{rm.regression_rate if rm.regression_rate is not None else 'NaN'}",
498
+ "# HELP selfheal_ttr_seconds_mean Mean drift-event to PR-open seconds",
499
+ "# TYPE selfheal_ttr_seconds_mean gauge",
500
+ "selfheal_ttr_seconds_mean "
501
+ f"{rm.ttr_seconds_mean if rm.ttr_seconds_mean is not None else 'NaN'}",
502
+ ]
503
+ )
504
+ lines.append("")
505
+ return "\n".join(lines)
506
+
507
+ def _query_org_id(self, query: dict[str, list[str]]) -> str:
508
+ org_vals = query.get("org_id")
509
+ if org_vals and org_vals[0].strip():
510
+ return org_vals[0].strip()
511
+ hdr = self.headers.get("X-SelfHeal-Org", "").strip()
512
+ return hdr or "default"
513
+
514
+ def do_HEAD(self) -> None:
515
+ path = urlparse(self.path).path
516
+ if path == "/healthz":
517
+ self.send_response(HTTPStatus.OK.value)
518
+ self.send_header("Content-Type", "application/json; charset=utf-8")
519
+ self.send_header("X-Request-Id", self._get_request_id())
520
+ self.send_header("X-Content-Type-Options", "nosniff")
521
+ self.end_headers()
522
+ return
523
+ if path == "/readyz":
524
+ healthy = (
525
+ self.server.drift_ledger.ping()
526
+ and self.server.billing_store.ping()
527
+ and self.server.installation_registry.ping()
528
+ )
529
+ status = HTTPStatus.OK if healthy else HTTPStatus.SERVICE_UNAVAILABLE
530
+ self.send_response(status.value)
531
+ self.send_header("Content-Type", "application/json; charset=utf-8")
532
+ self.send_header("X-Request-Id", self._get_request_id())
533
+ self.send_header("X-Content-Type-Options", "nosniff")
534
+ self.end_headers()
535
+ return
536
+ self.send_response(HTTPStatus.NOT_FOUND.value)
537
+ self.send_header("X-Request-Id", self._get_request_id())
538
+ self.end_headers()
539
+
540
+ def do_GET(self) -> None:
541
+ if server_hosted.dispatch(self):
542
+ return
543
+ parsed_url = urlparse(self.path)
544
+ path = parsed_url.path
545
+ query = parse_qs(parsed_url.query)
546
+ if path == "/healthz":
547
+ self._send_json(
548
+ HTTPStatus.OK,
549
+ {"status": "ok", "version": SERVER_VERSION},
550
+ )
551
+ return
552
+ if path == "/readyz":
553
+ stores = {
554
+ "ledger": self.server.drift_ledger.ping(),
555
+ "billing": self.server.billing_store.ping(),
556
+ "installations": self.server.installation_registry.ping(),
557
+ }
558
+ if all(stores.values()):
559
+ self._send_json(HTTPStatus.OK, {"status": "ready", "stores": stores})
560
+ else:
561
+ self._send_json(
562
+ HTTPStatus.SERVICE_UNAVAILABLE,
563
+ {"status": "unavailable", "stores": stores},
564
+ )
565
+ return
566
+ if path == "/openapi.json":
567
+ schemas: dict[str, Any] = {
568
+ name: cls.model_json_schema()
569
+ for name, cls in sorted(self.server.model_registry.items())
570
+ }
571
+ openapi_doc: dict[str, Any] = {
572
+ "openapi": "3.1.0",
573
+ "info": {
574
+ "title": "Datapi SelfHeal Control Plane",
575
+ "version": SERVER_VERSION,
576
+ },
577
+ "paths": {
578
+ "/healthz": {"get": {"summary": "Liveness probe"}},
579
+ "/readyz": {"get": {"summary": "Readiness probe across SQLite stores"}},
580
+ "/metrics": {"get": {"summary": "JSON or Prometheus metrics"}},
581
+ "/openapi.json": {"get": {"summary": "OpenAPI 3.1.0 specification"}},
582
+ "/api/v1/events": {"get": {"summary": "Paginated zero-PII drift events"}},
583
+ "/api/v1/events/export": {
584
+ "get": {"summary": "Export zero-PII drift events (CSV/JSONL)"}
585
+ },
586
+ "/api/v1/summary": {"get": {"summary": "Tenant drift summary"}},
587
+ "/dashboard": {"get": {"summary": "Self-contained HTML Drift Console"}},
588
+ "/webhooks/drift": {"post": {"summary": "Ingest drift payload"}},
589
+ "/webhooks/stripe": {"post": {"summary": "Stripe billing webhook"}},
590
+ "/webhooks/github": {"post": {"summary": "GitHub App webhook"}},
591
+ },
592
+ "components": {"schemas": schemas},
593
+ }
594
+ self._send_json(HTTPStatus.OK, openapi_doc)
595
+ return
596
+ if path == "/metrics":
597
+ fmt_vals = query.get("format")
598
+ if fmt_vals and fmt_vals[0].strip().lower() == "prometheus":
599
+ self._send_text(
600
+ HTTPStatus.OK,
601
+ self._format_prometheus_metrics(),
602
+ content_type="text/plain; version=0.0.4; charset=utf-8",
603
+ )
604
+ return
605
+ payload: dict[str, Any] = {
606
+ "version": SERVER_VERSION,
607
+ "tenants_active": len(self.server.registry.list_org_ids()),
608
+ "installations_active": len(
609
+ self.server.installation_registry.list_org_ids()
610
+ ),
611
+ "subscriptions_active": len(
612
+ self.server.billing_store.list_org_ids()
613
+ ),
614
+ }
615
+ try:
616
+ runs = self.server.hosted_store.list_all_repair_runs(limit=1000)
617
+ events = self.server.drift_ledger.list_events(limit=1000)
618
+ payload["remediation"] = compute_remediation_metrics(
619
+ runs, events
620
+ ).as_dict()
621
+ except Exception: # noqa: BLE001 - metrics must never 500
622
+ _logger.exception("remediation metrics rollup failed")
623
+ self._send_json(HTTPStatus.OK, payload)
624
+ return
625
+ if path == "/api/v1/events":
626
+ org_id = self._query_org_id(query)
627
+ if not self._authorize_tenant_read(org_id):
628
+ self._send_json(
629
+ HTTPStatus.UNAUTHORIZED, {"error": "unauthorized tenant read"}
630
+ )
631
+ return
632
+ try:
633
+ limit_raw = (query.get("limit") or ["50"])[0].strip()
634
+ offset_raw = (query.get("offset") or ["0"])[0].strip()
635
+ limit = int(limit_raw)
636
+ offset = int(offset_raw)
637
+ except ValueError:
638
+ self._send_json(
639
+ HTTPStatus.BAD_REQUEST,
640
+ {"error": "limit and offset must be integers"},
641
+ )
642
+ return
643
+ if limit < 1 or limit > 200 or offset < 0:
644
+ self._send_json(
645
+ HTTPStatus.BAD_REQUEST,
646
+ {"error": "limit must be in 1..200 and offset >= 0"},
647
+ )
648
+ return
649
+ model_vals = query.get("model")
650
+ model_filter = (
651
+ model_vals[0].strip() if model_vals and model_vals[0].strip() else None
652
+ )
653
+ events = self.server.drift_ledger.list_events(
654
+ org_id=org_id,
655
+ model_name=model_filter,
656
+ limit=limit,
657
+ offset=offset,
658
+ )
659
+ self._send_json(
660
+ HTTPStatus.OK,
661
+ {
662
+ "org_id": org_id,
663
+ "limit": limit,
664
+ "offset": offset,
665
+ "events": [ev.model_dump(mode="json") for ev in events],
666
+ },
667
+ )
668
+ return
669
+ if path == "/api/v1/events/export":
670
+ org_id = self._query_org_id(query)
671
+ if not self._authorize_tenant_read(org_id):
672
+ self._send_json(
673
+ HTTPStatus.UNAUTHORIZED, {"error": "unauthorized tenant read"}
674
+ )
675
+ return
676
+ fmt = (query.get("format") or ["csv"])[0].strip().lower()
677
+ if fmt not in {"csv", "jsonl"}:
678
+ self._send_json(
679
+ HTTPStatus.BAD_REQUEST,
680
+ {"error": "format must be 'csv' or 'jsonl'"},
681
+ )
682
+ return
683
+ try:
684
+ limit_raw = (query.get("limit") or ["200"])[0].strip()
685
+ offset_raw = (query.get("offset") or ["0"])[0].strip()
686
+ limit = int(limit_raw)
687
+ offset = int(offset_raw)
688
+ except ValueError:
689
+ self._send_json(
690
+ HTTPStatus.BAD_REQUEST,
691
+ {"error": "limit and offset must be integers"},
692
+ )
693
+ return
694
+ if limit < 1 or limit > 1000 or offset < 0:
695
+ self._send_json(
696
+ HTTPStatus.BAD_REQUEST,
697
+ {"error": "limit must be in 1..1000 and offset >= 0"},
698
+ )
699
+ return
700
+ model_vals = query.get("model")
701
+ model_filter = (
702
+ model_vals[0].strip() if model_vals and model_vals[0].strip() else None
703
+ )
704
+ events = self.server.drift_ledger.list_events(
705
+ org_id=org_id,
706
+ model_name=model_filter,
707
+ limit=limit,
708
+ offset=offset,
709
+ )
710
+ safe_org = re.sub(r"[^A-Za-z0-9_.-]+", "_", org_id) or "default"
711
+ extra_headers = {
712
+ "Content-Disposition": (
713
+ f'attachment; filename="drift-events-{safe_org}.{fmt}"'
714
+ ),
715
+ "X-Content-Type-Options": "nosniff",
716
+ "Cache-Control": "no-store",
717
+ }
718
+ if fmt == "jsonl":
719
+ lines = [json.dumps(ev.model_dump(mode="json")) for ev in events]
720
+ body_text = "\n".join(lines) + ("\n" if lines else "")
721
+ self._send_text(
722
+ HTTPStatus.OK,
723
+ body_text,
724
+ content_type="application/x-ndjson; charset=utf-8",
725
+ extra_headers=extra_headers,
726
+ )
727
+ return
728
+
729
+ csv_buf = io.StringIO(newline="")
730
+ writer = csv.writer(csv_buf, lineterminator="\r\n")
731
+ writer.writerow(
732
+ [
733
+ "event_id",
734
+ "created_at",
735
+ "org_id",
736
+ "model_name",
737
+ "fingerprint",
738
+ "has_drift",
739
+ "issue_count",
740
+ "issue_kinds",
741
+ "pr_url",
742
+ ]
743
+ )
744
+ for ev in events:
745
+ writer.writerow(
746
+ [
747
+ "" if ev.event_id is None else ev.event_id,
748
+ ev.created_at,
749
+ _sanitize_csv_cell(ev.org_id),
750
+ _sanitize_csv_cell(ev.model_name),
751
+ _sanitize_csv_cell(ev.fingerprint),
752
+ ev.has_drift,
753
+ ev.issue_count,
754
+ _sanitize_csv_cell(",".join(ev.issue_kinds)),
755
+ _sanitize_csv_cell(ev.pr_url or ""),
756
+ ]
757
+ )
758
+ self._send_text(
759
+ HTTPStatus.OK,
760
+ csv_buf.getvalue(),
761
+ content_type="text/csv; charset=utf-8",
762
+ extra_headers=extra_headers,
763
+ )
764
+ return
765
+ if path == "/api/v1/summary":
766
+ org_id = self._query_org_id(query)
767
+ if not self._authorize_tenant_read(org_id):
768
+ self._send_json(
769
+ HTTPStatus.UNAUTHORIZED, {"error": "unauthorized tenant read"}
770
+ )
771
+ return
772
+ summary = self.server.drift_ledger.get_org_summary(org_id)
773
+ self._send_json(HTTPStatus.OK, summary.model_dump(mode="json"))
774
+ return
775
+ if path == "/dashboard":
776
+ org_id = self._query_org_id(query)
777
+ if not self._authorize_tenant_read(org_id):
778
+ self._send_json(
779
+ HTTPStatus.UNAUTHORIZED, {"error": "unauthorized tenant read"}
780
+ )
781
+ return
782
+ status_vals = query.get("status")
783
+ status_filter = (
784
+ status_vals[0].strip().lower()
785
+ if status_vals and status_vals[0].strip()
786
+ else "all"
787
+ )
788
+ if status_filter not in {"all", "drifted", "ok"}:
789
+ self._send_json(
790
+ HTTPStatus.BAD_REQUEST,
791
+ {"error": "status must be 'all', 'drifted', or 'ok'"},
792
+ )
793
+ return
794
+ sub = self.server.billing_store.get_subscription(org_id)
795
+ limits = self.server.billing_store.get_limits(org_id)
796
+ summary = self.server.drift_ledger.get_org_summary(org_id)
797
+ fetch_limit = 15 if status_filter == "all" else 100
798
+ events = self.server.drift_ledger.list_events(
799
+ org_id=org_id, limit=fetch_limit
800
+ )
801
+ if status_filter == "drifted":
802
+ events = [ev for ev in events if ev.has_drift][:15]
803
+ elif status_filter == "ok":
804
+ events = [ev for ev in events if not ev.has_drift][:15]
805
+ snap = DashboardSnapshot(
806
+ org_id=org_id,
807
+ plan=str(sub.plan),
808
+ requests_per_minute_limit=limits.max_requests_per_minute,
809
+ llm_calls_limit=limits.max_llm_calls,
810
+ total_events=summary.total_events,
811
+ drifted_events=summary.drifted_events,
812
+ unique_fingerprints=summary.unique_fingerprints,
813
+ prs_opened=summary.prs_opened,
814
+ recent_events=[ev.model_dump(mode="json") for ev in events],
815
+ status_filter=status_filter,
816
+ )
817
+ self._send_html(HTTPStatus.OK, render_dashboard_html(snap))
818
+ return
819
+ self._send_json(HTTPStatus.NOT_FOUND, {"error": "not found"})
820
+
821
+ def do_POST(self) -> None:
822
+ if server_hosted.dispatch(self):
823
+ return
824
+ path = self.path.split("?", 1)[0]
825
+ if path == "/webhooks/drift":
826
+ self._handle_drift_webhook()
827
+ return
828
+ if path == "/webhooks/stripe":
829
+ self._handle_stripe_webhook_route()
830
+ return
831
+ if path == "/webhooks/github":
832
+ self._handle_github_webhook_route()
833
+ return
834
+ self._send_json(HTTPStatus.NOT_FOUND, {"error": "not found"})
835
+
836
+ def do_PATCH(self) -> None:
837
+ if server_hosted.dispatch(self):
838
+ return
839
+ self._send_json(HTTPStatus.NOT_FOUND, {"error": "not found"})
840
+
841
+ def do_DELETE(self) -> None:
842
+ if server_hosted.dispatch(self):
843
+ return
844
+ self._send_json(HTTPStatus.NOT_FOUND, {"error": "not found"})
845
+
846
+ def _sync_tenant_limits(self, org_id: str, tenant: TenantState | None = None) -> None:
847
+ target = tenant or self.server.registry.get_tenant(org_id)
848
+ if target is None:
849
+ return
850
+ if org_id in self.server.billing_store.list_org_ids():
851
+ limits = self.server.billing_store.get_limits(org_id)
852
+ target.apply_limits(limits.max_requests_per_minute, limits.max_llm_calls)
853
+
854
+ def _handle_stripe_webhook_route(self) -> None:
855
+ raw_body = self._read_body()
856
+ if raw_body is None:
857
+ return
858
+ sig_header = self.headers.get("Stripe-Signature", "")
859
+ code, payload = handle_stripe_webhook(
860
+ self.server.config.stripe_webhook_secret,
861
+ raw_body,
862
+ sig_header,
863
+ self.server.billing_store,
864
+ )
865
+ if code == HTTPStatus.OK.value:
866
+ org_id = payload.get("org_id")
867
+ if isinstance(org_id, str) and org_id:
868
+ self._sync_tenant_limits(org_id)
869
+ self._send_json(HTTPStatus(code), payload)
870
+
871
+ def _handle_github_webhook_route(self) -> None:
872
+ raw_body = self._read_body()
873
+ if raw_body is None:
874
+ return
875
+ sig_header = self.headers.get("X-Hub-Signature-256", "")
876
+ event_type = self.headers.get("X-GitHub-Event", "")
877
+ code, payload = handle_github_webhook(
878
+ self.server.config.github_webhook_secret,
879
+ raw_body,
880
+ sig_header,
881
+ event_type,
882
+ self.server.installation_registry,
883
+ )
884
+ self._send_json(HTTPStatus(code), payload)
885
+
886
+ def _read_body(self) -> bytes | None:
887
+ raw_len = self.headers.get("Content-Length")
888
+ if raw_len is None:
889
+ self._send_json(
890
+ HTTPStatus.BAD_REQUEST, {"error": "missing Content-Length header"}
891
+ )
892
+ return None
893
+ try:
894
+ content_length = int(raw_len)
895
+ except ValueError:
896
+ self._send_json(
897
+ HTTPStatus.BAD_REQUEST, {"error": "invalid Content-Length header"}
898
+ )
899
+ return None
900
+ if content_length < 0:
901
+ self._send_json(
902
+ HTTPStatus.BAD_REQUEST, {"error": "invalid Content-Length header"}
903
+ )
904
+ return None
905
+ if content_length > self.server.config.max_body_bytes:
906
+ self._send_json(
907
+ HTTPStatus.REQUEST_ENTITY_TOO_LARGE,
908
+ {"error": "request body exceeds maximum allowed size"},
909
+ )
910
+ return None
911
+ return self.rfile.read(content_length)
912
+
913
+ @staticmethod
914
+ def _auto_heal_payload(req: DriftWebhookRequest) -> dict[str, Any] | None:
915
+ """Return the drift payload as a dict, or None when not object-shaped."""
916
+ payload = req.payload
917
+ if isinstance(payload, dict):
918
+ return payload
919
+ if isinstance(payload, str):
920
+ try:
921
+ parsed = json.loads(payload)
922
+ except json.JSONDecodeError:
923
+ return None
924
+ return parsed if isinstance(parsed, dict) else None
925
+ return None
926
+
927
+ def _try_enqueue_auto_heal(
928
+ self, org_id: str, model_name: str, payload: dict[str, Any]
929
+ ) -> bool:
930
+ """Best-effort auto-heal enqueue; never breaks the webhook path."""
931
+ worker: AutoHealWorker | None = getattr(
932
+ self.server, "auto_heal_worker", None
933
+ )
934
+ if worker is None:
935
+ return False
936
+ try:
937
+ return worker.maybe_enqueue(org_id, model_name, payload)
938
+ except Exception:
939
+ _logger.exception(
940
+ "autoheal enqueue failed request_id pending org=%s model=%s",
941
+ org_id,
942
+ model_name,
943
+ )
944
+ return False
945
+
946
+ def _handle_drift_webhook(self) -> None:
947
+ org_id_raw = self.headers.get("X-SelfHeal-Org", "").strip()
948
+ if not org_id_raw or not _ORG_ID_RE.match(org_id_raw):
949
+ self._send_json(
950
+ HTTPStatus.BAD_REQUEST,
951
+ {"error": "missing or invalid X-SelfHeal-Org header"},
952
+ )
953
+ return
954
+
955
+ raw_body = self._read_body()
956
+ if raw_body is None:
957
+ return
958
+
959
+ existing_tenant = self.server.registry.get_tenant(org_id_raw)
960
+ if existing_tenant is None and not self.server.config.allow_unregistered_tenants:
961
+ self._send_json(
962
+ HTTPStatus.FORBIDDEN,
963
+ {"error": f"unknown organization: {org_id_raw}"},
964
+ )
965
+ return
966
+
967
+ expected_secret = (
968
+ existing_tenant.config.webhook_secret
969
+ if existing_tenant is not None
970
+ else self.server.config.webhook_secret
971
+ )
972
+ if expected_secret:
973
+ sig_header = (
974
+ self.headers.get("X-Hub-Signature-256")
975
+ or self.headers.get("X-SelfHeal-Signature")
976
+ or ""
977
+ )
978
+ if not verify_webhook_signature(expected_secret, raw_body, sig_header):
979
+ self._send_json(
980
+ HTTPStatus.UNAUTHORIZED,
981
+ {"error": "invalid or missing webhook signature"},
982
+ )
983
+ return
984
+
985
+ tenant = self.server.registry.get_or_create(org_id_raw)
986
+ if tenant is None:
987
+ if self.server.config.allow_unregistered_tenants:
988
+ self._send_json(
989
+ HTTPStatus.SERVICE_UNAVAILABLE,
990
+ {"error": "tenant capacity exceeded"},
991
+ )
992
+ else:
993
+ self._send_json(
994
+ HTTPStatus.FORBIDDEN,
995
+ {"error": f"unknown organization: {org_id_raw}"},
996
+ )
997
+ return
998
+
999
+ self._sync_tenant_limits(org_id_raw, tenant=tenant)
1000
+
1001
+ if not tenant.rate_limiter.allow():
1002
+ self._send_json(
1003
+ HTTPStatus.TOO_MANY_REQUESTS,
1004
+ {"error": "rate limit exceeded"},
1005
+ extra_headers={"Retry-After": "60"},
1006
+ )
1007
+ return
1008
+
1009
+ try:
1010
+ decoded = raw_body.decode("utf-8")
1011
+ parsed_json = json.loads(decoded)
1012
+ except (UnicodeDecodeError, json.JSONDecodeError):
1013
+ self._send_json(
1014
+ HTTPStatus.BAD_REQUEST, {"error": "invalid JSON request body"}
1015
+ )
1016
+ return
1017
+
1018
+ if not isinstance(parsed_json, dict):
1019
+ self._send_json(
1020
+ HTTPStatus.BAD_REQUEST, {"error": "request body must be a JSON object"}
1021
+ )
1022
+ return
1023
+
1024
+ try:
1025
+ req = DriftWebhookRequest.model_validate(parsed_json)
1026
+ except ValidationError as exc:
1027
+ self._send_json(
1028
+ HTTPStatus.BAD_REQUEST,
1029
+ {"error": "invalid webhook request schema", "details": exc.errors()},
1030
+ )
1031
+ return
1032
+
1033
+ auto_heal_payload = self._auto_heal_payload(req)
1034
+ expected_model = self.server.model_registry.get(req.model)
1035
+ if expected_model is None:
1036
+ if auto_heal_payload is not None and self._try_enqueue_auto_heal(
1037
+ org_id_raw, req.model, auto_heal_payload
1038
+ ):
1039
+ self._send_json(
1040
+ HTTPStatus.ACCEPTED,
1041
+ {
1042
+ "org_id": org_id_raw,
1043
+ "model": req.model,
1044
+ "status": "queued",
1045
+ "auto_heal": True,
1046
+ },
1047
+ )
1048
+ return
1049
+ self._send_json(
1050
+ HTTPStatus.NOT_FOUND,
1051
+ {"error": f"unknown model: {req.model}"},
1052
+ )
1053
+ return
1054
+
1055
+ request_id = self._get_request_id()
1056
+ try:
1057
+ pre_report = detect_drift(
1058
+ expected_model, req.payload, mapping_provider=None
1059
+ )
1060
+ pre_fp = compute_drift_fingerprint(pre_report)
1061
+
1062
+ is_new, cached_plan = tenant.deduplicator.begin(pre_fp)
1063
+ report = pre_report
1064
+ plan: PatchPlan | None = cached_plan
1065
+ if is_new:
1066
+ try:
1067
+ if pre_report.has_drift and tenant.mapping_provider is not None:
1068
+ report = detect_drift(
1069
+ expected_model,
1070
+ req.payload,
1071
+ mapping_provider=tenant.mapping_provider,
1072
+ )
1073
+ plan = build_patch_plan(report, root_model=expected_model)
1074
+ tenant.deduplicator.complete(pre_fp, plan)
1075
+ except Exception:
1076
+ tenant.deduplicator.abort(pre_fp)
1077
+ raise
1078
+ elif plan is None:
1079
+ plan = build_patch_plan(report, root_model=expected_model)
1080
+ fingerprint = compute_drift_fingerprint(report)
1081
+
1082
+ include_zod = (
1083
+ req.include_zod_adapter
1084
+ if req.include_zod_adapter is not None
1085
+ else self.server.config.include_zod_adapter
1086
+ )
1087
+ zod_adapter: str | None = None
1088
+ if include_zod and plan.actions:
1089
+ zod_adapter = synthesize_zod_preprocessor(plan)
1090
+
1091
+ issue_kinds = tuple(str(i.kind) for i in report.issues)
1092
+ self.server.drift_ledger.record_event(
1093
+ org_id=org_id_raw,
1094
+ model_name=req.model,
1095
+ fingerprint=fingerprint,
1096
+ has_drift=report.has_drift,
1097
+ issue_count=len(report.issues),
1098
+ issue_kinds=issue_kinds,
1099
+ )
1100
+ if report.has_drift and is_new and self.server.notifier is not None:
1101
+ self.server.notifier.notify(
1102
+ DriftAlert(
1103
+ org_id=org_id_raw,
1104
+ model_name=req.model,
1105
+ fingerprint=fingerprint,
1106
+ issue_count=len(report.issues),
1107
+ issue_kinds=issue_kinds,
1108
+ )
1109
+ )
1110
+ if report.has_drift and auto_heal_payload is not None:
1111
+ self._try_enqueue_auto_heal(
1112
+ org_id_raw, req.model, auto_heal_payload
1113
+ )
1114
+ except Exception:
1115
+ _logger.exception(
1116
+ "drift_webhook_failed request_id=%s org_id=%s model=%s",
1117
+ request_id,
1118
+ org_id_raw,
1119
+ req.model,
1120
+ )
1121
+ self._send_json(
1122
+ HTTPStatus.INTERNAL_SERVER_ERROR,
1123
+ {"error": "internal server error", "request_id": request_id},
1124
+ )
1125
+ return
1126
+
1127
+ _logger.info(
1128
+ "drift_webhook request_id=%s org_id=%s model=%s "
1129
+ "has_drift=%s fingerprint=%s deduplicated=%s",
1130
+ request_id,
1131
+ org_id_raw,
1132
+ req.model,
1133
+ report.has_drift,
1134
+ fingerprint,
1135
+ not is_new,
1136
+ )
1137
+
1138
+ self._send_json(
1139
+ HTTPStatus.OK,
1140
+ {
1141
+ "org_id": org_id_raw,
1142
+ "model": req.model,
1143
+ "has_drift": report.has_drift,
1144
+ "fingerprint": fingerprint,
1145
+ "deduplicated": not is_new,
1146
+ "issues": [issue.model_dump(mode="json") for issue in report.issues],
1147
+ "zod_adapter": zod_adapter,
1148
+ },
1149
+ )
1150
+
1151
+
1152
+ def _build_notifier_from_config(config: ServerConfig) -> AlertNotifier | None:
1153
+ notifiers: list[AlertNotifier] = []
1154
+ slack_url = config.slack_webhook_url.strip()
1155
+ if slack_url:
1156
+ notifiers.append(UrllibSlackNotifier(slack_url))
1157
+ webhook_url = config.alert_webhook_url.strip()
1158
+ if webhook_url:
1159
+ notifiers.append(
1160
+ SignedWebhookNotifier(
1161
+ webhook_url,
1162
+ signing_secret=config.alert_webhook_secret,
1163
+ )
1164
+ )
1165
+ if not notifiers:
1166
+ return None
1167
+ if len(notifiers) == 1:
1168
+ return notifiers[0]
1169
+ return CompositeAlertNotifier(notifiers)
1170
+
1171
+
1172
+ def create_server(
1173
+ host: str = "0.0.0.0",
1174
+ port: int = 8080,
1175
+ config: ServerConfig | None = None,
1176
+ model_registry: Mapping[str, type[BaseModel]] | None = None,
1177
+ notifier: AlertNotifier | None = None,
1178
+ ) -> SelfHealHTTPServer:
1179
+ resolved_config = config or ServerConfig(host=host, port=port)
1180
+ resolved_models: Mapping[str, type[BaseModel]]
1181
+ if model_registry is not None:
1182
+ resolved_models = model_registry
1183
+ elif resolved_config.model_specs:
1184
+ resolved_models = _load_model_registry(resolved_config.model_specs)
1185
+ else:
1186
+ resolved_models = {}
1187
+ resolved_notifier = (
1188
+ notifier if notifier is not None else _build_notifier_from_config(resolved_config)
1189
+ )
1190
+ registry = TenantRegistry(resolved_config)
1191
+ ledger = DriftLedger(db_path=resolved_config.db_path)
1192
+ if resolved_config.retention_days > 0:
1193
+ ledger.prune_older_than(resolved_config.retention_days * 86400.0)
1194
+ billing_store = BillingStore(db_path=resolved_config.db_path)
1195
+ installation_registry = InstallationRegistry(db_path=resolved_config.db_path)
1196
+ hosted_store = HostedStateStore(db_path=resolved_config.db_path)
1197
+ github_app_slug = os.environ.get("SELFHEAL_GITHUB_APP_SLUG", "").strip() or None
1198
+ state_secret = os.environ.get("SELFHEAL_STATE_SECRET", "")
1199
+ github_app_id = os.environ.get("SELFHEAL_GITHUB_APP_ID", "").strip()
1200
+ github_app_key = os.environ.get("SELFHEAL_GITHUB_APP_PRIVATE_KEY", "")
1201
+ github_app_auth: GitHubAppAuth | None = None
1202
+ if github_app_id and github_app_key:
1203
+ github_app_auth = GitHubAppAuth(
1204
+ app_id=github_app_id,
1205
+ private_key_pem=github_app_key,
1206
+ api_base_url=os.environ.get(
1207
+ "SELFHEAL_GITHUB_API_BASE_URL", "https://api.github.com"
1208
+ ),
1209
+ allow_insecure_http=os.environ.get(
1210
+ "SELFHEAL_GITHUB_API_INSECURE", ""
1211
+ ).lower()
1212
+ in {"1", "true", "yes"},
1213
+ )
1214
+ stripe_secret = os.environ.get("STRIPE_SECRET_KEY", "").strip()
1215
+ stripe_api: StripeAPI | None = None
1216
+ if stripe_secret:
1217
+ stripe_api = StripeAPI(
1218
+ secret_key=stripe_secret,
1219
+ api_base_url=os.environ.get(
1220
+ "STRIPE_API_BASE_URL", "https://api.stripe.com"
1221
+ ),
1222
+ allow_insecure_http=os.environ.get(
1223
+ "STRIPE_API_INSECURE", ""
1224
+ ).lower()
1225
+ in {"1", "true", "yes"},
1226
+ )
1227
+ stripe_price_ids = {
1228
+ "pro": os.environ.get("STRIPE_PRICE_PRO", "").strip(),
1229
+ "team": os.environ.get("STRIPE_PRICE_TEAM", "").strip(),
1230
+ }
1231
+ public_base_url = os.environ.get(
1232
+ "SELFHEAL_PUBLIC_BASE_URL", "http://127.0.0.1:8080"
1233
+ ).strip()
1234
+ jobs_token = os.environ.get("SELFHEAL_JOBS_TOKEN", "")
1235
+
1236
+ hosted_notifiers: list[AlertNotifier] = []
1237
+ email_notifier: EmailAlertNotifier | None = None
1238
+ smtp_host = os.environ.get("SELFHEAL_SMTP_HOST", "").strip()
1239
+ if smtp_host:
1240
+ def _email_recipient(org_id: str) -> str | None:
1241
+ rec = installation_registry.get_by_org(org_id)
1242
+ if rec is not None and rec.alert_email:
1243
+ return rec.alert_email
1244
+ return os.environ.get("SELFHEAL_ALERT_EMAIL", "").strip() or None
1245
+
1246
+ email_notifier = EmailAlertNotifier(
1247
+ smtp_host=smtp_host,
1248
+ smtp_port=int(os.environ.get("SELFHEAL_SMTP_PORT", "587")),
1249
+ smtp_user=os.environ.get("SELFHEAL_SMTP_USER", ""),
1250
+ smtp_password=os.environ.get("SELFHEAL_SMTP_PASS", ""),
1251
+ from_addr=(
1252
+ os.environ.get("SELFHEAL_SMTP_FROM", "").strip()
1253
+ or os.environ.get("SELFHEAL_SMTP_USER", "")
1254
+ ),
1255
+ recipient=_email_recipient,
1256
+ use_starttls=os.environ.get("SELFHEAL_SMTP_STARTTLS", "1")
1257
+ not in {"0", "false", "no"},
1258
+ )
1259
+ hosted_notifiers.append(email_notifier)
1260
+ pd_key = os.environ.get("SELFHEAL_PAGERDUTY_ROUTING_KEY", "").strip()
1261
+ if pd_key:
1262
+ def _pd_routing_key(org_id: str) -> str | None:
1263
+ rec = installation_registry.get_by_org(org_id)
1264
+ if rec is not None and rec.pagerduty_routing_key:
1265
+ return rec.pagerduty_routing_key
1266
+ return pd_key
1267
+
1268
+ hosted_notifiers.append(
1269
+ PagerDutyNotifier(
1270
+ routing_key=_pd_routing_key,
1271
+ events_url=os.environ.get(
1272
+ "SELFHEAL_PAGERDUTY_EVENTS_URL",
1273
+ "https://events.pagerduty.com/v2/enqueue",
1274
+ ),
1275
+ allow_private_urls=os.environ.get(
1276
+ "SELFHEAL_PAGERDUTY_INSECURE", ""
1277
+ ).lower()
1278
+ in {"1", "true", "yes"},
1279
+ )
1280
+ )
1281
+ all_notifiers: list[AlertNotifier] = []
1282
+ if resolved_notifier is not None:
1283
+ all_notifiers.append(resolved_notifier)
1284
+ all_notifiers.extend(hosted_notifiers)
1285
+ if len(all_notifiers) > 1:
1286
+ final_notifier: AlertNotifier | None = CompositeAlertNotifier(all_notifiers)
1287
+ elif all_notifiers:
1288
+ final_notifier = all_notifiers[0]
1289
+ else:
1290
+ final_notifier = None
1291
+
1292
+ auto_heal_worker: AutoHealWorker | None = None
1293
+ if github_app_auth is not None:
1294
+ auto_heal_runner = HostedAutoHealRunner(
1295
+ billing_store=billing_store,
1296
+ installation_registry=installation_registry,
1297
+ hosted_store=hosted_store,
1298
+ drift_ledger=ledger,
1299
+ github_auth=github_app_auth,
1300
+ notifier=final_notifier,
1301
+ )
1302
+ auto_heal_worker = AutoHealWorker(auto_heal_runner)
1303
+ auto_heal_worker.start()
1304
+
1305
+ server = SelfHealHTTPServer(
1306
+ (host, port),
1307
+ SelfHealRequestHandler,
1308
+ config=resolved_config,
1309
+ registry=registry,
1310
+ model_registry=resolved_models,
1311
+ drift_ledger=ledger,
1312
+ billing_store=billing_store,
1313
+ installation_registry=installation_registry,
1314
+ notifier=final_notifier,
1315
+ hosted_store=hosted_store,
1316
+ github_app_slug=github_app_slug,
1317
+ state_secret=state_secret,
1318
+ github_app_auth=github_app_auth,
1319
+ stripe_api=stripe_api,
1320
+ stripe_price_ids=stripe_price_ids,
1321
+ public_base_url=public_base_url,
1322
+ jobs_token=jobs_token,
1323
+ email_notifier=email_notifier,
1324
+ auto_heal_worker=auto_heal_worker,
1325
+ )
1326
+ if os.environ.get("SELFHEAL_DIGEST_SCHEDULER", "").strip().lower() == "inprocess":
1327
+ interval = float(
1328
+ os.environ.get("SELFHEAL_DIGEST_INTERVAL_SECONDS", "604800")
1329
+ )
1330
+ server_hosted.start_digest_scheduler(server, interval_seconds=interval)
1331
+ specwatch_interval = float(
1332
+ os.environ.get("SELFHEAL_SPECWATCH_INTERVAL_SECONDS", "0")
1333
+ )
1334
+ if specwatch_interval > 0:
1335
+ server_hosted.start_specwatch_scheduler(
1336
+ server, interval_seconds=specwatch_interval
1337
+ )
1338
+ return server
1339
+
1340
+
1341
+ def _load_config_from_env_and_file(config_path: str | None) -> ServerConfig:
1342
+ if config_path:
1343
+ raw = json.loads(Path(config_path).read_text(encoding="utf-8"))
1344
+ return ServerConfig.model_validate(raw)
1345
+ port_env = int(os.environ.get("PORT", "8080"))
1346
+ host_env = os.environ.get("SELFHEAL_HOST", "0.0.0.0")
1347
+ secret_env = os.environ.get("SELFHEAL_WEBHOOK_SECRET", "")
1348
+ stripe_env = os.environ.get(
1349
+ "STRIPE_WEBHOOK_SECRET",
1350
+ os.environ.get("SELFHEAL_STRIPE_WEBHOOK_SECRET", ""),
1351
+ )
1352
+ github_env = os.environ.get(
1353
+ "GITHUB_APP_WEBHOOK_SECRET",
1354
+ os.environ.get("SELFHEAL_GITHUB_WEBHOOK_SECRET", ""),
1355
+ )
1356
+ rpm_env = int(os.environ.get("SELFHEAL_MAX_RPM", "60"))
1357
+ llm_cap_env = int(os.environ.get("SELFHEAL_MAX_LLM_CALLS", "20"))
1358
+ db_path_env = os.environ.get("SELFHEAL_DB_PATH", "").strip() or ":memory:"
1359
+ retention_env = int(os.environ.get("SELFHEAL_RETENTION_DAYS", "0"))
1360
+ models_env = _parse_model_specs(os.environ.get("SELFHEAL_MODELS", ""))
1361
+ slack_url_env = os.environ.get("SELFHEAL_SLACK_WEBHOOK_URL", "").strip()
1362
+ alert_url_env = os.environ.get("SELFHEAL_ALERT_WEBHOOK_URL", "").strip()
1363
+ alert_secret_env = os.environ.get("SELFHEAL_ALERT_WEBHOOK_SECRET", "")
1364
+ opts: dict[str, Any] = {
1365
+ "host": host_env,
1366
+ "port": port_env,
1367
+ "webhook_secret": secret_env,
1368
+ "stripe_webhook_secret": stripe_env,
1369
+ "github_webhook_secret": github_env,
1370
+ "max_requests_per_minute": rpm_env,
1371
+ "max_llm_calls_per_tenant": llm_cap_env,
1372
+ "db_path": db_path_env,
1373
+ "retention_days": retention_env,
1374
+ "model_specs": models_env,
1375
+ "slack_webhook_url": slack_url_env,
1376
+ "alert_webhook_url": alert_url_env,
1377
+ "alert_webhook_secret": alert_secret_env,
1378
+ }
1379
+ return ServerConfig(**opts)
1380
+
1381
+
1382
+ def _load_model_registry(specs: list[str]) -> dict[str, type[BaseModel]]:
1383
+ """Import ``module.path:ClassName`` specs and validate each is a Pydantic BaseModel."""
1384
+ registry: dict[str, type[BaseModel]] = {}
1385
+ for raw_spec in specs:
1386
+ spec = raw_spec.strip()
1387
+ if not spec:
1388
+ continue
1389
+ if ":" not in spec:
1390
+ raise ValueError(
1391
+ f"Invalid model spec {spec!r}; expected 'module.path:ClassName'"
1392
+ )
1393
+ module_path, class_name = spec.split(":", 1)
1394
+ module_path = module_path.strip()
1395
+ class_name = class_name.strip()
1396
+ if not module_path or not class_name:
1397
+ raise ValueError(
1398
+ f"Invalid model spec {spec!r}; expected 'module.path:ClassName'"
1399
+ )
1400
+ module = importlib.import_module(module_path)
1401
+ attr = getattr(module, class_name, None)
1402
+ if attr is None:
1403
+ raise ValueError(f"Model {class_name!r} not found in module {module_path!r}")
1404
+ if not isinstance(attr, type) or not issubclass(attr, BaseModel):
1405
+ raise ValueError(f"Model {spec!r} is not a Pydantic BaseModel subclass")
1406
+ registry[class_name] = attr
1407
+ return registry
1408
+
1409
+
1410
+ def main_server(argv: list[str] | None = None) -> int:
1411
+ parser = argparse.ArgumentParser(
1412
+ prog="selfheal-server",
1413
+ description="Hosted multi-tenant selfheal-api drift webhook server",
1414
+ )
1415
+ parser.add_argument("--host", default=None, help="Bind host (default: 0.0.0.0)")
1416
+ parser.add_argument(
1417
+ "--port", type=int, default=None, help="Bind port (default: $PORT or 8080)"
1418
+ )
1419
+ parser.add_argument(
1420
+ "--config", default=None, help="Optional path to JSON ServerConfig file"
1421
+ )
1422
+ parser.add_argument(
1423
+ "--models",
1424
+ action="append",
1425
+ default=None,
1426
+ help="Model spec(s) 'module.path:ClassName' (or comma-separated via SELFHEAL_MODELS)",
1427
+ )
1428
+ args = parser.parse_args(argv)
1429
+
1430
+ logging.basicConfig(
1431
+ level=logging.INFO,
1432
+ format="%(asctime)s %(levelname)s %(name)s %(message)s",
1433
+ )
1434
+ config = _load_config_from_env_and_file(args.config)
1435
+ host = args.host if args.host is not None else config.host
1436
+ port = args.port if args.port is not None else config.port
1437
+
1438
+ raw_models: list[str] = []
1439
+ if args.models:
1440
+ raw_models = _parse_model_specs(args.models)
1441
+ else:
1442
+ env_models = os.environ.get("SELFHEAL_MODELS", "")
1443
+ raw_models = (
1444
+ _parse_model_specs(env_models) if env_models.strip() else config.model_specs
1445
+ )
1446
+ model_registry = _load_model_registry(raw_models)
1447
+
1448
+ server = create_server(
1449
+ host=host, port=port, config=config, model_registry=model_registry
1450
+ )
1451
+ _logger.info("Starting selfheal-server on %s:%d", host, port)
1452
+ prev_sigterm: Any = None
1453
+ if threading.current_thread() is threading.main_thread():
1454
+ def _handle_sigterm(signum: int, _frame: Any) -> None:
1455
+ _logger.info("Received signal %d; initiating graceful shutdown", signum)
1456
+ threading.Thread(target=server.shutdown, daemon=True).start()
1457
+
1458
+ prev_sigterm = signal.signal(signal.SIGTERM, _handle_sigterm)
1459
+ try:
1460
+ server.serve_forever()
1461
+ except KeyboardInterrupt:
1462
+ _logger.info("Shutting down selfheal-server")
1463
+ finally:
1464
+ if prev_sigterm is not None and threading.current_thread() is threading.main_thread():
1465
+ signal.signal(signal.SIGTERM, prev_sigterm)
1466
+ if hasattr(server, "drift_ledger"):
1467
+ server.drift_ledger.close()
1468
+ if hasattr(server, "billing_store"):
1469
+ server.billing_store.close()
1470
+ if hasattr(server, "installation_registry"):
1471
+ server.installation_registry.close()
1472
+ auto_heal = getattr(server, "auto_heal_worker", None)
1473
+ if auto_heal is not None:
1474
+ auto_heal.stop()
1475
+ server.server_close()
1476
+ return 0
1477
+
1478
+
1479
+ if __name__ == "__main__":
1480
+ raise SystemExit(main_server())