ostrya-remote 0.8.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
//! The progress handle of a push and the statistics of a session.

use std::fmt;
use std::sync::Arc;
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
use std::time::{Duration, Instant};

use ostrya_core::{ObjectName, ObjectType};

/// The step that a push is in.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PushPhase {
    /// The client reads its source and builds the object list.
    ///
    /// A tree push shows this phase from the start of its scan to the end of
    /// the walk, which lists and filters each directory. Hash jobs can run in
    /// this phase. A new [`PushProgress`] starts in this phase.
    ///
    /// A tree scan sets this phase with [`PushProgress::start_phase`] before
    /// its walk, and `Repo::push_to_bucket` sets it after its local checks.
    /// Thus the hook of a tree scan and of `Repo::push_to_bucket` gets one
    /// call with this phase, also on a new handle. A push that does not scan
    /// a tree, such as `Repo::push` of the `ostrya` crate, does not set this
    /// phase. Its first hook call has the phase
    /// [`Connecting`](PushPhase::Connecting).
    #[default]
    Scanning,
    /// The client hashes the files and the directories of a tree.
    ///
    /// A tree push shows this phase after the walk. In this phase, the hash
    /// jobs that still run come to an end, and the client hashes the
    /// directories bottom-up.
    Hashing,
    /// The session starts its transport and exchanges `Hello` with the server.
    ///
    /// In this phase, an ssh client can ask for a password or a passphrase on
    /// the terminal.
    Connecting,
    /// The session exchanges `Have` with the server.
    Negotiating,
    /// The session sends objects.
    Uploading,
    /// The session sends `Commit` and waits for the reply.
    Committing,
}

impl PushPhase {
    fn as_u8(self) -> u8 {
        match self {
            PushPhase::Scanning => 0,
            PushPhase::Hashing => 1,
            PushPhase::Negotiating => 2,
            PushPhase::Uploading => 3,
            PushPhase::Committing => 4,
            PushPhase::Connecting => 5,
        }
    }

    fn from_u8(byte: u8) -> PushPhase {
        match byte {
            1 => PushPhase::Hashing,
            2 => PushPhase::Negotiating,
            3 => PushPhase::Uploading,
            4 => PushPhase::Committing,
            5 => PushPhase::Connecting,
            _ => PushPhase::Scanning,
        }
    }
}

/// A hook that receives the counters of a [`PushProgress`] at the start of a
/// scan and when they change.
///
/// The hook gets a call at each call of
/// [`start_phase`](PushProgress::start_phase), also when the phase does not
/// change. A tree scan and `Repo::push_to_bucket` make this call. The hook
/// also gets a call at a change that a progress display shows.
/// [Hook calls](PushProgress#hook-calls) lists these calls.
///
/// The hook runs on the task that causes the hook call: the task of a
/// session or of a one-way export with [`export_stream`](super::export_stream),
/// the task of the scan of a tree push, the task of a push to a bucket
/// repository, or the task of a client that calls
/// [`set_phase`](PushProgress::set_phase),
/// [`start_phase`](PushProgress::start_phase),
/// [`object_uploaded`](PushProgress::object_uploaded), or
/// [`add_content`](PushProgress::add_content). Over HTTP, each parallel
/// object stream of a session calls the hook, so more than one thread can
/// call it at the same time. The session waits for the hook, so the hook
/// must return soon.
///
/// A hook that keeps state between calls holds that state behind interior
/// mutability of its own, for example an atomic or a mutex.
pub type PushProgressFn = Arc<dyn Fn(&PushProgressSnapshot) + Send + Sync>;

/// The step of the content count at which the hook gets a call: 100 KiB.
const HOOK_BYTE_STEP: u64 = 102_400;

/// A handle on the live counters of pushes.
///
/// A caller sets a clone of the handle in
/// [`SessionOptions::progress`](super::SessionOptions::progress). Then it
/// reads [`snapshot`](PushProgress::snapshot) from another task or thread
/// while the push runs. A session adds to the counters of the handle and
/// never sets them to zero.
///
/// If several sessions share a handle, the handle shows the sum of their
/// counters and the phase of the session that set it last.
///
/// The [`PushStats`] of a session come from counters of its own, and the
/// handle does not change them. Each count is one relaxed atomic add to those
/// counters, and one more to the handle if the session has one.
///
/// # Hook calls
///
/// A handle made with [`with_hook`](PushProgress::with_hook) calls its hook
/// with a snapshot at these times:
///
/// - at each call of [`start_phase`](PushProgress::start_phase), also when
///   the phase does not change
/// - each time the phase changes to another phase
/// - after each object of the object stream, and at each call of
///   [`object_uploaded`](PushProgress::object_uploaded), when
///   [`objects_sent`](PushProgressSnapshot::objects_sent) grows
/// - each time [`content_bytes`](PushProgressSnapshot::content_bytes)
///   reaches the next multiple of 102,400 bytes (100 KiB)
///
/// A `start_phase` call gives one hook call, also when it changes the phase.
/// A tree scan calls `start_phase` with [`Scanning`](PushPhase::Scanning)
/// before its walk. `Repo::push_to_bucket` of the `ostrya` crate pushes the
/// commits of a local repository to a bucket repository. It calls
/// `start_phase` with `Scanning` after its local checks and before it takes
/// the writer lock. A tree push to a bucket repository gets its one call
/// from its tree scan. Thus in these pushes the hook of a new handle, which
/// holds `Scanning`, gets a call with `Scanning`.
#[derive(Debug, Clone, Default)]
pub struct PushProgress {
    inner: Arc<ProgressCounters>,
}

impl PushProgress {
    /// Creates a handle whose counters are all zero.
    pub fn new() -> PushProgress {
        PushProgress::default()
    }

    /// Creates a handle whose counters are all zero and that calls `hook`.
    ///
    /// [Hook calls](PushProgress#hook-calls) lists the calls.
    /// [`PushProgressFn`] gives the rules of the hook.
    pub fn with_hook(hook: PushProgressFn) -> PushProgress {
        PushProgress {
            inner: Arc::new(ProgressCounters {
                hook: Some(hook),
                ..ProgressCounters::default()
            }),
        }
    }

    /// Returns the counters as they stand now.
    ///
    /// The method reads each counter on its own, so two counters of one
    /// snapshot can differ by the work of one step.
    pub fn snapshot(&self) -> PushProgressSnapshot {
        self.inner.snapshot()
    }

    /// Sets the phase of the handle, and calls the hook if the phase
    /// changed.
    ///
    /// A session and a tree push set the phase on their own. A client that
    /// uploads with no session, for example a push to a bucket repository,
    /// calls this method.
    pub fn set_phase(&self, phase: PushPhase) {
        self.inner.set_phase(phase);
    }

    /// Sets the phase of the handle, and calls the hook.
    ///
    /// This method calls the hook also when the phase does not change.
    /// [`set_phase`](PushProgress::set_phase) calls the hook only when the
    /// phase changes. A tree scan calls this method before its walk, and
    /// `Repo::push_to_bucket` of the `ostrya` crate calls it after its local
    /// checks. A tree push to a bucket repository gets its one call from its
    /// tree scan. Thus in these pushes the hook of a new handle, which holds
    /// [`PushPhase::Scanning`], gets a call with `Scanning`.
    ///
    /// [Hook calls](PushProgress#hook-calls) lists the calls.
    pub fn start_phase(&self, phase: PushPhase) {
        self.inner.start_phase(phase);
    }

    /// Adds `objects` to [`objects_needed`](PushProgressSnapshot::objects_needed)
    /// and `content_bytes` to [`bytes_total`](PushProgressSnapshot::bytes_total).
    ///
    /// A client that uploads with no session calls this method before its
    /// first upload. The call does not call the hook. The next change of the
    /// phase gives the hook the new counters.
    pub fn add_upload(&self, objects: u64, content_bytes: u64) {
        self.inner
            .objects_needed
            .fetch_add(objects, Ordering::Relaxed);
        self.inner
            .bytes_total
            .fetch_add(content_bytes, Ordering::Relaxed);
    }

    /// Adds one to [`objects_sent`](PushProgressSnapshot::objects_sent), and
    /// calls the hook.
    ///
    /// A client that uploads with no session calls this method after each
    /// object that it uploaded.
    pub fn object_uploaded(&self) {
        self.inner.object_sent();
    }

    /// Adds `n` to [`content_bytes`](PushProgressSnapshot::content_bytes),
    /// and calls the hook if the count reaches the next multiple of 102,400
    /// bytes (100 KiB).
    ///
    /// A client that uploads with no session calls this method as it reads
    /// the content of the file objects that it uploads.
    pub fn add_content(&self, n: u64) {
        self.inner.content(n);
    }
}

/// The counters of a [`PushProgress`] at one point in time.
///
/// Code outside this crate gets a snapshot from [`PushProgress::snapshot`],
/// from the hook, or from `Default`, and reads its fields by name.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct PushProgressSnapshot {
    /// The step that the push is in.
    pub phase: PushPhase,
    /// The count of [`PushStats::objects_total`] so far.
    pub objects_total: u64,
    /// The count of [`PushStats::objects_needed`] so far.
    pub objects_needed: u64,
    /// The count of [`PushStats::objects_sent`] so far.
    pub objects_sent: u64,
    /// The count of [`PushStats::bytes_sent`] so far.
    pub bytes_sent: u64,
    /// The count of [`PushStats::payload_bytes`] so far.
    pub payload_bytes: u64,
    /// The content bytes that the session read so far.
    ///
    /// These are the bytes that the session read from the reader that its
    /// source gave for each file object, before the compressor of the
    /// session. A stored `.filez` that the session sends as it is counts
    /// with its stored bytes. A symlink, a metadata object, and detached
    /// metadata count no byte.
    pub content_bytes: u64,
    /// The content bytes of the file objects that the session sends.
    ///
    /// The source tells this total before the first object, so
    /// `content_bytes` ends at this total. If the source does not tell it,
    /// or the query fails, the total stays 0. See
    /// [`ObjectSource::content_size`](super::ObjectSource::content_size).
    pub bytes_total: u64,
}

/// The statistics of one push session.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PushStats {
    /// The number of objects that the client offered in `Have`.
    ///
    /// A composefs image does not count.
    pub objects_total: u64,
    /// The number of objects that the server asked for in `HaveReply`.
    ///
    /// A composefs image does not count.
    pub objects_needed: u64,
    /// The number of objects that the session sent in the object stream.
    ///
    /// A detached metadata object and a composefs image do not count.
    pub objects_sent: u64,
    /// The number of bytes that the session gave to its transport.
    ///
    /// The count holds the frames, the chunk lengths, and the object bytes.
    /// On a stream transport, a byte counts when the session writes it to
    /// the stream.
    ///
    /// Over HTTP, the request bodies count and the HTTP heads do not:
    ///
    /// - A whole body, as for `Hello`, `Have`, and `Commit`, counts when the
    ///   client gives its request to a connection. It counts if the request
    ///   gets a response, and also if the request fails after the hand-over.
    /// - An object stream counts each byte that it writes into its request
    ///   body after the hand-over. At the hand-over, it counts the bytes that
    ///   it wrote before.
    /// - A request that the client never gives to a connection counts no
    ///   byte.
    pub bytes_sent: u64,
    /// The object bytes that the session sent, without the chunk lengths.
    ///
    /// The bytes are in the encoding that the session sent them in. Detached
    /// metadata objects and composefs images count.
    pub payload_bytes: u64,
    /// The time that the session ran.
    ///
    /// The clock starts when the session opens: after the ssh client starts,
    /// or before the first HTTP request. The scan and the hash pass of a tree
    /// push do not count.
    pub elapsed: Duration,
}

/// The counters behind a [`PushProgress`], and the counters of one session.
#[derive(Default)]
struct ProgressCounters {
    phase: AtomicU8,
    objects_total: AtomicU64,
    objects_needed: AtomicU64,
    objects_sent: AtomicU64,
    bytes_sent: AtomicU64,
    payload_bytes: AtomicU64,
    content_bytes: AtomicU64,
    bytes_total: AtomicU64,
    /// The hook of the handle. The counters of a session have none.
    hook: Option<PushProgressFn>,
}

impl fmt::Debug for ProgressCounters {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ProgressCounters")
            .field("counters", &self.snapshot())
            .field("hook", &self.hook.is_some())
            .finish()
    }
}

impl ProgressCounters {
    fn snapshot(&self) -> PushProgressSnapshot {
        PushProgressSnapshot {
            phase: PushPhase::from_u8(self.phase.load(Ordering::Relaxed)),
            objects_total: self.objects_total.load(Ordering::Relaxed),
            objects_needed: self.objects_needed.load(Ordering::Relaxed),
            objects_sent: self.objects_sent.load(Ordering::Relaxed),
            bytes_sent: self.bytes_sent.load(Ordering::Relaxed),
            payload_bytes: self.payload_bytes.load(Ordering::Relaxed),
            content_bytes: self.content_bytes.load(Ordering::Relaxed),
            bytes_total: self.bytes_total.load(Ordering::Relaxed),
        }
    }

    /// Calls the hook with the counters as they stand.
    fn call_hook(&self) {
        if let Some(hook) = &self.hook {
            hook(&self.snapshot());
        }
    }

    /// Sets the phase, and calls the hook if the phase changed.
    fn set_phase(&self, phase: PushPhase) {
        let before = self.phase.swap(phase.as_u8(), Ordering::Relaxed);
        if before != phase.as_u8() {
            self.call_hook();
        }
    }

    /// Sets the phase, and calls the hook also if the phase did not change.
    fn start_phase(&self, phase: PushPhase) {
        self.phase.store(phase.as_u8(), Ordering::Relaxed);
        self.call_hook();
    }

    /// Counts one object sent, and calls the hook.
    fn object_sent(&self) {
        self.objects_sent.fetch_add(1, Ordering::Relaxed);
        self.call_hook();
    }

    /// Counts `n` content bytes, and calls the hook if the count reaches the
    /// next multiple of [`HOOK_BYTE_STEP`].
    fn content(&self, n: u64) {
        let before = self.content_bytes.fetch_add(n, Ordering::Relaxed);
        if before / HOOK_BYTE_STEP != before.wrapping_add(n) / HOOK_BYTE_STEP {
            self.call_hook();
        }
    }
}

/// The counters that one session counts into: its own, which its
/// [`PushStats`] read, and the handle of the caller, which receives the same
/// additions.
#[derive(Debug)]
pub(crate) struct Counters {
    own: ProgressCounters,
    caller: Option<Arc<ProgressCounters>>,
    start: Instant,
}

impl Counters {
    /// Creates the counters of a session that starts now. The session also
    /// counts into `caller` if there is one.
    pub(crate) fn new(caller: Option<&PushProgress>) -> Counters {
        Counters {
            own: ProgressCounters::default(),
            caller: caller.map(|progress| Arc::clone(&progress.inner)),
            start: Instant::now(),
        }
    }

    /// Runs `f` on the own counters of the session, then on the counters of
    /// the caller.
    fn each(&self, f: impl Fn(&ProgressCounters)) {
        f(&self.own);
        if let Some(caller) = &self.caller {
            f(caller);
        }
    }

    pub(crate) fn phase(&self, phase: PushPhase) {
        self.each(|c| c.set_phase(phase));
    }

    /// Counts the objects of `names` as offered. A composefs image does not
    /// count.
    pub(crate) fn offered(&self, names: &[ObjectName]) {
        let n = object_count(names);
        self.each(|c| {
            c.objects_total.fetch_add(n, Ordering::Relaxed);
        });
    }

    /// Counts the objects of `names` as needed. A composefs image does not
    /// count.
    pub(crate) fn needed(&self, names: &[ObjectName]) {
        let n = object_count(names);
        self.each(|c| {
            c.objects_needed.fetch_add(n, Ordering::Relaxed);
        });
    }

    /// Counts the object `name` as sent. A composefs image does not count.
    pub(crate) fn object_sent(&self, name: &ObjectName) {
        if name.ty != ObjectType::ComposefsImage {
            self.each(ProgressCounters::object_sent);
        }
    }

    /// Counts `n` content bytes read from the source of a file object.
    pub(crate) fn content(&self, n: u64) {
        self.each(|c| c.content(n));
    }

    /// Adds `n` to the content bytes that the session will send.
    pub(crate) fn content_total(&self, n: u64) {
        self.each(|c| {
            c.bytes_total.fetch_add(n, Ordering::Relaxed);
        });
    }

    /// Returns `true` if a handle of the caller receives the counts.
    pub(crate) fn has_caller(&self) -> bool {
        self.caller.is_some()
    }

    pub(crate) fn wire(&self, n: u64) {
        self.each(|c| {
            c.bytes_sent.fetch_add(n, Ordering::Relaxed);
        });
    }

    pub(crate) fn payload(&self, n: u64) {
        self.each(|c| {
            c.payload_bytes.fetch_add(n, Ordering::Relaxed);
        });
    }

    /// Returns the statistics of the session so far.
    pub(crate) fn stats(&self) -> PushStats {
        let s = self.own.snapshot();
        PushStats {
            objects_total: s.objects_total,
            objects_needed: s.objects_needed,
            objects_sent: s.objects_sent,
            bytes_sent: s.bytes_sent,
            payload_bytes: s.payload_bytes,
            elapsed: self.start.elapsed(),
        }
    }
}

/// Returns the number of names in `names` that the object counts of a
/// session count: each name but a composefs image.
fn object_count(names: &[ObjectName]) -> u64 {
    names
        .iter()
        .filter(|n| n.ty != ObjectType::ComposefsImage)
        .count() as u64
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Mutex;

    /// The methods of a client with no session change the snapshot, and call
    /// the hook at a new phase, at each uploaded object, and at each 100 KiB
    /// step of the content.
    #[test]
    fn the_upload_methods_change_the_snapshot_and_call_the_hook() {
        let calls: Arc<Mutex<Vec<PushProgressSnapshot>>> = Arc::default();
        let seen = Arc::clone(&calls);
        let progress = PushProgress::with_hook(Arc::new(move |snapshot| {
            seen.lock().unwrap().push(*snapshot);
        }));
        progress.set_phase(PushPhase::Scanning);
        assert!(calls.lock().unwrap().is_empty(), "the phase did not change");
        progress.add_upload(3, 250_000);
        assert!(calls.lock().unwrap().is_empty(), "add_upload calls no hook");
        progress.set_phase(PushPhase::Uploading);
        let last = *calls.lock().unwrap().last().unwrap();
        assert_eq!(last.phase, PushPhase::Uploading);
        assert_eq!((last.objects_needed, last.bytes_total), (3, 250_000));

        progress.add_content(100_000);
        assert_eq!(calls.lock().unwrap().len(), 1, "below the first step");
        progress.add_content(2_400);
        assert_eq!(calls.lock().unwrap().len(), 2, "at the first step");
        progress.object_uploaded();
        let last = *calls.lock().unwrap().last().unwrap();
        assert_eq!(calls.lock().unwrap().len(), 3);
        assert_eq!((last.objects_sent, last.content_bytes), (1, 102_400));
        assert_eq!(progress.snapshot(), last);
    }

    /// On a new handle, `start_phase` with `Scanning` calls the hook one
    /// time. A `set_phase` with `Scanning` after it calls no hook.
    #[test]
    fn start_phase_calls_the_hook_when_the_phase_does_not_change() {
        let calls: Arc<Mutex<Vec<PushProgressSnapshot>>> = Arc::default();
        let seen = Arc::clone(&calls);
        let progress = PushProgress::with_hook(Arc::new(move |snapshot| {
            seen.lock().unwrap().push(*snapshot);
        }));
        progress.start_phase(PushPhase::Scanning);
        let phases: Vec<PushPhase> = calls.lock().unwrap().iter().map(|c| c.phase).collect();
        assert_eq!(phases, [PushPhase::Scanning]);
        progress.set_phase(PushPhase::Scanning);
        assert_eq!(calls.lock().unwrap().len(), 1, "the phase did not change");
    }
}