console_subscriber/aggregator/
shrink.rs

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
use std::{
    any::type_name,
    collections::hash_map::{HashMap, RandomState},
    hash::{BuildHasher, Hash},
    mem,
    ops::{Deref, DerefMut},
};

#[derive(Debug, Clone)]
pub(crate) struct ShrinkMap<K, V, S = RandomState> {
    map: HashMap<K, V, S>,
    shrink: Shrink,
}

#[derive(Debug, Clone)]
pub(crate) struct ShrinkVec<T> {
    vec: Vec<T>,
    shrink: Shrink,
}

#[derive(Debug, Clone)]
pub(crate) struct Shrink {
    shrink_every: usize,
    since_shrink: usize,
    min_bytes: usize,
}

// === impl ShrinkMap ===

impl<K, V> ShrinkMap<K, V>
where
    K: Hash + Eq,
{
    pub(crate) fn new() -> Self {
        Self {
            map: HashMap::new(),
            shrink: Shrink::default(),
        }
    }
}

impl<K, V, S> ShrinkMap<K, V, S>
where
    K: Hash + Eq,
    S: BuildHasher,
{
    pub(crate) fn try_shrink(&mut self) {
        self.shrink.try_shrink_map(&mut self.map)
    }

    pub(crate) fn retain_and_shrink(&mut self, f: impl FnMut(&K, &mut V) -> bool) {
        let len0 = self.len();

        self.retain(f);

        if self.len() < len0 {
            tracing::debug!(
                len = self.len(),
                dropped = len0.saturating_sub(self.len()),
                data.key = %type_name::<K>(),
                data.val = %type_name::<V>(),
                "dropped unused entries"
            );
            self.try_shrink();
        }
    }
}

impl<K, V, S> Deref for ShrinkMap<K, V, S> {
    type Target = HashMap<K, V, S>;
    fn deref(&self) -> &Self::Target {
        &self.map
    }
}

impl<K, V, S> DerefMut for ShrinkMap<K, V, S> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.map
    }
}

impl<K, V> Default for ShrinkMap<K, V>
where
    K: Hash + Eq,
{
    fn default() -> Self {
        Self::new()
    }
}

// === impl ShrinkVec ===

impl<T> ShrinkVec<T> {
    pub(crate) fn new() -> Self {
        Self {
            vec: Vec::new(),
            shrink: Shrink::default(),
        }
    }

    pub(crate) fn try_shrink(&mut self) {
        self.shrink.try_shrink_vec(&mut self.vec)
    }

    pub(crate) fn retain_and_shrink(&mut self, f: impl FnMut(&T) -> bool) {
        let len0 = self.len();

        self.retain(f);

        if self.len() < len0 {
            tracing::debug!(
                len = self.len(),
                dropped = len0.saturating_sub(self.len()),
                data = %type_name::<T>(),
                "dropped unused data"
            );
            self.try_shrink();
        }
    }
}

impl<T> Deref for ShrinkVec<T> {
    type Target = Vec<T>;
    fn deref(&self) -> &Self::Target {
        &self.vec
    }
}

impl<T> DerefMut for ShrinkVec<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.vec
    }
}

impl<T> Default for ShrinkVec<T> {
    fn default() -> Self {
        Self::new()
    }
}

// === impl Shrink ===

impl Shrink {
    /// Shrinking every 60 flushes should be roughly every minute.
    pub(crate) const DEFAULT_SHRINK_INTERVAL: usize = 60;

    /// Don't bother if we'd free less than 4KB of memory.
    // TODO(eliza): this number was chosen totally arbitrarily; it's the minimum
    // page size on x86.
    pub(crate) const DEFAULT_MIN_SIZE_BYTES: usize = 1024 * 4;

    pub(crate) fn try_shrink_map<K, V, S>(&mut self, map: &mut HashMap<K, V, S>)
    where
        K: Hash + Eq,
        S: BuildHasher,
    {
        if self.should_shrink::<(K, V)>(map.capacity(), map.len()) {
            map.shrink_to_fit();
        }
    }

    pub(crate) fn try_shrink_vec<T>(&mut self, vec: &mut Vec<T>) {
        if self.should_shrink::<T>(vec.capacity(), vec.len()) {
            vec.shrink_to_fit();
        }
    }

    /// Returns `true` if we should shrink with a capacity of `capacity` Ts and
    /// an actual length of `len` Ts.
    fn should_shrink<T>(&mut self, capacity: usize, len: usize) -> bool {
        // Has the required interval elapsed since the last shrink?
        self.since_shrink = self.since_shrink.saturating_add(1);
        if self.since_shrink < self.shrink_every {
            tracing::trace!(
                self.since_shrink,
                self.shrink_every,
                capacity_bytes = capacity * mem::size_of::<T>(),
                used_bytes = len * mem::size_of::<T>(),
                data = %type_name::<T>(),
                "should_shrink: shrink interval has not elapsed"
            );
            return false;
        }

        // Okay, would we free up at least `min_bytes` by shrinking?
        let capacity_bytes = capacity * mem::size_of::<T>();
        let used_bytes = len * mem::size_of::<T>();
        let diff = capacity_bytes.saturating_sub(used_bytes);
        if diff < self.min_bytes {
            tracing::trace!(
                self.since_shrink,
                self.shrink_every,
                self.min_bytes,
                freed_bytes = diff,
                capacity_bytes,
                used_bytes,
                data = %type_name::<T>(),
                "should_shrink: would not free sufficient bytes"
            );
            return false;
        }

        // Reset the clock! time to shrink!
        self.since_shrink = 0;
        tracing::debug!(
            self.since_shrink,
            self.shrink_every,
            self.min_bytes,
            freed_bytes = diff,
            capacity_bytes,
            used_bytes,
            data = %type_name::<T>(),
            "should_shrink: shrinking!"
        );
        true
    }
}

impl Default for Shrink {
    fn default() -> Self {
        Self {
            since_shrink: 0,
            shrink_every: Self::DEFAULT_SHRINK_INTERVAL,
            min_bytes: Self::DEFAULT_MIN_SIZE_BYTES,
        }
    }
}