use futures::StreamExt;
use super::{ModelError, ModelEvent, ModelStream, Usage};
use std::sync::{Arc, Mutex};
#[derive(Clone, Default)]
pub struct UsageTap {
reported: Option<Arc<Mutex<Option<Usage>>>>,
charge: Option<Arc<crate::interface::budget_policy::SpendNode>>,
tally: Option<Arc<crate::interface::budget_policy::SpendNode>>,
}
impl UsageTap {
pub fn new() -> Self {
Self {
reported: Some(Arc::default()),
charge: None,
tally: None,
}
}
pub fn charging(node: Arc<crate::interface::budget_policy::SpendNode>) -> Self {
Self {
reported: None,
charge: Some(node),
tally: None,
}
}
pub fn tallied_in(mut self, node: Arc<crate::interface::budget_policy::SpendNode>) -> Self {
self.tally = Some(node);
self
}
pub fn for_attempt(&self) -> Self {
Self {
charge: self.charge.clone(),
tally: self.tally.clone(),
..Self::new()
}
}
pub fn charge(&self) -> Option<&Arc<crate::interface::budget_policy::SpendNode>> {
self.charge.as_ref()
}
pub fn report(&self, usage: Usage) {
if let Some(slot) = &self.reported {
*slot.lock().unwrap_or_else(|e| e.into_inner()) = Some(usage);
}
}
pub fn reported(&self) -> Option<Usage> {
self.reported
.as_ref()
.and_then(|slot| *slot.lock().unwrap_or_else(|e| e.into_inner()))
}
}
impl std::fmt::Debug for UsageTap {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("UsageTap")
.field("reported", &self.reported())
.field("charged", &self.charge.is_some())
.finish()
}
}
pub type OnSpent = Box<dyn FnOnce(Usage) + Send>;
impl UsageTap {
pub fn metered(self, stream: ModelStream, also: Option<OnSpent>) -> ModelStream {
if also.is_none() && self.charge.is_none() && self.tally.is_none() {
return stream;
}
Box::new(Metering {
inner: stream,
tap: self,
also,
counted: false,
})
}
}
struct Metering {
inner: ModelStream,
tap: UsageTap,
also: Option<OnSpent>,
counted: bool,
}
impl Metering {
fn count_once(&mut self, usage: Usage) {
if std::mem::replace(&mut self.counted, true) {
return;
}
if let Some(also) = self.also.take() {
also(usage);
}
if let Some(node) = self.tap.charge() {
node.add(usage);
}
if let Some(node) = &self.tap.tally {
node.add(usage);
}
}
}
impl futures::Stream for Metering {
type Item = Result<ModelEvent, ModelError>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
let polled = self.inner.poll_next_unpin(cx);
if let std::task::Poll::Ready(Some(Ok(ModelEvent::EndTurn { usage, .. }))) = &polled {
let usage = *usage;
self.count_once(usage);
}
polled
}
}
impl Drop for Metering {
fn drop(&mut self) {
if let Some(usage) = self.tap.reported() {
self.count_once(usage);
}
}
}