-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.mjs
83 lines (70 loc) · 2.06 KB
/
index.mjs
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
import { spawn } from "child_process";
import http from "http";
import WebSocket, { WebSocketServer } from "ws";
const API_TOKEN = process.env.API_TOKEN
? process.env.API_TOKEN.length
? process.env.API_TOKEN
: undefined
: undefined;
const PORT = Number(process.env.PORT);
if (!PORT) {
throw new Error("Error: `PORT` environment variable is not defined.");
}
const server = http.createServer();
const wss = new WebSocketServer({ server });
wss.on("connection", (ws) => {
const lc0 = spawn("lc0", ["-w", "/lc0/build/release/tinygyal-8.pb.gz"]);
let isAuthenticated = !API_TOKEN;
lc0.stdout.on("data", (data) => {
const lines = data
.toString()
.trim()
.split("\n")
.map((line) => line.trim());
lines.forEach((line) => {
console.debug("[lc0]", line);
if (isAuthenticated) {
ws.send(JSON.stringify({ type: "uci:response", payload: line }));
}
});
});
ws.on("message", (message) => {
try {
const messageData = JSON.parse(message);
switch (messageData.type) {
case "auth:authenticate":
console.debug("[authenticate]", messageData.payload);
if (!API_TOKEN || messageData.payload === API_TOKEN) {
isAuthenticated = true;
ws.send(JSON.stringify({ type: "auth:authenticated" }));
} else {
ws.send(JSON.stringify({ type: "auth:unauthenticated" }));
}
break;
case "uci:command":
console.debug("[uci:command]", messageData.payload);
if (isAuthenticated) {
lc0.stdin.write(`${messageData.payload}\n`);
}
break;
}
} catch (error) {
console.error("Error parsing message: ", error);
}
});
ws.on("close", () => {
lc0.kill();
});
});
server.on("request", (req, res) => {
if (req.url === "/check") {
res.writeHead(200);
res.end("LeelaDocker is up and running.");
} else {
res.writeHead(404);
res.end("Not found");
}
});
server.listen(PORT, () => {
console.log(`Server is up and running on port ${PORT}.`);
});