use std::fmt;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use async_trait::async_trait;
use serde::Serialize;
use tokio::sync::Notify;
use super::LogRecord;
use crate::core::{poll_until, Error, PollOptions, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SortOrder {
#[default]
Desc,
Asc,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchOptions {
pub start: Option<SystemTime>,
pub end: Option<SystemTime>,
pub limit: usize,
pub order: SortOrder,
pub cursor: Option<String>,
}
impl Default for SearchOptions {
fn default() -> Self {
SearchOptions {
start: None,
end: None,
limit: 100,
order: SortOrder::Desc,
cursor: None,
}
}
}
impl SearchOptions {
pub fn limit(mut self, limit: usize) -> Self {
self.limit = limit;
self
}
pub fn range(mut self, start: Option<SystemTime>, end: Option<SystemTime>) -> Self {
self.start = start;
self.end = end;
self
}
pub fn order(mut self, order: SortOrder) -> Self {
self.order = order;
self
}
pub fn cursor(mut self, cursor: impl Into<String>) -> Self {
self.cursor = Some(cursor.into());
self
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LogSearchResult {
pub records: Vec<LogRecord>,
#[serde(skip_serializing_if = "Option::is_none")]
pub next_cursor: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub total: Option<u64>,
}
pub type RecordCallback = Arc<dyn Fn(LogRecord) + Send + Sync>;
pub type RecordPredicate = Arc<dyn Fn(&LogRecord) -> bool + Send + Sync>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TailOptions {
pub interval: Duration,
pub start: Option<SystemTime>,
}
impl Default for TailOptions {
fn default() -> Self {
TailOptions {
interval: TailOptions::DEFAULT_INTERVAL,
start: None,
}
}
}
impl TailOptions {
pub const DEFAULT_INTERVAL: Duration = Duration::from_secs(1);
pub fn interval_or(&self, service_default: Duration) -> Duration {
if self.interval.is_zero() || self.interval == Self::DEFAULT_INTERVAL {
service_default
} else {
self.interval
}
}
}
#[derive(Clone)]
pub struct TailHandle {
stopped: Arc<AtomicBool>,
notify: Arc<Notify>,
}
impl fmt::Debug for TailHandle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TailHandle")
.field("stopped", &self.is_stopped())
.finish()
}
}
impl Default for TailHandle {
fn default() -> Self {
Self::new()
}
}
impl TailHandle {
pub fn new() -> Self {
TailHandle {
stopped: Arc::new(AtomicBool::new(false)),
notify: Arc::new(Notify::new()),
}
}
pub fn stop(&self) {
self.stopped.store(true, Ordering::SeqCst);
self.notify.notify_waiters();
}
pub fn is_stopped(&self) -> bool {
self.stopped.load(Ordering::SeqCst)
}
pub async fn stopped(&self) {
loop {
let notified = self.notify.notified();
tokio::pin!(notified);
notified.as_mut().enable();
if self.is_stopped() {
return;
}
notified.await;
}
}
}
#[derive(Clone)]
pub struct WaitOptions {
pub timeout: Duration,
pub interval: Duration,
pub predicate: Option<RecordPredicate>,
}
impl Default for WaitOptions {
fn default() -> Self {
WaitOptions {
timeout: Duration::from_secs(30),
interval: Duration::from_secs(1),
predicate: None,
}
}
}
impl fmt::Debug for WaitOptions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WaitOptions")
.field("timeout", &self.timeout)
.field("interval", &self.interval)
.field("predicate", &self.predicate.is_some())
.finish()
}
}
impl WaitOptions {
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 predicate(mut self, f: impl Fn(&LogRecord) -> bool + Send + Sync + 'static) -> Self {
self.predicate = Some(Arc::new(f));
self
}
}
#[async_trait]
pub trait LogQueryClient: Send + Sync {
async fn search(&self, query: &str, opts: SearchOptions) -> Result<LogSearchResult>;
async fn tail(
&self,
query: &str,
on_record: RecordCallback,
opts: TailOptions,
) -> Result<TailHandle> {
let _ = (query, on_record, opts);
Err(Error::unsupported(
"logs.tail: not supported by this service",
))
}
async fn list_streams(&self) -> Result<Vec<String>> {
Err(Error::unsupported(
"logs.listStreams: not supported by this service",
))
}
async fn list_labels(&self) -> Result<Vec<String>> {
Err(Error::unsupported(
"logs.listLabels: not supported by this service",
))
}
async fn wait_for_log(&self, query: &str, opts: WaitOptions) -> Result<LogRecord> {
wait_for_log(self, query, opts).await
}
}
pub async fn wait_for_log<C>(client: &C, query: &str, opts: WaitOptions) -> Result<LogRecord>
where
C: LogQueryClient + ?Sized,
{
let predicate = opts.predicate.clone();
let poll = PollOptions {
timeout: opts.timeout,
interval: opts.interval,
};
poll_until("logs.waitForLog", poll, || async {
let page = client.search(query, SearchOptions::default()).await?;
Ok(page
.records
.into_iter()
.find(|r| predicate.as_ref().is_none_or(|p| p(r))))
})
.await
}
pub fn poll_tail(
client: Arc<dyn LogQueryClient>,
query: &str,
on_record: RecordCallback,
opts: TailOptions,
) -> TailHandle {
let handle = TailHandle::new();
let h = handle.clone();
let query = query.to_string();
tokio::spawn(async move {
let mut since = opts.start.unwrap_or_else(SystemTime::now);
let mut seen_at_since: Vec<String> = Vec::new();
while !h.is_stopped() {
let search = SearchOptions::default()
.range(Some(since), None)
.order(SortOrder::Asc)
.limit(1000);
let page = tokio::select! {
_ = h.stopped() => break,
page = client.search(&query, search) => page,
};
if let Ok(page) = page {
for r in page.records {
if h.is_stopped() {
break;
}
let key = r.to_json();
if r.timestamp < since || (r.timestamp == since && seen_at_since.contains(&key))
{
continue;
}
if r.timestamp > since {
since = r.timestamp;
seen_at_since.clear();
}
seen_at_since.push(key);
on_record(r);
}
}
tokio::select! {
_ = h.stopped() => break,
_ = tokio::time::sleep(opts.interval) => {}
}
}
});
handle
}