diff --git a/scripts/graph.ts b/scripts/graph.ts index ff4fff4..37d829f 100644 --- a/scripts/graph.ts +++ b/scripts/graph.ts @@ -1,5 +1,5 @@ -import * as metrics from "./graph/metrics.js"; import { Requests } from "./graph/requests.js"; +import { State } from "./graph/state.js"; import uPlot from "./uPlot.js"; @@ -122,16 +122,10 @@ const COLORS = [ // Initialization const plot_div = document.getElementById("plot")!; -const metrics_div = document.getElementById("metrics")!; +const metricsDiv = document.getElementById("metrics")!; let plot: uPlot | null = null; let requests = new Requests(); +let state = new State(requests, metricsDiv); -async function init() { - let response = await requests.get_metrics(); - console.log("Metrics:", response); - if (response !== null) { - metrics.update(metrics_div, response.metrics); - } -} -init(); +state.update(); diff --git a/scripts/graph/metrics.ts b/scripts/graph/metrics.ts index 8db1cec..de190cf 100644 --- a/scripts/graph/metrics.ts +++ b/scripts/graph/metrics.ts @@ -57,7 +57,7 @@ class Folder { } } -export function update(div: HTMLElement, metrics: string[]) { +export function updateMetricsDiv(div: HTMLElement, metrics: string[]) { let folder = new Folder(); for (let metric of metrics) { folder.add(metric); diff --git a/scripts/graph/state.ts b/scripts/graph/state.ts new file mode 100644 index 0000000..aef8756 --- /dev/null +++ b/scripts/graph/state.ts @@ -0,0 +1,42 @@ +import { updateMetricsDiv } from "./metrics.js"; +import { Requests, MetricsResponse } from "./requests.js"; + +export class State { + #requests: Requests; + #metricsDiv: HTMLElement; + + #updating: boolean = false; + #metrics: MetricsResponse | null = null; + + constructor(requests: Requests, metricsDiv: HTMLElement) { + this.#requests = requests; + this.#metricsDiv = metricsDiv; + } + + /** + * Look at current state and try to change it so that it represents what the + * user wants. + * + * This function is idempotent. + */ + async update() { + if (this.#updating) { + return; + } + try { + await this.#update_impl(); + } finally { + this.#updating = false; + } + } + + async #update_impl() { + this.#update_metrics(); + } + + async #update_metrics() { + this.#metrics = await this.#requests.get_metrics(); + if (this.#metrics === null) { return; } + updateMetricsDiv(this.#metricsDiv, this.#metrics.metrics); + } +}