rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! Upgrading an HTTP server (`rho mcp serve --http`, `rho daemon serve --http`)
//! in place, as the daemon upgrades (`daemon::Executable`): once `rho update`
//! replaced the server's executable with one that proves itself rho, the
//! server stops accepting connections, drains work under way, and moves onto
//! the replacement. On Unix it re-executes the replacement as the same
//! process, and hands the new binary its listening
//! socket (`--listener-fd`), so a client that connects meanwhile waits in the
//! backlog instead of finding nothing there, and a service manager sees the
//! same process.
//!
//! A replacement older than the running server, as after a rollback, may
//! predate `--listener-fd` and `--predecessor`, so it is told neither: the
//! server closes its socket as it moves, and the replacement listens anew.
//!
//! Windows can neither replace a process with another program nor hand a
//! child a listening socket, so there the server closes its socket, starts
//! the replacement as a new process with the same arguments, the console
//! and the output streams it has, and exits. The replacement waits for it
//! to exit (`--predecessor`), as a restarted daemon does, then listens
//! anew: a client that connects in between is refused and connects again.

use std::{
    ffi::OsString,
    future::Future,
    io,
    net::{SocketAddr, TcpListener},
    sync::{
        atomic::{AtomicUsize, Ordering},
        Arc,
    },
    time::Duration,
};

use anyhow::Context as _;
use tokio::sync::{watch, Notify};

use crate::daemon::Executable;

/// The hidden flag that hands a re-executed server its listening socket.
const LISTENER_FD_FLAG: &str = "--listener-fd";

/// The hidden flag that names, on Windows, the server a relaunched one took
/// over from, whose exit it waits for before it listens.
const PREDECESSOR_FLAG: &str = "--predecessor";

/// How often the server checks whether its executable was replaced.
//
// Matches the daemon's interval (`UPGRADE_CHECK_INTERVAL`): one `stat(2)` of
// the executable (~microseconds), bounding how long a server runs a replaced
// binary before it drains.
const CHECK_INTERVAL: Duration = Duration::from_secs(1);

/// How an HTTP server upgrades in place: its log label, the executable it
/// watches, and the arguments it re-executes the replacement with.
pub(crate) struct Upgrade {
    label: &'static str,
    executable: Executable,
    args: Vec<OsString>,
}

impl Upgrade {
    /// Upgrades of `executable`, re-executed with `args`, the arguments the
    /// server started with after its program.
    pub(crate) fn new(
        label: &'static str,
        executable: Executable,
        args: impl Iterator<Item = OsString>,
    ) -> Self {
        Self {
            label,
            executable,
            args: without_handoff(args),
        }
    }

    /// Resolves with the replacement's version once the executable was
    /// replaced by a binary that proves itself rho. Keep one such future
    /// for the server's life: it runs each replacement once.
    pub(crate) async fn replaced(&self) -> String {
        let executable = &self.executable;
        let mut checks = tokio::time::interval(CHECK_INTERVAL);
        checks.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
        // The replacement last probed to an answer, so each is run once; one
        // that could not run at all is tried again.
        let mut probed = None;
        loop {
            checks.tick().await;
            let Some(replacement) = executable.replacement() else {
                probed = None;
                continue;
            };
            if probed == Some(replacement.identity) {
                continue;
            }
            match executable.probe().await {
                Ok(version) => return version,
                Err(error) if error.is_transient() => {
                    tracing::debug!(%error, "could not probe the server's replaced executable; trying again");
                }
                Err(error) => {
                    eprintln!(
                        "{}: {} was replaced by a file that is not rho ({error}); not upgrading",
                        self.label,
                        executable.path().display()
                    );
                    probed = Some(replacement.identity);
                }
            }
        }
    }

    /// Moves onto the replacement, `version`, handing it `listener` (Unix)
    /// or this process's pid (Windows) unless it is older than this server.
    /// Returns only with why that failed.
    pub(crate) fn relaunch(self, listener: TcpListener, version: &str) -> anyhow::Error {
        let running = env!("CARGO_PKG_VERSION");
        let older = crate::update::version_is_newer(running, version);
        if older {
            eprintln!(
                "{}: {version} is older than {running} and may not know how this server hands over; it listens anew",
                self.label
            );
        }
        let path = self.executable.path();
        #[cfg(unix)]
        let error = unix::relaunch((!older).then_some(&listener), path, self.args);
        #[cfg(windows)]
        let error = windows::relaunch(
            (self.label, version),
            listener,
            (!older).then(std::process::id),
            path,
            self.args,
        );
        anyhow::Error::new(error).context(format!("could not run {} to upgrade", path.display()))
    }
}

/// What a server an upgrade started takes over from the one before it:
/// on Unix the listening socket handed as `listener_fd`, which it returns;
/// on Windows the wait for `predecessor` to exit. Call before anything this
/// process starts could inherit the socket.
pub(crate) async fn take_over(
    listener_fd: Option<i32>,
    predecessor: Option<u32>,
) -> anyhow::Result<Option<TcpListener>> {
    let listener = listener_fd
        .map(|fd| {
            inherit_listener(fd)
                .with_context(|| format!("could not take over the listening socket {fd}"))
        })
        .transpose()?;
    if let Some(pid) = predecessor {
        wait_for_predecessor(pid).await?;
    }
    Ok(listener)
}

/// The listening socket a re-executing server handed this one as `fd`,
/// with `--listener-fd`.
fn inherit_listener(fd: i32) -> io::Result<TcpListener> {
    #[cfg(unix)]
    {
        let listener = TcpListener::from(crate::daemon::adopt(fd)?);
        listener.local_addr()?;
        listener.set_nonblocking(true)?;
        Ok(listener)
    }
    #[cfg(not(unix))]
    Err(io::Error::other(format!(
        "a server hands on its listening socket only on Unix, not {LISTENER_FD_FLAG} {fd}"
    )))
}

/// Waits for the server this one took over from on Windows, process `pid`
/// (`--predecessor`), to exit, so nothing it still holds, as `rho mcp
/// serve`'s watch store, is held twice. It closed its listening socket
/// before it started this one, so a wait that runs out says so and goes
/// on: listening still fails loudly if the address is held.
async fn wait_for_predecessor(pid: u32) -> anyhow::Result<()> {
    #[cfg(windows)]
    {
        if let Err(error) =
            tokio::task::spawn_blocking(move || crate::daemon::wait_for_exit(pid)).await?
        {
            eprintln!("rho: taking over anyway: {error}");
        }
        Ok(())
    }
    #[cfg(not(windows))]
    anyhow::bail!(
        "a server takes over from another process only on Windows, not {PREDECESSOR_FLAG} {pid}"
    )
}

/// Validates that an inherited `socket` listens on `address` (allowing port
/// `0` as a wildcard for the requested port) and converts it to a Tokio
/// `TcpListener`.
pub(crate) fn adopted_listener(
    socket: TcpListener,
    address: SocketAddr,
) -> anyhow::Result<tokio::net::TcpListener> {
    let local = socket.local_addr()?;
    if local.ip() != address.ip() || (address.port() != 0 && local.port() != address.port()) {
        anyhow::bail!("the inherited listening socket is on {local}, not on --http {address}");
    }
    Ok(tokio::net::TcpListener::from_std(socket)?)
}

/// Draining an HTTP server for an upgrade: the calls under way, and the signal
/// that tells each connection to close after the call it serves.
pub(crate) struct Drain {
    calls: InFlight,
    begin: watch::Sender<bool>,
}

impl Drain {
    pub(crate) fn new() -> Self {
        Self {
            calls: InFlight::default(),
            begin: watch::Sender::new(false),
        }
    }

    /// The calls under way, for a connection to count its calls in.
    pub(crate) fn calls(&self) -> InFlight {
        self.calls.clone()
    }

    /// Resolves once draining began, so a connection closes after the call
    /// it serves and the client's next call lands on the replacement.
    pub(crate) fn began(&self) -> impl Future<Output = ()> + Send + 'static {
        let mut begin = self.begin.subscribe();
        async move { drop(begin.wait_for(|began| *began).await) }
    }

    /// Tells every connection to close after the call it serves, then waits
    /// for the calls under way, at most `timeout`. Returns how many are still
    /// under way: zero once they all ended.
    pub(crate) async fn settle(&self, timeout: Duration) -> usize {
        self.begin.send_replace(true);
        self.calls.drained(timeout).await;
        self.calls.count()
    }

    /// Waits for the calls under way, at most `timeout`, then re-executes
    /// `upgrade`'s replacement, `version`, handing it `listener`, which the
    /// caller stopped accepting on. Returns only with why that failed.
    pub(crate) async fn finish(
        &self,
        upgrade: Upgrade,
        version: &str,
        listener: tokio::net::TcpListener,
        timeout: Duration,
    ) -> anyhow::Error {
        // Begun before announcing it, so a call that ends once a client sees
        // the announcement already finds its connection told to close.
        self.begin.send_replace(true);
        eprintln!(
            "{}: upgrading to {version} in place once the calls under way end ({} now)",
            upgrade.label,
            self.calls.count()
        );
        let left = self.settle(timeout).await;
        if left > 0 {
            eprintln!(
                "{}: {left} calls still under way after {timeout:?}; cutting them short to upgrade",
                upgrade.label,
            );
        }
        match listener.into_std() {
            Ok(listener) => upgrade.relaunch(listener, version),
            Err(error) => {
                anyhow::Error::new(error).context("could not hand on the listening socket")
            }
        }
    }
}

/// The calls under way, which an upgrade waits for.
#[derive(Clone, Default)]
pub(crate) struct InFlight {
    count: Arc<AtomicUsize>,
    /// Wakes a drain each time a call ends.
    ended: Arc<Notify>,
}

/// One call under way, until dropped.
pub(crate) struct Call(InFlight);

impl InFlight {
    /// Counts a call under way until the returned guard drops.
    pub(crate) fn enter(&self) -> Call {
        self.count.fetch_add(1, Ordering::SeqCst);
        Call(self.clone())
    }

    fn count(&self) -> usize {
        self.count.load(Ordering::SeqCst)
    }

    /// Resolves once no call is under way, or after `timeout`.
    async fn drained(&self, timeout: Duration) {
        let _ = tokio::time::timeout(timeout, async {
            loop {
                let ended = self.ended.notified();
                if self.count() == 0 {
                    return;
                }
                ended.await;
            }
        })
        .await;
    }
}

impl Drop for Call {
    fn drop(&mut self) {
        self.0.count.fetch_sub(1, Ordering::SeqCst);
        self.0.ended.notify_waiters();
    }
}

/// `args` without the `--listener-fd` or `--predecessor` an earlier
/// upgrade added.
fn without_handoff(args: impl Iterator<Item = OsString>) -> Vec<OsString> {
    let mut kept = Vec::new();
    let mut args = args.peekable();
    while let Some(arg) = args.next() {
        if arg == LISTENER_FD_FLAG || arg == PREDECESSOR_FLAG {
            args.next();
        } else {
            kept.push(arg);
        }
    }
    kept
}

#[cfg(unix)]
mod unix {
    use std::{
        ffi::OsString,
        io,
        net::TcpListener,
        os::{
            fd::{AsFd, AsRawFd},
            unix::process::CommandExt,
        },
        path::Path,
        process::Command,
    };

    use super::LISTENER_FD_FLAG;
    use crate::daemon::{reap_exited_children, set_close_on_exec};

    /// Re-executes `executable` as this process with `args`, handing it
    /// `handed`, the listening socket, if any; without one the exec closes
    /// it. Returns only if that failed.
    pub(super) fn relaunch(
        handed: Option<&TcpListener>,
        executable: &Path,
        args: Vec<OsString>,
    ) -> io::Error {
        let socket = handed.map(AsFd::as_fd);
        // From here until the exec, a child another thread starts inherits
        // the socket too, as with the daemon's handoff; the window is the
        // two calls below.
        if let Some(Err(error)) =
            socket.map(|socket| set_close_on_exec(socket, /*close*/ false))
        {
            return error;
        }
        reap_exited_children();
        let mut command = Command::new(executable);
        command.args(args);
        if let Some(socket) = socket {
            command
                .arg(LISTENER_FD_FLAG)
                .arg(socket.as_raw_fd().to_string());
        }
        let error = command.exec();
        if let Some(socket) = socket {
            let _ = set_close_on_exec(socket, /*close*/ true);
        }
        error
    }
}

#[cfg(windows)]
mod windows {
    use std::{ffi::OsString, io, net::TcpListener, path::Path, process::Command};

    use super::PREDECESSOR_FLAG;

    /// Closes `listener`, then starts `executable` with `args` in this
    /// process's console, with its output streams, and exits; `predecessor`,
    /// this process's pid, tells it to wait for that exit before it
    /// listens. `(label, version)` name the server and the replacement in
    /// the line saying so. Returns only if the replacement did not start.
    pub(super) fn relaunch(
        (label, version): (&str, &str),
        listener: TcpListener,
        predecessor: Option<u32>,
        executable: &Path,
        args: Vec<OsString>,
    ) -> io::Error {
        drop(listener);
        let mut command = Command::new(executable);
        command.args(args);
        if let Some(pid) = predecessor {
            command.arg(PREDECESSOR_FLAG).arg(pid.to_string());
        }
        match command.spawn() {
            Ok(child) => {
                eprintln!(
                    "{label}: started {version} as process {} to take over; exiting",
                    child.id()
                );
                // As a Unix exec would, without running this process's
                // destructors: the drain is done.
                std::process::exit(0)
            }
            Err(error) => error,
        }
    }
}

#[cfg(test)]
#[path = "http_upgrade_tests.rs"]
mod tests;