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