-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserverDev.html
More file actions
298 lines (274 loc) · 12.5 KB
/
Copy pathserverDev.html
File metadata and controls
298 lines (274 loc) · 12.5 KB
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Server Dev - pyproc</title>
<link rel="icon" href="../assets/logo.svg">
<meta name="theme-color" content="#0a0f1c">
<link rel="stylesheet" href="demo.css">
<script type="module" src="siteChrome.js"></script>
</head>
<body>
<div class="wrap">
<header class="site">
<a class="logo" href="../"><img class="logoMark" src="../assets/logo.svg" width="22" height="22" alt=""> <span><span class="py">py</span>proc</span></a>
<nav>
<a href="agentSandbox.html">Agent</a>
<a href="machine.html">Machine</a>
<a href="serverDev.html" class="on">Server</a>
<a href="speedLab.html">Speed</a>
<a href="terminal.html">Terminal</a>
<a href="processOs.html">Process OS</a>
<a href="basic.html">Basics</a>
</nav>
<sns-links></sns-links>
</header>
<h1>A Python web server, inside the browser</h1>
<p class="lead">FastAPI, SQLite, an editable <code>app.py</code>, and a real URL all run inside this tab.
The preview below is served by Python through a Service Worker virtual origin, with zero TCP sockets.</p>
<div class="panel">
<div class="status" id="st">Booting CPython and building the project...</div>
<div class="row" style="margin:.6rem 0 .2rem">
<span class="badge ok">FastAPI in the kernel</span>
<span class="badge info">SQLite on /home/web</span>
<span class="badge">fetch("./pyproc/...") is Python</span>
</div>
<div class="kv" id="stats" style="display:none">
<div class="k">boot</div><div id="bootMs"></div>
<div class="k">install</div><div id="installMs"></div>
<div class="k">route</div><div id="routeMs"></div>
<div class="k">dev loop</div><div id="devMs"></div>
</div>
</div>
<div class="panel">
<p class="dim" style="margin:0 0 .5rem">This is the live project file in <code>/home/web/server/app.py</code>. Edit it by pressing the button: the running app reloads without leaving the browser.</p>
<div class="row">
<button id="add">POST todo</button>
<button id="edit" class="ghost">Edit app.py -> v2</button>
<button id="reload" class="ghost">Reload preview</button>
</div>
<div class="term" id="out"></div>
</div>
<div class="panel">
<p class="dim" style="margin:0 0 .5rem">Preview iframe. Its URL is served by the Python ASGI app, not by the static file server.</p>
<iframe id="preview" title="pyproc server preview" style="width:100%;height:14rem;border:1px solid var(--border);border-radius:10px;background:white"></iframe>
</div>
<footer class="site">Chromium/Edge. Source: <a href="https://github.com/eddmpython/pyproc">github.com/eddmpython/pyproc</a> · <a href="https://www.npmjs.com/package/pyproc">npm install pyproc</a></footer>
</div>
<script type="module">
import { boot } from "../index.js";
const st = document.getElementById("st"), out = document.getElementById("out"), preview = document.getElementById("preview");
const el = (id) => document.getElementById(id);
const params = new URLSearchParams(location.search);
const gateMode = params.has("gate");
const INDEX = params.get("indexURL") ? new URL(params.get("indexURL"), location.href).href : undefined;
const ASGI_PREFIX = new URL("pyproc/", location.href).pathname;
const API = "./pyproc";
const log = (m) => { out.textContent += m + "\n"; out.scrollTop = out.scrollHeight; };
const gateReport = (ok) => {
if (!gateMode) return;
fetch("/gateReport", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ok: !!ok, checks: [{ name: document.title, pass: !!ok, info: (st.textContent + " | " + out.textContent).slice(-220) }] }),
}).catch(() => {});
};
const scriptClose = "</scr" + "ipt>";
function appSource(version) {
const page = [
"<!doctype html><html><body data-version='" + version + "' style='font:15px system-ui;margin:1.2rem;color:#111'>",
"<h1>pyproc FastAPI " + version + "</h1>",
"<p>This page came from Python running in the browser tab.</p>",
"<button id='add'>add from served page</button>",
"<ul id='list'></ul>",
"<script>",
"async function refresh(){",
" const rows = await (await fetch('./api/todos')).json();",
" document.getElementById('list').innerHTML = rows.map((x) => '<li>' + x.text + '</li>').join('');",
" parent.postMessage({ pyprocServerDev: { version: document.body.dataset.version, count: rows.length, items: rows.map((x) => x.text) } }, location.origin);",
"}",
"document.getElementById('add').onclick = async () => { await fetch('./api/todos', { method: 'POST', body: JSON.stringify({ text: 'from served page' }) }); refresh(); };",
"refresh();",
scriptClose,
"</body></html>",
].join("");
return [
"from fastapi import FastAPI, Request",
"from fastapi.responses import HTMLResponse",
"import os, sqlite3",
"",
`version = ${JSON.stringify(version)}`,
`page = ${JSON.stringify(page)}`,
"dbPath = '/home/web/server/data.db'",
"app = FastAPI()",
"",
"def getConn():",
" os.makedirs('/home/web/server', exist_ok=True)",
" conn = sqlite3.connect(dbPath)",
" conn.execute('CREATE TABLE IF NOT EXISTS todos (id INTEGER PRIMARY KEY, text TEXT)')",
" return conn",
"",
"def listTodos():",
" conn = getConn()",
" rows = [{'id': r[0], 'text': r[1]} for r in conn.execute('SELECT id, text FROM todos ORDER BY id')]",
" conn.close()",
" return rows",
"",
"@app.get('/', response_class=HTMLResponse)",
"async def home():",
" return page",
"",
"@app.get('/api/version')",
"async def getVersion():",
" return {'version': version}",
"",
"@app.get('/api/todos')",
"async def getTodos():",
" return listTodos()",
"",
"@app.post('/api/todos')",
"async def postTodo(req: Request):",
" body = await req.json()",
" conn = getConn()",
" conn.execute('INSERT INTO todos (text) VALUES (?)', (body['text'],))",
" conn.commit()",
" conn.close()",
" return {'ok': True, 'count': len(listTodos())}",
].join("\n");
}
async function clearDirectory(dir) {
for await (const [name, handle] of dir.entries()) {
await dir.removeEntry(name, { recursive: handle.kind === "directory" });
}
}
let machine, asgi, home;
async function writeApp(version) {
machine.runtime.setGlobal("appSrc", appSource(version));
machine.run("import os\nos.makedirs('/home/web/server', exist_ok=True)\nopen('/home/web/server/app.py', 'w').write(appSrc)");
await home.sync();
}
async function importApp(reload = false) {
machine.run(reload
? "import importlib, app as appModule\nappModule = importlib.reload(appModule)\napp = appModule.app"
: "import sys\nsys.path.insert(0, '/home/web/server')\nimport app as appModule\napp = appModule.app");
}
// 가상 오리진의 페이지측 배선. serverDevSw.js(번들 pyprocSw.js 자산의 ?asgi= 계약)가
// 가로챈 "/pyproc/..." fetch를 pyprocAsgi 메시지로 위임하면, 이 문서가 공개 asgi.serve
// 계약으로 응답한다. hello(pyprocKernelHello)로 자신을 커널 클라이언트로 등록해야
// 서빙된 iframe이 낸 fetch도 이 커널로 라우팅된다(SW 재시작 = 등록 증발이라 재전송).
function bindKernelOrigin() {
navigator.serviceWorker.addEventListener("message", async (e) => {
const req = e.data && e.data.pyprocAsgi;
if (!req) return;
try {
const r = await asgi.serve(req.method, req.path, req.body, req.query, req.headers);
e.ports[0].postMessage({ status: r.status, headers: r.headers, body: r.bodyBytes });
} catch (err) {
e.ports[0].postMessage({ error: String(err).slice(-300) });
}
});
const hello = () => {
if (navigator.serviceWorker.controller) navigator.serviceWorker.controller.postMessage({ pyprocKernelHello: true });
};
hello();
navigator.serviceWorker.addEventListener("controllerchange", hello);
}
async function registerVirtualOrigin() {
const reg = await navigator.serviceWorker.register(`serverDevSw.js?asgi=${encodeURIComponent(ASGI_PREFIX)}&asgiTimeout=30000`);
await navigator.serviceWorker.ready;
if (!navigator.serviceWorker.controller) {
await new Promise((res) => navigator.serviceWorker.addEventListener("controllerchange", res, { once: true }));
}
bindKernelOrigin();
return reg;
}
function waitServedFrame(timeoutMs = 15000) {
return new Promise((resolve) => {
const timer = setTimeout(() => resolve(null), timeoutMs);
const onMsg = (e) => {
if (e.origin !== location.origin || !e.data?.pyprocServerDev) return;
clearTimeout(timer);
removeEventListener("message", onMsg);
resolve(e.data.pyprocServerDev);
};
addEventListener("message", onMsg);
});
}
async function reloadPreview() {
const seen = waitServedFrame();
preview.src = `${API}/?t=${Date.now()}`;
return seen;
}
async function addTodo(text) {
const r = await fetch(`${API}/api/todos`, { method: "POST", body: JSON.stringify({ text }) });
return r.json();
}
async function start() {
const root = await navigator.storage.getDirectory();
const homeDir = await root.getDirectoryHandle(gateMode ? "pyprocServerDevGateHome" : "pyprocServerDevHome", { create: true });
if (gateMode) await clearDirectory(homeDir);
let t = performance.now();
machine = await boot({ indexURL: INDEX });
home = await machine.runtime.mountHome(homeDir);
const bootMs = Math.round(performance.now() - t);
el("bootMs").textContent = `${bootMs}ms`;
log(`boot: ${bootMs}ms`);
t = performance.now();
await machine.runtime.install("fastapi");
const installMs = Math.round(performance.now() - t);
el("installMs").textContent = `${installMs}ms`;
log(`fastapi install: ${installMs}ms`);
await writeApp("v1");
await importApp(false);
asgi = machine.runtime.enableAsgiServer();
await asgi.install();
await registerVirtualOrigin();
t = performance.now();
const version = await (await fetch(`${API}/api/version`)).json();
const routeMs = Math.round(performance.now() - t);
el("routeMs").textContent = `${routeMs}ms`;
document.getElementById("stats").style.display = "grid";
st.textContent = `Server live at ${API}/ (version ${version.version}).`;
log(`GET ${API}/api/version -> ${JSON.stringify(version)} in ${routeMs}ms`);
return version.version === "v1";
}
async function editToV2() {
const t = performance.now();
await writeApp("v2");
await importApp(true);
const version = await (await fetch(`${API}/api/version`)).json();
const devMs = Math.round(performance.now() - t);
el("devMs").textContent = `${devMs}ms`;
log(`edited app.py -> ${version.version} in ${devMs}ms`);
return version.version === "v2";
}
try {
const okStart = await start();
document.getElementById("add").onclick = async () => {
const r = await addTodo(`todo ${Date.now()}`);
log(`POST todo -> ${JSON.stringify(r)}`);
await reloadPreview();
};
document.getElementById("edit").onclick = async () => {
await editToV2();
await reloadPreview();
};
document.getElementById("reload").onclick = reloadPreview;
await addTodo("ship browser server");
const rows = await (await fetch(`${API}/api/todos`)).json();
const frame1 = await reloadPreview();
if (gateMode) {
const okEdit = await editToV2();
const frame2 = await reloadPreview();
const ok = okStart && rows.length >= 1 && frame1?.count >= 1 && okEdit && frame2?.version === "v2";
gateReport(ok);
}
} catch (e) {
st.textContent = "Failed";
log("Error: " + String(e).slice(-260));
gateReport(false);
}
</script>
</body>
</html>