Skip to main content

darkbio_wire/protocol/
responder.rs

1// wire-rs: encrypted protocol between Ark and host
2// Copyright 2026 Dark Bio AG. All rights reserved.
3
4//! Sending one reply to a received request, or `UNANSWERED` when dropped.
5
6use super::session::SessionInner;
7use super::{Error, Message, Promise, schema};
8use std::sync::Weak;
9use std::time::Instant;
10
11/// Handle for answering one incoming request through the session that received it.
12/// The handler selects the success content, without a static request/response map.
13/// This handle cannot keep its session open or address a replacement session.
14///
15/// Dropping an unanswered responder queues an `UNANSWERED` error without blocking
16/// on I/O, using the session's current abandonment timeout.
17/// Configure it with [`super::Session::set_abandonment_timeout`] or
18/// [`super::Server::set_abandonment_timeout`]. If the session has closed, no reply
19/// is queued.
20///
21/// A held responder counts toward the session's inbound request limit. Queuing a
22/// reply keeps that slot until the writer takes it or the reply is discarded.
23/// See [`super::Session::set_inbound_limits`].
24///
25/// Both [`Self::reply`] and [`Self::fail`] consume the responder, so it cannot be reused:
26///
27/// ```compile_fail,E0382
28/// use darkbio_wire::protocol::{Responder, schema};
29/// use std::time::Instant;
30///
31/// fn answer_twice(responder: Responder, deadline: Instant) {
32///     let _ = responder.reply(schema::DeviceInfoResponse::default(), deadline);
33///     let _ = responder.fail(schema::Error::new(0x100, "refused"), deadline);
34/// }
35/// ```
36///
37/// Responders cannot be cloned either:
38///
39/// ```compile_fail,E0599
40/// use darkbio_wire::protocol::Responder;
41/// fn duplicate(responder: Responder) { let _ = responder.clone(); }
42/// ```
43#[derive(Debug)]
44pub struct Responder {
45    /// Session that received the request; holding a responder cannot keep it open.
46    session: Weak<SessionInner>,
47    /// Request ID to answer. Cleared after queueing a reply so `Drop` does nothing.
48    id: Option<u64>,
49}
50
51impl Responder {
52    /// Queues a successful response and consumes the responder. Returns a promise
53    /// for writing and flushing it. A closed session returns an error immediately.
54    /// The deadline includes time in the queue and I/O. Waiting on the promise
55    /// does not restart it.
56    ///
57    /// A message invalid for this session's direction fails the promise with
58    /// [`Error::WrongDirection`].
59    ///
60    /// A reply needs no further acknowledgment. Dropping its promise leaves it queued.
61    /// Accepts a protobuf response or [`Message`] directly. Use [`Self::fail`] to
62    /// return an error instead.
63    pub fn reply(
64        self,
65        response: impl Into<Message>,
66        deadline: Instant,
67    ) -> Result<Promise<()>, Error> {
68        self.enqueue(Ok(response.into()), deadline)
69    }
70
71    /// Queues an error response and consumes the responder. The deadline and write
72    /// promise work as in [`Self::reply`]. The error itself does not close the session.
73    /// Use [`schema::Error::reserved`] for a named protocol error or
74    /// [`schema::Error::new`] for a numeric error code.
75    pub fn fail(self, error: schema::Error, deadline: Instant) -> Result<Promise<()>, Error> {
76        self.enqueue(Err(error), deadline)
77    }
78
79    /// Queues either kind of response and marks this responder as answered.
80    fn enqueue(
81        mut self,
82        result: Result<Message, schema::Error>,
83        deadline: Instant,
84    ) -> Result<Promise<()>, Error> {
85        let promise = self.session.upgrade().ok_or(Error::Closed)?.reply(
86            self.id.expect("reply obligation present"),
87            result,
88            deadline,
89        )?;
90        self.id = None; // Prevent Drop from also queueing UNANSWERED.
91        Ok(promise)
92    }
93
94    /// Creates a responder for the request taken by `Session::recv()`.
95    pub(super) fn new(session: Weak<SessionInner>, id: u64) -> Self {
96        Self {
97            session,
98            id: Some(id),
99        }
100    }
101}
102
103impl Drop for Responder {
104    /// Queues `UNANSWERED` if this responder still has an ID and its session is
105    /// open. The writer sends the error later.
106    fn drop(&mut self) {
107        if let Some(id) = self.id.take()
108            && let Some(session) = self.session.upgrade()
109        {
110            session.reply_unanswered(id);
111        }
112    }
113}
114
115/// Checks responder ownership and compiles success, error and deferred reply paths.
116#[cfg(test)]
117#[cfg_attr(coverage_nightly, coverage(off))]
118mod tests {
119    use crate::protocol::schema::DeviceInfoResponse;
120    use crate::protocol::{Error, Message, Promise, Responder, Session, schema};
121    use std::fmt::Debug;
122    use std::time::Instant;
123
124    /// Compiles receiving a host-side request and returning an application error.
125    #[allow(dead_code)]
126    fn receive_on_host(session: &mut Session, deadline: Instant) -> Result<(), Error> {
127        let (request, responder): (Message, Responder) = session.recv()?;
128        let _ = request;
129        responder
130            .fail(
131                schema::Error::reserved(schema::ReservedErrors::Unspecified, "refused"),
132                deadline,
133            )?
134            .wait()
135    }
136
137    /// Compiles immediate replies, a background reverse request and responder abandonment.
138    #[allow(dead_code)]
139    fn receive_on_server(session: &mut Session, deadline: Instant) -> Result<(), Error> {
140        let (request, responder): (Message, Responder) = session.recv()?;
141        match request {
142            Message::DeviceInfoRequest(_) => {
143                let written: Promise<()> =
144                    responder.reply(DeviceInfoResponse::default(), deadline)?;
145                written.wait()?;
146            }
147            Message::Develop(bytes) => {
148                // Opaque development traffic is supported in both directions.
149                let requester = session.requester();
150                std::thread::spawn(move || -> Result<(), Error> {
151                    let answer: Vec<u8> = requester.request(bytes, deadline)?.wait()?;
152                    drop(responder.reply(answer, deadline)?);
153                    Ok(())
154                });
155            }
156            _ => drop(responder), // Schedules the standard unanswered error.
157        }
158        Ok(())
159    }
160
161    /// Checks the bounds required to move the responder to an application thread
162    /// and to print it.
163    #[test]
164    fn test_thread_capabilities() {
165        /// Requires an owned value to be printable and transferable to a background thread.
166        fn movable<T: Debug + Send + 'static>() {}
167        movable::<Responder>();
168    }
169}