File size: 2,199 Bytes
2bb5af3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/** How far along a run actually is.
 *
 * The dashboard used to draw a bar at 55% for anything running and 35% for
 * anything awaiting review - numbers that measured nothing. The brand promise
 * is "دقّة وثقة في كل مخرَج", and a progress bar that invents its own position
 * is the smallest possible version of breaking it.
 *
 * The real figure is already on hand: the pipeline definition lists every step
 * in order, and the run reports `current_step`. Position in that list is the
 * progress, and it is also sayable in words - "الخطوة ٧ من ١٢" - which a bar
 * on its own never is.
 */

import type { PipelineDef, Run } from "@/lib/types";

export interface RunProgress {
  /** Steps finished. */
  done: number;
  total: number;
  /** 0-1, for the bar. */
  ratio: number;
  /** Arabic label, or null when there is nothing honest to say. */
  label: string | null;
  /** True while work is moving, so the bar can show it is live. */
  live: boolean;
}

export function runProgress(run: Run, pipeline?: PipelineDef): RunProgress {
  const steps = pipeline?.steps ?? [];
  const total = steps.length;
  const live = run.status === "running" || run.status === "queued";

  // Terminal states are unambiguous whether or not the definition loaded.
  if (run.status === "succeeded") {
    return { done: total, total, ratio: 1, label: null, live: false };
  }

  const index = run.current_step ? steps.findIndex((s) => s.key === run.current_step) : -1;

  if (total === 0 || index < 0) {
    // The definition has not loaded, or the run is on a step the definition
    // does not name. Say nothing rather than guess: a full-width bar in the
    // failure tint still reads as "this stopped", which is the true part.
    return {
      done: 0,
      total,
      ratio: run.status === "failed" || run.status === "cancelled" ? 1 : 0,
      label: null,
      live,
    };
  }

  // The current step is in flight, so the steps behind it are the finished
  // ones. A run sitting on step 1 has completed none, and the bar shows none.
  return {
    done: index,
    total,
    ratio: index / total,
    label: `الخطوة ${index + 1} من ${total}`,
    live,
  };
}