Line data Source code
1 : //! This file contains generic utility functions over the interface types,
2 : //! which could be handy for any compaction implementation.
3 : use crate::interface::*;
4 :
5 : use futures::future::BoxFuture;
6 : use futures::{Stream, StreamExt};
7 : use itertools::Itertools;
8 : use pageserver_api::shard::ShardIdentity;
9 : use pin_project_lite::pin_project;
10 : use std::collections::BinaryHeap;
11 : use std::collections::VecDeque;
12 : use std::fmt::Display;
13 : use std::future::Future;
14 : use std::ops::{DerefMut, Range};
15 : use std::pin::Pin;
16 : use std::task::{ready, Poll};
17 : use utils::lsn::Lsn;
18 :
19 : pub const PAGE_SZ: u64 = 8192;
20 :
21 3 : pub fn keyspace_total_size<K>(
22 3 : keyspace: &CompactionKeySpace<K>,
23 3 : shard_identity: &ShardIdentity,
24 3 : ) -> u64
25 3 : where
26 3 : K: CompactionKey,
27 3 : {
28 3 : keyspace
29 3 : .iter()
30 3 : .map(|r| K::key_range_size(r, shard_identity) as u64)
31 3 : .sum()
32 3 : }
33 :
34 13549 : pub fn overlaps_with<T: Ord>(a: &Range<T>, b: &Range<T>) -> bool {
35 13549 : !(a.end <= b.start || b.end <= a.start)
36 13549 : }
37 :
38 2397 : pub fn union_to_keyspace<K: Ord>(a: &mut CompactionKeySpace<K>, b: CompactionKeySpace<K>) {
39 2397 : let x = std::mem::take(a);
40 2397 : let mut all_ranges_iter = [x.into_iter(), b.into_iter()]
41 2397 : .into_iter()
42 2397 : .kmerge_by(|a, b| a.start < b.start);
43 2397 : let mut ranges = Vec::new();
44 2397 : if let Some(first) = all_ranges_iter.next() {
45 2397 : let (mut start, mut end) = (first.start, first.end);
46 :
47 4792 : for r in all_ranges_iter {
48 2395 : assert!(r.start >= start);
49 2395 : if r.start > end {
50 0 : ranges.push(start..end);
51 0 : start = r.start;
52 0 : end = r.end;
53 2395 : } else if r.end > end {
54 0 : end = r.end;
55 2395 : }
56 : }
57 2397 : ranges.push(start..end);
58 0 : }
59 2397 : *a = ranges
60 2397 : }
61 :
62 3 : pub fn intersect_keyspace<K: Ord + Clone + Copy>(
63 3 : a: &CompactionKeySpace<K>,
64 3 : r: &Range<K>,
65 3 : ) -> CompactionKeySpace<K> {
66 3 : let mut ranges: Vec<Range<K>> = Vec::new();
67 :
68 3 : for x in a.iter() {
69 3 : if x.end <= r.start {
70 0 : continue;
71 3 : }
72 3 : if x.start >= r.end {
73 0 : break;
74 3 : }
75 3 : ranges.push(x.clone())
76 : }
77 :
78 : // trim the ends
79 3 : if let Some(first) = ranges.first_mut() {
80 3 : first.start = std::cmp::max(first.start, r.start);
81 3 : }
82 3 : if let Some(last) = ranges.last_mut() {
83 3 : last.end = std::cmp::min(last.end, r.end);
84 3 : }
85 3 : ranges
86 3 : }
87 :
88 : /// Create a stream that iterates through all DeltaEntrys among all input
89 : /// layers, in key-lsn order.
90 : ///
91 : /// This is public because the create_delta() implementation likely wants to use this too
92 : /// TODO: move to a more shared place
93 49 : pub fn merge_delta_keys<'a, E: CompactionJobExecutor>(
94 49 : layers: &'a [E::DeltaLayer],
95 49 : ctx: &'a E::RequestContext,
96 49 : ) -> MergeDeltaKeys<'a, E> {
97 49 : // Use a binary heap to merge the layers. Each input layer is initially
98 49 : // represented by a LazyLoadLayer::Unloaded element, which uses the start of
99 49 : // the layer's key range as the key. The first time a layer reaches the top
100 49 : // of the heap, all the keys of the layer are loaded into a sorted vector.
101 49 : //
102 49 : // This helps to keep the memory usage reasonable: we only need to hold in
103 49 : // memory the DeltaEntrys of the layers that overlap with the "current" key.
104 49 : let mut heap: BinaryHeap<LazyLoadLayer<'a, E>> = BinaryHeap::new();
105 1610 : for l in layers {
106 1561 : heap.push(LazyLoadLayer::Unloaded(l));
107 1561 : }
108 49 : MergeDeltaKeys {
109 49 : heap,
110 49 : ctx,
111 49 : load_future: None,
112 49 : }
113 49 : }
114 :
115 3 : pub async fn merge_delta_keys_buffered<'a, E: CompactionJobExecutor + 'a>(
116 3 : layers: &'a [E::DeltaLayer],
117 3 : ctx: &'a E::RequestContext,
118 3 : ) -> anyhow::Result<impl Stream<Item = <E::DeltaLayer as CompactionDeltaLayer<E>>::DeltaEntry<'a>>>
119 3 : {
120 3 : let mut keys = Vec::new();
121 50 : for l in layers {
122 : // Boxing and casting to LoadFuture is required to obtain the right Sync bound.
123 : // If we do l.load_keys(ctx).await? directly, there is a compilation error.
124 47 : let load_future: LoadFuture<'a, _> = Box::pin(l.load_keys(ctx));
125 47 : keys.extend(load_future.await?.into_iter());
126 : }
127 5296376 : keys.sort_by_key(|k| (k.key(), k.lsn()));
128 3 : let stream = futures::stream::iter(keys.into_iter());
129 3 : Ok(stream)
130 3 : }
131 :
132 : enum LazyLoadLayer<'a, E: CompactionJobExecutor> {
133 : Loaded(VecDeque<<E::DeltaLayer as CompactionDeltaLayer<E>>::DeltaEntry<'a>>),
134 : Unloaded(&'a E::DeltaLayer),
135 : }
136 : impl<'a, E: CompactionJobExecutor> LazyLoadLayer<'a, E> {
137 40891366 : fn min_key(&self) -> E::Key {
138 40891366 : match self {
139 33586899 : Self::Loaded(entries) => entries.front().unwrap().key(),
140 7304467 : Self::Unloaded(dl) => dl.key_range().start,
141 : }
142 40891366 : }
143 40891366 : fn min_lsn(&self) -> Lsn {
144 40891366 : match self {
145 33586899 : Self::Loaded(entries) => entries.front().unwrap().lsn(),
146 7304467 : Self::Unloaded(dl) => dl.lsn_range().start,
147 : }
148 40891366 : }
149 : }
150 : impl<'a, E: CompactionJobExecutor> PartialOrd for LazyLoadLayer<'a, E> {
151 20445683 : fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
152 20445683 : Some(self.cmp(other))
153 20445683 : }
154 : }
155 : impl<'a, E: CompactionJobExecutor> Ord for LazyLoadLayer<'a, E> {
156 20445683 : fn cmp(&self, other: &Self) -> std::cmp::Ordering {
157 20445683 : // reverse order so that we get a min-heap
158 20445683 : (other.min_key(), other.min_lsn()).cmp(&(self.min_key(), self.min_lsn()))
159 20445683 : }
160 : }
161 : impl<'a, E: CompactionJobExecutor> PartialEq for LazyLoadLayer<'a, E> {
162 0 : fn eq(&self, other: &Self) -> bool {
163 0 : self.cmp(other) == std::cmp::Ordering::Equal
164 0 : }
165 : }
166 : impl<'a, E: CompactionJobExecutor> Eq for LazyLoadLayer<'a, E> {}
167 :
168 : type LoadFuture<'a, E> = BoxFuture<'a, anyhow::Result<Vec<E>>>;
169 :
170 : // Stream returned by `merge_delta_keys`
171 : pin_project! {
172 : #[allow(clippy::type_complexity)]
173 : pub struct MergeDeltaKeys<'a, E: CompactionJobExecutor> {
174 : heap: BinaryHeap<LazyLoadLayer<'a, E>>,
175 :
176 : #[pin]
177 : load_future: Option<LoadFuture<'a, <E::DeltaLayer as CompactionDeltaLayer<E>>::DeltaEntry<'a>>>,
178 :
179 : ctx: &'a E::RequestContext,
180 : }
181 : }
182 :
183 : impl<'a, E> Stream for MergeDeltaKeys<'a, E>
184 : where
185 : E: CompactionJobExecutor + 'a,
186 : {
187 : type Item = anyhow::Result<<E::DeltaLayer as CompactionDeltaLayer<E>>::DeltaEntry<'a>>;
188 :
189 5522610 : fn poll_next(
190 5522610 : self: Pin<&mut Self>,
191 5522610 : cx: &mut std::task::Context<'_>,
192 5522610 : ) -> Poll<std::option::Option<<Self as futures::Stream>::Item>> {
193 5522610 : let mut this = self.project();
194 : loop {
195 5524171 : if let Some(mut load_future) = this.load_future.as_mut().as_pin_mut() {
196 : // We are waiting for loading the keys to finish
197 1561 : match ready!(load_future.as_mut().poll(cx)) {
198 1561 : Ok(entries) => {
199 1561 : this.load_future.set(None);
200 1561 : *this.heap.peek_mut().unwrap() =
201 1561 : LazyLoadLayer::Loaded(VecDeque::from(entries));
202 1561 : }
203 0 : Err(e) => {
204 0 : return Poll::Ready(Some(Err(e)));
205 : }
206 : }
207 5522610 : }
208 :
209 : // If the topmost layer in the heap hasn't been loaded yet, start
210 : // loading it. Otherwise return the next entry from it and update
211 : // the layer's position in the heap (this decreaseKey operation is
212 : // performed implicitly when `top` is dropped).
213 5524171 : if let Some(mut top) = this.heap.peek_mut() {
214 5524122 : match top.deref_mut() {
215 1561 : LazyLoadLayer::Unloaded(ref mut l) => {
216 1561 : let fut = l.load_keys(this.ctx);
217 1561 : this.load_future.set(Some(Box::pin(fut)));
218 1561 : continue;
219 : }
220 5522561 : LazyLoadLayer::Loaded(ref mut entries) => {
221 5522561 : let result = entries.pop_front().unwrap();
222 5522561 : if entries.is_empty() {
223 1561 : std::collections::binary_heap::PeekMut::pop(top);
224 5521000 : }
225 5522561 : return Poll::Ready(Some(Ok(result)));
226 : }
227 : }
228 : } else {
229 49 : return Poll::Ready(None);
230 : }
231 : }
232 5522610 : }
233 : }
234 :
235 : // Accumulate values at key boundaries
236 : pub struct KeySize<K> {
237 : pub key: K,
238 : pub num_values: u64,
239 : pub size: u64,
240 : /// The lsns to partition at (if empty then no per-lsn partitioning)
241 : pub partition_lsns: Vec<(Lsn, u64)>,
242 : }
243 :
244 3 : pub fn accum_key_values<'a, I, K, D, E>(
245 3 : input: I,
246 3 : target_size: u64,
247 3 : ) -> impl Stream<Item = Result<KeySize<K>, E>>
248 3 : where
249 3 : K: Eq + PartialOrd + Display + Copy,
250 3 : I: Stream<Item = Result<D, E>>,
251 3 : D: CompactionDeltaEntry<'a, K>,
252 3 : {
253 3 : async_stream::try_stream! {
254 3 : // Initialize the state from the first value
255 3 : let mut input = std::pin::pin!(input);
256 3 :
257 3 : if let Some(first) = input.next().await {
258 3 : let first = first?;
259 3 : let mut part_size = first.size();
260 3 : let mut accum: KeySize<K> = KeySize {
261 3 : key: first.key(),
262 3 : num_values: 1,
263 3 : size: part_size,
264 3 : partition_lsns: Vec::new(),
265 3 : };
266 3 : let mut last_key = accum.key;
267 3 : while let Some(this) = input.next().await {
268 3 : let this = this?;
269 3 : if this.key() == accum.key {
270 3 : let add_size = this.size();
271 3 : if part_size + add_size > target_size {
272 3 : accum.partition_lsns.push((this.lsn(), part_size));
273 3 : part_size = 0;
274 3 : }
275 3 : part_size += add_size;
276 3 : accum.size += add_size;
277 3 : accum.num_values += 1;
278 3 : } else {
279 3 : assert!(last_key <= accum.key, "last_key={last_key} <= accum.key={}", accum.key);
280 3 : last_key = accum.key;
281 3 : yield accum;
282 3 : part_size = this.size();
283 3 : accum = KeySize {
284 3 : key: this.key(),
285 3 : num_values: 1,
286 3 : size: part_size,
287 3 : partition_lsns: Vec::new(),
288 3 : };
289 3 : }
290 3 : }
291 3 : assert!(last_key <= accum.key, "last_key={last_key} <= accum.key={}", accum.key);
292 3 : yield accum;
293 3 : }
294 3 : }
295 3 : }
|