agix-base 0.4.8

Agix — foundation types, traits, and context
Documentation
//! A call's stream with its usage counted once: into the node its
//! [`UsageTap`] is charged to, and to whatever else the layer that routed the
//! call keeps (a provider's quota). Counted at [`ModelEvent::EndTurn`], or,
//! for a call that broke off, failed or was dropped before it, when the
//! stream goes, with what the client reported so far. The two metering points
//! — the provider router and the wrapper over a model nothing routes — both
//! count through this, so a call is counted the same way wherever it went.

use futures::StreamExt;

use super::{ModelError, ModelEvent, ModelStream, Usage};
use std::sync::{Arc, Mutex};

/// Usage a client has learned of a call so far — the input side, which an
/// Anthropic stream reports when it opens — and the node the call is charged
/// to. [`ModelEvent::EndTurn`]'s usage supersedes what was reported.
/// Reporting to a tap nobody made does nothing.
///
/// The charge is counted once, by whoever routes the call, through
/// [`UsageTap::metered`]: everything above the client only says where it
/// goes.
#[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,
        }
    }

    /// A tap whose call is charged to `node`.
    pub fn charging(node: Arc<crate::interface::budget_policy::SpendNode>) -> Self {
        Self {
            reported: None,
            charge: Some(node),
            tally: None,
        }
    }

    /// The call also counted into `node`, which nothing judges: whoever made
    /// the call reads there what it spent, a call that broke off included.
    pub fn tallied_in(mut self, node: Arc<crate::interface::budget_policy::SpendNode>) -> Self {
        self.tally = Some(node);
        self
    }

    /// A fresh tap for one attempt at the call, charged where this one is.
    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()
    }
}

/// Told what a metered call used, once.
pub type OnSpent = Box<dyn FnOnce(Usage) + Send>;

impl UsageTap {
    /// `stream`, its usage counted once into the node this tap is charged to
    /// and to `also`.
    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);
        }
    }
}