loveaa commited on
Commit
9df654d
·
verified ·
1 Parent(s): 2157cce

Add Home Pulse App API and verified device-command workflow

Browse files
Files changed (2) hide show
  1. app.py +21 -5
  2. web/server-bundle.mjs +7 -2
app.py CHANGED
@@ -13,6 +13,7 @@ import base64
13
  import io
14
  import time
15
  import asyncio
 
16
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
17
 
18
  import gradio as gr
@@ -44,6 +45,12 @@ atexit.register(node_process.terminate)
44
 
45
  REMOTE_SPACE=os.getenv('HOME_PULSE_REMOTE_SPACE','mohit67890/imajev')
46
  app=gr.Server(title='Home Pulse',docs_url=None,redoc_url=None)
 
 
 
 
 
 
47
 
48
  class ModelBridge(BaseHTTPRequestHandler):
49
  def do_POST(self):
@@ -79,6 +86,12 @@ def visual(route:str,body:str,workspace:str,request:gr.Request)->dict:
79
  return run_visual(route,body,workspace,dict(request.headers) if request else {})
80
 
81
  def run_visual(route:str,body:str,workspace:str,request_headers:dict)->dict:
 
 
 
 
 
 
82
  # The browser and native REST adapter share the visitor-quota protocol.
83
  token=request_headers.get('x-ip-token','')
84
  print('Visual gateway: visitor quota forwarded =',bool(token),flush=True)
@@ -116,19 +129,20 @@ async def api_proxy(path:str,request:Request):
116
  authorization=request.headers.get('authorization','')
117
  workspace=(authorization[7:] if native and authorization.startswith('Bearer ') else '') or request.headers.get('x-home-pulse-workspace') or request.cookies.get('hp_workspace','')
118
  if not public and not WORKSPACE.fullmatch(workspace):
119
- error={'error':{'code':'UNAUTHORIZED','message':'请提供 Home Pulse 空间令牌','retryable':False},'requestId':secrets.token_hex(16),'serverTime':__import__('datetime').datetime.now(__import__('datetime').timezone.utc).isoformat(),'apiVersion':'1.1.0'} if native else {'error':'请刷新页面,重新连接你的空间'}
120
- return JSONResponse(error,status_code=401)
121
  if request.method=='POST' and APP_VISUAL.fullmatch('/api/'+path):
122
  chunks=[];size=0
123
  async for chunk in request.stream():
124
  size+=len(chunk)
125
- if size>6*1024*1024:return JSONResponse({'error':{'code':'BODY_TOO_LARGE','message':'单次请求不能超过 6 MB','retryable':False}},status_code=413)
126
  chunks.append(chunk)
127
  try:
128
  result=await asyncio.to_thread(run_visual,'/api/'+path,b''.join(chunks).decode('utf-8'),workspace,dict(request.headers))
 
129
  return JSONResponse(result['body'],status_code=result['status'])
130
  except Exception:
131
- return JSONResponse({'error':{'code':'VISUAL_GATEWAY_UNAVAILABLE','message':'视觉服务暂时未返回结果,请稍后重试','retryable':True}},status_code=503)
132
  if request.method=='POST' and VISUAL.fullmatch('/api/'+path):
133
  return JSONResponse({'error':'请通过页面发起 GPU 观察'},status_code=400)
134
  headers={k:v for k,v in request.headers.items() if k.lower() in ('content-type','content-length','range','x-file-name','origin','host','idempotency-key')}
@@ -139,7 +153,9 @@ async def api_proxy(path:str,request:Request):
139
  outbound=client.build_request(request.method,target,headers=headers,content=request.stream())
140
  response=await client.send(outbound,stream=True)
141
  except Exception:
142
- await client.aclose();return JSONResponse({'error':'空间连接暂时中断,请重试'},status_code=502)
 
 
143
  async def close(): await response.aclose();await client.aclose()
144
  kept={k:v for k,v in response.headers.items() if k.lower() in ('content-type','content-length','content-range','accept-ranges','cache-control','content-disposition')}
145
  return StreamingResponse(response.aiter_raw(),status_code=response.status_code,headers=kept,background=BackgroundTask(close))
 
13
  import io
14
  import time
15
  import asyncio
16
+ from datetime import datetime, timezone
17
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
18
 
19
  import gradio as gr
 
45
 
46
  REMOTE_SPACE=os.getenv('HOME_PULSE_REMOTE_SPACE','mohit67890/imajev')
47
  app=gr.Server(title='Home Pulse',docs_url=None,redoc_url=None)
48
+ VISUAL_SLOT=threading.BoundedSemaphore(1)
49
+
50
+ def native_error(code,message,status,retryable=False):
51
+ return JSONResponse({'error':{'code':code,'message':message,'retryable':retryable},
52
+ 'requestId':secrets.token_hex(16),'serverTime':datetime.now(timezone.utc).isoformat(),
53
+ 'apiVersion':'1.1.0'},status_code=status)
54
 
55
  class ModelBridge(BaseHTTPRequestHandler):
56
  def do_POST(self):
 
86
  return run_visual(route,body,workspace,dict(request.headers) if request else {})
87
 
88
  def run_visual(route:str,body:str,workspace:str,request_headers:dict)->dict:
89
+ if not VISUAL_SLOT.acquire(timeout=1):
90
+ return {'status':429,'body':{'error':'视觉服务正在完成上一轮观察,请稍后重试。'}}
91
+ try:return run_visual_in_slot(route,body,workspace,request_headers)
92
+ finally:VISUAL_SLOT.release()
93
+
94
+ def run_visual_in_slot(route:str,body:str,workspace:str,request_headers:dict)->dict:
95
  # The browser and native REST adapter share the visitor-quota protocol.
96
  token=request_headers.get('x-ip-token','')
97
  print('Visual gateway: visitor quota forwarded =',bool(token),flush=True)
 
129
  authorization=request.headers.get('authorization','')
130
  workspace=(authorization[7:] if native and authorization.startswith('Bearer ') else '') or request.headers.get('x-home-pulse-workspace') or request.cookies.get('hp_workspace','')
131
  if not public and not WORKSPACE.fullmatch(workspace):
132
+ if native:return native_error('UNAUTHORIZED','请提供 Home Pulse 空间令牌',401)
133
+ return JSONResponse({'error':'请刷新页面,重新连接你的空间'},status_code=401)
134
  if request.method=='POST' and APP_VISUAL.fullmatch('/api/'+path):
135
  chunks=[];size=0
136
  async for chunk in request.stream():
137
  size+=len(chunk)
138
+ if size>6*1024*1024:return native_error('BODY_TOO_LARGE','单次请求不能超过 6 MB',413)
139
  chunks.append(chunk)
140
  try:
141
  result=await asyncio.to_thread(run_visual,'/api/'+path,b''.join(chunks).decode('utf-8'),workspace,dict(request.headers))
142
+ if isinstance(result['body'].get('error'),str):return native_error('VISUAL_BUSY',result['body']['error'],result['status'],True)
143
  return JSONResponse(result['body'],status_code=result['status'])
144
  except Exception:
145
+ return native_error('VISUAL_GATEWAY_UNAVAILABLE','视觉服务暂时未返回结果,请稍后重试',503,True)
146
  if request.method=='POST' and VISUAL.fullmatch('/api/'+path):
147
  return JSONResponse({'error':'请通过页面发起 GPU 观察'},status_code=400)
148
  headers={k:v for k,v in request.headers.items() if k.lower() in ('content-type','content-length','range','x-file-name','origin','host','idempotency-key')}
 
153
  outbound=client.build_request(request.method,target,headers=headers,content=request.stream())
154
  response=await client.send(outbound,stream=True)
155
  except Exception:
156
+ await client.aclose()
157
+ if native:return native_error('GATEWAY_UNAVAILABLE','空间连接暂时中断,请重试',502,True)
158
+ return JSONResponse({'error':'空间连接暂时中断,请重试'},status_code=502)
159
  async def close(): await response.aclose();await client.aclose()
160
  kept={k:v for k,v in response.headers.items() if k.lower() in ('content-type','content-length','content-range','accept-ranges','cache-control','content-disposition')}
161
  return StreamingResponse(response.aiter_raw(),status_code=response.status_code,headers=kept,background=BackgroundTask(close))
web/server-bundle.mjs CHANGED
@@ -15689,6 +15689,11 @@ function createCloudHandler({ dataDir, internalKey, plannerLimit = 12, totalPlan
15689
  res.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store" });
15690
  res.end(JSON.stringify({ error: error48 }));
15691
  };
 
 
 
 
 
15692
  const limited = (key, max) => {
15693
  const now = Date.now(), old = rates.get(key), row = old && now - old.start < 36e5 ? old : { start: now, count: 0 };
15694
  row.count++;
@@ -15719,11 +15724,11 @@ function createCloudHandler({ dataDir, internalKey, plannerLimit = 12, totalPlan
15719
  req.headers["x-home-pulse-workspace"] = token;
15720
  if (!url2.pathname.startsWith("/api/")) return send(res, 404, "\u63A5\u53E3\u4E0D\u5B58\u5728");
15721
  if (req.method === "POST" && ["/api/setup/draft", "/api/setup/prepare", "/api/plan", "/api/v1/setups/draft", "/api/v1/setups/prepare"].includes(url2.pathname)) {
15722
- if (limited(token, plannerLimit) || limited("all", totalPlannerLimit)) return send(res, 429, "\u672C\u5C0F\u65F6\u7684\u4EFB\u52A1\u8BBE\u7F6E\u6B21\u6570\u5DF2\u7528\u5B8C\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002\u5DF2\u6709\u4EFB\u52A1\u4ECD\u53EF\u89C2\u5BDF\u3002");
15723
  }
15724
  let entry = workspaces.get(token);
15725
  if (!entry) {
15726
- if (workspaces.size >= 2e3) return send(res, 503, "\u5F53\u524D\u4F53\u9A8C\u4EBA\u6570\u8F83\u591A\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
15727
  let middleware;
15728
  const root = path6.join(dataDir, "workspaces", token);
15729
  localApiPlugin(root, { appScoped: true }).configureServer({ middlewares: { use: (m) => middleware = m } });
 
15689
  res.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store" });
15690
  res.end(JSON.stringify({ error: error48 }));
15691
  };
15692
+ const sendApp = (res, status, code, message) => {
15693
+ const result = appError(new AppError(status, code, message));
15694
+ res.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store" });
15695
+ res.end(JSON.stringify(result.body));
15696
+ };
15697
  const limited = (key, max) => {
15698
  const now = Date.now(), old = rates.get(key), row = old && now - old.start < 36e5 ? old : { start: now, count: 0 };
15699
  row.count++;
 
15724
  req.headers["x-home-pulse-workspace"] = token;
15725
  if (!url2.pathname.startsWith("/api/")) return send(res, 404, "\u63A5\u53E3\u4E0D\u5B58\u5728");
15726
  if (req.method === "POST" && ["/api/setup/draft", "/api/setup/prepare", "/api/plan", "/api/v1/setups/draft", "/api/v1/setups/prepare"].includes(url2.pathname)) {
15727
+ if (limited(token, plannerLimit) || limited("all", totalPlannerLimit)) return native ? sendApp(res, 429, "PLANNER_RATE_LIMITED", "\u672C\u5C0F\u65F6\u7684\u4EFB\u52A1\u8BBE\u7F6E\u6B21\u6570\u5DF2\u7528\u5B8C\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002\u5DF2\u6709\u4EFB\u52A1\u4ECD\u53EF\u89C2\u5BDF\u3002") : send(res, 429, "\u672C\u5C0F\u65F6\u7684\u4EFB\u52A1\u8BBE\u7F6E\u6B21\u6570\u5DF2\u7528\u5B8C\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002\u5DF2\u6709\u4EFB\u52A1\u4ECD\u53EF\u89C2\u5BDF\u3002");
15728
  }
15729
  let entry = workspaces.get(token);
15730
  if (!entry) {
15731
+ if (workspaces.size >= 2e3) return native ? sendApp(res, 503, "WORKSPACE_LIMIT", "\u5F53\u524D\u4F53\u9A8C\u4EBA\u6570\u8F83\u591A\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5") : send(res, 503, "\u5F53\u524D\u4F53\u9A8C\u4EBA\u6570\u8F83\u591A\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
15732
  let middleware;
15733
  const root = path6.join(dataDir, "workspaces", token);
15734
  localApiPlugin(root, { appScoped: true }).configureServer({ middlewares: { use: (m) => middleware = m } });