use super::*;
impl Counter {
pub fn new() -> Self {
Self {
value: AtomicU64::new(0),
}
}
#[inline(always)]
pub fn inc(&self) {
self.inc_by(1);
}
#[inline(always)]
pub fn inc_by(&self, delta: u64) {
let Self { value } = self;
value.fetch_add(delta, Ordering::Relaxed);
}
#[inline(always)]
pub fn get(&self) -> u64 {
let Self { value } = self;
value.load(Ordering::Relaxed)
}
}
impl Gauge {
pub fn new() -> Self {
Self {
value: AtomicI64::new(0),
}
}
#[inline(always)]
pub fn inc(&self) {
let Self { value } = self;
value.fetch_add(1, Ordering::Relaxed);
}
#[inline(always)]
pub fn dec(&self) {
let Self { value } = self;
value.fetch_sub(1, Ordering::Relaxed);
}
#[inline(always)]
pub fn add(&self, delta: i64) {
let Self { value } = self;
value.fetch_add(delta, Ordering::Relaxed);
}
#[inline(always)]
pub fn set(&self, next: i64) {
let Self { value } = self;
value.store(next, Ordering::Relaxed);
}
#[inline(always)]
pub fn get(&self) -> i64 {
let Self { value } = self;
value.load(Ordering::Relaxed)
}
}
impl Histogram {
pub fn new(bounds: &[f64]) -> Self {
let mut sorted: Vec<f64> = bounds
.iter()
.copied()
.filter(|v: &f64| v.is_finite())
.collect();
sorted.sort_by(|a: &f64, b: &f64| a.total_cmp(b));
sorted.dedup();
let bound_labels: Vec<String> = sorted.iter().map(|b: &f64| b.to_string()).collect();
let mut bucket_counts: Vec<AtomicU64> = Vec::with_capacity(sorted.len() + 1);
for _ in 0..=sorted.len() {
bucket_counts.push(AtomicU64::new(0));
}
Self {
bounds: sorted.into_boxed_slice(),
bound_labels: bound_labels.into_boxed_slice(),
bucket_counts: bucket_counts.into_boxed_slice(),
total_count: AtomicU64::new(0),
sum_bits: AtomicU64::new(0.0_f64.to_bits()),
}
}
#[inline]
pub fn observe(&self, sample: f64) {
if !sample.is_finite() {
return;
}
let Self {
bounds,
bucket_counts,
total_count,
sum_bits,
..
} = self;
let idx: usize = if bounds.len() <= LINEAR_SCAN_BUCKET_LIMIT {
let mut count: usize = 0;
for &bound in bounds.iter() {
count += usize::from(bound < sample);
}
count
} else {
bounds.partition_point(|bound: &f64| *bound < sample)
};
bucket_counts[idx].fetch_add(1, Ordering::Relaxed);
total_count.fetch_add(1, Ordering::Relaxed);
atomic_f64_add(sum_bits, sample);
}
#[inline(always)]
pub fn count(&self) -> u64 {
let Self { total_count, .. } = self;
total_count.load(Ordering::Relaxed)
}
#[inline(always)]
pub fn sum(&self) -> f64 {
let Self { sum_bits, .. } = self;
f64::from_bits(sum_bits.load(Ordering::Relaxed))
}
#[inline]
pub(crate) fn write_prometheus_preformatted(
&self,
header: &str,
bucket_prefixes: &[String],
inf_prefix: &str,
sum_prefix: &str,
count_prefix: &str,
out: &mut String,
) {
let Self { bucket_counts, .. } = self;
out.push_str(header);
let mut cumulative: u64 = 0;
let mut num_buf: [u8; INT_STACK_BUF_LEN] = [0u8; INT_STACK_BUF_LEN];
let mut num_start: usize = INT_STACK_BUF_LEN;
let mut formatted_val: u64 = 0;
for (bucket_prefix, bucket_count) in bucket_prefixes.iter().zip(bucket_counts.iter()) {
cumulative += bucket_count.load(Ordering::Relaxed);
out.push_str(bucket_prefix);
if cumulative < 100 {
out.push_str(PROM_DEC_0_99_NL[cumulative as usize]);
} else {
if cumulative != formatted_val {
num_start = format_u64_nl_into(cumulative, &mut num_buf);
formatted_val = cumulative;
}
if let Ok(text) = from_utf8(&num_buf[num_start..]) {
out.push_str(text);
}
}
}
let total: u64 = self.count();
out.push_str(inf_prefix);
if total < 100 {
let total_str: &str = PROM_DEC_0_99_NL[total as usize];
out.push_str(total_str);
out.push_str(sum_prefix);
push_f64_nl(self.sum(), out);
out.push_str(count_prefix);
out.push_str(total_str);
} else {
if total != formatted_val {
num_start = format_u64_nl_into(total, &mut num_buf);
}
if let Ok(text) = from_utf8(&num_buf[num_start..]) {
out.push_str(text);
out.push_str(sum_prefix);
push_f64_nl(self.sum(), out);
out.push_str(count_prefix);
out.push_str(text);
} else {
out.push_str(sum_prefix);
push_f64_nl(self.sum(), out);
out.push_str(count_prefix);
}
}
}
}
impl Default for MetricsConfig {
fn default() -> Self {
Self {
endpoint: DEFAULT_METRICS_ENDPOINT.to_owned(),
namespace: DEFAULT_METRICS_NAMESPACE.to_owned(),
bearer_token: None,
}
}
}
impl MetricsConfig {
pub fn with_endpoint<E>(mut self, endpoint: E) -> Self
where
E: Into<String>,
{
self.set_endpoint(endpoint.into());
self
}
pub fn with_namespace<N>(mut self, namespace: N) -> Self
where
N: Into<String>,
{
self.set_namespace(namespace.into());
self
}
pub fn with_bearer_token<T>(mut self, token: T) -> Self
where
T: Into<String>,
{
self.set_bearer_token(Some(token.into()));
self
}
#[inline(always)]
pub(crate) fn get_bearer_token_ref(&self) -> Option<&str> {
self.bearer_token.as_deref()
}
}
impl BuiltinMetricsShard {
pub(crate) fn new() -> Self {
Self {
status_class_counts: from_fn(|_: usize| AtomicU64::new(0)),
in_flight: AtomicI64::new(0),
response_bytes_total: AtomicU64::new(0),
duration_buckets: from_fn(|_: usize| AtomicU64::new(0)),
duration_count: AtomicU64::new(0),
duration_nanos_sum: AtomicU64::new(0),
}
}
}
impl Default for MetricsRegistry {
fn default() -> Self {
Self::new(DEFAULT_METRICS_NAMESPACE)
}
}
impl MetricsRegistry {
pub fn new<N>(namespace: N) -> Self
where
N: Into<String>,
{
let ns: String = namespace.into();
let prom_req_header: String = format!(
"# HELP {ns}_http_requests_total Total HTTP requests partitioned by status class.\n# TYPE {ns}_http_requests_total counter\n"
);
let prom_req_lines: [String; 6] = from_fn(|idx: usize| {
format!(
"{ns}_http_requests_total{{status_class=\"{}\"}} ",
STATUS_CLASS_LABELS[idx]
)
});
let prom_in_flight_prefix: String = format!(
"# HELP {ns}_http_requests_in_flight Current number of active in-flight HTTP requests.\n# TYPE {ns}_http_requests_in_flight gauge\n{ns}_http_requests_in_flight "
);
let prom_resp_bytes_prefix: String = format!(
"# HELP {ns}_http_response_bytes_total Cumulative HTTP response body bytes sent.\n# TYPE {ns}_http_response_bytes_total counter\n{ns}_http_response_bytes_total "
);
let dur_name: String = format!("{ns}_http_request_duration_seconds");
let prom_dur_header: String =
format!("# HELP {dur_name} {HELP_HTTP_DURATION}\n# TYPE {dur_name} histogram\n");
let prom_dur_bucket_prefixes: Box<[String]> = DEFAULT_LATENCY_BUCKETS
.iter()
.map(|bound: &f64| format!("{dur_name}_bucket{{le=\"{bound}\"}} "))
.collect::<Vec<String>>()
.into_boxed_slice();
let prom_dur_inf_prefix: String = format!("{dur_name}_bucket{{le=\"+Inf\"}} ");
let prom_dur_sum_prefix: String = format!("{dur_name}_sum ");
let prom_dur_count_prefix: String = format!("{dur_name}_count ");
let mut builtin_est_bytes: usize = prom_req_header.len()
+ prom_in_flight_prefix.len()
+ PROM_EST_DIGITS_PER_LINE
+ prom_resp_bytes_prefix.len()
+ PROM_EST_DIGITS_PER_LINE
+ prom_dur_header.len()
+ prom_dur_inf_prefix.len()
+ PROM_EST_DIGITS_PER_LINE
+ prom_dur_sum_prefix.len()
+ PROM_EST_DIGITS_PER_LINE
+ 8
+ prom_dur_count_prefix.len()
+ PROM_EST_DIGITS_PER_LINE;
for line_prefix in &prom_req_lines {
builtin_est_bytes += line_prefix.len() + PROM_EST_DIGITS_PER_LINE;
}
for bucket_prefix in prom_dur_bucket_prefixes.iter() {
builtin_est_bytes += bucket_prefix.len() + PROM_EST_DIGITS_PER_LINE;
}
let builtin_shards: Box<[BuiltinMetricsShard; METRICS_SHARD_COUNT]> =
Box::new(from_fn(|_: usize| BuiltinMetricsShard::new()));
Self {
inner: Arc::new(MetricsRegistryInner {
builtin_est_bytes,
prom_req_header,
prom_req_lines,
prom_in_flight_prefix,
prom_resp_bytes_prefix,
prom_dur_header,
prom_dur_bucket_prefixes,
prom_dur_inf_prefix,
prom_dur_sum_prefix,
prom_dur_count_prefix,
builtin_shards,
duration_extra_sum_bits: AtomicU64::new(0.0_f64.to_bits()),
custom_counter_count: AtomicUsize::new(0),
custom_gauge_count: AtomicUsize::new(0),
custom_histogram_count: AtomicUsize::new(0),
custom_est_bytes: AtomicUsize::new(0),
custom_counters: RwLock::new(hash_map_xx_hash3_64()),
custom_gauges: RwLock::new(hash_map_xx_hash3_64()),
custom_histograms: RwLock::new(hash_map_xx_hash3_64()),
}),
}
}
pub fn register_counter<N, H>(&self, name: N, help: H) -> Arc<Counter>
where
N: Into<String>,
H: Into<String>,
{
let Self { inner } = self;
let key: String = name.into();
if let Ok(read_map) = inner.custom_counters.read()
&& let Some(entry) = read_map.get(&key)
{
return Arc::clone(&entry.metric);
}
let metric: Arc<Counter> = Arc::new(Counter::new());
if let Ok(mut write_map) = inner.custom_counters.write() {
let mut inserted_est: usize = 0;
let entry: &mut RegisteredCounter = write_map.entry(key.clone()).or_insert_with(|| {
let help_str: String = help.into();
let prom_prefix: String =
format!("# HELP {key} {help_str}\n# TYPE {key} counter\n{key} ");
inserted_est = prom_prefix.len() + PROM_EST_DIGITS_PER_LINE;
RegisteredCounter {
prom_prefix,
metric: Arc::clone(&metric),
}
});
if inserted_est != 0 {
inner.custom_counter_count.fetch_add(1, Ordering::Release);
inner
.custom_est_bytes
.fetch_add(inserted_est, Ordering::Relaxed);
}
return Arc::clone(&entry.metric);
}
metric
}
pub fn register_gauge<N, H>(&self, name: N, help: H) -> Arc<Gauge>
where
N: Into<String>,
H: Into<String>,
{
let Self { inner } = self;
let key: String = name.into();
if let Ok(read_map) = inner.custom_gauges.read()
&& let Some(entry) = read_map.get(&key)
{
return Arc::clone(&entry.metric);
}
let metric: Arc<Gauge> = Arc::new(Gauge::new());
if let Ok(mut write_map) = inner.custom_gauges.write() {
let mut inserted_est: usize = 0;
let entry: &mut RegisteredGauge = write_map.entry(key.clone()).or_insert_with(|| {
let help_str: String = help.into();
let prom_prefix: String =
format!("# HELP {key} {help_str}\n# TYPE {key} gauge\n{key} ");
inserted_est = prom_prefix.len() + PROM_EST_DIGITS_PER_LINE;
RegisteredGauge {
prom_prefix,
metric: Arc::clone(&metric),
}
});
if inserted_est != 0 {
inner.custom_gauge_count.fetch_add(1, Ordering::Release);
inner
.custom_est_bytes
.fetch_add(inserted_est, Ordering::Relaxed);
}
return Arc::clone(&entry.metric);
}
metric
}
pub fn register_histogram<N, H>(&self, name: N, help: H, bounds: &[f64]) -> Arc<Histogram>
where
N: Into<String>,
H: Into<String>,
{
let Self { inner } = self;
let key: String = name.into();
if let Ok(read_map) = inner.custom_histograms.read()
&& let Some(entry) = read_map.get(&key)
{
return Arc::clone(&entry.metric);
}
let metric: Arc<Histogram> = Arc::new(Histogram::new(bounds));
if let Ok(mut write_map) = inner.custom_histograms.write() {
let mut inserted_est: usize = 0;
let entry: &mut RegisteredHistogram =
write_map.entry(key.clone()).or_insert_with(|| {
let help_str: String = help.into();
let prom_header: String =
format!("# HELP {key} {help_str}\n# TYPE {key} histogram\n");
let prom_bucket_prefixes: Box<[String]> = metric
.bound_labels
.iter()
.map(|label: &String| format!("{key}_bucket{{le=\"{label}\"}} "))
.collect::<Vec<String>>()
.into_boxed_slice();
let prom_inf_prefix: String = format!("{key}_bucket{{le=\"+Inf\"}} ");
let prom_sum_prefix: String = format!("{key}_sum ");
let prom_count_prefix: String = format!("{key}_count ");
let mut est: usize = prom_header.len()
+ prom_inf_prefix.len()
+ PROM_EST_DIGITS_PER_LINE
+ prom_sum_prefix.len()
+ PROM_EST_DIGITS_PER_LINE
+ 8
+ prom_count_prefix.len()
+ PROM_EST_DIGITS_PER_LINE;
for bucket_prefix in prom_bucket_prefixes.iter() {
est += bucket_prefix.len() + PROM_EST_DIGITS_PER_LINE;
}
inserted_est = est;
RegisteredHistogram {
prom_header,
prom_bucket_prefixes,
prom_inf_prefix,
prom_sum_prefix,
prom_count_prefix,
metric: Arc::clone(&metric),
}
});
if inserted_est != 0 {
inner.custom_histogram_count.fetch_add(1, Ordering::Release);
inner
.custom_est_bytes
.fetch_add(inserted_est, Ordering::Relaxed);
}
return Arc::clone(&entry.metric);
}
metric
}
#[inline(always)]
pub fn record_request_start(&self) {
let Self { inner } = self;
inner.builtin_shards[worker_metrics_shard_index()]
.in_flight
.fetch_add(1, Ordering::Relaxed);
}
#[inline]
pub(crate) fn record_request_finish_nanos(
&self,
status_code: usize,
response_bytes: usize,
duration_ns: u64,
) {
let Self { inner } = self;
let shard: &BuiltinMetricsShard = &inner.builtin_shards[worker_metrics_shard_index()];
shard.in_flight.fetch_sub(1, Ordering::Relaxed);
let class_idx: usize = match status_code / 100 {
2 => 1,
4 => 3,
3 => 2,
5 => 4,
1 => 0,
_ => 5,
};
shard.status_class_counts[class_idx].fetch_add(1, Ordering::Relaxed);
shard
.response_bytes_total
.fetch_add(response_bytes as u64, Ordering::Relaxed);
let mut bucket_idx: usize = 0;
for &bound_ns in &DEFAULT_LATENCY_BUCKETS_NS {
bucket_idx += usize::from(bound_ns < duration_ns);
}
shard.duration_buckets[bucket_idx].fetch_add(1, Ordering::Relaxed);
shard.duration_count.fetch_add(1, Ordering::Relaxed);
shard
.duration_nanos_sum
.fetch_add(duration_ns, Ordering::Relaxed);
}
#[inline]
pub fn record_request_finish(
&self,
status_code: usize,
response_bytes: usize,
duration_secs: f64,
) {
let Self { inner } = self;
let shard: &BuiltinMetricsShard = &inner.builtin_shards[worker_metrics_shard_index()];
shard.in_flight.fetch_sub(1, Ordering::Relaxed);
let class_idx: usize = match status_code / 100 {
2 => 1,
4 => 3,
3 => 2,
5 => 4,
1 => 0,
_ => 5,
};
shard.status_class_counts[class_idx].fetch_add(1, Ordering::Relaxed);
shard
.response_bytes_total
.fetch_add(response_bytes as u64, Ordering::Relaxed);
if duration_secs.is_finite() {
let mut bucket_idx: usize = 0;
for &bound in &DEFAULT_LATENCY_BUCKETS {
bucket_idx += usize::from(bound < duration_secs);
}
shard.duration_buckets[bucket_idx].fetch_add(1, Ordering::Relaxed);
shard.duration_count.fetch_add(1, Ordering::Relaxed);
if (0.0..MAX_SHARD_DURATION_SECS).contains(&duration_secs) {
let nanos: u64 = (duration_secs * NANOS_PER_SEC_F64) as u64;
shard.duration_nanos_sum.fetch_add(nanos, Ordering::Relaxed);
} else {
atomic_f64_add(&inner.duration_extra_sum_bits, duration_secs);
}
}
}
#[inline]
pub fn total_http_requests(&self) -> u64 {
let Self { inner } = self;
let mut total: u64 = 0;
for shard in inner.builtin_shards.iter() {
for counter in &shard.status_class_counts {
total = total.wrapping_add(counter.load(Ordering::Relaxed));
}
}
total
}
pub fn render_prometheus(&self) -> String {
let Self { inner } = self;
let capacity: usize =
inner.builtin_est_bytes + inner.custom_est_bytes.load(Ordering::Relaxed);
let mut out: String = String::with_capacity(capacity);
let mut status_totals: [u64; 6] = [0; 6];
let mut in_flight_total: i64 = 0;
let mut resp_bytes_total: u64 = 0;
let mut bucket_totals: [u64; 12] = [0; 12];
let mut dur_count_total: u64 = 0;
let mut dur_nanos_total: u128 = 0;
for shard in inner.builtin_shards.iter() {
for idx in 0..6 {
status_totals[idx] = status_totals[idx]
.wrapping_add(shard.status_class_counts[idx].load(Ordering::Relaxed));
}
in_flight_total = in_flight_total.wrapping_add(shard.in_flight.load(Ordering::Relaxed));
resp_bytes_total =
resp_bytes_total.wrapping_add(shard.response_bytes_total.load(Ordering::Relaxed));
for idx in 0..12 {
bucket_totals[idx] = bucket_totals[idx]
.wrapping_add(shard.duration_buckets[idx].load(Ordering::Relaxed));
}
dur_count_total =
dur_count_total.wrapping_add(shard.duration_count.load(Ordering::Relaxed));
dur_nanos_total = dur_nanos_total
.wrapping_add(u128::from(shard.duration_nanos_sum.load(Ordering::Relaxed)));
}
let dur_sum_secs: f64 = ((dur_nanos_total as f64) / NANOS_PER_SEC_F64)
+ f64::from_bits(inner.duration_extra_sum_bits.load(Ordering::Relaxed));
out.push_str(&inner.prom_req_header);
for (line_prefix, count) in inner.prom_req_lines.iter().zip(status_totals.iter()) {
out.push_str(line_prefix);
push_u64_nl(*count, &mut out);
}
out.push_str(&inner.prom_in_flight_prefix);
push_i64_nl(in_flight_total, &mut out);
out.push_str(&inner.prom_resp_bytes_prefix);
push_u64_nl(resp_bytes_total, &mut out);
out.push_str(&inner.prom_dur_header);
let mut cumulative: u64 = 0;
let mut num_buf: [u8; INT_STACK_BUF_LEN] = [0u8; INT_STACK_BUF_LEN];
let mut num_start: usize = INT_STACK_BUF_LEN;
let mut formatted_val: u64 = 0;
for (bucket_prefix, bucket_count) in inner
.prom_dur_bucket_prefixes
.iter()
.zip(bucket_totals.iter())
{
cumulative = cumulative.wrapping_add(*bucket_count);
out.push_str(bucket_prefix);
if cumulative < 100 {
out.push_str(PROM_DEC_0_99_NL[cumulative as usize]);
} else {
if cumulative != formatted_val {
num_start = format_u64_nl_into(cumulative, &mut num_buf);
formatted_val = cumulative;
}
if let Ok(text) = from_utf8(&num_buf[num_start..]) {
out.push_str(text);
}
}
}
out.push_str(&inner.prom_dur_inf_prefix);
if dur_count_total < 100 {
let total_str: &str = PROM_DEC_0_99_NL[dur_count_total as usize];
out.push_str(total_str);
out.push_str(&inner.prom_dur_sum_prefix);
push_f64_nl(dur_sum_secs, &mut out);
out.push_str(&inner.prom_dur_count_prefix);
out.push_str(total_str);
} else {
if dur_count_total != formatted_val {
num_start = format_u64_nl_into(dur_count_total, &mut num_buf);
}
if let Ok(text) = from_utf8(&num_buf[num_start..]) {
out.push_str(text);
out.push_str(&inner.prom_dur_sum_prefix);
push_f64_nl(dur_sum_secs, &mut out);
out.push_str(&inner.prom_dur_count_prefix);
out.push_str(text);
} else {
out.push_str(&inner.prom_dur_sum_prefix);
push_f64_nl(dur_sum_secs, &mut out);
out.push_str(&inner.prom_dur_count_prefix);
}
}
if inner.custom_counter_count.load(Ordering::Acquire) != 0
&& let Ok(counters) = inner.custom_counters.read()
{
for entry in counters.values() {
out.push_str(&entry.prom_prefix);
push_u64_nl(entry.metric.get(), &mut out);
}
}
if inner.custom_gauge_count.load(Ordering::Acquire) != 0
&& let Ok(gauges) = inner.custom_gauges.read()
{
for entry in gauges.values() {
out.push_str(&entry.prom_prefix);
push_i64_nl(entry.metric.get(), &mut out);
}
}
if inner.custom_histogram_count.load(Ordering::Acquire) != 0
&& let Ok(histograms) = inner.custom_histograms.read()
{
for entry in histograms.values() {
entry.metric.write_prometheus_preformatted(
&entry.prom_header,
&entry.prom_bucket_prefixes,
&entry.prom_inf_prefix,
&entry.prom_sum_prefix,
&entry.prom_count_prefix,
&mut out,
);
}
}
out
}
}
impl MetricsPlugin {
pub fn init(config: MetricsConfig) -> &'static Self {
let registry: MetricsRegistry = MetricsRegistry::new(config.get_namespace().clone());
Self::init_with_registry(config, registry)
}
pub fn init_with_registry(config: MetricsConfig, registry: MetricsRegistry) -> &'static Self {
METRICS_PLUGIN.get_or_init(|| Self { config, registry })
}
#[inline(always)]
pub fn get() -> Option<&'static Self> {
METRICS_PLUGIN.get()
}
#[inline(always)]
pub fn get_config(&self) -> &MetricsConfig {
&self.config
}
#[inline(always)]
pub fn get_registry(&self) -> &MetricsRegistry {
&self.registry
}
}
impl ServerHook for MetricsRequestHook {
#[inline(always)]
async fn new(_: &mut Stream, _: &mut Context) -> Self {
Self
}
#[inline(always)]
fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option<Status> {
let Some(plugin) = MetricsPlugin::get() else {
return Some(Status::Continue);
};
if ctx.get_request().get_path() == plugin.get_config().get_endpoint() {
return None;
}
plugin.get_registry().record_request_start();
put_metrics_started_at(ctx, Instant::now());
Some(Status::Continue)
}
async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
let Some(plugin) = MetricsPlugin::get() else {
return Status::Continue;
};
let config: &MetricsConfig = plugin.get_config();
if ctx.get_request().get_path() == config.get_endpoint() {
if !is_scrape_authorized(ctx, config.get_bearer_token_ref()) {
ctx.get_mut_response()
.set_status_code(HttpStatus::Unauthorized.code())
.set_body(&[] as &[u8]);
} else {
let body: Vec<u8> = if ctx.get_request().get_method().is_head() {
Vec::new()
} else {
plugin.get_registry().render_prometheus().into_bytes()
};
ctx.get_mut_response()
.set_status_code(HttpStatus::Ok.code())
.set_header(CONTENT_TYPE, PROMETHEUS_CONTENT_TYPE)
.set_header(CACHE_CONTROL, CACHE_CONTROL_NO_STORE)
.set_body(body);
}
let _: Result<(), ResponseError> = ctx.try_send_response(stream).await;
return Status::Reject;
}
plugin.get_registry().record_request_start();
put_metrics_started_at(ctx, Instant::now());
Status::Continue
}
}
impl ServerHook for MetricsResponseHook {
#[inline(always)]
async fn new(_: &mut Stream, _: &mut Context) -> Self {
Self
}
#[inline(always)]
fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option<Status> {
let Some(plugin) = MetricsPlugin::get() else {
return Some(Status::Continue);
};
let Some(started_at) = get_metrics_started_at(ctx) else {
return Some(Status::Continue);
};
let status: usize = ctx.get_response().get_status_code();
let bytes: usize = ctx.get_response().get_body().len();
let duration_ns: u64 = started_at.elapsed().as_nanos().min(u64::MAX as u128) as u64;
plugin
.get_registry()
.record_request_finish_nanos(status, bytes, duration_ns);
Some(Status::Continue)
}
async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
Self::try_handle_sync(stream, ctx).unwrap_or(Status::Continue)
}
}