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