From 0edbb57e859c8a6a528ba4ead59202af45fa235b Mon Sep 17 00:00:00 2001 From: renerocksai Date: Sun, 13 Sep 2026 19:09:10 +0200 Subject: [PATCH 1/2] Add migration conveniences for files, forms, errors and LAN binding --- README.md | 9 +- build.zig | 2 +- build.zig.zon | 4 +- docs/APP-API.md | 10 +- docs/DEPENDENCY.md | 8 ++ docs/MIGRATION-HELPERS.md | 176 ++++++++++++++++++++++++++ docs/STREAMING.md | 5 + docs/WEBSITE.md | 2 +- docs/index.template.html | 9 +- examples/README.md | 12 +- examples/app_errors.zig | 15 ++- examples/decoded_forms.zig | 49 ++++++++ examples/runtime_file.zig | 68 ++++++++++ examples/support.zig | 3 + src/App.zig | 32 +++-- src/params.zig | 186 ++++++++++++++++++++++++++- src/response.zig | 229 ++++++++++++++++++++++++++++++++++ src/web.zig | 1 + tests/cli_integration.py | 13 +- tests/examples_integration.py | 49 ++++++++ tools/build_pages.py | 2 + tools/check_site.py | 4 +- tools/check_site_browser.mjs | 29 ++++- 23 files changed, 882 insertions(+), 35 deletions(-) create mode 100644 docs/MIGRATION-HELPERS.md create mode 100644 examples/decoded_forms.zig create mode 100644 examples/runtime_file.zig diff --git a/README.md b/README.md index 7c5999d..b3ed24a 100644 --- a/README.md +++ b/README.md @@ -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. @@ -209,3 +209,10 @@ retaining slices or introducing asynchronous work. Baz is [MIT licensed](LICENSE). The adapted Zap examples retain their [original copyright and license notice](examples/LICENSE-ZAP). + +### 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. diff --git a/build.zig b/build.zig index 98f643c..4999f4f 100644 --- a/build.zig +++ b/build.zig @@ -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, diff --git a/build.zig.zon b/build.zig.zon index fc075cb..f63e7dc 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -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" }, diff --git a/docs/APP-API.md b/docs/APP-API.md index 540a422..a6dd78c 100644 --- a/docs/APP-API.md +++ b/docs/APP-API.md @@ -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 @@ -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 @@ -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. | @@ -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. diff --git a/docs/DEPENDENCY.md b/docs/DEPENDENCY.md index 8b0533c..39a9413 100644 --- a/docs/DEPENDENCY.md +++ b/docs/DEPENDENCY.md @@ -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`. diff --git a/docs/MIGRATION-HELPERS.md b/docs/MIGRATION-HELPERS.md new file mode 100644 index 0000000..18ae8a2 --- /dev/null +++ b/docs/MIGRATION-HELPERS.md @@ -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. diff --git a/docs/STREAMING.md b/docs/STREAMING.md index e73539e..554bf00 100644 --- a/docs/STREAMING.md +++ b/docs/STREAMING.md @@ -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 diff --git a/docs/WEBSITE.md b/docs/WEBSITE.md index 96842c3..652a845 100644 --- a/docs/WEBSITE.md +++ b/docs/WEBSITE.md @@ -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 | diff --git a/docs/index.template.html b/docs/index.template.html index f46f39f..01eb91d 100644 --- a/docs/index.template.html +++ b/docs/index.template.html @@ -136,15 +136,16 @@

From a background job to a live page.

02 · In another terminal, from the Baz directory
curl 'http://127.0.0.1:8080/hello?name=Hello%20Zig'
 curl --data 'value=x+y%2Bz' http://127.0.0.1:8080/form
 curl -F 'files[]=@.zig-version' http://127.0.0.1:8080/upload
-

The current executable serves IPv4 loopback over plain HTTP/1.1. Stop it with Ctrl-C. On Windows, use curl.exe; executables have an .exe suffix. For embedding Baz in your own project, follow the package guide and independent consumer fixture.

+

The current executable defaults to IPv4 loopback over plain HTTP/1.1. Stop it with Ctrl-C. On Windows, use curl.exe; executables have an .exe suffix. For embedding Baz in your own project, follow the package guide and independent consumer fixture.

07 / Explore the examples

Examples you can run.

-

Twenty Zap ports and a new streaming example, using Baz’s public API. Every card opens maintained source in the reader. Pick a small example, then follow its types.

+

Twenty-six examples, from Zap ports to streaming and service composition, using Baz’s public API. Every card opens maintained source in the reader. Pick a small example, then follow its types.

+

New application conveniences: LAN binding, runtime downloads, decoded field iteration, and custom errors →

Build real pages with Mustache templates: a greeting form, typed user cards, and reusable partials. Parse once at startup and render straight into reserved HTML storage. The complete Zig example is just 52 lines → See the rendered preview →

24 of 24 examples

+ +

26 of 26 examples

@@EXAMPLES@@
Build all examples, or run one
zig build examples -Doptimize=ReleaseSafe
 zig build run-http_params -Doptimize=ReleaseSafe -- --port 8080
diff --git a/examples/README.md b/examples/README.md index 47154f3..4fa1f51 100644 --- a/examples/README.md +++ b/examples/README.md @@ -12,7 +12,8 @@ Run `zig build run-streaming -Doptimize=ReleaseSafe -- --port 8080`, then use See the [streaming guide](../docs/STREAMING.md) for its worker and lifetime bounds. [continuations.zig](continuations.zig) adds typed callbacks that release the executor between flushes and timers. [jobs.zig](jobs.zig) combines Mustache, sessions and -notification-driven SSE. Together with the 21 Zap ports below, there are 24 examples. +notification-driven SSE. The runtime download and decoded form examples bring +the catalog to 26 examples, including the 21 Zap ports below. Read the [complete application guide](../docs/JOBS.md) for its explicit limits. These examples adapt the public behavior of our predecessor @@ -150,3 +151,12 @@ pure Zig alternatives, and the independent original-Zap and official-core tests. The [framework roadmap](../docs/APP-API-ROADMAP.md) tracks repository publication with a pinned [bounded/http](https://technologylab-ai.github.io/bounded-http/) dependency, public middleware/resumable API work and remaining qualification. The engine remains a standalone case study. + +## Migration conveniences + +- `zig build runtime_file -Doptimize=ReleaseSafe`: runtime downloads at `/download`, selected with `--file PATH`. +- `zig build decoded_forms -Doptimize=ReleaseSafe`: ordered decoded form fields using a caller-owned arena on workers. +- `hello --bind-address 0.0.0.0`: explicit IPv4 LAN binding with the usual connection limits. +- `app_errors`: custom error presentation using `web.defaultErrorStatus` for other failures. + +Follow the [walkthrough](../docs/MIGRATION-HELPERS.md) for commands, lifetimes, and expected behavior. diff --git a/examples/app_errors.zig b/examples/app_errors.zig index a7275fb..6a502a7 100644 --- a/examples/app_errors.zig +++ b/examples/app_errors.zig @@ -21,7 +21,18 @@ fn mapError(ctx: *Application.Context, err: anyerror) !void { try ctx.response.header("X-Error-Handled", "app"); return ctx.response.jsonValue(500, .{ .error_message = "The example endpoint failed" }); } - return ctx.response.text(500, "Internal Server Error"); + return ctx.response.jsonValue(web.defaultErrorStatus(err), .{ .error_message = "Request failed" }); +} + +fn form(ctx: *Application.Context) !void { + _ = try ctx.request.formUrlEncoded(.{ .max_bytes = 32, .max_pairs = 2 }); + try ctx.response.text(200, "ok"); +} + +fn upload(ctx: *Application.Context) !void { + var boundary: [70]u8 = undefined; + _ = try ctx.request.multipartBoundaryInto(&boundary); + try ctx.response.text(200, "ok"); } fn state(ctx: *Application.Context) !void { @@ -39,6 +50,8 @@ pub fn main(init: std.process.Init) !void { defer app.deinit(); var endpoint: ErrorEndpoint = .{}; try app.endpoint("/error", &endpoint); + try app.route("POST", "/form", form); + try app.route("POST", "/upload", upload); try app.route("GET", "/state", state); try app.route("GET", "/stop", stop); try support.run(app, init); diff --git a/examples/decoded_forms.zig b/examples/decoded_forms.zig new file mode 100644 index 0000000..1f86e56 --- /dev/null +++ b/examples/decoded_forms.zig @@ -0,0 +1,49 @@ +//! Ordered decoded fields using an explicit, per-request application allocator. +const std = @import("std"); +const web = @import("baz"); +const support = @import("example_support"); + +const Shared = struct { allocator: std.mem.Allocator }; +const Application = web.App(Shared); +const limits: web.params.Limits = .{ .max_bytes = 4096, .max_pairs = 16, .max_name_bytes = 128, .max_value_bytes = 1024 }; + +fn form(ctx: *Application.Context) !void { + // General allocator work is explicit application work on a fixed worker. + _ = try ctx.serviceIo(); + var arena = std.heap.ArenaAllocator.init(ctx.shared.allocator); + defer arena.deinit(); + var body: [limits.max_bytes]u8 = undefined; + const fields = ctx.request.formUrlEncoded(limits) catch |err| switch (err) { + error.BodyNotContiguous => try web.form.parse(try ctx.request.body().copyTo(&body), limits), + else => return err, + }; + const Field = struct { name: []const u8, value: []const u8, has_equals: bool }; + var output: [limits.max_pairs]Field = undefined; + var count: usize = 0; + var it = fields.decodedIterator(arena.allocator(), .form); + while (try it.next()) |field| { + // The decoder accepts bytes. This JSON display deliberately requires UTF-8. + if (!std.unicode.utf8ValidateSlice(field.name) or !std.unicode.utf8ValidateSlice(field.value)) + return ctx.response.text(400, "This example displays UTF-8 fields only"); + output[count] = .{ .name = field.name, .value = field.value, .has_equals = field.has_equals }; + count += 1; + } + // Earlier fields stay valid after next(). jsonValue copies before arena teardown. + try ctx.response.jsonValue(200, .{ .fields = output[0..count] }); +} + +pub fn main(init: std.process.Init) !void { + var config = try support.workerConfig(init); + config.max_body = limits.max_bytes; + var shared: Shared = .{ .allocator = init.gpa }; + const app = try Application.init(.{ + .allocator = init.gpa, + .io = init.io, + .shared = &shared, + .server = config, + .response = .{ .body_bytes = 32768 }, + }); + defer app.deinit(); + try app.route("POST", "/", form); + try support.run(app, init); +} diff --git a/examples/runtime_file.zig b/examples/runtime_file.zig new file mode 100644 index 0000000..a9f154d --- /dev/null +++ b/examples/runtime_file.zig @@ -0,0 +1,68 @@ +//! Download a runtime-opened file with fixed copy scratch on application workers. +//! The operator chooses the path at startup; request paths never select files. +const std = @import("std"); +const web = @import("baz"); +const support = @import("example_support"); + +const maximum = 64 * 1024 * 1024; +const Options = struct { + port: u16 = 8080, + bind_address: []const u8 = "127.0.0.1", + duration_ms: u32 = 0, + execution: enum { @"inline", workers } = .workers, + workers: ?u16 = null, + connections: u16 = 16, + shards: u8 = 1, + file: []const u8 = "examples/assets/sendfile.txt", + + pub const aliases = .{ .port = "p" }; + pub const help = support.Options(true).help ++ + \\ + \\ --file PATH File to download at /download (opened per request) + \\Default: examples/assets/sendfile.txt; maximum response: 64 MiB. + ; +}; +const Shared = struct { path: []const u8 }; +const Application = web.App(Shared); + +fn download(ctx: *Application.Context) !void { + const io = try ctx.serviceIo(); + const file = try std.Io.Dir.cwd().openFile(io, ctx.shared.path, .{}); + defer file.close(io); + const size = (try file.stat(io)).size; + if (size > maximum) return error.FileTooLarge; + try ctx.response.header("Content-Disposition", "attachment; filename=download.bin"); + try ctx.response.header("Accept-Ranges", "none"); + var stream = try ctx.response.stream(200, "application/octet-stream", .{ + .content_length = @intCast(size), + }); + var read_buffer: [4096]u8 = undefined; + var reader = file.reader(io, &read_buffer); + var scratch: [16384]u8 = undefined; + _ = stream.copyFrom(&reader.interface, &scratch) catch |err| { + // Generic readers report ReadFailed; the concrete file reader retains + // the underlying I/O diagnostic. Stream failures remain sticky too. + if (err == error.ReadFailed) return reader.err orelse err; + return err; + }; + try stream.finish(); + // Copied bytes belong to the response. The file can close before the final + // transport send. HEAD follows this handler, but transmits no file payload. +} + +pub fn main(init: std.process.Init) !void { + const options = try support.parseOptions(init, Options); + var config = try support.configFromOptions(options, true); + config.max_response_bytes = maximum; + var shared: Shared = .{ .path = options.file }; + const app = try Application.init(.{ + .allocator = init.gpa, + .io = init.io, + .shared = &shared, + .server = config, + .response = .{ .body_bytes = 8192 }, + }); + defer app.deinit(); + try app.route("GET", "/download", download); + try support.run(app, init); +} diff --git a/examples/support.zig b/examples/support.zig index 6ba8f69..334ee35 100644 --- a/examples/support.zig +++ b/examples/support.zig @@ -21,6 +21,7 @@ pub fn workerConfig(init: std.process.Init) !web.Config { pub fn Options(comptime workers_required: bool) type { return struct { port: u16 = 8080, + bind_address: []const u8 = "127.0.0.1", duration_ms: u32 = 0, execution: enum { @"inline", workers } = if (workers_required) .workers else .@"inline", workers: ?u16 = null, @@ -33,6 +34,7 @@ pub fn Options(comptime workers_required: bool) type { \\ \\ -h, --help Show this help and exit \\ -p, --port N Listen port; 0 selects an available port (default: 8080) + \\ --bind-address A.B.C.D IPv4 listener address (default: 127.0.0.1) \\ --duration-ms N Stop after N milliseconds; 0 waits for shutdown \\ --execution inline|workers \\ --workers N Worker count (default: 2 for workers, 0 for inline) @@ -64,6 +66,7 @@ pub fn parseOptions(init: std.process.Init, comptime T: type) !T { pub fn configFromOptions(options: anytype, comptime workers_required: bool) !web.Config { const result: web.Config = .{ .port = options.port, + .bind_address = if (@hasField(@TypeOf(options), "bind_address")) try web.Config.parseBindAddress(options.bind_address) else .{ 127, 0, 0, 1 }, .duration_ms = options.duration_ms, .execution = if (options.execution == .workers) .workers else .inline_event_loop, .workers = options.workers orelse if (options.execution == .workers) @as(u16, 2) else 0, diff --git a/src/App.zig b/src/App.zig index ac84e98..6f55f56 100644 --- a/src/App.zig +++ b/src/App.zig @@ -6,6 +6,20 @@ const responses = @import("response.zig"); const routing = @import("router.zig"); const continuation = @import("continuation.zig"); +/// Default classification for errors that reach an App handler or middleware. +/// Custom on_error hooks can reuse it and override application-specific errors. +/// Engine framing failures occur before dispatch. Published responses cannot +/// be replaced, regardless of the status this function returns. +pub fn defaultErrorStatus(err: anyerror) u16 { + return switch (err) { + error.InvalidEscape, error.InvalidMetadata, error.DuplicateMetadataParameter, error.InvalidBoundary, error.InvalidMultipart, error.MissingBoundary, error.InvalidQuotedPair, error.AmbiguousContentType, error.MalformedCookie, error.MalformedHeaders, error.DuplicateCookie => 400, + error.CookiesTooLarge, error.TooManyCookies => 431, + error.ParamsTooLarge, error.TooManyParams, error.NameTooLarge, error.ValueTooLarge, error.MultipartTooLarge, error.TooManyParts, error.PartTooLarge, error.PartHeadersTooLarge, error.MetadataTooLarge, error.TooManyMetadataParameters => 413, + error.MissingContentType, error.UnsupportedMediaType, error.UnsupportedContentEncoding, error.UnsupportedMultipartEncoding => 415, + else => 500, + }; +} + pub fn App(comptime Shared: type) type { return AppWithLocals(Shared, struct {}); } @@ -664,14 +678,7 @@ pub fn AppWithLocals(comptime Shared: type, comptime Locals: type) type { self.validateContinuationBorrow(context.response) catch return context.response.errorResponse(500) catch .close; return context.response.finish() catch context.response.errorResponse(500) catch .close; } - const status: u16 = switch (err) { - error.InvalidEscape, error.InvalidMetadata, error.DuplicateMetadataParameter, error.InvalidBoundary, error.InvalidMultipart, error.MissingBoundary, error.InvalidQuotedPair, error.AmbiguousContentType, error.MalformedCookie, error.MalformedHeaders, error.DuplicateCookie => 400, - error.CookiesTooLarge, error.TooManyCookies => 431, - error.ParamsTooLarge, error.TooManyParams, error.NameTooLarge, error.ValueTooLarge, error.MultipartTooLarge, error.TooManyParts, error.PartTooLarge, error.PartHeadersTooLarge, error.MetadataTooLarge, error.TooManyMetadataParameters => 413, - error.MissingContentType, error.UnsupportedMediaType, error.UnsupportedContentEncoding, error.UnsupportedMultipartEncoding => 415, - else => 500, - }; - return context.response.errorResponse(status) catch .close; + return context.response.errorResponse(defaultErrorStatus(err)) catch .close; } fn handle(self: *Self, context: *Context) !void { @@ -932,3 +939,12 @@ test "typed locals, middleware unwinding, early responses and error cleanup run writer.release(); } } + +test "default error classification is reusable without mapping application errors" { + try std.testing.expectEqual(@as(u16, 400), defaultErrorStatus(error.MissingBoundary)); + try std.testing.expectEqual(@as(u16, 413), defaultErrorStatus(error.TooManyParams)); + try std.testing.expectEqual(@as(u16, 415), defaultErrorStatus(error.UnsupportedMediaType)); + try std.testing.expectEqual(@as(u16, 431), defaultErrorStatus(error.TooManyCookies)); + try std.testing.expectEqual(@as(u16, 500), defaultErrorStatus(error.OutOfMemory)); + try std.testing.expectEqual(@as(u16, 500), defaultErrorStatus(error.Overflow)); +} diff --git a/src/params.zig b/src/params.zig index 893c1fc..0c98514 100644 --- a/src/params.zig +++ b/src/params.zig @@ -1,4 +1,5 @@ -//! Ordered borrowed query/form pairs and explicit byte decoding. No allocator. +//! Ordered borrowed query/form pairs and explicit byte decoding. Raw iteration +//! needs no allocator; decoded iteration uses an explicit caller allocator. const std = @import("std"); pub const Limits = struct { @@ -10,6 +11,14 @@ pub const Limits = struct { pub const Error = error{ ParamsTooLarge, TooManyParams, NameTooLarge, ValueTooLarge }; pub const DecodeError = error{ InvalidEscape, NoSpaceLeft, OverlappingBuffers }; +pub const AllocDecodeError = std.mem.Allocator.Error || error{InvalidEscape}; + +pub const Encoding = enum { + /// Percent-decode bytes, preserving raw '+'. + percent, + /// Percent-decode bytes and replace raw '+' with SP. + form, +}; pub const Param = struct { name_raw: []const u8, @@ -17,6 +26,21 @@ pub const Param = struct { has_equals: bool, }; +/// Owned decoded bytes, independent of the input and other iterator results. +/// Release with deinit() using the iterator's allocator, or reset its arena +/// after every retained result is no longer needed. Do not free field subslices. +pub const DecodedParam = struct { + name: []const u8, + value: []const u8, + has_equals: bool, + storage: []u8, + + pub fn deinit(self: *DecodedParam, allocator: std.mem.Allocator) void { + allocator.free(self.storage); + self.* = undefined; + } +}; + /// Construct with parse(). Views borrow the supplied bytes without decoding. /// Empty separator components are skipped; duplicate names retain wire order. pub const Params = struct { @@ -40,6 +64,19 @@ pub const Params = struct { return .{ .raw = self.raw }; } + /// Decode each pair on demand with caller-owned allocation. The iterator + /// borrows the original input; each returned pair independently owns its + /// decoded bytes until deinit() or allocator arena reset. Wire order, + /// duplicates, and bare keys are preserved. Bytes are not UTF-8 validated, + /// normalized, or coerced. Encoding explicitly chooses the '+' policy. + /// + /// parse() limits still bound raw input and pairs; decoding never expands + /// fields. Allocator bookkeeping and retained results belong to the caller's + /// memory budget. Use application workers for arbitrary allocator work. + pub fn decodedIterator(self: Params, allocator: std.mem.Allocator, encoding: Encoding) DecodedIterator { + return .{ .pairs = self.iterator(), .allocator = allocator, .encoding = encoding }; + } + /// Exact raw-name comparison. A present bare key is still a Param. pub fn firstRaw(self: Params, name: []const u8) ?Param { var it = self.allRaw(name); @@ -83,6 +120,38 @@ pub const MatchingIterator = struct { } }; +pub const DecodedIterator = struct { + pairs: Iterator, + allocator: std.mem.Allocator, + encoding: Encoding, + + /// Allocates one owned byte buffer per pair. Neither errors nor allocation + /// failure advance the iterator. The iterator owns no returned storage and + /// requires no deinit(); callers release each successful result themselves. + pub fn next(self: *DecodedIterator) AllocDecodeError!?DecodedParam { + var next_pairs = self.pairs; + const pair = next_pairs.next() orelse { + self.pairs = next_pairs; + return null; + }; + const name_len = try decodedLength(pair.name_raw); + const value_len = try decodedLength(pair.value_raw); + // Both lengths are bounded by disjoint slices of the same input pair. + const storage_len = std.math.add(usize, name_len, value_len) catch return error.OutOfMemory; + const storage = try self.allocator.alloc(u8, storage_len); + const plus_as_space = self.encoding == .form; + decodeValidated(pair.name_raw, storage[0..name_len], plus_as_space); + decodeValidated(pair.value_raw, storage[name_len..], plus_as_space); + self.pairs = next_pairs; + return .{ + .name = storage[0..name_len], + .value = storage[name_len..], + .has_equals = pair.has_equals, + .storage = storage, + }; + } +}; + pub const parse = Params.parse; /// Decode once into caller storage; '+' remains a plus. On any error destination @@ -99,6 +168,13 @@ pub fn formDecodeInto(source: []const u8, destination: []u8) DecodeError![]u8 { fn decodeInto(source: []const u8, destination: []u8, plus_as_space: bool) DecodeError![]u8 { if (overlap(source, destination)) return error.OverlappingBuffers; + const count = try decodedLength(source); + if (count > destination.len) return error.NoSpaceLeft; + decodeValidated(source, destination[0..count], plus_as_space); + return destination[0..count]; +} + +fn decodedLength(source: []const u8) error{InvalidEscape}!usize { var input: usize = 0; var count: usize = 0; while (input < source.len) { @@ -109,8 +185,12 @@ fn decodeInto(source: []const u8, destination: []u8, plus_as_space: bool) Decode } else input += 1; count += 1; } - if (count > destination.len) return error.NoSpaceLeft; - input = 0; + return count; +} + +/// Source has passed decodedLength(); destination has exactly that length. +fn decodeValidated(source: []const u8, destination: []u8, plus_as_space: bool) void { + var input: usize = 0; var output: usize = 0; while (input < source.len) : (output += 1) { const byte = source[input]; @@ -122,7 +202,6 @@ fn decodeInto(source: []const u8, destination: []u8, plus_as_space: bool) Decode input += 1; } } - return destination[0..count]; } fn hex(byte: u8) ?u8 { @@ -198,3 +277,102 @@ test "explicit decoders preserve source, decode once and publish only on success try std.testing.expectEqualStrings("%20", &same); try std.testing.expectEqualStrings(source, "%26%3D%2520%2B+x%00%ff"); } + +test "decoded pairs preserve wire order, decoded duplicates, bare and empty fields" { + const pairs = try parse("&&name=Alice&%6eame=Bob&flag&flag=&=x&=&", .{}); + var it = pairs.decodedIterator(std.testing.allocator, .form); + const expected = [_]struct { name: []const u8, value: []const u8, has_equals: bool }{ + .{ .name = "name", .value = "Alice", .has_equals = true }, + .{ .name = "name", .value = "Bob", .has_equals = true }, + .{ .name = "flag", .value = "", .has_equals = false }, + .{ .name = "flag", .value = "", .has_equals = true }, + .{ .name = "", .value = "x", .has_equals = true }, + .{ .name = "", .value = "", .has_equals = true }, + }; + for (expected) |item| { + var pair = (try it.next()).?; + defer pair.deinit(std.testing.allocator); + try std.testing.expectEqualStrings(item.name, pair.name); + try std.testing.expectEqualStrings(item.value, pair.value); + try std.testing.expectEqual(item.has_equals, pair.has_equals); + } + try std.testing.expectEqual(null, try it.next()); + try std.testing.expectEqual(null, try it.next()); + try std.testing.expectEqualStrings("Bob", pairs.firstRaw("%6eame").?.value_raw); +} + +test "decoded iterator chooses plus policy explicitly and preserves arbitrary bytes" { + const pairs = try parse("a+b=%26%3D%2520%2B+x%00%ff", .{}); + var percent = pairs.decodedIterator(std.testing.allocator, .percent); + var form = pairs.decodedIterator(std.testing.allocator, .form); + var percent_pair = (try percent.next()).?; + defer percent_pair.deinit(std.testing.allocator); + var form_pair = (try form.next()).?; + defer form_pair.deinit(std.testing.allocator); + try std.testing.expectEqualStrings("a+b", percent_pair.name); + try std.testing.expectEqualStrings("&=%20++x\x00\xff", percent_pair.value); + try std.testing.expectEqualStrings("a b", form_pair.name); + try std.testing.expectEqualStrings("&=%20+ x\x00\xff", form_pair.value); +} + +test "decoded results outlive advancing the iterator and its source bytes" { + var source = "a=first&b=second".*; + const pairs = try parse(&source, .{}); + var it = pairs.decodedIterator(std.testing.allocator, .form); + var first = (try it.next()).?; + defer first.deinit(std.testing.allocator); + var second = (try it.next()).?; + defer second.deinit(std.testing.allocator); + try std.testing.expectEqual(null, try it.next()); + @memset(&source, 'x'); + try std.testing.expectEqualStrings("a", first.name); + try std.testing.expectEqualStrings("first", first.value); + try std.testing.expectEqualStrings("b", second.name); + try std.testing.expectEqualStrings("second", second.value); +} + +test "decoded iterator validates both fields before allocation and retains failed position" { + for ([_][]const u8{ "%=valid", "valid=%", "%GG=x", "a=%2", "a=x%4Z" }) |bad| { + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 0 }); + const pairs = try parse(bad, .{}); + var it = pairs.decodedIterator(failing.allocator(), .form); + try std.testing.expectError(error.InvalidEscape, it.next()); + try std.testing.expectError(error.InvalidEscape, it.next()); + try std.testing.expectEqual(@as(usize, 0), it.pairs.offset); + try std.testing.expectEqual(@as(usize, 0), failing.allocations); + try std.testing.expect(!failing.has_induced_failure); + } +} + +test "decoded iterator allocation failure preserves position and previous owned results" { + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 1 }); + const allocator = failing.allocator(); + const pairs = try parse("a=first&%62=second", .{}); + var it = pairs.decodedIterator(allocator, .form); + var first = (try it.next()).?; + defer first.deinit(allocator); + const offset = it.pairs.offset; + try std.testing.expectError(error.OutOfMemory, it.next()); + try std.testing.expectEqual(offset, it.pairs.offset); + try std.testing.expectEqualStrings("first", first.value); + failing.fail_index = std.math.maxInt(usize); + var second = (try it.next()).?; + defer second.deinit(allocator); + try std.testing.expectEqualStrings("b", second.name); + try std.testing.expectEqualStrings("second", second.value); + try std.testing.expectEqual(null, try it.next()); +} + +test "decoded fields fit raw parse bounds and exact caller allocation budget" { + const pairs = try parse("%61=%62", .{ .max_bytes = 7, .max_pairs = 1, .max_name_bytes = 3, .max_value_bytes = 3 }); + var scratch: [2]u8 = undefined; + var fixed = std.heap.FixedBufferAllocator.init(&scratch); + var it = pairs.decodedIterator(fixed.allocator(), .form); + var pair = (try it.next()).?; + defer pair.deinit(fixed.allocator()); + try std.testing.expectEqualStrings("a", pair.name); + try std.testing.expectEqualStrings("b", pair.value); + try std.testing.expectEqual(@as(usize, 2), fixed.end_index); + try std.testing.expectError(error.NameTooLarge, parse("%61=%62", .{ .max_name_bytes = 2 })); + try std.testing.expectError(error.ValueTooLarge, parse("%61=%62", .{ .max_value_bytes = 2 })); +} diff --git a/src/response.zig b/src/response.zig index 91e41b8..c2d0b16 100644 --- a/src/response.zig +++ b/src/response.zig @@ -538,6 +538,9 @@ pub const Stream = struct { .buffer = &.{}, }, + /// Unbuffered writer: operations requiring writable destination capacity, + /// including File.Reader.streamRemaining's fallback, are unsupported. + /// Use copyFrom with separate caller-owned scratch to transfer a reader. pub fn writer(self: *Stream) *std.Io.Writer { return &self.interface; } @@ -550,6 +553,39 @@ pub const Stream = struct { self.interface.writeAll(bytes) catch |err| return self.failure() orelse err; } + /// Copy until EOF through fixed caller-owned scratch, returning bytes copied. + /// Does not finish the stream. Scratch must be nonempty and must not overlap + /// the reader's buffer or response storage. Retain the reader and scratch + /// until this call returns; accepted bytes are copied into response storage. + /// Source and destination errors are sticky. Reader-specific diagnostics + /// remain on the source (for example File.Reader.err for ReadFailed). + /// Cancellation is checked before each read call, but cannot interrupt an + /// arbitrary source operation already in progress. Runtime file I/O belongs + /// on an application worker. Existing response limits and flush waits apply. + pub fn copyFrom(self: *Stream, reader: *std.Io.Reader, scratch: []u8) !usize { + errdefer |err| { + if (self.response.stream_error == null) self.response.stream_error = err; + } + try self.response.checkStream(); + if (scratch.len == 0) return error.EmptyScratchBuffer; + if (overlap(scratch, reader.buffer) or overlap(scratch, self.response.storage)) + return error.OverlappingBuffers; + var copied: usize = 0; + while (true) { + try self.response.checkStream(); + var slices: [1][]u8 = .{scratch}; + const n = reader.readVec(&slices) catch |err| switch (err) { + error.EndOfStream => return copied, + error.ReadFailed => return error.ReadFailed, + }; + // A reader may buffer input internally and report zero progress. + if (n == 0) continue; + const next = std.math.add(usize, copied, n) catch return error.ResponseLimit; + try self.writeAll(scratch[0..n]); + copied = next; + } + } + pub fn print(self: *Stream, comptime format: []const u8, args: anytype) !void { self.interface.print(format, args) catch |err| { if (self.response.stream_error == null) self.response.stream_error = err; @@ -812,6 +848,199 @@ test "stream writer preserves vector order and makes a length error sticky" { try testing.expectEqualStrings("Internal Server Error", writer.committed()); } +const CopyReaderFixture = struct { + interface: std.Io.Reader = .{ + .vtable = &.{ .stream = read }, + .buffer = &.{}, + .seek = 0, + .end = 0, + }, + bytes: []const u8 = "", + offset: usize = 0, + calls: usize = 0, + fail_at_end: bool = false, + zero_first: bool = false, + cancel_on_zero: ?*std.atomic.Value(bool) = null, + + fn read(reader: *std.Io.Reader, out: *std.Io.Writer, limit: std.Io.Limit) std.Io.Reader.StreamError!usize { + const self: *CopyReaderFixture = @fieldParentPtr("interface", reader); + self.calls += 1; + if (self.zero_first and self.calls == 1) { + if (self.cancel_on_zero) |cancelled| cancelled.store(true, .release); + return 0; + } + if (self.offset == self.bytes.len) { + if (self.fail_at_end) return error.ReadFailed; + return error.EndOfStream; + } + const n = try out.write(limit.sliceConst(self.bytes[self.offset..])); + self.offset += n; + return n; + } +}; + +test "stream copyFrom preserves binary bytes with tiny scratch and continues after EOF" { + for ([_]usize{ 1, 8 }) |scratch_len| { + var fixture: SnapshotFixture = .{}; + try fixture.init(16, 16); + fixture.response.allow_blocking_stream = true; + var stream = try fixture.response.stream(200, "application/octet-stream", .{ .content_length = 6 }); + var scratch: [8]u8 = undefined; + var empty: std.Io.Reader = .fixed(""); + try testing.expectEqual(@as(usize, 0), try stream.copyFrom(&empty, scratch[0..scratch_len])); + var source: CopyReaderFixture = .{ .bytes = "\x00\xffa\r\n", .zero_first = true }; + try testing.expectEqual(@as(usize, 5), try stream.copyFrom(&source.interface, scratch[0..scratch_len])); + try stream.writeAll("!"); + try stream.finish(); + try testing.expectEqualStrings("\x00\xffa\r\n!", fixture.response.bodyStorage()[0..fixture.response.body_len]); + try testing.expectEqual(@as(usize, if (scratch_len == 1) 7 else 3), source.calls); + try testing.expect(stream.failure() == null); + try testing.expectEqual(@as(usize, 0), fixture.blocking_calls); + } +} + +test "stream copyFrom rejects invalid scratch and completed streams without consuming input" { + for (0..4) |case| { + var fixture: SnapshotFixture = .{}; + try fixture.init(16, 16); + fixture.response.allow_blocking_stream = true; + var stream = try fixture.response.stream(200, "text/plain", .{}); + var source_bytes = "input".*; + var source: std.Io.Reader = .fixed(&source_bytes); + var scratch: [4]u8 = undefined; + const expected = switch (case) { + 0 => error.EmptyScratchBuffer, + 1, 2 => error.OverlappingBuffers, + 3 => error.InvalidState, + else => unreachable, + }; + const target: []u8 = switch (case) { + 0 => &.{}, + 1 => &source_bytes, + 2 => fixture.response.bodyStorage()[0..4], + 3 => &scratch, + else => unreachable, + }; + if (case == 3) try stream.finish(); + try testing.expectError(expected, stream.copyFrom(&source, target)); + try testing.expectEqual(expected, stream.failure().?); + try testing.expectEqual(@as(usize, 0), source.seek); + try testing.expectEqual(@as(usize, 0), fixture.response.body_len); + try testing.expectError(expected, fixture.response.finish()); + } +} + +test "stream copyFrom checks cancellation before initial and zero-progress reads" { + for ([_]bool{ false, true }) |during_read| { + var fixture: SnapshotFixture = .{}; + try fixture.init(16, 16); + fixture.response.allow_blocking_stream = true; + var stream = try fixture.response.stream(200, "text/plain", .{}); + var source: CopyReaderFixture = .{ + .bytes = "unread", + .zero_first = during_read, + .cancel_on_zero = &fixture.cancelled, + }; + var scratch: [2]u8 = undefined; + if (!during_read) fixture.cancelled.store(true, .release); + try testing.expectError(error.Cancelled, stream.copyFrom(&source.interface, &scratch)); + try testing.expectEqual(@as(usize, @intFromBool(during_read)), source.calls); + try testing.expectEqual(@as(usize, 0), source.offset); + try testing.expectEqual(error.Cancelled, stream.failure().?); + try testing.expectEqual(@as(usize, 0), fixture.response.body_len); + } +} + +test "stream copyFrom source failures are sticky and cannot finish a truncated response" { + for ([_][]const u8{ "", "ab" }) |prefix| { + var fixture: SnapshotFixture = .{}; + try fixture.init(16, 16); + fixture.response.allow_blocking_stream = true; + var stream = try fixture.response.stream(200, "text/plain", .{}); + var source: CopyReaderFixture = .{ .bytes = prefix, .fail_at_end = true }; + var scratch: [1]u8 = undefined; + try testing.expectError(error.ReadFailed, stream.copyFrom(&source.interface, &scratch)); + try testing.expectEqualStrings(prefix, fixture.response.bodyStorage()[0..fixture.response.body_len]); + try testing.expectEqual(error.ReadFailed, stream.failure().?); + const calls = source.calls; + try testing.expectError(error.ReadFailed, stream.copyFrom(&source.interface, &scratch)); + try testing.expectEqual(calls, source.calls); + try testing.expectError(error.ReadFailed, stream.finish()); + try testing.expectError(error.ReadFailed, fixture.response.finish()); + try testing.expect(!fixture.response.published); + } +} + +test "stream copyFrom retains total and declared response length bounds" { + const CompletedFlush = struct { + fixture: *SnapshotFixture, + bytes: [16]u8 = undefined, + len: usize = 0, + + fn flush(pointer: *anyopaque) api.FlushError!void { + const self: *@This() = @ptrCast(@alignCast(pointer)); + const committed = self.fixture.writer.committed(); + std.debug.assert(committed.len <= self.bytes.len - self.len); + @memcpy(self.bytes[self.len..][0..committed.len], committed); + self.len += committed.len; + self.fixture.blocking_calls += 1; + self.fixture.drained(); + } + }; + for (0..3) |case| { + var fixture: SnapshotFixture = .{}; + try fixture.init(if (case == 0) 2 else 16, if (case == 0) 3 else 16); + var completed: CompletedFlush = .{ .fixture = &fixture }; + fixture.context.blocking_flush = .{ .context = &completed, .flush = CompletedFlush.flush }; + fixture.response.allow_blocking_stream = true; + var stream = try fixture.response.stream(200, "text/plain", .{ + .content_length = if (case == 0) null else if (case == 1) 2 else 4, + }); + var source: std.Io.Reader = .fixed(if (case == 0) "abcd" else "abc"); + var scratch: [1]u8 = undefined; + if (case == 2) { + try testing.expectEqual(@as(usize, 3), try stream.copyFrom(&source, &scratch)); + try testing.expectError(error.ResponseLengthMismatch, stream.finish()); + } else { + const expected = if (case == 0) error.ResponseLimit else error.ResponseLengthMismatch; + try testing.expectError(expected, stream.copyFrom(&source, &scratch)); + try testing.expectEqualStrings(if (case == 0) "c" else "ab", fixture.response.bodyStorage()[0..fixture.response.body_len]); + try testing.expectEqual(expected, stream.failure().?); + } + try testing.expectEqualStrings(if (case == 0) "ab" else "", completed.bytes[0..completed.len]); + try testing.expectEqual(@as(usize, if (case == 0) 1 else 0), fixture.blocking_calls); + if (case == 0) { + try testing.expectEqual(@as(usize, 3), fixture.response.stream_written); + try testing.expectError(error.ResponseLimit, stream.finish()); + try testing.expect(fixture.response.published); + } + } +} + +test "stream copyFrom preserves flush failures and unsupported raw writer diagnostics" { + var fixture: SnapshotFixture = .{}; + try fixture.init(2, 16); + fixture.response.allow_blocking_stream = true; + var stream = try fixture.response.stream(200, "text/plain", .{}); + var source: CopyReaderFixture = .{ .bytes = "abcd" }; + var scratch: [1]u8 = undefined; + try testing.expectError(error.InvalidState, stream.copyFrom(&source.interface, &scratch)); + try testing.expectEqual(@as(usize, 1), fixture.blocking_calls); + try testing.expectEqual(@as(usize, 3), source.offset); + try testing.expectEqual(error.InvalidState, stream.failure().?); + try testing.expect(fixture.response.published); + + var raw: SnapshotFixture = .{}; + try raw.init(16, 16); + raw.response.allow_blocking_stream = true; + var unsupported = try raw.response.stream(200, "text/plain", .{}); + try testing.expectError(error.WriteFailed, unsupported.writer().writableSliceGreedy(1)); + try testing.expectEqual(error.WriterBufferUnavailable, unsupported.failure().?); + var unread: CopyReaderFixture = .{ .bytes = "unread" }; + try testing.expectError(error.WriterBufferUnavailable, unsupported.copyFrom(&unread.interface, &scratch)); + try testing.expectEqual(@as(usize, 0), unread.calls); +} + test "draft copies stack metadata and body and preserves earlier frozen bytes" { var arena: [2048]u8 = @splat(0xa5); const prefix = "older response stays frozen"; diff --git a/src/web.zig b/src/web.zig index 226bfeb..97b3b85 100644 --- a/src/web.zig +++ b/src/web.zig @@ -1,4 +1,5 @@ //! Baz: Bounded Async Zap. Experimental application API for exact Zig 0.16.0. +pub const defaultErrorStatus = @import("App.zig").defaultErrorStatus; pub const App = @import("App.zig").App; pub const AppWithLocals = @import("App.zig").AppWithLocals; pub const Request = @import("request.zig").Request; diff --git a/tests/cli_integration.py b/tests/cli_integration.py index a8c3e57..0a0edfb 100644 --- a/tests/cli_integration.py +++ b/tests/cli_integration.py @@ -27,10 +27,10 @@ "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", + "userpass_session", "cookies", "http_params", "bindataformpost", "streaming", "mustache", "continuations", "jobs", "runtime_file", "decoded_forms", ) FIXTURES = ("baz", "baz-streaming", "baz-borrow", "baz-cookies", "baz-middleware") -WORKER_EXAMPLES = frozenset(("endpoint", "streaming")) +WORKER_EXAMPLES = frozenset(("endpoint", "streaming", "runtime_file", "decoded_forms")) EXIT_TIMEOUT = 5 MAX_TRANSCRIPT = 65536 PROBE = b"OPTIONS * HTTP/1.1\r\nHost: localhost\r\n\r\n" @@ -183,6 +183,11 @@ def exit_case(name, label, arguments, code=1, diagnostic=None): exit_case(name, "worker-required example rejects zero workers", ["--workers=0"], diagnostic="InvalidConfiguration") + for name in ("hello", "runtime_file", "decoded_forms"): + for address in ("localhost", "256.0.0.1", "127.1", "::1"): + exit_case(name, "invalid IPv4 listener address", ["--bind-address", address], + diagnostic="InvalidBindAddress") + for option in ("session-ttl-ms", "job-ttl-ms", "tick-ms"): exit_case("jobs", "zero " + option, ["--" + option + "=0"], diagnostic="InvalidLifetime") @@ -206,6 +211,10 @@ def startup(name, label, arguments, workers, execution): "workers" if workers else "inline_event_loop") base = ["--port=0", "--connections=4", "--shards=1", "--duration-ms=15000"] + for address in ("0.0.0.0", "127.0.0.1"): + startup("hello", "explicit IPv4 binding " + address, base + ["--bind-address", address], + 0, "inline_event_loop") + for name in FIXTURES: workers = 0 if name in ("baz", "baz-cookies", "baz-middleware") else 2 startup(name, "fixture execution default", base, workers, diff --git a/tests/examples_integration.py b/tests/examples_integration.py index ced664f..10a1346 100644 --- a/tests/examples_integration.py +++ b/tests/examples_integration.py @@ -3,6 +3,7 @@ import argparse from contextlib import contextmanager import json +import tempfile from pathlib import Path import wire_support as wire @@ -77,6 +78,46 @@ def case(name, workers=0): headers=(("Range", "bytes=0-2"),)) wire.require(result[1][b"accept-ranges"] == b"none", "file example claimed unsupported ranges") + with tempfile.TemporaryDirectory(prefix="baz-download-") as temporary: + path = Path(temporary) / "runtime.bin" + payload = bytes(range(256)) * 257 # Binary data spanning several staging flushes. + path.write_bytes(payload) + download = ExampleServer(directory / "runtime_file", workers=2) + download.options["file"] = str(path) + with download as server: + response = call(server, "/download", expected=payload) + wire.require(int(response[1][b"content-length"]) == len(payload), "runtime file length changed") + response = call(server, "/download", method="HEAD", expected=b"") + wire.require(int(response[1][b"content-length"]) == len(payload), "runtime HEAD lost representation length") + # Reopen the runtime path for each request; no startup embedding/cache. + path.write_bytes(b"") + call(server, "/download", expected=b"") + path.unlink() + call(server, "/download", status=500) + passed.append("runtime_file") + print("PASS runtime_file", flush=True) + + with case("decoded_forms", workers=2) as server: + headers = (("Content-Type", "application/x-www-form-urlencoded"),) + body = b"name=Alice+Smith&%6eame=Bob%2BJones&flag&empty=" + expected = {"fields": [ + {"name": "name", "value": "Alice Smith", "has_equals": True}, + {"name": "name", "value": "Bob+Jones", "has_equals": True}, + {"name": "flag", "value": "", "has_equals": False}, + {"name": "empty", "value": "", "has_equals": True}, + ]} + wire.require(json.loads(call(server, "/?name=query", method="POST", body=body, headers=headers)[2]) == expected, + "decoded iterator merged parameters or lost names/order/duplicates") + call(server, method="POST", body=b"name=%GG", headers=headers, status=400) + call(server, method="POST", body=b"name=%ff", headers=headers, status=400) + call(server, method="POST", body=b"&".join([b"a=1"] * 17), headers=headers, status=413) + with server.connect() as sock: + sock.sendall(b"POST / HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/x-www-form-urlencoded\r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + + b"".join(b"1\r\n" + bytes([byte]) + b"\r\n" for byte in body) + b"0\r\n\r\n") + response = wire.ResponseReader(sock).response() + wire.require(response[0] == 200 and json.loads(response[2]) == expected, "segmented decoded form changed") + with case("senderror") as server: wire.require(json.loads(call(server, status=500)[2]) == {"error": "request failed"}, "private error leaked") @@ -110,6 +151,14 @@ def case(name, workers=0): result = call(server, "/error", status=500) wire.require(b"x-unpublished" not in result[1] and result[1][b"x-error-handled"] == b"app", "draft rollback lost mapper isolation") wire.require(json.loads(call(server, "/state")[2])["errors"] == 2, "error mapper was not instance-owned") + call(server, "/upload", method="POST", headers=(("Content-Type", "multipart/form-data"),), + body=b"invalid", status=400) + call(server, "/form", method="POST", headers=(("Content-Type", "application/x-www-form-urlencoded"),), + body=b"a=1&b=2&c=3", status=413) + call(server, "/form", method="POST", headers=(("Content-Type", "text/plain"),), + body=b"a=1", status=415) + wire.require(json.loads(call(server, "/state")[2])["errors"] == 5, + "custom hook did not observe classified form errors") with case("cookies") as server: result = call(server, headers=(("Cookie", 'ZIG_ZAP=a%20+b; other="001"; other=false'),)) diff --git a/tools/build_pages.py b/tools/build_pages.py index 1c7a88c..486ff71 100644 --- a/tools/build_pages.py +++ b/tools/build_pages.py @@ -21,6 +21,8 @@ ('simple_router', 'routing', 'Functions, stateful routes, and a synchronized counter.'), ('routes', 'routing', 'Static and dynamic responses in one router.'), ('serve', 'responses', 'Serve immutable embedded assets through explicit routes.'), + ('runtime_file', 'responses', 'Download a runtime-opened file using fixed copy scratch on application workers.'), + ('decoded_forms', 'data', 'An allocator-backed iterator: decoded names and values, ordered duplicates, explicit lifetimes.'), ('sendfile', 'responses', 'File content as an embedded asset; no sendfile syscall.'), ('senderror', 'responses', 'Controlled errors, with no client-visible stack trace.'), ('accept', 'responses', 'Explicit, bounded content negotiation.'), diff --git a/tools/check_site.py b/tools/check_site.py index d412907..7a0a526 100644 --- a/tools/check_site.py +++ b/tools/check_site.py @@ -51,10 +51,10 @@ def check(output, documents, document_urls): actual = {str(path.relative_to(output)) for path in output.rglob('*') if path.is_file()} assert actual == set(manifest['files_sha256']) | {'publication.json'}, 'Unexpected artifact files' index = (output / 'index.html').read_text() - assert len(re.findall(r'class="example-card"', index)) == 24 + assert len(re.findall(r'class="example-card"', index)) == 26 assert all(text in index for text in ['1.038×', '1.771×', '0.629×', '1.025×']) assert all((output / document_urls.get(name, name)).read_bytes() == (Path(__file__).resolve().parents[1] / name).read_bytes() for name in documents), 'Copied document changed' - print('Site checks passed: links, anchors, diagrams, 24 examples, four benchmark profiles, and document identity.') + print('Site checks passed: links, anchors, diagrams, 26 examples, four benchmark profiles, and document identity.') if __name__ == '__main__': diff --git a/tools/check_site_browser.mjs b/tools/check_site_browser.mjs index a4df5f9..6efcfb4 100644 --- a/tools/check_site_browser.mjs +++ b/tools/check_site_browser.mjs @@ -129,7 +129,7 @@ try { await check('desktop-landing', async () => { await navigate(); const state = await evaluate(`({title:document.title,headline:document.querySelector('h1').textContent,diagrams:document.querySelectorAll('svg[role="img"]').length,examples:document.querySelectorAll('.example-card').length,highlight:!!document.querySelector('.hljs-keyword')})`); - assert.equal(state.title,'Baz — Bounded Async Zap'); assert.equal(state.diagrams,5); assert.equal(state.examples,24); assert(state.highlight); + assert.equal(state.title,'Baz — Bounded Async Zap'); assert.equal(state.diagrams,5); assert.equal(state.examples,26); assert(state.highlight); await noOverflow(); await screenshot('baz-desktop'); return state; }); await check('maintained-source-excerpt', async () => { @@ -199,12 +199,12 @@ try { }); await check('example-filters', async () => { await evaluate('document.querySelector("#examples").scrollIntoView({behavior:"instant"})'); - for (const [group,count] of [['data',2],['composition',6],['app',4],['routing',5],['responses',7],['all',24]]) { + for (const [group,count] of [['data',3],['composition',6],['app',4],['routing',5],['responses',8],['all',26]]) { await click(`button[data-filter="${group}"]`); assert.equal(await evaluate('document.querySelectorAll(".example-card:not([hidden])").length'),count); - assert.equal(await evaluate('document.querySelector("#example-count").textContent'),`${count} of 24 examples`); + assert.equal(await evaluate('document.querySelector("#example-count").textContent'),`${count} of 26 examples`); } - return {groups:6,total:24}; + return {groups:6,total:26}; }); await check('desktop-diagrams-and-benchmark', async () => { await evaluate('document.querySelector("#engine").scrollIntoView({behavior:"instant"})'); await screenshot('baz-engine'); @@ -328,6 +328,23 @@ try { await noOverflow(); return {desktop:1440,mobile:390,clientSource:true}; }); + await check('migration-helpers-walkthrough', async () => { + await send('Emulation.setDeviceMetricsOverride',{width:1440,height:1040,deviceScaleFactor:1,mobile:false}); + await navigate('#examples'); + const selector = '#examples a[href="docs/read.html?file=docs/MIGRATION-HELPERS.md"]'; + await evaluate('document.querySelector('+JSON.stringify(selector)+').scrollIntoView({behavior:"instant",block:"center"})'); + await delay(300); + await click(selector); + await until(() => evaluate('document.documentElement.dataset.readerReady === "true"'), 'Migration guide did not load'); + assert.equal(await evaluate('document.querySelector("#document h1").textContent'),'From migration friction to everyday APIs'); + await noOverflow(); await screenshot('baz-migration-helpers-desktop'); + for (const file of ['runtime_file', 'decoded_forms']) { + assert(await evaluate('[...document.querySelectorAll("#document a")].some(a => new URL(a.href).searchParams.get("file") === "examples/'+file+'.zig")')); + } + await send('Emulation.setDeviceMetricsOverride',{width:390,height:844,deviceScaleFactor:1,mobile:false}); + await noOverflow(); await screenshot('baz-migration-helpers-mobile'); + return {desktop:1440,mobile:390,mainPageNavigation:true,examples:2}; + }); await check('all-published-documents-render', async () => { await navigate('docs/read.html','reader'); const files = await evaluate('window.DOC_SITE.documents'); @@ -348,10 +365,10 @@ try { await writeFile(path.join(output,'baz-print.pdf'),Buffer.from(pdf.data,'base64')); await send('Emulation.setEmulatedMedia',{media:''}); await send('Emulation.setScriptExecutionDisabled',{value:true}); await navigate(); - assert.equal(await evaluate('document.querySelectorAll(".example-card:not([hidden])").length'),24); + assert.equal(await evaluate('document.querySelectorAll(".example-card:not([hidden])").length'),26); assert(await evaluate('document.querySelector(".language-zig").textContent.includes("percentDecodeInto")')); assert(await evaluate('[...document.querySelectorAll("[role=tabpanel]")].every(panel => !panel.hidden && getComputedStyle(panel).display !== "none")')); - await send('Emulation.setScriptExecutionDisabled',{value:false}); return {printBytes:Buffer.from(pdf.data,'base64').length,noJsExamples:24}; + await send('Emulation.setScriptExecutionDisabled',{value:false}); return {printBytes:Buffer.from(pdf.data,'base64').length,noJsExamples:26}; }); await check('no-unexpected-network-or-errors', async () => { assert.equal(exceptions.length,0,JSON.stringify(exceptions)); From 173b4738c3c34d9eae79fdbf2e73699ee45a6eac Mon Sep 17 00:00:00 2001 From: renerocksai Date: Sun, 13 Sep 2026 19:11:55 +0200 Subject: [PATCH 2/2] Group the migration guide with API documentation --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index b3ed24a..20f170c 100644 --- a/README.md +++ b/README.md @@ -205,14 +205,14 @@ 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. -## License - -Baz is [MIT licensed](LICENSE). The adapted Zap examples retain their -[original copyright and license notice](examples/LICENSE-ZAP). - ### 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 +[original copyright and license notice](examples/LICENSE-ZAP).