Skip to main content

common_meta/
datanode.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::{HashMap, HashSet};
16use std::str::FromStr;
17
18use api::v1::meta::{DatanodeWorkloads, HeartbeatRequest, RequestHeader};
19use common_time::{Timestamp, util as time_util};
20use lazy_static::lazy_static;
21use regex::Regex;
22use serde::{Deserialize, Serialize};
23use snafu::{OptionExt, ResultExt, ensure};
24use store_api::region_engine::{RegionRole, RegionStatistic};
25use store_api::storage::RegionId;
26use table::metadata::TableId;
27
28use crate::error::{self, DeserializeFromJsonSnafu, Result};
29use crate::heartbeat::utils::get_datanode_workloads;
30
31const DATANODE_STAT_PREFIX: &str = "__meta_datanode_stat";
32
33pub const REGION_STATISTIC_KEY: &str = "__region_statistic";
34/// The private table name for persisted region statistics.
35pub const REGION_STATS_HISTORY_TABLE_NAME: &str = "region_statistics_history";
36
37lazy_static! {
38    pub(crate) static ref DATANODE_LEASE_KEY_PATTERN: Regex =
39        Regex::new("^__meta_datanode_lease-([0-9]+)-([0-9]+)$").unwrap();
40    static ref DATANODE_STAT_KEY_PATTERN: Regex =
41        Regex::new(&format!("^{DATANODE_STAT_PREFIX}-([0-9]+)-([0-9]+)$")).unwrap();
42    static ref INACTIVE_REGION_KEY_PATTERN: Regex =
43        Regex::new("^__meta_inactive_region-([0-9]+)-([0-9]+)-([0-9]+)$").unwrap();
44}
45
46/// The key of the datanode stat in the storage.
47///
48/// The format is `__meta_datanode_stat-0-{node_id}`.
49#[derive(Debug, Clone, Default, Serialize, Deserialize)]
50pub struct Stat {
51    pub timestamp_millis: i64,
52    // The datanode Id.
53    pub id: u64,
54    // The datanode address.
55    pub addr: String,
56    /// The read capacity units during this period
57    pub rcus: i64,
58    /// The write capacity units during this period
59    pub wcus: i64,
60    /// How many regions on this node
61    pub region_num: u64,
62    /// The region stats of the datanode.
63    pub region_stats: Vec<RegionStat>,
64    /// The topic stats of the datanode.
65    pub topic_stats: Vec<TopicStat>,
66    // The node epoch is used to check whether the node has restarted or redeployed.
67    pub node_epoch: u64,
68    /// The datanode workloads.
69    pub datanode_workloads: DatanodeWorkloads,
70    /// The GC statistics of the datanode.
71    pub gc_stat: Option<GcStat>,
72}
73
74/// The statistics of a region.
75#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
76pub struct RegionStat {
77    /// The region_id.
78    pub id: RegionId,
79    /// The read capacity units during this period
80    pub rcus: i64,
81    /// The write capacity units during this period
82    pub wcus: i64,
83    /// Approximate disk bytes of this region, including sst, index, manifest and wal
84    pub approximate_bytes: u64,
85    /// The engine name.
86    pub engine: String,
87    /// The region role.
88    pub role: RegionRole,
89    /// The number of rows
90    pub num_rows: u64,
91    /// The size of the memtable in bytes.
92    pub memtable_size: u64,
93    /// The size of the manifest in bytes.
94    pub manifest_size: u64,
95    /// The size of the SST data files in bytes.
96    pub sst_size: u64,
97    /// The num of the SST data files.
98    pub sst_num: u64,
99    /// The size of the SST index files in bytes.
100    pub index_size: u64,
101    /// The manifest infoof the region.
102    pub region_manifest: RegionManifestInfo,
103    /// The total bytes written of the region since region opened.
104    pub written_bytes: u64,
105    /// Total ingested Parquet bytes since the region opened.
106    /// Currently counts only committed flush output.
107    ///
108    /// Excludes index files, compaction and imported SSTs. Resets on region reopen.
109    /// Accepts the legacy `flushed_parquet_bytes` key; upgrade metasrv before datanodes.
110    #[serde(default, alias = "flushed_parquet_bytes")]
111    pub ingested_parquet_bytes: u64,
112    /// The total query CPU time of the region since region opened.
113    ///
114    /// Unit: nanoseconds.
115    #[serde(default)]
116    pub query_cpu_time: u64,
117    /// The total scanned bytes of the region since region opened.
118    #[serde(default)]
119    pub query_scanned_bytes: u64,
120    /// The latest entry id of topic used by data.
121    /// **Only used by remote WAL prune.**
122    pub data_topic_latest_entry_id: u64,
123    /// The latest entry id of topic used by metadata.
124    /// **Only used by remote WAL prune.**
125    /// In mito engine, this is the same as `data_topic_latest_entry_id`.
126    pub metadata_topic_latest_entry_id: u64,
127    /// The earliest timestamp of the region's current data, if it holds any.
128    #[serde(default)]
129    pub min_timestamp: Option<Timestamp>,
130    /// The latest timestamp of the region's current data, if it holds any.
131    #[serde(default)]
132    pub max_timestamp: Option<Timestamp>,
133    /// Whether the region still has WAL ranges to recover. Omitted from the serialized form
134    /// when false.
135    #[serde(default, skip_serializing_if = "store_api::is_false")]
136    pub has_pending_tails: bool,
137}
138
139#[derive(Debug, Clone, Serialize, Deserialize)]
140pub struct TopicStat {
141    /// The topic name.
142    pub topic: String,
143    /// The latest entry id of the topic.
144    pub latest_entry_id: u64,
145    /// The total size in bytes of records appended to the topic.
146    pub record_size: u64,
147    /// The total number of records appended to the topic.
148    pub record_num: u64,
149}
150
151/// Trait for reporting statistics about topics.
152pub trait TopicStatsReporter: Send + Sync {
153    /// Returns a list of topic statistics that can be reported.
154    fn reportable_topics(&mut self) -> Vec<TopicStat>;
155}
156
157#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
158pub enum RegionManifestInfo {
159    Mito {
160        manifest_version: u64,
161        flushed_entry_id: u64,
162        /// Number of files removed in the manifest's `removed_files` field.
163        file_removed_cnt: u64,
164    },
165    Metric {
166        data_manifest_version: u64,
167        data_flushed_entry_id: u64,
168        metadata_manifest_version: u64,
169        metadata_flushed_entry_id: u64,
170    },
171}
172
173impl Stat {
174    #[inline]
175    pub fn is_empty(&self) -> bool {
176        self.region_stats.is_empty()
177    }
178
179    pub fn stat_key(&self) -> DatanodeStatKey {
180        DatanodeStatKey { node_id: self.id }
181    }
182
183    /// Returns a tuple array containing [RegionId] and [RegionRole].
184    pub fn regions(&self) -> Vec<(RegionId, RegionRole)> {
185        self.region_stats.iter().map(|s| (s.id, s.role)).collect()
186    }
187
188    /// Returns all table ids in the region stats.
189    pub fn table_ids(&self) -> HashSet<TableId> {
190        self.region_stats.iter().map(|s| s.id.table_id()).collect()
191    }
192
193    /// Retains the active region stats and updates the rcus, wcus, and region_num.
194    pub fn retain_active_region_stats(&mut self, inactive_region_ids: &HashSet<RegionId>) {
195        if inactive_region_ids.is_empty() {
196            return;
197        }
198
199        self.region_stats
200            .retain(|r| !inactive_region_ids.contains(&r.id));
201        self.rcus = self.region_stats.iter().map(|s| s.rcus).sum();
202        self.wcus = self.region_stats.iter().map(|s| s.wcus).sum();
203        self.region_num = self.region_stats.len() as u64;
204    }
205
206    pub fn memory_size(&self) -> usize {
207        // timestamp_millis, rcus, wcus
208        std::mem::size_of::<i64>() * 3 +
209        // id, region_num, node_epoch
210        std::mem::size_of::<u64>() * 3 +
211        // addr
212        std::mem::size_of::<String>() + self.addr.capacity() +
213        // region_stats
214        self.region_stats.iter().map(|s| s.memory_size()).sum::<usize>()
215    }
216}
217
218impl RegionStat {
219    pub fn memory_size(&self) -> usize {
220        // role
221        std::mem::size_of::<RegionRole>() +
222        // id
223        std::mem::size_of::<RegionId>() +
224        // rcus, wcus, approximate_bytes, num_rows
225        std::mem::size_of::<i64>() * 4 +
226        // memtable_size, manifest_size, sst_size, sst_num, index_size
227        std::mem::size_of::<u64>() * 5 +
228        // engine
229        std::mem::size_of::<String>() + self.engine.capacity() +
230        // region_manifest
231        self.region_manifest.memory_size()
232    }
233}
234
235impl RegionManifestInfo {
236    pub fn memory_size(&self) -> usize {
237        match self {
238            RegionManifestInfo::Mito { .. } => std::mem::size_of::<u64>() * 2,
239            RegionManifestInfo::Metric { .. } => std::mem::size_of::<u64>() * 4,
240        }
241    }
242}
243
244impl TryFrom<&HeartbeatRequest> for Stat {
245    type Error = Option<RequestHeader>;
246
247    fn try_from(value: &HeartbeatRequest) -> std::result::Result<Self, Self::Error> {
248        let HeartbeatRequest {
249            header,
250            peer,
251            region_stats,
252            node_epoch,
253            node_workloads,
254            topic_stats,
255            extensions,
256            ..
257        } = value;
258
259        match (header, peer) {
260            (Some(header), Some(peer)) => {
261                let region_stats = region_stats
262                    .iter()
263                    .map(RegionStat::from)
264                    .collect::<Vec<_>>();
265                let topic_stats = topic_stats.iter().map(TopicStat::from).collect::<Vec<_>>();
266
267                let datanode_workloads = get_datanode_workloads(node_workloads.as_ref());
268
269                let gc_stat = GcStat::from_extensions(extensions).map_err(|err| {
270                    common_telemetry::error!(
271                        "Failed to deserialize GcStat from extensions: {}",
272                        err
273                    );
274                    header.clone()
275                })?;
276                Ok(Self {
277                    timestamp_millis: time_util::current_time_millis(),
278                    // datanode id
279                    id: peer.id,
280                    // datanode address
281                    addr: peer.addr.clone(),
282                    rcus: region_stats.iter().map(|s| s.rcus).sum(),
283                    wcus: region_stats.iter().map(|s| s.wcus).sum(),
284                    region_num: region_stats.len() as u64,
285                    region_stats,
286                    topic_stats,
287                    node_epoch: *node_epoch,
288                    datanode_workloads,
289                    gc_stat,
290                })
291            }
292            (header, _) => Err(header.clone()),
293        }
294    }
295}
296
297impl From<store_api::region_engine::RegionManifestInfo> for RegionManifestInfo {
298    fn from(value: store_api::region_engine::RegionManifestInfo) -> Self {
299        match value {
300            store_api::region_engine::RegionManifestInfo::Mito {
301                manifest_version,
302                flushed_entry_id,
303                file_removed_cnt,
304            } => RegionManifestInfo::Mito {
305                manifest_version,
306                flushed_entry_id,
307                file_removed_cnt,
308            },
309            store_api::region_engine::RegionManifestInfo::Metric {
310                data_manifest_version,
311                data_flushed_entry_id,
312                metadata_manifest_version,
313                metadata_flushed_entry_id,
314            } => RegionManifestInfo::Metric {
315                data_manifest_version,
316                data_flushed_entry_id,
317                metadata_manifest_version,
318                metadata_flushed_entry_id,
319            },
320        }
321    }
322}
323
324impl From<&api::v1::meta::RegionStat> for RegionStat {
325    fn from(value: &api::v1::meta::RegionStat) -> Self {
326        let region_stat = value
327            .extensions
328            .get(REGION_STATISTIC_KEY)
329            .and_then(|value| RegionStatistic::deserialize_from_slice(value))
330            .unwrap_or_default();
331
332        Self {
333            id: RegionId::from_u64(value.region_id),
334            rcus: value.rcus,
335            wcus: value.wcus,
336            approximate_bytes: value.approximate_bytes as u64,
337            engine: value.engine.clone(),
338            role: RegionRole::from(value.role()),
339            num_rows: region_stat.num_rows,
340            memtable_size: region_stat.memtable_size,
341            manifest_size: region_stat.manifest_size,
342            sst_size: region_stat.sst_size,
343            sst_num: region_stat.sst_num,
344            index_size: region_stat.index_size,
345            region_manifest: region_stat.manifest.into(),
346            written_bytes: region_stat.written_bytes,
347            ingested_parquet_bytes: region_stat.ingested_parquet_bytes,
348            query_cpu_time: region_stat.query_cpu_time,
349            query_scanned_bytes: region_stat.query_scanned_bytes,
350            data_topic_latest_entry_id: region_stat.data_topic_latest_entry_id,
351            metadata_topic_latest_entry_id: region_stat.metadata_topic_latest_entry_id,
352            min_timestamp: region_stat.min_timestamp,
353            max_timestamp: region_stat.max_timestamp,
354            has_pending_tails: region_stat.has_pending_tails,
355        }
356    }
357}
358
359impl From<&api::v1::meta::TopicStat> for TopicStat {
360    fn from(value: &api::v1::meta::TopicStat) -> Self {
361        Self {
362            topic: value.topic_name.clone(),
363            latest_entry_id: value.latest_entry_id,
364            record_size: value.record_size,
365            record_num: value.record_num,
366        }
367    }
368}
369
370#[derive(Debug, Clone, Serialize, Deserialize, Default)]
371pub struct GcStat {
372    /// Number of GC tasks currently running on the datanode.
373    pub running_gc_tasks: u32,
374    /// The maximum number of concurrent GC tasks the datanode can handle.
375    pub gc_concurrency: u32,
376}
377
378impl GcStat {
379    pub const GC_STAT_KEY: &str = "__gc_stat";
380
381    pub fn new(running_gc_tasks: u32, gc_concurrency: u32) -> Self {
382        Self {
383            running_gc_tasks,
384            gc_concurrency,
385        }
386    }
387
388    pub fn into_extensions(&self, extensions: &mut std::collections::HashMap<String, Vec<u8>>) {
389        let bytes = serde_json::to_vec(self).unwrap_or_default();
390        extensions.insert(Self::GC_STAT_KEY.to_string(), bytes);
391    }
392
393    pub fn from_extensions(
394        extensions: &std::collections::HashMap<String, Vec<u8>>,
395    ) -> Result<Option<Self>> {
396        extensions
397            .get(Self::GC_STAT_KEY)
398            .map(|bytes| {
399                serde_json::from_slice(bytes).with_context(|_| DeserializeFromJsonSnafu {
400                    input: String::from_utf8_lossy(bytes).to_string(),
401                })
402            })
403            .transpose()
404    }
405}
406
407/// Environment variables reported by a node in heartbeat messages.
408#[derive(Debug, Clone, Serialize, Deserialize, Default)]
409pub struct EnvVars {
410    pub vars: HashMap<String, String>,
411}
412
413impl EnvVars {
414    pub const ENV_VARS_KEY: &str = "__env_vars";
415
416    pub fn new(vars: HashMap<String, String>) -> Self {
417        Self { vars }
418    }
419
420    /// Read the configured env var keys from the environment and build an EnvVars.
421    pub fn from_config(keys: &[String]) -> Self {
422        let vars = keys
423            .iter()
424            .filter_map(|key| std::env::var(key).ok().map(|value| (key.clone(), value)))
425            .collect();
426        Self { vars }
427    }
428
429    pub fn into_extensions(&self, extensions: &mut HashMap<String, Vec<u8>>) {
430        if self.vars.is_empty() {
431            return;
432        }
433        let bytes = serde_json::to_vec(self).unwrap_or_default();
434        extensions.insert(Self::ENV_VARS_KEY.to_string(), bytes);
435    }
436
437    pub fn from_extensions(extensions: &HashMap<String, Vec<u8>>) -> Result<Option<Self>> {
438        extensions
439            .get(Self::ENV_VARS_KEY)
440            .map(|bytes| {
441                serde_json::from_slice(bytes).with_context(|_| DeserializeFromJsonSnafu {
442                    input: String::from_utf8_lossy(bytes).to_string(),
443                })
444            })
445            .transpose()
446    }
447}
448
449/// The key of the datanode stat in the memory store.
450///
451/// The format is `__meta_datanode_stat-0-{node_id}`.
452#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
453pub struct DatanodeStatKey {
454    pub node_id: u64,
455}
456
457impl DatanodeStatKey {
458    /// The key prefix.
459    pub fn prefix_key() -> Vec<u8> {
460        // todo(hl): remove cluster id in prefix
461        format!("{DATANODE_STAT_PREFIX}-0-").into_bytes()
462    }
463}
464
465impl From<DatanodeStatKey> for Vec<u8> {
466    fn from(value: DatanodeStatKey) -> Self {
467        // todo(hl): remove cluster id in prefix
468        format!("{}-0-{}", DATANODE_STAT_PREFIX, value.node_id).into_bytes()
469    }
470}
471
472impl FromStr for DatanodeStatKey {
473    type Err = error::Error;
474
475    fn from_str(key: &str) -> Result<Self> {
476        let caps = DATANODE_STAT_KEY_PATTERN
477            .captures(key)
478            .context(error::InvalidStatKeySnafu { key })?;
479
480        ensure!(caps.len() == 3, error::InvalidStatKeySnafu { key });
481        let node_id = caps[2].to_string();
482        let node_id: u64 = node_id.parse().context(error::ParseNumSnafu {
483            err_msg: format!("invalid node_id: {node_id}"),
484        })?;
485
486        Ok(Self { node_id })
487    }
488}
489
490impl TryFrom<Vec<u8>> for DatanodeStatKey {
491    type Error = error::Error;
492
493    fn try_from(bytes: Vec<u8>) -> Result<Self> {
494        String::from_utf8(bytes)
495            .context(error::FromUtf8Snafu {
496                name: "DatanodeStatKey",
497            })
498            .map(|x| x.parse())?
499    }
500}
501
502/// The value of the datanode stat in the memory store.
503#[derive(Debug, Clone, Serialize, Deserialize)]
504#[serde(transparent)]
505pub struct DatanodeStatValue {
506    pub stats: Vec<Stat>,
507}
508
509impl DatanodeStatValue {
510    /// Get the latest number of regions.
511    pub fn region_num(&self) -> Option<u64> {
512        self.stats.last().map(|x| x.region_num)
513    }
514
515    /// Get the latest node addr.
516    pub fn node_addr(&self) -> Option<String> {
517        self.stats.last().map(|x| x.addr.clone())
518    }
519}
520
521impl TryFrom<DatanodeStatValue> for Vec<u8> {
522    type Error = error::Error;
523
524    fn try_from(stats: DatanodeStatValue) -> Result<Self> {
525        Ok(serde_json::to_string(&stats)
526            .context(error::SerializeToJsonSnafu {
527                input: format!("{stats:?}"),
528            })?
529            .into_bytes())
530    }
531}
532
533impl FromStr for DatanodeStatValue {
534    type Err = error::Error;
535
536    fn from_str(value: &str) -> Result<Self> {
537        serde_json::from_str(value).context(error::DeserializeFromJsonSnafu { input: value })
538    }
539}
540
541impl TryFrom<Vec<u8>> for DatanodeStatValue {
542    type Error = error::Error;
543
544    fn try_from(value: Vec<u8>) -> Result<Self> {
545        String::from_utf8(value)
546            .context(error::FromUtf8Snafu {
547                name: "DatanodeStatValue",
548            })
549            .map(|x| x.parse())?
550    }
551}
552
553#[cfg(test)]
554mod tests {
555    use super::*;
556
557    #[test]
558    fn test_stat_key() {
559        let stat = Stat {
560            id: 101,
561            region_num: 10,
562            ..Default::default()
563        };
564
565        let stat_key = stat.stat_key();
566
567        assert_eq!(101, stat_key.node_id);
568    }
569
570    #[test]
571    fn test_stat_val_round_trip() {
572        let stat = Stat {
573            id: 101,
574            region_num: 100,
575            ..Default::default()
576        };
577
578        let stat_val = DatanodeStatValue { stats: vec![stat] };
579
580        let bytes: Vec<u8> = stat_val.try_into().unwrap();
581        let stat_val: DatanodeStatValue = bytes.try_into().unwrap();
582        let stats = stat_val.stats;
583
584        assert_eq!(1, stats.len());
585
586        let stat = stats.first().unwrap();
587        assert_eq!(101, stat.id);
588        assert_eq!(100, stat.region_num);
589    }
590
591    #[test]
592    fn test_stat_val_deserializes_without_optional_counters() {
593        let stat = Stat {
594            region_stats: vec![RegionStat {
595                id: RegionId::new(1024, 1),
596                rcus: 0,
597                wcus: 0,
598                approximate_bytes: 0,
599                engine: "mito".to_string(),
600                role: RegionRole::Leader,
601                num_rows: 0,
602                memtable_size: 0,
603                manifest_size: 0,
604                sst_size: 0,
605                sst_num: 0,
606                index_size: 0,
607                region_manifest: RegionManifestInfo::Mito {
608                    manifest_version: 0,
609                    flushed_entry_id: 0,
610                    file_removed_cnt: 0,
611                },
612                written_bytes: 0,
613                ingested_parquet_bytes: 4096,
614                query_cpu_time: 10,
615                query_scanned_bytes: 20,
616                data_topic_latest_entry_id: 0,
617                metadata_topic_latest_entry_id: 0,
618                min_timestamp: None,
619                max_timestamp: None,
620                has_pending_tails: false,
621            }],
622            ..Default::default()
623        };
624        let stat_val = DatanodeStatValue { stats: vec![stat] };
625        let mut value = serde_json::to_value(stat_val).unwrap();
626        let region_stat = value[0]["region_stats"][0].as_object_mut().unwrap();
627        region_stat.remove("ingested_parquet_bytes");
628        region_stat.remove("query_cpu_time");
629        region_stat.remove("query_scanned_bytes");
630
631        let stat_val: DatanodeStatValue = serde_json::from_value(value).unwrap();
632        let region_stat = &stat_val.stats[0].region_stats[0];
633
634        assert_eq!(region_stat.ingested_parquet_bytes, 0);
635        assert_eq!(region_stat.query_cpu_time, 0);
636        assert_eq!(region_stat.query_scanned_bytes, 0);
637    }
638
639    #[test]
640    fn test_get_addr_from_stat_val() {
641        let empty = DatanodeStatValue { stats: vec![] };
642        let addr = empty.node_addr();
643        assert!(addr.is_none());
644
645        let stat_val = DatanodeStatValue {
646            stats: vec![
647                Stat {
648                    addr: "1".to_string(),
649                    ..Default::default()
650                },
651                Stat {
652                    addr: "2".to_string(),
653                    ..Default::default()
654                },
655                Stat {
656                    addr: "3".to_string(),
657                    ..Default::default()
658                },
659            ],
660        };
661        let addr = stat_val.node_addr().unwrap();
662        assert_eq!("3", addr);
663    }
664
665    #[test]
666    fn test_get_region_num_from_stat_val() {
667        let empty = DatanodeStatValue { stats: vec![] };
668        let region_num = empty.region_num();
669        assert!(region_num.is_none());
670
671        let wrong = DatanodeStatValue {
672            stats: vec![Stat {
673                region_num: 0,
674                ..Default::default()
675            }],
676        };
677        let right = wrong.region_num();
678        assert_eq!(Some(0), right);
679
680        let stat_val = DatanodeStatValue {
681            stats: vec![
682                Stat {
683                    region_num: 1,
684                    ..Default::default()
685                },
686                Stat {
687                    region_num: 0,
688                    ..Default::default()
689                },
690                Stat {
691                    region_num: 2,
692                    ..Default::default()
693                },
694            ],
695        };
696        let region_num = stat_val.region_num().unwrap();
697        assert_eq!(2, region_num);
698    }
699
700    #[test]
701    fn test_region_stat_from_heartbeat_preserves_staging_leader_role() {
702        let request = HeartbeatRequest {
703            header: Some(RequestHeader::default()),
704            peer: Some(api::v1::meta::Peer {
705                id: 1,
706                addr: "127.0.0.1:3001".to_string(),
707            }),
708            region_stats: vec![api::v1::meta::RegionStat {
709                region_id: RegionId::new(1024, 1).as_u64(),
710                engine: "mito".to_string(),
711                role: api::v1::meta::RegionRole::StagingLeader.into(),
712                ..Default::default()
713            }],
714            ..Default::default()
715        };
716
717        let stat = Stat::try_from(&request).unwrap();
718
719        assert_eq!(stat.region_stats.len(), 1);
720        assert_eq!(stat.region_stats[0].role, RegionRole::StagingLeader);
721    }
722
723    #[test]
724    fn test_ingested_parquet_bytes_from_heartbeat() {
725        for bytes in [0, 4096, u64::MAX] {
726            let statistic = RegionStatistic {
727                ingested_parquet_bytes: bytes,
728                ..Default::default()
729            };
730            let mut region = api::v1::meta::RegionStat::default();
731            region.extensions.insert(
732                REGION_STATISTIC_KEY.to_string(),
733                serde_json::to_vec(&statistic).unwrap(),
734            );
735            let request = HeartbeatRequest {
736                header: Some(RequestHeader::default()),
737                peer: Some(api::v1::meta::Peer {
738                    id: 1,
739                    addr: "127.0.0.1:3001".to_string(),
740                }),
741                region_stats: vec![region.clone()],
742                ..Default::default()
743            };
744            let stat = Stat::try_from(&request).unwrap();
745            let stat = &stat.region_stats[0];
746            assert_eq!(stat.ingested_parquet_bytes, bytes);
747            let encoded = serde_json::to_vec(stat).unwrap();
748            let wire: serde_json::Value = serde_json::from_slice(&encoded).unwrap();
749            assert_eq!(wire["ingested_parquet_bytes"], bytes);
750            assert!(wire.get("flushed_parquet_bytes").is_none());
751            let mut old_wire = wire.clone();
752            old_wire
753                .as_object_mut()
754                .unwrap()
755                .remove("ingested_parquet_bytes");
756            old_wire["flushed_parquet_bytes"] = bytes.into();
757            assert_eq!(
758                &serde_json::from_value::<RegionStat>(old_wire).unwrap(),
759                stat
760            );
761            let decoded: RegionStat = serde_json::from_slice(&encoded).unwrap();
762            assert_eq!(&decoded, stat);
763
764            let mut legacy = serde_json::to_value(&statistic).unwrap();
765            legacy
766                .as_object_mut()
767                .unwrap()
768                .remove("ingested_parquet_bytes");
769            legacy["flushed_parquet_bytes"] = bytes.into();
770            region.extensions.insert(
771                REGION_STATISTIC_KEY.to_string(),
772                serde_json::to_vec(&legacy).unwrap(),
773            );
774            assert_eq!(RegionStat::from(&region).ingested_parquet_bytes, bytes);
775            legacy
776                .as_object_mut()
777                .unwrap()
778                .remove("flushed_parquet_bytes");
779            region.extensions.insert(
780                REGION_STATISTIC_KEY.to_string(),
781                serde_json::to_vec(&legacy).unwrap(),
782            );
783            assert_eq!(RegionStat::from(&region).ingested_parquet_bytes, 0);
784        }
785        assert_eq!(
786            RegionStat::from(&api::v1::meta::RegionStat::default()).ingested_parquet_bytes,
787            0
788        );
789    }
790
791    #[test]
792    fn test_has_pending_tails_wire() {
793        // Frozen encodings of a release without the field.
794        let legacy_statistic: &[u8] = include_bytes!(
795            "../../../../tests/compatibility/wire/region_statistic_pending_tails/legacy_region_statistic.json"
796        );
797        let legacy_stat: &[u8] = include_bytes!(
798            "../../../../tests/compatibility/wire/region_statistic_pending_tails/legacy_region_stat.json"
799        );
800        let statistic: RegionStatistic = serde_json::from_slice(legacy_statistic).unwrap();
801        assert!(!statistic.has_pending_tails);
802        // A false flag is not written, so the encoding stays as it was.
803        assert_eq!(serde_json::to_vec(&statistic).unwrap(), legacy_statistic);
804        let stat: RegionStat = serde_json::from_slice(legacy_stat).unwrap();
805        assert!(!stat.has_pending_tails);
806        assert_eq!(serde_json::to_vec(&stat).unwrap(), legacy_stat);
807
808        // A true flag is written under this key, which readers that support the flag decode;
809        // older readers ignore it.
810        let statistic = RegionStatistic {
811            has_pending_tails: true,
812            ..statistic
813        };
814        let encoded = serde_json::to_value(&statistic).unwrap();
815        assert_eq!(encoded["has_pending_tails"], serde_json::Value::Bool(true));
816        let encoded = serde_json::to_value(RegionStat {
817            has_pending_tails: true,
818            ..stat
819        })
820        .unwrap();
821        assert_eq!(encoded["has_pending_tails"], serde_json::Value::Bool(true));
822
823        // A true flag travels from the heartbeat extension to the stored statistic.
824        let mut region = api::v1::meta::RegionStat::default();
825        region.extensions.insert(
826            REGION_STATISTIC_KEY.to_string(),
827            serde_json::to_vec(&statistic).unwrap(),
828        );
829        let stat = RegionStat::from(&region);
830        assert!(stat.has_pending_tails);
831        let stored: RegionStat =
832            serde_json::from_slice(&serde_json::to_vec(&stat).unwrap()).unwrap();
833        assert_eq!(stored, stat);
834    }
835
836    #[test]
837    fn test_env_vars_round_trip() {
838        let mut vars = HashMap::new();
839        vars.insert("AZ".to_string(), "us-east-1a".to_string());
840        vars.insert("REGION".to_string(), "us-east-1".to_string());
841        let env_vars = EnvVars::new(vars);
842
843        let mut extensions = HashMap::new();
844        env_vars.into_extensions(&mut extensions);
845
846        let extracted = EnvVars::from_extensions(&extensions).unwrap().unwrap();
847        assert_eq!(extracted.vars.get("AZ").unwrap(), "us-east-1a");
848        assert_eq!(extracted.vars.get("REGION").unwrap(), "us-east-1");
849    }
850
851    #[test]
852    fn test_env_vars_empty_not_written() {
853        let env_vars = EnvVars::default();
854        let mut extensions = HashMap::new();
855        env_vars.into_extensions(&mut extensions);
856        assert!(extensions.is_empty());
857    }
858
859    #[test]
860    fn test_env_vars_from_extensions_missing() {
861        let extensions = HashMap::new();
862        let result = EnvVars::from_extensions(&extensions).unwrap();
863        assert!(result.is_none());
864    }
865}