allsource-core 0.30.0

High-performance event store core built in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
//! Counts resident heap bytes per owner. The ledger counts and never refuses,
//! reserves or evicts: a charge or release is a plain atomic add.
//!
//! Owners are charged where their bytes become resident and released where
//! they stop being resident. Owner counters change only through this API.

use crate::domain::entities::event::Event;
use dashmap::DashMap;
use std::sync::{
    OnceLock,
    atomic::{AtomicI64, AtomicU64, AtomicUsize, Ordering},
};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Owner {
    EventsResident,
    StoragePending,
    IndexEntity,
    IndexType,
    IndexId,
    FeedIndex,
    CacheGenerations,
    TenantLoader,
    ReadModels,
    PipelineWindows,
    PipelineState,
    WebhookQueue,
    Broadcast,
    ProjectionEventCounters,
    Query,
    EntityVersions,
    VersionIndexTenants,
    VersionIndexEntities,
    GeoIndex,
    SchemaEvolution,
    ProjectionPermanent,
    Search,
    SystemStore,
    Misc,
    RateLimiter,
    Metrics,
}

impl Owner {
    pub const COUNT: usize = 26;

    pub const ALL: [Owner; Self::COUNT] = [
        Owner::EventsResident,
        Owner::StoragePending,
        Owner::IndexEntity,
        Owner::IndexType,
        Owner::IndexId,
        Owner::FeedIndex,
        Owner::CacheGenerations,
        Owner::TenantLoader,
        Owner::ReadModels,
        Owner::PipelineWindows,
        Owner::PipelineState,
        Owner::WebhookQueue,
        Owner::Broadcast,
        Owner::ProjectionEventCounters,
        Owner::Query,
        Owner::EntityVersions,
        Owner::VersionIndexTenants,
        Owner::VersionIndexEntities,
        Owner::GeoIndex,
        Owner::SchemaEvolution,
        Owner::ProjectionPermanent,
        Owner::Search,
        Owner::SystemStore,
        Owner::Misc,
        Owner::RateLimiter,
        Owner::Metrics,
    ];

    /// The `owner` label value in the metrics.
    pub const fn label(self) -> &'static str {
        match self {
            Owner::EventsResident => "events.resident",
            Owner::StoragePending => "storage.pending",
            Owner::IndexEntity => "index.entity",
            Owner::IndexType => "index.type",
            Owner::IndexId => "index.id",
            Owner::FeedIndex => "feed_index",
            Owner::CacheGenerations => "cache_generations",
            Owner::TenantLoader => "tenant_loader",
            Owner::ReadModels => "read_models",
            Owner::PipelineWindows => "pipeline.windows",
            Owner::PipelineState => "pipeline.state",
            Owner::WebhookQueue => "webhook.queue",
            Owner::Broadcast => "broadcast",
            Owner::ProjectionEventCounters => "projection.event_counters",
            Owner::Query => "query",
            Owner::EntityVersions => "entity_versions",
            Owner::VersionIndexTenants => "version_index_tenants",
            Owner::VersionIndexEntities => "version_index_entities",
            Owner::GeoIndex => "geo_index",
            Owner::SchemaEvolution => "schema_evolution",
            Owner::ProjectionPermanent => "projection.permanent",
            Owner::Search => "search",
            Owner::SystemStore => "system_store",
            Owner::Misc => "misc",
            Owner::RateLimiter => "rate_limiter",
            Owner::Metrics => "metrics",
        }
    }

    /// Owners whose bytes are never released, summed in
    /// `allsource_core_permanent_bytes`.
    pub const fn is_permanent(self) -> bool {
        matches!(
            self,
            Owner::CacheGenerations
                | Owner::EntityVersions
                | Owner::VersionIndexTenants
                | Owner::VersionIndexEntities
                | Owner::GeoIndex
                | Owner::SchemaEvolution
                | Owner::ProjectionPermanent
                | Owner::Search
                | Owner::SystemStore
                | Owner::Misc
                | Owner::Metrics
        )
    }
}

pub struct ResidentLedger {
    owners: [AtomicI64; Owner::COUNT],
    rows_decoded: AtomicU64,
}

impl ResidentLedger {
    pub const fn new() -> Self {
        Self {
            owners: [const { AtomicI64::new(0) }; Owner::COUNT],
            rows_decoded: AtomicU64::new(0),
        }
    }

    pub fn charge(&self, owner: Owner, bytes: u64) {
        self.owners[owner as usize].fetch_add(saturating_i64(bytes), Ordering::Relaxed);
    }

    pub fn release(&self, owner: Owner, bytes: u64) {
        self.owners[owner as usize].fetch_sub(saturating_i64(bytes), Ordering::Relaxed);
    }

    /// Charge the growth of a `Vec`-like table from `before` to `after` slots,
    /// or release a shrink. Each slot is `slot_bytes` wide.
    pub fn track_capacity(&self, owner: Owner, before: usize, after: usize, slot_bytes: usize) {
        if after >= before {
            self.charge(owner, saturating_u64((after - before) * slot_bytes));
        } else {
            self.release(owner, saturating_u64((before - after) * slot_bytes));
        }
    }

    pub fn record_rows_decoded(&self, rows: u64) {
        self.rows_decoded.fetch_add(rows, Ordering::Relaxed);
    }

    pub fn rows_decoded_total(&self) -> u64 {
        self.rows_decoded.load(Ordering::Relaxed)
    }

    pub fn owner_bytes(&self, owner: Owner) -> i64 {
        self.owners[owner as usize].load(Ordering::Relaxed)
    }

    pub fn total_bytes(&self) -> i64 {
        self.owners
            .iter()
            .map(|owner| owner.load(Ordering::Relaxed))
            .sum()
    }

    pub fn permanent_bytes(&self) -> i64 {
        Owner::ALL
            .iter()
            .filter(|owner| owner.is_permanent())
            .map(|owner| self.owner_bytes(*owner))
            .sum()
    }
}

impl Default for ResidentLedger {
    fn default() -> Self {
        Self::new()
    }
}

static RESIDENT: ResidentLedger = ResidentLedger::new();

/// The process-wide ledger. Heap is process-wide too, so the unattributed gauge
/// compares the same scope on both sides.
pub fn resident() -> &'static ResidentLedger {
    &RESIDENT
}

/// The bytes one structure has charged to one owner. Releases never exceed
/// what this tally holds, and dropping it releases the rest, so an owner that
/// goes away cannot leave its bytes counted.
pub struct Tally {
    owner: Owner,
    bytes: AtomicU64,
}

impl Tally {
    pub const fn new(owner: Owner) -> Self {
        Self {
            owner,
            bytes: AtomicU64::new(0),
        }
    }

    pub fn add(&self, bytes: u64) {
        if bytes == 0 {
            return;
        }
        resident().charge(self.owner, bytes);
        self.bytes.fetch_add(bytes, Ordering::Relaxed);
    }

    pub fn sub(&self, bytes: u64) {
        let held = self
            .bytes
            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |held| {
                Some(held.saturating_sub(bytes))
            })
            .unwrap_or(0);
        let released = held.min(bytes);
        if released > 0 {
            resident().release(self.owner, released);
        }
    }

    /// Charge the growth of a slot table from `before` to `after` slots, or
    /// release a shrink. Each slot is `slot_bytes` wide.
    pub fn grow(&self, before: usize, after: usize, slot_bytes: usize) {
        let delta = after.abs_diff(before) as u64 * slot_bytes as u64;
        if after >= before {
            self.add(delta);
        } else {
            self.sub(delta);
        }
    }

    /// Charge or release the change of one value's heap from `before` to `after`.
    pub fn adjust(&self, before: u64, after: u64) {
        if after >= before {
            self.add(after - before);
        } else {
            self.sub(before - after);
        }
    }

    /// Move the held amount to `target`, charging or releasing the difference.
    pub fn set_to(&self, target: u64) {
        let held = self.bytes();
        if target >= held {
            self.add(target - held);
        } else {
            self.sub(held - target);
        }
    }

    /// Release the `resident_bytes()` of every event that `matches` selects.
    pub fn release_matching(&self, events: &[Event], matches: impl Fn(&Event) -> bool) {
        let released: u64 = events
            .iter()
            .filter(|event| matches(event))
            .map(Event::resident_bytes)
            .sum();
        self.sub(released);
    }

    /// Release everything held and return the released amount.
    pub fn take(&self) -> u64 {
        let held = self.bytes.swap(0, Ordering::Relaxed);
        if held > 0 {
            resident().release(self.owner, held);
        }
        held
    }

    pub fn bytes(&self) -> u64 {
        self.bytes.load(Ordering::Relaxed)
    }
}

impl Drop for Tally {
    fn drop(&mut self) {
        self.take();
    }
}

/// The table capacity last charged for each shard of one `DashMap`. A keyed
/// change re-reads only that key's shard: `DashMap::capacity` takes every
/// shard lock, one lock pair per shard for each new key on the ingest path.
pub struct ShardSlots(OnceLock<Box<[AtomicUsize]>>);

impl ShardSlots {
    pub const fn new() -> Self {
        Self(OnceLock::new())
    }

    fn slots<K, V, S>(&self, map: &DashMap<K, V, S>) -> &[AtomicUsize]
    where
        K: Eq + std::hash::Hash,
        S: std::hash::BuildHasher + Clone,
    {
        self.0
            .get_or_init(|| map.shards().iter().map(|_| AtomicUsize::new(0)).collect())
    }

    /// Charge `table` for the change in the capacity of the shard holding
    /// `key` since the last read. Call it after the entry guard is dropped.
    pub fn charge_key<K, Q, V, S>(
        &self,
        map: &DashMap<K, V, S>,
        key: &Q,
        table: &Tally,
        slot_bytes: usize,
    ) where
        K: Eq + std::hash::Hash + std::borrow::Borrow<Q>,
        Q: Eq + std::hash::Hash + ?Sized,
        S: std::hash::BuildHasher + Clone,
    {
        self.charge_shard(map, map.determine_map(key), table, slot_bytes);
    }

    /// Charge `table` for the change in every shard's capacity.
    pub fn charge_all<K, V, S>(&self, map: &DashMap<K, V, S>, table: &Tally, slot_bytes: usize)
    where
        K: Eq + std::hash::Hash,
        S: std::hash::BuildHasher + Clone,
    {
        for shard in 0..map.shards().len() {
            self.charge_shard(map, shard, table, slot_bytes);
        }
    }

    fn charge_shard<K, V, S>(
        &self,
        map: &DashMap<K, V, S>,
        shard: usize,
        table: &Tally,
        slot_bytes: usize,
    ) where
        K: Eq + std::hash::Hash,
        S: std::hash::BuildHasher + Clone,
    {
        // The read guard spans the swap: a resize needs the write lock, so two
        // racing charges cannot store an older capacity over a newer one.
        let guard = map.shards()[shard].read();
        let now = guard.capacity();
        let before = self.slots(map)[shard].swap(now, Ordering::Relaxed);
        drop(guard);
        table.grow(before, now, slot_bytes);
    }
}

impl Default for ShardSlots {
    fn default() -> Self {
        Self::new()
    }
}

/// Charges a concurrent map's new keys: each key's owned bytes, and the growth
/// of the map's table. The table stays charged after its entries are removed,
/// because the map keeps its allocation.
pub struct MapCharge {
    owned: Tally,
    table: Tally,
    slots: ShardSlots,
    slot_bytes: usize,
}

impl MapCharge {
    pub const fn new(owner: Owner, slot_bytes: usize) -> Self {
        Self {
            owned: Tally::new(owner),
            table: Tally::new(owner),
            slots: ShardSlots::new(),
            slot_bytes,
        }
    }

    /// Insert `key` with `value` if it is absent, charging a new key once.
    pub fn ensure<K, Q, V, S>(
        &self,
        map: &DashMap<K, V, S>,
        key: &Q,
        to_key: impl FnOnce() -> K,
        value: impl FnOnce() -> V,
        owned_bytes: u64,
    ) where
        K: Eq + std::hash::Hash + std::borrow::Borrow<Q>,
        Q: Eq + std::hash::Hash + ?Sized,
        S: std::hash::BuildHasher + Clone,
    {
        if map.contains_key(key) {
            return;
        }
        let inserted = match map.entry(to_key()) {
            dashmap::mapref::entry::Entry::Vacant(vacant) => {
                vacant.insert(value());
                true
            }
            dashmap::mapref::entry::Entry::Occupied(_) => false,
        };
        if inserted {
            self.owned.add(owned_bytes);
            self.slots
                .charge_key(map, key, &self.table, self.slot_bytes);
        }
    }

    pub fn release_owned(&self, bytes: u64) {
        self.owned.sub(bytes);
    }

    /// Remove `key` from `map` and release its owned bytes if it was present.
    /// The removal happens inside the call, so two removers cannot both release.
    pub fn forget<K, Q, V, S>(&self, map: &DashMap<K, V, S>, key: &Q, owned_bytes: u64)
    where
        K: Eq + std::hash::Hash + std::borrow::Borrow<Q>,
        Q: Eq + std::hash::Hash + ?Sized,
        S: std::hash::BuildHasher + Clone,
    {
        if map.remove(key).is_some() {
            self.owned.sub(owned_bytes);
        }
    }

    /// Release every owned byte, for a map cleared as a whole.
    pub fn clear_owned(&self) {
        self.owned.take();
    }

    /// Insert `value` under `key`, replacing any previous value. The entry's
    /// heap is `measure(key, value)`, and the table growth is charged too.
    pub fn insert<K, V, S>(
        &self,
        map: &DashMap<K, V, S>,
        key: K,
        value: V,
        measure: impl Fn(&K, &V) -> u64,
    ) where
        K: Eq + std::hash::Hash,
        S: std::hash::BuildHasher + Clone,
    {
        let shard = map.determine_map(&key);
        match map.entry(key) {
            dashmap::mapref::entry::Entry::Vacant(vacant) => {
                self.owned.add(measure(vacant.key(), &value));
                vacant.insert(value);
            }
            dashmap::mapref::entry::Entry::Occupied(mut occupied) => {
                let before = measure(occupied.key(), occupied.get());
                let after = measure(occupied.key(), &value);
                self.owned.adjust(before, after);
                occupied.insert(value);
            }
        }
        self.slots
            .charge_shard(map, shard, &self.table, self.slot_bytes);
    }

    /// Run `update` on the entry under `key`, first inserting `fresh()` if the
    /// key is absent. The insert, its charge and `update` run under one entry
    /// guard, so a concurrent `remove_entry` either sees the entry with its
    /// bytes charged or runs before the insert. `update` may change the value's
    /// heap; the charge follows the value's `measure` before and after it.
    pub fn upsert<K, V, S, R>(
        &self,
        map: &DashMap<K, V, S>,
        key: K,
        fresh: impl FnOnce() -> V,
        measure: impl Fn(&K, &V) -> u64,
        update: impl FnOnce(&mut V) -> R,
    ) -> R
    where
        K: Eq + std::hash::Hash,
        S: std::hash::BuildHasher + Clone,
    {
        let shard = map.determine_map(&key);
        let (inserted, result) = match map.entry(key) {
            dashmap::mapref::entry::Entry::Vacant(vacant) => {
                let mut slot = vacant.insert(fresh());
                let result = update(slot.value_mut());
                self.owned.add(measure(slot.key(), slot.value()));
                (true, result)
            }
            dashmap::mapref::entry::Entry::Occupied(mut occupied) => {
                let before = measure(occupied.key(), occupied.get());
                let result = update(occupied.get_mut());
                let after = measure(occupied.key(), occupied.get());
                self.owned.adjust(before, after);
                (false, result)
            }
        };
        if inserted {
            self.slots
                .charge_shard(map, shard, &self.table, self.slot_bytes);
        }
        result
    }

    /// Bytes charged to the entries' owned heap, excluding the table.
    pub fn owned_bytes(&self) -> u64 {
        self.owned.bytes()
    }

    /// Remove `key` and release the heap its entry held.
    pub fn remove_entry<K, Q, V, S>(
        &self,
        map: &DashMap<K, V, S>,
        key: &Q,
        measure: impl Fn(&K, &V) -> u64,
    ) -> Option<V>
    where
        K: Eq + std::hash::Hash + std::borrow::Borrow<Q>,
        Q: Eq + std::hash::Hash + ?Sized,
        S: std::hash::BuildHasher + Clone,
    {
        let (old_key, old_value) = map.remove(key)?;
        self.owned.sub(measure(&old_key, &old_value));
        self.slots
            .charge_key(map, key, &self.table, self.slot_bytes);
        Some(old_value)
    }

    /// Remove `key` when `remove_when` holds for its value, releasing the entry's heap.
    pub fn remove_entry_if<K, Q, V, S>(
        &self,
        map: &DashMap<K, V, S>,
        key: &Q,
        remove_when: impl FnOnce(&V) -> bool,
        measure: impl Fn(&K, &V) -> u64,
    ) -> Option<V>
    where
        K: Eq + std::hash::Hash + std::borrow::Borrow<Q>,
        Q: Eq + std::hash::Hash + ?Sized,
        S: std::hash::BuildHasher + Clone,
    {
        let (old_key, old_value) = map.remove_if(key, |_, value| remove_when(value))?;
        self.owned.sub(measure(&old_key, &old_value));
        self.slots
            .charge_key(map, key, &self.table, self.slot_bytes);
        Some(old_value)
    }

    /// Re-read every shard's table after a change made without this API.
    pub fn resize<K, V, S>(&self, map: &DashMap<K, V, S>)
    where
        K: Eq + std::hash::Hash,
        S: std::hash::BuildHasher + Clone,
    {
        self.slots.charge_all(map, &self.table, self.slot_bytes);
    }

    /// Charge or release the heap change of a value the map holds in place.
    pub fn adjust_owned(&self, before: u64, after: u64) {
        self.owned.adjust(before, after);
    }
}

/// Heap of an owned `String`: its capacity.
pub fn string_heap(text: &String) -> u64 {
    saturating_u64(text.capacity())
}

/// Heap of a `Vec<String>`: its slots, and each string's capacity.
pub fn strings_heap(items: &Vec<String>) -> u64 {
    saturating_u64(items.capacity() * std::mem::size_of::<String>())
        + items.iter().map(string_heap).sum::<u64>()
}

/// Heap of an optional `String`.
pub fn option_string_heap(text: &Option<String>) -> u64 {
    text.as_ref().map_or(0, string_heap)
}

/// Bytes charged to an owner for as long as the value holding the lease lives.
#[derive(Debug)]
pub struct Lease {
    owner: Owner,
    bytes: u64,
}

impl Lease {
    pub fn new(owner: Owner, bytes: u64) -> Self {
        resident().charge(owner, bytes);
        Self { owner, bytes }
    }

    /// Hold the `resident_bytes()` of `events` under `owner`.
    pub fn for_events(owner: Owner, events: &[Event]) -> Self {
        Self::new(owner, events.iter().map(Event::resident_bytes).sum())
    }
}

impl Drop for Lease {
    fn drop(&mut self) {
        resident().release(self.owner, self.bytes);
    }
}

/// Estimated heap held by one in-process broadcast ring: the slots a ring keeps
/// for live receivers, times the running mean `resident_bytes()` of the events
/// sent. A send returns `Ok` only when a receiver exists, so the slot count
/// rises on each `Ok` and resets when a send finds no receiver.
pub struct BroadcastRing {
    capacity: u64,
    state: parking_lot::Mutex<BroadcastState>,
}

struct BroadcastState {
    slots: u64,
    sent_bytes: u64,
    sent: u64,
    charged: Tally,
}

impl BroadcastRing {
    pub fn new(capacity: usize) -> Self {
        Self {
            capacity: capacity as u64,
            state: parking_lot::Mutex::new(BroadcastState {
                slots: 0,
                sent_bytes: 0,
                sent: 0,
                charged: Tally::new(Owner::Broadcast),
            }),
        }
    }

    /// Record one send. `delivered` is whether the send returned `Ok`.
    pub fn observe(&self, delivered: bool, event_bytes: u64) {
        let mut state = self.state.lock();
        if !delivered {
            state.slots = 0;
            state.charged.take();
            return;
        }
        state.slots = (state.slots + 1).min(self.capacity);
        state.sent_bytes += event_bytes;
        state.sent += 1;
        let mean = state.sent_bytes / state.sent;
        let value = state.slots * mean;
        let held = state.charged.bytes();
        if value >= held {
            state.charged.add(value - held);
        } else {
            state.charged.sub(held - value);
        }
    }
}

fn saturating_i64(bytes: u64) -> i64 {
    i64::try_from(bytes).unwrap_or(i64::MAX)
}

fn saturating_u64(bytes: usize) -> u64 {
    u64::try_from(bytes).unwrap_or(u64::MAX)
}