Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ The [package receipt](reports/2026-09-06-baz-extraction.md) records external-dep
verification and source identity. The [prototype receipt](reports/2026-09-06-app-api.md)
preserves the earlier combined engine/framework gates.

Current deployment is IPv4 loopback, plain HTTP/1.1. TLS is out of scope.
The listener defaults to IPv4 loopback; an explicit IPv4 address supports LAN clients over plain HTTP/1.1. TLS is out of scope.
Mustache uses a [pure Zig library with bounded rendering](docs/MUSTACHE.md).
WebSockets needs an engine upgrade lifecycle. Native Windows x64 now has its own
[CI gate](.github/workflows/windows-build.yml), alongside Linux and macOS.
Expand All @@ -205,6 +205,13 @@ until their owners finish. Application services and the caller's I/O provider
have their own resource responsibilities. Read the ownership contract before
retaining slices or introducing asynchronous work.

### Migration conveniences

[The migration guide](docs/MIGRATION-HELPERS.md) includes runnable LAN binding,
runtime file downloads with `Stream.copyFrom`, caller-allocator decoded field
iteration, and `defaultErrorStatus` for custom error hooks. The same guide is
available from the website's Examples section.

## License

Baz is [MIT licensed](LICENSE). The adapted Zap examples retain their
Expand Down
2 changes: 1 addition & 1 deletion build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ pub fn build(b: *std.Build) void {
check.dependOn(&middleware_fixture.step);
verify.dependOn(&middleware_fixture.step);
const examples = b.step("examples", "Build and install all supported Zap example ports");
for ([_][]const u8{ "hello", "hello2", "hello_json", "simple_router", "routes", "serve", "sendfile", "senderror", "accept", "app_basic", "app_auth", "app_errors", "endpoint", "endpoint_auth", "middleware", "middleware_with_endpoint", "userpass_session", "cookies", "http_params", "bindataformpost", "streaming", "mustache", "continuations", "jobs" }) |name| {
for ([_][]const u8{ "hello", "hello2", "hello_json", "simple_router", "routes", "serve", "sendfile", "senderror", "accept", "app_basic", "app_auth", "app_errors", "endpoint", "endpoint_auth", "middleware", "middleware_with_endpoint", "userpass_session", "cookies", "http_params", "bindataformpost", "streaming", "mustache", "continuations", "jobs", "runtime_file", "decoded_forms" }) |name| {
const example = b.addExecutable(.{
.name = name,
.use_llvm = if (target.result.os.tag == .linux and optimize == .Debug) true else null,
Expand Down
4 changes: 2 additions & 2 deletions build.zig.zon
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
.hash = "zli-0.1.1-pechgr4WAQBsw7p7JPU-GHHZ5xsBpEdfCRNpNtnQYnBz",
},
.bounded_http = .{
.url = "https://github.com/technologylab-ai/bounded-http/archive/886b728bec79c36ca1ec69345b609a725617a9ea.tar.gz",
.hash = "bounded_http-0.1.0-N3A1uB4HEgAhXPoOmXYv6DaPKLMYITEZJSk0kIsjrpMn",
.url = "https://github.com/technologylab-ai/bounded-http/archive/3f0ef4644ddb51092a0580c207fc5e0f2c5de9a0.tar.gz",
.hash = "bounded_http-0.1.0-N3A1uHM2EgBKoC7YKDOd0v0zue5SYOuYGFlD_rIMSPu_",
},
},
.paths = .{ "build.zig", "build.zig.zon", ".zig-version", "src", "tests", "tools", "examples", "docs", "reports", ".github", "LICENSE", "README.md", "ROADMAP.md", "HANDOFF.md", "AGENTS.md" },
Expand Down
10 changes: 8 additions & 2 deletions docs/APP-API.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ On Windows, use `zig-out/bin/baz.exe` and `curl.exe`.
The upload example has an 8 KiB body limit; choose a smaller file if needed.
It returns part metadata, lengths and byte sums, and does not save files.
`zig build run-app -- --port 8080` also runs the example. It binds IPv4
loopback and serves plain HTTP/1.1; inherited deployment limits remain in
loopback by default and serves plain HTTP/1.1; inherited deployment limits remain in
[README](../README.md). Public module exports are in [web.zig](../src/web.zig).

## App and endpoint composition
Expand Down Expand Up @@ -94,7 +94,9 @@ OPTIONS and method failures supply `Allow`; OPTIONS `*` lists App methods.
Unknown paths get 404 and unsupported methods on known paths get 405. An App
can supply `not_found` and `on_error` handlers. Error hooks receive the same typed
context after discarding the unpublished draft; failure in a hook produces a
bounded generic 500. CONNECT is currently 501.
bounded generic 500. Use `web.defaultErrorStatus(err)` inside a custom hook to
retain Baz's existing classifications while customizing presentation or adding
application-specific errors. CONNECT is currently 501.

## Borrowed request bytes

Expand All @@ -113,6 +115,7 @@ part in a background task.
| `try request.query()` | Bounded, validated pair view with default limits. |
| `queryWithLimits(limits)` | Caller-selected byte/pair/name/value limits. |
| `fields.iterator()` | Ordered `name_raw`, `value_raw`, `has_equals`. |
| `fields.decodedIterator(allocator, encoding)` | Owned decoded `name`, `value`, `has_equals`; explicit `.percent` or `.form` policy, ordered duplicates. |
| `fields.firstRaw(name)` / `allRaw(name)` | Exact raw-name matching; returns the first pair / an iterator over repeats. |
| `params.percentDecodeInto(raw, dst)` | Strict percent decoding; literal `+` stays `+`. |
| `params.formDecodeInto(raw, dst)` | Strict percent decoding plus `+` → space. |
Expand Down Expand Up @@ -294,3 +297,6 @@ overhead. wrk revisions differ across hosts; Zap retains its inherited `-Os`
and `-fno-sanitize=undefined` C flags. Bodies were checked before and after timing,
not individually throughout the load. The [full receipt](../reports/2026-09-06-basic-zap.md)
contains all ranges, source identities, commands, raw trials and cleanup records.

See the [migration conveniences guide](MIGRATION-HELPERS.md) for allocator/result
lifetimes, runtime file copying, custom errors, and IPv4 listener configuration.
8 changes: 8 additions & 0 deletions docs/DEPENDENCY.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,14 @@ records exact source identity, environments, and Windows handoff/shutdown behavi
The older tested `e52f09f` pin and provisional `bb14d987` draft remain in history.
The [repository record](REPOSITORY.md) describes branches and publication.

## IPv4 listener configuration

The current pin adopts configurable IPv4 binding from [engine PR #6](https://github.com/technologylab-ai/bounded-http/pull/6).
Merge that engine PR before the Baz adoption PR. The immutable source and package
hash remain explicit in `build.zig.zon`. Baz exposes the engine's `Config.bind_address`
and `Config.parseBindAddress` directly. The [migration guide](MIGRATION-HELPERS.md)
shows LAN startup alongside the Baz-owned reader, form, and error conveniences.

## Future updates

Update the engine URL, commit, and package hash together in `build.zig.zon`.
Expand Down
176 changes: 176 additions & 0 deletions docs/MIGRATION-HELPERS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
# From migration friction to everyday APIs

Serve LAN clients, download runtime files, decode ordered form fields, and keep
Baz's error classifications in a custom hook. These conveniences keep resource
ownership explicit. Use exact Zig 0.16.0.

## Reach your application from the LAN

The listener defaults to `127.0.0.1`. Select another IPv4 address at startup:

```zig
.server = .{
.bind_address = .{ 0, 0, 0, 0 },
.port = 8080,
.connections = 16,
}
```

`0.0.0.0` listens on all IPv4 interfaces. A specific local address selects that
address. Clients use the machine's actual LAN address, not `0.0.0.0`.
The address comes from the [bounded/http](https://technologylab-ai.github.io/bounded-http/)
configuration that Baz exposes directly. No name lookup or request allocation
is involved. Connection limits and [backpressure](LIMITS.md) still apply.

Try the hello example:

```sh
zig build hello -Doptimize=ReleaseSafe
./zig-out/bin/hello --bind-address 0.0.0.0 --port 8080 --connections 16
```

Open `http://YOUR-LAN-IP:8080/` on another device. Stop the server with Ctrl-C.
The shared example CLI accepts four decimal octets; embedded applications can
use `web.Config.parseBindAddress(text)`. The server still speaks plain HTTP/1.1.

## Copy a runtime file into a response

An embedded asset is useful when the file is known at compilation. For a file
created later, run the [runtime download example](../examples/runtime_file.zig):

```sh
zig build runtime_file -Doptimize=ReleaseSafe
./zig-out/bin/runtime_file --file ./export.zip --port 8080
curl --output downloaded.zip http://127.0.0.1:8080/download
curl --head http://127.0.0.1:8080/download
```

Supply an existing file. On Windows, use `.exe` executables and `curl.exe`.
The operator selects the path at startup; the request URL does not select a
filesystem path. The example opens the file for each request on a fixed worker.
It uses 16 KiB of copy scratch, 4 KiB of reader storage, 8 KiB of response staging,
and a 64 MiB total response limit. The scratch buffers live on the worker stack.

The central operation is:

```zig
var reader = file.reader(io, &read_buffer);
var stream = try ctx.response.stream(200, "application/zip", .{});
_ = try stream.copyFrom(&reader.interface, &scratch);
try stream.finish();
```

`copyFrom` reads until EOF and returns the copied byte count. It leaves the stream
open for additional writes. Scratch must be nonempty and separate from reader and
response storage. Every write copies into Baz's bounded response staging; a full
staging buffer waits for transport progress. This is not an OS zero-copy operation.

The raw stream writer has no writable destination buffer. Consequently,
`file_reader.interface.streamRemaining(stream.writer())` can fail with
`WriterBufferUnavailable` in Zig 0.16.0's file-reader fallback. Use `copyFrom` for
that transfer. Standard writer `writeAll`, `print`, and `flush` remain available.

Source and sink failures are sticky: `stream.failure()` retains the error, and
`copyFrom` returns it. A generic reader reports `ReadFailed`; its concrete file
reader retains the underlying diagnostic in `reader.err`. The complete example
shows how to propagate that diagnostic. An error before publication can become
an error response. After publication, failure closes the incomplete response.

Keep the file, reader, and scratch alive during the copy. The file can close after
the copied bytes have been accepted, even when final transport work remains.
For a generated temporary ZIP, close its generation writer before opening it for
reading. Close the reader's file before unlinking it; retain the path and arrange
cleanup on error too. Do not unlink a shared download while another request needs
to open it. That lifetime belongs to the application.

The file size from `stat` is a snapshot. Baz still enforces cumulative response
bounds and any declared content length if the file changes. HEAD executes the
handler and suppresses its payload; this example still reads the file for HEAD.
Cancellation is checked before each source read and while waiting for flushes.
It cannot interrupt arbitrary source I/O already in progress.

## Decode fields without losing the iterator

The raw iterator continues to return borrowed `name_raw`, `value_raw`, and
`has_equals`. Use a caller allocator when owned, decoded fields are more convenient:

```zig
var it = fields.decodedIterator(allocator, .form);
while (try it.next()) |decoded| {
var field = decoded;
defer field.deinit(allocator);
// Consume field.name, field.value, and field.has_equals here.
}
```

Each pair owns one allocation for its decoded name and value. Free the pair with
the same allocator, or reset its arena after all results are no longer needed.
Do not free the name and value subslices individually. Earlier results stay valid
after `next()`; the iterator itself still borrows the original encoded input.
An invalid escape or allocation failure leaves its position unchanged.

`.form` converts `+` to a space; `.percent` preserves `+`. Both decode percent
escapes once. Neither validates UTF-8, normalizes text, converts numbers, merges
query and body parameters, or chooses a duplicate policy.

| Encoded input | Decoded name | Decoded value | `has_equals` |
| --- | --- | --- | --- |
| `name=Alice+Smith` | `name` | `Alice Smith` | `true` |
| `%6eame=Bob%2BJones` | `name` | `Bob+Jones` | `true` |
| `flag` | `flag` | empty | `false` |
| `empty=` | `empty` | empty | `true` |

Both `name` entries remain in order. The application decides whether to accept
both, use one, or reject duplicates. Existing `firstRaw` and `allRaw` continue
matching the original encoded names.

Try the [decoded form example](../examples/decoded_forms.zig):

```sh
zig build decoded_forms -Doptimize=ReleaseSafe
./zig-out/bin/decoded_forms --port 8080
curl --data 'name=Alice+Smith&%6eame=Bob%2BJones&flag&empty=' http://127.0.0.1:8080/
```

The example uses a per-request application arena on a worker, preserves ordered
duplicates, and joins segmented bodies into bounded caller storage when needed.
Its JSON display explicitly requires UTF-8. Input byte and pair limits still apply;
allocator overhead and retained results are part of the application's memory use.

## Customize errors and preserve their status

An `on_error` hook replaces Baz's default handler. Reuse the default classification
when adding custom presentation or application error cases:

```zig
fn onError(ctx: *Application.Context, err: anyerror) !void {
const status = switch (err) {
error.ServiceUnavailable => 503,
else => web.defaultErrorStatus(err),
};
try ctx.response.jsonValue(status, .{ .message = "Request failed" });
}
```

Malformed forms retain their 400 classification, oversized forms their 413, and
unsupported form media types their 415. Cookie limits map to 431; unknown errors
map to 500. The [error example](../examples/app_errors.zig) counts failures and
customizes its demo error without exposing internal diagnostics.
Engine framing failures occur before App dispatch. A hook cannot replace bytes
already published. Logging or other work in the hook follows the same execution
rules as its handler.

## Bring a service to a clean stop

The [jobs application](JOBS.md) already demonstrates cached templates, sessions,
background work, and producer cleanup. For a persistent service, complete HTTP
draining, quiesce background mutations, perform the final persistence flush, and
then release shared storage. Keep dependencies needed by draining handlers alive.
Give service operations explicit deadlines where the provider supports them, and
join producers before freeing their storage.

A periodic save is not a final shutdown flush. A successful graceful-shutdown
test also does not prove crash durability. Whether an HTTP success acknowledges
durable storage is an application policy. A useful regression test updates state,
stops immediately, restarts, and verifies the update without waiting for the
periodic-save interval.
5 changes: 5 additions & 0 deletions docs/STREAMING.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ They return between flushes and timed waits; the linear API below retains one wo
Call `ctx.response.stream(status, content_type, options)` to obtain a `baz.Stream`.
Its `writer()` returns `*std.Io.Writer`. Standard `writeAll`, `print`, and `flush`
work; `Stream` also provides convenience `writeAll`, `print`, and `flush` methods.
`copyFrom(reader, scratch)` copies a standard reader to the stream using explicit
caller scratch. The raw writer has no writable destination buffer; Zig 0.16.0
file-reader `streamRemaining` can fail with `WriterBufferUnavailable`. Use
`copyFrom` for that path. See the [runtime download walkthrough](MIGRATION-HELPERS.md#copy-a-runtime-file-into-a-response)
for the runnable example, source diagnostics, HEAD, and file lifetimes.

Every write copies input bytes before returning. Stack buffers are valid sources.
Writes use the connection's startup-reserved staging buffer. Payload bytes then
Expand Down
2 changes: 1 addition & 1 deletion docs/WEBSITE.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ The website worktree is only a branch of Baz, not another project or repository.
| App excerpt | `Hello` in [app_demo.zig](../src/app_demo.zig), extracted at build time |
| Streaming excerpt | `progress` in [streaming.zig](../examples/streaming.zig), extracted at build time |
| Avoid-body-copies handler | App types and complete `index` handler in [serve.zig](../examples/serve.zig), extracted from the compiled example; copy avoidance leads the explanation, with the small-body threshold stated beside the example and the separate 5 MiB fixture backing the large-body evidence |
| Example cards | The catalog in [build_pages.py](../tools/build_pages.py), linked to all 21 compiled examples |
| Example cards | The catalog in [build_pages.py](../tools/build_pages.py), linked to all 26 compiled examples |
| Benchmark chart and table | Original [Mac](../reports/2026-09-06-basic-zap/macos-summary.json) and [Linux](../reports/2026-09-06-basic-zap/linux-summary.json) summaries; medians checked against recorded trial rates |
| Diagrams | [Raw parameters](diagrams/parameters.svg), [package boundary](diagrams/layers.svg), [response lifetime](diagrams/lifetime.svg) |
| Reader content | Repository Markdown and source files, copied unchanged from an explicit allowlist |
Expand Down
Loading
Loading