Skip to main content

allsource_core/infrastructure/memory/
ledger.rs

1//! Counts resident heap bytes per owner. The ledger counts and never refuses,
2//! reserves or evicts: a charge or release is a plain atomic add.
3//!
4//! Owners are charged where their bytes become resident and released where
5//! they stop being resident. Owner counters change only through this API.
6
7use crate::domain::entities::event::Event;
8use dashmap::DashMap;
9use std::sync::{
10    OnceLock,
11    atomic::{AtomicI64, AtomicU64, AtomicUsize, Ordering},
12};
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum Owner {
16    EventsResident,
17    StoragePending,
18    IndexEntity,
19    IndexType,
20    IndexId,
21    FeedIndex,
22    CacheGenerations,
23    TenantLoader,
24    ReadModels,
25    PipelineWindows,
26    PipelineState,
27    WebhookQueue,
28    Broadcast,
29    ProjectionEventCounters,
30    Query,
31    EntityVersions,
32    VersionIndexTenants,
33    VersionIndexEntities,
34    GeoIndex,
35    SchemaEvolution,
36    ProjectionPermanent,
37    Search,
38    SystemStore,
39    Misc,
40    RateLimiter,
41    Metrics,
42}
43
44impl Owner {
45    pub const COUNT: usize = 26;
46
47    pub const ALL: [Owner; Self::COUNT] = [
48        Owner::EventsResident,
49        Owner::StoragePending,
50        Owner::IndexEntity,
51        Owner::IndexType,
52        Owner::IndexId,
53        Owner::FeedIndex,
54        Owner::CacheGenerations,
55        Owner::TenantLoader,
56        Owner::ReadModels,
57        Owner::PipelineWindows,
58        Owner::PipelineState,
59        Owner::WebhookQueue,
60        Owner::Broadcast,
61        Owner::ProjectionEventCounters,
62        Owner::Query,
63        Owner::EntityVersions,
64        Owner::VersionIndexTenants,
65        Owner::VersionIndexEntities,
66        Owner::GeoIndex,
67        Owner::SchemaEvolution,
68        Owner::ProjectionPermanent,
69        Owner::Search,
70        Owner::SystemStore,
71        Owner::Misc,
72        Owner::RateLimiter,
73        Owner::Metrics,
74    ];
75
76    /// The `owner` label value in the metrics.
77    pub const fn label(self) -> &'static str {
78        match self {
79            Owner::EventsResident => "events.resident",
80            Owner::StoragePending => "storage.pending",
81            Owner::IndexEntity => "index.entity",
82            Owner::IndexType => "index.type",
83            Owner::IndexId => "index.id",
84            Owner::FeedIndex => "feed_index",
85            Owner::CacheGenerations => "cache_generations",
86            Owner::TenantLoader => "tenant_loader",
87            Owner::ReadModels => "read_models",
88            Owner::PipelineWindows => "pipeline.windows",
89            Owner::PipelineState => "pipeline.state",
90            Owner::WebhookQueue => "webhook.queue",
91            Owner::Broadcast => "broadcast",
92            Owner::ProjectionEventCounters => "projection.event_counters",
93            Owner::Query => "query",
94            Owner::EntityVersions => "entity_versions",
95            Owner::VersionIndexTenants => "version_index_tenants",
96            Owner::VersionIndexEntities => "version_index_entities",
97            Owner::GeoIndex => "geo_index",
98            Owner::SchemaEvolution => "schema_evolution",
99            Owner::ProjectionPermanent => "projection.permanent",
100            Owner::Search => "search",
101            Owner::SystemStore => "system_store",
102            Owner::Misc => "misc",
103            Owner::RateLimiter => "rate_limiter",
104            Owner::Metrics => "metrics",
105        }
106    }
107
108    /// Owners whose bytes are never released, summed in
109    /// `allsource_core_permanent_bytes`.
110    pub const fn is_permanent(self) -> bool {
111        matches!(
112            self,
113            Owner::CacheGenerations
114                | Owner::EntityVersions
115                | Owner::VersionIndexTenants
116                | Owner::VersionIndexEntities
117                | Owner::GeoIndex
118                | Owner::SchemaEvolution
119                | Owner::ProjectionPermanent
120                | Owner::Search
121                | Owner::SystemStore
122                | Owner::Misc
123                | Owner::Metrics
124        )
125    }
126}
127
128pub struct ResidentLedger {
129    owners: [AtomicI64; Owner::COUNT],
130    rows_decoded: AtomicU64,
131}
132
133impl ResidentLedger {
134    pub const fn new() -> Self {
135        Self {
136            owners: [const { AtomicI64::new(0) }; Owner::COUNT],
137            rows_decoded: AtomicU64::new(0),
138        }
139    }
140
141    pub fn charge(&self, owner: Owner, bytes: u64) {
142        self.owners[owner as usize].fetch_add(saturating_i64(bytes), Ordering::Relaxed);
143    }
144
145    pub fn release(&self, owner: Owner, bytes: u64) {
146        self.owners[owner as usize].fetch_sub(saturating_i64(bytes), Ordering::Relaxed);
147    }
148
149    /// Charge the growth of a `Vec`-like table from `before` to `after` slots,
150    /// or release a shrink. Each slot is `slot_bytes` wide.
151    pub fn track_capacity(&self, owner: Owner, before: usize, after: usize, slot_bytes: usize) {
152        if after >= before {
153            self.charge(owner, saturating_u64((after - before) * slot_bytes));
154        } else {
155            self.release(owner, saturating_u64((before - after) * slot_bytes));
156        }
157    }
158
159    pub fn record_rows_decoded(&self, rows: u64) {
160        self.rows_decoded.fetch_add(rows, Ordering::Relaxed);
161    }
162
163    pub fn rows_decoded_total(&self) -> u64 {
164        self.rows_decoded.load(Ordering::Relaxed)
165    }
166
167    pub fn owner_bytes(&self, owner: Owner) -> i64 {
168        self.owners[owner as usize].load(Ordering::Relaxed)
169    }
170
171    pub fn total_bytes(&self) -> i64 {
172        self.owners
173            .iter()
174            .map(|owner| owner.load(Ordering::Relaxed))
175            .sum()
176    }
177
178    pub fn permanent_bytes(&self) -> i64 {
179        Owner::ALL
180            .iter()
181            .filter(|owner| owner.is_permanent())
182            .map(|owner| self.owner_bytes(*owner))
183            .sum()
184    }
185}
186
187impl Default for ResidentLedger {
188    fn default() -> Self {
189        Self::new()
190    }
191}
192
193static RESIDENT: ResidentLedger = ResidentLedger::new();
194
195/// The process-wide ledger. Heap is process-wide too, so the unattributed gauge
196/// compares the same scope on both sides.
197pub fn resident() -> &'static ResidentLedger {
198    &RESIDENT
199}
200
201/// The bytes one structure has charged to one owner. Releases never exceed
202/// what this tally holds, and dropping it releases the rest, so an owner that
203/// goes away cannot leave its bytes counted.
204pub struct Tally {
205    owner: Owner,
206    bytes: AtomicU64,
207}
208
209impl Tally {
210    pub const fn new(owner: Owner) -> Self {
211        Self {
212            owner,
213            bytes: AtomicU64::new(0),
214        }
215    }
216
217    pub fn add(&self, bytes: u64) {
218        if bytes == 0 {
219            return;
220        }
221        resident().charge(self.owner, bytes);
222        self.bytes.fetch_add(bytes, Ordering::Relaxed);
223    }
224
225    pub fn sub(&self, bytes: u64) {
226        let held = self
227            .bytes
228            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |held| {
229                Some(held.saturating_sub(bytes))
230            })
231            .unwrap_or(0);
232        let released = held.min(bytes);
233        if released > 0 {
234            resident().release(self.owner, released);
235        }
236    }
237
238    /// Charge the growth of a slot table from `before` to `after` slots, or
239    /// release a shrink. Each slot is `slot_bytes` wide.
240    pub fn grow(&self, before: usize, after: usize, slot_bytes: usize) {
241        let delta = after.abs_diff(before) as u64 * slot_bytes as u64;
242        if after >= before {
243            self.add(delta);
244        } else {
245            self.sub(delta);
246        }
247    }
248
249    /// Charge or release the change of one value's heap from `before` to `after`.
250    pub fn adjust(&self, before: u64, after: u64) {
251        if after >= before {
252            self.add(after - before);
253        } else {
254            self.sub(before - after);
255        }
256    }
257
258    /// Move the held amount to `target`, charging or releasing the difference.
259    pub fn set_to(&self, target: u64) {
260        let held = self.bytes();
261        if target >= held {
262            self.add(target - held);
263        } else {
264            self.sub(held - target);
265        }
266    }
267
268    /// Release the `resident_bytes()` of every event that `matches` selects.
269    pub fn release_matching(&self, events: &[Event], matches: impl Fn(&Event) -> bool) {
270        let released: u64 = events
271            .iter()
272            .filter(|event| matches(event))
273            .map(Event::resident_bytes)
274            .sum();
275        self.sub(released);
276    }
277
278    /// Release everything held and return the released amount.
279    pub fn take(&self) -> u64 {
280        let held = self.bytes.swap(0, Ordering::Relaxed);
281        if held > 0 {
282            resident().release(self.owner, held);
283        }
284        held
285    }
286
287    pub fn bytes(&self) -> u64 {
288        self.bytes.load(Ordering::Relaxed)
289    }
290}
291
292impl Drop for Tally {
293    fn drop(&mut self) {
294        self.take();
295    }
296}
297
298/// The table capacity last charged for each shard of one `DashMap`. A keyed
299/// change re-reads only that key's shard: `DashMap::capacity` takes every
300/// shard lock, one lock pair per shard for each new key on the ingest path.
301pub struct ShardSlots(OnceLock<Box<[AtomicUsize]>>);
302
303impl ShardSlots {
304    pub const fn new() -> Self {
305        Self(OnceLock::new())
306    }
307
308    fn slots<K, V, S>(&self, map: &DashMap<K, V, S>) -> &[AtomicUsize]
309    where
310        K: Eq + std::hash::Hash,
311        S: std::hash::BuildHasher + Clone,
312    {
313        self.0
314            .get_or_init(|| map.shards().iter().map(|_| AtomicUsize::new(0)).collect())
315    }
316
317    /// Charge `table` for the change in the capacity of the shard holding
318    /// `key` since the last read. Call it after the entry guard is dropped.
319    pub fn charge_key<K, Q, V, S>(
320        &self,
321        map: &DashMap<K, V, S>,
322        key: &Q,
323        table: &Tally,
324        slot_bytes: usize,
325    ) where
326        K: Eq + std::hash::Hash + std::borrow::Borrow<Q>,
327        Q: Eq + std::hash::Hash + ?Sized,
328        S: std::hash::BuildHasher + Clone,
329    {
330        self.charge_shard(map, map.determine_map(key), table, slot_bytes);
331    }
332
333    /// Charge `table` for the change in every shard's capacity.
334    pub fn charge_all<K, V, S>(&self, map: &DashMap<K, V, S>, table: &Tally, slot_bytes: usize)
335    where
336        K: Eq + std::hash::Hash,
337        S: std::hash::BuildHasher + Clone,
338    {
339        for shard in 0..map.shards().len() {
340            self.charge_shard(map, shard, table, slot_bytes);
341        }
342    }
343
344    fn charge_shard<K, V, S>(
345        &self,
346        map: &DashMap<K, V, S>,
347        shard: usize,
348        table: &Tally,
349        slot_bytes: usize,
350    ) where
351        K: Eq + std::hash::Hash,
352        S: std::hash::BuildHasher + Clone,
353    {
354        // The read guard spans the swap: a resize needs the write lock, so two
355        // racing charges cannot store an older capacity over a newer one.
356        let guard = map.shards()[shard].read();
357        let now = guard.capacity();
358        let before = self.slots(map)[shard].swap(now, Ordering::Relaxed);
359        drop(guard);
360        table.grow(before, now, slot_bytes);
361    }
362}
363
364impl Default for ShardSlots {
365    fn default() -> Self {
366        Self::new()
367    }
368}
369
370/// Charges a concurrent map's new keys: each key's owned bytes, and the growth
371/// of the map's table. The table stays charged after its entries are removed,
372/// because the map keeps its allocation.
373pub struct MapCharge {
374    owned: Tally,
375    table: Tally,
376    slots: ShardSlots,
377    slot_bytes: usize,
378}
379
380impl MapCharge {
381    pub const fn new(owner: Owner, slot_bytes: usize) -> Self {
382        Self {
383            owned: Tally::new(owner),
384            table: Tally::new(owner),
385            slots: ShardSlots::new(),
386            slot_bytes,
387        }
388    }
389
390    /// Insert `key` with `value` if it is absent, charging a new key once.
391    pub fn ensure<K, Q, V, S>(
392        &self,
393        map: &DashMap<K, V, S>,
394        key: &Q,
395        to_key: impl FnOnce() -> K,
396        value: impl FnOnce() -> V,
397        owned_bytes: u64,
398    ) where
399        K: Eq + std::hash::Hash + std::borrow::Borrow<Q>,
400        Q: Eq + std::hash::Hash + ?Sized,
401        S: std::hash::BuildHasher + Clone,
402    {
403        if map.contains_key(key) {
404            return;
405        }
406        let inserted = match map.entry(to_key()) {
407            dashmap::mapref::entry::Entry::Vacant(vacant) => {
408                vacant.insert(value());
409                true
410            }
411            dashmap::mapref::entry::Entry::Occupied(_) => false,
412        };
413        if inserted {
414            self.owned.add(owned_bytes);
415            self.slots
416                .charge_key(map, key, &self.table, self.slot_bytes);
417        }
418    }
419
420    pub fn release_owned(&self, bytes: u64) {
421        self.owned.sub(bytes);
422    }
423
424    /// Remove `key` from `map` and release its owned bytes if it was present.
425    /// The removal happens inside the call, so two removers cannot both release.
426    pub fn forget<K, Q, V, S>(&self, map: &DashMap<K, V, S>, key: &Q, owned_bytes: u64)
427    where
428        K: Eq + std::hash::Hash + std::borrow::Borrow<Q>,
429        Q: Eq + std::hash::Hash + ?Sized,
430        S: std::hash::BuildHasher + Clone,
431    {
432        if map.remove(key).is_some() {
433            self.owned.sub(owned_bytes);
434        }
435    }
436
437    /// Release every owned byte, for a map cleared as a whole.
438    pub fn clear_owned(&self) {
439        self.owned.take();
440    }
441
442    /// Insert `value` under `key`, replacing any previous value. The entry's
443    /// heap is `measure(key, value)`, and the table growth is charged too.
444    pub fn insert<K, V, S>(
445        &self,
446        map: &DashMap<K, V, S>,
447        key: K,
448        value: V,
449        measure: impl Fn(&K, &V) -> u64,
450    ) where
451        K: Eq + std::hash::Hash,
452        S: std::hash::BuildHasher + Clone,
453    {
454        let shard = map.determine_map(&key);
455        match map.entry(key) {
456            dashmap::mapref::entry::Entry::Vacant(vacant) => {
457                self.owned.add(measure(vacant.key(), &value));
458                vacant.insert(value);
459            }
460            dashmap::mapref::entry::Entry::Occupied(mut occupied) => {
461                let before = measure(occupied.key(), occupied.get());
462                let after = measure(occupied.key(), &value);
463                self.owned.adjust(before, after);
464                occupied.insert(value);
465            }
466        }
467        self.slots
468            .charge_shard(map, shard, &self.table, self.slot_bytes);
469    }
470
471    /// Run `update` on the entry under `key`, first inserting `fresh()` if the
472    /// key is absent. The insert, its charge and `update` run under one entry
473    /// guard, so a concurrent `remove_entry` either sees the entry with its
474    /// bytes charged or runs before the insert. `update` may change the value's
475    /// heap; the charge follows the value's `measure` before and after it.
476    pub fn upsert<K, V, S, R>(
477        &self,
478        map: &DashMap<K, V, S>,
479        key: K,
480        fresh: impl FnOnce() -> V,
481        measure: impl Fn(&K, &V) -> u64,
482        update: impl FnOnce(&mut V) -> R,
483    ) -> R
484    where
485        K: Eq + std::hash::Hash,
486        S: std::hash::BuildHasher + Clone,
487    {
488        let shard = map.determine_map(&key);
489        let (inserted, result) = match map.entry(key) {
490            dashmap::mapref::entry::Entry::Vacant(vacant) => {
491                let mut slot = vacant.insert(fresh());
492                let result = update(slot.value_mut());
493                self.owned.add(measure(slot.key(), slot.value()));
494                (true, result)
495            }
496            dashmap::mapref::entry::Entry::Occupied(mut occupied) => {
497                let before = measure(occupied.key(), occupied.get());
498                let result = update(occupied.get_mut());
499                let after = measure(occupied.key(), occupied.get());
500                self.owned.adjust(before, after);
501                (false, result)
502            }
503        };
504        if inserted {
505            self.slots
506                .charge_shard(map, shard, &self.table, self.slot_bytes);
507        }
508        result
509    }
510
511    /// Bytes charged to the entries' owned heap, excluding the table.
512    pub fn owned_bytes(&self) -> u64 {
513        self.owned.bytes()
514    }
515
516    /// Remove `key` and release the heap its entry held.
517    pub fn remove_entry<K, Q, V, S>(
518        &self,
519        map: &DashMap<K, V, S>,
520        key: &Q,
521        measure: impl Fn(&K, &V) -> u64,
522    ) -> Option<V>
523    where
524        K: Eq + std::hash::Hash + std::borrow::Borrow<Q>,
525        Q: Eq + std::hash::Hash + ?Sized,
526        S: std::hash::BuildHasher + Clone,
527    {
528        let (old_key, old_value) = map.remove(key)?;
529        self.owned.sub(measure(&old_key, &old_value));
530        self.slots
531            .charge_key(map, key, &self.table, self.slot_bytes);
532        Some(old_value)
533    }
534
535    /// Remove `key` when `remove_when` holds for its value, releasing the entry's heap.
536    pub fn remove_entry_if<K, Q, V, S>(
537        &self,
538        map: &DashMap<K, V, S>,
539        key: &Q,
540        remove_when: impl FnOnce(&V) -> bool,
541        measure: impl Fn(&K, &V) -> u64,
542    ) -> Option<V>
543    where
544        K: Eq + std::hash::Hash + std::borrow::Borrow<Q>,
545        Q: Eq + std::hash::Hash + ?Sized,
546        S: std::hash::BuildHasher + Clone,
547    {
548        let (old_key, old_value) = map.remove_if(key, |_, value| remove_when(value))?;
549        self.owned.sub(measure(&old_key, &old_value));
550        self.slots
551            .charge_key(map, key, &self.table, self.slot_bytes);
552        Some(old_value)
553    }
554
555    /// Re-read every shard's table after a change made without this API.
556    pub fn resize<K, V, S>(&self, map: &DashMap<K, V, S>)
557    where
558        K: Eq + std::hash::Hash,
559        S: std::hash::BuildHasher + Clone,
560    {
561        self.slots.charge_all(map, &self.table, self.slot_bytes);
562    }
563
564    /// Charge or release the heap change of a value the map holds in place.
565    pub fn adjust_owned(&self, before: u64, after: u64) {
566        self.owned.adjust(before, after);
567    }
568}
569
570/// Heap of an owned `String`: its capacity.
571pub fn string_heap(text: &String) -> u64 {
572    saturating_u64(text.capacity())
573}
574
575/// Heap of a `Vec<String>`: its slots, and each string's capacity.
576pub fn strings_heap(items: &Vec<String>) -> u64 {
577    saturating_u64(items.capacity() * std::mem::size_of::<String>())
578        + items.iter().map(string_heap).sum::<u64>()
579}
580
581/// Heap of an optional `String`.
582pub fn option_string_heap(text: &Option<String>) -> u64 {
583    text.as_ref().map_or(0, string_heap)
584}
585
586/// Bytes charged to an owner for as long as the value holding the lease lives.
587#[derive(Debug)]
588pub struct Lease {
589    owner: Owner,
590    bytes: u64,
591}
592
593impl Lease {
594    pub fn new(owner: Owner, bytes: u64) -> Self {
595        resident().charge(owner, bytes);
596        Self { owner, bytes }
597    }
598
599    /// Hold the `resident_bytes()` of `events` under `owner`.
600    pub fn for_events(owner: Owner, events: &[Event]) -> Self {
601        Self::new(owner, events.iter().map(Event::resident_bytes).sum())
602    }
603}
604
605impl Drop for Lease {
606    fn drop(&mut self) {
607        resident().release(self.owner, self.bytes);
608    }
609}
610
611/// Estimated heap held by one in-process broadcast ring: the slots a ring keeps
612/// for live receivers, times the running mean `resident_bytes()` of the events
613/// sent. A send returns `Ok` only when a receiver exists, so the slot count
614/// rises on each `Ok` and resets when a send finds no receiver.
615pub struct BroadcastRing {
616    capacity: u64,
617    state: parking_lot::Mutex<BroadcastState>,
618}
619
620struct BroadcastState {
621    slots: u64,
622    sent_bytes: u64,
623    sent: u64,
624    charged: Tally,
625}
626
627impl BroadcastRing {
628    pub fn new(capacity: usize) -> Self {
629        Self {
630            capacity: capacity as u64,
631            state: parking_lot::Mutex::new(BroadcastState {
632                slots: 0,
633                sent_bytes: 0,
634                sent: 0,
635                charged: Tally::new(Owner::Broadcast),
636            }),
637        }
638    }
639
640    /// Record one send. `delivered` is whether the send returned `Ok`.
641    pub fn observe(&self, delivered: bool, event_bytes: u64) {
642        let mut state = self.state.lock();
643        if !delivered {
644            state.slots = 0;
645            state.charged.take();
646            return;
647        }
648        state.slots = (state.slots + 1).min(self.capacity);
649        state.sent_bytes += event_bytes;
650        state.sent += 1;
651        let mean = state.sent_bytes / state.sent;
652        let value = state.slots * mean;
653        let held = state.charged.bytes();
654        if value >= held {
655            state.charged.add(value - held);
656        } else {
657            state.charged.sub(held - value);
658        }
659    }
660}
661
662fn saturating_i64(bytes: u64) -> i64 {
663    i64::try_from(bytes).unwrap_or(i64::MAX)
664}
665
666fn saturating_u64(bytes: usize) -> u64 {
667    u64::try_from(bytes).unwrap_or(u64::MAX)
668}