Skip to main content

base/interface/model/
metering.rs

1//! A call's stream with its usage counted once: into the node its
2//! [`UsageTap`] is charged to, and to whatever else the layer that routed the
3//! call keeps (a provider's quota). Counted at [`ModelEvent::EndTurn`], or,
4//! for a call that broke off, failed or was dropped before it, when the
5//! stream goes, with what the client reported so far. The two metering points
6//! — the provider router and the wrapper over a model nothing routes — both
7//! count through this, so a call is counted the same way wherever it went.
8
9use futures::StreamExt;
10
11use super::{ModelError, ModelEvent, ModelStream, Usage};
12use std::sync::{Arc, Mutex};
13
14/// Usage a client has learned of a call so far — the input side, which an
15/// Anthropic stream reports when it opens — and the node the call is charged
16/// to. [`ModelEvent::EndTurn`]'s usage supersedes what was reported.
17/// Reporting to a tap nobody made does nothing.
18///
19/// The charge is counted once, by whoever routes the call, through
20/// [`UsageTap::metered`]: everything above the client only says where it
21/// goes.
22#[derive(Clone, Default)]
23pub struct UsageTap {
24    reported: Option<Arc<Mutex<Option<Usage>>>>,
25    charge: Option<Arc<crate::interface::budget_policy::SpendNode>>,
26    tally: Option<Arc<crate::interface::budget_policy::SpendNode>>,
27}
28
29impl UsageTap {
30    pub fn new() -> Self {
31        Self {
32            reported: Some(Arc::default()),
33            charge: None,
34            tally: None,
35        }
36    }
37
38    /// A tap whose call is charged to `node`.
39    pub fn charging(node: Arc<crate::interface::budget_policy::SpendNode>) -> Self {
40        Self {
41            reported: None,
42            charge: Some(node),
43            tally: None,
44        }
45    }
46
47    /// The call also counted into `node`, which nothing judges: whoever made
48    /// the call reads there what it spent, a call that broke off included.
49    pub fn tallied_in(mut self, node: Arc<crate::interface::budget_policy::SpendNode>) -> Self {
50        self.tally = Some(node);
51        self
52    }
53
54    /// A fresh tap for one attempt at the call, charged where this one is.
55    pub fn for_attempt(&self) -> Self {
56        Self {
57            charge: self.charge.clone(),
58            tally: self.tally.clone(),
59            ..Self::new()
60        }
61    }
62
63    pub fn charge(&self) -> Option<&Arc<crate::interface::budget_policy::SpendNode>> {
64        self.charge.as_ref()
65    }
66
67    pub fn report(&self, usage: Usage) {
68        if let Some(slot) = &self.reported {
69            *slot.lock().unwrap_or_else(|e| e.into_inner()) = Some(usage);
70        }
71    }
72
73    pub fn reported(&self) -> Option<Usage> {
74        self.reported
75            .as_ref()
76            .and_then(|slot| *slot.lock().unwrap_or_else(|e| e.into_inner()))
77    }
78}
79
80impl std::fmt::Debug for UsageTap {
81    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82        f.debug_struct("UsageTap")
83            .field("reported", &self.reported())
84            .field("charged", &self.charge.is_some())
85            .finish()
86    }
87}
88
89/// Told what a metered call used, once.
90pub type OnSpent = Box<dyn FnOnce(Usage) + Send>;
91
92impl UsageTap {
93    /// `stream`, its usage counted once into the node this tap is charged to
94    /// and to `also`.
95    pub fn metered(self, stream: ModelStream, also: Option<OnSpent>) -> ModelStream {
96        if also.is_none() && self.charge.is_none() && self.tally.is_none() {
97            return stream;
98        }
99        Box::new(Metering {
100            inner: stream,
101            tap: self,
102            also,
103            counted: false,
104        })
105    }
106}
107
108struct Metering {
109    inner: ModelStream,
110    tap: UsageTap,
111    also: Option<OnSpent>,
112    counted: bool,
113}
114
115impl Metering {
116    fn count_once(&mut self, usage: Usage) {
117        if std::mem::replace(&mut self.counted, true) {
118            return;
119        }
120        if let Some(also) = self.also.take() {
121            also(usage);
122        }
123        if let Some(node) = self.tap.charge() {
124            node.add(usage);
125        }
126        if let Some(node) = &self.tap.tally {
127            node.add(usage);
128        }
129    }
130}
131
132impl futures::Stream for Metering {
133    type Item = Result<ModelEvent, ModelError>;
134
135    fn poll_next(
136        mut self: std::pin::Pin<&mut Self>,
137        cx: &mut std::task::Context<'_>,
138    ) -> std::task::Poll<Option<Self::Item>> {
139        let polled = self.inner.poll_next_unpin(cx);
140        if let std::task::Poll::Ready(Some(Ok(ModelEvent::EndTurn { usage, .. }))) = &polled {
141            let usage = *usage;
142            self.count_once(usage);
143        }
144        polled
145    }
146}
147
148impl Drop for Metering {
149    fn drop(&mut self) {
150        if let Some(usage) = self.tap.reported() {
151            self.count_once(usage);
152        }
153    }
154}