Study · Bun + TypeScript · exact package 2.3.2
Bun is its own app host, not a Node alias
Bun keeps its own toolchain and host lifecycle. Package 2.3.2 uses the same typed CoAkka HTTP Runtime contract with a separate registry identity and qualification lane.
Beginner · 01 / 04
Install the package published for Bun
mkdir coakka-http-bun-study
cd coakka-http-bun-study
bun init -y
bun add --exact [email protected]- Bun
- 1.2.22+; run
bun --versionbefore installation. - Package
[email protected]; do not import the Node package and assume compatibility.- Native payload
- The tarball bundles macOS arm64, Linux x64/arm64 and Windows x64/arm64; the loader selects from the Bun process.
- TypeScript
- The package includes the released
index.d.tscontract; use the declaration's exact camelCase names.
Beginner · 02 / 04
Run the service under Bun itself
Save the complete file below as 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.mjsUse the printed URL or run curl -i http://127.0.0.1:49321/hello/Ada → 200 hello Ada. Ctrl+C invokes the close() Promise; do not exit before it settles.
127.0.0.1- Study stays on loopback.
0- The OS selects a port;
service.portis the observed bound port. - Owner
serviceremains in the signal closure until close completes or reports failure.
Beginner · 03 / 04
Typed request values belong to the 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- Preserves order, duplicates and null-versus-empty.
headers.getAll()- Case-insensitive lookup with duplicate values intact.
request.bytes()- A defensive body copy within the configured bound; large uploads use
postStream. Response.text- The app chooses status, headers and body; Core validates HTTP output.
Beginner · 04 / 04
Outbound runs in the Bun host, not through Node
Keep the server running and save this as 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"Replace 49321 with the real port. Expect 200 hello Ada. Match call slot/generation and terminal reason before reading status/body, and always await close in finally.
Advanced · 05
Learn one capability at a time, then combine them
Each first file opens one endpoint with the Bun 2.3.2 package, never the Node substitute.
01 · File deliveryAuthority, path and limits; the Runtime selects sendfile when eligible.
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 EventsTwo one-way events and an explicit terminal.
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 and bidirectional text echo.
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 · Combine them in one serviceAn optional integration exercise after the three contracts are clear.
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.mjsUse Ctrl+C to close the service. Look up parameters, failure modes and monitoring.
Find all feature guides · Try gzip · Run the upload labs · Resume a large upload · Try V1 handler replacement
Advanced · 06
Control uses generation-checked truth
| Operation | Bun API | Invariant |
|---|---|---|
| Snapshot | routes / routeSnapshot() | A Core-issued coherent cut. |
| Rebind | prepareHandler + rebindHandler | Expected generation and revision. |
| Publish | publishRoutes | One complete structural generation. |
| TLS rotation | tlsReload | A typed applied or rejected outcome. |
Advanced · 07
Effective state and Monitor in a Bun app host
runtimeInfo()- Core-issued requested, probed and effective provider facts.
health()/probeLiveness()- Direct health and a bounded fresh probe do not require Monitor.
- Monitor
- Reserve before start, then pull config, snapshots and events; a signal is only a hint.
pollError()- A bounded async handler or producer diagnostic, never a second response.
- Low-level runtime
- One reader per lane; Promise polling does not block the Bun event loop.
Advanced · 08
Failure, awaited close and Bun quick reference
- Identity
- Record Bun path/version/OS/CPU, package and tarball hash, and the loaded native path.
- Async
- Await handlers, producers, writers and readers; never busy-poll the event loop.
- Outbound
- Reason, phase, retry and certainty are typed Core facts; HTTP status does not define delivery safety.
- Close
- Await the Promise; refused drain retains the service owner for a safe retry.
- Support
- A Node execution does not substitute for Bun evidence even when source shapes match.
- Bun 1.2.22+ and the exact Bun package 2.3.2.
- Do not import the Node package.
disposecleans up exactly once.- Keep one reader per low-level lane.
- Never exit while close is unsettled.