id_effect_console 0.12.0

Operator console for id_effect services: live fibers, jobs and queues behind authorization guards
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
//! [`Console`] and its guarded JSON routes under [`API_PREFIX`].

use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;

use axum::extract::State;
use axum::extract::rejection::JsonRejection;
use axum::http::{HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use axum::{Json, Router};
use id_effect::runtime_metrics;
use id_effect::{Exit, FiberInfo, FiberState, MetricPair, MetricRegistry, MetricState, fiber_dump};
use id_effect_authz::Guard;
use id_effect_axum::{EffectExecutor, HealthRegistry};
use id_effect_process::SupervisorHandle;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use crate::log_level::{self, EnvFilterHandle, LogLevelChange, LogLevelError};
use crate::{supervisors, ui};

/// Where the console API is mounted: every route is `/_console/api/<name>`.
pub const API_PREFIX: &str = "/_console/api";

/// How long a `which_children` call may take before the supervisor is reported unreachable
/// ([`Console::call_timeout`]).
const DEFAULT_CALL_TIMEOUT: Duration = Duration::from_secs(2);

/// What the console shows, built up then turned into its guarded routes by [`Console::router`].
///
/// ```
/// use id_effect_authz::{Guard, require_role};
/// use id_effect_axum::HealthRegistry;
/// use id_effect_console::Console;
///
/// let routes: axum::Router = Console::new()
///   .health(HealthRegistry::new())
///   .router(Guard::new("console", require_role("operator")));
/// # let _ = routes;
/// ```
#[derive(Clone)]
pub struct Console {
  supervisors: Vec<(String, SupervisorHandle)>,
  health: HealthRegistry,
  metrics: MetricRegistry,
  env_filter: Option<EnvFilterHandle>,
  call_timeout: Duration,
  #[cfg(feature = "jobs")]
  jobs: Option<Arc<dyn id_effect_jobs::JobQueue>>,
}

impl Default for Console {
  fn default() -> Self {
    Self::new()
  }
}

impl fmt::Debug for Console {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    let supervisors: Vec<&str> = self.supervisors.iter().map(|(id, _)| id.as_str()).collect();
    f.debug_struct("Console")
      .field("supervisors", &supervisors)
      .field("health", &self.health)
      .field("env_filter", &self.env_filter.is_some())
      .field("call_timeout", &self.call_timeout)
      .finish_non_exhaustive()
  }
}

impl Console {
  /// A console over the process: every live fiber, the global [`MetricRegistry`], an empty
  /// (always up) [`HealthRegistry`], no supervisors and no reloadable `EnvFilter`.
  pub fn new() -> Self {
    Self {
      supervisors: Vec::new(),
      health: HealthRegistry::new(),
      metrics: MetricRegistry::global().clone(),
      env_filter: None,
      call_timeout: DEFAULT_CALL_TIMEOUT,
      #[cfg(feature = "jobs")]
      jobs: None,
    }
  }

  /// Shows `handle`'s tree under the name `id`. Register nested supervisors too (by the handle
  /// the app holds): one whose pid is a registered supervisor's child is shown inside its tree.
  #[must_use]
  pub fn supervisor(mut self, id: impl Into<String>, handle: SupervisorHandle) -> Self {
    self.supervisors.push((id.into(), handle));
    self
  }

  /// The health checks `GET health` runs.
  #[must_use]
  pub fn health(mut self, registry: HealthRegistry) -> Self {
    self.health = registry;
    self
  }

  /// The registry `GET metrics` reads (default: [`MetricRegistry::global`]).
  #[must_use]
  pub fn metrics(mut self, registry: MetricRegistry) -> Self {
    self.metrics = registry;
    self
  }

  /// The reload handle of the subscriber's `EnvFilter` that `log-level` reads and changes
  /// (`id_effect_opentelemetry`'s `OtelStarterGuard::env_filter`). Without one, `log-level`
  /// changes only the `EffectLogger` minimum.
  #[must_use]
  pub fn env_filter(mut self, handle: EnvFilterHandle) -> Self {
    self.env_filter = Some(handle);
    self
  }

  /// How long `GET supervisors` waits for each supervisor's `which_children` (default 2 s).
  #[must_use]
  pub fn call_timeout(mut self, timeout: Duration) -> Self {
    self.call_timeout = timeout;
    self
  }

  /// The job queue `GET jobs` reports on (feature `jobs`): per-queue counts by state and the
  /// newest 50 jobs, without their payloads; `POST jobs/{id}/retry` and `POST jobs/{id}/cancel`
  /// run [`JobQueue::retry_now`](id_effect_jobs::JobQueue::retry_now) and
  /// [`JobQueue::cancel`](id_effect_jobs::JobQueue::cancel) on one job. Without one, every jobs
  /// route is a `404` and the dashboard hides its jobs panel.
  #[cfg(feature = "jobs")]
  #[must_use]
  pub fn jobs(mut self, queue: impl id_effect_jobs::JobQueue) -> Self {
    self.jobs = Some(Arc::new(queue));
    self
  }

  /// The console routes under [`API_PREFIX`] and the dashboard page at `/_console`, every one of
  /// them (and the console API's fallback) behind `guard`. Merge the result into the app's
  /// router, inside its authentication layer; on a listener of its own, wrap it in
  /// [`ConsoleConfig::check_host_and_origin`](crate::ConsoleConfig::check_host_and_origin).
  pub fn router(self, guard: Guard) -> Router {
    let api = Router::new()
      .route("/fibers", get(fibers))
      .route("/supervisors", get(supervisors_tree))
      .route("/metrics", get(metrics))
      .route("/health", get(health))
      .route("/log-level", get(log_level_get).put(log_level_put));
    #[cfg(feature = "jobs")]
    let api = api
      .route("/jobs", get(jobs))
      .route("/jobs/{id}/retry", axum::routing::post(job_retry))
      .route("/jobs/{id}/cancel", axum::routing::post(job_cancel));
    let api = api
      .fallback(not_found)
      .layer(axum::middleware::map_response(no_store))
      .with_state(Arc::new(self));
    let page = Router::new()
      .route(ui::PATH, get(ui::index))
      .route_layer(guard.clone())
      .route_layer(axum::middleware::map_response(no_store));
    Router::new().nest(API_PREFIX, api.layer(guard)).merge(page)
  }
}

type Shared = State<Arc<Console>>;

/// One live fiber, as `GET /_console/api/fibers` lists it (by ascending id).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FiberView {
  /// The fiber's id.
  pub id: u64,
  /// The forking fiber, while it is alive.
  pub parent: Option<u64>,
  /// Children forked with `Effect::fork` that have not completed yet.
  pub children: Vec<u64>,
  /// `running`, `interrupting` or `done` (completed while the dump was taken).
  pub state: String,
  /// Milliseconds since the fiber was built.
  pub age_ms: u64,
  /// Span names from the current span outwards.
  pub spans: Vec<String>,
}

impl From<FiberInfo> for FiberView {
  fn from(info: FiberInfo) -> Self {
    let state = match info.state {
      FiberState::Running => "running",
      FiberState::Interrupting => "interrupting",
      FiberState::Done => "done",
      _ => "unknown",
    };
    Self {
      id: info.id.as_u64(),
      parent: info.parent.map(|p| p.as_u64()),
      children: info.children.iter().map(|c| c.as_u64()).collect(),
      state: state.to_owned(),
      age_ms: u64::try_from(info.age.as_millis()).unwrap_or(u64::MAX),
      spans: info.spans,
    }
  }
}

/// One metric series, as `GET /_console/api/metrics` lists it: the registry's series sorted by
/// name, kind and tags, then the runtime's `id_effect_fibers_live` and
/// `id_effect_fibers_started_total`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetricView {
  /// The metric name.
  pub name: String,
  /// `counter`, `gauge`, `histogram`, `summary` or `frequency`.
  pub kind: String,
  /// The series' tags.
  pub tags: BTreeMap<String, String>,
  /// The reading: `{count}` (counter), `{value}` (gauge), `{count, sum, min, max, buckets:
  /// [{le, count}]}` (histogram; the last `le` is `null`, +∞), `{count, sum, min, max,
  /// window_len, quantiles: [{q, value}]}` (summary) or `{occurrences: {value: count}}`
  /// (frequency).
  pub value: Value,
}

impl From<MetricPair> for MetricView {
  fn from(pair: MetricPair) -> Self {
    let value = match pair.state {
      MetricState::Counter { count } => json!({ "count": count }),
      MetricState::Gauge { value } => json!({ "value": value }),
      MetricState::Histogram(h) => json!({
        "count": h.count,
        "sum": h.sum,
        "min": h.min,
        "max": h.max,
        "buckets": h
          .buckets
          .iter()
          .map(|(le, count)| json!({ "le": le.is_finite().then_some(*le), "count": count }))
          .collect::<Vec<_>>(),
      }),
      MetricState::Summary(s) => json!({
        "count": s.count,
        "sum": s.sum,
        "min": s.min,
        "max": s.max,
        "window_len": s.window_len,
        "quantiles": s
          .quantiles
          .iter()
          .map(|(q, value)| json!({ "q": q, "value": value }))
          .collect::<Vec<_>>(),
      }),
      MetricState::Frequency { occurrences } => json!({
        "occurrences": occurrences.into_iter().collect::<BTreeMap<_, _>>(),
      }),
    };
    Self {
      name: pair.key.name().to_owned(),
      kind: pair.key.kind().label().to_owned(),
      tags: pair.key.tags().iter().cloned().collect(),
      value,
    }
  }
}

async fn fibers() -> Json<Vec<FiberView>> {
  Json(fiber_dump().into_iter().map(FiberView::from).collect())
}

async fn supervisors_tree(State(console): Shared) -> Json<supervisors::SupervisorsView> {
  Json(supervisors::snapshot(&console.supervisors, console.call_timeout).await)
}

async fn metrics(State(console): Shared) -> Json<Vec<MetricView>> {
  let series = console.metrics.snapshot().into_iter();
  Json(
    series
      .chain(runtime_metrics::snapshot())
      .map(MetricView::from)
      .collect(),
  )
}

/// The health report, `200` whatever its status: the console shows a down service, it does not
/// probe it (that is `/ready`).
async fn health(State(console): Shared) -> Response {
  match EffectExecutor::global()
    .run_effect(console.health.check())
    .await
  {
    Exit::Success(report) => Json(report).into_response(),
    Exit::Failure(cause) => problem(
      StatusCode::INTERNAL_SERVER_ERROR,
      format!("health check did not complete: {cause:?}"),
    ),
  }
}

async fn log_level_get(State(console): Shared) -> Json<log_level::LogLevelView> {
  Json(log_level::current(console.env_filter.as_ref()))
}

async fn log_level_put(
  State(console): Shared,
  body: Result<Json<LogLevelChange>, JsonRejection>,
) -> Response {
  let Json(change) = match body {
    Ok(body) => body,
    Err(rejection) => return problem(StatusCode::BAD_REQUEST, rejection.body_text()),
  };
  match log_level::apply(console.env_filter.as_ref(), change) {
    Ok(view) => Json(view).into_response(),
    Err(LogLevelError::Invalid(detail)) => problem(StatusCode::BAD_REQUEST, detail),
    Err(LogLevelError::Reload(detail)) => problem(StatusCode::INTERNAL_SERVER_ERROR, detail),
  }
}

#[cfg(feature = "jobs")]
async fn jobs(State(console): Shared) -> Response {
  let Some(queue) = &console.jobs else {
    return problem(StatusCode::NOT_FOUND, "no job queue registered");
  };
  match crate::jobs::snapshot(queue).await {
    Ok(view) => Json(view).into_response(),
    Err(detail) => problem(StatusCode::INTERNAL_SERVER_ERROR, detail),
  }
}

#[cfg(feature = "jobs")]
async fn job_retry(
  State(console): Shared,
  headers: axum::http::HeaderMap,
  id: Result<axum::extract::Path<i64>, axum::extract::rejection::PathRejection>,
) -> Response {
  job_action(&console, &headers, id, crate::jobs::Action::Retry).await
}

#[cfg(feature = "jobs")]
async fn job_cancel(
  State(console): Shared,
  headers: axum::http::HeaderMap,
  id: Result<axum::extract::Path<i64>, axum::extract::rejection::PathRejection>,
) -> Response {
  job_action(&console, &headers, id, crate::jobs::Action::Cancel).await
}

/// `POST jobs/{id}/retry` and `POST jobs/{id}/cancel`. The request must say
/// `Content-Type: application/json`: a cross-site HTML form cannot send that, and a cross-origin
/// `fetch` that does needs a CORS preflight the console never grants, so another site cannot
/// make an operator's browser retry or cancel a job.
#[cfg(feature = "jobs")]
async fn job_action(
  console: &Console,
  headers: &axum::http::HeaderMap,
  id: Result<axum::extract::Path<i64>, axum::extract::rejection::PathRejection>,
  action: crate::jobs::Action,
) -> Response {
  use crate::jobs::ActionError;

  let Some(queue) = &console.jobs else {
    return problem(StatusCode::NOT_FOUND, "no job queue registered");
  };
  if !is_json(headers) {
    return problem(
      StatusCode::UNSUPPORTED_MEDIA_TYPE,
      "job actions need `Content-Type: application/json`",
    );
  }
  let axum::extract::Path(id) = match id {
    Ok(id) => id,
    Err(rejection) => return problem(StatusCode::BAD_REQUEST, rejection.body_text()),
  };
  match crate::jobs::act(queue, id, action).await {
    Ok(view) => Json(view).into_response(),
    Err(ActionError::NotFound(detail)) => problem(StatusCode::NOT_FOUND, detail),
    Err(ActionError::Conflict(detail)) => problem(StatusCode::CONFLICT, detail),
    Err(ActionError::Failed(detail)) => problem(StatusCode::INTERNAL_SERVER_ERROR, detail),
  }
}

/// Whether the request's media type is `application/json` (parameters ignored).
#[cfg(feature = "jobs")]
fn is_json(headers: &axum::http::HeaderMap) -> bool {
  headers
    .get(header::CONTENT_TYPE)
    .and_then(|v| v.to_str().ok())
    .and_then(|v| v.split(';').next())
    .is_some_and(|media| media.trim().eq_ignore_ascii_case("application/json"))
}

async fn not_found() -> Response {
  problem(StatusCode::NOT_FOUND, "no such console route")
}

async fn no_store(mut response: Response) -> Response {
  response
    .headers_mut()
    .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
  response
}

/// A Problem Details (RFC 9457) answer, as the guard's denials are.
pub(crate) fn problem(status: StatusCode, detail: impl Into<String>) -> Response {
  let body = json!({
    "type": "about:blank",
    "title": status.canonical_reason().unwrap_or("Error"),
    "status": status.as_u16(),
    "detail": detail.into(),
  });
  let mut response = (status, body.to_string()).into_response();
  response.headers_mut().insert(
    header::CONTENT_TYPE,
    HeaderValue::from_static("application/problem+json"),
  );
  response
}