joule_profiler_cli/config/source.rs
1//! Source registration helpers for Joule Profiler.
2
3use anyhow::Result;
4use joule_profiler_core::{JouleProfiler, source::MetricReader};
5use serde::Deserialize;
6
7use crate::config::table::ConfigTable;
8
9/// Metric source configuration wrapper.
10#[derive(Debug, Default, Deserialize)]
11pub struct MetricSourceConfig<T> {
12 /// The source configuration, deserialized from a TOML table.
13 #[serde(flatten)]
14 pub inner: T,
15
16 /// When true, a failure to initialize this source is logged as a warning and silently skipped rather than propagating an error.
17 #[serde(default)]
18 pub ignore_on_failure: bool,
19}
20
21/// Builds a metric source reader of type `R` from `config_table` and, if
22/// successful, attaches it to `profiler`.
23///
24/// If the source is disabled or its initialization fails with
25/// `ignore_on_failure` set, no source is added and `Ok(())` is returned
26/// silently.
27///
28/// Returns an error if source initialization fails and `ignore_on_failure` is
29/// not set in the source's config.
30pub fn register_source<R>(
31 profiler: &mut JouleProfiler,
32 config_table: &mut ConfigTable,
33) -> Result<()>
34where
35 R: MetricReader,
36{
37 if let Some(reader) = config_table.build_source::<R>()? {
38 profiler.add_source(reader);
39 }
40 Ok(())
41}
42
43/// Builds a metric source reader with an external config override,
44/// then attaches it to `profiler` if initialization succeeds.
45///
46/// This is the override variant of [`register_source`], used when another
47/// subsystem needs to inject values into the source's config before it is
48/// constructed. The caller supplies a closure applied to the source's config.
49///
50/// If the source is disabled or its initialization fails with
51/// `ignore_on_failure` set, no source is added and `Ok(())` is returned.
52/// Returns an error if source initialization fails and `ignore_on_failure` is
53/// not set in the source's config.
54pub fn register_source_override<R>(
55 profiler: &mut JouleProfiler,
56 config_table: &mut ConfigTable,
57 config_override_fn: impl FnOnce(&mut R::Config),
58) -> Result<()>
59where
60 R: MetricReader,
61{
62 if let Some(reader) = config_table.build_source_override::<R>(config_override_fn)? {
63 profiler.add_source(reader);
64 }
65 Ok(())
66}