Skip to main content

git_policy_cli/service/
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 crate::service_journal::{BatchClaim, DONE_RETAINED, Recovery, claim_batch, landed_commits, prune_done};
16use crate::service_land_follow::storage_failure;
17use crate::service_index_lock::{Announce, unsettled_locks};
18use crate::service_index_prestage::{PrestageGuard, start as start_prestage};
19use crate::service_captures::CaptureMemory;
20use crate::service_land::{LandContext, Outcome, land_batch_timed, recover, recover_instance};
21use crate::journald_native::Priority;
22use crate::service_timing::{Answered, Arrival, ExitReason, LandTiming, answered_line, exit_line, log, log_entry, retire_line};
23use crate::private_storage::remove_tree;
24use crate::service_instance::instance_of;
25use crate::claim_time::ClaimTime;
26use crate::service_retry::RetrySchedule;
27use crate::push_retry::{PLAN_DIRECTORY, PushRetries};
28use crate::service_work::{GitHandlers, Wake, run_round};
29use crate::service_reply::{Reply, write_until_answered};
30use crate::service_protocol::{
31    ClientMessage, CommitRequest, FailureCode, HEARTBEAT_EVERY, MAX_LINE_BYTES, PROTOCOL_VERSION, RELEASE, ServiceMessage, decode_client, encode_service,
32};
33use std::collections::HashMap;
34use std::io::{BufRead, BufReader, Read, Write};
35use std::os::unix::net::{UnixListener, UnixStream};
36use std::sync::atomic::{AtomicUsize, Ordering};
37use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel};
38use std::sync::Arc;
39use std::path::PathBuf;
40use std::time::{Duration, Instant};
41
42/// The largest batch whose landing still costs about what its size predicts: 256. Measured with the service binary on throwaway
43///  repositories, 2026-11-03, bursts of simultaneous commit requests (`MAX_BATCH` raised to 4096 for the probe, three rounds
44///  alternating over 64, 128, 256, 512 and 1024 clients, other sessions running, a debug build): a landing took 71 to 76 ms for
45///  62 to 63 requests, 82 to 85 ms for 126, 104 to 109 ms for 253 to 255, 193 to 204 ms for 509 to 511 (once 2,002 ms, a host stall)
46///  and 525 to 547 ms for 1,021 to 1,023. The cost of each added request is 0.16 ms up to 254 requests, 0.36 ms from there to
47///  510, and 0.66 ms to 1,022, so the cost per request has not yet doubled at 256. The time a client waits for a burst of 128 was
48///  176 to 206 ms in one landing and 243 to 249 ms in three at the old cap of 64.
49pub const BATCH_COST_KNEE: usize = 256;
50
51/// The most requests landed as one batch: `BATCH_COST_KNEE`. A batch is answered all at once and holds the index lock while it
52///  lands, so the cap bounds both. The prototype's burst reached 64, and production never reached more than one request in a
53///  batch (1,302 answered requests, 2026-11-02T09:01:38Z to 2026-11-03T15:11:58Z), so the cap bites only in a burst. Option B of the
54///  batch size question, picked by the coordinator under the owner's delegation, open to the owner's veto
55///  (`doc/planning/cli-git-shipped-limits-audit.md`, "Picked for these follow-ups").
56pub const MAX_BATCH: usize = BATCH_COST_KNEE;
57
58/// How long a connection may take to send its request line before it is dropped.
59pub const REQUEST_READ_TIMEOUT: Duration = Duration::from_secs(10);
60
61/// How long the service waits with nothing to do before it exits; the manager's socket stays, so the next connection starts it
62///  again. Bazel's server does the same with `--max_idle_secs`, whose default is three hours, which is this value's precedent.
63///  Measured cost of exceeding it: of 1,051 commits in the commit timing log (2026-11-02T09:01:37Z to 2026-11-03T15:10:12Z), the 10
64///  that followed an idle gap of more than three hours reached the service in at most 70 ms (`reachMs`) after a start wait of at
65///  most 47 ms (`startWaitMs`); 110 idle exits happened in that window. The 28 running services held 212 MiB together (7.9 MiB each,
66///  `systemctl --user show --property=MemoryCurrent`). A shorter exit would trade at most that start for that memory; the owner's
67///  bound is that a commit should not take 5 s longer than native Git (`SPEC.md`). Kept at three hours as the coordinator's pick under the owner's delegation, open to the owner's veto (`doc/planning/cli-git-shipped-limits-audit.md`, "Sizes and ages of the service's own housekeeping").
68pub const IDLE_EXIT: Duration = Duration::from_secs(3 * 60 * 60);
69
70/// File descriptor the service manager passes the listening socket on (`SD_LISTEN_FDS_START`).
71pub const INHERITED_DESCRIPTOR: i32 = 3;
72
73/// How a service run behaves apart from where it listens and what it lands.
74#[derive(Clone, Debug, Eq, PartialEq)]
75pub struct ServeSettings {
76    /// How long the service waits with nothing to do before it exits.
77    pub idle: Duration,
78    /// The release the service announces to every client. It is this build's release (`RELEASE`) except in a test that
79    ///  needs a service of another release.
80    pub release: String,
81    /// The worktree this instance serves, as `service_instance::instance_of` names it; every message about another worktree
82    ///  is refused. Nothing in a development run that serves any worktree.
83    pub instance: Option<String>,
84}
85
86impl ServeSettings {
87    /// The settings of an ordinary run: the given idle exit and this build's release.
88    pub fn new(idle: Duration) -> Self {
89        return Self { idle, release: String::from(RELEASE), instance: None };
90    }
91}
92
93/// Where the listening socket comes from.
94#[derive(Clone, Debug, Eq, PartialEq)]
95pub enum Bind {
96    /// A Linux abstract name: one binder at a time, gone with the process, no file to go stale.
97    Abstract(String),
98    /// A path in a private directory, for platforms without abstract names.
99    Path(std::path::PathBuf),
100    /// The socket the service manager opened and passed in.
101    Inherited,
102}
103
104/// What:
105///  Opens the listening socket.
106/// Why:
107///   Socket activation hands over a bound socket, which is the normal way; the others serve tests and development runs.
108///
109/// In TS you'd write (pseudocode):
110/// ```ts
111/// const listener = bind(address)
112/// ```
113pub fn bind(address: &Bind) -> std::io::Result<UnixListener> {
114    return match address {
115        #[cfg(target_os = "linux")]
116        Bind::Abstract(name) => {
117            use std::os::linux::net::SocketAddrExt;
118            let socket = std::os::unix::net::SocketAddr::from_abstract_name(name.as_bytes())?;
119            UnixListener::bind_addr(&socket)
120        }
121        #[cfg(not(target_os = "linux"))]
122        Bind::Abstract(_) => Err(std::io::Error::other("abstract sockets need Linux")),
123        Bind::Path(path) => bind_path(path),
124        Bind::Inherited => {
125            use std::os::fd::FromRawFd;
126            ensure_socket_passed_in(std::env::var("LISTEN_PID").ok().as_deref(), std::env::var("LISTEN_FDS").ok().as_deref(), std::process::id())?;
127            // SAFETY: the manager passed this descriptor to this process and nothing else in the process owns it.
128            Ok(unsafe { UnixListener::from_raw_fd(INHERITED_DESCRIPTOR) })
129        }
130    };
131}
132
133/// What:
134///  Checks the service manager's socket-activation variables:
135/// `listen_pid` must name this process (`own_pid`) and
136///  `listen_fds` must count at least one descriptor.
137/// Why:
138///   The descriptor the manager passes is taken over as the listening socket,
139/// so a variable set for another process,
140/// or a
141///  count of none,
142/// must be refused instead of adopting a descriptor that was never passed to this process.
143///
144/// In TS you'd write (pseudocode):
145/// ```ts
146/// if (listenPid !== String(ownPid) || !(Number.parseInt(listenFds ?? '0') >= 1)) { throw new Error('no socket was passed in') }
147/// ```
148fn ensure_socket_passed_in(listen_pid: Option<&str>, listen_fds: Option<&str>, own_pid: u32) -> std::io::Result<()> {
149    let announced_for: bool = listen_pid.is_some_and(|pid| { return pid == own_pid.to_string(); });
150    let count: i32 = listen_fds.and_then(|text| { return text.parse().ok(); }).unwrap_or(0);
151    if !announced_for || count < 1 {
152        return Err(std::io::Error::other("no socket was passed in"));
153    }
154    return Ok(());
155}
156
157/// What:
158///  Binds a socket file, taking over one that no service listens on.
159/// Why:
160///   A service that was killed leaves its socket file behind, and the next bind of the same path then fails with
161///  "Address already in use" although nothing answers there. Only a socket that refuses a connection is replaced: one that
162///  answers belongs to a running service, and any other file is the person's. Two services started on one path at the same
163///  moment are the caller's to avoid (the service manager's socket, which production uses, never comes here).
164///
165/// In TS you'd write (pseudocode):
166/// ```ts
167/// try { return listen(path) } catch (inUse) { if (await refusesConnections(path)) { unlink(path); return listen(path) } throw inUse }
168/// ```
169fn bind_path(path: &std::path::Path) -> std::io::Result<UnixListener> {
170    use std::os::unix::fs::FileTypeExt;
171    let first: std::io::Error = match UnixListener::bind(path) {
172        Ok(listener) => return Ok(listener),
173        Err(error) if error.kind() == std::io::ErrorKind::AddrInUse => error,
174        Err(error) => return Err(error),
175    };
176    let is_socket: bool = std::fs::symlink_metadata(path).is_ok_and(|meta| { return meta.file_type().is_socket(); });
177    let refused: bool = matches!(UnixStream::connect(path), Err(error) if error.kind() == std::io::ErrorKind::ConnectionRefused);
178    if !is_socket || !refused {
179        return Err(first);
180    }
181    std::fs::remove_file(path)?;
182    return UnixListener::bind(path);
183}
184
185/// The user id of the process on the other end of a connection.
186fn peer_user(stream: &UnixStream) -> Option<u32> {
187    use std::os::fd::AsRawFd;
188    let mut credentials = libc::ucred { pid: 0, uid: 0, gid: 0 };
189    let mut length = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
190    // SAFETY: `credentials` and `length` are valid for the call and `length` is its size.
191    let status = unsafe {
192        libc::getsockopt(stream.as_raw_fd(), libc::SOL_SOCKET, libc::SO_PEERCRED, (&raw mut credentials).cast(), &raw mut length)
193    };
194    return if status == 0 { Some(credentials.uid) } else { None };
195}
196
197/// A request waiting to be landed:
198/// what the client sent,
199/// the connection to answer it on,
200/// and how it arrived.
201type Queued = (Box<CommitRequest>, Reply, Arrival);
202
203/// What a landing group shares:
204/// the common Git directory,
205/// the queue reference,
206/// and whether its request lands alone.
207type GroupKey = (std::path::PathBuf, String, bool);
208
209/// What:
210///  Puts `member` into the latest group of its common Git directory and queue reference,
211/// or into a group of its own when
212///  it lands alone,
213/// when that group's request does,
214/// or when no group of that branch exists yet.
215/// Why:
216///   Requests of one branch that may share a batch land together and in arrival order;
217/// an amend is a group of its own and
218///  what arrives after it starts another group,
219/// so the order on one branch is the order of arrival,
220/// and a request never
221///  lands in a batch of another branch.
222///
223/// In TS you'd write (pseudocode):
224/// ```ts
225/// const joined = groups.findLast((group) => group.common === key.common && group.reference === key.reference)
226/// if (joined && !key.alone && !joined.alone) { joined.members.push(member) } else { groups.push({ key, members: [member] }) }
227/// ```
228fn place_in_groups<T>(groups: &mut Vec<(GroupKey, Vec<T>)>, key: GroupKey, member: T) {
229    let joins = groups.iter_mut().rev().find(|((common, reference, _), _)| { return *common == key.0 && *reference == key.1; });
230    match joins {
231        Some((existing, members)) if !key.2 && !existing.2 => members.push(member),
232        _ => groups.push((key, vec![member])),
233    }
234}
235
236enum Job {
237    Commit(Box<CommitRequest>, Reply, Arrival),
238    Retire,
239    /// The client stopped waiting for the commit of this identity (its ceiling passed): answered with the landed commit, or
240    ///  withdrawn so that it never lands.
241    Withdraw(String, Reply),
242    /// After-commit work was announced; it only restarts the idle clock.
243    Activity,
244    /// A client that held a commit's scratch directory is gone; the directory is removed between batches, never during a
245    ///  landing that may read it.
246    Release(std::path::PathBuf),
247}
248
249/// Returns when the other end of the connection has closed it, or the connection failed. Anything the client sends is ignored.
250fn wait_for_close(stream: &UnixStream) {
251    let mut sink: [u8; 64] = [0; 64];
252    let mut reader = stream;
253    loop {
254        match reader.read(&mut sink) {
255            Ok(0) | Err(_) => return,
256            Ok(_) => {}
257        }
258    }
259}
260
261fn send(stream: &UnixStream, message: &ServiceMessage) {
262    let mut line: String = encode_service(message);
263    line.push('\n');
264    // A client that went away has nothing to be told.
265    let _written = (&*stream).write_all(line.as_bytes());
266}
267
268/// Starts a thread the service cannot do without, or ends the service with a plain line and status 4: a service that goes on
269///  without its acceptor or its work thread answers no one, while an ended service is started again by the manager.
270fn start_thread_or_exit(what: &str, body: impl FnOnce() + Send + 'static) {
271    if let Err(error) = std::thread::Builder::new().spawn(body) {
272        crate::service_error!("cannot start the thread for {what}: {error}");
273        std::process::exit(4);
274    }
275}
276
277/// How many withdrawn identities the service remembers before it forgets them all: the same count as the finished batches it
278///  remembers (`DONE_RETAINED`), since a client that withdrew sends nothing more for its request.
279const WITHDRAWN_RETAINED: usize = DONE_RETAINED;
280
281/// How long the acceptor waits after a connection it could not give a thread.
282const ACCEPT_BACKOFF: Duration = Duration::from_millis(100);
283
284/// Reads one request line from a new connection, checks who sent it, and queues it.
285fn handle_connection(stream: UnixStream, queue: &Sender<Job>, work: &Sender<Wake>, busy: &AtomicUsize, release: &str, instance: Option<&str>) {
286    let accepted: Instant = Instant::now();
287    send(&stream, &ServiceMessage::Welcome { version: PROTOCOL_VERSION, release: Some(release.to_string()) });
288    // SAFETY: `geteuid` takes no arguments and cannot fail.
289    if peer_user(&stream) != Some(unsafe { libc::geteuid() }) {
290        return;
291    }
292    let _timeout = stream.set_read_timeout(Some(REQUEST_READ_TIMEOUT));
293    let Ok(reader_stream) = stream.try_clone() else { return };
294    let mut line: String = String::new();
295    let limit: u64 = u64::try_from(MAX_LINE_BYTES).unwrap_or(u64::MAX) + 1;
296    if BufReader::new(reader_stream.take(limit)).read_line(&mut line).is_err() {
297        return;
298    }
299    let _cleared = stream.set_read_timeout(None);
300    if line.is_empty() {
301        // A connection that only looked (a readiness probe) sends nothing and is not an error.
302        return;
303    }
304    // A message about another worktree is not this instance's to act on: each worktree has its own instance, so one that
305    //  reaches the wrong socket is a mistake of the sender's, refused where it can be seen.
306    let foreign = |git_dir: &std::path::Path| -> bool { return instance.is_some_and(|mine| { return instance_of(git_dir) != mine; }); };
307    match decode_client(line.trim_end_matches('\n')) {
308        Ok(ClientMessage::Commit(request)) if foreign(request.git_dir.as_path()) => {
309            crate::service_warn!("refused a commit for {}, which another instance serves", request.git_dir.display());
310            send(&stream, &ServiceMessage::Failed { id: request.id.clone(), code: FailureCode::Rejected });
311        }
312        Ok(ClientMessage::Scratch { git_dir, .. } | ClientMessage::Work { git_dir, .. }) if foreign(git_dir.as_path()) => {
313            crate::service_warn!("refused a message for {}, which another instance serves", git_dir.display());
314            send(&stream, &ServiceMessage::Failed { id: String::new(), code: FailureCode::Rejected });
315        }
316        Ok(ClientMessage::Commit(request)) => {
317            let id: String = request.id.clone();
318            let (reply, messages) = Reply::new();
319            let _queued = queue.send(Job::Commit(request, reply, Arrival { accepted, read: accepted.elapsed() }));
320            crate::service_fault::queued(id.as_str());
321            // This thread has nothing else to do until the request is answered, so it writes the answers the landing thread
322            //  queues and keeps the client told that the service lives.
323            write_until_answered(&stream, &messages, HEARTBEAT_EVERY);
324        }
325        Ok(ClientMessage::Withdraw { id }) => {
326            // The landing thread answers between two landings, so the answer is either that the commit landed or that it never
327            //  will; meanwhile this thread keeps the client told that the service lives.
328            let (reply, messages) = Reply::new();
329            let _queued = queue.send(Job::Withdraw(id, reply));
330            write_until_answered(&stream, &messages, HEARTBEAT_EVERY);
331        }
332        Ok(ClientMessage::Retire) => {
333            log(retire_line(release).as_str());
334            let _queued = queue.send(Job::Retire);
335        }
336        Ok(ClientMessage::Scratch { git_dir, path }) => {
337            // The connection is the client's claim on the directory. While it is open the service is not idle, and when it
338            //  closes, by the client's end or its death, the directory is no one's.
339            busy.fetch_add(1, Ordering::SeqCst);
340            wait_for_close(&stream);
341            busy.fetch_sub(1, Ordering::SeqCst);
342            let _unused = git_dir;
343            let _queued = queue.send(Job::Release(path));
344        }
345        Ok(ClientMessage::Work { git_dir, review_key }) => {
346            let _queued = work.send((git_dir, review_key));
347            let _touched = queue.send(Job::Activity);
348        }
349        Err(reason) => {
350            crate::service_warn!("refused a request line: {reason}");
351            send(&stream, &ServiceMessage::Failed { id: String::new(), code: FailureCode::Rejected });
352        }
353    }
354}
355
356/// Finishes the open batches this instance owns: those of its worktree when it serves one, all of them in a development run.
357fn settle_open_batches(context: &LandContext, instance: Option<&str>) -> Vec<crate::service_land::RecoveryReport> {
358    let reports: Vec<crate::service_land::RecoveryReport> = match instance {
359        Some(mine) => recover_instance(context, mine),
360        None => recover(context),
361    };
362    // An open batch means an earlier service stopped between its intent and its end; each one settled is said.
363    for report in &reports {
364        log_entry(
365            Priority::Warning,
366            format!("settled the batch an earlier service left open batch={} decision={}", report.seq, if report.decision == Recovery::Finish { "finish" } else { "drop" }).as_str(),
367            &[("CLI_GIT_BATCH", report.seq.to_string())],
368        );
369    }
370    return reports;
371}
372
373/// The times of one batch that every request of it shares,
374/// and the moment the landing ended.
375struct BatchTimes {
376    /// The batch number,
377    /// zero when no batch ran (a request answered as already landed).
378    batch: u64,
379    /// How many requests of the branch the batch held.
380    size: usize,
381    /// When the group began to be handled,
382    /// which ends every request's wait in the queue.
383    group_began: Instant,
384    /// Time to settle the batches a killed service left open.
385    settle: Duration,
386    /// The phases of the landing.
387    landing: LandTiming,
388    /// Time the landing took,
389    /// from its start to its return.
390    land_total: Duration,
391    /// When the landing returned,
392    /// which starts the answers.
393    landed_at: Instant,
394}
395
396impl BatchTimes {
397    /// The times of a request that no batch landed.
398    fn not_landed(group_began: Instant) -> Self {
399        return Self { batch: 0, size: 0, group_began, settle: Duration::ZERO, landing: LandTiming::default(), land_total: Duration::ZERO, landed_at: Instant::now() };
400    }
401}
402
403/// Writes the log line for an answered request:
404/// the phases of its wait,
405/// from the acceptance of its connection to the answer.
406fn log_answer(times: &BatchTimes, request: &CommitRequest, arrival: &Arrival, position: usize, outcome: &str) {
407    let queued: Duration = times.group_began.saturating_duration_since(arrival.accepted + arrival.read);
408    // What the Git steps and tools since the previous answer showed; the answer that finds them takes them.
409    let quiet: Vec<(String, Duration)> = crate::quiet_ledger::drain();
410    let line: String = answered_line(&Answered {
411        request: request.id.as_str(),
412        reference: request.reference.as_str(),
413        outcome,
414        batch: times.batch,
415        size: times.size,
416        position,
417        arrival: *arrival,
418        queued,
419        settle: times.settle,
420        landing: &times.landing,
421        land_total: times.land_total,
422        answer: times.landed_at.elapsed(),
423        total: arrival.accepted.elapsed(),
424        quiet: quiet.as_slice(),
425    });
426    // A request that was answered with a failure is a warning, so `journalctl --priority=warning` finds the commits that failed.
427    let priority: Priority = if outcome.starts_with("failed") { Priority::Warning } else { Priority::Info };
428    let fields: [(&str, String); 4] = [
429        ("CLI_GIT_REQUEST_ID", request.id.clone()),
430        ("CLI_GIT_BRANCH", request.reference.clone()),
431        ("CLI_GIT_OUTCOME", outcome.to_string()),
432        ("CLI_GIT_BATCH", times.batch.to_string()),
433    ];
434    log_entry(priority, line.as_str(), &fields);
435}
436
437/// Lands one group of jobs that share a branch, and answers each client.
438fn land_group(context: &LandContext, instance: Option<&str>, seq: &mut u64, group: Vec<Queued>, landed: &mut HashMap<String, String>, captures: &mut CaptureMemory) {
439    let group_began: Instant = Instant::now();
440    let (again, pending): (Vec<_>, Vec<_>) = group.into_iter().partition(|(request, _, _)| { return landed.contains_key(&request.id); });
441    let unlanded: BatchTimes = BatchTimes::not_landed(group_began);
442    for (request, stream, arrival) in again {
443        stream.send(&ServiceMessage::Landed { id: request.id.clone(), commit: landed[&request.id].clone(), already: true });
444        log_answer(&unlanded, &request, &arrival, 1, "already");
445    }
446    // The same request sent twice into one batch (a client that reconnected) is landed once and answered twice.
447    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
448    let (fresh, repeats): (Vec<_>, Vec<_>) = pending.into_iter().partition(|(request, _, _)| { return seen.insert(request.id.clone()); });
449    if fresh.is_empty() {
450        return;
451    }
452    // A batch whose branch moved but whose index update had to give up (another program held Git's index lock the whole
453    //  time) left its intent open; settling it first puts the index right before anything else changes it.
454    let settling: Instant = Instant::now();
455    let _settled = settle_open_batches(context, instance);
456    let settle: Duration = settling.elapsed();
457    // The number is taken from the journal, not from this service's count alone: another service of the same journal may count
458    //  from the same clock reading, and two landings with one number would overwrite each other's records.
459    let claim: BatchClaim = match claim_batch(context.journal.as_path(), *seq + 1) {
460        Ok(claim) => claim,
461        Err(error) => {
462            let code: FailureCode = storage_failure(&error);
463            crate::service_error!("no batch number could be taken in {}: {error}", context.journal.display());
464            for (position, (request, stream, arrival)) in fresh.iter().enumerate() {
465                stream.send(&ServiceMessage::Failed { id: request.id.clone(), code });
466                log_answer(&unlanded, request, arrival, position + 1, format!("failed:{}", code.word()).as_str());
467            }
468            return;
469        }
470    };
471    *seq = claim.seq();
472    for (index, (_, stream, _)) in fresh.iter().enumerate().skip(1) {
473        stream.send(&ServiceMessage::Position { number: index + 1, of: fresh.len() });
474    }
475    let requests: Vec<CommitRequest> = fresh.iter().map(|(request, _, _)| { return (**request).clone(); }).collect();
476    let announce = |note: Announce| {
477        for (_, stream, _) in &fresh {
478            match &note {
479                Announce::Waiting(text) => stream.send(&ServiceMessage::Waiting { text: text.clone() }),
480                Announce::Holder(who) => stream.send(&ServiceMessage::Holder { who: who.clone() }),
481            }
482        }
483    };
484    let mut landing: LandTiming = LandTiming::default();
485    let landing_began: Instant = Instant::now();
486    let result = land_batch_timed(context, *seq, &requests, &announce, &mut landing);
487    // The intent or the finished batch keeps the number now; a landing that wrote none gives the number back.
488    drop(claim);
489    let times: BatchTimes = BatchTimes { batch: *seq, size: fresh.len(), group_began, settle, landing, land_total: landing_began.elapsed(), landed_at: Instant::now() };
490    match result {
491        Ok(outcomes) => {
492            // What this batch landed is remembered before any answer, so a commit sent back in the same batch is told about it.
493            for ((request, _, _), outcome) in fresh.iter().zip(&outcomes) {
494                if let Outcome::Landed { commit } = outcome {
495                    captures.record_landed(request.common_dir.as_path(), request.repository.as_path(), commit.as_str(), request.captured);
496                }
497            }
498            crate::service_fault::reach("before-ack");
499            for ((request, _, _), outcome) in fresh.iter().zip(&outcomes) {
500                if let Outcome::Landed { commit } = outcome {
501                    for (repeat, stream, arrival) in repeats.iter().filter(|(repeat, _, _)| { return repeat.id == request.id; }) {
502                        stream.send(&ServiceMessage::Landed { id: repeat.id.clone(), commit: commit.clone(), already: true });
503                        log_answer(&times, repeat, arrival, 1, "already");
504                    }
505                }
506            }
507            for (position, ((request, stream, arrival), outcome)) in fresh.iter().zip(outcomes).enumerate() {
508                let word: &str = match outcome {
509                    Outcome::Landed { commit } => {
510                        landed.insert(request.id.clone(), commit.clone());
511                        stream.send(&ServiceMessage::Landed { id: request.id.clone(), commit, already: false });
512                        "landed"
513                    }
514                    Outcome::RetryPrepare { base } => {
515                        let known = captures.remembered(request.common_dir.as_path(), request.repository.as_path());
516                        stream.send(&ServiceMessage::RetryPrepare { id: request.id.clone(), base, landed: known });
517                        "retry-prepare"
518                    }
519                    Outcome::BranchMoved => {
520                        stream.send(&ServiceMessage::Failed { id: request.id.clone(), code: FailureCode::BranchMoved });
521                        "branch-moved"
522                    }
523                };
524                log_answer(&times, request, arrival, position + 1, word);
525            }
526        }
527        Err(code) => {
528            for (position, (request, stream, arrival)) in fresh.iter().enumerate() {
529                stream.send(&ServiceMessage::Failed { id: request.id.clone(), code });
530                log_answer(&times, request, arrival, position + 1, format!("failed:{}", code.word()).as_str());
531            }
532        }
533    }
534}
535
536/// What:
537///  Runs the after-commit work of each repository named, one repository at a time, folding wakes that arrive while it
538///  works into the next round, and looks again at a repository whose claims another instance held when their lease is over.
539/// Why:
540///   Draining claims everything pending, so a burst of wakes for one repository is one pass. The instance that held a claim
541///  may have died, and nothing but this loop would then wake the work: it waits for a wake no longer than the first lease still
542///  running, and the service counts itself busy meanwhile, so it does not exit idle with work claimed by a dead holder. The same
543///  holds for a push the service stopped: the loop owns the plan of its new tries (`PushRetries`), each round hands the workers
544///  what is due and applies what they ask, and the wake for the earliest plan is kept in the same schedule as the lease wakes, so
545///  the service neither forgets the plan nor exits idle while a try is pending.
546///
547/// In TS you'd write (pseudocode):
548/// ```ts
549/// for await (const dir of wakesOrDueRetries) await drain(dir, handlers)
550/// ```
551pub fn work_loop(receiver: &Receiver<Wake>, handlers: &GitHandlers, busy: &AtomicUsize, mut push_retries: PushRetries) {
552    let mut retries: RetrySchedule = RetrySchedule::default();
553    let mut counted_waiting: bool = false;
554    // A plan that is already there when the loop starts (one rebuilt from disk) is woken for like one made by a round.
555    let started: Instant = Instant::now();
556    let restored: Vec<(PathBuf, Duration)> = push_retries
557        .directories()
558        .into_iter()
559        .filter_map(|directory| { return push_retries.next_wait(directory.as_path(), started).map(|wait| { return (directory, wait); }); })
560        .collect();
561    retries.replace(&[], restored, started);
562    if !retries.is_empty() {
563        busy.fetch_add(1, Ordering::SeqCst);
564        counted_waiting = true;
565    }
566    loop {
567        let first: Option<Wake> = match retries.next_wait(Instant::now()) {
568            None => match receiver.recv() {
569                Ok(wake) => Some(wake),
570                Err(_) => return,
571            },
572            Some(wait) => match receiver.recv_timeout(wait) {
573                Ok(wake) => Some(wake),
574                Err(RecvTimeoutError::Timeout) => None,
575                Err(RecvTimeoutError::Disconnected) => return,
576            },
577        };
578        busy.fetch_add(1, Ordering::SeqCst);
579        let mut wakes: Vec<Wake> = first.into_iter().chain(std::iter::from_fn(|| { return receiver.try_recv().ok(); })).collect();
580        wakes.extend(retries.take_due(Instant::now()).into_iter().map(|directory| { return (directory, None); }));
581        let mut ran: Vec<PathBuf> = wakes.iter().map(|(directory, _)| { return directory.clone(); }).collect();
582        let asked: Vec<(PathBuf, Duration)> = run_round(wakes, handlers, &mut push_retries, &ClaimTime::read());
583        // A directory the round named for its plan alone (the common directory of a bare repository) replaces its old entry too.
584        ran.extend(asked.iter().map(|(directory, _)| { return directory.clone(); }));
585        retries.replace(ran.as_slice(), asked, Instant::now());
586        // A repository waiting to be looked at again keeps the service from exiting idle, as running work does.
587        if !retries.is_empty() && !counted_waiting {
588            busy.fetch_add(1, Ordering::SeqCst);
589            counted_waiting = true;
590        } else if retries.is_empty() && counted_waiting {
591            busy.fetch_sub(1, Ordering::SeqCst);
592            counted_waiting = false;
593        }
594        busy.fetch_sub(1, Ordering::SeqCst);
595    }
596}
597
598/// What:
599///  Runs the service until it is told to retire.
600/// Why:
601///   Recovery runs before the first connection is accepted; then the loop takes everything queued as one batch, groups it
602///  by branch in order of first arrival, lands each group, and answers.
603///
604/// In TS you'd write (pseudocode):
605/// ```ts
606/// await serve(listener, context)
607/// ```
608pub fn serve(listener: UnixListener, context: &LandContext, settings: &ServeSettings) {
609    let serving_since: Instant = Instant::now();
610    let idle: Duration = settings.idle;
611    let _reports = settle_open_batches(context, settings.instance.as_deref());
612    // The memory of landed requests is bounded: the oldest finished batches go before the rest are read.
613    let pruned: usize = prune_done(context.journal.as_path(), DONE_RETAINED);
614    if pruned > 0 {
615        crate::service_log!("removed the records of {pruned} old finished batches from {}", context.journal.display());
616    }
617    let mut landed: HashMap<String, String> = landed_commits(context.journal.as_path());
618    // The identities of the requests their clients withdrew; a request with one of these is never landed.
619    let mut withdrawn: std::collections::HashSet<String> = std::collections::HashSet::new();
620    // What the landed commits were captured at: owned by this loop, the only thread that lands and answers.
621    let mut captures: CaptureMemory = CaptureMemory::default();
622    let (sender, receiver): (Sender<Job>, Receiver<Job>) = channel();
623    let acceptor_queue: Sender<Job> = sender.clone();
624    // After-commit work (push, upkeep) runs on its own thread, so a slow network never delays a landing.
625    let (work_sender, work_receiver): (Sender<Wake>, Receiver<Wake>) = channel();
626    let handlers: GitHandlers = GitHandlers::new(context.git.clone());
627    let busy: Arc<AtomicUsize> = Arc::new(AtomicUsize::new(0));
628    let worker_busy: Arc<AtomicUsize> = Arc::clone(&busy);
629    // The plan of the pushes waiting for a new try is kept in this instance's own journal, so a restarted service rebuilds it.
630    let plan_directory: PathBuf = context.journal.join(PLAN_DIRECTORY);
631    start_thread_or_exit("the after-commit work", move || { work_loop(&work_receiver, &handlers, &worker_busy, PushRetries::restored_from_environment(plan_directory.as_path())); });
632    let announced_release: String = settings.release.clone();
633    let connection_busy: Arc<AtomicUsize> = Arc::clone(&busy);
634    let instance: Option<String> = settings.instance.clone();
635    start_thread_or_exit("the acceptor of connections", move || {
636        for connection in listener.incoming().flatten() {
637            let queue: Sender<Job> = acceptor_queue.clone();
638            let work: Sender<Wake> = work_sender.clone();
639            let release: String = announced_release.clone();
640            let counted: Arc<AtomicUsize> = Arc::clone(&connection_busy);
641            let mine: Option<String> = instance.clone();
642            // A connection the service cannot give a thread is told so and closed; the acceptor goes on, because a panic here
643            //  would end the acceptor and leave a service that is running and answers no one.
644            let notice: Option<UnixStream> = connection.try_clone().ok();
645            let spawned = std::thread::Builder::new().spawn(move || { handle_connection(connection, &queue, &work, &counted, release.as_str(), mine.as_deref()); });
646            if let Err(error) = spawned {
647                crate::service_error!("no thread for a connection, which is closed after telling the client: {error}");
648                if let Some(stream) = notice {
649                    send(&stream, &ServiceMessage::Welcome { version: PROTOCOL_VERSION, release: Some(announced_release.clone()) });
650                    send(&stream, &ServiceMessage::Failed { id: String::new(), code: FailureCode::Unavailable });
651                }
652                // Starting a thread keeps failing while the pressure lasts; waiting a moment keeps the acceptor from spinning on it.
653                std::thread::sleep(ACCEPT_BACKOFF);
654            }
655        }
656    });
657    // Microseconds, so that instances started at different times count from different numbers; the number each batch takes is
658    //  still claimed in the journal (`claim_batch`), because equal readings and counts that overtake another's are possible.
659    let clock_seed: 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); });
660    let mut seq: u64 = crate::service_fault::pinned_first_batch().unwrap_or(clock_seed);
661    // The marker made ahead is removed whichever way this loop ends.
662    let _prestaged = PrestageGuard;
663    let mut retiring: bool = false;
664    while !retiring {
665        let first: Job = match receiver.recv_timeout(idle) {
666            Ok(job) => job,
667            // Work in flight keeps the service; otherwise it exits and the manager starts it on the next connection.
668            Err(RecvTimeoutError::Timeout) if busy.load(Ordering::SeqCst) > 0 => continue,
669            Err(RecvTimeoutError::Timeout) => {
670                // Leaving: the syncs of the landings that were answered are made before the service goes (a signal cannot wait for them).
671                crate::service_durable::drain();
672                log(exit_line(ExitReason::Idle, serving_since.elapsed()).as_str());
673                return;
674            }
675            Err(RecvTimeoutError::Disconnected) => {
676                // Leaving: the syncs of the landings that were answered are made before the service goes (a signal cannot wait for them).
677                crate::service_durable::drain();
678                log(exit_line(ExitReason::Error, serving_since.elapsed()).as_str());
679                return;
680            }
681        };
682        let mut jobs: Vec<Job> = vec![first];
683        while jobs.len() < MAX_BATCH {
684            match receiver.try_recv() {
685                Ok(job) => jobs.push(job),
686                Err(_) => break,
687            }
688        }
689        // Withdrawals are answered before anything lands, on this one thread, so each is either after a landing that is over (the
690        //  commit is on the branch, and that is the answer) or before the landing of its request begins (the request is dropped
691        //  and remembered, so it can never land, not even when it reaches the queue after the withdrawal).
692        if withdrawn.len() > WITHDRAWN_RETAINED {
693            withdrawn.clear();
694        }
695        for job in &jobs {
696            if let Job::Withdraw(id, reply) = job {
697                match landed.get(id) {
698                    Some(commit) => reply.send(&ServiceMessage::Landed { id: id.clone(), commit: commit.clone(), already: true }),
699                    None => {
700                        withdrawn.insert(id.clone());
701                        reply.send(&ServiceMessage::Withdrawn { id: id.clone() });
702                    }
703                }
704            }
705        }
706        // Branches in order of first arrival; within a branch, arrival order.
707        let mut groups: Vec<(GroupKey, Vec<Queued>)> = Vec::new();
708        let mut releases: Vec<std::path::PathBuf> = Vec::new();
709        for job in jobs {
710            match job {
711                Job::Withdraw(..) => {}
712                Job::Commit(request, _dropped, _arrival) if withdrawn.contains(&request.id) => {
713                    crate::service_log!("dropped the request {} that its client withdrew", request.id);
714                }
715                Job::Retire => retiring = true,
716                Job::Activity => {}
717                Job::Release(path) => releases.push(path),
718                Job::Commit(request, stream, arrival) => {
719                    // An amend is a group of its own, and what arrives after it starts another group, so the order on
720                    //  one branch is the order of arrival.
721                    // `HEAD` is a head of one worktree, so two detached worktrees of one repository are two branches.
722                    let queue_reference: String = if request.reference == "HEAD" {
723                        format!("HEAD@{}", request.repository.display())
724                    } else {
725                        request.reference.clone()
726                    };
727                    let key: GroupKey = (request.common_dir.clone(), queue_reference, request.lands_alone());
728                    place_in_groups(&mut groups, key, (request, stream, arrival));
729                }
730            }
731        }
732        for (_, group) in groups {
733            let index: Option<std::path::PathBuf> = group.first().map(|(request, _, _)| { return request.index.clone(); });
734            land_group(context, settings.instance.as_deref(), &mut seq, group, &mut landed, &mut captures);
735            // The batch after this one is numbered one more and lands on this index (a worktree has one), so its marker is
736            //  made and flushed now, while the service is idle, and the next commit only places it.
737            if let Some(next_index) = index {
738                start_prestage(next_index.as_path(), seq + 1);
739            }
740        }
741        // A lock this thread could not settle names this process: the restart reclaims it once this process is gone.
742        if unsettled_locks() > 0 {
743            crate::service_error!("ending, because an index lock could not be settled; the next connection starts the service again and its recovery reclaims the lock");
744            return;
745        }
746        for path in releases {
747            if let Err(error) = remove_tree(path.as_path()) {
748                crate::service_warn!("the scratch directory {} could not be removed: {error}", path.display());
749            }
750        }
751    }
752    // Leaving: the syncs of the landings that were answered are made before the service goes (a signal cannot wait for them).
753    crate::service_durable::drain();
754    log(exit_line(ExitReason::Retire, serving_since.elapsed()).as_str());
755}
756
757/// Socket controls stay out of the release executable.
758#[cfg(test)]
759#[path = "service_server_tests.rs"]
760mod tests;