Skip to main content

ostrya_remote/session/
progress.rs

1//! The progress handle of a push and the statistics of a session.
2
3use std::fmt;
4use std::sync::Arc;
5use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
6use std::time::{Duration, Instant};
7
8use ostrya_core::ObjectName;
9
10/// The step that a push is in.
11#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
12#[non_exhaustive]
13pub enum PushPhase {
14    /// The client reads its source and builds the object list.
15    ///
16    /// A tree push shows this phase from the start of its scan to the end of
17    /// the walk, which lists and filters each directory. Hash jobs can run in
18    /// this phase. A new [`PushProgress`] starts in this phase.
19    ///
20    /// A tree scan sets this phase with [`PushProgress::start_phase`] before
21    /// its walk, and `Repo::push_to_bucket` sets it after its local checks.
22    /// Thus the hook of a tree scan and of `Repo::push_to_bucket` gets one
23    /// call with this phase, also on a new handle. A push that does not scan
24    /// a tree, such as `Repo::push` of the `ostrya` crate, does not set this
25    /// phase. Its first hook call has the phase
26    /// [`Connecting`](PushPhase::Connecting).
27    #[default]
28    Scanning,
29    /// The client hashes the files and the directories of a tree.
30    ///
31    /// A tree push shows this phase after the walk. In this phase, the hash
32    /// jobs that still run come to an end, and the client hashes the
33    /// directories bottom-up.
34    Hashing,
35    /// The session starts its transport and exchanges `Hello` with the server.
36    ///
37    /// In this phase, an ssh client can ask for a password or a passphrase on
38    /// the terminal.
39    Connecting,
40    /// The session exchanges `Have` with the server.
41    Negotiating,
42    /// The session sends objects.
43    Uploading,
44    /// The session sends `Commit` and waits for the reply.
45    Committing,
46}
47
48impl PushPhase {
49    fn as_u8(self) -> u8 {
50        match self {
51            PushPhase::Scanning => 0,
52            PushPhase::Hashing => 1,
53            PushPhase::Negotiating => 2,
54            PushPhase::Uploading => 3,
55            PushPhase::Committing => 4,
56            PushPhase::Connecting => 5,
57        }
58    }
59
60    fn from_u8(byte: u8) -> PushPhase {
61        match byte {
62            1 => PushPhase::Hashing,
63            2 => PushPhase::Negotiating,
64            3 => PushPhase::Uploading,
65            4 => PushPhase::Committing,
66            5 => PushPhase::Connecting,
67            _ => PushPhase::Scanning,
68        }
69    }
70}
71
72/// A hook that receives the counters of a [`PushProgress`] at the start of a
73/// scan and when they change.
74///
75/// The hook gets a call at each call of
76/// [`start_phase`](PushProgress::start_phase), also when the phase does not
77/// change. A tree scan and `Repo::push_to_bucket` make this call. The hook
78/// also gets a call at a change that a progress display shows.
79/// [Hook calls](PushProgress#hook-calls) lists these calls.
80///
81/// The hook runs on the task that causes the hook call: the task of a
82/// session or of a one-way export with [`export_stream`](super::export_stream),
83/// the task of the scan of a tree push, the task of a push to a bucket
84/// repository, or the task of a client that calls
85/// [`set_phase`](PushProgress::set_phase),
86/// [`start_phase`](PushProgress::start_phase),
87/// [`object_uploaded`](PushProgress::object_uploaded), or
88/// [`add_content`](PushProgress::add_content). Over HTTP, each parallel
89/// object stream of a session calls the hook, so more than one thread can
90/// call it at the same time. The session waits for the hook, so the hook
91/// must return soon.
92///
93/// A hook that keeps state between calls holds that state behind interior
94/// mutability of its own, for example an atomic or a mutex.
95pub type PushProgressFn = Arc<dyn Fn(&PushProgressSnapshot) + Send + Sync>;
96
97/// The step of the content count at which the hook gets a call: 100 KiB.
98const HOOK_BYTE_STEP: u64 = 102_400;
99
100/// A handle on the live counters of pushes.
101///
102/// A caller sets a clone of the handle in
103/// [`SessionOptions::progress`](super::SessionOptions::progress). Then it
104/// reads [`snapshot`](PushProgress::snapshot) from another task or thread
105/// while the push runs. A session adds to the counters of the handle and
106/// never sets them to zero.
107///
108/// If several sessions share a handle, the handle shows the sum of their
109/// counters and the phase of the session that set it last.
110///
111/// The [`PushStats`] of a session come from counters of its own, and the
112/// handle does not change them. Each count is one relaxed atomic add to those
113/// counters, and one more to the handle if the session has one.
114///
115/// # Hook calls
116///
117/// A handle made with [`with_hook`](PushProgress::with_hook) calls its hook
118/// with a snapshot at these times:
119///
120/// - at each call of [`start_phase`](PushProgress::start_phase), also when
121///   the phase does not change
122/// - each time the phase changes to another phase
123/// - after each object of the object stream, and at each call of
124///   [`object_uploaded`](PushProgress::object_uploaded), when
125///   [`objects_sent`](PushProgressSnapshot::objects_sent) grows
126/// - each time [`content_bytes`](PushProgressSnapshot::content_bytes)
127///   reaches the next multiple of 102,400 bytes (100 KiB)
128///
129/// A `start_phase` call gives one hook call, also when it changes the phase.
130/// A tree scan calls `start_phase` with [`Scanning`](PushPhase::Scanning)
131/// before its walk. `Repo::push_to_bucket` of the `ostrya` crate pushes the
132/// commits of a local repository to a bucket repository. It calls
133/// `start_phase` with `Scanning` after its local checks and before it takes
134/// the writer lock. A tree push to a bucket repository gets its one call
135/// from its tree scan. Thus in these pushes the hook of a new handle, which
136/// holds `Scanning`, gets a call with `Scanning`.
137#[derive(Debug, Clone, Default)]
138pub struct PushProgress {
139    inner: Arc<ProgressCounters>,
140}
141
142impl PushProgress {
143    /// Creates a handle whose counters are all zero.
144    pub fn new() -> PushProgress {
145        PushProgress::default()
146    }
147
148    /// Creates a handle whose counters are all zero and that calls `hook`.
149    ///
150    /// [Hook calls](PushProgress#hook-calls) lists the calls.
151    /// [`PushProgressFn`] gives the rules of the hook.
152    pub fn with_hook(hook: PushProgressFn) -> PushProgress {
153        PushProgress {
154            inner: Arc::new(ProgressCounters {
155                hook: Some(hook),
156                ..ProgressCounters::default()
157            }),
158        }
159    }
160
161    /// Returns the counters as they stand now.
162    ///
163    /// The method reads each counter on its own, so two counters of one
164    /// snapshot can differ by the work of one step.
165    pub fn snapshot(&self) -> PushProgressSnapshot {
166        self.inner.snapshot()
167    }
168
169    /// Sets the phase of the handle, and calls the hook if the phase
170    /// changed.
171    ///
172    /// A session and a tree push set the phase on their own. A client that
173    /// uploads with no session, for example a push to a bucket repository,
174    /// calls this method.
175    pub fn set_phase(&self, phase: PushPhase) {
176        self.inner.set_phase(phase);
177    }
178
179    /// Sets the phase of the handle, and calls the hook.
180    ///
181    /// This method calls the hook also when the phase does not change.
182    /// [`set_phase`](PushProgress::set_phase) calls the hook only when the
183    /// phase changes. A tree scan calls this method before its walk, and
184    /// `Repo::push_to_bucket` of the `ostrya` crate calls it after its local
185    /// checks. A tree push to a bucket repository gets its one call from its
186    /// tree scan. Thus in these pushes the hook of a new handle, which holds
187    /// [`PushPhase::Scanning`], gets a call with `Scanning`.
188    ///
189    /// [Hook calls](PushProgress#hook-calls) lists the calls.
190    pub fn start_phase(&self, phase: PushPhase) {
191        self.inner.start_phase(phase);
192    }
193
194    /// Adds `objects` to [`objects_needed`](PushProgressSnapshot::objects_needed)
195    /// and `content_bytes` to [`bytes_total`](PushProgressSnapshot::bytes_total).
196    ///
197    /// A client that uploads with no session calls this method before its
198    /// first upload. The call does not call the hook. The next change of the
199    /// phase gives the hook the new counters.
200    pub fn add_upload(&self, objects: u64, content_bytes: u64) {
201        self.inner
202            .objects_needed
203            .fetch_add(objects, Ordering::Relaxed);
204        self.inner
205            .bytes_total
206            .fetch_add(content_bytes, Ordering::Relaxed);
207    }
208
209    /// Adds one to [`objects_sent`](PushProgressSnapshot::objects_sent), and
210    /// calls the hook.
211    ///
212    /// A client that uploads with no session calls this method after each
213    /// object that it uploaded.
214    pub fn object_uploaded(&self) {
215        self.inner.object_sent();
216    }
217
218    /// Adds `n` to [`content_bytes`](PushProgressSnapshot::content_bytes),
219    /// and calls the hook if the count reaches the next multiple of 102,400
220    /// bytes (100 KiB).
221    ///
222    /// A client that uploads with no session calls this method as it reads
223    /// the content of the file objects that it uploads.
224    pub fn add_content(&self, n: u64) {
225        self.inner.content(n);
226    }
227}
228
229/// The counters of a [`PushProgress`] at one point in time.
230///
231/// Code outside this crate gets a snapshot from [`PushProgress::snapshot`],
232/// from the hook, or from `Default`, and reads its fields by name.
233#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
234#[non_exhaustive]
235pub struct PushProgressSnapshot {
236    /// The step that the push is in.
237    pub phase: PushPhase,
238    /// The count of [`PushStats::objects_total`] so far.
239    pub objects_total: u64,
240    /// The count of [`PushStats::objects_needed`] so far.
241    pub objects_needed: u64,
242    /// The count of [`PushStats::objects_sent`] so far.
243    pub objects_sent: u64,
244    /// The count of [`PushStats::bytes_sent`] so far.
245    pub bytes_sent: u64,
246    /// The count of [`PushStats::payload_bytes`] so far.
247    pub payload_bytes: u64,
248    /// The content bytes that the session read so far.
249    ///
250    /// These are the bytes that the session read from the reader that its
251    /// source gave for each file object, before the compressor of the
252    /// session. A stored `.filez` that the session sends as it is counts
253    /// with its stored bytes. A symlink, a metadata object, and detached
254    /// metadata count no byte.
255    pub content_bytes: u64,
256    /// The content bytes of the file objects that the session sends.
257    ///
258    /// The source tells this total before the first object, so
259    /// `content_bytes` ends at this total. If the source does not tell it,
260    /// or the query fails, the total stays 0. See
261    /// [`ObjectSource::content_size`](super::ObjectSource::content_size).
262    pub bytes_total: u64,
263}
264
265/// The statistics of one push session.
266#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
267pub struct PushStats {
268    /// The number of objects that the client offered in `Have`.
269    pub objects_total: u64,
270    /// The number of objects that the server asked for in `HaveReply`.
271    pub objects_needed: u64,
272    /// The number of objects that the session sent in the object stream.
273    ///
274    /// A detached metadata object does not count.
275    pub objects_sent: u64,
276    /// The number of bytes that the session gave to its transport.
277    ///
278    /// The count holds the frames, the chunk lengths, and the object bytes.
279    /// On a stream transport, a byte counts when the session writes it to
280    /// the stream.
281    ///
282    /// Over HTTP, the request bodies count and the HTTP heads do not:
283    ///
284    /// - A whole body, as for `Hello`, `Have`, and `Commit`, counts when the
285    ///   client gives its request to a connection. It counts if the request
286    ///   gets a response, and also if the request fails after the hand-over.
287    /// - An object stream counts each byte that it writes into its request
288    ///   body after the hand-over. At the hand-over, it counts the bytes that
289    ///   it wrote before.
290    /// - A request that the client never gives to a connection counts no
291    ///   byte.
292    pub bytes_sent: u64,
293    /// The object bytes that the session sent, without the chunk lengths.
294    ///
295    /// The bytes are in the encoding that the session sent them in. Detached
296    /// metadata objects count.
297    pub payload_bytes: u64,
298    /// The time that the session ran.
299    ///
300    /// The clock starts when the session opens: after the ssh client starts,
301    /// or before the first HTTP request. The scan and the hash pass of a tree
302    /// push do not count.
303    pub elapsed: Duration,
304}
305
306/// The counters behind a [`PushProgress`], and the counters of one session.
307#[derive(Default)]
308struct ProgressCounters {
309    phase: AtomicU8,
310    objects_total: AtomicU64,
311    objects_needed: AtomicU64,
312    objects_sent: AtomicU64,
313    bytes_sent: AtomicU64,
314    payload_bytes: AtomicU64,
315    content_bytes: AtomicU64,
316    bytes_total: AtomicU64,
317    /// The hook of the handle. The counters of a session have none.
318    hook: Option<PushProgressFn>,
319}
320
321impl fmt::Debug for ProgressCounters {
322    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
323        f.debug_struct("ProgressCounters")
324            .field("counters", &self.snapshot())
325            .field("hook", &self.hook.is_some())
326            .finish()
327    }
328}
329
330impl ProgressCounters {
331    fn snapshot(&self) -> PushProgressSnapshot {
332        PushProgressSnapshot {
333            phase: PushPhase::from_u8(self.phase.load(Ordering::Relaxed)),
334            objects_total: self.objects_total.load(Ordering::Relaxed),
335            objects_needed: self.objects_needed.load(Ordering::Relaxed),
336            objects_sent: self.objects_sent.load(Ordering::Relaxed),
337            bytes_sent: self.bytes_sent.load(Ordering::Relaxed),
338            payload_bytes: self.payload_bytes.load(Ordering::Relaxed),
339            content_bytes: self.content_bytes.load(Ordering::Relaxed),
340            bytes_total: self.bytes_total.load(Ordering::Relaxed),
341        }
342    }
343
344    /// Calls the hook with the counters as they stand.
345    fn call_hook(&self) {
346        if let Some(hook) = &self.hook {
347            hook(&self.snapshot());
348        }
349    }
350
351    /// Sets the phase, and calls the hook if the phase changed.
352    fn set_phase(&self, phase: PushPhase) {
353        let before = self.phase.swap(phase.as_u8(), Ordering::Relaxed);
354        if before != phase.as_u8() {
355            self.call_hook();
356        }
357    }
358
359    /// Sets the phase, and calls the hook also if the phase did not change.
360    fn start_phase(&self, phase: PushPhase) {
361        self.phase.store(phase.as_u8(), Ordering::Relaxed);
362        self.call_hook();
363    }
364
365    /// Counts one object sent, and calls the hook.
366    fn object_sent(&self) {
367        self.objects_sent.fetch_add(1, Ordering::Relaxed);
368        self.call_hook();
369    }
370
371    /// Counts `n` content bytes, and calls the hook if the count reaches the
372    /// next multiple of [`HOOK_BYTE_STEP`].
373    fn content(&self, n: u64) {
374        let before = self.content_bytes.fetch_add(n, Ordering::Relaxed);
375        if before / HOOK_BYTE_STEP != before.wrapping_add(n) / HOOK_BYTE_STEP {
376            self.call_hook();
377        }
378    }
379}
380
381/// The counters that one session counts into: its own, which its
382/// [`PushStats`] read, and the handle of the caller, which receives the same
383/// additions.
384#[derive(Debug)]
385pub(crate) struct Counters {
386    own: ProgressCounters,
387    caller: Option<Arc<ProgressCounters>>,
388    start: Instant,
389}
390
391impl Counters {
392    /// Creates the counters of a session that starts now. The session also
393    /// counts into `caller` if there is one.
394    pub(crate) fn new(caller: Option<&PushProgress>) -> Counters {
395        Counters {
396            own: ProgressCounters::default(),
397            caller: caller.map(|progress| Arc::clone(&progress.inner)),
398            start: Instant::now(),
399        }
400    }
401
402    /// Runs `f` on the own counters of the session, then on the counters of
403    /// the caller.
404    fn each(&self, f: impl Fn(&ProgressCounters)) {
405        f(&self.own);
406        if let Some(caller) = &self.caller {
407            f(caller);
408        }
409    }
410
411    pub(crate) fn phase(&self, phase: PushPhase) {
412        self.each(|c| c.set_phase(phase));
413    }
414
415    /// Counts the objects of `names` as offered.
416    pub(crate) fn offered(&self, names: &[ObjectName]) {
417        let n = names.len() as u64;
418        self.each(|c| {
419            c.objects_total.fetch_add(n, Ordering::Relaxed);
420        });
421    }
422
423    /// Counts the objects of `names` as needed.
424    pub(crate) fn needed(&self, names: &[ObjectName]) {
425        let n = names.len() as u64;
426        self.each(|c| {
427            c.objects_needed.fetch_add(n, Ordering::Relaxed);
428        });
429    }
430
431    /// Counts one object as sent.
432    pub(crate) fn object_sent(&self) {
433        self.each(ProgressCounters::object_sent);
434    }
435
436    /// Counts `n` content bytes read from the source of a file object.
437    pub(crate) fn content(&self, n: u64) {
438        self.each(|c| c.content(n));
439    }
440
441    /// Adds `n` to the content bytes that the session will send.
442    pub(crate) fn content_total(&self, n: u64) {
443        self.each(|c| {
444            c.bytes_total.fetch_add(n, Ordering::Relaxed);
445        });
446    }
447
448    /// Returns `true` if a handle of the caller receives the counts.
449    pub(crate) fn has_caller(&self) -> bool {
450        self.caller.is_some()
451    }
452
453    pub(crate) fn wire(&self, n: u64) {
454        self.each(|c| {
455            c.bytes_sent.fetch_add(n, Ordering::Relaxed);
456        });
457    }
458
459    pub(crate) fn payload(&self, n: u64) {
460        self.each(|c| {
461            c.payload_bytes.fetch_add(n, Ordering::Relaxed);
462        });
463    }
464
465    /// Returns the statistics of the session so far.
466    pub(crate) fn stats(&self) -> PushStats {
467        let s = self.own.snapshot();
468        PushStats {
469            objects_total: s.objects_total,
470            objects_needed: s.objects_needed,
471            objects_sent: s.objects_sent,
472            bytes_sent: s.bytes_sent,
473            payload_bytes: s.payload_bytes,
474            elapsed: self.start.elapsed(),
475        }
476    }
477}
478
479#[cfg(test)]
480mod tests {
481    use super::*;
482    use std::sync::Mutex;
483
484    /// The methods of a client with no session change the snapshot, and call
485    /// the hook at a new phase, at each uploaded object, and at each 100 KiB
486    /// step of the content.
487    #[test]
488    fn the_upload_methods_change_the_snapshot_and_call_the_hook() {
489        let calls: Arc<Mutex<Vec<PushProgressSnapshot>>> = Arc::default();
490        let seen = Arc::clone(&calls);
491        let progress = PushProgress::with_hook(Arc::new(move |snapshot| {
492            seen.lock().unwrap().push(*snapshot);
493        }));
494        progress.set_phase(PushPhase::Scanning);
495        assert!(calls.lock().unwrap().is_empty(), "the phase did not change");
496        progress.add_upload(3, 250_000);
497        assert!(calls.lock().unwrap().is_empty(), "add_upload calls no hook");
498        progress.set_phase(PushPhase::Uploading);
499        let last = *calls.lock().unwrap().last().unwrap();
500        assert_eq!(last.phase, PushPhase::Uploading);
501        assert_eq!((last.objects_needed, last.bytes_total), (3, 250_000));
502
503        progress.add_content(100_000);
504        assert_eq!(calls.lock().unwrap().len(), 1, "below the first step");
505        progress.add_content(2_400);
506        assert_eq!(calls.lock().unwrap().len(), 2, "at the first step");
507        progress.object_uploaded();
508        let last = *calls.lock().unwrap().last().unwrap();
509        assert_eq!(calls.lock().unwrap().len(), 3);
510        assert_eq!((last.objects_sent, last.content_bytes), (1, 102_400));
511        assert_eq!(progress.snapshot(), last);
512    }
513
514    /// On a new handle, `start_phase` with `Scanning` calls the hook one
515    /// time. A `set_phase` with `Scanning` after it calls no hook.
516    #[test]
517    fn start_phase_calls_the_hook_when_the_phase_does_not_change() {
518        let calls: Arc<Mutex<Vec<PushProgressSnapshot>>> = Arc::default();
519        let seen = Arc::clone(&calls);
520        let progress = PushProgress::with_hook(Arc::new(move |snapshot| {
521            seen.lock().unwrap().push(*snapshot);
522        }));
523        progress.start_phase(PushPhase::Scanning);
524        let phases: Vec<PushPhase> = calls.lock().unwrap().iter().map(|c| c.phase).collect();
525        assert_eq!(phases, [PushPhase::Scanning]);
526        progress.set_phase(PushPhase::Scanning);
527        assert_eq!(calls.lock().unwrap().len(), 1, "the phase did not change");
528    }
529}