Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)
Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
168
akode-rs/otel/src/metrics/buffered.rs
Normal file
168
akode-rs/otel/src/metrics/buffered.rs
Normal file
@@ -0,0 +1,168 @@
|
||||
//! Buffers bounded operation counts and durations until process metrics are configured.
|
||||
//! Each pair is admitted together; lifecycle transitions serialize with local SDK recording.
|
||||
//! Shutting down the active installation resumes buffering until its replacement is ready.
|
||||
|
||||
use super::MetricsClient;
|
||||
use super::MetricsError;
|
||||
use super::Result;
|
||||
use super::validation::validate_metric_name;
|
||||
use super::validation::validate_tag_key;
|
||||
use super::validation::validate_tag_value;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
const MAX_PENDING_OPERATIONS: usize = 256;
|
||||
const MAX_METADATA_BYTES: usize = 1024;
|
||||
const MAX_TAGS: usize = 16;
|
||||
|
||||
struct PendingOperation {
|
||||
count_name: Box<str>,
|
||||
duration_name: Box<str>,
|
||||
duration: Duration,
|
||||
tags: Vec<(Box<str>, Box<str>)>,
|
||||
}
|
||||
|
||||
enum State {
|
||||
Startup(Vec<PendingOperation>),
|
||||
Ready(MetricsClient),
|
||||
}
|
||||
|
||||
pub(crate) struct BufferedMetrics {
|
||||
state: Mutex<State>,
|
||||
}
|
||||
|
||||
pub(crate) static GLOBAL: BufferedMetrics = BufferedMetrics::new();
|
||||
|
||||
/// Records one operation count and its duration in milliseconds through `MetricsClient`.
|
||||
/// While awaiting an active provider, retains at most 256 pairs, each with at most 16 tags and
|
||||
/// 1024 bytes of metric names, tag keys, and tag values. Overflow drops the entire pair.
|
||||
/// Supply bounded classifications, never credentials or user-provided identifiers.
|
||||
/// Disabling metrics discards pending pairs and suppresses subsequent recording.
|
||||
pub fn record_global_operation(
|
||||
count_name: &str,
|
||||
duration_name: &str,
|
||||
duration: Duration,
|
||||
tags: &[(&str, &str)],
|
||||
) -> Result<()> {
|
||||
GLOBAL.record(count_name, duration_name, duration, tags)
|
||||
}
|
||||
|
||||
impl BufferedMetrics {
|
||||
const fn new() -> Self {
|
||||
Self {
|
||||
state: Mutex::new(State::Startup(Vec::new())),
|
||||
}
|
||||
}
|
||||
|
||||
fn record(
|
||||
&self,
|
||||
count_name: &str,
|
||||
duration_name: &str,
|
||||
duration: Duration,
|
||||
tags: &[(&str, &str)],
|
||||
) -> Result<()> {
|
||||
if tags.len() > MAX_TAGS
|
||||
|| tags.iter().fold(
|
||||
count_name.len().saturating_add(duration_name.len()),
|
||||
|bytes, (key, value)| bytes.saturating_add(key.len()).saturating_add(value.len()),
|
||||
) > MAX_METADATA_BYTES
|
||||
{
|
||||
return Err(MetricsError::OperationMetadataTooLarge);
|
||||
}
|
||||
// Validate both instruments before accepting either half of the pair.
|
||||
for name in [count_name, duration_name] {
|
||||
validate_metric_name(name)?;
|
||||
// The SDK otherwise silently builds a no-op instrument for these names.
|
||||
if name.len() > 255 || !name.as_bytes()[0].is_ascii_alphabetic() {
|
||||
return Err(MetricsError::InvalidMetricName {
|
||||
name: name.to_owned(),
|
||||
});
|
||||
}
|
||||
}
|
||||
for (key, value) in tags {
|
||||
validate_tag_key(key)?;
|
||||
validate_tag_value(value)?;
|
||||
}
|
||||
let mut state = self
|
||||
.state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
match &mut *state {
|
||||
State::Startup(pending) => {
|
||||
if pending.len() < MAX_PENDING_OPERATIONS {
|
||||
pending.push(PendingOperation {
|
||||
count_name: count_name.into(),
|
||||
duration_name: duration_name.into(),
|
||||
duration,
|
||||
tags: tags
|
||||
.iter()
|
||||
.map(|(key, value)| ((*key).into(), (*value).into()))
|
||||
.collect(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
State::Ready(metrics) => record(metrics, count_name, duration_name, duration, tags),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn enable(&self, metrics: &MetricsClient) {
|
||||
let mut state = self
|
||||
.state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
// Bind to this installation so a provider replacement cannot split a pair
|
||||
// between exporters through the redirectable global MetricsClient handle.
|
||||
let metrics = MetricsClient {
|
||||
inner: Arc::clone(&metrics.inner),
|
||||
active: None,
|
||||
};
|
||||
if let State::Startup(pending) = &mut *state {
|
||||
for operation in pending.drain(..) {
|
||||
let tags: Vec<_> = operation
|
||||
.tags
|
||||
.iter()
|
||||
.map(|(key, value)| (key.as_ref(), value.as_ref()))
|
||||
.collect();
|
||||
let _ = record(
|
||||
&metrics,
|
||||
&operation.count_name,
|
||||
&operation.duration_name,
|
||||
operation.duration,
|
||||
&tags,
|
||||
);
|
||||
}
|
||||
}
|
||||
*state = State::Ready(metrics);
|
||||
}
|
||||
|
||||
pub(super) fn suspend(&self, metrics: &MetricsClient) {
|
||||
let mut state = self
|
||||
.state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
// A replaced provider may shut down after its successor is installed.
|
||||
// It must neither detach that successor nor undo an explicit opt-out.
|
||||
if let State::Ready(current) = &*state
|
||||
&& Arc::ptr_eq(¤t.inner, &metrics.inner)
|
||||
{
|
||||
*state = State::Startup(Vec::new());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn record(
|
||||
metrics: &MetricsClient,
|
||||
count_name: &str,
|
||||
duration_name: &str,
|
||||
duration: Duration,
|
||||
tags: &[(&str, &str)],
|
||||
) -> Result<()> {
|
||||
metrics.counter(count_name, /*inc*/ 1, tags)?;
|
||||
metrics.record_duration(duration_name, duration, tags)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "buffered_tests.rs"]
|
||||
mod tests;
|
||||
154
akode-rs/otel/src/metrics/buffered_tests.rs
Normal file
154
akode-rs/otel/src/metrics/buffered_tests.rs
Normal file
@@ -0,0 +1,154 @@
|
||||
use super::*;
|
||||
use crate::MetricsConfig;
|
||||
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
|
||||
use opentelemetry_sdk::metrics::data::MetricData;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::Barrier;
|
||||
use std::sync::RwLock;
|
||||
|
||||
fn client() -> MetricsClient {
|
||||
MetricsClient::new(
|
||||
MetricsConfig::in_memory("test", "test", "1", Default::default()).with_runtime_reader(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn observe(buffer: &BufferedMetrics) {
|
||||
buffer
|
||||
.record(
|
||||
"test.operations",
|
||||
"test.duration",
|
||||
Duration::from_millis(/*millis*/ 7),
|
||||
&[("component", "test")],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn totals(metrics: &MetricsClient) -> (u64, u64, f64) {
|
||||
let snapshot = metrics.snapshot().unwrap();
|
||||
let mut totals = (0, 0, 0.0);
|
||||
for metric in snapshot
|
||||
.scope_metrics()
|
||||
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
|
||||
{
|
||||
match metric.data() {
|
||||
AggregatedMetrics::U64(MetricData::Sum(sum)) => {
|
||||
totals.0 += sum
|
||||
.data_points()
|
||||
.map(opentelemetry_sdk::metrics::data::SumDataPoint::value)
|
||||
.sum::<u64>();
|
||||
}
|
||||
AggregatedMetrics::F64(MetricData::Histogram(histogram)) => {
|
||||
for point in histogram.data_points() {
|
||||
totals.1 += point.count();
|
||||
totals.2 += point.sum();
|
||||
}
|
||||
}
|
||||
_ => panic!("unexpected metric"),
|
||||
}
|
||||
}
|
||||
totals
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_limits_and_validation_preserve_whole_pairs() {
|
||||
let buffer = BufferedMetrics::new();
|
||||
let oversized = "x".repeat(MAX_METADATA_BYTES + 1);
|
||||
assert!(matches!(
|
||||
buffer.record("count", "duration", Duration::ZERO, &[("tag", &oversized)]),
|
||||
Err(MetricsError::OperationMetadataTooLarge)
|
||||
));
|
||||
assert!(matches!(
|
||||
buffer.record(
|
||||
"count",
|
||||
"duration",
|
||||
Duration::ZERO,
|
||||
&[("tag", "value"); MAX_TAGS + 1]
|
||||
),
|
||||
Err(MetricsError::OperationMetadataTooLarge)
|
||||
));
|
||||
for name in ["invalid duration", "1duration", &"d".repeat(256)] {
|
||||
assert!(buffer.record("count", name, Duration::ZERO, &[]).is_err());
|
||||
assert!(
|
||||
buffer
|
||||
.record(name, "duration", Duration::ZERO, &[])
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
buffer
|
||||
.record(
|
||||
"count",
|
||||
"duration",
|
||||
Duration::ZERO,
|
||||
&[("tag", "invalid value")]
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
for _ in 0..MAX_PENDING_OPERATIONS + 1 {
|
||||
observe(&buffer);
|
||||
}
|
||||
let metrics = client();
|
||||
buffer.enable(&metrics);
|
||||
assert_eq!(totals(&metrics), (256, 256, 1792.0));
|
||||
buffer.enable(&metrics);
|
||||
assert_eq!(totals(&metrics), (0, 0, 0.0));
|
||||
for name in ["invalid duration", "1duration", &"d".repeat(256)] {
|
||||
assert!(buffer.record("count", name, Duration::ZERO, &[]).is_err());
|
||||
assert!(
|
||||
buffer
|
||||
.record(name, "duration", Duration::ZERO, &[])
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
assert_eq!(totals(&metrics), (0, 0, 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_installation_and_replacement_record_each_pair_once() {
|
||||
let buffer = BufferedMetrics::new();
|
||||
let first = client();
|
||||
let second = client();
|
||||
let barrier = Barrier::new(/*n*/ 5);
|
||||
observe(&buffer);
|
||||
std::thread::scope(|scope| {
|
||||
for _ in 0..4 {
|
||||
scope.spawn(|| {
|
||||
barrier.wait();
|
||||
for _ in 0..16 {
|
||||
observe(&buffer);
|
||||
}
|
||||
});
|
||||
}
|
||||
barrier.wait();
|
||||
buffer.enable(&first);
|
||||
buffer.enable(&second);
|
||||
});
|
||||
let a = totals(&first);
|
||||
let b = totals(&second);
|
||||
assert_eq!((a.0 + b.0, a.1 + b.1, a.2 + b.2), (65, 65, 455.0));
|
||||
assert_eq!((a.0, b.0), (a.1, b.1));
|
||||
buffer.enable(&second);
|
||||
assert_eq!(totals(&second), (0, 0, 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redirecting_a_global_handle_does_not_change_the_buffers_installation() {
|
||||
let buffer = BufferedMetrics::new();
|
||||
let first = client();
|
||||
let second = client();
|
||||
let active = Arc::new(RwLock::new(Arc::clone(&first.inner)));
|
||||
let redirected = MetricsClient {
|
||||
inner: Arc::clone(&first.inner),
|
||||
active: Some(Arc::clone(&active)),
|
||||
};
|
||||
buffer.enable(&redirected);
|
||||
*active.write().unwrap() = Arc::clone(&second.inner);
|
||||
observe(&buffer);
|
||||
assert_eq!(totals(&first), (1, 1, 7.0));
|
||||
assert_eq!(totals(&second), (0, 0, 0.0));
|
||||
buffer.enable(&second);
|
||||
observe(&buffer);
|
||||
assert_eq!(totals(&first), (0, 0, 0.0));
|
||||
assert_eq!(totals(&second), (1, 1, 7.0));
|
||||
}
|
||||
561
akode-rs/otel/src/metrics/client.rs
Normal file
561
akode-rs/otel/src/metrics/client.rs
Normal file
@@ -0,0 +1,561 @@
|
||||
use crate::metrics::MetricsError;
|
||||
use crate::metrics::Result;
|
||||
use crate::metrics::config::MetricsConfig;
|
||||
use crate::metrics::names::TURN_CRITICAL_PATH_COMPONENT_METRIC;
|
||||
use crate::metrics::names::TURN_CRITICAL_PATH_DURATION_METRIC;
|
||||
use crate::metrics::timer::Timer;
|
||||
use crate::metrics::validation::validate_metric_name;
|
||||
use crate::metrics::validation::validate_tag_key;
|
||||
use crate::metrics::validation::validate_tag_value;
|
||||
use crate::metrics::validation::validate_tags;
|
||||
use akode_utils_string::sanitize_metric_tag_value;
|
||||
use opentelemetry::KeyValue;
|
||||
use opentelemetry::metrics::Counter;
|
||||
use opentelemetry::metrics::Gauge;
|
||||
use opentelemetry::metrics::Histogram;
|
||||
use opentelemetry::metrics::Meter;
|
||||
use opentelemetry::metrics::MeterProvider as _;
|
||||
use opentelemetry_sdk::Resource;
|
||||
use opentelemetry_sdk::metrics::InstrumentKind;
|
||||
use opentelemetry_sdk::metrics::ManualReader;
|
||||
use opentelemetry_sdk::metrics::PeriodicReader;
|
||||
use opentelemetry_sdk::metrics::Pipeline;
|
||||
use opentelemetry_sdk::metrics::SdkMeterProvider;
|
||||
use opentelemetry_sdk::metrics::Temporality;
|
||||
use opentelemetry_sdk::metrics::data::ResourceMetrics;
|
||||
use opentelemetry_sdk::metrics::reader::MetricReader;
|
||||
use opentelemetry_semantic_conventions as semconv;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::LazyLock;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::RwLock;
|
||||
use std::sync::Weak;
|
||||
use std::time::Duration;
|
||||
use tracing::debug;
|
||||
|
||||
const ENV_ATTRIBUTE: &str = "env";
|
||||
const METER_NAME: &str = "codex";
|
||||
const MILLISECOND_DURATION_UNIT: &str = "ms";
|
||||
const MILLISECOND_DURATION_DESCRIPTION: &str = "Duration in milliseconds.";
|
||||
const MILLISECOND_DURATION_BOUNDARIES: &[f64] = &[
|
||||
0.0, 5.0, 10.0, 25.0, 50.0, 75.0, 100.0, 250.0, 500.0, 750.0, 1_000.0, 1_250.0, 1_500.0,
|
||||
1_750.0, 2_000.0, 2_250.0, 2_500.0, 3_000.0, 3_500.0, 4_000.0, 4_500.0, 5_000.0, 6_000.0,
|
||||
7_000.0, 7_500.0, 8_000.0, 9_000.0, 10_000.0, 12_000.0, 15_000.0, 20_000.0, 30_000.0, 60_000.0,
|
||||
120_000.0,
|
||||
];
|
||||
// Whole-turn profiles can accumulate minutes of inference, tool execution, or user wait.
|
||||
static TURN_CRITICAL_PATH_DURATION_BOUNDARIES: LazyLock<Vec<f64>> = LazyLock::new(|| {
|
||||
let mut bounds = MILLISECOND_DURATION_BOUNDARIES.to_vec();
|
||||
bounds.extend([
|
||||
180_000.0,
|
||||
300_000.0,
|
||||
600_000.0,
|
||||
900_000.0,
|
||||
1_800_000.0,
|
||||
3_600_000.0,
|
||||
7_200_000.0,
|
||||
]);
|
||||
bounds
|
||||
});
|
||||
const SECOND_DURATION_UNIT: &str = "s";
|
||||
const SECOND_DURATION_BOUNDARIES: &[f64] = &[
|
||||
0.0, 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1.0, 2.5, 5.0, 7.5, 10.0, 12.0,
|
||||
15.0, 20.0, 30.0, 60.0, 120.0,
|
||||
];
|
||||
|
||||
#[derive(Debug, Eq, Hash, PartialEq)]
|
||||
struct InstrumentKey {
|
||||
name: String,
|
||||
unit: Option<&'static str>,
|
||||
description: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct SharedManualReader {
|
||||
inner: Arc<ManualReader>,
|
||||
}
|
||||
|
||||
impl SharedManualReader {
|
||||
fn new(inner: Arc<ManualReader>) -> Self {
|
||||
Self { inner }
|
||||
}
|
||||
}
|
||||
|
||||
impl MetricReader for SharedManualReader {
|
||||
fn register_pipeline(&self, pipeline: Weak<Pipeline>) {
|
||||
self.inner.register_pipeline(pipeline);
|
||||
}
|
||||
|
||||
fn collect(&self, rm: &mut ResourceMetrics) -> opentelemetry_sdk::error::OTelSdkResult {
|
||||
self.inner.collect(rm)
|
||||
}
|
||||
|
||||
fn force_flush(&self) -> opentelemetry_sdk::error::OTelSdkResult {
|
||||
self.inner.force_flush()
|
||||
}
|
||||
|
||||
fn shutdown_with_timeout(&self, timeout: Duration) -> opentelemetry_sdk::error::OTelSdkResult {
|
||||
self.inner.shutdown_with_timeout(timeout)
|
||||
}
|
||||
|
||||
fn temporality(&self, kind: InstrumentKind) -> Temporality {
|
||||
self.inner.temporality(kind)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct MetricsClientInner {
|
||||
meter_provider: SdkMeterProvider,
|
||||
meter: Meter,
|
||||
counters: Mutex<HashMap<InstrumentKey, Counter<u64>>>,
|
||||
gauges: Mutex<HashMap<InstrumentKey, Gauge<i64>>>,
|
||||
histograms: Mutex<HashMap<String, Histogram<f64>>>,
|
||||
duration_histograms: Mutex<HashMap<InstrumentKey, Histogram<f64>>>,
|
||||
runtime_reader: Option<Arc<ManualReader>>,
|
||||
default_tags: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl MetricsClientInner {
|
||||
fn counter(
|
||||
&self,
|
||||
name: &str,
|
||||
description: Option<&str>,
|
||||
inc: i64,
|
||||
tags: &[(&str, &str)],
|
||||
) -> Result<()> {
|
||||
validate_metric_name(name)?;
|
||||
if inc < 0 {
|
||||
return Err(MetricsError::NegativeCounterIncrement {
|
||||
name: name.to_string(),
|
||||
inc,
|
||||
});
|
||||
}
|
||||
let attributes = self.attributes(tags)?;
|
||||
|
||||
let mut counters = self
|
||||
.counters
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let key = InstrumentKey {
|
||||
name: name.to_string(),
|
||||
unit: None,
|
||||
description: description.map(str::to_string),
|
||||
};
|
||||
let counter = counters.entry(key).or_insert_with(|| {
|
||||
let builder = self.meter.u64_counter(name.to_string());
|
||||
match description {
|
||||
Some(description) => builder.with_description(description.to_string()).build(),
|
||||
None => builder.build(),
|
||||
}
|
||||
});
|
||||
counter.add(inc as u64, &attributes);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn histogram(
|
||||
&self,
|
||||
name: &str,
|
||||
value: i64,
|
||||
boundaries: Option<&[f64]>,
|
||||
tags: &[(&str, &str)],
|
||||
) -> Result<()> {
|
||||
validate_metric_name(name)?;
|
||||
let attributes = self.attributes(tags)?;
|
||||
|
||||
let mut histograms = self
|
||||
.histograms
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let histogram = histograms.entry(name.to_string()).or_insert_with(|| {
|
||||
let builder = self.meter.f64_histogram(name.to_string());
|
||||
match boundaries {
|
||||
Some(boundaries) => builder.with_boundaries(boundaries.to_vec()).build(),
|
||||
None => builder.build(),
|
||||
}
|
||||
});
|
||||
histogram.record(value as f64, &attributes);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn gauge(
|
||||
&self,
|
||||
name: &str,
|
||||
description: Option<&str>,
|
||||
value: i64,
|
||||
tags: &[(&str, &str)],
|
||||
) -> Result<()> {
|
||||
validate_metric_name(name)?;
|
||||
let attributes = self.attributes(tags)?;
|
||||
|
||||
let mut gauges = self
|
||||
.gauges
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let key = InstrumentKey {
|
||||
name: name.to_string(),
|
||||
unit: None,
|
||||
description: description.map(str::to_string),
|
||||
};
|
||||
let gauge = gauges.entry(key).or_insert_with(|| {
|
||||
let builder = self.meter.i64_gauge(name.to_string());
|
||||
match description {
|
||||
Some(description) => builder.with_description(description.to_string()).build(),
|
||||
None => builder.build(),
|
||||
}
|
||||
});
|
||||
gauge.record(value, &attributes);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn register_observable_gauge(
|
||||
&self,
|
||||
name: &str,
|
||||
description: &str,
|
||||
observe: impl Fn() -> i64 + Send + Sync + 'static,
|
||||
tags: &[(&str, &str)],
|
||||
) -> Result<()> {
|
||||
validate_metric_name(name)?;
|
||||
let attributes = self.attributes(tags)?;
|
||||
|
||||
let _gauge = self
|
||||
.meter
|
||||
.i64_observable_gauge(name.to_string())
|
||||
.with_description(description.to_string())
|
||||
.with_callback(move |observer| observer.observe(observe(), &attributes))
|
||||
.build();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn duration_histogram(
|
||||
&self,
|
||||
name: &str,
|
||||
value: f64,
|
||||
unit: &'static str,
|
||||
description: &str,
|
||||
boundaries: &'static [f64],
|
||||
tags: &[(&str, &str)],
|
||||
) -> Result<()> {
|
||||
validate_metric_name(name)?;
|
||||
let attributes = self.attributes(tags)?;
|
||||
|
||||
let mut histograms = self
|
||||
.duration_histograms
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let key = InstrumentKey {
|
||||
name: name.to_string(),
|
||||
unit: Some(unit),
|
||||
description: Some(description.to_string()),
|
||||
};
|
||||
let histogram = histograms.entry(key).or_insert_with(|| {
|
||||
self.meter
|
||||
.f64_histogram(name.to_string())
|
||||
.with_unit(unit)
|
||||
.with_description(description.to_string())
|
||||
.with_boundaries(boundaries.to_vec())
|
||||
.build()
|
||||
});
|
||||
histogram.record(value, &attributes);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn attributes(&self, tags: &[(&str, &str)]) -> Result<Vec<KeyValue>> {
|
||||
if tags.is_empty() {
|
||||
return Ok(self
|
||||
.default_tags
|
||||
.iter()
|
||||
.map(|(key, value)| KeyValue::new(key.clone(), value.clone()))
|
||||
.collect());
|
||||
}
|
||||
|
||||
let mut merged = self.default_tags.clone();
|
||||
for (key, value) in tags {
|
||||
validate_tag_key(key)?;
|
||||
validate_tag_value(value)?;
|
||||
merged.insert((*key).to_string(), (*value).to_string());
|
||||
}
|
||||
|
||||
Ok(merged
|
||||
.into_iter()
|
||||
.map(|(key, value)| KeyValue::new(key, value))
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn shutdown(&self) -> Result<()> {
|
||||
debug!("flushing OTEL metrics");
|
||||
self.meter_provider
|
||||
.force_flush()
|
||||
.map_err(|source| MetricsError::ProviderShutdown { source })?;
|
||||
self.meter_provider
|
||||
.shutdown()
|
||||
.map_err(|source| MetricsError::ProviderShutdown { source })?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Local, in-process OpenTelemetry metrics client. It never exports over the network.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct MetricsClient {
|
||||
// Keep the original provider so its owner only shuts down its own reader.
|
||||
pub(super) inner: Arc<MetricsClientInner>,
|
||||
// Installed clients share this slot, so existing clones follow account changes.
|
||||
pub(super) active: Option<Arc<RwLock<Arc<MetricsClientInner>>>>,
|
||||
}
|
||||
|
||||
impl MetricsClient {
|
||||
/// Build a metrics client from configuration and validate defaults.
|
||||
pub fn new(config: MetricsConfig) -> Result<Self> {
|
||||
let MetricsConfig {
|
||||
environment,
|
||||
service_name,
|
||||
service_version,
|
||||
exporter,
|
||||
export_interval,
|
||||
runtime_reader,
|
||||
default_tags,
|
||||
} = config;
|
||||
|
||||
validate_tags(&default_tags)?;
|
||||
|
||||
let mut resource_attributes = Vec::with_capacity(4);
|
||||
resource_attributes.push(KeyValue::new(
|
||||
semconv::attribute::SERVICE_VERSION,
|
||||
service_version,
|
||||
));
|
||||
resource_attributes.push(KeyValue::new(ENV_ATTRIBUTE, environment));
|
||||
resource_attributes.extend(os_resource_attributes());
|
||||
|
||||
let resource = Resource::builder()
|
||||
.with_service_name(service_name)
|
||||
.with_attributes(resource_attributes)
|
||||
.build();
|
||||
|
||||
let runtime_reader = runtime_reader.then(|| {
|
||||
Arc::new(
|
||||
ManualReader::builder()
|
||||
.with_temporality(Temporality::Delta)
|
||||
.build(),
|
||||
)
|
||||
});
|
||||
|
||||
let (meter_provider, meter) =
|
||||
build_provider(resource, exporter, export_interval, runtime_reader.clone());
|
||||
|
||||
Ok(Self {
|
||||
inner: Arc::new(MetricsClientInner {
|
||||
meter_provider,
|
||||
meter,
|
||||
counters: Mutex::new(HashMap::new()),
|
||||
gauges: Mutex::new(HashMap::new()),
|
||||
histograms: Mutex::new(HashMap::new()),
|
||||
duration_histograms: Mutex::new(HashMap::new()),
|
||||
runtime_reader,
|
||||
default_tags,
|
||||
}),
|
||||
active: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn active_inner(&self) -> Arc<MetricsClientInner> {
|
||||
match &self.active {
|
||||
Some(active) => active
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clone(),
|
||||
None => Arc::clone(&self.inner),
|
||||
}
|
||||
}
|
||||
|
||||
/// Send a single counter increment.
|
||||
pub fn counter(&self, name: &str, inc: i64, tags: &[(&str, &str)]) -> Result<()> {
|
||||
self.active_inner()
|
||||
.counter(name, /*description*/ None, inc, tags)
|
||||
}
|
||||
|
||||
/// Send a single counter increment with an instrument description.
|
||||
pub fn counter_with_description(
|
||||
&self,
|
||||
name: &str,
|
||||
description: &str,
|
||||
inc: i64,
|
||||
tags: &[(&str, &str)],
|
||||
) -> Result<()> {
|
||||
self.active_inner()
|
||||
.counter(name, Some(description), inc, tags)
|
||||
}
|
||||
|
||||
/// Send a single histogram sample.
|
||||
pub fn histogram(&self, name: &str, value: i64, tags: &[(&str, &str)]) -> Result<()> {
|
||||
self.active_inner()
|
||||
.histogram(name, value, /*boundaries*/ None, tags)
|
||||
}
|
||||
|
||||
/// Send a single histogram sample using explicit bucket boundaries.
|
||||
pub fn histogram_with_boundaries(
|
||||
&self,
|
||||
name: &str,
|
||||
value: i64,
|
||||
boundaries: &[f64],
|
||||
tags: &[(&str, &str)],
|
||||
) -> Result<()> {
|
||||
self.active_inner()
|
||||
.histogram(name, value, Some(boundaries), tags)
|
||||
}
|
||||
|
||||
/// Send a single gauge measurement.
|
||||
pub fn gauge(&self, name: &str, value: i64, tags: &[(&str, &str)]) -> Result<()> {
|
||||
self.active_inner()
|
||||
.gauge(name, /*description*/ None, value, tags)
|
||||
}
|
||||
|
||||
/// Send a single gauge measurement with an instrument description.
|
||||
pub fn gauge_with_description(
|
||||
&self,
|
||||
name: &str,
|
||||
description: &str,
|
||||
value: i64,
|
||||
tags: &[(&str, &str)],
|
||||
) -> Result<()> {
|
||||
self.active_inner()
|
||||
.gauge(name, Some(description), value, tags)
|
||||
}
|
||||
|
||||
/// Register a gauge callback that reports the current value on every collection.
|
||||
pub fn register_observable_gauge_with_description(
|
||||
&self,
|
||||
name: &str,
|
||||
description: &str,
|
||||
observe: impl Fn() -> i64 + Send + Sync + 'static,
|
||||
tags: &[(&str, &str)],
|
||||
) -> Result<()> {
|
||||
self.active_inner()
|
||||
.register_observable_gauge(name, description, observe, tags)
|
||||
}
|
||||
|
||||
/// Record a duration in milliseconds using a histogram.
|
||||
pub fn record_duration(
|
||||
&self,
|
||||
name: &str,
|
||||
duration: Duration,
|
||||
tags: &[(&str, &str)],
|
||||
) -> Result<()> {
|
||||
self.active_inner().duration_histogram(
|
||||
name,
|
||||
duration.as_millis().min(i64::MAX as u128) as f64,
|
||||
MILLISECOND_DURATION_UNIT,
|
||||
MILLISECOND_DURATION_DESCRIPTION,
|
||||
match name {
|
||||
TURN_CRITICAL_PATH_DURATION_METRIC | TURN_CRITICAL_PATH_COMPONENT_METRIC => {
|
||||
&TURN_CRITICAL_PATH_DURATION_BOUNDARIES
|
||||
}
|
||||
_ => MILLISECOND_DURATION_BOUNDARIES,
|
||||
},
|
||||
tags,
|
||||
)
|
||||
}
|
||||
|
||||
/// Record a duration supplied as fractional milliseconds using a histogram.
|
||||
pub(crate) fn record_duration_ms_f64(
|
||||
&self,
|
||||
name: &str,
|
||||
duration_ms: f64,
|
||||
tags: &[(&str, &str)],
|
||||
) -> Result<()> {
|
||||
self.active_inner().duration_histogram(
|
||||
name,
|
||||
duration_ms,
|
||||
MILLISECOND_DURATION_UNIT,
|
||||
MILLISECOND_DURATION_DESCRIPTION,
|
||||
MILLISECOND_DURATION_BOUNDARIES,
|
||||
tags,
|
||||
)
|
||||
}
|
||||
|
||||
/// Record a duration in seconds using a histogram with an instrument description.
|
||||
pub fn record_duration_seconds_with_description(
|
||||
&self,
|
||||
name: &str,
|
||||
description: &str,
|
||||
duration: Duration,
|
||||
tags: &[(&str, &str)],
|
||||
) -> Result<()> {
|
||||
self.active_inner().duration_histogram(
|
||||
name,
|
||||
duration.as_secs_f64(),
|
||||
SECOND_DURATION_UNIT,
|
||||
description,
|
||||
SECOND_DURATION_BOUNDARIES,
|
||||
tags,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn start_timer(
|
||||
&self,
|
||||
name: &str,
|
||||
tags: &[(&str, &str)],
|
||||
) -> std::result::Result<Timer, MetricsError> {
|
||||
Ok(Timer::new(name, tags, self))
|
||||
}
|
||||
|
||||
/// Collect a runtime metrics snapshot without shutting down the provider.
|
||||
pub fn snapshot(&self) -> Result<ResourceMetrics> {
|
||||
let inner = self.active_inner();
|
||||
let Some(reader) = &inner.runtime_reader else {
|
||||
return Err(MetricsError::RuntimeSnapshotUnavailable);
|
||||
};
|
||||
let mut snapshot = ResourceMetrics::default();
|
||||
reader
|
||||
.collect(&mut snapshot)
|
||||
.map_err(|source| MetricsError::RuntimeSnapshotCollect { source })?;
|
||||
Ok(snapshot)
|
||||
}
|
||||
|
||||
/// Flush metrics and stop the underlying OTEL meter provider.
|
||||
pub fn shutdown(&self) -> Result<()> {
|
||||
super::buffered::GLOBAL.suspend(self);
|
||||
self.inner.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
fn os_resource_attributes() -> Vec<KeyValue> {
|
||||
// Provider creation must not repeat OS discovery subprocesses.
|
||||
static OS_INFO: LazyLock<os_info::Info> = LazyLock::new(os_info::get);
|
||||
let os_info = &*OS_INFO;
|
||||
let os_type_raw = os_info.os_type().to_string();
|
||||
let os_type = sanitize_metric_tag_value(os_type_raw.as_str());
|
||||
let os_version_raw = os_info.version().to_string();
|
||||
let os_version = sanitize_metric_tag_value(os_version_raw.as_str());
|
||||
let mut attributes = Vec::new();
|
||||
if os_type != "unspecified" {
|
||||
attributes.push(KeyValue::new("os", os_type));
|
||||
}
|
||||
if os_version != "unspecified" {
|
||||
attributes.push(KeyValue::new("os_version", os_version));
|
||||
}
|
||||
attributes
|
||||
}
|
||||
|
||||
fn build_provider<E>(
|
||||
resource: Resource,
|
||||
exporter: E,
|
||||
interval: Option<Duration>,
|
||||
runtime_reader: Option<Arc<ManualReader>>,
|
||||
) -> (SdkMeterProvider, Meter)
|
||||
where
|
||||
E: opentelemetry_sdk::metrics::exporter::PushMetricExporter + 'static,
|
||||
{
|
||||
let mut reader_builder = PeriodicReader::builder(exporter);
|
||||
if let Some(interval) = interval {
|
||||
reader_builder = reader_builder.with_interval(interval);
|
||||
}
|
||||
let reader = reader_builder.build();
|
||||
let mut provider_builder = SdkMeterProvider::builder().with_resource(resource);
|
||||
if let Some(reader) = runtime_reader {
|
||||
provider_builder = provider_builder.with_reader(SharedManualReader::new(reader));
|
||||
}
|
||||
let provider = provider_builder.with_reader(reader).build();
|
||||
let meter = provider.meter(METER_NAME);
|
||||
(provider, meter)
|
||||
}
|
||||
60
akode-rs/otel/src/metrics/config.rs
Normal file
60
akode-rs/otel/src/metrics/config.rs
Normal file
@@ -0,0 +1,60 @@
|
||||
use crate::metrics::Result;
|
||||
use crate::metrics::validation::validate_tag_key;
|
||||
use crate::metrics::validation::validate_tag_value;
|
||||
use opentelemetry_sdk::metrics::InMemoryMetricExporter;
|
||||
use std::collections::BTreeMap;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Configuration for a local, in-process metrics client. There is no network exporter.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct MetricsConfig {
|
||||
pub(crate) environment: String,
|
||||
pub(crate) service_name: String,
|
||||
pub(crate) service_version: String,
|
||||
pub(crate) exporter: InMemoryMetricExporter,
|
||||
pub(crate) export_interval: Option<Duration>,
|
||||
pub(crate) runtime_reader: bool,
|
||||
pub(crate) default_tags: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl MetricsConfig {
|
||||
/// Create an in-memory config.
|
||||
pub fn in_memory(
|
||||
environment: impl Into<String>,
|
||||
service_name: impl Into<String>,
|
||||
service_version: impl Into<String>,
|
||||
exporter: InMemoryMetricExporter,
|
||||
) -> Self {
|
||||
Self {
|
||||
environment: environment.into(),
|
||||
service_name: service_name.into(),
|
||||
service_version: service_version.into(),
|
||||
exporter,
|
||||
export_interval: None,
|
||||
runtime_reader: false,
|
||||
default_tags: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Override the interval between periodic metric exports.
|
||||
pub fn with_export_interval(mut self, interval: Duration) -> Self {
|
||||
self.export_interval = Some(interval);
|
||||
self
|
||||
}
|
||||
|
||||
/// Enable a manual reader for on-demand runtime snapshots.
|
||||
pub fn with_runtime_reader(mut self) -> Self {
|
||||
self.runtime_reader = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// Add a default tag that will be recorded with every metric.
|
||||
pub fn with_tag(mut self, key: impl Into<String>, value: impl Into<String>) -> Result<Self> {
|
||||
let key = key.into();
|
||||
let value = value.into();
|
||||
validate_tag_key(&key)?;
|
||||
validate_tag_value(&value)?;
|
||||
self.default_tags.insert(key, value);
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
40
akode-rs/otel/src/metrics/error.rs
Normal file
40
akode-rs/otel/src/metrics/error.rs
Normal file
@@ -0,0 +1,40 @@
|
||||
use thiserror::Error;
|
||||
|
||||
pub type Result<T> = std::result::Result<T, MetricsError>;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum MetricsError {
|
||||
#[error("operation metrics exceed the metadata size or tag count limit")]
|
||||
OperationMetadataTooLarge,
|
||||
|
||||
// Metrics.
|
||||
#[error("metric name cannot be empty")]
|
||||
EmptyMetricName,
|
||||
#[error("metric name contains invalid characters: {name}")]
|
||||
InvalidMetricName { name: String },
|
||||
#[error("{label} cannot be empty")]
|
||||
EmptyTagComponent { label: String },
|
||||
#[error("{label} contains invalid characters: {value}")]
|
||||
InvalidTagComponent { label: String, value: String },
|
||||
|
||||
#[error("metrics are not installed")]
|
||||
ExporterDisabled,
|
||||
|
||||
#[error("counter increment must be non-negative for {name}: {inc}")]
|
||||
NegativeCounterIncrement { name: String, inc: i64 },
|
||||
|
||||
#[error("failed to flush or shutdown metrics provider")]
|
||||
ProviderShutdown {
|
||||
#[source]
|
||||
source: opentelemetry_sdk::error::OTelSdkError,
|
||||
},
|
||||
|
||||
#[error("runtime metrics snapshot reader is not enabled")]
|
||||
RuntimeSnapshotUnavailable,
|
||||
|
||||
#[error("failed to collect runtime metrics snapshot from metrics reader")]
|
||||
RuntimeSnapshotCollect {
|
||||
#[source]
|
||||
source: opentelemetry_sdk::error::OTelSdkError,
|
||||
},
|
||||
}
|
||||
44
akode-rs/otel/src/metrics/mod.rs
Normal file
44
akode-rs/otel/src/metrics/mod.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
pub(crate) mod buffered;
|
||||
mod client;
|
||||
mod config;
|
||||
mod error;
|
||||
pub(crate) mod names;
|
||||
mod process;
|
||||
pub(crate) mod runtime_metrics;
|
||||
pub(crate) mod tags;
|
||||
pub(crate) mod timer;
|
||||
pub(crate) mod validation;
|
||||
|
||||
pub use crate::metrics::buffered::record_global_operation;
|
||||
pub use crate::metrics::client::MetricsClient;
|
||||
pub use crate::metrics::config::MetricsConfig;
|
||||
pub use crate::metrics::error::MetricsError;
|
||||
pub use crate::metrics::error::Result;
|
||||
pub use crate::metrics::process::record_process_start_once;
|
||||
pub use names::*;
|
||||
use std::sync::Arc;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::RwLock;
|
||||
pub use tags::ORIGINATOR_TAG;
|
||||
pub use tags::SessionMetricTagValues;
|
||||
pub use tags::bounded_originator_tag_value;
|
||||
|
||||
static GLOBAL_METRICS: OnceLock<MetricsClient> = OnceLock::new();
|
||||
|
||||
pub(crate) fn install_global(mut metrics: MetricsClient) -> MetricsClient {
|
||||
let active = GLOBAL_METRICS
|
||||
.get()
|
||||
.and_then(|current| current.active.clone())
|
||||
.unwrap_or_else(|| Arc::new(RwLock::new(Arc::clone(&metrics.inner))));
|
||||
*active
|
||||
.write()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = Arc::clone(&metrics.inner);
|
||||
metrics.active = Some(active);
|
||||
let _ = GLOBAL_METRICS.set(metrics.clone());
|
||||
buffered::GLOBAL.enable(&metrics);
|
||||
metrics
|
||||
}
|
||||
|
||||
pub fn global() -> Option<MetricsClient> {
|
||||
GLOBAL_METRICS.get().cloned()
|
||||
}
|
||||
148
akode-rs/otel/src/metrics/names.rs
Normal file
148
akode-rs/otel/src/metrics/names.rs
Normal file
@@ -0,0 +1,148 @@
|
||||
use std::sync::LazyLock;
|
||||
|
||||
pub const TOOL_CALL_COUNT_METRIC: &str = "codex.tool.call";
|
||||
pub const TOOL_CALL_DURATION_METRIC: &str = "codex.tool.call.duration_ms";
|
||||
pub const TOOL_CALL_UNIFIED_EXEC_METRIC: &str = "codex.tool.unified_exec";
|
||||
pub const MULTI_AGENT_SPAWN_FAILURE_METRIC: &str = "codex.multi_agent.spawn.failure";
|
||||
pub const MULTI_AGENT_SPAWN_PHASE_DURATION_METRIC: &str =
|
||||
"codex.multi_agent.spawn.phase.duration_ms";
|
||||
pub const ARTIFACT_OPERATION_STARTED_METRIC: &str = "codex.artifact.operation.started";
|
||||
pub const ARTIFACT_OPERATION_EXPECTED_OUTPUT_COUNT_METRIC: &str =
|
||||
"codex.artifact.operation.expected_output_count";
|
||||
pub const PROCESS_START_METRIC: &str = "codex.process.start";
|
||||
/// Caller-side exec-server RPC attempts, including local admission and transport failures.
|
||||
pub const EXEC_SERVER_CLIENT_REQUEST_COUNT_METRIC: &str = "exec_server_client_requests_total";
|
||||
pub const API_CALL_COUNT_METRIC: &str = "codex.api_request";
|
||||
pub const API_CALL_DURATION_METRIC: &str = "codex.api_request.duration_ms";
|
||||
pub const SSE_EVENT_COUNT_METRIC: &str = "codex.sse_event";
|
||||
pub const SSE_EVENT_DURATION_METRIC: &str = "codex.sse_event.duration_ms";
|
||||
pub const WEBSOCKET_CONNECT_COUNT_METRIC: &str = "codex.websocket.connect";
|
||||
pub const WEBSOCKET_CONNECT_DURATION_METRIC: &str = "codex.websocket.connect.duration_ms";
|
||||
pub const WEBSOCKET_REQUEST_COUNT_METRIC: &str = "codex.websocket.request";
|
||||
pub const WEBSOCKET_CONTINUATION_COUNT_METRIC: &str = "codex.websocket.continuation";
|
||||
pub const WEBSOCKET_REQUEST_DURATION_METRIC: &str = "codex.websocket.request.duration_ms";
|
||||
pub const WEBSOCKET_EVENT_COUNT_METRIC: &str = "codex.websocket.event";
|
||||
pub const WEBSOCKET_EVENT_DURATION_METRIC: &str = "codex.websocket.event.duration_ms";
|
||||
pub const RESPONSES_API_OVERHEAD_DURATION_METRIC: &str = "codex.responses_api_overhead.duration_ms";
|
||||
pub const RESPONSES_API_INFERENCE_TIME_DURATION_METRIC: &str =
|
||||
"codex.responses_api_inference_time.duration_ms";
|
||||
pub const RESPONSES_API_ENGINE_IAPI_TTFT_DURATION_METRIC: &str =
|
||||
"codex.responses_api_engine_iapi_ttft.duration_ms";
|
||||
pub const RESPONSES_API_ENGINE_SERVICE_TTFT_DURATION_METRIC: &str =
|
||||
"codex.responses_api_engine_service_ttft.duration_ms";
|
||||
pub const RESPONSES_API_ENGINE_IAPI_TBT_DURATION_METRIC: &str =
|
||||
"codex.responses_api_engine_iapi_tbt.duration_ms";
|
||||
pub const RESPONSES_API_ENGINE_SERVICE_TBT_DURATION_METRIC: &str =
|
||||
"codex.responses_api_engine_service_tbt.duration_ms";
|
||||
pub const TURN_E2E_DURATION_METRIC: &str = "codex.turn.e2e_duration_ms";
|
||||
pub const TURN_TTFT_DURATION_METRIC: &str = "codex.turn.ttft.duration_ms";
|
||||
pub const TURN_TTFM_DURATION_METRIC: &str = "codex.turn.ttfm.duration_ms";
|
||||
pub const TURN_CRITICAL_PATH_CAPTURE_METRIC: &str = "codex.turn.critical_path.capture";
|
||||
pub const TURN_CRITICAL_PATH_DURATION_METRIC: &str = "codex.turn.critical_path.duration_ms";
|
||||
pub const TURN_CRITICAL_PATH_COMPONENT_METRIC: &str = "codex.turn.critical_path.component_ms";
|
||||
pub const TURN_NETWORK_PROXY_METRIC: &str = "codex.turn.network_proxy";
|
||||
pub const TURN_MEMORY_METRIC: &str = "codex.turn.memory";
|
||||
pub const TURN_TOOL_CALL_METRIC: &str = "codex.turn.tool.call";
|
||||
pub const TURN_TOKEN_USAGE_METRIC: &str = "codex.turn.token_usage";
|
||||
pub const TURN_COST_MICROUSD_METRIC: &str = "codex.turn.cost_microusd";
|
||||
pub const TURN_UNIFIED_EXEC_RUNNING_PROCESSES_METRIC: &str =
|
||||
"codex.turn.unified_exec.running_processes";
|
||||
pub const GUARDIAN_REVIEW_COUNT_METRIC: &str = "codex.guardian.review";
|
||||
pub const GUARDIAN_REVIEW_DURATION_METRIC: &str = "codex.guardian.review.duration_ms";
|
||||
pub const GUARDIAN_REVIEW_TTFT_DURATION_METRIC: &str = "codex.guardian.review.ttft.duration_ms";
|
||||
pub const GUARDIAN_REVIEW_TOKEN_USAGE_METRIC: &str = "codex.guardian.review.token_usage";
|
||||
pub const GUARDIAN_REVIEW_TRUNCATION_METRIC: &str = "codex.guardian.review.truncation";
|
||||
pub const GUARDIAN_REVIEW_TRUNCATION_BYTES_METRIC: &str = "codex.guardian.review.truncation.bytes";
|
||||
pub const GOAL_CREATED_METRIC: &str = "codex.goal.created";
|
||||
pub const GOAL_RESUMED_METRIC: &str = "codex.goal.resumed";
|
||||
pub const GOAL_COMPLETED_METRIC: &str = "codex.goal.completed";
|
||||
pub const GOAL_BUDGET_LIMITED_METRIC: &str = "codex.goal.budget_limited";
|
||||
pub const GOAL_USAGE_LIMITED_METRIC: &str = "codex.goal.usage_limited";
|
||||
pub const GOAL_BLOCKED_METRIC: &str = "codex.goal.blocked";
|
||||
pub const GOAL_TOKEN_COUNT_METRIC: &str = "codex.goal.token_count";
|
||||
pub const GOAL_DURATION_SECONDS_METRIC: &str = "codex.goal.duration_s";
|
||||
pub const PLUGIN_INSTALL_ELICITATION_SENT_METRIC: &str = "codex.plugins.install_elicitation.sent";
|
||||
pub const PLUGIN_INSTALL_SUGGESTION_METRIC: &str = "codex.plugins.install_suggestion";
|
||||
pub const CURATED_PLUGINS_STARTUP_SYNC_METRIC: &str = "codex.plugins.startup_sync";
|
||||
pub const CURATED_PLUGINS_STARTUP_SYNC_FINAL_METRIC: &str = "codex.plugins.startup_sync.final";
|
||||
pub const HOOK_RUN_METRIC: &str = "codex.hooks.run";
|
||||
pub const HOOK_RUN_DURATION_METRIC: &str = "codex.hooks.run.duration_ms";
|
||||
/// Duration for coarse startup phases, tagged by low-cardinality phase and status.
|
||||
pub const STARTUP_PHASE_DURATION_METRIC: &str = "codex.startup.phase.duration_ms";
|
||||
/// Total runtime of a startup prewarm attempt until it completes, tagged by final status.
|
||||
pub const STARTUP_PREWARM_DURATION_METRIC: &str = "codex.startup_prewarm.duration_ms";
|
||||
/// Age of the startup prewarm attempt when the first real turn resolves it, tagged by outcome.
|
||||
pub const STARTUP_PREWARM_AGE_AT_FIRST_TURN_METRIC: &str =
|
||||
"codex.startup_prewarm.age_at_first_turn_ms";
|
||||
pub const THREAD_STARTED_METRIC: &str = "codex.thread.started";
|
||||
/// Submitted additional-context entries, including unchanged entries, by kind and truncation status.
|
||||
/// The name tag is included only when explicitly supplied; opaque source keys are never tags.
|
||||
pub const ADDITIONAL_CONTEXT_COUNT_METRIC: &str = "codex.additional_context";
|
||||
/// UTF-8 value bytes before/after truncation, excluding message wrappers; after includes the marker.
|
||||
pub const ADDITIONAL_CONTEXT_VALUE_BYTES_METRIC: &str = "codex.additional_context.value_bytes";
|
||||
/// Logarithmic byte buckets through 4 MiB, with a 4 KiB boundary near the truncation cap.
|
||||
pub static ADDITIONAL_CONTEXT_VALUE_BYTES_BUCKETS: LazyLock<Vec<f64>> = LazyLock::new(|| {
|
||||
let mut buckets = context_log_buckets(/*max_exponent*/ 22.0)
|
||||
.into_iter()
|
||||
.chain([4096.0])
|
||||
.collect::<Vec<_>>();
|
||||
buckets.sort_by(f64::total_cmp);
|
||||
buckets.dedup();
|
||||
buckets
|
||||
});
|
||||
pub const THREAD_SKILLS_ENABLED_TOTAL_METRIC: &str = "codex.thread.skills.enabled_total";
|
||||
pub const THREAD_SKILLS_KEPT_TOTAL_METRIC: &str = "codex.thread.skills.kept_total";
|
||||
pub const THREAD_SKILLS_DESCRIPTION_TRUNCATED_CHARS_METRIC: &str =
|
||||
"codex.thread.skills.description_truncated_chars";
|
||||
pub const THREAD_SKILLS_TRUNCATED_METRIC: &str = "codex.thread.skills.truncated";
|
||||
// Tools measure the rendered block; kind=snapshot|delta distinguishes full catalogs from updates.
|
||||
pub const THREAD_TOOLS_NAMESPACES_TOTAL_METRIC: &str = "codex.thread.tools.namespaces_total";
|
||||
pub const THREAD_TOOLS_FRAGMENT_BYTES_METRIC: &str = "codex.thread.tools.fragment_bytes";
|
||||
|
||||
/// Finalized tool registrations per sampling request, tagged by exposure, tool_mode,
|
||||
/// and effective incremental_tools mode.
|
||||
pub const TOOL_REGISTRATIONS_METRIC: &str = "codex.tools.registered";
|
||||
pub const TOOL_REGISTRATIONS_METRIC_BUCKETS: &[f64] = &[
|
||||
0.0, 1.0, 2.0, 5.0, 10.0, 20.0, 30.0, 50.0, 75.0, 100.0, 150.0, 200.0, 300.0, 500.0, 750.0,
|
||||
1_000.0, 2_000.0, 5_000.0, 10_000.0, 20_000.0,
|
||||
];
|
||||
|
||||
/// Logarithmic boundaries up to 32,768 for tools bytes and namespace counts.
|
||||
pub static THREAD_TOOLS_METRIC_BUCKETS: LazyLock<[f64; 511]> =
|
||||
LazyLock::new(|| context_log_buckets(/*max_exponent*/ 15.0));
|
||||
|
||||
/// Rendered incremental tool deltas by action and qualified tool; excludes initial catalogs.
|
||||
/// schema_changed includes any definition change, such as description edits.
|
||||
pub const TOOL_INCREMENTAL_UPDATES_METRIC: &str = "codex.tools.incremental_updates";
|
||||
|
||||
/// UTF-8 description bytes on replacement by qualified tool; skips missing descriptions.
|
||||
pub const TOOL_SPEC_DESCRIPTION_BYTES_METRIC: &str = "codex.tools.spec_description_bytes";
|
||||
/// Logarithmic boundaries up to 1 MiB.
|
||||
pub static TOOL_SPEC_DESCRIPTION_BYTES_METRIC_BUCKETS: LazyLock<[f64; 511]> =
|
||||
LazyLock::new(|| context_log_buckets(/*max_exponent*/ 20.0));
|
||||
|
||||
/// Rendered exec entry deltas (tools and namespace instructions), by action.
|
||||
/// Excludes full declarations; schema_changed includes any entry replacement.
|
||||
pub const EXEC_TOOL_ENTRY_UPDATES_METRIC: &str = "codex.tools.exec_entry_updates";
|
||||
/// UTF-8 bytes per rendered added/changed exec batch, including hint and framing.
|
||||
/// Excludes full declarations and removal notices.
|
||||
pub const EXEC_TOOL_UPDATE_BYTES_METRIC: &str = "codex.tools.exec_update_bytes";
|
||||
|
||||
pub static THREAD_SKILLS_COUNT_METRIC_BUCKETS: LazyLock<[f64; 513]> =
|
||||
LazyLock::new(|| std::array::from_fn(|index| index as f64));
|
||||
|
||||
/// Logarithmic boundaries up to 131,072 removed description characters.
|
||||
pub static THREAD_SKILLS_DESCRIPTION_TRUNCATED_CHARS_BUCKETS: LazyLock<[f64; 511]> =
|
||||
LazyLock::new(|| context_log_buckets(/*max_exponent*/ 17.0));
|
||||
|
||||
pub const THREAD_SKILLS_TRUNCATED_BUCKETS: &[f64] = &[0.0, 1.0];
|
||||
|
||||
fn context_log_buckets(max_exponent: f64) -> [f64; 511] {
|
||||
std::array::from_fn(|index| {
|
||||
if index == 0 {
|
||||
0.0
|
||||
} else {
|
||||
2.0_f64.powf(max_exponent * (index - 1) as f64 / 509.0)
|
||||
}
|
||||
})
|
||||
}
|
||||
27
akode-rs/otel/src/metrics/process.rs
Normal file
27
akode-rs/otel/src/metrics/process.rs
Normal file
@@ -0,0 +1,27 @@
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use super::client::MetricsClient;
|
||||
use super::error::Result;
|
||||
use super::names::PROCESS_START_METRIC;
|
||||
use super::tags::ORIGINATOR_TAG;
|
||||
use super::tags::bounded_originator_tag_value;
|
||||
|
||||
static PROCESS_START_RECORDED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// Record the process start counter at most once for this process.
|
||||
pub fn record_process_start_once(metrics: &MetricsClient, originator: &str) -> Result<bool> {
|
||||
if PROCESS_START_RECORDED
|
||||
.compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed)
|
||||
.is_err()
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
metrics.counter(
|
||||
PROCESS_START_METRIC,
|
||||
/*inc*/ 1,
|
||||
&[(ORIGINATOR_TAG, bounded_originator_tag_value(originator))],
|
||||
)?;
|
||||
Ok(true)
|
||||
}
|
||||
220
akode-rs/otel/src/metrics/runtime_metrics.rs
Normal file
220
akode-rs/otel/src/metrics/runtime_metrics.rs
Normal file
@@ -0,0 +1,220 @@
|
||||
use crate::metrics::names::API_CALL_COUNT_METRIC;
|
||||
use crate::metrics::names::API_CALL_DURATION_METRIC;
|
||||
use crate::metrics::names::RESPONSES_API_ENGINE_IAPI_TBT_DURATION_METRIC;
|
||||
use crate::metrics::names::RESPONSES_API_ENGINE_IAPI_TTFT_DURATION_METRIC;
|
||||
use crate::metrics::names::RESPONSES_API_ENGINE_SERVICE_TBT_DURATION_METRIC;
|
||||
use crate::metrics::names::RESPONSES_API_ENGINE_SERVICE_TTFT_DURATION_METRIC;
|
||||
use crate::metrics::names::RESPONSES_API_INFERENCE_TIME_DURATION_METRIC;
|
||||
use crate::metrics::names::RESPONSES_API_OVERHEAD_DURATION_METRIC;
|
||||
use crate::metrics::names::SSE_EVENT_COUNT_METRIC;
|
||||
use crate::metrics::names::SSE_EVENT_DURATION_METRIC;
|
||||
use crate::metrics::names::TOOL_CALL_COUNT_METRIC;
|
||||
use crate::metrics::names::TOOL_CALL_DURATION_METRIC;
|
||||
use crate::metrics::names::TURN_TTFM_DURATION_METRIC;
|
||||
use crate::metrics::names::TURN_TTFT_DURATION_METRIC;
|
||||
use crate::metrics::names::WEBSOCKET_EVENT_COUNT_METRIC;
|
||||
use crate::metrics::names::WEBSOCKET_EVENT_DURATION_METRIC;
|
||||
use crate::metrics::names::WEBSOCKET_REQUEST_COUNT_METRIC;
|
||||
use crate::metrics::names::WEBSOCKET_REQUEST_DURATION_METRIC;
|
||||
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
|
||||
use opentelemetry_sdk::metrics::data::Metric;
|
||||
use opentelemetry_sdk::metrics::data::MetricData;
|
||||
use opentelemetry_sdk::metrics::data::ResourceMetrics;
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct RuntimeMetricTotals {
|
||||
pub count: u64,
|
||||
pub duration_ms: u64,
|
||||
}
|
||||
|
||||
impl RuntimeMetricTotals {
|
||||
pub fn is_empty(self) -> bool {
|
||||
self.count == 0 && self.duration_ms == 0
|
||||
}
|
||||
|
||||
pub fn merge(&mut self, other: Self) {
|
||||
self.count = self.count.saturating_add(other.count);
|
||||
self.duration_ms = self.duration_ms.saturating_add(other.duration_ms);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub struct RuntimeMetricsSummary {
|
||||
pub tool_calls: RuntimeMetricTotals,
|
||||
pub api_calls: RuntimeMetricTotals,
|
||||
pub streaming_events: RuntimeMetricTotals,
|
||||
pub websocket_calls: RuntimeMetricTotals,
|
||||
pub websocket_events: RuntimeMetricTotals,
|
||||
pub responses_api_overhead_ms: u64,
|
||||
pub responses_api_inference_time_ms: u64,
|
||||
pub responses_api_engine_iapi_ttft_ms: u64,
|
||||
pub responses_api_engine_service_ttft_ms: u64,
|
||||
pub responses_api_engine_iapi_tbt_ms: f64,
|
||||
pub responses_api_engine_service_tbt_ms: f64,
|
||||
pub turn_ttft_ms: u64,
|
||||
pub turn_ttfm_ms: u64,
|
||||
}
|
||||
|
||||
impl RuntimeMetricsSummary {
|
||||
pub fn is_empty(self) -> bool {
|
||||
self.tool_calls.is_empty()
|
||||
&& self.api_calls.is_empty()
|
||||
&& self.streaming_events.is_empty()
|
||||
&& self.websocket_calls.is_empty()
|
||||
&& self.websocket_events.is_empty()
|
||||
&& self.responses_api_overhead_ms == 0
|
||||
&& self.responses_api_inference_time_ms == 0
|
||||
&& self.responses_api_engine_iapi_ttft_ms == 0
|
||||
&& self.responses_api_engine_service_ttft_ms == 0
|
||||
&& self.responses_api_engine_iapi_tbt_ms == 0.0
|
||||
&& self.responses_api_engine_service_tbt_ms == 0.0
|
||||
&& self.turn_ttft_ms == 0
|
||||
&& self.turn_ttfm_ms == 0
|
||||
}
|
||||
|
||||
pub fn merge(&mut self, other: Self) {
|
||||
self.tool_calls.merge(other.tool_calls);
|
||||
self.api_calls.merge(other.api_calls);
|
||||
self.streaming_events.merge(other.streaming_events);
|
||||
self.websocket_calls.merge(other.websocket_calls);
|
||||
self.websocket_events.merge(other.websocket_events);
|
||||
if other.responses_api_overhead_ms > 0 {
|
||||
self.responses_api_overhead_ms = other.responses_api_overhead_ms;
|
||||
}
|
||||
if other.responses_api_inference_time_ms > 0 {
|
||||
self.responses_api_inference_time_ms = other.responses_api_inference_time_ms;
|
||||
}
|
||||
if other.responses_api_engine_iapi_ttft_ms > 0 {
|
||||
self.responses_api_engine_iapi_ttft_ms = other.responses_api_engine_iapi_ttft_ms;
|
||||
}
|
||||
if other.responses_api_engine_service_ttft_ms > 0 {
|
||||
self.responses_api_engine_service_ttft_ms = other.responses_api_engine_service_ttft_ms;
|
||||
}
|
||||
if other.responses_api_engine_iapi_tbt_ms > 0.0 {
|
||||
self.responses_api_engine_iapi_tbt_ms = other.responses_api_engine_iapi_tbt_ms;
|
||||
}
|
||||
if other.responses_api_engine_service_tbt_ms > 0.0 {
|
||||
self.responses_api_engine_service_tbt_ms = other.responses_api_engine_service_tbt_ms;
|
||||
}
|
||||
if other.turn_ttft_ms > 0 {
|
||||
self.turn_ttft_ms = other.turn_ttft_ms;
|
||||
}
|
||||
if other.turn_ttfm_ms > 0 {
|
||||
self.turn_ttfm_ms = other.turn_ttfm_ms;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn responses_api_summary(&self) -> RuntimeMetricsSummary {
|
||||
Self {
|
||||
responses_api_overhead_ms: self.responses_api_overhead_ms,
|
||||
responses_api_inference_time_ms: self.responses_api_inference_time_ms,
|
||||
responses_api_engine_iapi_ttft_ms: self.responses_api_engine_iapi_ttft_ms,
|
||||
responses_api_engine_service_ttft_ms: self.responses_api_engine_service_ttft_ms,
|
||||
responses_api_engine_iapi_tbt_ms: self.responses_api_engine_iapi_tbt_ms,
|
||||
responses_api_engine_service_tbt_ms: self.responses_api_engine_service_tbt_ms,
|
||||
..RuntimeMetricsSummary::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn from_snapshot(snapshot: &ResourceMetrics) -> Self {
|
||||
let tool_calls = RuntimeMetricTotals {
|
||||
count: sum_counter(snapshot, TOOL_CALL_COUNT_METRIC),
|
||||
duration_ms: sum_histogram_ms(snapshot, TOOL_CALL_DURATION_METRIC),
|
||||
};
|
||||
let api_calls = RuntimeMetricTotals {
|
||||
count: sum_counter(snapshot, API_CALL_COUNT_METRIC),
|
||||
duration_ms: sum_histogram_ms(snapshot, API_CALL_DURATION_METRIC),
|
||||
};
|
||||
let streaming_events = RuntimeMetricTotals {
|
||||
count: sum_counter(snapshot, SSE_EVENT_COUNT_METRIC),
|
||||
duration_ms: sum_histogram_ms(snapshot, SSE_EVENT_DURATION_METRIC),
|
||||
};
|
||||
let websocket_calls = RuntimeMetricTotals {
|
||||
count: sum_counter(snapshot, WEBSOCKET_REQUEST_COUNT_METRIC),
|
||||
duration_ms: sum_histogram_ms(snapshot, WEBSOCKET_REQUEST_DURATION_METRIC),
|
||||
};
|
||||
let websocket_events = RuntimeMetricTotals {
|
||||
count: sum_counter(snapshot, WEBSOCKET_EVENT_COUNT_METRIC),
|
||||
duration_ms: sum_histogram_ms(snapshot, WEBSOCKET_EVENT_DURATION_METRIC),
|
||||
};
|
||||
let responses_api_overhead_ms =
|
||||
sum_histogram_ms(snapshot, RESPONSES_API_OVERHEAD_DURATION_METRIC);
|
||||
let responses_api_inference_time_ms =
|
||||
sum_histogram_ms(snapshot, RESPONSES_API_INFERENCE_TIME_DURATION_METRIC);
|
||||
let responses_api_engine_iapi_ttft_ms =
|
||||
sum_histogram_ms(snapshot, RESPONSES_API_ENGINE_IAPI_TTFT_DURATION_METRIC);
|
||||
let responses_api_engine_service_ttft_ms =
|
||||
sum_histogram_ms(snapshot, RESPONSES_API_ENGINE_SERVICE_TTFT_DURATION_METRIC);
|
||||
let responses_api_engine_iapi_tbt_ms =
|
||||
sum_histogram_f64(snapshot, RESPONSES_API_ENGINE_IAPI_TBT_DURATION_METRIC);
|
||||
let responses_api_engine_service_tbt_ms =
|
||||
sum_histogram_f64(snapshot, RESPONSES_API_ENGINE_SERVICE_TBT_DURATION_METRIC);
|
||||
let turn_ttft_ms = sum_histogram_ms(snapshot, TURN_TTFT_DURATION_METRIC);
|
||||
let turn_ttfm_ms = sum_histogram_ms(snapshot, TURN_TTFM_DURATION_METRIC);
|
||||
Self {
|
||||
tool_calls,
|
||||
api_calls,
|
||||
streaming_events,
|
||||
websocket_calls,
|
||||
websocket_events,
|
||||
responses_api_overhead_ms,
|
||||
responses_api_inference_time_ms,
|
||||
responses_api_engine_iapi_ttft_ms,
|
||||
responses_api_engine_service_ttft_ms,
|
||||
responses_api_engine_iapi_tbt_ms,
|
||||
responses_api_engine_service_tbt_ms,
|
||||
turn_ttft_ms,
|
||||
turn_ttfm_ms,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn sum_counter(snapshot: &ResourceMetrics, name: &str) -> u64 {
|
||||
snapshot
|
||||
.scope_metrics()
|
||||
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
|
||||
.filter(|metric| metric.name() == name)
|
||||
.map(sum_counter_metric)
|
||||
.sum()
|
||||
}
|
||||
|
||||
fn sum_counter_metric(metric: &Metric) -> u64 {
|
||||
match metric.data() {
|
||||
AggregatedMetrics::U64(MetricData::Sum(sum)) => sum
|
||||
.data_points()
|
||||
.map(opentelemetry_sdk::metrics::data::SumDataPoint::value)
|
||||
.sum(),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn sum_histogram_ms(snapshot: &ResourceMetrics, name: &str) -> u64 {
|
||||
f64_to_u64(sum_histogram_f64(snapshot, name))
|
||||
}
|
||||
|
||||
fn sum_histogram_f64(snapshot: &ResourceMetrics, name: &str) -> f64 {
|
||||
snapshot
|
||||
.scope_metrics()
|
||||
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
|
||||
.filter(|metric| metric.name() == name)
|
||||
.map(sum_histogram_metric)
|
||||
.sum()
|
||||
}
|
||||
|
||||
fn sum_histogram_metric(metric: &Metric) -> f64 {
|
||||
match metric.data() {
|
||||
AggregatedMetrics::F64(MetricData::Histogram(histogram)) => histogram
|
||||
.data_points()
|
||||
.map(opentelemetry_sdk::metrics::data::HistogramDataPoint::sum)
|
||||
.sum(),
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn f64_to_u64(value: f64) -> u64 {
|
||||
if !value.is_finite() || value <= 0.0 {
|
||||
return 0;
|
||||
}
|
||||
let clamped = value.min(u64::MAX as f64);
|
||||
clamped.round() as u64
|
||||
}
|
||||
136
akode-rs/otel/src/metrics/tags.rs
Normal file
136
akode-rs/otel/src/metrics/tags.rs
Normal file
@@ -0,0 +1,136 @@
|
||||
use crate::metrics::Result;
|
||||
use crate::metrics::validation::validate_tag_key;
|
||||
use crate::metrics::validation::validate_tag_value;
|
||||
use akode_utils_string::sanitize_metric_tag_value;
|
||||
|
||||
pub const APP_VERSION_TAG: &str = "app.version";
|
||||
pub const AUTH_MODE_TAG: &str = "auth_mode";
|
||||
pub const MODEL_TAG: &str = "model";
|
||||
pub const ORIGINATOR_TAG: &str = "originator";
|
||||
pub const SERVICE_NAME_TAG: &str = "service_name";
|
||||
pub const SESSION_SOURCE_TAG: &str = "session_source";
|
||||
|
||||
const OTHER_ORIGINATOR_TAG_VALUE: &str = "other";
|
||||
const KNOWN_ORIGINATOR_TAG_VALUES: &[&str] = &[
|
||||
"codex_desktop",
|
||||
"akode-app-server",
|
||||
"codex_mcp_server",
|
||||
"codex_cli_rs",
|
||||
"akode-tui",
|
||||
"codex_vscode",
|
||||
"none",
|
||||
"akode_exec",
|
||||
"akode-cli",
|
||||
"codex_sdk_ts",
|
||||
"codex-app-server-sdk",
|
||||
];
|
||||
|
||||
/// Return a known low-cardinality originator tag value, or `other`.
|
||||
pub fn bounded_originator_tag_value(originator: &str) -> &'static str {
|
||||
let sanitized = sanitize_metric_tag_value(originator);
|
||||
KNOWN_ORIGINATOR_TAG_VALUES
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|known| *known == sanitized.as_str())
|
||||
.unwrap_or(OTHER_ORIGINATOR_TAG_VALUE)
|
||||
}
|
||||
|
||||
pub struct SessionMetricTagValues<'a> {
|
||||
pub auth_mode: Option<&'a str>,
|
||||
pub session_source: &'a str,
|
||||
pub originator: &'a str,
|
||||
pub service_name: Option<&'a str>,
|
||||
pub model: &'a str,
|
||||
pub app_version: &'a str,
|
||||
}
|
||||
|
||||
impl<'a> SessionMetricTagValues<'a> {
|
||||
pub fn into_tags(self) -> Result<Vec<(&'static str, &'a str)>> {
|
||||
let mut tags = Vec::with_capacity(6);
|
||||
Self::push_optional_tag(&mut tags, AUTH_MODE_TAG, self.auth_mode)?;
|
||||
Self::push_optional_tag(&mut tags, SESSION_SOURCE_TAG, Some(self.session_source))?;
|
||||
Self::push_optional_tag(&mut tags, ORIGINATOR_TAG, Some(self.originator))?;
|
||||
Self::push_optional_tag(&mut tags, SERVICE_NAME_TAG, self.service_name)?;
|
||||
Self::push_optional_tag(&mut tags, MODEL_TAG, Some(self.model))?;
|
||||
Self::push_optional_tag(&mut tags, APP_VERSION_TAG, Some(self.app_version))?;
|
||||
Ok(tags)
|
||||
}
|
||||
|
||||
fn push_optional_tag(
|
||||
tags: &mut Vec<(&'static str, &'a str)>,
|
||||
key: &'static str,
|
||||
value: Option<&'a str>,
|
||||
) -> Result<()> {
|
||||
let Some(value) = value else {
|
||||
return Ok(());
|
||||
};
|
||||
validate_tag_key(key)?;
|
||||
validate_tag_value(value)?;
|
||||
tags.push((key, value));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::APP_VERSION_TAG;
|
||||
use super::AUTH_MODE_TAG;
|
||||
use super::MODEL_TAG;
|
||||
use super::ORIGINATOR_TAG;
|
||||
use super::SERVICE_NAME_TAG;
|
||||
use super::SESSION_SOURCE_TAG;
|
||||
use super::SessionMetricTagValues;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn session_metric_tags_include_expected_tags_in_order() {
|
||||
for app_version in ["1.2.3", "0.164.0-alpha.1+internal"] {
|
||||
let tags = SessionMetricTagValues {
|
||||
auth_mode: Some("api_key"),
|
||||
session_source: "cli",
|
||||
originator: "akode_cli",
|
||||
service_name: Some("desktop_app"),
|
||||
model: "gpt-5.1",
|
||||
app_version,
|
||||
}
|
||||
.into_tags()
|
||||
.expect("tags");
|
||||
|
||||
assert_eq!(
|
||||
tags,
|
||||
vec![
|
||||
(AUTH_MODE_TAG, "api_key"),
|
||||
(SESSION_SOURCE_TAG, "cli"),
|
||||
(ORIGINATOR_TAG, "akode_cli"),
|
||||
(SERVICE_NAME_TAG, "desktop_app"),
|
||||
(MODEL_TAG, "gpt-5.1"),
|
||||
(APP_VERSION_TAG, app_version),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_metric_tags_skip_missing_optional_tags() {
|
||||
let tags = SessionMetricTagValues {
|
||||
auth_mode: None,
|
||||
session_source: "exec",
|
||||
originator: "akode_exec",
|
||||
service_name: None,
|
||||
model: "gpt-5.1",
|
||||
app_version: "1.2.3",
|
||||
}
|
||||
.into_tags()
|
||||
.expect("tags");
|
||||
|
||||
assert_eq!(
|
||||
tags,
|
||||
vec![
|
||||
(SESSION_SOURCE_TAG, "exec"),
|
||||
(ORIGINATOR_TAG, "akode_exec"),
|
||||
(MODEL_TAG, "gpt-5.1"),
|
||||
(APP_VERSION_TAG, "1.2.3"),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
41
akode-rs/otel/src/metrics/timer.rs
Normal file
41
akode-rs/otel/src/metrics/timer.rs
Normal file
@@ -0,0 +1,41 @@
|
||||
use crate::metrics::MetricsClient;
|
||||
use crate::metrics::error::Result;
|
||||
use std::time::Instant;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Timer {
|
||||
name: String,
|
||||
tags: Vec<(String, String)>,
|
||||
client: MetricsClient,
|
||||
start_time: Instant,
|
||||
}
|
||||
|
||||
impl Drop for Timer {
|
||||
fn drop(&mut self) {
|
||||
if let Err(e) = self.record(&[]) {
|
||||
tracing::error!("metrics client error: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Timer {
|
||||
pub(crate) fn new(name: &str, tags: &[(&str, &str)], client: &MetricsClient) -> Self {
|
||||
Self {
|
||||
name: name.to_string(),
|
||||
tags: tags
|
||||
.iter()
|
||||
.map(|(k, v)| (k.to_string(), v.to_string()))
|
||||
.collect(),
|
||||
client: client.clone(),
|
||||
start_time: Instant::now(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn record(&self, additional_tags: &[(&str, &str)]) -> Result<()> {
|
||||
let mut tags = Vec::with_capacity(self.tags.len() + additional_tags.len());
|
||||
tags.extend(additional_tags);
|
||||
tags.extend(self.tags.iter().map(|(k, v)| (k.as_str(), v.as_str())));
|
||||
self.client
|
||||
.record_duration(&self.name, self.start_time.elapsed(), &tags)
|
||||
}
|
||||
}
|
||||
55
akode-rs/otel/src/metrics/validation.rs
Normal file
55
akode-rs/otel/src/metrics/validation.rs
Normal file
@@ -0,0 +1,55 @@
|
||||
use crate::metrics::error::MetricsError;
|
||||
use crate::metrics::error::Result;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub(crate) fn validate_tags(tags: &BTreeMap<String, String>) -> Result<()> {
|
||||
for (key, value) in tags {
|
||||
validate_tag_key(key)?;
|
||||
validate_tag_value(value)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn validate_metric_name(name: &str) -> Result<()> {
|
||||
if name.is_empty() {
|
||||
return Err(MetricsError::EmptyMetricName);
|
||||
}
|
||||
if !name.chars().all(is_metric_char) {
|
||||
return Err(MetricsError::InvalidMetricName {
|
||||
name: name.to_string(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn validate_tag_key(key: &str) -> Result<()> {
|
||||
validate_tag_component(key, "tag key")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn validate_tag_value(value: &str) -> Result<()> {
|
||||
validate_tag_component(value, "tag value")
|
||||
}
|
||||
|
||||
fn validate_tag_component(value: &str, label: &str) -> Result<()> {
|
||||
if value.is_empty() {
|
||||
return Err(MetricsError::EmptyTagComponent {
|
||||
label: label.to_string(),
|
||||
});
|
||||
}
|
||||
if !value.chars().all(is_tag_char) {
|
||||
return Err(MetricsError::InvalidTagComponent {
|
||||
label: label.to_string(),
|
||||
value: value.to_string(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_metric_char(c: char) -> bool {
|
||||
c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')
|
||||
}
|
||||
|
||||
fn is_tag_char(c: char) -> bool {
|
||||
c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | '/' | '+')
|
||||
}
|
||||
Reference in New Issue
Block a user