base/interface/model/
metering.rs1use futures::StreamExt;
10
11use super::{ModelError, ModelEvent, ModelStream, Usage};
12use std::sync::{Arc, Mutex};
13
14#[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 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 pub fn tallied_in(mut self, node: Arc<crate::interface::budget_policy::SpendNode>) -> Self {
50 self.tally = Some(node);
51 self
52 }
53
54 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
89pub type OnSpent = Box<dyn FnOnce(Usage) + Send>;
91
92impl UsageTap {
93 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}