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
8/// The step that a push is in.
9#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
10#[non_exhaustive]
11pub enum PushPhase {
12 /// The client reads its source and builds the object list.
13 ///
14 /// A tree push shows this phase from the start of its scan to the end of
15 /// the walk, which lists and filters each directory. Hash jobs can run in
16 /// this phase. A new [`PushProgress`] starts in this phase.
17 #[default]
18 Scanning,
19 /// The client hashes the files and the directories of a tree.
20 ///
21 /// A tree push shows this phase after the walk. In this phase, the hash
22 /// jobs that still run come to an end, and the client hashes the
23 /// directories bottom-up.
24 Hashing,
25 /// The session starts its transport and exchanges `Hello` with the server.
26 ///
27 /// In this phase, an ssh client can ask for a password or a passphrase on
28 /// the terminal.
29 Connecting,
30 /// The session exchanges `Have` with the server.
31 Negotiating,
32 /// The session sends objects.
33 Uploading,
34 /// The session sends `Commit` and waits for the reply.
35 Committing,
36}
37
38impl PushPhase {
39 fn as_u8(self) -> u8 {
40 match self {
41 PushPhase::Scanning => 0,
42 PushPhase::Hashing => 1,
43 PushPhase::Negotiating => 2,
44 PushPhase::Uploading => 3,
45 PushPhase::Committing => 4,
46 PushPhase::Connecting => 5,
47 }
48 }
49
50 fn from_u8(byte: u8) -> PushPhase {
51 match byte {
52 1 => PushPhase::Hashing,
53 2 => PushPhase::Negotiating,
54 3 => PushPhase::Uploading,
55 4 => PushPhase::Committing,
56 5 => PushPhase::Connecting,
57 _ => PushPhase::Scanning,
58 }
59 }
60}
61
62/// A hook that receives the counters of a [`PushProgress`] when they change.
63///
64/// The hook gets a call only at a change that a progress display shows.
65/// [Hook calls](PushProgress#hook-calls) lists these changes.
66///
67/// The hook runs on the task that changed the counters: the task of the
68/// session, or the task of the scan of a tree push. Over HTTP, each parallel
69/// object stream of a session calls the hook, so more than one thread can call
70/// it at the same time. The session waits for the hook, so the hook must
71/// return soon.
72///
73/// A hook that keeps state between calls holds that state behind interior
74/// mutability of its own, for example an atomic or a mutex.
75pub type PushProgressFn = Arc<dyn Fn(&PushProgressSnapshot) + Send + Sync>;
76
77/// The step of the content count at which the hook gets a call: 100 KiB.
78const HOOK_BYTE_STEP: u64 = 102_400;
79
80/// A handle on the live counters of pushes.
81///
82/// A caller sets a clone of the handle in
83/// [`SessionOptions::progress`](super::SessionOptions::progress). Then it
84/// reads [`snapshot`](PushProgress::snapshot) from another task or thread
85/// while the push runs. A session adds to the counters of the handle and
86/// never sets them to zero.
87///
88/// If several sessions share a handle, the handle shows the sum of their
89/// counters and the phase of the session that set it last.
90///
91/// The [`PushStats`] of a session come from counters of its own, and the
92/// handle does not change them. Each count is one relaxed atomic add to those
93/// counters, and one more to the handle if the session has one.
94///
95/// # Hook calls
96///
97/// A handle made with [`with_hook`](PushProgress::with_hook) calls its hook
98/// with a snapshot at these changes:
99///
100/// - each time the phase changes to another phase
101/// - after each object of the object stream, when
102/// [`objects_sent`](PushProgressSnapshot::objects_sent) grows
103/// - each time [`content_bytes`](PushProgressSnapshot::content_bytes)
104/// reaches the next multiple of 102,400 bytes (100 KiB)
105#[derive(Debug, Clone, Default)]
106pub struct PushProgress {
107 inner: Arc<ProgressCounters>,
108}
109
110impl PushProgress {
111 /// Creates a handle whose counters are all zero.
112 pub fn new() -> PushProgress {
113 PushProgress::default()
114 }
115
116 /// Creates a handle whose counters are all zero and that calls `hook`.
117 ///
118 /// [Hook calls](PushProgress#hook-calls) lists the calls.
119 /// [`PushProgressFn`] gives the rules of the hook.
120 pub fn with_hook(hook: PushProgressFn) -> PushProgress {
121 PushProgress {
122 inner: Arc::new(ProgressCounters {
123 hook: Some(hook),
124 ..ProgressCounters::default()
125 }),
126 }
127 }
128
129 /// Returns the counters as they stand now.
130 ///
131 /// The method reads each counter on its own, so two counters of one
132 /// snapshot can differ by the work of one step.
133 pub fn snapshot(&self) -> PushProgressSnapshot {
134 self.inner.snapshot()
135 }
136
137 /// Sets the phase of the handle. A tree push sets the phases of its scan
138 /// before a session opens.
139 pub(crate) fn set_phase(&self, phase: PushPhase) {
140 self.inner.set_phase(phase);
141 }
142}
143
144/// The counters of a [`PushProgress`] at one point in time.
145///
146/// Code outside this crate gets a snapshot from [`PushProgress::snapshot`],
147/// from the hook, or from `Default`, and reads its fields by name.
148#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
149#[non_exhaustive]
150pub struct PushProgressSnapshot {
151 /// The step that the push is in.
152 pub phase: PushPhase,
153 /// The count of [`PushStats::objects_total`] so far.
154 pub objects_total: u64,
155 /// The count of [`PushStats::objects_needed`] so far.
156 pub objects_needed: u64,
157 /// The count of [`PushStats::objects_sent`] so far.
158 pub objects_sent: u64,
159 /// The count of [`PushStats::bytes_sent`] so far.
160 pub bytes_sent: u64,
161 /// The count of [`PushStats::payload_bytes`] so far.
162 pub payload_bytes: u64,
163 /// The content bytes that the session read so far.
164 ///
165 /// These are the bytes that the session read from the reader that its
166 /// source gave for each file object, before the compressor of the
167 /// session. A stored `.filez` that the session sends as it is counts
168 /// with its stored bytes. A symlink, a metadata object, and detached
169 /// metadata count no byte.
170 pub content_bytes: u64,
171 /// The content bytes of the file objects that the session sends.
172 ///
173 /// The source tells this total before the first object, so
174 /// `content_bytes` ends at this total. If the source does not tell it,
175 /// or the query fails, the total stays 0. See
176 /// [`ObjectSource::content_size`](super::ObjectSource::content_size).
177 pub bytes_total: u64,
178}
179
180/// The statistics of one push session.
181#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
182pub struct PushStats {
183 /// The number of objects that the client offered in `Have`.
184 pub objects_total: u64,
185 /// The number of objects that the server asked for in `HaveReply`.
186 pub objects_needed: u64,
187 /// The number of objects that the session sent in the object stream.
188 ///
189 /// A detached metadata object does not count.
190 pub objects_sent: u64,
191 /// The number of bytes that the session gave to its transport.
192 ///
193 /// The count holds the frames, the chunk lengths, and the object bytes.
194 /// On a stream transport, a byte counts when the session writes it to
195 /// the stream.
196 ///
197 /// Over HTTP, the request bodies count and the HTTP heads do not:
198 ///
199 /// - A whole body, as for `Hello`, `Have`, and `Commit`, counts when the
200 /// client gives its request to a connection. It counts if the request
201 /// gets a response, and also if the request fails after the hand-over.
202 /// - An object stream counts each byte that it writes into its request
203 /// body after the hand-over. At the hand-over, it counts the bytes that
204 /// it wrote before.
205 /// - A request that the client never gives to a connection counts no
206 /// byte.
207 pub bytes_sent: u64,
208 /// The object bytes that the session sent, without the chunk lengths.
209 ///
210 /// The bytes are in the encoding that the session sent them in. Detached
211 /// metadata objects count.
212 pub payload_bytes: u64,
213 /// The time that the session ran.
214 ///
215 /// The clock starts when the session opens: after the ssh client starts,
216 /// or before the first HTTP request. The scan and the hash pass of a tree
217 /// push do not count.
218 pub elapsed: Duration,
219}
220
221/// The counters behind a [`PushProgress`], and the counters of one session.
222#[derive(Default)]
223struct ProgressCounters {
224 phase: AtomicU8,
225 objects_total: AtomicU64,
226 objects_needed: AtomicU64,
227 objects_sent: AtomicU64,
228 bytes_sent: AtomicU64,
229 payload_bytes: AtomicU64,
230 content_bytes: AtomicU64,
231 bytes_total: AtomicU64,
232 /// The hook of the handle. The counters of a session have none.
233 hook: Option<PushProgressFn>,
234}
235
236impl fmt::Debug for ProgressCounters {
237 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238 f.debug_struct("ProgressCounters")
239 .field("counters", &self.snapshot())
240 .field("hook", &self.hook.is_some())
241 .finish()
242 }
243}
244
245impl ProgressCounters {
246 fn snapshot(&self) -> PushProgressSnapshot {
247 PushProgressSnapshot {
248 phase: PushPhase::from_u8(self.phase.load(Ordering::Relaxed)),
249 objects_total: self.objects_total.load(Ordering::Relaxed),
250 objects_needed: self.objects_needed.load(Ordering::Relaxed),
251 objects_sent: self.objects_sent.load(Ordering::Relaxed),
252 bytes_sent: self.bytes_sent.load(Ordering::Relaxed),
253 payload_bytes: self.payload_bytes.load(Ordering::Relaxed),
254 content_bytes: self.content_bytes.load(Ordering::Relaxed),
255 bytes_total: self.bytes_total.load(Ordering::Relaxed),
256 }
257 }
258
259 /// Calls the hook with the counters as they stand.
260 fn call_hook(&self) {
261 if let Some(hook) = &self.hook {
262 hook(&self.snapshot());
263 }
264 }
265
266 /// Sets the phase, and calls the hook if the phase changed.
267 fn set_phase(&self, phase: PushPhase) {
268 let before = self.phase.swap(phase.as_u8(), Ordering::Relaxed);
269 if before != phase.as_u8() {
270 self.call_hook();
271 }
272 }
273
274 /// Counts one object sent, and calls the hook.
275 fn object_sent(&self) {
276 self.objects_sent.fetch_add(1, Ordering::Relaxed);
277 self.call_hook();
278 }
279
280 /// Counts `n` content bytes, and calls the hook if the count reaches the
281 /// next multiple of [`HOOK_BYTE_STEP`].
282 fn content(&self, n: u64) {
283 let before = self.content_bytes.fetch_add(n, Ordering::Relaxed);
284 if before / HOOK_BYTE_STEP != before.wrapping_add(n) / HOOK_BYTE_STEP {
285 self.call_hook();
286 }
287 }
288}
289
290/// The counters that one session counts into: its own, which its
291/// [`PushStats`] read, and the handle of the caller, which receives the same
292/// additions.
293#[derive(Debug)]
294pub(crate) struct Counters {
295 own: ProgressCounters,
296 caller: Option<Arc<ProgressCounters>>,
297 start: Instant,
298}
299
300impl Counters {
301 /// Creates the counters of a session that starts now. The session also
302 /// counts into `caller` if there is one.
303 pub(crate) fn new(caller: Option<&PushProgress>) -> Counters {
304 Counters {
305 own: ProgressCounters::default(),
306 caller: caller.map(|progress| Arc::clone(&progress.inner)),
307 start: Instant::now(),
308 }
309 }
310
311 /// Runs `f` on the own counters of the session, then on the counters of
312 /// the caller.
313 fn each(&self, f: impl Fn(&ProgressCounters)) {
314 f(&self.own);
315 if let Some(caller) = &self.caller {
316 f(caller);
317 }
318 }
319
320 pub(crate) fn phase(&self, phase: PushPhase) {
321 self.each(|c| c.set_phase(phase));
322 }
323
324 pub(crate) fn offered(&self, n: u64) {
325 self.each(|c| {
326 c.objects_total.fetch_add(n, Ordering::Relaxed);
327 });
328 }
329
330 pub(crate) fn needed(&self, n: u64) {
331 self.each(|c| {
332 c.objects_needed.fetch_add(n, Ordering::Relaxed);
333 });
334 }
335
336 pub(crate) fn object_sent(&self) {
337 self.each(ProgressCounters::object_sent);
338 }
339
340 /// Counts `n` content bytes read from the source of a file object.
341 pub(crate) fn content(&self, n: u64) {
342 self.each(|c| c.content(n));
343 }
344
345 /// Adds `n` to the content bytes that the session will send.
346 pub(crate) fn content_total(&self, n: u64) {
347 self.each(|c| {
348 c.bytes_total.fetch_add(n, Ordering::Relaxed);
349 });
350 }
351
352 /// Returns `true` if a handle of the caller receives the counts.
353 pub(crate) fn has_caller(&self) -> bool {
354 self.caller.is_some()
355 }
356
357 pub(crate) fn wire(&self, n: u64) {
358 self.each(|c| {
359 c.bytes_sent.fetch_add(n, Ordering::Relaxed);
360 });
361 }
362
363 pub(crate) fn payload(&self, n: u64) {
364 self.each(|c| {
365 c.payload_bytes.fetch_add(n, Ordering::Relaxed);
366 });
367 }
368
369 /// Returns the statistics of the session so far.
370 pub(crate) fn stats(&self) -> PushStats {
371 let s = self.own.snapshot();
372 PushStats {
373 objects_total: s.objects_total,
374 objects_needed: s.objects_needed,
375 objects_sent: s.objects_sent,
376 bytes_sent: s.bytes_sent,
377 payload_bytes: s.payload_bytes,
378 elapsed: self.start.elapsed(),
379 }
380 }
381}