-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoreswitch.py
More file actions
70 lines (59 loc) · 2.51 KB
/
Copy pathcoreswitch.py
File metadata and controls
70 lines (59 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# coreswitch.py - Infrastructure Safety Boundary & Circuit Breaker (Peak Edition)
import time
from typing import Literal
from fastapi import FastAPI, Request, status
from fastapi.responses import ORJSONResponse
from pydantic import BaseModel, Field
app = FastAPI(
title="CoreSwitch Infrastructure Safety Boundary",
version="1.0.0",
description="Sub-5ms Deterministic Circuit Breaker Middleware",
default_response_class=ORJSONResponse # C-based ultra-fast JSON parsing
)
MAX_PAYLOAD_BYTES = 2 * 1024 * 1024 # 2MB Limit for DoS Protection
# Middleware: Protect against memory overload attacks
@app.middleware("http")
async def limit_payload_size(request: Request, call_next):
content_length = request.headers.get("content-length")
if content_length and int(content_length) > MAX_PAYLOAD_BYTES:
return ORJSONResponse(
status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
content={"detail": "Payload too large. CoreSwitch limits requests to 2MB."}
)
return await call_next(request)
# Data Contract Schemas
class CoreSwitchRequest(BaseModel):
raw_output: str
entropy_index: float = Field(..., ge=0.0, le=1.0, description="Real-time cognitive load (0.0 to 1.0)")
src_status: Literal["FULL", "PARTIAL", "CRITICAL"] = Field(..., description="Resource availability state")
context_weight: float = Field(..., ge=0.0, le=1.0, description="Context coherence score")
class Telemetry(BaseModel):
execution_time_ms: float
input_length: int
class CoreSwitchResponse(BaseModel):
processed_output: str
applied_action: Literal["PASS", "HARD_STOP"]
telemetry: Telemetry
# Deterministic Cascade Logic
@app.post("/evaluate", response_model=CoreSwitchResponse, status_code=status.HTTP_200_OK)
async def evaluate_circuit_breaker(payload: CoreSwitchRequest):
start_time = time.perf_counter()
input_len = len(payload.raw_output)
if payload.src_status == "CRITICAL" or payload.entropy_index > 0.7:
action = "HARD_STOP"
processed_output = ""
else:
action = "PASS"
processed_output = payload.raw_output
execution_time_ms = round((time.perf_counter() - start_time) * 1000, 4)
return CoreSwitchResponse(
processed_output=processed_output,
applied_action=action,
telemetry=Telemetry(
execution_time_ms=execution_time_ms,
input_length=input_len
)
)
@app.get("/healthz")
async def health_check():
return {"status": "ok", "layer": "CoreSwitch Circuit Breaker"}