From f646bb2fbfd1d2ff3c8e6e2ee0db780373c37020 Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Mon, 16 Nov 2026 11:10:42 -0500 Subject: [PATCH] refactor(packages): move the streaming HTTP client into albedo_http The transport and its connection machinery become the albedo_http workspace package. albedo_http, the top-level module, is the client: Options, open, receive and close. albedo_http/body holds request bodies and their parts, albedo_http/route the route, albedo_http/tls the trusted roots. connect, framing, pool, proxy and socket are internal modules. The native receive and body walk become albedo_http_ffi, the connection state key {albedo_http_state, Ref}, and the pool's registered name albedo_http_pool. The package depends on albedo_bytes, albedo_clock and albedo_protect. The httpc binding albedo_http.erl would collide with the package's top-level module, so it becomes albedo_httpc. The client's tests move with it: loopback framing, pooling, guard, open_once and dual-stack TLS probes. They now run in each package's Nix build, whose sandbox has no OS certificate store, so the TLS probes trust their fixture's CA through tls.Roots instead of loading it into OTP's store, and roots that cannot be read fail the connection as a TransportError rather than crash the caller. New tests show deferred and digest parts go out as materialized and break their rules as typed errors. albedo keeps stream_http's own tests, the first-event deadline and the header refusal, with a small fixture, and the httpc dual-stack probes. Claude's attestation test checks the materialized body rather than a server's copy of it. The pool's registration is reviewed in the lint allow-list as a cache. The boot preload list, the e2e areas, the Antigravity offline build and the test runner's timed list follow the renames. --- gleam.toml | 1 + manifest.toml | 2 + packages/albedo_http/.gitignore | 1 + packages/albedo_http/gleam.toml | 26 ++ packages/albedo_http/manifest.toml | 25 ++ .../albedo_http/src/albedo_http.gleam | 63 ++-- .../albedo_http/src/albedo_http/body.gleam | 10 +- .../src/albedo_http}/connect.gleam | 4 +- .../src/albedo_http}/framing.gleam | 0 .../albedo_http/src/albedo_http}/pool.gleam | 12 +- .../albedo_http/src/albedo_http}/proxy.gleam | 2 +- .../albedo_http/src/albedo_http}/route.gleam | 2 +- .../albedo_http/src/albedo_http}/socket.gleam | 6 +- .../albedo_http/src/albedo_http}/tls.gleam | 2 +- .../albedo_http/src/albedo_http_ffi.erl | 26 +- .../test/albedo_http/guard_test.gleam | 50 +-- .../test/albedo_http_dual_stack_test.erl | 84 ++--- .../test/albedo_http_guard_fixture.erl | 2 +- .../test/albedo_http_once_test.erl | 78 ++--- .../albedo_http/test/albedo_http_test.gleam | 326 ++++++++++-------- .../test/albedo_http_test_server.erl | 42 +-- .../extensions/bedrock/aws_profile.gleam | 2 +- .../harness/extensions/claude/wire.gleam | 2 +- .../harness/extensions/codex/images.gleam | 16 +- .../harness/extensions/codex/wire.gleam | 2 +- .../harness/extensions/discord/manager.gleam | 2 +- .../harness/extensions/mcp/client.gleam | 2 +- src/albedo/harness/extensions/mcp/http.gleam | 79 ++--- .../harness/extensions/openai/extension.gleam | 2 +- .../sdk/{albedo_http.erl => albedo_httpc.erl} | 4 +- src/albedo/harness/sdk/extension.gleam | 2 +- src/albedo/harness/sdk/http.gleam | 28 +- src/albedo/harness/sdk/network.gleam | 2 +- src/albedo/harness/sdk/network_context.gleam | 12 +- src/albedo/harness/sdk/usage_feed.gleam | 2 +- src/albedo/openai_api/attestation.gleam | 2 +- src/albedo/openai_api/stream_http.gleam | 50 +-- src/albedo/openai_api/types.gleam | 2 +- test/albedo_test_runner.erl | 7 +- test/e2e/antigravity_support.py | 32 +- test/e2e/areas.toml | 45 +-- test/harness/albedo_httpc_dual_stack_test.erl | 83 +++++ test/harness/antigravity_offline_test.py | 16 +- test/harness/claude_test.gleam | 36 +- test/harness/messages_cache_test.gleam | 2 +- test/harness/network_test.gleam | 2 +- .../openai_api/albedo_stream_http_fixture.erl | 50 +++ test/openai_api/stream_http_test.gleam | 89 +++++ .../lint/src/albedo_lint/registrations.gleam | 14 + 49 files changed, 793 insertions(+), 558 deletions(-) create mode 100644 packages/albedo_http/.gitignore create mode 100644 packages/albedo_http/gleam.toml create mode 100644 packages/albedo_http/manifest.toml rename src/albedo/openai_api/transport.gleam => packages/albedo_http/src/albedo_http.gleam (96%) rename src/albedo/openai_api/request_body.gleam => packages/albedo_http/src/albedo_http/body.gleam (97%) rename {src/albedo/openai_api => packages/albedo_http/src/albedo_http}/connect.gleam (99%) rename {src/albedo/openai_api => packages/albedo_http/src/albedo_http}/framing.gleam (100%) rename {src/albedo/openai_api => packages/albedo_http/src/albedo_http}/pool.gleam (97%) rename {src/albedo/openai_api => packages/albedo_http/src/albedo_http}/proxy.gleam (98%) rename {src/albedo/openai_api => packages/albedo_http/src/albedo_http}/route.gleam (91%) rename {src/albedo/openai_api => packages/albedo_http/src/albedo_http}/socket.gleam (95%) rename {src/albedo/openai_api => packages/albedo_http/src/albedo_http}/tls.gleam (90%) rename src/albedo/openai_api/albedo_openai_transport.erl => packages/albedo_http/src/albedo_http_ffi.erl (68%) rename test/harness/transport_request_guard_test.gleam => packages/albedo_http/test/albedo_http/guard_test.gleam (79%) rename test/harness/albedo_transport_dual_stack_test.erl => packages/albedo_http/test/albedo_http_dual_stack_test.erl (80%) rename test/harness/albedo_transport_request_guard_fixture.erl => packages/albedo_http/test/albedo_http_guard_fixture.erl (99%) rename test/harness/albedo_transport_once_test.erl => packages/albedo_http/test/albedo_http_once_test.erl (67%) rename test/openai_api/transport_test.gleam => packages/albedo_http/test/albedo_http_test.gleam (59%) rename test/openai_api/albedo_openai_transport_test_server.erl => packages/albedo_http/test/albedo_http_test_server.erl (91%) rename src/albedo/harness/sdk/{albedo_http.erl => albedo_httpc.erl} (96%) create mode 100644 test/harness/albedo_httpc_dual_stack_test.erl create mode 100644 test/openai_api/albedo_stream_http_fixture.erl create mode 100644 test/openai_api/stream_http_test.gleam diff --git a/gleam.toml b/gleam.toml index c60c84261..78121589a 100644 --- a/gleam.toml +++ b/gleam.toml @@ -29,6 +29,7 @@ gleam_crypto = ">= 1.0.0 and < 2.0.0" albedo_bytes = { path = "packages/albedo_bytes" } albedo_clock = { path = "packages/albedo_clock" } albedo_env = { path = "packages/albedo_env" } +albedo_http = { path = "packages/albedo_http" } albedo_ports = { path = "packages/albedo_ports" } albedo_process = { path = "packages/albedo_process" } albedo_protect = { path = "packages/albedo_protect" } diff --git a/manifest.toml b/manifest.toml index eb20728f3..43dea4281 100644 --- a/manifest.toml +++ b/manifest.toml @@ -10,6 +10,7 @@ packages = [ { name = "albedo_bytes", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_protect", "gleam_crypto", "gleam_erlang", "gleam_stdlib"], source = "local", path = "packages/albedo_bytes" }, { name = "albedo_clock", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_protect", "gleam_erlang", "gleam_stdlib"], source = "local", path = "packages/albedo_clock" }, { name = "albedo_env", version = "0.1.0", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_stdlib"], source = "local", path = "packages/albedo_env" }, + { name = "albedo_http", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_bytes", "albedo_clock", "albedo_protect", "gleam_erlang", "gleam_stdlib"], source = "local", path = "packages/albedo_http" }, { name = "albedo_ports", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_clock", "albedo_protect", "gleam_erlang", "gleam_stdlib"], source = "local", path = "packages/albedo_ports" }, { name = "albedo_process", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_clock", "albedo_protect", "gleam_erlang", "gleam_otp", "gleam_stdlib"], source = "local", path = "packages/albedo_process" }, { name = "albedo_protect", version = "0.1.0", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_stdlib"], source = "local", path = "packages/albedo_protect" }, @@ -38,6 +39,7 @@ packages = [ albedo_bytes = { path = "packages/albedo_bytes" } albedo_clock = { path = "packages/albedo_clock" } albedo_env = { path = "packages/albedo_env" } +albedo_http = { path = "packages/albedo_http" } albedo_ports = { path = "packages/albedo_ports" } albedo_process = { path = "packages/albedo_process" } albedo_protect = { path = "packages/albedo_protect" } diff --git a/packages/albedo_http/.gitignore b/packages/albedo_http/.gitignore new file mode 100644 index 000000000..796b96d1c --- /dev/null +++ b/packages/albedo_http/.gitignore @@ -0,0 +1 @@ +/build diff --git a/packages/albedo_http/gleam.toml b/packages/albedo_http/gleam.toml new file mode 100644 index 000000000..6822cb0d8 --- /dev/null +++ b/packages/albedo_http/gleam.toml @@ -0,0 +1,26 @@ +name = "albedo_http" +version = "0.1.0" +description = "A streaming HTTP/1.1 client: dual-stack and verified TLS dialling, SOCKS5 and HTTP CONNECT proxies, pooled keep-alive, chunked framing, streamed request bodies with deferred and digest parts, and compression" +# The albedo repository's licence; see robot-docs/workspace-packages.md. +licences = ["AGPL-3.0-only"] +gleam = ">= 1.19.0" +target = "erlang" +# The connection machinery behind albedo_http.open; callers use albedo_http, +# albedo_http/body, albedo_http/route and albedo_http/tls. +internal_modules = [ + "albedo_http/connect", + "albedo_http/framing", + "albedo_http/pool", + "albedo_http/proxy", + "albedo_http/socket", +] + +[dependencies] +gleam_stdlib = ">= 1.0.0 and < 2.0.0" +gleam_erlang = ">= 1.3.0 and < 2.0.0" +albedo_bytes = { path = "../albedo_bytes" } +albedo_clock = { path = "../albedo_clock" } +albedo_protect = { path = "../albedo_protect" } + +[dev_dependencies] +gleeunit = ">= 1.0.0 and < 2.0.0" diff --git a/packages/albedo_http/manifest.toml b/packages/albedo_http/manifest.toml new file mode 100644 index 000000000..58c0c24c0 --- /dev/null +++ b/packages/albedo_http/manifest.toml @@ -0,0 +1,25 @@ +# Do not manually edit this file, it is managed by Gleam. +# +# This file locks the dependency versions used, to make your build +# deterministic and to prevent unexpected versions from being included +# in your application. +# +# You should check this file into your source control repository. + +packages = [ + { name = "albedo_bytes", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_protect", "gleam_crypto", "gleam_erlang", "gleam_stdlib"], source = "local", path = "../albedo_bytes" }, + { name = "albedo_clock", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_protect", "gleam_erlang", "gleam_stdlib"], source = "local", path = "../albedo_clock" }, + { name = "albedo_protect", version = "0.1.0", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_stdlib"], source = "local", path = "../albedo_protect" }, + { name = "gleam_crypto", version = "1.6.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_crypto", source = "hex", outer_checksum = "2DE9E4EF53CF6FEE049D4F765731F7178F7A11AEFAE00EEE63BF7536B354AD3F" }, + { name = "gleam_erlang", version = "1.3.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_erlang", source = "hex", outer_checksum = "1124AD3AA21143E5AF0FC5CF3D9529F6DB8CA03E43A55711B60B6B7B3874375C" }, + { name = "gleam_stdlib", version = "1.0.5", build_tools = ["gleam"], requirements = [], otp_app = "gleam_stdlib", source = "hex", outer_checksum = "CEE5B6C076A85B45F60C585F4316C63EC8B7127C119D5738C3958A9C4D50404E" }, + { name = "gleeunit", version = "1.11.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleeunit", source = "hex", outer_checksum = "EC31ABA74256AEA531EDF8169931D775BBB384FED0A8A1BDC4DD9354E3E21826" }, +] + +[requirements] +albedo_bytes = { path = "../albedo_bytes" } +albedo_clock = { path = "../albedo_clock" } +albedo_protect = { path = "../albedo_protect" } +gleam_erlang = { version = ">= 1.3.0 and < 2.0.0" } +gleam_stdlib = { version = ">= 1.0.0 and < 2.0.0" } +gleeunit = { version = ">= 1.0.0 and < 2.0.0" } diff --git a/src/albedo/openai_api/transport.gleam b/packages/albedo_http/src/albedo_http.gleam similarity index 96% rename from src/albedo/openai_api/transport.gleam rename to packages/albedo_http/src/albedo_http.gleam index 2cf397bbc..c5b7ef059 100644 --- a/src/albedo/openai_api/transport.gleam +++ b/packages/albedo_http/src/albedo_http.gleam @@ -3,20 +3,26 @@ //// only the caller, and a finished exchange leaves its connection with //// `pool` for the next request to the same host. //// +//// `open` takes `Options`: the `route` the connection takes, direct or +//// through a proxy (`albedo_http/route`), the roots an HTTPS server must +//// chain to (`albedo_http/tls`), and an optional admission check. The +//// client reads no settings, environment or process context of its own. A +//// body is iodata that may carry deferred and digest parts and ask for +//// compression; `albedo_http/body` owns its rules. +//// //// A connection's state lives in its owner's process dictionary, so `close` //// sees how far the last receive read and can tell a reusable connection //// from a broken one. The socket closes when its owner exits. The -//// per-socket receive is native, in `albedo_openai_transport.erl`, and -//// `request_body` owns the body's plan and streaming write. - -import albedo/openai_api/connect.{type Transport, Tcp, Tls} -import albedo/openai_api/framing.{type Framing} -import albedo/openai_api/pool -import albedo/openai_api/request_body -import albedo/openai_api/route.{type Route} -import albedo/openai_api/socket.{type Socket} -import albedo/openai_api/tls.{type Trust} +//// per-socket receive is native, in `albedo_http_ffi.erl`. + import albedo_clock +import albedo_http/body as request_body +import albedo_http/connect.{type Transport, Tcp, Tls} +import albedo_http/framing.{type Framing} +import albedo_http/pool +import albedo_http/route.{type Route} +import albedo_http/socket.{type Socket} +import albedo_http/tls.{type Trust} import albedo_protect import gleam/bit_array import gleam/dict.{type Dict} @@ -151,9 +157,9 @@ type Head { // The body form the native writer sends. // The process-dictionary key of a connection's state, which compiles to -// `{albedo_openai_transport, Ref}`. +// `{albedo_http_state, Ref}`. type StateKey { - AlbedoOpenaiTransport(ref: Reference) + AlbedoHttpState(ref: Reference) } type SslNotStarted { @@ -389,8 +395,12 @@ fn connect_socket( // The host as it reaches the resolver: its bytes read as Latin-1 // characters. let host = binary_to_list(request.host) - case ensure_tls(request.transport) { - Ok(Nil) -> { + let tls_options = { + use Nil <- result.try(ensure_tls(request.transport)) + tls_options(request.transport, host, request.trust) + } + case tls_options { + Ok(tls_options) -> { let endpoint = connect.Endpoint( request.transport, @@ -401,7 +411,7 @@ fn connect_socket( connect.connect( endpoint, coerce(options), - coerce(tls_options(request.transport, host, request.trust)), + coerce(tls_options), timeout_ms, request.route, ) @@ -460,28 +470,33 @@ fn keepalive(timeout_ms: Int) -> List(SocketOption) { } // Verified against the request's trusted roots with HTTPS hostname matching; -// SNI names the host unless it is an IP address. +// SNI names the host unless it is an IP address. Roots that cannot be read, +// such as an OS store OTP finds no certificates in, fail the connection. fn tls_options( transport: Transport, host: Charlist, trust: Trust, -) -> List(TlsOption) { +) -> Result(List(TlsOption), Dynamic) { case transport { - Tcp -> [] + Tcp -> Ok([]) Tls -> { + use roots <- result.try( + albedo_protect.rescue(fn() { tls.roots(trust) }) + |> result.map_error(fn(crash) { crash.reason }), + ) let sni = case parse_address(host) { Ok(_) -> [] Error(_) -> [ServerNameIndication(host)] } - [ + Ok([ Verify(atom.create("verify_peer")), - Cacerts(tls.roots(trust)), + Cacerts(roots), CustomizeHostnameCheck([ MatchFun(pkix_verify_hostname_match_fun(atom.create("https"))), ]), AlpnAdvertisedProtocols([<<"http/1.1":utf8>>]), ..sni - ] + ]) } } } @@ -1143,7 +1158,7 @@ fn destination(url: String, _headers: List(#(String, String))) -> String { } fn load(ref: Reference) -> Option(State) { - let value = get(AlbedoOpenaiTransport(ref)) + let value = get(AlbedoHttpState(ref)) case value == coerce(Undefined) { True -> None False -> Some(coerce(value)) @@ -1151,7 +1166,7 @@ fn load(ref: Reference) -> Option(State) { } fn take(ref: Reference) -> Option(State) { - let value = erase(AlbedoOpenaiTransport(ref)) + let value = erase(AlbedoHttpState(ref)) case value == coerce(Undefined) { True -> None False -> Some(coerce(value)) @@ -1159,7 +1174,7 @@ fn take(ref: Reference) -> Option(State) { } fn store(ref: Reference, state: State) -> Nil { - put(AlbedoOpenaiTransport(ref), state) + put(AlbedoHttpState(ref), state) Nil } diff --git a/src/albedo/openai_api/request_body.gleam b/packages/albedo_http/src/albedo_http/body.gleam similarity index 97% rename from src/albedo/openai_api/request_body.gleam rename to packages/albedo_http/src/albedo_http/body.gleam index 469a1edd4..bcf7a29e7 100644 --- a/src/albedo/openai_api/request_body.gleam +++ b/packages/albedo_http/src/albedo_http/body.gleam @@ -1,4 +1,4 @@ -//// A request body as the streaming transport writes it: iodata, as a +//// A request body as `albedo_http` writes it: iodata, as a //// `StringTree`, that may carry parts besides bytes. //// //// - A deferred part has a known size and is read only while the body is @@ -15,7 +15,7 @@ //// a deferred part is never compressed, since compressing it would hold //// every payload in memory at once. //// -//// `albedo_openai_transport.erl` tells each untyped iodata term apart; this +//// `albedo_http_ffi.erl` tells each untyped iodata term apart; this //// module walks the body into a typed plan and owns what a plan means: its //// length on the wire, how it is written, and the bytes it stands for. @@ -28,7 +28,7 @@ import gleam/option.{type Option, None, Some} import gleam/string_tree.{type StringTree} /// A part as it sits in a body's iodata. The constructors compile to the -/// tagged tuples `albedo_openai_transport:piece/1` recognises. +/// tagged tuples `albedo_http_ffi:piece/1` recognises. type Part { AlbedoHttpDeferred(size: Int, read: fn() -> Result(BitArray, Nil)) AlbedoHttpDigest( @@ -360,7 +360,7 @@ fn read_payload( } } -/// One term of a body's iodata, as `albedo_openai_transport:piece/1` tells +/// One term of a body's iodata, as `albedo_http_ffi:piece/1` tells /// it apart. type Piece { /// A binary or a byte, kept as the term it was, and its size. @@ -450,7 +450,7 @@ fn flush(current: List(Dynamic), done: List(Segment)) -> List(Segment) { } } -@external(erlang, "albedo_openai_transport", "piece") +@external(erlang, "albedo_http_ffi", "piece") fn piece(term: Dynamic) -> Piece @external(erlang, "erlang", "iolist_size") diff --git a/src/albedo/openai_api/connect.gleam b/packages/albedo_http/src/albedo_http/connect.gleam similarity index 99% rename from src/albedo/openai_api/connect.gleam rename to packages/albedo_http/src/albedo_http/connect.gleam index 9ce10d1c8..618b46863 100644 --- a/src/albedo/openai_api/connect.gleam +++ b/packages/albedo_http/src/albedo_http/connect.gleam @@ -9,9 +9,9 @@ //// while it is inside a socket ownership operation. The socket and TLS calls //// themselves are direct bindings to gen_tcp, ssl, inet and public_key. -import albedo/openai_api/proxy -import albedo/openai_api/route.{type Route, Direct, Proxy} import albedo_clock +import albedo_http/proxy +import albedo_http/route.{type Route, Direct, Proxy} import albedo_protect import gleam/dynamic.{type Dynamic} import gleam/erlang/atom diff --git a/src/albedo/openai_api/framing.gleam b/packages/albedo_http/src/albedo_http/framing.gleam similarity index 100% rename from src/albedo/openai_api/framing.gleam rename to packages/albedo_http/src/albedo_http/framing.gleam diff --git a/src/albedo/openai_api/pool.gleam b/packages/albedo_http/src/albedo_http/pool.gleam similarity index 97% rename from src/albedo/openai_api/pool.gleam rename to packages/albedo_http/src/albedo_http/pool.gleam index 8bcaf5f9d..3f73710d6 100644 --- a/src/albedo/openai_api/pool.gleam +++ b/packages/albedo_http/src/albedo_http/pool.gleam @@ -7,13 +7,13 @@ //// `idle_per_host` per host. One that closes or sends anything meanwhile is //// dropped. -import albedo/openai_api/connect.{type Transport} -import albedo/openai_api/framing.{type Framing} -import albedo/openai_api/route.{type Route} -import albedo/openai_api/socket.{type Socket} -import albedo/openai_api/tls.{type Trust} import albedo_bytes/term import albedo_clock +import albedo_http/connect.{type Transport} +import albedo_http/framing.{type Framing} +import albedo_http/route.{type Route} +import albedo_http/socket.{type Socket} +import albedo_http/tls.{type Trust} import gleam/bit_array import gleam/dict.{type Dict} import gleam/dynamic.{type Dynamic} @@ -384,7 +384,7 @@ fn drop(socket: Socket, conns: Dict(Socket, Conn)) -> Dict(Socket, Conn) { } fn name() -> process.Name(Message) { - coerce(atom.create("albedo_openai_pool")) + coerce(atom.create("albedo_http_pool")) } // The pool's messages carry its registered name as their tag, so a sender diff --git a/src/albedo/openai_api/proxy.gleam b/packages/albedo_http/src/albedo_http/proxy.gleam similarity index 98% rename from src/albedo/openai_api/proxy.gleam rename to packages/albedo_http/src/albedo_http/proxy.gleam index 341619b43..6d16eccf1 100644 --- a/src/albedo/openai_api/proxy.gleam +++ b/packages/albedo_http/src/albedo_http/proxy.gleam @@ -1,8 +1,8 @@ //// SOCKS5 and HTTP CONNECT negotiation on a passive socket, before any //// origin bytes. The connector still verifies destination TLS through it. -import albedo/openai_api/route.{type Scheme, HttpConnect, Socks5h} import albedo_clock +import albedo_http/route.{type Scheme, HttpConnect, Socks5h} import gleam/bit_array import gleam/dynamic.{type Dynamic} import gleam/erlang/atom diff --git a/src/albedo/openai_api/route.gleam b/packages/albedo_http/src/albedo_http/route.gleam similarity index 91% rename from src/albedo/openai_api/route.gleam rename to packages/albedo_http/src/albedo_http/route.gleam index 8bbfd4536..cfa0bd149 100644 --- a/src/albedo/openai_api/route.gleam +++ b/packages/albedo_http/src/albedo_http/route.gleam @@ -1,6 +1,6 @@ //// How an outbound connection reaches its server: directly, or through a //// SOCKS5 or HTTP CONNECT proxy. The caller chooses the route and passes it -//// to `transport.open`; nothing here reads settings or process state. +//// to `albedo_http.open`; nothing here reads settings or process state. import gleam/int import gleam/string diff --git a/src/albedo/openai_api/socket.gleam b/packages/albedo_http/src/albedo_http/socket.gleam similarity index 95% rename from src/albedo/openai_api/socket.gleam rename to packages/albedo_http/src/albedo_http/socket.gleam index 770c69f61..b8fb8b438 100644 --- a/src/albedo/openai_api/socket.gleam +++ b/packages/albedo_http/src/albedo_http/socket.gleam @@ -1,10 +1,10 @@ //// Calls the streaming transport and its connection pool make on a connected //// socket, through gen_tcp, inet and ssl, and the per-socket receive in -//// `albedo_openai_transport.erl`. The process that owns a socket receives its +//// `albedo_http_ffi.erl`. The process that owns a socket receives its //// messages. `active` sockets send //// them until the given count, then go passive and say so. -import albedo/openai_api/connect.{type Transport} +import albedo_http/connect.{type Transport} import gleam/dynamic.{type Dynamic} import gleam/erlang/atom import gleam/erlang/process.{type Pid} @@ -35,7 +35,7 @@ type Mode { /// Waits at most `wait` ms, or forever for `None`, for the socket's next /// message, leaving every other message in the mailbox. -@external(erlang, "albedo_openai_transport", "await") +@external(erlang, "albedo_http_ffi", "await") pub fn await(transport: Transport, socket: Socket, wait: Option(Int)) -> Event pub fn send( diff --git a/src/albedo/openai_api/tls.gleam b/packages/albedo_http/src/albedo_http/tls.gleam similarity index 90% rename from src/albedo/openai_api/tls.gleam rename to packages/albedo_http/src/albedo_http/tls.gleam index cd54f37a2..904aeed5a 100644 --- a/src/albedo/openai_api/tls.gleam +++ b/packages/albedo_http/src/albedo_http/tls.gleam @@ -1,5 +1,5 @@ //// The roots an HTTPS server's certificate must chain to. The caller -//// chooses them and passes them to `transport.open`; the transport reads +//// chooses them and passes them to `albedo_http.open`, which reads //// them only when it opens an HTTPS connection. import gleam/dynamic.{type Dynamic} diff --git a/src/albedo/openai_api/albedo_openai_transport.erl b/packages/albedo_http/src/albedo_http_ffi.erl similarity index 68% rename from src/albedo/openai_api/albedo_openai_transport.erl rename to packages/albedo_http/src/albedo_http_ffi.erl index cd2dbe206..8900881ce 100644 --- a/src/albedo/openai_api/albedo_openai_transport.erl +++ b/packages/albedo_http/src/albedo_http_ffi.erl @@ -1,8 +1,8 @@ --module(albedo_openai_transport). +-module(albedo_http_ffi). -%% Native bindings for the streaming transport. transport.gleam owns the +%% Native bindings for the streaming client. albedo_http.gleam owns the %% request flow, pooling and replay policy, response framing, and connection -%% state; request_body.gleam owns the body plan and its streaming write. What +%% state; albedo_http/body.gleam owns the body plan and its streaming write. What %% stays here cannot be written in Gleam, or would be clearly worse there: %% %% - await/3, a receive that matches one socket's messages. A socket's @@ -10,7 +10,7 @@ %% selector selects by the first element and arity only. %% - piece/1, which tells one term of untyped iodata apart with guards: %% a binary, a byte, list structure, or a deferred or digest part. -%% request_body.gleam walks the body and applies the rules. +%% albedo_http/body.gleam walks the body and applies the rules. -export([await/3, piece/1]). @@ -34,18 +34,14 @@ await(Transport, Socket, Wait) -> tags(tcp) -> {tcp, tcp_passive, tcp_closed, tcp_error}; tags(tls) -> {ssl, ssl_passive, ssl_closed, ssl_error}. -%% One piece of an iodata body as request_body.Piece: {bytes, Term, Size} +%% One piece of an iodata body as albedo_http/body.Piece: {bytes, Term, Size} %% for a binary or a byte, {cons, Head, Tail} and empty for the (possibly %% improper) list structure, and {part_piece, Part} for a deferred or digest -%% part, request_body.Part's own tuples, which request_body.gleam places in -%% its plan. +%% part, albedo_http/body.Part's own tuples, which body.gleam places in its +%% plan. piece(Piece) when is_binary(Piece) -> {bytes, Piece, byte_size(Piece)}; piece(Byte) when is_integer(Byte) -> {bytes, Byte, 1}; -piece([Head | Tail]) -> - {cons, Head, Tail}; -piece([]) -> - empty; -piece({albedo_http_deferred, _Size, _Read} = Part) -> - {part_piece, Part}; -piece({albedo_http_digest, _Init, _Update, _Emit, _Placeholder} = Part) -> - {part_piece, Part}. +piece([Head | Tail]) -> {cons, Head, Tail}; +piece([]) -> empty; +piece({albedo_http_deferred, _Size, _Read} = Part) -> {part_piece, Part}; +piece({albedo_http_digest, _Init, _Update, _Emit, _Placeholder} = Part) -> {part_piece, Part}. diff --git a/test/harness/transport_request_guard_test.gleam b/packages/albedo_http/test/albedo_http/guard_test.gleam similarity index 79% rename from test/harness/transport_request_guard_test.gleam rename to packages/albedo_http/test/albedo_http/guard_test.gleam index 303538108..ea1994ff9 100644 --- a/test/harness/transport_request_guard_test.gleam +++ b/packages/albedo_http/test/albedo_http/guard_test.gleam @@ -2,8 +2,8 @@ //// replay bugs. Daemon E2E cannot insert a trusted host callback between //// socket acquisition and the first HTTP write. -import albedo/openai_api/transport import albedo_clock +import albedo_http import gleam/option.{type Option, None, Some} import gleam/result import gleam/string_tree @@ -16,37 +16,37 @@ type Mode { DropSecond } -@external(erlang, "albedo_transport_request_guard_fixture", "start") +@external(erlang, "albedo_http_guard_fixture", "start") fn start(mode: Mode) -> Fixture -@external(erlang, "albedo_transport_request_guard_fixture", "url") +@external(erlang, "albedo_http_guard_fixture", "url") fn url(fixture: Fixture) -> String -@external(erlang, "albedo_transport_request_guard_fixture", "stop") +@external(erlang, "albedo_http_guard_fixture", "stop") fn stop(fixture: Fixture) -> Nil -@external(erlang, "albedo_transport_request_guard_fixture", "connected") +@external(erlang, "albedo_http_guard_fixture", "connected") fn connected(fixture: Fixture, count: Int) -> Bool -@external(erlang, "albedo_transport_request_guard_fixture", "closed") +@external(erlang, "albedo_http_guard_fixture", "closed") fn closed(fixture: Fixture, count: Int) -> Bool -@external(erlang, "albedo_transport_request_guard_fixture", "requested") +@external(erlang, "albedo_http_guard_fixture", "requested") fn requested(fixture: Fixture, count: Int) -> Bool -@external(erlang, "albedo_transport_request_guard_fixture", "stats") +@external(erlang, "albedo_http_guard_fixture", "stats") fn stats(fixture: Fixture) -> #(Int, Int, Int) -@external(erlang, "albedo_transport_request_guard_fixture", "record") +@external(erlang, "albedo_http_guard_fixture", "record") fn record(event: String) -> Nil -@external(erlang, "albedo_transport_request_guard_fixture", "events") +@external(erlang, "albedo_http_guard_fixture", "events") fn events() -> List(String) -@external(erlang, "albedo_transport_request_guard_fixture", "raise_guard") +@external(erlang, "albedo_http_guard_fixture", "raise_guard") fn raise_guard() -> Result(Nil, String) -@external(erlang, "albedo_transport_request_guard_fixture", "close_client_socket") +@external(erlang, "albedo_http_guard_fixture", "close_client_socket") fn close_client_socket(fixture: Fixture) -> Result(Nil, String) type Guard = @@ -55,9 +55,9 @@ type Guard = fn open( fixture: Fixture, guard: Option(Guard), -) -> Result(transport.Connection, transport.Error) { - transport.open( - transport.Options(..transport.options(), guard:), +) -> Result(albedo_http.Connection, albedo_http.Error) { + albedo_http.open( + albedo_http.Options(..albedo_http.options(), guard:), url(fixture), [], string_tree.from_string("payload"), @@ -68,12 +68,12 @@ fn open( fn get( fixture: Fixture, guard: Option(Guard), -) -> Result(BitArray, transport.Error) { +) -> Result(BitArray, albedo_http.Error) { use connection <- result.try(open(fixture, guard)) - use <- transport.with_connection(connection) - let assert Ok(transport.Headers(200, _, False)) = - transport.receive(connection) - let assert Ok(transport.Data(bytes, True)) = transport.receive(connection) + use <- albedo_http.with_connection(connection) + let assert Ok(albedo_http.Headers(200, _, False)) = + albedo_http.receive(connection) + let assert Ok(albedo_http.Data(bytes, True)) = albedo_http.receive(connection) connected(fixture, 1) |> should.be_true Ok(bytes) } @@ -90,7 +90,7 @@ fn expect_refused( reason: String, ) -> Nil { let assert Error(error) = open(fixture, Some(guard)) - error |> should.equal(transport.RequestRefused(reason)) + error |> should.equal(albedo_http.RequestRefused(reason)) closed(fixture, count) |> should.be_true } @@ -176,7 +176,7 @@ pub fn guarded_cached_send_failure_has_no_fresh_fallback_test() -> Nil { get(fixture, None) |> should.equal(Ok(<<"ok">>)) requested(fixture, 1) |> should.be_true let before = stats(fixture) - let assert Error(transport.TransportError(_)) = + let assert Error(albedo_http.TransportError(_)) = open( fixture, Some(fn() { @@ -201,9 +201,9 @@ pub fn cached_close_before_response_never_replays_guarded_request_test() -> Nil Ok(Nil) }), ) - let response = transport.receive(connection) - transport.close(connection) - let assert Error(transport.TransportError(_)) = response + let response = albedo_http.receive(connection) + albedo_http.close(connection) + let assert Error(albedo_http.TransportError(_)) = response closed(fixture, 1) |> should.be_true stats(fixture).0 |> should.equal(1) stats(fixture).1 |> should.equal(2) diff --git a/test/harness/albedo_transport_dual_stack_test.erl b/packages/albedo_http/test/albedo_http_dual_stack_test.erl similarity index 80% rename from test/harness/albedo_transport_dual_stack_test.erl rename to packages/albedo_http/test/albedo_http_dual_stack_test.erl index 4bb928af6..4fd4ffb8e 100644 --- a/test/harness/albedo_transport_dual_stack_test.erl +++ b/packages/albedo_http/test/albedo_http_dual_stack_test.erl @@ -1,9 +1,9 @@ %% A host that publishes one address family, or a network that resolves one, -%% must still connect. E2E cannot control name resolution, so this registers -%% names with only an IPv4 or IPv6 address and checks that the streaming -%% transport and the httpc front door reach the host over whichever family -%% answers, even when the other refuses. --module(albedo_transport_dual_stack_test). +%% must still connect. Name resolution is outside the client's control, so +%% this registers names with only an IPv4 or IPv6 address and checks that the +%% client reaches the host over whichever family answers, even when the other +%% refuses. +-module(albedo_http_dual_stack_test). -include_lib("eunit/include/eunit.hrl"). -include_lib("public_key/include/public_key.hrl"). @@ -36,8 +36,8 @@ refusing_family_does_not_block_the_other_test() -> unresolvable_name_reports_the_failure_test() -> ?assertMatch( {error, {transport_error, <<"connection failed: nxdomain">>}}, - 'albedo@openai_api@transport':open_method( - 'albedo@openai_api@transport':options(), + albedo_http:open_method( + options(), <<"GET">>, <<"http://missing.dual-stack.test/">>, [], @@ -50,8 +50,8 @@ refused_connection_reports_refusal_not_a_missing_family_test() -> with_hosts([{?V4, "closed.dual-stack.test"}], fun() -> ?assertMatch( {error, {transport_error, <<"connection failed: econnrefused">>}}, - 'albedo@openai_api@transport':open_method( - 'albedo@openai_api@transport':options(), + albedo_http:open_method( + options(), <<"GET">>, <<"http://closed.dual-stack.test:1/">>, [], @@ -81,8 +81,8 @@ https_establishment_uses_one_budget_and_closes_timed_out_sockets_test() -> Started = erlang:monotonic_time(millisecond), ?assertEqual( {error, timed_out}, - 'albedo@openai_api@transport':open_method( - 'albedo@openai_api@transport':options(), + albedo_http:open_method( + options(), <<"GET">>, tls_url("tls.dual-stack.test", Port), [], @@ -100,9 +100,10 @@ https_establishment_uses_one_budget_and_closes_timed_out_sockets_test() -> caller_death_closes_an_in_progress_tls_attempt_test() -> with_tls_servers([?V4], ?V4, fun(Port, Servers, Ref) -> with_hosts([{?V4, "tls.dual-stack.test"}], fun() -> + Options = options(), {Caller, Monitor} = spawn_monitor(fun() -> - 'albedo@openai_api@transport':open_method( - 'albedo@openai_api@transport':options(), + albedo_http:open_method( + Options, <<"GET">>, tls_url("tls.dual-stack.test", Port), [], @@ -145,34 +146,14 @@ https_checks_dns_and_ip_certificate_identity_test() -> ] ). -only_ipv6_name_reaches_httpc_front_door_test() -> - with_listener(?V6, fun(Port) -> - with_hosts([{?V6, "httpc-v6.dual-stack.test"}], fun() -> - URL = iolist_to_binary(io_lib:format("http://httpc-v6.dual-stack.test:~B/", [Port])), - ?assertMatch( - {ok, {200, _, <<"ok">>}}, albedo_http:request(get, URL, [], none, 3000, 3000) - ) - end) - end). - -only_ipv4_name_reaches_httpc_front_door_test() -> - with_listener(?V4, fun(Port) -> - with_hosts([{?V4, "httpc-v4.dual-stack.test"}], fun() -> - URL = iolist_to_binary(io_lib:format("http://httpc-v4.dual-stack.test:~B/", [Port])), - ?assertMatch( - {ok, {200, _, <<"ok">>}}, albedo_http:request(get, URL, [], none, 3000, 3000) - ) - end) - end). - fetch(Host, Port) -> URL = iolist_to_binary(io_lib:format("http://~s:~B/", [Host, Port])), fetch_url(URL, 3000). fetch_url(URL, Timeout) -> case - 'albedo@openai_api@transport':open_method( - 'albedo@openai_api@transport':options(), <<"GET">>, URL, [], <<>>, Timeout + albedo_http:open_method( + options(), <<"GET">>, URL, [], <<>>, Timeout ) of {error, _} = Error -> Error; @@ -181,11 +162,11 @@ fetch_url(URL, Timeout) -> read_response(Connection) -> try - {ok, {headers, 200, _, false}} = 'albedo@openai_api@transport':'receive'(Connection), - {ok, {data, <<"ok">>, true}} = 'albedo@openai_api@transport':'receive'(Connection), + {ok, {headers, 200, _, false}} = albedo_http:'receive'(Connection), + {ok, {data, <<"ok">>, true}} = albedo_http:'receive'(Connection), ok after - 'albedo@openai_api@transport':close(Connection) + albedo_http:close(Connection) end. %% A one-shot HTTP answer on the loopback address of one family. @@ -242,10 +223,10 @@ with_hosts(Hosts, Run) -> end. %% Raw listeners let one family accept TCP without completing its TLS handshake. -%% The other uses a real certificate signed by a temporary trusted root. +%% The other uses a real certificate signed by a temporary root, which +%% options/0 trusts while the servers run. with_tls_servers(Addresses, Stalled, Run) -> {ok, _} = application:ensure_all_started(ssl), - PreviousRoots = public_key:cacerts_get(), Name = #'Extension'{ extnID = ?'id-ce-subjectAltName', critical = false, @@ -260,7 +241,7 @@ with_tls_servers(Addresses, Stalled, Run) -> server_chain => #{root => Key, intermediates => [], peer => [{extensions, [Name]} | Key]}, client_chain => #{root => Key, intermediates => [], peer => Key} }), - ok = load_roots(proplists:get_value(cacerts, Client)), + put({?MODULE, roots}, proplists:get_value(cacerts, Client)), Ref = make_ref(), Parent = self(), {Listeners, Port} = tls_listeners(Addresses, 0, []), @@ -276,7 +257,7 @@ with_tls_servers(Addresses, Stalled, Run) -> [exit(Pid, kill) || {Pid, _} <- Servers], [gen_tcp:close(Listen) || {_, Listen} <- Listeners], [erlang:demonitor(Monitor, [flush]) || {_, Monitor} <- Servers], - load_roots([Der || #cert{der = Der} <- PreviousRoots]), + erase({?MODULE, roots}), flush_server_messages(Ref) end. @@ -353,16 +334,11 @@ flush_server_messages(Ref) -> tls_url(Host, Port) -> iolist_to_binary(io_lib:format("https://~s:~B/", [Host, Port])). -load_roots(Roots) -> - Path = filename:join( - os:getenv("TMPDIR", "/tmp"), - "albedo-dual-stack-ca-" ++ integer_to_list(erlang:unique_integer([positive])) ++ ".pem" - ), - ok = file:write_file( - Path, public_key:pem_encode([{'Certificate', Der, not_encrypted} || Der <- Roots]) - ), - try - public_key:cacerts_load(Path) - after - file:delete(Path) +%% The client's options, trusting the temporary root of the TLS servers this +%% process is running, if any. Options = {options, Route, Trust, Guard}. +options() -> + {options, Route, Trust, Guard} = albedo_http:options(), + case get({?MODULE, roots}) of + undefined -> {options, Route, Trust, Guard}; + Roots -> {options, Route, {roots, fun() -> Roots end}, Guard} end. diff --git a/test/harness/albedo_transport_request_guard_fixture.erl b/packages/albedo_http/test/albedo_http_guard_fixture.erl similarity index 99% rename from test/harness/albedo_transport_request_guard_fixture.erl rename to packages/albedo_http/test/albedo_http_guard_fixture.erl index 7b9e31c9e..3f4d6ca2d 100644 --- a/test/harness/albedo_transport_request_guard_fixture.erl +++ b/packages/albedo_http/test/albedo_http_guard_fixture.erl @@ -1,4 +1,4 @@ --module(albedo_transport_request_guard_fixture). +-module(albedo_http_guard_fixture). -export([ start/1, url/1, diff --git a/test/harness/albedo_transport_once_test.erl b/packages/albedo_http/test/albedo_http_once_test.erl similarity index 67% rename from test/harness/albedo_transport_once_test.erl rename to packages/albedo_http/test/albedo_http_once_test.erl index f9875552c..d381db95d 100644 --- a/test/harness/albedo_transport_once_test.erl +++ b/packages/albedo_http/test/albedo_http_once_test.erl @@ -2,7 +2,7 @@ %% without inheriting pooled retries. E2E cannot inspect captured guards or %% transport retry state or socket budgets, nor insert a refusal immediately %% before HTTP write or malformed internal headers rejected by public APIs. --module(albedo_transport_once_test). +-module(albedo_http_once_test). -include_lib("eunit/include/eunit.hrl"). invalid_headers_never_connect_test_() -> @@ -32,8 +32,8 @@ invalid_headers_never_connect(Headers) -> try ?assertEqual( {error, invalid_headers}, - 'albedo@openai_api@transport':open_once( - 'albedo@openai_api@transport':options(), URL, Headers, <<"payload">>, 2000 + albedo_http:open_once( + albedo_http:options(), URL, Headers, <<"payload">>, 2000 ) ), %% A completed connect would be queued even with no acceptor running. @@ -50,13 +50,13 @@ invalid_headers_never_connect(Headers) -> network_budget_ignores_scaled_clock_test() -> Previous = albedo_clock:scale(), - Fixture = albedo_transport_request_guard_fixture:start(keep_alive), + Fixture = albedo_http_guard_fixture:start(keep_alive), albedo_clock:set_scale(10), try ?assertEqual(210, albedo_clock:delay_ms(2100)), - URL = albedo_transport_request_guard_fixture:url(Fixture), - {ok, Connection} = 'albedo@openai_api@transport':open_once( - 'albedo@openai_api@transport':options(), URL, [], <<"payload">>, 2100 + URL = albedo_http_guard_fixture:url(Fixture), + {ok, Connection} = albedo_http:open_once( + albedo_http:options(), URL, [], <<"payload">>, 2100 ), try Captured = state(Connection), @@ -68,60 +68,60 @@ network_budget_ignores_scaled_clock_test() -> ?assertEqual(none, maps:get(retry, Captured)), ?assertMatch( {ok, {headers, 200, _, false}}, - 'albedo@openai_api@transport':'receive'(Connection) + albedo_http:'receive'(Connection) ), ?assertEqual( {ok, {data, <<"ok">>, true}}, - 'albedo@openai_api@transport':'receive'(Connection) + albedo_http:'receive'(Connection) ) after - 'albedo@openai_api@transport':close(Connection) + albedo_http:close(Connection) end after albedo_clock:set_scale(Previous), - albedo_transport_request_guard_fixture:stop(Fixture) + albedo_http_guard_fixture:stop(Fixture) end. refused_guard_writes_no_bytes_test() -> - Fixture = albedo_transport_request_guard_fixture:start(keep_alive), + Fixture = albedo_http_guard_fixture:start(keep_alive), try - URL = albedo_transport_request_guard_fixture:url(Fixture), + URL = albedo_http_guard_fixture:url(Fixture), Guard = fun() -> - ?assert(albedo_transport_request_guard_fixture:connected(Fixture, 1)), + ?assert(albedo_http_guard_fixture:connected(Fixture, 1)), {error, <<"cancelled before write">>} end, ?assertEqual( {error, {request_refused, <<"cancelled before write">>}}, - 'albedo@openai_api@transport':open_once( + albedo_http:open_once( guarded(Guard), URL, [], <<"image prompt">>, 2000 ) ), - ?assert(albedo_transport_request_guard_fixture:closed(Fixture, 1)), - ?assertEqual({1, 0, 0}, albedo_transport_request_guard_fixture:stats(Fixture)) + ?assert(albedo_http_guard_fixture:closed(Fixture, 1)), + ?assertEqual({1, 0, 0}, albedo_http_guard_fixture:stats(Fixture)) after - albedo_transport_request_guard_fixture:stop(Fixture) + albedo_http_guard_fixture:stop(Fixture) end. fresh_even_with_idle_connection_test() -> - Fixture = albedo_transport_request_guard_fixture:start(keep_alive), + Fixture = albedo_http_guard_fixture:start(keep_alive), try - URL = albedo_transport_request_guard_fixture:url(Fixture), - {ok, First} = 'albedo@openai_api@transport':open( - 'albedo@openai_api@transport':options(), URL, [], <<"first">>, 2000 + URL = albedo_http_guard_fixture:url(Fixture), + {ok, First} = albedo_http:open( + albedo_http:options(), URL, [], <<"first">>, 2000 ), finish(First), - {ok, Second} = 'albedo@openai_api@transport':open_once( - 'albedo@openai_api@transport':options(), URL, [], <<"second">>, 2000 + {ok, Second} = albedo_http:open_once( + albedo_http:options(), URL, [], <<"second">>, 2000 ), try - ?assert(albedo_transport_request_guard_fixture:connected(Fixture, 2)), + ?assert(albedo_http_guard_fixture:connected(Fixture, 2)), ?assertEqual(none, maps:get(retry, state(Second))), - ?assert(albedo_transport_request_guard_fixture:requested(Fixture, 2)) + ?assert(albedo_http_guard_fixture:requested(Fixture, 2)) after - 'albedo@openai_api@transport':close(Second) + albedo_http:close(Second) end after - albedo_transport_request_guard_fixture:stop(Fixture) + albedo_http_guard_fixture:stop(Fixture) end. post_guard_timeout_and_early_close_test() -> @@ -143,7 +143,7 @@ post_guard_timeout_and_early_close_test() -> end), Guard = fun() -> {ok, nil} end, try - {ok, Connection} = 'albedo@openai_api@transport':open_once( + {ok, Connection} = albedo_http:open_once( guarded(Guard), URL, [], <<"payload">>, 2100 ), try @@ -158,12 +158,12 @@ post_guard_timeout_and_early_close_test() -> end, ?assertMatch(<<"POST /images HTTP/1.1\r\n", _/binary>>, Request), ?assertNotEqual(nomatch, binary:match(Request, <<"content-length: 7\r\n">>)), - ?assertMatch({error, _}, 'albedo@openai_api@transport':'receive'(Connection)), + ?assertMatch({error, _}, albedo_http:'receive'(Connection)), %% Failed reads cannot resurrect the side-effecting request. ?assertEqual(none, maps:get(retry, state(Connection))), - ?assertMatch({error, _}, 'albedo@openai_api@transport':'receive'(Connection)) + ?assertMatch({error, _}, albedo_http:'receive'(Connection)) after - 'albedo@openai_api@transport':close(Connection) + albedo_http:close(Connection) end, receive {'DOWN', Monitor, process, Server, normal} -> ok @@ -175,30 +175,30 @@ post_guard_timeout_and_early_close_test() -> erlang:demonitor(Monitor, [flush]) end. -%% The transport's default options with Guard as their admission check, the +%% The client's default options with Guard as their admission check, the %% record's last field. guarded(Guard) -> - Options = 'albedo@openai_api@transport':options(), + Options = albedo_http:options(), setelement(tuple_size(Options), Options, {some, Guard}). -%% The fields of transport.gleam's connection state these tests inspect. +%% The fields of albedo_http.gleam's connection state these tests inspect. state({albedo_http, Owner, Ref}) when Owner =:= self() -> {state, Socket, _Transport, _Key, Timeout, _Phase, _Reusable, Guard, Retry, _, _} = - get({albedo_openai_transport, Ref}), + get({albedo_http_state, Ref}), #{socket => Socket, timeout => Timeout, guard => Guard, retry => Retry}. finish(Connection) -> try ?assertMatch( {ok, {headers, 200, _, false}}, - 'albedo@openai_api@transport':'receive'(Connection) + albedo_http:'receive'(Connection) ), ?assertEqual( {ok, {data, <<"ok">>, true}}, - 'albedo@openai_api@transport':'receive'(Connection) + albedo_http:'receive'(Connection) ) after - 'albedo@openai_api@transport':close(Connection) + albedo_http:close(Connection) end. read_request(Socket, Buffer) -> diff --git a/test/openai_api/transport_test.gleam b/packages/albedo_http/test/albedo_http_test.gleam similarity index 59% rename from test/openai_api/transport_test.gleam rename to packages/albedo_http/test/albedo_http_test.gleam index 68720c4fe..5dc400f1d 100644 --- a/test/openai_api/transport_test.gleam +++ b/packages/albedo_http/test/albedo_http_test.gleam @@ -1,26 +1,27 @@ //// Hard process death cannot execute callback cleanup; real socket ownership, //// receive deadlines, responses split at every byte, connection reuse, and -//// certificate verification require native transport probes beyond daemon -//// output. Header probes also observe refusal before connection acquisition -//// and the exact signed bytes, which daemon output cannot establish. - -import albedo/harness/extensions/mcp/http as mcp_http -import albedo/openai_api -import albedo/openai_api/refusal -import albedo/openai_api/request_body -import albedo/openai_api/route -import albedo/openai_api/stream as reducer -import albedo/openai_api/stream_http -import albedo/openai_api/transport -import albedo/openai_api/types +//// certificate verification need a real server on loopback. Header probes +//// also observe refusal before connection acquisition and the exact signed +//// bytes. + +import albedo_http +import albedo_http/body as request_body +import albedo_http/route +import albedo_http/tls import gleam/bit_array +import gleam/dynamic.{type Dynamic} import gleam/erlang/process +import gleam/int import gleam/list -import gleam/option.{None, Some} import gleam/string import gleam/string_tree +import gleeunit import gleeunit/should +pub fn main() -> Nil { + gleeunit.main() +} + type Fixture type Owner @@ -34,54 +35,51 @@ type Mode { DropSecond SlowEnd LateEnd - KeepaliveComments SilentHead SilentBody CloseAfterHeaders } -@external(erlang, "albedo_openai_transport_test_server", "start") +@external(erlang, "albedo_http_test_server", "start") fn start(mode: Mode) -> Fixture -@external(erlang, "albedo_openai_transport_test_server", "start_tls") +@external(erlang, "albedo_http_test_server", "start_tls") fn start_tls(mode: Mode) -> Fixture -@external(erlang, "albedo_openai_transport_test_server", "url") +@external(erlang, "albedo_http_test_server", "url") fn url(fixture: Fixture) -> String -@external(erlang, "albedo_openai_transport_test_server", "trust") -fn trust(fixture: Fixture) -> Nil - -@external(erlang, "albedo_openai_transport_test_server", "distrust") -fn distrust() -> Nil +/// The DER roots a TLS fixture's certificate chains to. +@external(erlang, "albedo_http_test_server", "roots") +fn roots(fixture: Fixture) -> List(Dynamic) -@external(erlang, "albedo_openai_transport_test_server", "owner_after_headers") +@external(erlang, "albedo_http_test_server", "owner_after_headers") fn owner_after_headers(fixture: Fixture) -> Owner -@external(erlang, "albedo_openai_transport_test_server", "kill_owner") +@external(erlang, "albedo_http_test_server", "kill_owner") fn kill_owner(owner: Owner) -> Bool -@external(erlang, "albedo_openai_transport_test_server", "await_closed") +@external(erlang, "albedo_http_test_server", "await_closed") fn await_closed(fixture: Fixture) -> Bool -@external(erlang, "albedo_openai_transport_test_server", "stop") +@external(erlang, "albedo_http_test_server", "stop") fn stop(fixture: Fixture) -> Nil // HeaderProbe leaves accept under explicit fixture control so unopened checks // inspect the listener backlog after open returns, without an acceptor race. -@external(erlang, "albedo_openai_transport_test_server", "unopened") +@external(erlang, "albedo_http_test_server", "unopened") fn unopened(fixture: Fixture) -> Bool -@external(erlang, "albedo_openai_transport_test_server", "await_headers") +@external(erlang, "albedo_http_test_server", "await_headers") fn await_headers(fixture: Fixture) -> String -@external(erlang, "albedo_openai_transport_test_server", "await_body") +@external(erlang, "albedo_http_test_server", "await_body") fn await_body(fixture: Fixture) -> BitArray -@external(erlang, "albedo_openai_transport_test_server", "unzstd") +@external(erlang, "albedo_http_test_server", "unzstd") fn unzstd(bytes: BitArray) -> BitArray -@external(erlang, "albedo_openai_transport_test_server", "gunzip") +@external(erlang, "albedo_http_test_server", "gunzip") fn gunzip(bytes: BitArray) -> BitArray /// A body with a deferred part the transport reads only while sending. @@ -107,24 +105,24 @@ pub fn invalid_headers_are_refused_before_connecting_test() -> Nil { ] use header <- list.each(invalid) let fixture = start(HeaderProbe) - transport.open( - transport.options(), + albedo_http.open( + albedo_http.options(), url(fixture), [header], string_tree.new(), 1000, ) - |> should.equal(Error(transport.InvalidHeaders)) + |> should.equal(Error(albedo_http.InvalidHeaders)) unopened(fixture) |> should.be_true - transport.open_method( - transport.options(), + albedo_http.open_method( + albedo_http.options(), "GET", url(fixture), [header], string_tree.new(), 1000, ) - |> should.equal(Error(transport.InvalidHeaders)) + |> should.equal(Error(albedo_http.InvalidHeaders)) unopened(fixture) |> should.be_true stop(fixture) } @@ -140,16 +138,16 @@ pub fn valid_signed_headers_keep_their_bytes_test() -> Nil { ] let opened = case method { "POST" -> - transport.open( - transport.options(), + albedo_http.open( + albedo_http.options(), url(fixture), headers, string_tree.new(), 1000, ) _ -> - transport.open_method( - transport.options(), + albedo_http.open_method( + albedo_http.options(), method, url(fixture), headers, @@ -168,7 +166,7 @@ pub fn valid_signed_headers_keep_their_bytes_test() -> Nil { string.split(string.lowercase(captured), "\r\nhost:") |> list.length |> should.equal(2) - transport.close(connection) + albedo_http.close(connection) stop(fixture) } @@ -181,26 +179,26 @@ pub fn a_body_asked_for_compression_is_compressed_unless_it_carries_images_test( let body = compressed(string_tree.from_string(text)) let fixture = start(HeaderProbe) let assert Ok(connection) = - transport.open(transport.options(), url(fixture), [], body, 1000) + albedo_http.open(albedo_http.options(), url(fixture), [], body, 1000) let head = await_headers(fixture) string.contains(head, "\r\ncontent-encoding: " <> encoding <> "\r\n") |> should.be_true - transport.close(connection) + albedo_http.close(connection) stop(fixture) let fixture = start(ContentLength) let assert Ok(connection) = - transport.open(transport.options(), url(fixture), [], body, 1000) + albedo_http.open(albedo_http.options(), url(fixture), [], body, 1000) let sent = await_body(fixture) { bit_array.byte_size(sent) < string.byte_size(text) } |> should.be_true decompress(sent) |> should.equal(<>) - transport.close(connection) + albedo_http.close(connection) stop(fixture) let fixture = start(HeaderProbe) let assert Ok(connection) = - transport.open( - transport.options(), + albedo_http.open( + albedo_http.options(), url(fixture), [], compressed(deferred_body()), @@ -208,51 +206,10 @@ pub fn a_body_asked_for_compression_is_compressed_unless_it_carries_images_test( ) string.contains(await_headers(fixture), "content-encoding") |> should.be_false - transport.close(connection) + albedo_http.close(connection) stop(fixture) } -pub fn invalid_headers_are_nonretryable_for_streams_and_bodies_test() -> Nil { - let fixture = start(HeaderProbe) - let headers = [#("Authorization", "fixture-secret\r\nx-injected: yes")] - let expected = Error(types.InvalidRequest("invalid HTTP headers")) - openai_api.exchange( - openai_api.Exchange( - url(fixture), - headers, - string_tree.new(), - timeout_ms: 1000, - first_event_timeout_ms: None, - max_event_bytes: 65_536, - require_event_stream: True, - refusal: refusal.openai, - ), - reducer.reducer(types.Responses), - fn(_) { types.Continue }, - ) - |> should.equal(expected) - stream_http.with_body( - stream_http.Exchange( - url(fixture), - headers, - string_tree.new(), - 1000, - None, - 65_536, - refusal: refusal.openai, - ), - 65_536, - True, - fn(_) { types.Continue }, - fn(_) { Ok(Nil) }, - ) - |> should.equal(Error(types.InvalidRequest("invalid HTTP headers"))) - unopened(fixture) |> should.be_true - stop(fixture) - mcp_http.describe(transport.InvalidHeaders) - |> should.equal("the MCP request headers are invalid") -} - pub fn close_delimited_transport_releases_owned_sockets_test() -> Nil { let killed = start(CloseDelimited) let owner = owner_after_headers(killed) @@ -262,9 +219,15 @@ pub fn close_delimited_transport_releases_owned_sockets_test() -> Nil { let idle = start(SilentHead) let assert Ok(connection) = - transport.open(transport.options(), url(idle), [], string_tree.new(), 100) - transport.receive(connection) |> should.equal(Error(transport.TimedOut)) - transport.close(connection) + albedo_http.open( + albedo_http.options(), + url(idle), + [], + string_tree.new(), + 100, + ) + albedo_http.receive(connection) |> should.equal(Error(albedo_http.TimedOut)) + albedo_http.close(connection) await_closed(idle) |> should.be_true stop(idle) } @@ -274,17 +237,17 @@ pub fn close_delimited_transport_releases_owned_sockets_test() -> Nil { pub fn a_silent_body_is_awaited_past_the_timeout_test() -> Nil { let fixture = start(SilentBody) let assert Ok(connection) = - transport.open( - transport.options(), + albedo_http.open( + albedo_http.options(), url(fixture), [], string_tree.new(), 500, ) - let assert Ok(transport.Headers(200, _, False)) = - transport.receive(connection) + let assert Ok(albedo_http.Headers(200, _, False)) = + albedo_http.receive(connection) body(connection, <<>>) |> should.equal(Ok(<<"hello world, all">>)) - transport.close(connection) + albedo_http.close(connection) stop(fixture) } @@ -310,11 +273,11 @@ pub fn a_proxy_route_never_reuses_a_direct_connection_test() -> Nil { let fixture = start(KeepAlive) get(url(fixture)) |> should.equal(Ok(<<"hello world, all">>)) let unreachable = - transport.Options( - ..transport.options(), + albedo_http.Options( + ..albedo_http.options(), route: route.Proxy(route.Socks5h, "127.0.0.1", 1), ) - transport.open(unreachable, url(fixture), [], string_tree.new(), 10_000) + albedo_http.open(unreachable, url(fixture), [], string_tree.new(), 10_000) |> should.be_error get(url(fixture)) |> should.equal(Ok(<<"hello world, all">>)) stop(fixture) @@ -365,17 +328,19 @@ pub fn a_failed_body_send_reports_the_socket_reason_test() -> Nil { request_body.deferred(1_048_576, fn() { Ok(payload) }), 64, )) - let assert Error(transport.TransportError(reason)) = - transport.open(transport.options(), url(fixture), [], body, 10_000) + let assert Error(albedo_http.TransportError(reason)) = + albedo_http.open(albedo_http.options(), url(fixture), [], body, 10_000) stop(fixture) assert string.starts_with(reason, "request failed: ") } pub fn https_verifies_the_server_certificate_test() -> Nil { + // Each fixture has a CA of its own, so one's roots do not trust another. + let other = start_tls(KeepAlive) let untrusted = start_tls(KeepAlive) - let assert Error(transport.TransportError(reason)) = - transport.open( - transport.options(), + let assert Error(albedo_http.TransportError(reason)) = + albedo_http.open( + trusting(other), url(untrusted), [], string_tree.new(), @@ -383,48 +348,105 @@ pub fn https_verifies_the_server_certificate_test() -> Nil { ) string.contains(reason, "Unknown CA") |> should.be_true stop(untrusted) + stop(other) + // The caller's roots decide; the second request reuses the connection the + // first verified. let trusted = start_tls(KeepAlive) - trust(trusted) - let first = get(url(trusted)) - let second = get(url(trusted)) - distrust() + let first = get_with(trusting(trusted), url(trusted)) + let second = get_with(trusting(trusted), url(trusted)) stop(trusted) first |> should.equal(Ok(<<"hello world, all">>)) second |> should.equal(Ok(<<"hello world, all">>)) } -/// Keepalive comments carry no event, so they hold off the idle budget but -/// not the first-event deadline. -pub fn the_first_event_deadline_outlasts_keepalives_test() -> Nil { - let fixture = start(KeepaliveComments) - openai_api.exchange( - openai_api.Exchange( - url(fixture), - [], - string_tree.new(), - timeout_ms: 2000, - first_event_timeout_ms: Some(300), - max_event_bytes: 65_536, - require_event_stream: True, - refusal: refusal.openai, - ), - reducer.reducer(types.Responses), - fn(_) { types.Continue }, +/// Options that trust only the CA `fixture`'s certificate chains to. +fn trusting(fixture: Fixture) -> albedo_http.Options { + albedo_http.Options( + ..albedo_http.options(), + trust: tls.Roots(fn() { roots(fixture) }), ) - |> should.equal(Error(types.Timeout(types.AwaitingFirstEvent, 300))) +} + +/// The bytes on the wire are the body's materialized bytes: deferred parts +/// read in place, and the digest computed over the whole body with its +/// placeholder in its place. +pub fn deferred_and_digest_parts_go_out_as_materialized_test() -> Nil { + let body = + string_tree.concat([ + string_tree.from_string("head:"), + request_body.deferred(5, fn() { Ok(<<"image">>) }), + string_tree.from_string(":sum="), + request_body.digest( + init: fn() { 0 }, + update: fn(total, bytes) { total + bit_array.byte_size(bytes) }, + emit: fn(total) { <> }, + placeholder: <<"00":utf8>>, + ), + string_tree.from_string(":tail"), + ]) + let expected = <<"head:image:sum=22:tail":utf8>> + request_body.materialize(body) |> should.equal(Ok(expected)) + let fixture = start(ContentLength) + let assert Ok(connection) = + albedo_http.open(albedo_http.options(), url(fixture), [], body, 1000) + await_body(fixture) |> should.equal(expected) + albedo_http.close(connection) stop(fixture) } +/// The body module refuses a body that breaks its rules, before a byte is +/// sent. +pub fn bodies_that_break_the_part_rules_are_refused_test() -> Nil { + let digest = fn(emitted) { + request_body.digest( + init: fn() { Nil }, + update: fn(state, _) { state }, + emit: fn(_) { emitted }, + placeholder: <<"00":utf8>>, + ) + } + let deferred = request_body.deferred(2, fn() { Ok(<<"ab">>) }) + [ + #( + string_tree.concat([digest(<<"11">>), digest(<<"22">>)]), + request_body.SecondDigest, + ), + #( + string_tree.concat([digest(<<"11">>), deferred]), + request_body.DeferredAfterDigest, + ), + #(digest(<<"111">>), request_body.DigestLength), + #( + request_body.deferred(3, fn() { Ok(<<"ab">>) }), + request_body.UnreadablePart, + ), + #( + request_body.deferred(2, fn() { Error(Nil) }), + request_body.UnreadablePart, + ), + ] + |> list.each(fn(case_) { + request_body.materialize(case_.0) |> should.equal(Error(case_.1)) + }) +} + /// One request read to its end and closed. -fn get(url: String) -> Result(BitArray, transport.Error) { - let assert Ok(connection) = opened(url, 5) +fn get(url: String) -> Result(BitArray, albedo_http.Error) { + get_with(albedo_http.options(), url) +} + +fn get_with( + options: albedo_http.Options, + url: String, +) -> Result(BitArray, albedo_http.Error) { + let assert Ok(connection) = opened(options, url, 5) let read = { - let assert Ok(transport.Headers(200, _, False)) = - transport.receive(connection) + let assert Ok(albedo_http.Headers(200, _, False)) = + albedo_http.receive(connection) body(connection, <<>>) } - transport.close(connection) + albedo_http.close(connection) read } @@ -434,11 +456,12 @@ fn first_chunk( url: String, finish: fn(BitArray) -> Result(BitArray, Nil), ) -> Result(BitArray, Nil) { - let assert Ok(connection) = opened(url, 5) - use <- transport.with_connection(connection) - let assert Ok(transport.Headers(200, _, False)) = - transport.receive(connection) - let assert Ok(transport.Data(bytes, False)) = transport.receive(connection) + let assert Ok(connection) = opened(albedo_http.options(), url, 5) + use <- albedo_http.with_connection(connection) + let assert Ok(albedo_http.Headers(200, _, False)) = + albedo_http.receive(connection) + let assert Ok(albedo_http.Data(bytes, False)) = + albedo_http.receive(connection) finish(bytes) } @@ -448,33 +471,34 @@ fn first_chunk( /// still ending, and the server refuses the new one it would open instead; /// a fresh attempt finds the kept connection idle by then and reuses it. fn opened( + options: albedo_http.Options, url: String, attempts: Int, -) -> Result(transport.Connection, transport.Error) { - case transport.open(transport.options(), url, [], string_tree.new(), 10_000) { +) -> Result(albedo_http.Connection, albedo_http.Error) { + case albedo_http.open(options, url, [], string_tree.new(), 10_000) { Ok(connection) -> Ok(connection) - Error(transport.TransportError(reason)) -> + Error(albedo_http.TransportError(reason)) -> case attempts > 1 && string.contains(reason, "econnrefused") { True -> { process.sleep(100) - opened(url, attempts - 1) + opened(options, url, attempts - 1) } - False -> Error(transport.TransportError(reason)) + False -> Error(albedo_http.TransportError(reason)) } Error(error) -> Error(error) } } fn body( - connection: transport.Connection, + connection: albedo_http.Connection, read: BitArray, -) -> Result(BitArray, transport.Error) { - case transport.receive(connection) { - Ok(transport.Data(bytes, True)) -> Ok(bit_array.append(read, bytes)) - Ok(transport.Data(bytes, False)) -> +) -> Result(BitArray, albedo_http.Error) { + case albedo_http.receive(connection) { + Ok(albedo_http.Data(bytes, True)) -> Ok(bit_array.append(read, bytes)) + Ok(albedo_http.Data(bytes, False)) -> body(connection, bit_array.append(read, bytes)) - Ok(transport.Headers(..)) -> - Error(transport.TransportError("headers again")) + Ok(albedo_http.Headers(..)) -> + Error(albedo_http.TransportError("headers again")) Error(error) -> Error(error) } } diff --git a/test/openai_api/albedo_openai_transport_test_server.erl b/packages/albedo_http/test/albedo_http_test_server.erl similarity index 91% rename from test/openai_api/albedo_openai_transport_test_server.erl rename to packages/albedo_http/test/albedo_http_test_server.erl index f4cc07ee4..ba28c7f0a 100644 --- a/test/openai_api/albedo_openai_transport_test_server.erl +++ b/packages/albedo_http/test/albedo_http_test_server.erl @@ -1,4 +1,4 @@ --module(albedo_openai_transport_test_server). +-module(albedo_http_test_server). -include_lib("public_key/include/public_key.hrl"). @@ -6,8 +6,7 @@ start/1, start_tls/1, url/1, - trust/1, - distrust/0, + roots/1, await_body/1, await_closed/1, stop/1, @@ -40,8 +39,8 @@ start(Mode) -> URL = iolist_to_binary(io_lib:format("http://127.0.0.1:~B/v1/chat?fixture=yes", [Port])), {fixture, Pid, URL, none}. -%% A TLS server for localhost under a fresh test CA, which no system trusts -%% until trust/1 loads it. +%% A TLS server for localhost under a fresh test CA, which no system trusts; +%% roots/1 returns it for a client to trust. start_tls(Mode) -> {ok, _} = application:ensure_all_started(ssl), Name = #'Extension'{ @@ -72,13 +71,9 @@ key() -> [{key, {namedCurve, ?secp256r1}}, {digest, sha256}]. url({fixture, _Pid, URL, _}) -> URL. -trust({fixture, _Pid, _URL, CaFile}) -> - ok = public_key:cacerts_load(CaFile), - nil. - -distrust() -> - public_key:cacerts_clear(), - nil. +roots({fixture, _Pid, _URL, CaFile}) -> + {ok, Pem} = file:read_file(CaFile), + [Der || {'Certificate', Der, not_encrypted} <- public_key:pem_decode(Pem)]. await_body({fixture, Pid, _URL, _}) -> receive @@ -119,14 +114,14 @@ stop({fixture, Pid, _URL, CaFile}) -> owner_after_headers(Fixture) -> Parent = self(), {Owner, Monitor} = spawn_monitor(fun() -> - {ok, Connection} = 'albedo@openai_api@transport':open( - 'albedo@openai_api@transport':options(), url(Fixture), [], <<>>, 10000 + {ok, Connection} = albedo_http:open( + albedo_http:options(), url(Fixture), [], <<>>, 10000 ), {ok, {headers, 200, _, false}} = - 'albedo@openai_api@transport':'receive'(Connection), + albedo_http:'receive'(Connection), Parent ! {transport_owner_ready, self()}, receive - stop -> 'albedo@openai_api@transport':close(Connection) + stop -> albedo_http:close(Connection) end end), receive @@ -324,12 +319,6 @@ respond(Socket, slow_end, Owner) -> respond_slow(Socket, Owner, slow_end, 10); respond(Socket, late_end, Owner) -> respond_slow(Socket, Owner, late_end, 300); -respond(Socket, keepalive_comments, Owner) -> - ok = send(Socket, << - "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n" - "transfer-encoding: chunked\r\n\r\n" - >>), - ping(Socket, Owner); respond(Socket, silent_head, Owner) -> wait_for_close(Socket, Owner); respond(Socket, silent_body, Owner) -> @@ -346,15 +335,6 @@ respond(Socket, close_delimited, Owner) -> ]), wait_for_close(Socket, Owner). -%% SSE comments every 50 ms, which carry no event, until the client hangs up. -ping(Socket, Owner) -> - case send(Socket, <<"8\r\n: ping\n\n\r\n">>) of - ok -> receive - after 50 -> ping(Socket, Owner) - end; - {error, _} -> Owner ! {fixture_closed, self()} - end. - %% The last body chunk lands Delay ms after the response's data, past the %% pool's wait for a connection that is still ending in the late_end mode. respond_slow(Socket, Owner, Mode, Delay) -> diff --git a/src/albedo/harness/extensions/bedrock/aws_profile.gleam b/src/albedo/harness/extensions/bedrock/aws_profile.gleam index b8f89454d..d376e1e1a 100644 --- a/src/albedo/harness/extensions/bedrock/aws_profile.gleam +++ b/src/albedo/harness/extensions/bedrock/aws_profile.gleam @@ -4,8 +4,8 @@ import albedo/harness/sdk/env import albedo/harness/sdk/file import albedo/harness/sdk/network_context -import albedo/openai_api/route import albedo_bytes/scalars +import albedo_http/route import albedo_ports/subprocess import aws_sigv4 import gleam/bit_array diff --git a/src/albedo/harness/extensions/claude/wire.gleam b/src/albedo/harness/extensions/claude/wire.gleam index 1094ac359..d53019ad5 100644 --- a/src/albedo/harness/extensions/claude/wire.gleam +++ b/src/albedo/harness/extensions/claude/wire.gleam @@ -14,10 +14,10 @@ import albedo/openai_api import albedo/openai_api/cost import albedo/openai_api/decoding import albedo/openai_api/replay -import albedo/openai_api/request_body import albedo/openai_api/stream import albedo/openai_api/types import albedo_bytes/scalars +import albedo_http/body as request_body import gleam/bit_array import gleam/bool import gleam/crypto.{Sha256} diff --git a/src/albedo/harness/extensions/codex/images.gleam b/src/albedo/harness/extensions/codex/images.gleam index abe2759f3..3d8bd62c8 100644 --- a/src/albedo/harness/extensions/codex/images.gleam +++ b/src/albedo/harness/extensions/codex/images.gleam @@ -1,10 +1,10 @@ -//// Codex image generation wire transport. Shared imagegen admission owns +//// Codex image generation wire albedo_http. Shared imagegen admission owns //// the worker that calls it. import albedo/harness/sdk/env import albedo/harness/sdk/network_context -import albedo/openai_api/transport import albedo_clock +import albedo_http import gleam/bit_array import gleam/list import gleam/option.{None, Some} @@ -109,7 +109,7 @@ fn request( ] let deadline = albedo_clock.monotonic_ms() + timeout_ms case - transport.open_once( + albedo_http.open_once( network_context.connection_options(), url, headers, @@ -119,7 +119,7 @@ fn request( { Ok(connection) -> { let result = read(connection, deadline, 0, "", [], 0) - transport.close(connection) + albedo_http.close(connection) result } Error(_) -> uncertain("", "connection failed") @@ -127,7 +127,7 @@ fn request( } fn read( - connection: transport.Connection, + connection: albedo_http.Connection, deadline: Int, status: Int, request_id: String, @@ -138,8 +138,8 @@ fn read( case left > 0 { False -> uncertain(request_id, "deadline exceeded") True -> - case transport.receive_within(connection, left) { - Ok(transport.Headers(code, headers, final)) -> { + case albedo_http.receive_within(connection, left) { + Ok(albedo_http.Headers(code, headers, final)) -> { let id = header( "x-codex-imagegen-request-id", @@ -151,7 +151,7 @@ fn read( False -> read(connection, deadline, code, id, [], 0) } } - Ok(transport.Data(data, final)) -> { + Ok(albedo_http.Data(data, final)) -> { let size = size + bit_array.byte_size(data) case size <= max_body, final { False, _ -> uncertain(request_id, "response body exceeds limit") diff --git a/src/albedo/harness/extensions/codex/wire.gleam b/src/albedo/harness/extensions/codex/wire.gleam index 900e8e918..2524ed7fc 100644 --- a/src/albedo/harness/extensions/codex/wire.gleam +++ b/src/albedo/harness/extensions/codex/wire.gleam @@ -4,11 +4,11 @@ import albedo/openai_api import albedo/openai_api/cost import albedo/openai_api/refusal as openai_refusal import albedo/openai_api/request as shared -import albedo/openai_api/request_body import albedo/openai_api/stream import albedo/openai_api/types import albedo_bytes/ids import albedo_clock +import albedo_http/body as request_body import gleam/dynamic/decode import gleam/json import gleam/list diff --git a/src/albedo/harness/extensions/discord/manager.gleam b/src/albedo/harness/extensions/discord/manager.gleam index cb238355f..703479ac2 100644 --- a/src/albedo/harness/extensions/discord/manager.gleam +++ b/src/albedo/harness/extensions/discord/manager.gleam @@ -16,8 +16,8 @@ import albedo/harness/extensions/discord/port import albedo/harness/sdk/input import albedo/harness/sdk/network import albedo/harness/sdk/storage -import albedo/openai_api/route import albedo_clock +import albedo_http/route import albedo_process/actor_call import gleam/dict.{type Dict} import gleam/dynamic.{type Dynamic} diff --git a/src/albedo/harness/extensions/mcp/client.gleam b/src/albedo/harness/extensions/mcp/client.gleam index 96ea68e4a..8c89f4aef 100644 --- a/src/albedo/harness/extensions/mcp/client.gleam +++ b/src/albedo/harness/extensions/mcp/client.gleam @@ -14,8 +14,8 @@ import albedo/harness/extensions/mcp/jsonrpc.{type Incoming, type Rejection} import albedo/harness/sdk/http as service_http import albedo/harness/sdk/network import albedo/harness/sdk/network_context -import albedo/openai_api/route import albedo_clock +import albedo_http/route import albedo_ports import albedo_ports/subprocess import albedo_process/actor_call diff --git a/src/albedo/harness/extensions/mcp/http.gleam b/src/albedo/harness/extensions/mcp/http.gleam index 06bb092fb..41d70e857 100644 --- a/src/albedo/harness/extensions/mcp/http.gleam +++ b/src/albedo/harness/extensions/mcp/http.gleam @@ -8,8 +8,8 @@ import albedo/harness/extensions/mcp/jsonrpc.{type Incoming} import albedo/harness/sdk/network_context -import albedo/openai_api/transport import albedo_clock +import albedo_http import albedo_sse as sse import gleam/bit_array import gleam/bytes_tree.{type BytesTree} @@ -118,7 +118,7 @@ pub fn post( let deadline = albedo_clock.monotonic_ms() + albedo_clock.delay_ms(timeout) let exchange = Exchange(url, headers, in_session, Some(deadline), sink) case - transport.open( + albedo_http.open( network_context.connection_options(), url, headers, @@ -126,11 +126,11 @@ pub fn post( timeout, ) { - Error(transport.TimedOut) -> TimedOut + Error(albedo_http.TimedOut) -> TimedOut Error(error) -> Failed(describe(error)) Ok(connection) -> { let read = respond(exchange, connection, id) - transport.close(connection) + albedo_http.close(connection) case read { Answered -> Finished Stopped(outcome) -> outcome @@ -158,7 +158,7 @@ fn resume( process.sleep(wait) let headers = stream_headers(exchange.headers, last_event) case - transport.open_method( + albedo_http.open_method( network_context.connection_options(), "GET", exchange.url, @@ -170,7 +170,7 @@ fn resume( Error(error) -> Failed(describe(error)) Ok(connection) -> { let read = resumed(exchange, connection, id, progress) - transport.close(connection) + albedo_http.close(connection) case read { Answered -> Finished Stopped(outcome) -> outcome @@ -185,7 +185,7 @@ fn resume( fn resumed( exchange: Exchange, - connection: transport.Connection, + connection: albedo_http.Connection, id: Option(Int), progress: Progress, ) -> Read { @@ -224,7 +224,7 @@ pub fn listen( let exchange = Exchange(url, headers, in_session, None, sink) let #(opened, id, last_event) = case how { Get(last_event) -> #( - transport.open_method( + albedo_http.open_method( network_context.connection_options(), "GET", url, @@ -236,7 +236,7 @@ pub fn listen( last_event, ) Subscribe(frame, id) -> #( - transport.open( + albedo_http.open( network_context.connection_options(), url, headers, @@ -251,7 +251,7 @@ pub fn listen( Error(_) -> Dropped(last_event, None, False) Ok(connection) -> { let end = listened(exchange, connection, id, last_event) - transport.close(connection) + albedo_http.close(connection) end } } @@ -259,7 +259,7 @@ pub fn listen( fn listened( exchange: Exchange, - connection: transport.Connection, + connection: albedo_http.Connection, id: Option(Int), last_event: String, ) -> StreamEnd { @@ -303,7 +303,7 @@ fn listened( fn respond( exchange: Exchange, - connection: transport.Connection, + connection: albedo_http.Connection, id: Option(Int), ) -> Read { use status, content, final, challenge <- headers(exchange, connection) @@ -328,15 +328,15 @@ fn respond( /// `WWW-Authenticate` value ("" when none) to `next`. fn headers( exchange: Exchange, - connection: transport.Connection, + connection: albedo_http.Connection, next: fn(Int, String, Bool, String) -> Read, ) -> Read { case receive(exchange, connection) { - Error(transport.TimedOut) -> Stopped(TimedOut) + Error(albedo_http.TimedOut) -> Stopped(TimedOut) Error(error) -> Stopped(Failed(describe(error))) - Ok(transport.Data(..)) -> + Ok(albedo_http.Data(..)) -> Stopped(Failed("the MCP server sent data before headers")) - Ok(transport.Headers(status, headers, final)) -> { + Ok(albedo_http.Headers(status, headers, final)) -> { case list.key_find(headers, "mcp-session-id") { Ok(session) -> exchange.sink.session(session) Error(Nil) -> Nil @@ -358,7 +358,7 @@ fn is_stream(content: String) -> Bool { /// challenge is not an answer, so its body is drained unread. fn refused( exchange: Exchange, - connection: transport.Connection, + connection: albedo_http.Connection, status: Int, final: Bool, challenge: String, @@ -384,7 +384,7 @@ fn refused( /// challenge it carries; None for any other refusal. fn challenged( exchange: Exchange, - connection: transport.Connection, + connection: albedo_http.Connection, status: Int, final: Bool, challenge: String, @@ -402,9 +402,9 @@ fn challenged( } } -fn drain(exchange: Exchange, connection: transport.Connection) -> Nil { +fn drain(exchange: Exchange, connection: albedo_http.Connection) -> Nil { case receive(exchange, connection) { - Ok(transport.Data(_, False)) -> drain(exchange, connection) + Ok(albedo_http.Data(_, False)) -> drain(exchange, connection) _ -> Nil } } @@ -419,25 +419,26 @@ fn result_read(outcome: Result(Nil, Outcome), next: fn(Nil) -> Read) -> Read { /// Reads a whole JSON body and passes on its messages. fn body( exchange: Exchange, - connection: transport.Connection, + connection: albedo_http.Connection, ) -> Result(Nil, Outcome) { collect(exchange, connection, bytes_tree.new(), 0) } fn collect( exchange: Exchange, - connection: transport.Connection, + connection: albedo_http.Connection, collected: BytesTree, size: Int, ) -> Result(Nil, Outcome) { use message <- result.try(case receive(exchange, connection) { Ok(message) -> Ok(message) - Error(transport.TimedOut) -> Error(TimedOut) + Error(albedo_http.TimedOut) -> Error(TimedOut) Error(error) -> Error(Failed(describe(error))) }) case message { - transport.Headers(..) -> Error(Failed("the MCP server sent headers twice")) - transport.Data(bytes, final) -> { + albedo_http.Headers(..) -> + Error(Failed("the MCP server sent headers twice")) + albedo_http.Data(bytes, final) -> { let size = size + bit_array.byte_size(bytes) let collected = bytes_tree.append(collected, bytes) case size > max_message_bytes, final { @@ -460,13 +461,13 @@ fn collect( /// Reads SSE events, passing each message on, until one answers `id`. fn events( exchange: Exchange, - connection: transport.Connection, + connection: albedo_http.Connection, id: Option(Int), parser: sse.Parser, count: Int, ) -> Read { case receive(exchange, connection) { - Error(transport.TimedOut) -> Stopped(TimedOut) + Error(albedo_http.TimedOut) -> Stopped(TimedOut) Error(error) -> { let now = albedo_clock.monotonic_ms() case exchange.deadline { @@ -474,9 +475,9 @@ fn events( _ -> Ended(progress(parser, count)) } } - Ok(transport.Headers(..)) -> + Ok(albedo_http.Headers(..)) -> Stopped(Failed("the MCP server sent headers twice")) - Ok(transport.Data(bytes, final)) -> { + Ok(albedo_http.Data(bytes, final)) -> { let fed = case sse.feed(parser, bytes) { Error(_) -> Error(Nil) Ok(#(parser, frames)) if final -> @@ -530,11 +531,11 @@ fn deliver(sink: Sink, text: String, id: Option(Int)) -> Bool { fn receive( exchange: Exchange, - connection: transport.Connection, -) -> Result(transport.Message, transport.Error) { + connection: albedo_http.Connection, +) -> Result(albedo_http.Message, albedo_http.Error) { case exchange.deadline { - Some(deadline) -> transport.receive_until(connection, deadline) - None -> transport.receive(connection) + Some(deadline) -> albedo_http.receive_until(connection, deadline) + None -> albedo_http.receive(connection) } } @@ -555,12 +556,12 @@ fn stream_headers( } } -pub fn describe(error: transport.Error) -> String { +pub fn describe(error: albedo_http.Error) -> String { case error { - transport.InvalidUrl -> "the MCP server URL is invalid" - transport.InvalidHeaders -> "the MCP request headers are invalid" - transport.TransportError(reason) -> reason - transport.RequestRefused(reason) -> reason - transport.TimedOut -> "the MCP server timed out" + albedo_http.InvalidUrl -> "the MCP server URL is invalid" + albedo_http.InvalidHeaders -> "the MCP request headers are invalid" + albedo_http.TransportError(reason) -> reason + albedo_http.RequestRefused(reason) -> reason + albedo_http.TimedOut -> "the MCP server timed out" } } diff --git a/src/albedo/harness/extensions/openai/extension.gleam b/src/albedo/harness/extensions/openai/extension.gleam index 384f6ffd9..41bd8e654 100644 --- a/src/albedo/harness/extensions/openai/extension.gleam +++ b/src/albedo/harness/extensions/openai/extension.gleam @@ -18,10 +18,10 @@ import albedo/openai_api/cost import albedo/openai_api/count import albedo/openai_api/refusal import albedo/openai_api/request as wire -import albedo/openai_api/request_body import albedo/openai_api/stream as reducer import albedo/openai_api/types import albedo_bytes/digest +import albedo_http/body as request_body import gleam/bool import gleam/dict import gleam/dynamic/decode diff --git a/src/albedo/harness/sdk/albedo_http.erl b/src/albedo/harness/sdk/albedo_httpc.erl similarity index 96% rename from src/albedo/harness/sdk/albedo_http.erl rename to src/albedo/harness/sdk/albedo_httpc.erl index e7aca2154..87501f957 100644 --- a/src/albedo/harness/sdk/albedo_http.erl +++ b/src/albedo/harness/sdk/albedo_httpc.erl @@ -1,4 +1,4 @@ --module(albedo_http). +-module(albedo_httpc). %% The httpc binding behind albedo/harness/sdk/http.gleam, which owns method %% validation, response conversion, error text, and redirect lookups. This %% stays Erlang because httpc has no Gleam library: its request tuple and @@ -9,7 +9,7 @@ %% URL, and plain http has no TLS options. httpc reaches a host over IPv4 only %% unless told otherwise, so a name that resolves to IPv6 alone fails with %% nxdomain. started/0 sets inet6fb4: IPv6 first, IPv4 when that fails. -%% Streaming requests race both families in openai_api/connect.gleam instead. +%% Streaming requests race both families in the albedo_http package instead. -export([get/4, request/6, request/7]). diff --git a/src/albedo/harness/sdk/extension.gleam b/src/albedo/harness/sdk/extension.gleam index 91c640dda..9e9279c9d 100644 --- a/src/albedo/harness/sdk/extension.gleam +++ b/src/albedo/harness/sdk/extension.gleam @@ -32,11 +32,11 @@ import albedo/harness/sdk/web_search import albedo/harness/settings/declared as declared_settings import albedo/harness/size import albedo/harness/worktree -import albedo/openai_api/route import albedo/openai_api/types import albedo/startup import albedo/transfer import albedo_clock +import albedo_http/route import albedo_protect import gleam/bool import gleam/dict.{type Dict} diff --git a/src/albedo/harness/sdk/http.gleam b/src/albedo/harness/sdk/http.gleam index 8484e3efb..794cc16ad 100644 --- a/src/albedo/harness/sdk/http.gleam +++ b/src/albedo/harness/sdk/http.gleam @@ -6,9 +6,9 @@ //// validation, response conversion, error text, and redirect lookups. import albedo/harness/sdk/network_context -import albedo/openai_api/route.{Direct, Proxy} -import albedo/openai_api/transport import albedo_clock +import albedo_http +import albedo_http/route.{Direct, Proxy} import gleam/bit_array import gleam/bool import gleam/dynamic.{type Dynamic} @@ -336,7 +336,7 @@ fn routed( body: Dynamic, deadline: Int, redirects: Int, -) -> Result(#(Int, List(#(String, String)), BitArray), transport.Error) { +) -> Result(#(Int, List(#(String, String)), BitArray), albedo_http.Error) { let name = string.uppercase(atom.to_string(method)) let #(sent, bytes) = case body == no_body() { True -> #(headers, <<>>) @@ -346,8 +346,8 @@ fn routed( } } let left = deadline - albedo_clock.monotonic_ms() - use <- bool.guard(left <= 0, Error(transport.TimedOut)) - use connection <- result.try(transport.open_method( + use <- bool.guard(left <= 0, Error(albedo_http.TimedOut)) + use connection <- result.try(albedo_http.open_method( network_context.connection_options(), name, url, @@ -356,7 +356,7 @@ fn routed( left, )) let response = receive(connection, name == "HEAD", deadline, 0, [], []) - transport.close(connection) + albedo_http.close(connection) use #(status, received, _) as response <- result.try(response) let target = { use location <- result.try(list.key_find(received, "location")) @@ -391,21 +391,21 @@ fn routed( } fn receive( - connection: transport.Connection, + connection: albedo_http.Connection, head: Bool, deadline: Int, status: Int, headers: List(#(String, String)), chunks: List(BitArray), -) -> Result(#(Int, List(#(String, String)), BitArray), transport.Error) { - case transport.receive_until(connection, deadline) { - Ok(transport.Headers(status, headers, final)) if final || head -> +) -> Result(#(Int, List(#(String, String)), BitArray), albedo_http.Error) { + case albedo_http.receive_until(connection, deadline) { + Ok(albedo_http.Headers(status, headers, final)) if final || head -> Ok(#(status, headers, <<>>)) - Ok(transport.Headers(status, headers, _)) -> + Ok(albedo_http.Headers(status, headers, _)) -> receive(connection, head, deadline, status, headers, chunks) - Ok(transport.Data(bytes, False)) -> + Ok(albedo_http.Data(bytes, False)) -> receive(connection, head, deadline, status, headers, [bytes, ..chunks]) - Ok(transport.Data(bytes, True)) -> + Ok(albedo_http.Data(bytes, True)) -> Ok(#(status, headers, bit_array.concat(list.reverse([bytes, ..chunks])))) Error(error) -> Error(error) } @@ -413,7 +413,7 @@ fn receive( /// `body` is `none` or `{ContentType, Payload}`. Headers in the response are /// httpc's character lists. -@external(erlang, "albedo_http", "request") +@external(erlang, "albedo_httpc", "request") fn httpc_request( method: Atom, url: String, diff --git a/src/albedo/harness/sdk/network.gleam b/src/albedo/harness/sdk/network.gleam index 1d864f74a..b4c2cafa8 100644 --- a/src/albedo/harness/sdk/network.gleam +++ b/src/albedo/harness/sdk/network.gleam @@ -6,7 +6,7 @@ import albedo/harness/sdk/profiles import albedo/harness/sdk/settings -import albedo/openai_api/route.{ +import albedo_http/route.{ type Route, Direct, HttpConnect, Proxy, Socks5, Socks5h, } import gleam/dict.{type Dict} diff --git a/src/albedo/harness/sdk/network_context.gleam b/src/albedo/harness/sdk/network_context.gleam index f8ffdf5ed..7681f467a 100644 --- a/src/albedo/harness/sdk/network_context.gleam +++ b/src/albedo/harness/sdk/network_context.gleam @@ -2,9 +2,9 @@ import albedo/harness/sdk/network.{type Service} import albedo/harness/trust -import albedo/openai_api/route.{type Route, Direct} -import albedo/openai_api/tls -import albedo/openai_api/transport +import albedo_http +import albedo_http/route.{type Route, Direct} +import albedo_http/tls import albedo_protect import gleam/dynamic.{type Dynamic} import gleam/erlang/atom @@ -23,9 +23,9 @@ pub fn current() -> Route { /// Options for a streaming connection this process opens: its current route, /// verified against albedo's trusted roots. -pub fn connection_options() -> transport.Options { - transport.Options( - ..transport.options(), +pub fn connection_options() -> albedo_http.Options { + albedo_http.Options( + ..albedo_http.options(), route: current(), trust: tls.Roots(trust.cacerts), ) diff --git a/src/albedo/harness/sdk/usage_feed.gleam b/src/albedo/harness/sdk/usage_feed.gleam index c26dfbe97..fd559bef1 100644 --- a/src/albedo/harness/sdk/usage_feed.gleam +++ b/src/albedo/harness/sdk/usage_feed.gleam @@ -16,8 +16,8 @@ import albedo/harness/sdk/http import albedo/harness/sdk/key_environment.{type KeyEnvironment} import albedo/harness/sdk/network_context import albedo/harness/sdk/priv -import albedo/openai_api/route import albedo_env +import albedo_http/route import albedo_ports/subprocess import gleam/bit_array import gleam/dynamic/decode diff --git a/src/albedo/openai_api/attestation.gleam b/src/albedo/openai_api/attestation.gleam index 8f0654a7c..219e0369d 100644 --- a/src/albedo/openai_api/attestation.gleam +++ b/src/albedo/openai_api/attestation.gleam @@ -3,7 +3,7 @@ //// `request_body` owns the digest part's rules and computes it while the //// transport writes the body. -import albedo/openai_api/request_body +import albedo_http/body as request_body import gleam/json.{type Json} /// Raw JSON bytes `before`, the digest part, then raw JSON bytes `after`. diff --git a/src/albedo/openai_api/stream_http.gleam b/src/albedo/openai_api/stream_http.gleam index 179b19d81..f13c12eda 100644 --- a/src/albedo/openai_api/stream_http.gleam +++ b/src/albedo/openai_api/stream_http.gleam @@ -9,10 +9,10 @@ import albedo/harness/sdk/network_context import albedo/openai_api/stream -import albedo/openai_api/transport import albedo/openai_api/types import albedo_clock import albedo_env +import albedo_http import gleam/bit_array import gleam/int import gleam/list @@ -87,7 +87,7 @@ pub fn exchange( }), ) use connection <- result.try( - transport.open( + albedo_http.open( network_context.connection_options(), exchange.url, exchange.headers, @@ -103,7 +103,7 @@ pub fn exchange( use <- with_connection(connection, wire.discard_on_error) use first <- result.try(receive(connection, wait, types.AwaitingHeaders)) case first { - transport.Headers(status, headers, final) -> { + albedo_http.Headers(status, headers, final) -> { use _ <- result.try(notify([types.Responded(status)], on_event)) let failed = fn() { http_error(connection, wait, exchange.refusal, status, final, [], 0) @@ -137,7 +137,7 @@ pub fn exchange( } fn pump( - connection: transport.Connection, + connection: albedo_http.Connection, wait: Wait, phase: types.TimeoutPhase, parser: parser, @@ -148,7 +148,7 @@ fn pump( ) -> Result(types.Turn, types.Error) { use message <- result.try(receive(connection, wait, phase)) case message { - transport.Data(bytes, final) -> { + albedo_http.Data(bytes, final) -> { let now = albedo_clock.monotonic_ms() use #(parser, frames) <- result.try(wire.feed(parser, bytes)) let phase = case frames { @@ -235,13 +235,13 @@ fn settle( } fn with_connection( - connection: transport.Connection, + connection: albedo_http.Connection, discard_on_error: Bool, run: fn() -> value, ) -> value { case discard_on_error { - True -> transport.with_connection_discard_errors(connection, run) - False -> transport.with_connection(connection, run) + True -> albedo_http.with_connection_discard_errors(connection, run) + False -> albedo_http.with_connection(connection, run) } } @@ -315,41 +315,41 @@ type Wait { /// one runs, else within the idle budget until the first event. Once events /// flow, a body chunk waits while the connection is alive. fn receive( - connection: transport.Connection, + connection: albedo_http.Connection, wait: Wait, phase: types.TimeoutPhase, -) -> Result(transport.Message, types.Error) { +) -> Result(albedo_http.Message, types.Error) { case wait.first_event, phase { Some(#(deadline, total)), types.AwaitingHeaders | Some(#(deadline, total)), types.AwaitingFirstEvent -> - transport.receive_until(connection, deadline) + albedo_http.receive_until(connection, deadline) |> result.map_error(transport_error(_, phase, total)) _, types.Streaming -> - transport.receive(connection) + albedo_http.receive(connection) |> result.map_error(transport_error(_, phase, wait.idle_ms)) _, _ -> - transport.receive_within(connection, wait.idle_ms) + albedo_http.receive_within(connection, wait.idle_ms) |> result.map_error(transport_error(_, phase, wait.idle_ms)) } } fn transport_error( - error: transport.Error, + error: albedo_http.Error, phase: types.TimeoutPhase, waited_ms: Int, ) -> types.Error { case error { - transport.InvalidUrl -> types.InvalidRequest("invalid HTTP endpoint") - transport.InvalidHeaders -> types.InvalidRequest("invalid HTTP headers") - transport.RequestRefused(message) -> types.InvalidRequest(message) - transport.TransportError(message) -> types.ConnectionError(message) - transport.TimedOut -> types.Timeout(phase, waited_ms) + albedo_http.InvalidUrl -> types.InvalidRequest("invalid HTTP endpoint") + albedo_http.InvalidHeaders -> types.InvalidRequest("invalid HTTP headers") + albedo_http.RequestRefused(message) -> types.InvalidRequest(message) + albedo_http.TransportError(message) -> types.ConnectionError(message) + albedo_http.TimedOut -> types.Timeout(phase, waited_ms) } } fn http_error( - connection: transport.Connection, + connection: albedo_http.Connection, wait: Wait, refusal: fn(Int, String) -> types.Error, status: Int, @@ -374,7 +374,7 @@ fn http_error( types.AwaitingFirstEvent, )) case message { - transport.Data(bytes, final) -> { + albedo_http.Data(bytes, final) -> { let remaining = max_error_bytes - size let bytes = case bit_array.byte_size(bytes) > remaining { True -> bit_array.slice(bytes, 0, remaining) |> result.unwrap(<<>>) @@ -415,7 +415,7 @@ pub fn with_body( }), ) use connection <- result.try( - transport.open( + albedo_http.open( network_context.connection_options(), exchange.url, exchange.headers, @@ -431,7 +431,7 @@ pub fn with_body( use <- with_connection(connection, discard_on_error) use first <- result.try(receive(connection, wait, types.AwaitingHeaders)) case first { - transport.Headers(status, _, final) -> { + albedo_http.Headers(status, _, final) -> { use _ <- result.try(notify([types.Responded(status)], on_event)) case status >= 200 && status < 300 { False -> @@ -461,7 +461,7 @@ pub fn with_body( } fn collect( - connection: transport.Connection, + connection: albedo_http.Connection, wait: Wait, phase: types.TimeoutPhase, final: Bool, @@ -474,7 +474,7 @@ fn collect( False -> { use message <- result.try(receive(connection, wait, phase)) case message { - transport.Data(bytes, final) -> { + albedo_http.Data(bytes, final) -> { let size = size + bit_array.byte_size(bytes) case size > limit { True -> Error(types.EventTooLarge) diff --git a/src/albedo/openai_api/types.gleam b/src/albedo/openai_api/types.gleam index 681ddc90d..d80d961ef 100644 --- a/src/albedo/openai_api/types.gleam +++ b/src/albedo/openai_api/types.gleam @@ -1,4 +1,4 @@ -import albedo/openai_api/request_body +import albedo_http/body as request_body import gleam/bit_array import gleam/bool import gleam/crypto diff --git a/test/albedo_test_runner.erl b/test/albedo_test_runner.erl index 494739276..9cd9b7a7e 100644 --- a/test/albedo_test_runner.erl +++ b/test/albedo_test_runner.erl @@ -15,16 +15,15 @@ 'harness@runtime_test', 'harness@antigravity_errors_test', 'harness@bedrock_converse_http_test', - 'openai_api@transport_test', + 'openai_api@stream_http_test', %% Writes a sealed extension cache, which swaps HOME, PATH and TMPDIR. 'harness@extension_cache_test', 'harness@github_copilot_sign_in_test', 'harness@opencode_go_sign_in_test', %% Counts the VM's atoms, which other suites may create meanwhile. 'harness@oauth_test', - %% Changes the VM-wide clock scale, which other suites must not observe. - albedo_transport_once_test, - albedo_transport_dual_stack_test + %% Changes the VM-wide host table, which other suites must not observe. + albedo_httpc_dual_stack_test ]). main() -> diff --git a/test/e2e/antigravity_support.py b/test/e2e/antigravity_support.py index 6923716c8..c65e2587d 100644 --- a/test/e2e/antigravity_support.py +++ b/test/e2e/antigravity_support.py @@ -21,11 +21,14 @@ SIGNATURE = "Zml4dHVyZS1zaWduYXR1cmU=" GEMINI = "gemini-3-flash" CLAUDE = "claude-opus-5-5" GUARD = Path(__file__).with_name("albedo_antigravity_offline.erl") -TRANSPORT = "albedo@openai_api@transport" +TRANSPORT = "albedo_http" +HTTPC = "albedo_httpc" +# The OTP application each replaced module ships in. +APPLICATIONS = {TRANSPORT: "albedo_http", HTTPC: "albedo"} # No inets entry point in the private build can contact a provider. Retain # the production exports so an added front door fails fixture setup. -HTTP_STUB = """-module(albedo_http). +HTTP_STUB = """-module(albedo_httpc). -export([get/4, request/6, request/7]). get(U, H, T, C) -> request(get, U, H, none, T, C). request(M, U, H, B, T, C) -> request(M, U, H, B, T, C, true). @@ -33,7 +36,7 @@ request(_, _, _, _, _, _, _) -> {error, offline_fixture}. """ -# The streaming transport's routing seam, `destination` in transport.gleam, +# The streaming client's routing seam, `destination` in albedo_http.gleam, # as its generated Erlang: the identity on its first argument. SEAM = ( "[{function, _, destination, 2, Clauses}] = [F || {function, _, destination, 2, _} = F <- Forms], " @@ -59,7 +62,7 @@ def compile_offline(ebin: Path, source: Path, home: Path, target: str) -> None: ) # Rewrite the build's generated Erlang for the transport, read back from # its debug info, so only `destination` differs from production. - built = ROOT / f"build/dev/erlang/albedo/ebin/{TRANSPORT}.beam" + built = ROOT / f"build/dev/erlang/{APPLICATIONS[TRANSPORT]}/ebin/{TRANSPORT}.beam" patch = f""" {{ok, {{Module, [{{debug_info, {{debug_info_v1, Backend, Data}}}}]}}}} = beam_lib:chunks({chars(str(built))}, [debug_info]), @@ -82,7 +85,7 @@ def compile_offline(ebin: Path, source: Path, home: Path, target: str) -> None: if patched.returncode != 0: raise AssertionError(patched.stderr or patched.stdout) source.mkdir() - original = (ROOT / "src/albedo/harness/sdk/albedo_http.erl").read_text() + original = (ROOT / "src/albedo/harness/sdk/albedo_httpc.erl").read_text() def exports(text: str) -> set[str]: return set( @@ -93,7 +96,7 @@ def compile_offline(ebin: Path, source: Path, home: Path, target: str) -> None: if exports(original) != exports(HTTP_STUB): raise AssertionError("non-streaming HTTP exports changed") - (source / "albedo_http.erl").write_text(HTTP_STUB) + (source / f"{HTTPC}.erl").write_text(HTTP_STUB) subprocess.run( [ "erlc", @@ -114,16 +117,21 @@ def prepare(app: Albedo, provider: Provider) -> None: if app.daemon.concurrent or app.daemon.booted: raise AssertionError("Antigravity fixture requires a fresh exclusive daemon") original = Path(app.env["ALBEDO_DAEMON"]).parent - for module in [TRANSPORT, "albedo_http"]: - built = ROOT / f"build/dev/erlang/albedo/ebin/{module}.beam" - if (original / f"albedo/ebin/{module}.beam").read_bytes() != built.read_bytes(): + for module, application in APPLICATIONS.items(): + built = ROOT / f"build/dev/erlang/{application}/ebin/{module}.beam" + if ( + original / f"{application}/ebin/{module}.beam" + ).read_bytes() != built.read_bytes(): raise AssertionError("snapshot differs from the current daemon build") snapshot = app.root / "antigravity-daemon" shutil.copytree(original, snapshot) + for module, application in APPLICATIONS.items(): + directory = snapshot / application / "ebin" + directory.chmod(directory.stat().st_mode | 0o200) + (directory / f"{module}.beam").unlink() + # Every replacement goes in albedo's ebin, which the boot code path holds + # beside albedo_http's. ebin = snapshot / "albedo/ebin" - ebin.chmod(ebin.stat().st_mode | 0o200) - for module in [TRANSPORT, "albedo_http"]: - (ebin / f"{module}.beam").unlink() (app.home / ".antigravity-offline").write_text("offline fixture\n") compile_offline(ebin, app.root / "offline-source", app.home, provider.url) subprocess.run( diff --git a/test/e2e/areas.toml b/test/e2e/areas.toml index a08a31e16..121b825c2 100644 --- a/test/e2e/areas.toml +++ b/test/e2e/areas.toml @@ -3,7 +3,8 @@ [areas] "test/e2e/network_support.py" = ["network_test.py", "discord_test.py"] "src/albedo/harness/sdk/network*.gleam" = ["network_test.py", "discord_test.py"] -"src/albedo/openai_api/proxy.gleam" = ["network_test.py"] +"packages/albedo_http/src/albedo_http/proxy.gleam" = ["network_test.py"] +"packages/albedo_http/src/albedo_http/route.gleam" = ["network_test.py"] "priv/python/albedo_plugins/proxy.py" = ["discord_test.py", "browser_test.py"] "src/albedo/transfer/**" = [ "transfer_test.py", @@ -460,50 +461,18 @@ "context_test.py", "prompt_test.py", ] -"src/albedo/openai_api/albedo_openai_transport.erl" = [ - "antigravity_test.py", - "provider_protocols_test.py", - "integration_test.py", - "context_test.py", - "prompt_test.py", -] -"src/albedo/openai_api/transport.gleam" = [ +# The streaming client every provider request goes through. +"packages/albedo_http/**" = [ "antigravity_test.py", "provider_protocols_test.py", "integration_test.py", "context_test.py", "prompt_test.py", ] +# The event-stream parser of the OpenAI-compatible wires and MCP over HTTP. +"packages/albedo_sse/**" = ["provider_protocols_test.py", "mcp_http_test.py"] "src/albedo/openai_api/degenerate.gleam" = ["python_test.py"] -"src/albedo/openai_api/pool.gleam" = [ - "antigravity_test.py", - "provider_protocols_test.py", - "integration_test.py", - "context_test.py", - "prompt_test.py", -] -"src/albedo/openai_api/framing.gleam" = [ - "antigravity_test.py", - "provider_protocols_test.py", - "integration_test.py", - "context_test.py", - "prompt_test.py", -] -"src/albedo/openai_api/socket.gleam" = [ - "antigravity_test.py", - "provider_protocols_test.py", - "integration_test.py", - "context_test.py", - "prompt_test.py", -] -"src/albedo/openai_api/connect.gleam" = [ - "antigravity_test.py", - "provider_protocols_test.py", - "integration_test.py", - "context_test.py", - "prompt_test.py", -] -"src/albedo/harness/sdk/albedo_http.erl" = [ +"src/albedo/harness/sdk/albedo_httpc.erl" = [ "anthropic_api_test.py", "antigravity_test.py", "integration_test.py", diff --git a/test/harness/albedo_httpc_dual_stack_test.erl b/test/harness/albedo_httpc_dual_stack_test.erl new file mode 100644 index 000000000..1d51e43eb --- /dev/null +++ b/test/harness/albedo_httpc_dual_stack_test.erl @@ -0,0 +1,83 @@ +%% A host that publishes one address family, or a network that resolves one, +%% must still connect. E2E cannot control name resolution, so this registers +%% names with only an IPv4 or IPv6 address and checks that the httpc front +%% door in albedo_httpc.erl reaches the host over whichever family answers. +%% albedo_http's own tests cover the streaming client. +-module(albedo_httpc_dual_stack_test). +-include_lib("eunit/include/eunit.hrl"). + +-define(V4, {127, 0, 0, 1}). +-define(V6, {0, 0, 0, 0, 0, 0, 0, 1}). + +only_ipv6_name_reaches_httpc_front_door_test() -> + with_listener(?V6, fun(Port) -> + with_hosts([{?V6, "httpc-v6.dual-stack.test"}], fun() -> + URL = iolist_to_binary(io_lib:format("http://httpc-v6.dual-stack.test:~B/", [Port])), + ?assertMatch( + {ok, {200, _, <<"ok">>}}, albedo_httpc:request(get, URL, [], none, 3000, 3000) + ) + end) + end). + +only_ipv4_name_reaches_httpc_front_door_test() -> + with_listener(?V4, fun(Port) -> + with_hosts([{?V4, "httpc-v4.dual-stack.test"}], fun() -> + URL = iolist_to_binary(io_lib:format("http://httpc-v4.dual-stack.test:~B/", [Port])), + ?assertMatch( + {ok, {200, _, <<"ok">>}}, albedo_httpc:request(get, URL, [], none, 3000, 3000) + ) + end) + end). + +%% A one-shot HTTP answer on the loopback address of one family. +with_listener(Address, Run) -> + case + gen_tcp:listen(0, [ + binary, {ip, Address}, {active, false}, {reuseaddr, true}, inet_family(Address) + ]) + of + {ok, Listen} -> + {ok, Port} = inet:port(Listen), + Server = spawn_link(fun() -> serve(Listen) end), + try + Run(Port) + after + unlink(Server), + exit(Server, kill), + gen_tcp:close(Listen) + end; + {error, _} -> + %% No loopback in this family on this machine: nothing to test. + ok + end. + +inet_family(Address) when tuple_size(Address) =:= 4 -> inet; +inet_family(_) -> inet6. + +serve(Listen) -> + case gen_tcp:accept(Listen) of + {ok, Socket} -> + {ok, _} = gen_tcp:recv(Socket, 0, 3000), + ok = gen_tcp:send( + Socket, + <<"HTTP/1.1 200 OK\r\ncontent-length: 2\r\nconnection: close\r\n\r\nok">> + ), + gen_tcp:close(Socket), + serve(Listen); + {error, _} -> + ok + end. + +%% Names resolve from the in-memory host table for the test's duration. +with_hosts(Hosts, Run) -> + Previous = inet_db:res_option(lookup), + PreviousHosts = [{Address, Names} || {host, Address, Names} <- inet_db:get_rc()], + inet_db:set_lookup([file | Previous]), + [ok = inet_db:add_host(Address, [Name]) || {Address, Name} <- Hosts], + try + Run() + after + [inet_db:del_host(Address) || {Address, _} <- Hosts], + [inet_db:add_host(Address, Names) || {Address, Names} <- PreviousHosts], + inet_db:set_lookup(Previous) + end. diff --git a/test/harness/antigravity_offline_test.py b/test/harness/antigravity_offline_test.py index 4a543091d..5eaccf448 100644 --- a/test/harness/antigravity_offline_test.py +++ b/test/harness/antigravity_offline_test.py @@ -44,7 +44,7 @@ class AntigravityOfflineTests(unittest.TestCase): probe = f""" URL = {literal(INFERENCE)}, Target = {literal(target)}, Home = {literal(str(home))}, Good = [{{<<"authorization">>, <<"Bearer fixture-antigravity">>}}], - Options = 'albedo@openai_api@transport':options(), + Options = albedo_http:options(), true = os:putenv("ALBEDO_HOME", binary_to_list(Home)), Expected = <>, Expected = albedo_antigravity_offline:route(URL, Good, Target, Home), @@ -52,11 +52,11 @@ class AntigravityOfflineTests(unittest.TestCase): Duplicate = Good ++ Wrong, lists:foreach(fun(Headers) -> <<>> = albedo_antigravity_offline:route(URL, Headers, Target, Home), - {{error, invalid_url}} = 'albedo@openai_api@transport':open(Options, URL, Headers, <<>>, 100) + {{error, invalid_url}} = albedo_http:open(Options, URL, Headers, <<>>, 100) end, [[], Wrong, Duplicate]), - {{error, invalid_headers}} = 'albedo@openai_api@transport':open(Options, URL, + {{error, invalid_headers}} = albedo_http:open(Options, URL, [{{<<"x-test">>, <<"bad", 13, 10, "header">>}} | Good], <<>>, 100), - {{error, invalid_url}} = 'albedo@openai_api@transport':open(Options, <<"https://example.invalid/">>, Good, <<>>, 100), + {{error, invalid_url}} = albedo_http:open(Options, <<"https://example.invalid/">>, Good, <<>>, 100), lists:foreach(fun(Bad) -> <<>> = albedo_antigravity_offline:route(URL, Good, Bad, Home) end, [<<"https://127.0.0.1:80/t/1">>, <<"http://localhost:80/t/1">>, @@ -68,10 +68,10 @@ class AntigravityOfflineTests(unittest.TestCase): true = os:putenv("ALBEDO_HOME", binary_to_list(Home)), ok = file:delete(filename:join(binary_to_list(Home), ".antigravity-offline")), <<>> = albedo_antigravity_offline:route(URL, Good, Target, Home), - {{error, offline_fixture}} = albedo_http:request(get, URL, [], none, 100, 100), - {{error, offline_fixture}} = albedo_http:request(head, URL, [], none, 100, 100, false), - {{error, offline_fixture}} = albedo_http:request(post, URL, [], {{<<"application/json">>, <<"{{}}">>}}, 100, 100, true), - {{error, offline_fixture}} = albedo_http:get(URL, [], 100, 100), + {{error, offline_fixture}} = albedo_httpc:request(get, URL, [], none, 100, 100), + {{error, offline_fixture}} = albedo_httpc:request(head, URL, [], none, 100, 100, false), + {{error, offline_fixture}} = albedo_httpc:request(post, URL, [], {{<<"application/json">>, <<"{{}}">>}}, 100, 100, true), + {{error, offline_fixture}} = albedo_httpc:get(URL, [], 100, 100), halt(). """ result = subprocess.run( diff --git a/test/harness/claude_test.gleam b/test/harness/claude_test.gleam index 94672c646..4102a4e09 100644 --- a/test/harness/claude_test.gleam +++ b/test/harness/claude_test.gleam @@ -12,10 +12,9 @@ import albedo/harness/sdk/transcript import albedo/openai_api import albedo/openai_api/cost import albedo/openai_api/request -import albedo/openai_api/request_body import albedo/openai_api/stream as reducer -import albedo/openai_api/transport import albedo/openai_api/types +import albedo_http/body as request_body import gleam/bit_array import gleam/dict import gleam/dynamic.{type Dynamic} @@ -720,25 +719,10 @@ fn split_every(text: String, size: Int) -> List(String) { } } -type Fixture - -type ServerMode { - Stream -} - -@external(erlang, "albedo_openai_transport_test_server", "start") -fn start(mode: ServerMode) -> Fixture - -@external(erlang, "albedo_openai_transport_test_server", "url") -fn url(fixture: Fixture) -> String - -@external(erlang, "albedo_openai_transport_test_server", "await_body") -fn await_body(fixture: Fixture) -> BitArray - -@external(erlang, "albedo_openai_transport_test_server", "stop") -fn stop(fixture: Fixture) -> Nil - -pub fn claude_attested_body_streams_through_the_transport_test() -> Nil { +/// albedo_http's own tests show that a body goes out on the wire as its +/// materialized bytes; this checks that Claude's are attested over the whole +/// body, stored image included. +pub fn claude_attested_body_digests_the_whole_body_test() -> Nil { let image = stored_image( "image/png", @@ -760,15 +744,7 @@ pub fn claude_attested_body_streams_through_the_transport_test() -> Nil { ) let assert Ok(openai_api.Exchange(body: body, ..)) = wire.encode(no_files_home, subscription, limited(request)) - let fixture = start(Stream) - let assert Ok(connection) = - transport.open(transport.options(), url(fixture), [], body, 5000) - let received = await_body(fixture) - transport.close(connection) - stop(fixture) - let assert Ok(on_the_wire) = bit_array.to_string(received) - let assert Ok(materialized) = materialize(body) - assert on_the_wire == materialized + let assert Ok(on_the_wire) = materialize(body) assert string.contains(on_the_wire, png) let assert Ok(value) = json.parse(on_the_wire, decode.dynamic) let assert Ok([billing, _]) = diff --git a/test/harness/messages_cache_test.gleam b/test/harness/messages_cache_test.gleam index a9dee29d4..9f3ef9ad6 100644 --- a/test/harness/messages_cache_test.gleam +++ b/test/harness/messages_cache_test.gleam @@ -5,8 +5,8 @@ import albedo/harness/extensions/github_copilot/wire as copilot import albedo/harness/extensions/opencode_go/wire as opencode import albedo/openai_api -import albedo/openai_api/request_body import albedo/openai_api/types +import albedo_http/body as request_body import gleam/bit_array import gleam/dict import gleam/dynamic/decode diff --git a/test/harness/network_test.gleam b/test/harness/network_test.gleam index 7b5ad0df6..23aa9071c 100644 --- a/test/harness/network_test.gleam +++ b/test/harness/network_test.gleam @@ -1,6 +1,6 @@ import albedo/harness/sdk/network import albedo/harness/sdk/settings -import albedo/openai_api/route.{HttpConnect, Proxy, Socks5, Socks5h} +import albedo_http/route.{HttpConnect, Proxy, Socks5, Socks5h} import gleam/dynamic import gleam/list import gleam/result diff --git a/test/openai_api/albedo_stream_http_fixture.erl b/test/openai_api/albedo_stream_http_fixture.erl new file mode 100644 index 000000000..163286c07 --- /dev/null +++ b/test/openai_api/albedo_stream_http_fixture.erl @@ -0,0 +1,50 @@ +-module(albedo_stream_http_fixture). + +%% A loopback server for stream_http's own budgets: it answers one request +%% with an event stream that sends only SSE comments, every 50 ms, until the +%% client hangs up. +-export([start/0, url/1, stop/1]). + +start() -> + {ok, Listen} = gen_tcp:listen(0, [binary, {active, false}, {reuseaddr, true}]), + {ok, {_Address, Port}} = inet:sockname(Listen), + Pid = spawn(fun() -> serve(Listen) end), + ok = gen_tcp:controlling_process(Listen, Pid), + URL = iolist_to_binary(io_lib:format("http://127.0.0.1:~B/v1/responses", [Port])), + {fixture, Pid, URL}. + +url({fixture, _Pid, URL}) -> URL. + +stop({fixture, Pid, _URL}) -> + exit(Pid, shutdown), + nil. + +serve(Listen) -> + {ok, Socket} = gen_tcp:accept(Listen, 10000), + gen_tcp:close(Listen), + ok = read_head(Socket, <<>>), + ok = gen_tcp:send(Socket, << + "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n" + "transfer-encoding: chunked\r\n\r\n" + >>), + ping(Socket). + +%% The request's head; the requests sent here have empty bodies. +read_head(Socket, Read) -> + case binary:match(Read, <<"\r\n\r\n">>) of + {_, _} -> + ok; + nomatch -> + {ok, Bytes} = gen_tcp:recv(Socket, 0, 10000), + read_head(Socket, <>) + end. + +ping(Socket) -> + case gen_tcp:send(Socket, <<"8\r\n: ping\n\n\r\n">>) of + ok -> + receive + after 50 -> ping(Socket) + end; + {error, _} -> + gen_tcp:close(Socket) + end. diff --git a/test/openai_api/stream_http_test.gleam b/test/openai_api/stream_http_test.gleam new file mode 100644 index 000000000..bafd6bd0c --- /dev/null +++ b/test/openai_api/stream_http_test.gleam @@ -0,0 +1,89 @@ +//// stream_http's own budgets and refusals over a real socket. A first-event +//// deadline under keepalive comments, and a refusal before connecting, need +//// a server whose timing the fake E2E provider does not control. + +import albedo/harness/extensions/mcp/http as mcp_http +import albedo/openai_api +import albedo/openai_api/refusal +import albedo/openai_api/stream as reducer +import albedo/openai_api/stream_http +import albedo/openai_api/types +import albedo_http +import gleam/option.{None, Some} +import gleam/string_tree +import gleeunit/should + +type Fixture + +@external(erlang, "albedo_stream_http_fixture", "start") +fn start() -> Fixture + +@external(erlang, "albedo_stream_http_fixture", "url") +fn url(fixture: Fixture) -> String + +@external(erlang, "albedo_stream_http_fixture", "stop") +fn stop(fixture: Fixture) -> Nil + +/// Nothing listens on port 1, so reaching it would fail as a connection +/// error rather than the refusal of the headers. +const closed = "http://127.0.0.1:1/v1/responses" + +pub fn invalid_headers_are_nonretryable_for_streams_and_bodies_test() -> Nil { + let headers = [#("Authorization", "fixture-secret\r\nx-injected: yes")] + let expected = Error(types.InvalidRequest("invalid HTTP headers")) + openai_api.exchange( + openai_api.Exchange( + closed, + headers, + string_tree.new(), + timeout_ms: 1000, + first_event_timeout_ms: None, + max_event_bytes: 65_536, + require_event_stream: True, + refusal: refusal.openai, + ), + reducer.reducer(types.Responses), + fn(_) { types.Continue }, + ) + |> should.equal(expected) + stream_http.with_body( + stream_http.Exchange( + closed, + headers, + string_tree.new(), + 1000, + None, + 65_536, + refusal: refusal.openai, + ), + 65_536, + True, + fn(_) { types.Continue }, + fn(_) { Ok(Nil) }, + ) + |> should.equal(Error(types.InvalidRequest("invalid HTTP headers"))) + mcp_http.describe(albedo_http.InvalidHeaders) + |> should.equal("the MCP request headers are invalid") +} + +/// Keepalive comments carry no event, so they hold off the idle budget but +/// not the first-event deadline. +pub fn the_first_event_deadline_outlasts_keepalives_test() -> Nil { + let fixture = start() + openai_api.exchange( + openai_api.Exchange( + url(fixture), + [], + string_tree.new(), + timeout_ms: 2000, + first_event_timeout_ms: Some(300), + max_event_bytes: 65_536, + require_event_stream: True, + refusal: refusal.openai, + ), + reducer.reducer(types.Responses), + fn(_) { types.Continue }, + ) + |> should.equal(Error(types.Timeout(types.AwaitingFirstEvent, 300))) + stop(fixture) +} diff --git a/tools/lint/src/albedo_lint/registrations.gleam b/tools/lint/src/albedo_lint/registrations.gleam index bb79b2b29..82400695d 100644 --- a/tools/lint/src/albedo_lint/registrations.gleam +++ b/tools/lint/src/albedo_lint/registrations.gleam @@ -53,6 +53,8 @@ const memo = "packages/albedo_process/src/albedo_process/memo.gleam" const lock = "packages/albedo_process/src/albedo_process/lock.gleam" +const http_pool = "packages/albedo_http/src/albedo_http/pool.gleam" + /// Reviewed uses that hand out no daemon or extension behavior. pub const reviewed = [ Allowed( @@ -134,6 +136,18 @@ pub const reviewed = [ Lock, "a caller finds the lock owner, or starts it when there is none", ), + Allowed( + http_pool, + "gleam/erlang/process.register", + Cache, + "the connection pool registers as albedo_http_pool, so every request reuses one set of kept-alive connections", + ), + Allowed( + http_pool, + "gleam/erlang/process.named", + Cache, + "a request finds the connection pool, or starts it when there is none", + ), Allowed( clock, "persistent_term:get", -- knotmirror 0.0.1