ソースを参照

Update Bun (#9211)

* update bun

* use bun build --compile

* kill children on parent exit
Daniil Zotov 1 年間 前
コミット
61ebc1487c

+ 5 - 3
frameworks/TypeScript/bun/bun.dockerfile

@@ -1,13 +1,15 @@
-FROM oven/bun:1.0
+FROM oven/bun:1.1
 
 EXPOSE 8080
 
 WORKDIR /app
 
-USER bun
-
 COPY ./src .
 
 ENV NODE_ENV=production
 
+RUN bun build --compile --minify --outfile server .
+
+USER bun
+
 CMD ["bun", "spawn.ts"]

+ 7 - 7
frameworks/TypeScript/bun/src/index.ts

@@ -1,5 +1,5 @@
-const HELLO_WORLD_STR = "Hello, World!";
-const options: ResponseInit = { headers: { "Server": "Bun" } };
+const plainOptions: ResponseInit = { headers: { "Server": "Bun" } };
+const jsonOptions: ResponseInit = { headers: { "Server": "Bun", "Content-Type": "application/json" } };
 
 const server = Bun.serve({
   port: 8080,
@@ -7,16 +7,16 @@ const server = Bun.serve({
   fetch(req: Request) {
     const pathname = req.url.slice(req.url.indexOf("/", 8));
 
-    if (pathname === "/json") {
-      return Response.json({ message: HELLO_WORLD_STR }, options);
+    if (pathname == "/json") {
+      return new Response(JSON.stringify({ message: "Hello, World!" }), jsonOptions);
     }
 
-    if (pathname === "/plaintext") {
-      return new Response(HELLO_WORLD_STR, options);
+    if (pathname == "/plaintext") {
+      return new Response("Hello, World!", plainOptions);
     }
 
     return new Response("", { status: 404 })
   },
 });
 
-console.log(`Listening on localhost:${server.port}`);
+console.log(`Listening on ${server.url}\n`);

+ 13 - 4
frameworks/TypeScript/bun/src/spawn.ts

@@ -1,9 +1,18 @@
-import os from "node:os";
+const cpus = navigator.hardwareConcurrency;
+const buns = new Array(cpus);
 
-const numCPUs = os.cpus().length;
-for (let i = 0; i < numCPUs; i++) {
-  Bun.spawn(["bun", "index.ts"], {
+for (let i = 0; i < cpus; i++) {
+  buns[i] = Bun.spawn(["./server"], {
     stdio: ["inherit", "inherit", "inherit"],
     env: { ...process.env },
   });
 }
+
+function kill() {
+  for (const bun of buns) {
+    bun.kill();
+  }
+}
+
+process.on("SIGINT", kill);
+process.on("exit", kill);