repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/progress_model/src/progress_limit.rs
crate/progress_model/src/progress_limit.rs
use serde::{Deserialize, Serialize}; /// Unit of measurement and total number of units. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize, Serialize)] pub enum ProgressLimit { /// There is no meaningful way to measure progress. #[default] Unknown, /// Progress is complete when `n` steps have been completed. Steps(u64), /// Progress is complete when `n` bytes are processed. /// /// Useful for upload / download progress. Bytes(u64), }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/progress_model/src/lib.rs
crate/progress_model/src/lib.rs
//! Command progress data model for the peace automation framework. //! //! # Design Notes //! //! Only used when the `"output_progress"` feature is enabled in Peace. pub use crate::{ cmd_block_item_interaction_type::CmdBlockItemInteractionType, cmd_progress_update::CmdProgressUpdate, item_location_state::ItemLocationState, progress_complete::ProgressComplete, progress_delta::ProgressDelta, progress_limit::ProgressLimit, progress_msg_update::ProgressMsgUpdate, progress_sender::ProgressSender, progress_status::ProgressStatus, progress_tracker::ProgressTracker, progress_update::ProgressUpdate, progress_update_and_id::ProgressUpdateAndId, }; mod cmd_block_item_interaction_type; mod cmd_progress_update; mod item_location_state; mod progress_complete; mod progress_delta; mod progress_limit; mod progress_msg_update; mod progress_sender; mod progress_status; mod progress_tracker; mod progress_update; mod progress_update_and_id;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/progress_model/src/cmd_progress_update.rs
crate/progress_model/src/cmd_progress_update.rs
use serde::{Deserialize, Serialize}; use peace_item_model::ItemId; use crate::{CmdBlockItemInteractionType, ItemLocationState, ProgressUpdateAndId}; /// Progress update that affects all `ProgressTracker`s. /// /// This is sent at the `CmdExecution` level. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub enum CmdProgressUpdate { /// A `CmdBlock` has started. CmdBlockStart { /// The type of interactions the `CmdBlock` has with the /// `ItemLocation`s. cmd_block_item_interaction_type: CmdBlockItemInteractionType, }, /// `ProgressUpdateAndId` for a single item. /// /// # Design Note /// /// This isn't a tuple newtype as `serde_yaml` `0.9` is unable to serialize /// newtype enum variants. ItemProgress { /// The update. progress_update_and_id: ProgressUpdateAndId, }, /// `ItemLocationState` for a single item. /// /// # Design Note /// /// `ItemLocationState` should live in `peace_item_interaction_model`, but /// this creates a circular dependency. ItemLocationState { /// ID of the `Item`. item_id: ItemId, /// The representation of the state of an `ItemLocation`. item_location_state: ItemLocationState, }, /// `CmdExecution` has been interrupted, we should indicate this on all /// unstarted progress bars. Interrupt, /// We are in between `CmdBlock`s, set all progress bars to `ExecPending`. ResetToPending, } impl From<ProgressUpdateAndId> for CmdProgressUpdate { fn from(progress_update_and_id: ProgressUpdateAndId) -> Self { Self::ItemProgress { progress_update_and_id, } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/progress_model/src/cmd_block_item_interaction_type.rs
crate/progress_model/src/cmd_block_item_interaction_type.rs
use serde::{Deserialize, Serialize}; /// Type of interactions that a `CmdBlock`s has with `ItemLocation`s. /// /// # Design /// /// Together with `ProgressStatus` and `ItemLocationState`, this is used to /// compute how an `ItemLocation` should be rendered to a user. #[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)] pub enum CmdBlockItemInteractionType { /// Creates / modifies / deletes the item. /// /// Makes write calls to `ItemLocation`s. Write, /// Makes read-only calls to `ItemLocation`s. Read, /// Local logic that does not interact with `ItemLocation`s / external /// services. Local, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/progress_model/src/progress_status.rs
crate/progress_model/src/progress_status.rs
use serde::{Deserialize, Serialize}; use crate::ProgressComplete; /// Status of an item's execution progress. /// /// # Implementation Notes /// /// ## Variants /// /// The following variant is possible conceptually, but not applicable to the /// Peace framework: /// /// `Stopped`: Task is not running, but can be started. /// /// This is not applicable because Peace uses runtime borrowing to manage state, /// and a stopped task has potentially altered data non-atomically, so locking /// the data is not useful, and unlocking the data may cause undefined behaviour /// due to reasoning over inconsistent state. /// /// For rate limiting tasks, the task in its entirety would be held back. /// /// ## `!Copy` /// /// This type isn't `Copy`, because one way wish to include detail about the /// function to render as part of the progress output, and that detail may not /// be `Copy` -- not sure yet. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub enum ProgressStatus { /// This item is registered for execution. /// /// This status is used when we don't know the progress limit. Initialized, /// The item was waiting for execution, when the command was interrupted. Interrupted, /// Execution has not yet begun. /// /// This is waiting on either: /// /// * The framework to begin executing the logic. /// * A predecessor's execution completion. ExecPending, /// Execution has started for this item, but we haven't received /// `ProgressDelta` update from the item exec logic. Queued, /// Execution is in progress. /// /// This status is best conveyed alongside additional information: /// /// * **Units total:** Unknown (spinner) / known (progress bar). /// * **Units current** /// * **Function:** `Item::{state_current, state_goal, apply}`. /// /// Certain functions will not be applicable, e.g. when `StateCurrent` /// is feature gated, then the function won't be available when the /// feature is not enabled. Running, /// Progress updates have not been received for a given period. /// /// Item implementations are responsible for sending progress updates, /// but if there are no progress updates, or an identical "it's running" /// progress update is continuously received, then Peace may determine that /// the task may have stalled, and user attention is required. /// /// Peace may also provide a hook for implementors to output a suggestion to /// the user. RunningStalled, /// Task is pending user input. UserPending, /// Task has completed. /// /// This status is best conveyed alongside additional information: /// /// * **Completion Status**: Success, Failed. /// * **Function:** `Item::{state_current, state_goal, apply}`. Complete(ProgressComplete), }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/progress_model/src/progress_msg_update.rs
crate/progress_model/src/progress_msg_update.rs
use serde::{Deserialize, Serialize}; /// Whether to change the progress message. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub enum ProgressMsgUpdate { /// Clears the progress message. Clear, /// Does not change the progress message. NoChange, /// Sets the progress message. Set(String), }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/progress_model/src/progress_update.rs
crate/progress_model/src/progress_update.rs
use serde::{Deserialize, Serialize}; use crate::{ProgressDelta, ProgressLimit}; use super::ProgressComplete; /// Progress update for a single progress tracker. /// /// # Potential Future Variants /// /// * `PendingInput` /// * `Stall` /// /// # Implementation Note /// /// `serde-yaml` 0.9 does not support serializing / deserializing nested enums, /// and returns errors like the following: /// /// ```text /// "deserializing nested enum in ProgressUpdate::Delta from YAML is not supported yet" /// "serializing nested enums in YAML is not supported yet" /// ``` /// /// The [`serde_yaml::with::singleton_map`] attributes are necessary for /// `serde_yaml` to serialize nested enums. /// /// [`serde_yaml::with::singleton_map`]: https://docs.rs/serde_yaml/latest/serde_yaml/with/singleton_map/index.html #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub enum ProgressUpdate { /// Resets the progress tracker to the `Initialized` state. Reset, /// Resets the progress tracker to the `ExecPending` state. /// /// This is similar to `Reset`, but the progress bar is not styled as /// disabled. ResetToPending, /// Sets the progress tracker as `Queued`, meaning it musn't be interrupted /// as it is essentially `Running` Queued, /// `CmdExecution` has been interrupted, we should indicate this on the /// progress bar. Interrupt, /// Progress limit has been discovered. #[serde(with = "serde_yaml::with::singleton_map")] Limit(ProgressLimit), /// Progress units have changed. #[serde(with = "serde_yaml::with::singleton_map")] Delta(ProgressDelta), /// Execution has completed. #[serde(with = "serde_yaml::with::singleton_map")] Complete(ProgressComplete), }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/progress_model/src/progress_tracker.rs
crate/progress_model/src/progress_tracker.rs
use std::time::Duration; use chrono::{DateTime, Utc}; use indicatif::ProgressBar; use crate::{ProgressLimit, ProgressStatus}; /// Tracks progress for an item's `ApplyFns::exec` method. #[derive(Debug)] pub struct ProgressTracker { /// Status of the item's execution progress. progress_status: ProgressStatus, /// Internal progress bar to update. progress_bar: ProgressBar, /// Progress limit for the execution, if known. progress_limit: Option<ProgressLimit>, /// Message to display. message: Option<String>, /// Timestamp of last progress update. /// /// This is useful to determine if execution has stalled. last_update_dt: DateTime<Utc>, } impl ProgressTracker { /// Returns a new `ProgressTracker`. pub fn new(progress_bar: ProgressBar) -> Self { let last_update_dt = Utc::now(); Self { progress_status: ProgressStatus::Initialized, progress_bar, progress_limit: None, message: None, last_update_dt, } } /// Resets the progress tracker to `Initialized`. // TODO: write test for this pub fn reset(&mut self) { self.progress_status = ProgressStatus::Initialized; self.message = None; self.progress_limit = None; self.progress_bar.set_length(0); self.progress_bar.set_position(0); self.progress_bar.reset(); self.last_update_dt = Utc::now(); } /// Resets the progress tracker to `ExecPending`. // TODO: write test for this pub fn reset_to_pending(&mut self) { self.progress_status = ProgressStatus::ExecPending; self.message = None; self.progress_limit = None; self.progress_bar.set_length(0); self.progress_bar.set_position(0); self.progress_bar.reset(); self.last_update_dt = Utc::now(); } /// Resets the progress tracker to `ExecPending`. // TODO: write test for this pub fn interrupt(&mut self) { match self.progress_status { ProgressStatus::Initialized | ProgressStatus::ExecPending | ProgressStatus::UserPending => { self.progress_status = ProgressStatus::Interrupted; self.message = Some(String::from("interrupted")); self.progress_limit = None; self.last_update_dt = Utc::now(); } ProgressStatus::Interrupted | ProgressStatus::Queued | ProgressStatus::Running | ProgressStatus::RunningStalled | ProgressStatus::Complete(_) => {} } } /// Increments the progress by the given unit count. pub fn inc(&mut self, unit_count: u64) { self.progress_bar.inc(unit_count); self.last_update_dt_update(); } /// Ticks the tracker without incrementing its progress. /// /// This is useful for spinners -- progress trackers where there is an /// unknown. /// /// Note, this also updates the `last_update_dt`, so in the case of a /// spinner, this should only be called when there is actually a detected /// change. pub fn tick(&mut self) { self.progress_bar.tick(); self.last_update_dt_update(); } /// Returns a reference to the progress status. pub fn progress_status(&self) -> &ProgressStatus { &self.progress_status } /// Sets the progress status. pub fn set_progress_status(&mut self, progress_status: ProgressStatus) { self.progress_status = progress_status; self.last_update_dt_update(); } /// Returns a reference to the progress bar. pub fn progress_bar(&self) -> &ProgressBar { &self.progress_bar } /// Returns the estimated remaining duration to completion. pub fn eta(&self) -> Duration { self.progress_bar.eta() } /// Returns the elapsed duration. pub fn elapsed(&self) -> Duration { self.progress_bar.elapsed() } /// Returns the number of progress units already completed. pub fn units_current(&self) -> u64 { self.progress_bar.position() } /// Returns the total number of progress units. pub fn units_total(&self) -> Option<u64> { self.progress_limit .and_then(|progress_limit| match progress_limit { ProgressLimit::Unknown => None, ProgressLimit::Steps(units_total) | ProgressLimit::Bytes(units_total) => { Some(units_total) } }) } /// Returns the progress limit for the execution, if known. pub fn progress_limit(&self) -> Option<ProgressLimit> { self.progress_limit } /// Sets the progress limit of the execution. pub fn set_progress_limit(&mut self, progress_limit: ProgressLimit) { // Update units total on `ProgressBar`. match progress_limit { ProgressLimit::Unknown => { // Do nothing -- this keeps the `indicatif` internal `State` to // be `None`. } ProgressLimit::Steps(units_total) | ProgressLimit::Bytes(units_total) => { self.progress_bar.set_length(units_total); } } self.progress_limit = Some(progress_limit); self.last_update_dt_update(); } /// Returns the message for this progress tracker. pub fn message(&self) -> Option<&String> { self.message.as_ref() } /// Sets the message for this progress tracker. pub fn set_message(&mut self, message: Option<String>) { self.message = message; } /// Returns the timestamp a progress update was last made. pub fn last_update_dt(&self) -> DateTime<Utc> { self.last_update_dt } /// Returns the timestamp a progress update was last made. #[inline] fn last_update_dt_update(&mut self) { self.last_update_dt = Utc::now(); } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/progress_model/src/item_location_state.rs
crate/progress_model/src/item_location_state.rs
use serde::{Deserialize, Serialize}; /// A low-resolution representation of the state of an [`ItemLocation`]. /// /// Combined with [`ProgressStatus`], [`ItemLocationStateInProgress`] can be /// computed, to determine how an [`ItemLocation`] should be rendered. /// /// [`ItemLocation`]: crate::ItemLocation /// [`ItemLocationStateInProgress`]: crate::ItemLocationStateInProgress /// [`ProgressStatus`]: crate::ProgressStatus #[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)] pub enum ItemLocationState { /// [`ItemLocation`] does not exist. /// /// This means it should be rendered invisible / low opacity. NotExists, /// [`ItemLocation`] exists. /// /// This means it should be rendered with full opacity. /// /// [`ItemLocation`]: crate::ItemLocation Exists, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/progress_model/src/progress_sender.rs
crate/progress_model/src/progress_sender.rs
use peace_item_model::ItemId; use tokio::sync::mpsc::Sender; use crate::{ CmdProgressUpdate, ItemLocationState, ProgressDelta, ProgressMsgUpdate, ProgressUpdate, ProgressUpdateAndId, }; /// Submits progress for an item's `ApplyFns::exec` method. #[derive(Clone, Copy, Debug)] pub struct ProgressSender<'exec> { /// ID of the item this belongs to. item_id: &'exec ItemId, /// Channel sender to send progress updates to. progress_tx: &'exec Sender<CmdProgressUpdate>, } impl<'exec> ProgressSender<'exec> { /// Returns a new `ProgressSender`. pub fn new(item_id: &'exec ItemId, progress_tx: &'exec Sender<CmdProgressUpdate>) -> Self { Self { item_id, progress_tx, } } /// Increments the progress by the given unit count. pub fn inc(&self, unit_count: u64, msg_update: ProgressMsgUpdate) { let _progress_send_unused = self.progress_tx.try_send( ProgressUpdateAndId { item_id: self.item_id.clone(), progress_update: ProgressUpdate::Delta(ProgressDelta::Inc(unit_count)), msg_update, } .into(), ); } /// Ticks the tracker without incrementing its progress. /// /// This is useful for spinners -- progress trackers where there is an /// unknown. /// /// Note, this also updates the `last_update_dt`, so in the case of a /// spinner, this should only be called when there is actually a detected /// change. pub fn tick(&self, msg_update: ProgressMsgUpdate) { let _progress_send_unused = self.progress_tx.try_send( ProgressUpdateAndId { item_id: self.item_id.clone(), progress_update: ProgressUpdate::Delta(ProgressDelta::Tick), msg_update, } .into(), ); } /// Resets the progress tracker to a clean state. pub fn reset(&self) { let _progress_send_unused = self.progress_tx.try_send( ProgressUpdateAndId { item_id: self.item_id.clone(), progress_update: ProgressUpdate::Reset, msg_update: ProgressMsgUpdate::Clear, } .into(), ); } /// Resets the progress tracker to a clean state. pub fn reset_to_pending(&self) { let _progress_send_unused = self.progress_tx.try_send( ProgressUpdateAndId { item_id: self.item_id.clone(), progress_update: ProgressUpdate::ResetToPending, msg_update: ProgressMsgUpdate::Clear, } .into(), ); } /// Sends an `ItemLocationState` update. /// /// # Implementors /// /// This is only intended for use by the Peace framework for rendering. /// /// # Maintainers /// /// This is used in `ItemWrapper`. pub fn item_location_state_send(&self, item_location_state: ItemLocationState) { let _progress_send_unused = self.progress_tx .try_send(CmdProgressUpdate::ItemLocationState { item_id: self.item_id.clone(), item_location_state, }); } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/progress_model/src/progress_update_and_id.rs
crate/progress_model/src/progress_update_and_id.rs
use peace_item_model::ItemId; use serde::{Deserialize, Serialize}; use crate::{ProgressMsgUpdate, ProgressUpdate}; /// An item ID and its progress update. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct ProgressUpdateAndId { /// ID of the item whose progress is updated. pub item_id: ItemId, /// Delta update for the progress tracker. pub progress_update: ProgressUpdate, /// Whether to change the progress message. pub msg_update: ProgressMsgUpdate, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/progress_model/src/progress_delta.rs
crate/progress_model/src/progress_delta.rs
use serde::{Deserialize, Serialize}; /// The amount that the item progressed by. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub enum ProgressDelta { /// Ticks the progress bar without incrementing its value. /// /// Generally useful for progress bars with an unknown total. Tick, /// Increments the progress bar by the specified amount. Inc(u64), }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/progress_model/src/progress_complete.rs
crate/progress_model/src/progress_complete.rs
use serde::{Deserialize, Serialize}; /// Progress completion outcome. /// /// # Implementation Note /// /// Should we split `Fail` to be `Fail` and `Error`? /// /// The distinction will allow determining if: /// /// * The end user is using invalid values (need for education). /// * The environment is flakey (need for stabilization). /// /// Ideally [rust#84277] is implemented so `Item` implementations can use /// `?` when returning each variant. /// /// [rust#84277]: https://github.com/rust-lang/rust/issues/84277 #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub enum ProgressComplete { /// Execution completed successfully. Success, /// Execution did not complete. Fail, } impl ProgressComplete { /// Returns whether this is a successful outcome. pub fn is_successful(&self) -> bool { match self { Self::Success => true, Self::Fail => false, } } /// Returns whether this is a failure outcome. pub fn is_failure(&self) -> bool { match self { Self::Success => false, Self::Fail => true, } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/static_check_macros/src/lib.rs
crate/static_check_macros/src/lib.rs
use proc_macro2::Span; use quote::quote; use syn::{parse_macro_input, parse_quote, Ident, Path}; use self::lit_str_maybe::LitStrMaybe; mod lit_str_maybe; /// Returns a `const AppName` validated at compile time. /// /// This defaults to the crate name. /// /// # Examples /// /// Instantiate a valid `AppName` at compile time: /// /// ```rust /// # use peace_static_check_macros::app_name; /// // use peace::cfg::{app_name, AppName}; /// /// let _my_flow: AppName = app_name!("valid_id"); // Ok! /// /// # struct AppName(&'static str); /// # impl AppName { /// # fn new_unchecked(s: &'static str) -> Self { Self(s) } /// # } /// ``` /// /// If the ID is invalid, a compilation error is produced: /// /// ```rust,compile_fail /// # use peace_static_check_macros::app_name; /// // use peace::cfg::{app_name, AppName}; /// /// let _my_flow: AppName = app_name!("-invalid"); // Compile error /// // ^^^^^^^^^^^^^^^^^^^^^^^ /// // error: "-invalid" is not a valid `AppName`. /// // `AppName`s must begin with a letter or underscore, and contain only letters, numbers, or underscores. /// # /// # struct AppName(&'static str); /// # impl AppName { /// # fn new_unchecked(s: &'static str) -> Self { Self(s) } /// # } /// ``` #[proc_macro] pub fn app_name(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let crate_name = std::env::var("CARGO_PKG_NAME") .expect("Failed to read `CARGO_PKG_NAME` environmental variable to infer `AppName`."); ensure_valid_id( parse_quote!(peace::cfg), &parse_macro_input!(input as LitStrMaybe), "AppName", Some(crate_name.as_str()), ) .into() } /// Returns a `const ItemId` validated at compile time. /// /// # Examples /// /// Instantiate a valid `ItemId` at compile time: /// /// ```rust /// # use peace_static_check_macros::item_id; /// // use peace::item_model::{item_id, ItemId}; /// /// let _my_item_id: ItemId = item_id!("valid_id"); // Ok! /// /// # struct ItemId(&'static str); /// # impl ItemId { /// # fn new_unchecked(s: &'static str) -> Self { Self(s) } /// # } /// ``` /// /// If the ID is invalid, a compilation error is produced: /// /// ```rust,compile_fail /// # use peace_static_check_macros::item_id; /// // use peace::item_model::{item_id, ItemId}; /// /// let _my_item_id: ItemId = item_id!("-invalid_id"); // Compile error /// // ^^^^^^^^^^^^^^^^^^^^^^^^ /// // error: "-invalid_id" is not a valid `ItemId`. /// // `ItemId`s must begin with a letter or underscore, and contain only letters, numbers, or underscores. /// # /// # struct ItemId(&'static str); /// # impl ItemId { /// # fn new_unchecked(s: &'static str) -> Self { Self(s) } /// # } /// ``` #[proc_macro] pub fn item_id(input: proc_macro::TokenStream) -> proc_macro::TokenStream { ensure_valid_id( parse_quote!(peace::item_model), &parse_macro_input!(input as LitStrMaybe), "ItemId", None, ) .into() } /// Returns a `const Profile` validated at compile time. /// /// # Examples /// /// Instantiate a valid `Profile` at compile time: /// /// ```rust /// # use peace_static_check_macros::profile; /// // use peace::profile_model::{profile, Profile}; /// /// let _my_profile: Profile = profile!("valid_id"); // Ok! /// /// # struct Profile(&'static str); /// # impl Profile { /// # fn new_unchecked(s: &'static str) -> Self { Self(s) } /// # } /// ``` /// /// If the ID is invalid, a compilation error is produced: /// /// ```rust,compile_fail /// # use peace_static_check_macros::profile; /// // use peace::profile_model::{profile, Profile}; /// /// let _my_profile: Profile = profile!("-invalid_id"); // Compile error /// // ^^^^^^^^^^^^^^^^^^^^^^^ /// // error: "-invalid_id" is not a valid `Profile`. /// // `Profile`s must begin with a letter or underscore, and contain only letters, numbers, or underscores. /// # /// # struct Profile(&'static str); /// # impl Profile { /// # fn new_unchecked(s: &'static str) -> Self { Self(s) } /// # } /// ``` #[proc_macro] pub fn profile(input: proc_macro::TokenStream) -> proc_macro::TokenStream { ensure_valid_id( parse_quote!(peace::profile_model), &parse_macro_input!(input as LitStrMaybe), "Profile", None, ) .into() } /// Returns a `const FlowId` validated at compile time. /// /// # Examples /// /// Instantiate a valid `FlowId` at compile time: /// /// ```rust /// # use peace_static_check_macros::flow_id; /// // use peace::flow_model::{flow_id, FlowId}; /// /// let _my_flow: FlowId = flow_id!("valid_id"); // Ok! /// /// # struct FlowId(&'static str); /// # impl FlowId { /// # fn new_unchecked(s: &'static str) -> Self { Self(s) } /// # } /// ``` /// /// If the ID is invalid, a compilation error is produced: /// /// ```rust,compile_fail /// # use peace_static_check_macros::flow_id; /// // use peace::flow_model::{flow_id, FlowId}; /// /// let _my_flow: FlowId = flow_id!("-invalid_id"); // Compile error /// // ^^^^^^^^^^^^^^^^^^^^^^^ /// // error: "-invalid_id" is not a valid `FlowId`. /// // `FlowId`s must begin with a letter or underscore, and contain only letters, numbers, or underscores. /// # /// # struct FlowId(&'static str); /// # impl FlowId { /// # fn new_unchecked(s: &'static str) -> Self { Self(s) } /// # } /// ``` #[proc_macro] pub fn flow_id(input: proc_macro::TokenStream) -> proc_macro::TokenStream { ensure_valid_id( parse_quote!(peace::flow_model), &parse_macro_input!(input as LitStrMaybe), "FlowId", None, ) .into() } fn ensure_valid_id( crate_path: Path, proposed_id: &LitStrMaybe, ty_name: &str, default: Option<&str>, ) -> proc_macro2::TokenStream { let proposed_id = proposed_id.as_ref().map(|lit_str| lit_str.value()); let proposed_id = proposed_id.as_deref().or(default); if let Some(proposed_id) = proposed_id { if is_valid_id(proposed_id) { let ty_name = Ident::new(ty_name, Span::call_site()); quote!( #crate_path:: #ty_name ::new_unchecked( #proposed_id )) } else { let message = format!( "\"{proposed_id}\" is not a valid `{ty_name}`.\n\ `{ty_name}`s must begin with a letter or underscore, and contain only letters, numbers, or underscores." ); compile_fail(message) } } else { let message = format!( "`` is not a valid `{ty_name}`.\n\ `{ty_name}`s must begin with a letter or underscore, and contain only letters, numbers, or underscores." ); compile_fail(message) } } fn compile_fail(message: String) -> proc_macro2::TokenStream { quote!(compile_error!(#message)) } fn is_valid_id(proposed_id: &str) -> bool { let mut chars = proposed_id.chars(); let first_char = chars.next(); let first_char_valid = first_char .map(|c| c.is_ascii_alphabetic() || c == '_') .unwrap_or(false); let remainder_chars_valid = chars.all(|c| c.is_ascii_alphabetic() || c == '_' || c.is_ascii_digit()); first_char_valid && remainder_chars_valid } #[cfg(test)] mod tests { use proc_macro2::Span; use syn::{parse_quote, LitStr}; use crate::LitStrMaybe; use super::ensure_valid_id; #[test] fn name_beginning_with_underscore_is_valid() { let tokens = ensure_valid_id( parse_quote!(peace::cfg), &LitStrMaybe(Some(LitStr::new("_", Span::call_site()))), "Ty", None, ); assert_eq!( r#"peace :: cfg :: Ty :: new_unchecked ("_")"#, tokens.to_string() ); } #[test] fn name_beginning_with_alpha_is_valid() { let tokens = ensure_valid_id( parse_quote!(peace::cfg), &LitStrMaybe(Some(LitStr::new("a", Span::call_site()))), "Ty", None, ); assert_eq!( r#"peace :: cfg :: Ty :: new_unchecked ("a")"#, tokens.to_string() ); let tokens = ensure_valid_id( parse_quote!(peace::cfg), &LitStrMaybe(Some(LitStr::new("A", Span::call_site()))), "Ty", None, ); assert_eq!( r#"peace :: cfg :: Ty :: new_unchecked ("A")"#, tokens.to_string() ); } #[test] fn name_beginning_with_number_is_invalid() { let tokens = ensure_valid_id( parse_quote!(peace::cfg), &LitStrMaybe(Some(LitStr::new("1", Span::call_site()))), "Ty", None, ); assert_eq!( "compile_error ! (\"\\\"1\\\" is not a valid `Ty`.\\n\ `Ty`s must begin with a letter or underscore, and contain only letters, numbers, or underscores.\")", tokens.to_string() ); } #[test] fn name_containing_space_is_invalid() { let tokens = ensure_valid_id( parse_quote!(peace::cfg), &LitStrMaybe(Some(LitStr::new("a b", Span::call_site()))), "Ty", None, ); assert_eq!( "compile_error ! (\"\\\"a b\\\" is not a valid `Ty`.\\n\ `Ty`s must begin with a letter or underscore, and contain only letters, numbers, or underscores.\")", tokens.to_string() ); } #[test] fn name_containing_hyphen_is_invalid() { let tokens = ensure_valid_id( parse_quote!(peace::cfg), &LitStrMaybe(Some(LitStr::new("a-b", Span::call_site()))), "Ty", None, ); assert_eq!( "compile_error ! (\"\\\"a-b\\\" is not a valid `Ty`.\\n\ `Ty`s must begin with a letter or underscore, and contain only letters, numbers, or underscores.\")", tokens.to_string() ); } #[test] fn name_empty_string_is_invalid() { let tokens = ensure_valid_id( parse_quote!(peace::cfg), &LitStrMaybe(Some(LitStr::new("", Span::call_site()))), "Ty", None, ); assert_eq!( "compile_error ! (\"\\\"\\\" is not a valid `Ty`.\\n\ `Ty`s must begin with a letter or underscore, and contain only letters, numbers, or underscores.\")", tokens.to_string() ); } #[test] fn name_none_is_invalid() { let tokens = ensure_valid_id(parse_quote!(peace::cfg), &LitStrMaybe(None), "Ty", None); assert_eq!( "compile_error ! (\"`` is not a valid `Ty`.\\n\ `Ty`s must begin with a letter or underscore, and contain only letters, numbers, or underscores.\")", tokens.to_string() ); } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/static_check_macros/src/lit_str_maybe.rs
crate/static_check_macros/src/lit_str_maybe.rs
use syn::{ parse::{Parse, ParseStream}, LitStr, }; pub(crate) struct LitStrMaybe(pub Option<LitStr>); impl std::ops::Deref for LitStrMaybe { type Target = Option<LitStr>; fn deref(&self) -> &Self::Target { &self.0 } } impl Parse for LitStrMaybe { fn parse(input: ParseStream) -> syn::parse::Result<Self> { let value = if input.is_empty() { None } else { Some(input.parse::<LitStr>()?) }; Ok(LitStrMaybe(value)) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model_web/src/workspace.rs
crate/rt_model_web/src/workspace.rs
//! Types that store information about the directories that a command runs in. //! //! In the Peace framework, a command is run with the following contextual //! information: //! //! * The [`Workspace`] of a project that the command is built for. //! * A [`Profile`] (or namespace) for that project. //! * A workflow that the command is executing, identified by the [`FlowId`]. use peace_core::AppName; use peace_resource_rt::internal::WorkspaceDirs; use peace_rt_model_core::Error; use crate::{Storage, WorkspaceDirsBuilder, WorkspaceSpec}; /// Workspace that the `peace` tool runs in. #[derive(Clone, Debug)] pub struct Workspace { /// Name of the application that is run by end users. app_name: AppName, /// `Resources` in this workspace. dirs: WorkspaceDirs, /// Wrapper to retrieve `web_sys::Storage` on demand. storage: Storage, } impl Workspace { /// Prepares a workspace to run commands in. /// /// # Parameters /// /// * `app_name`: Name of the final application. /// * `workspace_spec`: Defines how to discover the workspace. /// * `profile`: The profile / namespace that the execution is flow. /// * `flow_id`: ID of the flow that is being executed. pub fn new(app_name: AppName, workspace_spec: WorkspaceSpec) -> Result<Self, Error> { let dirs = WorkspaceDirsBuilder::build(&app_name, workspace_spec)?; let storage = Storage::new(workspace_spec); Ok(Self { app_name, dirs, storage, }) } /// Returns the underlying data. pub fn into_inner(self) -> (AppName, WorkspaceDirs, Storage) { let Self { app_name, dirs, storage, } = self; (app_name, dirs, storage) } /// Returns a reference to the app name. pub fn app_name(&self) -> &AppName { &self.app_name } /// Returns a reference to the workspace's directories. pub fn dirs(&self) -> &WorkspaceDirs { &self.dirs } /// Returns a reference to the workspace's storage. pub fn storage(&self) -> &Storage { &self.storage } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model_web/src/lib.rs
crate/rt_model_web/src/lib.rs
// This crate is only developed for WASM targets. #![cfg(target_arch = "wasm32")] //! Web support for the peace automation framework. //! //! Consumers should depend on the `peace_rt_model` crate, which re-exports //! same-named types, depending on whether a native or WASM target is used. //! //! **This crate is intended to be used with `#[cfg(target_arch = "wasm32")]`.** pub use crate::{ storage::Storage, workspace::Workspace, workspace_dirs_builder::WorkspaceDirsBuilder, workspace_initializer::WorkspaceInitializer, workspace_spec::WorkspaceSpec, }; pub mod workspace; mod storage; mod workspace_dirs_builder; mod workspace_initializer; mod workspace_spec; /// Converts the `JsValue` to a `String` to allow `Error` to be `Send`. pub fn stringify_js_value(js_value: wasm_bindgen::JsValue) -> String { serde_wasm_bindgen::from_value::<String>(js_value).unwrap_or_else(|_| String::from("<??>")) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model_web/src/storage.rs
crate/rt_model_web/src/storage.rs
use std::{ fmt::Debug, hash::Hash, path::{Path, PathBuf}, }; use base64::Engine; use peace_resource_rt::type_reg::{ common::UnknownEntriesSome, untagged::{DataTypeWrapper, TypeMapOpt, TypeReg}, }; use peace_rt_model_core::{Error, WebError}; use serde::{de::DeserializeOwned, Serialize}; use wasm_bindgen::prelude::*; use crate::WorkspaceSpec; /// Wrapper to retrieve `web_sys::Storage` on demand. #[derive(Clone, Debug)] pub struct Storage { /// Describes how to store peace automation data. workspace_spec: WorkspaceSpec, } #[wasm_bindgen(module = "/js/workspace.js")] extern "C" { /// Returns whether local storage is available. fn localStorageAvailable() -> bool; /// Returns whether session storage is available. fn sessionStorageAvailable() -> bool; } impl Storage { /// Returns a new `Storage`. pub fn new(workspace_spec: WorkspaceSpec) -> Self { Self { workspace_spec } } /// Returns the browser storage used for the workspace. /// /// This is the local or session storage depending on the `WorkspaceSpec` /// passed into `Workspace::new`. /// /// `web_sys::Storage` is `!Send`, so cannot be inserted into `Resources`. /// As a compromise, we provide this function to fetch the storage when it /// needs to be accessed. pub fn get(&self) -> Result<web_sys::Storage, Error> { let window = web_sys::window().ok_or(WebError::WindowNone)?; let storage = match self.workspace_spec { WorkspaceSpec::LocalStorage => { if !localStorageAvailable() { return Err(Error::Web(WebError::LocalStorageUnavailable)); } window .local_storage() .map_err(crate::stringify_js_value) .map_err(WebError::LocalStorageGet) .map_err(Error::Web)? .ok_or(Error::Web(WebError::LocalStorageNone))? } WorkspaceSpec::SessionStorage => { if !sessionStorageAvailable() { return Err(Error::Web(WebError::SessionStorageUnavailable)); } window .session_storage() .map_err(crate::stringify_js_value) .map_err(WebError::SessionStorageGet) .map_err(Error::Web)? .ok_or(Error::Web(WebError::SessionStorageNone))? } }; Ok(storage) } /// Returns whether an item exists in the web storage. pub fn contains_item(&self, path: &Path) -> Result<bool, Error> { self.get_item_opt(path).map(|item| item.is_some()) } /// Gets an optional item in the web storage. /// /// * Use [`get_item_opt`] if you would like to fetch an item that may not /// exist. /// * Use [`get_items_opt`] if you would like to fetch multiple optional /// items. /// * Use [`get_item`] if you would like to fetch an item that must exist. /// * Use [`get_items`] if you would like to fetch multiple items that must /// exist. /// /// [`get_items_opt`]: Self::get_items pub fn get_item_opt(&self, path: &Path) -> Result<Option<String>, Error> { let storage = self.get()?; let key = path.to_string_lossy(); storage.get_item(key.as_ref()).map_err(|js_value| { Error::Web(WebError::StorageGetItem { path: path.to_path_buf(), error: crate::stringify_js_value(js_value), }) }) } /// Gets multiple items in the web storage. /// /// * Use [`get_item_opt`] if you would like to fetch an item that may not /// exist. /// * Use [`get_items_opt`] if you would like to fetch multiple optional /// items. /// * Use [`get_item`] if you would like to fetch an item that must exist. /// * Use [`get_items`] if you would like to fetch multiple items that must /// exist. /// /// [`get_item`]: Self::get_item pub fn get_items_opt<'f, I>( &self, iter: I, ) -> Result<impl Iterator<Item = Result<(&'f Path, Option<String>), Error>>, Error> where I: Iterator<Item = &'f Path>, { let storage = self.get()?; let iter = iter.map(move |path| { let key = path.to_string_lossy(); storage .get_item(key.as_ref()) .map(|value| (path, value)) .map_err(|js_value| { Error::Web(WebError::StorageGetItem { path: path.to_path_buf(), error: crate::stringify_js_value(js_value), }) }) }); Ok(iter) } /// Gets an item in the web storage. /// /// * Use [`get_item_opt`] if you would like to fetch an item that may not /// exist. /// * Use [`get_items_opt`] if you would like to fetch multiple optional /// items. /// * Use [`get_item`] if you would like to fetch an item that must exist. /// * Use [`get_items`] if you would like to fetch multiple items that must /// exist. /// /// [`get_items`]: Self::get_items pub fn get_item(&self, path: &Path) -> Result<String, Error> { let storage = self.get()?; let key = path.to_string_lossy(); storage .get_item(key.as_ref()) .map_err(|js_value| { Error::Web(WebError::StorageGetItem { path: path.to_path_buf(), error: crate::stringify_js_value(js_value), }) }) .and_then(|value| { value.ok_or_else(|| Error::ItemNotExists { path: path.to_path_buf(), }) }) } /// Gets a base64 encoded item in the web storage. /// /// * Use [`get_item_b64_opt`] if you would like to fetch an item that may /// not exist. /// /// [`get_items`]: Self::get_items pub fn get_item_b64_opt(&self, path: &Path) -> Result<Option<Vec<u8>>, Error> { self.get_item_opt(path).and_then(|value| { value .map(|value| { base64::engine::general_purpose::STANDARD .decode(&value) .map_err(|error| { Error::Web(WebError::StorageB64Decode { path: path.to_path_buf(), value, error, }) }) }) .transpose() }) } /// Gets a base64 encoded item in the web storage. /// /// * Use [`get_item_b64_opt`] if you would like to fetch an item that may /// not exist. /// /// [`get_items`]: Self::get_items pub fn get_item_b64(&self, path: &Path) -> Result<Vec<u8>, Error> { self.get_item(path).and_then(|value| { base64::engine::general_purpose::STANDARD .decode(&value) .map_err(|error| { Error::Web(WebError::StorageB64Decode { path: path.to_path_buf(), value, error, }) }) }) } /// Gets multiple items in the web storage. /// /// * Use [`get_item_opt`] if you would like to fetch an item that may not /// exist. /// * Use [`get_items_opt`] if you would like to fetch multiple optional /// items. /// * Use [`get_item`] if you would like to fetch an item that must exist. /// * Use [`get_items`] if you would like to fetch multiple items that must /// exist. /// /// [`get_item`]: Self::get_item pub fn get_items<'f, I>( &self, iter: I, ) -> Result<impl Iterator<Item = Result<(&'f Path, String), Error>>, Error> where I: Iterator<Item = &'f Path>, { let storage = self.get()?; let iter = iter.map(move |path| { let key = path.to_string_lossy(); storage .get_item(key.as_ref()) .map_err(|js_value| { Error::Web(WebError::StorageGetItem { path: path.to_path_buf(), error: crate::stringify_js_value(js_value), }) }) .and_then(|value| { value.ok_or_else(|| Error::ItemNotExists { path: path.to_path_buf(), }) }) .map(|value| (path, value)) }); Ok(iter) } /// Sets an item in the web storage. /// /// See [`set_items`] if you would like to set multiple items. /// /// [`set_items`]: Self::set_items pub fn set_item(&self, path: &Path, value: &str) -> Result<(), Error> { let storage = self.get()?; let key = path.to_string_lossy(); storage.set_item(key.as_ref(), value).map_err(|js_value| { Error::Web(WebError::StorageSetItem { path: path.to_path_buf(), value: value.to_string(), error: crate::stringify_js_value(js_value), }) }) } /// Base64 encodes and sets a value in the web storage. pub fn set_item_b64<B>(&self, path: &Path, bytes: &B) -> Result<(), Error> where B: AsRef<[u8]>, { let value = base64::engine::general_purpose::STANDARD.encode(bytes); self.set_item(path, &value) } /// Sets multiple items in the web storage. /// /// See [`set_item`] if you would like to set a single item. /// /// [`set_item`]: Self::set_item pub fn set_items<'f, I>(&self, mut iter: I) -> Result<(), Error> where I: Iterator<Item = (&'f Path, &'f str)>, { let storage = self.get()?; iter.try_for_each(|(path, value)| { let key = path.to_string_lossy(); storage.set_item(key.as_ref(), value).map_err(|js_value| { Error::Web(WebError::StorageSetItem { path: path.to_path_buf(), value: value.to_string(), error: crate::stringify_js_value(js_value), }) }) }) } /// Runs the provided closure for each item produced by the iterator, /// augmented with the web storage. /// /// Note that the `storage` passed to the closure is the browser storage, so /// `set_item` takes a `&str` for the key. /// /// # Example /// /// ```rust,ignore /// # use std::path::PathBuf; /// # use peace_rt_model_web::{Storage, WorkspaceSpec, Error}; /// # /// # fn main() -> Result<(), Error> { /// let storage = Storage::new(WorkspaceSpec::SessionStorage); /// let keys = ["abc", "def"]; /// /// storage.iter_with_storage(keys.into_iter(), |storage, key| { /// let value = "something"; /// storage /// .set_item(key, value) /// .map_err(|js_value| (PathBuf::from(key), value.to_string(), js_value)) /// })?; /// # /// # Ok(()) /// # } /// ``` pub fn iter_with_storage<F, I, T>(&self, mut iter: I, mut f: F) -> Result<(), Error> where F: for<'f> FnMut(&'f web_sys::Storage, T) -> Result<(), (PathBuf, String, JsValue)>, I: Iterator<Item = T>, { let storage = self.get()?; iter.try_for_each(|t| { f(&storage, t).map_err(|(path, value, js_value)| { Error::Web(WebError::StorageSetItem { path, value, error: crate::stringify_js_value(js_value), }) }) }) } /// Reads the file at the given path to string. /// /// # Parameters /// /// * `file_path`: Path to the file to read to string. pub async fn read_to_string(&self, file_path: &Path) -> Result<String, Error> { self.get_item(file_path) } /// Reads a serializable item from the given key. /// /// # Parameters /// /// * `path`: Path to read the serialized item. /// * `f_map_err`: Maps the deserialization error (if any) to an [`Error`]. pub async fn serialized_read_opt<T, F>( &self, path: &Path, f_map_err: F, ) -> Result<Option<T>, Error> where T: DeserializeOwned + Send + Sync, F: FnOnce(serde_yaml::Error) -> Error + Send, { self.get_item_opt(path)? .map(|s| serde_yaml::from_str::<T>(&s).map_err(f_map_err)) .transpose() } /// Deserializes a typemap from the given path if the file exists. /// /// # Parameters /// /// * `thread_name`: Name of the thread to use to do the read operation. /// * `type_reg`: Type registry with the stateful deserialization mappings. /// * `file_path`: Path to the file to read the serialized item. /// * `f_map_err`: Maps the deserialization error (if any) to an [`Error`]. pub async fn serialized_typemap_read_opt<K, BoxDT, F>( &self, type_reg: &TypeReg<K, BoxDT>, path: &Path, f_map_err: F, ) -> Result<Option<TypeMapOpt<K, BoxDT, UnknownEntriesSome<serde_yaml::Value>>>, Error> where K: Clone + Debug + DeserializeOwned + Eq + Hash + Sync + 'static, BoxDT: DataTypeWrapper + 'static, F: FnOnce(serde_yaml::Error) -> Error + Send, { self.get_item_opt(path)? .map(|s| { let deserializer = serde_yaml::Deserializer::from_str(&s); let type_map_opt = type_reg .deserialize_map_opt_with_unknowns::<'_, serde_yaml::Value, _, _>(deserializer) .map_err(f_map_err)?; Ok(type_map_opt) }) .transpose() } /// Writes a serializable item to the given path. /// /// # Parameters /// /// * `path`: Path to store the serialized item. /// * `t`: Item to serialize. /// * `f_map_err`: Maps the serialization error (if any) to an [`Error`]. pub async fn serialized_write<T, F>( &self, path: &Path, t: &T, f_map_err: F, ) -> Result<(), Error> where T: Serialize + Send + Sync, F: FnOnce(serde_yaml::Error) -> Error + Send, { self.set_item(path, &serde_yaml::to_string(t).map_err(f_map_err)?)?; Ok(()) } /// Serializes an item to a string. /// /// # Parameters /// /// * `t`: Item to serialize. /// * `f_map_err`: Maps the serialization error (if any) to an [`Error`]. pub fn serialized_write_string<T, F>(&self, t: &T, f_map_err: F) -> Result<String, Error> where T: Serialize + Send + Sync, F: FnOnce(serde_yaml::Error) -> Error + Send, { serde_yaml::to_string(t).map_err(f_map_err) } /// Deletes an item from the web storage. pub fn remove_item(&self, path: &Path) -> Result<(), Error> { let storage = self.get()?; let key = path.to_string_lossy(); storage.remove_item(key.as_ref()).map_err(|js_value| { Error::Web(WebError::StorageRemoveItem { path: path.to_path_buf(), error: crate::stringify_js_value(js_value), }) }) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model_web/src/workspace_spec.rs
crate/rt_model_web/src/workspace_spec.rs
/// Describes how to store peace automation data. /// /// See <https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API>. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum WorkspaceSpec { /// Use browser local storage to store peace data. /// /// Persists even when the browser is closed and reopened. /// /// * Stores data with no expiration date, and gets cleared only through /// JavaScript, or clearing the Browser cache / Locally Stored Data. /// * Storage limit is the maximum amongst the two. LocalStorage, /// Use session storage to store peace data. /// /// Maintains a separate storage area for each given origin that's available /// for the duration of the page session (as long as the browser is open, /// including page reloads and restores) /// /// * Stores data only for a session, meaning that the data is stored until /// the browser (or tab) is closed. /// * Data is never transferred to the server. /// * Storage limit is larger than a cookie (at most 5MB). SessionStorage, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model_web/src/workspace_initializer.rs
crate/rt_model_web/src/workspace_initializer.rs
use std::{fmt::Debug, hash::Hash, path::Path}; use peace_resource_rt::{ internal::{FlowParamsFile, ProfileParamsFile, WorkspaceParamsFile}, type_reg::untagged::{TypeMapOpt, TypeReg}, }; use peace_rt_model_core::{ params::{FlowParams, ProfileParams, WorkspaceParams}, Error, }; use serde::{de::DeserializeOwned, Serialize}; use crate::Storage; /// Logic to create peace directories and reads/writes initialization params. /// /// # Type Parameters /// /// * `WorkspaceInit`: Parameters to initialize the workspace. /// /// These are parameters common to the workspace. Examples: /// /// - Organization username. /// - Repository URL for multiple environments. /// /// This may be `()` if there are no parameters common to the workspace. /// /// * `ProfileInit`: Parameters to initialize the profile. /// /// These are parameters specific to a profile, but common to flows within /// that profile. Examples: /// /// - Environment specific credentials. /// - URL to publish / download an artifact. /// /// This may be `()` if there are no profile specific parameters. /// /// * `FlowInit`: Parameters to initialize the flow. /// /// These are parameters specific to a flow. Examples: /// /// - Configuration to skip warnings for the particular flow. /// /// This may be `()` if there are no flow specific parameters. #[derive(Debug)] pub struct WorkspaceInitializer; impl WorkspaceInitializer { /// Creates directories used by the peace framework. pub async fn dirs_create<'f, I>(storage: &Storage, dirs: I) -> Result<(), Error> where I: IntoIterator<Item = &'f Path>, { storage.set_items(dirs.into_iter().map(|dir| (dir, "")))?; Result::<_, Error>::Ok(()) } pub async fn workspace_params_serialize<K>( storage: &Storage, workspace_params: &WorkspaceParams<K>, workspace_params_file: &WorkspaceParamsFile, ) -> Result<(), Error> where K: Eq + Hash + Serialize + Send + Sync, { storage .serialized_write( workspace_params_file, workspace_params, Error::WorkspaceParamsSerialize, ) .await } pub async fn workspace_params_deserialize<K>( storage: &Storage, type_reg: &TypeReg<K>, workspace_params_file: &WorkspaceParamsFile, ) -> Result<Option<WorkspaceParams<K>>, Error> where K: Clone + Debug + Eq + Hash + DeserializeOwned + Send + Sync + 'static, { storage .serialized_typemap_read_opt( type_reg, workspace_params_file, Error::WorkspaceParamsDeserialize, ) .await .map(|type_map_opt| { type_map_opt .map(TypeMapOpt::into_type_map) .map(WorkspaceParams::from) }) } pub async fn profile_params_serialize<K>( storage: &Storage, profile_params: &ProfileParams<K>, profile_params_file: &ProfileParamsFile, ) -> Result<(), Error> where K: Eq + Hash + Serialize + Send + Sync, { storage .serialized_write( profile_params_file, profile_params, Error::ProfileParamsSerialize, ) .await } pub async fn profile_params_deserialize<K>( storage: &Storage, type_reg: &TypeReg<K>, profile_params_file: &ProfileParamsFile, ) -> Result<Option<ProfileParams<K>>, Error> where K: Clone + Debug + Eq + Hash + DeserializeOwned + Send + Sync + 'static, { storage .serialized_typemap_read_opt( type_reg, profile_params_file, Error::ProfileParamsDeserialize, ) .await .map(|type_map_opt| { type_map_opt .map(TypeMapOpt::into_type_map) .map(ProfileParams::from) }) } pub async fn flow_params_serialize<K>( storage: &Storage, flow_params: &FlowParams<K>, flow_params_file: &FlowParamsFile, ) -> Result<(), Error> where K: Eq + Hash + Serialize + Send + Sync, { storage .serialized_write(flow_params_file, flow_params, Error::FlowParamsSerialize) .await } pub async fn flow_params_deserialize<K>( storage: &Storage, type_reg: &TypeReg<K>, flow_params_file: &FlowParamsFile, ) -> Result<Option<FlowParams<K>>, Error> where K: Clone + Debug + Eq + Hash + DeserializeOwned + Send + Sync + 'static, { storage .serialized_typemap_read_opt(type_reg, flow_params_file, Error::FlowParamsDeserialize) .await .map(|type_map_opt| { type_map_opt .map(TypeMapOpt::into_type_map) .map(FlowParams::from) }) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model_web/src/workspace_dirs_builder.rs
crate/rt_model_web/src/workspace_dirs_builder.rs
use std::path::PathBuf; use peace_core::AppName; use peace_resource_rt::{ internal::WorkspaceDirs, paths::{PeaceAppDir, PeaceDir}, }; use peace_rt_model_core::Error; use crate::WorkspaceSpec; /// Computes paths of well-known directories for a workspace. #[derive(Debug)] pub struct WorkspaceDirsBuilder; impl WorkspaceDirsBuilder { /// Computes [`WorkspaceDirs`] paths. pub fn build( app_name: &AppName, workspace_spec: WorkspaceSpec, ) -> Result<WorkspaceDirs, Error> { // Written this way so that if we want to add a prefix, this would compile // error. let workspace_dir = match workspace_spec { WorkspaceSpec::LocalStorage | WorkspaceSpec::SessionStorage => PathBuf::from("").into(), }; let peace_dir = PeaceDir::from(&workspace_dir); let peace_app_dir = PeaceAppDir::from((&peace_dir, app_name)); Ok(WorkspaceDirs::new(workspace_dir, peace_dir, peace_app_dir)) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cli_model/src/lib.rs
crate/cli_model/src/lib.rs
//! Command line interface data types for the peace automation framework. pub use self::{output_format::OutputFormat, output_format_parse_error::OutputFormatParseError}; mod output_format; mod output_format_parse_error;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cli_model/src/output_format_parse_error.rs
crate/cli_model/src/output_format_parse_error.rs
use std::fmt; /// Failed to parse output format from string. #[derive(Clone, Debug, PartialEq, Eq)] pub struct OutputFormatParseError(pub String); impl fmt::Display for OutputFormatParseError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, r#"Failed to parse output format from string: `"{}"`. Valid values are ["text", "yaml", "json"]"#, self.0 ) } } impl std::error::Error for OutputFormatParseError {}
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cli_model/src/output_format.rs
crate/cli_model/src/output_format.rs
use std::str::FromStr; use crate::OutputFormatParseError; /// How to format command output -- human readable or machine parsable. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum OutputFormat { /// Human readable text. Text, /// The YAML Ain't Markup Languageβ„’ ([YAML]) format. /// /// [YAML]: https://yaml.org/ Yaml, /// The JavaScript Object Notation ([JSON]) format /// /// [JSON]: https://www.json.org/ Json, /// Don't output anything. None, } impl FromStr for OutputFormat { type Err = OutputFormatParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "text" => Ok(Self::Text), "yaml" => Ok(Self::Yaml), "json" => Ok(Self::Json), "none" => Ok(Self::None), _ => Err(OutputFormatParseError(s.to_string())), } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_rt/src/lib.rs
crate/cmd_rt/src/lib.rs
//! Runtime types for commands for the Peace framework. // Re-exports pub use async_trait::async_trait; pub use tynm; pub use crate::{ cmd_block::{CmdBlock, CmdBlockError, CmdBlockRt, CmdBlockRtBox, CmdBlockWrapper}, cmd_execution::{CmdExecution, CmdExecutionBuilder}, item_stream_outcome_mapper::ItemStreamOutcomeMapper, }; mod cmd_block; mod cmd_execution; mod item_stream_outcome_mapper; cfg_if::cfg_if! { if #[cfg(feature = "output_progress")] { /// Maximum number of progress messages to buffer. pub const CMD_PROGRESS_COUNT_MAX: usize = 256; pub(crate) use crate::progress::Progress; pub(crate) mod progress; } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_rt/src/cmd_execution.rs
crate/cmd_rt/src/cmd_execution.rs
use std::{collections::VecDeque, fmt::Debug}; use futures::{future, stream, Future, StreamExt, TryStreamExt}; use interruptible::InterruptSignal; use peace_cmd_ctx::{CmdCtxSpsf, CmdCtxSpsfFields, CmdCtxTypes}; use peace_cmd_model::{CmdBlockDesc, CmdOutcome}; use peace_resource_rt::{resources::ts::SetUp, Resources}; use crate::{CmdBlockError, CmdBlockRtBox, ItemStreamOutcomeMapper}; cfg_if::cfg_if! { if #[cfg(feature = "output_progress")] { use peace_progress_model::CmdProgressUpdate; use peace_rt_model::{output::OutputWrite, CmdProgressTracker}; use tokio::sync::mpsc::{self, Sender}; use crate::Progress; } } pub use self::{ cmd_execution_builder::CmdExecutionBuilder, cmd_execution_error_builder::CmdExecutionErrorBuilder, }; mod cmd_execution_builder; mod cmd_execution_error_builder; /// List of [`CmdBlock`]s to run for a `*Cmd`. /// /// A `CmdExecution` is interruptible if [`CmdExecutionBuilder::interruptible`] /// is called during construction. /// /// # Design /// /// Interruptibility is implemented as type state. It could be implemented as a /// feature flag as well; I don't know if developers want certain command /// executions to be interruptible, and others not. /// /// [`CmdBlock`]: crate::CmdBlock #[derive(Debug)] pub struct CmdExecution<'types, ExecutionOutcome, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Blocks of commands to run. cmd_blocks: VecDeque<CmdBlockRtBox<'types, CmdCtxTypesT, ExecutionOutcome>>, /// Logic to extract the `ExecutionOutcome` from `Resources`. execution_outcome_fetch: fn(&mut Resources<SetUp>) -> Option<ExecutionOutcome>, /// Whether or not to render progress. #[cfg(feature = "output_progress")] progress_render_enabled: bool, } impl<'types, ExecutionOutcome, CmdCtxTypesT> CmdExecution<'types, ExecutionOutcome, CmdCtxTypesT> where ExecutionOutcome: Debug + Send + Sync + Unpin + 'static, CmdCtxTypesT: CmdCtxTypes + 'types, { pub fn builder() -> CmdExecutionBuilder<'types, ExecutionOutcome, CmdCtxTypesT> { CmdExecutionBuilder::new() } /// Returns the result of executing the command. pub async fn exec( &mut self, cmd_ctx: &mut CmdCtxSpsf<'types, CmdCtxTypesT>, ) -> Result< CmdOutcome<ExecutionOutcome, <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > { let Self { cmd_blocks, execution_outcome_fetch, #[cfg(feature = "output_progress")] progress_render_enabled, } = self; #[cfg(feature = "output_progress")] let progress_render_enabled = *progress_render_enabled; cfg_if::cfg_if! { if #[cfg(feature = "output_progress")] { let CmdCtxSpsf { output, cmd_progress_tracker, fields: ref mut cmd_ctx_spsf_fields, } = cmd_ctx; let (cmd_progress_tx, cmd_progress_rx) = mpsc::channel::<CmdProgressUpdate>(crate::CMD_PROGRESS_COUNT_MAX); let cmd_progress_tx_for_interruptibility_state = cmd_progress_tx.clone().downgrade(); cmd_ctx_spsf_fields.interruptibility_state .set_fn_interrupt_activate(Some(move || { if let Some(cmd_progress_tx) = cmd_progress_tx_for_interruptibility_state.upgrade() { let _cmd_progress_send_result = cmd_progress_tx.try_send(CmdProgressUpdate::Interrupt); drop(cmd_progress_tx); } })); } else { let CmdCtxSpsf { fields: ref mut cmd_ctx_spsf_fields, .. } = cmd_ctx; } } let cmd_outcome_task = cmd_outcome_task( cmd_blocks, execution_outcome_fetch, cmd_ctx_spsf_fields, #[cfg(feature = "output_progress")] cmd_progress_tx, ); #[cfg(not(feature = "output_progress"))] { exec_internal(cmd_outcome_task).await } #[cfg(feature = "output_progress")] { exec_internal( cmd_outcome_task, progress_render_enabled, &mut **output, cmd_progress_tracker, cmd_progress_rx, ) .await } } // pub fn exec_bg -> CmdExecId } /// Executes and returns the `CmdOutcome`. /// /// This also runs the progress task if the `"output_progress"` feature is /// enabled. async fn exec_internal<ExecutionOutcome, E, #[cfg(feature = "output_progress")] O: OutputWrite>( cmd_outcome_task: impl Future<Output = Result<CmdOutcome<ExecutionOutcome, E>, E>>, #[cfg(feature = "output_progress")] progress_render_enabled: bool, #[cfg(feature = "output_progress")] output: &mut O, #[cfg(feature = "output_progress")] cmd_progress_tracker: &mut CmdProgressTracker, #[cfg(feature = "output_progress")] mut cmd_progress_rx: mpsc::Receiver<CmdProgressUpdate>, ) -> Result<CmdOutcome<ExecutionOutcome, E>, E> where ExecutionOutcome: Debug + Send + Sync + Unpin + 'static, E: std::error::Error + From<peace_rt_model::Error> + Send + Sync + Unpin + 'static, { #[cfg(not(feature = "output_progress"))] { cmd_outcome_task.await } #[cfg(feature = "output_progress")] if progress_render_enabled { output.progress_begin(cmd_progress_tracker).await; let progress_trackers = &mut cmd_progress_tracker.progress_trackers; let progress_render_task = Progress::progress_render(output, progress_trackers, cmd_progress_rx); let (cmd_outcome, ()) = futures::join!(cmd_outcome_task, progress_render_task); output.progress_end(cmd_progress_tracker).await; cmd_outcome } else { // When `progress_render_enabled` is false, still consumes progress updates // and drop them. let progress_render_task = async move { while cmd_progress_rx.recv().await.is_some() {} }; let (cmd_outcome, ()) = futures::join!(cmd_outcome_task, progress_render_task); cmd_outcome } } async fn cmd_outcome_task<'types: 'view, 'view, 'view_ref, ExecutionOutcome, CmdCtxTypesT>( cmd_blocks: &VecDeque<CmdBlockRtBox<'types, CmdCtxTypesT, ExecutionOutcome>>, execution_outcome_fetch: &mut fn(&mut Resources<SetUp>) -> Option<ExecutionOutcome>, cmd_ctx_spsf_fields: &mut CmdCtxSpsfFields<'view, CmdCtxTypesT>, #[cfg(feature = "output_progress")] cmd_progress_tx: Sender<CmdProgressUpdate>, ) -> Result< CmdOutcome<ExecutionOutcome, <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > where ExecutionOutcome: Debug + Send + Sync + Unpin + 'static, CmdCtxTypesT: CmdCtxTypes, { let cmd_ctx_spsf_fields_and_progress_result: Result< CmdViewAndProgress<'_, '_, _>, CmdBlockStreamBreak<'_, '_, _, _>, > = stream::unfold(cmd_blocks.iter(), |mut cmd_blocks| { let cmd_block_next = cmd_blocks.next(); future::ready(cmd_block_next.map(|cmd_block_next| (cmd_block_next, cmd_blocks))) }) .enumerate() .map(Result::<_, CmdBlockStreamBreak<'_, '_, ExecutionOutcome, CmdCtxTypesT>>::Ok) .try_fold( CmdViewAndProgress { cmd_ctx_spsf_fields, #[cfg(feature = "output_progress")] cmd_progress_tx, }, // `progress_tx` is moved into this closure, and dropped at the very end, so // that `progress_render_task` will actually end. |cmd_ctx_spsf_fields_and_progress, (cmd_block_index, cmd_block_rt)| async move { let CmdViewAndProgress { cmd_ctx_spsf_fields, #[cfg(feature = "output_progress")] cmd_progress_tx, } = cmd_ctx_spsf_fields_and_progress; #[cfg(feature = "output_progress")] if cmd_block_index != 0 { cmd_progress_tx .send(CmdProgressUpdate::ResetToPending) .await .expect( "Expected `CmdProgressUpdate` channel to remain open \ while iterating over `CmdBlock`s.", ); } // Check if we are interrupted before we execute this `CmdBlock`. if let Some(interrupt_signal) = cmd_ctx_spsf_fields .interruptibility_state .item_interrupt_poll(true) { let cmd_ctx_spsf_fields_and_progress = CmdViewAndProgress { cmd_ctx_spsf_fields, #[cfg(feature = "output_progress")] cmd_progress_tx, }; return Err(CmdBlockStreamBreak::Interrupt { cmd_ctx_spsf_fields_and_progress, cmd_block_index_next: cmd_block_index, interrupt_signal, }); } #[cfg(feature = "output_progress")] { let cmd_block_item_interaction_type = cmd_block_rt.cmd_block_item_interaction_type(); cmd_progress_tx .send(CmdProgressUpdate::CmdBlockStart { cmd_block_item_interaction_type, }) .await .expect( "Expected `CmdProgressUpdate` channel to remain open \ while iterating over `CmdBlock`s.", ); } let block_cmd_outcome_result = cmd_block_rt .exec( cmd_ctx_spsf_fields, #[cfg(feature = "output_progress")] cmd_progress_tx.clone(), ) .await; // `CmdBlock` block logic errors are propagated. let cmd_ctx_spsf_fields_and_progress = CmdViewAndProgress { cmd_ctx_spsf_fields, #[cfg(feature = "output_progress")] cmd_progress_tx, }; match block_cmd_outcome_result { Ok(()) => Ok(cmd_ctx_spsf_fields_and_progress), Err(cmd_block_error) => Err(CmdBlockStreamBreak::BlockErr(CmdViewAndErr { cmd_ctx_spsf_fields_and_progress, cmd_block_index, cmd_block_error, })), } }, ) .await; outcome_extract::<ExecutionOutcome, CmdCtxTypesT>( cmd_ctx_spsf_fields_and_progress_result, cmd_blocks, execution_outcome_fetch, ) } /// Extracts the `ExecutionOutcome` from the intermediate outcome collating /// types. /// /// # Parameters /// /// * `cmd_ctx_spsf_fields_and_progress_result`: The command context, progress, /// and maybe error. /// * `cmd_blocks`: `CmdBlock`s in this execution, used to build a useful error /// message if needed. /// * `execution_outcome_fetch`: Logic to extract the `ExecutionOutcome` type. fn outcome_extract<'types: 'view, 'view, 'view_ref, ExecutionOutcome, CmdCtxTypesT>( cmd_ctx_spsf_fields_and_progress_result: Result< CmdViewAndProgress<'view, 'view_ref, CmdCtxTypesT>, CmdBlockStreamBreak<'view, 'view_ref, ExecutionOutcome, CmdCtxTypesT>, >, cmd_blocks: &'view_ref VecDeque<CmdBlockRtBox<'types, CmdCtxTypesT, ExecutionOutcome>>, execution_outcome_fetch: &mut fn(&mut Resources<SetUp>) -> Option<ExecutionOutcome>, ) -> Result< CmdOutcome<ExecutionOutcome, <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > where ExecutionOutcome: Debug + Send + Sync + Unpin + 'static, CmdCtxTypesT: CmdCtxTypes, { let (cmd_ctx_spsf_fields_and_progress, cmd_block_index_and_error, cmd_block_index_next) = match cmd_ctx_spsf_fields_and_progress_result { Ok(cmd_ctx_spsf_fields_and_progress) => (cmd_ctx_spsf_fields_and_progress, None, None), Err(cmd_block_stream_break) => match cmd_block_stream_break { CmdBlockStreamBreak::Interrupt { cmd_ctx_spsf_fields_and_progress, cmd_block_index_next, interrupt_signal: InterruptSignal, } => ( cmd_ctx_spsf_fields_and_progress, None, Some(cmd_block_index_next), ), CmdBlockStreamBreak::BlockErr(CmdViewAndErr { cmd_ctx_spsf_fields_and_progress, cmd_block_index, cmd_block_error, }) => ( cmd_ctx_spsf_fields_and_progress, Some((cmd_block_index, cmd_block_error)), Some(cmd_block_index), ), }, }; let CmdViewAndProgress { cmd_ctx_spsf_fields: CmdCtxSpsfFields { flow, resources, .. }, #[cfg(feature = "output_progress")] cmd_progress_tx, } = cmd_ctx_spsf_fields_and_progress; #[cfg(feature = "output_progress")] drop(cmd_progress_tx); if let Some((cmd_block_index, cmd_block_error)) = cmd_block_index_and_error { match cmd_block_error { CmdBlockError::InputFetch(resource_fetch_error) => { Err(<CmdCtxTypesT as CmdCtxTypes>::AppError::from( peace_rt_model::Error::from(CmdExecutionErrorBuilder::build::<_, _, _>( cmd_blocks.iter(), cmd_block_index, resource_fetch_error, )), )) } CmdBlockError::Exec(error) => Err(error), CmdBlockError::Interrupt { stream_outcome } => { let item_stream_outcome = ItemStreamOutcomeMapper::map(flow, stream_outcome); let cmd_blocks_processed = cmd_blocks .range(0..cmd_block_index) .map(|cmd_block_rt| cmd_block_rt.cmd_block_desc()) .collect::<Vec<CmdBlockDesc>>(); let cmd_blocks_not_processed = cmd_blocks .range(cmd_block_index..) .map(|cmd_block_rt| cmd_block_rt.cmd_block_desc()) .collect::<Vec<CmdBlockDesc>>(); let cmd_outcome = CmdOutcome::BlockInterrupted { item_stream_outcome, cmd_blocks_processed, cmd_blocks_not_processed, }; Ok(cmd_outcome) } CmdBlockError::ItemError { stream_outcome, errors, } => { let item_stream_outcome = ItemStreamOutcomeMapper::map(flow, stream_outcome); let cmd_blocks_processed = cmd_blocks .range(0..cmd_block_index) .map(|cmd_block_rt| cmd_block_rt.cmd_block_desc()) .collect::<Vec<CmdBlockDesc>>(); let cmd_blocks_not_processed = cmd_blocks .range(cmd_block_index..) .map(|cmd_block_rt| cmd_block_rt.cmd_block_desc()) .collect::<Vec<CmdBlockDesc>>(); let cmd_outcome = CmdOutcome::ItemError { item_stream_outcome, cmd_blocks_processed, cmd_blocks_not_processed, errors, }; Ok(cmd_outcome) } } } else { let execution_outcome = execution_outcome_fetch(resources); let cmd_outcome = if let Some(cmd_block_index_next) = cmd_block_index_next { let cmd_blocks_processed = cmd_blocks .range(0..cmd_block_index_next) .map(|cmd_block_rt| cmd_block_rt.cmd_block_desc()) .collect::<Vec<CmdBlockDesc>>(); let cmd_blocks_not_processed = cmd_blocks .range(cmd_block_index_next..) .map(|cmd_block_rt| cmd_block_rt.cmd_block_desc()) .collect::<Vec<CmdBlockDesc>>(); CmdOutcome::ExecutionInterrupted { value: execution_outcome, cmd_blocks_processed, cmd_blocks_not_processed, } } else { let cmd_blocks_processed = cmd_blocks .iter() .map(|cmd_block_rt| cmd_block_rt.cmd_block_desc()) .collect::<Vec<CmdBlockDesc>>(); CmdOutcome::Complete { value: execution_outcome.unwrap_or_else(|| { let execution_outcome_type_name = tynm::type_name::<ExecutionOutcome>(); panic!( "Expected `{execution_outcome_type_name}` to exist in `Resources`.\n\ Make sure the final `CmdBlock` has that type as its `Outcome`.\n\ \n\ You may wish to call `CmdExecutionBuilder::with_execution_outcome_fetch`\n\ to specify how to fetch the `ExecutionOutcome`." ); }), cmd_blocks_processed, } }; Ok(cmd_outcome) } } struct CmdViewAndProgress<'view, 'view_ref, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { cmd_ctx_spsf_fields: &'view_ref mut CmdCtxSpsfFields<'view, CmdCtxTypesT>, #[cfg(feature = "output_progress")] cmd_progress_tx: Sender<CmdProgressUpdate>, } /// Reasons to stop processing `CmdBlock`s. enum CmdBlockStreamBreak<'view, 'view_ref, ExecutionOutcome, CmdCtxTypesT> where ExecutionOutcome: Debug, CmdCtxTypesT: CmdCtxTypes, { /// An interruption happened between `CmdBlock` executions. Interrupt { cmd_ctx_spsf_fields_and_progress: CmdViewAndProgress<'view, 'view_ref, CmdCtxTypesT>, /// Index of the next `CmdBlock` that hasn't been processed. cmd_block_index_next: usize, interrupt_signal: InterruptSignal, }, /// A `CmdBlockError` was returned from `CmdBlockRt::exec`. BlockErr(CmdViewAndErr<'view, 'view_ref, ExecutionOutcome, CmdCtxTypesT>), } struct CmdViewAndErr<'view, 'view_ref, ExecutionOutcome, CmdCtxTypesT> where ExecutionOutcome: Debug, CmdCtxTypesT: CmdCtxTypes, { cmd_ctx_spsf_fields_and_progress: CmdViewAndProgress<'view, 'view_ref, CmdCtxTypesT>, /// Index of the `CmdBlock` that erred. cmd_block_index: usize, cmd_block_error: CmdBlockError<ExecutionOutcome, <CmdCtxTypesT as CmdCtxTypes>::AppError>, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_rt/src/cmd_block.rs
crate/cmd_rt/src/cmd_block.rs
use std::fmt::Debug; use async_trait::async_trait; use peace_cmd_ctx::{CmdCtxSpsfFields, CmdCtxTypes}; use peace_cmd_model::CmdBlockOutcome; use peace_resource_rt::{resources::ts::SetUp, Resource, ResourceFetchError, Resources}; cfg_if::cfg_if! { if #[cfg(feature = "output_progress")] { use peace_progress_model::{CmdBlockItemInteractionType, CmdProgressUpdate}; use tokio::sync::mpsc::Sender; } } pub use self::{ cmd_block_error::CmdBlockError, cmd_block_rt::CmdBlockRt, cmd_block_rt_box::CmdBlockRtBox, cmd_block_wrapper::CmdBlockWrapper, }; mod cmd_block_error; mod cmd_block_rt; mod cmd_block_rt_box; mod cmd_block_wrapper; /// Runs one [`Item::*`] function for one iteration of items. /// /// A command may consist of: /// /// 1. Discovering the current state of an environment. /// 2. Ensuring new items that are not blocked, e.g. launch new servers before /// taking old servers away. /// 3. Cleaning unused items that block new items from being ensured, e.g. /// terminating servers before resizing a subnet's CIDR block. /// 4. Ensuring new / modified items that are newly unblocked, e.g. launching /// new servers in the resized subnet. /// 5. Cleaning unused items that are no longer needed, e.g. removing an old /// service. /// /// Each of these is an iteration through items, running one of the [`Item::*`] /// functions. /// /// A `CmdBlock` is the unit of one iteration logic. /// /// [`Item::*`]: peace_cfg::Item #[async_trait(?Send)] pub trait CmdBlock: Debug { /// Type parameters passed to the `CmdCtx`. /// /// `CmdBlock` uses the `AppError` and `ParamsKeys` associated type. type CmdCtxTypes: CmdCtxTypes; /// Outcome type of the command block, e.g. `(StatesCurrent, StatesGoal)`. type Outcome: Debug + Send + Sync + 'static; /// Input type of the command block, e.g. `StatesCurrent`. type InputT: Resource + 'static; /// Returns the type of interactions the `CmdBlock` has with /// `ItemLocation`s. #[cfg(feature = "output_progress")] fn cmd_block_item_interaction_type(&self) -> CmdBlockItemInteractionType; /// Fetch function for `InputT`. /// /// This is overridable so that `CmdBlock`s can change how their `InputT` is /// looked up. /// /// The most common use case for overriding this is for unit `()` inputs, /// which should provide an empty implementation. /// /// # Maintainers / Developers /// /// Whenever this method is overridden, `input_type_names` should be /// overridden as well. fn input_fetch( &self, resources: &mut Resources<SetUp>, ) -> Result<Self::InputT, ResourceFetchError> { resources.try_remove::<Self::InputT>() } /// Returns the short type name(s) of `CmdBlock::InputT`. /// /// If this `CmdBlock::InputT` is a tuple, and each member type is inserted /// separately into `resources`, then this method must return the short type /// name per member type. /// /// # Design /// /// This is a separate method to `input_fetch` as it is invoked separately. /// Though of course we *could* also change `input_fetch` to return a /// closure that returns the input type names. /// /// # Maintainers / Developers /// /// Example implementations are as follows. /// /// Within the `peace` framework: /// /// ```rust,ignore /// // type InputT = (StatesCurrent, StatesGoal); /// /// vec![tynm::type_name::<StatesCurrent>(), /// tynm::type_name::<StatesGoal>()] /// ``` /// /// Outside the `peace` framework: /// /// ```rust,ignore /// // type InputT = (StatesCurrent, StatesGoal); /// /// vec![ /// peace::cmd_rt::tynm::type_name::<StatesCurrent>(), /// peace::cmd_rt::tynm::type_name::<StatesGoal>(), /// ] /// ``` fn input_type_names(&self) -> Vec<String> { vec![tynm::type_name::<Self::InputT>()] } /// Inserts the `CmdBlock::Outcome` into `Resources`. /// /// This is overridable so that `CmdBlock`s can change how their `Outcome` /// is inserted. /// /// The most common use case for overriding this is for unit `()` inputs, /// which should provide an empty implementation. /// /// # Maintainers / Developers /// /// Whenever this method is overridden, `outcome_type_names` should be /// overridden as well. fn outcome_insert(&self, resources: &mut Resources<SetUp>, outcome: Self::Outcome) { resources.insert(outcome); } /// Returns the short type name(s) of `CmdBlock::Outcome`. /// /// If this `CmdBlock::Outcome` is a tuple, and each member type is inserted /// separately into `resources`, then this method must return the short type /// name per member type. /// /// # Maintainers / Developers /// /// Example implementations are as follows. /// /// Within the `peace` framework: /// /// ```rust,ignore /// // type Outcome = (StatesCurrent, StatesGoal); /// /// vec![tynm::type_name::<StatesCurrent>(), /// tynm::type_name::<StatesGoal>()] /// ``` /// /// Outside the `peace` framework: /// /// ```rust,ignore /// // type Outcome = (StatesCurrent, StatesGoal); /// /// vec![ /// peace::cmd_rt::tynm::type_name::<StatesCurrent>(), /// peace::cmd_rt::tynm::type_name::<StatesGoal>(), /// ] /// ``` fn outcome_type_names(&self) -> Vec<String> { vec![tynm::type_name::<Self::Outcome>()] } /// Producer function to process all items. /// /// This is infallible because errors are expected to be returned associated /// with an item. This may change if there are errors that are related to /// the block that are not associated with a specific item. /// /// # Implementors /// /// `StreamOutcome<()>` should be returned if the `CmdBlock` streams the /// items, as this captures whether or not the block execution was /// interrupted. /// /// If the block does not stream items, `None` should be returned. async fn exec( &self, input: Self::InputT, cmd_ctx_spsf_fields: &mut CmdCtxSpsfFields<'_, Self::CmdCtxTypes>, #[cfg(feature = "output_progress")] progress_tx: &Sender<CmdProgressUpdate>, ) -> Result< CmdBlockOutcome<Self::Outcome, <Self::CmdCtxTypes as CmdCtxTypes>::AppError>, <Self::CmdCtxTypes as CmdCtxTypes>::AppError, >; }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_rt/src/progress.rs
crate/cmd_rt/src/progress.rs
use std::ops::ControlFlow; use futures::stream::{self, StreamExt}; use peace_item_model::ItemId; use peace_progress_model::{ CmdBlockItemInteractionType, CmdProgressUpdate, ItemLocationState, ProgressDelta, ProgressMsgUpdate, ProgressStatus, ProgressTracker, ProgressUpdate, ProgressUpdateAndId, }; use peace_rt_model::{output::OutputWrite, IndexMap}; use tokio::sync::mpsc::Receiver; pub struct Progress; impl Progress { /// Receives progress updates and updates `output` to render it. // TODO: write test for this pub async fn progress_render<O>( output: &mut O, progress_trackers: &mut IndexMap<ItemId, ProgressTracker>, mut cmd_progress_rx: Receiver<CmdProgressUpdate>, ) where O: OutputWrite, { while let Some(cmd_progress_update) = cmd_progress_rx.recv().await { let _control_flow = Self::handle_cmd_progress_update(output, progress_trackers, cmd_progress_update) .await; } } async fn handle_cmd_progress_update<O>( output: &mut O, progress_trackers: &mut IndexMap<ItemId, ProgressTracker>, cmd_progress_update: CmdProgressUpdate, ) -> ControlFlow<()> where O: OutputWrite, { match cmd_progress_update { CmdProgressUpdate::CmdBlockStart { cmd_block_item_interaction_type, } => { Self::handle_cmd_block_start(output, cmd_block_item_interaction_type).await; ControlFlow::Continue(()) } CmdProgressUpdate::ItemProgress { progress_update_and_id, } => { Self::handle_progress_update_and_id( output, progress_trackers, progress_update_and_id, ) .await; ControlFlow::Continue(()) } CmdProgressUpdate::ItemLocationState { item_id, item_location_state, } => { Self::handle_item_location_state(output, item_id, item_location_state).await; ControlFlow::Continue(()) } CmdProgressUpdate::Interrupt => { stream::iter(progress_trackers.iter_mut()) .fold(output, |output, (item_id, progress_tracker)| async move { let item_id = item_id.clone(); let progress_update_and_id = ProgressUpdateAndId { item_id, progress_update: ProgressUpdate::Interrupt, msg_update: ProgressMsgUpdate::NoChange, }; Self::handle_progress_tracker_progress_update( output, progress_tracker, progress_update_and_id, ) .await; output }) .await; ControlFlow::Break(()) } CmdProgressUpdate::ResetToPending => { stream::iter(progress_trackers.iter_mut()) .fold(output, |output, (item_id, progress_tracker)| async move { let item_id = item_id.clone(); let progress_update_and_id = ProgressUpdateAndId { item_id, progress_update: ProgressUpdate::ResetToPending, msg_update: ProgressMsgUpdate::Clear, }; Self::handle_progress_tracker_progress_update( output, progress_tracker, progress_update_and_id, ) .await; output }) .await; ControlFlow::Continue(()) } } } async fn handle_cmd_block_start<O>( output: &mut O, cmd_block_item_interaction_type: CmdBlockItemInteractionType, ) where O: OutputWrite, { output .cmd_block_start(cmd_block_item_interaction_type) .await; } async fn handle_item_location_state<O>( output: &mut O, item_id: ItemId, item_location_state: ItemLocationState, ) where O: OutputWrite, { output .item_location_state(item_id, item_location_state) .await; } async fn handle_progress_update_and_id<O>( output: &mut O, progress_trackers: &mut IndexMap<ItemId, ProgressTracker>, progress_update_and_id: ProgressUpdateAndId, ) where O: OutputWrite, { let item_id = &progress_update_and_id.item_id; let Some(progress_tracker) = progress_trackers.get_mut(item_id) else { panic!("Expected `progress_tracker` to exist for item: `{item_id}`."); }; Self::handle_progress_tracker_progress_update( output, progress_tracker, progress_update_and_id, ) .await; } async fn handle_progress_tracker_progress_update<O>( output: &mut O, progress_tracker: &mut ProgressTracker, progress_update_and_id: ProgressUpdateAndId, ) where O: OutputWrite, { let ProgressUpdateAndId { item_id: _, progress_update, msg_update, } = &progress_update_and_id; match progress_update { ProgressUpdate::Reset => progress_tracker.reset(), ProgressUpdate::ResetToPending => progress_tracker.reset_to_pending(), ProgressUpdate::Queued => progress_tracker.set_progress_status(ProgressStatus::Queued), ProgressUpdate::Interrupt => progress_tracker.interrupt(), ProgressUpdate::Limit(progress_limit) => { progress_tracker.set_progress_limit(*progress_limit); progress_tracker.set_progress_status(ProgressStatus::ExecPending); } ProgressUpdate::Delta(delta) => { match delta { ProgressDelta::Tick => progress_tracker.tick(), ProgressDelta::Inc(unit_count) => progress_tracker.inc(*unit_count), } progress_tracker.set_progress_status(ProgressStatus::Running); } ProgressUpdate::Complete(progress_complete) => { progress_tracker .set_progress_status(ProgressStatus::Complete(progress_complete.clone())); } } match msg_update { ProgressMsgUpdate::Clear => progress_tracker.set_message(None), ProgressMsgUpdate::NoChange => {} ProgressMsgUpdate::Set(message) => progress_tracker.set_message(Some(message.clone())), } output .progress_update(progress_tracker, &progress_update_and_id) .await; } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_rt/src/item_stream_outcome_mapper.rs
crate/cmd_rt/src/item_stream_outcome_mapper.rs
use fn_graph::StreamOutcome; use peace_cmd_model::ItemStreamOutcome; use peace_flow_rt::Flow; /// Maps a `StreamOutcome<T>` to an `ItemStreamOutcome<T>`. /// /// # Design Note /// /// This resides in the `cmd_rt` package as the `Flow` type is needed for /// mapping, and adding `rt_model` as a dependency of `cmd_model` creates a /// dependency cycle with `rt_model_core`: /// /// ```text /// cmd_model -> rt_model /// ^ / /// / v /// rt_model_core /// ``` pub struct ItemStreamOutcomeMapper; impl ItemStreamOutcomeMapper { /// Maps `FnId`s into `ItemId`s for a better information abstraction level. pub fn map<T, E>(flow: &Flow<E>, stream_outcome: StreamOutcome<T>) -> ItemStreamOutcome<T> where E: 'static, { let StreamOutcome { value, state, fn_ids_processed, fn_ids_not_processed, } = stream_outcome; let item_ids_processed = fn_ids_processed .into_iter() .filter_map(|fn_id| { flow.graph() .node_weight(fn_id) .map(|item| item.id()) .cloned() }) .collect::<Vec<_>>(); let item_ids_not_processed = fn_ids_not_processed .into_iter() .filter_map(|fn_id| { flow.graph() .node_weight(fn_id) .map(|item| item.id()) .cloned() }) .collect::<Vec<_>>(); ItemStreamOutcome { value, state, item_ids_processed, item_ids_not_processed, } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_rt/src/cmd_execution/cmd_execution_builder.rs
crate/cmd_rt/src/cmd_execution/cmd_execution_builder.rs
use std::{collections::VecDeque, fmt::Debug}; use peace_cmd_ctx::CmdCtxTypes; use peace_resource_rt::{resources::ts::SetUp, Resource, Resources}; use crate::{CmdBlock, CmdBlockRtBox, CmdBlockWrapper, CmdExecution}; /// Collects the [`CmdBlock`]s to run in a `*Cmd` to build a [`CmdExecution`]. /// /// [`CmdBlock`]: crate::CmdBlock /// [`CmdExecution`]: crate::CmdExecution #[derive(Debug)] pub struct CmdExecutionBuilder<'types, ExecutionOutcome, CmdCtxTypesT> where ExecutionOutcome: Debug + Send + Sync + 'static, CmdCtxTypesT: CmdCtxTypes, { /// Blocks of commands to run. cmd_blocks: VecDeque<CmdBlockRtBox<'types, CmdCtxTypesT, ExecutionOutcome>>, /// Logic to extract the `ExecutionOutcome` from `Resources`. execution_outcome_fetch: fn(&mut Resources<SetUp>) -> Option<ExecutionOutcome>, /// Whether or not to render progress. /// /// This is intended for `*Cmd`s that do not have meaningful progress to /// render, such as deserializing a single file on disk, and there is no /// benefit to presenting empty progress bars for each item to the user /// /// Defaults to `true`. #[cfg(feature = "output_progress")] progress_render_enabled: bool, } impl<'types, ExecutionOutcome, CmdCtxTypesT> CmdExecutionBuilder<'types, ExecutionOutcome, CmdCtxTypesT> where ExecutionOutcome: Debug + Send + Sync + 'static, CmdCtxTypesT: CmdCtxTypes + 'types, { pub fn new() -> Self { Self::default() } /// Adds a `CmdBlock` to this execution. pub fn with_cmd_block<CB, BlockOutcomeNext, InputT>( self, cmd_block: CmdBlockWrapper<CB, CmdCtxTypesT, ExecutionOutcome, BlockOutcomeNext, InputT>, ) -> CmdExecutionBuilder<'types, ExecutionOutcome, CmdCtxTypesT> where CB: CmdBlock<CmdCtxTypes = CmdCtxTypesT, Outcome = BlockOutcomeNext, InputT = InputT> + Unpin + 'types, ExecutionOutcome: Debug + Resource + Unpin + 'static, BlockOutcomeNext: Debug + Resource + Unpin + 'static, InputT: Debug + Resource + Unpin + 'static, { let CmdExecutionBuilder { mut cmd_blocks, execution_outcome_fetch, #[cfg(feature = "output_progress")] progress_render_enabled, } = self; cmd_blocks.push_back(Box::pin(cmd_block)); CmdExecutionBuilder { cmd_blocks, execution_outcome_fetch, #[cfg(feature = "output_progress")] progress_render_enabled, } } /// Specifies the logic to fetch the `ExecutionOutcome` from `Resources`. /// /// By default, the `CmdExecution` will run /// `resources.remove::<ExecutionOutcome>()`. However, if the /// `ExecutionOutcome` is not inserted as a single type, this allows /// consumers to specify which types to remove from `resources` and return /// as the `ExecutionOutcome`. pub fn with_execution_outcome_fetch( mut self, execution_outcome_fetch: fn(&mut Resources<SetUp>) -> Option<ExecutionOutcome>, ) -> Self { self.execution_outcome_fetch = execution_outcome_fetch; self } /// Specifies whether or not to render progress. /// /// This is `true` by default, so usually this would be called with `false`. /// /// This is intended for `*Cmd`s that do not have meaningful progress to /// render, such as deserializing a single file on disk, and there is no /// benefit to presenting empty progress bars for each item to the user. /// /// When this method is called multiple times, the last call wins. #[cfg(feature = "output_progress")] pub fn with_progress_render_enabled(mut self, progress_render_enabled: bool) -> Self { self.progress_render_enabled = progress_render_enabled; self } /// Returns the `CmdExecution` to execute. pub fn build(self) -> CmdExecution<'types, ExecutionOutcome, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { let CmdExecutionBuilder { cmd_blocks, execution_outcome_fetch, #[cfg(feature = "output_progress")] progress_render_enabled, } = self; CmdExecution { cmd_blocks, execution_outcome_fetch, #[cfg(feature = "output_progress")] progress_render_enabled, } } } impl<ExecutionOutcome, CmdCtxTypesT> Default for CmdExecutionBuilder<'_, ExecutionOutcome, CmdCtxTypesT> where ExecutionOutcome: Debug + Resource + 'static, CmdCtxTypesT: CmdCtxTypes, { fn default() -> Self { Self { cmd_blocks: VecDeque::new(), execution_outcome_fetch, #[cfg(feature = "output_progress")] progress_render_enabled: true, } } } fn execution_outcome_fetch<ExecutionOutcome>( resources: &mut Resources<SetUp>, ) -> Option<ExecutionOutcome> where ExecutionOutcome: Debug + Send + Sync + 'static, { resources.try_remove::<ExecutionOutcome>().ok() }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_rt/src/cmd_execution/cmd_execution_error_builder.rs
crate/cmd_rt/src/cmd_execution/cmd_execution_error_builder.rs
use std::fmt::Debug; use peace_cmd_ctx::CmdCtxTypes; use peace_cmd_model::{CmdBlockDesc, CmdExecutionError, InputFetchError}; use peace_resource_rt::ResourceFetchError; use crate::CmdBlockRtBox; cfg_if::cfg_if! { if #[cfg(feature = "error_reporting")] { use std::fmt::{self, Write}; use tynm::TypeParamsFmtOpts; use miette::SourceSpan; use crate::CmdExecution; } } /// Computes the values to construct a `CmdExecutionError`. #[derive(Debug)] pub struct CmdExecutionErrorBuilder; impl CmdExecutionErrorBuilder { /// Returns a `CmdExecutionError` by collating `CmdBlock` information. /// /// Approximation of the source for `EnsureCmd`: /// /// ```yaml /// CmdExecution: /// ExecutionOutcome: (States<Previous>, States<Ensured>, States<Goal>) /// CmdBlocks: /// - StatesCurrentReadCmdBlock: /// Input: States<Current> /// Outcome: States<Goal> /// - StatesGoalReadCmdBlock: /// Input: States<Current> /// Outcome: States<Goal> /// - StatesDiscoverCmdBlock: /// Input: () /// Outcome: (States<Current>, States<Goal>) /// - ApplyStateSyncCheckCmdBlock: /// Input: (States<CurrentStored>, States<Current>, States<GoalStored>, States<Goal>) /// Outcome: (States<CurrentStored>, States<Current>, States<GoalStored>, States<Goal>) /// - ApplyExecCmdBlock: /// Input: (States<Current>, States<Goal>) /// Outcome: (States<Previous>, States<Ensured>, States<Goal>) /// ``` pub fn build<'types: 'f, 'f, ExecutionOutcome, CmdCtxTypesT, CmdBlockIterator>( cmd_blocks: CmdBlockIterator, cmd_block_index: usize, resource_fetch_error: ResourceFetchError, ) -> CmdExecutionError where CmdCtxTypesT: CmdCtxTypes + 'f, ExecutionOutcome: Debug + Send + Sync + Unpin + 'static, CmdBlockIterator: Iterator<Item = &'f CmdBlockRtBox<'types, CmdCtxTypesT, ExecutionOutcome>>, { let ResourceFetchError { resource_name_short: input_name_short, resource_name_full: input_name_full, } = resource_fetch_error; let cmd_block_descs = cmd_blocks .map(|cmd_block_rt| cmd_block_rt.cmd_block_desc()) .collect::<Vec<CmdBlockDesc>>(); #[cfg(feature = "error_reporting")] let (cmd_execution_src, input_span) = cmd_execution_src::<ExecutionOutcome, CmdCtxTypesT>( &cmd_block_descs, &input_name_short, ) .expect("Failed to write to `cmd_execution_src` buffer."); #[cfg(feature = "error_reporting")] let full_span = SourceSpan::from((0, cmd_execution_src.len())); CmdExecutionError::InputFetch(Box::new(InputFetchError { cmd_block_descs, cmd_block_index, input_name_short, input_name_full, #[cfg(feature = "error_reporting")] cmd_execution_src, #[cfg(feature = "error_reporting")] input_span, #[cfg(feature = "error_reporting")] full_span, })) } } #[cfg(feature = "error_reporting")] fn cmd_execution_src<ExecutionOutcome, CmdCtxTypesT>( cmd_block_descs: &[CmdBlockDesc], input_name_short: &str, ) -> Result<(String, Option<SourceSpan>), fmt::Error> where ExecutionOutcome: Debug + Send + Sync + Unpin + 'static, CmdCtxTypesT: CmdCtxTypes, { let mut cmd_execution_src = String::with_capacity(2048); let cmd_execution_name = tynm::type_name_opts::<CmdExecution<ExecutionOutcome, CmdCtxTypesT>>( TypeParamsFmtOpts::Std, ); let execution_outcome_types_name = tynm::type_name_opts::<ExecutionOutcome>(TypeParamsFmtOpts::All); writeln!(&mut cmd_execution_src, "{cmd_execution_name}:")?; writeln!( &mut cmd_execution_src, " ExecutionOutcome: {execution_outcome_types_name}" )?; writeln!(&mut cmd_execution_src, "CmdBlocks:")?; let input_span = cmd_block_descs .iter() .try_fold(None, |mut input_span_opt, cmd_block_desc| { let cmd_block_name = cmd_block_desc.cmd_block_name(); writeln!(&mut cmd_execution_src, " - {cmd_block_name}:")?; write!(&mut cmd_execution_src, " Input: ")?; match cmd_block_desc.cmd_block_input_names().split_first() { None => writeln!(&mut cmd_execution_src, "()")?, Some((input_first, input_remainder)) => { if input_remainder.is_empty() { if input_first == input_name_short { input_span_opt = Some(SourceSpan::from(( cmd_execution_src.len(), input_first.len(), ))); } writeln!(&mut cmd_execution_src, "{input_first}")?; } else { write!(&mut cmd_execution_src, "(")?; if input_first == input_name_short { input_span_opt = Some(SourceSpan::from(( cmd_execution_src.len(), input_first.len(), ))); } write!(&mut cmd_execution_src, "{input_first}")?; input_remainder .iter() .try_for_each(|cmd_block_input_name| { if cmd_block_input_name == input_name_short { input_span_opt = Some(SourceSpan::from(( // + 2 is for the comma and space cmd_execution_src.len() + 2, cmd_block_input_name.len(), ))); } write!(&mut cmd_execution_src, ", {cmd_block_input_name}")?; Ok(()) })?; writeln!(&mut cmd_execution_src, ")")?; } } } write!(&mut cmd_execution_src, " Outcome: ")?; match cmd_block_desc.cmd_block_outcome_names().split_first() { None => write!(&mut cmd_execution_src, "()")?, Some((outcome_first, outcome_remainder)) => { if outcome_remainder.is_empty() { writeln!(&mut cmd_execution_src, "{outcome_first}")?; } else { write!(&mut cmd_execution_src, "(")?; write!(&mut cmd_execution_src, "{outcome_first}")?; outcome_remainder .iter() .try_for_each(|cmd_block_outcome_name| { write!(&mut cmd_execution_src, ", {cmd_block_outcome_name}")?; Ok(()) })?; writeln!(&mut cmd_execution_src, ")")?; } } } Ok(input_span_opt) })?; Ok::<_, fmt::Error>((cmd_execution_src, input_span)) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_rt/src/cmd_block/cmd_block_wrapper.rs
crate/cmd_rt/src/cmd_block/cmd_block_wrapper.rs
use std::{fmt::Debug, marker::PhantomData}; use async_trait::async_trait; use fn_graph::StreamOutcomeState; use peace_cmd_ctx::{CmdCtxSpsfFields, CmdCtxTypes}; use peace_cmd_model::{CmdBlockDesc, CmdBlockOutcome}; use peace_resource_rt::Resource; use tynm::TypeParamsFmtOpts; use crate::{CmdBlock, CmdBlockError, CmdBlockRt}; cfg_if::cfg_if! { if #[cfg(feature = "output_progress")] { use peace_progress_model::{CmdBlockItemInteractionType, CmdProgressUpdate}; use tokio::sync::mpsc::Sender; } } /// Wraps a [`CmdBlock`] and holds a partial execution handler. /// /// The following are the technical reasons for this type's existence: /// /// * Being in the `peace_cmd` crate, the type erased [`CmdBlockRt`] trait can /// be implemented on this type within this crate. /// * The partial execution handler specifies how a command execution should /// finish, if execution is interrupted or there is an error with one item /// within the flow. /// /// [`CmdBlockRt`]: crate::CmdBlockRt #[derive(Debug)] pub struct CmdBlockWrapper<CB, CmdCtxTypesT, ExecutionOutcome, BlockOutcome, InputT> { /// Underlying `CmdBlock` implementation. /// /// The trait constraints are applied on impl blocks. cmd_block: CB, /// Function to run if interruption or an item failure happens while /// executing this `CmdBlock`. fn_partial_exec_handler: fn(BlockOutcome) -> ExecutionOutcome, /// Marker. marker: PhantomData<(CmdCtxTypesT, BlockOutcome, InputT)>, } impl<CB, CmdCtxTypesT, ExecutionOutcome, BlockOutcome, InputT> CmdBlockWrapper<CB, CmdCtxTypesT, ExecutionOutcome, BlockOutcome, InputT> where CB: CmdBlock<CmdCtxTypes = CmdCtxTypesT, InputT = InputT>, { /// Returns a new `CmdBlockWrapper`. /// /// # Parameters /// /// * `cmd_block`: The `CmdBlock` implementation. /// * `fn_partial_exec_handler`: How the `CmdExecution` should end, if /// execution ends with this `CmdBlock`. /// /// This could be due to interruption, or a `CmdOutcome` with an item /// failure. pub fn new( cmd_block: CB, fn_partial_exec_handler: fn(BlockOutcome) -> ExecutionOutcome, ) -> Self { Self { cmd_block, fn_partial_exec_handler, marker: PhantomData, } } } #[async_trait(?Send)] impl<CB, CmdCtxTypesT, ExecutionOutcome, BlockOutcome, InputT> CmdBlockRt for CmdBlockWrapper<CB, CmdCtxTypesT, ExecutionOutcome, BlockOutcome, InputT> where CB: CmdBlock<CmdCtxTypes = CmdCtxTypesT, Outcome = BlockOutcome, InputT = InputT> + Unpin, CmdCtxTypesT: CmdCtxTypes, ExecutionOutcome: Debug + Unpin + Send + Sync + 'static, BlockOutcome: Debug + Unpin + Send + Sync + 'static, InputT: Debug + Resource + Unpin + 'static, { type CmdCtxTypes = CmdCtxTypesT; type ExecutionOutcome = ExecutionOutcome; async fn exec( &self, cmd_ctx_spsf_fields: &mut CmdCtxSpsfFields<'_, CmdCtxTypesT>, #[cfg(feature = "output_progress")] progress_tx: Sender<CmdProgressUpdate>, ) -> Result<(), CmdBlockError<ExecutionOutcome, <Self::CmdCtxTypes as CmdCtxTypes>::AppError>> { let cmd_block = &self.cmd_block; let input = cmd_block.input_fetch(&mut cmd_ctx_spsf_fields.resources)?; let cmd_block_outcome = cmd_block .exec( input, cmd_ctx_spsf_fields, #[cfg(feature = "output_progress")] &progress_tx, ) .await .map_err(CmdBlockError::Exec)?; // `progress_tx` is dropped here, so `progress_rx` will safely end. #[cfg(feature = "output_progress")] drop(progress_tx); match cmd_block_outcome { CmdBlockOutcome::Single(block_outcome) => { cmd_block.outcome_insert(&mut cmd_ctx_spsf_fields.resources, block_outcome); Ok(()) } CmdBlockOutcome::ItemWise { stream_outcome, errors, } => { if errors.is_empty() { match stream_outcome.state { StreamOutcomeState::NotStarted => { let cmd_block_name = tynm::type_name::<CB>(); unreachable!( "`{cmd_block_name}` returned `StreamOutcomeState::NotStarted`.\n\ This should be impossible as `FnGraph` stream functions always poll their underlying stream.\n\ \n\ This is a bug, please report it at <https://github.com/azriel91/peace>." ); } StreamOutcomeState::Interrupted => { let stream_outcome = stream_outcome.map(self.fn_partial_exec_handler); Err(CmdBlockError::Interrupt { stream_outcome }) } StreamOutcomeState::Finished => { let block_outcome = stream_outcome.value; cmd_block .outcome_insert(&mut cmd_ctx_spsf_fields.resources, block_outcome); Ok(()) } } } else { // If possible, `CmdBlock` outcomes with item errors need to be mapped to // the `CmdExecution` outcome type, so we still return the item errors. // // e.g. `StatesCurrentMut` should be mapped into `StatesEnsured` when some // items fail to be ensured. // // Note, when discovering current and goal states for diffing, and an item // error occurs, mapping the partially accumulated `(StatesCurrentMut, // StatesGoalMut)` into `StateDiffs` may or may not be semantically // meaningful. let stream_outcome = stream_outcome.map(self.fn_partial_exec_handler); Err(CmdBlockError::ItemError { stream_outcome, errors, }) } } } } #[cfg(feature = "output_progress")] fn cmd_block_item_interaction_type(&self) -> CmdBlockItemInteractionType { self.cmd_block.cmd_block_item_interaction_type() } fn cmd_block_desc(&self) -> CmdBlockDesc { let cmd_block_name = tynm::type_name_opts::<CB>(TypeParamsFmtOpts::Std); let cmd_block_input_names = self.cmd_block.input_type_names(); let cmd_block_outcome_names = self.cmd_block.outcome_type_names(); CmdBlockDesc::new( cmd_block_name, cmd_block_input_names, cmd_block_outcome_names, ) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_rt/src/cmd_block/cmd_block_rt.rs
crate/cmd_rt/src/cmd_block/cmd_block_rt.rs
use std::fmt::Debug; use async_trait::async_trait; use peace_cmd_ctx::{CmdCtxSpsfFields, CmdCtxTypes}; use peace_cmd_model::CmdBlockDesc; use crate::CmdBlockError; cfg_if::cfg_if! { if #[cfg(feature = "output_progress")] { use peace_progress_model::{CmdBlockItemInteractionType, CmdProgressUpdate}; use tokio::sync::mpsc::Sender; } } /// Type erased [`CmdBlock`] /// /// [`CmdBlock`]: crate::CmdBlock #[async_trait(?Send)] pub trait CmdBlockRt: Debug + Unpin { /// Type parameters passed to the `CmdCtx`. type CmdCtxTypes: CmdCtxTypes; /// Outcome type of the command execution. type ExecutionOutcome: Debug + 'static; /// Executes this command block. async fn exec( &self, cmd_ctx_spsf_fields: &mut CmdCtxSpsfFields<'_, Self::CmdCtxTypes>, #[cfg(feature = "output_progress")] progress_tx: Sender<CmdProgressUpdate>, ) -> Result< (), CmdBlockError<Self::ExecutionOutcome, <Self::CmdCtxTypes as CmdCtxTypes>::AppError>, >; /// Returns the type of interactions the `CmdBlock` has with /// `ItemLocation`s. #[cfg(feature = "output_progress")] fn cmd_block_item_interaction_type(&self) -> CmdBlockItemInteractionType; /// Returns the `String` representation of the `CmdBlock` in a /// `CmdExecution`. /// /// This is used to provide a well-formatted error message so that /// developers can identify where a bug lies more easily. fn cmd_block_desc(&self) -> CmdBlockDesc; }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_rt/src/cmd_block/cmd_block_rt_box.rs
crate/cmd_rt/src/cmd_block/cmd_block_rt_box.rs
use std::pin::Pin; use crate::CmdBlockRt; /// Alias for `Box<dyn CmdBlockRt<..>>`. /// /// # Type Parameters /// /// * `E`: Automation software error type. /// * `PKeys`: Types of params keys. /// * `Outcome`: [`CmdBlock`] outcome type, e.g. `(StatesCurrent, StatesGoal)`. /// /// [`CmdBlock`]: crate::CmdBlock pub type CmdBlockRtBox<'types, CmdCtxTypesT, ExecutionOutcome> = Pin< Box<dyn CmdBlockRt<CmdCtxTypes = CmdCtxTypesT, ExecutionOutcome = ExecutionOutcome> + 'types>, >;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_rt/src/cmd_block/cmd_block_error.rs
crate/cmd_rt/src/cmd_block/cmd_block_error.rs
use std::fmt::Debug; use fn_graph::StreamOutcome; use indexmap::IndexMap; use peace_item_model::ItemId; use peace_resource_rt::ResourceFetchError; /// Error while executing a `CmdBlock`. /// /// # Type Parameters /// /// * `T`: Execution outcome, mapped from `CmdBlock::OutcomeAcc`. /// * `E`: Application error type. #[derive(Debug, thiserror::Error)] pub enum CmdBlockError<T, E> where T: Debug, E: Debug, { /// Error fetching `CmdBlock::InputT` from `resources`. /// /// If `CmdBlock::InputT` is a tuple, such as `(StatesCurrent, StatesGoal)`, /// and `states_current` and `states_goal` are inserted individually in /// `Resources`, then `CmdBlock::input_fetch` should be implemented to call /// `Resources::remove` for each of them. #[error( "Failed to fetch `{input_name_short}` from `resource`s.", input_name_short = _0.resource_name_short )] InputFetch( #[source] #[from] ResourceFetchError, ), /// Error originated from `CmdBlock` exec code. #[error("`CmdBlock` block execution or collation logic failed.")] Exec(E), /// Error originated from at least one item. /// /// The `CmdBlock::Outcome` is mapped to the `ExecutionOutcome` using /// `fn_partial_exec_handler`. #[error("`CmdBlock` item logic failed.")] ItemError { /// The outcome value. stream_outcome: StreamOutcome<T>, /// Item error(s) from the last command block's execution. errors: IndexMap<ItemId, E>, }, /// An interrupt signal was received while the `CmdBlock` was executing. #[error("`CmdBlock` item logic failed.")] Interrupt { /// The stream outcome of the interrupted command block. stream_outcome: StreamOutcome<T>, }, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/state_rt/src/lib.rs
crate/state_rt/src/lib.rs
//! State runtime logic for the peace automation framework. pub use crate::states_serializer::StatesSerializer; mod states_serializer;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/state_rt/src/states_serializer.rs
crate/state_rt/src/states_serializer.rs
use std::{marker::PhantomData, path::Path}; use peace_flow_model::FlowId; use peace_flow_rt::ItemGraph; use peace_item_model::ItemId; use peace_resource_rt::{ paths::{StatesCurrentFile, StatesGoalFile}, states::{ ts::{CurrentStored, GoalStored}, States, StatesCurrentStored, StatesGoalStored, }, type_reg::untagged::{BoxDtDisplay, TypeMapOpt, TypeReg}, }; use peace_rt_model::Storage; use peace_rt_model_core::{Error, StatesDeserializeError}; /// Reads and writes [`StatesCurrentStored`] and [`StatesGoalStored`] to and /// from storage. pub struct StatesSerializer<E>(PhantomData<E>); impl<E> StatesSerializer<E> where E: std::error::Error + From<Error> + Send + 'static, { /// Returns the [`StatesCurrentStored`] of all [`Item`]s if it exists on /// disk. /// /// # Parameters: /// /// * `storage`: `Storage` to read from. /// * `states`: States to serialize. /// * `states_file_path`: Path to save the serialized states to. /// /// [`Item`]: peace_cfg::Item pub async fn serialize<TS>( storage: &Storage, item_graph: &ItemGraph<E>, states: &States<TS>, states_file_path: &Path, ) -> Result<(), E> where TS: Send + Sync, { let states_serde = item_graph.states_serde::<serde_yaml::Value, _>(states); storage .serialized_write( #[cfg(not(target_arch = "wasm32"))] "StatesSerializer::serialize".to_string(), states_file_path, &states_serde, Error::StatesSerialize, ) .await?; Ok(()) } /// Returns the [`StatesCurrentStored`] of all [`Item`]s if it exists on /// disk. /// /// # Parameters: /// /// * `storage`: `Storage` to read from. /// * `states_type_reg`: Type registry with functions to deserialize each /// item state. /// * `states_current_file`: `StatesCurrentFile` to deserialize. /// /// [`Item`]: peace_cfg::Item pub async fn deserialize_stored( flow_id: &FlowId, storage: &Storage, states_type_reg: &TypeReg<ItemId, BoxDtDisplay>, states_current_file: &StatesCurrentFile, ) -> Result<StatesCurrentStored, E> { let states = Self::deserialize_internal::<CurrentStored>( #[cfg(not(target_arch = "wasm32"))] "StatesSerializer::deserialize_stored".to_string(), flow_id, storage, states_type_reg, states_current_file, ) .await?; states.ok_or_else(|| E::from(Error::StatesCurrentDiscoverRequired)) } /// Returns the [`StatesGoalStored`] of all [`Item`]s if it exists on disk. /// /// # Parameters: /// /// * `storage`: `Storage` to read from. /// * `states_type_reg`: Type registry with functions to deserialize each /// item state. /// * `states_goal_file`: `StatesGoalFile` to deserialize. /// /// [`Item`]: peace_cfg::Item pub async fn deserialize_goal( flow_id: &FlowId, storage: &Storage, states_type_reg: &TypeReg<ItemId, BoxDtDisplay>, states_goal_file: &StatesGoalFile, ) -> Result<StatesGoalStored, E> { let states = Self::deserialize_internal::<GoalStored>( #[cfg(not(target_arch = "wasm32"))] "StatesSerializer::deserialize_goal".to_string(), flow_id, storage, states_type_reg, states_goal_file, ) .await?; states.ok_or_else(|| E::from(Error::StatesGoalDiscoverRequired)) } /// Returns the [`StatesCurrentStored`] of all [`Item`]s if it exists on /// disk. /// /// # Parameters: /// /// * `storage`: `Storage` to read from. /// * `states_type_reg`: Type registry with functions to deserialize each /// item state. /// * `states_current_file`: `StatesCurrentFile` to deserialize. /// /// [`Item`]: peace_cfg::Item pub async fn deserialize_stored_opt( flow_id: &FlowId, storage: &Storage, states_type_reg: &TypeReg<ItemId, BoxDtDisplay>, states_current_file: &StatesCurrentFile, ) -> Result<Option<StatesCurrentStored>, E> { Self::deserialize_internal( #[cfg(not(target_arch = "wasm32"))] "StatesSerializer::deserialize_stored_opt".to_string(), flow_id, storage, states_type_reg, states_current_file, ) .await } /// Returns the [`States`] of all [`Item`]s if it exists on disk. /// /// # Parameters: /// /// * `storage`: `Storage` to read from. /// * `states_type_reg`: Type registry with functions to deserialize each /// item state. /// * `states_current_file`: `StatesCurrentFile` to deserialize. /// /// # Type Parameters /// /// * `TS`: The states type state to use, such as [`ts::Current`] or /// [`ts::CurrentStored`]. /// /// [`Item`]: peace_cfg::Item /// [`ts::Current`]: peace_resource_rt::states::ts::Current /// [`ts::CurrentStored`]: peace_resource_rt::states::ts::CurrentStored #[cfg(not(target_arch = "wasm32"))] async fn deserialize_internal<TS>( thread_name: String, flow_id: &FlowId, storage: &Storage, states_type_reg: &TypeReg<ItemId, BoxDtDisplay>, states_file_path: &Path, ) -> Result<Option<States<TS>>, E> where TS: Send + Sync, { let states_opt = storage .serialized_typemap_read_opt(thread_name, states_type_reg, states_file_path, |error| { #[cfg(not(feature = "error_reporting"))] { Error::StatesDeserialize(Box::new(StatesDeserializeError { flow_id: flow_id.clone(), error, })) } #[cfg(feature = "error_reporting")] { use miette::NamedSource; use yaml_error_context_hack::ErrorAndContext; let file_contents = std::fs::read_to_string(states_file_path).unwrap(); let ErrorAndContext { error_span, error_message, context_span, } = ErrorAndContext::new(&file_contents, &error); let states_file_source = NamedSource::new(states_file_path.to_string_lossy(), file_contents); Error::StatesDeserialize(Box::new(StatesDeserializeError { flow_id: flow_id.clone(), states_file_source, error_span, error_message, context_span, error, })) } }) .await .map(|type_map_opt| { type_map_opt .map(TypeMapOpt::into_type_map) .map(States::from) })?; Ok(states_opt) } /// Returns the [`States`] of all [`Item`]s if it exists on disk. /// /// # Parameters: /// /// * `storage`: `Storage` to read from. /// * `states_type_reg`: Type registry with functions to deserialize each /// item state. /// * `states_current_file`: `StatesCurrentFile` to deserialize. /// /// # Type Parameters /// /// * `TS`: The states type state to use, such as [`ts::Current`] or /// [`ts::CurrentStored`]. /// /// [`Item`]: peace_cfg::Item /// [`ts::Current`]: peace_resource_rt::states::ts::Current /// [`ts::CurrentStored`]: peace_resource_rt::states::ts::CurrentStored #[cfg(target_arch = "wasm32")] async fn deserialize_internal<TS>( flow_id: &FlowId, storage: &Storage, states_type_reg: &TypeReg<ItemId, BoxDtDisplay>, states_file_path: &Path, ) -> Result<Option<States<TS>>, E> where TS: Send + Sync, { let states_opt = storage .serialized_typemap_read_opt(states_type_reg, states_file_path, |error| { #[cfg(not(feature = "error_reporting"))] { Error::StatesDeserialize(Box::new(StatesDeserializeError { flow_id: flow_id.clone(), error, })) } #[cfg(feature = "error_reporting")] { use miette::NamedSource; use yaml_error_context_hack::ErrorAndContext; let file_contents = std::fs::read_to_string(states_file_path).unwrap(); let ErrorAndContext { error_span, error_message, context_span, } = ErrorAndContext::new(&file_contents, &error); let states_file_source = NamedSource::new(states_file_path.to_string_lossy(), file_contents); Error::StatesDeserialize(Box::new(StatesDeserializeError { flow_id: flow_id.clone(), states_file_source, error_span, error_message, context_span, error, })) } }) .await .map(|type_map_opt| { type_map_opt .map(TypeMapOpt::into_type_map) .map(States::from) })?; Ok(states_opt) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/webi/src/lib.rs
crate/webi/src/lib.rs
//! Web interface for the peace automation framework. pub use peace_webi_components as components; pub use peace_webi_model as model; #[cfg(feature = "ssr")] pub use peace_webi_output as output;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/webi_components/src/app.rs
crate/webi_components/src/app.rs
use std::time::Duration; use leptos::{ component, prelude::{signal, ClassAttribute, ElementChild, Get}, view, IntoView, }; use leptos_meta::{provide_meta_context, Link, Stylesheet}; use leptos_router::{ components::{Route, Router, Routes, RoutingProgress}, StaticSegment, }; use crate::ChildrenFn; /// Top level component of the `WebiOutput`. /// /// # Parameters: /// /// * `flow_component`: The web component to render for the flow. #[component] pub fn App(app_home: ChildrenFn) -> impl IntoView { // Provides context that manages stylesheets, titles, meta tags, etc. provide_meta_context(); let site_prefix = option_env!("SITE_PREFIX").unwrap_or(""); let favicon_path = format!("{site_prefix}/webi/favicon.ico"); let fonts_path = format!("{site_prefix}/webi/fonts/fonts.css"); let (is_routing, set_is_routing) = signal(false); view! { <Link rel="shortcut icon" type_="image/ico" href=favicon_path /> <Stylesheet id="fonts" href=fonts_path /> <Router set_is_routing> <div class="routing-progress"> <RoutingProgress is_routing max_time=Duration::from_millis(250)/> </div> <main> <Routes fallback=RouterFallback> <Route path=StaticSegment(site_prefix) view=move || app_home.call() /> </Routes> </main> </Router> } } #[component] fn RouterFallback() -> impl IntoView { let location = leptos_router::hooks::use_location(); let pathname = move || location.pathname.get(); view! { <p>"Path not found: " {pathname}</p> } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/webi_components/src/lib.rs
crate/webi_components/src/lib.rs
#![allow(non_snake_case)] // Components are all PascalCase. //! Web interface components for the peace automation framework. pub use leptos; pub use crate::{ app::App, children_fn::ChildrenFn, flow_graph::FlowGraph, flow_graph_current::FlowGraphCurrent, shell::Shell, }; mod app; mod children_fn; mod flow_graph; mod flow_graph_current; mod shell;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/webi_components/src/flow_graph.rs
crate/webi_components/src/flow_graph.rs
use dot_ix::{ model::{common::GraphvizDotTheme, info_graph::InfoGraph}, rt::IntoGraphvizDotSrc, web_components::DotSvg, }; use leptos::{ component, prelude::{ClassAttribute, ElementChild, ServerFnError, Set, Transition}, server, view, IntoView, }; /// Renders the flow graph. /// /// # Future /// /// * Take in whether any execution is running. Use that info to style /// nodes/edges. /// * Take in values so they can be rendered, or `WriteSignal`s, to notify the /// component that will render values about which node is selected. #[component] pub fn FlowGraph() -> impl IntoView { view! { <div class="flex items-center justify-center"> <ProgressGraph /> <OutcomeGraph /> </div> } } #[server] async fn progress_info_graph_fetch() -> Result<InfoGraph, ServerFnError> { use leptos::prelude::{Get, ReadSignal}; use peace_flow_model::FlowId; use peace_webi_model::FlowProgressInfoGraphs; let flow_id = leptos::prelude::use_context::<ReadSignal<FlowId>>(); let flow_progress_info_graphs = leptos::prelude::use_context::<FlowProgressInfoGraphs<FlowId>>(); let progress_info_graph = if let Some(flow_progress_info_graphs) = flow_progress_info_graphs { let flow_progress_info_graphs = flow_progress_info_graphs.lock().ok(); flow_id .as_ref() .map(Get::get) .zip(flow_progress_info_graphs) .and_then(|(flow_id, flow_progress_info_graphs)| { flow_progress_info_graphs.get(&flow_id).cloned() }) .unwrap_or_default() } else { InfoGraph::default() }; Ok(progress_info_graph) } #[component] fn ProgressGraph() -> impl IntoView { let (progress_info_graph, progress_info_graph_set) = leptos::prelude::signal(InfoGraph::default()); let (dot_src_and_styles, dot_src_and_styles_set) = leptos::prelude::signal(None); leptos::prelude::LocalResource::new(move || async move { let progress_info_graph = progress_info_graph_fetch().await.unwrap_or_default(); let dot_src_and_styles = IntoGraphvizDotSrc::into(&progress_info_graph, &GraphvizDotTheme::default()); if let Ok(progress_info_graph_serialized) = serde_yaml::to_string(&progress_info_graph) { leptos::logging::log!("{progress_info_graph_serialized}"); } progress_info_graph_set.set(progress_info_graph); dot_src_and_styles_set.set(Some(dot_src_and_styles)); }); view! { <Transition fallback=move || view! { <p>"Loading graph..."</p> }> <DotSvg info_graph=progress_info_graph.into() dot_src_and_styles=dot_src_and_styles.into() /> </Transition> } } #[server] async fn outcome_info_graph_fetch() -> Result<InfoGraph, ServerFnError> { use leptos::prelude::{Get, ReadSignal}; use peace_flow_model::FlowId; use peace_webi_model::FlowOutcomeInfoGraphs; let flow_id = leptos::prelude::use_context::<ReadSignal<FlowId>>(); let flow_outcome_info_graphs = leptos::prelude::use_context::<FlowOutcomeInfoGraphs<FlowId>>(); let outcome_info_graph = if let Some(flow_outcome_info_graphs) = flow_outcome_info_graphs { let flow_outcome_info_graphs = flow_outcome_info_graphs.lock().ok(); flow_id .as_ref() .map(Get::get) .zip(flow_outcome_info_graphs) .and_then(|(flow_id, flow_outcome_info_graphs)| { flow_outcome_info_graphs.get(&flow_id).cloned() }) .unwrap_or_default() } else { InfoGraph::default() }; Ok(outcome_info_graph) } #[component] fn OutcomeGraph() -> impl IntoView { let (outcome_info_graph, outcome_info_graph_set) = leptos::prelude::signal(InfoGraph::default()); let (dot_src_and_styles, dot_src_and_styles_set) = leptos::prelude::signal(None); leptos::prelude::LocalResource::new(move || async move { let outcome_info_graph = outcome_info_graph_fetch().await.unwrap_or_default(); let dot_src_and_styles = IntoGraphvizDotSrc::into(&outcome_info_graph, &GraphvizDotTheme::default()); if let Ok(outcome_info_graph_serialized) = serde_yaml::to_string(&outcome_info_graph) { leptos::logging::log!("{outcome_info_graph_serialized}"); } outcome_info_graph_set.set(outcome_info_graph); dot_src_and_styles_set.set(Some(dot_src_and_styles)); }); view! { <Transition fallback=move || view! { <p>"Loading graph..."</p> }> <DotSvg info_graph=outcome_info_graph.into() dot_src_and_styles=dot_src_and_styles.into() /> </Transition> } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/webi_components/src/flow_graph_current.rs
crate/webi_components/src/flow_graph_current.rs
use dot_ix::{ model::{common::GraphvizDotTheme, info_graph::InfoGraph}, rt::IntoGraphvizDotSrc, web_components::DotSvg, }; use leptos::{ component, prelude::{ClassAttribute, ElementChild, GetUntracked, ServerFnError, Set, Transition}, server, view, IntoView, }; /// Renders the flow graph. /// /// # Future /// /// * Take in whether any execution is running. Use that info to style /// nodes/edges. /// * Take in values so they can be rendered, or `WriteSignal`s, to notify the /// component that will render values about which node is selected. #[component] pub fn FlowGraphCurrent() -> impl IntoView { let (progress_info_graph_get, progress_info_graph_set) = leptos::prelude::signal(InfoGraph::default()); let (progress_dot_src_and_styles, progress_dot_src_and_styles_set) = leptos::prelude::signal(None); let (outcome_info_graph_get, outcome_info_graph_set) = leptos::prelude::signal(InfoGraph::default()); let (outcome_dot_src_and_styles, outcome_dot_src_and_styles_set) = leptos::prelude::signal(None); leptos::prelude::LocalResource::new(move || async move { use gloo_timers::future::TimeoutFuture; loop { if let Ok(Some((progress_info_graph, outcome_info_graph))) = info_graphs_fetch().await { // Progress let progress_dot_src_and_styles = IntoGraphvizDotSrc::into(&progress_info_graph, &GraphvizDotTheme::default()); if progress_info_graph != progress_info_graph_get.get_untracked() { progress_info_graph_set.set(progress_info_graph); progress_dot_src_and_styles_set.set(Some(progress_dot_src_and_styles)); } // Outcome let outcome_dot_src_and_styles = IntoGraphvizDotSrc::into(&outcome_info_graph, &GraphvizDotTheme::default()); if outcome_info_graph != outcome_info_graph_get.get_untracked() { if let Ok(outcome_info_graph_serialized) = serde_yaml::to_string(&outcome_info_graph) { leptos::logging::log!("{outcome_info_graph_serialized}"); } outcome_info_graph_set.set(outcome_info_graph); outcome_dot_src_and_styles_set.set(Some(outcome_dot_src_and_styles)); } } TimeoutFuture::new(250).await; } }); view! { <div class="flex items-center justify-center"> <Transition fallback=move || view! { <p>"Loading graph..."</p> }> <DotSvg info_graph=progress_info_graph_get.into() dot_src_and_styles=progress_dot_src_and_styles.into() /> <DotSvg info_graph=outcome_info_graph_get.into() dot_src_and_styles=outcome_dot_src_and_styles.into() /> </Transition> </div> } } #[server] async fn info_graphs_fetch() -> Result<Option<(InfoGraph, InfoGraph)>, ServerFnError> { use std::sync::{Arc, Mutex}; use peace_cmd_model::CmdExecutionId; use peace_webi_model::{FlowOutcomeInfoGraphs, FlowProgressInfoGraphs}; let cmd_execution_id = leptos::prelude::use_context::<Arc<Mutex<Option<CmdExecutionId>>>>(); let flow_progress_info_graphs = leptos::prelude::use_context::<FlowProgressInfoGraphs<CmdExecutionId>>(); let flow_outcome_info_graphs = leptos::prelude::use_context::<FlowOutcomeInfoGraphs<CmdExecutionId>>(); if let Some(((cmd_execution_id, flow_progress_info_graphs), flow_outcome_info_graphs)) = cmd_execution_id .zip(flow_progress_info_graphs) .zip(flow_outcome_info_graphs) { let cmd_execution_id = cmd_execution_id.lock().ok().as_deref().copied().flatten(); let flow_progress_info_graphs = flow_progress_info_graphs.lock().ok(); let progress_info_graph = cmd_execution_id.zip(flow_progress_info_graphs).and_then( |(cmd_execution_id, flow_progress_info_graphs)| { flow_progress_info_graphs.get(&cmd_execution_id).cloned() }, ); let flow_outcome_info_graphs = flow_outcome_info_graphs.lock().ok(); let outcome_info_graph = cmd_execution_id.zip(flow_outcome_info_graphs).and_then( |(cmd_execution_id, flow_outcome_info_graphs)| { flow_outcome_info_graphs.get(&cmd_execution_id).cloned() }, ); Ok(progress_info_graph.zip(outcome_info_graph)) } else { Ok(None) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/webi_components/src/shell.rs
crate/webi_components/src/shell.rs
use leptos::{ hydration::{AutoReload, HydrationScripts}, prelude::{ElementChild, GlobalAttributes, IntoView, LeptosOptions}, view, }; use leptos_meta::{provide_meta_context, MetaTags, Stylesheet, Title}; use crate::{App, ChildrenFn}; /// Main shell for server side rendered app. /// /// # Parameters /// /// * `app_name`: The name that `leptos` will compile the server side binary to. /// Usually the crate name, but may be changed by the `output-name` key in /// `Cargo.toml`. /// * `options`: The `LeptosOptions` from /// `leptos::prelude::get_configuration(None)?.leptos_options`. pub fn Shell(app_name: String, options: LeptosOptions, app_home: ChildrenFn) -> impl IntoView { // Provides context that manages stylesheets, titles, meta tags, etc. // // Normally this is in the `App` component, but for `peace_webi_components`, we // also include it in the `Shell` because the `Title` component calls // `leptos_meta::use_head()`, which logs a debug message about the meta context // not being provided. provide_meta_context(); view! { <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1" /> <AutoReload options=options.clone() /> <HydrationScripts options /> <MetaTags /> <Title text=format!("{app_name} β€’ peace")/> // injects a stylesheet into the document <head> // id=leptos means cargo-leptos will hot-reload this stylesheet <Stylesheet id="leptos" href=format!("/pkg/{app_name}.css") /> </head> <body> <App app_home /> </body> </html> } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/webi_components/src/children_fn.rs
crate/webi_components/src/children_fn.rs
use std::{fmt, sync::Arc}; use leptos::{ children::ToChildren, prelude::{AnyView, IntoAny, Render}, IntoView, }; /// Allows a consumer to pass in the view fragment for a /// [`leptos_router::Route`]. /// /// # Design /// /// In `leptos 0.6`, `leptos::ChildrenFn` is an alias for `Rc<_>`, so it cannot /// be passed to `leptos_axum::Router::leptos_routes`'s `app_fn` which requires /// `app_fn` to be `Clone`, so we need to create our own `ChildrenFn` which is /// `Clone`. /// /// When we migrate to `leptos 0.7`, `ChildrenFn` is an alias for `Arc<_>` so we /// can use it directly. #[derive(Clone)] pub struct ChildrenFn(Arc<dyn Fn() -> AnyView + Send + Sync>); impl ChildrenFn { /// Returns a new `ChildrenFn`; pub fn new<F, IV>(f: F) -> Self where F: Fn() -> IV + Send + Sync + 'static, IV: IntoView + 'static, <IV as Render>::State: 'static, { Self(Arc::new(move || f().into_view().into_any())) } /// Returns the underlying function. pub fn into_inner(self) -> Arc<dyn Fn() -> AnyView + Send + Sync> { self.0 } /// Calls the inner function to render the view. pub fn call(&self) -> AnyView { (self.0)() } } impl fmt::Debug for ChildrenFn { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_tuple("ChildrenFn") .field(&"Arc<dyn Fn() -> AnyView + Send + Sync>") .finish() } } impl<F> ToChildren<F> for ChildrenFn where F: Fn() -> AnyView + 'static + Send + Sync, { #[inline] fn to_children(f: F) -> Self { ChildrenFn(Arc::new(f)) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/flow_rt/src/lib.rs
crate/flow_rt/src/lib.rs
//! Flow runtime types for the peace automation framework. pub use crate::{flow::Flow, item_graph::ItemGraph, item_graph_builder::ItemGraphBuilder}; mod flow; mod item_graph; mod item_graph_builder;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/flow_rt/src/flow.rs
crate/flow_rt/src/flow.rs
use peace_data::fn_graph::GraphInfo; use peace_flow_model::{FlowId, FlowSpecInfo, ItemSpecInfo}; use crate::ItemGraph; cfg_if::cfg_if! { if #[cfg(all(feature = "item_interactions", feature = "item_state_example"))] { use std::collections::{BTreeMap, BTreeSet}; use indexmap::IndexMap; use peace_item_interaction_model::{ ItemInteraction, ItemInteractionsCurrentOrExample, ItemLocation, ItemLocationsAndInteractions, ItemLocationTree, }; use peace_item_model::ItemId; use peace_params::{MappingFnReg, ParamsSpecs}; use peace_resource_rt::{resources::ts::SetUp, Resources}; } } #[cfg(all( feature = "item_interactions", feature = "item_state_example", feature = "output_progress", ))] use std::collections::{HashMap, HashSet}; /// A flow to manage items. /// /// A Flow ID is strictly associated with an [`ItemGraph`], as the graph /// contains the definitions to read and write the items' [`State`]s. /// /// [`State`]: peace_cfg::Item::State #[derive(Debug)] pub struct Flow<E> { /// ID of this flow. flow_id: FlowId, /// Graph of [`Item`]s in this flow. /// /// [`Item`]: peace_cfg::Item graph: ItemGraph<E>, } impl<E> PartialEq for Flow<E> where E: 'static, { fn eq(&self, other: &Flow<E>) -> bool { self.flow_id == other.flow_id && self.graph == other.graph } } impl<E> Clone for Flow<E> { fn clone(&self) -> Self { Self { flow_id: self.flow_id.clone(), graph: self.graph.clone(), } } } impl<E> Eq for Flow<E> where E: 'static {} impl<E> Flow<E> { /// Returns a new `Flow`. pub fn new(flow_id: FlowId, graph: ItemGraph<E>) -> Self { Self { flow_id, graph } } /// Returns the flow ID. pub fn flow_id(&self) -> &FlowId { &self.flow_id } /// Returns the item graph. pub fn graph(&self) -> &ItemGraph<E> { &self.graph } /// Returns a mutable reference to the item graph. pub fn graph_mut(&self) -> &ItemGraph<E> { &self.graph } /// Generates a `FlowSpecInfo` from this `Flow`'s information. pub fn flow_spec_info(&self) -> FlowSpecInfo where E: 'static, { let flow_id = self.flow_id.clone(); let graph_info = GraphInfo::from_graph(&self.graph, |item_boxed| { let item_id = item_boxed.id().clone(); ItemSpecInfo { item_id } }); FlowSpecInfo::new(flow_id, graph_info) } // TODO: Refactor -- there is a lot of duplication between this method and // `item_locations_and_interactions_current` #[cfg(all(feature = "item_interactions", feature = "item_state_example"))] pub fn item_locations_and_interactions_example( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, ) -> ItemLocationsAndInteractions where E: 'static, { // Build the flattened hierarchy. // // Regardless of how nested each `ItemLocation` is, the map will have an entry // for it. // // The entry key is the `ItemLocation`, and the values are a list of its direct // descendent `ItemLocation`s. // // This means a lot of cloning of `ItemLocation`s. let item_interactions_ctx = ItemInteractionsCtx { item_location_direct_descendents: BTreeMap::new(), item_to_item_interactions: IndexMap::with_capacity(self.graph().node_count()), // Rough estimate that each item has about 4 item locations // // * 2 `ItemLocationAncestors`s for from, 2 for to. // * Some may have more, but we also combine `ItemLocation`s. // // After the `ItemLocationTree`s are constructed, we'll have an accurate // number, but they are being constructed at the same time as this map. #[cfg(feature = "output_progress")] item_location_to_item_id_sets: HashMap::with_capacity(self.graph().node_count() * 4), }; let item_interactions_ctx = self .graph() .iter() // Note: This will silently drop the item locations if `interactions_example` fails to // return. .filter_map(|item| { item.interactions_example(params_specs, mapping_fn_reg, resources) .ok() .map(|item_interactions_example| (item.id(), item_interactions_example)) }) .fold( item_interactions_ctx, |item_interactions_ctx, (item_id, item_interactions_example)| { let ItemInteractionsCtx { mut item_location_direct_descendents, mut item_to_item_interactions, #[cfg(feature = "output_progress")] mut item_location_to_item_id_sets, } = item_interactions_ctx; item_location_descendents_populate( &item_interactions_example, &mut item_location_direct_descendents, ); #[cfg(feature = "output_progress")] item_interactions_example .iter() .for_each(|item_interaction| match &item_interaction { ItemInteraction::Push(item_interaction_push) => item_interaction_push .location_from() .iter() .last() .into_iter() .chain(item_interaction_push.location_to().iter().last()) .for_each(|item_location| { item_location_to_item_id_sets_insert( &mut item_location_to_item_id_sets, item_location, item_id, ) }), ItemInteraction::Pull(item_interaction_pull) => item_interaction_pull .location_client() .iter() .last() .into_iter() .chain(item_interaction_pull.location_server().iter().last()) .for_each(|item_location| { item_location_to_item_id_sets_insert( &mut item_location_to_item_id_sets, item_location, item_id, ) }), ItemInteraction::Within(item_interaction_within) => { item_interaction_within .location() .iter() .last() .into_iter() .for_each(|item_location| { item_location_to_item_id_sets_insert( &mut item_location_to_item_id_sets, item_location, item_id, ) }) } }); item_to_item_interactions .insert(item_id.clone(), item_interactions_example.into_inner()); ItemInteractionsCtx { item_location_direct_descendents, item_to_item_interactions, #[cfg(feature = "output_progress")] item_location_to_item_id_sets, } }, ); let ItemInteractionsCtx { item_location_direct_descendents, item_to_item_interactions, #[cfg(feature = "output_progress")] item_location_to_item_id_sets, } = item_interactions_ctx; let item_locations_top_level = item_location_direct_descendents .keys() .filter(|item_location| { // this item_location is not in any descendents !item_location_direct_descendents .values() .any(|item_location_descendents| { item_location_descendents.contains(item_location) }) }) .cloned() .collect::<Vec<ItemLocation>>(); let item_locations_top_level_len = item_locations_top_level.len(); let (_item_location_direct_descendents, item_location_trees) = item_locations_top_level.into_iter().fold( ( item_location_direct_descendents, Vec::with_capacity(item_locations_top_level_len), ), |(mut item_location_direct_descendents, mut item_location_trees), item_location| { let item_location_tree = item_location_tree_collect( &mut item_location_direct_descendents, item_location, ); item_location_trees.push(item_location_tree); (item_location_direct_descendents, item_location_trees) }, ); let item_location_count = item_location_trees.iter().fold( item_location_trees.len(), |item_location_count_acc, item_location_tree| { item_location_count_acc + item_location_tree.item_location_count() }, ); ItemLocationsAndInteractions::new( item_location_trees, item_to_item_interactions, item_location_count, #[cfg(feature = "output_progress")] item_location_to_item_id_sets, ) } // TODO: Refactor -- there is a lot of duplication between this method and // `item_locations_and_interactions_example` #[cfg(all(feature = "item_interactions", feature = "item_state_example"))] pub fn item_locations_and_interactions_current( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, ) -> ItemLocationsAndInteractions where E: 'static, { // Build the flattened hierarchy. // // Regardless of how nested each `ItemLocation` is, the map will have an entry // for it. // // The entry key is the `ItemLocation`, and the values are a list of its direct // descendent `ItemLocation`s. // // This means a lot of cloning of `ItemLocation`s. let item_interactions_ctx = ItemInteractionsCtx { item_location_direct_descendents: BTreeMap::new(), item_to_item_interactions: IndexMap::with_capacity(self.graph().node_count()), // Rough estimate that each item has about 4 item locations // // * 2 `ItemLocationAncestors`s for from, 2 for to. // * Some may have more, but we also combine `ItemLocation`s. // // After the `ItemLocationTree`s are constructed, we'll have an accurate // number, but they are being constructed at the same time as this map. #[cfg(feature = "output_progress")] item_location_to_item_id_sets: HashMap::with_capacity(self.graph().node_count() * 4), }; let item_interactions_ctx = self .graph() .iter() // Note: This will silently drop the item locations if `interactions_try_current` fails // to return. .filter_map(|item| { item.interactions_try_current(params_specs, mapping_fn_reg, resources) .ok() .map(|item_interactions_current_or_example| { (item.id(), item_interactions_current_or_example) }) }) .fold( item_interactions_ctx, |item_interactions_ctx, (item_id, item_interactions_current_or_example)| { let ItemInteractionsCtx { mut item_location_direct_descendents, mut item_to_item_interactions, #[cfg(feature = "output_progress")] mut item_location_to_item_id_sets, } = item_interactions_ctx; // TODO: we need to hide the nodes if they came from `Example`. let item_interactions_current_or_example = match item_interactions_current_or_example { ItemInteractionsCurrentOrExample::Current( item_interactions_current, ) => item_interactions_current.into_inner(), ItemInteractionsCurrentOrExample::Example( item_interactions_example, ) => item_interactions_example.into_inner(), }; item_location_descendents_populate( &item_interactions_current_or_example, &mut item_location_direct_descendents, ); #[cfg(feature = "output_progress")] item_interactions_current_or_example .iter() .for_each(|item_interaction| match &item_interaction { ItemInteraction::Push(item_interaction_push) => item_interaction_push .location_from() .iter() .last() .into_iter() .chain(item_interaction_push.location_to().iter().last()) .for_each(|item_location| { item_location_to_item_id_sets_insert( &mut item_location_to_item_id_sets, item_location, item_id, ) }), ItemInteraction::Pull(item_interaction_pull) => item_interaction_pull .location_client() .iter() .last() .into_iter() .chain(item_interaction_pull.location_server().iter().last()) .for_each(|item_location| { item_location_to_item_id_sets_insert( &mut item_location_to_item_id_sets, item_location, item_id, ) }), ItemInteraction::Within(item_interaction_within) => { item_interaction_within .location() .iter() .last() .into_iter() .for_each(|item_location| { item_location_to_item_id_sets_insert( &mut item_location_to_item_id_sets, item_location, item_id, ) }) } }); item_to_item_interactions .insert(item_id.clone(), item_interactions_current_or_example); ItemInteractionsCtx { item_location_direct_descendents, item_to_item_interactions, #[cfg(feature = "output_progress")] item_location_to_item_id_sets, } }, ); let ItemInteractionsCtx { item_location_direct_descendents, item_to_item_interactions, #[cfg(feature = "output_progress")] item_location_to_item_id_sets, } = item_interactions_ctx; let item_locations_top_level = item_location_direct_descendents .keys() .filter(|item_location| { // this item_location is not in any descendents !item_location_direct_descendents .values() .any(|item_location_descendents| { item_location_descendents.contains(item_location) }) }) .cloned() .collect::<Vec<ItemLocation>>(); let item_locations_top_level_len = item_locations_top_level.len(); let (_item_location_direct_descendents, item_location_trees) = item_locations_top_level.into_iter().fold( ( item_location_direct_descendents, Vec::with_capacity(item_locations_top_level_len), ), |(mut item_location_direct_descendents, mut item_location_trees), item_location| { let item_location_tree = item_location_tree_collect( &mut item_location_direct_descendents, item_location, ); item_location_trees.push(item_location_tree); (item_location_direct_descendents, item_location_trees) }, ); let item_location_count = item_location_trees.iter().fold( item_location_trees.len(), |item_location_count_acc, item_location_tree| { item_location_count_acc + item_location_tree.item_location_count() }, ); ItemLocationsAndInteractions::new( item_location_trees, item_to_item_interactions, item_location_count, #[cfg(feature = "output_progress")] item_location_to_item_id_sets, ) } } #[cfg(all( feature = "item_interactions", feature = "item_state_example", feature = "output_progress", ))] fn item_location_to_item_id_sets_insert( item_location_to_item_id_sets: &mut HashMap<ItemLocation, HashSet<ItemId>>, item_location: &ItemLocation, item_id: &ItemId, ) { if let Some(item_id_set) = item_location_to_item_id_sets.get_mut(item_location) { item_id_set.insert(item_id.clone()); } else { let mut item_id_set = HashSet::new(); item_id_set.insert(item_id.clone()); item_location_to_item_id_sets.insert(item_location.clone(), item_id_set); } } #[cfg(all(feature = "item_interactions", feature = "item_state_example",))] fn item_location_descendents_populate( item_interactions_current_or_example: &[ItemInteraction], item_location_direct_descendents: &mut BTreeMap<ItemLocation, BTreeSet<ItemLocation>>, ) { item_interactions_current_or_example.iter().for_each( |item_interaction| match &item_interaction { ItemInteraction::Push(item_interaction_push) => { item_location_descendents_insert( item_location_direct_descendents, item_interaction_push.location_from(), ); item_location_descendents_insert( item_location_direct_descendents, item_interaction_push.location_to(), ); } ItemInteraction::Pull(item_interaction_pull) => { item_location_descendents_insert( item_location_direct_descendents, item_interaction_pull.location_client(), ); item_location_descendents_insert( item_location_direct_descendents, item_interaction_pull.location_server(), ); } ItemInteraction::Within(item_interaction_within) => { item_location_descendents_insert( item_location_direct_descendents, item_interaction_within.location(), ); } }, ); } /// Recursively constructs an `ItemLocationTree`. #[cfg(all(feature = "item_interactions", feature = "item_state_example"))] fn item_location_tree_collect( item_location_direct_descendents: &mut BTreeMap<ItemLocation, BTreeSet<ItemLocation>>, item_location_parent: ItemLocation, ) -> ItemLocationTree { match item_location_direct_descendents.remove_entry(&item_location_parent) { Some((item_location, item_location_children)) => { let children = item_location_children .into_iter() .map(|item_location_child| { item_location_tree_collect( item_location_direct_descendents, item_location_child, ) }) .collect::<Vec<ItemLocationTree>>(); ItemLocationTree::new(item_location, children) } // Should never be reached. None => ItemLocationTree::new(item_location_parent, Vec::new()), } } /// Inserts / extends the `item_location_direct_descendents` with an entry for /// each `ItemLocation` and its direct `ItemLocation` descendents. #[cfg(all(feature = "item_interactions", feature = "item_state_example"))] fn item_location_descendents_insert( item_location_direct_descendents: &mut BTreeMap<ItemLocation, BTreeSet<ItemLocation>>, item_location_ancestors: &[ItemLocation], ) { // Each subsequent `ItemLocation` in `location_from` is a child of the previous // `ItemLocation`. let item_location_iter = item_location_ancestors.iter(); let item_location_child_iter = item_location_ancestors.iter().skip(1); item_location_iter.zip(item_location_child_iter).for_each( |(item_location, item_location_child)| { // Save one clone by not using `BTreeSet::entry` if let Some(item_location_children) = item_location_direct_descendents.get_mut(item_location) { if !item_location_children.contains(item_location_child) { item_location_children.insert(item_location_child.clone()); } } else { let mut item_location_children = BTreeSet::new(); item_location_children.insert(item_location_child.clone()); item_location_direct_descendents .insert(item_location.clone(), item_location_children); } // Add an empty set for the child `ItemLocation`. if !item_location_direct_descendents.contains_key(item_location_child) { item_location_direct_descendents .insert(item_location_child.clone(), BTreeSet::new()); } }, ); } /// Accumulates the links between #[cfg(all(feature = "item_interactions", feature = "item_state_example"))] struct ItemInteractionsCtx { /// Map from each `ItemLocation` to all of its direct descendents collected /// from all items. item_location_direct_descendents: BTreeMap<ItemLocation, BTreeSet<ItemLocation>>, /// Map from each item to each of its `ItemInteractions`. item_to_item_interactions: IndexMap<ItemId, Vec<ItemInteraction>>, /// Tracks the items that referred to this item location. #[cfg(feature = "output_progress")] item_location_to_item_id_sets: HashMap<ItemLocation, HashSet<ItemId>>, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/flow_rt/src/item_graph.rs
crate/flow_rt/src/item_graph.rs
use std::{ fmt::Debug, ops::{Deref, DerefMut}, }; use peace_data::fn_graph::FnGraph; use peace_resource_rt::states::{States, StatesSerde}; use peace_rt_model::ItemBoxed; /// Graph of all [`Item`]s, `FnGraph<ItemBoxed<E>>` newtype. /// /// [`Item`]: peace_cfg::Item #[derive(Debug)] pub struct ItemGraph<E>(FnGraph<ItemBoxed<E>>); // Manual implementation because derive requires `E` to be `Clone`, // which causes `graph.clone()` to call `FnGraph::clone`. impl<E> Clone for ItemGraph<E> { fn clone(&self) -> Self { Self(self.0.clone()) } } impl<E> PartialEq for ItemGraph<E> where E: 'static, { fn eq(&self, other: &Self) -> bool { self.0 == other.0 } } impl<E> Eq for ItemGraph<E> where E: 'static {} impl<E> ItemGraph<E> { /// Returns the inner [`FnGraph`]. pub fn into_inner(self) -> FnGraph<ItemBoxed<E>> { self.0 } /// Returns a user-friendly serializable states map. /// /// This will contain an entry for all items, in order of flow item /// insertion, whether or not a state exists in the provided `states` map. pub fn states_serde<ValueT, TS>(&self, states: &States<TS>) -> StatesSerde<ValueT> where ValueT: Clone + Debug + PartialEq + Eq, E: 'static, { StatesSerde::from_iter(self.0.iter_insertion().map(|item| { let item_id = item.id(); (item_id.clone(), states.get_raw(item_id).cloned()) })) } } impl<E> Deref for ItemGraph<E> { type Target = FnGraph<ItemBoxed<E>>; fn deref(&self) -> &Self::Target { &self.0 } } impl<E> DerefMut for ItemGraph<E> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<E> From<FnGraph<ItemBoxed<E>>> for ItemGraph<E> { fn from(graph: FnGraph<ItemBoxed<E>>) -> Self { Self(graph) } } impl<'graph, ValueT, E> From<&'graph ItemGraph<E>> for StatesSerde<ValueT> where ValueT: Clone + Debug + PartialEq + Eq, E: 'static, { fn from(graph: &'graph ItemGraph<E>) -> Self { StatesSerde::from_iter(graph.iter_insertion().map(|item| (item.id().clone(), None))) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/flow_rt/src/item_graph_builder.rs
crate/flow_rt/src/item_graph_builder.rs
use std::ops::{Deref, DerefMut}; use peace_data::fn_graph::FnGraphBuilder; use peace_rt_model::ItemBoxed; use crate::ItemGraph; /// Builder for an [`ItemGraph`], `FnGraphBuilder<ItemBoxed<E>>` /// newtype. #[derive(Debug)] pub struct ItemGraphBuilder<E>(FnGraphBuilder<ItemBoxed<E>>); impl<E> ItemGraphBuilder<E> { /// Returns a new `ItemGraphBuilder`. pub fn new() -> Self { Self::default() } /// Returns the inner [`FnGraphBuilder`]. pub fn into_inner(self) -> FnGraphBuilder<ItemBoxed<E>> { self.0 } /// Builds and returns the [`ItemGraph`]. pub fn build(self) -> ItemGraph<E> { ItemGraph::from(self.0.build()) } } impl<E> Default for ItemGraphBuilder<E> { fn default() -> Self { Self(FnGraphBuilder::default()) } } impl<E> Deref for ItemGraphBuilder<E> { type Target = FnGraphBuilder<ItemBoxed<E>>; fn deref(&self) -> &Self::Target { &self.0 } } impl<E> DerefMut for ItemGraphBuilder<E> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<E> From<FnGraphBuilder<ItemBoxed<E>>> for ItemGraphBuilder<E> { fn from(graph: FnGraphBuilder<ItemBoxed<E>>) -> Self { Self(graph) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/diff/src/lib.rs
crate/diff/src/lib.rs
//! Types to represent changed values. pub use crate::{changeable::Changeable, equality::Equality, maybe_eq::MaybeEq, tracked::Tracked}; mod changeable; mod equality; mod maybe_eq; mod tracked;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/diff/src/tracked.rs
crate/diff/src/tracked.rs
use std::hash::{Hash, Hasher}; use serde::{Deserialize, Serialize}; use crate::{Equality, MaybeEq}; /// Tracks the known state of a value. #[derive(Clone, Debug, Deserialize, Serialize, Eq)] pub enum Tracked<T> { /// Value does not exist. None, /// Value exists, but its content is not known. Unknown, /// Value exists. Known(T), } impl<T> PartialEq for Tracked<T> where T: PartialEq, { fn eq(&self, other: &Self) -> bool { match (self, other) { // Both non-existent values. (Self::None, Self::None) => true, // Both known values with info. (Self::Known(t_self), Self::Known(t_other)) => t_self.eq(t_other), // One known value and one non-existent, or // Any unknown value. (Self::Known(_), Self::None) | (Self::None, Self::Known(_)) | (_, Self::Unknown) | (Self::Unknown, _) => false, } } } impl<T> Hash for Tracked<T> where T: Hash, { fn hash<H: Hasher>(&self, state: &mut H) { match self { Self::None => 0.hash(state), Self::Known(t) => t.hash(state), Self::Unknown => 2.hash(state), } } } impl<T> MaybeEq for Tracked<T> where T: MaybeEq, { fn maybe_eq(&self, other: &Self) -> Equality { match (self, other) { // Both non-existent values. (Self::None, Self::None) => Equality::Equal, // Both known values with info. (Self::Known(t_self), Self::Known(t_other)) => t_self.maybe_eq(t_other), // One known value and one non-existent. (Self::Known(_), Self::None) | (Self::None, Self::Known(_)) => Equality::NotEqual, // Any unknown value. (_, Self::Unknown) | (Self::Unknown, _) => Equality::Unknown, } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/diff/src/changeable.rs
crate/diff/src/changeable.rs
use serde::{Deserialize, Serialize}; use crate::{Equality, MaybeEq, Tracked}; /// Represents a changeable value. /// /// The `from` or `to` values are [`Tracked`] values, so the following cases /// mean the value is unchanged: /// /// * Both values are [`Tracked::None`] /// * Both values are [`Tracked::Known`]`(t)`, and both `t`s are equal. /// /// When either value is [`Tracked::Unknown`], then its [`Equality`] is /// [`Unknown`]. /// /// # Design Note /// /// This is deliberately called `Changeable` instead of `Change`, because /// `Change` implies there *is* a change, whereas `Changeable` means there may /// be one. #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] pub struct Changeable<T> { /// Current value. pub from: Tracked<T>, /// Next value. pub to: Tracked<T>, } impl<T> Changeable<T> where T: MaybeEq, { /// Returns a new `Changeable` value. /// /// See [`Changeable::known`] if both values are known. pub fn new(from: Tracked<T>, to: Tracked<T>) -> Self { Self { from, to } } /// Returns a new `Changeable` value. /// /// See [`Changeable::known`] if both values are known. pub fn known(from: T, to: T) -> Self { let from = Tracked::Known(from); let to = Tracked::Known(to); Self { from, to } } /// Returns the equality of the `from` and `to` values. pub fn equality(&self) -> Equality { <Tracked<T> as MaybeEq>::maybe_eq(&self.from, &self.to) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/diff/src/maybe_eq.rs
crate/diff/src/maybe_eq.rs
use std::{ collections::{BTreeMap, BTreeSet, HashMap, HashSet, LinkedList, VecDeque}, ops::ControlFlow, }; use crate::Equality; /// Types that may be equal. /// /// This trait and [`Equality`] represent when two values are known to exist, /// but their content is not known. pub trait MaybeEq<Rhs = Self> where Rhs: ?Sized, { fn maybe_eq(&self, other: &Rhs) -> Equality; } macro_rules! maybe_eq_impl { ($($name:tt,)+) => { $( impl MaybeEq for $name { fn maybe_eq(&self, other: &Self) -> Equality { Equality::from(self == other) } } )+ }; } macro_rules! maybe_eq_impl_list { ($($name:tt<$param:ident>,)+) => { $( impl<$param> MaybeEq for $name<$param> where $param: PartialEq { /// Note that this implementation uses `PartialEq` to determine [`Equality`]. /// /// There is no attempt to match elements together then do an element-wise /// comparison, as the order of elements affects comparison, and it is up to consumers to manually /// implement that level of accuracy. fn maybe_eq(&self, other: &Self) -> Equality { Equality::from(self == other) } } )+ }; } macro_rules! maybe_eq_impl_set { ($($name:tt<$param:ident>,)+) => { $( impl<$param> MaybeEq for $name<$param> where $param: MaybeEq + Eq + std::hash::Hash { fn maybe_eq(&self, other: &Self) -> Equality { Equality::from(self == other) } } )+ }; } // We have to choose whether we implement this for `Map<K, V>` where `V: // MaybeEq` or `V: PartialEq`. // // It should be less limiting to do it for the former, as consumers may be // able to implement `MaybeEq` for `V`. If `V` is not in their control, then // they wouldn't be able to use `MaybeEq` or `Equality` for their map anyway, // and so would be using a `PartialEq` comparison. macro_rules! maybe_eq_impl_map { ($($name:tt<$key:ident, $value:ident> $(+ $bound:tt)*,)+) => { $( impl<$key, $value> MaybeEq for $name<$key, $value> where $key: Eq + std::hash::Hash $(+ $bound)*, $value: MaybeEq { fn maybe_eq(&self, other: &Self) -> Equality { if self.len() != other.len() { Equality::NotEqual } else { let equality = self.iter() .try_fold(Equality::Equal, |equality, (k1, v1)| { if let Some(v2) = other.get(k1) { match v1.maybe_eq(v2) { Equality::NotEqual => ControlFlow::Break(Equality::NotEqual), Equality::Equal => ControlFlow::Continue(equality), Equality::Unknown => ControlFlow::Continue(Equality::Unknown), } } else { ControlFlow::Break(Equality::NotEqual) } }); // https://github.com/rust-lang/rust/issues/82223 match equality { ControlFlow::Continue(equality) | ControlFlow::Break(equality) => equality, } } } } )+ }; } maybe_eq_impl! { (), bool, char, str, String, f32, f64, i128, i16, i32, i64, i8, isize, u128, u16, u32, u64, u8, usize, } maybe_eq_impl_list! { Vec<T>, VecDeque<T>, LinkedList<T>, } maybe_eq_impl_set! { HashSet<T>, BTreeSet<T>, } maybe_eq_impl_map! { HashMap<K, V>, BTreeMap<K, V> + Ord, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/diff/src/equality.rs
crate/diff/src/equality.rs
use std::{cmp::Ordering, fmt}; /// Represents whether a value is equal to another. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Equality { /// Values are not equal. NotEqual, /// Values are equal. Equal, /// Cannot determine equality of values. /// /// This is when either or both [`Tracked`] values are [`Tracked::Unknown`]. /// /// [`Tracked`]: crate::Tracked /// [`Tracked::Unknown`]: crate::Tracked::Unknown Unknown, } impl fmt::Display for Equality { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::NotEqual => "!=".fmt(f), Self::Equal => "==".fmt(f), Self::Unknown => "?=".fmt(f), } } } impl PartialOrd for Equality { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { // Currently using this order: // // ``` // NotEqual < Equal < Unknown // ``` match (self, other) { (Self::NotEqual, Self::NotEqual) => Some(Ordering::Equal), (Self::NotEqual, Self::Equal) => Some(Ordering::Less), (Self::NotEqual, Self::Unknown) => Some(Ordering::Less), (Self::Equal, Self::NotEqual) => Some(Ordering::Greater), (Self::Equal, Self::Equal) => Some(Ordering::Equal), (Self::Equal, Self::Unknown) => Some(Ordering::Less), (Self::Unknown, Self::NotEqual) => Some(Ordering::Greater), (Self::Unknown, Self::Equal) => Some(Ordering::Greater), (Self::Unknown, Self::Unknown) => None, } } } impl From<bool> for Equality { fn from(eq: bool) -> Self { if eq { Equality::Equal } else { Equality::NotEqual } } } impl From<Equality> for bool { fn from(equality: Equality) -> bool { match equality { Equality::NotEqual => false, Equality::Equal => true, Equality::Unknown => false, } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model_native/src/workspace.rs
crate/rt_model_native/src/workspace.rs
//! Types that store information about the directories that a command runs in. //! //! In the Peace framework, a command is run with the following contextual //! information: //! //! * The [`Workspace`] of a project that the command is built for. //! * A [`Profile`] (or namespace) for that project. //! * A workflow that the command is executing, identified by the [`FlowId`]. use peace_core::AppName; use peace_resource_rt::internal::WorkspaceDirs; use peace_rt_model_core::Error; use crate::{Storage, WorkspaceDirsBuilder, WorkspaceSpec}; /// Workspace that the `peace` tool runs in. #[derive(Clone, Debug)] pub struct Workspace { /// Name of the application that is run by end users. app_name: AppName, /// Convention-based directories in this workspace. dirs: WorkspaceDirs, /// File system storage access. storage: Storage, } impl Workspace { /// Prepares a workspace to run commands in. /// /// # Parameters /// /// * `app_name`: Name of the final application. /// * `workspace_spec`: Defines how to discover the workspace. pub fn new(app_name: AppName, workspace_spec: WorkspaceSpec) -> Result<Self, Error> { let dirs = WorkspaceDirsBuilder::build(&app_name, workspace_spec)?; let storage = Storage; Ok(Self { app_name, dirs, storage, }) } /// Returns the underlying data. pub fn into_inner(self) -> (AppName, WorkspaceDirs, Storage) { let Self { app_name, dirs, storage, } = self; (app_name, dirs, storage) } /// Returns a reference to the app name. pub fn app_name(&self) -> &AppName { &self.app_name } /// Returns a reference to the workspace's directories. pub fn dirs(&self) -> &WorkspaceDirs { &self.dirs } /// Returns a reference to the workspace's storage. pub fn storage(&self) -> &Storage { &self.storage } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model_native/src/lib.rs
crate/rt_model_native/src/lib.rs
#![cfg_attr(coverage_nightly, feature(coverage_attribute))] //! Runtime data types for the peace automation framework (native). //! //! Consumers should depend on the `peace_rt_model` crate, which re-exports //! same-named types, depending on whether a native or WASM target is used. // Re-exports pub use tokio_util::io::SyncIoBridge; pub use crate::{ storage::Storage, workspace::Workspace, workspace_dirs_builder::WorkspaceDirsBuilder, workspace_initializer::WorkspaceInitializer, workspace_spec::WorkspaceSpec, }; pub mod workspace; mod storage; mod workspace_dirs_builder; mod workspace_initializer; mod workspace_spec;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model_native/src/storage.rs
crate/rt_model_native/src/storage.rs
use std::{fmt::Debug, hash::Hash, io::Write, path::Path, sync::Mutex}; use peace_resource_rt::type_reg::{ common::UnknownEntriesSome, untagged::{DataTypeWrapper, TypeMapOpt, TypeReg}, }; use peace_rt_model_core::{Error, NativeError}; use serde::{de::DeserializeOwned, Serialize}; use tokio::{ fs::File, io::{AsyncReadExt, BufReader, BufWriter}, }; use tokio_util::io::SyncIoBridge; /// Wrapper around file system operations. #[derive(Clone, Debug)] pub struct Storage; impl Storage { /// Reads the file at the given path to string. /// /// Note: This does not check the file size, so it will use as much memory /// as the file size. /// /// # Parameters /// /// * `file_path`: Path to the file to read to string. pub async fn read_to_string(&self, file_path: &Path) -> Result<String, Error> { if file_path.exists() { let mut file = File::open(file_path).await.map_err( // Tests currently don't cover file system failure cases, // e.g. disk space limits. #[cfg_attr(coverage_nightly, coverage(off))] |error| { let path = file_path.to_path_buf(); Error::Native(NativeError::FileOpen { path, error }) }, )?; let mut buffer = String::new(); file.read_to_string(&mut buffer).await.map_err( #[cfg_attr(coverage_nightly, coverage(off))] |error| { Error::Native(NativeError::FileRead { error, path: file_path.to_path_buf(), }) }, )?; Ok(buffer) } else { Err(Error::ItemNotExists { path: file_path.to_path_buf(), }) } } /// Reads a serializable item from the given path. /// /// # Parameters /// /// * `thread_name`: Name of the thread to use to do the read operation. /// * `file_path`: Path to the file to read the serialized item. /// * `f_map_err`: Maps the deserialization error (if any) to an [`Error`]. pub async fn serialized_read<T, F>( &self, thread_name: String, file_path: &Path, f_map_err: F, ) -> Result<T, Error> where T: Serialize + DeserializeOwned + Send + Sync, F: FnOnce(serde_yaml::Error) -> Error + Send, { if file_path.exists() { let t = self .read_with_sync_api(thread_name, file_path, |file| { serde_yaml::from_reader::<_, T>(file).map_err(f_map_err) }) .await?; Ok(t) } else { Err(Error::ItemNotExists { path: file_path.to_path_buf(), }) } } /// Reads a serializable item from the given path if the file exists. /// /// # Parameters /// /// * `thread_name`: Name of the thread to use to do the read operation. /// * `file_path`: Path to the file to read the serialized item. /// * `f_map_err`: Maps the deserialization error (if any) to an [`Error`]. pub async fn serialized_read_opt<T, F>( &self, thread_name: String, file_path: &Path, f_map_err: F, ) -> Result<Option<T>, Error> where T: DeserializeOwned + Send + Sync, F: FnOnce(serde_yaml::Error) -> Error + Send, { if file_path.exists() { let t = self .read_with_sync_api(thread_name, file_path, |file| { serde_yaml::from_reader::<_, T>(file).map_err(f_map_err) }) .await?; Ok(Some(t)) } else { Ok(None) } } /// Deserializes a typemap from the given path if the file exists. /// /// # Parameters /// /// * `thread_name`: Name of the thread to use to do the read operation. /// * `type_reg`: Type registry with the stateful deserialization mappings. /// * `file_path`: Path to the file to read the serialized item. /// * `f_map_err`: Maps the deserialization error (if any) to an [`Error`]. pub async fn serialized_typemap_read_opt<K, BoxDT, F>( &self, thread_name: String, type_reg: &TypeReg<K, BoxDT>, file_path: &Path, f_map_err: F, ) -> Result<Option<TypeMapOpt<K, BoxDT, UnknownEntriesSome<serde_yaml::Value>>>, Error> where K: Clone + Debug + DeserializeOwned + Eq + Hash + Send + Sync + 'static, BoxDT: DataTypeWrapper + Send + 'static, F: FnOnce(serde_yaml::Error) -> Error + Send, { if file_path.exists() { let type_map_opt = self .read_with_sync_api(thread_name, file_path, |file| { let deserializer = serde_yaml::Deserializer::from_reader(file); let type_map_opt = type_reg .deserialize_map_opt_with_unknowns::<'_, serde_yaml::Value, _, _>( deserializer, ) .map_err(f_map_err)?; Result::<_, Error>::Ok(type_map_opt) }) .await?; Ok(Some(type_map_opt)) } else { Ok(None) } } /// Writes a serializable item to the given path. /// /// # Parameters /// /// * `thread_name`: Name of the thread to use to do the write operation. /// * `file_path`: Path to the file to store the serialized item. /// * `t`: Item to serialize. /// * `f_map_err`: Maps the serialization error (if any) to an [`Error`]. pub async fn serialized_write<T, F>( &self, thread_name: String, file_path: &Path, t: &T, f_map_err: F, ) -> Result<(), Error> where T: Serialize + Send + Sync, F: FnOnce(serde_yaml::Error) -> Error + Send, { self.write_with_sync_api(thread_name, file_path, |file| { serde_yaml::to_writer(file, t).map_err(f_map_err) }) .await?; Ok(()) } /// Serializes an item to a string. /// /// # Parameters /// /// * `t`: Item to serialize. /// * `f_map_err`: Maps the serialization error (if any) to an [`Error`]. pub fn serialized_write_string<T, F>(&self, t: &T, f_map_err: F) -> Result<String, Error> where T: Serialize + Send + Sync, F: FnOnce(serde_yaml::Error) -> Error + Send, { serde_yaml::to_string(t).map_err(f_map_err) } /// Reads from a file, bridging to libraries that take a synchronous `Write` /// type. /// /// This method buffers the write, and calls flush on the buffer when the /// passed in closure returns. pub async fn read_with_sync_api<'f, F, T, E>( &self, thread_name: String, file_path: &Path, f: F, ) -> Result<T, E> where F: FnOnce(&mut SyncIoBridge<BufReader<File>>) -> Result<T, E> + Send + 'f, T: Send, E: From<Error> + Send, { let file = File::open(file_path).await.map_err( // Tests currently don't cover file system failure cases, // e.g. disk space limits. #[cfg_attr(coverage_nightly, coverage(off))] |error| { let path = file_path.to_path_buf(); Error::Native(NativeError::FileOpen { path, error }) }, )?; let mut sync_io_bridge = SyncIoBridge::new(BufReader::new(file)); // `tokio::task::spawn_blocking` doesn't work because it needs the closure's // environment to be `'static` let t = std::thread::scope(move |s| { std::thread::Builder::new() .name(thread_name) .spawn_scoped(s, move || f(&mut sync_io_bridge)) .map_err(NativeError::StorageSyncThreadSpawn) .map_err(Error::Native)? .join() .map_err(Mutex::new) .map_err(NativeError::StorageSyncThreadJoin) .map_err(Error::Native)? })?; Ok(t) } /// Writes to a file, bridging to libraries that take a synchronous `Write` /// type. /// /// This method buffers the write, and calls flush on the buffer when the /// passed in closure returns. /// /// # Parameters /// /// * `thread_name`: Name of the thread to use to do the write operation. /// * `file_path`: Path to the file to store the serialized item. /// * `f`: Function that is given the `Write` implementation to call the /// sync API with. pub async fn write_with_sync_api<'f, F, T>( &self, thread_name: String, file_path: &Path, f: F, ) -> Result<T, Error> where F: FnOnce(&mut SyncIoBridge<BufWriter<File>>) -> Result<T, Error> + Send + 'f, T: Send, { let file = File::create(file_path).await.map_err( // Tests currently don't cover file system failure cases, // e.g. disk space limits. #[cfg_attr(coverage_nightly, coverage(off))] |error| { let path = file_path.to_path_buf(); NativeError::FileCreate { path, error } }, )?; let mut sync_io_bridge = SyncIoBridge::new(BufWriter::new(file)); // `tokio::task::spawn_blocking` doesn't work because it needs the closure's // environment to be `'static` let t = std::thread::scope(move |s| { std::thread::Builder::new() .name(thread_name) .spawn_scoped(s, move || { let t = f(&mut sync_io_bridge)?; sync_io_bridge.flush().map_err( // Tests currently don't cover file system failure cases, // e.g. disk space limits. #[cfg_attr(coverage_nightly, coverage(off))] |error| { let path = file_path.to_path_buf(); NativeError::FileWrite { path, error } }, )?; Result::<_, Error>::Ok(t) }) .map_err(NativeError::StorageSyncThreadSpawn) .map_err(Error::Native)? .join() .map_err(Mutex::new) .map_err(NativeError::StorageSyncThreadJoin) .map_err(Error::Native)? })?; Ok(t) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model_native/src/workspace_spec.rs
crate/rt_model_native/src/workspace_spec.rs
use std::{ffi::OsString, path::PathBuf}; /// Describes how to discover the workspace directory. #[derive(Clone, Debug, PartialEq, Eq)] pub enum WorkspaceSpec { /// Use the exe working directory as the workspace directory. /// /// The working directory is the directory that the user ran the program in. /// /// # WASM /// /// When compiled to Web assembly (`target_arch = "wasm32"`), this variant /// indicates no prefix to keys within local storage. WorkingDir, /// Use a specified path. Path(PathBuf), /// Traverse up from the working directory until the given file is found. /// /// The workspace directory is the parent directory that contains a file or /// directory with the provided name. FirstDirWithFile(OsString), }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model_native/src/workspace_initializer.rs
crate/rt_model_native/src/workspace_initializer.rs
use std::{fmt::Debug, hash::Hash, path::Path}; use futures::{stream, StreamExt, TryStreamExt}; use peace_resource_rt::{ internal::{FlowParamsFile, ProfileParamsFile, WorkspaceParamsFile}, type_reg::untagged::{TypeMapOpt, TypeReg}, }; use peace_rt_model_core::{ params::{FlowParams, ProfileParams, WorkspaceParams}, Error, NativeError, }; use serde::{de::DeserializeOwned, Serialize}; use crate::Storage; /// Logic to create peace directories and reads/writes initialization params. /// /// # Type Parameters /// /// * `WorkspaceInit`: Parameters to initialize the workspace. /// /// These are parameters common to the workspace. Examples: /// /// - Organization username. /// - Repository URL for multiple environments. /// /// This may be `()` if there are no parameters common to the workspace. /// /// * `ProfileInit`: Parameters to initialize the profile. /// /// These are parameters specific to a profile, but common to flows within /// that profile. Examples: /// /// - Environment specific credentials. /// - URL to publish / download an artifact. /// /// This may be `()` if there are no profile specific parameters. /// /// * `FlowInit`: Parameters to initialize the flow. /// /// These are parameters specific to a flow. Examples: /// /// - Configuration to skip warnings for the particular flow. /// /// This may be `()` if there are no flow specific parameters. #[derive(Debug)] pub struct WorkspaceInitializer; impl WorkspaceInitializer { /// Creates directories used by the peace framework. pub async fn dirs_create<'f, I>(dirs: I) -> Result<(), Error> where I: IntoIterator<Item = &'f Path>, { stream::iter(dirs) .map(Result::<_, Error>::Ok) .try_for_each(|dir| async move { tokio::fs::create_dir_all(dir).await.map_err(|error| { let path = dir.to_path_buf(); Error::Native(NativeError::WorkspaceDirCreate { path, error }) }) }) .await } pub async fn workspace_params_serialize<K>( storage: &Storage, workspace_params: &WorkspaceParams<K>, workspace_params_file: &WorkspaceParamsFile, ) -> Result<(), Error> where K: Eq + Hash + Serialize + Send + Sync, { storage .serialized_write( "workspace_params_serialize".to_string(), workspace_params_file, workspace_params, Error::WorkspaceParamsSerialize, ) .await } // TODO: for every variant in `K`, we need to deserialize it // Also do this for profile_params and flow_params // // The TypeReg doesn't know what the Value type is. // *that*s why we had the ws_and_profile_params augment in envman. pub async fn workspace_params_deserialize<K>( storage: &Storage, type_reg: &TypeReg<K>, workspace_params_file: &WorkspaceParamsFile, ) -> Result<Option<WorkspaceParams<K>>, Error> where K: Clone + Debug + Eq + Hash + DeserializeOwned + Send + Sync + 'static, { storage .serialized_typemap_read_opt( "workspace_params_deserialize".to_string(), type_reg, workspace_params_file, Error::WorkspaceParamsDeserialize, ) .await .map(|type_map_opt| { type_map_opt .map(TypeMapOpt::into_type_map) .map(WorkspaceParams::from) }) } pub async fn profile_params_serialize<K>( storage: &Storage, profile_params: &ProfileParams<K>, profile_params_file: &ProfileParamsFile, ) -> Result<(), Error> where K: Eq + Hash + Serialize + Send + Sync, { storage .serialized_write( "profile_params_serialize".to_string(), profile_params_file, profile_params, Error::ProfileParamsSerialize, ) .await } pub async fn profile_params_deserialize<K>( storage: &Storage, type_reg: &TypeReg<K>, profile_params_file: &ProfileParamsFile, ) -> Result<Option<ProfileParams<K>>, Error> where K: Clone + Debug + Eq + Hash + DeserializeOwned + Send + Sync + 'static, { storage .serialized_typemap_read_opt( "profile_params_deserialize".to_string(), type_reg, profile_params_file, Error::ProfileParamsDeserialize, ) .await .map(|type_map_opt| { type_map_opt .map(TypeMapOpt::into_type_map) .map(ProfileParams::from) }) } pub async fn flow_params_serialize<K>( storage: &Storage, flow_params: &FlowParams<K>, flow_params_file: &FlowParamsFile, ) -> Result<(), Error> where K: Eq + Hash + Serialize + Send + Sync, { storage .serialized_write( "flow_params_serialize".to_string(), flow_params_file, flow_params, Error::FlowParamsSerialize, ) .await } pub async fn flow_params_deserialize<K>( storage: &Storage, type_reg: &TypeReg<K>, flow_params_file: &FlowParamsFile, ) -> Result<Option<FlowParams<K>>, Error> where K: Clone + Debug + Eq + Hash + DeserializeOwned + Send + Sync + 'static, { storage .serialized_typemap_read_opt( "flow_params_deserialize".to_string(), type_reg, flow_params_file, Error::FlowParamsDeserialize, ) .await .map(|type_map_opt| { type_map_opt .map(TypeMapOpt::into_type_map) .map(FlowParams::from) }) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model_native/src/workspace_dirs_builder.rs
crate/rt_model_native/src/workspace_dirs_builder.rs
use std::{ ffi::OsStr, path::{Path, PathBuf}, }; use peace_core::AppName; use peace_resource_rt::{ internal::WorkspaceDirs, paths::{PeaceAppDir, PeaceDir}, }; use peace_rt_model_core::{Error, NativeError}; use crate::WorkspaceSpec; /// Computes paths of well-known directories for a workspace. #[derive(Debug)] pub struct WorkspaceDirsBuilder; impl WorkspaceDirsBuilder { /// Computes [`WorkspaceDirs`] paths. pub fn build( app_name: &AppName, workspace_spec: WorkspaceSpec, ) -> Result<WorkspaceDirs, Error> { use peace_resource_rt::paths::WorkspaceDir; let workspace_dir = { let working_dir = std::env::current_dir() .map_err(NativeError::WorkingDirRead) .map_err(Error::Native)?; let workspace_dir = match workspace_spec { WorkspaceSpec::WorkingDir => working_dir, WorkspaceSpec::Path(path) => path, WorkspaceSpec::FirstDirWithFile(file_name) => { Self::first_dir_with_file(&working_dir, &file_name).ok_or({ Error::Native(NativeError::WorkspaceFileNotFound { working_dir, file_name, }) })? } }; WorkspaceDir::new(workspace_dir) }; let peace_dir = PeaceDir::from(&workspace_dir); let peace_app_dir = PeaceAppDir::from((&peace_dir, app_name)); Ok(WorkspaceDirs::new(workspace_dir, peace_dir, peace_app_dir)) } fn first_dir_with_file(working_dir: &Path, path: &OsStr) -> Option<PathBuf> { let mut candidate_dir = working_dir.to_path_buf(); loop { let candidate_marker = candidate_dir.join(path); if candidate_marker.exists() { return Some(candidate_dir); } // pop() returns false if there is no parent dir. if !candidate_dir.pop() { return None; } } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt/src/lib.rs
crate/rt/src/lib.rs
//! Runtime logic for the peace automation library. /// Maximum number of items to execute simultaneously. /// /// 64 is arbitrarily chosen, as there is not enough data to inform us what a /// suitable number is. pub const BUFFERED_FUTURES_MAX: usize = 64; pub mod cmd_blocks; pub mod cmds;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt/src/cmd_blocks.rs
crate/rt/src/cmd_blocks.rs
//! Blocks of logic that run one [`Item`] function //! //! [`Item`]: peace_cfg::Item pub use self::{ apply_exec_cmd_block::ApplyExecCmdBlock, apply_state_sync_check_cmd_block::ApplyStateSyncCheckCmdBlock, diff_cmd_block::{DiffCmdBlock, DiffCmdBlockStatesTsExt}, states_clean_insertion_cmd_block::StatesCleanInsertionCmdBlock, states_current_read_cmd_block::StatesCurrentReadCmdBlock, states_discover_cmd_block::StatesDiscoverCmdBlock, states_goal_read_cmd_block::StatesGoalReadCmdBlock, }; pub mod apply_exec_cmd_block; mod apply_state_sync_check_cmd_block; mod diff_cmd_block; mod states_clean_insertion_cmd_block; mod states_current_read_cmd_block; mod states_discover_cmd_block; mod states_goal_read_cmd_block;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt/src/cmds.rs
crate/rt/src/cmds.rs
//! Commands to provide user-facing output. //! //! Commands directly underneath this module write to the `OutputWrite` //! provided in the [`CmdContext`]. Commands at this level are intended to //! provide the information requested to the user; errors should inform the user //! of any steps that have to be run before the command is able to fulfill the //! information request. //! //! [`CmdContext`]: crate::CmdContext pub use self::{ apply_stored_state_sync::ApplyStoredStateSync, clean_cmd::CleanCmd, diff_cmd::{DiffCmd, DiffInfoSpec, DiffStateSpec}, ensure_cmd::EnsureCmd, states_current_read_cmd::StatesCurrentReadCmd, states_current_stored_display_cmd::StatesCurrentStoredDisplayCmd, states_discover_cmd::StatesDiscoverCmd, states_goal_display_cmd::StatesGoalDisplayCmd, states_goal_read_cmd::StatesGoalReadCmd, }; mod apply_stored_state_sync; mod clean_cmd; mod diff_cmd; mod ensure_cmd; mod states_current_read_cmd; mod states_current_stored_display_cmd; mod states_discover_cmd; mod states_goal_display_cmd; mod states_goal_read_cmd;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt/src/cmds/states_current_read_cmd.rs
crate/rt/src/cmds/states_current_read_cmd.rs
use std::{fmt::Debug, marker::PhantomData}; use peace_cmd_ctx::{CmdCtxSpsf, CmdCtxTypes}; use peace_cmd_model::CmdOutcome; use peace_cmd_rt::{CmdBlockWrapper, CmdExecution}; use peace_resource_rt::states::StatesCurrentStored; use crate::cmd_blocks::StatesCurrentReadCmdBlock; /// Reads [`StatesCurrentStored`]s from storage. #[derive(Debug)] pub struct StatesCurrentReadCmd<CmdCtxTypesT>(PhantomData<CmdCtxTypesT>); impl<CmdCtxTypesT> StatesCurrentReadCmd<CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Reads [`StatesCurrentStored`]s from storage. /// /// Either [`StatesCurrentStoredDiscoverCmd`] or [`StatesDiscoverCmd`] must /// have run prior to this command to read the state. /// /// [`StatesCurrentStoredDiscoverCmd`]: crate::StatesCurrentStoredDiscoverCmd /// [`StatesDiscoverCmd`]: crate::StatesDiscoverCmd pub async fn exec<'ctx>( cmd_ctx: &mut CmdCtxSpsf<'ctx, CmdCtxTypesT>, ) -> Result< CmdOutcome<StatesCurrentStored, <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > where CmdCtxTypesT: 'ctx, { let cmd_execution_builder = CmdExecution::<StatesCurrentStored, _>::builder() .with_cmd_block(CmdBlockWrapper::new( StatesCurrentReadCmdBlock::new(), std::convert::identity, )); #[cfg(feature = "output_progress")] let cmd_execution_builder = cmd_execution_builder.with_progress_render_enabled(false); cmd_execution_builder.build().exec(cmd_ctx).await } } impl<CmdCtxTypesT> Default for StatesCurrentReadCmd<CmdCtxTypesT> { fn default() -> Self { Self(PhantomData) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt/src/cmds/states_goal_read_cmd.rs
crate/rt/src/cmds/states_goal_read_cmd.rs
use std::{fmt::Debug, marker::PhantomData}; use peace_cmd_ctx::{CmdCtxSpsf, CmdCtxTypes}; use peace_cmd_model::CmdOutcome; use peace_cmd_rt::{CmdBlockWrapper, CmdExecution}; use peace_resource_rt::states::StatesGoalStored; use crate::cmd_blocks::StatesGoalReadCmdBlock; /// Reads [`StatesGoalStored`]s from storage. #[derive(Debug)] pub struct StatesGoalReadCmd<CmdCtxTypesT>(PhantomData<CmdCtxTypesT>); impl<CmdCtxTypesT> StatesGoalReadCmd<CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Reads [`StatesGoalStored`]s from storage. /// /// [`StatesDiscoverCmd`] must have run prior to this command to read the /// state. /// /// [`StatesDiscoverCmd`]: crate::StatesDiscoverCmd pub async fn exec<'ctx>( cmd_ctx: &mut CmdCtxSpsf<'ctx, CmdCtxTypesT>, ) -> Result< CmdOutcome<StatesGoalStored, <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > where CmdCtxTypesT: 'ctx, { let cmd_execution_builder = CmdExecution::<StatesGoalStored, _>::builder().with_cmd_block( CmdBlockWrapper::new(StatesGoalReadCmdBlock::new(), std::convert::identity), ); #[cfg(feature = "output_progress")] let cmd_execution_builder = cmd_execution_builder.with_progress_render_enabled(false); cmd_execution_builder.build().exec(cmd_ctx).await } } impl<CmdCtxTypesT> Default for StatesGoalReadCmd<CmdCtxTypesT> { fn default() -> Self { Self(PhantomData) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt/src/cmds/apply_stored_state_sync.rs
crate/rt/src/cmds/apply_stored_state_sync.rs
/// Whether to block an apply operation if stored states are not in sync with /// discovered state. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ApplyStoredStateSync { /// Neither stored current states nor stored goal state need to be in sync /// with the discovered current states and goal state. None, /// The stored current states must be in sync with the discovered current /// state for the apply to proceed. /// /// The stored goal state does not need to be in sync with the discovered /// goal state. Current, /// The stored goal state must be in sync with the discovered goal /// state for the apply to proceed. /// /// The stored current states does not need to be in sync with the /// discovered current state. /// /// For `CleanCmd`, this variant is equivalent to `None`. Goal, /// Both stored current states and stored goal state must be in sync with /// the discovered current states and goal state for the apply to /// proceed. /// /// For `CleanCmd`, this variant is equivalent to `Current`. Both, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt/src/cmds/clean_cmd.rs
crate/rt/src/cmds/clean_cmd.rs
use std::{fmt::Debug, marker::PhantomData}; use peace_cmd_ctx::{CmdCtxSpsf, CmdCtxSpsfFields, CmdCtxTypes}; use peace_cmd_model::CmdOutcome; use peace_cmd_rt::{CmdBlockWrapper, CmdExecution}; use peace_flow_rt::ItemGraph; use peace_resource_rt::{ paths::{FlowDir, StatesCurrentFile}, resources::ts::SetUp, states::{States, StatesCleaned, StatesCleanedDry, StatesPrevious}, Resources, }; use peace_rt_model::Storage; use crate::{ cmd_blocks::{ apply_exec_cmd_block::StatesTsApplyExt, ApplyExecCmdBlock, ApplyStateSyncCheckCmdBlock, StatesCleanInsertionCmdBlock, StatesCurrentReadCmdBlock, StatesDiscoverCmdBlock, }, cmds::ApplyStoredStateSync, }; #[derive(Debug)] pub struct CleanCmd<CmdCtxTypesT>(PhantomData<CmdCtxTypesT>); impl<CmdCtxTypesT> CleanCmd<CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Conditionally runs [`Item::apply_exec_dry`] for each [`Item`]. /// /// In practice this runs [`Item::apply_check`], and only runs /// [`apply_exec_dry`] if execution is required. /// /// # Design /// /// The grouping of item functions run for a `Clean` execution to work /// is as follows: /// /// 1. Run [`StatesDiscoverCmd::current`] for all `Item`s in the *forward* /// direction. /// /// This populates `resources` with `Current<IS::State>`, needed for /// `Item::try_state_current` during `ItemRt::clean_prepare`. /// /// 2. In the *reverse* direction, for each `Item` run /// `ItemRt::clean_prepare`, which runs: /// /// 1. `Item::try_state_current`, which resolves parameters from the /// *current* state. /// 2. `Item::state_goal` /// 3. `Item::apply_check` /// /// 3. For `Item`s that return `ApplyCheck::ExecRequired`, run /// `Item::apply_exec_dry`. /// /// [`apply_exec_dry`]: peace_cfg::Item::apply_exec_dry /// [`Item::apply_check`]: peace_cfg::Item::apply_check /// [`Item::apply_exec_dry`]: peace_cfg::ItemRt::apply_exec_dry /// [`Item`]: peace_cfg::Item pub async fn exec_dry<'ctx>( cmd_ctx: &mut CmdCtxSpsf<'ctx, CmdCtxTypesT>, ) -> Result< CmdOutcome<StatesCleanedDry, <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > where CmdCtxTypesT: 'ctx, { Self::exec_dry_with(cmd_ctx, ApplyStoredStateSync::Both).await } /// Conditionally runs [`Item::apply_exec_dry`] for each [`Item`]. /// /// See [`Self::exec_dry`] for full documentation. /// /// This function exists so that this command can be executed as sub /// functionality of another command. pub async fn exec_dry_with<'ctx>( cmd_ctx: &mut CmdCtxSpsf<'ctx, CmdCtxTypesT>, apply_stored_state_sync: ApplyStoredStateSync, ) -> Result< CmdOutcome<StatesCleanedDry, <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > where CmdCtxTypesT: 'ctx, { let cmd_outcome = Self::exec_internal(cmd_ctx, apply_stored_state_sync).await?; let cmd_outcome = cmd_outcome.map(|clean_exec_change| match clean_exec_change { CleanExecChange::None => Default::default(), CleanExecChange::Some(states_previous_and_cleaned) => { let (states_previous, states_cleaned) = *states_previous_and_cleaned; cmd_ctx .fields_mut() .resources_mut() .insert::<StatesPrevious>(states_previous); states_cleaned } }); Ok(cmd_outcome) } /// Conditionally runs [`Item::apply_exec`] for each [`Item`]. /// /// In practice this runs [`Item::apply_check`], and only runs /// [`apply_exec`] if execution is required. /// /// # Design /// /// The grouping of item functions run for a `Clean` execution to work /// is as follows: /// /// 1. Run [`StatesDiscoverCmd::current`] for all `Item`s in the *forward* /// direction. /// /// This populates `resources` with `Current<IS::State>`, needed for /// `Item::try_state_current` during `ItemRt::clean_prepare`. /// /// 2. In the *reverse* direction, for each `Item` run /// `ItemRt::clean_prepare`, which runs: /// /// 1. `Item::try_state_current`, which resolves parameters from the /// *current* state. /// 2. `Item::state_goal` /// 3. `Item::apply_check` /// /// 3. For `Item`s that return `ApplyCheck::ExecRequired`, run /// `Item::apply_exec`. /// /// [`apply_exec`]: peace_cfg::Item::apply_exec /// [`Item::apply_check`]: peace_cfg::Item::apply_check /// [`Item::apply_exec`]: peace_cfg::ItemRt::apply_exec /// [`Item`]: peace_cfg::Item pub async fn exec<'ctx>( cmd_ctx: &mut CmdCtxSpsf<'ctx, CmdCtxTypesT>, ) -> Result< CmdOutcome<StatesCleaned, <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > where CmdCtxTypesT: 'ctx, { Self::exec_with(cmd_ctx, ApplyStoredStateSync::Both).await } /// Conditionally runs [`Item::apply_exec`] for each [`Item`]. /// /// See [`Self::exec`] for full documentation. /// /// This function exists so that this command can be executed as sub /// functionality of another command. pub async fn exec_with<'ctx, 'ctx_ref>( cmd_ctx: &'ctx_ref mut CmdCtxSpsf<'ctx, CmdCtxTypesT>, apply_stored_state_sync: ApplyStoredStateSync, ) -> Result< CmdOutcome<StatesCleaned, <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > where CmdCtxTypesT: 'ctx, { let cmd_outcome = Self::exec_internal(cmd_ctx, apply_stored_state_sync).await?; let CmdCtxSpsfFields { flow, ref mut resources, .. } = cmd_ctx.fields_mut(); let item_graph = flow.graph(); // We shouldn't serialize current if we returned from an interruption / error // handler. let cmd_outcome = cmd_outcome .map_async(|clean_exec_change| async move { match clean_exec_change { CleanExecChange::None => Ok(Default::default()), CleanExecChange::Some(states_previous_and_cleaned) => { let (states_previous, states_cleaned) = *states_previous_and_cleaned; Self::serialize_current(item_graph, resources, &states_cleaned).await?; resources.insert::<StatesPrevious>(states_previous); Ok(states_cleaned) } } }) .await; cmd_outcome.transpose() } /// Conditionally runs [`ApplyFns`]`::`[`exec`] for each [`Item`]. /// /// Same as [`Self::exec`], but does not change the type state, and returns /// [`StatesCleaned`]. /// /// [`exec`]: peace_cfg::ApplyFns::exec /// [`Item`]: peace_cfg::Item /// [`ApplyFns`]: peace_cfg::Item::ApplyFns async fn exec_internal<'ctx, 'ctx_ref, StatesTs>( cmd_ctx: &'ctx_ref mut CmdCtxSpsf<'ctx, CmdCtxTypesT>, apply_stored_state_sync: ApplyStoredStateSync, ) -> Result< CmdOutcome<CleanExecChange<StatesTs>, <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > where CmdCtxTypesT: 'ctx, StatesTs: StatesTsApplyExt + Debug + Send + Sync + Unpin + 'static, { let mut cmd_execution = { let mut cmd_execution_builder = CmdExecution::<CleanExecChange<StatesTs>, _>::builder() .with_cmd_block(CmdBlockWrapper::new( StatesCurrentReadCmdBlock::new(), |_states_current_stored| CleanExecChange::None, )) // Always discover current states, as we need them to be able to clean up. .with_cmd_block(CmdBlockWrapper::new( StatesDiscoverCmdBlock::current(), |_states_current_mut| CleanExecChange::None, )) .with_cmd_block(CmdBlockWrapper::new( StatesCleanInsertionCmdBlock::new(), |_states_clean| CleanExecChange::None, )); cmd_execution_builder = match apply_stored_state_sync { // Data modelling doesn't work well here -- for `CleanCmd` we don't check if the // `goal` state is in sync before cleaning, as the target state is `state_clean` // instead of `state_goal`. ApplyStoredStateSync::None | ApplyStoredStateSync::Goal => cmd_execution_builder, // Similar to the above, we only discover `state_current` even if both are requested // to be in sync. ApplyStoredStateSync::Current | ApplyStoredStateSync::Both => cmd_execution_builder .with_cmd_block(CmdBlockWrapper::new( ApplyStateSyncCheckCmdBlock::current(), |_states_current_stored_and_current| CleanExecChange::None, )), }; cmd_execution_builder .with_cmd_block(CmdBlockWrapper::new( ApplyExecCmdBlock::<CmdCtxTypesT, StatesTs>::new(), |(states_previous, states_applied_mut, _states_target_mut)| { CleanExecChange::Some(Box::new((states_previous, states_applied_mut))) }, )) .with_execution_outcome_fetch(|resources| { let states_previous = resources.try_remove::<StatesPrevious>(); let states_cleaned = resources.try_remove::<States<StatesTs>>(); states_previous.ok().zip(states_cleaned.ok()).map( |(states_previous, states_cleaned)| { CleanExecChange::Some(Box::new((states_previous, states_cleaned))) }, ) }) .build() }; let cmd_outcome = cmd_execution.exec(cmd_ctx).await?; // TODO: Should we run `StatesCurrentFn` again? // // i.e. is it part of `ApplyFns::exec`'s contract to return the state. // // * It may be duplication of code. // * `FileDownloadItem` needs to know the ETag from the last request, which: // - in `StatesCurrentFn` comes from `StatesCurrent` // - in `CleanCmd` comes from `Cleaned` // * `ShCmdItem` doesn't return the state in the apply script, so in the item we // run the state current script after the apply exec script. Ok(cmd_outcome) } // TODO: This duplicates a bit of code with `StatesDiscoverCmd`, async fn serialize_current( item_graph: &ItemGraph<<CmdCtxTypesT as CmdCtxTypes>::AppError>, resources: &Resources<SetUp>, states_cleaned: &StatesCleaned, ) -> Result<(), <CmdCtxTypesT as CmdCtxTypes>::AppError> { use peace_state_rt::StatesSerializer; let flow_dir = resources.borrow::<FlowDir>(); let storage = resources.borrow::<Storage>(); let states_current_file = StatesCurrentFile::from(&*flow_dir); StatesSerializer::serialize(&storage, item_graph, states_cleaned, &states_current_file) .await?; drop(flow_dir); drop(storage); Ok(()) } } impl<CmdCtxTypesT> Default for CleanCmd<CmdCtxTypesT> { fn default() -> Self { Self(PhantomData) } } /// Whether #[derive(Debug)] enum CleanExecChange<StatesTs> { /// Nothing changed, so nothing to serialize. None, /// Some state was changed, so serialization is required. /// /// This variant is used for both partial and complete execution, as long as /// some state was altered. Some(Box<(StatesPrevious, States<StatesTs>)>), }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt/src/cmds/states_current_stored_display_cmd.rs
crate/rt/src/cmds/states_current_stored_display_cmd.rs
use std::{fmt::Debug, marker::PhantomData}; use peace_cmd_ctx::{CmdCtxSpsf, CmdCtxTypes}; use peace_cmd_model::CmdOutcome; use peace_resource_rt::states::StatesCurrentStored; use peace_rt_model_core::output::OutputWrite; use crate::cmds::StatesCurrentReadCmd; /// Displays [`StatesCurrent`]s from storage. #[derive(Debug)] pub struct StatesCurrentStoredDisplayCmd<CmdCtxTypesT>(PhantomData<CmdCtxTypesT>); #[cfg(not(feature = "error_reporting"))] impl<CmdCtxTypesT> StatesCurrentStoredDisplayCmd<CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Displays [`StatesCurrentStored`]s from storage. /// /// [`StatesDiscoverCmd`] must have run prior to this command to read the /// state. /// /// [`StatesDiscoverCmd`]: crate::StatesDiscoverCmd pub async fn exec<'ctx>( cmd_ctx: &mut CmdCtxSpsf<'ctx, CmdCtxTypesT>, ) -> Result< CmdOutcome<StatesCurrentStored, <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > where CmdCtxTypesT: 'ctx, { let states_current_stored_result = StatesCurrentReadCmd::exec(cmd_ctx).await; let output = cmd_ctx.output_mut(); match states_current_stored_result { Ok(states_current_cmd_outcome) => { if let Some(states_current_stored) = states_current_cmd_outcome.value() { output.present(states_current_stored).await?; } Ok(states_current_cmd_outcome) } Err(e) => { output.write_err(&e).await?; Err(e) } } } } // Pending: <https://github.com/rust-lang/rust/issues/115590> #[cfg(feature = "error_reporting")] impl<CmdCtxTypesT> StatesCurrentStoredDisplayCmd<CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, <CmdCtxTypesT as CmdCtxTypes>::AppError: miette::Diagnostic, { /// Displays [`StatesCurrentStored`]s from storage. /// /// [`StatesDiscoverCmd`] must have run prior to this command to read the /// state. /// /// [`StatesDiscoverCmd`]: crate::StatesDiscoverCmd pub async fn exec<'ctx>( cmd_ctx: &mut CmdCtxSpsf<'ctx, CmdCtxTypesT>, ) -> Result< CmdOutcome<StatesCurrentStored, <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > where CmdCtxTypesT: 'ctx, { let states_current_stored_result = StatesCurrentReadCmd::exec(cmd_ctx).await; let output = cmd_ctx.output_mut(); match states_current_stored_result { Ok(states_current_cmd_outcome) => { if let Some(states_current_stored) = states_current_cmd_outcome.value() { output.present(states_current_stored).await?; } Ok(states_current_cmd_outcome) } Err(e) => { output.write_err(&e).await?; Err(e) } } } } impl<CmdCtxTypesT> Default for StatesCurrentStoredDisplayCmd<CmdCtxTypesT> { fn default() -> Self { Self(PhantomData) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt/src/cmds/states_goal_display_cmd.rs
crate/rt/src/cmds/states_goal_display_cmd.rs
use std::{fmt::Debug, marker::PhantomData}; use peace_cmd_ctx::{CmdCtxSpsf, CmdCtxTypes}; use peace_cmd_model::CmdOutcome; use peace_resource_rt::states::StatesGoalStored; use peace_rt_model_core::output::OutputWrite; use crate::cmds::StatesGoalReadCmd; /// Displays [`StatesGoal`]s from storage. #[derive(Debug)] pub struct StatesGoalDisplayCmd<CmdCtxTypesT>(PhantomData<CmdCtxTypesT>); #[cfg(not(feature = "error_reporting"))] impl<CmdCtxTypesT> StatesGoalDisplayCmd<CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Displays [`StatesGoal`]s from storage. /// /// [`StatesDiscoverCmd`] must have run prior to this command to read the /// state. /// /// [`StatesDiscoverCmd`]: crate::StatesDiscoverCmd pub async fn exec<'ctx>( cmd_ctx: &mut CmdCtxSpsf<'ctx, CmdCtxTypesT>, ) -> Result< CmdOutcome<StatesGoalStored, <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > where CmdCtxTypesT: 'ctx, { let states_goal_stored_result = StatesGoalReadCmd::exec(cmd_ctx).await; let output = cmd_ctx.output_mut(); match states_goal_stored_result { Ok(states_goal_cmd_outcome) => { if let Some(states_goal) = states_goal_cmd_outcome.value() { output.present(states_goal).await?; } Ok(states_goal_cmd_outcome) } Err(e) => { output.write_err(&e).await?; Err(e) } } } } // Pending: <https://github.com/rust-lang/rust/issues/115590> #[cfg(feature = "error_reporting")] impl<CmdCtxTypesT> StatesGoalDisplayCmd<CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, <CmdCtxTypesT as CmdCtxTypes>::AppError: miette::Diagnostic, { /// Displays [`StatesGoal`]s from storage. /// /// [`StatesDiscoverCmd`] must have run prior to this command to read the /// state. /// /// [`StatesDiscoverCmd`]: crate::StatesDiscoverCmd pub async fn exec<'ctx>( cmd_ctx: &mut CmdCtxSpsf<'ctx, CmdCtxTypesT>, ) -> Result< CmdOutcome<StatesGoalStored, <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > where CmdCtxTypesT: 'ctx, { let states_goal_stored_result = StatesGoalReadCmd::exec(cmd_ctx).await; let output = cmd_ctx.output_mut(); match states_goal_stored_result { Ok(states_goal_cmd_outcome) => { if let Some(states_goal) = states_goal_cmd_outcome.value() { output.present(states_goal).await?; } Ok(states_goal_cmd_outcome) } Err(e) => { output.write_err(&e).await?; Err(e) } } } } impl<CmdCtxTypesT> Default for StatesGoalDisplayCmd<CmdCtxTypesT> { fn default() -> Self { Self(PhantomData) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt/src/cmds/ensure_cmd.rs
crate/rt/src/cmds/ensure_cmd.rs
use std::{fmt::Debug, marker::PhantomData}; use peace_cmd_ctx::{CmdCtxSpsf, CmdCtxSpsfFields, CmdCtxTypes}; use peace_cmd_model::CmdOutcome; use peace_cmd_rt::{CmdBlockWrapper, CmdExecution}; use peace_flow_rt::ItemGraph; use peace_resource_rt::{ paths::{FlowDir, StatesCurrentFile, StatesGoalFile}, resources::ts::SetUp, states::{States, StatesEnsured, StatesEnsuredDry, StatesGoal, StatesPrevious}, Resources, }; use peace_rt_model::Storage; use crate::{ cmd_blocks::{ apply_exec_cmd_block::StatesTsApplyExt, ApplyExecCmdBlock, ApplyStateSyncCheckCmdBlock, StatesCurrentReadCmdBlock, StatesDiscoverCmdBlock, StatesGoalReadCmdBlock, }, cmds::ApplyStoredStateSync, }; #[derive(Debug)] pub struct EnsureCmd<CmdCtxTypesT>(PhantomData<CmdCtxTypesT>); impl<CmdCtxTypesT> EnsureCmd<CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Conditionally runs [`Item::apply_exec_dry`] for each [`Item`]. /// /// In practice this runs [`Item::apply_check`], and only runs /// [`apply_exec_dry`] if execution is required. /// /// # Design /// /// The grouping of item functions run for an `Ensure` execution to /// work is as follows: /// /// 1. For each `Item` run `ItemRt::ensure_prepare`, which runs: /// /// 1. `Item::state_current` /// 2. `Item::state_goal` /// 3. `Item::apply_check` /// /// 2. For `Item`s that return `ApplyCheck::ExecRequired`, run /// `Item::apply_exec_dry`. /// /// [`apply_exec_dry`]: peace_cfg::Item::apply_exec_dry /// [`Item::apply_check`]: peace_cfg::Item::apply_check /// [`Item::apply_exec_dry`]: peace_cfg::ItemRt::apply_exec_dry /// [`Item`]: peace_cfg::Item pub async fn exec_dry<'ctx>( cmd_ctx: &mut CmdCtxSpsf<'ctx, CmdCtxTypesT>, ) -> Result< CmdOutcome<StatesEnsuredDry, <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > where CmdCtxTypesT: 'ctx, { Self::exec_dry_with(cmd_ctx, ApplyStoredStateSync::Both).await } /// Conditionally runs [`Item::apply_exec_dry`] for each [`Item`]. /// /// See [`Self::exec_dry`] for full documentation. /// /// This function exists so that this command can be executed as sub /// functionality of another command. pub async fn exec_dry_with<'ctx>( cmd_ctx: &mut CmdCtxSpsf<'ctx, CmdCtxTypesT>, apply_stored_state_sync: ApplyStoredStateSync, ) -> Result< CmdOutcome<StatesEnsuredDry, <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > where CmdCtxTypesT: 'ctx, { let cmd_outcome = Self::exec_internal(cmd_ctx, apply_stored_state_sync).await?; let cmd_outcome = cmd_outcome.map(|ensure_exec_change| match ensure_exec_change { EnsureExecChange::None => Default::default(), EnsureExecChange::Some(stateses_boxed) => { let (states_previous, states_applied_dry, _states_goal) = *stateses_boxed; cmd_ctx .fields_mut() .resources_mut() .insert::<StatesPrevious>(states_previous); states_applied_dry } }); Ok(cmd_outcome) } /// Conditionally runs [`Item::apply_exec`] for each [`Item`]. /// /// In practice this runs [`Item::apply_check`], and only runs /// [`apply_exec`] if execution is required. /// /// # Design /// /// The grouping of item functions run for an `Ensure` execution to /// work is as follows: /// /// 1. For each `Item` run `ItemRt::ensure_prepare`, which runs: /// /// 1. `Item::state_current` /// 2. `Item::state_goal` /// 3. `Item::apply_check` /// /// 2. For `Item`s that return `ApplyCheck::ExecRequired`, run /// `Item::apply_exec`. /// /// [`apply_exec`]: peace_cfg::Item::apply_exec /// [`Item::apply_check`]: peace_cfg::Item::apply_check /// [`Item::apply_exec`]: peace_cfg::ItemRt::apply_exec /// [`Item`]: peace_cfg::Item pub async fn exec<'ctx>( cmd_ctx: &mut CmdCtxSpsf<'ctx, CmdCtxTypesT>, ) -> Result< CmdOutcome<StatesEnsured, <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > where CmdCtxTypesT: 'ctx, { Self::exec_with(cmd_ctx, ApplyStoredStateSync::Both).await } /// Conditionally runs [`Item::apply_exec`] for each [`Item`]. /// /// See [`Self::exec`] for full documentation. /// /// This function exists so that this command can be executed as sub /// functionality of another command. pub async fn exec_with<'ctx>( cmd_ctx: &mut CmdCtxSpsf<'ctx, CmdCtxTypesT>, apply_stored_state_sync: ApplyStoredStateSync, ) -> Result< CmdOutcome<StatesEnsured, <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > where CmdCtxTypesT: 'ctx, { let cmd_outcome = Self::exec_internal(cmd_ctx, apply_stored_state_sync).await?; let CmdCtxSpsfFields { flow, ref mut resources, .. } = cmd_ctx.fields_mut(); let item_graph = flow.graph(); // We shouldn't serialize current or goal if we returned from an interruption / // error handler. let cmd_outcome = cmd_outcome .map_async(|ensure_exec_change| async move { match ensure_exec_change { EnsureExecChange::None => Ok(Default::default()), EnsureExecChange::Some(stateses_boxed) => { let (states_previous, states_applied, states_goal) = *stateses_boxed; Self::serialize_current(item_graph, resources, &states_applied).await?; Self::serialize_goal(item_graph, resources, &states_goal).await?; resources.insert::<StatesPrevious>(states_previous); Ok(states_applied) } } }) .await; cmd_outcome.transpose() } /// Conditionally runs [`ApplyFns`]`::`[`exec`] for each [`Item`]. /// /// Same as [`Self::exec`], but does not change the type state, and returns /// [`StatesEnsured`]. /// /// [`exec`]: peace_cfg::ApplyFns::exec /// [`Item`]: peace_cfg::Item /// [`ApplyFns`]: peace_cfg::Item::ApplyFns async fn exec_internal<'ctx, StatesTs>( cmd_ctx: &mut CmdCtxSpsf<'ctx, CmdCtxTypesT>, apply_stored_state_sync: ApplyStoredStateSync, ) -> Result< CmdOutcome<EnsureExecChange<StatesTs>, <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > where CmdCtxTypesT: 'ctx, StatesTs: StatesTsApplyExt + Debug + Send + Sync + Unpin + 'static, { let mut cmd_execution = { let mut cmd_execution_builder = CmdExecution::<EnsureExecChange<StatesTs>, _>::builder() .with_cmd_block(CmdBlockWrapper::new( StatesCurrentReadCmdBlock::new(), |_states_current_stored| EnsureExecChange::None, )) .with_cmd_block(CmdBlockWrapper::new( StatesGoalReadCmdBlock::new(), |_states_goal_stored| EnsureExecChange::None, )) // Always discover current and goal states, because they are read whether or not // we are checking for state sync. // // Exception: current states are not used for `ApplyStoredStateSync::None`, // since we have to discover the new current state after every apply. .with_cmd_block(CmdBlockWrapper::new( StatesDiscoverCmdBlock::current_and_goal(), |_states_current_and_goal_mut| EnsureExecChange::None, )); cmd_execution_builder = match apply_stored_state_sync { ApplyStoredStateSync::None => cmd_execution_builder, ApplyStoredStateSync::Current => cmd_execution_builder.with_cmd_block( CmdBlockWrapper::new(ApplyStateSyncCheckCmdBlock::current(), |_| { EnsureExecChange::None }), ), ApplyStoredStateSync::Goal => cmd_execution_builder.with_cmd_block( CmdBlockWrapper::new(ApplyStateSyncCheckCmdBlock::goal(), |_| { EnsureExecChange::None }), ), ApplyStoredStateSync::Both => cmd_execution_builder.with_cmd_block( CmdBlockWrapper::new(ApplyStateSyncCheckCmdBlock::current_and_goal(), |_| { EnsureExecChange::None }), ), }; cmd_execution_builder .with_cmd_block(CmdBlockWrapper::new( ApplyExecCmdBlock::<CmdCtxTypesT, StatesTs>::new(), |(states_previous, states_applied, states_target): ( StatesPrevious, States<StatesTs>, States<StatesTs::TsTarget>, )| { EnsureExecChange::Some(Box::new(( states_previous, states_applied, StatesGoal::from(states_target.into_inner()), ))) }, )) .with_execution_outcome_fetch(|resources| { let states_previous = resources.try_remove::<StatesPrevious>(); let states_applied = resources.try_remove::<States<StatesTs>>(); let states_goal = resources.try_remove::<StatesGoal>(); if let Some(((states_previous, states_applied), states_goal)) = states_previous .ok() .zip(states_applied.ok()) .zip(states_goal.ok()) { Some(EnsureExecChange::Some(Box::new(( states_previous, states_applied, states_goal, )))) } else { Some(EnsureExecChange::None) } }) .build() }; let ensure_exec_change = cmd_execution.exec(cmd_ctx).await?; // TODO: Should we run `StatesCurrentFn` again? // // i.e. is it part of `ApplyFns::exec`'s contract to return the state. // // * It may be duplication of code. // * `FileDownloadItem` needs to know the ETag from the last request, which: // - in `StatesCurrentFn` comes from `StatesCurrent` // - in `EnsureCmd` comes from `Ensured` // * `ShCmdItem` doesn't return the state in the apply script, so in the item we // run the state current script after the apply exec script. Ok(ensure_exec_change) } // TODO: This duplicates a bit of code with `StatesDiscoverCmd`, async fn serialize_current( item_graph: &ItemGraph<<CmdCtxTypesT as CmdCtxTypes>::AppError>, resources: &Resources<SetUp>, states_applied: &StatesEnsured, ) -> Result<(), <CmdCtxTypesT as CmdCtxTypes>::AppError> { use peace_state_rt::StatesSerializer; let flow_dir = resources.borrow::<FlowDir>(); let storage = resources.borrow::<Storage>(); let states_current_file = StatesCurrentFile::from(&*flow_dir); StatesSerializer::serialize(&storage, item_graph, states_applied, &states_current_file) .await?; drop(flow_dir); drop(storage); Ok(()) } async fn serialize_goal( item_graph: &ItemGraph<<CmdCtxTypesT as CmdCtxTypes>::AppError>, resources: &Resources<SetUp>, states_goal: &StatesGoal, ) -> Result<(), <CmdCtxTypesT as CmdCtxTypes>::AppError> { use peace_state_rt::StatesSerializer; let flow_dir = resources.borrow::<FlowDir>(); let storage = resources.borrow::<Storage>(); let states_goal_file = StatesGoalFile::from(&*flow_dir); StatesSerializer::serialize(&storage, item_graph, states_goal, &states_goal_file).await?; drop(flow_dir); drop(storage); Ok(()) } } impl<CmdCtxTypesT> Default for EnsureCmd<CmdCtxTypesT> { fn default() -> Self { Self(PhantomData) } } #[derive(Debug)] enum EnsureExecChange<StatesTs> { /// Nothing changed, so nothing to serialize. None, /// Some state was changed, so serialization is required. /// /// This variant is used for both partial and complete execution, as long as /// some state was altered. Some(Box<(StatesPrevious, States<StatesTs>, StatesGoal)>), }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt/src/cmds/states_discover_cmd.rs
crate/rt/src/cmds/states_discover_cmd.rs
use std::{fmt::Debug, marker::PhantomData}; use peace_cmd_ctx::{CmdCtxSpsf, CmdCtxSpsfFields, CmdCtxTypes}; use peace_cmd_model::CmdOutcome; use peace_cmd_rt::{CmdBlockWrapper, CmdExecution}; use peace_flow_rt::ItemGraph; use peace_resource_rt::{ paths::{FlowDir, StatesCurrentFile, StatesGoalFile}, resources::ts::SetUp, states::{StatesCurrent, StatesGoal}, Resources, }; use peace_rt_model::Storage; use crate::cmd_blocks::StatesDiscoverCmdBlock; pub struct StatesDiscoverCmd<CmdCtxTypesT>(PhantomData<CmdCtxTypesT>); impl<CmdCtxTypesT> Debug for StatesDiscoverCmd<CmdCtxTypesT> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_tuple("StatesDiscoverCmd").field(&self.0).finish() } } impl<CmdCtxTypesT> StatesDiscoverCmd<CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Runs [`try_state_current`] for each [`Item`]. /// /// At the end of this function, [`Resources`] will be populated with /// [`StatesCurrent`], and will be serialized to /// `$flow_dir/states_current.yaml`. /// /// If any `state_current` function needs to read the `State` from a /// previous `Item`, it may automatically be referenced using [`Current<T>`] /// where `T` us the predecessor's state. Peace will have automatically /// inserted it into `Resources`, and the successor should references it /// in their [`Data`]. /// /// This function will always serialize states to storage. /// /// [`Current<T>`]: https://docs.rs/peace_data/latest/peace_data/marker/struct.Current.html /// [`Data`]: peace_cfg::TryFnSpec::Data /// [`Item`]: peace_cfg::Item /// [`try_state_current`]: peace_cfg::Item::try_state_current pub async fn current<'ctx>( cmd_ctx: &mut CmdCtxSpsf<'ctx, CmdCtxTypesT>, ) -> Result< CmdOutcome<StatesCurrent, <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > where CmdCtxTypesT: 'ctx, { Self::current_with(cmd_ctx, true).await } /// Runs [`try_state_current`] for each [`Item`]. /// /// See [`Self::current`] for full documentation. /// /// This function exists so that this command can be executed as sub /// functionality of another command. /// /// # Parameters /// /// * `cmd_ctx`: Information needed to execute a command. /// * `serialize_to_storage`: Whether to write states to storage after /// discovery. /// /// [`try_state_current`]: peace_cfg::Item::try_state_current pub async fn current_with<'ctx>( cmd_ctx: &mut CmdCtxSpsf<'ctx, CmdCtxTypesT>, serialize_to_storage: bool, ) -> Result< CmdOutcome<StatesCurrent, <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > where CmdCtxTypesT: 'ctx, { let mut cmd_execution = CmdExecution::<StatesCurrent, _>::builder() .with_cmd_block(CmdBlockWrapper::new( #[cfg(not(feature = "output_progress"))] StatesDiscoverCmdBlock::current(), #[cfg(feature = "output_progress")] StatesDiscoverCmdBlock::current().progress_complete_on_success(), StatesCurrent::from, )) .build(); let cmd_outcome = cmd_execution.exec(cmd_ctx).await?; if let Some(states_current) = cmd_outcome.value() { let CmdCtxSpsfFields { flow, ref mut resources, .. } = cmd_ctx.fields_mut(); let item_graph = flow.graph(); if serialize_to_storage { Self::serialize_current(item_graph, resources, states_current).await?; } } Ok(cmd_outcome) } /// Runs [`try_state_goal`] for each [`Item`]. /// /// At the end of this function, [`Resources`] will be populated with /// [`StatesGoal`], and will be serialized to /// `$flow_dir/states_goal.yaml`. /// /// If any `state_goal` function needs to read the `State` from a /// previous `Item`, it may automatically be referenced using [`Goal<T>`] /// where `T` us the predecessor's state. Peace will have automatically /// inserted it into `Resources`, and the successor should references it /// in their [`Data`]. /// /// This function will always serialize states to storage. /// /// [`Data`]: peace_cfg::TryFnSpec::Data /// [`Goal<T>`]: https://docs.rs/peace_data/latest/peace_data/marker/struct.Goal.html /// [`Item`]: peace_cfg::Item /// [`try_state_goal`]: peace_cfg::Item::try_state_goal pub async fn goal<'ctx>( cmd_ctx: &mut CmdCtxSpsf<'ctx, CmdCtxTypesT>, ) -> Result< CmdOutcome<StatesGoal, <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > where CmdCtxTypesT: 'ctx, { Self::goal_with(cmd_ctx, true).await } /// Runs [`try_state_goal`] for each [`Item`]. /// /// See [`Self::goal`] for full documentation. /// /// This function exists so that this command can be executed as sub /// functionality of another command. /// /// # Parameters /// /// * `cmd_ctx`: Information needed to execute a command. /// * `serialize_to_storage`: Whether to write states to storage after /// discovery. /// /// [`try_state_goal`]: peace_cfg::Item::try_state_goal pub async fn goal_with<'ctx>( cmd_ctx: &mut CmdCtxSpsf<'ctx, CmdCtxTypesT>, serialize_to_storage: bool, ) -> Result< CmdOutcome<StatesGoal, <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > where CmdCtxTypesT: 'ctx, { let mut cmd_execution = CmdExecution::<StatesGoal, _>::builder() .with_cmd_block(CmdBlockWrapper::new( #[cfg(not(feature = "output_progress"))] StatesDiscoverCmdBlock::goal(), #[cfg(feature = "output_progress")] StatesDiscoverCmdBlock::goal().progress_complete_on_success(), StatesGoal::from, )) .build(); let cmd_outcome = cmd_execution.exec(cmd_ctx).await?; if let Some(states_goal) = cmd_outcome.value() { let CmdCtxSpsfFields { flow, ref mut resources, .. } = cmd_ctx.fields_mut(); let item_graph = flow.graph(); if serialize_to_storage { Self::serialize_goal(item_graph, resources, states_goal).await?; } } Ok(cmd_outcome) } /// Runs [`try_state_current`] and [`try_state_goal`]` for each /// [`Item`]. /// /// At the end of this function, [`Resources`] will be populated with /// [`StatesCurrent`] and [`StatesGoal`], and states will be serialized /// to `$flow_dir/states_current.yaml` and /// `$flow_dir/states_goal.yaml`. /// /// If any `state_current` function needs to read the `State` from a /// previous `Item`, the predecessor should insert a copy / clone of /// their state into `Resources`, and the successor should references it /// in their [`Data`]. /// /// If any `state_goal` function needs to read the `State` from a /// previous `Item`, it may automatically be referenced using /// [`Goal<T>`] where `T` us the predecessor's state. Peace will have /// automatically inserted it into `Resources`, and the successor should /// references it in their [`Data`]. /// /// This function will always serialize states to storage. /// /// [`Current<T>`]: https://docs.rs/peace_data/latest/peace_data/marker/struct.Current.html /// [`Data`]: peace_cfg::TryFnSpec::Data /// [`Goal<T>`]: https://docs.rs/peace_data/latest/peace_data/marker/struct.Goal.html /// [`Item`]: peace_cfg::Item /// [`try_state_current`]: peace_cfg::Item::try_state_current /// [`try_state_goal`]: peace_cfg::Item::try_state_goal pub async fn current_and_goal<'ctx>( cmd_ctx: &mut CmdCtxSpsf<'ctx, CmdCtxTypesT>, ) -> Result< CmdOutcome<(StatesCurrent, StatesGoal), <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > where CmdCtxTypesT: 'ctx, { Self::current_and_goal_with(cmd_ctx, true).await } /// Runs [`try_state_current`] and [`try_state_goal`]` for each /// [`Item`]. /// /// See [`Self::goal`] for full documentation. /// /// This function exists so that this command can be executed as sub /// functionality of another command. /// /// # Parameters /// /// * `cmd_ctx`: Information needed to execute a command. /// * `serialize_to_storage`: Whether to write states to storage after /// discovery. /// /// [`try_state_current`]: peace_cfg::Item::try_state_current /// [`try_state_goal`]: peace_cfg::Item::try_state_goal pub async fn current_and_goal_with<'ctx>( cmd_ctx: &mut CmdCtxSpsf<'ctx, CmdCtxTypesT>, serialize_to_storage: bool, ) -> Result< CmdOutcome<(StatesCurrent, StatesGoal), <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > where CmdCtxTypesT: 'ctx, { let mut cmd_execution = CmdExecution::<(StatesCurrent, StatesGoal), _>::builder() .with_cmd_block(CmdBlockWrapper::new( #[cfg(not(feature = "output_progress"))] StatesDiscoverCmdBlock::current_and_goal(), #[cfg(feature = "output_progress")] StatesDiscoverCmdBlock::current_and_goal().progress_complete_on_success(), |states_current_and_goal_mut| { let (states_current_mut, states_goal_mut) = states_current_and_goal_mut; ( StatesCurrent::from(states_current_mut), StatesGoal::from(states_goal_mut), ) }, )) .with_execution_outcome_fetch(|resources| { let states_current = resources.try_remove::<StatesCurrent>(); let states_goal = resources.try_remove::<StatesGoal>(); states_current.ok().zip(states_goal.ok()) }) .build(); let cmd_outcome = cmd_execution.exec(cmd_ctx).await?; if let Some((states_current, states_goal)) = cmd_outcome.value() { let CmdCtxSpsfFields { flow, ref mut resources, .. } = cmd_ctx.fields_mut(); let item_graph = flow.graph(); if serialize_to_storage { Self::serialize_current(item_graph, resources, states_current).await?; Self::serialize_goal(item_graph, resources, states_goal).await?; } } Ok(cmd_outcome) } // TODO: This duplicates a bit of code with `EnsureCmd` and `CleanCmd`. async fn serialize_current( item_graph: &ItemGraph<<CmdCtxTypesT as CmdCtxTypes>::AppError>, resources: &mut Resources<SetUp>, states_current: &StatesCurrent, ) -> Result<(), <CmdCtxTypesT as CmdCtxTypes>::AppError> { use peace_state_rt::StatesSerializer; let flow_dir = resources.borrow::<FlowDir>(); let storage = resources.borrow::<Storage>(); let states_current_file = StatesCurrentFile::from(&*flow_dir); StatesSerializer::serialize(&storage, item_graph, states_current, &states_current_file) .await?; drop(flow_dir); drop(storage); resources.insert(states_current_file); Ok(()) } async fn serialize_goal( item_graph: &ItemGraph<<CmdCtxTypesT as CmdCtxTypes>::AppError>, resources: &mut Resources<SetUp>, states_goal: &StatesGoal, ) -> Result<(), <CmdCtxTypesT as CmdCtxTypes>::AppError> { use peace_state_rt::StatesSerializer; let flow_dir = resources.borrow::<FlowDir>(); let storage = resources.borrow::<Storage>(); let states_goal_file = StatesGoalFile::from(&*flow_dir); StatesSerializer::serialize(&storage, item_graph, states_goal, &states_goal_file).await?; drop(flow_dir); drop(storage); resources.insert(states_goal_file); Ok(()) } } impl<CmdCtxTypesT> Default for StatesDiscoverCmd<CmdCtxTypesT> { fn default() -> Self { Self(PhantomData) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt/src/cmds/diff_cmd.rs
crate/rt/src/cmds/diff_cmd.rs
use std::{fmt::Debug, marker::PhantomData}; use futures::{StreamExt, TryStreamExt}; use peace_cmd_ctx::{CmdCtxMpsf, CmdCtxMpsfFields, CmdCtxSpsf, CmdCtxTypes}; use peace_cmd_model::CmdOutcome; use peace_cmd_rt::{CmdBlockWrapper, CmdExecution, CmdExecutionBuilder}; use peace_flow_rt::Flow; use peace_item_model::ItemId; use peace_params::{MappingFnReg, ParamsSpecs}; use peace_profile_model::Profile; use peace_resource_rt::{ internal::StateDiffsMut, resources::ts::SetUp, states::{ ts::{CurrentStored, GoalStored}, StateDiffs, }, type_reg::untagged::{BoxDtDisplay, TypeMap}, Resources, }; use peace_rt_model::Error; use crate::cmd_blocks::{ DiffCmdBlock, DiffCmdBlockStatesTsExt, StatesCurrentReadCmdBlock, StatesDiscoverCmdBlock, StatesGoalReadCmdBlock, }; pub use self::{diff_info_spec::DiffInfoSpec, diff_state_spec::DiffStateSpec}; mod diff_info_spec; mod diff_state_spec; pub struct DiffCmd<CmdCtxTypesT, Scope>(PhantomData<(CmdCtxTypesT, Scope)>); impl<CmdCtxTypesT, Scope> Debug for DiffCmd<CmdCtxTypesT, Scope> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_tuple("DiffCmd").field(&self.0).finish() } } impl<'ctx, CmdCtxTypesT> DiffCmd<CmdCtxTypesT, CmdCtxSpsf<'ctx, CmdCtxTypesT>> where CmdCtxTypesT: CmdCtxTypes, { /// Returns the [`state_diff`]`s between the stored current and goal /// states. /// /// Both current and goal states must have been discovered prior to /// running this. See [`StatesDiscoverCmd::current_and_goal`]. /// /// This is equivalent to calling: /// /// ```rust,ignore /// DiffCmd::diff(cmd_ctx, DiffStateSpec::CurrentStored, DiffStateSpec::GoalStored).await?; /// ``` /// /// [`state_diff`]: peace_cfg::Item::state_diff /// [`StatesDiscoverCmd::current_and_goal`]: crate::cmds::StatesDiscoverCmd::current_and_goal pub async fn diff_stored( cmd_ctx: &mut CmdCtxSpsf<'ctx, CmdCtxTypesT>, ) -> Result< CmdOutcome<StateDiffs, <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > { Self::diff::<CurrentStored, GoalStored>(cmd_ctx).await } /// Returns the [`state_diff`]`s between two states. /// /// For `CurrentStored` and `GoalStored`, states must have been discovered /// prior to running this. See [`StatesDiscoverCmd::current_and_goal`]. /// /// For `Current` and `Goal` states, though they are discovered during the /// `DiffCmd` execution, they are not serialized. /// /// [`state_diff`]: peace_cfg::Item::state_diff /// [`StatesDiscoverCmd::current_and_goal`]: crate::cmds::StatesDiscoverCmd::current_and_goal pub async fn diff<StatesTs0, StatesTs1>( cmd_ctx: &mut CmdCtxSpsf<'ctx, CmdCtxTypesT>, ) -> Result< CmdOutcome<StateDiffs, <CmdCtxTypesT as CmdCtxTypes>::AppError>, <CmdCtxTypesT as CmdCtxTypes>::AppError, > where StatesTs0: Debug + DiffCmdBlockStatesTsExt + Send + Sync + Unpin + 'static, StatesTs1: Debug + DiffCmdBlockStatesTsExt + Send + Sync + Unpin + 'static, { let mut cmd_execution_builder = CmdExecution::<StateDiffs, _>::builder(); cmd_execution_builder = Self::states_fetch_cmd_block_append( cmd_execution_builder, StatesTs0::diff_state_spec(), ); cmd_execution_builder = Self::states_fetch_cmd_block_append( cmd_execution_builder, StatesTs1::diff_state_spec(), ); cmd_execution_builder = cmd_execution_builder.with_cmd_block(CmdBlockWrapper::new( DiffCmdBlock::<_, StatesTs0, StatesTs1>::new(), |_state_diffs_ts0_and_ts1| StateDiffs::new(), )); #[cfg(feature = "output_progress")] let cmd_execution_builder = cmd_execution_builder.with_progress_render_enabled(false); cmd_execution_builder.build().exec(cmd_ctx).await } fn states_fetch_cmd_block_append( cmd_execution_builder: CmdExecutionBuilder<'ctx, StateDiffs, CmdCtxTypesT>, diff_state_spec: DiffStateSpec, ) -> CmdExecutionBuilder<'ctx, StateDiffs, CmdCtxTypesT> { match diff_state_spec { DiffStateSpec::Current => cmd_execution_builder.with_cmd_block(CmdBlockWrapper::new( StatesDiscoverCmdBlock::current(), |_states_current_mut| StateDiffs::new(), )), DiffStateSpec::CurrentStored => cmd_execution_builder.with_cmd_block( CmdBlockWrapper::new(StatesCurrentReadCmdBlock::new(), |_| StateDiffs::new()), ), DiffStateSpec::Goal => cmd_execution_builder .with_cmd_block(CmdBlockWrapper::new(StatesDiscoverCmdBlock::goal(), |_| { StateDiffs::new() })), DiffStateSpec::GoalStored => { cmd_execution_builder .with_cmd_block(CmdBlockWrapper::new(StatesGoalReadCmdBlock::new(), |_| { StateDiffs::new() })) } } } } impl<'ctx, CmdCtxTypesT> DiffCmd<CmdCtxTypesT, CmdCtxMpsf<'ctx, CmdCtxTypesT>> where CmdCtxTypesT: CmdCtxTypes, { /// Returns the [`state_diff`]`s between the stored current states of two /// profiles. /// /// Both profiles' current states must have been discovered prior to /// running this. See [`StatesDiscoverCmd::current`]. /// /// [`state_diff`]: peace_cfg::Item::state_diff /// [`StatesDiscoverCmd::current`]: crate::cmds::StatesDiscoverCmd::current pub async fn diff_current_stored( cmd_ctx: &mut CmdCtxMpsf<'ctx, CmdCtxTypesT>, profile_a: &Profile, profile_b: &Profile, ) -> Result<StateDiffs, <CmdCtxTypesT as CmdCtxTypes>::AppError> { let CmdCtxMpsfFields { flow, profiles, profile_to_params_specs, profile_to_states_current_stored, mapping_fn_reg, resources, .. } = cmd_ctx.fields(); let params_specs = profile_to_params_specs .get(profile_a) .or_else(|| profile_to_params_specs.get(profile_b)); let params_specs = if let Some(params_specs) = params_specs { params_specs } else { Err(Error::ParamsSpecsNotDefinedForDiff { profile_a: profile_a.clone(), profile_b: profile_b.clone(), })? }; let states_a = profile_to_states_current_stored .get(profile_a) .ok_or_else(|| { let profile = profile_a.clone(); let profiles_in_scope = profiles.to_vec(); Error::ProfileNotInScope { profile, profiles_in_scope, } })? .as_ref() .ok_or_else(|| { let profile = profile_a.clone(); Error::ProfileStatesCurrentNotDiscovered { profile } })?; let states_b = profile_to_states_current_stored .get(profile_b) .ok_or_else(|| { let profile = profile_b.clone(); let profiles_in_scope = profiles.to_vec(); Error::ProfileNotInScope { profile, profiles_in_scope, } })? .as_ref() .ok_or_else(|| { let profile = profile_b.clone(); Error::ProfileStatesCurrentNotDiscovered { profile } })?; Self::diff_any( flow, params_specs, mapping_fn_reg, resources, states_a, states_b, ) .await } } impl<CmdCtxTypesT, Scope> DiffCmd<CmdCtxTypesT, Scope> where CmdCtxTypesT: CmdCtxTypes, { /// Returns the [`state_diff`]` for each [`Item`]. /// /// This does not take in `CmdCtx` as it may be used by both /// `CmdCtxSpsf` and `CmdCtxMpsf` /// commands. /// /// [`Item`]: peace_cfg::Item /// [`state_diff`]: peace_cfg::Item::state_diff pub async fn diff_any( flow: &Flow<<CmdCtxTypesT as CmdCtxTypes>::AppError>, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, states_a: &TypeMap<ItemId, BoxDtDisplay>, states_b: &TypeMap<ItemId, BoxDtDisplay>, ) -> Result<StateDiffs, <CmdCtxTypesT as CmdCtxTypes>::AppError> { let state_diffs = { let state_diffs_mut = flow .graph() .stream() .map(Result::<_, <CmdCtxTypesT as CmdCtxTypes>::AppError>::Ok) .try_filter_map(|item| async move { let state_diff_opt = item .state_diff_exec( params_specs, mapping_fn_reg, resources, states_a, states_b, ) .await?; Ok(state_diff_opt.map(|state_diff| (item.id().clone(), state_diff))) }) .try_collect::<StateDiffsMut>() .await?; StateDiffs::from(state_diffs_mut) }; Ok(state_diffs) } } impl<CmdCtxTypesT, Scope> Default for DiffCmd<CmdCtxTypesT, Scope> { fn default() -> Self { Self(PhantomData) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt/src/cmds/diff_cmd/diff_info_spec.rs
crate/rt/src/cmds/diff_cmd/diff_info_spec.rs
use peace_profile_model::Profile; use crate::cmds::diff_cmd::DiffStateSpec; /// Indicates where to source information to diff. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct DiffInfoSpec<'diff> { /// Profile to read parameters and state from. pub profile: &'diff Profile, /// Whether to read stored state or discover state. pub diff_state_spec: DiffStateSpec, } impl<'diff> DiffInfoSpec<'diff> { /// Returns a new `DiffInfoSpec`. pub fn new(profile: &'diff Profile, diff_state_spec: DiffStateSpec) -> Self { Self { profile, diff_state_spec, } } /// Returns the profile to read parameters and state from. pub fn profile(&self) -> &Profile { self.profile } /// Returns whether to read stored state or discover state. pub fn diff_state_spec(&self) -> DiffStateSpec { self.diff_state_spec } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt/src/cmds/diff_cmd/diff_state_spec.rs
crate/rt/src/cmds/diff_cmd/diff_state_spec.rs
/// Whether to read stored state or discover state. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DiffStateSpec { /// Discovers the current state upon execution. Current, /// Reads previously stored current state. CurrentStored, /// Discovers the goal state upon execution. Goal, /// Reads previously stored goal state. GoalStored, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt/src/cmd_blocks/states_discover_cmd_block.rs
crate/rt/src/cmd_blocks/states_discover_cmd_block.rs
use std::{fmt::Debug, marker::PhantomData}; use futures::join; use peace_cfg::FnCtx; use peace_cmd_ctx::{CmdCtxSpsfFields, CmdCtxTypes}; use peace_cmd_model::CmdBlockOutcome; use peace_cmd_rt::{async_trait, CmdBlock}; use peace_item_model::ItemId; use peace_params::MappingFnReg; use peace_resource_rt::{ internal::StatesMut, resources::ts::SetUp, states::{ ts::{Current, Goal}, States, StatesCurrent, StatesGoal, }, type_reg::untagged::BoxDtDisplay, ResourceFetchError, Resources, }; use peace_rt_model::{fn_graph::StreamOpts, ItemBoxed}; use peace_rt_model_core::IndexMap; use tokio::sync::mpsc::{self, Receiver}; use crate::BUFFERED_FUTURES_MAX; cfg_if::cfg_if! { if #[cfg(feature = "output_progress")] { use peace_progress_model::{ CmdBlockItemInteractionType, CmdProgressUpdate, ProgressComplete, ProgressDelta, ProgressMsgUpdate, ProgressSender, ProgressUpdate, ProgressUpdateAndId, }; use tokio::sync::mpsc::Sender; } } /// Discovers current states. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct DiscoverForCurrent; /// Discovers goal states. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct DiscoverForGoal; /// Discovers current and goal states. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct DiscoverForCurrentAndGoal; /// Discovers [`StatesCurrent`] and/or [`StatesGoal`]. pub struct StatesDiscoverCmdBlock<CmdCtxTypesT, DiscoverFor> { /// Whether or not to mark progress bars complete on success. #[cfg(feature = "output_progress")] progress_complete_on_success: bool, /// Marker. marker: PhantomData<(CmdCtxTypesT, DiscoverFor)>, } impl<CmdCtxTypesT, DiscoverFor> Debug for StatesDiscoverCmdBlock<CmdCtxTypesT, DiscoverFor> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut debug_struct = f.debug_struct("StatesDiscoverCmdBlock"); #[cfg(feature = "output_progress")] debug_struct.field( "progress_complete_on_success", &self.progress_complete_on_success, ); debug_struct.field("marker", &self.marker).finish() } } impl<CmdCtxTypesT> StatesDiscoverCmdBlock<CmdCtxTypesT, DiscoverForCurrent> where CmdCtxTypesT: CmdCtxTypes, { /// Returns a block that discovers current states. pub fn current() -> Self { Self { #[cfg(feature = "output_progress")] progress_complete_on_success: false, marker: PhantomData, } } } impl<CmdCtxTypesT> StatesDiscoverCmdBlock<CmdCtxTypesT, DiscoverForGoal> where CmdCtxTypesT: CmdCtxTypes, { /// Returns a block that discovers goal states. pub fn goal() -> Self { Self { #[cfg(feature = "output_progress")] progress_complete_on_success: false, marker: PhantomData, } } } impl<CmdCtxTypesT> StatesDiscoverCmdBlock<CmdCtxTypesT, DiscoverForCurrentAndGoal> where CmdCtxTypesT: CmdCtxTypes, { /// Returns a block that discovers both current and goal states. pub fn current_and_goal() -> Self { Self { #[cfg(feature = "output_progress")] progress_complete_on_success: false, marker: PhantomData, } } } impl<CmdCtxTypesT, DiscoverFor> StatesDiscoverCmdBlock<CmdCtxTypesT, DiscoverFor> where CmdCtxTypesT: CmdCtxTypes, DiscoverFor: Discover, { /// Indicate that the progress tracker should be marked complete on success. /// /// This should be used only if this is the last `CmdBlock` in a /// `CmdExecution`. #[cfg(feature = "output_progress")] pub fn progress_complete_on_success(mut self) -> Self { self.progress_complete_on_success = true; self } async fn item_states_discover( #[cfg(feature = "output_progress")] progress_tx: &Sender<CmdProgressUpdate>, #[cfg(feature = "output_progress")] progress_complete_on_success: bool, params_specs: &peace_params::ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, outcomes_tx: &tokio::sync::mpsc::Sender< ItemDiscoverOutcome<<CmdCtxTypesT as CmdCtxTypes>::AppError>, >, item: &ItemBoxed<<CmdCtxTypesT as CmdCtxTypes>::AppError>, ) { let item_id = item.id(); let fn_ctx = FnCtx::new( item_id, #[cfg(feature = "output_progress")] ProgressSender::new(item_id, progress_tx), ); let (states_current_result, states_goal_result) = DiscoverFor::discover(item, params_specs, mapping_fn_reg, resources, fn_ctx).await; // Send progress update. #[cfg(feature = "output_progress")] Self::discover_progress_update( progress_complete_on_success, states_current_result.as_ref(), states_goal_result.as_ref(), progress_tx, item_id, ); let mut item_error = None; let state_current = if let Some(states_current_result) = states_current_result { match states_current_result { Ok(state_current_opt) => state_current_opt, Err(error) => { item_error = Some(error); None } } } else { None }; let state_goal = if let Some(states_goal_result) = states_goal_result { match states_goal_result { Ok(state_goal_opt) => state_goal_opt, Err(error) => { // It's probably more crucial to store the // `states_current` // error than the states goal error, if both err. if item_error.is_none() { item_error = Some(error); } None } } } else { None }; if let Some(error) = item_error { outcomes_tx .send(ItemDiscoverOutcome::Fail { item_id: item_id.clone(), state_current, state_goal, error, }) .await .expect("unreachable: `outcomes_rx` is in a sibling task."); } else { outcomes_tx .send(ItemDiscoverOutcome::Success { item_id: item_id.clone(), state_current, state_goal, }) .await .expect("unreachable: `outcomes_rx` is in a sibling task."); } } #[cfg(feature = "output_progress")] fn discover_progress_update( progress_complete_on_success: bool, states_current_result: Option< &Result<Option<BoxDtDisplay>, <CmdCtxTypesT as CmdCtxTypes>::AppError>, >, states_goal_result: Option< &Result<Option<BoxDtDisplay>, <CmdCtxTypesT as CmdCtxTypes>::AppError>, >, progress_tx: &Sender<CmdProgressUpdate>, item_id: &ItemId, ) { if let Some((progress_update, msg_update)) = DiscoverFor::progress_update( progress_complete_on_success, states_current_result, states_goal_result, ) { let _progress_send_unused = progress_tx.try_send( ProgressUpdateAndId { item_id: item_id.clone(), progress_update, msg_update, } .into(), ); } } } #[derive(Debug)] pub enum ItemDiscoverOutcome<AppErrorT> { /// Discover succeeded. Success { item_id: ItemId, state_current: Option<BoxDtDisplay>, state_goal: Option<BoxDtDisplay>, }, /// Discover failed. Fail { item_id: ItemId, state_current: Option<BoxDtDisplay>, state_goal: Option<BoxDtDisplay>, error: AppErrorT, }, } #[async_trait(?Send)] impl<CmdCtxTypesT> CmdBlock for StatesDiscoverCmdBlock<CmdCtxTypesT, DiscoverForCurrent> where CmdCtxTypesT: CmdCtxTypes, { type CmdCtxTypes = CmdCtxTypesT; type InputT = (); type Outcome = States<Current>; #[cfg(feature = "output_progress")] fn cmd_block_item_interaction_type(&self) -> CmdBlockItemInteractionType { CmdBlockItemInteractionType::Read } fn input_fetch(&self, _resources: &mut Resources<SetUp>) -> Result<(), ResourceFetchError> { Ok(()) } fn input_type_names(&self) -> Vec<String> { vec![] } async fn exec( &self, _input: Self::InputT, cmd_ctx_spsf_fields: &mut CmdCtxSpsfFields<'_, Self::CmdCtxTypes>, #[cfg(feature = "output_progress")] progress_tx: &Sender<CmdProgressUpdate>, ) -> Result< CmdBlockOutcome<Self::Outcome, <Self::CmdCtxTypes as CmdCtxTypes>::AppError>, <Self::CmdCtxTypes as CmdCtxTypes>::AppError, > { let CmdCtxSpsfFields { interruptibility_state, flow, params_specs, mapping_fn_reg, resources, .. } = cmd_ctx_spsf_fields; let (outcomes_tx, outcomes_rx) = mpsc::channel::< ItemDiscoverOutcome<<CmdCtxTypesT as CmdCtxTypes>::AppError>, >(flow.graph().node_count()); let (stream_outcome, outcome_collate) = { let states_current_mut = StatesMut::<Current>::with_capacity(flow.graph().node_count()); let item_states_discover_task = async move { let stream_outcome = flow .graph() .for_each_concurrent_with( BUFFERED_FUTURES_MAX, StreamOpts::new() .interruptibility_state(interruptibility_state.reborrow()) .interrupted_next_item_include(false), |item| { Self::item_states_discover( #[cfg(feature = "output_progress")] progress_tx, #[cfg(feature = "output_progress")] self.progress_complete_on_success, params_specs, mapping_fn_reg, resources, &outcomes_tx, item, ) }, ) .await; drop(outcomes_tx); stream_outcome }; let outcome_collate_task = Self::outcome_collate_task(outcomes_rx, states_current_mut); join!(item_states_discover_task, outcome_collate_task) }; outcome_collate.map(|(states_current, errors)| { let (stream_outcome, ()) = stream_outcome.replace(states_current); CmdBlockOutcome::ItemWise { stream_outcome, errors, } }) } } impl<CmdCtxTypesT> StatesDiscoverCmdBlock<CmdCtxTypesT, DiscoverForCurrent> where CmdCtxTypesT: CmdCtxTypes, { async fn outcome_collate_task( mut outcomes_rx: Receiver<ItemDiscoverOutcome<<CmdCtxTypesT as CmdCtxTypes>::AppError>>, mut states_current_mut: StatesMut<Current>, ) -> Result< ( States<Current>, IndexMap<ItemId, <CmdCtxTypesT as CmdCtxTypes>::AppError>, ), <CmdCtxTypesT as CmdCtxTypes>::AppError, > { let mut errors = IndexMap::new(); while let Some(item_outcome) = outcomes_rx.recv().await { Self::outcome_collate(&mut states_current_mut, &mut errors, item_outcome)?; } let states_current = States::<Current>::from(states_current_mut); Ok((states_current, errors)) } fn outcome_collate( states_current_mut: &mut StatesMut<Current>, errors: &mut IndexMap<ItemId, <CmdCtxTypesT as CmdCtxTypes>::AppError>, outcome_partial: ItemDiscoverOutcome<<CmdCtxTypesT as CmdCtxTypes>::AppError>, ) -> Result<(), <CmdCtxTypesT as CmdCtxTypes>::AppError> { match outcome_partial { ItemDiscoverOutcome::Success { item_id, state_current, state_goal: _, } => { if let Some(state_current) = state_current { states_current_mut.insert_raw(item_id.clone(), state_current); } } ItemDiscoverOutcome::Fail { item_id, state_current, state_goal: _, error, } => { errors.insert(item_id.clone(), error); if let Some(state_current) = state_current { states_current_mut.insert_raw(item_id.clone(), state_current); } } } Ok(()) } } #[async_trait(?Send)] impl<CmdCtxTypesT> CmdBlock for StatesDiscoverCmdBlock<CmdCtxTypesT, DiscoverForGoal> where CmdCtxTypesT: CmdCtxTypes, { type CmdCtxTypes = CmdCtxTypesT; type InputT = (); type Outcome = States<Goal>; #[cfg(feature = "output_progress")] fn cmd_block_item_interaction_type(&self) -> CmdBlockItemInteractionType { CmdBlockItemInteractionType::Read } fn input_fetch(&self, _resources: &mut Resources<SetUp>) -> Result<(), ResourceFetchError> { Ok(()) } fn input_type_names(&self) -> Vec<String> { vec![] } async fn exec( &self, _input: Self::InputT, cmd_ctx_spsf_fields: &mut CmdCtxSpsfFields<'_, Self::CmdCtxTypes>, #[cfg(feature = "output_progress")] progress_tx: &Sender<CmdProgressUpdate>, ) -> Result< CmdBlockOutcome<Self::Outcome, <Self::CmdCtxTypes as CmdCtxTypes>::AppError>, <Self::CmdCtxTypes as CmdCtxTypes>::AppError, > { let CmdCtxSpsfFields { interruptibility_state, flow, params_specs, mapping_fn_reg, resources, .. } = cmd_ctx_spsf_fields; let (outcomes_tx, outcomes_rx) = mpsc::channel::< ItemDiscoverOutcome<<CmdCtxTypesT as CmdCtxTypes>::AppError>, >(flow.graph().node_count()); let (stream_outcome, outcome_collate) = { let states_goal_mut = StatesMut::<Goal>::with_capacity(flow.graph().node_count()); let item_states_discover_task = async move { let stream_outcome = flow .graph() .for_each_concurrent_with( BUFFERED_FUTURES_MAX, StreamOpts::new() .interruptibility_state(interruptibility_state.reborrow()) .interrupted_next_item_include(false), |item| { Self::item_states_discover( #[cfg(feature = "output_progress")] progress_tx, #[cfg(feature = "output_progress")] self.progress_complete_on_success, params_specs, mapping_fn_reg, resources, &outcomes_tx, item, ) }, ) .await; drop(outcomes_tx); stream_outcome }; let outcome_collate_task = Self::outcome_collate_task(outcomes_rx, states_goal_mut); join!(item_states_discover_task, outcome_collate_task) }; outcome_collate.map(|(states_goal, errors)| { let (stream_outcome, ()) = stream_outcome.replace(states_goal); CmdBlockOutcome::ItemWise { stream_outcome, errors, } }) } } impl<CmdCtxTypesT> StatesDiscoverCmdBlock<CmdCtxTypesT, DiscoverForGoal> where CmdCtxTypesT: CmdCtxTypes, { async fn outcome_collate_task( mut outcomes_rx: Receiver<ItemDiscoverOutcome<<CmdCtxTypesT as CmdCtxTypes>::AppError>>, mut states_goal_mut: StatesMut<Goal>, ) -> Result< ( States<Goal>, IndexMap<ItemId, <CmdCtxTypesT as CmdCtxTypes>::AppError>, ), <CmdCtxTypesT as CmdCtxTypes>::AppError, > { let mut errors = IndexMap::new(); while let Some(item_outcome) = outcomes_rx.recv().await { Self::outcome_collate(&mut states_goal_mut, &mut errors, item_outcome)?; } let states_goal = States::<Goal>::from(states_goal_mut); Ok((states_goal, errors)) } fn outcome_collate( states_goal_mut: &mut StatesMut<Goal>, errors: &mut IndexMap<ItemId, <CmdCtxTypesT as CmdCtxTypes>::AppError>, outcome_partial: ItemDiscoverOutcome<<CmdCtxTypesT as CmdCtxTypes>::AppError>, ) -> Result<(), <CmdCtxTypesT as CmdCtxTypes>::AppError> { match outcome_partial { ItemDiscoverOutcome::Success { item_id, state_current: _, state_goal, } => { if let Some(state_goal) = state_goal { states_goal_mut.insert_raw(item_id, state_goal); } } ItemDiscoverOutcome::Fail { item_id, state_current: _, state_goal, error, } => { errors.insert(item_id.clone(), error); if let Some(state_goal) = state_goal { states_goal_mut.insert_raw(item_id, state_goal); } } } Ok(()) } } #[async_trait(?Send)] impl<CmdCtxTypesT> CmdBlock for StatesDiscoverCmdBlock<CmdCtxTypesT, DiscoverForCurrentAndGoal> where CmdCtxTypesT: CmdCtxTypes, { type CmdCtxTypes = CmdCtxTypesT; type InputT = (); type Outcome = (States<Current>, States<Goal>); #[cfg(feature = "output_progress")] fn cmd_block_item_interaction_type(&self) -> CmdBlockItemInteractionType { CmdBlockItemInteractionType::Read } fn input_fetch(&self, _resources: &mut Resources<SetUp>) -> Result<(), ResourceFetchError> { Ok(()) } fn input_type_names(&self) -> Vec<String> { vec![] } fn outcome_insert(&self, resources: &mut Resources<SetUp>, outcome: Self::Outcome) { let (states_current, states_goal) = outcome; resources.insert(states_current); resources.insert(states_goal); } fn outcome_type_names(&self) -> Vec<String> { vec![ tynm::type_name::<StatesCurrent>(), tynm::type_name::<StatesGoal>(), ] } async fn exec( &self, _input: Self::InputT, cmd_ctx_spsf_fields: &mut CmdCtxSpsfFields<'_, Self::CmdCtxTypes>, #[cfg(feature = "output_progress")] progress_tx: &Sender<CmdProgressUpdate>, ) -> Result< CmdBlockOutcome<Self::Outcome, <Self::CmdCtxTypes as CmdCtxTypes>::AppError>, <Self::CmdCtxTypes as CmdCtxTypes>::AppError, > { let CmdCtxSpsfFields { interruptibility_state, flow, params_specs, mapping_fn_reg, resources, .. } = cmd_ctx_spsf_fields; let (outcomes_tx, outcomes_rx) = mpsc::channel::< ItemDiscoverOutcome<<CmdCtxTypesT as CmdCtxTypes>::AppError>, >(flow.graph().node_count()); let (stream_outcome, outcome_collate) = { let states_current_mut = StatesMut::<Current>::with_capacity(flow.graph().node_count()); let states_goal_mut = StatesMut::<Goal>::with_capacity(flow.graph().node_count()); let item_states_discover_task = async move { let stream_outcome = flow .graph() .for_each_concurrent_with( BUFFERED_FUTURES_MAX, StreamOpts::new() .interruptibility_state(interruptibility_state.reborrow()) .interrupted_next_item_include(false), |item| { Self::item_states_discover( #[cfg(feature = "output_progress")] progress_tx, #[cfg(feature = "output_progress")] self.progress_complete_on_success, params_specs, mapping_fn_reg, resources, &outcomes_tx, item, ) }, ) .await; drop(outcomes_tx); stream_outcome }; let outcome_collate_task = Self::outcome_collate_task(outcomes_rx, states_current_mut, states_goal_mut); join!(item_states_discover_task, outcome_collate_task) }; outcome_collate.map(|(states_current, states_goal, errors)| { let (stream_outcome, ()) = stream_outcome.replace((states_current, states_goal)); CmdBlockOutcome::ItemWise { stream_outcome, errors, } }) } } impl<CmdCtxTypesT> StatesDiscoverCmdBlock<CmdCtxTypesT, DiscoverForCurrentAndGoal> where CmdCtxTypesT: CmdCtxTypes, { async fn outcome_collate_task( mut outcomes_rx: Receiver<ItemDiscoverOutcome<<CmdCtxTypesT as CmdCtxTypes>::AppError>>, mut states_current_mut: StatesMut<Current>, mut states_goal_mut: StatesMut<Goal>, ) -> Result< ( States<Current>, States<Goal>, IndexMap<ItemId, <CmdCtxTypesT as CmdCtxTypes>::AppError>, ), <CmdCtxTypesT as CmdCtxTypes>::AppError, > { let mut errors = IndexMap::new(); while let Some(item_outcome) = outcomes_rx.recv().await { Self::outcome_collate( &mut states_current_mut, &mut states_goal_mut, &mut errors, item_outcome, )?; } let states_current = States::<Current>::from(states_current_mut); let states_goal = States::<Goal>::from(states_goal_mut); Ok((states_current, states_goal, errors)) } fn outcome_collate( states_current_mut: &mut StatesMut<Current>, states_goal_mut: &mut StatesMut<Goal>, errors: &mut IndexMap<ItemId, <CmdCtxTypesT as CmdCtxTypes>::AppError>, outcome_partial: ItemDiscoverOutcome<<CmdCtxTypesT as CmdCtxTypes>::AppError>, ) -> Result<(), <CmdCtxTypesT as CmdCtxTypes>::AppError> { match outcome_partial { ItemDiscoverOutcome::Success { item_id, state_current, state_goal, } => { if let Some(state_current) = state_current { states_current_mut.insert_raw(item_id.clone(), state_current); } if let Some(state_goal) = state_goal { states_goal_mut.insert_raw(item_id, state_goal); } } ItemDiscoverOutcome::Fail { item_id, state_current, state_goal, error, } => { errors.insert(item_id.clone(), error); if let Some(state_current) = state_current { states_current_mut.insert_raw(item_id.clone(), state_current); } if let Some(state_goal) = state_goal { states_goal_mut.insert_raw(item_id, state_goal); } } } Ok(()) } } /// Behaviour for each discover variant. #[async_trait::async_trait(?Send)] pub trait Discover { async fn discover<AppErrorT>( item: &ItemBoxed<AppErrorT>, params_specs: &peace_params::ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, fn_ctx: FnCtx<'_>, ) -> ( Option<Result<Option<BoxDtDisplay>, AppErrorT>>, Option<Result<Option<BoxDtDisplay>, AppErrorT>>, ) where AppErrorT: peace_value_traits::AppError + From<peace_rt_model::Error>; #[cfg(feature = "output_progress")] fn progress_update<AppErrorT>( progress_complete_on_success: bool, states_current_result: Option<&Result<Option<BoxDtDisplay>, AppErrorT>>, states_goal_result: Option<&Result<Option<BoxDtDisplay>, AppErrorT>>, ) -> Option<(ProgressUpdate, ProgressMsgUpdate)> where AppErrorT: peace_value_traits::AppError + From<peace_rt_model::Error>; } #[async_trait::async_trait(?Send)] impl Discover for DiscoverForCurrent { async fn discover<AppErrorT>( item: &ItemBoxed<AppErrorT>, params_specs: &peace_params::ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, fn_ctx: FnCtx<'_>, ) -> ( Option<Result<Option<BoxDtDisplay>, AppErrorT>>, Option<Result<Option<BoxDtDisplay>, AppErrorT>>, ) where AppErrorT: peace_value_traits::AppError + From<peace_rt_model::Error>, { let states_current_result = item .state_current_try_exec(params_specs, mapping_fn_reg, resources, fn_ctx) .await; (Some(states_current_result), None) } #[cfg(feature = "output_progress")] fn progress_update<AppErrorT>( progress_complete_on_success: bool, states_current_result: Option<&Result<Option<BoxDtDisplay>, AppErrorT>>, _states_goal_result: Option<&Result<Option<BoxDtDisplay>, AppErrorT>>, ) -> Option<(ProgressUpdate, ProgressMsgUpdate)> where AppErrorT: peace_value_traits::AppError + From<peace_rt_model::Error>, { states_current_result.map(|states_current_result| match states_current_result { Ok(_) => { let progress_update = if progress_complete_on_success { ProgressUpdate::Complete(ProgressComplete::Success) } else { ProgressUpdate::Delta(ProgressDelta::Tick) }; (progress_update, ProgressMsgUpdate::Clear) } Err(error) => ( ProgressUpdate::Complete(ProgressComplete::Fail), ProgressMsgUpdate::Set(format!("{error}")), ), }) } } #[async_trait::async_trait(?Send)] impl Discover for DiscoverForGoal { async fn discover<AppErrorT>( item: &ItemBoxed<AppErrorT>, params_specs: &peace_params::ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, fn_ctx: FnCtx<'_>, ) -> ( Option<Result<Option<BoxDtDisplay>, AppErrorT>>, Option<Result<Option<BoxDtDisplay>, AppErrorT>>, ) where AppErrorT: peace_value_traits::AppError + From<peace_rt_model::Error>, { let states_goal_result = item .state_goal_try_exec(params_specs, mapping_fn_reg, resources, fn_ctx) .await; (None, Some(states_goal_result)) } #[cfg(feature = "output_progress")] fn progress_update<AppErrorT>( progress_complete_on_success: bool, _states_current_result: Option<&Result<Option<BoxDtDisplay>, AppErrorT>>, states_goal_result: Option<&Result<Option<BoxDtDisplay>, AppErrorT>>, ) -> Option<(ProgressUpdate, ProgressMsgUpdate)> where AppErrorT: peace_value_traits::AppError + From<peace_rt_model::Error>, { states_goal_result.map(|states_goal_result| match states_goal_result { Ok(_) => { let progress_update = if progress_complete_on_success { ProgressUpdate::Complete(ProgressComplete::Success) } else { ProgressUpdate::Delta(ProgressDelta::Tick) }; (progress_update, ProgressMsgUpdate::Clear) } Err(error) => ( ProgressUpdate::Complete(ProgressComplete::Fail), ProgressMsgUpdate::Set(format!("{error}")), ), }) } } #[async_trait::async_trait(?Send)] impl Discover for DiscoverForCurrentAndGoal { async fn discover<AppErrorT>( item: &ItemBoxed<AppErrorT>, params_specs: &peace_params::ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, fn_ctx: FnCtx<'_>, ) -> ( Option<Result<Option<BoxDtDisplay>, AppErrorT>>, Option<Result<Option<BoxDtDisplay>, AppErrorT>>, ) where AppErrorT: peace_value_traits::AppError + From<peace_rt_model::Error>, { let states_current_result = item .state_current_try_exec(params_specs, mapping_fn_reg, resources, fn_ctx) .await; let states_goal_result = item .state_goal_try_exec(params_specs, mapping_fn_reg, resources, fn_ctx) .await; (Some(states_current_result), Some(states_goal_result)) } #[cfg(feature = "output_progress")] fn progress_update<AppErrorT>( progress_complete_on_success: bool, states_current_result: Option<&Result<Option<BoxDtDisplay>, AppErrorT>>, states_goal_result: Option<&Result<Option<BoxDtDisplay>, AppErrorT>>, ) -> Option<(ProgressUpdate, ProgressMsgUpdate)> where AppErrorT: peace_value_traits::AppError + From<peace_rt_model::Error>, { states_current_result .zip(states_goal_result) .map( |states_current_and_states_goal_result| match states_current_and_states_goal_result { (Ok(_), Ok(_)) => { let progress_update = if progress_complete_on_success { ProgressUpdate::Complete(ProgressComplete::Success) } else { ProgressUpdate::Delta(ProgressDelta::Tick) }; (progress_update, ProgressMsgUpdate::Clear) } (Ok(_), Err(error)) | (Err(error), Ok(_)) => ( ProgressUpdate::Complete(ProgressComplete::Fail), ProgressMsgUpdate::Set(format!("{error}")), ), (Err(error_current), Err(error_goal)) => ( ProgressUpdate::Complete(ProgressComplete::Fail), ProgressMsgUpdate::Set(format!("{error_current}, {error_goal}")), ), }, ) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt/src/cmd_blocks/apply_exec_cmd_block.rs
crate/rt/src/cmd_blocks/apply_exec_cmd_block.rs
use std::{fmt::Debug, marker::PhantomData}; use fn_graph::{StreamOpts, StreamOutcome}; use futures::join; use peace_cfg::{ApplyCheck, FnCtx}; use peace_cmd_ctx::{CmdCtxSpsfFields, CmdCtxTypes}; use peace_cmd_model::CmdBlockOutcome; use peace_cmd_rt::{async_trait, CmdBlock}; use peace_item_model::ItemId; use peace_params::{MappingFnReg, ParamsSpecs}; use peace_resource_rt::{ internal::StatesMut, resources::ts::SetUp, states::{ ts::{Clean, Cleaned, CleanedDry, Ensured, EnsuredDry, Goal}, States, StatesCurrent, StatesPrevious, }, ResourceFetchError, Resources, }; use peace_rt_model::{ outcomes::{ItemApplyBoxed, ItemApplyPartialBoxed}, ItemBoxed, ItemRt, }; use tokio::sync::mpsc::{self, Receiver}; use peace_rt_model_core::IndexMap; use tokio::sync::mpsc::Sender; use crate::BUFFERED_FUTURES_MAX; cfg_if::cfg_if! { if #[cfg(feature = "output_progress")] { use std::error::Error; use peace_progress_model::{ CmdBlockItemInteractionType, CmdProgressUpdate, ProgressComplete, ProgressMsgUpdate, ProgressUpdate, ProgressUpdateAndId, ProgressSender, }; } } /// Stops a `CmdExecution` if stored states and discovered states are not in /// sync. pub struct ApplyExecCmdBlock<CmdCtxTypesT, StatesTs>(PhantomData<(CmdCtxTypesT, StatesTs)>); impl<CmdCtxTypesT, StatesTs> Debug for ApplyExecCmdBlock<CmdCtxTypesT, StatesTs> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_tuple("ApplyExecCmdBlock").field(&self.0).finish() } } impl<CmdCtxTypesT, StatesTs> ApplyExecCmdBlock<CmdCtxTypesT, StatesTs> { /// Returns an `ApplyExecCmdBlock`. /// /// This is a generic constructor where `StatesTs` determines whether the /// goal state or clean state is the target state. pub fn new() -> Self { Self(PhantomData) } } impl<CmdCtxTypesT, StatesTs> Default for ApplyExecCmdBlock<CmdCtxTypesT, StatesTs> { fn default() -> Self { Self(PhantomData) } } impl<CmdCtxTypesT> ApplyExecCmdBlock<CmdCtxTypesT, Ensured> where CmdCtxTypesT: CmdCtxTypes, { /// Returns an `ApplyExecCmdBlock` with the goal state as the target state. pub fn ensure() -> Self { Self(PhantomData) } } impl<CmdCtxTypesT> ApplyExecCmdBlock<CmdCtxTypesT, EnsuredDry> where CmdCtxTypesT: CmdCtxTypes, { /// Returns an `ApplyExecCmdBlock` with the goal state as the target state. pub fn ensure_dry() -> Self { Self(PhantomData) } } impl<CmdCtxTypesT> ApplyExecCmdBlock<CmdCtxTypesT, Cleaned> where CmdCtxTypesT: CmdCtxTypes, { /// Returns an `ApplyExecCmdBlock` with the clean state as the target state. pub fn clean() -> Self { Self(PhantomData) } } impl<CmdCtxTypesT> ApplyExecCmdBlock<CmdCtxTypesT, CleanedDry> where CmdCtxTypesT: CmdCtxTypes, { /// Returns an `ApplyExecCmdBlock` with the clean state as the target state. pub fn clean_dry() -> Self { Self(PhantomData) } } impl<CmdCtxTypesT, StatesTs> ApplyExecCmdBlock<CmdCtxTypesT, StatesTs> where CmdCtxTypesT: CmdCtxTypes, StatesTs: StatesTsApplyExt + Debug + Send, { /// /// # Implementation Note /// /// Tried passing through the function to execute instead of a `dry_run` /// parameter, but couldn't convince the compiler that the lifetimes match /// up: /// /// ```rust,ignore /// async fn item_apply_exec<F, Fut>( /// resources: &Resources<SetUp>, /// outcomes_tx: &Sender<ItemApplyOutcome<<CmdCtxTypesT as CmdCtxTypes>::AppError>>, /// item: FnRef<'_, ItemBoxed<<CmdCtxTypesT as CmdCtxTypes>::AppError>>, /// f: F, /// ) -> bool /// where /// F: (Fn(&dyn ItemRt<<CmdCtxTypesT as CmdCtxTypes>::AppError>, fn_ctx: OpCtx<'_>, &Resources<SetUp>, &mut ItemApplyBoxed) -> Fut) + Copy, /// Fut: Future<Output = Result<(), <CmdCtxTypesT as CmdCtxTypes>::AppError>>, /// ``` async fn item_apply_exec( item_apply_exec_ctx: ItemApplyExecCtx<'_, <CmdCtxTypesT as CmdCtxTypes>::AppError>, item: &ItemBoxed<<CmdCtxTypesT as CmdCtxTypes>::AppError>, ) -> Result<(), ()> { let ItemApplyExecCtx { params_specs, mapping_fn_reg, resources, apply_for_internal, #[cfg(feature = "output_progress")] progress_tx, outcomes_tx, } = item_apply_exec_ctx; let item_id = item.id(); // Indicate this item is running, so that an `Interrupt` message from // `CmdExecution` does not cause it to be rendered as `Interrupted`. #[cfg(feature = "output_progress")] let _progress_send_unused = progress_tx.try_send( ProgressUpdateAndId { item_id: item_id.clone(), progress_update: ProgressUpdate::Queued, msg_update: ProgressMsgUpdate::NoChange, } .into(), ); let apply_fn = if StatesTs::dry_run() { ItemRt::apply_exec_dry } else { ItemRt::apply_exec }; let fn_ctx = FnCtx::new( item_id, #[cfg(feature = "output_progress")] ProgressSender::new(item_id, progress_tx), ); let item_apply = match apply_for_internal { ApplyForInternal::Ensure => { ItemRt::ensure_prepare(&**item, params_specs, mapping_fn_reg, resources, fn_ctx) .await } ApplyForInternal::Clean { states_current } => { ItemRt::clean_prepare( &**item, states_current, params_specs, mapping_fn_reg, resources, ) .await } }; match item_apply { Ok(mut item_apply) => { match item_apply.apply_check() { #[cfg(not(feature = "output_progress"))] ApplyCheck::ExecRequired => {} #[cfg(feature = "output_progress")] ApplyCheck::ExecRequired { progress_limit } => { // Update `OutputWrite`s with progress limit. let _progress_send_unused = progress_tx.try_send( ProgressUpdateAndId { item_id: item_id.clone(), progress_update: ProgressUpdate::Limit(progress_limit), msg_update: ProgressMsgUpdate::Set(String::from("in progress")), } .into(), ); } ApplyCheck::ExecNotRequired => { #[cfg(feature = "output_progress")] let _progress_send_unused = progress_tx.try_send( ProgressUpdateAndId { item_id: item_id.clone(), progress_update: ProgressUpdate::Complete( ProgressComplete::Success, ), msg_update: ProgressMsgUpdate::Set(String::from("nothing to do!")), } .into(), ); // TODO: write test for this case // In case of an interrupt or power failure, we may not have written states // to disk. outcomes_tx .send(ItemApplyOutcome::Success { item_id: item.id().clone(), item_apply, }) .await .expect("unreachable: `outcomes_rx` is in a sibling task."); // short-circuit return Ok(()); } } match apply_fn( &**item, params_specs, mapping_fn_reg, resources, fn_ctx, &mut item_apply, ) .await { Ok(()) => { // apply succeeded #[cfg(feature = "output_progress")] let _progress_send_unused = progress_tx.try_send( ProgressUpdateAndId { item_id: item_id.clone(), progress_update: ProgressUpdate::Complete( ProgressComplete::Success, ), msg_update: ProgressMsgUpdate::Set(String::from("done!")), } .into(), ); outcomes_tx .send(ItemApplyOutcome::Success { item_id: item.id().clone(), item_apply, }) .await .expect("unreachable: `outcomes_rx` is in a sibling task."); Ok(()) } Err(error) => { // apply failed #[cfg(feature = "output_progress")] let _progress_send_unused = progress_tx.try_send( ProgressUpdateAndId { item_id: item_id.clone(), progress_update: ProgressUpdate::Complete(ProgressComplete::Fail), msg_update: ProgressMsgUpdate::Set( error .source() .map(|source| format!("{source}")) .unwrap_or_else(|| format!("{error}")), ), } .into(), ); outcomes_tx .send(ItemApplyOutcome::Fail { item_id: item.id().clone(), item_apply, error, }) .await .expect("unreachable: `outcomes_rx` is in a sibling task."); // we should stop processing. Err(()) } } } Err((error, item_apply_partial)) => { #[cfg(feature = "output_progress")] let _progress_send_unused = progress_tx.try_send( ProgressUpdateAndId { item_id: item.id().clone(), progress_update: ProgressUpdate::Complete(ProgressComplete::Fail), msg_update: ProgressMsgUpdate::Set( error .source() .map(|source| format!("{source}")) .unwrap_or_else(|| format!("{error}")), ), } .into(), ); outcomes_tx .send(ItemApplyOutcome::PrepareFail { item_id: item.id().clone(), item_apply_partial, error, }) .await .expect("unreachable: `outcomes_rx` is in a sibling task."); Err(()) } } } async fn outcome_collate_task( mut outcomes_rx: Receiver<ItemApplyOutcome<<CmdCtxTypesT as CmdCtxTypes>::AppError>>, mut states_applied_mut: StatesMut<StatesTs>, mut states_target_mut: StatesMut<StatesTs::TsTarget>, ) -> Result< ( States<StatesTs>, States<StatesTs::TsTarget>, IndexMap<ItemId, <CmdCtxTypesT as CmdCtxTypes>::AppError>, ), <CmdCtxTypesT as CmdCtxTypes>::AppError, > { let mut errors = IndexMap::new(); while let Some(item_outcome) = outcomes_rx.recv().await { Self::outcome_collate( &mut states_applied_mut, &mut states_target_mut, &mut errors, item_outcome, )?; } let states_applied = States::<StatesTs>::from(states_applied_mut); let states_target = States::<StatesTs::TsTarget>::from(states_target_mut); Ok((states_applied, states_target, errors)) } fn outcome_collate( states_applied_mut: &mut StatesMut<StatesTs>, states_target_mut: &mut StatesMut<StatesTs::TsTarget>, errors: &mut IndexMap<ItemId, <CmdCtxTypesT as CmdCtxTypes>::AppError>, outcome_partial: ItemApplyOutcome<<CmdCtxTypesT as CmdCtxTypes>::AppError>, ) -> Result<(), <CmdCtxTypesT as CmdCtxTypes>::AppError> { let apply_for = StatesTs::apply_for(); match outcome_partial { ItemApplyOutcome::PrepareFail { item_id, item_apply_partial, error, } => { errors.insert(item_id.clone(), error); // Save `state_target` (which is `state_goal`) if we are not cleaning // up. match apply_for { ApplyFor::Ensure => { if let Some(state_target) = item_apply_partial.state_target() { states_target_mut.insert_raw(item_id, state_target); } } ApplyFor::Clean => {} } } ItemApplyOutcome::Success { item_id, item_apply, } => { if let Some(state_applied) = item_apply.state_applied() { states_applied_mut.insert_raw(item_id.clone(), state_applied); } else { // Item was already in the goal state. // No change to current state. } // Save `state_target` (which is state_target) if we are not cleaning // up. match apply_for { ApplyFor::Ensure => { let state_target = item_apply.state_target(); states_target_mut.insert_raw(item_id, state_target); } ApplyFor::Clean => {} } } ItemApplyOutcome::Fail { item_id, item_apply, error, } => { errors.insert(item_id.clone(), error); if let Some(state_applied) = item_apply.state_applied() { states_applied_mut.insert_raw(item_id.clone(), state_applied); } // Save `state_target` (which is `state_goal`) if we are not cleaning // up. match apply_for { ApplyFor::Ensure => { let state_target = item_apply.state_target(); states_target_mut.insert_raw(item_id, state_target); } ApplyFor::Clean => {} } } } Ok(()) } } #[async_trait(?Send)] impl<CmdCtxTypesT, StatesTs> CmdBlock for ApplyExecCmdBlock<CmdCtxTypesT, StatesTs> where CmdCtxTypesT: CmdCtxTypes, StatesTs: StatesTsApplyExt + Debug + Send + Sync + 'static, { type CmdCtxTypes = CmdCtxTypesT; type InputT = (StatesCurrent, States<StatesTs::TsTarget>); type Outcome = (StatesPrevious, States<StatesTs>, States<StatesTs::TsTarget>); #[cfg(feature = "output_progress")] fn cmd_block_item_interaction_type(&self) -> CmdBlockItemInteractionType { CmdBlockItemInteractionType::Write } fn input_fetch( &self, resources: &mut Resources<SetUp>, ) -> Result<Self::InputT, ResourceFetchError> { let states_current = resources.try_remove::<StatesCurrent>()?; let states_target = resources.try_remove::<States<StatesTs::TsTarget>>()?; Ok((states_current, states_target)) } fn input_type_names(&self) -> Vec<String> { vec![ tynm::type_name::<StatesCurrent>(), tynm::type_name::<States<StatesTs::TsTarget>>(), ] } fn outcome_insert(&self, resources: &mut Resources<SetUp>, outcome: Self::Outcome) { let (states_previous, states_applied, states_target) = outcome; resources.insert(states_previous); resources.insert(states_applied); resources.insert(states_target); } fn outcome_type_names(&self) -> Vec<String> { vec![ tynm::type_name::<StatesPrevious>(), tynm::type_name::<States<StatesTs>>(), tynm::type_name::<States<StatesTs::TsTarget>>(), ] } async fn exec( &self, input: Self::InputT, cmd_ctx_spsf_fields: &mut CmdCtxSpsfFields<'_, Self::CmdCtxTypes>, #[cfg(feature = "output_progress")] progress_tx: &Sender<CmdProgressUpdate>, ) -> Result< CmdBlockOutcome<Self::Outcome, <Self::CmdCtxTypes as CmdCtxTypes>::AppError>, <Self::CmdCtxTypes as CmdCtxTypes>::AppError, > { let (states_current, states_target) = input; let (states_previous, states_applied_mut, states_target_mut) = { let states_previous = StatesPrevious::from(states_current.clone()); // `Ensured`, `EnsuredDry`, `Cleaned`, `CleanedDry` states start as the current // state, and are altered. let states_applied_mut = StatesMut::<StatesTs>::from(states_current.clone().into_inner()); let states_target_mut = StatesMut::<StatesTs::TsTarget>::from(states_target.clone().into_inner()); (states_previous, states_applied_mut, states_target_mut) }; let CmdCtxSpsfFields { interruptibility_state, flow, params_specs, mapping_fn_reg, resources, .. } = cmd_ctx_spsf_fields; let item_graph = flow.graph(); let resources_ref = &*resources; let apply_for = StatesTs::apply_for(); let apply_for_internal = match apply_for { ApplyFor::Ensure => ApplyForInternal::Ensure, ApplyFor::Clean => ApplyForInternal::Clean { states_current }, }; let (outcomes_tx, outcomes_rx) = mpsc::channel::< ItemApplyOutcome<<CmdCtxTypesT as CmdCtxTypes>::AppError>, >(item_graph.node_count()); let stream_opts = { let stream_opts = StreamOpts::new() .interruptibility_state(interruptibility_state.reborrow()) .interrupted_next_item_include(false); match apply_for { ApplyFor::Ensure => stream_opts, ApplyFor::Clean => stream_opts.rev(), } }; let (stream_outcome_result, outcome_collate) = { let item_apply_exec_task = async move { let stream_outcome = item_graph .try_for_each_concurrent_with(BUFFERED_FUTURES_MAX, stream_opts, |item| { let item_apply_exec_ctx = ItemApplyExecCtx { params_specs, mapping_fn_reg, resources: resources_ref, apply_for_internal: &apply_for_internal, #[cfg(feature = "output_progress")] progress_tx, outcomes_tx: &outcomes_tx, }; Self::item_apply_exec(item_apply_exec_ctx, item) }) .await; drop(outcomes_tx); stream_outcome }; let outcome_collate_task = Self::outcome_collate_task(outcomes_rx, states_applied_mut, states_target_mut); join!(item_apply_exec_task, outcome_collate_task) }; let (states_applied, states_target, errors) = outcome_collate?; let stream_outcome = { let (Ok(stream_outcome) | Err((stream_outcome, ()))) = stream_outcome_result.map_err( |(stream_outcome, _vec_unit): (StreamOutcome<()>, Vec<()>)| (stream_outcome, ()), ); stream_outcome.map(|()| (states_previous, states_applied, states_target)) }; Ok(CmdBlockOutcome::ItemWise { stream_outcome, errors, }) } } /// Whether the `ApplyCmd` is for `Ensure` or `Clean`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ApplyFor { /// The apply target state is `state_goal`. Ensure, /// The apply target state is `state_clean`. Clean, } /// Whether the `ApplyCmd` is for `Ensure` or `Clean`. #[derive(Debug)] enum ApplyForInternal { Ensure, Clean { states_current: StatesCurrent }, } struct ItemApplyExecCtx<'f, E> { /// Map of item ID to its params' specs. params_specs: &'f ParamsSpecs, /// Map of `MappingFnId` to its `MappingFn` logic. mapping_fn_reg: &'f MappingFnReg, /// Map of all types at runtime. resources: &'f Resources<SetUp>, /// Whether the `ApplyCmd` is for `Ensure` or `Clean`. apply_for_internal: &'f ApplyForInternal, /// Channel sender for `CmdBlock` item outcomes. #[cfg(feature = "output_progress")] progress_tx: &'f Sender<CmdProgressUpdate>, outcomes_tx: &'f Sender<ItemApplyOutcome<E>>, } #[derive(Debug)] pub enum ItemApplyOutcome<E> { /// Error occurred when discovering current state, goal states, state /// diff, or `ApplyCheck`. PrepareFail { item_id: ItemId, item_apply_partial: ItemApplyPartialBoxed, error: E, }, /// Ensure execution succeeded. Success { item_id: ItemId, item_apply: ItemApplyBoxed, }, /// Ensure execution failed. Fail { item_id: ItemId, item_apply: ItemApplyBoxed, error: E, }, } /// Infers the target state, ensure or clean, and dry run, from a `StateTs`. pub trait StatesTsApplyExt { type TsTarget: Debug + Send + Sync + Unpin + 'static; /// Returns the `ApplyFor` this `StatesTs` is meant for. fn apply_for() -> ApplyFor; /// Returns whether this `StatesTs` is for a dry run. fn dry_run() -> bool; } impl StatesTsApplyExt for Ensured { type TsTarget = Goal; fn apply_for() -> ApplyFor { ApplyFor::Ensure } fn dry_run() -> bool { false } } impl StatesTsApplyExt for EnsuredDry { type TsTarget = Goal; fn apply_for() -> ApplyFor { ApplyFor::Ensure } fn dry_run() -> bool { true } } impl StatesTsApplyExt for Cleaned { type TsTarget = Clean; fn apply_for() -> ApplyFor { ApplyFor::Clean } fn dry_run() -> bool { false } } impl StatesTsApplyExt for CleanedDry { type TsTarget = Clean; fn apply_for() -> ApplyFor { ApplyFor::Clean } fn dry_run() -> bool { true } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt/src/cmd_blocks/apply_state_sync_check_cmd_block.rs
crate/rt/src/cmd_blocks/apply_state_sync_check_cmd_block.rs
use std::{fmt::Debug, marker::PhantomData}; use peace_cmd_ctx::{CmdCtxSpsfFields, CmdCtxTypes}; use peace_cmd_model::CmdBlockOutcome; use peace_cmd_rt::{async_trait, CmdBlock}; use peace_resource_rt::{ resources::ts::SetUp, states::{States, StatesCurrent, StatesCurrentStored, StatesGoal, StatesGoalStored}, ResourceFetchError, Resources, }; use peace_rt_model::Error; use peace_rt_model_core::{ApplyCmdError, ItemsStateStoredStale, StateStoredAndDiscovered}; cfg_if::cfg_if! { if #[cfg(feature = "output_progress")] { use peace_progress_model::{ CmdBlockItemInteractionType, CmdProgressUpdate, ProgressComplete, ProgressDelta, ProgressMsgUpdate, ProgressUpdate, ProgressUpdateAndId, }; use tokio::sync::mpsc::Sender; } } // Whether to block an apply operation if stored states are not in sync with // discovered state. /// Neither stored current states nor stored goal state need to be in sync /// with the discovered current states and goal state. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ApplyStoreStateSyncNone; /// The stored current states must be in sync with the discovered current /// state for the apply to proceed. /// /// The stored goal state does not need to be in sync with the discovered /// goal state. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ApplyStoreStateSyncCurrent; /// The stored goal state must be in sync with the discovered goal /// state for the apply to proceed. /// /// The stored current states does not need to be in sync with the /// discovered current state. /// /// For `CleanCmd`, this variant is equivalent to `None`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ApplyStoreStateSyncGoal; /// Both stored current states and stored goal state must be in sync with /// the discovered current states and goal state for the apply to /// proceed. /// /// For `CleanCmd`, this variant is equivalent to `Current`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ApplyStoreStateSyncCurrentAndGoal; /// Stops a `CmdExecution` if stored states and discovered states are not in /// sync. pub struct ApplyStateSyncCheckCmdBlock<CmdCtxTypesT, ApplyStoreStateSync>( PhantomData<(CmdCtxTypesT, ApplyStoreStateSync)>, ); impl<CmdCtxTypesT, ApplyStoreStateSync> Debug for ApplyStateSyncCheckCmdBlock<CmdCtxTypesT, ApplyStoreStateSync> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_tuple("ApplyStateSyncCheckCmdBlock") .field(&self.0) .finish() } } impl<CmdCtxTypesT> ApplyStateSyncCheckCmdBlock<CmdCtxTypesT, ApplyStoreStateSyncNone> where CmdCtxTypesT: CmdCtxTypes, { /// Returns a block that discovers current states. pub fn none() -> Self { Self(PhantomData) } } impl<CmdCtxTypesT> ApplyStateSyncCheckCmdBlock<CmdCtxTypesT, ApplyStoreStateSyncCurrent> where CmdCtxTypesT: CmdCtxTypes, { /// Returns a block that discovers current states. pub fn current() -> Self { Self(PhantomData) } } impl<CmdCtxTypesT> ApplyStateSyncCheckCmdBlock<CmdCtxTypesT, ApplyStoreStateSyncGoal> where CmdCtxTypesT: CmdCtxTypes, { /// Returns a block that discovers goal states. pub fn goal() -> Self { Self(PhantomData) } } impl<CmdCtxTypesT> ApplyStateSyncCheckCmdBlock<CmdCtxTypesT, ApplyStoreStateSyncCurrentAndGoal> where CmdCtxTypesT: CmdCtxTypes, { /// Returns a block that discovers both current and goal states. pub fn current_and_goal() -> Self { Self(PhantomData) } } impl<CmdCtxTypesT, ApplyStoreStateSync> ApplyStateSyncCheckCmdBlock<CmdCtxTypesT, ApplyStoreStateSync> where CmdCtxTypesT: CmdCtxTypes, { fn items_state_stored_stale<StatesTsStored, StatesTs>( cmd_ctx_spsf_fields: &CmdCtxSpsfFields<'_, CmdCtxTypesT>, states_stored: &States<StatesTsStored>, states_discovered: &States<StatesTs>, #[cfg(feature = "output_progress")] progress_tx: &Sender<CmdProgressUpdate>, ) -> Result<ItemsStateStoredStale, <CmdCtxTypesT as CmdCtxTypes>::AppError> { let items_state_stored_stale = cmd_ctx_spsf_fields.flow.graph().iter_insertion().try_fold( ItemsStateStoredStale::new(), |mut items_state_stored_stale, item_rt| { let item_id = item_rt.id(); let state_stored = states_stored.get_raw(item_id); let state_discovered = states_discovered.get_raw(item_id); match (state_stored, state_discovered) { (None, None) => { // Item not discoverable, may be dependent on // predecessor } (None, Some(state_discovered)) => { let item_id = item_id.clone(); let state_discovered = state_discovered.clone(); items_state_stored_stale.insert( item_id, StateStoredAndDiscovered::OnlyDiscoveredExists { state_discovered }, ); } (Some(state_stored), None) => { let item_id = item_id.clone(); let state_stored = state_stored.clone(); items_state_stored_stale.insert( item_id, StateStoredAndDiscovered::OnlyStoredExists { state_stored }, ); } (Some(state_stored), Some(state_discovered)) => { let state_eq = item_rt.state_eq(state_stored, state_discovered); match state_eq { Ok(true) => { #[cfg(feature = "output_progress")] { let state_type = tynm::type_name::<StatesTs>(); let _progress_send_unused = progress_tx.try_send( ProgressUpdateAndId { item_id: item_id.clone(), progress_update: ProgressUpdate::Delta( ProgressDelta::Tick, ), msg_update: ProgressMsgUpdate::Set(format!( "State {state_type} in sync" )), } .into(), ); } } Ok(false) => { #[cfg(feature = "output_progress")] { let state_type = tynm::type_name::<StatesTs>(); let _progress_send_unused = progress_tx.try_send( ProgressUpdateAndId { item_id: item_id.clone(), progress_update: ProgressUpdate::Complete( ProgressComplete::Fail, ), msg_update: ProgressMsgUpdate::Set(format!( "State {state_type} out of sync" )), } .into(), ); } let item_id = item_id.clone(); let state_stored = state_stored.clone(); let state_discovered = state_discovered.clone(); items_state_stored_stale.insert( item_id, StateStoredAndDiscovered::ValuesDiffer { state_stored, state_discovered, }, ); } Err(error) => return Err(error), } } } Ok(items_state_stored_stale) }, )?; Ok(items_state_stored_stale) } } #[async_trait(?Send)] impl<CmdCtxTypesT> CmdBlock for ApplyStateSyncCheckCmdBlock<CmdCtxTypesT, ApplyStoreStateSyncNone> where CmdCtxTypesT: CmdCtxTypes, { type CmdCtxTypes = CmdCtxTypesT; type InputT = (); type Outcome = Self::InputT; #[cfg(feature = "output_progress")] fn cmd_block_item_interaction_type(&self) -> CmdBlockItemInteractionType { CmdBlockItemInteractionType::Read } fn input_fetch(&self, _resources: &mut Resources<SetUp>) -> Result<(), ResourceFetchError> { Ok(()) } fn input_type_names(&self) -> Vec<String> { vec![] } fn outcome_insert(&self, _resources: &mut Resources<SetUp>, _outcome: Self::Outcome) {} fn outcome_type_names(&self) -> Vec<String> { vec![] } async fn exec( &self, input: Self::InputT, _cmd_ctx_spsf_fields: &mut CmdCtxSpsfFields<'_, Self::CmdCtxTypes>, #[cfg(feature = "output_progress")] _progress_tx: &Sender<CmdProgressUpdate>, ) -> Result< CmdBlockOutcome<Self::Outcome, <Self::CmdCtxTypes as CmdCtxTypes>::AppError>, <Self::CmdCtxTypes as CmdCtxTypes>::AppError, > { outcome_collate(input, OutcomeResult::Ok) } } #[async_trait(?Send)] impl<CmdCtxTypesT> CmdBlock for ApplyStateSyncCheckCmdBlock<CmdCtxTypesT, ApplyStoreStateSyncCurrent> where CmdCtxTypesT: CmdCtxTypes, { type CmdCtxTypes = CmdCtxTypesT; type InputT = (StatesCurrentStored, StatesCurrent); type Outcome = Self::InputT; #[cfg(feature = "output_progress")] fn cmd_block_item_interaction_type(&self) -> CmdBlockItemInteractionType { CmdBlockItemInteractionType::Read } fn input_fetch( &self, resources: &mut Resources<SetUp>, ) -> Result<Self::InputT, ResourceFetchError> { input_fetch_current(resources) } fn input_type_names(&self) -> Vec<String> { vec![ tynm::type_name::<StatesCurrentStored>(), tynm::type_name::<StatesCurrent>(), ] } fn outcome_insert(&self, resources: &mut Resources<SetUp>, outcome: Self::Outcome) { let (states_current_stored, states_current) = outcome; resources.insert(states_current_stored); resources.insert(states_current); } fn outcome_type_names(&self) -> Vec<String> { vec![ tynm::type_name::<StatesCurrentStored>(), tynm::type_name::<StatesCurrent>(), ] } async fn exec( &self, mut input: Self::InputT, cmd_ctx_spsf_fields: &mut CmdCtxSpsfFields<'_, Self::CmdCtxTypes>, #[cfg(feature = "output_progress")] progress_tx: &Sender<CmdProgressUpdate>, ) -> Result< CmdBlockOutcome<Self::Outcome, <Self::CmdCtxTypes as CmdCtxTypes>::AppError>, <Self::CmdCtxTypes as CmdCtxTypes>::AppError, > { let (states_current_stored, states_current) = &mut input; let state_current_stale_result = Self::items_state_stored_stale( cmd_ctx_spsf_fields, states_current_stored, states_current, #[cfg(feature = "output_progress")] progress_tx, ); match state_current_stale_result { Ok(items_state_stored_stale) => { if items_state_stored_stale.stale() { return outcome_collate( input, OutcomeResult::StatesCurrentOutOfSync { items_state_stored_stale, }, ); } } Err(error) => { return outcome_collate(input, OutcomeResult::StatesDowncastError { error }); } }; outcome_collate(input, OutcomeResult::Ok) } } #[async_trait(?Send)] impl<CmdCtxTypesT> CmdBlock for ApplyStateSyncCheckCmdBlock<CmdCtxTypesT, ApplyStoreStateSyncGoal> where CmdCtxTypesT: CmdCtxTypes, { type CmdCtxTypes = CmdCtxTypesT; type InputT = (StatesGoalStored, StatesGoal); type Outcome = Self::InputT; #[cfg(feature = "output_progress")] fn cmd_block_item_interaction_type(&self) -> CmdBlockItemInteractionType { CmdBlockItemInteractionType::Read } fn input_fetch( &self, resources: &mut Resources<SetUp>, ) -> Result<Self::InputT, ResourceFetchError> { input_fetch_goal(resources) } fn input_type_names(&self) -> Vec<String> { vec![ tynm::type_name::<StatesGoalStored>(), tynm::type_name::<StatesGoal>(), ] } fn outcome_insert(&self, resources: &mut Resources<SetUp>, outcome: Self::Outcome) { let (states_goal_stored, states_goal) = outcome; resources.insert(states_goal_stored); resources.insert(states_goal); } fn outcome_type_names(&self) -> Vec<String> { vec![ tynm::type_name::<StatesGoalStored>(), tynm::type_name::<StatesGoal>(), ] } async fn exec( &self, mut input: Self::InputT, cmd_ctx_spsf_fields: &mut CmdCtxSpsfFields<'_, Self::CmdCtxTypes>, #[cfg(feature = "output_progress")] progress_tx: &Sender<CmdProgressUpdate>, ) -> Result< CmdBlockOutcome<Self::Outcome, <Self::CmdCtxTypes as CmdCtxTypes>::AppError>, <Self::CmdCtxTypes as CmdCtxTypes>::AppError, > { let (states_goal_stored, states_goal) = &mut input; let state_goal_stale_result = Self::items_state_stored_stale( cmd_ctx_spsf_fields, states_goal_stored, states_goal, #[cfg(feature = "output_progress")] progress_tx, ); match state_goal_stale_result { Ok(items_state_stored_stale) => { if items_state_stored_stale.stale() { return outcome_collate( input, OutcomeResult::StatesGoalOutOfSync { items_state_stored_stale, }, ); } } Err(error) => { return outcome_collate(input, OutcomeResult::StatesDowncastError { error }); } }; outcome_collate(input, OutcomeResult::Ok) } } #[async_trait(?Send)] impl<CmdCtxTypesT> CmdBlock for ApplyStateSyncCheckCmdBlock<CmdCtxTypesT, ApplyStoreStateSyncCurrentAndGoal> where CmdCtxTypesT: CmdCtxTypes, { type CmdCtxTypes = CmdCtxTypesT; type InputT = ( StatesCurrentStored, StatesCurrent, StatesGoalStored, StatesGoal, ); type Outcome = Self::InputT; #[cfg(feature = "output_progress")] fn cmd_block_item_interaction_type(&self) -> CmdBlockItemInteractionType { CmdBlockItemInteractionType::Read } fn input_fetch( &self, resources: &mut Resources<SetUp>, ) -> Result<Self::InputT, ResourceFetchError> { let (states_current_stored, states_current) = input_fetch_current(resources)?; let (states_goal_stored, states_goal) = input_fetch_goal(resources)?; Ok(( states_current_stored, states_current, states_goal_stored, states_goal, )) } fn input_type_names(&self) -> Vec<String> { vec![ tynm::type_name::<StatesCurrentStored>(), tynm::type_name::<StatesCurrent>(), tynm::type_name::<StatesGoalStored>(), tynm::type_name::<StatesGoal>(), ] } fn outcome_insert(&self, resources: &mut Resources<SetUp>, outcome: Self::Outcome) { let (states_current_stored, states_current, states_goal_stored, states_goal) = outcome; resources.insert(states_current_stored); resources.insert(states_current); resources.insert(states_goal_stored); resources.insert(states_goal); } fn outcome_type_names(&self) -> Vec<String> { vec![ tynm::type_name::<StatesCurrentStored>(), tynm::type_name::<StatesCurrent>(), tynm::type_name::<StatesGoalStored>(), tynm::type_name::<StatesGoal>(), ] } async fn exec( &self, mut input: Self::InputT, cmd_ctx_spsf_fields: &mut CmdCtxSpsfFields<'_, Self::CmdCtxTypes>, #[cfg(feature = "output_progress")] progress_tx: &Sender<CmdProgressUpdate>, ) -> Result< CmdBlockOutcome<Self::Outcome, <Self::CmdCtxTypes as CmdCtxTypes>::AppError>, <Self::CmdCtxTypes as CmdCtxTypes>::AppError, > { let (states_current_stored, states_current, states_goal_stored, states_goal) = &mut input; let state_current_stale_result = Self::items_state_stored_stale( cmd_ctx_spsf_fields, states_current_stored, states_current, #[cfg(feature = "output_progress")] progress_tx, ); match state_current_stale_result { Ok(items_state_stored_stale) => { if items_state_stored_stale.stale() { return outcome_collate( input, OutcomeResult::StatesCurrentOutOfSync { items_state_stored_stale, }, ); } } Err(error) => { return outcome_collate(input, OutcomeResult::StatesDowncastError { error }); } }; let state_goal_stale_result = Self::items_state_stored_stale( cmd_ctx_spsf_fields, states_goal_stored, states_goal, #[cfg(feature = "output_progress")] progress_tx, ); match state_goal_stale_result { Ok(items_state_stored_stale) => { if items_state_stored_stale.stale() { return outcome_collate( input, OutcomeResult::StatesGoalOutOfSync { items_state_stored_stale, }, ); } } Err(error) => { return outcome_collate(input, OutcomeResult::StatesDowncastError { error }); } } outcome_collate(input, OutcomeResult::Ok) } } #[derive(Debug)] enum OutcomeResult<E> { /// States that are desired to be in sync are in sync. Ok, /// Stored current states are not in sync with the actual current state. StatesCurrentOutOfSync { /// Items whose stored current state is out of sync with the discovered /// state. items_state_stored_stale: ItemsStateStoredStale, }, /// Stored goal states are not in sync with the actual goal state. StatesGoalOutOfSync { /// Items whose stored goal state is out of sync with the discovered /// state. items_state_stored_stale: ItemsStateStoredStale, }, /// Error downcasting a boxed item state to its concrete stype. StatesDowncastError { /// The error from state downcast. error: E, }, } // Use trampolining to decrease compiled code size.. fn input_fetch_current( resources: &mut Resources<SetUp>, ) -> Result<(StatesCurrentStored, StatesCurrent), ResourceFetchError> { let states_current_stored = resources.try_remove::<StatesCurrentStored>()?; let states_current = resources.try_remove::<StatesCurrent>()?; Ok((states_current_stored, states_current)) } fn input_fetch_goal( resources: &mut Resources<SetUp>, ) -> Result<(StatesGoalStored, StatesGoal), ResourceFetchError> { let states_goal_stored = resources.try_remove::<StatesGoalStored>()?; let states_goal = resources.try_remove::<StatesGoal>()?; Ok((states_goal_stored, states_goal)) } fn outcome_collate<AppErrorT, InputT>( states_stored_and_discovered: InputT, outcome_result: OutcomeResult<AppErrorT>, ) -> Result<CmdBlockOutcome<InputT, AppErrorT>, AppErrorT> where AppErrorT: peace_value_traits::AppError + From<peace_rt_model::Error>, { match outcome_result { OutcomeResult::Ok => Ok(CmdBlockOutcome::Single(states_stored_and_discovered)), OutcomeResult::StatesCurrentOutOfSync { items_state_stored_stale, } => Err(AppErrorT::from(Error::ApplyCmdError( ApplyCmdError::StatesCurrentOutOfSync { items_state_stored_stale, }, ))), OutcomeResult::StatesGoalOutOfSync { items_state_stored_stale, } => Err(AppErrorT::from(Error::ApplyCmdError( ApplyCmdError::StatesGoalOutOfSync { items_state_stored_stale, }, ))), OutcomeResult::StatesDowncastError { error } => Err(error), } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt/src/cmd_blocks/diff_cmd_block.rs
crate/rt/src/cmd_blocks/diff_cmd_block.rs
use std::{fmt::Debug, marker::PhantomData}; use fn_graph::{StreamOpts, StreamOutcome}; use futures::FutureExt; use interruptible::InterruptibilityState; use peace_cmd_ctx::{CmdCtxSpsfFields, CmdCtxTypes}; use peace_cmd_model::CmdBlockOutcome; use peace_cmd_rt::{async_trait, CmdBlock}; use peace_flow_rt::Flow; use peace_item_model::ItemId; use peace_params::{MappingFnReg, ParamsSpecs}; use peace_resource_rt::{ internal::StateDiffsMut, resources::ts::SetUp, states::{ ts::{Current, CurrentStored, Goal, GoalStored}, StateDiffs, States, }, type_reg::untagged::{BoxDtDisplay, TypeMap}, ResourceFetchError, Resources, }; use crate::cmds::DiffStateSpec; cfg_if::cfg_if! { if #[cfg(feature = "output_progress")] { use peace_progress_model::{CmdBlockItemInteractionType, CmdProgressUpdate}; use tokio::sync::mpsc::Sender; } } pub struct DiffCmdBlock<CmdCtxTypesT, StatesTs0, StatesTs1>( PhantomData<(CmdCtxTypesT, StatesTs0, StatesTs1)>, ); impl<CmdCtxTypesT, StatesTs0, StatesTs1> Debug for DiffCmdBlock<CmdCtxTypesT, StatesTs0, StatesTs1> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_tuple("DiffCmdBlock").field(&self.0).finish() } } impl<CmdCtxTypesT, StatesTs0, StatesTs1> DiffCmdBlock<CmdCtxTypesT, StatesTs0, StatesTs1> { /// Returns a new `DiffCmdBlock`. pub fn new() -> Self { Self(PhantomData) } } impl<CmdCtxTypesT, StatesTs0, StatesTs1> DiffCmdBlock<CmdCtxTypesT, StatesTs0, StatesTs1> where CmdCtxTypesT: CmdCtxTypes, { /// Returns the [`state_diff`]` for each [`Item`]. /// /// This does not take in `CmdCtx` as it may be used by both /// `CmdCtxSpsf` and `CmdCtxMpsf` /// commands. /// /// [`Item`]: peace_cfg::Item /// [`state_diff`]: peace_cfg::Item::state_diff pub async fn diff_any( interruptibility_state: InterruptibilityState<'_, '_>, flow: &Flow<<CmdCtxTypesT as CmdCtxTypes>::AppError>, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, states_a: &TypeMap<ItemId, BoxDtDisplay>, states_b: &TypeMap<ItemId, BoxDtDisplay>, ) -> Result<StreamOutcome<StateDiffs>, <CmdCtxTypesT as CmdCtxTypes>::AppError> { let stream_outcome_result = flow .graph() .try_fold_async_with( StateDiffsMut::with_capacity(states_a.len()), StreamOpts::new() .interruptibility_state(interruptibility_state) .interrupted_next_item_include(false), |mut state_diffs_mut, item| { async move { let _params_specs = &params_specs; let state_diff_opt = item .state_diff_exec( params_specs, mapping_fn_reg, resources, states_a, states_b, ) .await?; if let Some(state_diff) = state_diff_opt { state_diffs_mut.insert_raw(item.id().clone(), state_diff); } Result::<_, <CmdCtxTypesT as CmdCtxTypes>::AppError>::Ok(state_diffs_mut) } .boxed_local() }, ) .await; stream_outcome_result.map(|stream_outcome| stream_outcome.map(StateDiffs::from)) } } impl<CmdCtxTypesT, StatesTs0, StatesTs1> Default for DiffCmdBlock<CmdCtxTypesT, StatesTs0, StatesTs1> { fn default() -> Self { Self(PhantomData) } } #[async_trait(?Send)] impl<CmdCtxTypesT, StatesTs0, StatesTs1> CmdBlock for DiffCmdBlock<CmdCtxTypesT, StatesTs0, StatesTs1> where CmdCtxTypesT: CmdCtxTypes, StatesTs0: Debug + Send + Sync + 'static, StatesTs1: Debug + Send + Sync + 'static, { type CmdCtxTypes = CmdCtxTypesT; type InputT = (States<StatesTs0>, States<StatesTs1>); type Outcome = (StateDiffs, Self::InputT); #[cfg(feature = "output_progress")] fn cmd_block_item_interaction_type(&self) -> CmdBlockItemInteractionType { CmdBlockItemInteractionType::Local } fn input_fetch( &self, resources: &mut Resources<SetUp>, ) -> Result<Self::InputT, ResourceFetchError> { let states_ts0 = resources.try_remove::<States<StatesTs0>>()?; let states_ts1 = resources.try_remove::<States<StatesTs1>>()?; Ok((states_ts0, states_ts1)) } fn input_type_names(&self) -> Vec<String> { vec![ tynm::type_name::<States<StatesTs0>>(), tynm::type_name::<States<StatesTs1>>(), ] } fn outcome_insert(&self, resources: &mut Resources<SetUp>, outcome: Self::Outcome) { let (state_diffs, (states_ts0, states_ts1)) = outcome; resources.insert(state_diffs); resources.insert(states_ts0); resources.insert(states_ts1); } fn outcome_type_names(&self) -> Vec<String> { vec![ tynm::type_name::<StateDiffs>(), tynm::type_name::<States<StatesTs0>>(), tynm::type_name::<States<StatesTs1>>(), ] } async fn exec( &self, input: Self::InputT, cmd_ctx_spsf_fields: &mut CmdCtxSpsfFields<'_, Self::CmdCtxTypes>, #[cfg(feature = "output_progress")] _progress_tx: &Sender<CmdProgressUpdate>, ) -> Result< CmdBlockOutcome<Self::Outcome, <Self::CmdCtxTypes as CmdCtxTypes>::AppError>, <Self::CmdCtxTypes as CmdCtxTypes>::AppError, > { let CmdCtxSpsfFields { interruptibility_state, flow, params_specs, mapping_fn_reg, resources, .. } = cmd_ctx_spsf_fields; let (states_ts0, states_ts1) = input; let stream_outcome = Self::diff_any( interruptibility_state.reborrow(), flow, params_specs, mapping_fn_reg, resources, &states_ts0, &states_ts1, ) .await? .map(move |state_diffs| (state_diffs, (states_ts0, states_ts1))); Ok(CmdBlockOutcome::new_item_wise(stream_outcome)) } } /// Infers the states to use in diffing, from a `StateTs`. pub trait DiffCmdBlockStatesTsExt { /// Returns the `ApplyFor` this `StatesTs` is meant for. fn diff_state_spec() -> DiffStateSpec; } impl DiffCmdBlockStatesTsExt for Current { fn diff_state_spec() -> DiffStateSpec { DiffStateSpec::Current } } impl DiffCmdBlockStatesTsExt for CurrentStored { fn diff_state_spec() -> DiffStateSpec { DiffStateSpec::CurrentStored } } impl DiffCmdBlockStatesTsExt for Goal { fn diff_state_spec() -> DiffStateSpec { DiffStateSpec::Goal } } impl DiffCmdBlockStatesTsExt for GoalStored { fn diff_state_spec() -> DiffStateSpec { DiffStateSpec::GoalStored } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt/src/cmd_blocks/states_goal_read_cmd_block.rs
crate/rt/src/cmd_blocks/states_goal_read_cmd_block.rs
use std::{fmt::Debug, marker::PhantomData}; use peace_cmd_ctx::{CmdCtxSpsfFields, CmdCtxTypes}; use peace_cmd_model::CmdBlockOutcome; use peace_cmd_rt::{async_trait, CmdBlock}; use peace_flow_model::FlowId; use peace_item_model::ItemId; use peace_resource_rt::{ paths::{FlowDir, StatesGoalFile}, resources::ts::SetUp, states::StatesGoalStored, type_reg::untagged::{BoxDtDisplay, TypeReg}, ResourceFetchError, Resources, }; use peace_rt_model::Storage; use peace_state_rt::StatesSerializer; cfg_if::cfg_if! { if #[cfg(feature = "output_progress")] { use peace_progress_model::{CmdBlockItemInteractionType, CmdProgressUpdate}; use tokio::sync::mpsc::Sender; } } /// Reads [`StatesGoalStored`]s from storage. /// /// Either [`StatesDiscoverCmdBlock::goal`] or /// [`StatesDiscoverCmdBlock::current_and_goal`] must have run prior to this /// command to read the state. /// /// [`StatesDiscoverCmd`]: crate::StatesDiscoverCmd #[derive(Debug)] pub struct StatesGoalReadCmdBlock<CmdCtxTypesT>(PhantomData<CmdCtxTypesT>); impl<CmdCtxTypesT> StatesGoalReadCmdBlock<CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Returns a new `StatesGoalReadCmdBlock`. pub fn new() -> Self { Self::default() } pub(crate) async fn deserialize_internal( resources: &mut Resources<SetUp>, states_type_reg: &TypeReg<ItemId, BoxDtDisplay>, ) -> Result<StatesGoalStored, <CmdCtxTypesT as CmdCtxTypes>::AppError> { let flow_id = resources.borrow::<FlowId>(); let flow_dir = resources.borrow::<FlowDir>(); let storage = resources.borrow::<Storage>(); let states_goal_file = StatesGoalFile::from(&*flow_dir); let states_goal_stored = StatesSerializer::<<CmdCtxTypesT as CmdCtxTypes>::AppError>::deserialize_goal( &flow_id, &storage, states_type_reg, &states_goal_file, ) .await?; drop(storage); drop(flow_dir); drop(flow_id); resources.insert(states_goal_file); Ok(states_goal_stored) } } impl<CmdCtxTypesT> Default for StatesGoalReadCmdBlock<CmdCtxTypesT> { fn default() -> Self { Self(PhantomData) } } #[async_trait(?Send)] impl<CmdCtxTypesT> CmdBlock for StatesGoalReadCmdBlock<CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { type CmdCtxTypes = CmdCtxTypesT; type InputT = (); type Outcome = StatesGoalStored; #[cfg(feature = "output_progress")] fn cmd_block_item_interaction_type(&self) -> CmdBlockItemInteractionType { CmdBlockItemInteractionType::Local } fn input_fetch(&self, _resources: &mut Resources<SetUp>) -> Result<(), ResourceFetchError> { Ok(()) } fn input_type_names(&self) -> Vec<String> { vec![] } async fn exec( &self, _input: Self::InputT, cmd_ctx_spsf_fields: &mut CmdCtxSpsfFields<'_, Self::CmdCtxTypes>, #[cfg(feature = "output_progress")] _progress_tx: &Sender<CmdProgressUpdate>, ) -> Result< CmdBlockOutcome<Self::Outcome, <Self::CmdCtxTypes as CmdCtxTypes>::AppError>, <Self::CmdCtxTypes as CmdCtxTypes>::AppError, > { let CmdCtxSpsfFields { states_type_reg, resources, .. } = cmd_ctx_spsf_fields; Self::deserialize_internal(resources, states_type_reg) .await .map(CmdBlockOutcome::Single) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt/src/cmd_blocks/states_current_read_cmd_block.rs
crate/rt/src/cmd_blocks/states_current_read_cmd_block.rs
use std::{fmt::Debug, marker::PhantomData}; use peace_cmd_ctx::{CmdCtxSpsfFields, CmdCtxTypes}; use peace_cmd_model::CmdBlockOutcome; use peace_cmd_rt::{async_trait, CmdBlock}; use peace_flow_model::FlowId; use peace_item_model::ItemId; use peace_resource_rt::{ paths::{FlowDir, StatesCurrentFile}, resources::ts::SetUp, states::StatesCurrentStored, type_reg::untagged::{BoxDtDisplay, TypeReg}, ResourceFetchError, Resources, }; use peace_rt_model::Storage; use peace_state_rt::StatesSerializer; cfg_if::cfg_if! { if #[cfg(feature = "output_progress")] { use peace_progress_model::{CmdBlockItemInteractionType, CmdProgressUpdate}; use tokio::sync::mpsc::Sender; } } /// Reads [`StatesCurrentStored`]s from storage. /// /// Either [`StatesDiscoverCmdBlock::current`] or /// [`StatesDiscoverCmdBlock::current_and_goal`] must have run prior to this /// command to read the state. /// /// [`StatesDiscoverCmd`]: crate::StatesDiscoverCmd #[derive(Debug)] pub struct StatesCurrentReadCmdBlock<CmdCtxTypesT>(PhantomData<CmdCtxTypesT>); impl<CmdCtxTypesT> StatesCurrentReadCmdBlock<CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Returns a new `StatesCurrentReadCmdBlock`. pub fn new() -> Self { Self::default() } pub(crate) async fn deserialize_internal( resources: &mut Resources<SetUp>, states_type_reg: &TypeReg<ItemId, BoxDtDisplay>, ) -> Result<StatesCurrentStored, <CmdCtxTypesT as CmdCtxTypes>::AppError> { let flow_id = resources.borrow::<FlowId>(); let flow_dir = resources.borrow::<FlowDir>(); let storage = resources.borrow::<Storage>(); let states_current_file = StatesCurrentFile::from(&*flow_dir); let states_current_stored = StatesSerializer::<<CmdCtxTypesT as CmdCtxTypes>::AppError>::deserialize_stored( &flow_id, &storage, states_type_reg, &states_current_file, ) .await?; drop(storage); drop(flow_dir); drop(flow_id); resources.insert(states_current_file); Ok(states_current_stored) } } impl<CmdCtxTypesT> Default for StatesCurrentReadCmdBlock<CmdCtxTypesT> { fn default() -> Self { Self(PhantomData) } } #[async_trait(?Send)] impl<CmdCtxTypesT> CmdBlock for StatesCurrentReadCmdBlock<CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { type CmdCtxTypes = CmdCtxTypesT; type InputT = (); type Outcome = StatesCurrentStored; #[cfg(feature = "output_progress")] fn cmd_block_item_interaction_type(&self) -> CmdBlockItemInteractionType { CmdBlockItemInteractionType::Local } fn input_fetch(&self, _resources: &mut Resources<SetUp>) -> Result<(), ResourceFetchError> { Ok(()) } fn input_type_names(&self) -> Vec<String> { vec![] } async fn exec( &self, _input: Self::InputT, cmd_ctx_spsf_fields: &mut CmdCtxSpsfFields<'_, Self::CmdCtxTypes>, #[cfg(feature = "output_progress")] _progress_tx: &Sender<CmdProgressUpdate>, ) -> Result< CmdBlockOutcome<Self::Outcome, <Self::CmdCtxTypes as CmdCtxTypes>::AppError>, <Self::CmdCtxTypes as CmdCtxTypes>::AppError, > { let CmdCtxSpsfFields { states_type_reg, resources, .. } = cmd_ctx_spsf_fields; Self::deserialize_internal(resources, states_type_reg) .await .map(CmdBlockOutcome::Single) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt/src/cmd_blocks/states_clean_insertion_cmd_block.rs
crate/rt/src/cmd_blocks/states_clean_insertion_cmd_block.rs
use std::{fmt::Debug, marker::PhantomData}; use futures::FutureExt; use peace_cmd_ctx::{CmdCtxSpsfFields, CmdCtxTypes}; use peace_cmd_model::CmdBlockOutcome; use peace_cmd_rt::{async_trait, CmdBlock}; use peace_resource_rt::{ internal::StatesMut, resources::ts::SetUp, states::{ts::Clean, StatesClean}, ResourceFetchError, Resources, }; use peace_rt_model::fn_graph::StreamOpts; use peace_rt_model_core::IndexMap; cfg_if::cfg_if! { if #[cfg(feature = "output_progress")] { use peace_progress_model::{CmdBlockItemInteractionType, CmdProgressUpdate}; use tokio::sync::mpsc::Sender; } } /// Inserts [`StatesClean`]s for each item. /// /// This calls [`Item::state_clean`] for each item, and groups them together /// into `StatesClean`. #[derive(Debug)] pub struct StatesCleanInsertionCmdBlock<CmdCtxTypesT>(PhantomData<CmdCtxTypesT>); impl<CmdCtxTypesT> StatesCleanInsertionCmdBlock<CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Returns a new `StatesCleanInsertionCmdBlock`. pub fn new() -> Self { Self::default() } } impl<CmdCtxTypesT> Default for StatesCleanInsertionCmdBlock<CmdCtxTypesT> { fn default() -> Self { Self(PhantomData) } } #[async_trait(?Send)] impl<CmdCtxTypesT> CmdBlock for StatesCleanInsertionCmdBlock<CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { type CmdCtxTypes = CmdCtxTypesT; type InputT = (); type Outcome = StatesClean; #[cfg(feature = "output_progress")] fn cmd_block_item_interaction_type(&self) -> CmdBlockItemInteractionType { CmdBlockItemInteractionType::Local } fn input_fetch(&self, _resources: &mut Resources<SetUp>) -> Result<(), ResourceFetchError> { Ok(()) } fn input_type_names(&self) -> Vec<String> { vec![] } async fn exec( &self, _input: Self::InputT, cmd_ctx_spsf_fields: &mut CmdCtxSpsfFields<'_, Self::CmdCtxTypes>, #[cfg(feature = "output_progress")] _progress_tx: &Sender<CmdProgressUpdate>, ) -> Result< CmdBlockOutcome<Self::Outcome, <Self::CmdCtxTypes as CmdCtxTypes>::AppError>, <Self::CmdCtxTypes as CmdCtxTypes>::AppError, > { let CmdCtxSpsfFields { interruptibility_state, flow, params_specs, mapping_fn_reg, resources, .. } = cmd_ctx_spsf_fields; let params_specs = &*params_specs; let mapping_fn_reg = &*mapping_fn_reg; let resources = &*resources; let (stream_outcome, errors) = flow .graph() .fold_async_with( (StatesMut::<Clean>::new(), IndexMap::new()), StreamOpts::new() .interruptibility_state(interruptibility_state.reborrow()) .interrupted_next_item_include(false), |(mut states_clean_mut, mut errors), item_rt| { async move { let item_id = item_rt.id().clone(); let state_clean_boxed_result = item_rt .state_clean(params_specs, mapping_fn_reg, resources) .await; match state_clean_boxed_result { Ok(state_clean_boxed) => { states_clean_mut.insert_raw(item_id, state_clean_boxed); } Err(error) => { errors.insert(item_id, error); } } (states_clean_mut, errors) } .boxed_local() }, ) .await .replace_with(std::convert::identity); let stream_outcome = stream_outcome.map(StatesClean::from); Ok(CmdBlockOutcome::ItemWise { stream_outcome, errors, }) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model/src/outcomes.rs
crate/rt_model/src/outcomes.rs
//! Type that represent outcomes of execution. //! //! Types in this module must all be serializable, as this allows execution //! outcomes to be redisplayed without re-executing commands. pub use self::{ item_apply::ItemApply, item_apply_boxed::ItemApplyBoxed, item_apply_partial::ItemApplyPartial, item_apply_partial_boxed::ItemApplyPartialBoxed, item_apply_partial_rt::ItemApplyPartialRt, item_apply_rt::ItemApplyRt, }; mod item_apply; mod item_apply_boxed; mod item_apply_partial; mod item_apply_partial_boxed; mod item_apply_partial_rt; mod item_apply_rt; macro_rules! box_data_type_newtype { ($ty_name:ident, $trait_path:path) => { impl std::fmt::Debug for $ty_name { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.debug_tuple(stringify!($ty_name)).field(&self.0).finish() } } impl $ty_name { /// Returns the inner boxed trait. pub fn into_inner(self) -> Box<dyn $trait_path> { self.0 } } impl std::ops::Deref for $ty_name { type Target = dyn $trait_path; fn deref(&self) -> &Self::Target { &self.0 } } impl std::ops::DerefMut for $ty_name { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<T> peace_resource_rt::type_reg::untagged::BoxDataTypeDowncast<T> for $ty_name where T: $trait_path, { fn downcast_ref(&self) -> Option<&T> { self.0.as_data_type().downcast_ref::<T>() } fn downcast_mut(&mut self) -> Option<&mut T> { self.0.as_data_type_mut().downcast_mut::<T>() } } impl peace_resource_rt::type_reg::untagged::DataTypeWrapper for $ty_name { fn type_name(&self) -> peace_resource_rt::type_reg::TypeNameLit { peace_resource_rt::type_reg::untagged::DataType::type_name(&*self.0) } fn clone(&self) -> Self { Self(self.0.clone()) } fn debug(&self) -> &dyn std::fmt::Debug { &self.0 } fn inner(&self) -> &dyn peace_resource_rt::type_reg::untagged::DataType { &self.0 } } }; } pub(crate) use box_data_type_newtype;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model/src/in_memory_text_output.rs
crate/rt_model/src/in_memory_text_output.rs
use peace_fmt::Presentable; use peace_rt_model_core::{async_trait, output::OutputWrite}; use crate::Error; cfg_if::cfg_if! { if #[cfg(feature = "output_progress")] { use peace_item_interaction_model::ItemLocationState; use peace_item_model::ItemId; use peace_progress_model::{ CmdBlockItemInteractionType, ProgressTracker, ProgressUpdateAndId, }; use crate::CmdProgressTracker; } } /// An `OutputWrite` implementation that writes to the command line. /// /// Currently this only outputs return values or errors, not progress. #[derive(Debug, Default)] pub struct InMemoryTextOutput { /// Buffer to write to. buffer: String, /// The `miette::ReportHandler` to format errors nicely. #[cfg(feature = "error_reporting")] pub(crate) report_handler: miette::GraphicalReportHandler, } impl InMemoryTextOutput { /// Returns a new `InMemoryTextOutput`. pub fn new() -> Self { Self::default() } /// Returns the inner buffer. pub fn into_inner(self) -> String { self.buffer } } /// Simple serialization implementations for now. /// /// See <https://github.com/azriel91/peace/issues/28> for further improvements. #[async_trait(?Send)] impl OutputWrite for InMemoryTextOutput { type Error = Error; #[cfg(feature = "output_progress")] async fn progress_begin(&mut self, _cmd_progress_tracker: &CmdProgressTracker) {} #[cfg(feature = "output_progress")] async fn progress_update( &mut self, _progress_tracker: &ProgressTracker, _progress_update_and_id: &ProgressUpdateAndId, ) { } #[cfg(feature = "output_progress")] async fn cmd_block_start( &mut self, _cmd_block_item_interaction_type: CmdBlockItemInteractionType, ) { } #[cfg(feature = "output_progress")] async fn item_location_state( &mut self, _item_id: ItemId, _item_location_state: ItemLocationState, ) { } #[cfg(feature = "output_progress")] async fn progress_end(&mut self, _cmd_progress_tracker: &CmdProgressTracker) {} async fn present<P>(&mut self, presentable: P) -> Result<(), Error> where P: Presentable, { self.buffer .push_str(&serde_yaml::to_string(&presentable).map_err(Error::StatesSerialize)?); Ok(()) } #[cfg(not(feature = "error_reporting"))] async fn write_err<E>(&mut self, error: &E) -> Result<(), Error> where E: std::error::Error, { self.buffer = format!("{error}\n"); Ok(()) } #[cfg(feature = "error_reporting")] async fn write_err<E>(&mut self, error: &E) -> Result<(), Error> where E: miette::Diagnostic, { use miette::Diagnostic; let mut err_buffer = String::new(); let mut diagnostic_opt: Option<&dyn Diagnostic> = Some(error); while let Some(diagnostic) = diagnostic_opt { if diagnostic.help().is_some() || diagnostic.labels().is_some() || diagnostic.diagnostic_source().is_none() { // Ignore failures when writing errors let (Ok(()) | Err(_)) = self .report_handler .render_report(&mut err_buffer, diagnostic); err_buffer.push('\n'); let err_buffer = err_buffer.lines().fold( String::with_capacity(err_buffer.len()), |mut buffer, line| { if line.trim().is_empty() { buffer.push('\n'); } else { buffer.push_str(line); buffer.push('\n'); } buffer }, ); self.buffer.push_str(&err_buffer); } diagnostic_opt = diagnostic.diagnostic_source(); err_buffer.clear(); } Ok(()) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model/src/lib.rs
crate/rt_model/src/lib.rs
#![cfg_attr(coverage_nightly, feature(coverage_attribute))] //! Runtime data types for the peace automation framework. //! //! This crate re-exports types from `peace_rt_model_native` or //! `peace_rt_model_web` depending on the compilation target architecture. // Re-exports pub use peace_data::fn_graph::{self, FnRef}; pub use peace_rt_model_core::*; #[cfg(not(target_arch = "wasm32"))] pub use peace_rt_model_native::*; #[cfg(target_arch = "wasm32")] pub use peace_rt_model_web::*; pub use crate::{ in_memory_text_output::InMemoryTextOutput, item_boxed::ItemBoxed, item_rt::ItemRt, item_wrapper::ItemWrapper, params_specs_serializer::ParamsSpecsSerializer, params_specs_type_reg::ParamsSpecsTypeReg, states_type_reg::StatesTypeReg, }; pub mod outcomes; mod in_memory_text_output; mod item_boxed; mod item_rt; mod item_wrapper; mod params_specs_serializer; mod params_specs_type_reg; mod states_type_reg;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model/src/item_rt.rs
crate/rt_model/src/item_rt.rs
use std::{any::Any, fmt::Debug}; use dyn_clone::DynClone; use peace_cfg::{async_trait, FnCtx}; use peace_data::fn_graph::{DataAccess, DataAccessDyn}; use peace_item_model::ItemId; use peace_params::{MappingFnReg, ParamsSpecs}; use peace_resource_rt::{ resources::ts::{Empty, SetUp}, states::StatesCurrent, type_reg::untagged::{BoxDtDisplay, TypeMap}, Resources, }; use crate::{ outcomes::{ItemApplyBoxed, ItemApplyPartialBoxed}, ParamsSpecsTypeReg, StatesTypeReg, }; /// Internal trait that erases the types from [`Item`] /// /// This exists so that different implementations of [`Item`] can be held /// under the same boxed trait. /// /// [`Item`]: peace_cfg::Item #[async_trait(?Send)] pub trait ItemRt<E>: Any + Debug + DataAccess + DataAccessDyn + DynClone + Send + Sync + 'static { /// Returns the ID of this item. /// /// See [`Item::id`]; /// /// [`Item::id`]: peace_cfg::Item::id fn id(&self) -> &ItemId; /// Returns whether this item is equal to the other. fn eq(&self, other: &dyn ItemRt<E>) -> bool; /// Returns `&self` as `&dyn Any`. /// /// This is needed to upcast to `&dyn Any` and satisfy the upcast lifetime /// requirement. fn as_any(&self) -> &dyn Any; /// Initializes data for the item's functions. async fn setup(&self, resources: &mut Resources<Empty>) -> Result<(), E> where E: Debug + std::error::Error; /// Registers params and state types with the type registries for /// deserializing from disk. /// /// This is necessary to deserialize `ItemParamsFile`, /// `ParamsSpecsFile`, `StatesCurrentFile`, and `StatesGoalFile`. fn params_and_state_register( &self, params_specs_type_reg: &mut ParamsSpecsTypeReg, states_type_reg: &mut StatesTypeReg, ); /// Returns if the given two states equal. /// /// This returns an error if the boxed states could not be downcasted to /// this item's state, which indicates one of the following: /// /// * Peace contains a bug, and passed an incorrect box to this item. /// * Item IDs were swapped, such that `ItemA`'s state is passed to `ItemB`. /// /// This needs some rework on how item IDs are implemented -- as in, /// whether we should use a string newtype for `ItemId`s, or redesign /// how `Item`s or related types are keyed. /// /// Note: it is impossible to call this method if an `Item`'s state type has /// changed -- it would have failed on deserialization. fn state_eq(&self, state_a: &BoxDtDisplay, state_b: &BoxDtDisplay) -> Result<bool, E> where E: Debug + std::error::Error; /// Returns an example fully deployed state of the managed item. /// /// # Design /// /// This is *expected* to always return a value, as it is used to: /// /// * Display a diagram that shows the user what the item looks like when it /// is fully deployed, without actually interacting with any external /// state. /// /// As much as possible, use the values in the provided params and data. /// /// This function should **NOT** interact with any external services, or /// read from files that are part of the automation process, e.g. /// querying data from a web endpoint, or reading files that may be /// downloaded by a predecessor. /// /// ## Fallibility /// /// [`Item::state_example`] is deliberately infallible to signal to /// implementors that calling an external service / read from a file is /// incorrect implementation for this method -- values in params / data /// may be example values from other items that may not resolve. /// /// [`ItemRt::state_example`] *is* fallible as value resolution for /// parameters may fail, e.g. if there is a bug in Peace, or an item's /// parameters requests a type that doesn't exist in [`Resources`]. /// /// ## Non-async /// /// This signals to implementors that this function should be a cheap /// example state computation that is relatively realistic rather than /// determining an accurate value. /// /// [`Item::state_example`]: peace_cfg::Item::Item::state_example #[cfg(feature = "item_state_example")] fn state_example( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, ) -> Result<BoxDtDisplay, E> where E: Debug + std::error::Error; /// Runs [`Item::state_clean`]. /// /// [`Item::state_clean`]: peace_cfg::Item::state_clean async fn state_clean( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, ) -> Result<BoxDtDisplay, E> where E: Debug + std::error::Error; /// Runs [`Item::state_current`]`::`[`try_exec`]. /// /// [`Item::state_current`]: peace_cfg::Item::state_current /// [`try_exec`]: peace_cfg::TryFnSpec::try_exec async fn state_current_try_exec( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, fn_ctx: FnCtx<'_>, ) -> Result<Option<BoxDtDisplay>, E> where E: Debug + std::error::Error; /// Runs [`Item::state_current`]`::`[`exec`]. /// /// [`Item::state_current`]: peace_cfg::Item::state_current /// [`exec`]: peace_cfg::TryFnSpec::exec async fn state_current_exec( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, fn_ctx: FnCtx<'_>, ) -> Result<BoxDtDisplay, E> where E: Debug + std::error::Error; /// Runs [`Item::state_goal`]`::`[`try_exec`]. /// /// [`Item::state_goal`]: peace_cfg::Item::state_goal /// [`try_exec`]: peace_cfg::TryFnSpec::try_exec async fn state_goal_try_exec( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, fn_ctx: FnCtx<'_>, ) -> Result<Option<BoxDtDisplay>, E> where E: Debug + std::error::Error; /// Runs [`Item::state_goal`]`::`[`exec`]. /// /// [`Item::state_goal`]: peace_cfg::Item::state_goal /// [`exec`]: peace_cfg::TryFnSpec::exec async fn state_goal_exec( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, fn_ctx: FnCtx<'_>, ) -> Result<BoxDtDisplay, E> where E: Debug + std::error::Error; /// Returns the diff between the given [`State`]s. /// /// Given `states_a` and `states_b` represent current states and goal /// states, then this method returns `None` in the following cases: /// /// * The current state cannot be retrieved, due to a predecessor's state /// not existing. /// * The goal state cannot be retrieved, due to a predecessor's state not /// existing. /// * A bug exists, e.g. the state is stored against the wrong type /// parameter. /// /// [`State`]: peace_cfg::State async fn state_diff_exec( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, states_a: &TypeMap<ItemId, BoxDtDisplay>, states_b: &TypeMap<ItemId, BoxDtDisplay>, ) -> Result<Option<BoxDtDisplay>, E> where E: Debug + std::error::Error; /// Discovers the information needed for an ensure execution. /// /// This runs the following functions in order: /// /// * [`Item::state_current`] /// * [`Item::state_goal`] /// * [`Item::state_diff`] /// * [`ApplyFns::check`] /// /// [`Item::state_current`]: peace_cfg::Item::state_current /// [`Item::state_goal`]: peace_cfg::Item::state_goal /// [`Item::state_diff`]: peace_cfg::Item::state_diff /// [`ApplyFns::check`]: peace_cfg::Item::ApplyFns async fn ensure_prepare( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, fn_ctx: FnCtx<'_>, ) -> Result<ItemApplyBoxed, (E, ItemApplyPartialBoxed)> where E: Debug + std::error::Error; /// Discovers the information needed for a clean execution. /// /// This runs the following functions in order: /// /// * [`Item::state_current`] /// * [`Item::state_clean`] /// * [`Item::state_diff`] /// * [`ApplyFns::check`] /// /// [`Item::state_current`]: peace_cfg::Item::state_current /// [`Item::state_clean`]: peace_cfg::Item::state_clean /// [`Item::state_diff`]: peace_cfg::Item::state_diff /// [`ApplyFns::check`]: peace_cfg::Item::ApplyFns async fn clean_prepare( &self, states_current: &StatesCurrent, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, ) -> Result<ItemApplyBoxed, (E, ItemApplyPartialBoxed)> where E: Debug + std::error::Error; /// Dry applies the item from its current state to its goal state. /// /// This runs the following function in order, passing in the information /// collected from [`ensure_prepare`] or [`clean_prepare`]: /// /// * [`ApplyFns::exec_dry`] /// /// # Parameters /// /// * `resources`: The resources in the current execution. /// * `item_apply`: The information collected in `self.ensure_prepare`. /// /// [`ApplyFns::exec_dry`]: peace_cfg::Item::ApplyFns async fn apply_exec_dry( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, fn_ctx: FnCtx<'_>, item_apply: &mut ItemApplyBoxed, ) -> Result<(), E> where E: Debug + std::error::Error; /// Applies the item from its current state to its goal state. /// /// This runs the following function in order, passing in the information /// collected from [`ensure_prepare`] or [`clean_prepare`]: /// /// * [`ApplyFns::exec`] /// /// # Parameters /// /// * `resources`: The resources in the current execution. /// * `item_apply`: The information collected in `self.ensure_prepare`. /// /// [`ApplyFns::exec`]: peace_cfg::Item::ApplyFns async fn apply_exec( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, fn_ctx: FnCtx<'_>, item_apply: &mut ItemApplyBoxed, ) -> Result<(), E> where E: Debug + std::error::Error; /// Returns the physical resources that this item interacts with, purely /// using example state. /// /// # Design /// /// This method returns interactions from [`Item::interactions`], passing in /// parameters computed from example state. /// /// ## Fallibility /// /// [`Item::interactions`] is infallible as computing `ItemInteractions` /// should purely be instantiating objects. /// /// [`ItemRt::interactions_example`] *is* fallible as value resolution for /// parameters may fail, e.g. if there is a bug in Peace, or an item's /// parameters requests a type that doesn't exist in [`Resources`]. #[cfg(all(feature = "item_interactions", feature = "item_state_example"))] fn interactions_example( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, ) -> Result<peace_item_interaction_model::ItemInteractionsExample, E>; /// Returns the physical resources that this item interacts with, merging /// any available current state over example state. /// /// # Design /// /// This method returns interactions from [`Item::interactions`], passing in /// parameters computed from current state, or if not available, example /// state. /// /// For tracking which item interactions are known, for the purpose of /// styling unknown state differently, we could return the /// `ItemInteractions` alongside with how they were constructed: /// /// 1. One for `ItemInteraction`s where params are fully computed using /// fully known state. /// 2. One for `ItemInteraction`s where params are computed using some or /// all example state. /// /// ## Fallibility /// /// [`Item::interactions`] is infallible as computing `ItemInteractions` /// should purely be instantiating objects. /// /// [`ItemRt::interactions_current`] *is* fallible as value resolution /// for parameters may fail, e.g. if there is a bug in Peace, or an /// item's parameters requests a type that doesn't exist in /// [`Resources`]. #[cfg(all(feature = "item_interactions", feature = "item_state_example"))] fn interactions_try_current( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, ) -> Result<peace_item_interaction_model::ItemInteractionsCurrentOrExample, E>; /// Returns a human readable tag name that represents this item. /// /// For example, a `FileDownloadItem<WebApp>` should return a string similar /// to: `"Web App: File Download"`. This allows tags to be grouped by the /// concept / information they are associated with, rather than grouping /// tags by the type of operation. #[cfg(all(feature = "item_interactions", feature = "item_state_example"))] fn interactions_tag_name(&self) -> String; }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model/src/params_specs_serializer.rs
crate/rt_model/src/params_specs_serializer.rs
use std::marker::PhantomData; use peace_flow_model::FlowId; use peace_params::ParamsSpecs; use peace_profile_model::Profile; use peace_resource_rt::{paths::ParamsSpecsFile, type_reg::untagged::TypeMapOpt}; use peace_rt_model_core::ParamsSpecsDeserializeError; use crate::{Error, ParamsSpecsTypeReg, Storage}; /// Reads and writes [`ParamsSpecs`] to and from storage. pub struct ParamsSpecsSerializer<E>(PhantomData<E>); impl<E> ParamsSpecsSerializer<E> where E: std::error::Error + From<Error> + Send, { /// Serializes the [`ParamsSpecs`] of all [`Item`]s to disk. /// /// # Parameters: /// /// * `storage`: `Storage` to write to. /// * `params_specs`: `ParamsSpecs` to serialize. /// * `params_specs_file`: Path to save the serialized params_specs to. /// /// [`Item`]: peace_cfg::Item pub async fn serialize( storage: &Storage, params_specs: &ParamsSpecs, params_specs_file: &ParamsSpecsFile, ) -> Result<(), E> { storage .serialized_write( #[cfg(not(target_arch = "wasm32"))] "ParamsSpecsSerializer::serialize".to_string(), params_specs_file, params_specs, Error::ParamsSpecsSerialize, ) .await?; Ok(()) } /// Returns the [`ParamsSpecs`] of all [`Item`]s if it exists on disk. /// /// # Parameters: /// /// * `storage`: `Storage` to read from. /// * `params_specs_type_reg`: Type registry with functions to deserialize /// each params spec. /// * `params_specs_file`: `ParamsSpecsFile` to deserialize. /// /// [`Item`]: peace_cfg::Item pub async fn deserialize_opt( profile: &Profile, flow_id: &FlowId, storage: &Storage, params_specs_type_reg: &ParamsSpecsTypeReg, params_specs_file: &ParamsSpecsFile, ) -> Result<Option<ParamsSpecs>, E> { Self::deserialize_internal( #[cfg(not(target_arch = "wasm32"))] "ParamsSpecsSerializer::deserialize_opt".to_string(), profile, flow_id, storage, params_specs_type_reg, params_specs_file, ) .await } /// Returns the [`ParamsSpecs`] of all [`Item`]s if it exists on disk. /// /// # Parameters: /// /// * `storage`: `Storage` to read from. /// * `params_specs_type_reg`: Type registry with functions to deserialize /// each params spec. /// * `params_specs_file`: `ParamsSpecsFile` to deserialize. /// /// [`Item`]: peace_cfg::Item #[cfg(not(target_arch = "wasm32"))] async fn deserialize_internal( thread_name: String, profile: &Profile, flow_id: &FlowId, storage: &Storage, params_specs_type_reg: &ParamsSpecsTypeReg, params_specs_file: &ParamsSpecsFile, ) -> Result<Option<ParamsSpecs>, E> { let params_specs_opt = storage .serialized_typemap_read_opt( thread_name, params_specs_type_reg, params_specs_file, #[cfg_attr(coverage_nightly, coverage(off))] |error| { #[cfg(not(feature = "error_reporting"))] { Error::ParamsSpecsDeserialize(Box::new(ParamsSpecsDeserializeError { profile: profile.clone(), flow_id: flow_id.clone(), error, })) } #[cfg(feature = "error_reporting")] { use miette::NamedSource; use yaml_error_context_hack::ErrorAndContext; let file_contents = std::fs::read_to_string(params_specs_file).unwrap(); let ErrorAndContext { error_span, error_message, context_span, } = ErrorAndContext::new(&file_contents, &error); let params_specs_file_source = NamedSource::new(params_specs_file.to_string_lossy(), file_contents); Error::ParamsSpecsDeserialize(Box::new(ParamsSpecsDeserializeError { profile: profile.clone(), flow_id: flow_id.clone(), params_specs_file_source, error_span, error_message, context_span, error, })) } }, ) .await .map(|type_map_opt| { type_map_opt .map(TypeMapOpt::into_type_map) .map(ParamsSpecs::from) })?; Ok(params_specs_opt) } /// Returns the [`ParamsSpecs`] of all [`Item`]s if it exists on disk. /// /// # Parameters: /// /// * `storage`: `Storage` to read from. /// * `params_specs_type_reg`: Type registry with functions to deserialize /// each params spec. /// * `params_specs_file`: `ParamsSpecsFile` to deserialize. /// /// [`Item`]: peace_cfg::Item #[cfg(target_arch = "wasm32")] async fn deserialize_internal( profile: &Profile, flow_id: &FlowId, storage: &Storage, params_specs_type_reg: &ParamsSpecsTypeReg, params_specs_file: &ParamsSpecsFile, ) -> Result<Option<ParamsSpecs>, E> { let params_specs_opt = storage .serialized_typemap_read_opt(params_specs_type_reg, params_specs_file, |error| { #[cfg(not(feature = "error_reporting"))] { Error::ParamsSpecsDeserialize(Box::new(ParamsSpecsDeserializeError { profile: profile.clone(), flow_id: flow_id.clone(), error, })) } #[cfg(feature = "error_reporting")] { use miette::NamedSource; use yaml_error_context_hack::ErrorAndContext; let file_contents = std::fs::read_to_string(params_specs_file).unwrap(); let ErrorAndContext { error_span, error_message, context_span, } = ErrorAndContext::new(&file_contents, &error); let params_specs_file_source = NamedSource::new(params_specs_file.to_string_lossy(), file_contents); Error::ParamsSpecsDeserialize(Box::new(ParamsSpecsDeserializeError { profile: profile.clone(), flow_id: flow_id.clone(), params_specs_file_source, error_span, error_message, context_span, error, })) } }) .await .map(|type_map_opt| { type_map_opt .map(TypeMapOpt::into_type_map) .map(ParamsSpecs::from) })?; Ok(params_specs_opt) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model/src/item_boxed.rs
crate/rt_model/src/item_boxed.rs
//! Contains type-erased `Item` types and traits. //! //! Types and traits in this module don't reference any associated types from //! the `Item`, allowing them to be passed around as common types at compile //! time. //! //! For the logic that is aware of the type parameters, see the //! [`item_wrapper`] module and [`ItemWrapper`] type. //! //! [`item_wrapper`]: crate::item_wrapper //! [`ItemWrapper`]: crate::ItemWrapper use std::{ fmt::Debug, ops::{Deref, DerefMut}, }; use peace_cfg::Item; use peace_data::fn_graph::{DataAccessDyn, TypeIds}; use peace_params::{Params, ParamsMergeExt}; use crate::{ItemRt, ItemWrapper}; /// Holds a type-erased `ItemWrapper` in a `Box`. /// /// # Type Parameters /// /// * `E`: Application specific error type. /// /// Notably, `E` here should be the application's error type, which is not /// necessarily the item's error type (unless you have only one item /// spec in the application). #[derive(Debug)] pub struct ItemBoxed<E>(Box<dyn ItemRt<E>>); impl<E> Clone for ItemBoxed<E> { fn clone(&self) -> Self { Self(dyn_clone::clone_box(self.0.as_ref())) } } impl<E> Deref for ItemBoxed<E> { type Target = dyn ItemRt<E>; fn deref(&self) -> &Self::Target { &*self.0 } } impl<E> DerefMut for ItemBoxed<E> { fn deref_mut(&mut self) -> &mut Self::Target { &mut *self.0 } } impl<E> PartialEq for ItemBoxed<E> where E: 'static, { fn eq(&self, other: &Self) -> bool { self.0.eq(&*other.0) } } impl<E> Eq for ItemBoxed<E> where E: 'static {} impl<I, E> From<I> for ItemBoxed<E> where I: Clone + Debug + Item + Send + Sync + 'static, <I as Item>::Error: Send + Sync, E: Debug + Send + Sync + std::error::Error + From<<I as Item>::Error> + From<crate::Error> + 'static, for<'params> <I as Item>::Params<'params>: ParamsMergeExt + TryFrom<<<I as Item>::Params<'params> as Params>::Partial>, for<'params> <<I as Item>::Params<'params> as Params>::Partial: From< <<I as Item>::Params<'params> as TryFrom< <<I as Item>::Params<'params> as Params>::Partial, >>::Error, >, for<'params> <I::Params<'params> as Params>::Partial: From<I::Params<'params>>, { fn from(item: I) -> Self { Self(Box::new(ItemWrapper::from(item))) } } impl<E> DataAccessDyn for ItemBoxed<E> { fn borrows(&self) -> TypeIds { DataAccessDyn::borrows(self.0.as_ref()) } fn borrow_muts(&self) -> TypeIds { DataAccessDyn::borrow_muts(self.0.as_ref()) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model/src/states_type_reg.rs
crate/rt_model/src/states_type_reg.rs
use std::ops::{Deref, DerefMut}; use peace_item_model::ItemId; use peace_resource_rt::type_reg::untagged::{BoxDtDisplay, TypeReg}; /// Type registry for each item's `State`. /// /// This is used to deserialize [`StatesCurrentFile`] and [`StatesGoalFile`]. /// /// Note: [`ItemParamsTypeReg`] uses [`BoxDt`], whereas this uses /// [`BoxDtDisplay`]. /// /// [`BoxDt`]: peace_resource_rt::type_reg::untagged::BoxDt /// [`BoxDtDisplay`]: peace_resource_rt::type_reg::untagged::BoxDtDisplay /// [`ItemParamsTypeReg`]: crate::ItemParamsTypeReg /// [`Params`]: peace_cfg::Item::Params /// [`StatesGoalFile`]: peace_resource_rt::paths::StatesGoalFile /// [`StatesCurrentFile`]: peace_resource_rt::paths::StatesCurrentFile #[derive(Debug, Default)] pub struct StatesTypeReg(TypeReg<ItemId, BoxDtDisplay>); impl StatesTypeReg { /// Returns new `StatesTypeReg`. pub fn new() -> Self { Self::default() } } impl Deref for StatesTypeReg { type Target = TypeReg<ItemId, BoxDtDisplay>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for StatesTypeReg { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model/src/item_wrapper.rs
crate/rt_model/src/item_wrapper.rs
use std::{ any::Any, fmt::{self, Debug}, marker::PhantomData, ops::{Deref, DerefMut}, }; use peace_cfg::{async_trait, ApplyCheck, FnCtx, Item}; use peace_data::{ fn_graph::{DataAccess, DataAccessDyn, TypeIds}, marker::{ApplyDry, Clean, Current, Goal}, Data, }; use peace_item_model::ItemId; use peace_params::{ MappingFnReg, Params, ParamsMergeExt, ParamsSpec, ParamsSpecs, ValueResolutionCtx, ValueResolutionMode, }; use peace_resource_rt::{ resources::ts::{Empty, SetUp}, states::StatesCurrent, type_reg::untagged::{BoxDtDisplay, TypeMap}, Resources, }; use type_reg::untagged::BoxDataTypeDowncast; use crate::{ outcomes::{ItemApply, ItemApplyBoxed, ItemApplyPartial, ItemApplyPartialBoxed}, ItemRt, ParamsSpecsTypeReg, StateDowncastError, StatesTypeReg, }; #[cfg(feature = "output_progress")] use peace_cfg::RefInto; #[cfg(feature = "item_state_example")] use peace_data::marker::Example; #[cfg(feature = "output_progress")] use peace_item_interaction_model::ItemLocationState; /// Wraps a type implementing [`Item`]. /// /// # Type Parameters /// /// * `I`: Item type to wrap. /// * `E`: Application specific error type. /// /// Notably, `E` here should be the application's error type, which is not /// necessarily the item's error type (unless you have only one item /// spec in the application). #[allow(clippy::type_complexity)] pub struct ItemWrapper<I, E>(I, PhantomData<E>); impl<I, E> Clone for ItemWrapper<I, E> where I: Clone, { fn clone(&self) -> Self { Self(self.0.clone(), PhantomData) } } impl<I, E> PartialEq for ItemWrapper<I, E> { fn eq(&self, _other: &Self) -> bool { true } } impl<I, E> Eq for ItemWrapper<I, E> {} impl<I, E> ItemWrapper<I, E> where I: Debug + Item + Send + Sync, E: Debug + Send + Sync + std::error::Error + From<<I as Item>::Error> + From<crate::Error> + 'static, for<'params> <I as Item>::Params<'params>: TryFrom<<<I as Item>::Params<'params> as Params>::Partial>, for<'params> <I::Params<'params> as Params>::Partial: From<I::Params<'params>>, { #[cfg(feature = "item_state_example")] fn state_example( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, ) -> Result<I::State, E> { let state_example = { let params = self.params( params_specs, mapping_fn_reg, resources, ValueResolutionMode::Example, )?; let data = <I::Data<'_> as Data>::borrow(self.id(), resources); I::state_example(&params, data) }; resources.borrow_mut::<Example<I::State>>().0 = Some(state_example.clone()); Ok(state_example) } async fn state_clean( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, ) -> Result<I::State, E> { let state_clean = { let params_partial = self.params_partial( params_specs, mapping_fn_reg, resources, ValueResolutionMode::Clean, )?; let data = <I::Data<'_> as Data>::borrow(self.id(), resources); I::state_clean(&params_partial, data).await? }; resources.borrow_mut::<Clean<I::State>>().0 = Some(state_clean.clone()); Ok(state_clean) } async fn state_current_try_exec( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, fn_ctx: FnCtx<'_>, ) -> Result<Option<I::State>, E> { let state_current = { let params_partial = self.params_partial( params_specs, mapping_fn_reg, resources, ValueResolutionMode::Current, )?; let data = <I::Data<'_> as Data>::borrow(self.id(), resources); I::try_state_current(fn_ctx, &params_partial, data).await? }; if let Some(state_current) = state_current.as_ref() { resources.borrow_mut::<Current<I::State>>().0 = Some(state_current.clone()); #[cfg(feature = "output_progress")] fn_ctx .progress_sender() .item_location_state_send(RefInto::<ItemLocationState>::into(state_current)); } Ok(state_current) } async fn state_current_exec( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, fn_ctx: FnCtx<'_>, ) -> Result<I::State, E> { let state_current = { let params = self.params( params_specs, mapping_fn_reg, resources, ValueResolutionMode::Current, )?; let data = <I::Data<'_> as Data>::borrow(self.id(), resources); I::state_current(fn_ctx, &params, data).await? }; resources.borrow_mut::<Current<I::State>>().0 = Some(state_current.clone()); #[cfg(feature = "output_progress")] fn_ctx .progress_sender() .item_location_state_send(RefInto::<ItemLocationState>::into(&state_current)); Ok(state_current) } async fn state_goal_try_exec( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, fn_ctx: FnCtx<'_>, ) -> Result<Option<I::State>, E> { let params_partial = self.params_partial( params_specs, mapping_fn_reg, resources, ValueResolutionMode::Goal, )?; // If a predecessor's goal state is the same as current, then a successor's // `state_goal_try_exec` should kind of use `ValueResolutionMode::Current`. // // But really we should insert the predecessor's current state as the // `Goal<Predecessor::State>`. let data = <I::Data<'_> as Data>::borrow(self.id(), resources); let state_goal = I::try_state_goal(fn_ctx, &params_partial, data).await?; if let Some(state_goal) = state_goal.as_ref() { resources.borrow_mut::<Goal<I::State>>().0 = Some(state_goal.clone()); } Ok(state_goal) } /// Returns the goal state for this item. /// /// `value_resolution_ctx` is passed in because: /// /// * When discovering the goal state for a flow, without altering any /// items, the goal state of a successor is dependent on the goal state of /// a predecessor. /// * When discovering the goal state of a successor, after a predecessor /// has had state applied, the predecessor's goal state does not /// necessarily contain the generated values, so we need to tell the /// successor to look up the predecessor's newly current state. /// * When cleaning up, the predecessor's current state must be used to /// resolve a successor's params. Since clean up is applied in reverse, /// the `Goal` state of a predecessor may not exist, and cause the /// successor to not be cleaned up. async fn state_goal_exec( &self, value_resolution_mode: ValueResolutionMode, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, fn_ctx: FnCtx<'_>, ) -> Result<I::State, E> { let params = self.params( params_specs, mapping_fn_reg, resources, value_resolution_mode, )?; let data = <I::Data<'_> as Data>::borrow(self.id(), resources); let state_goal = I::state_goal(fn_ctx, &params, data).await?; resources.borrow_mut::<Goal<I::State>>().0 = Some(state_goal.clone()); Ok(state_goal) } async fn state_diff_exec( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, states_a: &TypeMap<ItemId, BoxDtDisplay>, states_b: &TypeMap<ItemId, BoxDtDisplay>, ) -> Result<Option<I::StateDiff>, E> { let item_id = <I as Item>::id(self); let state_base = states_a.get::<I::State, _>(item_id); let state_goal = states_b.get::<I::State, _>(item_id); if let Some((state_base, state_goal)) = state_base.zip(state_goal) { let state_diff: I::StateDiff = self .state_diff_exec_with( params_specs, mapping_fn_reg, resources, state_base, state_goal, ) .await?; Ok(Some(state_diff)) } else { // When we reach here, one of the following is true: // // * The current state cannot be retrieved, due to a predecessor's state not // existing. // * The goal state cannot be retrieved, due to a predecessor's state not // existing. // * A bug exists, e.g. the state is stored against the wrong type parameter. Ok(None) } } async fn state_diff_exec_with( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, state_a: &I::State, state_b: &I::State, ) -> Result<I::StateDiff, E> { let state_diff: I::StateDiff = { // Running `diff` for a single profile will be between the current and goal // states, and parameters are not really intended to be used for diffing. // // However for `ShCmdItem`, the shell script for diffing's path is in // params, which *likely* would be provided as direct `Value`s instead of // mapped from predecessors' state(s). Iff the values are mapped from a // predecessor's state, then we would want it to be the goal state, as that // is closest to the correct value -- `ValueResolutionMode::ApplyDry` is used in // `Item::apply_dry`, and `ValueResolutionMode::Apply` is used in // `Item::apply`. // // Running `diff` for multiple profiles will likely be between two profiles' // current states. let params_partial = self.params_partial( params_specs, mapping_fn_reg, resources, ValueResolutionMode::Goal, )?; let data = <I::Data<'_> as Data>::borrow(self.id(), resources); I::state_diff(&params_partial, data, state_a, state_b) .await .map_err(Into::<E>::into)? }; Ok(state_diff) } async fn apply_check( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, state_current: &I::State, state_target: &I::State, state_diff: &I::StateDiff, value_resolution_mode: ValueResolutionMode, ) -> Result<ApplyCheck, E> { // Normally an `apply_check` only compares the states / state diff. // // We use `ValueResolutionMode::Goal` because an apply is between the current // and goal states, and when resolving values, we want the target state's // parameters to be used. Note that during an apply, the goal state is // resolved as execution happens -- values that rely on predecessors' applied // state will be fed into successors' goal state. let params_partial = self.params_partial( params_specs, mapping_fn_reg, resources, value_resolution_mode, )?; let data = <I::Data<'_> as Data>::borrow(self.id(), resources); if let Ok(params) = params_partial.try_into() { I::apply_check(&params, data, state_current, state_target, state_diff) .await .map_err(Into::<E>::into) } else { // > If we cannot resolve parameters, then this item, and its predecessor are // > cleaned up. // // The above is not necessarily true -- the user may have provided an incorrect // type to map from. However, it is more likely to be true than false. Ok(ApplyCheck::ExecNotRequired) } } async fn apply_exec_dry( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, fn_ctx: FnCtx<'_>, state_current: &I::State, state_goal: &I::State, state_diff: &I::StateDiff, ) -> Result<I::State, E> { let params = self.params( params_specs, mapping_fn_reg, resources, ValueResolutionMode::ApplyDry, )?; let data = <I::Data<'_> as Data>::borrow(self.id(), resources); let state_ensured_dry = I::apply_dry(fn_ctx, &params, data, state_current, state_goal, state_diff) .await .map_err(Into::<E>::into)?; resources.borrow_mut::<ApplyDry<I::State>>().0 = Some(state_ensured_dry.clone()); Ok(state_ensured_dry) } async fn apply_exec( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, fn_ctx: FnCtx<'_>, state_current: &I::State, state_goal: &I::State, state_diff: &I::StateDiff, ) -> Result<I::State, E> { let params = self.params( params_specs, mapping_fn_reg, resources, ValueResolutionMode::Current, )?; let data = <I::Data<'_> as Data>::borrow(self.id(), resources); let state_ensured = I::apply(fn_ctx, &params, data, state_current, state_goal, state_diff) .await .map_err(Into::<E>::into)?; resources.borrow_mut::<Current<I::State>>().0 = Some(state_ensured.clone()); #[cfg(feature = "output_progress")] fn_ctx .progress_sender() .item_location_state_send(RefInto::<ItemLocationState>::into(&state_ensured)); Ok(state_ensured) } fn params_partial( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, value_resolution_mode: ValueResolutionMode, ) -> Result<<<I as Item>::Params<'_> as Params>::Partial, E> { let item_id = self.id(); let params_spec = params_specs .get::<ParamsSpec<I::Params<'_>>, _>(item_id) .ok_or_else(|| crate::Error::ParamsSpecNotFound { item_id: item_id.clone(), })?; let mut value_resolution_ctx = ValueResolutionCtx::new( value_resolution_mode, item_id.clone(), tynm::type_name::<I::Params<'_>>(), ); Ok(params_spec .resolve_partial(&mapping_fn_reg, resources, &mut value_resolution_ctx) .map_err(crate::Error::ParamsResolveError)?) } fn params( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, value_resolution_mode: ValueResolutionMode, ) -> Result<<I as Item>::Params<'_>, E> { let item_id = self.id(); let params_spec = params_specs .get::<ParamsSpec<I::Params<'_>>, _>(item_id) .ok_or_else(|| crate::Error::ParamsSpecNotFound { item_id: item_id.clone(), })?; let mut value_resolution_ctx = ValueResolutionCtx::new( value_resolution_mode, item_id.clone(), tynm::type_name::<I::Params<'_>>(), ); Ok(params_spec .resolve(&mapping_fn_reg, resources, &mut value_resolution_ctx) .map_err(crate::Error::ParamsResolveError)?) } } impl<I, E> Debug for ItemWrapper<I, E> where I: Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } impl<I, E> Deref for ItemWrapper<I, E> { type Target = I; fn deref(&self) -> &Self::Target { &self.0 } } impl<I, E> DerefMut for ItemWrapper<I, E> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<I, E> From<I> for ItemWrapper<I, E> where I: Debug + Item + Send + Sync, E: Debug + Send + Sync + std::error::Error + From<<I as Item>::Error> + 'static, { fn from(item: I) -> Self { Self(item, PhantomData) } } impl<I, E> DataAccess for ItemWrapper<I, E> where I: Debug + Item + Send + Sync, E: Debug + Send + Sync + std::error::Error + From<<I as Item>::Error> + 'static, { fn borrows() -> TypeIds { let mut type_ids = <I::Data<'_> as DataAccess>::borrows(); type_ids.push(std::any::TypeId::of::<I::Params<'_>>()); type_ids } fn borrow_muts() -> TypeIds { <I::Data<'_> as DataAccess>::borrow_muts() } } impl<I, E> DataAccessDyn for ItemWrapper<I, E> where I: Debug + Item + Send + Sync, E: Debug + Send + Sync + std::error::Error + From<<I as Item>::Error> + 'static, { fn borrows(&self) -> TypeIds { let mut type_ids = <I::Data<'_> as DataAccess>::borrows(); type_ids.push(std::any::TypeId::of::<I::Params<'_>>()); type_ids } fn borrow_muts(&self) -> TypeIds { <I::Data<'_> as DataAccess>::borrow_muts() } } #[async_trait(?Send)] impl<I, E> ItemRt<E> for ItemWrapper<I, E> where I: Clone + Debug + Item + Send + Sync + 'static, E: Debug + Send + Sync + std::error::Error + From<<I as Item>::Error> + From<crate::Error> + 'static, for<'params> I::Params<'params>: ParamsMergeExt + TryFrom<<I::Params<'params> as Params>::Partial>, for<'params> <I::Params<'params> as Params>::Partial: From<I::Params<'params>> + From<<I::Params<'params> as TryFrom<<I::Params<'params> as Params>::Partial>>::Error>, { fn id(&self) -> &ItemId { <I as Item>::id(self) } fn eq(&self, other: &dyn ItemRt<E>) -> bool { if self.id() == other.id() { let other = other.as_any(); if let Some(item_wrapper) = other.downcast_ref::<Self>() { self == item_wrapper } else { false } } else { false } } fn as_any(&self) -> &dyn Any where Self: 'static, { self } async fn setup(&self, resources: &mut Resources<Empty>) -> Result<(), E> { // Insert `XMarker<I::State>` to create entries in `Resources`. // This is used for referential param values (#94) #[cfg(feature = "item_state_example")] resources.insert(Example::<I::State>(None)); resources.insert(Clean::<I::State>(None)); resources.insert(Current::<I::State>(None)); resources.insert(Goal::<I::State>(None)); resources.insert(ApplyDry::<I::State>(None)); // Run user defined setup. <I as Item>::setup(self, resources) .await .map_err(Into::<E>::into) } fn params_and_state_register( &self, params_specs_type_reg: &mut ParamsSpecsTypeReg, states_type_reg: &mut StatesTypeReg, ) { params_specs_type_reg.register::<ParamsSpec<I::Params<'_>>>(I::id(self).clone()); states_type_reg.register::<I::State>(I::id(self).clone()); } fn state_eq(&self, state_a: &BoxDtDisplay, state_b: &BoxDtDisplay) -> Result<bool, E> { let state_a_downcasted = BoxDataTypeDowncast::<I::State>::downcast_ref(state_a); let state_b_downcasted = BoxDataTypeDowncast::<I::State>::downcast_ref(state_b); match (state_a_downcasted, state_b_downcasted) { (None, None) => Err(crate::Error::StateDowncastError(StateDowncastError::Both { ty_name: tynm::type_name::<I::State>(), state_a: state_a.clone(), state_b: state_b.clone(), }) .into()), (None, Some(_)) => Err(crate::Error::StateDowncastError(StateDowncastError::First { ty_name: tynm::type_name::<I::State>(), state_a: state_a.clone(), }) .into()), (Some(_), None) => Err( crate::Error::StateDowncastError(StateDowncastError::Second { ty_name: tynm::type_name::<I::State>(), state_b: state_b.clone(), }) .into(), ), (Some(state_a), Some(state_b)) => Ok(state_a == state_b), } } #[cfg(feature = "item_state_example")] fn state_example( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, ) -> Result<BoxDtDisplay, E> { self.state_example(params_specs, mapping_fn_reg, resources) .map(BoxDtDisplay::new) } async fn state_clean( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, ) -> Result<BoxDtDisplay, E> { self.state_clean(params_specs, mapping_fn_reg, resources) .await .map(BoxDtDisplay::new) } async fn state_current_try_exec( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, fn_ctx: FnCtx<'_>, ) -> Result<Option<BoxDtDisplay>, E> { self.state_current_try_exec(params_specs, mapping_fn_reg, resources, fn_ctx) .await .map(|state_current| state_current.map(BoxDtDisplay::new)) } async fn state_current_exec( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, fn_ctx: FnCtx<'_>, ) -> Result<BoxDtDisplay, E> { self.state_current_exec(params_specs, mapping_fn_reg, resources, fn_ctx) .await .map(BoxDtDisplay::new) } async fn state_goal_try_exec( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, fn_ctx: FnCtx<'_>, ) -> Result<Option<BoxDtDisplay>, E> { self.state_goal_try_exec(params_specs, mapping_fn_reg, resources, fn_ctx) .await .map(|state_goal| state_goal.map(BoxDtDisplay::new)) } async fn state_goal_exec( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, fn_ctx: FnCtx<'_>, ) -> Result<BoxDtDisplay, E> { self.state_goal_exec( // Use the would-be state of predecessor to discover goal state of this item. // // TODO: this means we may need to overlay the goal state with the predecessor's // current state. // // Or more feasibly, if predecessor's ApplyCheck is ExecNotRequired, then we can use // predecessor's current state. ValueResolutionMode::Goal, params_specs, mapping_fn_reg, resources, fn_ctx, ) .await .map(BoxDtDisplay::new) } async fn state_diff_exec( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, states_a: &TypeMap<ItemId, BoxDtDisplay>, states_b: &TypeMap<ItemId, BoxDtDisplay>, ) -> Result<Option<BoxDtDisplay>, E> { self.state_diff_exec(params_specs, mapping_fn_reg, resources, states_a, states_b) .await .map(|state_diff_opt| state_diff_opt.map(BoxDtDisplay::new)) } async fn ensure_prepare( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, fn_ctx: FnCtx<'_>, ) -> Result<ItemApplyBoxed, (E, ItemApplyPartialBoxed)> { let mut item_apply_partial = ItemApplyPartial::<I::State, I::StateDiff>::new(); match self .state_current_exec(params_specs, mapping_fn_reg, resources, fn_ctx) .await { Ok(state_current) => item_apply_partial.state_current = Some(state_current), Err(error) => return Err((error, item_apply_partial.into())), } #[cfg(feature = "output_progress")] fn_ctx.progress_sender().reset_to_pending(); match self .state_goal_exec( // Use current state of predecessor to discover goal state. ValueResolutionMode::Current, params_specs, mapping_fn_reg, resources, fn_ctx, ) .await { Ok(state_goal) => item_apply_partial.state_target = Some(state_goal), Err(error) => return Err((error, item_apply_partial.into())), } #[cfg(feature = "output_progress")] fn_ctx.progress_sender().reset_to_pending(); match self .state_diff_exec_with( params_specs, mapping_fn_reg, resources, item_apply_partial .state_current .as_ref() .expect("unreachable: This is set just above."), item_apply_partial .state_target .as_ref() .expect("unreachable: This is set just above."), ) .await { Ok(state_diff) => item_apply_partial.state_diff = Some(state_diff), Err(error) => return Err((error, item_apply_partial.into())), } let (Some(state_current), Some(state_goal), Some(state_diff)) = ( item_apply_partial.state_current.as_ref(), item_apply_partial.state_target.as_ref(), item_apply_partial.state_diff.as_ref(), ) else { unreachable!("These are set just above."); }; let apply_check = self .apply_check( params_specs, mapping_fn_reg, resources, state_current, state_goal, state_diff, // Use current state of predecessor to discover goal state. ValueResolutionMode::Current, ) .await; let state_applied = match apply_check { Ok(apply_check) => { item_apply_partial.apply_check = Some(apply_check); // TODO: write test for this case match apply_check { #[cfg(not(feature = "output_progress"))] ApplyCheck::ExecRequired => None, #[cfg(feature = "output_progress")] ApplyCheck::ExecRequired { .. } => None, ApplyCheck::ExecNotRequired => item_apply_partial.state_current.clone(), } } Err(error) => return Err((error, item_apply_partial.into())), }; Ok(ItemApply::try_from((item_apply_partial, state_applied)) .expect("unreachable: All the fields are set above.") .into()) } async fn apply_exec_dry( &self, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, fn_ctx: FnCtx<'_>, item_apply_boxed: &mut ItemApplyBoxed, ) -> Result<(), E> { let Some(item_apply) = item_apply_boxed .as_data_type_mut() .downcast_mut::<ItemApply<I::State, I::StateDiff>>() else { panic!( "Failed to downcast `ItemApplyBoxed` to `{concrete_type}`.\n\ This is a bug in the Peace framework.", concrete_type = std::any::type_name::<ItemApply<I::State, I::StateDiff>>() ) }; let ItemApply { state_current_stored: _, state_current, state_target, state_diff, apply_check, state_applied, } = item_apply; match apply_check { #[cfg(not(feature = "output_progress"))] ApplyCheck::ExecRequired => { let state_applied_dry = self .apply_exec_dry( params_specs, mapping_fn_reg, resources, fn_ctx, state_current, state_target, state_diff, ) .await?; *state_applied = Some(state_applied_dry); } #[cfg(feature = "output_progress")] ApplyCheck::ExecRequired { progress_limit: _ } => { let state_applied_dry = self .apply_exec_dry( params_specs, mapping_fn_reg, resources, fn_ctx, state_current, state_target, state_diff, ) .await?; *state_applied = Some(state_applied_dry); } ApplyCheck::ExecNotRequired => {} } Ok(()) } async fn clean_prepare( &self, states_current: &StatesCurrent, params_specs: &ParamsSpecs, mapping_fn_reg: &MappingFnReg, resources: &Resources<SetUp>, ) -> Result<ItemApplyBoxed, (E, ItemApplyPartialBoxed)> { let mut item_apply_partial = ItemApplyPartial::<I::State, I::StateDiff>::new(); if let Some(state_current) = states_current.get::<I::State, _>(self.id()) { item_apply_partial.state_current = Some(state_current.clone()); } else { // Hack: Setting ItemApplyPartial state_current to state_clean is a hack, // which allows successor items to read the state of a predecessor, when // none can be discovered. // // This may not necessarily be a hack. match self .state_clean(params_specs, mapping_fn_reg, resources) .await { Ok(state_clean) => item_apply_partial.state_current = Some(state_clean), Err(error) => return Err((error, item_apply_partial.into())), } } match self .state_clean(params_specs, mapping_fn_reg, resources) .await { Ok(state_clean) => item_apply_partial.state_target = Some(state_clean), Err(error) => return Err((error, item_apply_partial.into())), } match self .state_diff_exec_with( params_specs, mapping_fn_reg, resources, item_apply_partial .state_current .as_ref() .expect("unreachable: This is confirmed just above."), item_apply_partial .state_target .as_ref() .expect("unreachable: This is set just above."), ) .await { Ok(state_diff) => item_apply_partial.state_diff = Some(state_diff), Err(error) => return Err((error, item_apply_partial.into())), } let (Some(state_current), Some(state_clean), Some(state_diff)) = ( item_apply_partial.state_current.as_ref(), item_apply_partial.state_target.as_ref(), item_apply_partial.state_diff.as_ref(), ) else { unreachable!("These are set just above."); }; let apply_check = self .apply_check( params_specs, mapping_fn_reg, resources, state_current, state_clean, state_diff, // Use current state of predecessor to discover goal state. ValueResolutionMode::Current, ) .await;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
true
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model/src/params_specs_type_reg.rs
crate/rt_model/src/params_specs_type_reg.rs
use std::ops::{Deref, DerefMut}; use peace_item_model::ItemId; use peace_params::AnySpecRtBoxed; use peace_resource_rt::type_reg::untagged::TypeReg; /// Type registry for each item's [`Params`]'s Spec. /// /// This is used to deserialize [`ParamsSpecsFile`]. /// /// Note: [`StatesTypeReg`] uses [`BoxDtDisplay`], whereas this uses /// [`AnySpecRtBoxed`]. /// /// [`AnySpecRtBoxed`]: peace_params::AnySpecRtBoxed /// [`BoxDtDisplay`]: peace_resource_rt::type_reg::untagged::BoxDtDisplay /// [`Params`]: peace_cfg::Item::Params /// [`StatesTypeReg`]: crate::StatesTypeReg #[derive(Debug, Default)] pub struct ParamsSpecsTypeReg(TypeReg<ItemId, AnySpecRtBoxed>); impl ParamsSpecsTypeReg { /// Returns a new `ParamsSpecsTypeReg`. pub fn new() -> Self { Self::default() } } impl Deref for ParamsSpecsTypeReg { type Target = TypeReg<ItemId, AnySpecRtBoxed>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for ParamsSpecsTypeReg { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model/src/outcomes/item_apply_partial_rt.rs
crate/rt_model/src/outcomes/item_apply_partial_rt.rs
use peace_cfg::ApplyCheck; use peace_resource_rt::type_reg::untagged::{BoxDtDisplay, DataType}; /// Trait to allow inspecting a type-erased `ItemApplyPartial`. pub trait ItemApplyPartialRt: DataType { /// Returns `state_current_stored` as type-erased data. fn state_current_stored(&self) -> Option<BoxDtDisplay>; /// Returns `state_current` as type-erased data. fn state_current(&self) -> Option<BoxDtDisplay>; /// Returns `state_target` as type-erased data. fn state_target(&self) -> Option<BoxDtDisplay>; /// Returns `state_diff` as type-erased data. fn state_diff(&self) -> Option<BoxDtDisplay>; /// Returns `apply_check` as type-erased data. fn apply_check(&self) -> Option<ApplyCheck>; /// Returns self as a `&dyn DataType`; fn as_data_type(&self) -> &dyn DataType; /// Returns self as a `&mut dyn DataType`; fn as_data_type_mut(&mut self) -> &mut dyn DataType; } dyn_clone::clone_trait_object!(ItemApplyPartialRt); impl ItemApplyPartialRt for Box<dyn ItemApplyPartialRt> { fn state_current_stored(&self) -> Option<BoxDtDisplay> { self.as_ref().state_current_stored() } fn state_current(&self) -> Option<BoxDtDisplay> { self.as_ref().state_current() } fn state_target(&self) -> Option<BoxDtDisplay> { self.as_ref().state_target() } fn state_diff(&self) -> Option<BoxDtDisplay> { self.as_ref().state_diff() } fn apply_check(&self) -> Option<ApplyCheck> { self.as_ref().apply_check() } fn as_data_type(&self) -> &dyn DataType { self.as_ref().as_data_type() } fn as_data_type_mut(&mut self) -> &mut dyn DataType { self.as_mut().as_data_type_mut() } } impl serde::Serialize for dyn ItemApplyPartialRt + '_ { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { erased_serde::serialize(self, serializer) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model/src/outcomes/item_apply_boxed.rs
crate/rt_model/src/outcomes/item_apply_boxed.rs
use crate::outcomes::{ItemApply, ItemApplyRt}; /// A boxed `ItemApply`. #[derive(Clone, serde::Serialize)] pub struct ItemApplyBoxed(pub(crate) Box<dyn ItemApplyRt>); impl<State, StateDiff> From<ItemApply<State, StateDiff>> for ItemApplyBoxed where ItemApply<State, StateDiff>: ItemApplyRt, { /// Returns an `ItemApplyBoxed` which erases an `ItemApply`'s type /// parameters. fn from(item_apply: ItemApply<State, StateDiff>) -> Self { Self(Box::new(item_apply)) } } crate::outcomes::box_data_type_newtype!(ItemApplyBoxed, ItemApplyRt);
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model/src/outcomes/item_apply_rt.rs
crate/rt_model/src/outcomes/item_apply_rt.rs
use peace_cfg::ApplyCheck; use peace_resource_rt::type_reg::untagged::{BoxDtDisplay, DataType}; /// Trait to allow inspecting a type-erased `ItemApply`. pub trait ItemApplyRt: DataType { /// Returns `state_current_stored` as type-erased data. fn state_current_stored(&self) -> Option<BoxDtDisplay>; /// Returns `state_current` as type-erased data. fn state_current(&self) -> BoxDtDisplay; /// Returns `state_target` as type-erased data. fn state_target(&self) -> BoxDtDisplay; /// Returns `state_diff` as type-erased data. fn state_diff(&self) -> BoxDtDisplay; /// Returns `apply_check` as type-erased data. fn apply_check(&self) -> ApplyCheck; /// Returns `state_applied` as type-erased data. fn state_applied(&self) -> Option<BoxDtDisplay>; /// Returns self as a `&dyn DataType`; fn as_data_type(&self) -> &dyn DataType; /// Returns self as a `&mut dyn DataType`; fn as_data_type_mut(&mut self) -> &mut dyn DataType; } dyn_clone::clone_trait_object!(ItemApplyRt); impl ItemApplyRt for Box<dyn ItemApplyRt> { fn state_current_stored(&self) -> Option<BoxDtDisplay> { self.as_ref().state_current_stored() } fn state_current(&self) -> BoxDtDisplay { self.as_ref().state_current() } fn state_target(&self) -> BoxDtDisplay { self.as_ref().state_target() } fn state_diff(&self) -> BoxDtDisplay { self.as_ref().state_diff() } fn apply_check(&self) -> ApplyCheck { self.as_ref().apply_check() } fn state_applied(&self) -> Option<BoxDtDisplay> { self.as_ref().state_applied() } fn as_data_type(&self) -> &dyn DataType { self.as_ref().as_data_type() } fn as_data_type_mut(&mut self) -> &mut dyn DataType { self.as_mut().as_data_type_mut() } } impl serde::Serialize for dyn ItemApplyRt + '_ { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { erased_serde::serialize(self, serializer) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model/src/outcomes/item_apply.rs
crate/rt_model/src/outcomes/item_apply.rs
use std::fmt::{Debug, Display}; use peace_cfg::ApplyCheck; use peace_resource_rt::type_reg::untagged::{BoxDtDisplay, DataType}; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use crate::outcomes::{ItemApplyPartial, ItemApplyRt}; /// Information about an item during an `ApplyCmd` execution. /// /// This is similar to [`ItemApplyPartial`], with most fields being /// non-optional, and the added `state_applied` field. #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] pub struct ItemApply<State, StateDiff> { /// Current state stored on disk before the execution. pub state_current_stored: Option<State>, /// Current state discovered during the execution. pub state_current: State, /// Target state discovered during the execution. pub state_target: State, /// Diff between current and goal states. pub state_diff: StateDiff, /// Whether item execution was required. pub apply_check: ApplyCheck, /// The state that was applied, `None` if execution was not required. pub state_applied: Option<State>, } impl<State, StateDiff> TryFrom<(ItemApplyPartial<State, StateDiff>, Option<State>)> for ItemApply<State, StateDiff> { type Error = (ItemApplyPartial<State, StateDiff>, Option<State>); fn try_from( (partial, state_applied): (ItemApplyPartial<State, StateDiff>, Option<State>), ) -> Result<Self, Self::Error> { let ItemApplyPartial { state_current_stored, state_current, state_target, state_diff, apply_check, } = partial; if state_current.is_some() && state_target.is_some() && state_diff.is_some() && apply_check.is_some() { let (Some(state_current), Some(state_target), Some(state_diff), Some(apply_check)) = (state_current, state_target, state_diff, apply_check) else { unreachable!("All are checked to be `Some` above."); }; Ok(Self { state_current_stored, state_current, state_target, state_diff, apply_check, state_applied, }) } else { let partial = ItemApplyPartial { state_current_stored, state_current, state_target, state_diff, apply_check, }; Err((partial, state_applied)) } } } impl<State, StateDiff> ItemApplyRt for ItemApply<State, StateDiff> where State: Clone + Debug + Display + Serialize + DeserializeOwned + Send + Sync + 'static, StateDiff: Clone + Debug + Display + Serialize + DeserializeOwned + Send + Sync + 'static, { fn state_current_stored(&self) -> Option<BoxDtDisplay> { self.state_current_stored.clone().map(BoxDtDisplay::new) } fn state_current(&self) -> BoxDtDisplay { BoxDtDisplay::new(self.state_current.clone()) } fn state_target(&self) -> BoxDtDisplay { BoxDtDisplay::new(self.state_target.clone()) } fn state_diff(&self) -> BoxDtDisplay { BoxDtDisplay::new(self.state_diff.clone()) } fn apply_check(&self) -> ApplyCheck { self.apply_check } fn state_applied(&self) -> Option<BoxDtDisplay> { self.state_applied.clone().map(BoxDtDisplay::new) } fn as_data_type(&self) -> &dyn DataType { self } fn as_data_type_mut(&mut self) -> &mut dyn DataType { self } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model/src/outcomes/item_apply_partial_boxed.rs
crate/rt_model/src/outcomes/item_apply_partial_boxed.rs
use crate::outcomes::{ItemApplyPartial, ItemApplyPartialRt}; /// A boxed `ItemApplyPartial`. #[derive(Clone, serde::Serialize)] pub struct ItemApplyPartialBoxed(pub(crate) Box<dyn ItemApplyPartialRt>); impl<State, StateDiff> From<ItemApplyPartial<State, StateDiff>> for ItemApplyPartialBoxed where ItemApplyPartial<State, StateDiff>: ItemApplyPartialRt, { /// Returns an `ItemApplyPartialBoxed` which erases an /// `ItemApplyPartial`'s type parameters. fn from(item_apply: ItemApplyPartial<State, StateDiff>) -> Self { Self(Box::new(item_apply)) } } crate::outcomes::box_data_type_newtype!(ItemApplyPartialBoxed, ItemApplyPartialRt);
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model/src/outcomes/item_apply_partial.rs
crate/rt_model/src/outcomes/item_apply_partial.rs
use std::fmt::{Debug, Display}; use peace_cfg::ApplyCheck; use peace_resource_rt::type_reg::untagged::{BoxDtDisplay, DataType}; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use crate::outcomes::ItemApplyPartialRt; /// Information about an item during an `ApplyCmd` execution. /// /// # Design Note /// /// 1. `ApplyCmd` calls the following function for each item. /// /// - [`Item::state_current`] /// - [`Item::state_goal`] or [`Item::state_clean`] /// - [`Item::state_diff`] /// - [`ApplyFns::check`] /// - [`ApplyFns::exec`] /// - [`Item::state_current`] /// /// 2. Each function call *may* fail. /// 3. If we have an enum representing the state after each function call, we /// have to duplicate the earlier fields per variant. /// /// It is not likely to be error prone or too unergonomic to store each field as /// optional. /// /// [`Item::state_current`]: peace_cfg::Item::state_current /// [`Item::state_goal`]: peace_cfg::Item::state_goal /// [`Item::state_diff`]: peace_cfg::Item::state_diff /// [`ApplyFns::check`]: peace_cfg::Item::ApplyFns /// [`ApplyFns::exec`]: peace_cfg::Item::ApplyFns #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] pub struct ItemApplyPartial<State, StateDiff> { /// Current state stored on disk before the execution. pub state_current_stored: Option<State>, /// Current state discovered during the execution. pub state_current: Option<State>, /// Target state discovered during the execution. pub state_target: Option<State>, /// Diff between current and goal states. pub state_diff: Option<StateDiff>, /// Whether item execution is required. pub apply_check: Option<ApplyCheck>, } impl<State, StateDiff> ItemApplyPartial<State, StateDiff> { /// Returns a new `ItemApplyPartial` with all fields set to `None`. pub fn new() -> Self { Self::default() } } impl<State, StateDiff> Default for ItemApplyPartial<State, StateDiff> { fn default() -> Self { Self { state_current_stored: None, state_current: None, state_target: None, state_diff: None, apply_check: None, } } } impl<State, StateDiff> ItemApplyPartialRt for ItemApplyPartial<State, StateDiff> where State: Clone + Debug + Display + Serialize + DeserializeOwned + Send + Sync + 'static, StateDiff: Clone + Debug + Display + Serialize + DeserializeOwned + Send + Sync + 'static, { fn state_current_stored(&self) -> Option<BoxDtDisplay> { self.state_current_stored.clone().map(BoxDtDisplay::new) } fn state_current(&self) -> Option<BoxDtDisplay> { self.state_current.clone().map(BoxDtDisplay::new) } fn state_target(&self) -> Option<BoxDtDisplay> { self.state_target.clone().map(BoxDtDisplay::new) } fn state_diff(&self) -> Option<BoxDtDisplay> { self.state_diff.clone().map(BoxDtDisplay::new) } fn apply_check(&self) -> Option<ApplyCheck> { self.apply_check } fn as_data_type(&self) -> &dyn DataType { self } fn as_data_type_mut(&mut self) -> &mut dyn DataType { self } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_ctx/src/cmd_ctx_mpsf_params.rs
crate/cmd_ctx/src/cmd_ctx_mpsf_params.rs
use std::{collections::BTreeMap, fmt::Debug, future::IntoFuture}; use futures::{future::LocalBoxFuture, FutureExt}; use interruptible::Interruptibility; use own::{OwnedOrMutRef, OwnedOrRef}; use peace_flow_rt::Flow; use peace_item_model::ItemId; use peace_params::{ParamsSpecs, ParamsValue}; use peace_profile_model::Profile; use peace_resource_rt::{internal::WorkspaceParamsFile, resources::ts::Empty, Resources}; use peace_rt_model::{ params::{FlowParamsOpt, ProfileParamsOpt, WorkspaceParamsOpt}, Workspace, WorkspaceInitializer, }; use typed_builder::TypedBuilder; use crate::{ CmdCtxBuilderSupport, CmdCtxBuilderSupportMulti, CmdCtxMpsf, CmdCtxMpsfFields, CmdCtxTypes, ProfileFilterFn, }; /// A command that works with multiple profiles, and a single flow. /// /// ```bash /// path/to/repo/.peace/envman /// |- πŸ“ workspace_params.yaml # βœ… can read or write `WorkspaceParams` /// | /// |- 🌏 internal_dev_a # βœ… can list multiple `Profile`s /// | |- πŸ“ profile_params.yaml # βœ… can read multiple `ProfileParams` /// | | /// | |- 🌊 deploy # βœ… can read `FlowId` /// | | |- πŸ“ flow_params.yaml # βœ… can read or write `FlowParams` /// | | |- πŸ“‹ states_goal.yaml # βœ… can read or write `StatesGoal` /// | | |- πŸ“‹ states_current.yaml # βœ… can read or write `StatesCurrentStored` /// | | /// | |- 🌊 .. # ❌ cannot read or write other `Flow` information /// | /// |- 🌏 customer_a_dev # βœ… /// | |- πŸ“ profile_params.yaml # βœ… /// | | /// | |- 🌊 deploy # βœ… /// | |- πŸ“ flow_params.yaml # βœ… /// | |- πŸ“‹ states_goal.yaml # βœ… /// | |- πŸ“‹ states_current.yaml # βœ… /// | /// |- 🌏 customer_a_prod # βœ… /// | |- πŸ“ profile_params.yaml # βœ… /// | | /// | |- 🌊 deploy # βœ… /// | |- πŸ“ flow_params.yaml # βœ… /// | |- πŸ“‹ states_goal.yaml # βœ… /// | |- πŸ“‹ states_current.yaml # βœ… /// | /// | /// |- 🌏 workspace_init # βœ… can list multiple `Profile`s /// |- πŸ“ profile_params.yaml # ❌ cannot read profile params of different underlying type /// | |- 🌊 workspace_init # ❌ cannot read unrelated flows /// ``` /// /// ## Capabilities /// /// This kind of command can: /// /// * Read or write workspace parameters. /// * Read or write multiple profiles' parameters &ndash; as long as they are of /// the same type (same `struct`). /// * Read or write flow parameters for the same flow. /// * Read or write flow state for the same flow. /// /// This kind of command cannot: /// /// * Read or write flow parameters for different flows. /// * Read or write flow state for different flows. #[derive(Debug, TypedBuilder)] #[builder(build_method(vis="", name=build_partial))] pub struct CmdCtxMpsfParams<'ctx, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Output endpoint to return values / errors, and write progress /// information to. /// /// See [`OutputWrite`]. /// /// [`OutputWrite`]: peace_rt_model_core::OutputWrite #[builder(setter(prefix = "with_"))] pub output: OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>, /// The interrupt channel receiver if this `CmdExecution` is interruptible. #[builder(setter(prefix = "with_"), default = Interruptibility::NonInterruptible)] pub interruptibility: Interruptibility<'static>, /// Workspace that the `peace` tool runs in. #[builder(setter(prefix = "with_"))] pub workspace: OwnedOrRef<'ctx, Workspace>, /// Function to filter the profiles that are accessible by this command. #[builder(setter( prefix = "with_", transform = |f: impl Fn(&Profile) -> bool + 'static| Some(ProfileFilterFn(Box::new(f)))), default = None )] pub profile_filter_fn: Option<ProfileFilterFn>, /// The chosen process flow. #[builder(setter(prefix = "with_"))] pub flow: OwnedOrRef<'ctx, Flow<CmdCtxTypesT::AppError>>, /// Workspace params. // // NOTE: When updating this mutator, also update it for all the other `CmdCtx*Params` types. #[builder( setter(prefix = "with_"), via_mutators(init = WorkspaceParamsOpt::default()), mutators( /// Sets the value at the given workspace params key. /// /// # Parameters /// /// * `key`: The key to store the given value against. /// * `value`: The value to store at the given key. This is an /// `Option` so that you may remove a value if desired. /// /// # Type Parameters /// /// * `V`: The serializable type stored at the given key. pub fn with_workspace_param<V>( &mut self, key: CmdCtxTypesT::WorkspaceParamsKey, value: Option<V>, ) where V: ParamsValue, { let _ = self.workspace_params.insert(key, value); } ) )] #[builder(setter(prefix = "with_"))] pub workspace_params: WorkspaceParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::WorkspaceParamsKey>, /// Profile params for each profile. // // NOTE: When updating this mutator, also update it for all the other `CmdCtx*Params` types. #[builder( setter(prefix = "with_"), via_mutators(init = BTreeMap::new()), mutators( /// Sets the value at the given profile params key for a given profile. /// /// # Parameters /// /// * `key`: The key to store the given value against. /// * `value`: The value to store at the given key. This is an /// `Option` so that you may remove a value if desired. /// /// # Type Parameters /// /// * `V`: The serializable type stored at the given key. pub fn with_profile_param<V>( &mut self, profile: &Profile, key: CmdCtxTypesT::ProfileParamsKey, value: Option<V>, ) where V: ParamsValue, { match self.profile_to_profile_params.get_mut(profile) { Some(profile_params) => { let _ = profile_params.insert(key, value); } None => { let mut profile_params = ProfileParamsOpt::new(); let _ = profile_params.insert(key, value); self.profile_to_profile_params.insert(profile.clone(), profile_params); } } } ) )] pub profile_to_profile_params: BTreeMap<Profile, ProfileParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::ProfileParamsKey>>, /// Flow params for each profile. #[builder( setter(prefix = "with_"), via_mutators(init = BTreeMap::new()), mutators( /// Sets the value at the given flow params key for a given profile. /// /// # Parameters /// /// * `profile`: The profile whose parameters to modify. /// * `key`: The key to store the given value against. /// * `value`: The value to store at the given key. This is an /// `Option` so that you may remove a value if desired. /// /// # Type Parameters /// /// * `V`: The serializable type stored at the given key. pub fn with_flow_param<V>( &mut self, profile: &Profile, key: CmdCtxTypesT::FlowParamsKey, value: Option<V>, ) where V: ParamsValue, { match self.profile_to_flow_params.get_mut(profile) { Some(flow_params) => { let _ = flow_params.insert(key, value); } None => { let mut flow_params = FlowParamsOpt::new(); let _ = flow_params.insert(key, value); self.profile_to_flow_params.insert(profile.clone(), flow_params); } } } ) )] pub profile_to_flow_params: BTreeMap<Profile, FlowParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::FlowParamsKey>>, /// Item params specs for the selected flow for each profile. // // NOTE: When updating this mutator, also check if `CmdCtxSpsf` needs its mutator updated. #[builder( via_mutators(init = BTreeMap::new()), mutators( /// Sets an item's parameters at a given profile. /// /// # Parameters /// /// * `profile`: The profile whose item parameters to set. /// * `item_id`: The ID of the item whose parameters to set. /// * `params_spec`: The specification of how to resolve the /// parameters. /// /// # Type Parameters /// /// * `I`: The `Item` type. pub fn with_item_params<I>( &mut self, profile: &Profile, item_id: ItemId, params_spec: <I::Params<'_> as peace_params::Params>::Spec, ) where I: peace_cfg::Item, CmdCtxTypesT::AppError: From<I::Error>, { match self.profile_to_params_specs.get_mut(profile) { Some(params_specs) => { params_specs.insert(item_id, params_spec); } None => { let mut params_specs = ParamsSpecs::new(); params_specs.insert(item_id, params_spec); self.profile_to_params_specs.insert(profile.clone(), params_specs); } } } ) )] pub profile_to_params_specs: BTreeMap<Profile, ParamsSpecs>, /// `Resources` for flow execution. /// /// A "resource" is any object, and `resources` is a map where each object /// is keyed by its type. This means only one instance of each type can be /// held by the map. /// /// Resources are made available to `Item`s through their `Data` associated /// type. // // NOTE: When updating this mutator, also check if `CmdCtxMpsf` needs its mutator updated. #[builder( setter(prefix = "with_"), via_mutators(init = Resources::<Empty>::new()), mutators( /// Adds an object to the in-memory resources. pub fn with_resource<R>( &mut self, resource: R, ) where R: peace_resource_rt::Resource, { self.resources.insert(resource); } ) )] pub resources: Resources<Empty>, } // Use one of the following to obtain the generated type signature: // // ```sh // cargo expand -p peace_cmd_ctx cmd_ctx_mpsf_params // ``` // // Sublime text command: // // **LSP-rust-analyzer: Expand Macro Recursively** while the caret is on the // `TypedBuilder` derive. #[allow(non_camel_case_types)] impl<'ctx, CmdCtxTypesT, __interruptibility, __profile_filter_fn> CmdCtxMpsfParamsBuilder< 'ctx, CmdCtxTypesT, ( (OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>,), __interruptibility, (OwnedOrRef<'ctx, Workspace>,), __profile_filter_fn, (OwnedOrRef<'ctx, Flow<CmdCtxTypesT::AppError>>,), (WorkspaceParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::WorkspaceParamsKey>,), ( BTreeMap< Profile, ProfileParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::ProfileParamsKey>, >, ), (BTreeMap<Profile, FlowParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::FlowParamsKey>>,), (BTreeMap<Profile, ParamsSpecs>,), (Resources<Empty>,), ), > where CmdCtxTypesT: CmdCtxTypes, CmdCtxMpsfParams<'ctx, CmdCtxTypesT>: for<'__typed_builder_lifetime_for_default> ::typed_builder::NextFieldDefault< ( &'__typed_builder_lifetime_for_default OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>, __interruptibility, ), Output = Interruptibility<'static>, >, CmdCtxMpsfParams<'ctx, CmdCtxTypesT>: for<'__typed_builder_lifetime_for_default> ::typed_builder::NextFieldDefault< ( &'__typed_builder_lifetime_for_default OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>, &'__typed_builder_lifetime_for_default Interruptibility<'static>, &'__typed_builder_lifetime_for_default OwnedOrRef<'ctx, Workspace>, __profile_filter_fn, ), Output = Option<ProfileFilterFn>, >, { pub async fn build(self) -> Result<CmdCtxMpsf<'ctx, CmdCtxTypesT>, CmdCtxTypesT::AppError> { let CmdCtxMpsfParams { output, interruptibility, workspace, profile_filter_fn, flow, workspace_params: workspace_params_provided, profile_to_profile_params: profile_to_profile_params_provided, profile_to_flow_params: profile_to_flow_params_provided, profile_to_params_specs: profile_to_params_specs_provided, resources: resources_override, } = self.build_partial(); let workspace_params_type_reg = CmdCtxBuilderSupport::params_type_reg_initialize::<CmdCtxTypesT::WorkspaceParamsKey>(); let profile_params_type_reg = CmdCtxBuilderSupport::params_type_reg_initialize::<CmdCtxTypesT::ProfileParamsKey>(); let flow_params_type_reg = CmdCtxBuilderSupport::params_type_reg_initialize::<CmdCtxTypesT::FlowParamsKey>(); let workspace_dirs = workspace.dirs(); let storage = workspace.storage(); let workspace_params_file = WorkspaceParamsFile::from(workspace_dirs.peace_app_dir()); let workspace_params = CmdCtxBuilderSupport::workspace_params_merge( storage, &workspace_params_type_reg, workspace_params_provided, &workspace_params_file, ) .await?; let profiles = CmdCtxBuilderSupportMulti::<CmdCtxTypesT>::profiles_from_peace_app_dir( workspace_dirs.peace_app_dir(), profile_filter_fn.as_ref(), ) .await?; let (profile_dirs, profile_history_dirs) = CmdCtxBuilderSupportMulti::<CmdCtxTypesT>::profile_and_history_dirs_read( &profiles, workspace_dirs, ); let flow_dirs = CmdCtxBuilderSupportMulti::<CmdCtxTypesT>::flow_dirs_read(&profile_dirs, &flow); let mut dirs_to_create = vec![ AsRef::<std::path::Path>::as_ref(workspace_dirs.workspace_dir()), AsRef::<std::path::Path>::as_ref(workspace_dirs.peace_dir()), AsRef::<std::path::Path>::as_ref(workspace_dirs.peace_app_dir()), ]; profile_dirs .values() .map(AsRef::<std::path::Path>::as_ref) .chain( profile_history_dirs .values() .map(AsRef::<std::path::Path>::as_ref), ) .chain(flow_dirs.values().map(AsRef::<std::path::Path>::as_ref)) .for_each(|dir| dirs_to_create.push(dir)); // Create directories and write init parameters to storage. #[cfg(target_arch = "wasm32")] { WorkspaceInitializer::dirs_create(storage, dirs_to_create).await?; } #[cfg(not(target_arch = "wasm32"))] { WorkspaceInitializer::dirs_create(dirs_to_create).await?; let workspace_dir = workspace_dirs.workspace_dir(); std::env::set_current_dir(workspace_dir).map_err( #[cfg_attr(coverage_nightly, coverage(off))] |error| { peace_rt_model::Error::Native(peace_rt_model::NativeError::CurrentDirSet { workspace_dir: workspace_dir.clone(), error, }) }, )?; } // profile_params_deserialize let profile_to_profile_params = CmdCtxBuilderSupportMulti::<CmdCtxTypesT>::profile_params_deserialize( &profile_dirs, profile_to_profile_params_provided, storage, &profile_params_type_reg, ) .await?; // flow_params_deserialize let profile_to_flow_params = CmdCtxBuilderSupportMulti::<CmdCtxTypesT>::flow_params_deserialize( &flow_dirs, profile_to_flow_params_provided, storage, &flow_params_type_reg, ) .await?; let interruptibility_state = interruptibility.into(); // Serialize params to `PeaceAppDir`. CmdCtxBuilderSupport::workspace_params_serialize( &workspace_params, storage, &workspace_params_file, ) .await?; // profile_params_serialize CmdCtxBuilderSupportMulti::<CmdCtxTypesT>::profile_params_serialize( &profile_to_profile_params, &profile_dirs, storage, ) .await?; // flow_params_serialize CmdCtxBuilderSupportMulti::<CmdCtxTypesT>::flow_params_serialize( &profile_to_flow_params, &flow_dirs, storage, ) .await?; // Track items in memory. let mut resources = peace_resource_rt::Resources::new(); CmdCtxBuilderSupport::workspace_params_insert(workspace_params.clone(), &mut resources); resources.insert(workspace_params_file); // `profile_params_insert` is not supported for multi-profile `CmdCtx`s. // `flow_params_insert` is not supported for multi-profile `CmdCtx`s. // Register each mapping function with the `MappingFnReg`. let mapping_fn_reg = CmdCtxBuilderSupport::mapping_fn_reg_setup::<CmdCtxTypesT::MappingFns>(); // Insert resources { let (app_name, workspace_dirs, storage) = (*workspace).clone().into_inner(); let (workspace_dir, peace_dir, peace_app_dir) = workspace_dirs.into_inner(); resources.insert(app_name); resources.insert(storage); resources.insert(workspace_dir); resources.insert(peace_dir); resources.insert(peace_app_dir); resources.insert(flow.flow_id().clone()); } let flow_id = flow.flow_id(); let item_graph = flow.graph(); let (params_specs_type_reg, states_type_reg) = CmdCtxBuilderSupport::params_and_states_type_reg(item_graph); let app_name = workspace.app_name(); let profile_to_params_specs = CmdCtxBuilderSupportMulti::<CmdCtxTypesT>::params_specs_load_merge_and_store( &flow_dirs, profile_to_params_specs_provided, &flow, storage, &params_specs_type_reg, app_name, ) .await?; let profile_to_states_current_stored = CmdCtxBuilderSupportMulti::<CmdCtxTypesT>::states_current_read( &flow_dirs, flow_id, storage, &states_type_reg, ) .await?; // Call each `Item`'s initialization function. let mut resources = CmdCtxBuilderSupport::item_graph_setup(item_graph, resources).await?; // Needs to come before `state_example`, because params resolution may need // some resources to be inserted for `state_example` to work. resources.merge(resources_override.into_inner()); let cmd_ctx_mpsf = CmdCtxMpsf { output, fields: CmdCtxMpsfFields { interruptibility_state, workspace, profiles, profile_dirs, profile_history_dirs, flow, flow_dirs, workspace_params_type_reg, workspace_params, profile_params_type_reg, profile_to_profile_params, flow_params_type_reg, profile_to_flow_params, profile_to_states_current_stored, params_specs_type_reg, profile_to_params_specs, mapping_fn_reg, states_type_reg, resources, }, }; Ok(cmd_ctx_mpsf) } } #[allow(non_camel_case_types)] impl<'ctx, CmdCtxTypesT, __interruptibility, __profile_filter_fn> IntoFuture for CmdCtxMpsfParamsBuilder< 'ctx, CmdCtxTypesT, ( (OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>,), __interruptibility, (OwnedOrRef<'ctx, Workspace>,), __profile_filter_fn, (OwnedOrRef<'ctx, Flow<CmdCtxTypesT::AppError>>,), (WorkspaceParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::WorkspaceParamsKey>,), ( BTreeMap< Profile, ProfileParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::ProfileParamsKey>, >, ), (BTreeMap<Profile, FlowParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::FlowParamsKey>>,), (BTreeMap<Profile, ParamsSpecs>,), (Resources<Empty>,), ), > where CmdCtxTypesT: CmdCtxTypes, CmdCtxMpsfParams<'ctx, CmdCtxTypesT>: for<'__typed_builder_lifetime_for_default> ::typed_builder::NextFieldDefault< ( &'__typed_builder_lifetime_for_default OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>, __interruptibility, ), Output = Interruptibility<'static>, >, CmdCtxMpsfParams<'ctx, CmdCtxTypesT>: for<'__typed_builder_lifetime_for_default> ::typed_builder::NextFieldDefault< ( &'__typed_builder_lifetime_for_default OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>, &'__typed_builder_lifetime_for_default Interruptibility<'static>, &'__typed_builder_lifetime_for_default OwnedOrRef<'ctx, Workspace>, __profile_filter_fn, ), Output = Option<ProfileFilterFn>, >, __interruptibility: 'ctx, __profile_filter_fn: 'ctx, { /// Future that returns the `CmdCtxMpsf`. /// /// This is boxed since [TAIT] is not yet available ([rust#63063]). /// /// [TAIT]: https://rust-lang.github.io/impl-trait-initiative/explainer/tait.html /// [rust#63063]: https://github.com/rust-lang/rust/issues/63063 type IntoFuture = LocalBoxFuture<'ctx, Result<CmdCtxMpsf<'ctx, CmdCtxTypesT>, CmdCtxTypesT::AppError>>; type Output = <Self::IntoFuture as std::future::Future>::Output; fn into_future(self) -> Self::IntoFuture { self.build().boxed_local() } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_ctx/src/cmd_ctx_npnf_params.rs
crate/cmd_ctx/src/cmd_ctx_npnf_params.rs
use std::future::IntoFuture; use futures::{future::LocalBoxFuture, FutureExt}; use interruptible::Interruptibility; use own::{OwnedOrMutRef, OwnedOrRef}; use peace_params::ParamsValue; use peace_resource_rt::internal::WorkspaceParamsFile; use peace_rt_model::{params::WorkspaceParamsOpt, Workspace, WorkspaceInitializer}; use typed_builder::TypedBuilder; use crate::{CmdCtxBuilderSupport, CmdCtxNpnf, CmdCtxNpnfFields, CmdCtxTypes}; /// Context for a command that only works with workspace parameters -- no /// profile / no flow. /// /// ```bash /// path/to/repo/.peace/envman /// |- πŸ“ workspace_params.yaml # βœ… can read or write `WorkspaceParams` /// | /// |- 🌏 .. # ❌ cannot read or write `Profile` information /// ``` /// /// ## Capabilities /// /// This kind of command can: /// /// * Read or write workspace parameters. /// /// This kind of command cannot: /// /// * Read or write profile parameters -- see [`CmdCtxSpnf`] or [`CmdCtxMpnf`]. /// * Read or write flow parameters or state -- see [`CmdCtxSpsf`] or /// [`CmdCtxMpsf`]. /// /// [`CmdCtxMpnf`]: crate::CmdCtxMpnf /// [`CmdCtxMpsf`]: crate::CmdCtxMpsf /// [`CmdCtxSpnf`]: crate::CmdCtxSpnf /// [`CmdCtxSpsf`]: crate::CmdCtxSpsf #[derive(Debug, TypedBuilder)] #[builder(build_method(vis="", name=build_partial))] pub struct CmdCtxNpnfParams<'ctx, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Output endpoint to return values / errors, and write progress /// information to. /// /// See [`OutputWrite`]. /// /// [`OutputWrite`]: peace_rt_model_core::OutputWrite #[builder(setter(prefix = "with_"))] pub output: OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>, /// The interrupt channel receiver if this `CmdExecution` is interruptible. #[builder(setter(prefix = "with_"), default = Interruptibility::NonInterruptible)] pub interruptibility: Interruptibility<'static>, /// Workspace that the `peace` tool runs in. #[builder(setter(prefix = "with_"))] pub workspace: OwnedOrRef<'ctx, Workspace>, /// Workspace params. // // NOTE: When updating this mutator, also update it for all the other `CmdCtx*Params` types. #[builder( setter(prefix = "with_"), via_mutators(init = WorkspaceParamsOpt::default()), mutators( /// Sets the value at the given workspace params key. /// /// # Parameters /// /// * `key`: The key to store the given value against. /// * `value`: The value to store at the given key. This is an /// `Option` so that you may remove a value if desired. /// /// # Type Parameters /// /// * `V`: The serializable type stored at the given key. pub fn with_workspace_param<V>( &mut self, key: CmdCtxTypesT::WorkspaceParamsKey, value: Option<V>, ) where V: ParamsValue, { let _ = self.workspace_params.insert(key, value); } ) )] #[builder(setter(prefix = "with_"))] pub workspace_params: WorkspaceParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::WorkspaceParamsKey>, } // Use one of the following to obtain the generated type signature: // // ```sh // cargo expand -p peace_cmd_ctx cmd_ctx_npnf_params // ``` // // Sublime text command: // // **LSP-rust-analyzer: Expand Macro Recursively** while the caret is on the // `TypedBuilder` derive. #[allow(non_camel_case_types)] impl<'ctx, CmdCtxTypesT, __interruptibility> CmdCtxNpnfParamsBuilder< 'ctx, CmdCtxTypesT, ( (OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>,), __interruptibility, (OwnedOrRef<'ctx, Workspace>,), (WorkspaceParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::WorkspaceParamsKey>,), ), > where CmdCtxTypesT: CmdCtxTypes, CmdCtxNpnfParams<'ctx, CmdCtxTypesT>: for<'__typed_builder_lifetime_for_default> ::typed_builder::NextFieldDefault< ( &'__typed_builder_lifetime_for_default OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>, __interruptibility, ), Output = Interruptibility<'static>, >, { pub async fn build(self) -> Result<CmdCtxNpnf<'ctx, CmdCtxTypesT>, CmdCtxTypesT::AppError> { let CmdCtxNpnfParams { output, interruptibility, workspace, workspace_params: workspace_params_provided, } = self.build_partial(); let workspace_params_type_reg = CmdCtxBuilderSupport::params_type_reg_initialize::<CmdCtxTypesT::WorkspaceParamsKey>(); let workspace_dirs = workspace.dirs(); let storage = workspace.storage(); let workspace_params_file = WorkspaceParamsFile::from(workspace_dirs.peace_app_dir()); let workspace_params = CmdCtxBuilderSupport::workspace_params_merge( storage, &workspace_params_type_reg, workspace_params_provided, &workspace_params_file, ) .await?; let dirs_to_create = [ AsRef::<std::path::Path>::as_ref(workspace_dirs.workspace_dir()), AsRef::<std::path::Path>::as_ref(workspace_dirs.peace_dir()), AsRef::<std::path::Path>::as_ref(workspace_dirs.peace_app_dir()), ]; // Create directories and write init parameters to storage. #[cfg(target_arch = "wasm32")] { WorkspaceInitializer::dirs_create(storage, dirs_to_create).await?; } #[cfg(not(target_arch = "wasm32"))] { WorkspaceInitializer::dirs_create(dirs_to_create).await?; let workspace_dir = workspace_dirs.workspace_dir(); std::env::set_current_dir(workspace_dir).map_err( #[cfg_attr(coverage_nightly, coverage(off))] |error| { peace_rt_model::Error::Native(peace_rt_model::NativeError::CurrentDirSet { workspace_dir: workspace_dir.clone(), error, }) }, )?; } let interruptibility_state = interruptibility.into(); // Serialize params to `PeaceAppDir`. CmdCtxBuilderSupport::workspace_params_serialize( &workspace_params, storage, &workspace_params_file, ) .await?; // No mapping function registration because there are no flow params to // deserialize. let cmd_ctx_npnf = CmdCtxNpnf { output, fields: CmdCtxNpnfFields { interruptibility_state, workspace, workspace_params_type_reg, workspace_params, }, }; Ok(cmd_ctx_npnf) } } #[allow(non_camel_case_types)] impl<'ctx, CmdCtxTypesT, __interruptibility> IntoFuture for CmdCtxNpnfParamsBuilder< 'ctx, CmdCtxTypesT, ( (OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>,), __interruptibility, (OwnedOrRef<'ctx, Workspace>,), (WorkspaceParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::WorkspaceParamsKey>,), ), > where CmdCtxTypesT: CmdCtxTypes, CmdCtxNpnfParams<'ctx, CmdCtxTypesT>: for<'__typed_builder_lifetime_for_default> ::typed_builder::NextFieldDefault< ( &'__typed_builder_lifetime_for_default OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>, __interruptibility, ), Output = Interruptibility<'static>, >, __interruptibility: 'ctx, { /// Future that returns the `CmdCtxNpnf`. /// /// This is boxed since [TAIT] is not yet available ([rust#63063]). /// /// [TAIT]: https://rust-lang.github.io/impl-trait-initiative/explainer/tait.html /// [rust#63063]: https://github.com/rust-lang/rust/issues/63063 type IntoFuture = LocalBoxFuture<'ctx, Result<CmdCtxNpnf<'ctx, CmdCtxTypesT>, CmdCtxTypesT::AppError>>; type Output = <Self::IntoFuture as std::future::Future>::Output; fn into_future(self) -> Self::IntoFuture { self.build().boxed_local() } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_ctx/src/cmd_ctx_spnf.rs
crate/cmd_ctx/src/cmd_ctx_spnf.rs
use interruptible::InterruptibilityState; use own::{OwnedOrMutRef, OwnedOrRef}; use peace_params::MappingFnReg; use peace_profile_model::Profile; use peace_resource_rt::paths::{ PeaceAppDir, PeaceDir, ProfileDir, ProfileHistoryDir, WorkspaceDir, }; use peace_rt_model::Workspace; use peace_rt_model_core::params::{ProfileParams, WorkspaceParams}; use type_reg::untagged::{BoxDt, TypeReg}; use crate::{CmdCtxSpnfParams, CmdCtxSpnfParamsBuilder, CmdCtxTypes}; /// A command that works with a single profile, not scoped to a flow. /// /// ```bash /// path/to/repo/.peace/envman /// |- πŸ“ workspace_params.yaml # βœ… can read or write `WorkspaceParams` /// | /// |- 🌏 internal_dev_a # βœ… can read `Profile` /// | |- πŸ“ profile_params.yaml # βœ… can read or write `ProfileParams` /// | | /// | |- 🌊 .. # ❌ cannot read or write Flow information /// | /// |- 🌏 .. # ❌ cannot read or write other `Profile` information /// ``` /// /// ## Capabilities /// /// This kind of command can: /// /// * Read or write workspace parameters. /// * Read or write a single profile's parameters. For multiple profiles, see /// [`CmdCtxMpnf`]. /// /// This kind of command cannot: /// /// * Read or write flow parameters or state -- see [`CmdCtxSpsf`] or /// [`CmdCtxMpsf`]. /// /// [`CmdCtxMpnf`]: crate::CmdCtxMpnf /// [`CmdCtxMpsf`]: crate::CmdCtxMpsf /// [`CmdCtxSpsf`]: crate::CmdCtxSpsf #[derive(Debug)] pub struct CmdCtxSpnf<'ctx, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Output endpoint to return values / errors, and write progress /// information to. /// /// See [`OutputWrite`]. /// /// [`OutputWrite`]: peace_rt_model_core::OutputWrite pub output: OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>, /// Inner fields without the `output`. /// /// # Design /// /// This is necessary so that the `output` can be separated from the fields /// during execution. pub fields: CmdCtxSpnfFields<'ctx, CmdCtxTypesT>, } /// Fields of [`CmdCtxSpnf`]. /// /// # Design /// /// This is necessary so that the `output` can be separated from the fields /// during execution. #[derive(Debug)] pub struct CmdCtxSpnfFields<'ctx, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Whether the `CmdExecution` is interruptible. /// /// If it is, this holds the interrupt channel receiver. pub interruptibility_state: InterruptibilityState<'static, 'static>, /// Workspace that the `peace` tool runs in. pub workspace: OwnedOrRef<'ctx, Workspace>, /// The profile this command operates on. pub profile: Profile, /// Profile directory that stores params and flows. pub profile_dir: ProfileDir, /// Directory to store profile execution history. pub profile_history_dir: ProfileHistoryDir, /// Type registry for [`WorkspaceParams`] deserialization. /// /// [`WorkspaceParams`]: peace_rt_model::params::WorkspaceParams pub workspace_params_type_reg: TypeReg<CmdCtxTypesT::WorkspaceParamsKey, BoxDt>, /// Workspace params. pub workspace_params: WorkspaceParams<CmdCtxTypesT::WorkspaceParamsKey>, /// Type registry for [`ProfileParams`] deserialization. /// /// [`ProfileParams`]: peace_rt_model::params::ProfileParams pub profile_params_type_reg: TypeReg<CmdCtxTypesT::ProfileParamsKey, BoxDt>, /// Profile params for the profile. pub profile_params: ProfileParams<CmdCtxTypesT::ProfileParamsKey>, /// Mapping function registry for each item's [`Params`]`::Spec`. /// /// This maps the [`MappingFnId`] stored in [`ParamsSpecsFile`] to the /// [`MappingFn`] logic. /// /// [`MappingFn`]: peace_params::MappingFn /// [`MappingFnId`]: peace_params::MappingFnId /// [`Params`]: peace_cfg::Item::Params /// [`ParamsSpecsFile`]: peace_resource_rt::paths::ParamsSpecsFile pub mapping_fn_reg: MappingFnReg, } impl<'ctx, CmdCtxTypesT> CmdCtxSpnf<'ctx, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Returns a [`CmdCtxSpnfParamsBuilder`] to construct this command context. pub fn builder<'ctx_local>() -> CmdCtxSpnfParamsBuilder<'ctx_local, CmdCtxTypesT> { CmdCtxSpnfParams::<'ctx_local, CmdCtxTypesT>::builder() } /// Returns a reference to the output. pub fn output(&self) -> &CmdCtxTypesT::Output { &self.output } /// Returns a mutable reference to the output. pub fn output_mut(&mut self) -> &mut CmdCtxTypesT::Output { &mut self.output } /// Returns a reference to the fields. pub fn fields(&self) -> &CmdCtxSpnfFields<'_, CmdCtxTypesT> { &self.fields } /// Returns a mutable reference to the fields. pub fn fields_mut(&mut self) -> &mut CmdCtxSpnfFields<'ctx, CmdCtxTypesT> { &mut self.fields } } impl<CmdCtxTypesT> CmdCtxSpnfFields<'_, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Returns the interruptibility capability. pub fn interruptibility_state(&mut self) -> InterruptibilityState<'_, '_> { self.interruptibility_state.reborrow() } /// Returns the workspace that the `peace` tool runs in. pub fn workspace(&self) -> &Workspace { &self.workspace } /// Returns a reference to the workspace directory. /// /// Convenience method for `cmd_ctx_Spsf.workspace.dirs().workspace_dir()`. pub fn workspace_dir(&self) -> &WorkspaceDir { self.workspace.dirs().workspace_dir() } /// Returns a reference to the `.peace` directory. /// /// Convenience method for `cmd_ctx_Spsf.workspace.dirs().peace_dir()`. pub fn peace_dir(&self) -> &PeaceDir { self.workspace.dirs().peace_dir() } /// Returns a reference to the `.peace/$app` directory. /// /// Convenience method for `cmd_ctx_Spsf.workspace.dirs().peace_app_dir()`. pub fn peace_app_dir(&self) -> &PeaceAppDir { self.workspace.dirs().peace_app_dir() } /// Returns a reference to the profile. pub fn profile(&self) -> &Profile { &self.profile } /// Returns a reference to the profile directory. pub fn profile_dir(&self) -> &ProfileDir { &self.profile_dir } /// Returns a reference to the profile history directory. pub fn profile_history_dir(&self) -> &ProfileHistoryDir { &self.profile_history_dir } /// Returns a reference to the workspace params type registry. pub fn workspace_params_type_reg(&self) -> &TypeReg<CmdCtxTypesT::WorkspaceParamsKey, BoxDt> { &self.workspace_params_type_reg } /// Returns a mutable reference to the workspace params type registry. pub fn workspace_params_type_reg_mut( &mut self, ) -> &mut TypeReg<CmdCtxTypesT::WorkspaceParamsKey, BoxDt> { &mut self.workspace_params_type_reg } /// Returns the workspace params. pub fn workspace_params(&self) -> &WorkspaceParams<CmdCtxTypesT::WorkspaceParamsKey> { &self.workspace_params } /// Returns the workspace params. pub fn workspace_params_mut( &mut self, ) -> &mut WorkspaceParams<CmdCtxTypesT::WorkspaceParamsKey> { &mut self.workspace_params } /// Returns a reference to the profile params type registry. pub fn profile_params_type_reg(&self) -> &TypeReg<CmdCtxTypesT::ProfileParamsKey, BoxDt> { &self.profile_params_type_reg } /// Returns a mutable reference to the profile params type registry. pub fn profile_params_type_reg_mut( &mut self, ) -> &mut TypeReg<CmdCtxTypesT::ProfileParamsKey, BoxDt> { &mut self.profile_params_type_reg } /// Returns the profile params. pub fn profile_params(&self) -> &ProfileParams<CmdCtxTypesT::ProfileParamsKey> { &self.profile_params } /// Returns the profile params. pub fn profile_params_mut(&mut self) -> &mut ProfileParams<CmdCtxTypesT::ProfileParamsKey> { &mut self.profile_params } /// Returns the mapping function registry for each item's /// [`Params`]`::Spec`. /// /// This maps the [`MappingFnId`] stored in [`ParamsSpecsFile`] to the /// [`MappingFn`] logic. /// /// [`MappingFn`]: peace_params::MappingFn /// [`MappingFnId`]: peace_params::MappingFnId /// [`Params`]: peace_cfg::Item::Params /// [`ParamsSpecsFile`]: peace_resource_rt::paths::ParamsSpecsFile pub fn mapping_fn_reg(&self) -> &MappingFnReg { &self.mapping_fn_reg } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_ctx/src/lib.rs
crate/cmd_ctx/src/lib.rs
#![cfg_attr(coverage_nightly, feature(coverage_attribute))] //! Information such as which profile or flow a command is run for for the Peace //! framework. // Re-exports pub use interruptible; pub use type_reg; pub use crate::{ cmd_ctx_mpnf::{CmdCtxMpnf, CmdCtxMpnfFields}, cmd_ctx_mpnf_params::{CmdCtxMpnfParams, CmdCtxMpnfParamsBuilder}, cmd_ctx_mpsf::{CmdCtxMpsf, CmdCtxMpsfFields}, cmd_ctx_mpsf_params::{CmdCtxMpsfParams, CmdCtxMpsfParamsBuilder}, cmd_ctx_npnf::{CmdCtxNpnf, CmdCtxNpnfFields}, cmd_ctx_npnf_params::{CmdCtxNpnfParams, CmdCtxNpnfParamsBuilder}, cmd_ctx_spnf::{CmdCtxSpnf, CmdCtxSpnfFields}, cmd_ctx_spnf_params::{CmdCtxSpnfParams, CmdCtxSpnfParamsBuilder}, cmd_ctx_spsf::{CmdCtxSpsf, CmdCtxSpsfFields}, cmd_ctx_spsf_params::{CmdCtxSpsfParams, CmdCtxSpsfParamsBuilder}, cmd_ctx_types::CmdCtxTypes, profile_filter_fn::ProfileFilterFn, profile_selection::ProfileSelection, }; pub(crate) use crate::{ cmd_ctx_builder_support::CmdCtxBuilderSupport, cmd_ctx_builder_support_multi::CmdCtxBuilderSupportMulti, }; mod cmd_ctx_builder_support; mod cmd_ctx_builder_support_multi; mod cmd_ctx_mpnf; mod cmd_ctx_mpnf_params; mod cmd_ctx_mpsf; mod cmd_ctx_mpsf_params; mod cmd_ctx_npnf; mod cmd_ctx_npnf_params; mod cmd_ctx_spnf; mod cmd_ctx_spnf_params; mod cmd_ctx_spsf; mod cmd_ctx_spsf_params; mod cmd_ctx_types; mod profile_filter_fn; mod profile_selection;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_ctx/src/cmd_ctx_types.rs
crate/cmd_ctx/src/cmd_ctx_types.rs
use std::fmt::Debug; use peace_params::{MappingFns, ParamsKey}; use peace_rt_model::output::OutputWrite; /// Trait so that a single type parameter can be used in `CmdCtx` and `Scopes`. /// /// The associated types linked to the concrete type can all be queried through /// this trait. pub trait CmdCtxTypes: Debug + Unpin + 'static { /// Error type of the automation software. type AppError: Debug + std::error::Error + From<peace_rt_model::Error> + From<<Self::Output as OutputWrite>::Error> + Send + Sync + Unpin + 'static; /// Output to write progress or outcome to. type Output: OutputWrite; /// Key type for parameters that are common for the workspace. /// /// If this is not needed, you may use the [`!` never type][never_type]. /// /// # Examples /// /// ```rust,ignore /// use serde::{Deserialize, Serialize}; /// /// #[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)] /// pub enum WorkspaceParam { /// UserEmail, /// Profile, /// } /// /// impl CmdCtxTypes for MyCmdCtxTypes { /// // .. /// type WorkspaceParamsKey = WorkspaceParam; /// } /// ``` /// /// [never_type]: https://doc.rust-lang.org/std/primitive.never.html type WorkspaceParamsKey: ParamsKey; /// Key type for parameters that differ between profiles. /// /// If this is not needed, you may use the [`!` never type][never_type]. /// /// # Examples /// /// Store an instance type that will be used as a parameter to an item that /// launches a virtual machine. /// /// ```rust,ignore /// use serde::{Deserialize, Serialize}; /// /// #[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)] /// pub enum ProfileParam { /// /// Default instance type to use across all flows within the same profile. /// InstanceType, /// } /// /// impl CmdCtxTypes for MyCmdCtxTypes { /// // .. /// type ProfileParamsKey = ProfileParam; /// } /// ``` /// /// [never_type]: https://doc.rust-lang.org/std/primitive.never.html type ProfileParamsKey: ParamsKey; /// Key type for parameters that differ between flows. /// /// If this is not needed, you may use the [`!` never type][never_type]. /// /// # Examples /// /// Store an instance type that will be used as a parameter to an item that /// launches a virtual machine. /// /// ```rust,ignore /// use serde::{Deserialize, Serialize}; /// /// #[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)] /// pub enum FlowParam { /// /// Instance type to use within this flow. /// /// /// /// Overrides `ProfileParam::InstanceType` if set. /// InstanceType, /// } /// /// impl CmdCtxTypes for MyCmdCtxTypes { /// // .. /// type FlowParamsKey = FlowParam; /// } /// ``` /// /// [never_type]: https://doc.rust-lang.org/std/primitive.never.html type FlowParamsKey: ParamsKey; /// Enum to give names to mapping functions, so that params specs and value /// specs can be serialized. /// /// Item parameters may be mapped from other items' state, and that logic /// exists as code. However, we want the ability to store (remember) those /// mappings across command executions. If a closure is held in the params /// specs and value specs, then they cannot be serialized. However, if we /// place that logic elsewhere (like in the `CmdCtxTypes` implementation), /// and have an intermediate enum to represent the mapping functions, we can /// serialize the enum instead of the closure. type MappingFns: MappingFns; }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false