use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
use std::time::{Duration, SystemTime};
use futures_core::Stream;
use serde::Serialize;
use super::Store;
use super::run;
use crate::cancel::{self, Captured};
use crate::pool::Pool;
use crate::sync::lock;
use crate::{ErrorKind, Result};
pub use crate::records::{
Aggregate, Damage, Event, FieldInfo, Fields, Kind, Level, NameCount, NewEvent, Number, PAGE_EVENTS, Page, Part,
PollBatch, Row, SpanId, Stats, StreamFields, StreamInfo, TailBatch, Top, TraceId,
};
impl Store {
pub fn logger(&self, stream: &str) -> crate::records::LoggerBuilder<'_> {
self.blocking().logger(stream)
}
pub fn events(&self, stream: &str) -> EventsBuilder<'_> {
EventsBuilder { builder: self.blocking().events(stream), pool: self.pool() }
}
pub fn all_events(&self) -> Result<AllEvents> {
Ok(AllEvents { all: self.blocking().all_events()?, pool: Arc::clone(self.pool()) })
}
}
#[derive(Debug)]
pub struct EventsBuilder<'s> {
builder: crate::records::EventsBuilder<'s>,
pool: &'s Arc<Pool>,
}
impl<'s> EventsBuilder<'s> {
#[cfg(feature = "sql")]
pub(crate) fn new(builder: crate::records::EventsBuilder<'s>, pool: &'s Arc<Pool>) -> Self {
EventsBuilder { builder, pool }
}
pub fn keep(mut self, keep: Duration) -> Self {
self.builder = self.builder.keep(keep);
self
}
pub fn open(self) -> Result<Events> {
Ok(Events { events: self.builder.open()?, pool: Arc::clone(self.pool) })
}
}
#[derive(Clone)]
pub struct Events {
events: crate::records::Events,
pool: Arc<Pool>,
}
impl fmt::Debug for Events {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.events, f)
}
}
impl From<crate::records::Events> for Events {
fn from(events: crate::records::Events) -> Events {
let pool = events.store().map_or_else(Pool::stopped, |store| Pool::of_or_stopped(&store));
Events { events, pool }
}
}
impl Events {
pub fn blocking(&self) -> &crate::records::Events {
&self.events
}
pub fn append(&self, name: &str, fields: &impl Serialize) -> impl Future<Output = Result<bool>> + Send + 'static {
one(self.append_all([NewEvent::new(name).fields(fields)]))
}
pub fn event(&self, name: &str) -> EventCall<'_> {
EventCall { events: self, event: NewEvent::new(name) }
}
pub fn append_all(
&self,
events: impl IntoIterator<Item = NewEvent>,
) -> impl Future<Output = Result<usize>> + Send + 'static {
let (handle, events) = (self.events.clone(), events.into_iter().collect::<Vec<_>>());
let what = format!("events {}: an append", self.events.name());
run::write(&self.pool, what, move |answer| handle.append_then(events, move |appended| answer.send(appended)))
}
pub fn list(&self) -> List {
let named = format!("events {}", self.events.name());
List { list: self.events.list(), pool: Arc::clone(&self.pool), named: Arc::from(named) }
}
pub fn lines(&self) -> Result<Lines> {
let named = format!("lines of events {}", self.events.name());
Ok(Lines { lines: self.events.lines()?, pool: Arc::clone(&self.pool), named })
}
}
#[derive(Debug)]
pub struct EventCall<'e> {
events: &'e Events,
event: NewEvent,
}
impl<'e> EventCall<'e> {
pub fn id(mut self, id: impl AsRef<str>) -> Self {
self.event = self.event.id(id);
self
}
pub fn at(mut self, at: SystemTime) -> Self {
self.event = self.event.at(at);
self
}
pub fn level(mut self, level: Level) -> Self {
self.event = self.event.level(level);
self
}
pub fn message(mut self, message: &str) -> Self {
self.event = self.event.message(message);
self
}
pub fn context(mut self, context: &impl Serialize) -> Self {
self.event = self.event.context(context);
self
}
pub fn trace(mut self, trace_id: TraceId, span_id: SpanId) -> Self {
self.event = self.event.trace(trace_id, span_id);
self
}
pub fn append(self, fields: &impl Serialize) -> impl Future<Output = Result<bool>> + Send + 'static {
one(self.events.append_all([self.event.fields(fields)]))
}
#[cfg(feature = "sql")]
pub(crate) fn into_blocking(self) -> crate::records::EventCall<'e> {
self.events.events.call(self.event)
}
}
#[cfg(feature = "sql")]
impl crate::transaction::sealed::Sealed for Events {}
#[cfg(feature = "sql")]
impl crate::TxHandle for Events {
type InTx<'t> = crate::records::TxEvents<'t>;
fn in_tx<'t>(&'t self, tx: &'t crate::Transaction<'t>) -> crate::records::TxEvents<'t> {
crate::TxHandle::in_tx(&self.events, tx)
}
}
async fn one(appended: impl Future<Output = Result<usize>>) -> Result<bool> {
appended.await.map(|written| written == 1)
}
#[derive(Clone)]
pub struct AllEvents {
all: crate::records::AllEvents,
pool: Arc<Pool>,
}
impl fmt::Debug for AllEvents {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.all, f)
}
}
impl From<crate::records::AllEvents> for AllEvents {
fn from(all: crate::records::AllEvents) -> AllEvents {
let pool = all.store().map_or_else(Pool::stopped, |store| Pool::of_or_stopped(&store));
AllEvents { all, pool }
}
}
impl AllEvents {
pub fn blocking(&self) -> &crate::records::AllEvents {
&self.all
}
pub fn list(&self) -> List {
List { list: self.all.list(), pool: Arc::clone(&self.pool), named: Arc::from("events") }
}
pub fn streams(&self) -> impl Future<Output = Result<Vec<StreamInfo>>> + Send + 'static {
let all = self.all.clone();
run::read(&self.pool, "events: the streams".to_owned(), move || all.streams())
}
pub fn fields(&self, stream: &str) -> impl Future<Output = Result<StreamFields>> + Send + 'static {
let (all, stream) = (self.all.clone(), stream.to_owned());
run::read(&self.pool, "events: a stream's fields".to_owned(), move || all.fields(&stream))
}
pub fn poll(&self, cursor: Option<&str>) -> impl Future<Output = Result<PollBatch>> + Send + 'static {
let (all, cursor) = (self.all.clone(), cursor.map(str::to_owned));
run::read(&self.pool, "events: a poll".to_owned(), move || all.poll(cursor.as_deref()))
}
pub fn poll_limit(
&self,
cursor: Option<&str>,
limit: usize,
) -> impl Future<Output = Result<PollBatch>> + Send + 'static {
let (all, cursor) = (self.all.clone(), cursor.map(str::to_owned));
run::read(&self.pool, "events: a poll".to_owned(), move || all.poll_limit(cursor.as_deref(), limit))
}
pub fn damaged(&self) -> impl Future<Output = Result<Vec<Damage>>> + Send + 'static {
let all = self.all.clone();
run::read(&self.pool, "events: what is damaged".to_owned(), move || all.damaged())
}
pub fn drop(&self, damage: &Damage) -> impl Future<Output = Result<()>> + Send + 'static {
let (all, damage) = (self.all.clone(), damage.clone());
run::blocking(&self.pool, None, format!("events: a drop of {damage}"), move || all.drop(&damage))
}
}
#[derive(Clone)]
pub struct List {
list: crate::records::List,
pool: Arc<Pool>,
named: Arc<str>,
}
impl fmt::Debug for List {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.list, f)
}
}
impl List {
pub fn since(self, span: Duration) -> Self {
self.with(|list| list.since(span))
}
pub fn from(self, at: SystemTime) -> Self {
self.with(|list| list.from(at))
}
pub fn to(self, at: SystemTime) -> Self {
self.with(|list| list.to(at))
}
pub fn streams<S: Into<String>>(self, streams: impl IntoIterator<Item = S>) -> Self {
self.with(|list| list.streams(streams))
}
pub fn names<S: Into<String>>(self, names: impl IntoIterator<Item = S>) -> Self {
self.with(|list| list.names(names))
}
pub fn min_level(self, level: Level) -> Self {
self.with(|list| list.min_level(level))
}
pub fn trace_id(self, trace_id: TraceId) -> Self {
self.with(|list| list.trace_id(trace_id))
}
pub fn filter(self, key: &str, value: &impl Serialize) -> Self {
self.with(|list| list.filter(key, value))
}
pub fn search(self, text: &str) -> Self {
self.with(|list| list.search(text))
}
pub fn newest(self) -> Self {
self.with(crate::records::List::newest)
}
pub fn limit(self, events: usize) -> Self {
self.with(|list| list.limit(events))
}
pub fn after(self, next: &str) -> Self {
self.with(|list| list.after(next))
}
fn with(mut self, narrow: impl FnOnce(crate::records::List) -> crate::records::List) -> Self {
self.list = narrow(self.list);
self
}
pub fn page(&self) -> impl Future<Output = Result<Page>> + Send + 'static {
let list = self.list.clone();
run::read(&self.pool, format!("{}: a page", self.named), move || list.page())
}
pub fn field_names(&self) -> impl Future<Output = Result<Vec<String>>> + Send + 'static {
self.field_names_prefix("")
}
pub fn field_names_prefix(&self, prefix: &str) -> impl Future<Output = Result<Vec<String>>> + Send + 'static {
let (list, prefix) = (self.list.clone(), prefix.to_owned());
run::read(&self.pool, format!("{}: its field names", self.named), move || list.field_names_prefix(&prefix))
}
pub fn count(&self) -> impl Future<Output = Result<u64>> + Send + 'static {
let list = self.list.clone();
run::read(&self.pool, format!("{}: a count", self.named), move || list.count())
}
pub fn top(&self, key: &str) -> impl Future<Output = Result<Vec<Top>>> + Send + 'static {
let (list, key) = (self.list.clone(), key.to_owned());
run::read(&self.pool, format!("{}: a top of {key}", self.named), move || list.top(&key))
}
pub fn aggregate(&self, aggregate: &Aggregate) -> impl Future<Output = Result<Vec<Row>>> + Send + 'static {
let (list, aggregate) = (self.list.clone(), aggregate.clone());
run::read(&self.pool, format!("{}: an aggregate", self.named), move || list.aggregate(&aggregate))
}
pub fn tail(&self) -> Result<Tail> {
Ok(Tail::waking(self.list.tail()?))
}
pub fn all(self) -> All {
let List { list, pool, named } = self;
All {
walk: Some(list.all()),
page: Vec::new().into_iter(),
reading: None,
pool,
named,
tokens: cancel::captured(),
}
}
}
type Read = Pin<Box<dyn Future<Output = Result<(crate::records::All, Option<Result<Vec<Event>>>)>> + Send>>;
pub struct All {
walk: Option<crate::records::All>,
page: std::vec::IntoIter<Event>,
reading: Option<Read>,
pool: Arc<Pool>,
named: Arc<str>,
tokens: Captured,
}
impl fmt::Debug for All {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("All").field("read", &self.named).field("reading", &self.reading.is_some()).finish()
}
}
impl Stream for All {
type Item = Result<Event>;
fn poll_next(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let all = self.get_mut();
loop {
if let Some(event) = all.page.next() {
return Poll::Ready(Some(Ok(event)));
}
if let Some(reading) = &mut all.reading {
let read = std::task::ready!(reading.as_mut().poll(context));
all.reading = None;
match read {
Ok((walk, Some(Ok(events)))) => (all.walk, all.page) = (Some(walk), events.into_iter()),
Ok((_, Some(Err(error)))) | Err(error) => return Poll::Ready(Some(Err(error))),
Ok((_, None)) => return Poll::Ready(None),
}
continue;
}
let Some(mut walk) = all.walk.take() else { return Poll::Ready(None) };
let tokens = all.tokens.clone();
let next = move || {
let page = tokens.run(None, || walk.page());
Ok((walk, page))
};
all.reading = Some(Box::pin(run::read(&all.pool, format!("{}: a page of all", all.named), next)));
}
}
}
pub struct Tail {
tail: crate::records::Tail,
waker: Arc<Mutex<Option<std::task::Waker>>>,
ended: bool,
}
impl fmt::Debug for Tail {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.tail, f)
}
}
impl Tail {
fn waking(tail: crate::records::Tail) -> Tail {
let waker: Arc<Mutex<Option<std::task::Waker>>> = Arc::default();
let woken = Arc::clone(&waker);
tail.wake_with(Arc::new(move || {
let waker = lock(&woken).clone();
if let Some(waker) = waker {
waker.wake();
}
}));
Tail { tail, waker, ended: false }
}
}
impl Stream for Tail {
type Item = Result<TailBatch>;
fn poll_next(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let tail = self.get_mut();
if tail.ended {
return Poll::Ready(None);
}
let mut waker = lock(&tail.waker);
if !waker.as_ref().is_some_and(|kept| kept.will_wake(context.waker())) {
*waker = Some(context.waker().clone());
}
drop(waker);
match tail.tail.next_within(Duration::ZERO) {
Ok(Some(batch)) => Poll::Ready(Some(Ok(batch))),
Ok(None) => Poll::Pending,
Err(error) if error.kind() == ErrorKind::Closed => {
tail.ended = true;
Poll::Ready(None)
}
Err(error) => Poll::Ready(Some(Err(error))),
}
}
}
pub struct Lines {
lines: crate::records::Lines,
pool: Arc<Pool>,
named: String,
}
impl fmt::Debug for Lines {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.lines, f)
}
}
impl Lines {
pub fn write(&mut self, bytes: &[u8]) -> Result<()> {
self.lines.take(bytes)
}
pub fn flush(&mut self) -> impl Future<Output = Result<()>> + Send + 'static {
run::blocking(&self.pool, None, format!("{}: a flush", self.named), self.lines.flushing())
}
pub fn dropped(&self) -> u64 {
self.lines.dropped()
}
}
#[cfg(test)]
#[path = "records_tests.rs"]
mod tests;