alkgit 0.1.0

Git smart protocol for the alk family: pkt-line substrates, protocol V2 serving (upload-pack/receive-pack), producer/consumer halves on alkcall channels, and the backend seam traits — the shipped alkstore+alkblobs composition is the alkgit-substrate crate (ADR-010/025)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//! The protocol V2 machines (ADR-003): the capability advertisement and
//! the ls-refs command machine — substrate-agnostic per ADR-005 §3
//! (both serving entries feed the same machines; the machines are pure
//! protocol).
//!
//! The machines' substrate surface is [`PktLineWriter`]: the framing
//! helpers both substrates expose ([`crate::duplex::Session`] and
//! [`StatelessResponse`](crate::stateless::StatelessResponse) both
//! implement it), so no duplex- or stateless-specific type appears in
//! any machine signature below, and the packetline raw API stays under
//! the substrate surface (ADR-005 §3's rule).
//!
//! - **The advertisement** ([`advertise_v2`]): `version 2` + the honest
//!   capability list — exactly `ls-refs=unborn`, `fetch=wait-for-done`
//!   (the ack loop is grammar, not capability — ADR-014),
//!   `object-format=sha1` (the sha256 line rides the `sha256` feature
//!   flag per OQ-05's passthrough policy; sha1 stays the pinned
//!   default). Unimplemented features are declined by omission
//!   (shallow, filter, packfile-uris, object-info, server-option —
//!   POC-1 confirmed real git accepts the omission). Emitted once per
//!   duplex session, never between commands (real git hangs on
//!   re-advertisement); per-request-set on the stateless substrate —
//!   the once-only discipline is the serving entries', not the
//!   machine's (the machine writes one advertisement, on call).
//! - **ls-refs** ([`parse_ls_refs_args`] + [`serve_ls_refs`]): the
//!   command arguments parsed per the ls-refs grammar (`peel`,
//!   `symrefs`, `ref-prefix <prefix>`, `unborn` — the capability is
//!   advertised, so the argument is served; unknown arguments are
//!   session errors, fail closed), ref lines streamed from the
//!   backend's listed full set with the machine-side ref-prefix filter
//!   (client-driven), the response ending at flush. Attribute order on
//!   the line is the observed wire shape (POC-1):
//!   `"<oid> <ref>[ symref-target:…][ peeled:…]"` — symref-target
//!   before peeled, attributes on the same line.
//! - **The unborn symref line** (the N-5 rider's shape): a
//!   [`RefLine`](crate::RefLine) with `oid: None` maps to the unborn
//!   line (`unborn <name>` — the upstream ls-refs.c emission,
//!   capture-pinned against git 2.43.0; see [`UNBORN_TOKEN`]). The line
//!   is emitted only when the client requested `unborn`; without the
//!   request the row is omitted, real git's serving behavior. The real
//!   clients validated the line OQ-19 rider (a) (wave 5): `git
//!   ls-remote` and the unborn-HEAD clone consume the line.
//! - **The advertisement ref cap, fail-closed** (ADR-009 + review 001
//!   N-1): the listed ref set exceeding
//!   [`Limits::max_advertisement_refs`] is a session error, never a
//!   silent truncation — a partial ref list is the worst failure mode
//!   an advertisement can have (clones appear to succeed). The check
//!   precedes the first written line: no partial list can be emitted.
//!
//! Error mapping of backend `StorageError` is the serving entries'
//! (decomposition record, wave 2 — the machines stay pure protocol),
//! so [`serve_ls_refs`] receives the listed set, not the trait.

use async_trait::async_trait;

use crate::limits::Limits;
use crate::seam::RefLine;
use crate::stateless::StatelessResponse;
use crate::substrate::SubstrateError;

/// The pkt-line text/flush framing plus the packfile section's data
/// band — both substrates expose the same surface (ADR-005 §3's
/// substrate-agnostic shape): the machines write through this surface
/// and never see a duplex- or stateless-specific type.
#[async_trait]
pub trait PktLineWriter {
    /// Writes one pkt-line text line (newline-augmented by the codec).
    async fn write_text_line(&mut self, line: &[u8]) -> Result<(), SubstrateError>;

    /// Writes the terminating flush.
    async fn write_flush(&mut self) -> Result<(), SubstrateError>;

    /// Writes band-1 sideband data, chunked at
    /// [`SIDEBAND_CHUNK_SIZE`](crate::limits::SIDEBAND_CHUNK_SIZE) — the
    /// done-round packfile section's data band (ADR-014 §2).
    async fn write_data_band(&mut self, data: &[u8]) -> Result<(), SubstrateError>;
}

#[async_trait]
impl<T> PktLineWriter for crate::duplex::Session<T>
where
    T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send,
{
    async fn write_text_line(&mut self, line: &[u8]) -> Result<(), SubstrateError> {
        crate::duplex::Session::write_text_line(self, line).await
    }

    async fn write_flush(&mut self) -> Result<(), SubstrateError> {
        crate::duplex::Session::write_flush(self).await
    }

    async fn write_data_band(&mut self, data: &[u8]) -> Result<(), SubstrateError> {
        crate::duplex::Session::write_data_band(self, data).await
    }
}

#[async_trait]
impl<W> PktLineWriter for StatelessResponse<W>
where
    W: futures::io::AsyncWrite + Unpin + Send,
{
    async fn write_text_line(&mut self, line: &[u8]) -> Result<(), SubstrateError> {
        StatelessResponse::write_text_line(self, line).await
    }

    async fn write_flush(&mut self) -> Result<(), SubstrateError> {
        StatelessResponse::write_flush(self).await
    }

    async fn write_data_band(&mut self, data: &[u8]) -> Result<(), SubstrateError> {
        StatelessResponse::write_data_band(self, data).await
    }
}

/// The honest V2 capability list (ADR-003): exactly what the wire layer
/// serves — nothing unimplemented advertised.
pub(crate) const CAPABILITY_LINES: &[&str] = &[
    "ls-refs=unborn",
    "fetch=wait-for-done",
    "object-format=sha1",
];

/// The advertisement version line.
pub(crate) const VERSION_LINE: &str = "version 2";

/// Writes the V2 capability advertisement (ADR-003): `version 2`, the
/// honest capability list, flush. Emitted once per duplex session /
/// per-request-set on the stateless substrate — the once-only
/// discipline is the serving entries' (the machine writes one
/// advertisement, on call).
///
/// Under the `sha256` feature the additional `object-format=sha256`
/// line is emitted after the pinned default (OQ-05's passthrough
/// policy; sha1 stays the default and the crate pin).
pub async fn advertise_v2(writer: &mut impl PktLineWriter) -> Result<(), SubstrateError> {
    writer.write_text_line(VERSION_LINE.as_bytes()).await?;
    for capability in CAPABILITY_LINES {
        writer.write_text_line(capability.as_bytes()).await?;
    }
    #[cfg(feature = "sha256")]
    writer.write_text_line(b"object-format=sha256").await?;
    writer.write_flush().await
}

/// The parsed `ls-refs` command arguments (the ls-refs grammar, wire
/// side): the client-driven filtering and attribute requests.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct LsRefsArgs {
    /// `peel` — the `peeled <oid>` attribute is emitted on annotated-tag
    /// ref lines carrying a peel result.
    pub peel: bool,
    /// `symrefs` — the `symref-target <name>` attribute is emitted on
    /// symbolic ref lines carrying a symref target.
    pub symrefs: bool,
    /// The `ref-prefix <prefix>` prefixes (possibly repeated): ref
    /// lines are filtered to names with any prefix. Empty — no
    /// filtering, the full set streams.
    pub ref_prefixes: Vec<String>,
    /// `unborn` — the HEAD symref row shape (`oid: None`) is emitted as
    /// the unborn line; without the request the row is omitted (real
    /// git's behavior; the token is advertised via `ls-refs=unborn`).
    pub unborn: bool,
}

/// Parses the `ls-refs` argument lines (the args after the `0001`
/// delimiter of a `command=ls-refs` request — one argument per pkt-line,
/// `ref-prefix <prefix>` riding one line with its value). Unknown
/// arguments, a missing `ref-prefix` value, and an empty prefix are
/// session errors — fail closed (ADR-009's posture: never guess at what
/// was meant).
pub fn parse_ls_refs_args(args: &[String]) -> Result<LsRefsArgs, SubstrateError> {
    let mut parsed = LsRefsArgs::default();
    for arg in args {
        match arg.as_str() {
            "peel" => parsed.peel = true,
            "symrefs" => parsed.symrefs = true,
            "unborn" => parsed.unborn = true,
            "ref-prefix" => {
                return Err(SubstrateError::Protocol(
                    "ls-refs: ref-prefix given without a value".to_owned(),
                ));
            }
            other => match other.strip_prefix("ref-prefix ") {
                Some("") => {
                    return Err(SubstrateError::Protocol(
                        "ls-refs: ref-prefix given without a value".to_owned(),
                    ));
                }
                Some(prefix) => parsed.ref_prefixes.push(prefix.to_owned()),
                None => {
                    return Err(SubstrateError::Protocol(format!(
                        "ls-refs: unexpected argument {other:?}"
                    )));
                }
            },
        }
    }
    Ok(parsed)
}

impl LsRefsArgs {
    /// The client-driven ref-prefix filter (`ref-prefix` may repeat; an
    /// empty prefix list leaves the full set).
    fn accepts(&self, name: &str) -> bool {
        self.ref_prefixes.is_empty() || self.ref_prefixes.iter().any(|p| name.starts_with(p))
    }
}

/// The unborn HEAD line's oid field: the **literal `unborn` token** —
/// the upstream ls-refs.c emission, capture-pinned against git
/// 2.43.0's own server. Not the zero oid: a real client turns a
/// zero-oid HEAD into a fetch want of the null oid and the session
/// errors (`ERR object <zero-oid> does not exist`, captured live on
/// rider 1's unborn clone session). The inbound ref-line parser
/// accepts both shapes (`oid: None`); the outbound emission is the
/// upstream pin (pre-publish correction — the freeze is at the
/// publish).
pub(crate) const UNBORN_TOKEN: &str = "unborn";

/// Formats one ref line per the ls-refs grammar (the observed wire
/// shape, POC-1: attributes on the same line, symref-target before
/// peeled).
fn ref_line_text(line: &RefLine, hex: &str, args: &LsRefsArgs) -> String {
    let mut text = format!("{hex} {}", line.name);
    if args.symrefs {
        if let Some(target) = &line.symref_target {
            text.push_str(&format!(" symref-target:{target}"));
        }
    }
    if args.peel {
        if let Some(peeled) = line.peeled {
            text.push_str(&format!(" peeled:{peeled}"));
        }
    }
    text
}

/// Serves one `ls-refs` command (ADR-005 §3's machine core): the listed
/// ref set is capped fail-closed, filtered by the client's
/// `ref-prefix`, streamed as ref lines, and the response ends at
/// flush.
///
/// `refs` is the backend's
/// [`list_refs`](crate::GitRefs::list_refs) result — the full set; the
/// machine applies its own ref-prefix filter (the pinned split). The
/// cap check ([`Limits::max_advertisement_refs`]) precedes the first
/// written line: a breach errors the session with nothing emitted —
/// the fail-closed rule, never a silent truncation (ADR-009 + review
/// 001 N-1).
pub async fn serve_ls_refs(
    writer: &mut impl PktLineWriter,
    refs: Vec<RefLine>,
    args: &LsRefsArgs,
    limits: &Limits,
) -> Result<(), SubstrateError> {
    if refs.len() > limits.max_advertisement_refs {
        return Err(SubstrateError::Protocol(format!(
            "ls-refs: advertisement ref cap of {} exceeded by {} refs — fail closed, no partial list (ADR-009, review 001 N-1)",
            limits.max_advertisement_refs,
            refs.len()
        )));
    }
    for line in &refs {
        if !args.accepts(&line.name) {
            continue;
        }
        let bytes = match line.oid {
            Some(oid) => ref_line_text(line, &oid.to_string(), args),
            None => {
                // The unborn symref row (the N-5 rider's shape): emitted
                // as the literal-unborn line only when the client
                // requested `unborn`, omitted otherwise (real git's
                // behavior; [`UNBORN_TOKEN`] explains the shape).
                if !args.unborn {
                    continue;
                }
                ref_line_text(line, UNBORN_TOKEN, args)
            }
        };
        writer.write_text_line(bytes.as_bytes()).await?;
    }
    writer.write_flush().await
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::substrate::SubstrateError;
    use gix_hash::ObjectId;

    fn oid(b: u8) -> ObjectId {
        ObjectId::from([b; 20])
    }

    fn ref_line(name: &str, oid: Option<ObjectId>) -> RefLine {
        RefLine {
            name: name.to_owned(),
            oid,
            peeled: None,
            symref_target: None,
        }
    }

    fn protocol_error(result: Result<LsRefsArgs, SubstrateError>) -> String {
        match result {
            Err(SubstrateError::Protocol(message)) => message,
            Ok(args) => panic!("expected a protocol error, got {args:?}"),
            Err(other) => panic!("expected a protocol error, got {other:?}"),
        }
    }

    #[test]
    fn advertisement_capabilities_are_exactly_the_honest_list() {
        assert_eq!(
            CAPABILITY_LINES,
            &[
                "ls-refs=unborn",
                "fetch=wait-for-done",
                "object-format=sha1",
            ]
        );
        let declined = [
            "shallow",
            "filter",
            "packfile-uris",
            "object-info",
            "server-option",
        ];
        for capability in declined {
            assert!(
                !CAPABILITY_LINES
                    .iter()
                    .any(|line| line.contains(capability)),
                "{capability} is declined by omission (ADR-003)"
            );
        }
    }

    #[test]
    fn parse_reads_flags_and_repeated_prefixes() {
        let args = parse_ls_refs_args(&[
            "symrefs".to_owned(),
            "ref-prefix refs/heads/".to_owned(),
            "peel".to_owned(),
            "ref-prefix refs/tags/".to_owned(),
        ])
        .unwrap();
        assert!(args.peel);
        assert!(args.symrefs);
        assert!(!args.unborn);
        assert_eq!(args.ref_prefixes, vec!["refs/heads/", "refs/tags/"]);
    }

    #[test]
    fn parse_reads_the_unborn_argument() {
        let args = parse_ls_refs_args(&["unborn".to_owned(), "symrefs".to_owned()]).unwrap();
        assert!(args.unborn);
        assert!(args.symrefs);
    }

    #[test]
    fn parse_rejects_unknown_arguments_fail_closed() {
        let message = protocol_error(parse_ls_refs_args(&["shallow".to_owned()]));
        assert!(message.contains("shallow"), "{message}");
    }

    #[test]
    fn parse_rejects_a_ref_prefix_without_its_value() {
        let message = protocol_error(parse_ls_refs_args(&["ref-prefix".to_owned()]));
        assert!(message.contains("ref-prefix"), "{message}");
    }

    #[test]
    fn empty_args_parse_to_no_filtering_and_no_attributes() {
        let args = parse_ls_refs_args(&[]).unwrap();
        assert_eq!(args, LsRefsArgs::default());
    }

    #[test]
    fn the_unborn_token_is_the_upstream_literal() {
        assert_eq!(UNBORN_TOKEN, "unborn");
    }

    #[tokio::test]
    async fn serve_streams_filtered_attribute_lines_and_flushes() {
        let refs = vec![
            ref_line("HEAD", Some(oid(1))),
            ref_line("refs/heads/main", Some(oid(2))),
            ref_line("refs/tags/v1", Some(oid(3))),
        ];
        let mut sink: Vec<String> = Vec::new();
        struct Sink<'a>(&'a mut Vec<String>);
        #[async_trait]
        impl PktLineWriter for Sink<'_> {
            async fn write_text_line(&mut self, line: &[u8]) -> Result<(), SubstrateError> {
                self.0.push(String::from_utf8_lossy(line).into_owned());
                Ok(())
            }

            async fn write_flush(&mut self) -> Result<(), SubstrateError> {
                self.0.push(String::new());
                Ok(())
            }

            async fn write_data_band(&mut self, data: &[u8]) -> Result<(), SubstrateError> {
                self.0
                    .push(format!("band:{}", String::from_utf8_lossy(data)));
                Ok(())
            }
        }
        let args = parse_ls_refs_args(&[
            "peel".to_owned(),
            "symrefs".to_owned(),
            "ref-prefix refs/".to_owned(),
        ])
        .unwrap();
        serve_ls_refs(&mut Sink(&mut sink), refs, &args, &Limits::default())
            .await
            .unwrap();
        // HEAD is filtered out (no prefix match), the rest stream, the
        // response ends at flush.
        assert_eq!(
            sink,
            vec![
                format!("{} refs/heads/main", oid(2)),
                format!("{} refs/tags/v1", oid(3)),
                String::new(),
            ]
        );
    }
}