Skip to main content

common_meta/
instruction.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::fmt::{Display, Formatter};
17use std::time::Duration;
18
19use base64::Engine;
20use common_error::ext::{ErrorExt, RetryHint};
21use common_error::status_code::StatusCode;
22use serde::{Deserialize, Deserializer, Serialize, Serializer};
23use snafu::ResultExt as _;
24use store_api::region_engine::SyncRegionFromRequest;
25use store_api::region_request::{RegionFlushReason, RegionRequirements};
26use store_api::storage::{FileId, FileRef, FileRefsManifest, GcReport, RegionId, RegionNumber};
27use strum::Display;
28use table::metadata::TableId;
29use table::table_name::TableName;
30
31use crate::error::{DecodePackedFileRefsSnafu, InvalidPackedFileRefsSnafu};
32use crate::flow_name::FlowName;
33use crate::key::schema_name::SchemaName;
34use crate::key::{FlowId, FlowPartitionId};
35use crate::peer::Peer;
36use crate::wal_provider::{RegionWalOptions, region_wal_options_serde};
37use crate::{DatanodeId, FlownodeId};
38
39/// A structured error returned by instruction replies.
40#[derive(Debug, Serialize, PartialEq, Eq, Clone)]
41pub struct InstructionError {
42    /// Numeric status code aligned with [`StatusCode`].
43    #[serde(
44        serialize_with = "StatusCode::serialize_as_u32",
45        deserialize_with = "StatusCode::deserialize_from_u32"
46    )]
47    pub code: StatusCode,
48    /// User-facing error message aligned with [`ErrorExt::output_msg`].
49    pub message: String,
50    /// Retry hint serialized as a string.
51    #[serde(
52        serialize_with = "InstructionError::serialize_retry_hint",
53        deserialize_with = "RetryHint::deserialize_from_str"
54    )]
55    pub retry_hint: RetryHint,
56}
57
58impl<'de> Deserialize<'de> for InstructionError {
59    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
60    where
61        D: Deserializer<'de>,
62    {
63        #[derive(Deserialize)]
64        #[serde(untagged)]
65        enum Compat {
66            Structured {
67                #[serde(deserialize_with = "StatusCode::deserialize_from_u32")]
68                code: StatusCode,
69                message: String,
70                #[serde(deserialize_with = "RetryHint::deserialize_from_str")]
71                retry_hint: RetryHint,
72            },
73            Legacy(String),
74        }
75
76        match Compat::deserialize(deserializer)? {
77            Compat::Structured {
78                code,
79                message,
80                retry_hint,
81            } => Ok(Self {
82                code,
83                message,
84                retry_hint,
85            }),
86            Compat::Legacy(message) => Ok(Self::legacy_internal_retryable(message)),
87        }
88    }
89}
90
91impl InstructionError {
92    pub fn new(code: StatusCode, message: impl Into<String>, retry_hint: RetryHint) -> Self {
93        Self {
94            code,
95            message: message.into(),
96            retry_hint,
97        }
98    }
99
100    pub fn legacy_internal_retryable(message: impl Into<String>) -> Self {
101        Self::new(StatusCode::Internal, message, RetryHint::Retryable)
102    }
103
104    pub fn from_error<E: ErrorExt>(error: &E) -> Self {
105        Self {
106            code: error.status_code(),
107            message: error.output_msg(),
108            retry_hint: error.retry_hint(),
109        }
110    }
111
112    /// Keeps instruction replies readable by peers that only know the legacy hints.
113    fn serialize_retry_hint<S>(hint: &RetryHint, serializer: S) -> Result<S::Ok, S::Error>
114    where
115        S: Serializer,
116    {
117        let hint = match hint {
118            RetryHint::RetryAfterRouteRefresh => RetryHint::Retryable,
119            hint => *hint,
120        };
121        RetryHint::serialize_as_str(&hint, serializer)
122    }
123}
124
125impl Display for InstructionError {
126    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
127        write!(
128            f,
129            "InstructionError(code={}, retry_hint={}, message={})",
130            self.code as u32,
131            self.retry_hint.as_str(),
132            self.message
133        )
134    }
135}
136
137pub type InstructionResult<T> = std::result::Result<T, InstructionError>;
138
139#[derive(Eq, Hash, PartialEq, Clone, Debug, Serialize, Deserialize)]
140pub struct RegionIdent {
141    pub datanode_id: DatanodeId,
142    pub table_id: TableId,
143    pub region_number: RegionNumber,
144    pub engine: String,
145}
146
147impl RegionIdent {
148    pub fn get_region_id(&self) -> RegionId {
149        RegionId::new(self.table_id, self.region_number)
150    }
151}
152
153impl Display for RegionIdent {
154    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
155        write!(
156            f,
157            "RegionIdent(datanode_id='{}', table_id={}, region_number={}, engine = {})",
158            self.datanode_id, self.table_id, self.region_number, self.engine
159        )
160    }
161}
162
163/// The result of downgrade leader region.
164#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
165pub struct DowngradeRegionReply {
166    /// The [RegionId].
167    /// For compatibility, it is defaulted to [RegionId::new(0, 0)].
168    #[serde(default)]
169    pub region_id: RegionId,
170    /// Returns the `last_entry_id` if available.
171    pub last_entry_id: Option<u64>,
172    /// Returns the `metadata_last_entry_id` if available (Only available for metric engine).
173    pub metadata_last_entry_id: Option<u64>,
174    /// Indicates whether the region exists.
175    pub exists: bool,
176    /// Return error if any during the operation.
177    pub error: Option<InstructionError>,
178    /// Whether rows written without the WAL, which a takeover cannot recover, may remain on the
179    /// region, so the migration rolls back instead; false from a datanode that sets the field means
180    /// none remained when the reply was built. A datanode that predates the field never sets it,
181    /// and a metasrv that predates it ignores it, so the rollback protects such rows only once
182    /// both are upgraded. Omitted from the serialized form when false.
183    #[serde(default, skip_serializing_if = "store_api::is_false")]
184    pub has_skip_wal_writes: bool,
185}
186
187impl Display for DowngradeRegionReply {
188    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
189        write!(
190            f,
191            "(last_entry_id={:?}, exists={}, error={:?})",
192            self.last_entry_id, self.exists, self.error
193        )
194    }
195}
196
197#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
198pub struct SimpleReply {
199    pub result: bool,
200    pub error: Option<InstructionError>,
201}
202
203/// Reply for flush region operations with support for batch results.
204#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
205pub struct FlushRegionReply {
206    /// Results for each region that was attempted to be flushed.
207    /// For single region flushes, this will contain one result.
208    /// For batch flushes, this contains results for all attempted regions.
209    pub results: Vec<(RegionId, InstructionResult<()>)>,
210    /// Overall success: true if all regions were flushed successfully.
211    pub overall_success: bool,
212}
213
214impl FlushRegionReply {
215    /// Create a successful single region reply.
216    pub fn success_single(region_id: RegionId) -> Self {
217        Self {
218            results: vec![(region_id, Ok(()))],
219            overall_success: true,
220        }
221    }
222
223    /// Create a failed single region reply.
224    pub fn error_single(region_id: RegionId, error: InstructionError) -> Self {
225        Self {
226            results: vec![(region_id, Err(error))],
227            overall_success: false,
228        }
229    }
230
231    /// Create a batch reply from individual results.
232    pub fn from_results(results: Vec<(RegionId, InstructionResult<()>)>) -> Self {
233        let overall_success = results.iter().all(|(_, result)| result.is_ok());
234        Self {
235            results,
236            overall_success,
237        }
238    }
239
240    /// Convert to SimpleReply for backward compatibility.
241    pub fn to_simple_reply(&self) -> SimpleReply {
242        if self.overall_success {
243            SimpleReply {
244                result: true,
245                error: None,
246            }
247        } else {
248            let errors: Vec<String> = self
249                .results
250                .iter()
251                .filter_map(|(region_id, result)| {
252                    result
253                        .as_ref()
254                        .err()
255                        .map(|err| format!("{}: {}", region_id, err))
256                })
257                .collect();
258            SimpleReply {
259                result: false,
260                error: Some(InstructionError::legacy_internal_retryable(
261                    errors.join("; "),
262                )),
263            }
264        }
265    }
266}
267
268impl Display for SimpleReply {
269    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
270        write!(f, "(result={}, error={:?})", self.result, self.error)
271    }
272}
273
274impl Display for FlushRegionReply {
275    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
276        let results_str = self
277            .results
278            .iter()
279            .map(|(region_id, result)| match result {
280                Ok(()) => format!("{}:OK", region_id),
281                Err(err) => format!("{}:ERR({})", region_id, err),
282            })
283            .collect::<Vec<_>>()
284            .join(", ");
285        write!(
286            f,
287            "(overall_success={}, results=[{}])",
288            self.overall_success, results_str
289        )
290    }
291}
292
293impl Display for OpenRegion {
294    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
295        write!(
296            f,
297            "OpenRegion(region_ident={}, region_storage_path={}, reason={:?})",
298            self.region_ident, self.region_storage_path, self.reason
299        )
300    }
301}
302
303/// The reason why an open region instruction is triggered.
304#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
305pub enum OpenRegionReason {
306    /// Open triggered before region migration.
307    RegionMigration,
308    /// Open triggered by region failover.
309    RegionFailover,
310    /// Open triggered when adding a follower region.
311    #[cfg(feature = "enterprise")]
312    RegionFollower,
313}
314
315#[serde_with::serde_as]
316#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
317pub struct OpenRegion {
318    pub region_ident: RegionIdent,
319    pub region_storage_path: String,
320    pub region_options: HashMap<String, String>,
321    #[serde(default)]
322    #[serde(with = "region_wal_options_serde")]
323    pub region_wal_options: RegionWalOptions,
324    #[serde(default)]
325    pub skip_wal_replay: bool,
326    #[serde(default, skip_serializing_if = "Option::is_none")]
327    pub reason: Option<OpenRegionReason>,
328    #[serde(default)]
329    pub requirements: RegionRequirements,
330}
331
332impl OpenRegion {
333    pub fn new(
334        region_ident: RegionIdent,
335        path: &str,
336        region_options: HashMap<String, String>,
337        region_wal_options: RegionWalOptions,
338        skip_wal_replay: bool,
339        reason: Option<OpenRegionReason>,
340        requirements: RegionRequirements,
341    ) -> Self {
342        Self {
343            region_ident,
344            region_storage_path: path.to_string(),
345            region_options,
346            region_wal_options,
347            skip_wal_replay,
348            reason,
349            requirements,
350        }
351    }
352}
353
354/// The instruction of downgrading leader region.
355#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
356pub struct DowngradeRegion {
357    /// The [RegionId].
358    pub region_id: RegionId,
359    /// The timeout of the whole downgrade: the flush and the change to follower.
360    ///
361    /// `None` stands for don't flush before downgrading the region, with no timeout.
362    #[serde(default)]
363    pub flush_timeout: Option<Duration>,
364}
365
366impl Display for DowngradeRegion {
367    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
368        write!(
369            f,
370            "DowngradeRegion(region_id={}, flush_timeout={:?})",
371            self.region_id, self.flush_timeout,
372        )
373    }
374}
375
376/// Upgrades a follower region to leader region.
377#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
378pub struct UpgradeRegion {
379    /// The [RegionId].
380    pub region_id: RegionId,
381    /// The `last_entry_id` of old leader region.
382    pub last_entry_id: Option<u64>,
383    /// The `last_entry_id` of old leader metadata region (Only used for metric engine).
384    pub metadata_last_entry_id: Option<u64>,
385    /// The timeout of waiting for a wal replay.
386    ///
387    /// `None` stands for no wait,
388    /// it's helpful to verify whether the leader region is ready.
389    #[serde(with = "humantime_serde")]
390    pub replay_timeout: Duration,
391    /// Id of the datanode that led the region before the migration. The datanode passes it to
392    /// the catchup as the source of `last_entry_id`.
393    #[serde(default)]
394    pub location_id: Option<u64>,
395    #[serde(default, skip_serializing_if = "Option::is_none")]
396    pub replay_entry_id: Option<u64>,
397    #[serde(default, skip_serializing_if = "Option::is_none")]
398    pub metadata_replay_entry_id: Option<u64>,
399    /// The candidate lease id of the migration's registration of this target region.
400    #[serde(default, skip_serializing_if = "Option::is_none")]
401    pub candidate_lease_id: Option<u64>,
402}
403
404impl UpgradeRegion {
405    /// Sets the replay entry id.
406    pub fn with_replay_entry_id(mut self, replay_entry_id: Option<u64>) -> Self {
407        self.replay_entry_id = replay_entry_id;
408        self
409    }
410
411    /// Sets the metadata replay entry id.
412    pub fn with_metadata_replay_entry_id(mut self, metadata_replay_entry_id: Option<u64>) -> Self {
413        self.metadata_replay_entry_id = metadata_replay_entry_id;
414        self
415    }
416}
417
418#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
419/// The identifier of cache.
420pub enum CacheIdent {
421    FlowId(FlowId),
422    /// Indicates a change of trigger metadata; invalidated by enterprise plugins.
423    #[cfg(feature = "enterprise")]
424    TriggerId(u64),
425    /// Indicate change of address of flownode.
426    FlowNodeAddressChange(u64),
427    FlowName(FlowName),
428    TableId(TableId),
429    TableName(TableName),
430    SchemaName(SchemaName),
431    CreateFlow(CreateFlow),
432    DropFlow(DropFlow),
433    /// Indicate change of user metadata.
434    User(UserCacheIdent),
435}
436
437impl CacheIdent {
438    pub(crate) fn flow_id_key(&self) -> Option<&FlowId> {
439        match self {
440            Self::FlowId(id) => Some(id),
441            _ => None,
442        }
443    }
444
445    pub(crate) fn schema_name_key(&self) -> Option<&SchemaName> {
446        match self {
447            Self::SchemaName(name) => Some(name),
448            _ => None,
449        }
450    }
451
452    pub fn table_id_key(&self) -> Option<&TableId> {
453        if let Self::TableId(id) = self {
454            Some(id)
455        } else {
456            None
457        }
458    }
459
460    pub fn table_name_key(&self) -> Option<&TableName> {
461        if let Self::TableName(name) = self {
462            Some(name)
463        } else {
464            None
465        }
466    }
467}
468
469#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
470pub struct UserCacheIdent {
471    pub catalog: String,
472    pub username: String,
473}
474
475#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
476pub struct CreateFlow {
477    /// The unique identifier for the flow.
478    pub flow_id: FlowId,
479    pub source_table_ids: Vec<TableId>,
480    /// Mapping of flow partition to peer information
481    pub partition_to_peer_mapping: Vec<(FlowPartitionId, Peer)>,
482}
483
484#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
485pub struct DropFlow {
486    pub flow_id: FlowId,
487    pub source_table_ids: Vec<TableId>,
488    /// Mapping of flow partition to flownode id
489    pub flow_part2node_id: Vec<(FlowPartitionId, FlownodeId)>,
490}
491
492/// Strategy for executing flush operations.
493#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
494pub enum FlushStrategy {
495    /// Synchronous operation that waits for completion and expects a reply
496    #[default]
497    Sync,
498    /// Asynchronous hint operation (fire-and-forget, no reply expected)
499    Async,
500}
501
502/// Error handling strategy for batch flush operations.
503#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
504pub enum FlushErrorStrategy {
505    /// Abort on first error (fail-fast)
506    #[default]
507    FailFast,
508    /// Attempt to flush all regions and collect all errors
509    TryAll,
510}
511
512/// Unified flush instruction supporting both single and batch operations
513/// with configurable execution strategies and error handling.
514#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
515pub struct FlushRegions {
516    /// List of region IDs to flush. Can contain a single region or multiple regions.
517    pub region_ids: Vec<RegionId>,
518    /// Execution strategy: Sync (expects reply) or Async (fire-and-forget hint).
519    #[serde(default)]
520    pub strategy: FlushStrategy,
521    /// Error handling strategy for batch operations (only applies when multiple regions and sync strategy).
522    #[serde(default)]
523    pub error_strategy: FlushErrorStrategy,
524    /// The source that triggered this flush.
525    #[serde(default, skip_serializing_if = "Option::is_none")]
526    pub reason: Option<RegionFlushReason>,
527}
528
529impl Display for FlushRegions {
530    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
531        write!(
532            f,
533            "FlushRegions(region_ids={:?}, strategy={:?}, error_strategy={:?}, reason={:?})",
534            self.region_ids, self.strategy, self.error_strategy, self.reason
535        )
536    }
537}
538
539impl FlushRegions {
540    /// Create synchronous single-region flush
541    pub fn sync_single(region_id: RegionId) -> Self {
542        Self {
543            region_ids: vec![region_id],
544            strategy: FlushStrategy::Sync,
545            error_strategy: FlushErrorStrategy::FailFast,
546            reason: None,
547        }
548    }
549
550    /// Create asynchronous batch flush (fire-and-forget)
551    pub fn async_batch(region_ids: Vec<RegionId>) -> Self {
552        Self {
553            region_ids,
554            strategy: FlushStrategy::Async,
555            error_strategy: FlushErrorStrategy::TryAll,
556            reason: None,
557        }
558    }
559
560    /// Create synchronous batch flush with error strategy
561    pub fn sync_batch(region_ids: Vec<RegionId>, error_strategy: FlushErrorStrategy) -> Self {
562        Self {
563            region_ids,
564            strategy: FlushStrategy::Sync,
565            error_strategy,
566            reason: None,
567        }
568    }
569
570    pub fn with_reason(mut self, reason: RegionFlushReason) -> Self {
571        self.reason = Some(reason);
572        self
573    }
574
575    /// Check if this is a single region flush.
576    pub fn is_single_region(&self) -> bool {
577        self.region_ids.len() == 1
578    }
579
580    /// Get the single region ID if this is a single region flush.
581    pub fn single_region_id(&self) -> Option<RegionId> {
582        if self.is_single_region() {
583            self.region_ids.first().copied()
584        } else {
585            None
586        }
587    }
588
589    /// Check if this is a hint (asynchronous) operation.
590    pub fn is_hint(&self) -> bool {
591        matches!(self.strategy, FlushStrategy::Async)
592    }
593
594    /// Check if this is a synchronous operation.
595    pub fn is_sync(&self) -> bool {
596        matches!(self.strategy, FlushStrategy::Sync)
597    }
598}
599
600impl From<RegionId> for FlushRegions {
601    fn from(region_id: RegionId) -> Self {
602        Self::sync_single(region_id)
603    }
604}
605
606#[derive(Debug, Deserialize)]
607#[serde(untagged)]
608enum SingleOrMultiple<T> {
609    Single(T),
610    Multiple(Vec<T>),
611}
612
613fn single_or_multiple_from<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
614where
615    D: Deserializer<'de>,
616    T: Deserialize<'de>,
617{
618    let helper = SingleOrMultiple::<T>::deserialize(deserializer)?;
619    Ok(match helper {
620        SingleOrMultiple::Single(x) => vec![x],
621        SingleOrMultiple::Multiple(xs) => xs,
622    })
623}
624
625/// Instruction to get file references for specified regions.
626#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
627pub struct GetFileRefs {
628    /// List of region IDs to get file references from active FileHandles (in-memory).
629    pub query_regions: Vec<RegionId>,
630    /// Mapping from the src region IDs (whose file references to look for) to
631    /// the dst region IDs (where to read the manifests).
632    /// Key: The source region IDs (where files originally came from).
633    /// Value: The set of destination region IDs (whose manifests need to be read).
634    pub related_regions: HashMap<RegionId, HashSet<RegionId>>,
635}
636
637impl Display for GetFileRefs {
638    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
639        write!(f, "GetFileRefs(region_ids={:?})", self.query_regions)
640    }
641}
642
643/// Instruction to get file references using the packed manifest format.
644#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
645pub struct GetPackedFileRefs {
646    /// List of region IDs to get file references from active FileHandles (in-memory).
647    pub query_regions: Vec<RegionId>,
648    /// Mapping from the src region IDs (whose file references to look for) to
649    /// the dst region IDs (where to read the manifests).
650    /// Key: The source region IDs (where files originally came from).
651    /// Value: The set of destination region IDs (whose manifests need to be read).
652    pub related_regions: HashMap<RegionId, HashSet<RegionId>>,
653}
654
655impl Display for GetPackedFileRefs {
656    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
657        write!(f, "GetPackedFileRefs(region_ids={:?})", self.query_regions)
658    }
659}
660
661/// Instruction to trigger garbage collection for a region.
662#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
663pub struct GcRegions {
664    /// The region ID to perform GC on, only regions that are currently on the given datanode can be garbage collected, regions not on the datanode will report errors.
665    pub regions: Vec<RegionId>,
666    /// The file references manifest containing temporary file references.
667    pub file_refs_manifest: FileRefsManifest,
668    /// Whether to perform a full file listing to find orphan files.
669    pub full_file_listing: bool,
670}
671
672/// Instruction to trigger garbage collection with a packed file-reference manifest.
673#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
674pub struct PackedGcRegions {
675    /// The region ID to perform GC on.
676    pub regions: Vec<RegionId>,
677    /// Packed manifest used by the packed-only GC protocol.
678    pub packed_file_refs_manifest: PackedFileRefsManifest,
679    /// Whether to perform a full file listing to find orphan files.
680    pub full_file_listing: bool,
681}
682
683impl Display for PackedGcRegions {
684    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
685        let file_refs_count = self.packed_file_refs_manifest.file_refs.len();
686        write!(
687            f,
688            "PackedGcRegions(regions={:?}, file_refs_count={}, full_file_listing={})",
689            self.regions, file_refs_count, self.full_file_listing
690        )
691    }
692}
693
694/// A packed, JSON-compatible encoding of a file reference manifest.
695#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
696pub struct PackedFileRefsManifest {
697    /// Required packed file references for each region.
698    pub file_refs: HashMap<RegionId, PackedRegionFileRefs>,
699    #[serde(default)]
700    pub manifest_version: HashMap<RegionId, u64>,
701    #[serde(default)]
702    pub cross_region_refs: HashMap<RegionId, HashSet<RegionId>>,
703}
704
705/// Packed file references for one region, encoded with STANDARD Base64.
706///
707/// `files` is required and contains 16-byte UUID records for references whose
708/// `index_version` is `None`. `indexed` is required and contains 24-byte records
709/// for references whose `index_version` is `Some`: a 16-byte UUID followed by
710/// an 8-byte big-endian `u64` version. Decoding fails when either field is not
711/// valid STANDARD Base64 or its decoded bytes do not align to the corresponding
712/// record width.
713#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
714pub struct PackedRegionFileRefs {
715    /// Required STANDARD Base64-encoded 16-byte UUID records.
716    pub files: String,
717    /// Required STANDARD Base64-encoded 16-byte UUID and 8-byte version records.
718    pub indexed: String,
719}
720
721impl PackedFileRefsManifest {
722    /// Packs a file reference manifest using required [`PackedRegionFileRefs`]
723    /// STANDARD Base64 fields.
724    ///
725    /// References whose `index_version` is `None` are encoded as 16-byte UUID
726    /// `files` records; references whose `index_version` is `Some` are encoded
727    /// as 24-byte `indexed` records: a 16-byte UUID followed by an 8-byte
728    /// big-endian `u64` version.
729    pub fn from_manifest(manifest: &FileRefsManifest) -> Self {
730        Self {
731            file_refs: manifest
732                .file_refs
733                .iter()
734                .map(|(region, refs)| (*region, PackedRegionFileRefs::from_refs(refs)))
735                .collect(),
736            manifest_version: manifest.manifest_version.clone(),
737            cross_region_refs: manifest.cross_region_refs.clone(),
738        }
739    }
740
741    /// Decodes this packed representation into a file reference manifest.
742    ///
743    /// Returns a typed error for invalid STANDARD Base64 or malformed record
744    /// framing without retaining encoded payloads.
745    pub fn into_manifest(self) -> crate::error::Result<FileRefsManifest> {
746        let mut file_refs = HashMap::new();
747        for (region, encoded) in self.file_refs {
748            file_refs.insert(region, encoded.into_refs(region)?);
749        }
750        Ok(FileRefsManifest {
751            file_refs,
752            manifest_version: self.manifest_version,
753            cross_region_refs: self.cross_region_refs,
754        })
755    }
756}
757
758impl PackedRegionFileRefs {
759    /// Packs file references as the documented STANDARD Base64 record streams.
760    pub fn from_refs(refs: &HashSet<FileRef>) -> Self {
761        let engine = base64::engine::general_purpose::STANDARD;
762        let mut files = Vec::new();
763        let mut indexed = Vec::new();
764        for file_ref in refs {
765            match file_ref.index_version {
766                None => files.extend_from_slice(file_ref.file_id.as_bytes()),
767                Some(version) => {
768                    indexed.extend_from_slice(file_ref.file_id.as_bytes());
769                    indexed.extend_from_slice(&version.to_be_bytes());
770                }
771            }
772        }
773        Self {
774            files: engine.encode(files),
775            indexed: engine.encode(indexed),
776        }
777    }
778
779    /// Decodes the documented STANDARD Base64 record streams for `region`.
780    fn into_refs(self, region: RegionId) -> crate::error::Result<HashSet<FileRef>> {
781        let engine = base64::engine::general_purpose::STANDARD;
782        let files = engine
783            .decode(self.files)
784            .context(DecodePackedFileRefsSnafu)?;
785        let indexed = engine
786            .decode(self.indexed)
787            .context(DecodePackedFileRefsSnafu)?;
788        if files.len() % 16 != 0 || indexed.len() % 24 != 0 {
789            return InvalidPackedFileRefsSnafu.fail();
790        }
791
792        let mut refs = HashSet::new();
793        for bytes in files.as_chunks::<16>().0 {
794            let mut id = [0; 16];
795            id.copy_from_slice(bytes);
796            refs.insert(FileRef::new(region, FileId::from_bytes(id), None));
797        }
798        for bytes in indexed.as_chunks::<24>().0 {
799            let mut id = [0; 16];
800            id.copy_from_slice(&bytes[..16]);
801            let mut version = [0; 8];
802            version.copy_from_slice(&bytes[16..]);
803            refs.insert(FileRef::new(
804                region,
805                FileId::from_bytes(id),
806                Some(u64::from_be_bytes(version)),
807            ));
808        }
809        Ok(refs)
810    }
811}
812
813impl Display for GcRegions {
814    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
815        write!(
816            f,
817            "GcRegion(regions={:?}, file_refs_count={}, full_file_listing={})",
818            self.regions,
819            self.file_refs_manifest.file_refs.len(),
820            self.full_file_listing
821        )
822    }
823}
824
825/// Reply for GetFileRefs instruction.
826#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
827pub struct GetFileRefsReply {
828    /// The file references manifest.
829    pub file_refs_manifest: FileRefsManifest,
830    /// Whether the operation was successful.
831    pub success: bool,
832    /// Error message if any.
833    pub error: Option<InstructionError>,
834}
835
836impl Display for GetFileRefsReply {
837    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
838        write!(
839            f,
840            "GetFileRefsReply(success={}, file_refs_count={}, error={:?})",
841            self.success,
842            self.file_refs_manifest.file_refs.len(),
843            self.error
844        )
845    }
846}
847
848/// Reply for GetPackedFileRefs instruction.
849#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
850pub struct GetPackedFileRefsReply {
851    pub packed_file_refs_manifest: PackedFileRefsManifest,
852    pub success: bool,
853    pub error: Option<InstructionError>,
854}
855
856impl Display for GetPackedFileRefsReply {
857    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
858        write!(
859            f,
860            "GetPackedFileRefsReply(success={}, file_refs_count={}, error={:?})",
861            self.success,
862            self.packed_file_refs_manifest.file_refs.len(),
863            self.error
864        )
865    }
866}
867
868/// Reply for GC instruction.
869#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
870pub struct GcRegionsReply {
871    pub result: InstructionResult<GcReport>,
872}
873
874impl Display for GcRegionsReply {
875    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
876        write!(
877            f,
878            "GcReply(result={})",
879            match &self.result {
880                Ok(report) => format!(
881                    "GcReport(deleted_files_count={}, need_retry_regions_count={})",
882                    report.deleted_files.len(),
883                    report.need_retry_regions.len()
884                ),
885                Err(err) => format!("Err({})", err),
886            }
887        )
888    }
889}
890
891#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
892pub struct EnterStagingRegion {
893    pub region_id: RegionId,
894    #[serde(
895        alias = "partition_expr",
896        deserialize_with = "deserialize_enter_staging_partition_directive",
897        serialize_with = "serialize_enter_staging_partition_directive"
898    )]
899    pub partition_directive: StagingPartitionDirective,
900}
901
902impl Display for EnterStagingRegion {
903    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
904        write!(
905            f,
906            "EnterStagingRegion(region_id={}, partition_directive={})",
907            self.region_id, self.partition_directive
908        )
909    }
910}
911
912#[derive(Debug, Clone, PartialEq, Eq)]
913pub enum StagingPartitionDirective {
914    UpdatePartitionExpr(String),
915    RejectAllWrites,
916}
917
918impl StagingPartitionDirective {
919    /// Returns the partition expression carried by this directive, if any.
920    pub fn as_partition_expr(&self) -> Option<&str> {
921        match self {
922            Self::UpdatePartitionExpr(expr) => Some(expr),
923            Self::RejectAllWrites => None,
924        }
925    }
926}
927
928impl Display for StagingPartitionDirective {
929    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
930        match self {
931            Self::UpdatePartitionExpr(expr) => write!(f, "UpdatePartitionExpr({})", expr),
932            Self::RejectAllWrites => write!(f, "RejectAllWrites"),
933        }
934    }
935}
936
937fn serialize_enter_staging_partition_directive<S>(
938    rule: &StagingPartitionDirective,
939    serializer: S,
940) -> std::result::Result<S::Ok, S::Error>
941where
942    S: Serializer,
943{
944    match rule {
945        StagingPartitionDirective::UpdatePartitionExpr(expr) => serializer.serialize_str(expr),
946        StagingPartitionDirective::RejectAllWrites => {
947            #[derive(Serialize)]
948            struct RejectAllWritesSer<'a> {
949                r#type: &'a str,
950            }
951
952            RejectAllWritesSer {
953                r#type: "reject_all_writes",
954            }
955            .serialize(serializer)
956        }
957    }
958}
959
960fn deserialize_enter_staging_partition_directive<'de, D>(
961    deserializer: D,
962) -> std::result::Result<StagingPartitionDirective, D::Error>
963where
964    D: Deserializer<'de>,
965{
966    #[derive(Deserialize)]
967    #[serde(untagged)]
968    enum Compat {
969        Legacy(String),
970        TypeTagged { r#type: String },
971    }
972
973    match Compat::deserialize(deserializer)? {
974        Compat::Legacy(expr) => Ok(StagingPartitionDirective::UpdatePartitionExpr(expr)),
975        Compat::TypeTagged { r#type } if r#type == "reject_all_writes" => {
976            Ok(StagingPartitionDirective::RejectAllWrites)
977        }
978        Compat::TypeTagged { r#type } => Err(serde::de::Error::custom(format!(
979            "Unknown enter staging partition directive type: {}",
980            r#type
981        ))),
982    }
983}
984
985/// Instruction payload for syncing a region from a manifest or another region.
986#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
987pub struct SyncRegion {
988    /// Region id to sync.
989    pub region_id: RegionId,
990    /// Request to sync the region.
991    pub request: SyncRegionFromRequest,
992}
993
994impl Display for SyncRegion {
995    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
996        write!(
997            f,
998            "SyncRegion(region_id={}, request={:?})",
999            self.region_id, self.request
1000        )
1001    }
1002}
1003
1004#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
1005pub struct RemapManifest {
1006    pub region_id: RegionId,
1007    /// Regions to remap manifests from.
1008    pub input_regions: Vec<RegionId>,
1009    /// For each old region, which new regions should receive its files
1010    pub region_mapping: HashMap<RegionId, Vec<RegionId>>,
1011    /// New partition expressions for the new regions.
1012    pub new_partition_exprs: HashMap<RegionId, String>,
1013    /// Only verify that the remap would be accepted instead of writing staging manifests.
1014    ///
1015    /// The repartition procedure sends such a request to each *source leader* before it publishes
1016    /// the new routes; the datanode then reads the region's persisted manifest and reports whether
1017    /// the region holds a file it did not create itself. Nothing is staged and nothing is written.
1018    ///
1019    /// An older datanode ignores this unknown field (it is `#[serde(default)]`, so it simply
1020    /// deserializes as `false`) and performs an ordinary remap. That is still safe: an ordinary
1021    /// remap requires the region to be in staging state, and these sources are not staged yet, so
1022    /// the datanode answers with the structured stage-required error
1023    /// (`mito2::worker::handle_remap` → `InvalidRequest` "region is not in staging state"). Metasrv
1024    /// therefore sees an error rather than a silent success, and aborts the group before the
1025    /// routes are published.
1026    #[serde(default)]
1027    pub validate_only: bool,
1028}
1029
1030impl Display for RemapManifest {
1031    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1032        write!(
1033            f,
1034            "RemapManifest(region_id={}, input_regions={:?}, region_mapping={:?}, new_partition_exprs={:?}, validate_only={})",
1035            self.region_id,
1036            self.input_regions,
1037            self.region_mapping,
1038            self.new_partition_exprs,
1039            self.validate_only
1040        )
1041    }
1042}
1043
1044#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1045pub struct ApplyStagingManifest {
1046    /// The region ID to apply the staging manifest to.
1047    pub region_id: RegionId,
1048    /// The partition expression of the staging region.
1049    pub partition_expr: String,
1050    /// The region that stores the staging manifests in its staging blob storage.
1051    pub central_region_id: RegionId,
1052    /// The relative path to the staging manifest within the central region's staging blob storage.
1053    pub manifest_path: String,
1054}
1055
1056impl Display for ApplyStagingManifest {
1057    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1058        write!(
1059            f,
1060            "ApplyStagingManifest(region_id={}, partition_expr={}, central_region_id={}, manifest_path={})",
1061            self.region_id, self.partition_expr, self.central_region_id, self.manifest_path
1062        )
1063    }
1064}
1065
1066#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1067pub enum MetadataCompaction {
1068    /// Wait for compaction to drain, then hold the pause for the remaining sync budget.
1069    Pause {
1070        region_id: RegionId,
1071        remaining: Duration,
1072    },
1073    /// Resume compaction on the source metadata region.
1074    Release { region_id: RegionId },
1075}
1076
1077#[derive(Debug, Clone, Serialize, Deserialize, Display, PartialEq)]
1078pub enum Instruction {
1079    /// Opens regions.
1080    #[serde(deserialize_with = "single_or_multiple_from", alias = "OpenRegion")]
1081    OpenRegions(Vec<OpenRegion>),
1082    /// Closes regions.
1083    #[serde(deserialize_with = "single_or_multiple_from", alias = "CloseRegion")]
1084    CloseRegions(Vec<RegionIdent>),
1085    /// Upgrades regions.
1086    #[serde(deserialize_with = "single_or_multiple_from", alias = "UpgradeRegion")]
1087    UpgradeRegions(Vec<UpgradeRegion>),
1088    #[serde(
1089        deserialize_with = "single_or_multiple_from",
1090        alias = "DowngradeRegion"
1091    )]
1092    /// Downgrades regions.
1093    DowngradeRegions(Vec<DowngradeRegion>),
1094    /// Invalidates batch cache.
1095    InvalidateCaches(Vec<CacheIdent>),
1096    /// Flushes regions.
1097    FlushRegions(FlushRegions),
1098    /// Gets file references for regions.
1099    GetFileRefs(GetFileRefs),
1100    /// Gets file references using the packed manifest format.
1101    GetPackedFileRefs(GetPackedFileRefs),
1102    /// Triggers garbage collection for a region.
1103    GcRegions(GcRegions),
1104    /// Triggers garbage collection with a packed file-reference manifest.
1105    PackedGcRegions(PackedGcRegions),
1106    /// Temporary suspend serving reads or writes
1107    Suspend,
1108    /// Makes regions enter staging state.
1109    EnterStagingRegions(Vec<EnterStagingRegion>),
1110    /// Controls source metadata compaction during repartition.
1111    MetadataCompaction(MetadataCompaction),
1112    /// Syncs regions.
1113    SyncRegions(Vec<SyncRegion>),
1114    /// Remaps manifests for a region.
1115    RemapManifest(RemapManifest),
1116
1117    /// Applies staging manifests for a region.
1118    ApplyStagingManifests(Vec<ApplyStagingManifest>),
1119}
1120
1121impl Instruction {
1122    /// Converts the instruction into a vector of [OpenRegion].
1123    pub fn into_open_regions(self) -> Option<Vec<OpenRegion>> {
1124        match self {
1125            Self::OpenRegions(open_regions) => Some(open_regions),
1126            _ => None,
1127        }
1128    }
1129
1130    /// Converts the instruction into a vector of [RegionIdent].
1131    pub fn into_close_regions(self) -> Option<Vec<RegionIdent>> {
1132        match self {
1133            Self::CloseRegions(close_regions) => Some(close_regions),
1134            _ => None,
1135        }
1136    }
1137
1138    /// Converts the instruction into a [FlushRegions].
1139    pub fn into_flush_regions(self) -> Option<FlushRegions> {
1140        match self {
1141            Self::FlushRegions(flush_regions) => Some(flush_regions),
1142            _ => None,
1143        }
1144    }
1145
1146    /// Converts the instruction into a [DowngradeRegion].
1147    pub fn into_downgrade_regions(self) -> Option<Vec<DowngradeRegion>> {
1148        match self {
1149            Self::DowngradeRegions(downgrade_region) => Some(downgrade_region),
1150            _ => None,
1151        }
1152    }
1153
1154    /// Converts the instruction into a [UpgradeRegion].
1155    pub fn into_upgrade_regions(self) -> Option<Vec<UpgradeRegion>> {
1156        match self {
1157            Self::UpgradeRegions(upgrade_region) => Some(upgrade_region),
1158            _ => None,
1159        }
1160    }
1161
1162    pub fn into_get_file_refs(self) -> Option<GetFileRefs> {
1163        match self {
1164            Self::GetFileRefs(get_file_refs) => Some(get_file_refs),
1165            _ => None,
1166        }
1167    }
1168
1169    pub fn into_gc_regions(self) -> Option<GcRegions> {
1170        match self {
1171            Self::GcRegions(gc_regions) => Some(gc_regions),
1172            _ => None,
1173        }
1174    }
1175
1176    pub fn into_enter_staging_regions(self) -> Option<Vec<EnterStagingRegion>> {
1177        match self {
1178            Self::EnterStagingRegions(enter_staging) => Some(enter_staging),
1179            _ => None,
1180        }
1181    }
1182
1183    pub fn into_sync_regions(self) -> Option<Vec<SyncRegion>> {
1184        match self {
1185            Self::SyncRegions(sync_regions) => Some(sync_regions),
1186            _ => None,
1187        }
1188    }
1189}
1190
1191/// The reply of [UpgradeRegion].
1192#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
1193pub struct UpgradeRegionReply {
1194    /// The [RegionId].
1195    /// For compatibility, it is defaulted to [RegionId::new(0, 0)].
1196    #[serde(default)]
1197    pub region_id: RegionId,
1198    /// Returns true if `last_entry_id` has been replayed to the latest.
1199    pub ready: bool,
1200    /// Indicates whether the region exists.
1201    pub exists: bool,
1202    /// Returns error if any.
1203    pub error: Option<InstructionError>,
1204}
1205
1206impl Display for UpgradeRegionReply {
1207    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1208        write!(
1209            f,
1210            "(ready={}, exists={}, error={:?})",
1211            self.ready, self.exists, self.error
1212        )
1213    }
1214}
1215
1216#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
1217pub struct DowngradeRegionsReply {
1218    pub replies: Vec<DowngradeRegionReply>,
1219}
1220
1221impl DowngradeRegionsReply {
1222    pub fn new(replies: Vec<DowngradeRegionReply>) -> Self {
1223        Self { replies }
1224    }
1225
1226    pub fn single(reply: DowngradeRegionReply) -> Self {
1227        Self::new(vec![reply])
1228    }
1229}
1230
1231#[derive(Deserialize)]
1232#[serde(untagged)]
1233enum DowngradeRegionsCompat {
1234    Single(DowngradeRegionReply),
1235    Multiple(DowngradeRegionsReply),
1236}
1237
1238fn downgrade_regions_compat_from<'de, D>(deserializer: D) -> Result<DowngradeRegionsReply, D::Error>
1239where
1240    D: Deserializer<'de>,
1241{
1242    let helper = DowngradeRegionsCompat::deserialize(deserializer)?;
1243    Ok(match helper {
1244        DowngradeRegionsCompat::Single(x) => DowngradeRegionsReply::new(vec![x]),
1245        DowngradeRegionsCompat::Multiple(reply) => reply,
1246    })
1247}
1248
1249#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
1250pub struct UpgradeRegionsReply {
1251    pub replies: Vec<UpgradeRegionReply>,
1252}
1253
1254impl UpgradeRegionsReply {
1255    pub fn new(replies: Vec<UpgradeRegionReply>) -> Self {
1256        Self { replies }
1257    }
1258
1259    pub fn single(reply: UpgradeRegionReply) -> Self {
1260        Self::new(vec![reply])
1261    }
1262}
1263
1264#[derive(Deserialize)]
1265#[serde(untagged)]
1266enum UpgradeRegionsCompat {
1267    Single(UpgradeRegionReply),
1268    Multiple(UpgradeRegionsReply),
1269}
1270
1271fn upgrade_regions_compat_from<'de, D>(deserializer: D) -> Result<UpgradeRegionsReply, D::Error>
1272where
1273    D: Deserializer<'de>,
1274{
1275    let helper = UpgradeRegionsCompat::deserialize(deserializer)?;
1276    Ok(match helper {
1277        UpgradeRegionsCompat::Single(x) => UpgradeRegionsReply::new(vec![x]),
1278        UpgradeRegionsCompat::Multiple(reply) => reply,
1279    })
1280}
1281
1282#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
1283pub struct EnterStagingRegionReply {
1284    pub region_id: RegionId,
1285    /// Returns true if the region has entered staging with the target directive.
1286    pub ready: bool,
1287    /// Indicates whether the region exists.
1288    pub exists: bool,
1289    /// Return error if any during the operation.
1290    pub error: Option<InstructionError>,
1291}
1292
1293#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
1294pub struct EnterStagingRegionsReply {
1295    pub replies: Vec<EnterStagingRegionReply>,
1296}
1297
1298impl EnterStagingRegionsReply {
1299    pub fn new(replies: Vec<EnterStagingRegionReply>) -> Self {
1300        Self { replies }
1301    }
1302}
1303
1304/// Reply for a single region sync request.
1305#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
1306pub struct SyncRegionReply {
1307    /// Region id of the synced region.
1308    pub region_id: RegionId,
1309    /// Returns true if the region is successfully synced and ready.
1310    pub ready: bool,
1311    /// Indicates whether the region exists.
1312    pub exists: bool,
1313    /// Return error message if any during the operation.
1314    pub error: Option<InstructionError>,
1315}
1316
1317/// Reply for a batch of region sync requests.
1318#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
1319pub struct SyncRegionsReply {
1320    pub replies: Vec<SyncRegionReply>,
1321}
1322
1323impl SyncRegionsReply {
1324    pub fn new(replies: Vec<SyncRegionReply>) -> Self {
1325        Self { replies }
1326    }
1327}
1328
1329#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
1330pub struct RemapManifestReply {
1331    /// Returns false if the region does not exist.
1332    pub exists: bool,
1333    /// A map from region IDs to their corresponding remapped manifest paths.
1334    pub manifest_paths: HashMap<RegionId, String>,
1335    /// Return error if any during the operation.
1336    pub error: Option<InstructionError>,
1337}
1338
1339impl Display for RemapManifestReply {
1340    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1341        write!(
1342            f,
1343            "RemapManifestReply(manifest_paths={:?}, error={:?})",
1344            self.manifest_paths, self.error
1345        )
1346    }
1347}
1348
1349#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
1350pub struct ApplyStagingManifestsReply {
1351    pub replies: Vec<ApplyStagingManifestReply>,
1352}
1353
1354impl ApplyStagingManifestsReply {
1355    pub fn new(replies: Vec<ApplyStagingManifestReply>) -> Self {
1356        Self { replies }
1357    }
1358}
1359
1360#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
1361pub struct ApplyStagingManifestReply {
1362    pub region_id: RegionId,
1363    /// Returns true if the region is ready to serve reads and writes.
1364    pub ready: bool,
1365    /// Indicates whether the region exists.
1366    pub exists: bool,
1367    /// Return error if any during the operation.
1368    pub error: Option<InstructionError>,
1369}
1370
1371#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
1372#[serde(tag = "type", rename_all = "snake_case")]
1373pub enum InstructionReply {
1374    #[serde(alias = "open_region")]
1375    OpenRegions(SimpleReply),
1376    #[serde(alias = "close_region")]
1377    CloseRegions(SimpleReply),
1378    #[serde(
1379        deserialize_with = "upgrade_regions_compat_from",
1380        alias = "upgrade_region"
1381    )]
1382    UpgradeRegions(UpgradeRegionsReply),
1383    #[serde(
1384        alias = "downgrade_region",
1385        deserialize_with = "downgrade_regions_compat_from"
1386    )]
1387    DowngradeRegions(DowngradeRegionsReply),
1388    FlushRegions(FlushRegionReply),
1389    GetFileRefs(GetFileRefsReply),
1390    GetPackedFileRefs(GetPackedFileRefsReply),
1391    GcRegions(GcRegionsReply),
1392    EnterStagingRegions(EnterStagingRegionsReply),
1393    MetadataCompaction(SimpleReply),
1394    SyncRegions(SyncRegionsReply),
1395    RemapManifest(RemapManifestReply),
1396    ApplyStagingManifests(ApplyStagingManifestsReply),
1397}
1398
1399impl Display for InstructionReply {
1400    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1401        match self {
1402            Self::OpenRegions(reply) => write!(f, "InstructionReply::OpenRegions({})", reply),
1403            Self::CloseRegions(reply) => write!(f, "InstructionReply::CloseRegions({})", reply),
1404            Self::UpgradeRegions(reply) => {
1405                write!(f, "InstructionReply::UpgradeRegions({:?})", reply.replies)
1406            }
1407            Self::DowngradeRegions(reply) => {
1408                write!(f, "InstructionReply::DowngradeRegions({:?})", reply.replies)
1409            }
1410            Self::FlushRegions(reply) => write!(f, "InstructionReply::FlushRegions({})", reply),
1411            Self::GetFileRefs(reply) => write!(f, "InstructionReply::GetFileRefs({})", reply),
1412            Self::GetPackedFileRefs(reply) => {
1413                write!(f, "InstructionReply::GetPackedFileRefs({})", reply)
1414            }
1415            Self::GcRegions(reply) => write!(f, "InstructionReply::GcRegion({})", reply),
1416            Self::EnterStagingRegions(reply) => {
1417                write!(
1418                    f,
1419                    "InstructionReply::EnterStagingRegions({:?})",
1420                    reply.replies
1421                )
1422            }
1423            Self::MetadataCompaction(reply) => {
1424                write!(f, "InstructionReply::MetadataCompaction({reply})")
1425            }
1426            Self::SyncRegions(reply) => {
1427                write!(f, "InstructionReply::SyncRegions({:?})", reply.replies)
1428            }
1429            Self::RemapManifest(reply) => write!(f, "InstructionReply::RemapManifest({})", reply),
1430            Self::ApplyStagingManifests(reply) => write!(
1431                f,
1432                "InstructionReply::ApplyStagingManifests({:?})",
1433                reply.replies
1434            ),
1435        }
1436    }
1437}
1438
1439#[cfg(any(test, feature = "testing"))]
1440impl InstructionReply {
1441    pub fn expect_close_regions_reply(self) -> SimpleReply {
1442        match self {
1443            Self::CloseRegions(reply) => reply,
1444            _ => panic!("Expected CloseRegions reply"),
1445        }
1446    }
1447
1448    pub fn expect_open_regions_reply(self) -> SimpleReply {
1449        match self {
1450            Self::OpenRegions(reply) => reply,
1451            _ => panic!("Expected OpenRegions reply"),
1452        }
1453    }
1454
1455    pub fn expect_upgrade_regions_reply(self) -> Vec<UpgradeRegionReply> {
1456        match self {
1457            Self::UpgradeRegions(reply) => reply.replies,
1458            _ => panic!("Expected UpgradeRegion reply"),
1459        }
1460    }
1461
1462    pub fn expect_downgrade_regions_reply(self) -> Vec<DowngradeRegionReply> {
1463        match self {
1464            Self::DowngradeRegions(reply) => reply.replies,
1465            _ => panic!("Expected DowngradeRegion reply"),
1466        }
1467    }
1468
1469    pub fn expect_flush_regions_reply(self) -> FlushRegionReply {
1470        match self {
1471            Self::FlushRegions(reply) => reply,
1472            _ => panic!("Expected FlushRegions reply"),
1473        }
1474    }
1475
1476    pub fn expect_enter_staging_regions_reply(self) -> Vec<EnterStagingRegionReply> {
1477        match self {
1478            Self::EnterStagingRegions(reply) => reply.replies,
1479            _ => panic!("Expected EnterStagingRegion reply"),
1480        }
1481    }
1482
1483    pub fn expect_sync_regions_reply(self) -> Vec<SyncRegionReply> {
1484        match self {
1485            Self::SyncRegions(reply) => reply.replies,
1486            _ => panic!("Expected SyncRegion reply"),
1487        }
1488    }
1489
1490    pub fn expect_remap_manifest_reply(self) -> RemapManifestReply {
1491        match self {
1492            Self::RemapManifest(reply) => reply,
1493            _ => panic!("Expected RemapManifest reply"),
1494        }
1495    }
1496
1497    pub fn expect_apply_staging_manifests_reply(self) -> Vec<ApplyStagingManifestReply> {
1498        match self {
1499            Self::ApplyStagingManifests(reply) => reply.replies,
1500            _ => panic!("Expected ApplyStagingManifest reply"),
1501        }
1502    }
1503}
1504
1505#[cfg(test)]
1506mod tests {
1507    use std::collections::{HashMap, HashSet};
1508    use std::error::Error as _;
1509
1510    use common_error::mock::MockError;
1511    use common_wal::options::WalOptions;
1512    use store_api::storage::{FileId, FileRef};
1513
1514    use super::*;
1515
1516    #[test]
1517    fn test_metadata_compaction_mailbox_wire() {
1518        let wire = serde_json::json!([
1519            {"MetadataCompaction": {"Pause": {
1520                "region_id": 4294967298_u64,
1521                "remaining": {"secs": 19, "nanos": 500000000}
1522            }}},
1523            {"MetadataCompaction": {"Release": {
1524                "region_id": 4294967298_u64
1525            }}}
1526        ]);
1527        let region_id = RegionId::new(1, 2);
1528        let expected = vec![
1529            Instruction::MetadataCompaction(MetadataCompaction::Pause {
1530                region_id,
1531                remaining: Duration::from_millis(19_500),
1532            }),
1533            Instruction::MetadataCompaction(MetadataCompaction::Release { region_id }),
1534        ];
1535        assert_eq!(
1536            expected,
1537            serde_json::from_value::<Vec<Instruction>>(wire.clone()).unwrap()
1538        );
1539        assert_eq!(wire, serde_json::to_value(expected).unwrap());
1540    }
1541
1542    #[test]
1543    fn test_instruction_error_serde() {
1544        let error = InstructionError::new(
1545            StatusCode::RegionNotFound,
1546            "region not found",
1547            RetryHint::Retryable,
1548        );
1549
1550        let serialized = serde_json::to_string(&error).unwrap();
1551        assert_eq!(
1552            r#"{"code":4005,"message":"region not found","retry_hint":"retryable"}"#,
1553            serialized
1554        );
1555
1556        let deserialized: InstructionError = serde_json::from_str(&serialized).unwrap();
1557        assert_eq!(error, deserialized);
1558
1559        assert!(
1560            serde_json::from_str::<InstructionError>(
1561                r#"{"code":999999,"message":"unknown","retry_hint":"retryable"}"#
1562            )
1563            .is_err()
1564        );
1565        assert!(
1566            serde_json::from_str::<InstructionError>(
1567                r#"{"code":4005,"message":"unknown","retry_hint":"unknown"}"#
1568            )
1569            .is_err()
1570        );
1571    }
1572
1573    #[test]
1574    fn test_instruction_error_route_refresh_compatibility() {
1575        let error = InstructionError::new(
1576            StatusCode::RegionNotFound,
1577            "region not found",
1578            RetryHint::RetryAfterRouteRefresh,
1579        );
1580        let serialized = serde_json::to_string(&error).unwrap();
1581        assert_eq!(
1582            r#"{"code":4005,"message":"region not found","retry_hint":"retryable"}"#,
1583            serialized
1584        );
1585        let decoded: InstructionError = serde_json::from_str(&serialized).unwrap();
1586        assert_eq!(decoded.code, error.code);
1587        assert_eq!(decoded.message, error.message);
1588        assert_eq!(decoded.retry_hint, RetryHint::Retryable);
1589        assert_eq!(error.retry_hint, RetryHint::RetryAfterRouteRefresh);
1590        assert_eq!(error.retry_hint.as_str(), "retry_after_route_refresh");
1591    }
1592
1593    #[test]
1594    fn test_remap_manifest_wire_accepts_a_metasrv_without_validate_only() {
1595        // A metasrv that predates the pre-publication check sends no `validate_only` key. A new
1596        // datanode has to read that as an ordinary remap - the old behaviour - so a mixed
1597        // cluster keeps working: nothing is staged yet, and the remap is refused.
1598        let region_id = RegionId::new(1, 2);
1599        let new_region_id = RegionId::new(1, 3);
1600        let mut wire = serde_json::to_value(Instruction::RemapManifest(RemapManifest {
1601            region_id,
1602            input_regions: vec![region_id],
1603            region_mapping: HashMap::from([(region_id, vec![new_region_id])]),
1604            new_partition_exprs: HashMap::from([(
1605                new_region_id,
1606                "col(x) >= 0 AND col(x) < 100".to_string(),
1607            )]),
1608            validate_only: true,
1609        }))
1610        .unwrap();
1611        wire["RemapManifest"]
1612            .as_object_mut()
1613            .unwrap()
1614            .remove("validate_only");
1615
1616        let instruction: Instruction = serde_json::from_value(wire).unwrap();
1617        let Instruction::RemapManifest(remap) = instruction else {
1618            panic!("expected a remap manifest instruction");
1619        };
1620        assert!(!remap.validate_only);
1621        assert_eq!(remap.region_id, region_id);
1622
1623        // A validate-only instruction is told apart by the key alone, and an old datanode that
1624        // drops it performs an ordinary remap, which fails because nothing is staged: metasrv
1625        // never mistakes it for a successful check.
1626        let wire = serde_json::to_value(Instruction::RemapManifest(RemapManifest {
1627            region_id,
1628            input_regions: vec![region_id],
1629            region_mapping: HashMap::from([(region_id, vec![new_region_id])]),
1630            new_partition_exprs: HashMap::new(),
1631            validate_only: true,
1632        }))
1633        .unwrap();
1634        assert_eq!(
1635            wire["RemapManifest"]["validate_only"],
1636            serde_json::json!(true)
1637        );
1638        let decoded: Instruction = serde_json::from_value(wire).unwrap();
1639        let Instruction::RemapManifest(decoded) = decoded else {
1640            panic!("expected a remap manifest instruction");
1641        };
1642        assert!(decoded.validate_only);
1643    }
1644
1645    #[test]
1646    fn test_instruction_error_from_error() {
1647        let error = MockError::new(StatusCode::RegionNotFound);
1648
1649        let instruction_error = InstructionError::from_error(&error);
1650
1651        assert_eq!(StatusCode::RegionNotFound, instruction_error.code);
1652        assert_eq!("RegionNotFound", instruction_error.message);
1653        assert_eq!(RetryHint::NonRetryable, instruction_error.retry_hint);
1654    }
1655
1656    #[test]
1657    fn test_instruction_result_serde() {
1658        let success: InstructionResult<bool> = Ok(true);
1659        let serialized = serde_json::to_string(&success).unwrap();
1660        assert_eq!(r#"{"Ok":true}"#, serialized);
1661        let deserialized: InstructionResult<bool> = serde_json::from_str(&serialized).unwrap();
1662        assert_eq!(success, deserialized);
1663
1664        let failure: InstructionResult<bool> = Err(InstructionError::new(
1665            StatusCode::RegionBusy,
1666            "region busy",
1667            RetryHint::Retryable,
1668        ));
1669        let serialized = serde_json::to_string(&failure).unwrap();
1670        assert_eq!(
1671            r#"{"Err":{"code":4009,"message":"region busy","retry_hint":"retryable"}}"#,
1672            serialized
1673        );
1674        let deserialized: InstructionResult<bool> = serde_json::from_str(&serialized).unwrap();
1675        assert_eq!(failure, deserialized);
1676    }
1677
1678    #[test]
1679    fn test_serialize_instruction() {
1680        let open_region = Instruction::OpenRegions(vec![OpenRegion::new(
1681            RegionIdent {
1682                datanode_id: 2,
1683                table_id: 1024,
1684                region_number: 1,
1685                engine: "mito2".to_string(),
1686            },
1687            "test/foo",
1688            HashMap::new(),
1689            HashMap::new(),
1690            false,
1691            None,
1692            RegionRequirements::empty(),
1693        )]);
1694
1695        let serialized = serde_json::to_string(&open_region).unwrap();
1696        assert_eq!(
1697            r#"{"OpenRegions":[{"region_ident":{"datanode_id":2,"table_id":1024,"region_number":1,"engine":"mito2"},"region_storage_path":"test/foo","region_options":{},"region_wal_options":{},"skip_wal_replay":false,"requirements":{"object_storage":false}}]}"#,
1698            serialized
1699        );
1700
1701        let close_region = Instruction::CloseRegions(vec![RegionIdent {
1702            datanode_id: 2,
1703            table_id: 1024,
1704            region_number: 1,
1705            engine: "mito2".to_string(),
1706        }]);
1707
1708        let serialized = serde_json::to_string(&close_region).unwrap();
1709        assert_eq!(
1710            r#"{"CloseRegions":[{"datanode_id":2,"table_id":1024,"region_number":1,"engine":"mito2"}]}"#,
1711            serialized
1712        );
1713
1714        let upgrade_region = Instruction::UpgradeRegions(vec![UpgradeRegion {
1715            region_id: RegionId::new(1024, 1),
1716            last_entry_id: None,
1717            metadata_last_entry_id: None,
1718            replay_timeout: Duration::from_millis(1000),
1719            location_id: None,
1720            replay_entry_id: None,
1721            metadata_replay_entry_id: None,
1722            candidate_lease_id: None,
1723        }]);
1724
1725        let serialized = serde_json::to_string(&upgrade_region).unwrap();
1726        assert_eq!(
1727            r#"{"UpgradeRegions":[{"region_id":4398046511105,"last_entry_id":null,"metadata_last_entry_id":null,"replay_timeout":"1s","location_id":null}]}"#,
1728            serialized
1729        );
1730    }
1731
1732    #[test]
1733    fn test_serialize_instruction_reply() {
1734        let downgrade_region_reply = InstructionReply::DowngradeRegions(
1735            DowngradeRegionsReply::single(DowngradeRegionReply {
1736                region_id: RegionId::new(1024, 1),
1737                last_entry_id: None,
1738                metadata_last_entry_id: None,
1739                exists: true,
1740                error: None,
1741                has_skip_wal_writes: false,
1742            }),
1743        );
1744
1745        let serialized = serde_json::to_string(&downgrade_region_reply).unwrap();
1746        assert_eq!(
1747            r#"{"type":"downgrade_regions","replies":[{"region_id":4398046511105,"last_entry_id":null,"metadata_last_entry_id":null,"exists":true,"error":null}]}"#,
1748            serialized
1749        );
1750
1751        let upgrade_region_reply =
1752            InstructionReply::UpgradeRegions(UpgradeRegionsReply::single(UpgradeRegionReply {
1753                region_id: RegionId::new(1024, 1),
1754                ready: true,
1755                exists: true,
1756                error: None,
1757            }));
1758        let serialized = serde_json::to_string(&upgrade_region_reply).unwrap();
1759        assert_eq!(
1760            r#"{"type":"upgrade_regions","replies":[{"region_id":4398046511105,"ready":true,"exists":true,"error":null}]}"#,
1761            serialized
1762        );
1763    }
1764
1765    #[test]
1766    fn test_has_skip_wal_writes_wire() {
1767        // A generated encoding in the layout before the field (see the fixture's README), not a
1768        // capture from a release.
1769        let legacy: &[u8] = include_bytes!(
1770            "../../../../tests/compatibility/wire/downgrade_region_skip_wal_writes/legacy_downgrade_regions_reply.json"
1771        );
1772        let reply: InstructionReply = serde_json::from_slice(legacy).unwrap();
1773        assert_eq!(serde_json::to_vec(&reply).unwrap(), legacy);
1774        let replies = reply.expect_downgrade_regions_reply();
1775        assert!(!replies[0].has_skip_wal_writes);
1776
1777        let flagged = DowngradeRegionReply {
1778            has_skip_wal_writes: true,
1779            ..replies[0].clone()
1780        };
1781        let encoded = serde_json::to_value(&flagged).unwrap();
1782        assert_eq!(
1783            encoded["has_skip_wal_writes"],
1784            serde_json::Value::Bool(true)
1785        );
1786        #[allow(dead_code)]
1787        #[derive(Deserialize)]
1788        struct LegacyDowngradeRegionReply {
1789            #[serde(default)]
1790            region_id: RegionId,
1791            last_entry_id: Option<u64>,
1792            metadata_last_entry_id: Option<u64>,
1793            exists: bool,
1794            error: Option<InstructionError>,
1795        }
1796        serde_json::from_value::<LegacyDowngradeRegionReply>(encoded).unwrap();
1797    }
1798
1799    #[test]
1800    fn test_deserialize_instruction() {
1801        // legacy open region instruction
1802        let open_region_instruction = r#"{"OpenRegion":{"region_ident":{"datanode_id":2,"table_id":1024,"region_number":1,"engine":"mito2"},"region_storage_path":"test/foo","region_options":{},"region_wal_options":{},"skip_wal_replay":false}}"#;
1803        let open_region_instruction: Instruction =
1804            serde_json::from_str(open_region_instruction).unwrap();
1805        let open_region = Instruction::OpenRegions(vec![OpenRegion::new(
1806            RegionIdent {
1807                datanode_id: 2,
1808                table_id: 1024,
1809                region_number: 1,
1810                engine: "mito2".to_string(),
1811            },
1812            "test/foo",
1813            HashMap::new(),
1814            HashMap::new(),
1815            false,
1816            None,
1817            RegionRequirements::empty(),
1818        )]);
1819        assert_eq!(open_region_instruction, open_region);
1820
1821        // legacy close region instruction
1822        let close_region_instruction = r#"{"CloseRegion":{"datanode_id":2,"table_id":1024,"region_number":1,"engine":"mito2"}}"#;
1823        let close_region_instruction: Instruction =
1824            serde_json::from_str(close_region_instruction).unwrap();
1825        let close_region = Instruction::CloseRegions(vec![RegionIdent {
1826            datanode_id: 2,
1827            table_id: 1024,
1828            region_number: 1,
1829            engine: "mito2".to_string(),
1830        }]);
1831        assert_eq!(close_region_instruction, close_region);
1832
1833        // legacy downgrade region instruction
1834        let downgrade_region_instruction = r#"{"DowngradeRegions":{"region_id":4398046511105,"flush_timeout":{"secs":1,"nanos":0}}}"#;
1835        let downgrade_region_instruction: Instruction =
1836            serde_json::from_str(downgrade_region_instruction).unwrap();
1837        let downgrade_region = Instruction::DowngradeRegions(vec![DowngradeRegion {
1838            region_id: RegionId::new(1024, 1),
1839            flush_timeout: Some(Duration::from_millis(1000)),
1840        }]);
1841        assert_eq!(downgrade_region_instruction, downgrade_region);
1842
1843        // legacy upgrade region instruction
1844        let upgrade_region_instruction = r#"{"UpgradeRegion":{"region_id":4398046511105,"last_entry_id":null,"metadata_last_entry_id":null,"replay_timeout":"1s","location_id":null,"replay_entry_id":null,"metadata_replay_entry_id":null}}"#;
1845        let upgrade_region_instruction: Instruction =
1846            serde_json::from_str(upgrade_region_instruction).unwrap();
1847        let upgrade_region = Instruction::UpgradeRegions(vec![UpgradeRegion {
1848            region_id: RegionId::new(1024, 1),
1849            last_entry_id: None,
1850            metadata_last_entry_id: None,
1851            replay_timeout: Duration::from_millis(1000),
1852            location_id: None,
1853            replay_entry_id: None,
1854            metadata_replay_entry_id: None,
1855            candidate_lease_id: None,
1856        }]);
1857        assert_eq!(upgrade_region_instruction, upgrade_region);
1858    }
1859
1860    #[test]
1861    fn test_upgrade_region_candidate_lease_id_json() {
1862        let upgrade_region = UpgradeRegion {
1863            region_id: RegionId::new(1024, 1),
1864            replay_timeout: Duration::from_millis(1000),
1865            candidate_lease_id: Some(7),
1866            ..Default::default()
1867        };
1868        let json = serde_json::to_value(&upgrade_region).unwrap();
1869        assert_eq!(json["candidate_lease_id"], 7);
1870        assert_eq!(
1871            serde_json::from_value::<UpgradeRegion>(json).unwrap(),
1872            upgrade_region
1873        );
1874    }
1875
1876    #[test]
1877    fn test_deserialize_instruction_reply() {
1878        // legacy close region reply
1879        let close_region_instruction_reply =
1880            r#"{"result":true,"error":null,"type":"close_region"}"#;
1881        let close_region_instruction_reply: InstructionReply =
1882            serde_json::from_str(close_region_instruction_reply).unwrap();
1883        let close_region_reply = InstructionReply::CloseRegions(SimpleReply {
1884            result: true,
1885            error: None,
1886        });
1887        assert_eq!(close_region_instruction_reply, close_region_reply);
1888
1889        // legacy open region reply
1890        let open_region_instruction_reply = r#"{"result":true,"error":null,"type":"open_region"}"#;
1891        let open_region_instruction_reply: InstructionReply =
1892            serde_json::from_str(open_region_instruction_reply).unwrap();
1893        let open_region_reply = InstructionReply::OpenRegions(SimpleReply {
1894            result: true,
1895            error: None,
1896        });
1897        assert_eq!(open_region_instruction_reply, open_region_reply);
1898
1899        // legacy downgrade region reply
1900        let downgrade_region_instruction_reply = r#"{"region_id":4398046511105,"last_entry_id":null,"metadata_last_entry_id":null,"exists":true,"error":null,"type":"downgrade_region"}"#;
1901        let downgrade_region_instruction_reply: InstructionReply =
1902            serde_json::from_str(downgrade_region_instruction_reply).unwrap();
1903        let downgrade_region_reply = InstructionReply::DowngradeRegions(
1904            DowngradeRegionsReply::single(DowngradeRegionReply {
1905                region_id: RegionId::new(1024, 1),
1906                last_entry_id: None,
1907                metadata_last_entry_id: None,
1908                exists: true,
1909                error: None,
1910                has_skip_wal_writes: false,
1911            }),
1912        );
1913        assert_eq!(downgrade_region_instruction_reply, downgrade_region_reply);
1914
1915        // legacy upgrade region reply
1916        let upgrade_region_instruction_reply = r#"{"region_id":4398046511105,"ready":true,"exists":true,"error":null,"type":"upgrade_region"}"#;
1917        let upgrade_region_instruction_reply: InstructionReply =
1918            serde_json::from_str(upgrade_region_instruction_reply).unwrap();
1919        let upgrade_region_reply =
1920            InstructionReply::UpgradeRegions(UpgradeRegionsReply::single(UpgradeRegionReply {
1921                region_id: RegionId::new(1024, 1),
1922                ready: true,
1923                exists: true,
1924                error: None,
1925            }));
1926        assert_eq!(upgrade_region_instruction_reply, upgrade_region_reply);
1927    }
1928
1929    #[test]
1930    fn test_enter_staging_partition_rule_compatibility() {
1931        let legacy = r#"{"region_id":4398046511105,"partition_expr":"{\"Expr\":{\"lhs\":{\"Column\":\"x\"},\"op\":\"GtEq\",\"rhs\":{\"Value\":{\"Int32\":0}}}}"}"#;
1932        let enter: EnterStagingRegion = serde_json::from_str(legacy).unwrap();
1933        assert_eq!(enter.region_id, RegionId::new(1024, 1));
1934        assert_eq!(
1935            enter.partition_directive,
1936            StagingPartitionDirective::UpdatePartitionExpr(
1937                "{\"Expr\":{\"lhs\":{\"Column\":\"x\"},\"op\":\"GtEq\",\"rhs\":{\"Value\":{\"Int32\":0}}}}"
1938                    .to_string()
1939            )
1940        );
1941
1942        let serialized = serde_json::to_string(&enter).unwrap();
1943        assert!(serialized.contains("\"partition_directive\":\""));
1944        assert!(!serialized.contains("partition_expr"));
1945
1946        let reject = r#"{"region_id":4398046511105,"partition_expr":{"type":"reject_all_writes"}}"#;
1947        let enter: EnterStagingRegion = serde_json::from_str(reject).unwrap();
1948        assert_eq!(
1949            enter.partition_directive,
1950            StagingPartitionDirective::RejectAllWrites
1951        );
1952    }
1953
1954    #[derive(Debug, Clone, Serialize, Deserialize)]
1955    struct LegacyOpenRegion {
1956        region_ident: RegionIdent,
1957        region_storage_path: String,
1958        region_options: HashMap<String, String>,
1959    }
1960
1961    #[test]
1962    fn test_compatible_serialize_open_region() {
1963        let region_ident = RegionIdent {
1964            datanode_id: 2,
1965            table_id: 1024,
1966            region_number: 1,
1967            engine: "mito2".to_string(),
1968        };
1969        let region_storage_path = "test/foo".to_string();
1970        let region_options = HashMap::from([
1971            ("a".to_string(), "aa".to_string()),
1972            ("b".to_string(), "bb".to_string()),
1973        ]);
1974
1975        // Serialize a legacy OpenRegion.
1976        let legacy_open_region = LegacyOpenRegion {
1977            region_ident: region_ident.clone(),
1978            region_storage_path: region_storage_path.clone(),
1979            region_options: region_options.clone(),
1980        };
1981        let serialized = serde_json::to_string(&legacy_open_region).unwrap();
1982
1983        // Deserialize to OpenRegion.
1984        let deserialized = serde_json::from_str(&serialized).unwrap();
1985        let expected = OpenRegion {
1986            region_ident,
1987            region_storage_path,
1988            region_options,
1989            region_wal_options: HashMap::new(),
1990            skip_wal_replay: false,
1991            reason: None,
1992            requirements: RegionRequirements::empty(),
1993        };
1994        assert_eq!(expected, deserialized);
1995    }
1996
1997    #[test]
1998    fn test_deserialize_open_region_with_legacy_region_wal_options() {
1999        let open_region = r#"{"region_ident":{"datanode_id":2,"table_id":1024,"region_number":1,"engine":"mito2"},"region_storage_path":"test/foo","region_options":{},"region_wal_options":{"1":"{\"wal.provider\":\"raft_engine\"}"},"skip_wal_replay":false}"#;
2000
2001        let open_region: OpenRegion = serde_json::from_str(open_region).unwrap();
2002
2003        assert_eq!(
2004            open_region.region_wal_options,
2005            HashMap::from([(1, WalOptions::RaftEngine)])
2006        );
2007    }
2008
2009    #[test]
2010    fn test_serialize_open_region_with_reason_and_requirements() {
2011        let open_region = OpenRegion::new(
2012            RegionIdent {
2013                datanode_id: 2,
2014                table_id: 1024,
2015                region_number: 1,
2016                engine: "mito2".to_string(),
2017            },
2018            "test/foo",
2019            HashMap::new(),
2020            HashMap::new(),
2021            false,
2022            Some(OpenRegionReason::RegionMigration),
2023            RegionRequirements::object_storage(),
2024        );
2025
2026        let serialized = serde_json::to_string(&open_region).unwrap();
2027        assert!(serialized.contains(r#""reason":"RegionMigration""#));
2028        assert!(serialized.contains(r#""object_storage":true"#));
2029
2030        let deserialized: OpenRegion = serde_json::from_str(&serialized).unwrap();
2031        assert_eq!(Some(OpenRegionReason::RegionMigration), deserialized.reason);
2032        assert_eq!(
2033            RegionRequirements::object_storage(),
2034            deserialized.requirements
2035        );
2036    }
2037
2038    #[test]
2039    fn test_flush_regions_creation() {
2040        let region_id = RegionId::new(1024, 1);
2041
2042        // Single region sync flush
2043        let single_sync = FlushRegions::sync_single(region_id);
2044        assert_eq!(single_sync.region_ids, vec![region_id]);
2045        assert_eq!(single_sync.strategy, FlushStrategy::Sync);
2046        assert!(!single_sync.is_hint());
2047        assert!(single_sync.is_sync());
2048        assert_eq!(single_sync.error_strategy, FlushErrorStrategy::FailFast);
2049        assert_eq!(single_sync.reason, None);
2050        assert!(single_sync.is_single_region());
2051        assert_eq!(single_sync.single_region_id(), Some(region_id));
2052
2053        // Batch async flush (hint)
2054        let region_ids = vec![RegionId::new(1024, 1), RegionId::new(1024, 2)];
2055        let batch_async = FlushRegions::async_batch(region_ids.clone());
2056        assert_eq!(batch_async.region_ids, region_ids);
2057        assert_eq!(batch_async.strategy, FlushStrategy::Async);
2058        assert!(batch_async.is_hint());
2059        assert!(!batch_async.is_sync());
2060        assert_eq!(batch_async.error_strategy, FlushErrorStrategy::TryAll);
2061        assert_eq!(batch_async.reason, None);
2062        assert!(!batch_async.is_single_region());
2063        assert_eq!(batch_async.single_region_id(), None);
2064
2065        // Batch sync flush
2066        let batch_sync = FlushRegions::sync_batch(region_ids.clone(), FlushErrorStrategy::FailFast);
2067        assert_eq!(batch_sync.region_ids, region_ids);
2068        assert_eq!(batch_sync.strategy, FlushStrategy::Sync);
2069        assert!(!batch_sync.is_hint());
2070        assert!(batch_sync.is_sync());
2071        assert_eq!(batch_sync.error_strategy, FlushErrorStrategy::FailFast);
2072        assert_eq!(batch_sync.reason, None);
2073
2074        let with_reason = batch_sync.with_reason(RegionFlushReason::RemoteWalPrune);
2075        assert_eq!(with_reason.reason, Some(RegionFlushReason::RemoteWalPrune));
2076    }
2077
2078    #[test]
2079    fn test_flush_regions_conversion() {
2080        let region_id = RegionId::new(1024, 1);
2081
2082        let from_region_id: FlushRegions = region_id.into();
2083        assert_eq!(from_region_id.region_ids, vec![region_id]);
2084        assert_eq!(from_region_id.strategy, FlushStrategy::Sync);
2085        assert!(!from_region_id.is_hint());
2086        assert!(from_region_id.is_sync());
2087
2088        // Test default construction
2089        let flush_regions = FlushRegions {
2090            region_ids: vec![region_id],
2091            strategy: FlushStrategy::Async,
2092            error_strategy: FlushErrorStrategy::TryAll,
2093            reason: None,
2094        };
2095        assert_eq!(flush_regions.region_ids, vec![region_id]);
2096        assert_eq!(flush_regions.strategy, FlushStrategy::Async);
2097        assert!(flush_regions.is_hint());
2098        assert!(!flush_regions.is_sync());
2099    }
2100
2101    #[test]
2102    fn test_flush_region_reply() {
2103        let region_id = RegionId::new(1024, 1);
2104
2105        // Successful single region reply
2106        let success_reply = FlushRegionReply::success_single(region_id);
2107        assert!(success_reply.overall_success);
2108        assert_eq!(success_reply.results.len(), 1);
2109        assert_eq!(success_reply.results[0].0, region_id);
2110        assert!(success_reply.results[0].1.is_ok());
2111
2112        // Failed single region reply
2113        let error_reply = FlushRegionReply::error_single(
2114            region_id,
2115            InstructionError::legacy_internal_retryable("test error"),
2116        );
2117        assert!(!error_reply.overall_success);
2118        assert_eq!(error_reply.results.len(), 1);
2119        assert_eq!(error_reply.results[0].0, region_id);
2120        assert!(error_reply.results[0].1.is_err());
2121
2122        // Batch reply
2123        let region_id2 = RegionId::new(1024, 2);
2124        let results = vec![
2125            (region_id, Ok(())),
2126            (
2127                region_id2,
2128                Err(InstructionError::legacy_internal_retryable("flush failed")),
2129            ),
2130        ];
2131        let batch_reply = FlushRegionReply::from_results(results);
2132        assert!(!batch_reply.overall_success);
2133        assert_eq!(batch_reply.results.len(), 2);
2134
2135        // Conversion to SimpleReply
2136        let simple_reply = batch_reply.to_simple_reply();
2137        assert!(!simple_reply.result);
2138        assert!(simple_reply.error.is_some());
2139        assert!(simple_reply.error.unwrap().message.contains("flush failed"));
2140    }
2141
2142    #[test]
2143    fn test_serialize_flush_regions_instruction() {
2144        let region_id = RegionId::new(1024, 1);
2145        let flush_regions = FlushRegions::sync_single(region_id);
2146        let instruction = Instruction::FlushRegions(flush_regions.clone());
2147
2148        let serialized = serde_json::to_string(&instruction).unwrap();
2149        assert!(!serialized.contains("reason"));
2150        let deserialized: Instruction = serde_json::from_str(&serialized).unwrap();
2151
2152        match deserialized {
2153            Instruction::FlushRegions(fr) => {
2154                assert_eq!(fr.region_ids, vec![region_id]);
2155                assert_eq!(fr.strategy, FlushStrategy::Sync);
2156                assert_eq!(fr.error_strategy, FlushErrorStrategy::FailFast);
2157                assert_eq!(fr.reason, None);
2158            }
2159            _ => panic!("Expected FlushRegions instruction"),
2160        }
2161
2162        let legacy = r#"{"FlushRegions":{"region_ids":[4398046511105],"strategy":"Sync","error_strategy":"FailFast"}}"#;
2163        let deserialized: Instruction = serde_json::from_str(legacy).unwrap();
2164        match deserialized {
2165            Instruction::FlushRegions(fr) => {
2166                assert_eq!(fr.region_ids, vec![region_id]);
2167                assert_eq!(fr.strategy, FlushStrategy::Sync);
2168                assert_eq!(fr.error_strategy, FlushErrorStrategy::FailFast);
2169                assert_eq!(fr.reason, None);
2170            }
2171            _ => panic!("Expected FlushRegions instruction"),
2172        }
2173
2174        let flush_regions = FlushRegions::async_batch(vec![region_id])
2175            .with_reason(RegionFlushReason::RemoteWalPrune);
2176        let instruction = Instruction::FlushRegions(flush_regions);
2177        let serialized = serde_json::to_string(&instruction).unwrap();
2178        assert!(serialized.contains(r#""reason":"RemoteWalPrune""#));
2179        let deserialized: Instruction = serde_json::from_str(&serialized).unwrap();
2180        match deserialized {
2181            Instruction::FlushRegions(fr) => {
2182                assert_eq!(fr.reason, Some(RegionFlushReason::RemoteWalPrune));
2183            }
2184            _ => panic!("Expected FlushRegions instruction"),
2185        }
2186    }
2187
2188    #[test]
2189    fn test_serialize_flush_regions_batch_instruction() {
2190        let region_ids = vec![RegionId::new(1024, 1), RegionId::new(1024, 2)];
2191        let flush_regions =
2192            FlushRegions::sync_batch(region_ids.clone(), FlushErrorStrategy::TryAll);
2193        let instruction = Instruction::FlushRegions(flush_regions);
2194
2195        let serialized = serde_json::to_string(&instruction).unwrap();
2196        let deserialized: Instruction = serde_json::from_str(&serialized).unwrap();
2197
2198        match deserialized {
2199            Instruction::FlushRegions(fr) => {
2200                assert_eq!(fr.region_ids, region_ids);
2201                assert_eq!(fr.strategy, FlushStrategy::Sync);
2202                assert!(!fr.is_hint());
2203                assert!(fr.is_sync());
2204                assert_eq!(fr.error_strategy, FlushErrorStrategy::TryAll);
2205                assert_eq!(fr.reason, None);
2206            }
2207            _ => panic!("Expected FlushRegions instruction"),
2208        }
2209    }
2210
2211    #[test]
2212    fn test_legacy_gc_file_refs_compatibility() {
2213        #[derive(Debug, Deserialize)]
2214        struct LegacyGetFileRefs {
2215            query_regions: Vec<RegionId>,
2216            related_regions: HashMap<RegionId, HashSet<RegionId>>,
2217        }
2218
2219        #[derive(Debug, Deserialize)]
2220        struct LegacyGetFileRefsReply {
2221            file_refs_manifest: FileRefsManifest,
2222            success: bool,
2223            error: Option<InstructionError>,
2224        }
2225
2226        #[derive(Debug, Deserialize)]
2227        enum LegacyInstruction {
2228            GetFileRefs(LegacyGetFileRefs),
2229        }
2230
2231        let get_file_refs = Instruction::GetFileRefs(GetFileRefs {
2232            query_regions: vec![RegionId::new(7, 3)],
2233            related_regions: HashMap::new(),
2234        });
2235        let get_file_refs_json = serde_json::to_string(&get_file_refs).unwrap();
2236        let legacy_get_file_refs: LegacyInstruction =
2237            serde_json::from_str(&get_file_refs_json).unwrap();
2238        let LegacyInstruction::GetFileRefs(legacy_get_file_refs) = legacy_get_file_refs;
2239        assert_eq!(legacy_get_file_refs.query_regions.len(), 1);
2240        assert!(legacy_get_file_refs.related_regions.is_empty());
2241
2242        let reply = GetFileRefsReply {
2243            file_refs_manifest: FileRefsManifest::default(),
2244            success: true,
2245            error: None,
2246        };
2247        let reply_json = serde_json::to_string(&reply).unwrap();
2248        let legacy_reply: LegacyGetFileRefsReply = serde_json::from_str(&reply_json).unwrap();
2249        let current_reply: GetFileRefsReply = serde_json::from_str(&reply_json).unwrap();
2250        assert!(legacy_reply.success);
2251        assert!(legacy_reply.error.is_none());
2252        assert!(legacy_reply.file_refs_manifest.file_refs.is_empty());
2253        assert_eq!(current_reply, reply);
2254
2255        let packed = Instruction::PackedGcRegions(PackedGcRegions {
2256            regions: vec![],
2257            packed_file_refs_manifest: PackedFileRefsManifest::default(),
2258            full_file_listing: false,
2259        });
2260        let packed_json = serde_json::to_string(&packed).unwrap();
2261        assert!(serde_json::from_str::<LegacyInstruction>(&packed_json).is_err());
2262    }
2263
2264    #[test]
2265    fn test_packed_gc_regions_round_trip_is_distinct() {
2266        let instruction = Instruction::PackedGcRegions(PackedGcRegions {
2267            regions: vec![RegionId::new(7, 3)],
2268            packed_file_refs_manifest: PackedFileRefsManifest::default(),
2269            full_file_listing: true,
2270        });
2271        let serialized = serde_json::to_string(&instruction).unwrap();
2272        assert!(serialized.contains("PackedGcRegions"));
2273        assert_eq!(
2274            serde_json::from_str::<Instruction>(&serialized).unwrap(),
2275            instruction
2276        );
2277    }
2278
2279    #[test]
2280    fn test_packed_file_refs_manifest_round_trip_and_validation() {
2281        let region = RegionId::new(7, 3);
2282        let file_id = FileId::parse_str("00000000-0000-0000-0000-000000000001").unwrap();
2283        let mut manifest = FileRefsManifest::default();
2284        manifest.file_refs.insert(
2285            region,
2286            HashSet::from([
2287                FileRef::new(region, file_id, None),
2288                FileRef::new(region, file_id, Some(0)),
2289                FileRef::new(region, file_id, Some(u64::MAX)),
2290            ]),
2291        );
2292        manifest.manifest_version.insert(region, 42);
2293        manifest
2294            .cross_region_refs
2295            .insert(region, HashSet::from([RegionId::new(7, 4)]));
2296        let packed = PackedFileRefsManifest::from_manifest(&manifest);
2297        assert_eq!(packed.clone().into_manifest().unwrap(), manifest);
2298        let mut missing_files = serde_json::to_value(&packed).unwrap();
2299        missing_files
2300            .get_mut("file_refs")
2301            .and_then(serde_json::Value::as_object_mut)
2302            .and_then(|file_refs| file_refs.values_mut().next())
2303            .and_then(serde_json::Value::as_object_mut)
2304            .unwrap()
2305            .remove("files");
2306        assert!(serde_json::from_value::<PackedFileRefsManifest>(missing_files).is_err());
2307
2308        let mut missing_indexed = serde_json::to_value(&packed).unwrap();
2309        missing_indexed
2310            .get_mut("file_refs")
2311            .and_then(serde_json::Value::as_object_mut)
2312            .and_then(|file_refs| file_refs.values_mut().next())
2313            .and_then(serde_json::Value::as_object_mut)
2314            .unwrap()
2315            .remove("indexed");
2316        assert!(serde_json::from_value::<PackedFileRefsManifest>(missing_indexed).is_err());
2317
2318        let mut malformed = packed.clone();
2319        malformed.file_refs.get_mut(&region).unwrap().indexed = "!".to_string();
2320        let err = malformed.into_manifest().unwrap_err();
2321        assert!(matches!(
2322            &err,
2323            crate::error::Error::DecodePackedFileRefs { .. }
2324        ));
2325        assert!(
2326            err.source()
2327                .is_some_and(|source| source.is::<base64::DecodeError>())
2328        );
2329        assert_eq!(err.status_code(), StatusCode::Unexpected);
2330        assert_eq!(err.retry_hint(), RetryHint::NonRetryable);
2331
2332        let mut malformed = packed;
2333        malformed.file_refs.get_mut(&region).unwrap().indexed =
2334            base64::engine::general_purpose::STANDARD.encode([0; 1]);
2335        let err = malformed.into_manifest().unwrap_err();
2336        assert!(matches!(
2337            &err,
2338            crate::error::Error::InvalidPackedFileRefs { .. }
2339        ));
2340        assert!(err.source().is_none());
2341        assert_eq!(err.status_code(), StatusCode::Unexpected);
2342        assert_eq!(err.retry_hint(), RetryHint::NonRetryable);
2343    }
2344
2345    #[test]
2346    fn test_packed_file_refs_is_smaller_than_legacy() {
2347        let region = RegionId::new(7, 3);
2348        let mut manifest = FileRefsManifest::default();
2349        manifest.file_refs.insert(
2350            region,
2351            (0..500)
2352                .map(|i| {
2353                    let id =
2354                        FileId::parse_str(&format!("00000000-0000-0000-0000-{i:012}")).unwrap();
2355                    FileRef::new(region, id, None)
2356                })
2357                .collect(),
2358        );
2359        let legacy = serde_json::to_vec(&manifest).unwrap().len();
2360        let packed = serde_json::to_vec(&PackedFileRefsManifest::from_manifest(&manifest))
2361            .unwrap()
2362            .len();
2363        assert!(packed * 2 < legacy, "packed={packed}, legacy={legacy}");
2364    }
2365
2366    #[test]
2367    fn test_serialize_get_file_refs_instruction_reply() {
2368        let mut manifest = FileRefsManifest::default();
2369        let r0 = RegionId::new(1024, 1);
2370        let r1 = RegionId::new(1024, 2);
2371        manifest.file_refs.insert(
2372            r0,
2373            HashSet::from([FileRef::new(r0, FileId::random(), None)]),
2374        );
2375        manifest.file_refs.insert(
2376            r1,
2377            HashSet::from([FileRef::new(r1, FileId::random(), None)]),
2378        );
2379        manifest.manifest_version.insert(r0, 10);
2380        manifest.manifest_version.insert(r1, 20);
2381
2382        let instruction_reply = InstructionReply::GetFileRefs(GetFileRefsReply {
2383            file_refs_manifest: manifest,
2384            success: true,
2385            error: None,
2386        });
2387
2388        let serialized = serde_json::to_string(&instruction_reply).unwrap();
2389        let deserialized = serde_json::from_str(&serialized).unwrap();
2390
2391        assert_eq!(instruction_reply, deserialized);
2392    }
2393}