ostrya-remote 0.4.0

The push and pull protocol of ostrya: the wire codec, the push client session, and the ssh and HTTP transports
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
//! The sender of a one-way stream: the messages of a push session in one
//! direction, with no reply.

use std::collections::HashSet;
use std::io;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use futures_io::AsyncWrite;
use futures_lite::io::BufWriter;
use ostrya_core::{Checksum, ObjectName};

use super::progress::Counters;
use super::stream::WRITE_BUFFER;
use super::writer::{Counting, HandOver, MetaClaims, ObjectWriter, Pass, Stop, Upload};
use super::{
    Compression, ObjectSource, PushPhase, PushStats, SessionOptions, count_content_total,
    deflate_level, invalid, refuse_off_wire,
};
use crate::error::{Error, Result};
use crate::proto::{
    CommitRequest, Expected, Hello, MIN_FRAME_LIMIT, Message, PROTOCOL_VERSION, RefUpdate,
    encode_frame,
};

/// The output of a one-way stream. Each byte that it takes reaches the writer
/// of the caller, so the output is handed over at once.
struct Direct<W> {
    inner: W,
}

impl<W> HandOver for Direct<W> {
    fn is_handed_over(&self) -> bool {
        true
    }
}

impl<W: AsyncWrite + Unpin> AsyncWrite for Direct<W> {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.get_mut().inner).poll_write(cx, buf)
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.get_mut().inner).poll_flush(cx)
    }

    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.get_mut().inner).poll_close(cx)
    }
}

/// Writes a push as one one-way stream to `output`.
///
/// The receiver of a [one-way stream](crate::proto#one-way-stream) sends no
/// reply, so the call reads nothing, does no negotiation, and sends each name
/// of `names`. The call returns the statistics of the stream as [`PushStats`].
///
/// # Stream
///
/// The stream holds these parts, in this order:
///
/// 1. One `Hello` with `one-way` set to `true` and the refs of `updates`.
/// 2. One object stream, closed by `ObjectsEnd`. It carries the objects of
///    `names` from `source`, then the detached metadata of each commit of
///    `commits` that has some. If the stream has no object to carry, it has
///    no object stream.
/// 3. One `Commit` with `updates` and `force` set to `false`.
///
/// The frame limit and the chunk limit are [`MIN_FRAME_LIMIT`]. If
/// `compression` asks for `deflate`, the call sends the content objects with
/// the `deflate` encoding. A one-way receiver accepts this encoding in every
/// repository mode.
///
/// # Output
///
/// The call writes `output` in blocks of 64 KiB, so the caller does not need
/// to give a buffered writer. After `Commit`, the call flushes `output` and
/// does not close it. The caller closes `output`, and this close gives the end
/// of file that ends the stream. A caller that keeps its writer gives `&mut W`.
///
/// # Progress
///
/// - `opts.agent` is the `agent` of `Hello`.
/// - `opts.progress` receives the counters.
/// - The statistics count each name of `names` as offered and as needed.
/// - The phases are [`PushPhase::Uploading`] and then
///   [`PushPhase::Committing`].
///
/// If `opts.progress` is set and `names` holds at least one file object, the
/// call asks [`ObjectSource::content_size`] for the content bytes of `names`.
/// It asks before it writes the first byte.
///
/// # Failures
///
/// The source can fail while the call writes the stream, for example on a
/// missing file object or a failed read. The source can also give data that
/// the stream cannot carry. In both cases, the call ends the stream inside an
/// object:
///
/// 1. It writes the header of the object, if it did not write it yet.
/// 2. It writes the abandon marker and `Abort`.
/// 3. It flushes `output`.
///
/// A one-way receiver refuses an `Abort` between two objects with the code
/// `protocol`, so the call writes the header first. If a write fails, the
/// call returns the error of the write and writes nothing more.
///
/// # Errors
///
/// Before it writes the first byte, the call returns:
///
/// - [`Error::InvalidInput`] if `updates` is empty, or names a ref twice.
/// - [`Error::InvalidInput`] if a ref name fails the rule of
///   [`ostrya_core::is_refspec`].
/// - [`Error::InvalidInput`] if an update writes a ref name of 64 lowercase
///   hex characters with no `REMOTE:` part. A revision reads such a name as a
///   commit checksum.
/// - [`Error::InvalidInput`] if an update expects [`Expected::Commit`], or
///   has no new commit, because the sender cannot learn the current tips.
/// - [`Error::InvalidInput`] if `compression` is [`Compression::Deflate`]
///   with a level outside 1 through 9.
/// - [`Error::InvalidInput`] if the type of a name of `names` is not a file,
///   a dirtree, a dirmeta, or a commit.
/// - [`Error::InvalidInput`] if the `Hello` frame or the `Commit` frame is
///   more than [`MIN_FRAME_LIMIT`].
/// - [`Error::Protocol`] if `opts.agent` holds a NUL byte, because the
///   `Hello` frame does not encode.
///
/// After the first byte, the call returns:
///
/// - [`Error::Source`] if a call of the source fails. It holds the error of
///   the source.
/// - [`Error::Source`] if a read of an object reader fails. It holds the
///   I/O error of the read.
/// - [`Error::InvalidInput`] if the source gives data that the stream cannot
///   carry:
///   - an object with a type that its data does not permit
///   - a symlink with a payload, or a regular file with no payload
///   - a file header that does not encode
///   - detached metadata that does not serialize as `a{sv}`, or that is more
///     than [`MAX_METADATA_SIZE`](ostrya_core::MAX_METADATA_SIZE) bytes
/// - [`Error::Io`] if a write to `output` or a flush of `output` fails.
///
/// # Panics
///
/// Under the `tokio` backend, the call panics outside a tokio runtime context
/// if `source` gives a
/// [`DetachedMetadata::Dict`](super::DetachedMetadata::Dict) for a commit of
/// `commits`.
pub async fn export_stream<W>(
    output: W,
    source: &dyn ObjectSource,
    names: &[ObjectName],
    commits: &[Checksum],
    updates: &[RefUpdate],
    compression: Compression,
    opts: SessionOptions,
) -> Result<PushStats>
where
    W: AsyncWrite + Unpin + Send,
{
    check_updates(updates)?;
    let level = deflate_level(compression)?;
    refuse_off_wire(names)?;
    let agent = opts
        .agent
        .unwrap_or_else(|| format!("ostrya/{}", env!("CARGO_PKG_VERSION")));
    // The call encodes each frame once, before the first byte. The stream
    // keeps the bytes of `Commit` and no message.
    let hello = frame(
        &Message::Hello(Hello {
            version: PROTOCOL_VERSION,
            agent: Some(agent),
            refs: updates.iter().map(|u| u.name.clone()).collect(),
            collection: None,
            one_way: true,
        }),
        "Hello",
    )?;
    let commit = frame(
        &Message::Commit(CommitRequest {
            updates: updates.to_vec(),
            force: false,
            server_commit: None,
        }),
        "Commit",
    )?;

    let counters = Arc::new(Counters::new(opts.progress.as_ref()));
    count_content_total(&counters, source, names, level).await;
    counters.phase(PushPhase::Uploading);
    counters.offered(names.len() as u64);
    counters.needed(names.len() as u64);
    let counting = Counting::new(Direct { inner: output }, Arc::clone(&counters));
    let mut writer = ObjectWriter::new(
        BufWriter::with_capacity(WRITE_BUFFER, counting),
        Arc::clone(&counters),
    );
    writer.frames().write_frame(&hello).await?;
    drop(hello);

    let claims = MetaClaims::default();
    let up = Upload::new(source, names, commits, level, true, &claims);
    let mut started = false;
    let mut pass = Pass::default();
    match writer.write_items(&up, &mut pass, &mut started).await {
        Ok(()) => {}
        Err(Stop::Wire(e)) => return Err(e),
        Err(Stop::Abandon {
            error,
            in_object,
            next,
        }) => {
            // A one-way receiver refuses `Abort` between two objects with
            // the code `protocol`, so the stream opens the object that it
            // was to send and abandons it. A failed write ends the call with
            // its error.
            let mut in_object = in_object;
            if let (false, Some(header)) = (in_object, next) {
                writer
                    .frames()
                    .write_message(&Message::ObjectHeader(header))
                    .await?;
                in_object = true;
            }
            writer.abandon(in_object).await?;
            writer.frames().flush().await?;
            return Err(error);
        }
    }
    if started {
        writer.frames().write_message(&Message::ObjectsEnd).await?;
    }
    counters.phase(PushPhase::Committing);
    let frames = writer.frames();
    frames.write_frame(&commit).await?;
    frames.flush().await?;
    Ok(counters.stats())
}

/// Refuses empty `updates`, a ref named twice, a ref name that is not a
/// refspec, a write to a ref name of 64 lowercase hex characters, an expected
/// commit, and a delete.
fn check_updates(updates: &[RefUpdate]) -> Result<()> {
    if updates.is_empty() {
        return Err(invalid("a commit needs at least one ref update"));
    }
    let mut seen = HashSet::new();
    for u in updates {
        if !ostrya_core::is_refspec(&u.name)
            || (u.new.is_some() && ostrya_core::is_checksum_shaped(&u.name))
        {
            return Err(invalid(format!("'{}' is not a valid ref name", u.name)));
        }
        if !seen.insert(u.name.as_str()) {
            return Err(invalid(format!("ref '{}' is updated twice", u.name)));
        }
        if let Expected::Commit(_) = u.expected {
            return Err(invalid(format!(
                "the update of '{}' expects a commit, which a one-way stream cannot state",
                u.name
            )));
        }
        if u.new.is_none() {
            return Err(invalid(format!(
                "the update of '{}' deletes the ref, which a one-way stream cannot do",
                u.name
            )));
        }
    }
    Ok(())
}

/// Returns the frame of `msg`. If the frame is more than [`MIN_FRAME_LIMIT`],
/// the limit of a one-way stream, the call returns `Error::InvalidInput`.
fn frame(msg: &Message, what: &str) -> Result<Vec<u8>> {
    match encode_frame(msg, MIN_FRAME_LIMIT) {
        Ok(frame) => Ok(frame),
        Err(Error::LimitExceeded(e)) => Err(invalid(format!(
            "the {what} frame of the one-way stream: {e}"
        ))),
        Err(e) => Err(e),
    }
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::{AtomicBool, Ordering};

    use futures_lite::io::{AsyncReadExt, Cursor};
    use ostrya_core::ObjectType;
    use ostrya_gvariant::Value;

    use super::super::{BoxFuture, ObjectData};
    use super::*;
    use crate::proto::{ABANDON, Encoding, FrameReader, ObjectHeader, ObjectRead};

    /// A source of metadata objects whose bytes are their checksum, with one
    /// detached metadata dict for each commit. A name in `missing` fails to
    /// open.
    struct Source {
        missing: Option<ObjectName>,
    }

    impl ObjectSource for Source {
        fn objects<'a>(&'a self, _: &'a Checksum) -> BoxFuture<'a, Result<Vec<ObjectName>>> {
            Box::pin(async { Ok(Vec::new()) })
        }

        fn open<'a>(
            &'a self,
            name: &'a ObjectName,
            _: Encoding,
        ) -> BoxFuture<'a, Result<ObjectData>> {
            Box::pin(async move {
                if self.missing == Some(*name) {
                    return Err(invalid("no such object"));
                }
                Ok(ObjectData::Encoded {
                    encoding: Encoding::Raw,
                    reader: Box::new(Cursor::new(name.checksum.as_bytes().to_vec())),
                })
            })
        }

        fn detached_metadata<'a>(
            &'a self,
            _: &'a Checksum,
        ) -> BoxFuture<'a, Result<Option<Value>>> {
            Box::pin(async {
                let mut dict = ostrya_gvariant::DictBuilder::new();
                dict.insert_str("k", "v");
                Ok(Some(dict.build()))
            })
        }
    }

    fn commit() -> Checksum {
        Checksum::from_bytes([1; 32])
    }

    fn names() -> Vec<ObjectName> {
        vec![
            ObjectName::new(commit(), ObjectType::Commit),
            ObjectName::new(Checksum::from_bytes([2; 32]), ObjectType::DirTree),
            ObjectName::new(Checksum::from_bytes([3; 32]), ObjectType::DirMeta),
        ]
    }

    fn update(name: &str, expected: Expected, new: Option<Checksum>) -> RefUpdate {
        RefUpdate {
            name: name.into(),
            expected,
            new,
        }
    }

    fn updates() -> Vec<RefUpdate> {
        vec![
            update("main", Expected::Absent, Some(commit())),
            update("origin:main", Expected::Any, Some(commit())),
        ]
    }

    fn export<W: AsyncWrite + Unpin + Send>(
        source: &Source,
        names: &[ObjectName],
        updates: &[RefUpdate],
        compression: Compression,
        out: W,
    ) -> Result<PushStats> {
        ostrya_rt::block_on(export_stream(
            out,
            source,
            names,
            &[commit()],
            updates,
            compression,
            SessionOptions::default(),
        ))
    }

    /// Read the body of the current object to its end.
    fn body(reader: &mut FrameReader<&[u8]>) -> Vec<u8> {
        let mut out = Vec::new();
        ostrya_rt::block_on(reader.object_body().read_to_end(&mut out)).unwrap();
        out
    }

    fn next(reader: &mut FrameReader<&[u8]>) -> Option<Message> {
        ostrya_rt::block_on(reader.read_message()).unwrap()
    }

    /// The stream is `Hello` with `one-way` set to `true` and the refs of the
    /// updates, each object, the detached metadata of the commit, then
    /// `ObjectsEnd`, `Commit` with `force` set to `false`, and the end. The
    /// statistics count each name as offered, needed, and sent.
    #[test]
    fn the_stream_is_hello_objects_metadata_objects_end_and_commit() {
        let source = Source { missing: None };
        let mut out = Vec::new();
        let stats = export(&source, &names(), &updates(), Compression::None, &mut out).unwrap();
        assert_eq!(stats.objects_total, 3);
        assert_eq!(stats.objects_needed, 3);
        assert_eq!(stats.objects_sent, 3);
        assert_eq!(stats.bytes_sent, out.len() as u64);

        let mut reader = FrameReader::new(&out[..]);
        match next(&mut reader) {
            Some(Message::Hello(hello)) => {
                assert!(hello.one_way);
                assert_eq!(hello.version, PROTOCOL_VERSION);
                assert_eq!(hello.refs, vec!["main", "origin:main"]);
            }
            other => panic!("{other:?}"),
        }
        for name in names() {
            assert_eq!(
                next(&mut reader),
                Some(Message::ObjectHeader(ObjectHeader {
                    name,
                    encoding: Encoding::Raw,
                }))
            );
            assert_eq!(body(&mut reader), name.checksum.as_bytes());
        }
        assert_eq!(
            next(&mut reader),
            Some(Message::ObjectHeader(ObjectHeader {
                name: ObjectName::new(commit(), ObjectType::CommitMeta),
                encoding: Encoding::Raw,
            }))
        );
        assert!(!body(&mut reader).is_empty());
        assert_eq!(next(&mut reader), Some(Message::ObjectsEnd));
        assert_eq!(
            next(&mut reader),
            Some(Message::Commit(CommitRequest {
                updates: updates(),
                force: false,
                server_commit: None,
            }))
        );
        assert_eq!(next(&mut reader), None);
    }

    /// An output that takes each byte until `fail` is set. After that it
    /// fails each call of `poll_write`, `poll_flush`, and `poll_close`, and
    /// counts it in `failed`.
    struct Probe {
        fail: Arc<AtomicBool>,
        failed: usize,
    }

    impl Probe {
        fn new(fail: bool) -> Probe {
            Probe {
                fail: Arc::new(AtomicBool::new(fail)),
                failed: 0,
            }
        }

        fn call<T>(&mut self, ok: T) -> Poll<io::Result<T>> {
            if self.fail.load(Ordering::Relaxed) {
                self.failed += 1;
                return Poll::Ready(Err(io::Error::other("the output fails")));
            }
            Poll::Ready(Ok(ok))
        }
    }

    impl AsyncWrite for Probe {
        fn poll_write(
            self: Pin<&mut Self>,
            _: &mut Context<'_>,
            buf: &[u8],
        ) -> Poll<io::Result<usize>> {
            self.get_mut().call(buf.len())
        }

        fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
            self.get_mut().call(())
        }

        fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
            self.get_mut().call(())
        }
    }

    /// Each refusal comes before the first byte, as `InvalidInput`, and
    /// makes no call on the output.
    #[test]
    fn a_refusal_writes_nothing() {
        let source = Source { missing: None };
        let long = |n: usize, len: usize| {
            (0..n)
                .map(|i| update(&format!("{i:0len$}"), Expected::Any, Some(commit())))
                .collect::<Vec<_>>()
        };
        let cases: Vec<(&str, Vec<RefUpdate>, Compression, Vec<ObjectName>)> = vec![
            ("empty updates", vec![], Compression::None, names()),
            (
                "a ref named twice",
                vec![updates()[0].clone(), updates()[0].clone()],
                Compression::None,
                names(),
            ),
            (
                "an invalid ref name",
                vec![update("a/../b", Expected::Any, Some(commit()))],
                Compression::None,
                names(),
            ),
            (
                "a ref name outside the ref-name rule",
                vec![update("a b", Expected::Any, Some(commit()))],
                Compression::None,
                names(),
            ),
            (
                "a refspec with a second colon",
                vec![update("o:a:b", Expected::Any, Some(commit()))],
                Compression::None,
                names(),
            ),
            (
                "a ref name of 64 lowercase hex characters",
                vec![update(&"ab".repeat(32), Expected::Any, Some(commit()))],
                Compression::None,
                names(),
            ),
            (
                "an expected commit",
                vec![update("main", Expected::Commit(commit()), Some(commit()))],
                Compression::None,
                names(),
            ),
            (
                "a delete",
                vec![update("main", Expected::Any, None)],
                Compression::None,
                names(),
            ),
            (
                "level 0",
                updates(),
                Compression::Deflate { level: 0 },
                names(),
            ),
            (
                "level 10",
                updates(),
                Compression::Deflate { level: 10 },
                names(),
            ),
            (
                "a name off the wire",
                updates(),
                Compression::None,
                vec![ObjectName::new(commit(), ObjectType::CommitMeta)],
            ),
            (
                "a Hello frame over the limit",
                long(30_000, 40),
                Compression::None,
                names(),
            ),
            (
                "a Commit frame over the limit",
                long(20_000, 40),
                Compression::None,
                names(),
            ),
        ];
        for (case, updates, compression, names) in cases {
            let mut out = Probe::new(true);
            match export(&source, &names, &updates, compression, &mut out) {
                Err(Error::InvalidInput(_)) => {}
                other => panic!("{case}: {other:?}"),
            }
            assert_eq!(out.failed, 0, "{case}: calls on the output");
        }
        // The Commit frame is the one over the limit in the last case.
        let hello = Message::Hello(Hello {
            version: PROTOCOL_VERSION,
            agent: Some("ostrya".into()),
            refs: long(20_000, 40).into_iter().map(|u| u.name).collect(),
            collection: None,
            one_way: true,
        });
        frame(&hello, "Hello").unwrap();
    }

    /// The check of 64 lowercase hex characters applies to a write alone. A
    /// delete of such a name is refused as a delete.
    #[test]
    fn a_delete_of_64_lowercase_hex_characters_is_refused_as_a_delete() {
        let source = Source { missing: None };
        let updates = vec![update(&"ab".repeat(32), Expected::Any, None)];
        let mut out = Probe::new(true);
        match export(&source, &names(), &updates, Compression::None, &mut out) {
            Err(Error::InvalidInput(m)) => assert!(m.contains("deletes the ref"), "{m}"),
            other => panic!("{other:?}"),
        }
        assert_eq!(out.failed, 0);
    }

    /// A source that fails to open an object ends the stream inside that
    /// object: its header, the abandon marker, and `Abort`. The call returns
    /// the error of the source.
    #[test]
    fn a_failed_source_abandons_the_object_it_was_to_send() {
        let missing = names()[1];
        let source = Source {
            missing: Some(missing),
        };
        let mut out = Vec::new();
        match export(&source, &names(), &updates(), Compression::None, &mut out) {
            Err(Error::Source(_)) => {}
            other => panic!("{other:?}"),
        }
        let mut reader = FrameReader::new(&out[..]);
        assert!(matches!(next(&mut reader), Some(Message::Hello(_))));
        assert!(matches!(next(&mut reader), Some(Message::ObjectHeader(_))));
        body(&mut reader);
        assert_eq!(
            next(&mut reader),
            Some(Message::ObjectHeader(ObjectHeader {
                name: missing,
                encoding: Encoding::Raw,
            }))
        );
        let mut buf = [0u8; 64];
        assert_eq!(
            ostrya_rt::block_on(reader.read_object_data(&mut buf)).unwrap(),
            ObjectRead::Abandoned
        );
        assert_eq!(next(&mut reader), None);
        let tail = [&ABANDON.to_be_bytes()[..], &[0, 0, 0, 2, 11, 0]].concat();
        assert!(out.ends_with(&tail));
    }

    /// A failed write of the header of the object that the source fails to
    /// open ends the call with the error of the write, and the call writes
    /// nothing more: no `Abort` and no flush.
    #[test]
    fn a_failed_header_write_ends_the_call() {
        /// A source whose first name has `len` bytes, and whose other names
        /// fail to open and make the output fail.
        struct Failing {
            len: usize,
            fail: Arc<AtomicBool>,
        }

        impl ObjectSource for Failing {
            fn objects<'a>(&'a self, _: &'a Checksum) -> BoxFuture<'a, Result<Vec<ObjectName>>> {
                Box::pin(async { Ok(Vec::new()) })
            }

            fn open<'a>(
                &'a self,
                name: &'a ObjectName,
                _: Encoding,
            ) -> BoxFuture<'a, Result<ObjectData>> {
                Box::pin(async move {
                    if *name != names()[0] {
                        self.fail.store(true, Ordering::Relaxed);
                        return Err(invalid("no such object"));
                    }
                    Ok(ObjectData::Encoded {
                        encoding: Encoding::Raw,
                        reader: Box::new(Cursor::new(vec![0; self.len])),
                    })
                })
            }

            fn detached_metadata<'a>(
                &'a self,
                _: &'a Checksum,
            ) -> BoxFuture<'a, Result<Option<Value>>> {
                Box::pin(async { Ok(None) })
            }
        }

        let header = |name: ObjectName| {
            encode_frame(
                &Message::ObjectHeader(ObjectHeader {
                    name,
                    encoding: Encoding::Raw,
                }),
                MIN_FRAME_LIMIT,
            )
            .unwrap()
            .len()
        };
        let hello = frame(
            &Message::Hello(Hello {
                version: PROTOCOL_VERSION,
                agent: Some("test".into()),
                refs: updates().into_iter().map(|u| u.name).collect(),
                collection: None,
                one_way: true,
            }),
            "Hello",
        )
        .unwrap()
        .len();
        // The first object, its one chunk with its length, and its end
        // chunk leave one free byte in the output buffer, so the header of
        // the second object makes the buffer write to the output.
        let len = WRITE_BUFFER - 1 - hello - header(names()[0]) - 4 - 4;
        assert!(len <= super::super::writer::CHUNK_PAYLOAD);
        let mut out = Probe::new(false);
        let source = Failing {
            len,
            fail: Arc::clone(&out.fail),
        };
        let result = ostrya_rt::block_on(export_stream(
            &mut out,
            &source,
            &names(),
            &[commit()],
            &updates(),
            Compression::None,
            SessionOptions {
                agent: Some("test".into()),
                ..SessionOptions::default()
            },
        ));
        match result {
            Err(Error::Io(_)) => {}
            other => panic!("{other:?}"),
        }
        assert_eq!(out.failed, 1, "calls on the output after the failure");
    }
}