Drain all accumulated counters for flushing to the store. Returns aggregated events and resets counters to zero.
(&self)
| 80 | /// Drain all accumulated counters for flushing to the store. |
| 81 | /// Returns aggregated events and resets counters to zero. |
| 82 | pub fn drain(&self) -> Vec<UsageEvent> { |
| 83 | let now = std::time::SystemTime::now() |
| 84 | .duration_since(std::time::UNIX_EPOCH) |
| 85 | .unwrap_or_default() |
| 86 | .as_secs(); |
| 87 | |
| 88 | let buckets = self.buckets.read().unwrap_or_else(|p| p.into_inner()); |
| 89 | let mut events = Vec::with_capacity(buckets.len()); |
| 90 | |
| 91 | for (key, counter) in buckets.iter() { |
| 92 | let tokens = counter.swap(0, Ordering::Relaxed); |
| 93 | if tokens > 0 { |
| 94 | events.push(UsageEvent { |
| 95 | auth_user_id: key.auth_user_id.clone(), |
| 96 | org_id: key.org_id.clone(), |
| 97 | tenant_id: key.tenant_id, |
| 98 | collection: key.collection.clone(), |
| 99 | engine: key.engine.clone(), |
| 100 | operation: key.operation.clone(), |
| 101 | tokens, |
| 102 | timestamp_secs: now, |
| 103 | }); |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | self.total_tokens.store(0, Ordering::Relaxed); |
| 108 | events |
| 109 | } |
| 110 | |
| 111 | /// Total tokens metered since last flush. |
| 112 | pub fn total_tokens(&self) -> u64 { |