parent
85205593e4
commit
817cc92dd3
@ -1,2 +1,8 @@
|
||||
node_modules
|
||||
bun.lockb
|
||||
pnpm-lock.yaml
|
||||
|
||||
.idea
|
||||
.vscode
|
||||
*.js
|
||||
*.tsbuildinfo
|
||||
|
@ -0,0 +1,3 @@
|
||||
# labyrinth
|
||||
|
||||
The HTTP backend for the Sandkasten website.
|
@ -1,21 +1,56 @@
|
||||
import { Client, TcpClient } from 'msgpack-rpc-node';
|
||||
import http from 'http';
|
||||
import { nanoid } from 'nanoid';
|
||||
import { Pull, Push } from 'zeromq';
|
||||
|
||||
const RPC_PORT = 9000;
|
||||
const client = new Client(TcpClient, RPC_PORT);
|
||||
await client.connect();
|
||||
const host = 'localhost';
|
||||
const port = 3000;
|
||||
|
||||
const server = Bun.serve({
|
||||
port: 3000,
|
||||
fetch(request) {
|
||||
const url = new URL(request.url);
|
||||
switch (url.pathname) {
|
||||
case '/run':
|
||||
client.call('Add', 'echo $(( 1 + 2 ))', 'msh').then(console.log);
|
||||
return new Response('Your code is running...');
|
||||
default:
|
||||
return new Response('404!', { status: 404 });
|
||||
}
|
||||
},
|
||||
const sender = new Push();
|
||||
await sender.bind(`tcp://127.0.0.1:5567`);
|
||||
const receiver = new Pull();
|
||||
await receiver.bind(`tcp://127.0.0.1:5568`);
|
||||
|
||||
const generateId = () => nanoid(32);
|
||||
|
||||
const clients: Record<string, http.ServerResponse> = {};
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
switch (req.url) {
|
||||
case '/run':
|
||||
const jobId = generateId();
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'text/event-stream',
|
||||
Connection: 'keep-alive',
|
||||
'Cache-Control': 'no-cache',
|
||||
});
|
||||
sender.send(`${jobId}echo a`).then(() => {
|
||||
res.write('event: connected\n');
|
||||
res.write(`data: ${jobId}\n`);
|
||||
res.write('id: 0\n');
|
||||
});
|
||||
req.on('close', () => {
|
||||
res.end('OK');
|
||||
delete clients[jobId];
|
||||
});
|
||||
clients[jobId] = res;
|
||||
break;
|
||||
default:
|
||||
res.writeHead(404);
|
||||
res.end('404!');
|
||||
}
|
||||
});
|
||||
server.listen(port, () => {
|
||||
console.log(`Server is running on http://${host}:${port}`);
|
||||
});
|
||||
|
||||
console.log(`Listening on http://localhost:${server.port}`);
|
||||
for await (const [buff] of receiver) {
|
||||
const jobId = buff.slice(0, 32).toString();
|
||||
console.log(`Received ${jobId}`);
|
||||
const res = clients[jobId];
|
||||
if (!res) {
|
||||
continue;
|
||||
}
|
||||
res.write('event: message\n');
|
||||
res.write(`data: ${encodeURIComponent(buff.slice(32).toString())}\n`);
|
||||
res.write('id: 0\n');
|
||||
}
|
||||
|
Loading…
Reference in new issue