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
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 --versiontrướ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.tscù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:
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;
});
});
bun server.mjsDù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.portlà observed bound port. - Owner
servicesố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.
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:
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();
}
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.
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 });
}
});
bun file.mjs02 · Server-Sent EventsHai event một chiều và một terminal rõ ràng.
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();
});
bun sse.mjs03 · WebSocketSubprotocol, greeting và text echo hai chiều.
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();
});
bun websocket.mjs04 · Kết hợp trong một serviceBài tích hợp tùy chọn sau khi ba contract riêng đã rõ.
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;
});
});
bun advanced.mjsDù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ệc | Bun API | Invariant |
|---|---|---|
| Snapshot | routes / routeSnapshot() | Core-issued coherent cut. |
| Rebind | prepareHandler + rebindHandler | Expected generation/revision. |
| Publish | publishRoutes | Complete structural generation. |
| TLS rotation | tlsReload | Typed applied/rejected outcome. |
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.
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.
disposecleanup đúng một lần.- Mỗi low-level lane một reader.
- Không exit khi close chưa settle.