Spaces:
Paused
Paused
Fix async binary request forwarding
Browse files- scripts/space_server.py +139 -139
scripts/space_server.py
CHANGED
|
@@ -1,140 +1,140 @@
|
|
| 1 |
-
"""Single-process public gateway. Backend is loopback-only; uploads are session-owned."""
|
| 2 |
-
import asyncio, contextlib, hashlib, hmac, json, os, re, secrets, shutil, subprocess, sys, tempfile, time
|
| 3 |
-
from contextlib import asynccontextmanager
|
| 4 |
-
from pathlib import Path
|
| 5 |
-
import httpx
|
| 6 |
-
from fastapi import FastAPI, Request
|
| 7 |
-
from fastapi.responses import JSONResponse, RedirectResponse, Response
|
| 8 |
-
from fastapi.staticfiles import StaticFiles
|
| 9 |
-
ROOT=Path(__file__).resolve().parents[1]
|
| 10 |
-
PUBLIC=Path(os.environ.get('ACE_PUBLIC_DIR',ROOT/'public'))
|
| 11 |
-
KEY=secrets.token_bytes(32);owners={};busy=set();gate=asyncio.Semaphore(1);waiting=0
|
| 12 |
-
TTL=7200;MAX_UPLOAD=50*1024*1024
|
| 13 |
-
backend_url=os.environ.get('ACE_BACKEND_URL','http://127.0.0.1:9877')
|
| 14 |
-
client=None;store=None
|
| 15 |
-
|
| 16 |
-
def sign(n):return hmac.new(KEY,n.encode(),hashlib.sha256).hexdigest()
|
| 17 |
-
def session(req):
|
| 18 |
-
token=req.cookies.get('ace_session','');bits=token.split('.')
|
| 19 |
-
if len(bits)==2 and re.fullmatch('[a-f0-9]{64}',bits[0]) and hmac.compare_digest(sign(bits[0]),bits[1]):return bits[0],None
|
| 20 |
-
n=secrets.token_hex(32);return n,n+'.'+sign(n)
|
| 21 |
-
|
| 22 |
-
def remove_job(j):
|
| 23 |
-
if store is None:return
|
| 24 |
-
target=(store/j).resolve()
|
| 25 |
-
if target.parent!=store.resolve() or not re.fullmatch('[a-f0-9]{32}',j):raise ValueError('Invalid cleanup target')
|
| 26 |
-
if target.exists():shutil.rmtree(target)
|
| 27 |
-
owners.pop(j,None)
|
| 28 |
-
|
| 29 |
-
async def cleanup():
|
| 30 |
-
while True:
|
| 31 |
-
await asyncio.sleep(60)
|
| 32 |
-
for j,entry in list(owners.items()):
|
| 33 |
-
if j not in busy and time.time()-entry['created']>TTL:remove_job(j)
|
| 34 |
-
|
| 35 |
-
@asynccontextmanager
|
| 36 |
-
async def lifespan(app):
|
| 37 |
-
global client,store
|
| 38 |
-
with tempfile.TemporaryDirectory(prefix='ace-public-') as temp:
|
| 39 |
-
store=Path(temp)
|
| 40 |
-
env={**os.environ,'ACE_PORT':'9877','ACE_STORE':temp,'PYTHONUNBUFFERED':'1'}
|
| 41 |
-
proc=subprocess.Popen([sys.executable,str(ROOT/'scripts/casting_app.py')],env=env)
|
| 42 |
-
client=httpx.AsyncClient(base_url=backend_url,timeout=420)
|
| 43 |
-
task=None
|
| 44 |
-
try:
|
| 45 |
-
for _ in range(240):
|
| 46 |
-
if proc.poll() is not None:raise RuntimeError('Inference backend failed to start')
|
| 47 |
-
try:
|
| 48 |
-
r=await client.get('/api/model')
|
| 49 |
-
if r.status_code==200:break
|
| 50 |
-
except httpx.HTTPError:pass
|
| 51 |
-
await asyncio.sleep(1)
|
| 52 |
-
else:raise RuntimeError('Inference backend startup timed out')
|
| 53 |
-
task=asyncio.create_task(cleanup());yield
|
| 54 |
-
finally:
|
| 55 |
-
if task:
|
| 56 |
-
task.cancel()
|
| 57 |
-
with contextlib.suppress(asyncio.CancelledError):await task
|
| 58 |
-
await client.aclose();proc.terminate()
|
| 59 |
-
try:proc.wait(timeout=10)
|
| 60 |
-
except subprocess.TimeoutExpired:proc.kill();proc.wait()
|
| 61 |
-
|
| 62 |
-
app=FastAPI(lifespan=lifespan,docs_url=None,redoc_url=None,openapi_url=None)
|
| 63 |
-
@app.middleware('http')
|
| 64 |
-
async def identity(req,call_next):
|
| 65 |
-
sid,cookie=session(req);req.state.sid=sid
|
| 66 |
-
response=await call_next(req)
|
| 67 |
-
if cookie:response.set_cookie('ace_session',cookie,httponly=True,secure=req.url.scheme=='https',samesite='lax',max_age=TTL)
|
| 68 |
-
if req.url.path.startswith('/api'):response.headers['Cache-Control']='no-store'
|
| 69 |
-
response.headers['X-Content-Type-Options']='nosniff'
|
| 70 |
-
return response
|
| 71 |
-
|
| 72 |
-
@app.get('/')
|
| 73 |
-
async def home():return RedirectResponse('/artifacts/whitepaper/index.html')
|
| 74 |
-
@app.get('/app')
|
| 75 |
-
async def app_root():return RedirectResponse('/app/')
|
| 76 |
-
@app.get('/healthz')
|
| 77 |
-
async def health():return {'status':'ready'}
|
| 78 |
-
|
| 79 |
-
def err(message,code=400):return JSONResponse({'error':message},status_code=code)
|
| 80 |
-
def owned(j,sid):return j in owners and owners[j]['owner']==sid and time.time()-owners[j]['created']<=TTL
|
| 81 |
-
|
| 82 |
-
def forward(r):
|
| 83 |
-
# httpx decompresses; do not forward Content-Encoding/Length from upstream.
|
| 84 |
-
return Response(r.content,status_code=r.status_code,media_type=r.headers.get('content-type','application/json'))
|
| 85 |
-
|
| 86 |
-
@app.api_route('/api/{route:path}',methods=['GET','POST'])
|
| 87 |
-
async def api(route,req:Request):
|
| 88 |
-
global waiting
|
| 89 |
-
sid=req.state.sid
|
| 90 |
-
if req.method=='GET':
|
| 91 |
-
if route=='model':return forward(await client.get('/api/model'))
|
| 92 |
-
if route=='recent':return [{'id':j,'name':e['name']} for j,e in owners.items() if owned(j,sid)]
|
| 93 |
-
if not re.fullmatch(r'(job|geometry)/[a-f0-9]{32}',route):return err('Not found',404)
|
| 94 |
-
if not owned(route.split('/')[-1],sid):return err('Part not found or session expired',404)
|
| 95 |
-
return forward(await client.get('/api/'+route))
|
| 96 |
-
# Browser requests must originate from this host; no cross-origin upload API.
|
| 97 |
-
origin=req.headers.get('origin')
|
| 98 |
-
if origin and origin.rstrip('/')!=str(req.base_url).rstrip('/'):return err('Origin not allowed',403)
|
| 99 |
-
if route not in ['upload','resume','predict']:return err('Not found',404)
|
| 100 |
-
raw=bytearray();limit=MAX_UPLOAD if route=='upload' else 65536
|
| 101 |
-
async for chunk in req.stream():
|
| 102 |
-
raw.extend(chunk)
|
| 103 |
-
if len(raw)>limit:return err('Request exceeds size limit',413)
|
| 104 |
-
if route=='upload':
|
| 105 |
-
if len(owners)>=24 or sum(owned(j,sid) for j in owners)>=3:return err('Upload limit reached. Temporary parts expire after two hours.',429)
|
| 106 |
-
if b'ISO-10303-21' not in raw[:4096].upper():return err('Expected a STEP/STP file')
|
| 107 |
-
else:
|
| 108 |
-
try:opt=json.loads(raw);j=opt['id']
|
| 109 |
-
except (ValueError,KeyError,TypeError):return err('Invalid request')
|
| 110 |
-
if not isinstance(j,str) or not owned(j,sid):return err('Part not found or session expired',404)
|
| 111 |
-
if route=='resume':return forward(await client.post('/api/resume',content=raw))
|
| 112 |
-
if waiting>=4:return err('Prediction service is busy. Please retry shortly.',429)
|
| 113 |
-
waiting+=1;j=None
|
| 114 |
-
try:
|
| 115 |
-
async with gate:
|
| 116 |
-
headers={'Accept':req.headers.get('accept','application/json')}
|
| 117 |
-
if route=='upload':
|
| 118 |
-
if len(owners)>=24 or sum(owned(k,sid) for k in owners)>=3:return err('Upload limit reached',429)
|
| 119 |
-
name=req.headers.get('x-filename','Uploaded STEP')[:200];headers['X-Filename']=name
|
| 120 |
-
r=await client.post('/api/upload',content=raw,headers=headers)
|
| 121 |
-
if r.status_code!=200:return forward(r)
|
| 122 |
-
result=r.json();j=result['id'];owners[j]={'owner':sid,'created':time.time(),'name':name};busy.add(j)
|
| 123 |
-
# Keep CAD and inference serialized; browser shows its preparing state.
|
| 124 |
-
for _ in range(390):
|
| 125 |
-
state=await client.get('/api/job/'+j)
|
| 126 |
-
if state.json().get('status')!='processing':return forward(state)
|
| 127 |
-
await asyncio.sleep(1)
|
| 128 |
-
return err('Geometry preparation timed out',504)
|
| 129 |
-
j=opt['id']
|
| 130 |
-
if not owned(j,sid):return err('Part expired',404)
|
| 131 |
-
busy.add(j)
|
| 132 |
-
return forward(await client.post('/api/predict',content=raw,headers=headers))
|
| 133 |
-
except httpx.HTTPError:return err('Prediction service unavailable; please retry',503)
|
| 134 |
-
finally:
|
| 135 |
-
waiting-=1
|
| 136 |
-
if j:busy.discard(j)
|
| 137 |
-
|
| 138 |
-
# Only explicitly packaged assets are served. No repository or job-directory mounts.
|
| 139 |
-
app.mount('/app',StaticFiles(directory=PUBLIC/'artifacts/casting_app',html=True),name='app')
|
| 140 |
app.mount('/artifacts',StaticFiles(directory=PUBLIC/'artifacts'),name='showcase')
|
|
|
|
| 1 |
+
"""Single-process public gateway. Backend is loopback-only; uploads are session-owned."""
|
| 2 |
+
import asyncio, contextlib, hashlib, hmac, json, os, re, secrets, shutil, subprocess, sys, tempfile, time
|
| 3 |
+
from contextlib import asynccontextmanager
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import httpx
|
| 6 |
+
from fastapi import FastAPI, Request
|
| 7 |
+
from fastapi.responses import JSONResponse, RedirectResponse, Response
|
| 8 |
+
from fastapi.staticfiles import StaticFiles
|
| 9 |
+
ROOT=Path(__file__).resolve().parents[1]
|
| 10 |
+
PUBLIC=Path(os.environ.get('ACE_PUBLIC_DIR',ROOT/'public'))
|
| 11 |
+
KEY=secrets.token_bytes(32);owners={};busy=set();gate=asyncio.Semaphore(1);waiting=0
|
| 12 |
+
TTL=7200;MAX_UPLOAD=50*1024*1024
|
| 13 |
+
backend_url=os.environ.get('ACE_BACKEND_URL','http://127.0.0.1:9877')
|
| 14 |
+
client=None;store=None
|
| 15 |
+
|
| 16 |
+
def sign(n):return hmac.new(KEY,n.encode(),hashlib.sha256).hexdigest()
|
| 17 |
+
def session(req):
|
| 18 |
+
token=req.cookies.get('ace_session','');bits=token.split('.')
|
| 19 |
+
if len(bits)==2 and re.fullmatch('[a-f0-9]{64}',bits[0]) and hmac.compare_digest(sign(bits[0]),bits[1]):return bits[0],None
|
| 20 |
+
n=secrets.token_hex(32);return n,n+'.'+sign(n)
|
| 21 |
+
|
| 22 |
+
def remove_job(j):
|
| 23 |
+
if store is None:return
|
| 24 |
+
target=(store/j).resolve()
|
| 25 |
+
if target.parent!=store.resolve() or not re.fullmatch('[a-f0-9]{32}',j):raise ValueError('Invalid cleanup target')
|
| 26 |
+
if target.exists():shutil.rmtree(target)
|
| 27 |
+
owners.pop(j,None)
|
| 28 |
+
|
| 29 |
+
async def cleanup():
|
| 30 |
+
while True:
|
| 31 |
+
await asyncio.sleep(60)
|
| 32 |
+
for j,entry in list(owners.items()):
|
| 33 |
+
if j not in busy and time.time()-entry['created']>TTL:remove_job(j)
|
| 34 |
+
|
| 35 |
+
@asynccontextmanager
|
| 36 |
+
async def lifespan(app):
|
| 37 |
+
global client,store
|
| 38 |
+
with tempfile.TemporaryDirectory(prefix='ace-public-') as temp:
|
| 39 |
+
store=Path(temp)
|
| 40 |
+
env={**os.environ,'ACE_PORT':'9877','ACE_STORE':temp,'PYTHONUNBUFFERED':'1'}
|
| 41 |
+
proc=subprocess.Popen([sys.executable,str(ROOT/'scripts/casting_app.py')],env=env)
|
| 42 |
+
client=httpx.AsyncClient(base_url=backend_url,timeout=420)
|
| 43 |
+
task=None
|
| 44 |
+
try:
|
| 45 |
+
for _ in range(240):
|
| 46 |
+
if proc.poll() is not None:raise RuntimeError('Inference backend failed to start')
|
| 47 |
+
try:
|
| 48 |
+
r=await client.get('/api/model')
|
| 49 |
+
if r.status_code==200:break
|
| 50 |
+
except httpx.HTTPError:pass
|
| 51 |
+
await asyncio.sleep(1)
|
| 52 |
+
else:raise RuntimeError('Inference backend startup timed out')
|
| 53 |
+
task=asyncio.create_task(cleanup());yield
|
| 54 |
+
finally:
|
| 55 |
+
if task:
|
| 56 |
+
task.cancel()
|
| 57 |
+
with contextlib.suppress(asyncio.CancelledError):await task
|
| 58 |
+
await client.aclose();proc.terminate()
|
| 59 |
+
try:proc.wait(timeout=10)
|
| 60 |
+
except subprocess.TimeoutExpired:proc.kill();proc.wait()
|
| 61 |
+
|
| 62 |
+
app=FastAPI(lifespan=lifespan,docs_url=None,redoc_url=None,openapi_url=None)
|
| 63 |
+
@app.middleware('http')
|
| 64 |
+
async def identity(req,call_next):
|
| 65 |
+
sid,cookie=session(req);req.state.sid=sid
|
| 66 |
+
response=await call_next(req)
|
| 67 |
+
if cookie:response.set_cookie('ace_session',cookie,httponly=True,secure=req.url.scheme=='https',samesite='lax',max_age=TTL)
|
| 68 |
+
if req.url.path.startswith('/api'):response.headers['Cache-Control']='no-store'
|
| 69 |
+
response.headers['X-Content-Type-Options']='nosniff'
|
| 70 |
+
return response
|
| 71 |
+
|
| 72 |
+
@app.get('/')
|
| 73 |
+
async def home():return RedirectResponse('/artifacts/whitepaper/index.html')
|
| 74 |
+
@app.get('/app')
|
| 75 |
+
async def app_root():return RedirectResponse('/app/')
|
| 76 |
+
@app.get('/healthz')
|
| 77 |
+
async def health():return {'status':'ready'}
|
| 78 |
+
|
| 79 |
+
def err(message,code=400):return JSONResponse({'error':message},status_code=code)
|
| 80 |
+
def owned(j,sid):return j in owners and owners[j]['owner']==sid and time.time()-owners[j]['created']<=TTL
|
| 81 |
+
|
| 82 |
+
def forward(r):
|
| 83 |
+
# httpx decompresses; do not forward Content-Encoding/Length from upstream.
|
| 84 |
+
return Response(r.content,status_code=r.status_code,media_type=r.headers.get('content-type','application/json'))
|
| 85 |
+
|
| 86 |
+
@app.api_route('/api/{route:path}',methods=['GET','POST'])
|
| 87 |
+
async def api(route,req:Request):
|
| 88 |
+
global waiting
|
| 89 |
+
sid=req.state.sid
|
| 90 |
+
if req.method=='GET':
|
| 91 |
+
if route=='model':return forward(await client.get('/api/model'))
|
| 92 |
+
if route=='recent':return [{'id':j,'name':e['name']} for j,e in owners.items() if owned(j,sid)]
|
| 93 |
+
if not re.fullmatch(r'(job|geometry)/[a-f0-9]{32}',route):return err('Not found',404)
|
| 94 |
+
if not owned(route.split('/')[-1],sid):return err('Part not found or session expired',404)
|
| 95 |
+
return forward(await client.get('/api/'+route))
|
| 96 |
+
# Browser requests must originate from this host; no cross-origin upload API.
|
| 97 |
+
origin=req.headers.get('origin')
|
| 98 |
+
if origin and origin.rstrip('/')!=str(req.base_url).rstrip('/'):return err('Origin not allowed',403)
|
| 99 |
+
if route not in ['upload','resume','predict']:return err('Not found',404)
|
| 100 |
+
raw=bytearray();limit=MAX_UPLOAD if route=='upload' else 65536
|
| 101 |
+
async for chunk in req.stream():
|
| 102 |
+
raw.extend(chunk)
|
| 103 |
+
if len(raw)>limit:return err('Request exceeds size limit',413)
|
| 104 |
+
if route=='upload':
|
| 105 |
+
if len(owners)>=24 or sum(owned(j,sid) for j in owners)>=3:return err('Upload limit reached. Temporary parts expire after two hours.',429)
|
| 106 |
+
if b'ISO-10303-21' not in raw[:4096].upper():return err('Expected a STEP/STP file')
|
| 107 |
+
else:
|
| 108 |
+
try:opt=json.loads(raw);j=opt['id']
|
| 109 |
+
except (ValueError,KeyError,TypeError):return err('Invalid request')
|
| 110 |
+
if not isinstance(j,str) or not owned(j,sid):return err('Part not found or session expired',404)
|
| 111 |
+
if route=='resume':return forward(await client.post('/api/resume',content=bytes(raw)))
|
| 112 |
+
if waiting>=4:return err('Prediction service is busy. Please retry shortly.',429)
|
| 113 |
+
waiting+=1;j=None
|
| 114 |
+
try:
|
| 115 |
+
async with gate:
|
| 116 |
+
headers={'Accept':req.headers.get('accept','application/json')}
|
| 117 |
+
if route=='upload':
|
| 118 |
+
if len(owners)>=24 or sum(owned(k,sid) for k in owners)>=3:return err('Upload limit reached',429)
|
| 119 |
+
name=req.headers.get('x-filename','Uploaded STEP')[:200];headers['X-Filename']=name
|
| 120 |
+
r=await client.post('/api/upload',content=bytes(raw),headers=headers)
|
| 121 |
+
if r.status_code!=200:return forward(r)
|
| 122 |
+
result=r.json();j=result['id'];owners[j]={'owner':sid,'created':time.time(),'name':name};busy.add(j)
|
| 123 |
+
# Keep CAD and inference serialized; browser shows its preparing state.
|
| 124 |
+
for _ in range(390):
|
| 125 |
+
state=await client.get('/api/job/'+j)
|
| 126 |
+
if state.json().get('status')!='processing':return forward(state)
|
| 127 |
+
await asyncio.sleep(1)
|
| 128 |
+
return err('Geometry preparation timed out',504)
|
| 129 |
+
j=opt['id']
|
| 130 |
+
if not owned(j,sid):return err('Part expired',404)
|
| 131 |
+
busy.add(j)
|
| 132 |
+
return forward(await client.post('/api/predict',content=bytes(raw),headers=headers))
|
| 133 |
+
except httpx.HTTPError:return err('Prediction service unavailable; please retry',503)
|
| 134 |
+
finally:
|
| 135 |
+
waiting-=1
|
| 136 |
+
if j:busy.discard(j)
|
| 137 |
+
|
| 138 |
+
# Only explicitly packaged assets are served. No repository or job-directory mounts.
|
| 139 |
+
app.mount('/app',StaticFiles(directory=PUBLIC/'artifacts/casting_app',html=True),name='app')
|
| 140 |
app.mount('/artifacts',StaticFiles(directory=PUBLIC/'artifacts'),name='showcase')
|