diff --git a/apps/albedo/test/albedo/composition/albedo_mcp_client_test_support.erl b/apps/albedo/test/albedo/composition/albedo_mcp_client_test_support.erl deleted file mode 100644 index cc6763fc9..000000000 --- a/apps/albedo/test/albedo/composition/albedo_mcp_client_test_support.erl +++ /dev/null @@ -1,378 +0,0 @@ -%% Test support for MCP client lifecycle tests: builds client transports -%% for the fake stdio server and a minimal modern HTTP fake, and reports -%% real port and socket termination. --module(albedo_mcp_client_test_support). --export([ - stdio_transport/2, - file_exists/1, - wait_file/2, - port_count/1, - start_http_fake/0, - http_transport/1, - http_hold_calls/1, - http_await_held/2, - http_await_closed/2, - http_stop/1, - anonymous_workers/0 -]). - -stdio_transport(Mode, Delay) -> - Unique = - integer_to_list(erlang:system_time(nanosecond)) ++ "-" ++ - integer_to_list(erlang:unique_integer([positive])), - Dir = filename:join(os:getenv("TMPDIR", "/tmp"), "albedo-mcp-client-test-" ++ Unique), - ok = file:make_dir(Dir), - case Mode of - <<>> -> ok; - _ -> ok = file:write_file(Dir ++ "/mode", Mode) - end, - case Delay of - <<>> -> ok; - _ -> ok = file:write_file(Dir ++ "/delay", Delay) - end, - {ok, Cwd} = file:get_cwd(), - Script = filename:join([Cwd, "..", "..", "e2e", "fake_mcp_server.py"]), - Python = - case os:find_executable("python3") of - false -> "python3"; - Path -> Path - end, - Closed = Dir ++ "/closed", - PidFile = Dir ++ "/server-pid", - Env = [ - {"FAKE_MCP_CONTROL", Dir}, - {"FAKE_MCP_CLOSED", Closed}, - {"FAKE_MCP_PIDFILE", PidFile} - ], - Transport = {stdio, list_to_binary(Python), [list_to_binary(Script)], Env}, - {Transport, list_to_binary(Dir), list_to_binary(Closed), list_to_binary(PidFile)}. - -file_exists(Path) when is_binary(Path) -> - filelib:is_file(binary_to_list(Path)). - -wait_file(Path, TimeoutMs) -> - Deadline = erlang:monotonic_time(millisecond) + TimeoutMs, - wait_file_loop(Path, Deadline). - -wait_file_loop(Path, Deadline) -> - case file_exists(Path) of - true -> - true; - false -> - case erlang:monotonic_time(millisecond) < Deadline of - true -> - timer:sleep(5), - wait_file_loop(Path, Deadline); - false -> - false - end - end. - -port_count(Pid) -> - length([ - Port - || Port <- erlang:ports(), - case erlang:port_info(Port, connected) of - {connected, Pid} -> true; - _ -> false - end - ]). - -%% Minimal 2026-07-28 HTTP fake. The controller owns the listener state; -%% handlers ask it whether a tools/call should be held open. - -start_http_fake() -> - spawn(fun() -> - {ok, Listen} = gen_tcp:listen(0, [ - binary, - {packet, raw}, - {active, false}, - {reuseaddr, true}, - {ip, {127, 0, 0, 1}} - ]), - {ok, Port} = inet:port(Listen), - Controller = self(), - spawn_link(fun() -> accept_loop(Listen, Controller) end), - http_loop(#{ - port => Port, - hold => false, - held => 0, - closed => 0, - held_waiters => [], - closed_waiters => [] - }) - end). - -http_transport(Controller) -> - Ref = make_ref(), - Controller ! {http_call, self(), Ref, port}, - receive - {Ref, Port} -> ok - end, - Url = iolist_to_binary(io_lib:format("http://127.0.0.1:~p/mcp", [Port])), - {http, Url, [], none}. - -http_hold_calls(Controller) -> - Controller ! http_hold, - nil. - -http_await_held(Controller, TimeoutMs) -> - await_event(Controller, await_held, TimeoutMs). - -http_await_closed(Controller, TimeoutMs) -> - await_event(Controller, await_closed, TimeoutMs). - -await_event(Controller, Kind, TimeoutMs) -> - Ref = make_ref(), - Controller ! {Kind, self(), Ref}, - receive - {Ref, Value} -> Value - after TimeoutMs -> false - end. - -http_stop(Controller) -> - exit(Controller, kill), - nil. - -http_loop(State) -> - receive - http_hold -> - http_loop(State#{hold := true}); - http_hold_replies -> - http_loop(State#{hold := replies}); - {held, _Handler} -> - Waiters = maps:get(held_waiters, State), - [From ! {Ref, true} || {From, Ref} <- Waiters], - http_loop(State#{ - held := maps:get(held, State) + 1, - held_waiters := [] - }); - {closed, _Handler} -> - Waiters = maps:get(closed_waiters, State), - [From ! {Ref, true} || {From, Ref} <- Waiters], - http_loop(State#{ - closed := maps:get(closed, State) + 1, - closed_waiters := [] - }); - {http_call, From, Ref, port} -> - From ! {Ref, maps:get(port, State)}, - http_loop(State); - {should_hold, From, Ref, Body} -> - Hold = - case maps:get(hold, State) of - replies -> not maps:is_key(<<"method">>, json:decode(Body)); - true -> binary:match(Body, <<"tools/call">>) =/= nomatch; - false -> false - end, - From ! {Ref, Hold}, - http_loop(State); - {await_held, From, Ref} -> - case maps:get(held, State) > 0 of - true -> - From ! {Ref, true}, - http_loop(State); - false -> - http_loop(State#{ - held_waiters := - [{From, Ref} | maps:get(held_waiters, State)] - }) - end; - {await_closed, From, Ref} -> - case maps:get(closed, State) > 0 of - true -> - From ! {Ref, true}, - http_loop(State); - false -> - http_loop(State#{ - closed_waiters := - [{From, Ref} | maps:get(closed_waiters, State)] - }) - end - end. - -accept_loop(Listen, Controller) -> - case gen_tcp:accept(Listen) of - {ok, Socket} -> - spawn_link(fun() -> handle(Socket, Controller) end), - accept_loop(Listen, Controller); - {error, _} -> - ok - end. - -handle(Socket, Controller) -> - case read_request(Socket, <<>>) of - {ok, Body} -> - dispatch(Socket, Controller, Body); - {error, _} -> - Controller ! {closed, self()}, - gen_tcp:close(Socket) - end. - -dispatch(Socket, Controller, Body) -> - case binary:match(Body, <<"server/discover">>) of - {_, _} -> - #{<<"id">> := Id} = json:decode(Body), - Result = #{ - <<"resultType">> => <<"complete">>, - <<"supportedVersions">> => [<<"2026-07-28">>], - <<"capabilities">> => #{} - }, - respond(Socket, Id, Result); - nomatch -> - Ref = make_ref(), - Controller ! {should_hold, self(), Ref, Body}, - Hold = - receive - {Ref, Value} -> Value - end, - case Hold of - true -> - Controller ! {held, self()}, - case gen_tcp:recv(Socket, 0) of - {error, _} -> Controller ! {closed, self()} - end, - gen_tcp:close(Socket); - false -> - case json:decode(Body) of - #{<<"id">> := Id, <<"method">> := <<"ownership/ping">>} -> - respond_frames(Socket, [ - #{ - <<"jsonrpc">> => <<"2.0">>, - <<"id">> => <<"server-ping">>, - <<"method">> => <<"ping">> - }, - #{<<"jsonrpc">> => <<"2.0">>, <<"id">> => Id, <<"result">> => #{}} - ]); - #{<<"id">> := Id, <<"method">> := _} -> - respond(Socket, Id, #{<<"content">> => []}); - _ -> - gen_tcp:send( - Socket, <<"HTTP/1.1 202 Accepted\r\ncontent-length: 0\r\n\r\n">> - ), - gen_tcp:close(Socket) - end - end - end. - -respond(Socket, Id, Result) -> - respond_frames(Socket, #{<<"jsonrpc">> => <<"2.0">>, <<"id">> => Id, <<"result">> => Result}). - -respond_frames(Socket, Frames) -> - Body = iolist_to_binary(json:encode(Frames)), - Head = io_lib:format( - "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\n" - "content-length: ~p\r\n\r\n", - [byte_size(Body)] - ), - gen_tcp:send(Socket, [Head, Body]), - gen_tcp:close(Socket). - -read_request(Socket, Acc) -> - case binary:match(Acc, <<"\r\n\r\n">>) of - {At, 4} -> - Head = binary:part(Acc, 0, At), - Rest = binary:part(Acc, At + 4, byte_size(Acc) - At - 4), - Length = content_length(Head), - read_body(Socket, Rest, Length); - nomatch -> - case gen_tcp:recv(Socket, 0, 5000) of - {ok, Bytes} -> read_request(Socket, <>); - {error, Reason} -> {error, Reason} - end - end. - -read_body(_Socket, Body, Length) when byte_size(Body) >= Length -> - {ok, binary:part(Body, 0, Length)}; -read_body(Socket, Body, Length) -> - case gen_tcp:recv(Socket, 0, 5000) of - {ok, Bytes} -> read_body(Socket, <>, Length); - {error, Reason} -> {error, Reason} - end. - -content_length(Head) -> - Lines = binary:split(string:lowercase(Head), <<"\r\n">>, [global]), - case [V || <<"content-length:", V/binary>> <- Lines] of - [Value] -> binary_to_integer(string:trim(Value)); - _ -> 0 - end. - -%% Trace actual loop states, rather than depending on the private State tuple -%% layout. A completed POST's pid must no longer be retained anywhere in it. -anonymous_workers() -> - ClientModule = 'albedo_ext_mcp@client', - HttpModule = 'albedo_ext_mcp@http', - Fake = start_http_fake(), - {ok, Client} = ClientModule:start(http_transport(Fake), 5000, self()), - ClientPid = ClientModule:pid(Client), - erlang:trace_pattern({ClientModule, loop, 1}, true, [local]), - erlang:trace_pattern({HttpModule, post, 8}, true, [local]), - erlang:trace(ClientPid, true, [call, set_on_spawn, {tracer, self()}]), - try - lists:foreach( - fun(_) -> - {ok, _} = ClientModule:request(Client, <<"ownership/ping">>, <<"{}">>, 5000), - Worker = anonymous_post(HttpModule), - await_process(Worker), - Delivered = erlang:trace_delivered(ClientPid), - receive - {trace_delivered, ClientPid, Delivered} -> ok - end, - discard_states(ClientPid, ClientModule), - {ok, nil} = ClientModule:transfer(Client, self()), - await_retired(ClientPid, ClientModule, Worker) - end, - lists:seq(1, 3) - ), - Fake ! http_hold_replies, - {ok, _} = ClientModule:request(Client, <<"ownership/ping">>, <<"{}">>, 5000), - Active = anonymous_post(HttpModule), - true = http_await_held(Fake, 5000), - ClientModule:close(Client), - await_process(ClientPid), - await_process(Active), - true = http_await_closed(Fake, 5000), - true - after - try - ClientModule:close(Client) - catch - _:_ -> ok - end, - exit(ClientPid, kill), - await_process(ClientPid), - http_stop(Fake), - erlang:trace_pattern({ClientModule, loop, 1}, false, [local]), - erlang:trace_pattern({HttpModule, post, 8}, false, [local]) - end. - -anonymous_post(HttpModule) -> - receive - {trace, Worker, call, {HttpModule, post, [_, _, _, none | _]}} -> Worker - after 5000 -> error(no_anonymous_post) - end. - -await_process(Pid) -> - Monitor = monitor(process, Pid), - receive - {'DOWN', Monitor, process, Pid, _} -> ok - after 5000 -> error({process_survived, Pid}) - end. - -discard_states(Client, Module) -> - receive - {trace, Client, call, {Module, loop, [_]}} -> discard_states(Client, Module) - after 0 -> ok - end. - -await_retired(Client, Module, Worker) -> - receive - {trace, Client, call, {Module, loop, [State]}} -> - false = contains_pid(State, Worker) - after 5000 -> error(no_client_state) - end. - -contains_pid(Pid, Pid) -> true; -contains_pid(Value, Pid) when is_tuple(Value) -> contains_pid(tuple_to_list(Value), Pid); -contains_pid(Value, Pid) when is_map(Value) -> contains_pid(maps:to_list(Value), Pid); -contains_pid([Head | Tail], Pid) -> contains_pid(Head, Pid) orelse contains_pid(Tail, Pid); -contains_pid(_, _) -> false. diff --git a/apps/albedo/test/albedo/composition/mcp_client_lifecycle_test.gleam b/apps/albedo/test/albedo/composition/mcp_client_lifecycle_test.gleam index 8c61f7127..565cce280 100644 --- a/apps/albedo/test/albedo/composition/mcp_client_lifecycle_test.gleam +++ b/apps/albedo/test/albedo/composition/mcp_client_lifecycle_test.gleam @@ -3,43 +3,452 @@ //// client's stdio port, so these drive the real client against the fake //// stdio server and a minimal local HTTP fake. +import albedo/support/scratch +import albedo/support/tcp +import albedo_clock import albedo_ext_mcp/client +import albedo_file +import albedo_ports/subprocess +import albedo_protect +import gleam/bit_array import gleam/dynamic.{type Dynamic} +import gleam/dynamic/decode +import gleam/erlang/atom +import gleam/erlang/charlist.{type Charlist} +import gleam/erlang/port.{type Port} import gleam/erlang/process.{type Pid, type Subject} +import gleam/erlang/reference.{type Reference} +import gleam/int +import gleam/json +import gleam/list +import gleam/option.{None} +import gleam/result +import gleam/string import gleeunit/should -@external(erlang, "albedo_mcp_client_test_support", "stdio_transport") +/// The longest wait for an event a test expects. +const event_ms = 10_000 + +/// A transport for the fake stdio server in a fresh control directory, as +/// `#(transport, directory, closed marker, pid file)`. An empty `mode` or +/// `delay` leaves the server's default. fn stdio_transport( mode: String, delay: String, -) -> #(client.Transport, String, String, String) +) -> #(client.Transport, String, String, String) { + let dir = scratch.directory("albedo-mcp-client-test-") + case mode { + "" -> Nil + _ -> { + let _ = scratch.write(dir, "mode", mode) + Nil + } + } + case delay { + "" -> Nil + _ -> { + let _ = scratch.write(dir, "delay", delay) + Nil + } + } + let assert Ok(cwd) = get_cwd() + let script = + albedo_file.join(charlist.to_string(cwd), "../../e2e/fake_mcp_server.py") + let python = subprocess.on_path("python3") |> result.unwrap("python3") + let closed = dir <> "/closed" + let pid_file = dir <> "/server-pid" + let environment = + list.map( + [ + #("FAKE_MCP_CONTROL", dir), + #("FAKE_MCP_CLOSED", closed), + #("FAKE_MCP_PIDFILE", pid_file), + ], + fn(entry) { + #( + charlist.from_string(entry.0), + as_dynamic(charlist.from_string(entry.1)), + ) + }, + ) + #(client.Stdio(python, [script], environment), dir, closed, pid_file) +} + +fn file_exists(path: String) -> Bool { + is_file(path) +} + +/// Whether `path` exists within `timeout_ms`. +fn wait_file(path: String, timeout_ms: Int) -> Bool { + wait_file_until(path, albedo_clock.monotonic_ms() + timeout_ms) +} + +fn wait_file_until(path: String, deadline: Int) -> Bool { + case is_file(path), albedo_clock.monotonic_ms() < deadline { + True, _ -> True + False, True -> { + process.sleep(5) + wait_file_until(path, deadline) + } + False, False -> False + } +} + +/// The ports `pid` owns. +fn port_count(pid: Pid) -> Int { + let owner = as_dynamic(#(atom.create("connected"), pid)) + list.count(ports(), fn(port) { + port_info(port, atom.create("connected")) == owner + }) +} + +/// A minimal 2026-07-28 HTTP MCP server. Its controller counts held and +/// closed requests; each connection's handler asks it whether to hold a +/// request open. +type HttpFake { + HttpFake(pid: Pid, controller: Subject(FakeMessage)) +} + +type HoldMode { + HoldNothing + /// Hold each `tools/call` open. + HoldCalls + /// Hold each POST that is a reply rather than a request. + HoldReplies +} + +type FakeMessage { + SetHold(HoldMode) + HeldOne + ClosedOne + AskPort(reply: Subject(Int)) + ShouldHold(body: String, reply: Subject(Bool)) + AwaitHeld(reply: Subject(Bool)) + AwaitClosed(reply: Subject(Bool)) +} + +type FakeState { + FakeState( + port: Int, + hold: HoldMode, + held: Int, + closed: Int, + held_waiters: List(Subject(Bool)), + closed_waiters: List(Subject(Bool)), + ) +} + +fn start_http_fake() -> HttpFake { + let ready = process.new_subject() + let pid = + process.spawn_unlinked(fn() { + let assert Ok(listener) = + tcp.listen(0, [ + tcp.Binary, + tcp.Packet(tcp.Raw), + tcp.Active(False), + tcp.Reuseaddr(True), + tcp.Ip(tcp.loopback), + ]) + let controller = process.new_subject() + process.send(ready, controller) + process.spawn(fn() { accept_loop(listener, controller) }) + http_loop( + controller, + FakeState(tcp.port(listener), HoldNothing, 0, 0, [], []), + ) + }) + let assert Ok(controller) = process.receive(ready, event_ms) + HttpFake(pid, controller) +} -@external(erlang, "albedo_mcp_client_test_support", "file_exists") -fn file_exists(path: String) -> Bool +fn http_transport(fake: HttpFake) -> client.Transport { + let port = process.call(fake.controller, event_ms, AskPort) + client.Http("http://127.0.0.1:" <> int.to_string(port) <> "/mcp", [], None) +} -@external(erlang, "albedo_mcp_client_test_support", "wait_file") -fn wait_file(path: String, timeout_ms: Int) -> Bool +fn http_hold_calls(fake: HttpFake) -> Nil { + process.send(fake.controller, SetHold(HoldCalls)) +} -@external(erlang, "albedo_mcp_client_test_support", "port_count") -fn port_count(pid: Pid) -> Int +/// Whether the fake holds a request open within `timeout_ms`. +fn http_await_held(fake: HttpFake, timeout_ms: Int) -> Bool { + await_event(fake, AwaitHeld, timeout_ms) +} -@external(erlang, "albedo_mcp_client_test_support", "start_http_fake") -fn start_http_fake() -> Pid +/// Whether a held request's connection closes within `timeout_ms`. +fn http_await_closed(fake: HttpFake, timeout_ms: Int) -> Bool { + await_event(fake, AwaitClosed, timeout_ms) +} -@external(erlang, "albedo_mcp_client_test_support", "http_transport") -fn http_transport(fake: Pid) -> client.Transport +fn await_event( + fake: HttpFake, + ask: fn(Subject(Bool)) -> FakeMessage, + timeout_ms: Int, +) -> Bool { + let reply = process.new_subject() + process.send(fake.controller, ask(reply)) + process.receive(reply, timeout_ms) |> result.unwrap(False) +} -@external(erlang, "albedo_mcp_client_test_support", "http_hold_calls") -fn http_hold_calls(fake: Pid) -> Nil +fn http_stop(fake: HttpFake) -> Nil { + process.kill(fake.pid) +} + +fn http_loop(controller: Subject(FakeMessage), state: FakeState) -> Nil { + let state = case process.receive_forever(controller) { + SetHold(hold) -> FakeState(..state, hold:) + HeldOne -> { + list.each(state.held_waiters, process.send(_, True)) + FakeState(..state, held: state.held + 1, held_waiters: []) + } + ClosedOne -> { + list.each(state.closed_waiters, process.send(_, True)) + FakeState(..state, closed: state.closed + 1, closed_waiters: []) + } + AskPort(reply) -> { + process.send(reply, state.port) + state + } + ShouldHold(body, reply) -> { + process.send(reply, case state.hold { + HoldReplies -> + result.is_error(json.parse( + body, + decode.at(["method"], decode.dynamic), + )) + HoldCalls -> string.contains(body, "tools/call") + HoldNothing -> False + }) + state + } + AwaitHeld(reply) -> + case state.held > 0 { + True -> { + process.send(reply, True) + state + } + False -> FakeState(..state, held_waiters: [reply, ..state.held_waiters]) + } + AwaitClosed(reply) -> + case state.closed > 0 { + True -> { + process.send(reply, True) + state + } + False -> + FakeState(..state, closed_waiters: [reply, ..state.closed_waiters]) + } + } + http_loop(controller, state) +} -@external(erlang, "albedo_mcp_client_test_support", "http_await_held") -fn http_await_held(fake: Pid, timeout_ms: Int) -> Bool +fn accept_loop(listener: tcp.Socket, controller: Subject(FakeMessage)) -> Nil { + case tcp.accept(listener) { + Ok(socket) -> { + process.spawn(fn() { handle(socket, controller) }) + accept_loop(listener, controller) + } + Error(_) -> Nil + } +} -@external(erlang, "albedo_mcp_client_test_support", "http_await_closed") -fn http_await_closed(fake: Pid, timeout_ms: Int) -> Bool +fn handle(socket: tcp.Socket, controller: Subject(FakeMessage)) -> Nil { + case read_request(socket, <<>>) { + Ok(body) -> { + let assert Ok(body) = bit_array.to_string(body) + dispatch(socket, controller, body) + } + Error(_) -> { + process.send(controller, ClosedOne) + let _ = tcp.close(socket) + Nil + } + } +} -@external(erlang, "albedo_mcp_client_test_support", "http_stop") -fn http_stop(fake: Pid) -> Nil +fn dispatch( + socket: tcp.Socket, + controller: Subject(FakeMessage), + body: String, +) -> Nil { + case string.contains(body, "server/discover") { + True -> { + let assert Ok(id) = json.parse(body, decode.at(["id"], json_id())) + respond( + socket, + id, + json.object([ + #("resultType", json.string("complete")), + #("supportedVersions", json.array(["2026-07-28"], json.string)), + #("capabilities", json.object([])), + ]), + ) + } + False -> + case process.call(controller, event_ms, ShouldHold(body, _)) { + True -> { + process.send(controller, HeldOne) + let assert Error(_) = recv_forever(socket, 0) + process.send(controller, ClosedOne) + let _ = tcp.close(socket) + Nil + } + False -> + case + json.parse(body, { + use id <- decode.field("id", json_id()) + use method <- decode.field("method", decode.string) + decode.success(#(id, method)) + }) + { + Ok(#(id, "ownership/ping")) -> + respond_frames( + socket, + json.preprocessed_array([ + json.object([ + #("jsonrpc", json.string("2.0")), + #("id", json.string("server-ping")), + #("method", json.string("ping")), + ]), + json.object([ + #("jsonrpc", json.string("2.0")), + #("id", id), + #("result", json.object([])), + ]), + ]), + ) + Ok(#(id, _)) -> + respond( + socket, + id, + json.object([#("content", json.preprocessed_array([]))]), + ) + Error(_) -> { + let _ = + tcp.send(socket, << + "HTTP/1.1 202 Accepted\r\ncontent-length: 0\r\n\r\n", + >>) + let _ = tcp.close(socket) + Nil + } + } + } + } +} + +/// A JSON-RPC id, a number or a string, as JSON again. +fn json_id() -> decode.Decoder(json.Json) { + decode.one_of(decode.int |> decode.map(json.int), [ + decode.string |> decode.map(json.string), + ]) +} + +fn respond(socket: tcp.Socket, id: json.Json, result: json.Json) -> Nil { + respond_frames( + socket, + json.object([ + #("jsonrpc", json.string("2.0")), + #("id", id), + #("result", result), + ]), + ) +} + +fn respond_frames(socket: tcp.Socket, frames: json.Json) -> Nil { + let body = json.to_string(frames) + let _ = + tcp.send( + socket, + bit_array.from_string( + "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: " + <> int.to_string(string.byte_size(body)) + <> "\r\n\r\n" + <> body, + ), + ) + let _ = tcp.close(socket) + Nil +} + +/// The body of the next request on `socket`. +fn read_request( + socket: tcp.Socket, + read: BitArray, +) -> Result(BitArray, Dynamic) { + case head_end(read, 0) { + Ok(at) -> { + let assert Ok(head) = bit_array.slice(read, 0, at) + let assert Ok(head) = bit_array.to_string(head) + let size = bit_array.byte_size(read) - at - 4 + let assert Ok(rest) = bit_array.slice(read, at + 4, size) + read_body(socket, rest, content_length(head)) + } + Error(Nil) -> { + use bytes <- result.try(tcp.recv(socket, 0, event_ms)) + read_request(socket, <>) + } + } +} + +fn read_body( + socket: tcp.Socket, + body: BitArray, + length: Int, +) -> Result(BitArray, Dynamic) { + case bit_array.byte_size(body) >= length { + True -> { + let assert Ok(body) = bit_array.slice(body, 0, length) + Ok(body) + } + False -> { + use bytes <- result.try(tcp.recv(socket, 0, event_ms)) + read_body(socket, <>, length) + } + } +} + +fn head_end(bytes: BitArray, from: Int) -> Result(Int, Nil) { + case bit_array.slice(bytes, from, 4) { + Ok(<<"\r\n\r\n">>) -> Ok(from) + Ok(_) -> head_end(bytes, from + 1) + Error(Nil) -> Error(Nil) + } +} + +fn content_length(head: String) -> Int { + let lengths = + string.split(string.lowercase(head), "\r\n") + |> list.filter_map(fn(line) { + case line { + "content-length:" <> value -> int.parse(string.trim(value)) + _ -> Error(Nil) + } + }) + case lengths { + [length] -> length + _ -> 0 + } +} + +@external(erlang, "file", "get_cwd") +fn get_cwd() -> Result(Charlist, Dynamic) + +@external(erlang, "filelib", "is_file") +fn is_file(path: String) -> Bool + +@external(erlang, "erlang", "ports") +fn ports() -> List(Port) + +@external(erlang, "erlang", "port_info") +fn port_info(port: Port, item: atom.Atom) -> Dynamic + +/// Waits for bytes or the socket's close, however long that takes. +@external(erlang, "gen_tcp", "recv") +fn recv_forever(socket: tcp.Socket, length: Int) -> Result(BitArray, Dynamic) + +@external(erlang, "gleam@function", "identity") +fn as_dynamic(value: a) -> Dynamic fn gate_owner() -> #(Pid, Subject(Nil)) { let ready = process.new_subject() @@ -50,7 +459,7 @@ fn gate_owner() -> #(Pid, Subject(Nil)) { let _ = process.receive_forever(gate) Nil }) - let assert Ok(gate) = process.receive(ready, 5000) + let assert Ok(gate) = process.receive(ready, event_ms) #(owner, gate) } @@ -59,7 +468,7 @@ fn await_down(pid: Pid) -> Nil { let assert Ok(Nil) = process.new_selector() |> process.select_specific_monitor(monitor, fn(_) { Nil }) - |> process.selector_receive(5000) + |> process.selector_receive(event_ms) Nil } @@ -90,12 +499,12 @@ pub fn owner_killed_before_start_completes_test() -> Nil { process.send(ready, Nil) process.send(results, client.start(transport, 10_000, owner)) }) - let assert Ok(Nil) = receive_within(ready, 5000) - wait_file(pid_file, 5000) |> should.be_true + let assert Ok(Nil) = receive_within(ready, event_ms) + wait_file(pid_file, event_ms) |> should.be_true process.kill(owner) await_down(owner) - let assert Ok(Error(_)) = receive_within(results, 8000) - wait_file(closed, 8000) |> should.be_true + let assert Ok(Error(_)) = receive_within(results, event_ms) + wait_file(closed, event_ms) |> should.be_true } pub fn owner_exits_normally_after_start_closes_port_test() -> Nil { @@ -108,7 +517,7 @@ pub fn owner_exits_normally_after_start_closes_port_test() -> Nil { await_down(owner) await_down(client_pid) port_count(client_pid) |> should.equal(0) - wait_file(closed, 5000) |> should.be_true + wait_file(closed, event_ms) |> should.be_true } pub fn owner_killed_after_start_closes_port_test() -> Nil { @@ -121,7 +530,7 @@ pub fn owner_killed_after_start_closes_port_test() -> Nil { await_down(owner) await_down(client_pid) port_count(client_pid) |> should.equal(0) - wait_file(closed, 5000) |> should.be_true + wait_file(closed, event_ms) |> should.be_true } pub fn transfer_then_old_owner_exits_client_survives_test() -> Nil { @@ -176,7 +585,7 @@ pub fn pending_request_fails_on_owner_death_test() -> Nil { ) }) process.kill(owner) - let assert Ok(Error(client.Lost(_))) = receive_within(results, 8000) + let assert Ok(Error(client.Lost(_))) = receive_within(results, event_ms) await_down(client.pid(started)) } @@ -197,17 +606,187 @@ pub fn http_workers_die_with_client_test() -> Nil { ), ) }) - http_await_held(fake, 8000) |> should.be_true + http_await_held(fake, event_ms) |> should.be_true process.kill(owner) - let assert Ok(Error(client.Lost(_))) = receive_within(results, 8000) + let assert Ok(Error(client.Lost(_))) = receive_within(results, event_ms) await_down(client.pid(started)) - http_await_closed(fake, 8000) |> should.be_true + http_await_closed(fake, event_ms) |> should.be_true http_stop(fake) } -@external(erlang, "albedo_mcp_client_test_support", "anonymous_workers") -fn anonymous_workers() -> Bool - +/// A completed POST's worker must no longer be retained anywhere in the +/// client's state, and closing the client ends a POST still waiting. The +/// test traces the client's loop states rather than depending on the +/// private State layout. pub fn completed_http_replies_retire_workers_and_pending_replies_close_test() -> Nil { - anonymous_workers() |> should.be_true + let fake = start_http_fake() + let assert Ok(started) = + client.start(http_transport(fake), 5000, process.self()) + let client_pid = client.pid(started) + let client_module = atom.create("albedo_ext_mcp@client") + let http_module = atom.create("albedo_ext_mcp@http") + let loop = #(client_module, atom.create("loop"), 1) + let post = #(http_module, atom.create("post"), 8) + let _ = trace_pattern(loop, True, [Local]) + let _ = trace_pattern(post, True, [Local]) + let _ = trace(client_pid, True, [Call, SetOnSpawn, Tracer(process.self())]) + use <- albedo_protect.finally(after: fn() { + let _ = albedo_protect.rescue(fn() { client.close(started) }) + process.kill(client_pid) + await_down(client_pid) + http_stop(fake) + let _ = trace_pattern(loop, False, [Local]) + let _ = trace_pattern(post, False, [Local]) + Nil + }) + list.each([1, 2, 3], fn(_) { + let assert Ok(_) = client.request(started, "ownership/ping", "{}", 5000) + let worker = anonymous_post(http_module) + await_down(worker) + await_trace_delivered(client_pid) + discard_traces() + assert client.transfer(started, process.self()) == Ok(Nil) + let state = next_loop_state(client_pid, client_module) + assert !contains(state, as_dynamic(worker)) + as "the client retained a completed POST's worker" + }) + process.send(fake.controller, SetHold(HoldReplies)) + let assert Ok(_) = client.request(started, "ownership/ping", "{}", 5000) + let active = anonymous_post(http_module) + assert http_await_held(fake, event_ms) + client.close(started) + await_down(client_pid) + await_down(active) + assert http_await_closed(fake, event_ms) +} + +type PatternFlag { + Local } + +/// `erlang:trace` flags, as OTP spells them. +type TraceFlag { + Call + SetOnSpawn + Tracer(Pid) +} + +/// The process whose next traced `http.post` call carries no request id. +fn anonymous_post(http_module: atom.Atom) -> Pid { + let wanted_module = atom.to_dynamic(http_module) + let no_id = atom.to_dynamic(atom.create("none")) + let traced = + process.new_selector() + |> process.select_record(atom.create("trace"), 3, fn(message) { + decode.run(message, { + use pid <- decode.field(1, decode.dynamic) + use module <- decode.subfield([3, 0], decode.dynamic) + use id <- decode.subfield([3, 2], decode.at([3], decode.dynamic)) + decode.success(#(pid, module, id)) + }) + }) + |> process.selector_receive(event_ms) + case traced { + Ok(Ok(#(pid, module, id))) if module == wanted_module && id == no_id -> + as_pid(pid) + Ok(_) -> anonymous_post(http_module) + Error(Nil) -> panic as "no anonymous POST was traced" + } +} + +fn await_trace_delivered(pid: Pid) -> Nil { + let reference = trace_delivered(pid) + let delivered = + process.new_selector() + |> process.select_record(atom.create("trace_delivered"), 2, fn(message) { + decode.run(message, decode.at([2], decode.dynamic)) + == Ok(as_dynamic(reference)) + }) + |> process.selector_receive(event_ms) + case delivered { + Ok(True) -> Nil + Ok(False) -> await_trace_delivered(pid) + Error(Nil) -> panic as "the trace was not delivered" + } +} + +/// Drops the traces already delivered. +fn discard_traces() -> Nil { + case + process.new_selector() + |> process.select_record(atom.create("trace"), 3, fn(_) { Nil }) + |> process.selector_receive(0) + { + Ok(Nil) -> discard_traces() + Error(Nil) -> Nil + } +} + +/// The state the client's loop is next called with. +fn next_loop_state(client_pid: Pid, client_module: atom.Atom) -> Dynamic { + let wanted_pid = as_dynamic(client_pid) + let wanted_module = atom.to_dynamic(client_module) + let traced = + process.new_selector() + |> process.select_record(atom.create("trace"), 3, fn(message) { + decode.run(message, { + use pid <- decode.field(1, decode.dynamic) + use module <- decode.subfield([3, 0], decode.dynamic) + use args <- decode.subfield([3, 2], decode.list(decode.dynamic)) + decode.success(#(pid, module, args)) + }) + }) + |> process.selector_receive(event_ms) + case traced { + Ok(Ok(#(pid, module, [state]))) + if pid == wanted_pid && module == wanted_module + -> state + Ok(_) -> next_loop_state(client_pid, client_module) + Error(Nil) -> panic as "the client's loop did not run" + } +} + +/// Whether `target` appears anywhere in `value`'s tuples, maps and lists. +fn contains(value: Dynamic, target: Dynamic) -> Bool { + case value == target { + True -> True + False -> + case is_tuple(value), is_map(value) { + True, _ -> list.any(tuple_to_list(value), contains(_, target)) + _, True -> list.any(maps_to_list(value), contains(_, target)) + False, False -> + case decode.run(value, decode.list(decode.dynamic)) { + Ok(items) -> list.any(items, contains(_, target)) + Error(_) -> False + } + } + } +} + +@external(erlang, "erlang", "trace_pattern") +fn trace_pattern( + function: #(atom.Atom, atom.Atom, Int), + enable: Bool, + flags: List(PatternFlag), +) -> Int + +@external(erlang, "erlang", "trace") +fn trace(pid: Pid, enable: Bool, flags: List(TraceFlag)) -> Int + +@external(erlang, "erlang", "trace_delivered") +fn trace_delivered(pid: Pid) -> Reference + +@external(erlang, "erlang", "is_tuple") +fn is_tuple(value: Dynamic) -> Bool + +@external(erlang, "erlang", "is_map") +fn is_map(value: Dynamic) -> Bool + +@external(erlang, "erlang", "tuple_to_list") +fn tuple_to_list(value: Dynamic) -> List(Dynamic) + +@external(erlang, "maps", "to_list") +fn maps_to_list(value: Dynamic) -> List(Dynamic) + +@external(erlang, "gleam@function", "identity") +fn as_pid(value: Dynamic) -> Pid