use std::time::{Duration, SystemTime};
use async_trait::async_trait;
use super::{normalize_trace_id, DependencyLink, Trace, TraceSearchQuery, TraceSummary};
use crate::core::{poll_until, Error, PollOptions, Result};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DependencyOptions {
pub start: Option<SystemTime>,
pub end: Option<SystemTime>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WaitForTraceOptions {
pub timeout: Duration,
pub interval: Duration,
pub min_spans: usize,
}
impl Default for WaitForTraceOptions {
fn default() -> Self {
WaitForTraceOptions {
timeout: Duration::from_secs(30),
interval: Duration::from_secs(1),
min_spans: 1,
}
}
}
impl WaitForTraceOptions {
pub fn timeout(mut self, d: Duration) -> Self {
self.timeout = d;
self
}
pub fn interval(mut self, d: Duration) -> Self {
self.interval = d;
self
}
pub fn min_spans(mut self, n: usize) -> Self {
self.min_spans = n;
self
}
}
#[async_trait]
pub trait TraceQueryClient: Send + Sync {
async fn get_trace(&self, trace_id: &str) -> Result<Option<Trace>>;
async fn search_traces(&self, query: &TraceSearchQuery) -> Result<Vec<TraceSummary>>;
async fn list_services(&self) -> Result<Vec<String>>;
async fn list_operations(&self, service: &str) -> Result<Vec<String>>;
async fn get_dependencies(&self, opts: DependencyOptions) -> Result<Vec<DependencyLink>> {
let _ = opts;
Err(Error::unsupported(
"traces.getDependencies: not supported by this service",
))
}
async fn wait_for_trace(&self, trace_id: &str, opts: WaitForTraceOptions) -> Result<Trace> {
wait_for_trace(self, trace_id, opts).await
}
}
pub async fn wait_for_trace<C>(
client: &C,
trace_id: &str,
opts: WaitForTraceOptions,
) -> Result<Trace>
where
C: TraceQueryClient + ?Sized,
{
wait_for_trace_with(client, trace_id, opts, normalize_trace_id).await
}
pub async fn wait_for_trace_with<C, N>(
client: &C,
trace_id: &str,
opts: WaitForTraceOptions,
normalize: N,
) -> Result<Trace>
where
C: TraceQueryClient + ?Sized,
N: Fn(&str) -> Result<String>,
{
let id = normalize(trace_id)?;
let poll = PollOptions {
timeout: opts.timeout,
interval: opts.interval,
};
poll_until("traces.waitForTrace", poll, || async {
Ok(client
.get_trace(&id)
.await?
.filter(|t| t.spans.len() >= opts.min_spans))
})
.await
}