Study · Bun + TypeScript · exact package 2.3.2

Bun là app host riêng, không phải Node alias

Bun giữ toolchain và host lifecycle riêng. Package 2.3.2 dùng cùng typed CoAkka HTTP Runtime contract nhưng có registry identity và qualification riêng.

Beginner · 01 / 04

Cài package được phát hành cho Bun

Terminal
mkdir coakka-http-bun-study
cd coakka-http-bun-study
bun init -y
bun add --exact [email protected]
Bun
1.2.22+; chạy bun --version trước khi cài.
Package
[email protected]; không import Node package để giả định compatibility.
Native payload
Tarball chứa macOS arm64, Linux x64/arm64 và Windows x64/arm64; loader chọn theo Bun process.
TypeScript
Package có index.d.ts cùng contract surface đã phát hành; dùng camelCase names đúng declaration.

Beginner · 02 / 04

Chạy service bằng Bun thật

Lưu file dưới thành server.mjs:

server.mjs
import { Builder, Response } from "coakka-http-runtime-bun";

const service = new Builder()
  .listen("127.0.0.1", 0)
  .get("/hello/{name}", (request) => {
    const encodedName = request.pathParameters[0].encodedValue;
    const name = Buffer.from(encodedName).toString("utf8");
    return Response.text(`hello ${name}`, { status: 200 });
  })
  .start();

console.log(`http://127.0.0.1:${service.port}/hello/Ada`);
console.log("Press Ctrl+C to close");

process.once("SIGINT", () => {
  service.close().catch((error) => {
    console.error("CoAkka HTTP Runtime close failed", error);
    process.exitCode = 1;
  });
});
Terminal
bun server.mjs

Dùng URL được in ra hoặc curl -i http://127.0.0.1:49321/hello/Ada → 200 hello Ada. Ctrl+C gọi Promise close(); không exit trước khi nó settle.

127.0.0.1
Chỉ loopback trong Study.
0
OS chọn port; service.port là observed bound port.
Owner
service sống trong signal closure cho đến khi close hoàn tất hoặc trả failure.

Beginner · 03 / 04

Typed request values đã thuộc JavaScript host

const encodedName = request.pathParameters[0].encodedValue;
const name = Buffer.from(encodedName).toString("utf8");
return Response.text(`hello ${name}`, { status: 200 });
pathParameters
Ordered percent-encoded byte captures.
queryParameters
Giữ order, duplicates và null-versus-empty.
headers.getAll()
Case-insensitive lookup, duplicate values còn nguyên.
request.bytes()
Defensive body copy trong configured bound; upload lớn dùng postStream.
Response.text
App chọn status/headers/body; Core validate HTTP output.

Request anatomy đầy đủ

Beginner · 04 / 04

Outbound chạy trong Bun host, không qua Node

Giữ server đang chạy, lưu file thành outbound.mjs:

outbound.mjs
import {
  Builder,
  OutboundReason,
  TransportSecurity,
} from "coakka-http-runtime-bun";

const port = Number.parseInt(process.argv[2] ?? "", 10);
if (!Number.isInteger(port) || port < 1 || port > 65_535) {
  throw new TypeError("Pass the server port as the first argument");
}

const service = new Builder()
  .outboundTarget({
    name: "hello",
    generation: 1,
    endpoints: [{
      nodeId: "loopback",
      connectHost: "127.0.0.1",
      connectPort: port,
      httpAuthority: `127.0.0.1:${port}`,
      security: TransportSecurity.PLAINTEXT,
    }],
  })
  .start();

try {
  const call = service.outboundSubmit({
    logicalTarget: "hello",
    method: "GET",
    target: "/hello/Ada",
    timeoutMillis: 3_000,
  });
  const terminal = await service.takeOutbound(5_000);
  if (terminal === null) {
    throw new Error("No outbound terminal within five seconds");
  }
  if (
    terminal.call.slot !== call.slot
    || terminal.call.generation !== call.generation
  ) {
    throw new Error("Outbound terminal belongs to another call");
  }
  if (terminal.reason !== OutboundReason.RESPONSE) {
    throw new Error(`Outbound ended with reason ${terminal.reason}`);
  }
  console.log(
    terminal.responseStatus,
    new TextDecoder().decode(terminal.body),
  );
} finally {
  await service.close();
}
Terminal
SERVER_PORT=49321
bun outbound.mjs "$SERVER_PORT"

Thay 49321 bằng port thật. Kết quả 200 hello Ada. Match call slot/generation và terminal reason trước khi đọc status/body; luôn await close trong finally.

Advanced · 05

Học từng capability trước khi kết hợp

Mỗi file đầu tiên chỉ mở một endpoint bằng package Bun 2.3.2, không thay bằng package Node.

01 · File deliveryAuthority, path và limit; Runtime tự chọn sendfile khi đủ điều kiện.
file.mjs
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { Builder, FileResponse } from "coakka-http-runtime-bun";

const root = mkdtempSync(join(tmpdir(), "coakka-http-file-"));
writeFileSync(join(root, "manual.txt"), "CoAkka file delivery\n");

const service = new Builder()
  .listen("127.0.0.1", 0)
  .fileAuthority({
    id: 1,
    rootPath: root,
    maxActiveFiles: 4,
    maxFileBytes: 1024,
  })
  .get("/download", () => new FileResponse(1, "/manual.txt"), { response: "file" })
  .start();

console.log(`curl http://127.0.0.1:${service.port}/download`);

process.once("SIGINT", async () => {
  try {
    await service.close();
  } finally {
    rmSync(root, { recursive: true, force: true });
  }
});
Chạy
bun file.mjs
02 · Server-Sent EventsHai event một chiều và một terminal rõ ràng.
sse.mjs
import { Builder, sse } from "coakka-http-runtime-bun";

const service = new Builder()
  .listen("127.0.0.1", 0)
  .get("/events", () => sse([
    { data: "ready", event: "state", id: "1", retry: 1000n },
    { data: "done" },
  ]), { response: "sse" })
  .start();

console.log(`curl -N http://127.0.0.1:${service.port}/events`);

process.once("SIGINT", async () => {
  await service.close();
});
Chạy
bun sse.mjs
03 · WebSocketSubprotocol, greeting và text echo hai chiều.
websocket.mjs
import { Builder, websocket } from "coakka-http-runtime-bun";

const service = new Builder()
  .listen("127.0.0.1", 0)
  .get("/socket", () => websocket({
    protocol: "coakka.demo",
    open(session) {
      session.send("ready");
    },
    message(session, message) {
      if (message.type === "text") session.send(`echo: ${message.data}`);
    },
  }), { response: "websocket" })
  .start();

console.log(
  `new WebSocket('ws://127.0.0.1:${service.port}/socket', 'coakka.demo')`,
);

process.once("SIGINT", async () => {
  await service.close();
});
Chạy
bun websocket.mjs
04 · Kết hợp trong một serviceBài tích hợp tùy chọn sau khi ba contract riêng đã rõ.
advanced.mjs
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
  Builder,
  FileResponse,
  sse,
  websocket,
} from "coakka-http-runtime-bun";

const root = mkdtempSync(join(tmpdir(), "coakka-http-advanced-"));
writeFileSync(join(root, "manual.txt"), "CoAkka file delivery\n");

const service = new Builder()
  .listen("127.0.0.1", 0)
  .fileAuthority({
    id: 1,
    rootPath: root,
    maxActiveFiles: 4,
    maxFileBytes: 1024,
  })
  .get("/download", () => new FileResponse(1, "/manual.txt"), { response: "file" })
  .get("/events", () => sse([
    { data: "ready", event: "state", id: "1", retry: 1000n },
    { data: "done" },
  ]), { response: "sse" })
  .get("/socket", () => websocket({
    protocol: "coakka.demo",
    open(session) {
      session.send("ready");
    },
    message(session, message) {
      if (message.type === "text") session.send(`echo: ${message.data}`);
    },
  }), { response: "websocket" })
  .start();

console.log(`file: curl http://127.0.0.1:${service.port}/download`);
console.log(`SSE:  curl -N http://127.0.0.1:${service.port}/events`);
console.log(`WS:   new WebSocket('ws://127.0.0.1:${service.port}/socket', 'coakka.demo')`);

let closing = false;
async function close() {
  if (closing) return;
  closing = true;
  try {
    await service.close();
  } finally {
    rmSync(root, { recursive: true, force: true });
  }
}

process.once("SIGINT", () => {
  close().catch((error) => {
    console.error("CoAkka HTTP Runtime close failed", error);
    process.exitCode = 1;
  });
});
Chạy bài tích hợp
bun advanced.mjs

Dùng Ctrl+C để đóng service. Tra tham số, failure mode và monitor.

Tra cứu toàn bộ tính năng · Thử gzip · Chạy bài upload · Tiếp tục tải tệp lớn lên · Thử đổi handler trên Listener V1

Advanced · 06

Control dùng generation-checked truth

ViệcBun APIInvariant
Snapshotroutes / routeSnapshot()Core-issued coherent cut.
RebindprepareHandler + rebindHandlerExpected generation/revision.
PublishpublishRoutesComplete structural generation.
TLS rotationtlsReloadTyped applied/rejected outcome.

Live control decision guide

Advanced · 07

Effective state và Monitor trong Bun app host

runtimeInfo()
Requested/probed/effective provider facts từ Core.
health() / probeLiveness()
Direct health và bounded fresh probe không cần Monitor.
Monitor
Reserve trước start, rồi pull config/snapshot/events; signal chỉ là hint.
pollError()
Bounded async handler/producer diagnostic, không phải response thứ hai.
Low-level runtime
Mỗi lane một reader; Promise polling không block Bun event loop.

Monitoring & evidence · Finite lifecycle

Advanced · 08

Failure, awaited close và Bun quick reference

Identity
Ghi Bun path/version/OS/CPU, package/tarball hash và loaded native path.
Async
Await handlers/producers/writers/readers; không busy-poll event loop.
Outbound
Reason/phase/retry/certainty là typed Core facts; HTTP status không định nghĩa delivery safety.
Close
Await Promise; refused drain giữ service owner để retry an toàn.
Support
Node execution không thay thế Bun evidence dù source shape giống nhau.
  • Bun 1.2.22+ và exact Bun package 2.3.2.
  • Không import Node package.
  • dispose cleanup đúng một lần.
  • Mỗi low-level lane một reader.
  • Không exit khi close chưa settle.