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, UsageTap};
12
13/// Told what a metered call used, once.
14pub type OnSpent = Box<dyn FnOnce(Usage) + Send>;
15
16impl UsageTap {
17    /// `stream`, its usage counted once into the node this tap is charged to
18    /// and to `also`.
19    pub fn metered(self, stream: ModelStream, also: Option<OnSpent>) -> ModelStream {
20        if also.is_none() && self.charge.is_none() {
21            return stream;
22        }
23        Box::new(Metering {
24            inner: stream,
25            tap: self,
26            also,
27            counted: false,
28        })
29    }
30}
31
32struct Metering {
33    inner: ModelStream,
34    tap: UsageTap,
35    also: Option<OnSpent>,
36    counted: bool,
37}
38
39impl Metering {
40    fn count_once(&mut self, usage: Usage) {
41        if std::mem::replace(&mut self.counted, true) {
42            return;
43        }
44        if let Some(also) = self.also.take() {
45            also(usage);
46        }
47        if let Some(node) = self.tap.charge() {
48            node.add(usage);
49        }
50    }
51}
52
53impl futures::Stream for Metering {
54    type Item = Result<ModelEvent, ModelError>;
55
56    fn poll_next(
57        mut self: std::pin::Pin<&mut Self>,
58        cx: &mut std::task::Context<'_>,
59    ) -> std::task::Poll<Option<Self::Item>> {
60        let polled = self.inner.poll_next_unpin(cx);
61        if let std::task::Poll::Ready(Some(Ok(ModelEvent::EndTurn { usage, .. }))) = &polled {
62            let usage = *usage;
63            self.count_once(usage);
64        }
65        polled
66    }
67}
68
69impl Drop for Metering {
70    fn drop(&mut self) {
71        if let Some(usage) = self.tap.reported() {
72            self.count_once(usage);
73        }
74    }
75}