File size: 5,810 Bytes
428e1c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
befafc9
 
428e1c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import asyncio
import os
import subprocess
import tarfile
import time
import urllib.request
from pathlib import Path

import httpx
import spaces
import gradio as gr
import websockets
from starlette.responses import RedirectResponse, StreamingResponse
from starlette.background import BackgroundTask
from starlette.routing import Route, WebSocketRoute

CODE_VERSION = "4.128.0"
CODE_PORT = 8080
CODE_BACKEND = f"http://127.0.0.1:{CODE_PORT}"
CODE_DIR = Path.home() / ".code-server"
METHODS = ["GET", "POST", "PUT", "DELETE", "PATCH"]


def ensure_code_server():
    name = f"code-server-{CODE_VERSION}-linux-amd64"
    binary = CODE_DIR / name / "bin" / "code-server"
    if binary.exists():
        return str(binary)
    CODE_DIR.mkdir(parents=True, exist_ok=True)
    url = f"https://github.com/coder/code-server/releases/download/v{CODE_VERSION}/{name}.tar.gz"
    archive = CODE_DIR / f"{name}.tar.gz"
    urllib.request.urlretrieve(url, archive)
    with tarfile.open(archive, "r:gz") as tar:
        tar.extractall(CODE_DIR, filter="data")
    archive.unlink()
    return str(binary)


def start_code_server():
    binary = ensure_code_server()
    workspace = Path.home() / "workspace"
    workspace.mkdir(parents=True, exist_ok=True)
    password = os.environ.get("CODE_SERVER_PASSWORD")
    if not password:
        raise RuntimeError("CODE_SERVER_PASSWORD must be configured as a Space secret")
    env = dict(os.environ, PASSWORD=password)
    subprocess.Popen(
        [binary, "--bind-addr", f"127.0.0.1:{CODE_PORT}", "--auth", "password",
         "--disable-telemetry", "--disable-update-check", str(workspace)],
        env=env,
    )
    for _ in range(120):
        try:
            httpx.get(CODE_BACKEND, timeout=1.0)
            return
        except Exception:
            time.sleep(0.5)


# ZeroGPU requires the app to launch through Gradio with at least one
# @spaces.GPU function, or the Space never reaches RUNNING.
@spaces.GPU(duration=30)
def health():
    out = subprocess.run(["nvidia-smi"], capture_output=True, text=True)
    return out.stdout or out.stderr


with gr.Blocks() as demo:
    gr.Markdown(
        "code-server: `/code/`\n\n"
        "---\n"
        "Made with love by latemate\n"
        "Updated by @conabe511"
    )
    btn = gr.Button("health check")
    box = gr.Textbox()
    btn.click(health, outputs=box)

client = httpx.AsyncClient(base_url=CODE_BACKEND, timeout=None)
HOP_BY_HOP = {"transfer-encoding", "connection", "keep-alive", "content-length"}


def strip(path):
    return path[len("/code"):] or "/"


async def code_http(request):
    if request.url.path == "/code":
        return RedirectResponse("/code/")
    url = httpx.URL(path=strip(request.url.path), query=request.url.query.encode())
    content = request.stream() if request.method in ("POST", "PUT", "PATCH", "DELETE") else None
    headers = [(k, v) for k, v in request.headers.raw]
    headers.append((b"x-forwarded-proto", b"https"))
    upstream = client.build_request(request.method, url, headers=headers, content=content)
    resp = await client.send(upstream, stream=True)
    out = {k.decode(): v.decode() for k, v in resp.headers.raw if k.decode().lower() not in HOP_BY_HOP}
    return StreamingResponse(resp.aiter_raw(), status_code=resp.status_code,
                              headers=out, background=BackgroundTask(resp.aclose))


async def code_ws(websocket):
    subprotocols = websocket.scope.get("subprotocols") or []
    await websocket.accept(subprotocol=subprotocols[0] if subprotocols else None)

    target = f"ws://127.0.0.1:{CODE_PORT}{strip(websocket.url.path)}"
    if websocket.url.query:
        target += "?" + websocket.url.query
    fwd = {}
    if websocket.headers.get("cookie"):
        fwd["cookie"] = websocket.headers["cookie"]

    kwargs = dict(subprotocols=subprotocols or None, max_size=None, open_timeout=30)
    try:
        try:
            upstream = await websockets.connect(target, additional_headers=fwd, **kwargs)
        except TypeError:
            upstream = await websockets.connect(target, extra_headers=fwd, **kwargs)
    except Exception:
        try:
            await websocket.close()
        except Exception:
            pass
        return

    async def client_to_upstream():
        try:
            while True:
                msg = await websocket.receive()
                if msg["type"] == "websocket.disconnect":
                    break
                if msg.get("bytes") is not None:
                    await upstream.send(msg["bytes"])
                elif msg.get("text") is not None:
                    await upstream.send(msg["text"])
        except Exception:
            pass
        finally:
            await upstream.close()

    async def upstream_to_client():
        try:
            async for message in upstream:
                if isinstance(message, (bytes, bytearray)):
                    await websocket.send_bytes(message)
                else:
                    await websocket.send_text(message)
        except Exception:
            pass
        finally:
            try:
                await websocket.close()
            except Exception:
                pass

    await asyncio.gather(client_to_upstream(), upstream_to_client())


if __name__ == "__main__":
    start_code_server()
    demo.launch(
        server_name="0.0.0.0",
        server_port=int(os.environ.get("PORT", "7860")),
        ssr_mode=False,
        prevent_thread_lock=True,
    )
    # Insert before Gradio's own catch-all routes.
    demo.app.router.routes[0:0] = [
        WebSocketRoute("/code", code_ws),
        WebSocketRoute("/code/{path:path}", code_ws),
        Route("/code", code_http, methods=METHODS),
        Route("/code/{path:path}", code_http, methods=METHODS),
    ]
    demo.block_thread()