git-zero-server 0.2.0

Allocation-free no_std Git smart/dumb HTTP serving and receive-pack primitives
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
//! Host-driven request intake and pull-based responses. HTTP transfer framing,
//! socket readiness and staging unsent output remain the host's responsibility.
#[cfg(feature = "read")]
pub mod preparation;

use crate::{
    Request, Response,
    http_backend::{self, Plan},
    upload_pack,
};
use git_zero_core::{Error, Repository, Result, io::SliceWriter, pack};

/// Incrementally collect a bounded request body in caller-owned storage. No
/// protocol output is possible until `finish` returns a complete body to parse.
/// Pass a validated Content-Length when known; otherwise the host supplies EOF.
pub struct RequestBody<'a> {
    storage: &'a mut [u8],
    length: usize,
    expected: Option<usize>,
    cancelled: bool,
}

impl<'a> RequestBody<'a> {
    pub fn new(storage: &'a mut [u8], expected: Option<usize>) -> Result<Self> {
        if expected.is_some_and(|length| length > storage.len()) {
            return Err(Error::BufferTooSmall);
        }
        Ok(Self {
            storage,
            length: 0,
            expected,
            cancelled: false,
        })
    }

    /// Append all bytes or none. A rejected fragment leaves intake resumable.
    pub fn push(&mut self, bytes: &[u8]) -> Result<()> {
        if self.cancelled {
            return Err(Error::InvalidRequest);
        }
        let end = self
            .length
            .checked_add(bytes.len())
            .ok_or(Error::BufferTooSmall)?;
        if self.expected.is_some_and(|length| end > length) {
            return Err(Error::InvalidRequest);
        }
        self.storage
            .get_mut(self.length..end)
            .ok_or(Error::BufferTooSmall)?
            .copy_from_slice(bytes);
        self.length = end;
        Ok(())
    }

    pub fn received(&self) -> usize {
        self.length
    }

    /// Terminal cancellation. Drop this value to reuse its caller-owned storage.
    pub fn cancel(&mut self) {
        self.cancelled = true;
    }

    pub fn finish(self) -> Result<&'a [u8]> {
        if self.cancelled || self.expected.is_some_and(|length| length != self.length) {
            return Err(Error::InvalidRequest);
        }
        Ok(&self.storage[..self.length])
    }
}

// Inline variants keep the cursor allocation-free with a fixed size budget.
#[allow(clippy::large_enum_variant)]
enum Body<'a> {
    Buffered,
    Pack(pack::Encoder<'a>),
    Loose(pack::LooseEncoder),
    #[cfg(feature = "read")]
    Cached {
        bytes: &'a [u8],
        position: usize,
    },
}

/// An independent response cursor with bounded inline framing state. The host
/// owns the repository, request and control buffers. Keep the same stable
/// repository for every `read`; it may be recreated from immutable inputs.
/// Discovery/ref/ACK bytes must fit `control`; object bodies never use it.
/// A completed prepare validates routes, commands, wants and selection budgets
/// before output. Provider failures after headers require aborting the transport.
pub struct ResponseEncoder<'a> {
    response: Response,
    prefix: &'a [u8],
    position: usize,
    body: Body<'a>,
    band: u8,
    packet: [u8; 1029],
    packet_position: usize,
    packet_length: usize,
    terminated: bool,
    cancelled: bool,
    started: bool,
}

impl<'a> ResponseEncoder<'a> {
    /// Prepare a HEAD-only repository. Independent roots need `with_selection`.
    pub fn new(
        repository: &impl Repository,
        request: Request<'_>,
        control: &'a mut [u8],
    ) -> Result<Self> {
        let mut output = SliceWriter::new(control);
        let plan = http_backend::prepare(repository, request, &mut output, false)?;
        let Plan::Upload(version) = plan else {
            return Self::ordinary_response(repository, plan, output.finish());
        };
        let upload = upload_pack::prepare_complete(repository, request.body, version)?;
        upload.acknowledge(repository, &mut output)?;
        let mut encoder = Self::buffered(upload_pack::response(), output.finish());
        if upload.done {
            encoder.body = Body::Pack(pack::Encoder::new(repository, None)?);
            encoder.band = upload.band();
        }
        Ok(encoder)
    }

    /// Prepare the exact requested closure with the same limits as
    /// `serve_with_selection`. Selection slots stay borrowed until this cursor
    /// is dropped; separate storage permits independent overlapping responses.
    #[cfg(feature = "read")]
    pub fn with_selection<R: Repository + ?Sized>(
        repository: &git_zero_core::ValidatedRepository<'_, '_, R>,
        request: Request<'_>,
        storage: &'a mut crate::SelectionStorage<'_>,
        control: &'a mut [u8],
    ) -> Result<Self> {
        Self::with_selection_storage(repository, request, storage.reborrow(), control)
    }

    /// Move a request's storage descriptor into preparation. Only its selected
    /// index array and control bytes remain borrowed by the resulting cursor.
    #[cfg(feature = "read")]
    pub fn with_selection_storage<R: Repository + ?Sized>(
        repository: &git_zero_core::ValidatedRepository<'_, '_, R>,
        request: Request<'_>,
        storage: crate::SelectionStorage<'a>,
        control: &'a mut [u8],
    ) -> Result<Self> {
        Self::with_selection_storage_policy(
            repository,
            request,
            storage,
            crate::WantOptions::STRICT,
            control,
        )
    }

    /// Additive host-granted selection. Only selected indices/control are pinned;
    /// the policy cannot be inherited by another cursor or strict constructor.
    #[cfg(feature = "read")]
    pub fn with_selection_policy<R: Repository + ?Sized>(
        repository: &git_zero_core::ValidatedRepository<'_, '_, R>,
        request: Request<'_>,
        storage: &'a mut crate::SelectionStorage<'_>,
        options: crate::WantOptions,
        control: &'a mut [u8],
    ) -> Result<Self> {
        Self::with_selection_storage_policy(
            repository,
            request,
            storage.reborrow(),
            options,
            control,
        )
    }

    #[cfg(feature = "read")]
    pub fn with_selection_storage_policy<R: Repository + ?Sized>(
        repository: &git_zero_core::ValidatedRepository<'_, '_, R>,
        request: Request<'_>,
        storage: crate::SelectionStorage<'a>,
        options: crate::WantOptions,
        control: &'a mut [u8],
    ) -> Result<Self> {
        Self::selected_storage(repository, request, storage, options, None, control)
    }

    /// Opt in to time/exclusion deepening. Boundary state is temporary; only
    /// selected indices and prepared control bytes survive in the response.
    #[cfg(feature = "read")]
    pub fn with_revisions<R: Repository + ?Sized>(
        repository: &git_zero_core::ValidatedRepository<'_, '_, R>,
        request: Request<'_>,
        storage: &'a mut crate::RevisionStorage<'_>,
        control: &'a mut [u8],
    ) -> Result<Self> {
        Self::with_revision_storage(repository, request, storage.reborrow(), control)
    }

    #[cfg(feature = "read")]
    pub fn with_revision_storage<R: Repository + ?Sized>(
        repository: &git_zero_core::ValidatedRepository<'_, '_, R>,
        request: Request<'_>,
        storage: crate::RevisionStorage<'a>,
        control: &'a mut [u8],
    ) -> Result<Self> {
        Self::with_revision_storage_policy(
            repository,
            request,
            storage,
            crate::WantOptions::STRICT,
            control,
        )
    }

    /// Combine explicit revision budgets with a request-local want grant. Neither
    /// capability can be inherited by another response or a strict constructor.
    #[cfg(feature = "read")]
    pub fn with_revision_storage_policy<R: Repository + ?Sized>(
        repository: &git_zero_core::ValidatedRepository<'_, '_, R>,
        request: Request<'_>,
        storage: crate::RevisionStorage<'a>,
        options: crate::WantOptions,
        control: &'a mut [u8],
    ) -> Result<Self> {
        Self::selected_storage(
            repository,
            request,
            storage.selection,
            options,
            Some((storage.state, storage.limits)),
            control,
        )
    }

    #[cfg(feature = "read")]
    fn selected_storage<R: Repository + ?Sized>(
        repository: &git_zero_core::ValidatedRepository<'_, '_, R>,
        request: Request<'_>,
        storage: crate::SelectionStorage<'a>,
        options: crate::WantOptions,
        revision: Option<(&mut [u8], git_zero_core::RevisionLimits)>,
        control: &'a mut [u8],
    ) -> Result<Self> {
        let mut output = SliceWriter::new(control);
        let plan = upload_pack::prepare_route(
            repository,
            request,
            options,
            revision.is_some(),
            &mut output,
        )?;
        let Plan::Upload(version) = plan else {
            return Self::ordinary_response(repository, plan, output.finish());
        };
        let selected = upload_pack::prepare_fetch(
            repository,
            request,
            version,
            storage,
            options,
            revision,
            &mut output,
        )?;
        let mut encoder = Self::buffered(upload_pack::response(), output.finish());
        if let Some(indices) = selected.indices {
            encoder.body = Body::Pack(pack::Encoder::new(repository, Some(indices))?);
            encoder.band = selected.upload.band();
        }
        Ok(encoder)
    }

    fn buffered(response: Response, prefix: &'a [u8]) -> Self {
        Self {
            response,
            prefix,
            position: 0,
            body: Body::Buffered,
            band: 0,
            packet: [0; 1029],
            packet_position: 0,
            packet_length: 0,
            terminated: false,
            cancelled: false,
            started: false,
        }
    }

    fn ordinary_response(
        repository: &impl Repository,
        plan: Plan,
        prefix: &'a [u8],
    ) -> Result<Self> {
        match plan {
            Plan::Buffered(response) => Ok(Self::buffered(response, prefix)),
            Plan::Loose(index) => {
                let mut encoder = Self::buffered(
                    Response {
                        status: 200,
                        content_type: "application/x-git-loose-object",
                    },
                    prefix,
                );
                encoder.body = Body::Loose(pack::LooseEncoder::new(repository, index)?);
                Ok(encoder)
            }
            Plan::Upload(_) => unreachable!(),
        }
    }

    pub fn response(&self) -> Response {
        self.response
    }

    /// Terminal cancellation never emits a successful terminator. Close/reset
    /// the transport; no subsequent read can access repository objects.
    pub fn cancel(&mut self) {
        self.cancelled = true;
    }

    /// Pull into host staging only when ready. Retain unsent bytes across short
    /// writes. Empty output is rejected while active. Zero denotes clean EOF.
    pub fn read(&mut self, repository: &impl Repository, output: &mut [u8]) -> Result<usize> {
        if self.cancelled {
            return Err(Error::InvalidRequest);
        }
        self.started = true;
        if self.position < self.prefix.len() {
            return copy(self.prefix, &mut self.position, output);
        }
        if self.band == 0 {
            return self.read_body(repository, output);
        }
        if self.packet_position == self.packet_length && !self.terminated {
            if output.is_empty() {
                return Err(Error::BufferTooSmall);
            }
            self.next_packet(repository)?;
        }

        if self.packet_position == self.packet_length {
            return Ok(0);
        }
        copy(
            &self.packet[..self.packet_length],
            &mut self.packet_position,
            output,
        )
    }

    fn next_packet(&mut self, repository: &impl Repository) -> Result<()> {
        let capacity = if self.band == 1 { 995 } else { 1024 };
        let length = match &mut self.body {
            Body::Pack(pack) => pack.read(repository, &mut self.packet[5..5 + capacity])?,
            #[cfg(feature = "read")]
            Body::Cached { bytes, position } => {
                if *position == bytes.len() {
                    0
                } else {
                    copy(bytes, position, &mut self.packet[5..5 + capacity])?
                }
            }
            _ => unreachable!(),
        };
        self.packet_position = 0;
        if length == 0 {
            self.packet[..4].copy_from_slice(b"0000");
            self.packet_length = 4;
            self.terminated = true;
        } else {
            let size = length + 5;
            for (index, byte) in self.packet[..4].iter_mut().enumerate() {
                *byte = b"0123456789abcdef"[(size >> ((3 - index) * 4)) & 15];
            }
            self.packet[4] = 1;
            self.packet_length = size;
        }
        Ok(())
    }

    fn read_body(&mut self, repository: &impl Repository, output: &mut [u8]) -> Result<usize> {
        match &mut self.body {
            Body::Buffered => Ok(0),
            Body::Pack(pack) => pack.read(repository, output),
            Body::Loose(loose) => loose.read(repository, output),
            #[cfg(feature = "read")]
            Body::Cached { bytes, position } => {
                if *position == bytes.len() {
                    Ok(0)
                } else {
                    copy(bytes, position, output)
                }
            }
        }
    }
}

fn copy(bytes: &[u8], position: &mut usize, output: &mut [u8]) -> Result<usize> {
    if output.is_empty() {
        return Err(Error::BufferTooSmall);
    }
    let count = output.len().min(bytes.len() - *position);
    output[..count].copy_from_slice(&bytes[*position..*position + count]);
    *position += count;
    Ok(count)
}