umar-sharif821 commited on
Commit
a9c6a15
·
1 Parent(s): 56d33d1

fix: add server/app.py for openenv validate

Browse files
Files changed (1) hide show
  1. server/app.py +103 -0
server/app.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FastAPI server exposing OpenEnv interface over HTTP.
3
+ Endpoints: POST /reset, POST /step, GET /state, GET /health, GET /tasks
4
+ """
5
+
6
+ import sys
7
+ import os
8
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
9
+
10
+ from fastapi import FastAPI, Request, HTTPException
11
+ from fastapi.middleware.cors import CORSMiddleware
12
+ from pydantic import BaseModel
13
+ from typing import Optional
14
+ import uvicorn
15
+
16
+ from env.cache import CDNCacheEnv, TASK_CONFIGS
17
+ from env.models import Action, StepResult
18
+
19
+ app = FastAPI(title="CDN Cache Optimizer - OpenEnv", version="1.0.0")
20
+
21
+ app.add_middleware(
22
+ CORSMiddleware,
23
+ allow_origins=["*"],
24
+ allow_methods=["*"],
25
+ allow_headers=["*"],
26
+ )
27
+
28
+ _env: Optional[CDNCacheEnv] = None
29
+
30
+
31
+ @app.get("/health")
32
+ def health():
33
+ return {"status": "ok", "env": "cdn-cache-optimizer"}
34
+
35
+ @app.post("/health")
36
+ def health_post():
37
+ return {"status": "ok", "env": "cdn-cache-optimizer"}
38
+
39
+ @app.get("/tasks")
40
+ def list_tasks():
41
+ return {
42
+ task_id: {
43
+ "name": cfg.name,
44
+ "difficulty": cfg.difficulty,
45
+ "description": cfg.description,
46
+ "cache_capacity_mb": cfg.cache_capacity_mb,
47
+ "episode_length": cfg.episode_length,
48
+ }
49
+ for task_id, cfg in TASK_CONFIGS.items()
50
+ }
51
+
52
+ @app.post("/reset")
53
+ async def reset(request: Request):
54
+ global _env
55
+ task_id = "task_easy"
56
+ seed = 42
57
+ try:
58
+ body = await request.json()
59
+ task_id = body.get("task_id", "task_easy")
60
+ seed = body.get("seed", 42)
61
+ except Exception:
62
+ pass
63
+ if task_id not in TASK_CONFIGS:
64
+ raise HTTPException(status_code=400, detail=f"Unknown task_id '{task_id}'.")
65
+ _env = CDNCacheEnv(task_id=task_id, seed=seed)
66
+ obs = _env.reset()
67
+ return {"observation": obs.dict(), "task": _env.config.dict()}
68
+
69
+ @app.post("/step")
70
+ async def step(request: Request):
71
+ global _env
72
+ if _env is None:
73
+ raise HTTPException(status_code=400, detail="Call /reset first.")
74
+ if _env._done:
75
+ raise HTTPException(status_code=400, detail="Episode done. Call /reset.")
76
+ evict_file_id = None
77
+ try:
78
+ body = await request.json()
79
+ evict_file_id = body.get("evict_file_id", None)
80
+ except Exception:
81
+ pass
82
+ action = Action(evict_file_id=evict_file_id)
83
+ result: StepResult = _env.step(action)
84
+ return result.dict()
85
+
86
+ @app.get("/state")
87
+ def state():
88
+ global _env
89
+ if _env is None:
90
+ raise HTTPException(status_code=400, detail="Call /reset first.")
91
+ return _env.state()
92
+
93
+ @app.get("/")
94
+ def root():
95
+ return {
96
+ "name": "CDN Cache Optimizer",
97
+ "spec": "OpenEnv v1",
98
+ "endpoints": ["/reset", "/step", "/state", "/health", "/tasks"],
99
+ "tasks": list(TASK_CONFIGS.keys()),
100
+ }
101
+
102
+ if __name__ == "__main__":
103
+ uvicorn.run("api.main:app", host="0.0.0.0", port=7860, reload=False)