-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
316 lines (247 loc) · 9.12 KB
/
main.py
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
import asyncio
import hashlib
import json
import os
import zipfile
from asyncio import to_thread
from datetime import datetime
from datetime import timedelta
from functools import partial
from importlib import import_module
from io import BytesIO
from time import mktime
from types import SimpleNamespace
from typing import AsyncGenerator
from urllib.parse import urlparse
from wsgiref.handlers import format_date_time
import docker
import httpx
import yaml
from fastapi import APIRouter
from fastapi import Depends
from fastapi import FastAPI
from fastapi import HTTPException
from fastapi import Request
from fastapi import WebSocket
from fastapi import WebSocketDisconnect
from fastapi import status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
from fastapi.responses import StreamingResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from redis.asyncio import Redis
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
clients = set()
with open("database.yaml", "rt") as f:
database = yaml.safe_load(f)
async def online(clients: set) -> None:
message = {"event": {"topic": "online", "data": {"clients": len(clients)}}}
tasks = (asyncio.create_task(c.send_json(message)) for c in clients)
results = await asyncio.gather(*tasks, return_exceptions=True)
failed = {c for c, r in zip(clients, results) if isinstance(r, Exception)}
clients.difference_update(failed)
broadcast = SimpleNamespace(online=online)
async def add(websocket: WebSocket) -> None:
clients.add(websocket)
await broadcast.online(clients)
async def disconnect(websocket: WebSocket) -> None:
clients.discard(websocket)
await broadcast.online(clients)
@app.websocket("/socket")
async def websocket(websocket: WebSocket) -> None:
await websocket.accept()
await add(websocket)
try:
async def heartbeat() -> None:
while True:
try:
await asyncio.sleep(10)
await websocket.send_text(json.dumps({"command": "ping"}))
except (WebSocketDisconnect, asyncio.TimeoutError):
break
async def relay() -> None:
try:
async for message in websocket.iter_text():
match json.loads(message):
case {"rpc": {"request": {"id": id, "method": method, "arguments": arguments}}}:
response = {"rpc": {"response": {"id": id}}}
try:
module = import_module(f"procedures.{method}")
func = partial(module.run, **arguments)
result = await to_thread(func)
response["rpc"]["response"]["result"] = result
except Exception as exc:
response["rpc"]["response"]["error"] = str(exc)
await websocket.send_text(json.dumps(response))
case _:
pass
except WebSocketDisconnect:
pass
_, pending = await asyncio.wait(
[
asyncio.create_task(heartbeat()),
asyncio.create_task(relay()),
],
return_when=asyncio.FIRST_COMPLETED,
)
for task in pending:
task.cancel()
finally:
await disconnect(websocket)
redis = None
client = docker.from_env()
container = client.containers.get("redis")
hostname = container.attrs["Config"]["Hostname"]
@app.on_event("startup")
async def startup_event():
global redis
redis = Redis(host=hostname, port=6379, decode_responses=False)
await redis.ping()
@app.on_event("shutdown")
async def shutdown_event():
global redis
if redis:
await redis.close()
async def get_redis() -> Redis:
if not redis:
raise RuntimeError("Redis client is not initialized.")
return redis
async def download(
redis: Redis,
url: str,
filename: str,
ttl: timedelta = timedelta(days=365),
) -> tuple[AsyncGenerator[bytes, None], str] | None:
namespace = url.split("://", 1)[-1]
def key(parts: tuple[str, ...]) -> str:
return ":".join(parts)
async with redis.pipeline(transaction=True) as pipe:
pipe.get(key((namespace, filename, "content")))
pipe.get(key((namespace, filename, "hash")))
data, hash = await pipe.execute()
match data, hash:
case (bytes() as data, bytes() as hash) if all(value and value.strip() for value in (data, hash)):
async def stream():
yield data
return stream(), hash.decode()
async with httpx.AsyncClient(follow_redirects=True) as client:
response = await client.get(url)
if not response.is_success:
return None
ext = os.path.splitext(urlparse(url).path)[-1].lower()
async with redis.pipeline(transaction=True) as pipe:
def store(pipe, key_parts: tuple[str, ...], content: bytes, hash: str) -> None:
prefix = key(key_parts)
pipe.set(key((prefix, "hash")), hash, ex=ttl)
pipe.set(key((prefix, "content")), content, ex=ttl)
match ext:
case ".zip":
with zipfile.ZipFile(BytesIO(response.content)) as zf:
result = None
for name in zf.namelist():
content = zf.read(name)
content_hash = hashlib.sha1(content).hexdigest()
store(pipe, (namespace, name), content, content_hash)
if name == filename:
async def stream():
yield content
result = (stream(), content_hash)
await pipe.execute()
return result
case _:
data = response.content
content_hash = hashlib.sha1(data).hexdigest()
store(pipe, (namespace, filename), data, content_hash)
await pipe.execute()
async def stream():
yield data
return stream(), content_hash
@app.head("/", status_code=status.HTTP_201_CREATED)
async def healthcheck(redis: Redis = Depends(get_redis)):
await redis.ping()
return
@app.get("/", response_class=HTMLResponse)
async def index(request: Request):
artifacts = database.get("artifacts", [])
return templates.TemplateResponse(
request=request,
name="index.html",
context={"artifacts": artifacts},
)
router = APIRouter(prefix="/play/{runtime}/{organization}/{repository}/{release}/{resolution}")
@router.get("/", response_class=HTMLResponse)
async def play(
runtime: str,
organization: str,
repository: str,
release: str,
resolution: str,
request: Request,
):
mapping = {
"480p": (854, 480),
"720p": (1280, 720),
"1080p": (1920, 1080),
}
width, height = mapping[resolution]
url = f"/play/{runtime}/{organization}/{repository}/{release}/{resolution}/"
return templates.TemplateResponse(
request=request,
name="play.html",
context={
"url": url,
"width": width,
"height": height,
},
)
@router.get("/{filename}")
async def dynamic(
runtime: str,
organization: str,
repository: str,
release: str,
resolution: str,
filename: str,
redis: Redis = Depends(get_redis),
):
match filename:
case "bundle.7z":
url = f"https://github.com/{organization}/{repository}/releases/download/v{release}/bundle.7z"
media_type = "application/x-7z-compressed"
case "carimbo.js":
url = f"https://github.com/pigmentolabs/carimbo/releases/download/v{runtime}/WebAssembly.zip"
media_type = "application/javascript"
case "carimbo.wasm":
url = f"https://github.com/pigmentolabs/carimbo/releases/download/v{runtime}/WebAssembly.zip"
media_type = "application/wasm"
case _:
raise HTTPException(status_code=404)
result = await download(redis, url, filename)
if result is None:
raise HTTPException(status_code=404)
content, hash = result
now = datetime.utcnow()
timestamp = mktime(now.timetuple())
modified = format_date_time(timestamp)
duration = timedelta(days=365).total_seconds()
headers = {
"Cache-Control": f"public, max-age={int(duration)}, immutable",
"Content-Disposition": f'inline; filename="{filename}"',
"Last-Modified": modified,
"ETag": hash,
}
return StreamingResponse(
content=content,
media_type=media_type,
headers=headers,
)
app.include_router(router)