Line data Source code
1 : pub mod detach_ancestor;
2 : pub mod partitioning;
3 : pub mod utilization;
4 :
5 : use core::ops::Range;
6 : use std::collections::HashMap;
7 : use std::fmt::Display;
8 : use std::io::{BufRead, Read};
9 : use std::num::{NonZeroU32, NonZeroU64, NonZeroUsize};
10 : use std::str::FromStr;
11 : use std::time::{Duration, SystemTime};
12 :
13 : use byteorder::{BigEndian, ReadBytesExt};
14 : use bytes::{Buf, BufMut, Bytes, BytesMut};
15 : #[cfg(feature = "testing")]
16 : use camino::Utf8PathBuf;
17 : use postgres_ffi::BLCKSZ;
18 : use serde::{Deserialize, Deserializer, Serialize, Serializer};
19 : use serde_with::serde_as;
20 : pub use utilization::PageserverUtilization;
21 : use utils::id::{NodeId, TenantId, TimelineId};
22 : use utils::lsn::Lsn;
23 : use utils::postgres_client::PostgresClientProtocol;
24 : use utils::{completion, serde_system_time};
25 :
26 : use crate::key::{CompactKey, Key};
27 : use crate::reltag::RelTag;
28 : use crate::shard::{ShardCount, ShardStripeSize, TenantShardId};
29 :
30 : /// The state of a tenant in this pageserver.
31 : ///
32 : /// ```mermaid
33 : /// stateDiagram-v2
34 : ///
35 : /// [*] --> Attaching: spawn_attach()
36 : ///
37 : /// Attaching --> Activating: activate()
38 : /// Activating --> Active: infallible
39 : ///
40 : /// Attaching --> Broken: attach() failure
41 : ///
42 : /// Active --> Stopping: set_stopping(), part of shutdown & detach
43 : /// Stopping --> Broken: late error in remove_tenant_from_memory
44 : ///
45 : /// Broken --> [*]: ignore / detach / shutdown
46 : /// Stopping --> [*]: remove_from_memory complete
47 : ///
48 : /// Active --> Broken: cfg(testing)-only tenant break point
49 : /// ```
50 : #[derive(
51 : Clone,
52 : PartialEq,
53 : Eq,
54 0 : serde::Serialize,
55 1 : serde::Deserialize,
56 : strum_macros::Display,
57 : strum_macros::VariantNames,
58 : strum_macros::AsRefStr,
59 : strum_macros::IntoStaticStr,
60 : )]
61 : #[serde(tag = "slug", content = "data")]
62 : pub enum TenantState {
63 : /// This tenant is being attached to the pageserver.
64 : ///
65 : /// `set_stopping()` and `set_broken()` do not work in this state and wait for it to pass.
66 : Attaching,
67 : /// The tenant is transitioning from Loading/Attaching to Active.
68 : ///
69 : /// While in this state, the individual timelines are being activated.
70 : ///
71 : /// `set_stopping()` and `set_broken()` do not work in this state and wait for it to pass.
72 : Activating(ActivatingFrom),
73 : /// The tenant has finished activating and is open for business.
74 : ///
75 : /// Transitions out of this state are possible through `set_stopping()` and `set_broken()`.
76 : Active,
77 : /// The tenant is recognized by pageserver, but it is being detached or the
78 : /// system is being shut down.
79 : ///
80 : /// Transitions out of this state are possible through `set_broken()`.
81 : Stopping {
82 : // Because of https://github.com/serde-rs/serde/issues/2105 this has to be a named field,
83 : // otherwise it will not be skipped during deserialization
84 : #[serde(skip)]
85 : progress: completion::Barrier,
86 : },
87 : /// The tenant is recognized by the pageserver, but can no longer be used for
88 : /// any operations.
89 : ///
90 : /// If the tenant fails to load or attach, it will transition to this state
91 : /// and it is guaranteed that no background tasks are running in its name.
92 : ///
93 : /// The other way to transition into this state is from `Stopping` state
94 : /// through `set_broken()` called from `remove_tenant_from_memory()`. That happens
95 : /// if the cleanup future executed by `remove_tenant_from_memory()` fails.
96 : Broken { reason: String, backtrace: String },
97 : }
98 :
99 : impl TenantState {
100 0 : pub fn attachment_status(&self) -> TenantAttachmentStatus {
101 : use TenantAttachmentStatus::*;
102 :
103 : // Below TenantState::Activating is used as "transient" or "transparent" state for
104 : // attachment_status determining.
105 0 : match self {
106 : // The attach procedure writes the marker file before adding the Attaching tenant to the tenants map.
107 : // So, technically, we can return Attached here.
108 : // However, as soon as Console observes Attached, it will proceed with the Postgres-level health check.
109 : // But, our attach task might still be fetching the remote timelines, etc.
110 : // So, return `Maybe` while Attaching, making Console wait for the attach task to finish.
111 0 : Self::Attaching | Self::Activating(ActivatingFrom::Attaching) => Maybe,
112 : // We only reach Active after successful load / attach.
113 : // So, call atttachment status Attached.
114 0 : Self::Active => Attached,
115 : // If the (initial or resumed) attach procedure fails, the tenant becomes Broken.
116 : // However, it also becomes Broken if the regular load fails.
117 : // From Console's perspective there's no practical difference
118 : // because attachment_status is polled by console only during attach operation execution.
119 0 : Self::Broken { reason, .. } => Failed {
120 0 : reason: reason.to_owned(),
121 0 : },
122 : // Why is Stopping a Maybe case? Because, during pageserver shutdown,
123 : // we set the Stopping state irrespective of whether the tenant
124 : // has finished attaching or not.
125 0 : Self::Stopping { .. } => Maybe,
126 : }
127 0 : }
128 :
129 0 : pub fn broken_from_reason(reason: String) -> Self {
130 0 : let backtrace_str: String = format!("{}", std::backtrace::Backtrace::force_capture());
131 0 : Self::Broken {
132 0 : reason,
133 0 : backtrace: backtrace_str,
134 0 : }
135 0 : }
136 : }
137 :
138 : impl std::fmt::Debug for TenantState {
139 2 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140 2 : match self {
141 2 : Self::Broken { reason, backtrace } if !reason.is_empty() => {
142 2 : write!(f, "Broken due to: {reason}. Backtrace:\n{backtrace}")
143 : }
144 0 : _ => write!(f, "{self}"),
145 : }
146 2 : }
147 : }
148 :
149 : /// A temporary lease to a specific lsn inside a timeline.
150 : /// Access to the lsn is guaranteed by the pageserver until the expiration indicated by `valid_until`.
151 : #[serde_as]
152 0 : #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
153 : pub struct LsnLease {
154 : #[serde_as(as = "SystemTimeAsRfc3339Millis")]
155 : pub valid_until: SystemTime,
156 : }
157 :
158 : serde_with::serde_conv!(
159 : SystemTimeAsRfc3339Millis,
160 : SystemTime,
161 0 : |time: &SystemTime| humantime::format_rfc3339_millis(*time).to_string(),
162 0 : |value: String| -> Result<_, humantime::TimestampError> { humantime::parse_rfc3339(&value) }
163 : );
164 :
165 : impl LsnLease {
166 : /// The default length for an explicit LSN lease request (10 minutes).
167 : pub const DEFAULT_LENGTH: Duration = Duration::from_secs(10 * 60);
168 :
169 : /// The default length for an implicit LSN lease granted during
170 : /// `get_lsn_by_timestamp` request (1 minutes).
171 : pub const DEFAULT_LENGTH_FOR_TS: Duration = Duration::from_secs(60);
172 :
173 : /// Checks whether the lease is expired.
174 12 : pub fn is_expired(&self, now: &SystemTime) -> bool {
175 12 : now > &self.valid_until
176 12 : }
177 : }
178 :
179 : /// Controls the detach ancestor behavior.
180 : /// - When set to `NoAncestorAndReparent`, we will only detach a branch if its ancestor is a root branch. It will automatically reparent any children of the ancestor before and at the branch point.
181 : /// - When set to `MultiLevelAndNoReparent`, we will detach a branch from multiple levels of ancestors, and no reparenting will happen at all.
182 : #[derive(Debug, Clone, Copy, Default)]
183 : pub enum DetachBehavior {
184 : #[default]
185 : NoAncestorAndReparent,
186 : MultiLevelAndNoReparent,
187 : }
188 :
189 : impl std::str::FromStr for DetachBehavior {
190 : type Err = &'static str;
191 :
192 0 : fn from_str(s: &str) -> Result<Self, Self::Err> {
193 0 : match s {
194 0 : "no_ancestor_and_reparent" => Ok(DetachBehavior::NoAncestorAndReparent),
195 0 : "multi_level_and_no_reparent" => Ok(DetachBehavior::MultiLevelAndNoReparent),
196 0 : "v1" => Ok(DetachBehavior::NoAncestorAndReparent),
197 0 : "v2" => Ok(DetachBehavior::MultiLevelAndNoReparent),
198 0 : _ => Err("cannot parse detach behavior"),
199 : }
200 0 : }
201 : }
202 :
203 : impl std::fmt::Display for DetachBehavior {
204 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
205 0 : match self {
206 0 : DetachBehavior::NoAncestorAndReparent => write!(f, "no_ancestor_and_reparent"),
207 0 : DetachBehavior::MultiLevelAndNoReparent => write!(f, "multi_level_and_no_reparent"),
208 : }
209 0 : }
210 : }
211 :
212 : /// The only [`TenantState`] variants we could be `TenantState::Activating` from.
213 : ///
214 : /// XXX: We used to have more variants here, but now it's just one, which makes this rather
215 : /// useless. Remove, once we've checked that there's no client code left that looks at this.
216 1 : #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
217 : pub enum ActivatingFrom {
218 : /// Arrived to [`TenantState::Activating`] from [`TenantState::Attaching`]
219 : Attaching,
220 : }
221 :
222 : /// A state of a timeline in pageserver's memory.
223 0 : #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
224 : pub enum TimelineState {
225 : /// The timeline is recognized by the pageserver but is not yet operational.
226 : /// In particular, the walreceiver connection loop is not running for this timeline.
227 : /// It will eventually transition to state Active or Broken.
228 : Loading,
229 : /// The timeline is fully operational.
230 : /// It can be queried, and the walreceiver connection loop is running.
231 : Active,
232 : /// The timeline was previously Loading or Active but is shutting down.
233 : /// It cannot transition back into any other state.
234 : Stopping,
235 : /// The timeline is broken and not operational (previous states: Loading or Active).
236 : Broken { reason: String, backtrace: String },
237 : }
238 :
239 : #[serde_with::serde_as]
240 0 : #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
241 : pub struct CompactLsnRange {
242 : pub start: Lsn,
243 : pub end: Lsn,
244 : }
245 :
246 : #[serde_with::serde_as]
247 0 : #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
248 : pub struct CompactKeyRange {
249 : #[serde_as(as = "serde_with::DisplayFromStr")]
250 : pub start: Key,
251 : #[serde_as(as = "serde_with::DisplayFromStr")]
252 : pub end: Key,
253 : }
254 :
255 : impl From<Range<Lsn>> for CompactLsnRange {
256 12 : fn from(range: Range<Lsn>) -> Self {
257 12 : Self {
258 12 : start: range.start,
259 12 : end: range.end,
260 12 : }
261 12 : }
262 : }
263 :
264 : impl From<Range<Key>> for CompactKeyRange {
265 32 : fn from(range: Range<Key>) -> Self {
266 32 : Self {
267 32 : start: range.start,
268 32 : end: range.end,
269 32 : }
270 32 : }
271 : }
272 :
273 : impl From<CompactLsnRange> for Range<Lsn> {
274 20 : fn from(range: CompactLsnRange) -> Self {
275 20 : range.start..range.end
276 20 : }
277 : }
278 :
279 : impl From<CompactKeyRange> for Range<Key> {
280 32 : fn from(range: CompactKeyRange) -> Self {
281 32 : range.start..range.end
282 32 : }
283 : }
284 :
285 : impl CompactLsnRange {
286 8 : pub fn above(lsn: Lsn) -> Self {
287 8 : Self {
288 8 : start: lsn,
289 8 : end: Lsn::MAX,
290 8 : }
291 8 : }
292 : }
293 :
294 : #[derive(Debug, Clone, Serialize)]
295 : pub struct CompactInfoResponse {
296 : pub compact_key_range: Option<CompactKeyRange>,
297 : pub compact_lsn_range: Option<CompactLsnRange>,
298 : pub sub_compaction: bool,
299 : pub running: bool,
300 : pub job_id: usize,
301 : }
302 :
303 0 : #[derive(Serialize, Deserialize, Clone)]
304 : pub struct TimelineCreateRequest {
305 : pub new_timeline_id: TimelineId,
306 : #[serde(flatten)]
307 : pub mode: TimelineCreateRequestMode,
308 : }
309 :
310 : /// Storage controller specific extensions to [`TimelineInfo`].
311 0 : #[derive(Serialize, Deserialize, Clone)]
312 : pub struct TimelineCreateResponseStorcon {
313 : #[serde(flatten)]
314 : pub timeline_info: TimelineInfo,
315 :
316 : pub safekeepers: Option<SafekeepersInfo>,
317 : }
318 :
319 : /// Safekeepers as returned in timeline creation request to storcon or pushed to
320 : /// cplane in the post migration hook.
321 0 : #[derive(Serialize, Deserialize, Clone)]
322 : pub struct SafekeepersInfo {
323 : pub tenant_id: TenantId,
324 : pub timeline_id: TimelineId,
325 : pub generation: u32,
326 : pub safekeepers: Vec<SafekeeperInfo>,
327 : }
328 :
329 0 : #[derive(Serialize, Deserialize, Clone)]
330 : pub struct SafekeeperInfo {
331 : pub id: NodeId,
332 : pub hostname: String,
333 : }
334 :
335 0 : #[derive(Serialize, Deserialize, Clone)]
336 : #[serde(untagged)]
337 : pub enum TimelineCreateRequestMode {
338 : Branch {
339 : ancestor_timeline_id: TimelineId,
340 : #[serde(default)]
341 : ancestor_start_lsn: Option<Lsn>,
342 : // TODO: cplane sets this, but, the branching code always
343 : // inherits the ancestor's pg_version. Earlier code wasn't
344 : // using a flattened enum, so, it was an accepted field, and
345 : // we continue to accept it by having it here.
346 : pg_version: Option<u32>,
347 : },
348 : ImportPgdata {
349 : import_pgdata: TimelineCreateRequestModeImportPgdata,
350 : },
351 : // NB: Bootstrap is all-optional, and thus the serde(untagged) will cause serde to stop at Bootstrap.
352 : // (serde picks the first matching enum variant, in declaration order).
353 : Bootstrap {
354 : #[serde(default)]
355 : existing_initdb_timeline_id: Option<TimelineId>,
356 : pg_version: Option<u32>,
357 : },
358 : }
359 :
360 0 : #[derive(Serialize, Deserialize, Clone)]
361 : pub struct TimelineCreateRequestModeImportPgdata {
362 : pub location: ImportPgdataLocation,
363 : pub idempotency_key: ImportPgdataIdempotencyKey,
364 : }
365 :
366 0 : #[derive(Serialize, Deserialize, Clone, Debug)]
367 : pub enum ImportPgdataLocation {
368 : #[cfg(feature = "testing")]
369 : LocalFs { path: Utf8PathBuf },
370 : AwsS3 {
371 : region: String,
372 : bucket: String,
373 : /// A better name for this would be `prefix`; changing requires coordination with cplane.
374 : /// See <https://github.com/neondatabase/cloud/issues/20646>.
375 : key: String,
376 : },
377 : }
378 :
379 0 : #[derive(Serialize, Deserialize, Clone)]
380 : #[serde(transparent)]
381 : pub struct ImportPgdataIdempotencyKey(pub String);
382 :
383 : impl ImportPgdataIdempotencyKey {
384 0 : pub fn random() -> Self {
385 : use rand::Rng;
386 : use rand::distributions::Alphanumeric;
387 0 : Self(
388 0 : rand::thread_rng()
389 0 : .sample_iter(&Alphanumeric)
390 0 : .take(20)
391 0 : .map(char::from)
392 0 : .collect(),
393 0 : )
394 0 : }
395 : }
396 :
397 0 : #[derive(Serialize, Deserialize, Clone)]
398 : pub struct LsnLeaseRequest {
399 : pub lsn: Lsn,
400 : }
401 :
402 0 : #[derive(Serialize, Deserialize)]
403 : pub struct TenantShardSplitRequest {
404 : pub new_shard_count: u8,
405 :
406 : // A tenant's stripe size is only meaningful the first time their shard count goes
407 : // above 1: therefore during a split from 1->N shards, we may modify the stripe size.
408 : //
409 : // If this is set while the stripe count is being increased from an already >1 value,
410 : // then the request will fail with 400.
411 : pub new_stripe_size: Option<ShardStripeSize>,
412 : }
413 :
414 0 : #[derive(Serialize, Deserialize)]
415 : pub struct TenantShardSplitResponse {
416 : pub new_shards: Vec<TenantShardId>,
417 : }
418 :
419 : /// Parameters that apply to all shards in a tenant. Used during tenant creation.
420 0 : #[derive(Serialize, Deserialize, Debug)]
421 : #[serde(deny_unknown_fields)]
422 : pub struct ShardParameters {
423 : pub count: ShardCount,
424 : pub stripe_size: ShardStripeSize,
425 : }
426 :
427 : impl ShardParameters {
428 : pub const DEFAULT_STRIPE_SIZE: ShardStripeSize = ShardStripeSize(256 * 1024 / 8);
429 :
430 0 : pub fn is_unsharded(&self) -> bool {
431 0 : self.count.is_unsharded()
432 0 : }
433 : }
434 :
435 : impl Default for ShardParameters {
436 453 : fn default() -> Self {
437 453 : Self {
438 453 : count: ShardCount::new(0),
439 453 : stripe_size: Self::DEFAULT_STRIPE_SIZE,
440 453 : }
441 453 : }
442 : }
443 :
444 : #[derive(Debug, Default, Clone, Eq, PartialEq)]
445 : pub enum FieldPatch<T> {
446 : Upsert(T),
447 : Remove,
448 : #[default]
449 : Noop,
450 : }
451 :
452 : impl<T> FieldPatch<T> {
453 70 : fn is_noop(&self) -> bool {
454 70 : matches!(self, FieldPatch::Noop)
455 70 : }
456 :
457 35 : pub fn apply(self, target: &mut Option<T>) {
458 35 : match self {
459 1 : Self::Upsert(v) => *target = Some(v),
460 1 : Self::Remove => *target = None,
461 33 : Self::Noop => {}
462 : }
463 35 : }
464 :
465 10 : pub fn map<U, E, F: FnOnce(T) -> Result<U, E>>(self, map: F) -> Result<FieldPatch<U>, E> {
466 10 : match self {
467 0 : Self::Upsert(v) => Ok(FieldPatch::<U>::Upsert(map(v)?)),
468 0 : Self::Remove => Ok(FieldPatch::<U>::Remove),
469 10 : Self::Noop => Ok(FieldPatch::<U>::Noop),
470 : }
471 10 : }
472 : }
473 :
474 : impl<'de, T: Deserialize<'de>> Deserialize<'de> for FieldPatch<T> {
475 2 : fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
476 2 : where
477 2 : D: Deserializer<'de>,
478 2 : {
479 2 : Option::deserialize(deserializer).map(|opt| match opt {
480 1 : None => FieldPatch::Remove,
481 1 : Some(val) => FieldPatch::Upsert(val),
482 2 : })
483 2 : }
484 : }
485 :
486 : impl<T: Serialize> Serialize for FieldPatch<T> {
487 2 : fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
488 2 : where
489 2 : S: Serializer,
490 2 : {
491 2 : match self {
492 1 : FieldPatch::Upsert(val) => serializer.serialize_some(val),
493 1 : FieldPatch::Remove => serializer.serialize_none(),
494 0 : FieldPatch::Noop => unreachable!(),
495 : }
496 2 : }
497 : }
498 :
499 2 : #[derive(Serialize, Deserialize, Debug, Default, Clone, Eq, PartialEq)]
500 : #[serde(default)]
501 : pub struct TenantConfigPatch {
502 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
503 : pub checkpoint_distance: FieldPatch<u64>,
504 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
505 : pub checkpoint_timeout: FieldPatch<String>,
506 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
507 : pub compaction_target_size: FieldPatch<u64>,
508 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
509 : pub compaction_period: FieldPatch<String>,
510 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
511 : pub compaction_threshold: FieldPatch<usize>,
512 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
513 : pub compaction_upper_limit: FieldPatch<usize>,
514 : // defer parsing compaction_algorithm, like eviction_policy
515 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
516 : pub compaction_algorithm: FieldPatch<CompactionAlgorithmSettings>,
517 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
518 : pub compaction_l0_first: FieldPatch<bool>,
519 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
520 : pub compaction_l0_semaphore: FieldPatch<bool>,
521 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
522 : pub l0_flush_delay_threshold: FieldPatch<usize>,
523 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
524 : pub l0_flush_stall_threshold: FieldPatch<usize>,
525 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
526 : pub l0_flush_wait_upload: FieldPatch<bool>,
527 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
528 : pub gc_horizon: FieldPatch<u64>,
529 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
530 : pub gc_period: FieldPatch<String>,
531 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
532 : pub image_creation_threshold: FieldPatch<usize>,
533 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
534 : pub pitr_interval: FieldPatch<String>,
535 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
536 : pub walreceiver_connect_timeout: FieldPatch<String>,
537 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
538 : pub lagging_wal_timeout: FieldPatch<String>,
539 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
540 : pub max_lsn_wal_lag: FieldPatch<NonZeroU64>,
541 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
542 : pub eviction_policy: FieldPatch<EvictionPolicy>,
543 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
544 : pub min_resident_size_override: FieldPatch<u64>,
545 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
546 : pub evictions_low_residence_duration_metric_threshold: FieldPatch<String>,
547 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
548 : pub heatmap_period: FieldPatch<String>,
549 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
550 : pub lazy_slru_download: FieldPatch<bool>,
551 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
552 : pub timeline_get_throttle: FieldPatch<ThrottleConfig>,
553 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
554 : pub image_layer_creation_check_threshold: FieldPatch<u8>,
555 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
556 : pub image_creation_preempt_threshold: FieldPatch<usize>,
557 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
558 : pub lsn_lease_length: FieldPatch<String>,
559 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
560 : pub lsn_lease_length_for_ts: FieldPatch<String>,
561 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
562 : pub timeline_offloading: FieldPatch<bool>,
563 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
564 : pub wal_receiver_protocol_override: FieldPatch<PostgresClientProtocol>,
565 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
566 : pub rel_size_v2_enabled: FieldPatch<bool>,
567 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
568 : pub gc_compaction_enabled: FieldPatch<bool>,
569 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
570 : pub gc_compaction_initial_threshold_kb: FieldPatch<u64>,
571 : #[serde(skip_serializing_if = "FieldPatch::is_noop")]
572 : pub gc_compaction_ratio_percent: FieldPatch<u64>,
573 : }
574 :
575 : /// An alternative representation of `pageserver::tenant::TenantConf` with
576 : /// simpler types.
577 40 : #[derive(Serialize, Deserialize, Debug, Default, Clone, Eq, PartialEq)]
578 : pub struct TenantConfig {
579 : pub checkpoint_distance: Option<u64>,
580 : #[serde(default)]
581 : #[serde(with = "humantime_serde")]
582 : pub checkpoint_timeout: Option<Duration>,
583 : pub compaction_target_size: Option<u64>,
584 : #[serde(default)]
585 : #[serde(with = "humantime_serde")]
586 : pub compaction_period: Option<Duration>,
587 : pub compaction_threshold: Option<usize>,
588 : pub compaction_upper_limit: Option<usize>,
589 : // defer parsing compaction_algorithm, like eviction_policy
590 : pub compaction_algorithm: Option<CompactionAlgorithmSettings>,
591 : pub compaction_l0_first: Option<bool>,
592 : pub compaction_l0_semaphore: Option<bool>,
593 : pub l0_flush_delay_threshold: Option<usize>,
594 : pub l0_flush_stall_threshold: Option<usize>,
595 : pub l0_flush_wait_upload: Option<bool>,
596 : pub gc_horizon: Option<u64>,
597 : #[serde(default)]
598 : #[serde(with = "humantime_serde")]
599 : pub gc_period: Option<Duration>,
600 : pub image_creation_threshold: Option<usize>,
601 : #[serde(default)]
602 : #[serde(with = "humantime_serde")]
603 : pub pitr_interval: Option<Duration>,
604 : #[serde(default)]
605 : #[serde(with = "humantime_serde")]
606 : pub walreceiver_connect_timeout: Option<Duration>,
607 : #[serde(default)]
608 : #[serde(with = "humantime_serde")]
609 : pub lagging_wal_timeout: Option<Duration>,
610 : pub max_lsn_wal_lag: Option<NonZeroU64>,
611 : pub eviction_policy: Option<EvictionPolicy>,
612 : pub min_resident_size_override: Option<u64>,
613 : #[serde(default)]
614 : #[serde(with = "humantime_serde")]
615 : pub evictions_low_residence_duration_metric_threshold: Option<Duration>,
616 : #[serde(default)]
617 : #[serde(with = "humantime_serde")]
618 : pub heatmap_period: Option<Duration>,
619 : pub lazy_slru_download: Option<bool>,
620 : pub timeline_get_throttle: Option<ThrottleConfig>,
621 : pub image_layer_creation_check_threshold: Option<u8>,
622 : pub image_creation_preempt_threshold: Option<usize>,
623 : #[serde(default)]
624 : #[serde(with = "humantime_serde")]
625 : pub lsn_lease_length: Option<Duration>,
626 : #[serde(default)]
627 : #[serde(with = "humantime_serde")]
628 : pub lsn_lease_length_for_ts: Option<Duration>,
629 : pub timeline_offloading: Option<bool>,
630 : pub wal_receiver_protocol_override: Option<PostgresClientProtocol>,
631 : pub rel_size_v2_enabled: Option<bool>,
632 : pub gc_compaction_enabled: Option<bool>,
633 : pub gc_compaction_initial_threshold_kb: Option<u64>,
634 : pub gc_compaction_ratio_percent: Option<u64>,
635 : }
636 :
637 : impl TenantConfig {
638 1 : pub fn apply_patch(
639 1 : self,
640 1 : patch: TenantConfigPatch,
641 1 : ) -> Result<TenantConfig, humantime::DurationError> {
642 1 : let Self {
643 1 : mut checkpoint_distance,
644 1 : mut checkpoint_timeout,
645 1 : mut compaction_target_size,
646 1 : mut compaction_period,
647 1 : mut compaction_threshold,
648 1 : mut compaction_upper_limit,
649 1 : mut compaction_algorithm,
650 1 : mut compaction_l0_first,
651 1 : mut compaction_l0_semaphore,
652 1 : mut l0_flush_delay_threshold,
653 1 : mut l0_flush_stall_threshold,
654 1 : mut l0_flush_wait_upload,
655 1 : mut gc_horizon,
656 1 : mut gc_period,
657 1 : mut image_creation_threshold,
658 1 : mut pitr_interval,
659 1 : mut walreceiver_connect_timeout,
660 1 : mut lagging_wal_timeout,
661 1 : mut max_lsn_wal_lag,
662 1 : mut eviction_policy,
663 1 : mut min_resident_size_override,
664 1 : mut evictions_low_residence_duration_metric_threshold,
665 1 : mut heatmap_period,
666 1 : mut lazy_slru_download,
667 1 : mut timeline_get_throttle,
668 1 : mut image_layer_creation_check_threshold,
669 1 : mut image_creation_preempt_threshold,
670 1 : mut lsn_lease_length,
671 1 : mut lsn_lease_length_for_ts,
672 1 : mut timeline_offloading,
673 1 : mut wal_receiver_protocol_override,
674 1 : mut rel_size_v2_enabled,
675 1 : mut gc_compaction_enabled,
676 1 : mut gc_compaction_initial_threshold_kb,
677 1 : mut gc_compaction_ratio_percent,
678 1 : } = self;
679 1 :
680 1 : patch.checkpoint_distance.apply(&mut checkpoint_distance);
681 1 : patch
682 1 : .checkpoint_timeout
683 1 : .map(|v| humantime::parse_duration(&v))?
684 1 : .apply(&mut checkpoint_timeout);
685 1 : patch
686 1 : .compaction_target_size
687 1 : .apply(&mut compaction_target_size);
688 1 : patch
689 1 : .compaction_period
690 1 : .map(|v| humantime::parse_duration(&v))?
691 1 : .apply(&mut compaction_period);
692 1 : patch.compaction_threshold.apply(&mut compaction_threshold);
693 1 : patch
694 1 : .compaction_upper_limit
695 1 : .apply(&mut compaction_upper_limit);
696 1 : patch.compaction_algorithm.apply(&mut compaction_algorithm);
697 1 : patch.compaction_l0_first.apply(&mut compaction_l0_first);
698 1 : patch
699 1 : .compaction_l0_semaphore
700 1 : .apply(&mut compaction_l0_semaphore);
701 1 : patch
702 1 : .l0_flush_delay_threshold
703 1 : .apply(&mut l0_flush_delay_threshold);
704 1 : patch
705 1 : .l0_flush_stall_threshold
706 1 : .apply(&mut l0_flush_stall_threshold);
707 1 : patch.l0_flush_wait_upload.apply(&mut l0_flush_wait_upload);
708 1 : patch.gc_horizon.apply(&mut gc_horizon);
709 1 : patch
710 1 : .gc_period
711 1 : .map(|v| humantime::parse_duration(&v))?
712 1 : .apply(&mut gc_period);
713 1 : patch
714 1 : .image_creation_threshold
715 1 : .apply(&mut image_creation_threshold);
716 1 : patch
717 1 : .pitr_interval
718 1 : .map(|v| humantime::parse_duration(&v))?
719 1 : .apply(&mut pitr_interval);
720 1 : patch
721 1 : .walreceiver_connect_timeout
722 1 : .map(|v| humantime::parse_duration(&v))?
723 1 : .apply(&mut walreceiver_connect_timeout);
724 1 : patch
725 1 : .lagging_wal_timeout
726 1 : .map(|v| humantime::parse_duration(&v))?
727 1 : .apply(&mut lagging_wal_timeout);
728 1 : patch.max_lsn_wal_lag.apply(&mut max_lsn_wal_lag);
729 1 : patch.eviction_policy.apply(&mut eviction_policy);
730 1 : patch
731 1 : .min_resident_size_override
732 1 : .apply(&mut min_resident_size_override);
733 1 : patch
734 1 : .evictions_low_residence_duration_metric_threshold
735 1 : .map(|v| humantime::parse_duration(&v))?
736 1 : .apply(&mut evictions_low_residence_duration_metric_threshold);
737 1 : patch
738 1 : .heatmap_period
739 1 : .map(|v| humantime::parse_duration(&v))?
740 1 : .apply(&mut heatmap_period);
741 1 : patch.lazy_slru_download.apply(&mut lazy_slru_download);
742 1 : patch
743 1 : .timeline_get_throttle
744 1 : .apply(&mut timeline_get_throttle);
745 1 : patch
746 1 : .image_layer_creation_check_threshold
747 1 : .apply(&mut image_layer_creation_check_threshold);
748 1 : patch
749 1 : .image_creation_preempt_threshold
750 1 : .apply(&mut image_creation_preempt_threshold);
751 1 : patch
752 1 : .lsn_lease_length
753 1 : .map(|v| humantime::parse_duration(&v))?
754 1 : .apply(&mut lsn_lease_length);
755 1 : patch
756 1 : .lsn_lease_length_for_ts
757 1 : .map(|v| humantime::parse_duration(&v))?
758 1 : .apply(&mut lsn_lease_length_for_ts);
759 1 : patch.timeline_offloading.apply(&mut timeline_offloading);
760 1 : patch
761 1 : .wal_receiver_protocol_override
762 1 : .apply(&mut wal_receiver_protocol_override);
763 1 : patch.rel_size_v2_enabled.apply(&mut rel_size_v2_enabled);
764 1 : patch
765 1 : .gc_compaction_enabled
766 1 : .apply(&mut gc_compaction_enabled);
767 1 : patch
768 1 : .gc_compaction_initial_threshold_kb
769 1 : .apply(&mut gc_compaction_initial_threshold_kb);
770 1 : patch
771 1 : .gc_compaction_ratio_percent
772 1 : .apply(&mut gc_compaction_ratio_percent);
773 1 :
774 1 : Ok(Self {
775 1 : checkpoint_distance,
776 1 : checkpoint_timeout,
777 1 : compaction_target_size,
778 1 : compaction_period,
779 1 : compaction_threshold,
780 1 : compaction_upper_limit,
781 1 : compaction_algorithm,
782 1 : compaction_l0_first,
783 1 : compaction_l0_semaphore,
784 1 : l0_flush_delay_threshold,
785 1 : l0_flush_stall_threshold,
786 1 : l0_flush_wait_upload,
787 1 : gc_horizon,
788 1 : gc_period,
789 1 : image_creation_threshold,
790 1 : pitr_interval,
791 1 : walreceiver_connect_timeout,
792 1 : lagging_wal_timeout,
793 1 : max_lsn_wal_lag,
794 1 : eviction_policy,
795 1 : min_resident_size_override,
796 1 : evictions_low_residence_duration_metric_threshold,
797 1 : heatmap_period,
798 1 : lazy_slru_download,
799 1 : timeline_get_throttle,
800 1 : image_layer_creation_check_threshold,
801 1 : image_creation_preempt_threshold,
802 1 : lsn_lease_length,
803 1 : lsn_lease_length_for_ts,
804 1 : timeline_offloading,
805 1 : wal_receiver_protocol_override,
806 1 : rel_size_v2_enabled,
807 1 : gc_compaction_enabled,
808 1 : gc_compaction_initial_threshold_kb,
809 1 : gc_compaction_ratio_percent,
810 1 : })
811 1 : }
812 : }
813 :
814 : /// The policy for the aux file storage.
815 : ///
816 : /// It can be switched through `switch_aux_file_policy` tenant config.
817 : /// When the first aux file written, the policy will be persisted in the
818 : /// `index_part.json` file and has a limited migration path.
819 : ///
820 : /// Currently, we only allow the following migration path:
821 : ///
822 : /// Unset -> V1
823 : /// -> V2
824 : /// -> CrossValidation -> V2
825 : #[derive(
826 : Eq,
827 : PartialEq,
828 : Debug,
829 : Copy,
830 : Clone,
831 0 : strum_macros::EnumString,
832 : strum_macros::Display,
833 4 : serde_with::DeserializeFromStr,
834 : serde_with::SerializeDisplay,
835 : )]
836 : #[strum(serialize_all = "kebab-case")]
837 : pub enum AuxFilePolicy {
838 : /// V1 aux file policy: store everything in AUX_FILE_KEY
839 : #[strum(ascii_case_insensitive)]
840 : V1,
841 : /// V2 aux file policy: store in the AUX_FILE keyspace
842 : #[strum(ascii_case_insensitive)]
843 : V2,
844 : /// Cross validation runs both formats on the write path and does validation
845 : /// on the read path.
846 : #[strum(ascii_case_insensitive)]
847 : CrossValidation,
848 : }
849 :
850 0 : #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
851 : #[serde(tag = "kind")]
852 : pub enum EvictionPolicy {
853 : NoEviction,
854 : LayerAccessThreshold(EvictionPolicyLayerAccessThreshold),
855 : OnlyImitiate(EvictionPolicyLayerAccessThreshold),
856 : }
857 :
858 : impl EvictionPolicy {
859 0 : pub fn discriminant_str(&self) -> &'static str {
860 0 : match self {
861 0 : EvictionPolicy::NoEviction => "NoEviction",
862 0 : EvictionPolicy::LayerAccessThreshold(_) => "LayerAccessThreshold",
863 0 : EvictionPolicy::OnlyImitiate(_) => "OnlyImitiate",
864 : }
865 0 : }
866 : }
867 :
868 : #[derive(
869 : Eq,
870 : PartialEq,
871 : Debug,
872 : Copy,
873 : Clone,
874 0 : strum_macros::EnumString,
875 : strum_macros::Display,
876 0 : serde_with::DeserializeFromStr,
877 : serde_with::SerializeDisplay,
878 : )]
879 : #[strum(serialize_all = "kebab-case")]
880 : pub enum CompactionAlgorithm {
881 : Legacy,
882 : Tiered,
883 : }
884 :
885 : #[derive(
886 4 : Debug, Clone, Copy, PartialEq, Eq, serde_with::DeserializeFromStr, serde_with::SerializeDisplay,
887 : )]
888 : pub enum ImageCompressionAlgorithm {
889 : // Disabled for writes, support decompressing during read path
890 : Disabled,
891 : /// Zstandard compression. Level 0 means and None mean the same (default level). Levels can be negative as well.
892 : /// For details, see the [manual](http://facebook.github.io/zstd/zstd_manual.html).
893 : Zstd {
894 : level: Option<i8>,
895 : },
896 : }
897 :
898 : impl FromStr for ImageCompressionAlgorithm {
899 : type Err = anyhow::Error;
900 8 : fn from_str(s: &str) -> Result<Self, Self::Err> {
901 8 : let mut components = s.split(['(', ')']);
902 8 : let first = components
903 8 : .next()
904 8 : .ok_or_else(|| anyhow::anyhow!("empty string"))?;
905 8 : match first {
906 8 : "disabled" => Ok(ImageCompressionAlgorithm::Disabled),
907 6 : "zstd" => {
908 6 : let level = if let Some(v) = components.next() {
909 4 : let v: i8 = v.parse()?;
910 4 : Some(v)
911 : } else {
912 2 : None
913 : };
914 :
915 6 : Ok(ImageCompressionAlgorithm::Zstd { level })
916 : }
917 0 : _ => anyhow::bail!("invalid specifier '{first}'"),
918 : }
919 8 : }
920 : }
921 :
922 : impl Display for ImageCompressionAlgorithm {
923 12 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
924 12 : match self {
925 3 : ImageCompressionAlgorithm::Disabled => write!(f, "disabled"),
926 9 : ImageCompressionAlgorithm::Zstd { level } => {
927 9 : if let Some(level) = level {
928 6 : write!(f, "zstd({})", level)
929 : } else {
930 3 : write!(f, "zstd")
931 : }
932 : }
933 : }
934 12 : }
935 : }
936 :
937 0 : #[derive(Eq, PartialEq, Debug, Clone, Serialize, Deserialize)]
938 : pub struct CompactionAlgorithmSettings {
939 : pub kind: CompactionAlgorithm,
940 : }
941 :
942 8 : #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
943 : #[serde(tag = "mode", rename_all = "kebab-case", deny_unknown_fields)]
944 : pub enum L0FlushConfig {
945 : #[serde(rename_all = "snake_case")]
946 : Direct { max_concurrency: NonZeroUsize },
947 : }
948 :
949 0 : #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
950 : pub struct EvictionPolicyLayerAccessThreshold {
951 : #[serde(with = "humantime_serde")]
952 : pub period: Duration,
953 : #[serde(with = "humantime_serde")]
954 : pub threshold: Duration,
955 : }
956 :
957 6 : #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
958 : pub struct ThrottleConfig {
959 : /// See [`ThrottleConfigTaskKinds`] for why we do the serde `rename`.
960 : #[serde(rename = "task_kinds")]
961 : pub enabled: ThrottleConfigTaskKinds,
962 : pub initial: u32,
963 : #[serde(with = "humantime_serde")]
964 : pub refill_interval: Duration,
965 : pub refill_amount: NonZeroU32,
966 : pub max: u32,
967 : }
968 :
969 : /// Before <https://github.com/neondatabase/neon/pull/9962>
970 : /// the throttle was a per `Timeline::get`/`Timeline::get_vectored` call.
971 : /// The `task_kinds` field controlled which Pageserver "Task Kind"s
972 : /// were subject to the throttle.
973 : ///
974 : /// After that PR, the throttle is applied at pagestream request level
975 : /// and the `task_kinds` field does not apply since the only task kind
976 : /// that us subject to the throttle is that of the page service.
977 : ///
978 : /// However, we don't want to make a breaking config change right now
979 : /// because it means we have to migrate all the tenant configs.
980 : /// This will be done in a future PR.
981 : ///
982 : /// In the meantime, we use emptiness / non-emptsiness of the `task_kinds`
983 : /// field to determine if the throttle is enabled or not.
984 1 : #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
985 : #[serde(transparent)]
986 : pub struct ThrottleConfigTaskKinds(Vec<String>);
987 :
988 : impl ThrottleConfigTaskKinds {
989 925 : pub fn disabled() -> Self {
990 925 : Self(vec![])
991 925 : }
992 454 : pub fn is_enabled(&self) -> bool {
993 454 : !self.0.is_empty()
994 454 : }
995 : }
996 :
997 : impl ThrottleConfig {
998 925 : pub fn disabled() -> Self {
999 925 : Self {
1000 925 : enabled: ThrottleConfigTaskKinds::disabled(),
1001 925 : // other values don't matter with emtpy `task_kinds`.
1002 925 : initial: 0,
1003 925 : refill_interval: Duration::from_millis(1),
1004 925 : refill_amount: NonZeroU32::new(1).unwrap(),
1005 925 : max: 1,
1006 925 : }
1007 925 : }
1008 : /// The requests per second allowed by the given config.
1009 0 : pub fn steady_rps(&self) -> f64 {
1010 0 : (self.refill_amount.get() as f64) / (self.refill_interval.as_secs_f64())
1011 0 : }
1012 : }
1013 :
1014 : #[cfg(test)]
1015 : mod throttle_config_tests {
1016 : use super::*;
1017 :
1018 : #[test]
1019 1 : fn test_disabled_is_disabled() {
1020 1 : let config = ThrottleConfig::disabled();
1021 1 : assert!(!config.enabled.is_enabled());
1022 1 : }
1023 : #[test]
1024 1 : fn test_enabled_backwards_compat() {
1025 1 : let input = serde_json::json!({
1026 1 : "task_kinds": ["PageRequestHandler"],
1027 1 : "initial": 40000,
1028 1 : "refill_interval": "50ms",
1029 1 : "refill_amount": 1000,
1030 1 : "max": 40000,
1031 1 : "fair": true
1032 1 : });
1033 1 : let config: ThrottleConfig = serde_json::from_value(input).unwrap();
1034 1 : assert!(config.enabled.is_enabled());
1035 1 : }
1036 : }
1037 :
1038 : /// A flattened analog of a `pagesever::tenant::LocationMode`, which
1039 : /// lists out all possible states (and the virtual "Detached" state)
1040 : /// in a flat form rather than using rust-style enums.
1041 0 : #[derive(Serialize, Deserialize, Debug, Clone, Copy, Eq, PartialEq)]
1042 : pub enum LocationConfigMode {
1043 : AttachedSingle,
1044 : AttachedMulti,
1045 : AttachedStale,
1046 : Secondary,
1047 : Detached,
1048 : }
1049 :
1050 0 : #[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
1051 : pub struct LocationConfigSecondary {
1052 : pub warm: bool,
1053 : }
1054 :
1055 : /// An alternative representation of `pageserver::tenant::LocationConf`,
1056 : /// for use in external-facing APIs.
1057 0 : #[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
1058 : pub struct LocationConfig {
1059 : pub mode: LocationConfigMode,
1060 : /// If attaching, in what generation?
1061 : #[serde(default)]
1062 : pub generation: Option<u32>,
1063 :
1064 : // If requesting mode `Secondary`, configuration for that.
1065 : #[serde(default)]
1066 : pub secondary_conf: Option<LocationConfigSecondary>,
1067 :
1068 : // Shard parameters: if shard_count is nonzero, then other shard_* fields
1069 : // must be set accurately.
1070 : #[serde(default)]
1071 : pub shard_number: u8,
1072 : #[serde(default)]
1073 : pub shard_count: u8,
1074 : #[serde(default)]
1075 : pub shard_stripe_size: u32,
1076 :
1077 : // This configuration only affects attached mode, but should be provided irrespective
1078 : // of the mode, as a secondary location might transition on startup if the response
1079 : // to the `/re-attach` control plane API requests it.
1080 : pub tenant_conf: TenantConfig,
1081 : }
1082 :
1083 0 : #[derive(Serialize, Deserialize)]
1084 : pub struct LocationConfigListResponse {
1085 : pub tenant_shards: Vec<(TenantShardId, Option<LocationConfig>)>,
1086 : }
1087 :
1088 : #[derive(Serialize)]
1089 : pub struct StatusResponse {
1090 : pub id: NodeId,
1091 : }
1092 :
1093 0 : #[derive(Serialize, Deserialize, Debug)]
1094 : #[serde(deny_unknown_fields)]
1095 : pub struct TenantLocationConfigRequest {
1096 : #[serde(flatten)]
1097 : pub config: LocationConfig, // as we have a flattened field, we should reject all unknown fields in it
1098 : }
1099 :
1100 0 : #[derive(Serialize, Deserialize, Debug)]
1101 : #[serde(deny_unknown_fields)]
1102 : pub struct TenantTimeTravelRequest {
1103 : pub shard_counts: Vec<ShardCount>,
1104 : }
1105 :
1106 0 : #[derive(Serialize, Deserialize, Debug)]
1107 : #[serde(deny_unknown_fields)]
1108 : pub struct TenantShardLocation {
1109 : pub shard_id: TenantShardId,
1110 : pub node_id: NodeId,
1111 : }
1112 :
1113 0 : #[derive(Serialize, Deserialize, Debug)]
1114 : #[serde(deny_unknown_fields)]
1115 : pub struct TenantLocationConfigResponse {
1116 : pub shards: Vec<TenantShardLocation>,
1117 : // If the shards' ShardCount count is >1, stripe_size will be set.
1118 : pub stripe_size: Option<ShardStripeSize>,
1119 : }
1120 :
1121 2 : #[derive(Serialize, Deserialize, Debug)]
1122 : #[serde(deny_unknown_fields)]
1123 : pub struct TenantConfigRequest {
1124 : pub tenant_id: TenantId,
1125 : #[serde(flatten)]
1126 : pub config: TenantConfig, // as we have a flattened field, we should reject all unknown fields in it
1127 : }
1128 :
1129 : impl std::ops::Deref for TenantConfigRequest {
1130 : type Target = TenantConfig;
1131 :
1132 0 : fn deref(&self) -> &Self::Target {
1133 0 : &self.config
1134 0 : }
1135 : }
1136 :
1137 : impl TenantConfigRequest {
1138 0 : pub fn new(tenant_id: TenantId) -> TenantConfigRequest {
1139 0 : let config = TenantConfig::default();
1140 0 : TenantConfigRequest { tenant_id, config }
1141 0 : }
1142 : }
1143 :
1144 3 : #[derive(Serialize, Deserialize, Debug)]
1145 : #[serde(deny_unknown_fields)]
1146 : pub struct TenantConfigPatchRequest {
1147 : pub tenant_id: TenantId,
1148 : #[serde(flatten)]
1149 : pub config: TenantConfigPatch, // as we have a flattened field, we should reject all unknown fields in it
1150 : }
1151 :
1152 0 : #[derive(Serialize, Deserialize, Debug)]
1153 : pub struct TenantWaitLsnRequest {
1154 : #[serde(flatten)]
1155 : pub timelines: HashMap<TimelineId, Lsn>,
1156 : pub timeout: Duration,
1157 : }
1158 :
1159 : /// See [`TenantState::attachment_status`] and the OpenAPI docs for context.
1160 0 : #[derive(Serialize, Deserialize, Clone)]
1161 : #[serde(tag = "slug", content = "data", rename_all = "snake_case")]
1162 : pub enum TenantAttachmentStatus {
1163 : Maybe,
1164 : Attached,
1165 : Failed { reason: String },
1166 : }
1167 :
1168 0 : #[derive(Serialize, Deserialize, Clone)]
1169 : pub struct TenantInfo {
1170 : pub id: TenantShardId,
1171 : // NB: intentionally not part of OpenAPI, we don't want to commit to a specific set of TenantState's
1172 : pub state: TenantState,
1173 : /// Sum of the size of all layer files.
1174 : /// If a layer is present in both local FS and S3, it counts only once.
1175 : pub current_physical_size: Option<u64>, // physical size is only included in `tenant_status` endpoint
1176 : pub attachment_status: TenantAttachmentStatus,
1177 : pub generation: u32,
1178 :
1179 : /// Opaque explanation if gc is being blocked.
1180 : ///
1181 : /// Only looked up for the individual tenant detail, not the listing.
1182 : #[serde(skip_serializing_if = "Option::is_none")]
1183 : pub gc_blocking: Option<String>,
1184 : }
1185 :
1186 0 : #[derive(Serialize, Deserialize, Clone)]
1187 : pub struct TenantDetails {
1188 : #[serde(flatten)]
1189 : pub tenant_info: TenantInfo,
1190 :
1191 : pub walredo: Option<WalRedoManagerStatus>,
1192 :
1193 : pub timelines: Vec<TimelineId>,
1194 : }
1195 :
1196 0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Copy, Debug)]
1197 : pub enum TimelineArchivalState {
1198 : Archived,
1199 : Unarchived,
1200 : }
1201 :
1202 0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone)]
1203 : pub struct TimelineArchivalConfigRequest {
1204 : pub state: TimelineArchivalState,
1205 : }
1206 :
1207 0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone)]
1208 : pub struct TimelinePatchIndexPartRequest {
1209 : pub rel_size_migration: Option<RelSizeMigration>,
1210 : pub gc_compaction_last_completed_lsn: Option<Lsn>,
1211 : pub applied_gc_cutoff_lsn: Option<Lsn>,
1212 : #[serde(default)]
1213 : pub force_index_update: bool,
1214 : }
1215 :
1216 0 : #[derive(Debug, Serialize, Deserialize, Clone)]
1217 : pub struct TimelinesInfoAndOffloaded {
1218 : pub timelines: Vec<TimelineInfo>,
1219 : pub offloaded: Vec<OffloadedTimelineInfo>,
1220 : }
1221 :
1222 : /// Analog of [`TimelineInfo`] for offloaded timelines.
1223 0 : #[derive(Debug, Serialize, Deserialize, Clone)]
1224 : pub struct OffloadedTimelineInfo {
1225 : pub tenant_id: TenantShardId,
1226 : pub timeline_id: TimelineId,
1227 : /// Whether the timeline has a parent it has been branched off from or not
1228 : pub ancestor_timeline_id: Option<TimelineId>,
1229 : /// Whether to retain the branch lsn at the ancestor or not
1230 : pub ancestor_retain_lsn: Option<Lsn>,
1231 : /// The time point when the timeline was archived
1232 : pub archived_at: chrono::DateTime<chrono::Utc>,
1233 : }
1234 :
1235 12 : #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1236 : #[serde(rename_all = "camelCase")]
1237 : pub enum RelSizeMigration {
1238 : /// The tenant is using the old rel_size format.
1239 : /// Note that this enum is persisted as `Option<RelSizeMigration>` in the index part, so
1240 : /// `None` is the same as `Some(RelSizeMigration::Legacy)`.
1241 : Legacy,
1242 : /// The tenant is migrating to the new rel_size format. Both old and new rel_size format are
1243 : /// persisted in the index part. The read path will read both formats and merge them.
1244 : Migrating,
1245 : /// The tenant has migrated to the new rel_size format. Only the new rel_size format is persisted
1246 : /// in the index part, and the read path will not read the old format.
1247 : Migrated,
1248 : }
1249 :
1250 : /// This represents the output of the "timeline_detail" and "timeline_list" API calls.
1251 0 : #[derive(Debug, Serialize, Deserialize, Clone)]
1252 : pub struct TimelineInfo {
1253 : pub tenant_id: TenantShardId,
1254 : pub timeline_id: TimelineId,
1255 :
1256 : pub ancestor_timeline_id: Option<TimelineId>,
1257 : pub ancestor_lsn: Option<Lsn>,
1258 : pub last_record_lsn: Lsn,
1259 : pub prev_record_lsn: Option<Lsn>,
1260 :
1261 : /// Legacy field, retained for one version to enable old storage controller to
1262 : /// decode (it was a mandatory field).
1263 : #[serde(default, rename = "latest_gc_cutoff_lsn")]
1264 : pub _unused: Lsn,
1265 :
1266 : /// The LSN up to which GC has advanced: older data may still exist but it is not available for clients.
1267 : /// This LSN is not suitable for deciding where to create branches etc: use [`TimelineInfo::min_readable_lsn`] instead,
1268 : /// as it is easier to reason about.
1269 : #[serde(default)]
1270 : pub applied_gc_cutoff_lsn: Lsn,
1271 :
1272 : /// The upper bound of data which is either already GC'ed, or elegible to be GC'ed at any time based on PITR interval.
1273 : /// This LSN represents the "end of history" for this timeline, and callers should use it to figure out the oldest
1274 : /// LSN at which it is legal to create a branch or ephemeral endpoint.
1275 : ///
1276 : /// Note that holders of valid LSN leases may be able to create branches and read pages earlier
1277 : /// than this LSN, but new leases may not be taken out earlier than this LSN.
1278 : #[serde(default)]
1279 : pub min_readable_lsn: Lsn,
1280 :
1281 : pub disk_consistent_lsn: Lsn,
1282 :
1283 : /// The LSN that we have succesfully uploaded to remote storage
1284 : pub remote_consistent_lsn: Lsn,
1285 :
1286 : /// The LSN that we are advertizing to safekeepers
1287 : pub remote_consistent_lsn_visible: Lsn,
1288 :
1289 : /// The LSN from the start of the root timeline (never changes)
1290 : pub initdb_lsn: Lsn,
1291 :
1292 : pub current_logical_size: u64,
1293 : pub current_logical_size_is_accurate: bool,
1294 :
1295 : pub directory_entries_counts: Vec<u64>,
1296 :
1297 : /// Sum of the size of all layer files.
1298 : /// If a layer is present in both local FS and S3, it counts only once.
1299 : pub current_physical_size: Option<u64>, // is None when timeline is Unloaded
1300 : pub current_logical_size_non_incremental: Option<u64>,
1301 :
1302 : /// How many bytes of WAL are within this branch's pitr_interval. If the pitr_interval goes
1303 : /// beyond the branch's branch point, we only count up to the branch point.
1304 : pub pitr_history_size: u64,
1305 :
1306 : /// Whether this branch's branch point is within its ancestor's PITR interval (i.e. any
1307 : /// ancestor data used by this branch would have been retained anyway). If this is false, then
1308 : /// this branch may be imposing a cost on the ancestor by causing it to retain layers that it would
1309 : /// otherwise be able to GC.
1310 : pub within_ancestor_pitr: bool,
1311 :
1312 : pub timeline_dir_layer_file_size_sum: Option<u64>,
1313 :
1314 : pub wal_source_connstr: Option<String>,
1315 : pub last_received_msg_lsn: Option<Lsn>,
1316 : /// the timestamp (in microseconds) of the last received message
1317 : pub last_received_msg_ts: Option<u128>,
1318 : pub pg_version: u32,
1319 :
1320 : pub state: TimelineState,
1321 :
1322 : pub walreceiver_status: String,
1323 :
1324 : // ALWAYS add new fields at the end of the struct with `Option` to ensure forward/backward compatibility.
1325 : // Backward compatibility: you will get a JSON not containing the newly-added field.
1326 : // Forward compatibility: a previous version of the pageserver will receive a JSON. serde::Deserialize does
1327 : // not deny unknown fields by default so it's safe to set the field to some value, though it won't be
1328 : // read.
1329 : /// Whether the timeline is archived.
1330 : pub is_archived: Option<bool>,
1331 :
1332 : /// The status of the rel_size migration.
1333 : pub rel_size_migration: Option<RelSizeMigration>,
1334 : }
1335 :
1336 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
1337 : pub struct LayerMapInfo {
1338 : pub in_memory_layers: Vec<InMemoryLayerInfo>,
1339 : pub historic_layers: Vec<HistoricLayerInfo>,
1340 : }
1341 :
1342 : /// The residence status of a layer
1343 0 : #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
1344 : pub enum LayerResidenceStatus {
1345 : /// Residence status for a layer file that exists locally.
1346 : /// It may also exist on the remote, we don't care here.
1347 : Resident,
1348 : /// Residence status for a layer file that only exists on the remote.
1349 : Evicted,
1350 : }
1351 :
1352 : #[serde_as]
1353 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
1354 : pub struct LayerAccessStats {
1355 : #[serde_as(as = "serde_with::TimestampMilliSeconds")]
1356 : pub access_time: SystemTime,
1357 :
1358 : #[serde_as(as = "serde_with::TimestampMilliSeconds")]
1359 : pub residence_time: SystemTime,
1360 :
1361 : pub visible: bool,
1362 : }
1363 :
1364 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
1365 : #[serde(tag = "kind")]
1366 : pub enum InMemoryLayerInfo {
1367 : Open { lsn_start: Lsn },
1368 : Frozen { lsn_start: Lsn, lsn_end: Lsn },
1369 : }
1370 :
1371 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
1372 : #[serde(tag = "kind")]
1373 : pub enum HistoricLayerInfo {
1374 : Delta {
1375 : layer_file_name: String,
1376 : layer_file_size: u64,
1377 :
1378 : lsn_start: Lsn,
1379 : lsn_end: Lsn,
1380 : remote: bool,
1381 : access_stats: LayerAccessStats,
1382 :
1383 : l0: bool,
1384 : },
1385 : Image {
1386 : layer_file_name: String,
1387 : layer_file_size: u64,
1388 :
1389 : lsn_start: Lsn,
1390 : remote: bool,
1391 : access_stats: LayerAccessStats,
1392 : },
1393 : }
1394 :
1395 : impl HistoricLayerInfo {
1396 0 : pub fn layer_file_name(&self) -> &str {
1397 0 : match self {
1398 : HistoricLayerInfo::Delta {
1399 0 : layer_file_name, ..
1400 0 : } => layer_file_name,
1401 : HistoricLayerInfo::Image {
1402 0 : layer_file_name, ..
1403 0 : } => layer_file_name,
1404 : }
1405 0 : }
1406 0 : pub fn is_remote(&self) -> bool {
1407 0 : match self {
1408 0 : HistoricLayerInfo::Delta { remote, .. } => *remote,
1409 0 : HistoricLayerInfo::Image { remote, .. } => *remote,
1410 : }
1411 0 : }
1412 0 : pub fn set_remote(&mut self, value: bool) {
1413 0 : let field = match self {
1414 0 : HistoricLayerInfo::Delta { remote, .. } => remote,
1415 0 : HistoricLayerInfo::Image { remote, .. } => remote,
1416 : };
1417 0 : *field = value;
1418 0 : }
1419 0 : pub fn layer_file_size(&self) -> u64 {
1420 0 : match self {
1421 : HistoricLayerInfo::Delta {
1422 0 : layer_file_size, ..
1423 0 : } => *layer_file_size,
1424 : HistoricLayerInfo::Image {
1425 0 : layer_file_size, ..
1426 0 : } => *layer_file_size,
1427 : }
1428 0 : }
1429 : }
1430 :
1431 0 : #[derive(Debug, Serialize, Deserialize)]
1432 : pub struct DownloadRemoteLayersTaskSpawnRequest {
1433 : pub max_concurrent_downloads: NonZeroUsize,
1434 : }
1435 :
1436 0 : #[derive(Debug, Serialize, Deserialize)]
1437 : pub struct IngestAuxFilesRequest {
1438 : pub aux_files: HashMap<String, String>,
1439 : }
1440 :
1441 0 : #[derive(Debug, Serialize, Deserialize)]
1442 : pub struct ListAuxFilesRequest {
1443 : pub lsn: Lsn,
1444 : }
1445 :
1446 0 : #[derive(Debug, Serialize, Deserialize, Clone)]
1447 : pub struct DownloadRemoteLayersTaskInfo {
1448 : pub task_id: String,
1449 : pub state: DownloadRemoteLayersTaskState,
1450 : pub total_layer_count: u64, // stable once `completed`
1451 : pub successful_download_count: u64, // stable once `completed`
1452 : pub failed_download_count: u64, // stable once `completed`
1453 : }
1454 :
1455 0 : #[derive(Debug, Serialize, Deserialize, Clone)]
1456 : pub enum DownloadRemoteLayersTaskState {
1457 : Running,
1458 : Completed,
1459 : ShutDown,
1460 : }
1461 :
1462 0 : #[derive(Debug, Serialize, Deserialize)]
1463 : pub struct TimelineGcRequest {
1464 : pub gc_horizon: Option<u64>,
1465 : }
1466 :
1467 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
1468 : pub struct WalRedoManagerProcessStatus {
1469 : pub pid: u32,
1470 : }
1471 :
1472 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
1473 : pub struct WalRedoManagerStatus {
1474 : pub last_redo_at: Option<chrono::DateTime<chrono::Utc>>,
1475 : pub process: Option<WalRedoManagerProcessStatus>,
1476 : }
1477 :
1478 : /// The progress of a secondary tenant.
1479 : ///
1480 : /// It is mostly useful when doing a long running download: e.g. initiating
1481 : /// a download job, timing out while waiting for it to run, and then inspecting this status to understand
1482 : /// what's happening.
1483 0 : #[derive(Default, Debug, Serialize, Deserialize, Clone)]
1484 : pub struct SecondaryProgress {
1485 : /// The remote storage LastModified time of the heatmap object we last downloaded.
1486 : pub heatmap_mtime: Option<serde_system_time::SystemTime>,
1487 :
1488 : /// The number of layers currently on-disk
1489 : pub layers_downloaded: usize,
1490 : /// The number of layers in the most recently seen heatmap
1491 : pub layers_total: usize,
1492 :
1493 : /// The number of layer bytes currently on-disk
1494 : pub bytes_downloaded: u64,
1495 : /// The number of layer bytes in the most recently seen heatmap
1496 : pub bytes_total: u64,
1497 : }
1498 :
1499 0 : #[derive(Serialize, Deserialize, Debug)]
1500 : pub struct TenantScanRemoteStorageShard {
1501 : pub tenant_shard_id: TenantShardId,
1502 : pub generation: Option<u32>,
1503 : }
1504 :
1505 0 : #[derive(Serialize, Deserialize, Debug, Default)]
1506 : pub struct TenantScanRemoteStorageResponse {
1507 : pub shards: Vec<TenantScanRemoteStorageShard>,
1508 : }
1509 :
1510 0 : #[derive(Serialize, Deserialize, Debug, Clone)]
1511 : #[serde(rename_all = "snake_case")]
1512 : pub enum TenantSorting {
1513 : /// Total size of layers on local disk for all timelines in a shard.
1514 : ResidentSize,
1515 : /// The logical size of the largest timeline within a _tenant_ (not shard). Only tracked on
1516 : /// shard 0, contains the sum across all shards.
1517 : MaxLogicalSize,
1518 : /// The logical size of the largest timeline within a _tenant_ (not shard), divided by number of
1519 : /// shards. Only tracked on shard 0, and estimates the per-shard logical size.
1520 : MaxLogicalSizePerShard,
1521 : }
1522 :
1523 : impl Default for TenantSorting {
1524 0 : fn default() -> Self {
1525 0 : Self::ResidentSize
1526 0 : }
1527 : }
1528 :
1529 0 : #[derive(Serialize, Deserialize, Debug, Clone)]
1530 : pub struct TopTenantShardsRequest {
1531 : // How would you like to sort the tenants?
1532 : pub order_by: TenantSorting,
1533 :
1534 : // How many results?
1535 : pub limit: usize,
1536 :
1537 : // Omit tenants with more than this many shards (e.g. if this is the max number of shards
1538 : // that the caller would ever split to)
1539 : pub where_shards_lt: Option<ShardCount>,
1540 :
1541 : // Omit tenants where the ordering metric is less than this (this is an optimization to
1542 : // let us quickly exclude numerous tiny shards)
1543 : pub where_gt: Option<u64>,
1544 : }
1545 :
1546 0 : #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
1547 : pub struct TopTenantShardItem {
1548 : pub id: TenantShardId,
1549 :
1550 : /// Total size of layers on local disk for all timelines in this shard.
1551 : pub resident_size: u64,
1552 :
1553 : /// Total size of layers in remote storage for all timelines in this shard.
1554 : pub physical_size: u64,
1555 :
1556 : /// The largest logical size of a timeline within this _tenant_ (not shard). This is only
1557 : /// tracked on shard 0, and contains the sum of the logical size across all shards.
1558 : pub max_logical_size: u64,
1559 :
1560 : /// The largest logical size of a timeline within this _tenant_ (not shard) divided by number of
1561 : /// shards. This is only tracked on shard 0, and is only an estimate as we divide it evenly by
1562 : /// shard count, rounded up.
1563 : pub max_logical_size_per_shard: u64,
1564 : }
1565 :
1566 0 : #[derive(Serialize, Deserialize, Debug, Default)]
1567 : pub struct TopTenantShardsResponse {
1568 : pub shards: Vec<TopTenantShardItem>,
1569 : }
1570 :
1571 : pub mod virtual_file {
1572 : #[derive(
1573 : Copy,
1574 : Clone,
1575 : PartialEq,
1576 : Eq,
1577 : Hash,
1578 0 : strum_macros::EnumString,
1579 : strum_macros::Display,
1580 0 : serde_with::DeserializeFromStr,
1581 : serde_with::SerializeDisplay,
1582 : Debug,
1583 : )]
1584 : #[strum(serialize_all = "kebab-case")]
1585 : pub enum IoEngineKind {
1586 : StdFs,
1587 : #[cfg(target_os = "linux")]
1588 : TokioEpollUring,
1589 : }
1590 :
1591 : /// Direct IO modes for a pageserver.
1592 : #[derive(
1593 : Copy,
1594 : Clone,
1595 : PartialEq,
1596 : Eq,
1597 : Hash,
1598 0 : strum_macros::EnumString,
1599 : strum_macros::Display,
1600 0 : serde_with::DeserializeFromStr,
1601 : serde_with::SerializeDisplay,
1602 : Debug,
1603 : )]
1604 : #[strum(serialize_all = "kebab-case")]
1605 : #[repr(u8)]
1606 : pub enum IoMode {
1607 : /// Uses buffered IO.
1608 : Buffered,
1609 : /// Uses direct IO, error out if the operation fails.
1610 : #[cfg(target_os = "linux")]
1611 : Direct,
1612 : }
1613 :
1614 : impl IoMode {
1615 488 : pub const fn preferred() -> Self {
1616 488 : Self::Buffered
1617 488 : }
1618 : }
1619 :
1620 : impl TryFrom<u8> for IoMode {
1621 : type Error = u8;
1622 :
1623 5096 : fn try_from(value: u8) -> Result<Self, Self::Error> {
1624 5096 : Ok(match value {
1625 5096 : v if v == (IoMode::Buffered as u8) => IoMode::Buffered,
1626 : #[cfg(target_os = "linux")]
1627 0 : v if v == (IoMode::Direct as u8) => IoMode::Direct,
1628 0 : x => return Err(x),
1629 : })
1630 5096 : }
1631 : }
1632 : }
1633 :
1634 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
1635 : pub struct ScanDisposableKeysResponse {
1636 : pub disposable_count: usize,
1637 : pub not_disposable_count: usize,
1638 : }
1639 :
1640 : // Wrapped in libpq CopyData
1641 : #[derive(PartialEq, Eq, Debug)]
1642 : pub enum PagestreamFeMessage {
1643 : Exists(PagestreamExistsRequest),
1644 : Nblocks(PagestreamNblocksRequest),
1645 : GetPage(PagestreamGetPageRequest),
1646 : DbSize(PagestreamDbSizeRequest),
1647 : GetSlruSegment(PagestreamGetSlruSegmentRequest),
1648 : #[cfg(feature = "testing")]
1649 : Test(PagestreamTestRequest),
1650 : }
1651 :
1652 : // Wrapped in libpq CopyData
1653 : #[derive(strum_macros::EnumProperty)]
1654 : pub enum PagestreamBeMessage {
1655 : Exists(PagestreamExistsResponse),
1656 : Nblocks(PagestreamNblocksResponse),
1657 : GetPage(PagestreamGetPageResponse),
1658 : Error(PagestreamErrorResponse),
1659 : DbSize(PagestreamDbSizeResponse),
1660 : GetSlruSegment(PagestreamGetSlruSegmentResponse),
1661 : #[cfg(feature = "testing")]
1662 : Test(PagestreamTestResponse),
1663 : }
1664 :
1665 : // Keep in sync with `pagestore_client.h`
1666 : #[repr(u8)]
1667 : enum PagestreamFeMessageTag {
1668 : Exists = 0,
1669 : Nblocks = 1,
1670 : GetPage = 2,
1671 : DbSize = 3,
1672 : GetSlruSegment = 4,
1673 : /* future tags above this line */
1674 : /// For testing purposes, not available in production.
1675 : #[cfg(feature = "testing")]
1676 : Test = 99,
1677 : }
1678 :
1679 : // Keep in sync with `pagestore_client.h`
1680 : #[repr(u8)]
1681 : enum PagestreamBeMessageTag {
1682 : Exists = 100,
1683 : Nblocks = 101,
1684 : GetPage = 102,
1685 : Error = 103,
1686 : DbSize = 104,
1687 : GetSlruSegment = 105,
1688 : /* future tags above this line */
1689 : /// For testing purposes, not available in production.
1690 : #[cfg(feature = "testing")]
1691 : Test = 199,
1692 : }
1693 :
1694 : impl TryFrom<u8> for PagestreamFeMessageTag {
1695 : type Error = u8;
1696 4 : fn try_from(value: u8) -> Result<Self, u8> {
1697 4 : match value {
1698 1 : 0 => Ok(PagestreamFeMessageTag::Exists),
1699 1 : 1 => Ok(PagestreamFeMessageTag::Nblocks),
1700 1 : 2 => Ok(PagestreamFeMessageTag::GetPage),
1701 1 : 3 => Ok(PagestreamFeMessageTag::DbSize),
1702 0 : 4 => Ok(PagestreamFeMessageTag::GetSlruSegment),
1703 : #[cfg(feature = "testing")]
1704 0 : 99 => Ok(PagestreamFeMessageTag::Test),
1705 0 : _ => Err(value),
1706 : }
1707 4 : }
1708 : }
1709 :
1710 : impl TryFrom<u8> for PagestreamBeMessageTag {
1711 : type Error = u8;
1712 0 : fn try_from(value: u8) -> Result<Self, u8> {
1713 0 : match value {
1714 0 : 100 => Ok(PagestreamBeMessageTag::Exists),
1715 0 : 101 => Ok(PagestreamBeMessageTag::Nblocks),
1716 0 : 102 => Ok(PagestreamBeMessageTag::GetPage),
1717 0 : 103 => Ok(PagestreamBeMessageTag::Error),
1718 0 : 104 => Ok(PagestreamBeMessageTag::DbSize),
1719 0 : 105 => Ok(PagestreamBeMessageTag::GetSlruSegment),
1720 : #[cfg(feature = "testing")]
1721 0 : 199 => Ok(PagestreamBeMessageTag::Test),
1722 0 : _ => Err(value),
1723 : }
1724 0 : }
1725 : }
1726 :
1727 : // A GetPage request contains two LSN values:
1728 : //
1729 : // request_lsn: Get the page version at this point in time. Lsn::Max is a special value that means
1730 : // "get the latest version present". It's used by the primary server, which knows that no one else
1731 : // is writing WAL. 'not_modified_since' must be set to a proper value even if request_lsn is
1732 : // Lsn::Max. Standby servers use the current replay LSN as the request LSN.
1733 : //
1734 : // not_modified_since: Hint to the pageserver that the client knows that the page has not been
1735 : // modified between 'not_modified_since' and the request LSN. It's always correct to set
1736 : // 'not_modified_since equal' to 'request_lsn' (unless Lsn::Max is used as the 'request_lsn'), but
1737 : // passing an earlier LSN can speed up the request, by allowing the pageserver to process the
1738 : // request without waiting for 'request_lsn' to arrive.
1739 : //
1740 : // The now-defunct V1 interface contained only one LSN, and a boolean 'latest' flag. The V1 interface was
1741 : // sufficient for the primary; the 'lsn' was equivalent to the 'not_modified_since' value, and
1742 : // 'latest' was set to true. The V2 interface was added because there was no correct way for a
1743 : // standby to request a page at a particular non-latest LSN, and also include the
1744 : // 'not_modified_since' hint. That led to an awkward choice of either using an old LSN in the
1745 : // request, if the standby knows that the page hasn't been modified since, and risk getting an error
1746 : // if that LSN has fallen behind the GC horizon, or requesting the current replay LSN, which could
1747 : // require the pageserver unnecessarily to wait for the WAL to arrive up to that point. The new V2
1748 : // interface allows sending both LSNs, and let the pageserver do the right thing. There was no
1749 : // difference in the responses between V1 and V2.
1750 : //
1751 : // V3 version of protocol adds request ID to all requests. This request ID is also included in response
1752 : // as well as other fields from requests, which allows to verify that we receive response for our request.
1753 : // We copy fields from request to response to make checking more reliable: request ID is formed from process ID
1754 : // and local counter, so in principle there can be duplicated requests IDs if process PID is reused.
1755 : //
1756 : #[derive(Debug, PartialEq, Eq, Clone, Copy)]
1757 : pub enum PagestreamProtocolVersion {
1758 : V2,
1759 : V3,
1760 : }
1761 :
1762 : pub type RequestId = u64;
1763 :
1764 : #[derive(Debug, PartialEq, Eq, Clone, Copy)]
1765 : pub struct PagestreamRequest {
1766 : pub reqid: RequestId,
1767 : pub request_lsn: Lsn,
1768 : pub not_modified_since: Lsn,
1769 : }
1770 :
1771 : #[derive(Debug, PartialEq, Eq, Clone, Copy)]
1772 : pub struct PagestreamExistsRequest {
1773 : pub hdr: PagestreamRequest,
1774 : pub rel: RelTag,
1775 : }
1776 :
1777 : #[derive(Debug, PartialEq, Eq, Clone, Copy)]
1778 : pub struct PagestreamNblocksRequest {
1779 : pub hdr: PagestreamRequest,
1780 : pub rel: RelTag,
1781 : }
1782 :
1783 : #[derive(Debug, PartialEq, Eq, Clone, Copy)]
1784 : pub struct PagestreamGetPageRequest {
1785 : pub hdr: PagestreamRequest,
1786 : pub rel: RelTag,
1787 : pub blkno: u32,
1788 : }
1789 :
1790 : #[derive(Debug, PartialEq, Eq, Clone, Copy)]
1791 : pub struct PagestreamDbSizeRequest {
1792 : pub hdr: PagestreamRequest,
1793 : pub dbnode: u32,
1794 : }
1795 :
1796 : #[derive(Debug, PartialEq, Eq, Clone, Copy)]
1797 : pub struct PagestreamGetSlruSegmentRequest {
1798 : pub hdr: PagestreamRequest,
1799 : pub kind: u8,
1800 : pub segno: u32,
1801 : }
1802 :
1803 : #[derive(Debug)]
1804 : pub struct PagestreamExistsResponse {
1805 : pub req: PagestreamExistsRequest,
1806 : pub exists: bool,
1807 : }
1808 :
1809 : #[derive(Debug)]
1810 : pub struct PagestreamNblocksResponse {
1811 : pub req: PagestreamNblocksRequest,
1812 : pub n_blocks: u32,
1813 : }
1814 :
1815 : #[derive(Debug)]
1816 : pub struct PagestreamGetPageResponse {
1817 : pub req: PagestreamGetPageRequest,
1818 : pub page: Bytes,
1819 : }
1820 :
1821 : #[derive(Debug)]
1822 : pub struct PagestreamGetSlruSegmentResponse {
1823 : pub req: PagestreamGetSlruSegmentRequest,
1824 : pub segment: Bytes,
1825 : }
1826 :
1827 : #[derive(Debug)]
1828 : pub struct PagestreamErrorResponse {
1829 : pub req: PagestreamRequest,
1830 : pub message: String,
1831 : }
1832 :
1833 : #[derive(Debug)]
1834 : pub struct PagestreamDbSizeResponse {
1835 : pub req: PagestreamDbSizeRequest,
1836 : pub db_size: i64,
1837 : }
1838 :
1839 : #[cfg(feature = "testing")]
1840 : #[derive(Debug, PartialEq, Eq, Clone)]
1841 : pub struct PagestreamTestRequest {
1842 : pub hdr: PagestreamRequest,
1843 : pub batch_key: u64,
1844 : pub message: String,
1845 : }
1846 :
1847 : #[cfg(feature = "testing")]
1848 : #[derive(Debug)]
1849 : pub struct PagestreamTestResponse {
1850 : pub req: PagestreamTestRequest,
1851 : }
1852 :
1853 : // This is a cut-down version of TenantHistorySize from the pageserver crate, omitting fields
1854 : // that require pageserver-internal types. It is sufficient to get the total size.
1855 0 : #[derive(Serialize, Deserialize, Debug)]
1856 : pub struct TenantHistorySize {
1857 : pub id: TenantId,
1858 : /// Size is a mixture of WAL and logical size, so the unit is bytes.
1859 : ///
1860 : /// Will be none if `?inputs_only=true` was given.
1861 : pub size: Option<u64>,
1862 : }
1863 :
1864 : impl PagestreamFeMessage {
1865 : /// Serialize a compute -> pageserver message. This is currently only used in testing
1866 : /// tools. Always uses protocol version 3.
1867 4 : pub fn serialize(&self) -> Bytes {
1868 4 : let mut bytes = BytesMut::new();
1869 4 :
1870 4 : match self {
1871 1 : Self::Exists(req) => {
1872 1 : bytes.put_u8(PagestreamFeMessageTag::Exists as u8);
1873 1 : bytes.put_u64(req.hdr.reqid);
1874 1 : bytes.put_u64(req.hdr.request_lsn.0);
1875 1 : bytes.put_u64(req.hdr.not_modified_since.0);
1876 1 : bytes.put_u32(req.rel.spcnode);
1877 1 : bytes.put_u32(req.rel.dbnode);
1878 1 : bytes.put_u32(req.rel.relnode);
1879 1 : bytes.put_u8(req.rel.forknum);
1880 1 : }
1881 :
1882 1 : Self::Nblocks(req) => {
1883 1 : bytes.put_u8(PagestreamFeMessageTag::Nblocks as u8);
1884 1 : bytes.put_u64(req.hdr.reqid);
1885 1 : bytes.put_u64(req.hdr.request_lsn.0);
1886 1 : bytes.put_u64(req.hdr.not_modified_since.0);
1887 1 : bytes.put_u32(req.rel.spcnode);
1888 1 : bytes.put_u32(req.rel.dbnode);
1889 1 : bytes.put_u32(req.rel.relnode);
1890 1 : bytes.put_u8(req.rel.forknum);
1891 1 : }
1892 :
1893 1 : Self::GetPage(req) => {
1894 1 : bytes.put_u8(PagestreamFeMessageTag::GetPage as u8);
1895 1 : bytes.put_u64(req.hdr.reqid);
1896 1 : bytes.put_u64(req.hdr.request_lsn.0);
1897 1 : bytes.put_u64(req.hdr.not_modified_since.0);
1898 1 : bytes.put_u32(req.rel.spcnode);
1899 1 : bytes.put_u32(req.rel.dbnode);
1900 1 : bytes.put_u32(req.rel.relnode);
1901 1 : bytes.put_u8(req.rel.forknum);
1902 1 : bytes.put_u32(req.blkno);
1903 1 : }
1904 :
1905 1 : Self::DbSize(req) => {
1906 1 : bytes.put_u8(PagestreamFeMessageTag::DbSize as u8);
1907 1 : bytes.put_u64(req.hdr.reqid);
1908 1 : bytes.put_u64(req.hdr.request_lsn.0);
1909 1 : bytes.put_u64(req.hdr.not_modified_since.0);
1910 1 : bytes.put_u32(req.dbnode);
1911 1 : }
1912 :
1913 0 : Self::GetSlruSegment(req) => {
1914 0 : bytes.put_u8(PagestreamFeMessageTag::GetSlruSegment as u8);
1915 0 : bytes.put_u64(req.hdr.reqid);
1916 0 : bytes.put_u64(req.hdr.request_lsn.0);
1917 0 : bytes.put_u64(req.hdr.not_modified_since.0);
1918 0 : bytes.put_u8(req.kind);
1919 0 : bytes.put_u32(req.segno);
1920 0 : }
1921 : #[cfg(feature = "testing")]
1922 0 : Self::Test(req) => {
1923 0 : bytes.put_u8(PagestreamFeMessageTag::Test as u8);
1924 0 : bytes.put_u64(req.hdr.reqid);
1925 0 : bytes.put_u64(req.hdr.request_lsn.0);
1926 0 : bytes.put_u64(req.hdr.not_modified_since.0);
1927 0 : bytes.put_u64(req.batch_key);
1928 0 : let message = req.message.as_bytes();
1929 0 : bytes.put_u64(message.len() as u64);
1930 0 : bytes.put_slice(message);
1931 0 : }
1932 : }
1933 :
1934 4 : bytes.into()
1935 4 : }
1936 :
1937 4 : pub fn parse<R: std::io::Read>(
1938 4 : body: &mut R,
1939 4 : protocol_version: PagestreamProtocolVersion,
1940 4 : ) -> anyhow::Result<PagestreamFeMessage> {
1941 : // these correspond to the NeonMessageTag enum in pagestore_client.h
1942 : //
1943 : // TODO: consider using protobuf or serde bincode for less error prone
1944 : // serialization.
1945 4 : let msg_tag = body.read_u8()?;
1946 4 : let (reqid, request_lsn, not_modified_since) = match protocol_version {
1947 : PagestreamProtocolVersion::V2 => (
1948 : 0,
1949 0 : Lsn::from(body.read_u64::<BigEndian>()?),
1950 0 : Lsn::from(body.read_u64::<BigEndian>()?),
1951 : ),
1952 : PagestreamProtocolVersion::V3 => (
1953 4 : body.read_u64::<BigEndian>()?,
1954 4 : Lsn::from(body.read_u64::<BigEndian>()?),
1955 4 : Lsn::from(body.read_u64::<BigEndian>()?),
1956 : ),
1957 : };
1958 :
1959 4 : match PagestreamFeMessageTag::try_from(msg_tag)
1960 4 : .map_err(|tag: u8| anyhow::anyhow!("invalid tag {tag}"))?
1961 : {
1962 : PagestreamFeMessageTag::Exists => {
1963 : Ok(PagestreamFeMessage::Exists(PagestreamExistsRequest {
1964 1 : hdr: PagestreamRequest {
1965 1 : reqid,
1966 1 : request_lsn,
1967 1 : not_modified_since,
1968 1 : },
1969 1 : rel: RelTag {
1970 1 : spcnode: body.read_u32::<BigEndian>()?,
1971 1 : dbnode: body.read_u32::<BigEndian>()?,
1972 1 : relnode: body.read_u32::<BigEndian>()?,
1973 1 : forknum: body.read_u8()?,
1974 : },
1975 : }))
1976 : }
1977 : PagestreamFeMessageTag::Nblocks => {
1978 : Ok(PagestreamFeMessage::Nblocks(PagestreamNblocksRequest {
1979 1 : hdr: PagestreamRequest {
1980 1 : reqid,
1981 1 : request_lsn,
1982 1 : not_modified_since,
1983 1 : },
1984 1 : rel: RelTag {
1985 1 : spcnode: body.read_u32::<BigEndian>()?,
1986 1 : dbnode: body.read_u32::<BigEndian>()?,
1987 1 : relnode: body.read_u32::<BigEndian>()?,
1988 1 : forknum: body.read_u8()?,
1989 : },
1990 : }))
1991 : }
1992 : PagestreamFeMessageTag::GetPage => {
1993 : Ok(PagestreamFeMessage::GetPage(PagestreamGetPageRequest {
1994 1 : hdr: PagestreamRequest {
1995 1 : reqid,
1996 1 : request_lsn,
1997 1 : not_modified_since,
1998 1 : },
1999 1 : rel: RelTag {
2000 1 : spcnode: body.read_u32::<BigEndian>()?,
2001 1 : dbnode: body.read_u32::<BigEndian>()?,
2002 1 : relnode: body.read_u32::<BigEndian>()?,
2003 1 : forknum: body.read_u8()?,
2004 : },
2005 1 : blkno: body.read_u32::<BigEndian>()?,
2006 : }))
2007 : }
2008 : PagestreamFeMessageTag::DbSize => {
2009 : Ok(PagestreamFeMessage::DbSize(PagestreamDbSizeRequest {
2010 1 : hdr: PagestreamRequest {
2011 1 : reqid,
2012 1 : request_lsn,
2013 1 : not_modified_since,
2014 1 : },
2015 1 : dbnode: body.read_u32::<BigEndian>()?,
2016 : }))
2017 : }
2018 : PagestreamFeMessageTag::GetSlruSegment => Ok(PagestreamFeMessage::GetSlruSegment(
2019 : PagestreamGetSlruSegmentRequest {
2020 0 : hdr: PagestreamRequest {
2021 0 : reqid,
2022 0 : request_lsn,
2023 0 : not_modified_since,
2024 0 : },
2025 0 : kind: body.read_u8()?,
2026 0 : segno: body.read_u32::<BigEndian>()?,
2027 : },
2028 : )),
2029 : #[cfg(feature = "testing")]
2030 : PagestreamFeMessageTag::Test => Ok(PagestreamFeMessage::Test(PagestreamTestRequest {
2031 0 : hdr: PagestreamRequest {
2032 0 : reqid,
2033 0 : request_lsn,
2034 0 : not_modified_since,
2035 0 : },
2036 0 : batch_key: body.read_u64::<BigEndian>()?,
2037 : message: {
2038 0 : let len = body.read_u64::<BigEndian>()?;
2039 0 : let mut buf = vec![0; len as usize];
2040 0 : body.read_exact(&mut buf)?;
2041 0 : String::from_utf8(buf)?
2042 : },
2043 : })),
2044 : }
2045 4 : }
2046 : }
2047 :
2048 : impl PagestreamBeMessage {
2049 0 : pub fn serialize(&self, protocol_version: PagestreamProtocolVersion) -> Bytes {
2050 0 : let mut bytes = BytesMut::new();
2051 :
2052 : use PagestreamBeMessageTag as Tag;
2053 0 : match protocol_version {
2054 : PagestreamProtocolVersion::V2 => {
2055 0 : match self {
2056 0 : Self::Exists(resp) => {
2057 0 : bytes.put_u8(Tag::Exists as u8);
2058 0 : bytes.put_u8(resp.exists as u8);
2059 0 : }
2060 :
2061 0 : Self::Nblocks(resp) => {
2062 0 : bytes.put_u8(Tag::Nblocks as u8);
2063 0 : bytes.put_u32(resp.n_blocks);
2064 0 : }
2065 :
2066 0 : Self::GetPage(resp) => {
2067 0 : bytes.put_u8(Tag::GetPage as u8);
2068 0 : bytes.put(&resp.page[..])
2069 : }
2070 :
2071 0 : Self::Error(resp) => {
2072 0 : bytes.put_u8(Tag::Error as u8);
2073 0 : bytes.put(resp.message.as_bytes());
2074 0 : bytes.put_u8(0); // null terminator
2075 0 : }
2076 0 : Self::DbSize(resp) => {
2077 0 : bytes.put_u8(Tag::DbSize as u8);
2078 0 : bytes.put_i64(resp.db_size);
2079 0 : }
2080 :
2081 0 : Self::GetSlruSegment(resp) => {
2082 0 : bytes.put_u8(Tag::GetSlruSegment as u8);
2083 0 : bytes.put_u32((resp.segment.len() / BLCKSZ as usize) as u32);
2084 0 : bytes.put(&resp.segment[..]);
2085 0 : }
2086 :
2087 : #[cfg(feature = "testing")]
2088 0 : Self::Test(resp) => {
2089 0 : bytes.put_u8(Tag::Test as u8);
2090 0 : bytes.put_u64(resp.req.batch_key);
2091 0 : let message = resp.req.message.as_bytes();
2092 0 : bytes.put_u64(message.len() as u64);
2093 0 : bytes.put_slice(message);
2094 0 : }
2095 : }
2096 : }
2097 : PagestreamProtocolVersion::V3 => {
2098 0 : match self {
2099 0 : Self::Exists(resp) => {
2100 0 : bytes.put_u8(Tag::Exists as u8);
2101 0 : bytes.put_u64(resp.req.hdr.reqid);
2102 0 : bytes.put_u64(resp.req.hdr.request_lsn.0);
2103 0 : bytes.put_u64(resp.req.hdr.not_modified_since.0);
2104 0 : bytes.put_u32(resp.req.rel.spcnode);
2105 0 : bytes.put_u32(resp.req.rel.dbnode);
2106 0 : bytes.put_u32(resp.req.rel.relnode);
2107 0 : bytes.put_u8(resp.req.rel.forknum);
2108 0 : bytes.put_u8(resp.exists as u8);
2109 0 : }
2110 :
2111 0 : Self::Nblocks(resp) => {
2112 0 : bytes.put_u8(Tag::Nblocks as u8);
2113 0 : bytes.put_u64(resp.req.hdr.reqid);
2114 0 : bytes.put_u64(resp.req.hdr.request_lsn.0);
2115 0 : bytes.put_u64(resp.req.hdr.not_modified_since.0);
2116 0 : bytes.put_u32(resp.req.rel.spcnode);
2117 0 : bytes.put_u32(resp.req.rel.dbnode);
2118 0 : bytes.put_u32(resp.req.rel.relnode);
2119 0 : bytes.put_u8(resp.req.rel.forknum);
2120 0 : bytes.put_u32(resp.n_blocks);
2121 0 : }
2122 :
2123 0 : Self::GetPage(resp) => {
2124 0 : bytes.put_u8(Tag::GetPage as u8);
2125 0 : bytes.put_u64(resp.req.hdr.reqid);
2126 0 : bytes.put_u64(resp.req.hdr.request_lsn.0);
2127 0 : bytes.put_u64(resp.req.hdr.not_modified_since.0);
2128 0 : bytes.put_u32(resp.req.rel.spcnode);
2129 0 : bytes.put_u32(resp.req.rel.dbnode);
2130 0 : bytes.put_u32(resp.req.rel.relnode);
2131 0 : bytes.put_u8(resp.req.rel.forknum);
2132 0 : bytes.put_u32(resp.req.blkno);
2133 0 : bytes.put(&resp.page[..])
2134 : }
2135 :
2136 0 : Self::Error(resp) => {
2137 0 : bytes.put_u8(Tag::Error as u8);
2138 0 : bytes.put_u64(resp.req.reqid);
2139 0 : bytes.put_u64(resp.req.request_lsn.0);
2140 0 : bytes.put_u64(resp.req.not_modified_since.0);
2141 0 : bytes.put(resp.message.as_bytes());
2142 0 : bytes.put_u8(0); // null terminator
2143 0 : }
2144 0 : Self::DbSize(resp) => {
2145 0 : bytes.put_u8(Tag::DbSize as u8);
2146 0 : bytes.put_u64(resp.req.hdr.reqid);
2147 0 : bytes.put_u64(resp.req.hdr.request_lsn.0);
2148 0 : bytes.put_u64(resp.req.hdr.not_modified_since.0);
2149 0 : bytes.put_u32(resp.req.dbnode);
2150 0 : bytes.put_i64(resp.db_size);
2151 0 : }
2152 :
2153 0 : Self::GetSlruSegment(resp) => {
2154 0 : bytes.put_u8(Tag::GetSlruSegment as u8);
2155 0 : bytes.put_u64(resp.req.hdr.reqid);
2156 0 : bytes.put_u64(resp.req.hdr.request_lsn.0);
2157 0 : bytes.put_u64(resp.req.hdr.not_modified_since.0);
2158 0 : bytes.put_u8(resp.req.kind);
2159 0 : bytes.put_u32(resp.req.segno);
2160 0 : bytes.put_u32((resp.segment.len() / BLCKSZ as usize) as u32);
2161 0 : bytes.put(&resp.segment[..]);
2162 0 : }
2163 :
2164 : #[cfg(feature = "testing")]
2165 0 : Self::Test(resp) => {
2166 0 : bytes.put_u8(Tag::Test as u8);
2167 0 : bytes.put_u64(resp.req.hdr.reqid);
2168 0 : bytes.put_u64(resp.req.hdr.request_lsn.0);
2169 0 : bytes.put_u64(resp.req.hdr.not_modified_since.0);
2170 0 : bytes.put_u64(resp.req.batch_key);
2171 0 : let message = resp.req.message.as_bytes();
2172 0 : bytes.put_u64(message.len() as u64);
2173 0 : bytes.put_slice(message);
2174 0 : }
2175 : }
2176 : }
2177 : }
2178 0 : bytes.into()
2179 0 : }
2180 :
2181 0 : pub fn deserialize(buf: Bytes) -> anyhow::Result<Self> {
2182 0 : let mut buf = buf.reader();
2183 0 : let msg_tag = buf.read_u8()?;
2184 :
2185 : use PagestreamBeMessageTag as Tag;
2186 0 : let ok =
2187 0 : match Tag::try_from(msg_tag).map_err(|tag: u8| anyhow::anyhow!("invalid tag {tag}"))? {
2188 : Tag::Exists => {
2189 0 : let reqid = buf.read_u64::<BigEndian>()?;
2190 0 : let request_lsn = Lsn(buf.read_u64::<BigEndian>()?);
2191 0 : let not_modified_since = Lsn(buf.read_u64::<BigEndian>()?);
2192 0 : let rel = RelTag {
2193 0 : spcnode: buf.read_u32::<BigEndian>()?,
2194 0 : dbnode: buf.read_u32::<BigEndian>()?,
2195 0 : relnode: buf.read_u32::<BigEndian>()?,
2196 0 : forknum: buf.read_u8()?,
2197 : };
2198 0 : let exists = buf.read_u8()? != 0;
2199 0 : Self::Exists(PagestreamExistsResponse {
2200 0 : req: PagestreamExistsRequest {
2201 0 : hdr: PagestreamRequest {
2202 0 : reqid,
2203 0 : request_lsn,
2204 0 : not_modified_since,
2205 0 : },
2206 0 : rel,
2207 0 : },
2208 0 : exists,
2209 0 : })
2210 : }
2211 : Tag::Nblocks => {
2212 0 : let reqid = buf.read_u64::<BigEndian>()?;
2213 0 : let request_lsn = Lsn(buf.read_u64::<BigEndian>()?);
2214 0 : let not_modified_since = Lsn(buf.read_u64::<BigEndian>()?);
2215 0 : let rel = RelTag {
2216 0 : spcnode: buf.read_u32::<BigEndian>()?,
2217 0 : dbnode: buf.read_u32::<BigEndian>()?,
2218 0 : relnode: buf.read_u32::<BigEndian>()?,
2219 0 : forknum: buf.read_u8()?,
2220 : };
2221 0 : let n_blocks = buf.read_u32::<BigEndian>()?;
2222 0 : Self::Nblocks(PagestreamNblocksResponse {
2223 0 : req: PagestreamNblocksRequest {
2224 0 : hdr: PagestreamRequest {
2225 0 : reqid,
2226 0 : request_lsn,
2227 0 : not_modified_since,
2228 0 : },
2229 0 : rel,
2230 0 : },
2231 0 : n_blocks,
2232 0 : })
2233 : }
2234 : Tag::GetPage => {
2235 0 : let reqid = buf.read_u64::<BigEndian>()?;
2236 0 : let request_lsn = Lsn(buf.read_u64::<BigEndian>()?);
2237 0 : let not_modified_since = Lsn(buf.read_u64::<BigEndian>()?);
2238 0 : let rel = RelTag {
2239 0 : spcnode: buf.read_u32::<BigEndian>()?,
2240 0 : dbnode: buf.read_u32::<BigEndian>()?,
2241 0 : relnode: buf.read_u32::<BigEndian>()?,
2242 0 : forknum: buf.read_u8()?,
2243 : };
2244 0 : let blkno = buf.read_u32::<BigEndian>()?;
2245 0 : let mut page = vec![0; 8192]; // TODO: use MaybeUninit
2246 0 : buf.read_exact(&mut page)?;
2247 0 : Self::GetPage(PagestreamGetPageResponse {
2248 0 : req: PagestreamGetPageRequest {
2249 0 : hdr: PagestreamRequest {
2250 0 : reqid,
2251 0 : request_lsn,
2252 0 : not_modified_since,
2253 0 : },
2254 0 : rel,
2255 0 : blkno,
2256 0 : },
2257 0 : page: page.into(),
2258 0 : })
2259 : }
2260 : Tag::Error => {
2261 0 : let reqid = buf.read_u64::<BigEndian>()?;
2262 0 : let request_lsn = Lsn(buf.read_u64::<BigEndian>()?);
2263 0 : let not_modified_since = Lsn(buf.read_u64::<BigEndian>()?);
2264 0 : let mut msg = Vec::new();
2265 0 : buf.read_until(0, &mut msg)?;
2266 0 : let cstring = std::ffi::CString::from_vec_with_nul(msg)?;
2267 0 : let rust_str = cstring.to_str()?;
2268 0 : Self::Error(PagestreamErrorResponse {
2269 0 : req: PagestreamRequest {
2270 0 : reqid,
2271 0 : request_lsn,
2272 0 : not_modified_since,
2273 0 : },
2274 0 : message: rust_str.to_owned(),
2275 0 : })
2276 : }
2277 : Tag::DbSize => {
2278 0 : let reqid = buf.read_u64::<BigEndian>()?;
2279 0 : let request_lsn = Lsn(buf.read_u64::<BigEndian>()?);
2280 0 : let not_modified_since = Lsn(buf.read_u64::<BigEndian>()?);
2281 0 : let dbnode = buf.read_u32::<BigEndian>()?;
2282 0 : let db_size = buf.read_i64::<BigEndian>()?;
2283 0 : Self::DbSize(PagestreamDbSizeResponse {
2284 0 : req: PagestreamDbSizeRequest {
2285 0 : hdr: PagestreamRequest {
2286 0 : reqid,
2287 0 : request_lsn,
2288 0 : not_modified_since,
2289 0 : },
2290 0 : dbnode,
2291 0 : },
2292 0 : db_size,
2293 0 : })
2294 : }
2295 : Tag::GetSlruSegment => {
2296 0 : let reqid = buf.read_u64::<BigEndian>()?;
2297 0 : let request_lsn = Lsn(buf.read_u64::<BigEndian>()?);
2298 0 : let not_modified_since = Lsn(buf.read_u64::<BigEndian>()?);
2299 0 : let kind = buf.read_u8()?;
2300 0 : let segno = buf.read_u32::<BigEndian>()?;
2301 0 : let n_blocks = buf.read_u32::<BigEndian>()?;
2302 0 : let mut segment = vec![0; n_blocks as usize * BLCKSZ as usize];
2303 0 : buf.read_exact(&mut segment)?;
2304 0 : Self::GetSlruSegment(PagestreamGetSlruSegmentResponse {
2305 0 : req: PagestreamGetSlruSegmentRequest {
2306 0 : hdr: PagestreamRequest {
2307 0 : reqid,
2308 0 : request_lsn,
2309 0 : not_modified_since,
2310 0 : },
2311 0 : kind,
2312 0 : segno,
2313 0 : },
2314 0 : segment: segment.into(),
2315 0 : })
2316 : }
2317 : #[cfg(feature = "testing")]
2318 : Tag::Test => {
2319 0 : let reqid = buf.read_u64::<BigEndian>()?;
2320 0 : let request_lsn = Lsn(buf.read_u64::<BigEndian>()?);
2321 0 : let not_modified_since = Lsn(buf.read_u64::<BigEndian>()?);
2322 0 : let batch_key = buf.read_u64::<BigEndian>()?;
2323 0 : let len = buf.read_u64::<BigEndian>()?;
2324 0 : let mut msg = vec![0; len as usize];
2325 0 : buf.read_exact(&mut msg)?;
2326 0 : let message = String::from_utf8(msg)?;
2327 0 : Self::Test(PagestreamTestResponse {
2328 0 : req: PagestreamTestRequest {
2329 0 : hdr: PagestreamRequest {
2330 0 : reqid,
2331 0 : request_lsn,
2332 0 : not_modified_since,
2333 0 : },
2334 0 : batch_key,
2335 0 : message,
2336 0 : },
2337 0 : })
2338 : }
2339 : };
2340 0 : let remaining = buf.into_inner();
2341 0 : if !remaining.is_empty() {
2342 0 : anyhow::bail!(
2343 0 : "remaining bytes in msg with tag={msg_tag}: {}",
2344 0 : remaining.len()
2345 0 : );
2346 0 : }
2347 0 : Ok(ok)
2348 0 : }
2349 :
2350 0 : pub fn kind(&self) -> &'static str {
2351 0 : match self {
2352 0 : Self::Exists(_) => "Exists",
2353 0 : Self::Nblocks(_) => "Nblocks",
2354 0 : Self::GetPage(_) => "GetPage",
2355 0 : Self::Error(_) => "Error",
2356 0 : Self::DbSize(_) => "DbSize",
2357 0 : Self::GetSlruSegment(_) => "GetSlruSegment",
2358 : #[cfg(feature = "testing")]
2359 0 : Self::Test(_) => "Test",
2360 : }
2361 0 : }
2362 : }
2363 :
2364 0 : #[derive(Debug, Serialize, Deserialize)]
2365 : pub struct PageTraceEvent {
2366 : pub key: CompactKey,
2367 : pub effective_lsn: Lsn,
2368 : pub time: SystemTime,
2369 : }
2370 :
2371 : impl Default for PageTraceEvent {
2372 0 : fn default() -> Self {
2373 0 : Self {
2374 0 : key: Default::default(),
2375 0 : effective_lsn: Default::default(),
2376 0 : time: std::time::UNIX_EPOCH,
2377 0 : }
2378 0 : }
2379 : }
2380 :
2381 : #[cfg(test)]
2382 : mod tests {
2383 : use std::str::FromStr;
2384 :
2385 : use serde_json::json;
2386 :
2387 : use super::*;
2388 :
2389 : #[test]
2390 1 : fn test_pagestream() {
2391 1 : // Test serialization/deserialization of PagestreamFeMessage
2392 1 : let messages = vec![
2393 1 : PagestreamFeMessage::Exists(PagestreamExistsRequest {
2394 1 : hdr: PagestreamRequest {
2395 1 : reqid: 0,
2396 1 : request_lsn: Lsn(4),
2397 1 : not_modified_since: Lsn(3),
2398 1 : },
2399 1 : rel: RelTag {
2400 1 : forknum: 1,
2401 1 : spcnode: 2,
2402 1 : dbnode: 3,
2403 1 : relnode: 4,
2404 1 : },
2405 1 : }),
2406 1 : PagestreamFeMessage::Nblocks(PagestreamNblocksRequest {
2407 1 : hdr: PagestreamRequest {
2408 1 : reqid: 0,
2409 1 : request_lsn: Lsn(4),
2410 1 : not_modified_since: Lsn(4),
2411 1 : },
2412 1 : rel: RelTag {
2413 1 : forknum: 1,
2414 1 : spcnode: 2,
2415 1 : dbnode: 3,
2416 1 : relnode: 4,
2417 1 : },
2418 1 : }),
2419 1 : PagestreamFeMessage::GetPage(PagestreamGetPageRequest {
2420 1 : hdr: PagestreamRequest {
2421 1 : reqid: 0,
2422 1 : request_lsn: Lsn(4),
2423 1 : not_modified_since: Lsn(3),
2424 1 : },
2425 1 : rel: RelTag {
2426 1 : forknum: 1,
2427 1 : spcnode: 2,
2428 1 : dbnode: 3,
2429 1 : relnode: 4,
2430 1 : },
2431 1 : blkno: 7,
2432 1 : }),
2433 1 : PagestreamFeMessage::DbSize(PagestreamDbSizeRequest {
2434 1 : hdr: PagestreamRequest {
2435 1 : reqid: 0,
2436 1 : request_lsn: Lsn(4),
2437 1 : not_modified_since: Lsn(3),
2438 1 : },
2439 1 : dbnode: 7,
2440 1 : }),
2441 1 : ];
2442 5 : for msg in messages {
2443 4 : let bytes = msg.serialize();
2444 4 : let reconstructed =
2445 4 : PagestreamFeMessage::parse(&mut bytes.reader(), PagestreamProtocolVersion::V3)
2446 4 : .unwrap();
2447 4 : assert!(msg == reconstructed);
2448 : }
2449 1 : }
2450 :
2451 : #[test]
2452 1 : fn test_tenantinfo_serde() {
2453 1 : // Test serialization/deserialization of TenantInfo
2454 1 : let original_active = TenantInfo {
2455 1 : id: TenantShardId::unsharded(TenantId::generate()),
2456 1 : state: TenantState::Active,
2457 1 : current_physical_size: Some(42),
2458 1 : attachment_status: TenantAttachmentStatus::Attached,
2459 1 : generation: 1,
2460 1 : gc_blocking: None,
2461 1 : };
2462 1 : let expected_active = json!({
2463 1 : "id": original_active.id.to_string(),
2464 1 : "state": {
2465 1 : "slug": "Active",
2466 1 : },
2467 1 : "current_physical_size": 42,
2468 1 : "attachment_status": {
2469 1 : "slug":"attached",
2470 1 : },
2471 1 : "generation" : 1
2472 1 : });
2473 1 :
2474 1 : let original_broken = TenantInfo {
2475 1 : id: TenantShardId::unsharded(TenantId::generate()),
2476 1 : state: TenantState::Broken {
2477 1 : reason: "reason".into(),
2478 1 : backtrace: "backtrace info".into(),
2479 1 : },
2480 1 : current_physical_size: Some(42),
2481 1 : attachment_status: TenantAttachmentStatus::Attached,
2482 1 : generation: 1,
2483 1 : gc_blocking: None,
2484 1 : };
2485 1 : let expected_broken = json!({
2486 1 : "id": original_broken.id.to_string(),
2487 1 : "state": {
2488 1 : "slug": "Broken",
2489 1 : "data": {
2490 1 : "backtrace": "backtrace info",
2491 1 : "reason": "reason",
2492 1 : }
2493 1 : },
2494 1 : "current_physical_size": 42,
2495 1 : "attachment_status": {
2496 1 : "slug":"attached",
2497 1 : },
2498 1 : "generation" : 1
2499 1 : });
2500 1 :
2501 1 : assert_eq!(
2502 1 : serde_json::to_value(&original_active).unwrap(),
2503 1 : expected_active
2504 1 : );
2505 :
2506 1 : assert_eq!(
2507 1 : serde_json::to_value(&original_broken).unwrap(),
2508 1 : expected_broken
2509 1 : );
2510 1 : assert!(format!("{:?}", &original_broken.state).contains("reason"));
2511 1 : assert!(format!("{:?}", &original_broken.state).contains("backtrace info"));
2512 1 : }
2513 :
2514 : #[test]
2515 1 : fn test_reject_unknown_field() {
2516 1 : let id = TenantId::generate();
2517 1 : let config_request = json!({
2518 1 : "tenant_id": id.to_string(),
2519 1 : "unknown_field": "unknown_value".to_string(),
2520 1 : });
2521 1 : let err = serde_json::from_value::<TenantConfigRequest>(config_request).unwrap_err();
2522 1 : assert!(
2523 1 : err.to_string().contains("unknown field `unknown_field`"),
2524 0 : "expect unknown field `unknown_field` error, got: {}",
2525 : err
2526 : );
2527 1 : }
2528 :
2529 : #[test]
2530 1 : fn tenantstatus_activating_serde() {
2531 1 : let states = [TenantState::Activating(ActivatingFrom::Attaching)];
2532 1 : let expected = "[{\"slug\":\"Activating\",\"data\":\"Attaching\"}]";
2533 1 :
2534 1 : let actual = serde_json::to_string(&states).unwrap();
2535 1 :
2536 1 : assert_eq!(actual, expected);
2537 :
2538 1 : let parsed = serde_json::from_str::<Vec<TenantState>>(&actual).unwrap();
2539 1 :
2540 1 : assert_eq!(states.as_slice(), &parsed);
2541 1 : }
2542 :
2543 : #[test]
2544 1 : fn tenantstatus_activating_strum() {
2545 1 : // tests added, because we use these for metrics
2546 1 : let examples = [
2547 1 : (line!(), TenantState::Attaching, "Attaching"),
2548 1 : (
2549 1 : line!(),
2550 1 : TenantState::Activating(ActivatingFrom::Attaching),
2551 1 : "Activating",
2552 1 : ),
2553 1 : (line!(), TenantState::Active, "Active"),
2554 1 : (
2555 1 : line!(),
2556 1 : TenantState::Stopping {
2557 1 : progress: utils::completion::Barrier::default(),
2558 1 : },
2559 1 : "Stopping",
2560 1 : ),
2561 1 : (
2562 1 : line!(),
2563 1 : TenantState::Broken {
2564 1 : reason: "Example".into(),
2565 1 : backtrace: "Looooong backtrace".into(),
2566 1 : },
2567 1 : "Broken",
2568 1 : ),
2569 1 : ];
2570 :
2571 6 : for (line, rendered, expected) in examples {
2572 5 : let actual: &'static str = rendered.into();
2573 5 : assert_eq!(actual, expected, "example on {line}");
2574 : }
2575 1 : }
2576 :
2577 : #[test]
2578 1 : fn test_image_compression_algorithm_parsing() {
2579 : use ImageCompressionAlgorithm::*;
2580 1 : let cases = [
2581 1 : ("disabled", Disabled),
2582 1 : ("zstd", Zstd { level: None }),
2583 1 : ("zstd(18)", Zstd { level: Some(18) }),
2584 1 : ("zstd(-3)", Zstd { level: Some(-3) }),
2585 1 : ];
2586 :
2587 5 : for (display, expected) in cases {
2588 4 : assert_eq!(
2589 4 : ImageCompressionAlgorithm::from_str(display).unwrap(),
2590 : expected,
2591 0 : "parsing works"
2592 : );
2593 4 : assert_eq!(format!("{expected}"), display, "Display FromStr roundtrip");
2594 :
2595 4 : let ser = serde_json::to_string(&expected).expect("serialization");
2596 4 : assert_eq!(
2597 4 : serde_json::from_str::<ImageCompressionAlgorithm>(&ser).unwrap(),
2598 : expected,
2599 0 : "serde roundtrip"
2600 : );
2601 :
2602 4 : assert_eq!(
2603 4 : serde_json::Value::String(display.to_string()),
2604 4 : serde_json::to_value(expected).unwrap(),
2605 0 : "Display is the serde serialization"
2606 : );
2607 : }
2608 1 : }
2609 :
2610 : #[test]
2611 1 : fn test_tenant_config_patch_request_serde() {
2612 1 : let patch_request = TenantConfigPatchRequest {
2613 1 : tenant_id: TenantId::from_str("17c6d121946a61e5ab0fe5a2fd4d8215").unwrap(),
2614 1 : config: TenantConfigPatch {
2615 1 : checkpoint_distance: FieldPatch::Upsert(42),
2616 1 : gc_horizon: FieldPatch::Remove,
2617 1 : compaction_threshold: FieldPatch::Noop,
2618 1 : ..TenantConfigPatch::default()
2619 1 : },
2620 1 : };
2621 1 :
2622 1 : let json = serde_json::to_string(&patch_request).unwrap();
2623 1 :
2624 1 : let expected = r#"{"tenant_id":"17c6d121946a61e5ab0fe5a2fd4d8215","checkpoint_distance":42,"gc_horizon":null}"#;
2625 1 : assert_eq!(json, expected);
2626 :
2627 1 : let decoded: TenantConfigPatchRequest = serde_json::from_str(&json).unwrap();
2628 1 : assert_eq!(decoded.tenant_id, patch_request.tenant_id);
2629 1 : assert_eq!(decoded.config, patch_request.config);
2630 :
2631 : // Now apply the patch to a config to demonstrate semantics
2632 :
2633 1 : let base = TenantConfig {
2634 1 : checkpoint_distance: Some(28),
2635 1 : gc_horizon: Some(100),
2636 1 : compaction_target_size: Some(1024),
2637 1 : ..Default::default()
2638 1 : };
2639 1 :
2640 1 : let expected = TenantConfig {
2641 1 : checkpoint_distance: Some(42),
2642 1 : gc_horizon: None,
2643 1 : ..base.clone()
2644 1 : };
2645 1 :
2646 1 : let patched = base.apply_patch(decoded.config).unwrap();
2647 1 :
2648 1 : assert_eq!(patched, expected);
2649 1 : }
2650 : }
|