MARY.WIN

RUSTY — DESIGN PATTERNS — 11

Adapter:
one deliver, a webhook and a command-line tool behind it

Pattern 11 of 12 · In the life of one value: wrapped for a stranger.
Part of Rust design patterns.

Learning question: When your code needs one small answer and two outside tools each give a different one, where do their calls and their failures get translated?

This article is the exception in the set. The other eleven each read one piece of existing open-source Rust. This one reads code written for this course, examples/cp11-adapters/, and it reads two adapters, where the series rule is one example per pattern. Nothing in src/lib.rs is from a published project. Only the two things being wrapped are: the ureq HTTP client at version 2.12.1, and std::process::Command.

A program has finished its work and holds a report. Something outside the program has to be told. This article reads a trait with one method, the two types that implement it, and the one error type that both of them answer in.

Scope. We read examples/cp11-adapters/src/lib.rs (174 lines) and examples/cp11-adapters/before/src/lib.rs (32 lines) [C1, C2]. For the two wrapped tools we read ureq 2.12.1 as Cargo unpacked it, and library/std/src/process.rs from the rust-src component of Rust 1.97.0 [U1, T1]. We do not cover async HTTP, retries, TLS configuration, or dyn trait objects beyond one check. You need traits at the level of "a set of methods a type promises", Result, and match. The role names Client, Target, Adapter and Adaptee are used as the conventional ones; Design Patterns was not opened for this draft, so the attribution to it is UNVERIFIED [S1].

Versions. The series targets Rust 1.100.0. Every run reported below was made on rustc 1.97.0 on Linux [R1]. That gap is not closed here.

A close handler with one line and no doubts

Example 1 is the code before any adapter exists.

Example 1. Compiles; its one test passes by panicking (before/src/lib.rs lines 16 to 21 [C2])

// tell the dashboard
pub fn on_window_close(report: &ShutdownReport) {
    ureq::post("https://hooks.example.test/reports")
        .send_string(&report.summary())
        .unwrap();
}

The function on_window_close held that telling the dashboard was one statement's work. It carried a comment of three words, a URL written into its body, and a return type of nothing at all, and it finished on .unwrap() the way a man signs a form he has not turned over. It did not expect to be asked how the telling went. It was run on a machine where hooks.example.test did not resolve.

OUTPUT
thread 'tests::closing_needs_the_network' (5374) panicked at src/lib.rs:20:10:
called `Result::unwrap()` on an `Err` value: Transport(Transport { kind: Dns,
message: Some("resolve dns name 'hooks.example.test:443'"), […] })

That is the output of cargo test -- --nocapture in before/, shortened where marked [R1]. The other articles in the set show a compiler error at this point. This one cannot: Example 1 compiles. Its failure arrives at run time, and the crate's only test, closing_needs_the_network, is marked #[should_panic].

Three things are fixed inside those six lines. The destination is one URL. The outcome is a panic or silence, with no value a caller could inspect. And running the function at all means attempting a DNS lookup.

Predict

The close handler needs one answer: was the report delivered, and if not, why not? ureq answers with its own Result<Response, ureq::Error>. A command-line tool answers with an exit status. Before reading on: write the smallest list of failure names that a close handler could act on and that covers both tools. How many names did you need, and does any name mention HTTP or a process?

Name the parts

Role (conventional names; [S1] UNVERIFIED) In this crate Where [C1]
Client close_window<S: ReportSink> src/lib.rs lines 89 to 94
Target trait ReportSink, one method, deliver lines 29 to 31
The answer both adapters give enum ReportError, four variants lines 21 to 27
Adapter 1 WebhookSink struct, lines 33 to 36; impl ReportSink, lines 47 to 55
Adaptee 1 ureq::Agent (ureq 2.12.1) held in the field at line 34; called at line 49
Adapter 2 CommandSink struct, lines 57 to 60; impl ReportSink, lines 71 to 87
Adaptee 2 std::process::Command built and run at lines 73 to 76
The value delivered ShutdownReport and its summary() lines 5 to 19

What does the caller get to see?

Every place that reports out would otherwise repeat Example 1 with a different vendor call in the middle. Thankfully, the caller's side can be written once. Take a look at Example 2.

Example 2. The target and its one error type (src/lib.rs lines 21 to 31 [C1])

#[derive(Debug, PartialEq)]
pub enum ReportError {
    Unreachable,
    Rejected(u16),
    ToolMissing,
    ToolFailed(i32),
}

pub trait ReportSink {
    fn deliver(&self, report: &ShutdownReport) -> Result<(), ReportError>;
}

There are two pieces. ReportSink is a trait with one method: borrow a report, answer Ok(()) or a ReportError. And ReportError is the answer to the prediction as this crate gives it: four names. No type from ureq and no type from std::io or std::process appears in either item. Compare your list with the four. Two of them, Rejected(u16) and ToolFailed(i32), carry a number whose meaning belongs to one tool. We come back to that.

How does a ureq call become a deliver?

Take a look at Example 3, the first adapter.

Example 3. The webhook adapter (src/lib.rs lines 33 to 36 and 47 to 55 [C1])

pub struct WebhookSink {
    agent: ureq::Agent,
    url: String,
}

impl ReportSink for WebhookSink {
    fn deliver(&self, report: &ShutdownReport) -> Result<(), ReportError> {
        match self.agent.post(&self.url).send_string(&report.summary()) {
            Ok(_) => Ok(()),
            Err(ureq::Error::Status(code, _)) => Err(ReportError::Rejected(code)),
            Err(ureq::Error::Transport(_)) => Err(ReportError::Unreachable),
        }
    }
}

The struct owns its adaptee: agent is a ureq::Agent held by value, built once in WebhookSink::new with a two-second timeout (lines 39 to 44). The match has three arms and no wildcard, and it compiles, so those two Err arms are every variant ureq::Error has at this version. The source agrees: Status(u16, Response) for a response whose status code is 400 or above, and Transport(Transport) for a failure to make the request or receive the response [U1, src/error.rs lines 81 to 87; src/request.rs lines 169 to 170]. The adapter keeps the status code and drops the response beside it. It drops everything inside Transport, so a DNS failure, a refused connection and a timeout all leave as Unreachable.

And a process?

Example 4 is the second adapter, behind the same trait.

Example 4. The command adapter (src/lib.rs lines 71 to 87 [C1])

impl ReportSink for CommandSink {
    fn deliver(&self, report: &ShutdownReport) -> Result<(), ReportError> {
        let status = Command::new(&self.program)
            .args(&self.args)
            .arg(report.summary())
            .status()
            .map_err(|e| match e.kind() {
                ErrorKind::NotFound => ReportError::ToolMissing,
                _ => ReportError::Unreachable,
            })?;
        if status.success() {
            Ok(())
        } else {
            Err(ReportError::ToolFailed(status.code().unwrap_or(-1)))
        }
    }
}

There are three new pieces. Command::new(...).status() starts the program as a child process and waits for it; the summary is appended as the last argument, and the child inherits the parent's stdin, stdout and stderr [T1, process.rs lines 1117 to 1137]. The map_err handles the case where the program never started: ErrorKind::NotFound becomes ToolMissing, and every other kind becomes Unreachable. And if the program did run, a zero exit status is Ok(()) and anything else is ToolFailed with the code, or with -1 when there is no code, which on Unix is how std reports a child terminated by a signal [T1, lines 1924 to 1925 and 1949 to 1977].

One difference from Example 3: CommandSink does not own a Command. Its fields are program: String and args: Vec<String> (lines 57 to 60), and it builds a fresh Command inside each deliver.

The caller is four lines (lines 89 to 94): close_window<S: ReportSink>(sink: &S, report: &ShutdownReport) calls sink.deliver(report) and returns what it gets.

What transfers, and what does not

A PHP class that implements an interface and keeps the vendor's client in a private property is the same arrangement. (This comparison is prose; no PHP was run.) Three things in the Rust version are stated where PHP leaves them to convention, and all three can be read off the signatures above.

The failures are in the return type. A PHP adapter would catch the vendor's exception and throw its own; here deliver returns Result<(), ReportError>, and close_window returns the same.

The adapter is chosen when the code is compiled. S is a type parameter. As written, close_window does not accept a &dyn ReportSink: a scratch copy that tried it was rejected with E0277, "the trait Sized is not implemented for dyn ReportSink", and rustc's suggested change was S: ReportSink + ?Sized [R1, side check]. The crate itself does not use dyn anywhere.

And who holds what is written down. WebhookSink owns its ureq::Agent. close_window borrows the sink (&S) and borrows the report (&ShutdownReport), so both are still the caller's afterward.

Is it an adapter if the interface was written the same afternoon?

So the caller sees one method and one error type, and the crate compiles. The conventional Adapter starts from two interfaces that already exist and cannot be changed, and here ReportSink was written beside both of its implementations, in one file, by one author, with ReportError holding, depending on how you count, either four neutral outcomes or a status code for the HTTP tool and an exit code and a "missing" for the process tool, which is the adaptees' vocabulary relabelled, and the wildcard arm at line 79 files a permission error from the operating system under Unreachable, a name chosen for networks. A reader who called this plain trait implementation, or Strategy with I/O, would have the code on their side. I'd still teach it as Adapter, on one condition: that the test is whether close_window names anything from ureq or std::process, and it names neither.

Would a third sink, say a file, fit the four variants or need a fifth? If every new sink adds a variant, what has the caller been spared? Which of the four would your close handler treat differently from the others?

Practice tier: judgment. The compiler confirms each adapter has a deliver with the trait's signature and that the match in Example 3 covers every ureq::Error variant. Whether Unreachable is the right name for what line 79 sends there is not something it can see.

Testing

The claim is that the caller sees one interface and each tool's failure keeps its meaning. Take a look at Example 5.

Example 5. Two of the seven tests (src/lib.rs lines 145 to 149 and 163 to 167 [C1])

#[test]
fn webhook_refusal_keeps_its_status() {
    let sink = WebhookSink::new(&serve_once("HTTP/1.1 503 Service Unavailable"));
    assert_eq!(close_window(&sink, &report()), Err(ReportError::Rejected(503)));
}

#[test]
fn command_tool_failure_keeps_its_exit_code() {
    let sink = CommandSink::new("sh", &["-c", "exit 3", "--"]);
    assert_eq!(close_window(&sink, &report()), Err(ReportError::ToolFailed(3)));
}

Both go through close_window, and each would fail if its adapter lost the number. cargo test --locked, rustc 1.97.0, Linux, exit status 0 [R1]:

OUTPUT
running 7 tests
test tests::command_tool_failure_keeps_its_exit_code ... ok
test tests::command_tool_that_is_not_installed_is_named ... ok
test tests::the_caller_sees_one_interface ... ok
test tests::webhook_accepts_a_report ... ok
test tests::command_tool_succeeds ... ok
test tests::webhook_refusal_keeps_its_status ... ok
test tests::webhook_with_nothing_listening_is_unreachable ... ok

test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s

The saved test-output.txt lists the same seven names, all ok. It records no toolchain.

What the seven do not show. The webhook tests talk to a listener the test starts on 127.0.0.1 (serve_once, lines 119 to 130), which answers with a fixed status line and checks nothing about the request, so no test confirms the method, the path or the body. The "nothing listening" test assumes port 9 on the local machine is closed. The command tests run true and sh, need a Unix-like PATH, and do not check that the summary reached the child. No test reaches the wildcard at line 79 or the -1 at line 84. And the_caller_sees_one_interface is the only test that uses a sink that is neither adapter: a FakeSink in the test module (lines 108 to 117).

Retrieve

  1. Which two ureq::Error variants does WebhookSink::deliver match, and which ReportError does each become?
  2. WebhookSink owns a ureq::Agent. What does CommandSink keep in its fields, and when does a Command exist?

The Strategy article ended by pointing here, to "a trait the caller is written against". This is the last pattern in the set. The first article asked where a program's parts are chosen; this crate has no such place yet, since only its tests ever construct a sink.

TL;DR

ReportSink is a trait with one method, deliver, returning Result<(), ReportError>. WebhookSink implements it over an owned ureq::Agent and maps ureq::Error::Status to Rejected(code) and ureq::Error::Transport to Unreachable. CommandSink implements it by building a std::process::Command on each call and maps a missing program to ToolMissing and a non-zero exit to ToolFailed(code). close_window is generic over the trait and names neither tool. The code is written for the course, the seven tests passed here on rustc 1.97.0, and they use a local listener, true and sh, so they do not show that a real endpoint or tool accepts the report.

The sources.

Each article names its sources in brackets, with the file, chapter or line to look at. Line numbers are for the tag or commit each article names and will move. Each article says which toolchain its tests passed on: rustc 1.100.0 for eleven of them, rustc 1.97.0 on Linux for Adapter.

SOURCES — 7
  • [C1] examples/cp11-adapters/src/lib.rs, course-written, read in full 2026-11-29.
  • [C2] examples/cp11-adapters/before/src/lib.rs, course-written, read in full 2026-11-29.
  • [R1] The recorded test run: commands, versions and full output; rustc 1.97.0, cargo 1.97.0, Linux.
  • [U1] ureq 2.12.1, the crate source as downloaded from crates.io by Cargo under the pinned Cargo.lock: src/error.rs, src/request.rs, src/agent.rs. Read locally. The docs.rs pages for 2.12.1 were requested and could not be opened in this session.
  • [T1] library/std/src/process.rs and library/core/src/io/error.rs from the rust-src component of Rust 1.97.0, not the 1.100.0 tag the series pins. The doc.rust-lang.org pages were requested and could not be opened. Line numbers are for 1.97.0 and will differ at 1.100.0.
  • [S1] Gamma, Helm, Johnson, Vlissides, Design Patterns, "Adapter". NOT OPENED. The four role names are used as conventional; no page is cited and no statement about what the book says is made from it.
  • Not verified: any behavior on Rust 1.100.0 or on macOS; the PHP comparison; whether .test names are guaranteed never to resolve (the article says only that this one did not, in this run).
NOT CHECKED — 6
  • Every run reported in this article was made on rustc 1.97.0 on Linux. Rust 1.100.0 and macOS are not covered here.
  • The std line numbers are from the 1.97.0 source and will differ at 1.100.0.
  • ureq 2.12.1 was read from the crate's source. Its docs.rs pages could not be opened.
  • *Design Patterns* was not opened. The four role names are used as the conventional ones.
  • The PHP comparison is prose. No PHP was run.
  • The article says only that hooks.example.test did not resolve in that run, not that .test names never resolve.