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