Skip to main content

git_policy_cli/service/
service_client.rs

1//! What:
2//!  The wrapper's side of a commit through the resident service: connect, wait honestly while the operating system
3//!  starts the service, send the request, show the queue position, survive a service that dies mid-request, and turn
4//!  every failure into the plain text of `service_messages.rs`.
5//! Why:
6//!  A failure the system can resolve is resolved here without the user: a service that is starting is waited for, one
7//!  that crashed is reconnected to with the same request identity, one that was started from another release of the
8//!  wrapper (older or newer, found by the release its welcome names) is asked to retire and is reached again once the
9//!  manager has started the current one. Only what cannot be resolved ends the command.
10//!
11//! In TS you'd write (pseudocode):
12//! ```ts
13//! const result = await submit(config, request, stderr); // landed, or prepare again, or a ClientFailure
14//! ```
15
16use crate::commit_timing::{ReachTrace, SubmitTrace, holder_kind_of};
17use crate::service_messages::{ClientFailure, Platform, SILENT_NOTICE, STARTING_NOTICE, UPDATING_NOTICE, position_notice};
18use crate::service_protocol::{
19    ClientMessage, CommitRequest, FailureCode, LandedCapture, PROTOCOL_VERSION, RELEASE, ServiceMessage, decode_service, encode_client, encode_retire,
20};
21use crate::service_instance::service_unit_instance;
22use crate::service_provision::ProvisionHost;
23use crate::service_review_key::ReviewKey;
24use crate::systemd_dbus::{Bus, EXCHANGE_WAIT};
25use crate::service_server::Bind;
26use std::io::{BufRead, BufReader, Write};
27use std::os::unix::net::UnixStream;
28use std::time::{Duration, Instant};
29
30/// How long the client waits for a service to start or to retire when it cannot ask the service manager how the start is going.
31///  Ten times the slowest of 52 cold starts in this repository's commit timing log (`startWaitMs`, longest 1041 ms,
32///  median 47 ms, 2026-11-03); the 70 commits that also asked an older service to retire all reached the service within
33///  that same 1041 ms (`reachMs`). A client that can ask the manager has no such bound: it ends when the manager says the
34///  start failed.
35pub const START_WAIT: Duration = Duration::from_secs(10);
36
37/// How long a start takes before the client says it is starting the service.
38pub const START_NOTICE_GRACE: Duration = Duration::from_secs(1);
39
40/// How many times a request is sent again after the connection broke before the client says it cannot be sure.
41pub const RECONNECTS: usize = 5;
42
43/// The pause between connection tries while the service starts.
44const CONNECT_PAUSE: Duration = Duration::from_millis(25);
45
46/// What the client may rely on the operating system to do.
47#[derive(Clone, Copy, Debug, Eq, PartialEq)]
48pub enum Activation {
49    /// The manager owns the socket and starts the service on demand.
50    Managed,
51    /// This platform cannot start the service on demand.
52    Unsupported(Platform),
53}
54
55/// What the client needs to reach the service.
56#[derive(Clone, Debug)]
57pub struct ClientConfig {
58    /// Where the service listens.
59    pub address: Bind,
60    /// What the operating system can do about a service that is not running.
61    pub activation: Activation,
62    /// Longest wait for a start when `start_watch` is absent; with a watch the wait ends only when the manager says the start
63    ///  failed, and this is the wait for an older service to retire.
64    pub start_wait: Duration,
65    /// How long the service may send nothing, heartbeats included, before the client treats it as stopped. There is no limit
66    ///  on how long a request waits while the service keeps sending.
67    pub heartbeat_silence: Duration,
68    /// How to ask the service manager whether the service failed to start; absent where the client cannot ask.
69    pub start_watch: Option<ManagerWatch>,
70    /// A scratch directory of this command to keep from being swept as stale while the command waits.
71    pub keep_fresh: Option<FreshScratch>,
72    /// The longest the client waits for the service's answer; then it withdraws the request (`wait_ceilings.rs`).
73    pub answer_ceiling: Duration,
74    /// The longest the client waits for the service to answer the withdrawal.
75    pub withdraw_ceiling: Duration,
76    /// The longest a start is waited for when the service manager can be asked.
77    pub start_ceiling: Duration,
78}
79
80/// What:
81///  A scratch directory a waiting command keeps fresh, and how often.
82/// Why:
83///   The scratch sweep removes entries by age, and a wait with no bound can outlast any age; a waiter that is alive says so by
84///  touching its directory, one that died stops and the sweep collects the directory.
85///
86/// In TS you'd write (pseudocode):
87/// ```ts
88/// type FreshScratch = { path: string; every: number };
89/// ```
90#[derive(Clone, Debug)]
91pub struct FreshScratch {
92    /// The directory.
93    pub path: std::path::PathBuf,
94    /// How often its modification time is renewed while the command waits.
95    pub every: Duration,
96}
97
98/// What:
99///  How the client asks the service manager whether the service unit has failed.
100/// Why:
101///   A service that is starting sends nothing, so the wait for its first greeting has no heartbeat to listen for. The manager
102///  knows whether the start failed, which is the one thing that ends that wait.
103///
104/// In TS you'd write (pseudocode):
105/// ```ts
106/// type ManagerWatch = { bus: string; unit: string; every: number; state: (bus, unit) => string | undefined; start: (bus, unit) => boolean };
107/// ```
108#[derive(Clone, Debug)]
109pub struct ManagerWatch {
110    /// The session bus of the account.
111    pub bus: std::path::PathBuf,
112    /// The service unit of the worktree.
113    pub unit: String,
114    /// How often the manager is asked while the greeting has not come.
115    pub every: Duration,
116    /// The unit's `ActiveState` now (`active`, `activating`, `inactive`, `failed`, ...); nothing when the manager cannot be
117    ///  asked, which leaves the wait to the start wait.
118    pub state: fn(&std::path::Path, &str) -> Option<String>,
119    /// Asks the manager to start the unit; whether the manager took the request.
120    pub start: fn(&std::path::Path, &str) -> bool,
121}
122
123/// How often the service manager is asked whether the service unit failed, while a start is waited for.
124pub const MANAGER_ASK_EVERY: Duration = START_NOTICE_GRACE;
125
126/// The manager's `ActiveState` of `unit`: nothing when the bus or the unit cannot be asked about.
127fn unit_state(bus: &std::path::Path, unit: &str) -> Option<String> {
128    let mut connection: Bus = Bus::connect(bus, EXCHANGE_WAIT).ok()?;
129    return connection.active_state(unit).ok()?;
130}
131
132/// Asks the manager to start `unit`; whether the request was taken.
133fn start_unit(bus: &std::path::Path, unit: &str) -> bool {
134    let Ok(mut connection) = Bus::connect(bus, EXCHANGE_WAIT) else { return false };
135    return connection.start_unit(unit).is_ok();
136}
137
138/// What:
139///  The watch that asks the account's service manager about the worktree's service unit.
140/// Why:
141///   The route knows the session bus and the worktree's instance, which is all the unit's name needs.
142///
143/// In TS you'd write (pseudocode):
144/// ```ts
145/// const watch = managerWatchFor(host)
146/// ```
147pub fn manager_watch_for(host: &ProvisionHost) -> ManagerWatch {
148    return ManagerWatch { bus: host.bus.clone(), unit: service_unit_instance(host.instance.as_str()), every: MANAGER_ASK_EVERY, state: unit_state, start: start_unit };
149}
150
151/// What the client heard from the service in one read.
152enum Heard {
153    /// A message.
154    Message(ServiceMessage),
155    /// The service closed the connection, or sent something that is not a message.
156    Closed,
157    /// Nothing came within the silence bound.
158    Silent,
159}
160
161/// What a request came to.
162#[derive(Clone, Debug, Eq, PartialEq)]
163pub enum Submitted {
164    /// The commit is on the branch.
165    Landed { commit: String, already: bool },
166    /// A named path changed on the branch: prepare again from this base and submit again with the same identity.
167    ///  `landed` tells when the bytes of the commits the service landed since were captured, for the ones it knows.
168    PrepareAgain { base: String, landed: Vec<LandedCapture> },
169    /// The branch is no longer at the base of a commit that cannot be moved to another tip (an amend, or a commit Git built).
170    ///  The caller decides whether to build it again on the new tip or to stop.
171    Moved,
172}
173
174fn connect(address: &Bind) -> std::io::Result<UnixStream> {
175    return match address {
176        #[cfg(target_os = "linux")]
177        Bind::Abstract(name) => {
178            use std::os::linux::net::SocketAddrExt;
179            UnixStream::connect_addr(&std::os::unix::net::SocketAddr::from_abstract_name(name.as_bytes())?)
180        }
181        #[cfg(not(target_os = "linux"))]
182        Bind::Abstract(_) => Err(std::io::Error::other("abstract sockets need Linux")),
183        Bind::Path(path) => UnixStream::connect(path),
184        Bind::Inherited => Err(std::io::Error::other("a client does not inherit the socket")),
185    };
186}
187
188fn read_message(reader: &mut BufReader<UnixStream>) -> Option<ServiceMessage> {
189    return match listen(reader) {
190        Heard::Message(message) => Some(message),
191        Heard::Closed | Heard::Silent => None,
192    };
193}
194
195/// What:
196///  Reads one line from the service and says whether it was a message, a close, or silence.
197/// Why:
198///   A read that times out is the service saying nothing for the silence bound, which is not the same as a service that
199///  closed its end: the first is asked again with the same request, the second is a service that went away.
200///
201/// In TS you'd write (pseudocode):
202/// ```ts
203/// const heard = await listen(reader) // { message } | 'closed' | 'silent'
204/// ```
205fn listen(reader: &mut BufReader<UnixStream>) -> Heard {
206    let mut line: String = String::new();
207    return match reader.read_line(&mut line) {
208        Ok(read) if read > 0 => decode_service(line.trim_end_matches('\n')).map_or(Heard::Closed, Heard::Message),
209        Err(error) if matches!(error.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => Heard::Silent,
210        _ => Heard::Closed,
211    };
212}
213
214/// What:
215///  Connects, waiting for a start the operating system performs, and returns the stream with the service's version.
216/// Why:
217///   With a manager to ask, the wait has no clock: it ends when the service greets, or when the manager has said twice in a
218///  row that the unit failed. Where the manager cannot be asked it ends at the start wait, as it always did. Once a service
219///  has greeted during this command (`service_seen`), a service that then greets nothing within the silence bound is the
220///  one that stopped, and that ends the wait.
221///
222/// In TS you'd write (pseudocode):
223/// ```ts
224/// const { stream, version } = await reach(config, notices, serviceSeen)
225/// ```
226fn reach(
227    config: &ClientConfig,
228    notices: &mut dyn Write,
229    announced: &mut bool,
230    trace: &mut ReachTrace,
231    service_seen: bool,
232) -> Result<(BufReader<UnixStream>, u32, Option<String>), ClientFailure> {
233    let started: Instant = Instant::now();
234    let mut refused_here: bool = false;
235    let mut last_asked: Instant = started;
236    let mut failed_answers: u32 = 0;
237    let mut cannot_ask: bool = false;
238    let mut last_start_request: Option<Instant> = None;
239    loop {
240        trace.tries += 1;
241        match connect(&config.address) {
242            Ok(stream) => {
243                let patience: Duration = match (&config.start_watch, service_seen) {
244                    (_, true) => config.heartbeat_silence,
245                    (Some(watch), false) => watch.every,
246                    (None, false) => config.start_wait,
247                };
248                let _timeout = stream.set_read_timeout(Some(patience));
249                let mut reader: BufReader<UnixStream> = BufReader::new(stream);
250                match listen(&mut reader) {
251                    Heard::Message(ServiceMessage::Welcome { version, release }) => {
252                        let _widened = reader.get_ref().set_read_timeout(Some(config.heartbeat_silence));
253                        trace.saw_release(release.as_deref());
254                        if refused_here {
255                            trace.start_waited += started.elapsed();
256                        }
257                        return Ok((reader, version, release));
258                    }
259                    // A service that greeted before and now greets nothing is the one that stopped.
260                    Heard::Silent if service_seen => return Err(ClientFailure::ServiceSilent),
261                    // Connected, but nothing greeted: the service is still starting or is going away.
262                    Heard::Message(_) | Heard::Closed | Heard::Silent => {
263                        trace.refused += 1;
264                        refused_here = true;
265                    }
266                }
267            }
268            Err(_) => match config.activation {
269                Activation::Unsupported(platform) => return Err(ClientFailure::NoActivation(platform)),
270                Activation::Managed => {
271                    trace.refused += 1;
272                    refused_here = true;
273                }
274            },
275        }
276        match &config.start_watch {
277            Some(watch) => {
278                if last_asked.elapsed() >= watch.every {
279                    last_asked = Instant::now();
280                    let answer: Option<String> = (watch.state)(watch.bus.as_path(), watch.unit.as_str());
281                    // A unit still `inactive` after the start wait, with the client's connection waiting on its socket, is one the
282                    //  manager did not start; it is asked to, again after each further start wait, and the client goes on waiting.
283                    // A unit that is `activating` is being started and is left alone.
284                    if answer.as_deref() == Some("inactive")
285                        && started.elapsed() >= config.start_wait
286                        && last_start_request.is_none_or(|at| { return at.elapsed() >= config.start_wait; })
287                    {
288                        let _taken = (watch.start)(watch.bus.as_path(), watch.unit.as_str());
289                        last_start_request = Some(Instant::now());
290                    }
291                    cannot_ask = answer.is_none();
292                    failed_answers = if answer.as_deref() == Some("failed") { failed_answers + 1 } else { 0 };
293                }
294                // One answer of "failed" can be the unit's last run, before the connection made the manager start it again. A start the
295                //  manager reports as under way is waited for until the start ceiling and no longer (owner, 2026-11-03: "nothing
296                //  should ever wait forever or indefinitely").
297                if failed_answers >= 2 || (cannot_ask && started.elapsed() >= config.start_wait) || started.elapsed() >= config.start_ceiling {
298                    return Err(ClientFailure::DidNotStart);
299                }
300            }
301            None => {
302                if started.elapsed() >= config.start_wait {
303                    return Err(ClientFailure::DidNotStart);
304                }
305            }
306        }
307        if !*announced && started.elapsed() >= START_NOTICE_GRACE {
308            *announced = true;
309            let _written = writeln!(notices, "{STARTING_NOTICE}");
310        }
311        std::thread::sleep(CONNECT_PAUSE);
312    }
313}
314
315/// What:
316///  Reaches a service that speaks this wrapper's protocol and was started from this wrapper's release, asking any other to
317///  retire first.
318/// Why:
319///   The manager keeps its socket across an upgrade or a downgrade, so a service from the other release may answer: one
320///  whose program was since removed, or one that behaves as the other release did. It is asked to finish its batch and
321///  exit, and the next connection makes the manager start the program the rewritten unit names. The asking is bounded by
322///  the start wait from the first ask (the same wait the manager's start gets), because the retiring service still accepts connections until it has exited, and
323///  each connection it accepts in that time is asked again. A service of a newer protocol cannot be asked (it refuses a
324///  message it cannot read as its own), so that ends the command.
325///
326/// In TS you'd write (pseudocode):
327/// ```ts
328/// const reader = await reachCurrent(config, notices, announced)
329/// ```
330fn reach_current(config: &ClientConfig, notices: &mut dyn Write, announced: &mut bool, trace: &mut ReachTrace, service_seen: bool) -> Result<BufReader<UnixStream>, ClientFailure> {
331    let began: Instant = Instant::now();
332    let reached = reach_current_untimed(config, notices, announced, trace, service_seen);
333    trace.elapsed += began.elapsed();
334    return reached;
335}
336
337/// `reach_current` without the clock around it.
338fn reach_current_untimed(config: &ClientConfig, notices: &mut dyn Write, announced: &mut bool, trace: &mut ReachTrace, service_seen: bool) -> Result<BufReader<UnixStream>, ClientFailure> {
339    let mut give_up_at: Option<Instant> = None;
340    loop {
341        let (mut reader, version, release) = reach(config, notices, announced, trace, service_seen)?;
342        if version == PROTOCOL_VERSION && release.as_deref() == Some(RELEASE) {
343            trace.answered_by = release;
344            return Ok(reader);
345        }
346        if version > PROTOCOL_VERSION {
347            return Err(ClientFailure::NoCommonVersion);
348        }
349        let deadline: Instant = *give_up_at.get_or_insert_with(|| {
350            let _written = writeln!(notices, "{UPDATING_NOTICE}");
351            return Instant::now() + config.start_wait;
352        });
353        if Instant::now() >= deadline {
354            return Err(ClientFailure::OtherRelease);
355        }
356        // Written in the version the service announced: a service of an earlier release reads a retire in no other.
357        let mut retire: String = encode_retire(version);
358        retire.push('\n');
359        let _sent = reader.get_mut().write_all(retire.as_bytes());
360        trace.retires_sent += 1;
361        std::thread::sleep(CONNECT_PAUSE * 4);
362    }
363}
364
365/// The user-facing failure for a code the service gave.
366pub fn failure_for(code: FailureCode, request: &CommitRequest) -> ClientFailure {
367    let repository: String = request.repository.display().to_string();
368    return match code {
369        FailureCode::RepositoryFull => ClientFailure::RepositoryFull(repository),
370        FailureCode::RepositoryReadOnly => ClientFailure::RepositoryReadOnly(repository),
371        FailureCode::IndexInUse => ClientFailure::IndexInUse(String::from("Another program")),
372        FailureCode::Rejected => ClientFailure::Refused,
373        FailureCode::BranchKeepsChanging => ClientFailure::BranchKeepsChanging {
374            branch: request.reference.trim_start_matches("refs/heads/").to_string(),
375            times: crate::service_land::LANDING_ATTEMPTS,
376        },
377        FailureCode::BranchMoved => ClientFailure::BranchMoved { branch: request.reference.trim_start_matches("refs/heads/").to_string() },
378        FailureCode::StepTooSlow => ClientFailure::StepTooSlow,
379        FailureCode::Unavailable => ClientFailure::Unavailable,
380    };
381}
382
383/// What:
384///  Sends a commit request and waits until it is answered.
385/// Why:
386///   The same identity goes with every send, so a service that landed the commit and died before answering reports it
387///  as already landed, and nothing lands twice.
388///
389/// In TS you'd write (pseudocode):
390/// ```ts
391/// await submit(config, request, notices)
392/// ```
393pub fn submit(config: &ClientConfig, request: &CommitRequest, notices: &mut dyn Write) -> Result<Submitted, ClientFailure> {
394    return submit_traced(config, request, notices, &mut SubmitTrace::default());
395}
396
397/// What:
398///  `submit`,
399/// leaving in `trace` how the service was reached and how long the answer took.
400/// Why:
401///   The wrapper's timing record states the tries,
402/// the retires and the releases of the reach,
403/// the queue positions the service
404///  reported and the time between the request being written and the answer;
405/// the trace is filled as the send proceeds,
406/// so a
407///  send that fails still reports what it did.
408///
409/// In TS you'd write (pseudocode):
410/// ```ts
411/// await submitTraced(config, request, notices, trace)
412/// ```
413pub fn submit_traced(config: &ClientConfig, request: &CommitRequest, notices: &mut dyn Write, trace: &mut SubmitTrace) -> Result<Submitted, ClientFailure> {
414    let began: Instant = Instant::now();
415    let answered = submit_loop(config, request, notices, trace);
416    trace.total += began.elapsed();
417    return answered;
418}
419
420/// The sends and the waits of `submit_traced`.
421///
422/// The wait for the answer has no clock: it lasts as long as the service keeps sending, and ends when the service goes
423///  silent for the silence bound. The request is then sent again with the same identity, so nothing lands twice, and the
424///  command ends only when every try has met silence or a closed connection.
425fn submit_loop(config: &ClientConfig, request: &CommitRequest, notices: &mut dyn Write, trace: &mut SubmitTrace) -> Result<Submitted, ClientFailure> {
426    let line: String = encode_client(&ClientMessage::Commit(Box::new(request.clone())));
427    let mut announced: bool = false;
428    let mut breaks: usize = 0;
429    let mut last_position: Option<usize> = None;
430    let mut holder: Option<String> = None;
431    let mut service_seen: bool = false;
432    let mut last_break_was_silence: bool = false;
433    // The scratch directory of a command that waits is renewed at once and then as often as the config says, whatever the
434    //  service sends, so a wait longer than the sweep's age never has its directory swept.
435    let waiting_since: Instant = Instant::now();
436    let mut last_blocker: Option<String> = None;
437    let mut last_renewed: Option<Instant> = None;
438    let mut renew_scratch = |settings: &ClientConfig| {
439        if let Some(fresh) = settings.keep_fresh.as_ref()
440            && last_renewed.is_none_or(|at| { return at.elapsed() >= fresh.every; })
441        {
442            crate::scratch_location::renew(fresh.path.as_path());
443            last_renewed = Some(Instant::now());
444        }
445    };
446    loop {
447        let mut reader: BufReader<UnixStream> = reach_current(config, notices, &mut announced, &mut trace.reach, service_seen)?;
448        service_seen = true;
449        let mut payload: String = line.clone();
450        payload.push('\n');
451        if reader.get_mut().write_all(payload.as_bytes()).is_err() {
452            breaks += 1;
453            trace.reconnects += 1;
454            if breaks > RECONNECTS {
455                return Err(ClientFailure::MayNotHaveLanded);
456            }
457            continue;
458        }
459        trace.sends += 1;
460        renew_scratch(config);
461        let written_at: Instant = Instant::now();
462        let answered: Option<Result<Submitted, ClientFailure>> = loop {
463            let heard: Heard = listen(&mut reader);
464            if matches!(heard, Heard::Message(_)) {
465                renew_scratch(config);
466            }
467            // The wait ends at the ceiling whatever the service sends: the request is withdrawn, and the answer to that is
468            //  the command's end (landed after all, or the error).
469            if waiting_since.elapsed() >= config.answer_ceiling && !matches!(heard, Heard::Message(ServiceMessage::Landed { .. } | ServiceMessage::RetryPrepare { .. } | ServiceMessage::Failed { .. })) {
470                trace.answer_wait += written_at.elapsed();
471                return withdraw(config, request.id.as_str(), last_blocker.take());
472            }
473            match heard {
474                Heard::Message(ServiceMessage::Position { number, of }) => {
475                    if last_position != Some(number) {
476                        last_position = Some(number);
477                        trace.positions.push(number);
478                        let _written = writeln!(notices, "{}", position_notice(number, of));
479                    }
480                }
481                Heard::Message(ServiceMessage::Landed { commit, already, .. }) => break Some(Ok(Submitted::Landed { commit, already })),
482                Heard::Message(ServiceMessage::RetryPrepare { base, landed, .. }) => break Some(Ok(Submitted::PrepareAgain { base, landed })),
483                Heard::Message(ServiceMessage::Failed { code: FailureCode::BranchMoved, .. }) => break Some(Ok(Submitted::Moved)),
484                Heard::Message(ServiceMessage::Failed { code: FailureCode::IndexInUse, .. }) => {
485                    break Some(Err(ClientFailure::IndexInUse(holder.take().unwrap_or_else(|| { return String::from("Another program"); }))));
486                }
487                Heard::Message(ServiceMessage::Failed { code, .. }) => break Some(Err(failure_for(code, request))),
488                Heard::Message(ServiceMessage::Waiting { text }) => {
489                    last_blocker = Some(text.trim().to_string());
490                    trace.waiting_notices += 1;
491                    trace.holder_kind = Some(holder_kind_of(text.as_str()));
492                    let _written = write!(notices, "{text}");
493                }
494                Heard::Message(ServiceMessage::Holder { who }) => holder = Some(who),
495                // Each message, this one too, restarts the silence bound; nothing else is needed.
496                Heard::Message(ServiceMessage::Welcome { .. } | ServiceMessage::Heartbeat | ServiceMessage::Withdrawn { .. }) => {}
497                Heard::Silent => {
498                    last_break_was_silence = true;
499                    break None;
500                }
501                Heard::Closed => {
502                    last_break_was_silence = false;
503                    break None;
504                }
505            }
506        };
507        trace.answer_wait += written_at.elapsed();
508        if let Some(done) = answered {
509            return done;
510        }
511        // The service went silent or the connection broke before an answer: the service died, hung or was replaced. Send the
512        //  same request again.
513        breaks += 1;
514        if breaks > RECONNECTS {
515            return Err(if last_break_was_silence { ClientFailure::ServiceSilent } else { ClientFailure::MayNotHaveLanded });
516        }
517        if last_break_was_silence {
518            let _written = writeln!(notices, "{SILENT_NOTICE}");
519        }
520        std::thread::sleep(CONNECT_PAUSE * u32::try_from(breaks).unwrap_or(1));
521    }
522}
523
524/// What:
525///  Withdraws the request after the answer ceiling: asks the service, on a connection of its own, to drop the request of this
526///  identity, and turns its answer into the command's end.
527/// Why:
528///   The owner's answer is that a wait that reaches its bound returns an error and the commit never lands later by itself. The
529///  service takes the withdrawal between two landings, so either the commit landed first (the answer is `Landed`, and the command
530///  succeeds) or it never will (`Withdrawn`). A service that does not answer within the withdrawal ceiling leaves it unknown.
531///
532/// In TS you'd write (pseudocode):
533/// ```ts
534/// const answer = await askToWithdraw(config, id); // 'landed' | 'withdrawn' | undefined
535/// ```
536fn withdraw(config: &ClientConfig, id: &str, blocker: Option<String>) -> Result<Submitted, ClientFailure> {
537    let minutes: u64 = config.answer_ceiling.as_secs() / 60;
538    let mut announced: bool = true;
539    let Ok(mut reader) = reach_current(config, &mut std::io::sink(), &mut announced, &mut ReachTrace::default(), true) else {
540        return Err(ClientFailure::WithdrawalUnconfirmed);
541    };
542    let mut asking: String = encode_client(&ClientMessage::Withdraw { id: id.to_string() });
543    asking.push('\n');
544    if reader.get_mut().write_all(asking.as_bytes()).is_err() {
545        return Err(ClientFailure::WithdrawalUnconfirmed);
546    }
547    let deadline: Instant = Instant::now() + config.withdraw_ceiling;
548    while Instant::now() < deadline {
549        // No read waits past the withdrawal's ceiling, whatever the silence bound says.
550        let _timeout = reader.get_ref().set_read_timeout(Some(deadline.saturating_duration_since(Instant::now()).max(Duration::from_millis(1)).min(config.heartbeat_silence)));
551        match listen(&mut reader) {
552            Heard::Message(ServiceMessage::Landed { commit, .. }) => return Ok(Submitted::Landed { commit, already: true }),
553            Heard::Message(ServiceMessage::Withdrawn { .. }) => return Err(ClientFailure::StillWithService { minutes, blocker }),
554            Heard::Message(_) => {}
555            Heard::Silent | Heard::Closed => return Err(ClientFailure::WithdrawalUnconfirmed),
556        }
557    }
558    return Err(ClientFailure::WithdrawalUnconfirmed);
559}
560
561/// What:
562///  Asks the service listening at `socket` to finish its batch and exit, when one answers; nothing else is waited for.
563/// Why:
564///   The single service of the earlier releases is replaced by one service per worktree. It is asked politely first, in the
565///  protocol version it announced, so that a batch it is landing is finished; the manager then stops its units. A socket
566///  nobody listens on, or a service that does not greet, is no one to ask.
567///
568/// In TS you'd write (pseudocode):
569/// ```ts
570/// await askToRetire(socket)
571/// ```
572pub fn ask_to_retire(socket: &std::path::Path) {
573    let Ok(stream) = UnixStream::connect(socket) else { return };
574    let _timeout = stream.set_read_timeout(Some(START_WAIT));
575    let mut reader: BufReader<UnixStream> = BufReader::new(stream);
576    let Some(ServiceMessage::Welcome { version, .. }) = read_message(&mut reader) else { return };
577    let mut retire: String = encode_retire(version);
578    retire.push('\n');
579    let _sent = reader.get_mut().write_all(retire.as_bytes());
580}
581
582/// A scratch directory handed to the service: the service removes it when this value is dropped, and when the process that
583///  holds it dies by any means, because the connection is the only thing that says the directory is still wanted.
584pub struct ScratchWatch {
585    /// The open connection. Close-on-exec, so no program the wrapper starts keeps it open after the wrapper is gone.
586    _connection: UnixStream,
587}
588
589/// What:
590///  Hands the commit's scratch directory to the service, which removes it when the connection closes.
591/// Why:
592///   A client killed without warning cannot remove what it made, and no one can tell afterwards whether it is gone or
593///  stopped: the open connection is the signal, without a process id and without a lock. The announcement is written at once
594///  and the greeting is not waited for, so a service that is frozen or still starting takes it when it reads, and a client
595///  killed meanwhile still loses its directory. A service that is not running takes nothing, and a service of another release
596///  refuses a message it does not know and closes nothing of the client's; in both the client removes the directory itself
597///  when it ends, as it always has.
598///
599/// In TS you'd write (pseudocode):
600/// ```ts
601/// const watch = watchScratch(config, gitDir, path) // undefined when nothing listens
602/// ```
603pub fn watch_scratch(config: &ClientConfig, git_dir: &std::path::Path, path: &std::path::Path) -> Option<ScratchWatch> {
604    let mut connection: UnixStream = connect(&config.address).ok()?;
605    let mut line: String = encode_client(&ClientMessage::Scratch { git_dir: git_dir.to_path_buf(), path: path.to_path_buf() });
606    line.push('\n');
607    connection.write_all(line.as_bytes()).ok()?;
608    return Some(ScratchWatch { _connection: connection });
609}
610
611/// What:
612///  Tells the service that work items were written for a repository, starting it through the operating system when it
613///  is not running, and returns once the service has taken the message.
614/// Why:
615///   The wrapper never starts the service or runs the work itself; the message is the only thing the service needs to
616///  look at the repository's work directory. The connection closes when the service has read the line, which is the
617///  confirmation that it will act.
618///
619/// In TS you'd write (pseudocode):
620/// ```ts
621/// await wake(config, gitDir, reviewKey)
622/// ```
623pub fn wake(config: &ClientConfig, git_dir: &std::path::Path, review_key: Option<&ReviewKey>, notices: &mut dyn Write) -> Result<(), ClientFailure> {
624    let mut line: String = encode_client(&ClientMessage::Work { git_dir: git_dir.to_path_buf(), review_key: review_key.cloned() });
625    line.push('\n');
626    let mut announced: bool = false;
627    let mut reader: BufReader<UnixStream> = reach_current(config, notices, &mut announced, &mut ReachTrace::default(), false)?;
628    if reader.get_mut().write_all(line.as_bytes()).is_err() {
629        return Err(ClientFailure::Unavailable);
630    }
631    // The service closes the connection after it has read the line.
632    while read_message(&mut reader).is_some() {}
633    return Ok(());
634}
635
636/// The client's bounds and how it reads the service's lines.
637#[cfg(test)]
638#[path = "service_client_tests.rs"]
639mod tests;