Skip to main content

git_policy_cli/
service_server.rs

1//! What:
2//!  The resident service's loop: accept connections, queue requests in arrival order, land what is queued as a batch,
3//!  answer each client, and exit when told to retire.
4//! Why:
5//!  One writer lands every commit, so there is no lock to take, hold or wait for: order is the order of the queue, the
6//!  cost of the one durable write is shared by the batch, and a client that waits blocks on its socket instead of
7//!  polling (`doc/planning/cli-git-resident-service.md`). The service never starts itself: the operating system hands it
8//!  the listening socket (socket activation), or a development run binds one.
9//!
10//! In TS you'd write (pseudocode):
11//! ```ts
12//! for await (const batch of queue.batches()) { const outcomes = await landBatch(batch); for (...) reply(outcome); }
13//! ```
14
15use super::service_journal::{DONE_RETAINED, landed_commits, prune_done};
16use super::service_index_lock::Announce;
17use super::service_land::{LandContext, Outcome, land_batch_announcing, recover, recover_instance};
18use super::private_storage::remove_tree;
19use super::service_instance::instance_of;
20use super::service_work::{GitHandlers, Wake, run_round};
21use super::service_protocol::{
22    ClientMessage, CommitRequest, FailureCode, MAX_LINE_BYTES, PROTOCOL_VERSION, RELEASE, ServiceMessage, decode_client, encode_service,
23};
24use std::collections::HashMap;
25use std::io::{BufRead, BufReader, Read, Write};
26use std::os::unix::net::{UnixListener, UnixStream};
27use std::sync::atomic::{AtomicUsize, Ordering};
28use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel};
29use std::sync::Arc;
30use std::time::Duration;
31
32/// The most requests landed as one batch.
33pub const MAX_BATCH: usize = 64;
34
35/// How long a connection may take to send its request line before it is dropped.
36pub const REQUEST_READ_TIMEOUT: Duration = Duration::from_secs(10);
37
38/// How long the service waits with nothing to do before it exits; the manager's socket stays, so the next connection starts it
39///  again. Bazel's server does the same with `--max_idle_secs`, whose default is three hours, which is this value's precedent.
40pub const IDLE_EXIT: Duration = Duration::from_secs(3 * 60 * 60);
41
42/// File descriptor the service manager passes the listening socket on (`SD_LISTEN_FDS_START`).
43pub const INHERITED_DESCRIPTOR: i32 = 3;
44
45/// How a service run behaves apart from where it listens and what it lands.
46#[derive(Clone, Debug, Eq, PartialEq)]
47pub struct ServeSettings {
48    /// How long the service waits with nothing to do before it exits.
49    pub idle: Duration,
50    /// The release the service announces to every client. It is this build's release (`RELEASE`) except in a test that
51    ///  needs a service of another release.
52    pub release: String,
53    /// The worktree this instance serves, as `service_instance::instance_of` names it; every message about another worktree
54    ///  is refused. Nothing in a development run that serves any worktree.
55    pub instance: Option<String>,
56}
57
58impl ServeSettings {
59    /// The settings of an ordinary run: the given idle exit and this build's release.
60    pub fn new(idle: Duration) -> Self {
61        return Self { idle, release: String::from(RELEASE), instance: None };
62    }
63}
64
65/// Where the listening socket comes from.
66#[derive(Clone, Debug, Eq, PartialEq)]
67pub enum Bind {
68    /// A Linux abstract name: one binder at a time, gone with the process, no file to go stale.
69    Abstract(String),
70    /// A path in a private directory, for platforms without abstract names.
71    Path(std::path::PathBuf),
72    /// The socket the service manager opened and passed in.
73    Inherited,
74}
75
76/// What:
77///  Opens the listening socket.
78/// Why:
79///   Socket activation hands over a bound socket, which is the normal way; the others serve tests and development runs.
80///
81/// In TS you'd write (pseudocode):
82/// ```ts
83/// const listener = bind(address)
84/// ```
85pub fn bind(address: &Bind) -> std::io::Result<UnixListener> {
86    return match address {
87        #[cfg(target_os = "linux")]
88        Bind::Abstract(name) => {
89            use std::os::linux::net::SocketAddrExt;
90            let socket = std::os::unix::net::SocketAddr::from_abstract_name(name.as_bytes())?;
91            UnixListener::bind_addr(&socket)
92        }
93        #[cfg(not(target_os = "linux"))]
94        Bind::Abstract(_) => Err(std::io::Error::other("abstract sockets need Linux")),
95        Bind::Path(path) => bind_path(path),
96        Bind::Inherited => {
97            use std::os::fd::FromRawFd;
98            let announced_for: bool = std::env::var("LISTEN_PID").is_ok_and(|pid| { return pid == std::process::id().to_string(); });
99            let count: i32 = std::env::var("LISTEN_FDS").ok().and_then(|text| { return text.parse().ok(); }).unwrap_or(0);
100            if !announced_for || count < 1 {
101                return Err(std::io::Error::other("no socket was passed in"));
102            }
103            // SAFETY: the manager passed this descriptor to this process and nothing else in the process owns it.
104            Ok(unsafe { UnixListener::from_raw_fd(INHERITED_DESCRIPTOR) })
105        }
106    };
107}
108
109/// What:
110///  Binds a socket file, taking over one that no service listens on.
111/// Why:
112///   A service that was killed leaves its socket file behind, and the next bind of the same path then fails with
113///  "Address already in use" although nothing answers there. Only a socket that refuses a connection is replaced: one that
114///  answers belongs to a running service, and any other file is the person's. Two services started on one path at the same
115///  moment are the caller's to avoid (the service manager's socket, which production uses, never comes here).
116///
117/// In TS you'd write (pseudocode):
118/// ```ts
119/// try { return listen(path) } catch (inUse) { if (await refusesConnections(path)) { unlink(path); return listen(path) } throw inUse }
120/// ```
121fn bind_path(path: &std::path::Path) -> std::io::Result<UnixListener> {
122    use std::os::unix::fs::FileTypeExt;
123    let first: std::io::Error = match UnixListener::bind(path) {
124        Ok(listener) => return Ok(listener),
125        Err(error) if error.kind() == std::io::ErrorKind::AddrInUse => error,
126        Err(error) => return Err(error),
127    };
128    let is_socket: bool = std::fs::symlink_metadata(path).is_ok_and(|meta| { return meta.file_type().is_socket(); });
129    let refused: bool = matches!(UnixStream::connect(path), Err(error) if error.kind() == std::io::ErrorKind::ConnectionRefused);
130    if !is_socket || !refused {
131        return Err(first);
132    }
133    std::fs::remove_file(path)?;
134    return UnixListener::bind(path);
135}
136
137/// The user id of the process on the other end of a connection.
138fn peer_user(stream: &UnixStream) -> Option<u32> {
139    use std::os::fd::AsRawFd;
140    let mut credentials = libc::ucred { pid: 0, uid: 0, gid: 0 };
141    let mut length = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
142    // SAFETY: `credentials` and `length` are valid for the call and `length` is its size.
143    let status = unsafe {
144        libc::getsockopt(stream.as_raw_fd(), libc::SOL_SOCKET, libc::SO_PEERCRED, (&raw mut credentials).cast(), &raw mut length)
145    };
146    return if status == 0 { Some(credentials.uid) } else { None };
147}
148
149enum Job {
150    Commit(Box<CommitRequest>, UnixStream),
151    Retire,
152    /// After-commit work was announced; it only restarts the idle clock.
153    Activity,
154    /// A client that held a commit's scratch directory is gone; the directory is removed between batches, never during a
155    ///  landing that may read it.
156    Release(std::path::PathBuf),
157}
158
159/// Returns when the other end of the connection has closed it, or the connection failed. Anything the client sends is ignored.
160fn wait_for_close(stream: &UnixStream) {
161    let mut sink: [u8; 64] = [0; 64];
162    let mut reader = stream;
163    loop {
164        match reader.read(&mut sink) {
165            Ok(0) | Err(_) => return,
166            Ok(_) => {}
167        }
168    }
169}
170
171fn send(stream: &UnixStream, message: &ServiceMessage) {
172    let mut line: String = encode_service(message);
173    line.push('\n');
174    // A client that went away has nothing to be told.
175    let _written = (&*stream).write_all(line.as_bytes());
176}
177
178/// Reads one request line from a new connection, checks who sent it, and queues it.
179fn handle_connection(stream: UnixStream, queue: &Sender<Job>, work: &Sender<Wake>, busy: &AtomicUsize, release: &str, instance: Option<&str>) {
180    send(&stream, &ServiceMessage::Welcome { version: PROTOCOL_VERSION, release: Some(release.to_string()) });
181    // SAFETY: `geteuid` takes no arguments and cannot fail.
182    if peer_user(&stream) != Some(unsafe { libc::geteuid() }) {
183        return;
184    }
185    let _timeout = stream.set_read_timeout(Some(REQUEST_READ_TIMEOUT));
186    let Ok(reader_stream) = stream.try_clone() else { return };
187    let mut line: String = String::new();
188    let limit: u64 = u64::try_from(MAX_LINE_BYTES).unwrap_or(u64::MAX) + 1;
189    if BufReader::new(reader_stream.take(limit)).read_line(&mut line).is_err() {
190        return;
191    }
192    let _cleared = stream.set_read_timeout(None);
193    if line.is_empty() {
194        // A connection that only looked (a readiness probe) sends nothing and is not an error.
195        return;
196    }
197    // A message about another worktree is not this instance's to act on: each worktree has its own instance, so one that
198    //  reaches the wrong socket is a mistake of the sender's, refused where it can be seen.
199    let foreign = |git_dir: &std::path::Path| -> bool { return instance.is_some_and(|mine| { return instance_of(git_dir) != mine; }); };
200    match decode_client(line.trim_end_matches('\n')) {
201        Ok(ClientMessage::Commit(request)) if foreign(request.git_dir.as_path()) => {
202            eprintln!("cli-git-service: refused a commit for {}, which another instance serves", request.git_dir.display());
203            send(&stream, &ServiceMessage::Failed { id: request.id.clone(), code: FailureCode::Rejected });
204        }
205        Ok(ClientMessage::Scratch { git_dir, .. } | ClientMessage::Work { git_dir, .. }) if foreign(git_dir.as_path()) => {
206            eprintln!("cli-git-service: refused a message for {}, which another instance serves", git_dir.display());
207            send(&stream, &ServiceMessage::Failed { id: String::new(), code: FailureCode::Rejected });
208        }
209        Ok(ClientMessage::Commit(request)) => {
210            let _queued = queue.send(Job::Commit(request, stream));
211        }
212        Ok(ClientMessage::Retire) => {
213            let _queued = queue.send(Job::Retire);
214        }
215        Ok(ClientMessage::Scratch { git_dir, path }) => {
216            // The connection is the client's claim on the directory. While it is open the service is not idle, and when it
217            //  closes, by the client's end or its death, the directory is no one's.
218            busy.fetch_add(1, Ordering::SeqCst);
219            wait_for_close(&stream);
220            busy.fetch_sub(1, Ordering::SeqCst);
221            let _unused = git_dir;
222            let _queued = queue.send(Job::Release(path));
223        }
224        Ok(ClientMessage::Work { git_dir, review_key }) => {
225            let _queued = work.send((git_dir, review_key));
226            let _touched = queue.send(Job::Activity);
227        }
228        Err(reason) => {
229            eprintln!("cli-git-service: refused a request line: {reason}");
230            send(&stream, &ServiceMessage::Failed { id: String::new(), code: FailureCode::Rejected });
231        }
232    }
233}
234
235/// Finishes the open batches this instance owns: those of its worktree when it serves one, all of them in a development run.
236fn settle_open_batches(context: &LandContext, instance: Option<&str>) -> Vec<super::service_land::RecoveryReport> {
237    return match instance {
238        Some(mine) => recover_instance(context, mine),
239        None => recover(context),
240    };
241}
242
243/// Lands one group of jobs that share a branch, and answers each client.
244fn land_group(context: &LandContext, instance: Option<&str>, seq: &mut u64, group: Vec<(Box<CommitRequest>, UnixStream)>, landed: &mut HashMap<String, String>) {
245    let (again, pending): (Vec<_>, Vec<_>) = group.into_iter().partition(|(request, _)| { return landed.contains_key(&request.id); });
246    for (request, stream) in again {
247        send(&stream, &ServiceMessage::Landed { id: request.id.clone(), commit: landed[&request.id].clone(), already: true });
248    }
249    // The same request sent twice into one batch (a client that reconnected) is landed once and answered twice.
250    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
251    let (fresh, repeats): (Vec<_>, Vec<_>) = pending.into_iter().partition(|(request, _)| { return seen.insert(request.id.clone()); });
252    if fresh.is_empty() {
253        return;
254    }
255    // A batch whose branch moved but whose index update had to give up (another program held Git's index lock the whole
256    //  time) left its intent open; settling it first puts the index right before anything else changes it.
257    let _settled = settle_open_batches(context, instance);
258    *seq += 1;
259    for (index, (_, stream)) in fresh.iter().enumerate().skip(1) {
260        send(stream, &ServiceMessage::Position { number: index + 1, of: fresh.len() });
261    }
262    let requests: Vec<CommitRequest> = fresh.iter().map(|(request, _)| { return (**request).clone(); }).collect();
263    let announce = |note: Announce| {
264        for (_, stream) in &fresh {
265            match &note {
266                Announce::Waiting(text) => send(stream, &ServiceMessage::Waiting { text: text.clone() }),
267                Announce::Holder(who) => send(stream, &ServiceMessage::Holder { who: who.clone() }),
268            }
269        }
270    };
271    match land_batch_announcing(context, *seq, &requests, &announce) {
272        Ok(outcomes) => {
273            super::service_fault::reach("before-ack");
274            for ((request, _), outcome) in fresh.iter().zip(&outcomes) {
275                if let Outcome::Landed { commit } = outcome {
276                    for (repeat, stream) in repeats.iter().filter(|(repeat, _)| { return repeat.id == request.id; }) {
277                        send(stream, &ServiceMessage::Landed { id: repeat.id.clone(), commit: commit.clone(), already: true });
278                    }
279                }
280            }
281            for ((request, stream), outcome) in fresh.iter().zip(outcomes) {
282                match outcome {
283                    Outcome::Landed { commit } => {
284                        landed.insert(request.id.clone(), commit.clone());
285                        send(stream, &ServiceMessage::Landed { id: request.id.clone(), commit, already: false });
286                    }
287                    Outcome::RetryPrepare { base } => {
288                        let captures = super::service_captures::remembered(request.common_dir.as_path(), request.repository.as_path());
289                        send(stream, &ServiceMessage::RetryPrepare { id: request.id.clone(), base, landed: captures });
290                    }
291                    Outcome::BranchMoved => send(stream, &ServiceMessage::Failed { id: request.id.clone(), code: FailureCode::BranchMoved }),
292                }
293            }
294        }
295        Err(code) => {
296            for (request, stream) in &fresh {
297                send(stream, &ServiceMessage::Failed { id: request.id.clone(), code });
298            }
299        }
300    }
301}
302
303/// What:
304///  Runs the after-commit work of each repository named, one repository at a time, folding wakes that arrive while it
305///  works into the next round.
306/// Why:
307///   Draining claims everything pending, so a burst of wakes for one repository is one pass.
308///
309/// In TS you'd write (pseudocode):
310/// ```ts
311/// for await (const dir of wakes) await drain(dir, handlers)
312/// ```
313fn work_loop(receiver: &Receiver<Wake>, handlers: &GitHandlers, busy: &AtomicUsize) {
314    while let Ok(first) = receiver.recv() {
315        busy.fetch_add(1, Ordering::SeqCst);
316        let wakes: Vec<Wake> = std::iter::once(first).chain(std::iter::from_fn(|| { return receiver.try_recv().ok(); })).collect();
317        run_round(wakes, handlers, std::time::SystemTime::now());
318        busy.fetch_sub(1, Ordering::SeqCst);
319    }
320}
321
322/// What:
323///  Runs the service until it is told to retire.
324/// Why:
325///   Recovery runs before the first connection is accepted; then the loop takes everything queued as one batch, groups it
326///  by branch in order of first arrival, lands each group, and answers.
327///
328/// In TS you'd write (pseudocode):
329/// ```ts
330/// await serve(listener, context)
331/// ```
332pub fn serve(listener: UnixListener, context: &LandContext, settings: &ServeSettings) {
333    let idle: Duration = settings.idle;
334    let _reports = settle_open_batches(context, settings.instance.as_deref());
335    // The memory of landed requests is bounded: the oldest finished batches go before the rest are read.
336    let pruned: usize = prune_done(context.journal.as_path(), DONE_RETAINED);
337    if pruned > 0 {
338        eprintln!("cli-git-service: removed the records of {pruned} old finished batches from {}", context.journal.display());
339    }
340    let mut landed: HashMap<String, String> = landed_commits(context.journal.as_path());
341    let (sender, receiver): (Sender<Job>, Receiver<Job>) = channel();
342    let acceptor_queue: Sender<Job> = sender.clone();
343    // After-commit work (push, upkeep) runs on its own thread, so a slow network never delays a landing.
344    let (work_sender, work_receiver): (Sender<Wake>, Receiver<Wake>) = channel();
345    let handlers: GitHandlers = GitHandlers::new(context.git.clone());
346    let busy: Arc<AtomicUsize> = Arc::new(AtomicUsize::new(0));
347    let worker_busy: Arc<AtomicUsize> = Arc::clone(&busy);
348    std::thread::spawn(move || { work_loop(&work_receiver, &handlers, &worker_busy); });
349    let announced_release: String = settings.release.clone();
350    let connection_busy: Arc<AtomicUsize> = Arc::clone(&busy);
351    let instance: Option<String> = settings.instance.clone();
352    std::thread::spawn(move || {
353        for connection in listener.incoming().flatten() {
354            let queue: Sender<Job> = acceptor_queue.clone();
355            let work: Sender<Wake> = work_sender.clone();
356            let release: String = announced_release.clone();
357            let counted: Arc<AtomicUsize> = Arc::clone(&connection_busy);
358            let mine: Option<String> = instance.clone();
359            std::thread::spawn(move || { handle_connection(connection, &queue, &work, &counted, release.as_str(), mine.as_deref()); });
360        }
361    });
362    // Microseconds, so that instances started at nearly the same time do not number their batches alike in a shared journal.
363    let mut seq: u64 = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(1, |elapsed| { return u64::try_from(elapsed.as_micros()).unwrap_or(1); });
364    let mut retiring: bool = false;
365    while !retiring {
366        let first: Job = match receiver.recv_timeout(idle) {
367            Ok(job) => job,
368            // Work in flight keeps the service; otherwise it exits and the manager starts it on the next connection.
369            Err(RecvTimeoutError::Timeout) if busy.load(Ordering::SeqCst) > 0 => continue,
370            Err(_) => return,
371        };
372        let mut jobs: Vec<Job> = vec![first];
373        while jobs.len() < MAX_BATCH {
374            match receiver.try_recv() {
375                Ok(job) => jobs.push(job),
376                Err(_) => break,
377            }
378        }
379        // Branches in order of first arrival; within a branch, arrival order.
380        let mut groups: Vec<((std::path::PathBuf, String, bool), Vec<(Box<CommitRequest>, UnixStream)>)> = Vec::new();
381        let mut releases: Vec<std::path::PathBuf> = Vec::new();
382        for job in jobs {
383            match job {
384                Job::Retire => retiring = true,
385                Job::Activity => {}
386                Job::Release(path) => releases.push(path),
387                Job::Commit(request, stream) => {
388                    // An amend is a group of its own, and what arrives after it starts another group, so the order on
389                    //  one branch is the order of arrival.
390                    // `HEAD` is a head of one worktree, so two detached worktrees of one repository are two branches.
391                    let queue_reference: String = if request.reference == "HEAD" {
392                        format!("HEAD@{}", request.repository.display())
393                    } else {
394                        request.reference.clone()
395                    };
396                    let key = (request.common_dir.clone(), queue_reference, request.lands_alone());
397                    let joins = groups.iter_mut().rev().find(|((common, reference, _), _)| { return *common == key.0 && *reference == key.1; });
398                    match joins {
399                        Some((existing, members)) if !key.2 && !existing.2 => members.push((request, stream)),
400                        _ => groups.push((key, vec![(request, stream)])),
401                    }
402                }
403            }
404        }
405        for (_, group) in groups {
406            land_group(context, settings.instance.as_deref(), &mut seq, group, &mut landed);
407        }
408        for path in releases {
409            if let Err(error) = remove_tree(path.as_path()) {
410                eprintln!("cli-git-service: the scratch directory {} could not be removed: {error}", path.display());
411            }
412        }
413    }
414}
415
416/// Socket controls stay out of the release executable.
417#[cfg(test)]
418#[path = "service_server_tests.rs"]
419mod tests;