Skip to main content

git_policy_cli/
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 super::service_messages::{ClientFailure, Platform, STARTING_NOTICE, UPDATING_NOTICE, position_notice};
17use super::service_protocol::{
18    ClientMessage, CommitRequest, FailureCode, LandedCapture, PROTOCOL_VERSION, RELEASE, ServiceMessage, decode_service, encode_client, encode_retire,
19};
20use super::service_review_key::ReviewKey;
21use super::service_server::Bind;
22use std::io::{BufRead, BufReader, Write};
23use std::os::unix::net::UnixStream;
24use std::time::{Duration, Instant};
25
26/// How long the client waits for the operating system to start the service.
27pub const START_WAIT: Duration = Duration::from_secs(10);
28
29/// How long a start takes before the client says it is starting the service.
30pub const START_NOTICE_GRACE: Duration = Duration::from_secs(1);
31
32/// How long a commit waits in the queue before the client gives up and says so.
33pub const COMMIT_WAIT: Duration = Duration::from_secs(10 * 60);
34
35/// How many times a request is sent again after the connection broke before the client says it cannot be sure.
36pub const RECONNECTS: usize = 5;
37
38/// The pause between connection tries while the service starts.
39const CONNECT_PAUSE: Duration = Duration::from_millis(25);
40
41/// What the client may rely on the operating system to do.
42#[derive(Clone, Copy, Debug, Eq, PartialEq)]
43pub enum Activation {
44    /// The manager owns the socket and starts the service on demand.
45    Managed,
46    /// This platform cannot start the service on demand.
47    Unsupported(Platform),
48}
49
50/// What the client needs to reach the service.
51#[derive(Clone, Debug)]
52pub struct ClientConfig {
53    /// Where the service listens.
54    pub address: Bind,
55    /// What the operating system can do about a service that is not running.
56    pub activation: Activation,
57    /// Longest wait for a start.
58    pub start_wait: Duration,
59    /// Longest wait in the queue.
60    pub commit_wait: Duration,
61}
62
63/// What a request came to.
64#[derive(Clone, Debug, Eq, PartialEq)]
65pub enum Submitted {
66    /// The commit is on the branch.
67    Landed { commit: String, already: bool },
68    /// A named path changed on the branch: prepare again from this base and submit again with the same identity.
69    ///  `landed` tells when the bytes of the commits the service landed since were captured, for the ones it knows.
70    PrepareAgain { base: String, landed: Vec<LandedCapture> },
71    /// 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).
72    ///  The caller decides whether to build it again on the new tip or to stop.
73    Moved,
74}
75
76fn connect(address: &Bind) -> std::io::Result<UnixStream> {
77    return match address {
78        #[cfg(target_os = "linux")]
79        Bind::Abstract(name) => {
80            use std::os::linux::net::SocketAddrExt;
81            UnixStream::connect_addr(&std::os::unix::net::SocketAddr::from_abstract_name(name.as_bytes())?)
82        }
83        #[cfg(not(target_os = "linux"))]
84        Bind::Abstract(_) => Err(std::io::Error::other("abstract sockets need Linux")),
85        Bind::Path(path) => UnixStream::connect(path),
86        Bind::Inherited => Err(std::io::Error::other("a client does not inherit the socket")),
87    };
88}
89
90fn read_message(reader: &mut BufReader<UnixStream>) -> Option<ServiceMessage> {
91    let mut line: String = String::new();
92    return match reader.read_line(&mut line) {
93        Ok(read) if read > 0 => decode_service(line.trim_end_matches('\n')).ok(),
94        _ => None,
95    };
96}
97
98/// What:
99///  Connects, waiting for a start the operating system performs, and returns the stream with the service's version.
100/// Why:
101///   The wait is bounded and honest: one notice after the grace, then silence until the bound.
102///
103/// In TS you'd write (pseudocode):
104/// ```ts
105/// const { stream, version } = await reach(config, notices)
106/// ```
107fn reach(config: &ClientConfig, notices: &mut dyn Write, announced: &mut bool) -> Result<(BufReader<UnixStream>, u32, Option<String>), ClientFailure> {
108    let started: Instant = Instant::now();
109    loop {
110        match connect(&config.address) {
111            Ok(stream) => {
112                let _timeout = stream.set_read_timeout(Some(config.start_wait));
113                let mut reader: BufReader<UnixStream> = BufReader::new(stream);
114                if let Some(ServiceMessage::Welcome { version, release }) = read_message(&mut reader) {
115                    let _widened = reader.get_ref().set_read_timeout(Some(config.commit_wait));
116                    return Ok((reader, version, release));
117                }
118            }
119            Err(_) => match config.activation {
120                Activation::Unsupported(platform) => return Err(ClientFailure::NoActivation(platform)),
121                Activation::Managed => {}
122            },
123        }
124        if started.elapsed() >= config.start_wait {
125            return Err(ClientFailure::DidNotStart);
126        }
127        if !*announced && started.elapsed() >= START_NOTICE_GRACE {
128            *announced = true;
129            let _written = writeln!(notices, "{STARTING_NOTICE}");
130        }
131        std::thread::sleep(CONNECT_PAUSE);
132    }
133}
134
135/// What:
136///  Reaches a service that speaks this wrapper's protocol and was started from this wrapper's release, asking any other to
137///  retire first.
138/// Why:
139///   The manager keeps its socket across an upgrade or a downgrade, so a service from the other release may answer: one
140///  whose program was since removed, or one that behaves as the other release did. It is asked to finish its batch and
141///  exit, and the next connection makes the manager start the program the rewritten unit names. The asking is bounded by
142///  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
143///  each connection it accepts in that time is asked again. A service of a newer protocol cannot be asked (it refuses a
144///  message it cannot read as its own), so that ends the command.
145///
146/// In TS you'd write (pseudocode):
147/// ```ts
148/// const reader = await reachCurrent(config, notices, announced)
149/// ```
150fn reach_current(config: &ClientConfig, notices: &mut dyn Write, announced: &mut bool) -> Result<BufReader<UnixStream>, ClientFailure> {
151    let mut give_up_at: Option<Instant> = None;
152    loop {
153        let (mut reader, version, release) = reach(config, notices, announced)?;
154        if version == PROTOCOL_VERSION && release.as_deref() == Some(RELEASE) {
155            return Ok(reader);
156        }
157        if version > PROTOCOL_VERSION {
158            return Err(ClientFailure::NoCommonVersion);
159        }
160        let deadline: Instant = *give_up_at.get_or_insert_with(|| {
161            let _written = writeln!(notices, "{UPDATING_NOTICE}");
162            return Instant::now() + config.start_wait;
163        });
164        if Instant::now() >= deadline {
165            return Err(ClientFailure::OtherRelease);
166        }
167        // Written in the version the service announced: a service of an earlier release reads a retire in no other.
168        let mut retire: String = encode_retire(version);
169        retire.push('\n');
170        let _sent = reader.get_mut().write_all(retire.as_bytes());
171        std::thread::sleep(CONNECT_PAUSE * 4);
172    }
173}
174
175/// The user-facing failure for a code the service gave.
176pub fn failure_for(code: FailureCode, request: &CommitRequest) -> ClientFailure {
177    let repository: String = request.repository.display().to_string();
178    return match code {
179        FailureCode::RepositoryFull => ClientFailure::RepositoryFull(repository),
180        FailureCode::RepositoryReadOnly => ClientFailure::RepositoryReadOnly(repository),
181        FailureCode::IndexInUse => ClientFailure::IndexInUse(String::from("Another program")),
182        FailureCode::Rejected => ClientFailure::Refused,
183        FailureCode::BranchKeepsChanging => ClientFailure::BranchKeepsChanging {
184            branch: request.reference.trim_start_matches("refs/heads/").to_string(),
185            times: super::service_land::LANDING_ATTEMPTS,
186        },
187        FailureCode::BranchMoved => ClientFailure::BranchMoved { branch: request.reference.trim_start_matches("refs/heads/").to_string() },
188        FailureCode::Unavailable => ClientFailure::Unavailable,
189    };
190}
191
192/// What:
193///  Sends a commit request and waits until it is answered.
194/// Why:
195///   The same identity goes with every send, so a service that landed the commit and died before answering reports it
196///  as already landed, and nothing lands twice.
197///
198/// In TS you'd write (pseudocode):
199/// ```ts
200/// await submit(config, request, notices)
201/// ```
202pub fn submit(config: &ClientConfig, request: &CommitRequest, notices: &mut dyn Write) -> Result<Submitted, ClientFailure> {
203    let line: String = encode_client(&ClientMessage::Commit(Box::new(request.clone())));
204    let waiting_since: Instant = Instant::now();
205    let mut announced: bool = false;
206    let mut breaks: usize = 0;
207    let mut last_position: Option<usize> = None;
208    let mut holder: Option<String> = None;
209    loop {
210        if waiting_since.elapsed() >= config.commit_wait {
211            return Err(ClientFailure::WaitedTooLong { minutes: config.commit_wait.as_secs() / 60 });
212        }
213        let mut reader: BufReader<UnixStream> = reach_current(config, notices, &mut announced)?;
214        let mut payload: String = line.clone();
215        payload.push('\n');
216        if reader.get_mut().write_all(payload.as_bytes()).is_err() {
217            breaks += 1;
218            if breaks > RECONNECTS {
219                return Err(ClientFailure::MayNotHaveLanded);
220            }
221            continue;
222        }
223        loop {
224            match read_message(&mut reader) {
225                Some(ServiceMessage::Position { number, of }) => {
226                    if last_position != Some(number) {
227                        last_position = Some(number);
228                        let _written = writeln!(notices, "{}", position_notice(number, of));
229                    }
230                }
231                Some(ServiceMessage::Landed { commit, already, .. }) => return Ok(Submitted::Landed { commit, already }),
232                Some(ServiceMessage::RetryPrepare { base, landed, .. }) => return Ok(Submitted::PrepareAgain { base, landed }),
233                Some(ServiceMessage::Failed { code: FailureCode::BranchMoved, .. }) => return Ok(Submitted::Moved),
234                Some(ServiceMessage::Failed { code: FailureCode::IndexInUse, .. }) => {
235                    return Err(ClientFailure::IndexInUse(holder.take().unwrap_or_else(|| { return String::from("Another program"); })));
236                }
237                Some(ServiceMessage::Failed { code, .. }) => return Err(failure_for(code, request)),
238                Some(ServiceMessage::Waiting { text }) => {
239                    let _written = write!(notices, "{text}");
240                }
241                Some(ServiceMessage::Holder { who }) => holder = Some(who),
242                Some(ServiceMessage::Welcome { .. }) => {}
243                None => break,
244            }
245        }
246        // The connection broke before an answer: the service died or was replaced. Send the same request again.
247        breaks += 1;
248        if breaks > RECONNECTS {
249            return Err(ClientFailure::MayNotHaveLanded);
250        }
251        std::thread::sleep(CONNECT_PAUSE * u32::try_from(breaks).unwrap_or(1));
252    }
253}
254
255/// What:
256///  Asks the service listening at `socket` to finish its batch and exit, when one answers; nothing else is waited for.
257/// Why:
258///   The single service of the earlier releases is replaced by one service per worktree. It is asked politely first, in the
259///  protocol version it announced, so that a batch it is landing is finished; the manager then stops its units. A socket
260///  nobody listens on, or a service that does not greet, is no one to ask.
261///
262/// In TS you'd write (pseudocode):
263/// ```ts
264/// await askToRetire(socket)
265/// ```
266pub fn ask_to_retire(socket: &std::path::Path) {
267    let Ok(stream) = UnixStream::connect(socket) else { return };
268    let _timeout = stream.set_read_timeout(Some(START_WAIT));
269    let mut reader: BufReader<UnixStream> = BufReader::new(stream);
270    let Some(ServiceMessage::Welcome { version, .. }) = read_message(&mut reader) else { return };
271    let mut retire: String = encode_retire(version);
272    retire.push('\n');
273    let _sent = reader.get_mut().write_all(retire.as_bytes());
274}
275
276/// A scratch directory handed to the service: the service removes it when this value is dropped, and when the process that
277///  holds it dies by any means, because the connection is the only thing that says the directory is still wanted.
278pub struct ScratchWatch {
279    /// The open connection. Close-on-exec, so no program the wrapper starts keeps it open after the wrapper is gone.
280    _connection: UnixStream,
281}
282
283/// What:
284///  Hands the commit's scratch directory to the service, which removes it when the connection closes.
285/// Why:
286///   A client killed without warning cannot remove what it made, and no one can tell afterwards whether it is gone or
287///  stopped: the open connection is the signal, without a process id and without a lock. The announcement is written at once
288///  and the greeting is not waited for, so a service that is frozen or still starting takes it when it reads, and a client
289///  killed meanwhile still loses its directory. A service that is not running takes nothing, and a service of another release
290///  refuses a message it does not know and closes nothing of the client's; in both the client removes the directory itself
291///  when it ends, as it always has.
292///
293/// In TS you'd write (pseudocode):
294/// ```ts
295/// const watch = watchScratch(config, gitDir, path) // undefined when nothing listens
296/// ```
297pub fn watch_scratch(config: &ClientConfig, git_dir: &std::path::Path, path: &std::path::Path) -> Option<ScratchWatch> {
298    let mut connection: UnixStream = connect(&config.address).ok()?;
299    let mut line: String = encode_client(&ClientMessage::Scratch { git_dir: git_dir.to_path_buf(), path: path.to_path_buf() });
300    line.push('\n');
301    connection.write_all(line.as_bytes()).ok()?;
302    return Some(ScratchWatch { _connection: connection });
303}
304
305/// What:
306///  Tells the service that work items were written for a repository, starting it through the operating system when it
307///  is not running, and returns once the service has taken the message.
308/// Why:
309///   The wrapper never starts the service or runs the work itself; the message is the only thing the service needs to
310///  look at the repository's work directory. The connection closes when the service has read the line, which is the
311///  confirmation that it will act.
312///
313/// In TS you'd write (pseudocode):
314/// ```ts
315/// await wake(config, gitDir, reviewKey)
316/// ```
317pub fn wake(config: &ClientConfig, git_dir: &std::path::Path, review_key: Option<&ReviewKey>, notices: &mut dyn Write) -> Result<(), ClientFailure> {
318    let mut line: String = encode_client(&ClientMessage::Work { git_dir: git_dir.to_path_buf(), review_key: review_key.cloned() });
319    line.push('\n');
320    let mut announced: bool = false;
321    let mut reader: BufReader<UnixStream> = reach_current(config, notices, &mut announced)?;
322    if reader.get_mut().write_all(line.as_bytes()).is_err() {
323        return Err(ClientFailure::Unavailable);
324    }
325    // The service closes the connection after it has read the line.
326    while read_message(&mut reader).is_some() {}
327    return Ok(());
328}