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