Line data Source code
1 : //!
2 : //! This provides an abstraction to store PostgreSQL relations and other files
3 : //! in the key-value store that implements the Repository interface.
4 : //!
5 : //! (TODO: The line between PUT-functions here and walingest.rs is a bit blurry, as
6 : //! walingest.rs handles a few things like implicit relation creation and extension.
7 : //! Clarify that)
8 : //!
9 : use super::tenant::{PageReconstructError, Timeline};
10 : use crate::context::RequestContext;
11 : use crate::keyspace::{KeySpace, KeySpaceAccum};
12 : use crate::span::debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id;
13 : use crate::walrecord::NeonWalRecord;
14 : use crate::{aux_file, repository::*};
15 : use anyhow::{ensure, Context};
16 : use bytes::{Buf, Bytes, BytesMut};
17 : use enum_map::Enum;
18 : use itertools::Itertools;
19 : use pageserver_api::key::{
20 : dbdir_key_range, rel_block_to_key, rel_dir_to_key, rel_key_range, rel_size_to_key,
21 : relmap_file_key, repl_origin_key, repl_origin_key_range, slru_block_to_key, slru_dir_to_key,
22 : slru_segment_key_range, slru_segment_size_to_key, twophase_file_key, twophase_key_range,
23 : AUX_FILES_KEY, CHECKPOINT_KEY, CONTROLFILE_KEY, DBDIR_KEY, TWOPHASEDIR_KEY,
24 : };
25 : use pageserver_api::keyspace::SparseKeySpace;
26 : use pageserver_api::models::AuxFilePolicy;
27 : use pageserver_api::reltag::{BlockNumber, RelTag, SlruKind};
28 : use postgres_ffi::relfile_utils::{FSM_FORKNUM, VISIBILITYMAP_FORKNUM};
29 : use postgres_ffi::BLCKSZ;
30 : use postgres_ffi::{Oid, RepOriginId, TimestampTz, TransactionId};
31 : use serde::{Deserialize, Serialize};
32 : use std::collections::{hash_map, HashMap, HashSet};
33 : use std::ops::ControlFlow;
34 : use std::ops::Range;
35 : use strum::IntoEnumIterator;
36 : use tokio_util::sync::CancellationToken;
37 : use tracing::{debug, info, trace, warn};
38 : use utils::bin_ser::DeserializeError;
39 : use utils::pausable_failpoint;
40 : use utils::vec_map::{VecMap, VecMapOrdering};
41 : use utils::{bin_ser::BeSer, lsn::Lsn};
42 :
43 : /// Max delta records appended to the AUX_FILES_KEY (for aux v1). The write path will write a full image once this threshold is reached.
44 : pub const MAX_AUX_FILE_DELTAS: usize = 1024;
45 :
46 : /// Max number of aux-file-related delta layers. The compaction will create a new image layer once this threshold is reached.
47 : pub const MAX_AUX_FILE_V2_DELTAS: usize = 64;
48 :
49 : #[derive(Debug)]
50 : pub enum LsnForTimestamp {
51 : /// Found commits both before and after the given timestamp
52 : Present(Lsn),
53 :
54 : /// Found no commits after the given timestamp, this means
55 : /// that the newest data in the branch is older than the given
56 : /// timestamp.
57 : ///
58 : /// All commits <= LSN happened before the given timestamp
59 : Future(Lsn),
60 :
61 : /// The queried timestamp is past our horizon we look back at (PITR)
62 : ///
63 : /// All commits > LSN happened after the given timestamp,
64 : /// but any commits < LSN might have happened before or after
65 : /// the given timestamp. We don't know because no data before
66 : /// the given lsn is available.
67 : Past(Lsn),
68 :
69 : /// We have found no commit with a timestamp,
70 : /// so we can't return anything meaningful.
71 : ///
72 : /// The associated LSN is the lower bound value we can safely
73 : /// create branches on, but no statement is made if it is
74 : /// older or newer than the timestamp.
75 : ///
76 : /// This variant can e.g. be returned right after a
77 : /// cluster import.
78 : NoData(Lsn),
79 : }
80 :
81 0 : #[derive(Debug, thiserror::Error)]
82 : pub(crate) enum CalculateLogicalSizeError {
83 : #[error("cancelled")]
84 : Cancelled,
85 :
86 : /// Something went wrong while reading the metadata we use to calculate logical size
87 : /// Note that cancellation variants of `PageReconstructError` are transformed to [`Self::Cancelled`]
88 : /// in the `From` implementation for this variant.
89 : #[error(transparent)]
90 : PageRead(PageReconstructError),
91 :
92 : /// Something went wrong deserializing metadata that we read to calculate logical size
93 : #[error("decode error: {0}")]
94 : Decode(#[from] DeserializeError),
95 : }
96 :
97 0 : #[derive(Debug, thiserror::Error)]
98 : pub(crate) enum CollectKeySpaceError {
99 : #[error(transparent)]
100 : Decode(#[from] DeserializeError),
101 : #[error(transparent)]
102 : PageRead(PageReconstructError),
103 : #[error("cancelled")]
104 : Cancelled,
105 : }
106 :
107 : impl From<PageReconstructError> for CollectKeySpaceError {
108 0 : fn from(err: PageReconstructError) -> Self {
109 0 : match err {
110 0 : PageReconstructError::Cancelled => Self::Cancelled,
111 0 : err => Self::PageRead(err),
112 : }
113 0 : }
114 : }
115 :
116 : impl From<PageReconstructError> for CalculateLogicalSizeError {
117 0 : fn from(pre: PageReconstructError) -> Self {
118 0 : match pre {
119 0 : PageReconstructError::Cancelled => Self::Cancelled,
120 0 : _ => Self::PageRead(pre),
121 : }
122 0 : }
123 : }
124 :
125 0 : #[derive(Debug, thiserror::Error)]
126 : pub enum RelationError {
127 : #[error("Relation Already Exists")]
128 : AlreadyExists,
129 : #[error("invalid relnode")]
130 : InvalidRelnode,
131 : #[error(transparent)]
132 : Other(#[from] anyhow::Error),
133 : }
134 :
135 : ///
136 : /// This impl provides all the functionality to store PostgreSQL relations, SLRUs,
137 : /// and other special kinds of files, in a versioned key-value store. The
138 : /// Timeline struct provides the key-value store.
139 : ///
140 : /// This is a separate impl, so that we can easily include all these functions in a Timeline
141 : /// implementation, and might be moved into a separate struct later.
142 : impl Timeline {
143 : /// Start ingesting a WAL record, or other atomic modification of
144 : /// the timeline.
145 : ///
146 : /// This provides a transaction-like interface to perform a bunch
147 : /// of modifications atomically.
148 : ///
149 : /// To ingest a WAL record, call begin_modification(lsn) to get a
150 : /// DatadirModification object. Use the functions in the object to
151 : /// modify the repository state, updating all the pages and metadata
152 : /// that the WAL record affects. When you're done, call commit() to
153 : /// commit the changes.
154 : ///
155 : /// Lsn stored in modification is advanced by `ingest_record` and
156 : /// is used by `commit()` to update `last_record_lsn`.
157 : ///
158 : /// Calling commit() will flush all the changes and reset the state,
159 : /// so the `DatadirModification` struct can be reused to perform the next modification.
160 : ///
161 : /// Note that any pending modifications you make through the
162 : /// modification object won't be visible to calls to the 'get' and list
163 : /// functions of the timeline until you finish! And if you update the
164 : /// same page twice, the last update wins.
165 : ///
166 268372 : pub fn begin_modification(&self, lsn: Lsn) -> DatadirModification
167 268372 : where
168 268372 : Self: Sized,
169 268372 : {
170 268372 : DatadirModification {
171 268372 : tline: self,
172 268372 : pending_lsns: Vec::new(),
173 268372 : pending_updates: HashMap::new(),
174 268372 : pending_deletions: Vec::new(),
175 268372 : pending_nblocks: 0,
176 268372 : pending_directory_entries: Vec::new(),
177 268372 : lsn,
178 268372 : }
179 268372 : }
180 :
181 : //------------------------------------------------------------------------------
182 : // Public GET functions
183 : //------------------------------------------------------------------------------
184 :
185 : /// Look up given page version.
186 18384 : pub(crate) async fn get_rel_page_at_lsn(
187 18384 : &self,
188 18384 : tag: RelTag,
189 18384 : blknum: BlockNumber,
190 18384 : version: Version<'_>,
191 18384 : ctx: &RequestContext,
192 18384 : ) -> Result<Bytes, PageReconstructError> {
193 18384 : if tag.relnode == 0 {
194 0 : return Err(PageReconstructError::Other(
195 0 : RelationError::InvalidRelnode.into(),
196 0 : ));
197 18384 : }
198 :
199 18384 : let nblocks = self.get_rel_size(tag, version, ctx).await?;
200 18384 : if blknum >= nblocks {
201 0 : debug!(
202 0 : "read beyond EOF at {} blk {} at {}, size is {}: returning all-zeros page",
203 0 : tag,
204 0 : blknum,
205 0 : version.get_lsn(),
206 : nblocks
207 : );
208 0 : return Ok(ZERO_PAGE.clone());
209 18384 : }
210 18384 :
211 18384 : let key = rel_block_to_key(tag, blknum);
212 18384 : version.get(self, key, ctx).await
213 18384 : }
214 :
215 : // Get size of a database in blocks
216 0 : pub(crate) async fn get_db_size(
217 0 : &self,
218 0 : spcnode: Oid,
219 0 : dbnode: Oid,
220 0 : version: Version<'_>,
221 0 : ctx: &RequestContext,
222 0 : ) -> Result<usize, PageReconstructError> {
223 0 : let mut total_blocks = 0;
224 :
225 0 : let rels = self.list_rels(spcnode, dbnode, version, ctx).await?;
226 :
227 0 : for rel in rels {
228 0 : let n_blocks = self.get_rel_size(rel, version, ctx).await?;
229 0 : total_blocks += n_blocks as usize;
230 : }
231 0 : Ok(total_blocks)
232 0 : }
233 :
234 : /// Get size of a relation file
235 24434 : pub(crate) async fn get_rel_size(
236 24434 : &self,
237 24434 : tag: RelTag,
238 24434 : version: Version<'_>,
239 24434 : ctx: &RequestContext,
240 24434 : ) -> Result<BlockNumber, PageReconstructError> {
241 24434 : if tag.relnode == 0 {
242 0 : return Err(PageReconstructError::Other(
243 0 : RelationError::InvalidRelnode.into(),
244 0 : ));
245 24434 : }
246 :
247 24434 : if let Some(nblocks) = self.get_cached_rel_size(&tag, version.get_lsn()) {
248 19294 : return Ok(nblocks);
249 5140 : }
250 5140 :
251 5140 : if (tag.forknum == FSM_FORKNUM || tag.forknum == VISIBILITYMAP_FORKNUM)
252 0 : && !self.get_rel_exists(tag, version, ctx).await?
253 : {
254 : // FIXME: Postgres sometimes calls smgrcreate() to create
255 : // FSM, and smgrnblocks() on it immediately afterwards,
256 : // without extending it. Tolerate that by claiming that
257 : // any non-existent FSM fork has size 0.
258 0 : return Ok(0);
259 5140 : }
260 5140 :
261 5140 : let key = rel_size_to_key(tag);
262 5140 : let mut buf = version.get(self, key, ctx).await?;
263 5136 : let nblocks = buf.get_u32_le();
264 5136 :
265 5136 : self.update_cached_rel_size(tag, version.get_lsn(), nblocks);
266 5136 :
267 5136 : Ok(nblocks)
268 24434 : }
269 :
270 : /// Does relation exist?
271 6050 : pub(crate) async fn get_rel_exists(
272 6050 : &self,
273 6050 : tag: RelTag,
274 6050 : version: Version<'_>,
275 6050 : ctx: &RequestContext,
276 6050 : ) -> Result<bool, PageReconstructError> {
277 6050 : if tag.relnode == 0 {
278 0 : return Err(PageReconstructError::Other(
279 0 : RelationError::InvalidRelnode.into(),
280 0 : ));
281 6050 : }
282 :
283 : // first try to lookup relation in cache
284 6050 : if let Some(_nblocks) = self.get_cached_rel_size(&tag, version.get_lsn()) {
285 6032 : return Ok(true);
286 18 : }
287 18 : // fetch directory listing
288 18 : let key = rel_dir_to_key(tag.spcnode, tag.dbnode);
289 18 : let buf = version.get(self, key, ctx).await?;
290 :
291 18 : match RelDirectory::des(&buf).context("deserialization failure") {
292 18 : Ok(dir) => {
293 18 : let exists = dir.rels.contains(&(tag.relnode, tag.forknum));
294 18 : Ok(exists)
295 : }
296 0 : Err(e) => Err(PageReconstructError::from(e)),
297 : }
298 6050 : }
299 :
300 : /// Get a list of all existing relations in given tablespace and database.
301 : ///
302 : /// # Cancel-Safety
303 : ///
304 : /// This method is cancellation-safe.
305 0 : pub(crate) async fn list_rels(
306 0 : &self,
307 0 : spcnode: Oid,
308 0 : dbnode: Oid,
309 0 : version: Version<'_>,
310 0 : ctx: &RequestContext,
311 0 : ) -> Result<HashSet<RelTag>, PageReconstructError> {
312 0 : // fetch directory listing
313 0 : let key = rel_dir_to_key(spcnode, dbnode);
314 0 : let buf = version.get(self, key, ctx).await?;
315 :
316 0 : match RelDirectory::des(&buf).context("deserialization failure") {
317 0 : Ok(dir) => {
318 0 : let rels: HashSet<RelTag> =
319 0 : HashSet::from_iter(dir.rels.iter().map(|(relnode, forknum)| RelTag {
320 0 : spcnode,
321 0 : dbnode,
322 0 : relnode: *relnode,
323 0 : forknum: *forknum,
324 0 : }));
325 0 :
326 0 : Ok(rels)
327 : }
328 0 : Err(e) => Err(PageReconstructError::from(e)),
329 : }
330 0 : }
331 :
332 : /// Get the whole SLRU segment
333 0 : pub(crate) async fn get_slru_segment(
334 0 : &self,
335 0 : kind: SlruKind,
336 0 : segno: u32,
337 0 : lsn: Lsn,
338 0 : ctx: &RequestContext,
339 0 : ) -> Result<Bytes, PageReconstructError> {
340 0 : let n_blocks = self
341 0 : .get_slru_segment_size(kind, segno, Version::Lsn(lsn), ctx)
342 0 : .await?;
343 0 : let mut segment = BytesMut::with_capacity(n_blocks as usize * BLCKSZ as usize);
344 0 : for blkno in 0..n_blocks {
345 0 : let block = self
346 0 : .get_slru_page_at_lsn(kind, segno, blkno, lsn, ctx)
347 0 : .await?;
348 0 : segment.extend_from_slice(&block[..BLCKSZ as usize]);
349 : }
350 0 : Ok(segment.freeze())
351 0 : }
352 :
353 : /// Look up given SLRU page version.
354 0 : pub(crate) async fn get_slru_page_at_lsn(
355 0 : &self,
356 0 : kind: SlruKind,
357 0 : segno: u32,
358 0 : blknum: BlockNumber,
359 0 : lsn: Lsn,
360 0 : ctx: &RequestContext,
361 0 : ) -> Result<Bytes, PageReconstructError> {
362 0 : let key = slru_block_to_key(kind, segno, blknum);
363 0 : self.get(key, lsn, ctx).await
364 0 : }
365 :
366 : /// Get size of an SLRU segment
367 0 : pub(crate) async fn get_slru_segment_size(
368 0 : &self,
369 0 : kind: SlruKind,
370 0 : segno: u32,
371 0 : version: Version<'_>,
372 0 : ctx: &RequestContext,
373 0 : ) -> Result<BlockNumber, PageReconstructError> {
374 0 : let key = slru_segment_size_to_key(kind, segno);
375 0 : let mut buf = version.get(self, key, ctx).await?;
376 0 : Ok(buf.get_u32_le())
377 0 : }
378 :
379 : /// Get size of an SLRU segment
380 0 : pub(crate) async fn get_slru_segment_exists(
381 0 : &self,
382 0 : kind: SlruKind,
383 0 : segno: u32,
384 0 : version: Version<'_>,
385 0 : ctx: &RequestContext,
386 0 : ) -> Result<bool, PageReconstructError> {
387 0 : // fetch directory listing
388 0 : let key = slru_dir_to_key(kind);
389 0 : let buf = version.get(self, key, ctx).await?;
390 :
391 0 : match SlruSegmentDirectory::des(&buf).context("deserialization failure") {
392 0 : Ok(dir) => {
393 0 : let exists = dir.segments.contains(&segno);
394 0 : Ok(exists)
395 : }
396 0 : Err(e) => Err(PageReconstructError::from(e)),
397 : }
398 0 : }
399 :
400 : /// Locate LSN, such that all transactions that committed before
401 : /// 'search_timestamp' are visible, but nothing newer is.
402 : ///
403 : /// This is not exact. Commit timestamps are not guaranteed to be ordered,
404 : /// so it's not well defined which LSN you get if there were multiple commits
405 : /// "in flight" at that point in time.
406 : ///
407 0 : pub(crate) async fn find_lsn_for_timestamp(
408 0 : &self,
409 0 : search_timestamp: TimestampTz,
410 0 : cancel: &CancellationToken,
411 0 : ctx: &RequestContext,
412 0 : ) -> Result<LsnForTimestamp, PageReconstructError> {
413 : pausable_failpoint!("find-lsn-for-timestamp-pausable");
414 :
415 0 : let gc_cutoff_lsn_guard = self.get_latest_gc_cutoff_lsn();
416 0 : // We use this method to figure out the branching LSN for the new branch, but the
417 0 : // GC cutoff could be before the branching point and we cannot create a new branch
418 0 : // with LSN < `ancestor_lsn`. Thus, pick the maximum of these two to be
419 0 : // on the safe side.
420 0 : let min_lsn = std::cmp::max(*gc_cutoff_lsn_guard, self.get_ancestor_lsn());
421 0 : let max_lsn = self.get_last_record_lsn();
422 0 :
423 0 : // LSNs are always 8-byte aligned. low/mid/high represent the
424 0 : // LSN divided by 8.
425 0 : let mut low = min_lsn.0 / 8;
426 0 : let mut high = max_lsn.0 / 8 + 1;
427 0 :
428 0 : let mut found_smaller = false;
429 0 : let mut found_larger = false;
430 :
431 0 : while low < high {
432 0 : if cancel.is_cancelled() {
433 0 : return Err(PageReconstructError::Cancelled);
434 0 : }
435 0 : // cannot overflow, high and low are both smaller than u64::MAX / 2
436 0 : let mid = (high + low) / 2;
437 :
438 0 : let cmp = self
439 0 : .is_latest_commit_timestamp_ge_than(
440 0 : search_timestamp,
441 0 : Lsn(mid * 8),
442 0 : &mut found_smaller,
443 0 : &mut found_larger,
444 0 : ctx,
445 0 : )
446 0 : .await?;
447 :
448 0 : if cmp {
449 0 : high = mid;
450 0 : } else {
451 0 : low = mid + 1;
452 0 : }
453 : }
454 : // If `found_smaller == true`, `low = t + 1` where `t` is the target LSN,
455 : // so the LSN of the last commit record before or at `search_timestamp`.
456 : // Remove one from `low` to get `t`.
457 : //
458 : // FIXME: it would be better to get the LSN of the previous commit.
459 : // Otherwise, if you restore to the returned LSN, the database will
460 : // include physical changes from later commits that will be marked
461 : // as aborted, and will need to be vacuumed away.
462 0 : let commit_lsn = Lsn((low - 1) * 8);
463 0 : match (found_smaller, found_larger) {
464 : (false, false) => {
465 : // This can happen if no commit records have been processed yet, e.g.
466 : // just after importing a cluster.
467 0 : Ok(LsnForTimestamp::NoData(min_lsn))
468 : }
469 : (false, true) => {
470 : // Didn't find any commit timestamps smaller than the request
471 0 : Ok(LsnForTimestamp::Past(min_lsn))
472 : }
473 0 : (true, _) if commit_lsn < min_lsn => {
474 0 : // the search above did set found_smaller to true but it never increased the lsn.
475 0 : // Then, low is still the old min_lsn, and the subtraction above gave a value
476 0 : // below the min_lsn. We should never do that.
477 0 : Ok(LsnForTimestamp::Past(min_lsn))
478 : }
479 : (true, false) => {
480 : // Only found commits with timestamps smaller than the request.
481 : // It's still a valid case for branch creation, return it.
482 : // And `update_gc_info()` ignores LSN for a `LsnForTimestamp::Future`
483 : // case, anyway.
484 0 : Ok(LsnForTimestamp::Future(commit_lsn))
485 : }
486 0 : (true, true) => Ok(LsnForTimestamp::Present(commit_lsn)),
487 : }
488 0 : }
489 :
490 : /// Subroutine of find_lsn_for_timestamp(). Returns true, if there are any
491 : /// commits that committed after 'search_timestamp', at LSN 'probe_lsn'.
492 : ///
493 : /// Additionally, sets 'found_smaller'/'found_Larger, if encounters any commits
494 : /// with a smaller/larger timestamp.
495 : ///
496 0 : pub(crate) async fn is_latest_commit_timestamp_ge_than(
497 0 : &self,
498 0 : search_timestamp: TimestampTz,
499 0 : probe_lsn: Lsn,
500 0 : found_smaller: &mut bool,
501 0 : found_larger: &mut bool,
502 0 : ctx: &RequestContext,
503 0 : ) -> Result<bool, PageReconstructError> {
504 0 : self.map_all_timestamps(probe_lsn, ctx, |timestamp| {
505 0 : if timestamp >= search_timestamp {
506 0 : *found_larger = true;
507 0 : return ControlFlow::Break(true);
508 0 : } else {
509 0 : *found_smaller = true;
510 0 : }
511 0 : ControlFlow::Continue(())
512 0 : })
513 0 : .await
514 0 : }
515 :
516 : /// Obtain the possible timestamp range for the given lsn.
517 : ///
518 : /// If the lsn has no timestamps, returns None. returns `(min, max, median)` if it has timestamps.
519 0 : pub(crate) async fn get_timestamp_for_lsn(
520 0 : &self,
521 0 : probe_lsn: Lsn,
522 0 : ctx: &RequestContext,
523 0 : ) -> Result<Option<TimestampTz>, PageReconstructError> {
524 0 : let mut max: Option<TimestampTz> = None;
525 0 : self.map_all_timestamps::<()>(probe_lsn, ctx, |timestamp| {
526 0 : if let Some(max_prev) = max {
527 0 : max = Some(max_prev.max(timestamp));
528 0 : } else {
529 0 : max = Some(timestamp);
530 0 : }
531 0 : ControlFlow::Continue(())
532 0 : })
533 0 : .await?;
534 :
535 0 : Ok(max)
536 0 : }
537 :
538 : /// Runs the given function on all the timestamps for a given lsn
539 : ///
540 : /// The return value is either given by the closure, or set to the `Default`
541 : /// impl's output.
542 0 : async fn map_all_timestamps<T: Default>(
543 0 : &self,
544 0 : probe_lsn: Lsn,
545 0 : ctx: &RequestContext,
546 0 : mut f: impl FnMut(TimestampTz) -> ControlFlow<T>,
547 0 : ) -> Result<T, PageReconstructError> {
548 0 : for segno in self
549 0 : .list_slru_segments(SlruKind::Clog, Version::Lsn(probe_lsn), ctx)
550 0 : .await?
551 : {
552 0 : let nblocks = self
553 0 : .get_slru_segment_size(SlruKind::Clog, segno, Version::Lsn(probe_lsn), ctx)
554 0 : .await?;
555 0 : for blknum in (0..nblocks).rev() {
556 0 : let clog_page = self
557 0 : .get_slru_page_at_lsn(SlruKind::Clog, segno, blknum, probe_lsn, ctx)
558 0 : .await?;
559 :
560 0 : if clog_page.len() == BLCKSZ as usize + 8 {
561 0 : let mut timestamp_bytes = [0u8; 8];
562 0 : timestamp_bytes.copy_from_slice(&clog_page[BLCKSZ as usize..]);
563 0 : let timestamp = TimestampTz::from_be_bytes(timestamp_bytes);
564 0 :
565 0 : match f(timestamp) {
566 0 : ControlFlow::Break(b) => return Ok(b),
567 0 : ControlFlow::Continue(()) => (),
568 : }
569 0 : }
570 : }
571 : }
572 0 : Ok(Default::default())
573 0 : }
574 :
575 0 : pub(crate) async fn get_slru_keyspace(
576 0 : &self,
577 0 : version: Version<'_>,
578 0 : ctx: &RequestContext,
579 0 : ) -> Result<KeySpace, PageReconstructError> {
580 0 : let mut accum = KeySpaceAccum::new();
581 :
582 0 : for kind in SlruKind::iter() {
583 0 : let mut segments: Vec<u32> = self
584 0 : .list_slru_segments(kind, version, ctx)
585 0 : .await?
586 0 : .into_iter()
587 0 : .collect();
588 0 : segments.sort_unstable();
589 :
590 0 : for seg in segments {
591 0 : let block_count = self.get_slru_segment_size(kind, seg, version, ctx).await?;
592 :
593 0 : accum.add_range(
594 0 : slru_block_to_key(kind, seg, 0)..slru_block_to_key(kind, seg, block_count),
595 0 : );
596 : }
597 : }
598 :
599 0 : Ok(accum.to_keyspace())
600 0 : }
601 :
602 : /// Get a list of SLRU segments
603 0 : pub(crate) async fn list_slru_segments(
604 0 : &self,
605 0 : kind: SlruKind,
606 0 : version: Version<'_>,
607 0 : ctx: &RequestContext,
608 0 : ) -> Result<HashSet<u32>, PageReconstructError> {
609 0 : // fetch directory entry
610 0 : let key = slru_dir_to_key(kind);
611 :
612 0 : let buf = version.get(self, key, ctx).await?;
613 0 : match SlruSegmentDirectory::des(&buf).context("deserialization failure") {
614 0 : Ok(dir) => Ok(dir.segments),
615 0 : Err(e) => Err(PageReconstructError::from(e)),
616 : }
617 0 : }
618 :
619 0 : pub(crate) async fn get_relmap_file(
620 0 : &self,
621 0 : spcnode: Oid,
622 0 : dbnode: Oid,
623 0 : version: Version<'_>,
624 0 : ctx: &RequestContext,
625 0 : ) -> Result<Bytes, PageReconstructError> {
626 0 : let key = relmap_file_key(spcnode, dbnode);
627 :
628 0 : let buf = version.get(self, key, ctx).await?;
629 0 : Ok(buf)
630 0 : }
631 :
632 268 : pub(crate) async fn list_dbdirs(
633 268 : &self,
634 268 : lsn: Lsn,
635 268 : ctx: &RequestContext,
636 268 : ) -> Result<HashMap<(Oid, Oid), bool>, PageReconstructError> {
637 : // fetch directory entry
638 2446 : let buf = self.get(DBDIR_KEY, lsn, ctx).await?;
639 :
640 268 : match DbDirectory::des(&buf).context("deserialization failure") {
641 268 : Ok(dir) => Ok(dir.dbdirs),
642 0 : Err(e) => Err(PageReconstructError::from(e)),
643 : }
644 268 : }
645 :
646 0 : pub(crate) async fn get_twophase_file(
647 0 : &self,
648 0 : xid: TransactionId,
649 0 : lsn: Lsn,
650 0 : ctx: &RequestContext,
651 0 : ) -> Result<Bytes, PageReconstructError> {
652 0 : let key = twophase_file_key(xid);
653 0 : let buf = self.get(key, lsn, ctx).await?;
654 0 : Ok(buf)
655 0 : }
656 :
657 2 : pub(crate) async fn list_twophase_files(
658 2 : &self,
659 2 : lsn: Lsn,
660 2 : ctx: &RequestContext,
661 2 : ) -> Result<HashSet<TransactionId>, PageReconstructError> {
662 : // fetch directory entry
663 2 : let buf = self.get(TWOPHASEDIR_KEY, lsn, ctx).await?;
664 :
665 2 : match TwoPhaseDirectory::des(&buf).context("deserialization failure") {
666 2 : Ok(dir) => Ok(dir.xids),
667 0 : Err(e) => Err(PageReconstructError::from(e)),
668 : }
669 2 : }
670 :
671 0 : pub(crate) async fn get_control_file(
672 0 : &self,
673 0 : lsn: Lsn,
674 0 : ctx: &RequestContext,
675 0 : ) -> Result<Bytes, PageReconstructError> {
676 0 : self.get(CONTROLFILE_KEY, lsn, ctx).await
677 0 : }
678 :
679 12 : pub(crate) async fn get_checkpoint(
680 12 : &self,
681 12 : lsn: Lsn,
682 12 : ctx: &RequestContext,
683 12 : ) -> Result<Bytes, PageReconstructError> {
684 12 : self.get(CHECKPOINT_KEY, lsn, ctx).await
685 12 : }
686 :
687 28 : async fn list_aux_files_v1(
688 28 : &self,
689 28 : lsn: Lsn,
690 28 : ctx: &RequestContext,
691 28 : ) -> Result<HashMap<String, Bytes>, PageReconstructError> {
692 28 : match self.get(AUX_FILES_KEY, lsn, ctx).await {
693 22 : Ok(buf) => match AuxFilesDirectory::des(&buf).context("deserialization failure") {
694 22 : Ok(dir) => Ok(dir.files),
695 0 : Err(e) => Err(PageReconstructError::from(e)),
696 : },
697 6 : Err(e) => {
698 6 : // This is expected: historical databases do not have the key.
699 6 : debug!("Failed to get info about AUX files: {}", e);
700 6 : Ok(HashMap::new())
701 : }
702 : }
703 28 : }
704 :
705 12 : async fn list_aux_files_v2(
706 12 : &self,
707 12 : lsn: Lsn,
708 12 : ctx: &RequestContext,
709 12 : ) -> Result<HashMap<String, Bytes>, PageReconstructError> {
710 12 : let kv = self
711 12 : .scan(KeySpace::single(Key::metadata_aux_key_range()), lsn, ctx)
712 0 : .await
713 12 : .context("scan")?;
714 12 : let mut result = HashMap::new();
715 12 : let mut sz = 0;
716 30 : for (_, v) in kv {
717 18 : let v = v.context("get value")?;
718 18 : let v = aux_file::decode_file_value_bytes(&v).context("value decode")?;
719 36 : for (fname, content) in v {
720 18 : sz += fname.len();
721 18 : sz += content.len();
722 18 : result.insert(fname, content);
723 18 : }
724 : }
725 12 : self.aux_file_size_estimator.on_initial(sz);
726 12 : Ok(result)
727 12 : }
728 :
729 0 : pub(crate) async fn trigger_aux_file_size_computation(
730 0 : &self,
731 0 : lsn: Lsn,
732 0 : ctx: &RequestContext,
733 0 : ) -> Result<(), PageReconstructError> {
734 0 : let current_policy = self.last_aux_file_policy.load();
735 0 : if let Some(AuxFilePolicy::V2) | Some(AuxFilePolicy::CrossValidation) = current_policy {
736 0 : self.list_aux_files_v2(lsn, ctx).await?;
737 0 : }
738 0 : Ok(())
739 0 : }
740 :
741 26 : pub(crate) async fn list_aux_files(
742 26 : &self,
743 26 : lsn: Lsn,
744 26 : ctx: &RequestContext,
745 26 : ) -> Result<HashMap<String, Bytes>, PageReconstructError> {
746 26 : let current_policy = self.last_aux_file_policy.load();
747 26 : match current_policy {
748 14 : Some(AuxFilePolicy::V1) | None => self.list_aux_files_v1(lsn, ctx).await,
749 10 : Some(AuxFilePolicy::V2) => self.list_aux_files_v2(lsn, ctx).await,
750 : Some(AuxFilePolicy::CrossValidation) => {
751 2 : let v1_result = self.list_aux_files_v1(lsn, ctx).await;
752 2 : let v2_result = self.list_aux_files_v2(lsn, ctx).await;
753 2 : match (v1_result, v2_result) {
754 2 : (Ok(v1), Ok(v2)) => {
755 2 : if v1 != v2 {
756 0 : tracing::error!(
757 0 : "unmatched aux file v1 v2 result:\nv1 {v1:?}\nv2 {v2:?}"
758 : );
759 0 : return Err(PageReconstructError::Other(anyhow::anyhow!(
760 0 : "unmatched aux file v1 v2 result"
761 0 : )));
762 2 : }
763 2 : Ok(v1)
764 : }
765 0 : (Ok(_), Err(v2)) => {
766 0 : tracing::error!("aux file v1 returns Ok while aux file v2 returns an err");
767 0 : Err(v2)
768 : }
769 0 : (Err(v1), Ok(_)) => {
770 0 : tracing::error!("aux file v2 returns Ok while aux file v1 returns an err");
771 0 : Err(v1)
772 : }
773 0 : (Err(_), Err(v2)) => Err(v2),
774 : }
775 : }
776 : }
777 26 : }
778 :
779 0 : pub(crate) async fn get_replorigins(
780 0 : &self,
781 0 : lsn: Lsn,
782 0 : ctx: &RequestContext,
783 0 : ) -> Result<HashMap<RepOriginId, Lsn>, PageReconstructError> {
784 0 : let kv = self
785 0 : .scan(KeySpace::single(repl_origin_key_range()), lsn, ctx)
786 0 : .await
787 0 : .context("scan")?;
788 0 : let mut result = HashMap::new();
789 0 : for (k, v) in kv {
790 0 : let v = v.context("get value")?;
791 0 : let origin_id = k.field6 as RepOriginId;
792 0 : let origin_lsn = Lsn::des(&v).unwrap();
793 0 : if origin_lsn != Lsn::INVALID {
794 0 : result.insert(origin_id, origin_lsn);
795 0 : }
796 : }
797 0 : Ok(result)
798 0 : }
799 :
800 : /// Does the same as get_current_logical_size but counted on demand.
801 : /// Used to initialize the logical size tracking on startup.
802 : ///
803 : /// Only relation blocks are counted currently. That excludes metadata,
804 : /// SLRUs, twophase files etc.
805 : ///
806 : /// # Cancel-Safety
807 : ///
808 : /// This method is cancellation-safe.
809 0 : pub(crate) async fn get_current_logical_size_non_incremental(
810 0 : &self,
811 0 : lsn: Lsn,
812 0 : ctx: &RequestContext,
813 0 : ) -> Result<u64, CalculateLogicalSizeError> {
814 0 : debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id();
815 :
816 : // Fetch list of database dirs and iterate them
817 0 : let buf = self.get(DBDIR_KEY, lsn, ctx).await?;
818 0 : let dbdir = DbDirectory::des(&buf)?;
819 :
820 0 : let mut total_size: u64 = 0;
821 0 : for (spcnode, dbnode) in dbdir.dbdirs.keys() {
822 0 : for rel in self
823 0 : .list_rels(*spcnode, *dbnode, Version::Lsn(lsn), ctx)
824 0 : .await?
825 : {
826 0 : if self.cancel.is_cancelled() {
827 0 : return Err(CalculateLogicalSizeError::Cancelled);
828 0 : }
829 0 : let relsize_key = rel_size_to_key(rel);
830 0 : let mut buf = self.get(relsize_key, lsn, ctx).await?;
831 0 : let relsize = buf.get_u32_le();
832 0 :
833 0 : total_size += relsize as u64;
834 : }
835 : }
836 0 : Ok(total_size * BLCKSZ as u64)
837 0 : }
838 :
839 : ///
840 : /// Get a KeySpace that covers all the Keys that are in use at the given LSN.
841 : /// Anything that's not listed maybe removed from the underlying storage (from
842 : /// that LSN forwards).
843 : ///
844 : /// The return value is (dense keyspace, sparse keyspace).
845 268 : pub(crate) async fn collect_keyspace(
846 268 : &self,
847 268 : lsn: Lsn,
848 268 : ctx: &RequestContext,
849 268 : ) -> Result<(KeySpace, SparseKeySpace), CollectKeySpaceError> {
850 268 : // Iterate through key ranges, greedily packing them into partitions
851 268 : let mut result = KeySpaceAccum::new();
852 268 :
853 268 : // The dbdir metadata always exists
854 268 : result.add_key(DBDIR_KEY);
855 :
856 : // Fetch list of database dirs and iterate them
857 2446 : let dbdir = self.list_dbdirs(lsn, ctx).await?;
858 268 : let mut dbs: Vec<((Oid, Oid), bool)> = dbdir.into_iter().collect();
859 268 :
860 268 : dbs.sort_unstable_by(|(k_a, _), (k_b, _)| k_a.cmp(k_b));
861 268 : for ((spcnode, dbnode), has_relmap_file) in dbs {
862 0 : if has_relmap_file {
863 0 : result.add_key(relmap_file_key(spcnode, dbnode));
864 0 : }
865 0 : result.add_key(rel_dir_to_key(spcnode, dbnode));
866 :
867 0 : let mut rels: Vec<RelTag> = self
868 0 : .list_rels(spcnode, dbnode, Version::Lsn(lsn), ctx)
869 0 : .await?
870 0 : .into_iter()
871 0 : .collect();
872 0 : rels.sort_unstable();
873 0 : for rel in rels {
874 0 : let relsize_key = rel_size_to_key(rel);
875 0 : let mut buf = self.get(relsize_key, lsn, ctx).await?;
876 0 : let relsize = buf.get_u32_le();
877 0 :
878 0 : result.add_range(rel_block_to_key(rel, 0)..rel_block_to_key(rel, relsize));
879 0 : result.add_key(relsize_key);
880 : }
881 : }
882 :
883 : // Iterate SLRUs next
884 804 : for kind in [
885 268 : SlruKind::Clog,
886 268 : SlruKind::MultiXactMembers,
887 268 : SlruKind::MultiXactOffsets,
888 : ] {
889 804 : let slrudir_key = slru_dir_to_key(kind);
890 804 : result.add_key(slrudir_key);
891 8321 : let buf = self.get(slrudir_key, lsn, ctx).await?;
892 804 : let dir = SlruSegmentDirectory::des(&buf)?;
893 804 : let mut segments: Vec<u32> = dir.segments.iter().cloned().collect();
894 804 : segments.sort_unstable();
895 804 : for segno in segments {
896 0 : let segsize_key = slru_segment_size_to_key(kind, segno);
897 0 : let mut buf = self.get(segsize_key, lsn, ctx).await?;
898 0 : let segsize = buf.get_u32_le();
899 0 :
900 0 : result.add_range(
901 0 : slru_block_to_key(kind, segno, 0)..slru_block_to_key(kind, segno, segsize),
902 0 : );
903 0 : result.add_key(segsize_key);
904 : }
905 : }
906 :
907 : // Then pg_twophase
908 268 : result.add_key(TWOPHASEDIR_KEY);
909 3164 : let buf = self.get(TWOPHASEDIR_KEY, lsn, ctx).await?;
910 268 : let twophase_dir = TwoPhaseDirectory::des(&buf)?;
911 268 : let mut xids: Vec<TransactionId> = twophase_dir.xids.iter().cloned().collect();
912 268 : xids.sort_unstable();
913 268 : for xid in xids {
914 0 : result.add_key(twophase_file_key(xid));
915 0 : }
916 :
917 268 : result.add_key(CONTROLFILE_KEY);
918 268 : result.add_key(CHECKPOINT_KEY);
919 268 : if self.get(AUX_FILES_KEY, lsn, ctx).await.is_ok() {
920 164 : result.add_key(AUX_FILES_KEY);
921 164 : }
922 :
923 : // Add extra keyspaces in the test cases. Some test cases write keys into the storage without
924 : // creating directory keys. These test cases will add such keyspaces into `extra_test_dense_keyspace`
925 : // and the keys will not be garbage-colllected.
926 : #[cfg(test)]
927 : {
928 268 : let guard = self.extra_test_dense_keyspace.load();
929 268 : for kr in &guard.ranges {
930 0 : result.add_range(kr.clone());
931 0 : }
932 : }
933 :
934 268 : let dense_keyspace = result.to_keyspace();
935 268 : let sparse_keyspace = SparseKeySpace(KeySpace {
936 268 : ranges: vec![Key::metadata_aux_key_range(), repl_origin_key_range()],
937 268 : });
938 268 :
939 268 : if cfg!(debug_assertions) {
940 : // Verify if the sparse keyspaces are ordered and non-overlapping.
941 :
942 : // We do not use KeySpaceAccum for sparse_keyspace because we want to ensure each
943 : // category of sparse keys are split into their own image/delta files. If there
944 : // are overlapping keyspaces, they will be automatically merged by keyspace accum,
945 : // and we want the developer to keep the keyspaces separated.
946 :
947 268 : let ranges = &sparse_keyspace.0.ranges;
948 :
949 : // TODO: use a single overlaps_with across the codebase
950 268 : fn overlaps_with<T: Ord>(a: &Range<T>, b: &Range<T>) -> bool {
951 268 : !(a.end <= b.start || b.end <= a.start)
952 268 : }
953 536 : for i in 0..ranges.len() {
954 536 : for j in 0..i {
955 268 : if overlaps_with(&ranges[i], &ranges[j]) {
956 0 : panic!(
957 0 : "overlapping sparse keyspace: {}..{} and {}..{}",
958 0 : ranges[i].start, ranges[i].end, ranges[j].start, ranges[j].end
959 0 : );
960 268 : }
961 : }
962 : }
963 268 : for i in 1..ranges.len() {
964 268 : assert!(
965 268 : ranges[i - 1].end <= ranges[i].start,
966 0 : "unordered sparse keyspace: {}..{} and {}..{}",
967 0 : ranges[i - 1].start,
968 0 : ranges[i - 1].end,
969 0 : ranges[i].start,
970 0 : ranges[i].end
971 : );
972 : }
973 0 : }
974 :
975 268 : Ok((dense_keyspace, sparse_keyspace))
976 268 : }
977 :
978 : /// Get cached size of relation if it not updated after specified LSN
979 448540 : pub fn get_cached_rel_size(&self, tag: &RelTag, lsn: Lsn) -> Option<BlockNumber> {
980 448540 : let rel_size_cache = self.rel_size_cache.read().unwrap();
981 448540 : if let Some((cached_lsn, nblocks)) = rel_size_cache.map.get(tag) {
982 448518 : if lsn >= *cached_lsn {
983 443372 : return Some(*nblocks);
984 5146 : }
985 22 : }
986 5168 : None
987 448540 : }
988 :
989 : /// Update cached relation size if there is no more recent update
990 5136 : pub fn update_cached_rel_size(&self, tag: RelTag, lsn: Lsn, nblocks: BlockNumber) {
991 5136 : let mut rel_size_cache = self.rel_size_cache.write().unwrap();
992 5136 :
993 5136 : if lsn < rel_size_cache.complete_as_of {
994 : // Do not cache old values. It's safe to cache the size on read, as long as
995 : // the read was at an LSN since we started the WAL ingestion. Reasoning: we
996 : // never evict values from the cache, so if the relation size changed after
997 : // 'lsn', the new value is already in the cache.
998 0 : return;
999 5136 : }
1000 5136 :
1001 5136 : match rel_size_cache.map.entry(tag) {
1002 5136 : hash_map::Entry::Occupied(mut entry) => {
1003 5136 : let cached_lsn = entry.get_mut();
1004 5136 : if lsn >= cached_lsn.0 {
1005 0 : *cached_lsn = (lsn, nblocks);
1006 5136 : }
1007 : }
1008 0 : hash_map::Entry::Vacant(entry) => {
1009 0 : entry.insert((lsn, nblocks));
1010 0 : }
1011 : }
1012 5136 : }
1013 :
1014 : /// Store cached relation size
1015 288732 : pub fn set_cached_rel_size(&self, tag: RelTag, lsn: Lsn, nblocks: BlockNumber) {
1016 288732 : let mut rel_size_cache = self.rel_size_cache.write().unwrap();
1017 288732 : rel_size_cache.map.insert(tag, (lsn, nblocks));
1018 288732 : }
1019 :
1020 : /// Remove cached relation size
1021 2 : pub fn remove_cached_rel_size(&self, tag: &RelTag) {
1022 2 : let mut rel_size_cache = self.rel_size_cache.write().unwrap();
1023 2 : rel_size_cache.map.remove(tag);
1024 2 : }
1025 : }
1026 :
1027 : /// DatadirModification represents an operation to ingest an atomic set of
1028 : /// updates to the repository. It is created by the 'begin_record'
1029 : /// function. It is called for each WAL record, so that all the modifications
1030 : /// by a one WAL record appear atomic.
1031 : pub struct DatadirModification<'a> {
1032 : /// The timeline this modification applies to. You can access this to
1033 : /// read the state, but note that any pending updates are *not* reflected
1034 : /// in the state in 'tline' yet.
1035 : pub tline: &'a Timeline,
1036 :
1037 : /// Current LSN of the modification
1038 : lsn: Lsn,
1039 :
1040 : // The modifications are not applied directly to the underlying key-value store.
1041 : // The put-functions add the modifications here, and they are flushed to the
1042 : // underlying key-value store by the 'finish' function.
1043 : pending_lsns: Vec<Lsn>,
1044 : pending_updates: HashMap<Key, Vec<(Lsn, Value)>>,
1045 : pending_deletions: Vec<(Range<Key>, Lsn)>,
1046 : pending_nblocks: i64,
1047 :
1048 : /// For special "directory" keys that store key-value maps, track the size of the map
1049 : /// if it was updated in this modification.
1050 : pending_directory_entries: Vec<(DirectoryKind, usize)>,
1051 : }
1052 :
1053 : impl<'a> DatadirModification<'a> {
1054 : /// Get the current lsn
1055 418056 : pub(crate) fn get_lsn(&self) -> Lsn {
1056 418056 : self.lsn
1057 418056 : }
1058 :
1059 : /// Set the current lsn
1060 145858 : pub(crate) fn set_lsn(&mut self, lsn: Lsn) -> anyhow::Result<()> {
1061 145858 : ensure!(
1062 145858 : lsn >= self.lsn,
1063 0 : "setting an older lsn {} than {} is not allowed",
1064 : lsn,
1065 : self.lsn
1066 : );
1067 145858 : if lsn > self.lsn {
1068 145858 : self.pending_lsns.push(self.lsn);
1069 145858 : self.lsn = lsn;
1070 145858 : }
1071 145858 : Ok(())
1072 145858 : }
1073 :
1074 : /// Initialize a completely new repository.
1075 : ///
1076 : /// This inserts the directory metadata entries that are assumed to
1077 : /// always exist.
1078 154 : pub fn init_empty(&mut self) -> anyhow::Result<()> {
1079 154 : let buf = DbDirectory::ser(&DbDirectory {
1080 154 : dbdirs: HashMap::new(),
1081 154 : })?;
1082 154 : self.pending_directory_entries.push((DirectoryKind::Db, 0));
1083 154 : self.put(DBDIR_KEY, Value::Image(buf.into()));
1084 154 :
1085 154 : // Create AuxFilesDirectory
1086 154 : self.init_aux_dir()?;
1087 :
1088 154 : let buf = TwoPhaseDirectory::ser(&TwoPhaseDirectory {
1089 154 : xids: HashSet::new(),
1090 154 : })?;
1091 154 : self.pending_directory_entries
1092 154 : .push((DirectoryKind::TwoPhase, 0));
1093 154 : self.put(TWOPHASEDIR_KEY, Value::Image(buf.into()));
1094 :
1095 154 : let buf: Bytes = SlruSegmentDirectory::ser(&SlruSegmentDirectory::default())?.into();
1096 154 : let empty_dir = Value::Image(buf);
1097 154 : self.put(slru_dir_to_key(SlruKind::Clog), empty_dir.clone());
1098 154 : self.pending_directory_entries
1099 154 : .push((DirectoryKind::SlruSegment(SlruKind::Clog), 0));
1100 154 : self.put(
1101 154 : slru_dir_to_key(SlruKind::MultiXactMembers),
1102 154 : empty_dir.clone(),
1103 154 : );
1104 154 : self.pending_directory_entries
1105 154 : .push((DirectoryKind::SlruSegment(SlruKind::Clog), 0));
1106 154 : self.put(slru_dir_to_key(SlruKind::MultiXactOffsets), empty_dir);
1107 154 : self.pending_directory_entries
1108 154 : .push((DirectoryKind::SlruSegment(SlruKind::MultiXactOffsets), 0));
1109 154 :
1110 154 : Ok(())
1111 154 : }
1112 :
1113 : #[cfg(test)]
1114 152 : pub fn init_empty_test_timeline(&mut self) -> anyhow::Result<()> {
1115 152 : self.init_empty()?;
1116 152 : self.put_control_file(bytes::Bytes::from_static(
1117 152 : b"control_file contents do not matter",
1118 152 : ))
1119 152 : .context("put_control_file")?;
1120 152 : self.put_checkpoint(bytes::Bytes::from_static(
1121 152 : b"checkpoint_file contents do not matter",
1122 152 : ))
1123 152 : .context("put_checkpoint_file")?;
1124 152 : Ok(())
1125 152 : }
1126 :
1127 : /// Put a new page version that can be constructed from a WAL record
1128 : ///
1129 : /// NOTE: this will *not* implicitly extend the relation, if the page is beyond the
1130 : /// current end-of-file. It's up to the caller to check that the relation size
1131 : /// matches the blocks inserted!
1132 145630 : pub fn put_rel_wal_record(
1133 145630 : &mut self,
1134 145630 : rel: RelTag,
1135 145630 : blknum: BlockNumber,
1136 145630 : rec: NeonWalRecord,
1137 145630 : ) -> anyhow::Result<()> {
1138 145630 : anyhow::ensure!(rel.relnode != 0, RelationError::InvalidRelnode);
1139 145630 : self.put(rel_block_to_key(rel, blknum), Value::WalRecord(rec));
1140 145630 : Ok(())
1141 145630 : }
1142 :
1143 : // Same, but for an SLRU.
1144 8 : pub fn put_slru_wal_record(
1145 8 : &mut self,
1146 8 : kind: SlruKind,
1147 8 : segno: u32,
1148 8 : blknum: BlockNumber,
1149 8 : rec: NeonWalRecord,
1150 8 : ) -> anyhow::Result<()> {
1151 8 : self.put(
1152 8 : slru_block_to_key(kind, segno, blknum),
1153 8 : Value::WalRecord(rec),
1154 8 : );
1155 8 : Ok(())
1156 8 : }
1157 :
1158 : /// Like put_wal_record, but with ready-made image of the page.
1159 280864 : pub fn put_rel_page_image(
1160 280864 : &mut self,
1161 280864 : rel: RelTag,
1162 280864 : blknum: BlockNumber,
1163 280864 : img: Bytes,
1164 280864 : ) -> anyhow::Result<()> {
1165 280864 : anyhow::ensure!(rel.relnode != 0, RelationError::InvalidRelnode);
1166 280864 : self.put(rel_block_to_key(rel, blknum), Value::Image(img));
1167 280864 : Ok(())
1168 280864 : }
1169 :
1170 6 : pub fn put_slru_page_image(
1171 6 : &mut self,
1172 6 : kind: SlruKind,
1173 6 : segno: u32,
1174 6 : blknum: BlockNumber,
1175 6 : img: Bytes,
1176 6 : ) -> anyhow::Result<()> {
1177 6 : self.put(slru_block_to_key(kind, segno, blknum), Value::Image(img));
1178 6 : Ok(())
1179 6 : }
1180 :
1181 : /// Store a relmapper file (pg_filenode.map) in the repository
1182 16 : pub async fn put_relmap_file(
1183 16 : &mut self,
1184 16 : spcnode: Oid,
1185 16 : dbnode: Oid,
1186 16 : img: Bytes,
1187 16 : ctx: &RequestContext,
1188 16 : ) -> anyhow::Result<()> {
1189 : // Add it to the directory (if it doesn't exist already)
1190 16 : let buf = self.get(DBDIR_KEY, ctx).await?;
1191 16 : let mut dbdir = DbDirectory::des(&buf)?;
1192 :
1193 16 : let r = dbdir.dbdirs.insert((spcnode, dbnode), true);
1194 16 : if r.is_none() || r == Some(false) {
1195 : // The dbdir entry didn't exist, or it contained a
1196 : // 'false'. The 'insert' call already updated it with
1197 : // 'true', now write the updated 'dbdirs' map back.
1198 16 : let buf = DbDirectory::ser(&dbdir)?;
1199 16 : self.put(DBDIR_KEY, Value::Image(buf.into()));
1200 16 :
1201 16 : // Create AuxFilesDirectory as well
1202 16 : self.init_aux_dir()?;
1203 0 : }
1204 16 : if r.is_none() {
1205 8 : // Create RelDirectory
1206 8 : let buf = RelDirectory::ser(&RelDirectory {
1207 8 : rels: HashSet::new(),
1208 8 : })?;
1209 8 : self.pending_directory_entries.push((DirectoryKind::Rel, 0));
1210 8 : self.put(
1211 8 : rel_dir_to_key(spcnode, dbnode),
1212 8 : Value::Image(Bytes::from(buf)),
1213 8 : );
1214 8 : }
1215 :
1216 16 : self.put(relmap_file_key(spcnode, dbnode), Value::Image(img));
1217 16 : Ok(())
1218 16 : }
1219 :
1220 0 : pub async fn put_twophase_file(
1221 0 : &mut self,
1222 0 : xid: TransactionId,
1223 0 : img: Bytes,
1224 0 : ctx: &RequestContext,
1225 0 : ) -> anyhow::Result<()> {
1226 : // Add it to the directory entry
1227 0 : let buf = self.get(TWOPHASEDIR_KEY, ctx).await?;
1228 0 : let mut dir = TwoPhaseDirectory::des(&buf)?;
1229 0 : if !dir.xids.insert(xid) {
1230 0 : anyhow::bail!("twophase file for xid {} already exists", xid);
1231 0 : }
1232 0 : self.pending_directory_entries
1233 0 : .push((DirectoryKind::TwoPhase, dir.xids.len()));
1234 0 : self.put(
1235 0 : TWOPHASEDIR_KEY,
1236 0 : Value::Image(Bytes::from(TwoPhaseDirectory::ser(&dir)?)),
1237 : );
1238 :
1239 0 : self.put(twophase_file_key(xid), Value::Image(img));
1240 0 : Ok(())
1241 0 : }
1242 :
1243 0 : pub async fn set_replorigin(
1244 0 : &mut self,
1245 0 : origin_id: RepOriginId,
1246 0 : origin_lsn: Lsn,
1247 0 : ) -> anyhow::Result<()> {
1248 0 : let key = repl_origin_key(origin_id);
1249 0 : self.put(key, Value::Image(origin_lsn.ser().unwrap().into()));
1250 0 : Ok(())
1251 0 : }
1252 :
1253 0 : pub async fn drop_replorigin(&mut self, origin_id: RepOriginId) -> anyhow::Result<()> {
1254 0 : self.set_replorigin(origin_id, Lsn::INVALID).await
1255 0 : }
1256 :
1257 154 : pub fn put_control_file(&mut self, img: Bytes) -> anyhow::Result<()> {
1258 154 : self.put(CONTROLFILE_KEY, Value::Image(img));
1259 154 : Ok(())
1260 154 : }
1261 :
1262 168 : pub fn put_checkpoint(&mut self, img: Bytes) -> anyhow::Result<()> {
1263 168 : self.put(CHECKPOINT_KEY, Value::Image(img));
1264 168 : Ok(())
1265 168 : }
1266 :
1267 0 : pub async fn drop_dbdir(
1268 0 : &mut self,
1269 0 : spcnode: Oid,
1270 0 : dbnode: Oid,
1271 0 : ctx: &RequestContext,
1272 0 : ) -> anyhow::Result<()> {
1273 0 : let total_blocks = self
1274 0 : .tline
1275 0 : .get_db_size(spcnode, dbnode, Version::Modified(self), ctx)
1276 0 : .await?;
1277 :
1278 : // Remove entry from dbdir
1279 0 : let buf = self.get(DBDIR_KEY, ctx).await?;
1280 0 : let mut dir = DbDirectory::des(&buf)?;
1281 0 : if dir.dbdirs.remove(&(spcnode, dbnode)).is_some() {
1282 0 : let buf = DbDirectory::ser(&dir)?;
1283 0 : self.pending_directory_entries
1284 0 : .push((DirectoryKind::Db, dir.dbdirs.len()));
1285 0 : self.put(DBDIR_KEY, Value::Image(buf.into()));
1286 : } else {
1287 0 : warn!(
1288 0 : "dropped dbdir for spcnode {} dbnode {} did not exist in db directory",
1289 : spcnode, dbnode
1290 : );
1291 : }
1292 :
1293 : // Update logical database size.
1294 0 : self.pending_nblocks -= total_blocks as i64;
1295 0 :
1296 0 : // Delete all relations and metadata files for the spcnode/dnode
1297 0 : self.delete(dbdir_key_range(spcnode, dbnode));
1298 0 : Ok(())
1299 0 : }
1300 :
1301 : /// Create a relation fork.
1302 : ///
1303 : /// 'nblocks' is the initial size.
1304 1920 : pub async fn put_rel_creation(
1305 1920 : &mut self,
1306 1920 : rel: RelTag,
1307 1920 : nblocks: BlockNumber,
1308 1920 : ctx: &RequestContext,
1309 1920 : ) -> Result<(), RelationError> {
1310 1920 : if rel.relnode == 0 {
1311 0 : return Err(RelationError::InvalidRelnode);
1312 1920 : }
1313 : // It's possible that this is the first rel for this db in this
1314 : // tablespace. Create the reldir entry for it if so.
1315 1920 : let mut dbdir = DbDirectory::des(&self.get(DBDIR_KEY, ctx).await.context("read db")?)
1316 1920 : .context("deserialize db")?;
1317 1920 : let rel_dir_key = rel_dir_to_key(rel.spcnode, rel.dbnode);
1318 1920 : let mut rel_dir =
1319 1920 : if let hash_map::Entry::Vacant(e) = dbdir.dbdirs.entry((rel.spcnode, rel.dbnode)) {
1320 : // Didn't exist. Update dbdir
1321 8 : e.insert(false);
1322 8 : let buf = DbDirectory::ser(&dbdir).context("serialize db")?;
1323 8 : self.pending_directory_entries
1324 8 : .push((DirectoryKind::Db, dbdir.dbdirs.len()));
1325 8 : self.put(DBDIR_KEY, Value::Image(buf.into()));
1326 8 :
1327 8 : // and create the RelDirectory
1328 8 : RelDirectory::default()
1329 : } else {
1330 : // reldir already exists, fetch it
1331 1912 : RelDirectory::des(&self.get(rel_dir_key, ctx).await.context("read db")?)
1332 1912 : .context("deserialize db")?
1333 : };
1334 :
1335 : // Add the new relation to the rel directory entry, and write it back
1336 1920 : if !rel_dir.rels.insert((rel.relnode, rel.forknum)) {
1337 0 : return Err(RelationError::AlreadyExists);
1338 1920 : }
1339 1920 :
1340 1920 : self.pending_directory_entries
1341 1920 : .push((DirectoryKind::Rel, rel_dir.rels.len()));
1342 1920 :
1343 1920 : self.put(
1344 1920 : rel_dir_key,
1345 1920 : Value::Image(Bytes::from(
1346 1920 : RelDirectory::ser(&rel_dir).context("serialize")?,
1347 : )),
1348 : );
1349 :
1350 : // Put size
1351 1920 : let size_key = rel_size_to_key(rel);
1352 1920 : let buf = nblocks.to_le_bytes();
1353 1920 : self.put(size_key, Value::Image(Bytes::from(buf.to_vec())));
1354 1920 :
1355 1920 : self.pending_nblocks += nblocks as i64;
1356 1920 :
1357 1920 : // Update relation size cache
1358 1920 : self.tline.set_cached_rel_size(rel, self.lsn, nblocks);
1359 1920 :
1360 1920 : // Even if nblocks > 0, we don't insert any actual blocks here. That's up to the
1361 1920 : // caller.
1362 1920 : Ok(())
1363 1920 : }
1364 :
1365 : /// Truncate relation
1366 6012 : pub async fn put_rel_truncation(
1367 6012 : &mut self,
1368 6012 : rel: RelTag,
1369 6012 : nblocks: BlockNumber,
1370 6012 : ctx: &RequestContext,
1371 6012 : ) -> anyhow::Result<()> {
1372 6012 : anyhow::ensure!(rel.relnode != 0, RelationError::InvalidRelnode);
1373 6012 : if self
1374 6012 : .tline
1375 6012 : .get_rel_exists(rel, Version::Modified(self), ctx)
1376 0 : .await?
1377 : {
1378 6012 : let size_key = rel_size_to_key(rel);
1379 : // Fetch the old size first
1380 6012 : let old_size = self.get(size_key, ctx).await?.get_u32_le();
1381 6012 :
1382 6012 : // Update the entry with the new size.
1383 6012 : let buf = nblocks.to_le_bytes();
1384 6012 : self.put(size_key, Value::Image(Bytes::from(buf.to_vec())));
1385 6012 :
1386 6012 : // Update relation size cache
1387 6012 : self.tline.set_cached_rel_size(rel, self.lsn, nblocks);
1388 6012 :
1389 6012 : // Update relation size cache
1390 6012 : self.tline.set_cached_rel_size(rel, self.lsn, nblocks);
1391 6012 :
1392 6012 : // Update logical database size.
1393 6012 : self.pending_nblocks -= old_size as i64 - nblocks as i64;
1394 0 : }
1395 6012 : Ok(())
1396 6012 : }
1397 :
1398 : /// Extend relation
1399 : /// If new size is smaller, do nothing.
1400 276680 : pub async fn put_rel_extend(
1401 276680 : &mut self,
1402 276680 : rel: RelTag,
1403 276680 : nblocks: BlockNumber,
1404 276680 : ctx: &RequestContext,
1405 276680 : ) -> anyhow::Result<()> {
1406 276680 : anyhow::ensure!(rel.relnode != 0, RelationError::InvalidRelnode);
1407 :
1408 : // Put size
1409 276680 : let size_key = rel_size_to_key(rel);
1410 276680 : let old_size = self.get(size_key, ctx).await?.get_u32_le();
1411 276680 :
1412 276680 : // only extend relation here. never decrease the size
1413 276680 : if nblocks > old_size {
1414 274788 : let buf = nblocks.to_le_bytes();
1415 274788 : self.put(size_key, Value::Image(Bytes::from(buf.to_vec())));
1416 274788 :
1417 274788 : // Update relation size cache
1418 274788 : self.tline.set_cached_rel_size(rel, self.lsn, nblocks);
1419 274788 :
1420 274788 : self.pending_nblocks += nblocks as i64 - old_size as i64;
1421 274788 : }
1422 276680 : Ok(())
1423 276680 : }
1424 :
1425 : /// Drop a relation.
1426 2 : pub async fn put_rel_drop(&mut self, rel: RelTag, ctx: &RequestContext) -> anyhow::Result<()> {
1427 2 : anyhow::ensure!(rel.relnode != 0, RelationError::InvalidRelnode);
1428 :
1429 : // Remove it from the directory entry
1430 2 : let dir_key = rel_dir_to_key(rel.spcnode, rel.dbnode);
1431 2 : let buf = self.get(dir_key, ctx).await?;
1432 2 : let mut dir = RelDirectory::des(&buf)?;
1433 :
1434 2 : self.pending_directory_entries
1435 2 : .push((DirectoryKind::Rel, dir.rels.len()));
1436 2 :
1437 2 : if dir.rels.remove(&(rel.relnode, rel.forknum)) {
1438 2 : self.put(dir_key, Value::Image(Bytes::from(RelDirectory::ser(&dir)?)));
1439 : } else {
1440 0 : warn!("dropped rel {} did not exist in rel directory", rel);
1441 : }
1442 :
1443 : // update logical size
1444 2 : let size_key = rel_size_to_key(rel);
1445 2 : let old_size = self.get(size_key, ctx).await?.get_u32_le();
1446 2 : self.pending_nblocks -= old_size as i64;
1447 2 :
1448 2 : // Remove enty from relation size cache
1449 2 : self.tline.remove_cached_rel_size(&rel);
1450 2 :
1451 2 : // Delete size entry, as well as all blocks
1452 2 : self.delete(rel_key_range(rel));
1453 2 :
1454 2 : Ok(())
1455 2 : }
1456 :
1457 6 : pub async fn put_slru_segment_creation(
1458 6 : &mut self,
1459 6 : kind: SlruKind,
1460 6 : segno: u32,
1461 6 : nblocks: BlockNumber,
1462 6 : ctx: &RequestContext,
1463 6 : ) -> anyhow::Result<()> {
1464 6 : // Add it to the directory entry
1465 6 : let dir_key = slru_dir_to_key(kind);
1466 6 : let buf = self.get(dir_key, ctx).await?;
1467 6 : let mut dir = SlruSegmentDirectory::des(&buf)?;
1468 :
1469 6 : if !dir.segments.insert(segno) {
1470 0 : anyhow::bail!("slru segment {kind:?}/{segno} already exists");
1471 6 : }
1472 6 : self.pending_directory_entries
1473 6 : .push((DirectoryKind::SlruSegment(kind), dir.segments.len()));
1474 6 : self.put(
1475 6 : dir_key,
1476 6 : Value::Image(Bytes::from(SlruSegmentDirectory::ser(&dir)?)),
1477 : );
1478 :
1479 : // Put size
1480 6 : let size_key = slru_segment_size_to_key(kind, segno);
1481 6 : let buf = nblocks.to_le_bytes();
1482 6 : self.put(size_key, Value::Image(Bytes::from(buf.to_vec())));
1483 6 :
1484 6 : // even if nblocks > 0, we don't insert any actual blocks here
1485 6 :
1486 6 : Ok(())
1487 6 : }
1488 :
1489 : /// Extend SLRU segment
1490 0 : pub fn put_slru_extend(
1491 0 : &mut self,
1492 0 : kind: SlruKind,
1493 0 : segno: u32,
1494 0 : nblocks: BlockNumber,
1495 0 : ) -> anyhow::Result<()> {
1496 0 : // Put size
1497 0 : let size_key = slru_segment_size_to_key(kind, segno);
1498 0 : let buf = nblocks.to_le_bytes();
1499 0 : self.put(size_key, Value::Image(Bytes::from(buf.to_vec())));
1500 0 : Ok(())
1501 0 : }
1502 :
1503 : /// This method is used for marking truncated SLRU files
1504 0 : pub async fn drop_slru_segment(
1505 0 : &mut self,
1506 0 : kind: SlruKind,
1507 0 : segno: u32,
1508 0 : ctx: &RequestContext,
1509 0 : ) -> anyhow::Result<()> {
1510 0 : // Remove it from the directory entry
1511 0 : let dir_key = slru_dir_to_key(kind);
1512 0 : let buf = self.get(dir_key, ctx).await?;
1513 0 : let mut dir = SlruSegmentDirectory::des(&buf)?;
1514 :
1515 0 : if !dir.segments.remove(&segno) {
1516 0 : warn!("slru segment {:?}/{} does not exist", kind, segno);
1517 0 : }
1518 0 : self.pending_directory_entries
1519 0 : .push((DirectoryKind::SlruSegment(kind), dir.segments.len()));
1520 0 : self.put(
1521 0 : dir_key,
1522 0 : Value::Image(Bytes::from(SlruSegmentDirectory::ser(&dir)?)),
1523 : );
1524 :
1525 : // Delete size entry, as well as all blocks
1526 0 : self.delete(slru_segment_key_range(kind, segno));
1527 0 :
1528 0 : Ok(())
1529 0 : }
1530 :
1531 : /// Drop a relmapper file (pg_filenode.map)
1532 0 : pub fn drop_relmap_file(&mut self, _spcnode: Oid, _dbnode: Oid) -> anyhow::Result<()> {
1533 0 : // TODO
1534 0 : Ok(())
1535 0 : }
1536 :
1537 : /// This method is used for marking truncated SLRU files
1538 0 : pub async fn drop_twophase_file(
1539 0 : &mut self,
1540 0 : xid: TransactionId,
1541 0 : ctx: &RequestContext,
1542 0 : ) -> anyhow::Result<()> {
1543 : // Remove it from the directory entry
1544 0 : let buf = self.get(TWOPHASEDIR_KEY, ctx).await?;
1545 0 : let mut dir = TwoPhaseDirectory::des(&buf)?;
1546 :
1547 0 : if !dir.xids.remove(&xid) {
1548 0 : warn!("twophase file for xid {} does not exist", xid);
1549 0 : }
1550 0 : self.pending_directory_entries
1551 0 : .push((DirectoryKind::TwoPhase, dir.xids.len()));
1552 0 : self.put(
1553 0 : TWOPHASEDIR_KEY,
1554 0 : Value::Image(Bytes::from(TwoPhaseDirectory::ser(&dir)?)),
1555 : );
1556 :
1557 : // Delete it
1558 0 : self.delete(twophase_key_range(xid));
1559 0 :
1560 0 : Ok(())
1561 0 : }
1562 :
1563 170 : pub fn init_aux_dir(&mut self) -> anyhow::Result<()> {
1564 170 : if let AuxFilePolicy::V2 = self.tline.get_switch_aux_file_policy() {
1565 2 : return Ok(());
1566 168 : }
1567 168 : let buf = AuxFilesDirectory::ser(&AuxFilesDirectory {
1568 168 : files: HashMap::new(),
1569 168 : })?;
1570 168 : self.pending_directory_entries
1571 168 : .push((DirectoryKind::AuxFiles, 0));
1572 168 : self.put(AUX_FILES_KEY, Value::Image(Bytes::from(buf)));
1573 168 : Ok(())
1574 170 : }
1575 :
1576 30 : pub async fn put_file(
1577 30 : &mut self,
1578 30 : path: &str,
1579 30 : content: &[u8],
1580 30 : ctx: &RequestContext,
1581 30 : ) -> anyhow::Result<()> {
1582 30 : let switch_policy = self.tline.get_switch_aux_file_policy();
1583 :
1584 30 : let policy = {
1585 30 : let current_policy = self.tline.last_aux_file_policy.load();
1586 : // Allowed switch path:
1587 : // * no aux files -> v1/v2/cross-validation
1588 : // * cross-validation->v2
1589 :
1590 30 : let current_policy = if current_policy.is_none() {
1591 : // This path will only be hit once per tenant: we will decide the final policy in this code block.
1592 : // The next call to `put_file` will always have `last_aux_file_policy != None`.
1593 12 : let lsn = Lsn::max(self.tline.get_last_record_lsn(), self.lsn);
1594 12 : let aux_files_key_v1 = self.tline.list_aux_files_v1(lsn, ctx).await?;
1595 12 : if aux_files_key_v1.is_empty() {
1596 10 : None
1597 : } else {
1598 2 : self.tline.do_switch_aux_policy(AuxFilePolicy::V1)?;
1599 2 : Some(AuxFilePolicy::V1)
1600 : }
1601 : } else {
1602 18 : current_policy
1603 : };
1604 :
1605 30 : if AuxFilePolicy::is_valid_migration_path(current_policy, switch_policy) {
1606 12 : self.tline.do_switch_aux_policy(switch_policy)?;
1607 12 : info!(current=?current_policy, next=?switch_policy, "switching aux file policy");
1608 12 : switch_policy
1609 : } else {
1610 : // This branch handles non-valid migration path, and the case that switch_policy == current_policy.
1611 : // And actually, because the migration path always allow unspecified -> *, this unwrap_or will never be hit.
1612 18 : current_policy.unwrap_or(AuxFilePolicy::default_tenant_config())
1613 : }
1614 : };
1615 :
1616 30 : if let AuxFilePolicy::V2 | AuxFilePolicy::CrossValidation = policy {
1617 10 : let key = aux_file::encode_aux_file_key(path);
1618 : // retrieve the key from the engine
1619 10 : let old_val = match self.get(key, ctx).await {
1620 2 : Ok(val) => Some(val),
1621 8 : Err(PageReconstructError::MissingKey(_)) => None,
1622 0 : Err(e) => return Err(e.into()),
1623 : };
1624 10 : let files: Vec<(&str, &[u8])> = if let Some(ref old_val) = old_val {
1625 2 : aux_file::decode_file_value(old_val)?
1626 : } else {
1627 8 : Vec::new()
1628 : };
1629 10 : let mut other_files = Vec::with_capacity(files.len());
1630 10 : let mut modifying_file = None;
1631 12 : for file @ (p, content) in files {
1632 2 : if path == p {
1633 2 : assert!(
1634 2 : modifying_file.is_none(),
1635 0 : "duplicated entries found for {}",
1636 : path
1637 : );
1638 2 : modifying_file = Some(content);
1639 0 : } else {
1640 0 : other_files.push(file);
1641 0 : }
1642 : }
1643 10 : let mut new_files = other_files;
1644 10 : match (modifying_file, content.is_empty()) {
1645 2 : (Some(old_content), false) => {
1646 2 : self.tline
1647 2 : .aux_file_size_estimator
1648 2 : .on_update(old_content.len(), content.len());
1649 2 : new_files.push((path, content));
1650 2 : }
1651 0 : (Some(old_content), true) => {
1652 0 : self.tline
1653 0 : .aux_file_size_estimator
1654 0 : .on_remove(old_content.len());
1655 0 : // not adding the file key to the final `new_files` vec.
1656 0 : }
1657 8 : (None, false) => {
1658 8 : self.tline.aux_file_size_estimator.on_add(content.len());
1659 8 : new_files.push((path, content));
1660 8 : }
1661 0 : (None, true) => warn!("removing non-existing aux file: {}", path),
1662 : }
1663 10 : let new_val = aux_file::encode_file_value(&new_files)?;
1664 10 : self.put(key, Value::Image(new_val.into()));
1665 20 : }
1666 :
1667 30 : if let AuxFilePolicy::V1 | AuxFilePolicy::CrossValidation = policy {
1668 22 : let file_path = path.to_string();
1669 22 : let content = if content.is_empty() {
1670 2 : None
1671 : } else {
1672 20 : Some(Bytes::copy_from_slice(content))
1673 : };
1674 :
1675 : let n_files;
1676 22 : let mut aux_files = self.tline.aux_files.lock().await;
1677 22 : if let Some(mut dir) = aux_files.dir.take() {
1678 : // We already updated aux files in `self`: emit a delta and update our latest value.
1679 10 : dir.upsert(file_path.clone(), content.clone());
1680 10 : n_files = dir.files.len();
1681 10 : if aux_files.n_deltas == MAX_AUX_FILE_DELTAS {
1682 0 : self.put(
1683 0 : AUX_FILES_KEY,
1684 0 : Value::Image(Bytes::from(
1685 0 : AuxFilesDirectory::ser(&dir).context("serialize")?,
1686 : )),
1687 : );
1688 0 : aux_files.n_deltas = 0;
1689 10 : } else {
1690 10 : self.put(
1691 10 : AUX_FILES_KEY,
1692 10 : Value::WalRecord(NeonWalRecord::AuxFile { file_path, content }),
1693 10 : );
1694 10 : aux_files.n_deltas += 1;
1695 10 : }
1696 10 : aux_files.dir = Some(dir);
1697 : } else {
1698 : // Check if the AUX_FILES_KEY is initialized
1699 12 : match self.get(AUX_FILES_KEY, ctx).await {
1700 8 : Ok(dir_bytes) => {
1701 8 : let mut dir = AuxFilesDirectory::des(&dir_bytes)?;
1702 : // Key is already set, we may append a delta
1703 8 : self.put(
1704 8 : AUX_FILES_KEY,
1705 8 : Value::WalRecord(NeonWalRecord::AuxFile {
1706 8 : file_path: file_path.clone(),
1707 8 : content: content.clone(),
1708 8 : }),
1709 8 : );
1710 8 : dir.upsert(file_path, content);
1711 8 : n_files = dir.files.len();
1712 8 : aux_files.dir = Some(dir);
1713 : }
1714 : Err(
1715 0 : e @ (PageReconstructError::Cancelled
1716 0 : | PageReconstructError::AncestorLsnTimeout(_)),
1717 0 : ) => {
1718 0 : // Important that we do not interpret a shutdown error as "not found" and thereby
1719 0 : // reset the map.
1720 0 : return Err(e.into());
1721 : }
1722 : // Note: we added missing key error variant in https://github.com/neondatabase/neon/pull/7393 but
1723 : // the original code assumes all other errors are missing keys. Therefore, we keep the code path
1724 : // the same for now, though in theory, we should only match the `MissingKey` variant.
1725 : Err(
1726 : PageReconstructError::Other(_)
1727 : | PageReconstructError::WalRedo(_)
1728 : | PageReconstructError::MissingKey { .. },
1729 : ) => {
1730 : // Key is missing, we must insert an image as the basis for subsequent deltas.
1731 :
1732 4 : let mut dir = AuxFilesDirectory {
1733 4 : files: HashMap::new(),
1734 4 : };
1735 4 : dir.upsert(file_path, content);
1736 4 : self.put(
1737 4 : AUX_FILES_KEY,
1738 4 : Value::Image(Bytes::from(
1739 4 : AuxFilesDirectory::ser(&dir).context("serialize")?,
1740 : )),
1741 : );
1742 4 : n_files = 1;
1743 4 : aux_files.dir = Some(dir);
1744 : }
1745 : }
1746 : }
1747 :
1748 22 : self.pending_directory_entries
1749 22 : .push((DirectoryKind::AuxFiles, n_files));
1750 8 : }
1751 :
1752 30 : Ok(())
1753 30 : }
1754 :
1755 : ///
1756 : /// Flush changes accumulated so far to the underlying repository.
1757 : ///
1758 : /// Usually, changes made in DatadirModification are atomic, but this allows
1759 : /// you to flush them to the underlying repository before the final `commit`.
1760 : /// That allows to free up the memory used to hold the pending changes.
1761 : ///
1762 : /// Currently only used during bulk import of a data directory. In that
1763 : /// context, breaking the atomicity is OK. If the import is interrupted, the
1764 : /// whole import fails and the timeline will be deleted anyway.
1765 : /// (Or to be precise, it will be left behind for debugging purposes and
1766 : /// ignored, see <https://github.com/neondatabase/neon/pull/1809>)
1767 : ///
1768 : /// Note: A consequence of flushing the pending operations is that they
1769 : /// won't be visible to subsequent operations until `commit`. The function
1770 : /// retains all the metadata, but data pages are flushed. That's again OK
1771 : /// for bulk import, where you are just loading data pages and won't try to
1772 : /// modify the same pages twice.
1773 1930 : pub async fn flush(&mut self, ctx: &RequestContext) -> anyhow::Result<()> {
1774 1930 : // Unless we have accumulated a decent amount of changes, it's not worth it
1775 1930 : // to scan through the pending_updates list.
1776 1930 : let pending_nblocks = self.pending_nblocks;
1777 1930 : if pending_nblocks < 10000 {
1778 1930 : return Ok(());
1779 0 : }
1780 :
1781 0 : let mut writer = self.tline.writer().await;
1782 :
1783 : // Flush relation and SLRU data blocks, keep metadata.
1784 0 : let mut retained_pending_updates = HashMap::<_, Vec<_>>::new();
1785 0 : for (key, values) in self.pending_updates.drain() {
1786 0 : for (lsn, value) in values {
1787 0 : if key.is_rel_block_key() || key.is_slru_block_key() {
1788 : // This bails out on first error without modifying pending_updates.
1789 : // That's Ok, cf this function's doc comment.
1790 0 : writer.put(key, lsn, &value, ctx).await?;
1791 0 : } else {
1792 0 : retained_pending_updates
1793 0 : .entry(key)
1794 0 : .or_default()
1795 0 : .push((lsn, value));
1796 0 : }
1797 : }
1798 : }
1799 :
1800 0 : self.pending_updates = retained_pending_updates;
1801 0 :
1802 0 : if pending_nblocks != 0 {
1803 0 : writer.update_current_logical_size(pending_nblocks * i64::from(BLCKSZ));
1804 0 : self.pending_nblocks = 0;
1805 0 : }
1806 :
1807 0 : for (kind, count) in std::mem::take(&mut self.pending_directory_entries) {
1808 0 : writer.update_directory_entries_count(kind, count as u64);
1809 0 : }
1810 :
1811 0 : Ok(())
1812 1930 : }
1813 :
1814 : ///
1815 : /// Finish this atomic update, writing all the updated keys to the
1816 : /// underlying timeline.
1817 : /// All the modifications in this atomic update are stamped by the specified LSN.
1818 : ///
1819 743056 : pub async fn commit(&mut self, ctx: &RequestContext) -> anyhow::Result<()> {
1820 743056 : let mut writer = self.tline.writer().await;
1821 :
1822 743056 : let pending_nblocks = self.pending_nblocks;
1823 743056 : self.pending_nblocks = 0;
1824 743056 :
1825 743056 : if !self.pending_updates.is_empty() {
1826 : // The put_batch call below expects expects the inputs to be sorted by Lsn,
1827 : // so we do that first.
1828 414040 : let lsn_ordered_batch: VecMap<Lsn, (Key, Value)> = VecMap::from_iter(
1829 414040 : self.pending_updates
1830 414040 : .drain()
1831 700344 : .map(|(key, vals)| vals.into_iter().map(move |(lsn, val)| (lsn, (key, val))))
1832 414040 : .kmerge_by(|lhs, rhs| lhs.0 < rhs.0),
1833 414040 : VecMapOrdering::GreaterOrEqual,
1834 414040 : );
1835 414040 :
1836 414040 : writer.put_batch(lsn_ordered_batch, ctx).await?;
1837 329016 : }
1838 :
1839 743056 : if !self.pending_deletions.is_empty() {
1840 2 : writer.delete_batch(&self.pending_deletions, ctx).await?;
1841 2 : self.pending_deletions.clear();
1842 743054 : }
1843 :
1844 743056 : self.pending_lsns.push(self.lsn);
1845 888914 : for pending_lsn in self.pending_lsns.drain(..) {
1846 888914 : // Ideally, we should be able to call writer.finish_write() only once
1847 888914 : // with the highest LSN. However, the last_record_lsn variable in the
1848 888914 : // timeline keeps track of the latest LSN and the immediate previous LSN
1849 888914 : // so we need to record every LSN to not leave a gap between them.
1850 888914 : writer.finish_write(pending_lsn);
1851 888914 : }
1852 :
1853 743056 : if pending_nblocks != 0 {
1854 270570 : writer.update_current_logical_size(pending_nblocks * i64::from(BLCKSZ));
1855 472486 : }
1856 :
1857 743056 : for (kind, count) in std::mem::take(&mut self.pending_directory_entries) {
1858 2904 : writer.update_directory_entries_count(kind, count as u64);
1859 2904 : }
1860 :
1861 743056 : Ok(())
1862 743056 : }
1863 :
1864 291704 : pub(crate) fn len(&self) -> usize {
1865 291704 : self.pending_updates.len() + self.pending_deletions.len()
1866 291704 : }
1867 :
1868 : // Internal helper functions to batch the modifications
1869 :
1870 286582 : async fn get(&self, key: Key, ctx: &RequestContext) -> Result<Bytes, PageReconstructError> {
1871 : // Have we already updated the same key? Read the latest pending updated
1872 : // version in that case.
1873 : //
1874 : // Note: we don't check pending_deletions. It is an error to request a
1875 : // value that has been removed, deletion only avoids leaking storage.
1876 286582 : if let Some(values) = self.pending_updates.get(&key) {
1877 15928 : if let Some((_, value)) = values.last() {
1878 15928 : return if let Value::Image(img) = value {
1879 15928 : Ok(img.clone())
1880 : } else {
1881 : // Currently, we never need to read back a WAL record that we
1882 : // inserted in the same "transaction". All the metadata updates
1883 : // work directly with Images, and we never need to read actual
1884 : // data pages. We could handle this if we had to, by calling
1885 : // the walredo manager, but let's keep it simple for now.
1886 0 : Err(PageReconstructError::from(anyhow::anyhow!(
1887 0 : "unexpected pending WAL record"
1888 0 : )))
1889 : };
1890 0 : }
1891 270654 : }
1892 270654 : let lsn = Lsn::max(self.tline.get_last_record_lsn(), self.lsn);
1893 270654 : self.tline.get(key, lsn, ctx).await
1894 286582 : }
1895 :
1896 : /// Only used during unit tests, force putting a key into the modification.
1897 : #[cfg(test)]
1898 2 : pub(crate) fn put_for_test(&mut self, key: Key, val: Value) {
1899 2 : self.put(key, val);
1900 2 : }
1901 :
1902 712504 : fn put(&mut self, key: Key, val: Value) {
1903 712504 : let values = self.pending_updates.entry(key).or_default();
1904 : // Replace the previous value if it exists at the same lsn
1905 712504 : if let Some((last_lsn, last_value)) = values.last_mut() {
1906 12166 : if *last_lsn == self.lsn {
1907 12160 : *last_value = val;
1908 12160 : return;
1909 6 : }
1910 700338 : }
1911 700344 : values.push((self.lsn, val));
1912 712504 : }
1913 :
1914 2 : fn delete(&mut self, key_range: Range<Key>) {
1915 2 : trace!("DELETE {}-{}", key_range.start, key_range.end);
1916 2 : self.pending_deletions.push((key_range, self.lsn));
1917 2 : }
1918 : }
1919 :
1920 : /// This struct facilitates accessing either a committed key from the timeline at a
1921 : /// specific LSN, or the latest uncommitted key from a pending modification.
1922 : /// During WAL ingestion, the records from multiple LSNs may be batched in the same
1923 : /// modification before being flushed to the timeline. Hence, the routines in WalIngest
1924 : /// need to look up the keys in the modification first before looking them up in the
1925 : /// timeline to not miss the latest updates.
1926 : #[derive(Clone, Copy)]
1927 : pub enum Version<'a> {
1928 : Lsn(Lsn),
1929 : Modified(&'a DatadirModification<'a>),
1930 : }
1931 :
1932 : impl<'a> Version<'a> {
1933 23542 : async fn get(
1934 23542 : &self,
1935 23542 : timeline: &Timeline,
1936 23542 : key: Key,
1937 23542 : ctx: &RequestContext,
1938 23542 : ) -> Result<Bytes, PageReconstructError> {
1939 23542 : match self {
1940 23532 : Version::Lsn(lsn) => timeline.get(key, *lsn, ctx).await,
1941 10 : Version::Modified(modification) => modification.get(key, ctx).await,
1942 : }
1943 23542 : }
1944 :
1945 35620 : fn get_lsn(&self) -> Lsn {
1946 35620 : match self {
1947 29574 : Version::Lsn(lsn) => *lsn,
1948 6046 : Version::Modified(modification) => modification.lsn,
1949 : }
1950 35620 : }
1951 : }
1952 :
1953 : //--- Metadata structs stored in key-value pairs in the repository.
1954 :
1955 2204 : #[derive(Debug, Serialize, Deserialize)]
1956 : struct DbDirectory {
1957 : // (spcnode, dbnode) -> (do relmapper and PG_VERSION files exist)
1958 : dbdirs: HashMap<(Oid, Oid), bool>,
1959 : }
1960 :
1961 270 : #[derive(Debug, Serialize, Deserialize)]
1962 : struct TwoPhaseDirectory {
1963 : xids: HashSet<TransactionId>,
1964 : }
1965 :
1966 1932 : #[derive(Debug, Serialize, Deserialize, Default)]
1967 : struct RelDirectory {
1968 : // Set of relations that exist. (relfilenode, forknum)
1969 : //
1970 : // TODO: Store it as a btree or radix tree or something else that spans multiple
1971 : // key-value pairs, if you have a lot of relations
1972 : rels: HashSet<(Oid, u8)>,
1973 : }
1974 :
1975 58 : #[derive(Debug, Serialize, Deserialize, Default, PartialEq)]
1976 : pub(crate) struct AuxFilesDirectory {
1977 : pub(crate) files: HashMap<String, Bytes>,
1978 : }
1979 :
1980 : impl AuxFilesDirectory {
1981 48 : pub(crate) fn upsert(&mut self, key: String, value: Option<Bytes>) {
1982 48 : if let Some(value) = value {
1983 42 : self.files.insert(key, value);
1984 42 : } else {
1985 6 : self.files.remove(&key);
1986 6 : }
1987 48 : }
1988 : }
1989 :
1990 0 : #[derive(Debug, Serialize, Deserialize)]
1991 : struct RelSizeEntry {
1992 : nblocks: u32,
1993 : }
1994 :
1995 810 : #[derive(Debug, Serialize, Deserialize, Default)]
1996 : struct SlruSegmentDirectory {
1997 : // Set of SLRU segments that exist.
1998 : segments: HashSet<u32>,
1999 : }
2000 :
2001 : #[derive(Copy, Clone, PartialEq, Eq, Debug, enum_map::Enum)]
2002 : #[repr(u8)]
2003 : pub(crate) enum DirectoryKind {
2004 : Db,
2005 : TwoPhase,
2006 : Rel,
2007 : AuxFiles,
2008 : SlruSegment(SlruKind),
2009 : }
2010 :
2011 : impl DirectoryKind {
2012 : pub(crate) const KINDS_NUM: usize = <DirectoryKind as Enum>::LENGTH;
2013 5808 : pub(crate) fn offset(&self) -> usize {
2014 5808 : self.into_usize()
2015 5808 : }
2016 : }
2017 :
2018 : static ZERO_PAGE: Bytes = Bytes::from_static(&[0u8; BLCKSZ as usize]);
2019 :
2020 : #[allow(clippy::bool_assert_comparison)]
2021 : #[cfg(test)]
2022 : mod tests {
2023 : use hex_literal::hex;
2024 : use utils::id::TimelineId;
2025 :
2026 : use super::*;
2027 :
2028 : use crate::{tenant::harness::TenantHarness, DEFAULT_PG_VERSION};
2029 :
2030 : /// Test a round trip of aux file updates, from DatadirModification to reading back from the Timeline
2031 : #[tokio::test]
2032 2 : async fn aux_files_round_trip() -> anyhow::Result<()> {
2033 2 : let name = "aux_files_round_trip";
2034 2 : let harness = TenantHarness::create(name).await?;
2035 2 :
2036 2 : pub const TIMELINE_ID: TimelineId =
2037 2 : TimelineId::from_array(hex!("11223344556677881122334455667788"));
2038 2 :
2039 8 : let (tenant, ctx) = harness.load().await;
2040 2 : let tline = tenant
2041 2 : .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
2042 2 : .await?;
2043 2 : let tline = tline.raw_timeline().unwrap();
2044 2 :
2045 2 : // First modification: insert two keys
2046 2 : let mut modification = tline.begin_modification(Lsn(0x1000));
2047 2 : modification.put_file("foo/bar1", b"content1", &ctx).await?;
2048 2 : modification.set_lsn(Lsn(0x1008))?;
2049 2 : modification.put_file("foo/bar2", b"content2", &ctx).await?;
2050 2 : modification.commit(&ctx).await?;
2051 2 : let expect_1008 = HashMap::from([
2052 2 : ("foo/bar1".to_string(), Bytes::from_static(b"content1")),
2053 2 : ("foo/bar2".to_string(), Bytes::from_static(b"content2")),
2054 2 : ]);
2055 2 :
2056 2 : let readback = tline.list_aux_files(Lsn(0x1008), &ctx).await?;
2057 2 : assert_eq!(readback, expect_1008);
2058 2 :
2059 2 : // Second modification: update one key, remove the other
2060 2 : let mut modification = tline.begin_modification(Lsn(0x2000));
2061 2 : modification.put_file("foo/bar1", b"content3", &ctx).await?;
2062 2 : modification.set_lsn(Lsn(0x2008))?;
2063 2 : modification.put_file("foo/bar2", b"", &ctx).await?;
2064 2 : modification.commit(&ctx).await?;
2065 2 : let expect_2008 =
2066 2 : HashMap::from([("foo/bar1".to_string(), Bytes::from_static(b"content3"))]);
2067 2 :
2068 2 : let readback = tline.list_aux_files(Lsn(0x2008), &ctx).await?;
2069 2 : assert_eq!(readback, expect_2008);
2070 2 :
2071 2 : // Reading back in time works
2072 2 : let readback = tline.list_aux_files(Lsn(0x1008), &ctx).await?;
2073 2 : assert_eq!(readback, expect_1008);
2074 2 :
2075 2 : Ok(())
2076 2 : }
2077 :
2078 : /*
2079 : fn assert_current_logical_size<R: Repository>(timeline: &DatadirTimeline<R>, lsn: Lsn) {
2080 : let incremental = timeline.get_current_logical_size();
2081 : let non_incremental = timeline
2082 : .get_current_logical_size_non_incremental(lsn)
2083 : .unwrap();
2084 : assert_eq!(incremental, non_incremental);
2085 : }
2086 : */
2087 :
2088 : /*
2089 : ///
2090 : /// Test list_rels() function, with branches and dropped relations
2091 : ///
2092 : #[test]
2093 : fn test_list_rels_drop() -> Result<()> {
2094 : let repo = RepoHarness::create("test_list_rels_drop")?.load();
2095 : let tline = create_empty_timeline(repo, TIMELINE_ID)?;
2096 : const TESTDB: u32 = 111;
2097 :
2098 : // Import initial dummy checkpoint record, otherwise the get_timeline() call
2099 : // after branching fails below
2100 : let mut writer = tline.begin_record(Lsn(0x10));
2101 : writer.put_checkpoint(ZERO_CHECKPOINT.clone())?;
2102 : writer.finish()?;
2103 :
2104 : // Create a relation on the timeline
2105 : let mut writer = tline.begin_record(Lsn(0x20));
2106 : writer.put_rel_page_image(TESTREL_A, 0, TEST_IMG("foo blk 0 at 2"))?;
2107 : writer.finish()?;
2108 :
2109 : let writer = tline.begin_record(Lsn(0x00));
2110 : writer.finish()?;
2111 :
2112 : // Check that list_rels() lists it after LSN 2, but no before it
2113 : assert!(!tline.list_rels(0, TESTDB, Lsn(0x10))?.contains(&TESTREL_A));
2114 : assert!(tline.list_rels(0, TESTDB, Lsn(0x20))?.contains(&TESTREL_A));
2115 : assert!(tline.list_rels(0, TESTDB, Lsn(0x30))?.contains(&TESTREL_A));
2116 :
2117 : // Create a branch, check that the relation is visible there
2118 : repo.branch_timeline(&tline, NEW_TIMELINE_ID, Lsn(0x30))?;
2119 : let newtline = match repo.get_timeline(NEW_TIMELINE_ID)?.local_timeline() {
2120 : Some(timeline) => timeline,
2121 : None => panic!("Should have a local timeline"),
2122 : };
2123 : let newtline = DatadirTimelineImpl::new(newtline);
2124 : assert!(newtline
2125 : .list_rels(0, TESTDB, Lsn(0x30))?
2126 : .contains(&TESTREL_A));
2127 :
2128 : // Drop it on the branch
2129 : let mut new_writer = newtline.begin_record(Lsn(0x40));
2130 : new_writer.drop_relation(TESTREL_A)?;
2131 : new_writer.finish()?;
2132 :
2133 : // Check that it's no longer listed on the branch after the point where it was dropped
2134 : assert!(newtline
2135 : .list_rels(0, TESTDB, Lsn(0x30))?
2136 : .contains(&TESTREL_A));
2137 : assert!(!newtline
2138 : .list_rels(0, TESTDB, Lsn(0x40))?
2139 : .contains(&TESTREL_A));
2140 :
2141 : // Run checkpoint and garbage collection and check that it's still not visible
2142 : newtline.checkpoint(CheckpointConfig::Forced)?;
2143 : repo.gc_iteration(Some(NEW_TIMELINE_ID), 0, true)?;
2144 :
2145 : assert!(!newtline
2146 : .list_rels(0, TESTDB, Lsn(0x40))?
2147 : .contains(&TESTREL_A));
2148 :
2149 : Ok(())
2150 : }
2151 : */
2152 :
2153 : /*
2154 : #[test]
2155 : fn test_read_beyond_eof() -> Result<()> {
2156 : let repo = RepoHarness::create("test_read_beyond_eof")?.load();
2157 : let tline = create_test_timeline(repo, TIMELINE_ID)?;
2158 :
2159 : make_some_layers(&tline, Lsn(0x20))?;
2160 : let mut writer = tline.begin_record(Lsn(0x60));
2161 : walingest.put_rel_page_image(
2162 : &mut writer,
2163 : TESTREL_A,
2164 : 0,
2165 : TEST_IMG(&format!("foo blk 0 at {}", Lsn(0x60))),
2166 : )?;
2167 : writer.finish()?;
2168 :
2169 : // Test read before rel creation. Should error out.
2170 : assert!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x10), false).is_err());
2171 :
2172 : // Read block beyond end of relation at different points in time.
2173 : // These reads should fall into different delta, image, and in-memory layers.
2174 : assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x20), false)?, ZERO_PAGE);
2175 : assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x25), false)?, ZERO_PAGE);
2176 : assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x30), false)?, ZERO_PAGE);
2177 : assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x35), false)?, ZERO_PAGE);
2178 : assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x40), false)?, ZERO_PAGE);
2179 : assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x45), false)?, ZERO_PAGE);
2180 : assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x50), false)?, ZERO_PAGE);
2181 : assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x55), false)?, ZERO_PAGE);
2182 : assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x60), false)?, ZERO_PAGE);
2183 :
2184 : // Test on an in-memory layer with no preceding layer
2185 : let mut writer = tline.begin_record(Lsn(0x70));
2186 : walingest.put_rel_page_image(
2187 : &mut writer,
2188 : TESTREL_B,
2189 : 0,
2190 : TEST_IMG(&format!("foo blk 0 at {}", Lsn(0x70))),
2191 : )?;
2192 : writer.finish()?;
2193 :
2194 : assert_eq!(tline.get_rel_page_at_lsn(TESTREL_B, 1, Lsn(0x70), false)?6, ZERO_PAGE);
2195 :
2196 : Ok(())
2197 : }
2198 : */
2199 : }
|