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/examples/envman/src/items/peace_aws_s3_object/s3_object_params.rs | examples/envman/src/items/peace_aws_s3_object/s3_object_params.rs | use std::{
marker::PhantomData,
path::{Path, PathBuf},
};
use derivative::Derivative;
use peace::params::Params;
use serde::{Deserialize, Serialize};
/// S3Object item parameters.
///
/// The `Id` type parameter is needed for each S3 object params to be a
/// distinct type.
///
/// # Type Parameters
///
/// * `Id`: A zero-sized type used to distinguish different S3 object parameters
/// from each other.
#[derive(Derivative, Params, PartialEq, Eq, Deserialize, Serialize)]
#[derivative(Clone, Debug)]
#[serde(bound = "")]
pub struct S3ObjectParams<Id> {
/// Path to the file to upload.
file_path: PathBuf,
/// Name of the bucket to insert the S3 object into.
bucket_name: String,
/// Key for the S3 object.
object_key: String,
/// Marker for unique S3 object parameters type.
marker: PhantomData<Id>,
}
impl<Id> S3ObjectParams<Id> {
pub fn new(file_path: PathBuf, bucket_name: String, object_key: String) -> Self {
Self {
file_path,
bucket_name,
object_key,
marker: PhantomData,
}
}
/// Returns the path to the file to upload.
pub fn file_path(&self) -> &Path {
&self.file_path
}
/// Returns the bucket_name to put the S3 object into.
pub fn bucket_name(&self) -> &str {
self.bucket_name.as_ref()
}
/// Returns the key for the S3 object.
pub fn object_key(&self) -> &str {
self.object_key.as_ref()
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_s3_object/s3_object_state_diff.rs | examples/envman/src/items/peace_aws_s3_object/s3_object_state_diff.rs | use std::fmt;
use serde::{Deserialize, Serialize};
/// Diff between current (dest) and goal (src) state.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub enum S3ObjectStateDiff {
/// S3 object would be added.
Added,
/// S3 object would be removed.
Removed,
/// S3 bucket for the object renamed.
///
/// We could do an AWS `copy_object` then remove the current.
BucketNameModified {
/// Current bucket name.
bucket_name_current: String,
/// Goal bucket name.
bucket_name_goal: String,
},
/// S3 object renamed.
///
/// We could do an AWS `copy_object` then remove the current if the content
/// hasn't changed.
ObjectKeyModified {
/// Current object key.
object_key_current: String,
/// Goal object key.
object_key_goal: String,
},
/// S3 object content has changed.
ObjectContentModified {
/// Current MD5 hex string of object content.
content_md5_hexstr_current: Option<String>,
/// Goal MD5 hex string of object content.
content_md5_hexstr_goal: Option<String>,
},
/// S3 object exists and is up to date.
InSyncExists,
/// S3 object does not exist, which is goal.
InSyncDoesNotExist,
}
impl fmt::Display for S3ObjectStateDiff {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
S3ObjectStateDiff::Added => {
write!(f, "will be created.")
}
S3ObjectStateDiff::Removed => {
write!(f, "will be removed.")
}
S3ObjectStateDiff::BucketNameModified {
bucket_name_current,
bucket_name_goal,
} => write!(
f,
"bucket name has changed from {bucket_name_current} to {bucket_name_goal}"
),
S3ObjectStateDiff::ObjectKeyModified {
object_key_current,
object_key_goal,
} => write!(
f,
"object key has changed from {object_key_current} to {object_key_goal}"
),
S3ObjectStateDiff::ObjectContentModified {
content_md5_hexstr_current,
content_md5_hexstr_goal,
} => {
let content_md5_hexstr_current =
content_md5_hexstr_current.as_deref().unwrap_or("<none>");
let content_md5_hexstr_goal =
content_md5_hexstr_goal.as_deref().unwrap_or("<none>");
write!(
f,
"object content has changed from {content_md5_hexstr_current} to {content_md5_hexstr_goal}"
)
}
S3ObjectStateDiff::InSyncExists => {
write!(f, "exists and is up to date.")
}
S3ObjectStateDiff::InSyncDoesNotExist => {
write!(f, "does not exist as intended.")
}
}
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_instance_profile/instance_profile_error.rs | examples/envman/src/items/peace_aws_instance_profile/instance_profile_error.rs | use aws_sdk_iam::{
error::SdkError,
operation::{
add_role_to_instance_profile::AddRoleToInstanceProfileError,
create_instance_profile::CreateInstanceProfileError,
delete_instance_profile::DeleteInstanceProfileError,
get_instance_profile::GetInstanceProfileError,
remove_role_from_instance_profile::RemoveRoleFromInstanceProfileError,
},
};
#[cfg(feature = "error_reporting")]
use peace::miette::{self, SourceSpan};
/// Error while managing instance profile state.
#[cfg_attr(feature = "error_reporting", derive(peace::miette::Diagnostic))]
#[derive(Debug, thiserror::Error)]
pub enum InstanceProfileError {
/// Instance profile name or path was attempted to be modified.
#[error("Instance profile name or path modification is not supported.")]
NameOrPathModificationNotSupported {
/// Whether the name has been changed.
name_diff: Option<(String, String)>,
/// Whether the path has been changed.
path_diff: Option<(String, String)>,
},
/// Failed to decode URL-encoded instance profile document.
#[error("Failed to decode URL-encoded instance_profile document.")]
InstanceProfileDocumentNonUtf8 {
/// InstanceProfile friendly name.
instance_profile_name: String,
/// InstanceProfile path.
instance_profile_path: String,
/// The URL encoded document from the AWS `get_instance_profile_version`
/// call.
url_encoded_document: String,
/// Underlying error.
#[source]
error: std::string::FromUtf8Error,
},
/// Failed to create instance profile.
#[error("Failed to create instance profile.")]
#[cfg_attr(
feature = "error_reporting",
diagnostic(help("Make sure you are connected to the internet and try again."))
)]
InstanceProfileCreateError {
/// InstanceProfile friendly name.
instance_profile_name: String,
/// InstanceProfile path.
instance_profile_path: String,
/// Error description from AWS error.
#[cfg(feature = "error_reporting")]
#[source_code]
aws_desc: String,
/// Span of the description to highlight.
#[cfg(feature = "error_reporting")]
#[label]
aws_desc_span: SourceSpan,
/// Underlying error.
#[source]
error: Box<SdkError<CreateInstanceProfileError>>,
},
/// Failed to discover instance profile.
#[error("Failed to discover instance profile.")]
#[cfg_attr(
feature = "error_reporting",
diagnostic(help("Make sure you are connected to the internet and try again."))
)]
InstanceProfileGetError {
/// Expected instance profile friendly name.
instance_profile_name: String,
/// InstanceProfile path.
instance_profile_path: String,
/// Error description from AWS error.
#[cfg(feature = "error_reporting")]
#[source_code]
aws_desc: String,
/// Span of the description to highlight.
#[cfg(feature = "error_reporting")]
#[label]
aws_desc_span: SourceSpan,
/// Underlying error.
#[source]
error: Box<SdkError<GetInstanceProfileError>>,
},
/// InstanceProfile existed when listing policies, but did not exist when
/// retrieving details.
#[error("InstanceProfile details failed to be retrieved.")]
InstanceProfileNotFoundAfterList {
/// Expected instance profile friendly name.
instance_profile_name: String,
/// InstanceProfile path.
instance_profile_path: String,
/// InstanceProfile stable ID.
instance_profile_id: String,
/// InstanceProfile ARN.
instance_profile_arn: String,
},
/// Failed to delete instance profile.
#[error("Failed to delete instance profile.")]
#[cfg_attr(
feature = "error_reporting",
diagnostic(help("Make sure you are connected to the internet and try again."))
)]
InstanceProfileDeleteError {
/// InstanceProfile friendly name.
instance_profile_name: String,
/// InstanceProfile path.
instance_profile_path: String,
/// InstanceProfile stable ID.
instance_profile_id: String,
/// InstanceProfile ARN.
instance_profile_arn: String,
/// Error description from AWS error.
#[cfg(feature = "error_reporting")]
#[source_code]
aws_desc: String,
/// Span of the description to highlight.
#[cfg(feature = "error_reporting")]
#[label]
aws_desc_span: SourceSpan,
/// Underlying error.
#[source]
error: Box<SdkError<DeleteInstanceProfileError>>,
},
/// Failed to add role to instance profile.
#[error("Failed to add role to instance profile: {role_name}.")]
#[cfg_attr(
feature = "error_reporting",
diagnostic(help("Make sure you are connected to the internet and try again."))
)]
InstanceProfileRoleAddError {
/// InstanceProfile friendly name.
instance_profile_name: String,
/// InstanceProfile path.
instance_profile_path: String,
/// Role friendly name.
role_name: String,
/// Error description from AWS error.
#[cfg(feature = "error_reporting")]
#[source_code]
aws_desc: String,
/// Span of the description to highlight.
#[cfg(feature = "error_reporting")]
#[label]
aws_desc_span: SourceSpan,
/// Underlying error.
#[source]
error: Box<SdkError<AddRoleToInstanceProfileError>>,
},
/// Failed to remove role from instance profile.
#[error("Failed to remove role from instance profile.")]
#[cfg_attr(
feature = "error_reporting",
diagnostic(help("Make sure you are connected to the internet and try again."))
)]
InstanceProfileRoleRemoveError {
/// InstanceProfile friendly name.
instance_profile_name: String,
/// InstanceProfile path.
instance_profile_path: String,
/// Error description from AWS error.
#[cfg(feature = "error_reporting")]
#[source_code]
aws_desc: String,
/// Span of the description to highlight.
#[cfg(feature = "error_reporting")]
#[label]
aws_desc_span: SourceSpan,
/// Underlying error.
#[source]
error: Box<SdkError<RemoveRoleFromInstanceProfileError>>,
},
/// User changed the instance profile name or path, but AWS does not support
/// changing this.
#[error("InstanceProfile name or path cannot be modified, as it is not supported by AWS.")]
InstanceProfileModificationNotSupported {
/// Name diff.
name_diff: Option<(String, String)>,
/// Path diff.
path_diff: Option<(String, String)>,
},
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_instance_profile/instance_profile_state_goal_fn.rs | examples/envman/src/items/peace_aws_instance_profile/instance_profile_state_goal_fn.rs | use std::marker::PhantomData;
use peace::{
cfg::{state::Generated, FnCtx},
params::Params,
};
use crate::items::peace_aws_instance_profile::{
InstanceProfileData, InstanceProfileError, InstanceProfileParams, InstanceProfileState,
};
/// Reads the goal state of the instance profile state.
#[derive(Debug)]
pub struct InstanceProfileStateGoalFn<Id>(PhantomData<Id>);
impl<Id> InstanceProfileStateGoalFn<Id>
where
Id: Send + Sync + 'static,
{
pub async fn try_state_goal(
_fn_ctx: FnCtx<'_>,
params_partial: &<InstanceProfileParams<Id> as Params>::Partial,
_data: InstanceProfileData<'_, Id>,
) -> Result<Option<InstanceProfileState>, InstanceProfileError> {
let name = params_partial.name();
let path = params_partial.path();
let role_associate = params_partial.role_associate();
if let Some(((name, path), role_associated)) = name.zip(path).zip(role_associate) {
Self::state_goal_internal(name.to_string(), path.to_string(), *role_associated)
.await
.map(Some)
} else {
Ok(None)
}
}
pub async fn state_goal(
_fn_ctx: FnCtx<'_>,
params: &InstanceProfileParams<Id>,
_data: InstanceProfileData<'_, Id>,
) -> Result<InstanceProfileState, InstanceProfileError> {
let name = params.name().to_string();
let path = params.path().to_string();
let role_associated = params.role_associate();
Self::state_goal_internal(name, path, role_associated).await
}
async fn state_goal_internal(
name: String,
path: String,
role_associated: bool,
) -> Result<InstanceProfileState, InstanceProfileError> {
let instance_profile_id_and_arn = Generated::Tbd;
Ok(InstanceProfileState::Some {
name,
path,
instance_profile_id_and_arn,
role_associated,
})
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_instance_profile/instance_profile_state.rs | examples/envman/src/items/peace_aws_instance_profile/instance_profile_state.rs | use std::fmt;
use peace::cfg::state::Generated;
use serde::{Deserialize, Serialize};
use crate::items::peace_aws_instance_profile::model::InstanceProfileIdAndArn;
#[cfg(feature = "output_progress")]
use peace::item_interaction_model::ItemLocationState;
/// Instance profile state.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum InstanceProfileState {
/// Instance profile does not exist.
None,
/// Instance profile exists.
Some {
/// Instance profile name.
///
/// Alphanumeric characters and `_+=,.@-` are allowed.
///
/// TODO: newtype + proc macro.
name: String,
/// String that begins and ends with a forward slash.
///
/// Defaults to `/`.
///
/// e.g. `/demo/`
#[serde(default = "path_default")]
path: String,
/// The stable and unique IDs identifying the instance profile.
instance_profile_id_and_arn: Generated<InstanceProfileIdAndArn>,
/// Whether the role has been associated with the instance profile.
role_associated: bool,
},
}
fn path_default() -> String {
String::from("/")
}
impl fmt::Display for InstanceProfileState {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::None => "does not exist".fmt(f),
Self::Some {
name,
path,
instance_profile_id_and_arn,
role_associated,
} => {
match instance_profile_id_and_arn {
Generated::Tbd => write!(f, "`{path}{name}` should exist ")?,
Generated::Value(_instance_profile_id_and_arn) => {
// https://console.aws.amazon.com/iamv2/home#/roles/details/demo
write!(
f,
"exists at https://console.aws.amazon.com/iamv2/home#/roles/details/{name} "
)?;
}
}
if *role_associated {
write!(f, "associated with same named role")?;
} else {
write!(f, "but role not associated")?;
}
Ok(())
}
}
}
}
#[cfg(feature = "output_progress")]
impl<'state> From<&'state InstanceProfileState> for ItemLocationState {
fn from(instance_profile_state: &'state InstanceProfileState) -> ItemLocationState {
match instance_profile_state {
InstanceProfileState::Some { .. } => ItemLocationState::Exists,
InstanceProfileState::None => ItemLocationState::NotExists,
}
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_instance_profile/instance_profile_state_diff_fn.rs | examples/envman/src/items/peace_aws_instance_profile/instance_profile_state_diff_fn.rs | use crate::items::peace_aws_instance_profile::{
InstanceProfileError, InstanceProfileState, InstanceProfileStateDiff,
};
/// Tar extraction status diff function.
#[derive(Debug)]
pub struct InstanceProfileStateDiffFn;
impl InstanceProfileStateDiffFn {
pub async fn state_diff(
state_current: &InstanceProfileState,
state_goal: &InstanceProfileState,
) -> Result<InstanceProfileStateDiff, InstanceProfileError> {
let diff = match (state_current, state_goal) {
(InstanceProfileState::None, InstanceProfileState::None) => {
InstanceProfileStateDiff::InSyncDoesNotExist
}
(InstanceProfileState::None, InstanceProfileState::Some { .. }) => {
InstanceProfileStateDiff::Added
}
(InstanceProfileState::Some { .. }, InstanceProfileState::None) => {
InstanceProfileStateDiff::Removed
}
(
InstanceProfileState::Some {
name: name_current,
path: path_current,
instance_profile_id_and_arn: _,
role_associated: role_associated_current,
},
InstanceProfileState::Some {
name: name_goal,
path: path_goal,
instance_profile_id_and_arn: _,
role_associated: role_associated_goal,
},
) => {
let role_associated_current = *role_associated_current;
let role_associated_goal = *role_associated_goal;
let name_diff = if name_current != name_goal {
Some((name_current.clone(), name_goal.clone()))
} else {
None
};
let path_diff = if path_current != path_goal {
Some((path_current.clone(), path_goal.clone()))
} else {
None
};
if name_diff.is_none() && path_diff.is_none() {
if role_associated_current == role_associated_goal {
InstanceProfileStateDiff::InSyncExists
} else {
InstanceProfileStateDiff::RoleAssociatedModified {
role_associated_current,
role_associated_goal,
}
}
} else {
InstanceProfileStateDiff::NameOrPathModified {
name_diff,
path_diff,
}
}
}
};
Ok(diff)
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_instance_profile/instance_profile_state_diff.rs | examples/envman/src/items/peace_aws_instance_profile/instance_profile_state_diff.rs | use std::fmt;
use serde::{Deserialize, Serialize};
/// Diff between current (dest) and goal (src) state.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub enum InstanceProfileStateDiff {
/// InstanceProfile would be added.
Added,
/// InstanceProfile would be removed.
Removed,
/// InstanceProfile would be replaced.
///
/// AWS' SDK doesn't support modifying a instance profile's name or path.
NameOrPathModified {
/// Whether the name has been changed.
name_diff: Option<(String, String)>,
/// Whether the path has been changed.
path_diff: Option<(String, String)>,
},
/// The instance profile role association has been modified.
RoleAssociatedModified {
/// Current instance profile role association.
role_associated_current: bool,
/// Goal instance profile role association.
role_associated_goal: bool,
},
/// InstanceProfile exists and is up to date.
InSyncExists,
/// InstanceProfile does not exist, which is goal.
InSyncDoesNotExist,
}
impl fmt::Display for InstanceProfileStateDiff {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
InstanceProfileStateDiff::Added => {
write!(f, "will be created.")
}
InstanceProfileStateDiff::Removed => {
write!(f, "will be removed.")
}
InstanceProfileStateDiff::RoleAssociatedModified {
role_associated_current,
role_associated_goal,
} => {
if !role_associated_current && *role_associated_goal {
write!(f, "role will be disassociated from instance profile.")
} else {
write!(f, "role will be associated with instance profile.")
}
}
InstanceProfileStateDiff::NameOrPathModified {
name_diff,
path_diff,
} => match (name_diff, path_diff) {
(None, None) => {
unreachable!(
"Modified is only valid when either name or path has changed.\n\
This is a bug."
)
}
(None, Some((path_current, path_goal))) => {
write!(f, "path changed from {path_current} to {path_goal}")
}
(Some((name_current, name_goal)), None) => {
write!(f, "name changed from {name_current} to {name_goal}")
}
(Some((name_current, name_goal)), Some((path_current, path_goal))) => write!(
f,
"name and path changed from {name_current}:{path_current} to {name_goal}:{path_goal}"
),
},
InstanceProfileStateDiff::InSyncExists => {
write!(f, "exists and is up to date.")
}
InstanceProfileStateDiff::InSyncDoesNotExist => {
write!(f, "does not exist as intended.")
}
}
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_instance_profile/instance_profile_state_current_fn.rs | examples/envman/src/items/peace_aws_instance_profile/instance_profile_state_current_fn.rs | use std::marker::PhantomData;
use aws_sdk_iam::{error::SdkError, operation::get_instance_profile::GetInstanceProfileError};
use peace::{
cfg::{state::Generated, FnCtx},
params::Params,
};
use crate::items::peace_aws_instance_profile::{
model::InstanceProfileIdAndArn, InstanceProfileData, InstanceProfileError,
InstanceProfileParams, InstanceProfileState,
};
#[cfg(feature = "output_progress")]
use peace::progress_model::ProgressMsgUpdate;
/// Reads the current state of the instance profile state.
#[derive(Debug)]
pub struct InstanceProfileStateCurrentFn<Id>(PhantomData<Id>);
impl<Id> InstanceProfileStateCurrentFn<Id>
where
Id: Send + Sync,
{
pub async fn try_state_current(
fn_ctx: FnCtx<'_>,
params_partial: &<InstanceProfileParams<Id> as Params>::Partial,
data: InstanceProfileData<'_, Id>,
) -> Result<Option<InstanceProfileState>, InstanceProfileError> {
if let Ok(params) = params_partial.try_into() {
Self::state_current(fn_ctx, ¶ms, data).await.map(Some)
} else {
Ok(None)
}
}
pub async fn state_current(
fn_ctx: FnCtx<'_>,
params: &InstanceProfileParams<Id>,
data: InstanceProfileData<'_, Id>,
) -> Result<InstanceProfileState, InstanceProfileError> {
let name = params.name();
let path = params.path();
Self::state_current_internal(fn_ctx, data, name, path).await
}
async fn state_current_internal(
fn_ctx: FnCtx<'_>,
data: InstanceProfileData<'_, Id>,
name: &str,
path: &str,
) -> Result<InstanceProfileState, InstanceProfileError> {
let client = data.client();
#[cfg(not(feature = "output_progress"))]
let _fn_ctx = fn_ctx;
#[cfg(feature = "output_progress")]
let progress_sender = &fn_ctx.progress_sender;
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from(
"fetching instance profile",
)));
let get_instance_profile_result = client
.get_instance_profile()
.instance_profile_name(name)
.send()
.await;
let instance_profile_opt = match get_instance_profile_result {
Ok(get_instance_profile_output) => {
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from(
"instance profile fetched",
)));
let instance_profile = get_instance_profile_output.instance_profile().expect(
"Expected instance profile to be some when get_instance_profile is successful.",
);
let instance_profile_name = instance_profile.instance_profile_name().to_string();
let instance_profile_path = instance_profile.path().to_string();
let instance_profile_id = instance_profile.instance_profile_id().to_string();
let instance_profile_arn = instance_profile.arn().to_string();
let instance_profile_id_and_arn =
InstanceProfileIdAndArn::new(instance_profile_id, instance_profile_arn);
let role_associated = !instance_profile.roles().is_empty();
Some((
instance_profile_name,
instance_profile_path,
instance_profile_id_and_arn,
role_associated,
))
}
Err(error) => {
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from(
"instance profile not fetched",
)));
#[cfg(feature = "error_reporting")]
let (aws_desc, aws_desc_span) = crate::items::aws_error_desc!(&error);
match &error {
SdkError::ServiceError(service_error) => match service_error.err() {
GetInstanceProfileError::NoSuchEntityException(_) => None,
_ => {
let error = Box::new(error);
return Err(InstanceProfileError::InstanceProfileGetError {
instance_profile_name: name.to_string(),
instance_profile_path: path.to_string(),
#[cfg(feature = "error_reporting")]
aws_desc,
#[cfg(feature = "error_reporting")]
aws_desc_span,
error,
});
}
},
_ => {
let error = Box::new(error);
return Err(InstanceProfileError::InstanceProfileGetError {
instance_profile_name: name.to_string(),
instance_profile_path: path.to_string(),
#[cfg(feature = "error_reporting")]
aws_desc,
#[cfg(feature = "error_reporting")]
aws_desc_span,
error,
});
}
}
}
};
if let Some((
instance_profile_name,
instance_profile_path,
instance_profile_id_and_arn,
role_associated,
)) = instance_profile_opt
{
let state_current = InstanceProfileState::Some {
name: instance_profile_name,
path: instance_profile_path,
instance_profile_id_and_arn: Generated::Value(instance_profile_id_and_arn),
role_associated,
};
Ok(state_current)
} else {
Ok(InstanceProfileState::None)
}
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_instance_profile/instance_profile_data.rs | examples/envman/src/items/peace_aws_instance_profile/instance_profile_data.rs | use std::marker::PhantomData;
use peace::data::{accessors::R, Data};
/// Data used to manage instance profile state.
///
/// # Type Parameters
///
/// * `Id`: A zero-sized type used to distinguish different instance profile
/// parameters from each other.
#[derive(Data, Debug)]
pub struct InstanceProfileData<'exec, Id>
where
Id: Send + Sync + 'static,
{
/// IAM client to communicate with AWS.
client: R<'exec, aws_sdk_iam::Client>,
/// Marker.
marker: PhantomData<Id>,
}
impl<'exec, Id> InstanceProfileData<'exec, Id>
where
Id: Send + Sync + 'static,
{
pub fn client(&self) -> &R<'exec, aws_sdk_iam::Client> {
&self.client
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_instance_profile/instance_profile_apply_fns.rs | examples/envman/src/items/peace_aws_instance_profile/instance_profile_apply_fns.rs | use std::marker::PhantomData;
use peace::cfg::{state::Generated, ApplyCheck, FnCtx};
#[cfg(feature = "output_progress")]
use peace::progress_model::{ProgressLimit, ProgressMsgUpdate, ProgressSender};
use crate::items::peace_aws_instance_profile::{
model::InstanceProfileIdAndArn, InstanceProfileData, InstanceProfileError,
InstanceProfileParams, InstanceProfileState, InstanceProfileStateDiff,
};
/// ApplyFns for the instance profile state.
#[derive(Debug)]
pub struct InstanceProfileApplyFns<Id>(PhantomData<Id>);
impl<Id> InstanceProfileApplyFns<Id> {
async fn role_associate(
#[cfg(feature = "output_progress")] progress_sender: &ProgressSender<'_>,
client: &aws_sdk_iam::Client,
name: &str,
path: &str,
) -> Result<(), InstanceProfileError> {
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from("associating role")));
let _instance_profile_role_add_output = client
.add_role_to_instance_profile()
.role_name(name)
.instance_profile_name(name)
.send()
.await
.map_err(|error| {
let instance_profile_name = name.to_string();
let instance_profile_path = path.to_string();
let role_name = name.to_string();
#[cfg(feature = "error_reporting")]
let (aws_desc, aws_desc_span) = crate::items::aws_error_desc!(&error);
let error = Box::new(error);
InstanceProfileError::InstanceProfileRoleAddError {
instance_profile_name,
instance_profile_path,
role_name,
#[cfg(feature = "error_reporting")]
aws_desc,
#[cfg(feature = "error_reporting")]
aws_desc_span,
error,
}
})?;
#[cfg(feature = "output_progress")]
progress_sender.inc(1, ProgressMsgUpdate::Set(String::from("role associated")));
Ok(())
}
pub(crate) async fn role_disassociate(
#[cfg(feature = "output_progress")] progress_sender: &ProgressSender<'_>,
client: &aws_sdk_iam::Client,
name: &str,
path: &str,
) -> Result<(), InstanceProfileError> {
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from("disassociating role")));
client
.remove_role_from_instance_profile()
.instance_profile_name(name)
.role_name(name)
.send()
.await
.map_err(|error| {
let instance_profile_name = name.to_string();
let instance_profile_path = path.to_string();
#[cfg(feature = "error_reporting")]
let (aws_desc, aws_desc_span) = crate::items::aws_error_desc!(&error);
let error = Box::new(error);
InstanceProfileError::InstanceProfileRoleRemoveError {
instance_profile_name,
instance_profile_path,
#[cfg(feature = "error_reporting")]
aws_desc,
#[cfg(feature = "error_reporting")]
aws_desc_span,
error,
}
})?;
#[cfg(feature = "output_progress")]
progress_sender.inc(
1,
ProgressMsgUpdate::Set(String::from("role disassociated")),
);
Ok(())
}
}
impl<Id> InstanceProfileApplyFns<Id>
where
Id: Send + Sync + 'static,
{
pub async fn apply_check(
_params: &InstanceProfileParams<Id>,
_data: InstanceProfileData<'_, Id>,
state_current: &InstanceProfileState,
_state_goal: &InstanceProfileState,
diff: &InstanceProfileStateDiff,
) -> Result<ApplyCheck, InstanceProfileError> {
match diff {
InstanceProfileStateDiff::Added
| InstanceProfileStateDiff::RoleAssociatedModified { .. } => {
let apply_check = {
#[cfg(not(feature = "output_progress"))]
{
ApplyCheck::ExecRequired
}
#[cfg(feature = "output_progress")]
{
// Create instance profile, associate role
let progress_limit = ProgressLimit::Steps(2);
ApplyCheck::ExecRequired { progress_limit }
}
};
Ok(apply_check)
}
InstanceProfileStateDiff::Removed => {
let apply_check = match state_current {
InstanceProfileState::None => ApplyCheck::ExecNotRequired,
InstanceProfileState::Some {
name: _,
path: _,
instance_profile_id_and_arn,
role_associated,
} => {
let mut steps_required = 0;
if *role_associated {
steps_required += 1;
}
if matches!(instance_profile_id_and_arn, Generated::Value(_)) {
steps_required += 1;
}
if steps_required == 0 {
ApplyCheck::ExecNotRequired
} else {
#[cfg(not(feature = "output_progress"))]
{
ApplyCheck::ExecRequired
}
#[cfg(feature = "output_progress")]
{
let progress_limit = ProgressLimit::Steps(steps_required);
ApplyCheck::ExecRequired { progress_limit }
}
}
}
};
Ok(apply_check)
}
InstanceProfileStateDiff::NameOrPathModified {
name_diff,
path_diff,
} => Err(
InstanceProfileError::InstanceProfileModificationNotSupported {
name_diff: name_diff.clone(),
path_diff: path_diff.clone(),
},
),
InstanceProfileStateDiff::InSyncExists
| InstanceProfileStateDiff::InSyncDoesNotExist => Ok(ApplyCheck::ExecNotRequired),
}
}
pub async fn apply_dry(
_fn_ctx: FnCtx<'_>,
_params: &InstanceProfileParams<Id>,
_data: InstanceProfileData<'_, Id>,
_state_current: &InstanceProfileState,
state_goal: &InstanceProfileState,
_diff: &InstanceProfileStateDiff,
) -> Result<InstanceProfileState, InstanceProfileError> {
Ok(state_goal.clone())
}
pub async fn apply(
#[cfg(not(feature = "output_progress"))] _fn_ctx: FnCtx<'_>,
#[cfg(feature = "output_progress")] fn_ctx: FnCtx<'_>,
_params: &InstanceProfileParams<Id>,
data: InstanceProfileData<'_, Id>,
state_current: &InstanceProfileState,
state_goal: &InstanceProfileState,
diff: &InstanceProfileStateDiff,
) -> Result<InstanceProfileState, InstanceProfileError> {
#[cfg(feature = "output_progress")]
let progress_sender = &fn_ctx.progress_sender;
match diff {
InstanceProfileStateDiff::Added => match state_goal {
InstanceProfileState::None => {
panic!("`InstanceProfileApplyFns::exec` called with state_goal being None.");
}
InstanceProfileState::Some {
name,
path,
instance_profile_id_and_arn: _,
role_associated: _,
} => {
let client = data.client();
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from(
"creating instance profile",
)));
let create_instance_profile_output = client
.create_instance_profile()
.instance_profile_name(name)
.path(path)
.send()
.await
.map_err(|error| {
let instance_profile_name = name.to_string();
let instance_profile_path = path.to_string();
#[cfg(feature = "error_reporting")]
let (aws_desc, aws_desc_span) = crate::items::aws_error_desc!(&error);
let error = Box::new(error);
InstanceProfileError::InstanceProfileCreateError {
instance_profile_name,
instance_profile_path,
#[cfg(feature = "error_reporting")]
aws_desc,
#[cfg(feature = "error_reporting")]
aws_desc_span,
error,
}
})?;
#[cfg(feature = "output_progress")]
progress_sender.inc(
1,
ProgressMsgUpdate::Set(String::from("instance profile created")),
);
let instance_profile = create_instance_profile_output
.instance_profile()
.expect("Expected instance_profile to be Some when create_instance_profile is successful.");
let instance_profile_id = instance_profile.instance_profile_id().to_string();
let instance_profile_arn = instance_profile.arn().to_string();
let instance_profile_id_and_arn =
InstanceProfileIdAndArn::new(instance_profile_id, instance_profile_arn);
Self::role_associate(
#[cfg(feature = "output_progress")]
progress_sender,
client,
name,
path,
)
.await?;
let state_applied = InstanceProfileState::Some {
name: name.to_string(),
path: path.clone(),
instance_profile_id_and_arn: Generated::Value(instance_profile_id_and_arn),
role_associated: true,
};
Ok(state_applied)
}
},
InstanceProfileStateDiff::Removed => match state_current {
InstanceProfileState::None => {
unreachable!("Instance profile must be Some when it is to be removed.")
}
InstanceProfileState::Some {
name,
path,
instance_profile_id_and_arn,
role_associated,
} => {
let client = data.client();
if *role_associated {
Self::role_disassociate(
#[cfg(feature = "output_progress")]
progress_sender,
client,
name,
path,
)
.await?;
}
if let Generated::Value(instance_profile_id_and_arn) =
instance_profile_id_and_arn
{
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from(
"deleting instance profile",
)));
client
.delete_instance_profile()
.instance_profile_name(name)
.send()
.await
.map_err(|error| {
let instance_profile_name = name.to_string();
let instance_profile_path = path.to_string();
let instance_profile_id =
instance_profile_id_and_arn.id().to_string();
let instance_profile_arn =
instance_profile_id_and_arn.arn().to_string();
#[cfg(feature = "error_reporting")]
let (aws_desc, aws_desc_span) =
crate::items::aws_error_desc!(&error);
let error = Box::new(error);
InstanceProfileError::InstanceProfileDeleteError {
instance_profile_name,
instance_profile_path,
instance_profile_id,
instance_profile_arn,
#[cfg(feature = "error_reporting")]
aws_desc,
#[cfg(feature = "error_reporting")]
aws_desc_span,
error,
}
})?;
#[cfg(feature = "output_progress")]
progress_sender.inc(
1,
ProgressMsgUpdate::Set(String::from("instance profile deleted")),
);
}
let state_applied = state_goal.clone();
Ok(state_applied)
}
},
InstanceProfileStateDiff::InSyncExists
| InstanceProfileStateDiff::InSyncDoesNotExist => {
unreachable!(
"`InstanceProfileApplyFns::exec` should never be called when state is in sync."
);
}
InstanceProfileStateDiff::NameOrPathModified {
name_diff,
path_diff,
} => Err(InstanceProfileError::NameOrPathModificationNotSupported {
name_diff: name_diff.clone(),
path_diff: path_diff.clone(),
}),
InstanceProfileStateDiff::RoleAssociatedModified {
role_associated_current,
role_associated_goal: _,
} => {
let (name, path) = match state_goal {
InstanceProfileState::None => {
panic!(
"`InstanceProfileApplyFns::exec` called with state_goal being None."
);
}
InstanceProfileState::Some {
name,
path,
instance_profile_id_and_arn: _,
role_associated: _,
} => (name, path),
};
let client = data.client();
if *role_associated_current {
// Remove the association.
Self::role_disassociate(
#[cfg(feature = "output_progress")]
progress_sender,
client,
name,
path,
)
.await?;
} else {
// Associate the role.
Self::role_associate(
#[cfg(feature = "output_progress")]
progress_sender,
client,
name,
path,
)
.await?;
}
let state_applied = state_goal.clone();
Ok(state_applied)
}
}
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_instance_profile/instance_profile_item.rs | examples/envman/src/items/peace_aws_instance_profile/instance_profile_item.rs | use std::marker::PhantomData;
use aws_config::BehaviorVersion;
use peace::{
cfg::{async_trait, ApplyCheck, FnCtx, Item},
item_model::ItemId,
params::Params,
resource_rt::{resources::ts::Empty, Resources},
};
use crate::items::peace_aws_instance_profile::{
InstanceProfileApplyFns, InstanceProfileData, InstanceProfileError, InstanceProfileParams,
InstanceProfileState, InstanceProfileStateCurrentFn, InstanceProfileStateDiff,
InstanceProfileStateDiffFn, InstanceProfileStateGoalFn,
};
/// Item to create an IAM instance profile and IAM role.
///
/// In sequence, this will:
///
/// * Create the IAM Role.
/// * Create the instance profile.
/// * Add the IAM role to the instance profile.
///
/// The `Id` type parameter is needed for each instance profile params to be a
/// distinct type.
///
/// # Type Parameters
///
/// * `Id`: A zero-sized type used to distinguish different instance profile
/// parameters from each other.
#[derive(Debug)]
pub struct InstanceProfileItem<Id> {
/// ID of the instance profile item.
item_id: ItemId,
/// Marker for unique instance profile parameters type.
marker: PhantomData<Id>,
}
impl<Id> InstanceProfileItem<Id> {
/// Returns a new `InstanceProfileItem`.
pub fn new(item_id: ItemId) -> Self {
Self {
item_id,
marker: PhantomData,
}
}
}
impl<Id> Clone for InstanceProfileItem<Id> {
fn clone(&self) -> Self {
Self {
item_id: self.item_id.clone(),
marker: PhantomData,
}
}
}
#[async_trait(?Send)]
impl<Id> Item for InstanceProfileItem<Id>
where
Id: Send + Sync + 'static,
{
type Data<'exec> = InstanceProfileData<'exec, Id>;
type Error = InstanceProfileError;
type Params<'exec> = InstanceProfileParams<Id>;
type State = InstanceProfileState;
type StateDiff = InstanceProfileStateDiff;
fn id(&self) -> &ItemId {
&self.item_id
}
async fn setup(&self, resources: &mut Resources<Empty>) -> Result<(), InstanceProfileError> {
if !resources.contains::<aws_sdk_iam::Client>() {
let sdk_config = aws_config::load_defaults(BehaviorVersion::latest()).await;
let client = aws_sdk_iam::Client::new(&sdk_config);
resources.insert(client);
}
Ok(())
}
#[cfg(feature = "item_state_example")]
fn state_example(params: &Self::Params<'_>, _data: Self::Data<'_>) -> Self::State {
use peace::cfg::state::Generated;
use crate::items::peace_aws_instance_profile::model::InstanceProfileIdAndArn;
let name = params.name().to_string();
let path = params.path().to_string();
let aws_account_id = "123456789012"; // Can this be looked up without calling AWS?
let id = String::from("instance_profile_example_id");
let arn = format!("arn:aws:iam::{aws_account_id}:instance-profile/{name}");
InstanceProfileState::Some {
name,
path,
instance_profile_id_and_arn: Generated::Value(InstanceProfileIdAndArn::new(id, arn)),
role_associated: true,
}
}
async fn try_state_current(
fn_ctx: FnCtx<'_>,
params_partial: &<Self::Params<'_> as Params>::Partial,
data: InstanceProfileData<'_, Id>,
) -> Result<Option<Self::State>, InstanceProfileError> {
InstanceProfileStateCurrentFn::try_state_current(fn_ctx, params_partial, data).await
}
async fn state_current(
fn_ctx: FnCtx<'_>,
params: &Self::Params<'_>,
data: InstanceProfileData<'_, Id>,
) -> Result<Self::State, InstanceProfileError> {
InstanceProfileStateCurrentFn::state_current(fn_ctx, params, data).await
}
async fn try_state_goal(
fn_ctx: FnCtx<'_>,
params_partial: &<Self::Params<'_> as Params>::Partial,
data: InstanceProfileData<'_, Id>,
) -> Result<Option<Self::State>, InstanceProfileError> {
InstanceProfileStateGoalFn::try_state_goal(fn_ctx, params_partial, data).await
}
async fn state_goal(
fn_ctx: FnCtx<'_>,
params: &Self::Params<'_>,
data: InstanceProfileData<'_, Id>,
) -> Result<Self::State, InstanceProfileError> {
InstanceProfileStateGoalFn::state_goal(fn_ctx, params, data).await
}
async fn state_diff(
_params_partial: &<Self::Params<'_> as Params>::Partial,
_data: Self::Data<'_>,
state_current: &Self::State,
state_goal: &Self::State,
) -> Result<Self::StateDiff, InstanceProfileError> {
InstanceProfileStateDiffFn::state_diff(state_current, state_goal).await
}
async fn state_clean(
_params_partial: &<Self::Params<'_> as Params>::Partial,
_data: Self::Data<'_>,
) -> Result<Self::State, InstanceProfileError> {
Ok(InstanceProfileState::None)
}
async fn apply_check(
params: &Self::Params<'_>,
data: Self::Data<'_>,
state_current: &Self::State,
state_target: &Self::State,
diff: &Self::StateDiff,
) -> Result<ApplyCheck, Self::Error> {
InstanceProfileApplyFns::<Id>::apply_check(params, data, state_current, state_target, diff)
.await
}
async fn apply_dry(
fn_ctx: FnCtx<'_>,
params: &Self::Params<'_>,
data: Self::Data<'_>,
state_current: &Self::State,
state_target: &Self::State,
diff: &Self::StateDiff,
) -> Result<Self::State, Self::Error> {
InstanceProfileApplyFns::<Id>::apply_dry(
fn_ctx,
params,
data,
state_current,
state_target,
diff,
)
.await
}
async fn apply(
fn_ctx: FnCtx<'_>,
params: &Self::Params<'_>,
data: Self::Data<'_>,
state_current: &Self::State,
state_target: &Self::State,
diff: &Self::StateDiff,
) -> Result<Self::State, Self::Error> {
InstanceProfileApplyFns::<Id>::apply(
fn_ctx,
params,
data,
state_current,
state_target,
diff,
)
.await
}
#[cfg(feature = "item_interactions")]
fn interactions(
params: &Self::Params<'_>,
_data: Self::Data<'_>,
) -> Vec<peace::item_interaction_model::ItemInteraction> {
use peace::item_interaction_model::{
ItemInteractionPush, ItemLocation, ItemLocationAncestors,
};
let instance_profile_name = format!("📝 {}", params.name());
let item_interaction = ItemInteractionPush::new(
ItemLocationAncestors::new(vec![ItemLocation::localhost()]),
ItemLocationAncestors::new(vec![
ItemLocation::group(String::from("IAM")),
ItemLocation::group(String::from("Instance Profiles")),
ItemLocation::path(instance_profile_name),
]),
)
.into();
vec![item_interaction]
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_instance_profile/model.rs | examples/envman/src/items/peace_aws_instance_profile/model.rs | pub use self::instance_profile_id_and_arn::InstanceProfileIdAndArn;
mod instance_profile_id_and_arn;
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_instance_profile/instance_profile_params.rs | examples/envman/src/items/peace_aws_instance_profile/instance_profile_params.rs | use std::marker::PhantomData;
use derivative::Derivative;
use peace::params::Params;
use serde::{Deserialize, Serialize};
/// InstanceProfile item parameters.
///
/// The `Id` type parameter is needed for each instance profile params to be a
/// distinct type.
///
/// # Type Parameters
///
/// * `Id`: A zero-sized type used to distinguish different instance profile
/// parameters from each other.
#[derive(Derivative, Params, PartialEq, Eq, Deserialize, Serialize)]
#[derivative(Clone, Debug)]
#[serde(bound = "")]
pub struct InstanceProfileParams<Id> {
/// Name for both the instance profile and role.
///
/// Alphanumeric characters and `_+=,.@-` are allowed.
///
/// TODO: newtype + proc macro.
name: String,
/// Namespace for both the instance profile and role.
///
/// String that begins and ends with a forward slash.
///
/// e.g. `/demo/`
#[serde(default = "path_default")]
path: String,
/// Whether or not to associate the profile with a role of the same name.
///
/// The role must already exist.
role_associate: bool,
/// Marker for unique instance profile parameters type.
marker: PhantomData<Id>,
}
fn path_default() -> String {
String::from("/")
}
impl<Id> InstanceProfileParams<Id> {
pub fn new(name: String, path: String, role_associate: bool) -> Self {
Self {
name,
path,
role_associate,
marker: PhantomData,
}
}
/// Returns the name for both the instance profile and role.
///
/// Alphanumeric characters and `_+=,.@-` are allowed.
pub fn name(&self) -> &str {
self.name.as_ref()
}
/// Returns the namespace for both the instance profile and role.
///
/// String that begins and ends with a forward slash.
///
/// e.g. `/demo/`
pub fn path(&self) -> &str {
self.path.as_ref()
}
/// Whether or not to associate the profile with a role of the same name.
pub fn role_associate(&self) -> bool {
self.role_associate
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_instance_profile/model/instance_profile_id_and_arn.rs | examples/envman/src/items/peace_aws_instance_profile/model/instance_profile_id_and_arn.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct InstanceProfileIdAndArn {
/// The stable and unique string identifying the instance profile. For more
/// information about IDs, see [IAM identifiers] in the *IAM User
/// Guide*.
///
/// [IAM identifiers]: https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html
id: String,
/// The Amazon Resource Name (ARN) specifying the instance profile. For more
/// information about ARNs and how to use them in policies, see [IAM
/// identifiers] in the *IAM User Guide*.
///
/// [IAM identifiers]: https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html
arn: String,
}
impl InstanceProfileIdAndArn {
pub fn new(id: String, arn: String) -> Self {
Self { id, arn }
}
pub fn id(&self) -> &str {
self.id.as_ref()
}
pub fn arn(&self) -> &str {
self.arn.as_ref()
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_role/iam_role_state.rs | examples/envman/src/items/peace_aws_iam_role/iam_role_state.rs | use std::fmt;
use peace::cfg::state::Generated;
use serde::{Deserialize, Serialize};
use crate::items::peace_aws_iam_role::model::{ManagedPolicyAttachment, RoleIdAndArn};
#[cfg(feature = "output_progress")]
use peace::item_interaction_model::ItemLocationState;
/// IAM role state.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum IamRoleState {
/// Instance profile does not exist.
None,
/// Instance profile exists.
Some {
/// Instance profile name.
///
/// Alphanumeric characters and `_+=,.@-` are allowed.
///
/// TODO: newtype + proc macro.
name: String,
/// String that begins and ends with a forward slash.
///
/// Defaults to `/`.
///
/// e.g. `/demo/`
#[serde(default = "path_default")]
path: String,
/// The stable and unique IDs identifying the role.
role_id_and_arn: Generated<RoleIdAndArn>,
/// Managed policy to attach to the role.
managed_policy_attachment: ManagedPolicyAttachment,
},
}
fn path_default() -> String {
String::from("/")
}
impl fmt::Display for IamRoleState {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::None => "does not exist".fmt(f),
Self::Some {
name,
path,
role_id_and_arn,
managed_policy_attachment,
} => {
match role_id_and_arn {
Generated::Tbd => write!(f, "`{path}{name}` should exist")?,
Generated::Value(_role_id_and_arn) => {
// https://console.aws.amazon.com/iamv2/home#/roles/details/demo
write!(
f,
"exists at https://console.aws.amazon.com/iamv2/home#/roles/details/{name}"
)?;
}
}
if managed_policy_attachment.attached() {
write!(f, " with policy attached")?;
} else {
write!(f, ", but managed policy not attached")?;
};
Ok(())
}
}
}
}
#[cfg(feature = "output_progress")]
impl<'state> From<&'state IamRoleState> for ItemLocationState {
fn from(iam_role_state: &'state IamRoleState) -> ItemLocationState {
match iam_role_state {
IamRoleState::Some { .. } => ItemLocationState::Exists,
IamRoleState::None => ItemLocationState::NotExists,
}
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_role/iam_role_apply_fns.rs | examples/envman/src/items/peace_aws_iam_role/iam_role_apply_fns.rs | use std::marker::PhantomData;
use peace::cfg::{state::Generated, ApplyCheck, FnCtx};
#[cfg(feature = "output_progress")]
use peace::progress_model::{ProgressLimit, ProgressMsgUpdate, ProgressSender};
use crate::items::peace_aws_iam_role::{
model::RoleIdAndArn, IamRoleData, IamRoleError, IamRoleParams, IamRoleState, IamRoleStateDiff,
};
/// ApplyFns for the instance profile state.
#[derive(Debug)]
pub struct IamRoleApplyFns<Id>(PhantomData<Id>);
impl<Id> IamRoleApplyFns<Id> {
pub(crate) async fn managed_policy_detach(
#[cfg(feature = "output_progress")] progress_sender: &ProgressSender<'_>,
client: &aws_sdk_iam::Client,
name: &str,
path: &str,
managed_policy_arn: &str,
) -> Result<(), IamRoleError> {
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from("detaching policy")));
client
.detach_role_policy()
.role_name(name)
.policy_arn(managed_policy_arn)
.send()
.await
.map_err(|error| {
let role_name = name.to_string();
let role_path = path.to_string();
#[cfg(feature = "error_reporting")]
let (aws_desc, aws_desc_span) = crate::items::aws_error_desc!(&error);
let error = Box::new(error);
IamRoleError::ManagedPolicyDetachError {
role_name,
role_path,
#[cfg(feature = "error_reporting")]
aws_desc,
#[cfg(feature = "error_reporting")]
aws_desc_span,
error,
}
})?;
#[cfg(feature = "output_progress")]
progress_sender.inc(1, ProgressMsgUpdate::Set(String::from("detaching policy")));
Ok(())
}
}
impl<Id> IamRoleApplyFns<Id>
where
Id: Send + Sync + 'static,
{
pub async fn apply_check(
_params: &IamRoleParams<Id>,
_data: IamRoleData<'_, Id>,
state_current: &IamRoleState,
_state_goal: &IamRoleState,
diff: &IamRoleStateDiff,
) -> Result<ApplyCheck, IamRoleError> {
match diff {
IamRoleStateDiff::Added => {
let apply_check = {
#[cfg(not(feature = "output_progress"))]
{
ApplyCheck::ExecRequired
}
#[cfg(feature = "output_progress")]
{
let progress_limit = ProgressLimit::Steps(2);
ApplyCheck::ExecRequired { progress_limit }
}
};
Ok(apply_check)
}
IamRoleStateDiff::Removed => {
let apply_check = match state_current {
IamRoleState::None => ApplyCheck::ExecNotRequired,
IamRoleState::Some {
name: _,
path: _,
role_id_and_arn,
managed_policy_attachment,
} => {
let mut steps_required = 0;
if managed_policy_attachment.attached() {
steps_required += 1;
}
if matches!(role_id_and_arn, Generated::Value(_)) {
steps_required += 1;
}
if steps_required == 0 {
ApplyCheck::ExecNotRequired
} else {
#[cfg(not(feature = "output_progress"))]
{
ApplyCheck::ExecRequired
}
#[cfg(feature = "output_progress")]
{
let progress_limit = ProgressLimit::Steps(steps_required);
ApplyCheck::ExecRequired { progress_limit }
}
}
}
};
Ok(apply_check)
}
IamRoleStateDiff::ManagedPolicyAttachmentModified { .. } => {
let apply_check = {
#[cfg(not(feature = "output_progress"))]
{
ApplyCheck::ExecRequired
}
#[cfg(feature = "output_progress")]
{
// Technically could be 1 or 2, whether we detach an existing before
// attaching another, or just attach one.
let progress_limit = ProgressLimit::Steps(2);
ApplyCheck::ExecRequired { progress_limit }
}
};
Ok(apply_check)
}
IamRoleStateDiff::NameOrPathModified {
name_diff,
path_diff,
} => Err(IamRoleError::RoleModificationNotSupported {
name_diff: name_diff.clone(),
path_diff: path_diff.clone(),
}),
IamRoleStateDiff::InSyncExists | IamRoleStateDiff::InSyncDoesNotExist => {
Ok(ApplyCheck::ExecNotRequired)
}
}
}
pub async fn apply_dry(
_fn_ctx: FnCtx<'_>,
_params: &IamRoleParams<Id>,
_data: IamRoleData<'_, Id>,
_state_current: &IamRoleState,
state_goal: &IamRoleState,
_diff: &IamRoleStateDiff,
) -> Result<IamRoleState, IamRoleError> {
Ok(state_goal.clone())
}
pub async fn apply(
#[cfg(not(feature = "output_progress"))] _fn_ctx: FnCtx<'_>,
#[cfg(feature = "output_progress")] fn_ctx: FnCtx<'_>,
_params: &IamRoleParams<Id>,
data: IamRoleData<'_, Id>,
state_current: &IamRoleState,
state_goal: &IamRoleState,
diff: &IamRoleStateDiff,
) -> Result<IamRoleState, IamRoleError> {
#[cfg(feature = "output_progress")]
let progress_sender = &fn_ctx.progress_sender;
match diff {
IamRoleStateDiff::Added => match state_goal {
IamRoleState::None => {
panic!("`IamRoleApplyFns::exec` called with state_goal being None.");
}
IamRoleState::Some {
name,
path,
role_id_and_arn: _,
managed_policy_attachment,
} => {
let assume_role_policy_document =
include_str!("ec2_assume_role_policy_document.json");
let client = data.client();
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from("creating role")));
let role_create_output = client
.create_role()
.role_name(name)
.path(path)
.assume_role_policy_document(assume_role_policy_document)
.send()
.await
.map_err(|error| {
let role_name = name.to_string();
#[cfg(feature = "error_reporting")]
let (aws_desc, aws_desc_span) = crate::items::aws_error_desc!(&error);
let error = Box::new(error);
IamRoleError::RoleCreateError {
role_name,
#[cfg(feature = "error_reporting")]
aws_desc,
#[cfg(feature = "error_reporting")]
aws_desc_span,
error,
}
})?;
#[cfg(feature = "output_progress")]
progress_sender.inc(1, ProgressMsgUpdate::Set(String::from("role created")));
let role = role_create_output
.role()
.expect("Expected role to be Some when created.");
let role_id = role.role_id();
let role_arn = role.arn();
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from("attaching policy")));
let Generated::Value(managed_policy_arn) = managed_policy_attachment.arn()
else {
unreachable!(
"Impossible to have an attached managed policy without an ARN."
);
};
client
.attach_role_policy()
.role_name(name)
.policy_arn(managed_policy_arn)
.send()
.await
.map_err(|error| {
#[cfg(feature = "error_reporting")]
let (aws_desc, aws_desc_span) = crate::items::aws_error_desc!(&error);
let error = Box::new(error);
IamRoleError::ManagedPolicyAttachError {
role_name: name.clone(),
role_path: path.clone(),
managed_policy_arn: managed_policy_attachment.arn().to_string(),
#[cfg(feature = "error_reporting")]
aws_desc,
#[cfg(feature = "error_reporting")]
aws_desc_span,
error,
}
})?;
#[cfg(feature = "output_progress")]
progress_sender.inc(1, ProgressMsgUpdate::Set(String::from("policy attached")));
let state_ensured = IamRoleState::Some {
name: name.to_string(),
path: path.clone(),
role_id_and_arn: Generated::Value(RoleIdAndArn::new(
role_id.to_string(),
role_arn.to_string(),
)),
managed_policy_attachment: managed_policy_attachment.clone(),
};
Ok(state_ensured)
}
},
IamRoleStateDiff::Removed => {
match state_current {
IamRoleState::None => {}
IamRoleState::Some {
name,
path,
role_id_and_arn,
managed_policy_attachment,
} => {
let client = data.client();
if managed_policy_attachment.attached() {
let Generated::Value(managed_policy_arn) =
managed_policy_attachment.arn()
else {
unreachable!(
"Impossible to have an attached managed policy without an ARN."
);
};
Self::managed_policy_detach(
#[cfg(feature = "output_progress")]
progress_sender,
client,
name,
path,
managed_policy_arn,
)
.await?;
}
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from("deleting role")));
if let Generated::Value(role_id_and_arn) = role_id_and_arn {
client
.delete_role()
.role_name(name)
.send()
.await
.map_err(|error| {
let role_name = name.to_string();
let role_id = role_id_and_arn.id().to_string();
let role_arn = role_id_and_arn.arn().to_string();
#[cfg(feature = "error_reporting")]
let (aws_desc, aws_desc_span) =
crate::items::aws_error_desc!(&error);
let error = Box::new(error);
IamRoleError::RoleDeleteError {
role_name,
role_id,
role_arn,
#[cfg(feature = "error_reporting")]
aws_desc,
#[cfg(feature = "error_reporting")]
aws_desc_span,
error,
}
})?;
#[cfg(feature = "output_progress")]
progress_sender
.inc(1, ProgressMsgUpdate::Set(String::from("role deleted")));
}
}
}
let state_applied = state_goal.clone();
Ok(state_applied)
}
IamRoleStateDiff::InSyncExists | IamRoleStateDiff::InSyncDoesNotExist => {
unreachable!(
"`IamRoleApplyFns::exec` should never be called when state is in sync."
);
}
IamRoleStateDiff::ManagedPolicyAttachmentModified {
managed_policy_attachment_current,
managed_policy_attachment_goal,
} => {
let IamRoleState::Some {
name,
path,
role_id_and_arn: _,
managed_policy_attachment,
} = state_goal
else {
panic!("`IamRoleApplyFns::exec` called with state_goal being None.");
};
let client = data.client();
if managed_policy_attachment_current.attached() {
// Detach it.
let Generated::Value(managed_policy_arn) =
managed_policy_attachment_current.arn()
else {
unreachable!(
"Impossible to have an attached managed policy without an ARN."
);
};
Self::managed_policy_detach(
#[cfg(feature = "output_progress")]
progress_sender,
client,
name,
path,
managed_policy_arn,
)
.await?;
}
if managed_policy_attachment_goal.attached() {
let Generated::Value(managed_policy_arn) = managed_policy_attachment_goal.arn()
else {
unreachable!(
"Impossible to have an attached managed policy without an ARN."
);
};
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from("attaching policy")));
client
.attach_role_policy()
.role_name(name)
.policy_arn(managed_policy_arn)
.send()
.await
.map_err(|error| {
#[cfg(feature = "error_reporting")]
let (aws_desc, aws_desc_span) = crate::items::aws_error_desc!(&error);
let error = Box::new(error);
IamRoleError::ManagedPolicyAttachError {
role_name: name.clone(),
role_path: path.clone(),
managed_policy_arn: managed_policy_attachment.arn().to_string(),
#[cfg(feature = "error_reporting")]
aws_desc,
#[cfg(feature = "error_reporting")]
aws_desc_span,
error,
}
})?;
#[cfg(feature = "output_progress")]
progress_sender.inc(1, ProgressMsgUpdate::Set(String::from("policy attached")));
}
let state_ensured = state_goal.clone();
Ok(state_ensured)
}
IamRoleStateDiff::NameOrPathModified {
name_diff,
path_diff,
} => Err(IamRoleError::NameOrPathModificationNotSupported {
name_diff: name_diff.clone(),
path_diff: path_diff.clone(),
}),
}
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_role/iam_role_state_diff_fn.rs | examples/envman/src/items/peace_aws_iam_role/iam_role_state_diff_fn.rs | use crate::items::peace_aws_iam_role::{IamRoleError, IamRoleState, IamRoleStateDiff};
/// Tar extraction status diff function.
#[derive(Debug)]
pub struct IamRoleStateDiffFn;
impl IamRoleStateDiffFn {
pub async fn state_diff(
state_current: &IamRoleState,
state_goal: &IamRoleState,
) -> Result<IamRoleStateDiff, IamRoleError> {
let diff = match (state_current, state_goal) {
(IamRoleState::None, IamRoleState::None) => IamRoleStateDiff::InSyncDoesNotExist,
(IamRoleState::None, IamRoleState::Some { .. }) => IamRoleStateDiff::Added,
(IamRoleState::Some { .. }, IamRoleState::None) => IamRoleStateDiff::Removed,
(
IamRoleState::Some {
name: name_current,
path: path_current,
role_id_and_arn: _,
managed_policy_attachment: managed_policy_attachment_current,
},
IamRoleState::Some {
name: name_goal,
path: path_goal,
role_id_and_arn: _,
managed_policy_attachment: managed_policy_attachment_goal,
},
) => {
let name_diff = if name_current != name_goal {
Some((name_current.clone(), name_goal.clone()))
} else {
None
};
let path_diff = if path_current != path_goal {
Some((path_current.clone(), path_goal.clone()))
} else {
None
};
if name_diff.is_none() && path_diff.is_none() {
if managed_policy_attachment_current != managed_policy_attachment_goal {
IamRoleStateDiff::ManagedPolicyAttachmentModified {
managed_policy_attachment_current: managed_policy_attachment_current
.clone(),
managed_policy_attachment_goal: managed_policy_attachment_goal.clone(),
}
} else {
IamRoleStateDiff::InSyncExists
}
} else {
IamRoleStateDiff::NameOrPathModified {
name_diff,
path_diff,
}
}
}
};
Ok(diff)
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_role/iam_role_state_current_fn.rs | examples/envman/src/items/peace_aws_iam_role/iam_role_state_current_fn.rs | use std::marker::PhantomData;
use aws_sdk_iam::{error::SdkError, operation::get_role::GetRoleError};
use peace::{
cfg::{state::Generated, FnCtx},
params::Params,
};
use crate::items::peace_aws_iam_role::{
model::{ManagedPolicyAttachment, RoleIdAndArn},
IamRoleData, IamRoleError, IamRoleParams, IamRoleState,
};
#[cfg(feature = "output_progress")]
use peace::progress_model::ProgressMsgUpdate;
/// Reads the current state of the instance profile state.
#[derive(Debug)]
pub struct IamRoleStateCurrentFn<Id>(PhantomData<Id>);
impl<Id> IamRoleStateCurrentFn<Id>
where
Id: Send + Sync,
{
pub async fn try_state_current(
fn_ctx: FnCtx<'_>,
params_partial: &<IamRoleParams<Id> as Params>::Partial,
data: IamRoleData<'_, Id>,
) -> Result<Option<IamRoleState>, IamRoleError> {
let name = params_partial.name();
let path = params_partial.path();
if let Some((name, path)) = name.zip(path) {
Self::state_current_internal(fn_ctx, data, name, path)
.await
.map(Some)
} else {
Ok(None)
}
}
pub async fn state_current(
fn_ctx: FnCtx<'_>,
params: &IamRoleParams<Id>,
data: IamRoleData<'_, Id>,
) -> Result<IamRoleState, IamRoleError> {
let name = params.name();
let path = params.path();
Self::state_current_internal(fn_ctx, data, name, path).await
}
async fn state_current_internal(
fn_ctx: FnCtx<'_>,
data: IamRoleData<'_, Id>,
name: &str,
path: &str,
) -> Result<IamRoleState, IamRoleError> {
let client = data.client();
#[cfg(not(feature = "output_progress"))]
let _fn_ctx = fn_ctx;
#[cfg(feature = "output_progress")]
let progress_sender = &fn_ctx.progress_sender;
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from("fetching role")));
let get_role_result = client.get_role().role_name(name).send().await;
let role_opt = match get_role_result {
Ok(get_role_output) => {
let role = get_role_output
.role()
.expect("Expected Role to exist when get_role is successful");
let role_name = role.role_name().to_string();
let role_path = role.path().to_string();
let role_id = role.role_id().to_string();
let role_arn = role.arn().to_string();
let role_id_and_arn = RoleIdAndArn::new(role_id, role_arn);
Some((role_name, role_path, role_id_and_arn))
}
Err(error) => {
#[cfg(feature = "error_reporting")]
let (aws_desc, aws_desc_span) = crate::items::aws_error_desc!(&error);
match &error {
SdkError::ServiceError(service_error) => match service_error.err() {
GetRoleError::NoSuchEntityException(_) => None,
_ => {
let error = Box::new(error);
return Err(IamRoleError::RoleGetError {
role_name: name.to_string(),
#[cfg(feature = "error_reporting")]
aws_desc,
#[cfg(feature = "error_reporting")]
aws_desc_span,
error,
});
}
},
_ => {
let error = Box::new(error);
return Err(IamRoleError::RoleGetError {
role_name: name.to_string(),
#[cfg(feature = "error_reporting")]
aws_desc,
#[cfg(feature = "error_reporting")]
aws_desc_span,
error,
});
}
}
}
};
match role_opt {
None => {
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from("policy not fetched")));
Ok(IamRoleState::None)
}
Some((role_name, role_path, role_id_and_arn)) => {
assert_eq!(name, role_name);
assert_eq!(path, role_path);
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from("policy fetched")));
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from(
"listing attached policies",
)));
let list_attached_role_policies_output = client
.list_attached_role_policies()
.role_name(name)
.path_prefix(path)
.send()
.await
.map_err(|error| {
#[cfg(feature = "error_reporting")]
let (aws_desc, aws_desc_span) = crate::items::aws_error_desc!(&error);
let error = Box::new(error);
IamRoleError::ManagedPoliciesListError {
role_name: name.to_string(),
role_path: path.to_string(),
#[cfg(feature = "error_reporting")]
aws_desc,
#[cfg(feature = "error_reporting")]
aws_desc_span,
error,
}
})?;
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from(
"filtering attached policies",
)));
let managed_policy_attachment = list_attached_role_policies_output
.attached_policies()
.iter()
.find_map(|attached_policy| {
let policy_name = attached_policy
.policy_name()
.expect("Expected policy_name to be Some for any attached policy.");
if policy_name == name {
Some(
attached_policy
.policy_arn()
.expect(
"Expected policy_arn to be Some for \
any attached policy.",
)
.to_string(),
)
} else {
None
}
})
.map(|managed_policy_arn| {
ManagedPolicyAttachment::new(Generated::Value(managed_policy_arn), true)
})
.unwrap_or(ManagedPolicyAttachment::new(Generated::Tbd, false));
#[cfg(feature = "output_progress")]
{
let message = if managed_policy_attachment.attached() {
"policy attached"
} else {
"policy not attached"
};
progress_sender.tick(ProgressMsgUpdate::Set(String::from(message)));
}
let state_current = IamRoleState::Some {
name: name.to_string(),
path: path.to_string(),
role_id_and_arn: Generated::Value(role_id_and_arn),
managed_policy_attachment,
};
Ok(state_current)
}
}
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_role/iam_role_state_diff.rs | examples/envman/src/items/peace_aws_iam_role/iam_role_state_diff.rs | use std::fmt;
use peace::cfg::state::Generated;
use serde::{Deserialize, Serialize};
use crate::items::peace_aws_iam_role::model::ManagedPolicyAttachment;
/// Diff between current (dest) and goal (src) state.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub enum IamRoleStateDiff {
/// Role would be added.
Added,
/// Role would be removed.
Removed,
/// The managed policy attached to the role has changed.
ManagedPolicyAttachmentModified {
/// Current state of the managed policy attachment.
managed_policy_attachment_current: ManagedPolicyAttachment,
/// Goal state of the managed policy attachment.
managed_policy_attachment_goal: ManagedPolicyAttachment,
},
/// Role would be replaced.
///
/// AWS doesn't support modifying a role in place, so this item must be
/// cleaned and re-created.
NameOrPathModified {
/// Whether the name has been changed.
name_diff: Option<(String, String)>,
/// Whether the path has been changed.
path_diff: Option<(String, String)>,
},
/// Role exists and is up to date.
InSyncExists,
/// Role does not exist, which is goal.
InSyncDoesNotExist,
}
impl fmt::Display for IamRoleStateDiff {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
IamRoleStateDiff::Added => {
write!(f, "will be created.")
}
IamRoleStateDiff::Removed => {
write!(f, "will be removed.")
}
IamRoleStateDiff::ManagedPolicyAttachmentModified {
managed_policy_attachment_current,
managed_policy_attachment_goal,
} => {
let current_arn = managed_policy_attachment_current.arn();
let goal_arn = managed_policy_attachment_goal.arn();
if current_arn != goal_arn {
match (current_arn, goal_arn) {
(Generated::Value(_), Generated::Value(_)) |
(Generated::Tbd, Generated::Value(_)) |
(Generated::Tbd, Generated::Tbd) => {
write!(f, "Managed policy attachment will be replaced.")
}
// TODO: not always true.
(Generated::Value(_), Generated::Tbd)
=> write!(f, "exists and is up to date."),
}
} else {
match (
managed_policy_attachment_current.attached(),
managed_policy_attachment_goal.attached(),
) {
(false, false) | (true, true) => unreachable!(
"If the attached managed policy ARNs are the same, then the attached state must be different."
),
(true, false) => write!(f, "Managed policy will be detached."),
(false, true) => write!(f, "Managed policy will be attached."),
}
}
}
IamRoleStateDiff::NameOrPathModified {
name_diff,
path_diff,
} => match (name_diff, path_diff) {
(None, None) => {
unreachable!(
"Modified is only valid when either name or path has changed.\n\
This is a bug."
)
}
(None, Some((path_current, path_goal))) => write!(
f,
"path modified from {path_current} to {path_goal}. ⚠️ This modification requires deletion and recreation."
),
(Some((name_current, name_goal)), None) => write!(
f,
"name modified from {name_current} to {name_goal}. ⚠️ This modification requires deletion and recreation."
),
(Some((name_current, name_goal)), Some((path_current, path_goal))) => write!(
f,
"modified from {path_current}{name_current} to {path_goal}{name_goal}. ⚠️ This modification requires deletion and recreation."
),
},
IamRoleStateDiff::InSyncExists => {
write!(f, "exists and is up to date.")
}
IamRoleStateDiff::InSyncDoesNotExist => {
write!(f, "does not exist as intended.")
}
}
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_role/iam_role_params.rs | examples/envman/src/items/peace_aws_iam_role/iam_role_params.rs | use std::marker::PhantomData;
use derivative::Derivative;
use peace::params::Params;
use serde::{Deserialize, Serialize};
/// IamRole item parameters.
///
/// The `Id` type parameter is needed for each instance profile params to be a
/// distinct type.
///
/// # Type Parameters
///
/// * `Id`: A zero-sized type used to distinguish different instance profile
/// parameters from each other.
#[derive(Derivative, Params, PartialEq, Eq, Deserialize, Serialize)]
#[derivative(Clone, Debug)]
#[serde(bound = "")]
pub struct IamRoleParams<Id> {
/// Name for both the instance profile and role.
///
/// Alphanumeric characters and `_+=,.@-` are allowed.
///
/// TODO: newtype + proc macro.
name: String,
/// Namespace for both the instance profile and role.
///
/// String that begins and ends with a forward slash.
///
/// e.g. `/demo/`
#[serde(default = "path_default")]
path: String,
/// Managed policy ARN to attach to the role.
managed_policy_arn: String,
/// Marker for unique instance profile parameters type.
marker: PhantomData<Id>,
}
fn path_default() -> String {
String::from("/")
}
impl<Id> IamRoleParams<Id> {
/// Returns the name for both the instance profile and role.
///
/// Alphanumeric characters and `_+=,.@-` are allowed.
pub fn name(&self) -> &str {
self.name.as_ref()
}
/// Returns the namespace for both the instance profile and role.
///
/// String that begins and ends with a forward slash.
///
/// e.g. `/demo/`
pub fn path(&self) -> &str {
self.path.as_ref()
}
/// Returns the ARN of the managed policy to attach.
pub fn managed_policy_arn(&self) -> &str {
self.managed_policy_arn.as_ref()
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_role/model.rs | examples/envman/src/items/peace_aws_iam_role/model.rs | pub use self::{managed_policy_attachment::ManagedPolicyAttachment, role_id_and_arn::RoleIdAndArn};
mod managed_policy_attachment;
mod role_id_and_arn;
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_role/iam_role_error.rs | examples/envman/src/items/peace_aws_iam_role/iam_role_error.rs | use aws_sdk_iam::{
error::SdkError,
operation::{
attach_role_policy::AttachRolePolicyError, create_role::CreateRoleError,
delete_role::DeleteRoleError, detach_role_policy::DetachRolePolicyError,
get_role::GetRoleError, list_attached_role_policies::ListAttachedRolePoliciesError,
},
};
#[cfg(feature = "error_reporting")]
use peace::miette::{self, SourceSpan};
/// Error while managing instance profile state.
#[cfg_attr(feature = "error_reporting", derive(peace::miette::Diagnostic))]
#[derive(Debug, thiserror::Error)]
pub enum IamRoleError {
/// Role name or path was attempted to be modified.
#[error("Role name or path modification is not supported.")]
NameOrPathModificationNotSupported {
/// Whether the name has been changed.
name_diff: Option<(String, String)>,
/// Whether the path has been changed.
path_diff: Option<(String, String)>,
},
/// A `peace` runtime error occurred.
#[error("A `peace` runtime error occurred.")]
PeaceRtError(
#[cfg_attr(feature = "error_reporting", diagnostic_source)]
#[source]
#[from]
peace::rt_model::Error,
),
/// Failed to attach managed policy.
#[error("Failed to attach managed policy.")]
#[cfg_attr(
feature = "error_reporting",
diagnostic(help("Make sure you are connected to the internet and try again."))
)]
ManagedPolicyAttachError {
/// Role friendly name.
role_name: String,
/// Role path.
role_path: String,
/// ARN of the managed policy.
managed_policy_arn: String,
/// Error description from AWS error.
#[cfg(feature = "error_reporting")]
#[source_code]
aws_desc: String,
/// Span of the description to highlight.
#[cfg(feature = "error_reporting")]
#[label]
aws_desc_span: SourceSpan,
/// Underlying error.
#[source]
error: Box<SdkError<AttachRolePolicyError>>,
},
/// Failed to detach managed policy.
#[error("Failed to detach managed policy.")]
#[cfg_attr(
feature = "error_reporting",
diagnostic(help("Make sure you are connected to the internet and try again."))
)]
ManagedPolicyDetachError {
/// Role friendly name.
role_name: String,
/// Role path.
role_path: String,
/// Error description from AWS error.
#[cfg(feature = "error_reporting")]
#[source_code]
aws_desc: String,
/// Span of the description to highlight.
#[cfg(feature = "error_reporting")]
#[label]
aws_desc_span: SourceSpan,
/// Underlying error.
#[source]
error: Box<SdkError<DetachRolePolicyError>>,
},
/// Failed to list managed policies for role.
#[error("Failed to list managed policies for role.")]
#[cfg_attr(
feature = "error_reporting",
diagnostic(help("Make sure you are connected to the internet and try again."))
)]
ManagedPoliciesListError {
/// Role friendly name.
role_name: String,
/// Role path.
role_path: String,
/// Error description from AWS error.
#[cfg(feature = "error_reporting")]
#[source_code]
aws_desc: String,
/// Span of the description to highlight.
#[cfg(feature = "error_reporting")]
#[label]
aws_desc_span: SourceSpan,
/// Underlying error.
#[source]
error: Box<SdkError<ListAttachedRolePoliciesError>>,
},
/// Failed to create role.
#[error("Failed to create role.")]
#[cfg_attr(
feature = "error_reporting",
diagnostic(help("Make sure you are connected to the internet and try again."))
)]
RoleCreateError {
/// Role friendly name.
role_name: String,
/// Error description from AWS error.
#[cfg(feature = "error_reporting")]
#[source_code]
aws_desc: String,
/// Span of the description to highlight.
#[cfg(feature = "error_reporting")]
#[label]
aws_desc_span: SourceSpan,
/// Underlying error.
#[source]
error: Box<SdkError<CreateRoleError>>,
},
/// Failed to discover role.
#[error("Failed to discover role.")]
#[cfg_attr(
feature = "error_reporting",
diagnostic(help("Make sure you are connected to the internet and try again."))
)]
RoleGetError {
/// Expected role friendly name.
role_name: String,
/// Error description from AWS error.
#[cfg(feature = "error_reporting")]
#[source_code]
aws_desc: String,
/// Span of the description to highlight.
#[cfg(feature = "error_reporting")]
#[label]
aws_desc_span: SourceSpan,
/// Underlying error.
#[source]
error: Box<SdkError<GetRoleError>>,
},
/// Failed to delete role.
#[error("Failed to delete role.")]
#[cfg_attr(
feature = "error_reporting",
diagnostic(help("Make sure you are connected to the internet and try again."))
)]
RoleDeleteError {
/// Role friendly name.
role_name: String,
/// Role stable ID.
role_id: String,
/// Role ARN.
role_arn: String,
/// Error description from AWS error.
#[cfg(feature = "error_reporting")]
#[source_code]
aws_desc: String,
/// Span of the description to highlight.
#[cfg(feature = "error_reporting")]
#[label]
aws_desc_span: SourceSpan,
/// Underlying error.
#[source]
error: Box<SdkError<DeleteRoleError>>,
},
/// User changed the role name or path, but AWS does not support changing
/// this.
#[error("Role name or path cannot be modified, as it is not supported by AWS.")]
RoleModificationNotSupported {
/// Name diff.
name_diff: Option<(String, String)>,
/// Path diff.
path_diff: Option<(String, String)>,
},
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_role/iam_role_item.rs | examples/envman/src/items/peace_aws_iam_role/iam_role_item.rs | use std::marker::PhantomData;
use aws_config::BehaviorVersion;
use peace::{
cfg::{async_trait, ApplyCheck, FnCtx, Item},
item_model::ItemId,
params::Params,
resource_rt::{resources::ts::Empty, Resources},
};
use crate::items::peace_aws_iam_role::{
IamRoleApplyFns, IamRoleData, IamRoleError, IamRoleParams, IamRoleState, IamRoleStateCurrentFn,
IamRoleStateDiff, IamRoleStateDiffFn, IamRoleStateGoalFn,
};
/// Item to create an IAM instance profile and IAM role.
///
/// In sequence, this will:
///
/// * Create the IAM Role.
/// * Create the instance profile.
/// * Add the IAM role to the instance profile.
///
/// The `Id` type parameter is needed for each instance profile params to be a
/// distinct type.
///
/// # Type Parameters
///
/// * `Id`: A zero-sized type used to distinguish different instance profile
/// parameters from each other.
#[derive(Debug)]
pub struct IamRoleItem<Id> {
/// ID of the instance profile item.
item_id: ItemId,
/// Marker for unique instance profile parameters type.
marker: PhantomData<Id>,
}
impl<Id> IamRoleItem<Id> {
/// Returns a new `IamRoleItem`.
pub fn new(item_id: ItemId) -> Self {
Self {
item_id,
marker: PhantomData,
}
}
}
impl<Id> Clone for IamRoleItem<Id> {
fn clone(&self) -> Self {
Self {
item_id: self.item_id.clone(),
marker: PhantomData,
}
}
}
#[async_trait(?Send)]
impl<Id> Item for IamRoleItem<Id>
where
Id: Send + Sync + 'static,
{
type Data<'exec> = IamRoleData<'exec, Id>;
type Error = IamRoleError;
type Params<'exec> = IamRoleParams<Id>;
type State = IamRoleState;
type StateDiff = IamRoleStateDiff;
fn id(&self) -> &ItemId {
&self.item_id
}
async fn setup(&self, resources: &mut Resources<Empty>) -> Result<(), IamRoleError> {
if !resources.contains::<aws_sdk_iam::Client>() {
let sdk_config = aws_config::load_defaults(BehaviorVersion::latest()).await;
let client = aws_sdk_iam::Client::new(&sdk_config);
resources.insert(client);
}
Ok(())
}
#[cfg(feature = "item_state_example")]
fn state_example(params: &Self::Params<'_>, _data: Self::Data<'_>) -> Self::State {
use peace::cfg::state::Generated;
use crate::items::peace_aws_iam_role::model::{ManagedPolicyAttachment, RoleIdAndArn};
let name = params.name().to_string();
let path = params.path().to_string();
let aws_account_id = "123456789012"; // Can this be looked up without calling AWS?
let role_id_and_arn = {
let id = String::from("iam_role_example_id");
let arn = format!("arn:aws:iam::{aws_account_id}:role/{name}");
Generated::Value(RoleIdAndArn::new(id, arn))
};
let managed_policy_attachment = {
let arn = params.managed_policy_arn().to_string();
ManagedPolicyAttachment::new(Generated::Value(arn), true)
};
IamRoleState::Some {
name,
path,
role_id_and_arn,
managed_policy_attachment,
}
}
async fn try_state_current(
fn_ctx: FnCtx<'_>,
params_partial: &<Self::Params<'_> as Params>::Partial,
data: IamRoleData<'_, Id>,
) -> Result<Option<Self::State>, IamRoleError> {
IamRoleStateCurrentFn::try_state_current(fn_ctx, params_partial, data).await
}
async fn state_current(
fn_ctx: FnCtx<'_>,
params: &Self::Params<'_>,
data: IamRoleData<'_, Id>,
) -> Result<Self::State, IamRoleError> {
IamRoleStateCurrentFn::state_current(fn_ctx, params, data).await
}
async fn try_state_goal(
fn_ctx: FnCtx<'_>,
params_partial: &<Self::Params<'_> as Params>::Partial,
data: IamRoleData<'_, Id>,
) -> Result<Option<Self::State>, IamRoleError> {
IamRoleStateGoalFn::try_state_goal(fn_ctx, params_partial, data).await
}
async fn state_goal(
fn_ctx: FnCtx<'_>,
params: &Self::Params<'_>,
data: IamRoleData<'_, Id>,
) -> Result<Self::State, IamRoleError> {
IamRoleStateGoalFn::state_goal(fn_ctx, params, data).await
}
async fn state_diff(
_params_partial: &<Self::Params<'_> as Params>::Partial,
_data: Self::Data<'_>,
state_current: &Self::State,
state_goal: &Self::State,
) -> Result<Self::StateDiff, IamRoleError> {
IamRoleStateDiffFn::state_diff(state_current, state_goal).await
}
async fn state_clean(
_params_partial: &<Self::Params<'_> as Params>::Partial,
_data: Self::Data<'_>,
) -> Result<Self::State, IamRoleError> {
Ok(IamRoleState::None)
}
async fn apply_check(
params: &Self::Params<'_>,
data: Self::Data<'_>,
state_current: &Self::State,
state_target: &Self::State,
diff: &Self::StateDiff,
) -> Result<ApplyCheck, Self::Error> {
IamRoleApplyFns::<Id>::apply_check(params, data, state_current, state_target, diff).await
}
async fn apply_dry(
fn_ctx: FnCtx<'_>,
params: &Self::Params<'_>,
data: Self::Data<'_>,
state_current: &Self::State,
state_target: &Self::State,
diff: &Self::StateDiff,
) -> Result<Self::State, Self::Error> {
IamRoleApplyFns::<Id>::apply_dry(fn_ctx, params, data, state_current, state_target, diff)
.await
}
async fn apply(
fn_ctx: FnCtx<'_>,
params: &Self::Params<'_>,
data: Self::Data<'_>,
state_current: &Self::State,
state_target: &Self::State,
diff: &Self::StateDiff,
) -> Result<Self::State, Self::Error> {
IamRoleApplyFns::<Id>::apply(fn_ctx, params, data, state_current, state_target, diff).await
}
#[cfg(feature = "item_interactions")]
fn interactions(
params: &Self::Params<'_>,
_data: Self::Data<'_>,
) -> Vec<peace::item_interaction_model::ItemInteraction> {
use peace::item_interaction_model::{
ItemInteractionPush, ItemLocation, ItemLocationAncestors,
};
let iam_role_name = format!("🧢 {}", params.name());
let item_interaction = ItemInteractionPush::new(
ItemLocationAncestors::new(vec![ItemLocation::localhost()]),
ItemLocationAncestors::new(vec![
ItemLocation::group(String::from("IAM")),
ItemLocation::group(String::from("Roles")),
ItemLocation::path(iam_role_name),
]),
)
.into();
vec![item_interaction]
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_role/iam_role_data.rs | examples/envman/src/items/peace_aws_iam_role/iam_role_data.rs | use std::marker::PhantomData;
use peace::data::{accessors::R, Data};
/// Data used to manage instance profile state.
///
/// # Type Parameters
///
/// * `Id`: A zero-sized type used to distinguish different instance profile
/// parameters from each other.
#[derive(Data, Debug)]
pub struct IamRoleData<'exec, Id>
where
Id: Send + Sync + 'static,
{
/// IAM client to communicate with AWS.
client: R<'exec, aws_sdk_iam::Client>,
/// Marker.
marker: PhantomData<Id>,
}
impl<'exec, Id> IamRoleData<'exec, Id>
where
Id: Send + Sync + 'static,
{
pub fn client(&self) -> &R<'exec, aws_sdk_iam::Client> {
&self.client
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_role/iam_role_state_goal_fn.rs | examples/envman/src/items/peace_aws_iam_role/iam_role_state_goal_fn.rs | use std::marker::PhantomData;
use peace::{
cfg::{state::Generated, FnCtx},
params::Params,
};
use crate::items::peace_aws_iam_role::{
model::ManagedPolicyAttachment, IamRoleData, IamRoleError, IamRoleParams, IamRoleState,
};
/// Reads the goal state of the instance profile state.
#[derive(Debug)]
pub struct IamRoleStateGoalFn<Id>(PhantomData<Id>);
impl<Id> IamRoleStateGoalFn<Id>
where
Id: Send + Sync,
{
pub async fn try_state_goal(
_fn_ctx: FnCtx<'_>,
params_partial: &<IamRoleParams<Id> as Params>::Partial,
_data: IamRoleData<'_, Id>,
) -> Result<Option<IamRoleState>, IamRoleError> {
let name = params_partial.name();
let path = params_partial.path();
if let Some((name, path)) = name.zip(path) {
Self::state_goal_internal(
name.to_string(),
path.to_string(),
params_partial
.managed_policy_arn()
.map(|managed_policy_arn| managed_policy_arn.to_string()),
)
.await
.map(Some)
} else {
Ok(None)
}
}
pub async fn state_goal(
_fn_ctx: FnCtx<'_>,
params: &IamRoleParams<Id>,
_data: IamRoleData<'_, Id>,
) -> Result<IamRoleState, IamRoleError> {
let name = params.name().to_string();
let path = params.path().to_string();
let managed_policy_arn = Some(params.managed_policy_arn().to_string());
Self::state_goal_internal(name, path, managed_policy_arn).await
}
async fn state_goal_internal(
name: String,
path: String,
managed_policy_arn: Option<String>,
) -> Result<IamRoleState, IamRoleError> {
let managed_policy_attachment = ManagedPolicyAttachment::new(
managed_policy_arn
// Hack: Remove this when referential param values is implemented.
.map(Generated::Value)
.unwrap_or(Generated::Tbd),
true,
);
let role_id_and_arn = Generated::Tbd;
Ok(IamRoleState::Some {
name,
path,
role_id_and_arn,
managed_policy_attachment,
})
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_role/model/managed_policy_attachment.rs | examples/envman/src/items/peace_aws_iam_role/model/managed_policy_attachment.rs | use peace::cfg::state::Generated;
use serde::{Deserialize, Serialize};
/// Managed policy to attach to the role.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct ManagedPolicyAttachment {
/// ARN of the managed policy to attach to the role.
arn: Generated<String>,
/// Whether the policy has been attached to the role.
attached: bool,
}
impl ManagedPolicyAttachment {
pub fn new(arn: Generated<String>, attached: bool) -> Self {
Self { arn, attached }
}
pub fn arn(&self) -> &Generated<String> {
&self.arn
}
pub fn attached(&self) -> bool {
self.attached
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_role/model/role_id_and_arn.rs | examples/envman/src/items/peace_aws_iam_role/model/role_id_and_arn.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct RoleIdAndArn {
/// The stable and unique string identifying the role. For more information
/// about IDs, see [IAM identifiers] in the *IAM User Guide*.
///
/// [IAM identifiers]: https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html
id: String,
/// The Amazon Resource Name (ARN) specifying the role. For more information
/// about ARNs and how to use them in policies, see [IAM identifiers] in the
/// *IAM User Guide*.
///
/// [IAM identifiers]: https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html
arn: String,
}
impl RoleIdAndArn {
pub fn new(id: String, arn: String) -> Self {
Self { id, arn }
}
pub fn id(&self) -> &str {
self.id.as_ref()
}
pub fn arn(&self) -> &str {
self.arn.as_ref()
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_policy/iam_policy_state_goal_fn.rs | examples/envman/src/items/peace_aws_iam_policy/iam_policy_state_goal_fn.rs | use std::marker::PhantomData;
use peace::{
cfg::{state::Generated, FnCtx},
params::Params,
};
use crate::items::peace_aws_iam_policy::{
IamPolicyData, IamPolicyError, IamPolicyParams, IamPolicyState,
};
/// Reads the goal state of the instance profile state.
#[derive(Debug)]
pub struct IamPolicyStateGoalFn<Id>(PhantomData<Id>);
impl<Id> IamPolicyStateGoalFn<Id>
where
Id: Send + Sync,
{
pub async fn try_state_goal(
_fn_ctx: FnCtx<'_>,
params_partial: &<IamPolicyParams<Id> as Params>::Partial,
_data: IamPolicyData<'_, Id>,
) -> Result<Option<IamPolicyState>, IamPolicyError> {
let name = params_partial.name();
let path = params_partial.path();
let policy_document = params_partial.policy_document();
if let Some(((name, path), policy_document)) = name.zip(path).zip(policy_document) {
Self::state_goal_internal(
name.to_string(),
path.to_string(),
policy_document.to_string(),
)
.await
.map(Some)
} else {
Ok(None)
}
}
pub async fn state_goal(
_fn_ctx: FnCtx<'_>,
params: &IamPolicyParams<Id>,
_data: IamPolicyData<'_, Id>,
) -> Result<IamPolicyState, IamPolicyError> {
let name = params.name().to_string();
let path = params.path().to_string();
let policy_document = params.policy_document().to_string();
Self::state_goal_internal(name, path, policy_document).await
}
async fn state_goal_internal(
name: String,
path: String,
policy_document: String,
) -> Result<IamPolicyState, IamPolicyError> {
// TODO: `Generated::Tbd` is should be saved as `Generated::Value` at the point
// of applying a change.
let policy_id_arn_version = Generated::Tbd;
Ok(IamPolicyState::Some {
name,
path,
policy_document,
policy_id_arn_version,
})
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_policy/iam_policy_data.rs | examples/envman/src/items/peace_aws_iam_policy/iam_policy_data.rs | use std::marker::PhantomData;
use peace::data::{accessors::R, Data};
/// Data used to manage instance profile state.
///
/// # Type Parameters
///
/// * `Id`: A zero-sized type used to distinguish different instance profile
/// parameters from each other.
#[derive(Data, Debug)]
pub struct IamPolicyData<'exec, Id>
where
Id: Send + Sync + 'static,
{
/// IAM client to communicate with AWS.
client: R<'exec, aws_sdk_iam::Client>,
/// Marker.
marker: PhantomData<Id>,
}
impl<'exec, Id> IamPolicyData<'exec, Id>
where
Id: Send + Sync + 'static,
{
pub fn client(&self) -> &R<'exec, aws_sdk_iam::Client> {
&self.client
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_policy/iam_policy_state_diff_fn.rs | examples/envman/src/items/peace_aws_iam_policy/iam_policy_state_diff_fn.rs | use crate::items::peace_aws_iam_policy::{IamPolicyError, IamPolicyState, IamPolicyStateDiff};
/// Tar extraction status diff function.
#[derive(Debug)]
pub struct IamPolicyStateDiffFn;
impl IamPolicyStateDiffFn {
pub async fn state_diff(
state_current: &IamPolicyState,
state_goal: &IamPolicyState,
) -> Result<IamPolicyStateDiff, IamPolicyError> {
let diff = match (state_current, state_goal) {
(IamPolicyState::None, IamPolicyState::None) => IamPolicyStateDiff::InSyncDoesNotExist,
(IamPolicyState::None, IamPolicyState::Some { .. }) => IamPolicyStateDiff::Added,
(IamPolicyState::Some { .. }, IamPolicyState::None) => IamPolicyStateDiff::Removed,
(
IamPolicyState::Some {
name: name_current,
path: path_current,
policy_document: document_current,
policy_id_arn_version: _,
},
IamPolicyState::Some {
name: name_goal,
path: path_goal,
policy_document: document_goal,
policy_id_arn_version: _,
},
) => {
let name_diff = if name_current != name_goal {
Some((name_current.clone(), name_goal.clone()))
} else {
None
};
let path_diff = if path_current != path_goal {
Some((path_current.clone(), path_goal.clone()))
} else {
None
};
if name_diff.is_none() && path_diff.is_none() {
if document_current == document_goal {
IamPolicyStateDiff::InSyncExists
} else {
IamPolicyStateDiff::DocumentModified {
document_current: document_current.clone(),
document_goal: document_goal.clone(),
}
}
} else {
IamPolicyStateDiff::NameOrPathModified {
name_diff,
path_diff,
}
}
}
};
Ok(diff)
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_policy/iam_policy_state.rs | examples/envman/src/items/peace_aws_iam_policy/iam_policy_state.rs | use std::fmt;
use peace::cfg::state::Generated;
use serde::{Deserialize, Serialize};
use crate::items::peace_aws_iam_policy::model::PolicyIdArnVersion;
#[cfg(feature = "output_progress")]
use peace::item_interaction_model::ItemLocationState;
/// Instance profile state.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum IamPolicyState {
/// Instance profile does not exist.
None,
/// Instance profile exists.
Some {
/// Instance profile name.
///
/// Alphanumeric characters and `_+=,.@-` are allowed.
///
/// TODO: newtype + proc macro.
name: String,
/// String that begins and ends with a forward slash.
///
/// Defaults to `/`.
///
/// e.g. `/demo/`
#[serde(default = "path_default")]
path: String,
/// Policy document to use.
policy_document: String,
/// The stable and unique IDs identifying the policy.
policy_id_arn_version: Generated<PolicyIdArnVersion>,
},
}
impl IamPolicyState {
/// Returns the `policy_id_arn_version` if it exists.
pub fn policy_id_arn_version(&self) -> Option<String> {
if let IamPolicyState::Some {
policy_id_arn_version: Generated::Value(policy_id_arn_version),
..
} = self
{
Some(policy_id_arn_version.arn().to_string())
} else {
None
}
}
}
fn path_default() -> String {
String::from("/")
}
impl fmt::Display for IamPolicyState {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::None => "does not exist".fmt(f),
Self::Some {
name,
path,
policy_document: _,
policy_id_arn_version,
} => {
match policy_id_arn_version {
Generated::Tbd => write!(f, "`{path}{name}` should exist"),
Generated::Value(policy_id_arn_version) => {
let arn = policy_id_arn_version.arn();
// https://console.aws.amazon.com/iam/home#/policies/arn:aws:iam::$acc_number:policy/demo
write!(
f,
"exists at https://console.aws.amazon.com/iam/home#/policies/{arn}"
)
}
}
}
}
}
}
#[cfg(feature = "output_progress")]
impl<'state> From<&'state IamPolicyState> for ItemLocationState {
fn from(iam_policy_state: &'state IamPolicyState) -> ItemLocationState {
match iam_policy_state {
IamPolicyState::Some { .. } => ItemLocationState::Exists,
IamPolicyState::None => ItemLocationState::NotExists,
}
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_policy/iam_policy_item.rs | examples/envman/src/items/peace_aws_iam_policy/iam_policy_item.rs | use std::marker::PhantomData;
use aws_config::BehaviorVersion;
use peace::{
cfg::{async_trait, ApplyCheck, FnCtx, Item},
item_model::ItemId,
params::Params,
resource_rt::{resources::ts::Empty, Resources},
};
use crate::items::peace_aws_iam_policy::{
IamPolicyApplyFns, IamPolicyData, IamPolicyError, IamPolicyParams, IamPolicyState,
IamPolicyStateCurrentFn, IamPolicyStateDiff, IamPolicyStateDiffFn, IamPolicyStateGoalFn,
};
/// Item to create an IAM instance profile and IAM role.
///
/// In sequence, this will:
///
/// * Create the IAM Role.
/// * Create the instance profile.
/// * Add the IAM role to the instance profile.
///
/// The `Id` type parameter is needed for each instance profile params to be a
/// distinct type.
///
/// # Type Parameters
///
/// * `Id`: A zero-sized type used to distinguish different instance profile
/// parameters from each other.
#[derive(Debug)]
pub struct IamPolicyItem<Id> {
/// ID of the instance profile item.
item_id: ItemId,
/// Marker for unique instance profile parameters type.
marker: PhantomData<Id>,
}
impl<Id> IamPolicyItem<Id> {
/// Returns a new `IamPolicyItem`.
pub fn new(item_id: ItemId) -> Self {
Self {
item_id,
marker: PhantomData,
}
}
}
impl<Id> Clone for IamPolicyItem<Id> {
fn clone(&self) -> Self {
Self {
item_id: self.item_id.clone(),
marker: PhantomData,
}
}
}
#[async_trait(?Send)]
impl<Id> Item for IamPolicyItem<Id>
where
Id: Send + Sync + 'static,
{
type Data<'exec> = IamPolicyData<'exec, Id>;
type Error = IamPolicyError;
type Params<'exec> = IamPolicyParams<Id>;
type State = IamPolicyState;
type StateDiff = IamPolicyStateDiff;
fn id(&self) -> &ItemId {
&self.item_id
}
async fn setup(&self, resources: &mut Resources<Empty>) -> Result<(), IamPolicyError> {
if !resources.contains::<aws_sdk_iam::Client>() {
let sdk_config = aws_config::load_defaults(BehaviorVersion::latest()).await;
let client = aws_sdk_iam::Client::new(&sdk_config);
resources.insert(client);
}
Ok(())
}
#[cfg(feature = "item_state_example")]
fn state_example(params: &Self::Params<'_>, _data: Self::Data<'_>) -> Self::State {
use peace::cfg::state::Generated;
use crate::items::peace_aws_iam_policy::model::PolicyIdArnVersion;
let name = params.name().to_string();
let path = params.path().to_string();
let policy_document = params.policy_document().to_string();
let policy_id_arn_version = {
let aws_account_id = "123456789012"; // Can this be looked up without calling AWS?
let id = String::from("iam_role_example_id");
let arn = format!("arn:aws:iam::{aws_account_id}:policy/{name}");
let version = String::from("v1");
Generated::Value(PolicyIdArnVersion::new(id, arn, version))
};
IamPolicyState::Some {
name,
path,
policy_document,
policy_id_arn_version,
}
}
async fn try_state_current(
fn_ctx: FnCtx<'_>,
params_partial: &<Self::Params<'_> as Params>::Partial,
data: IamPolicyData<'_, Id>,
) -> Result<Option<Self::State>, IamPolicyError> {
IamPolicyStateCurrentFn::try_state_current(fn_ctx, params_partial, data).await
}
async fn state_current(
fn_ctx: FnCtx<'_>,
params: &Self::Params<'_>,
data: IamPolicyData<'_, Id>,
) -> Result<Self::State, IamPolicyError> {
IamPolicyStateCurrentFn::state_current(fn_ctx, params, data).await
}
async fn try_state_goal(
fn_ctx: FnCtx<'_>,
params_partial: &<Self::Params<'_> as Params>::Partial,
data: IamPolicyData<'_, Id>,
) -> Result<Option<Self::State>, IamPolicyError> {
IamPolicyStateGoalFn::try_state_goal(fn_ctx, params_partial, data).await
}
async fn state_goal(
fn_ctx: FnCtx<'_>,
params: &Self::Params<'_>,
data: IamPolicyData<'_, Id>,
) -> Result<Self::State, IamPolicyError> {
IamPolicyStateGoalFn::state_goal(fn_ctx, params, data).await
}
async fn state_diff(
_params_partial: &<Self::Params<'_> as Params>::Partial,
_data: Self::Data<'_>,
state_current: &Self::State,
state_goal: &Self::State,
) -> Result<Self::StateDiff, IamPolicyError> {
IamPolicyStateDiffFn::state_diff(state_current, state_goal).await
}
async fn state_clean(
_params_partial: &<Self::Params<'_> as Params>::Partial,
_data: Self::Data<'_>,
) -> Result<Self::State, IamPolicyError> {
Ok(IamPolicyState::None)
}
async fn apply_check(
params: &Self::Params<'_>,
data: Self::Data<'_>,
state_current: &Self::State,
state_target: &Self::State,
diff: &Self::StateDiff,
) -> Result<ApplyCheck, Self::Error> {
IamPolicyApplyFns::<Id>::apply_check(params, data, state_current, state_target, diff).await
}
async fn apply_dry(
fn_ctx: FnCtx<'_>,
params: &Self::Params<'_>,
data: Self::Data<'_>,
state_current: &Self::State,
state_target: &Self::State,
diff: &Self::StateDiff,
) -> Result<Self::State, Self::Error> {
IamPolicyApplyFns::<Id>::apply_dry(fn_ctx, params, data, state_current, state_target, diff)
.await
}
async fn apply(
fn_ctx: FnCtx<'_>,
params: &Self::Params<'_>,
data: Self::Data<'_>,
state_current: &Self::State,
state_target: &Self::State,
diff: &Self::StateDiff,
) -> Result<Self::State, Self::Error> {
IamPolicyApplyFns::<Id>::apply(fn_ctx, params, data, state_current, state_target, diff)
.await
}
#[cfg(feature = "item_interactions")]
fn interactions(
params: &Self::Params<'_>,
_data: Self::Data<'_>,
) -> Vec<peace::item_interaction_model::ItemInteraction> {
use peace::item_interaction_model::{
ItemInteractionPush, ItemLocation, ItemLocationAncestors,
};
let iam_policy_name = format!("📝 {}", params.name());
let item_interaction = ItemInteractionPush::new(
ItemLocationAncestors::new(vec![ItemLocation::localhost()]),
ItemLocationAncestors::new(vec![
ItemLocation::group(String::from("IAM")),
ItemLocation::group(String::from("Policies")),
ItemLocation::path(iam_policy_name),
]),
)
.into();
vec![item_interaction]
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_policy/iam_policy_error.rs | examples/envman/src/items/peace_aws_iam_policy/iam_policy_error.rs | use aws_sdk_iam::{
error::SdkError,
operation::{
create_policy::CreatePolicyError, create_policy_version::CreatePolicyVersionError,
delete_policy::DeletePolicyError, delete_policy_version::DeletePolicyVersionError,
get_policy::GetPolicyError, get_policy_version::GetPolicyVersionError,
list_policies::ListPoliciesError, list_policy_versions::ListPolicyVersionsError,
},
};
#[cfg(feature = "error_reporting")]
use peace::miette::{self, SourceSpan};
/// Error while managing instance profile state.
#[cfg_attr(feature = "error_reporting", derive(peace::miette::Diagnostic))]
#[derive(Debug, thiserror::Error)]
pub enum IamPolicyError {
/// Policy name or path was attempted to be modified.
#[error("Policy name or path modification is not supported.")]
NameOrPathModificationNotSupported {
/// Whether the name has been changed.
name_diff: Option<(String, String)>,
/// Whether the path has been changed.
path_diff: Option<(String, String)>,
},
/// A `peace` runtime error occurred.
#[error("A `peace` runtime error occurred.")]
PeaceRtError(
#[cfg_attr(feature = "error_reporting", diagnostic_source)]
#[source]
#[from]
peace::rt_model::Error,
),
/// Failed to list policies.
#[error("Failed to list policies.")]
#[cfg_attr(
feature = "error_reporting",
diagnostic(help("Make sure you are connected to the internet and try again."))
)]
PoliciesListError {
/// Path prefix used to list policies
path: String,
/// Error description from AWS error.
#[cfg(feature = "error_reporting")]
#[source_code]
aws_desc: String,
/// Span of the description to highlight.
#[cfg(feature = "error_reporting")]
#[label]
aws_desc_span: SourceSpan,
/// Underlying error.
#[source]
error: Box<SdkError<ListPoliciesError>>,
},
/// Failed to decode URL-encoded policy document.
#[error("Failed to decode URL-encoded policy document.")]
PolicyDocumentNonUtf8 {
/// Policy friendly name.
policy_name: String,
/// Policy path.
policy_path: String,
/// The URL encoded document from the AWS `get_policy_version` call.
url_encoded_document: String,
/// Underlying error.
#[source]
error: std::string::FromUtf8Error,
},
/// Failed to create policy.
#[error("Failed to create policy.")]
#[cfg_attr(
feature = "error_reporting",
diagnostic(help("Make sure you are connected to the internet and try again."))
)]
PolicyCreateError {
/// Policy friendly name.
policy_name: String,
/// Policy path.
policy_path: String,
/// Error description from AWS error.
#[cfg(feature = "error_reporting")]
#[source_code]
aws_desc: String,
/// Span of the description to highlight.
#[cfg(feature = "error_reporting")]
#[label]
aws_desc_span: SourceSpan,
/// Underlying error.
#[source]
error: Box<SdkError<CreatePolicyError>>,
},
/// Failed to discover policy.
#[error("Failed to discover policy.")]
#[cfg_attr(
feature = "error_reporting",
diagnostic(help("Make sure you are connected to the internet and try again."))
)]
PolicyGetError {
/// Expected policy friendly name.
policy_name: String,
/// Policy path.
policy_path: String,
/// Error description from AWS error.
#[cfg(feature = "error_reporting")]
#[source_code]
aws_desc: String,
/// Span of the description to highlight.
#[cfg(feature = "error_reporting")]
#[label]
aws_desc_span: SourceSpan,
/// Underlying error.
#[source]
error: Box<SdkError<GetPolicyError>>,
},
/// Failed to create policy version.
#[error("Failed to create policy version.")]
#[cfg_attr(
feature = "error_reporting",
diagnostic(help("Make sure you are connected to the internet and try again."))
)]
PolicyVersionCreateError {
/// Policy friendly name.
policy_name: String,
/// Policy path.
policy_path: String,
/// Error description from AWS error.
#[cfg(feature = "error_reporting")]
#[source_code]
aws_desc: String,
/// Span of the description to highlight.
#[cfg(feature = "error_reporting")]
#[label]
aws_desc_span: SourceSpan,
/// Underlying error.
#[source]
error: Box<SdkError<CreatePolicyVersionError>>,
},
/// Failed to delete policy version.
#[error("Failed to delete policy version.")]
#[cfg_attr(
feature = "error_reporting",
diagnostic(help("Make sure you are connected to the internet and try again."))
)]
PolicyVersionDeleteError {
/// Policy friendly name.
policy_name: String,
/// Policy path.
policy_path: String,
/// Version ID of the policy version to delete.
version: String,
/// Error description from AWS error.
#[cfg(feature = "error_reporting")]
#[source_code]
aws_desc: String,
/// Span of the description to highlight.
#[cfg(feature = "error_reporting")]
#[label]
aws_desc_span: SourceSpan,
/// Underlying error.
#[source]
error: Box<SdkError<DeletePolicyVersionError>>,
},
/// Failed to get policy version.
#[error("Failed to get policy version.")]
#[cfg_attr(
feature = "error_reporting",
diagnostic(help("Make sure you are connected to the internet and try again."))
)]
PolicyVersionGetError {
/// Policy friendly name.
policy_name: String,
/// Policy path.
policy_path: String,
/// Error description from AWS error.
#[cfg(feature = "error_reporting")]
#[source_code]
aws_desc: String,
/// Span of the description to highlight.
#[cfg(feature = "error_reporting")]
#[label]
aws_desc_span: SourceSpan,
/// Underlying error.
#[source]
error: Box<SdkError<GetPolicyVersionError>>,
},
/// Failed to discover policy.
#[error("Failed to discover policy.")]
#[cfg_attr(
feature = "error_reporting",
diagnostic(help("Make sure you are connected to the internet and try again."))
)]
PolicyVersionsListError {
/// Expected policy friendly name.
policy_name: String,
/// Policy path.
policy_path: String,
/// Error description from AWS error.
#[cfg(feature = "error_reporting")]
#[source_code]
aws_desc: String,
/// Span of the description to highlight.
#[cfg(feature = "error_reporting")]
#[label]
aws_desc_span: SourceSpan,
/// Underlying error.
#[source]
error: Box<SdkError<ListPolicyVersionsError>>,
},
/// Policy existed when listing policies, but did not exist when retrieving
/// details.
#[error("Policy details failed to be retrieved.")]
#[cfg_attr(
feature = "error_reporting",
diagnostic(help("Someone may have deleted it, please try again."))
)]
PolicyNotFoundAfterList {
/// Expected policy friendly name.
policy_name: String,
/// Policy path.
policy_path: String,
/// Policy stable ID.
policy_id: String,
/// Policy ARN.
policy_arn: String,
/// Error description from AWS error.
#[cfg(feature = "error_reporting")]
#[source_code]
aws_desc: String,
/// Span of the description to highlight.
#[cfg(feature = "error_reporting")]
#[label]
aws_desc_span: SourceSpan,
},
/// Failed to delete policy.
#[error("Failed to delete policy.")]
#[cfg_attr(
feature = "error_reporting",
diagnostic(help("Make sure you are connected to the internet and try again."))
)]
PolicyDeleteError {
/// Policy friendly name.
policy_name: String,
/// Policy path.
policy_path: String,
/// Policy stable ID.
policy_id: String,
/// Policy ARN.
policy_arn: String,
/// Error description from AWS error.
#[cfg(feature = "error_reporting")]
#[source_code]
aws_desc: String,
/// Span of the description to highlight.
#[cfg(feature = "error_reporting")]
#[label]
aws_desc_span: SourceSpan,
/// Underlying error.
#[source]
error: Box<SdkError<DeletePolicyError>>,
},
/// User changed the policy name or path, but AWS does not support changing
/// this.
#[error("Policy name or path cannot be modified, as it is not supported by AWS.")]
PolicyModificationNotSupported {
/// Name diff.
name_diff: Option<(String, String)>,
/// Path diff.
path_diff: Option<(String, String)>,
},
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_policy/model.rs | examples/envman/src/items/peace_aws_iam_policy/model.rs | pub use self::policy_id_arn_version::PolicyIdArnVersion;
mod policy_id_arn_version;
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_policy/iam_policy_apply_fns.rs | examples/envman/src/items/peace_aws_iam_policy/iam_policy_apply_fns.rs | use std::marker::PhantomData;
use aws_sdk_iam::{error::SdkError, operation::list_policy_versions::ListPolicyVersionsError};
use peace::cfg::{state::Generated, ApplyCheck, FnCtx};
#[cfg(feature = "output_progress")]
use peace::progress_model::{ProgressLimit, ProgressMsgUpdate};
use crate::items::peace_aws_iam_policy::{
model::PolicyIdArnVersion, IamPolicyData, IamPolicyError, IamPolicyParams, IamPolicyState,
IamPolicyStateDiff,
};
/// ApplyFns for the instance profile state.
#[derive(Debug)]
pub struct IamPolicyApplyFns<Id>(PhantomData<Id>);
impl<Id> IamPolicyApplyFns<Id>
where
Id: Send + Sync + 'static,
{
pub async fn apply_check(
_params: &IamPolicyParams<Id>,
_data: IamPolicyData<'_, Id>,
state_current: &IamPolicyState,
_state_goal: &IamPolicyState,
diff: &IamPolicyStateDiff,
) -> Result<ApplyCheck, IamPolicyError> {
match diff {
IamPolicyStateDiff::Added | IamPolicyStateDiff::DocumentModified { .. } => {
let apply_check = {
#[cfg(not(feature = "output_progress"))]
{
ApplyCheck::ExecRequired
}
#[cfg(feature = "output_progress")]
{
let progress_limit = ProgressLimit::Steps(3);
ApplyCheck::ExecRequired { progress_limit }
}
};
Ok(apply_check)
}
IamPolicyStateDiff::Removed => {
let apply_check = match state_current {
IamPolicyState::None => ApplyCheck::ExecNotRequired,
IamPolicyState::Some {
name: _,
path: _,
policy_document: _,
policy_id_arn_version,
} => {
let mut steps_required = 0;
if matches!(policy_id_arn_version, Generated::Value(_)) {
steps_required += 1;
}
if steps_required == 0 {
ApplyCheck::ExecNotRequired
} else {
#[cfg(not(feature = "output_progress"))]
{
ApplyCheck::ExecRequired
}
#[cfg(feature = "output_progress")]
{
let progress_limit = ProgressLimit::Steps(steps_required);
ApplyCheck::ExecRequired { progress_limit }
}
}
}
};
Ok(apply_check)
}
IamPolicyStateDiff::NameOrPathModified {
name_diff,
path_diff,
} => Err(IamPolicyError::PolicyModificationNotSupported {
name_diff: name_diff.clone(),
path_diff: path_diff.clone(),
}),
IamPolicyStateDiff::InSyncExists => {
// Hack: Remove this when referential param values is implemented.
let IamPolicyState::Some {
policy_id_arn_version,
..
} = state_current
else {
unreachable!()
};
let Generated::Value(_policy_id_version_arn) = policy_id_arn_version else {
unreachable!()
};
Ok(ApplyCheck::ExecNotRequired)
}
IamPolicyStateDiff::InSyncDoesNotExist => Ok(ApplyCheck::ExecNotRequired),
}
}
pub async fn apply_dry(
_fn_ctx: FnCtx<'_>,
_params: &IamPolicyParams<Id>,
_iam_policy_data: IamPolicyData<'_, Id>,
_state_current: &IamPolicyState,
state_goal: &IamPolicyState,
_diff: &IamPolicyStateDiff,
) -> Result<IamPolicyState, IamPolicyError> {
Ok(state_goal.clone())
}
pub async fn apply(
#[cfg(not(feature = "output_progress"))] _fn_ctx: FnCtx<'_>,
#[cfg(feature = "output_progress")] fn_ctx: FnCtx<'_>,
_params: &IamPolicyParams<Id>,
data: IamPolicyData<'_, Id>,
state_current: &IamPolicyState,
state_goal: &IamPolicyState,
diff: &IamPolicyStateDiff,
) -> Result<IamPolicyState, IamPolicyError> {
#[cfg(feature = "output_progress")]
let progress_sender = &fn_ctx.progress_sender;
match diff {
IamPolicyStateDiff::Added => match state_goal {
IamPolicyState::None => {
panic!("`IamPolicyApplyFns::exec` called with state_goal being None.");
}
IamPolicyState::Some {
name,
path,
policy_document,
policy_id_arn_version: _,
} => {
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from("creating policy")));
let create_policy_output = data
.client()
.create_policy()
.policy_name(name)
.path(path)
.policy_document(policy_document)
.send()
.await
.map_err(|error| {
let policy_name = name.to_string();
let policy_path = path.to_string();
#[cfg(feature = "error_reporting")]
let (aws_desc, aws_desc_span) = crate::items::aws_error_desc!(&error);
let error = Box::new(error);
IamPolicyError::PolicyCreateError {
policy_name,
policy_path,
#[cfg(feature = "error_reporting")]
aws_desc,
#[cfg(feature = "error_reporting")]
aws_desc_span,
error,
}
})?;
#[cfg(feature = "output_progress")]
progress_sender.inc(1, ProgressMsgUpdate::Set(String::from("policy created")));
let policy = create_policy_output
.policy()
.expect("Expected policy to be Some when create_policy is successful.");
let policy_id = policy
.policy_id()
.expect("Expected policy id to be Some when create_policy is successful.")
.to_string();
let policy_arn = policy
.arn()
.expect("Expected policy ARN to be Some when create_policy is successful.")
.to_string();
let policy_version = policy
.default_version_id()
.expect(
"Expected policy default version ID to be Some \
when create_policy is successful.",
)
.to_string();
let policy_id_arn_version =
PolicyIdArnVersion::new(policy_id, policy_arn, policy_version);
let state_applied = IamPolicyState::Some {
name: name.to_string(),
path: path.clone(),
policy_document: policy_document.clone(),
policy_id_arn_version: Generated::Value(policy_id_arn_version),
};
Ok(state_applied)
}
},
IamPolicyStateDiff::Removed => {
match state_current {
IamPolicyState::None => {}
IamPolicyState::Some {
name,
path,
policy_document: _,
policy_id_arn_version,
} => {
if let Generated::Value(policy_id_arn_version) = policy_id_arn_version {
let client = data.client();
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from(
"discovering policy versions",
)));
let list_policy_versions_result = client
.list_policy_versions()
.policy_arn(policy_id_arn_version.arn())
.send()
.await;
#[cfg(feature = "output_progress")]
progress_sender.inc(
1,
ProgressMsgUpdate::Set(String::from("policy versions discovered")),
);
// Need to delete all of the non-default versions individually.
match list_policy_versions_result {
Ok(list_policy_versions_output) => {
let policy_versions = list_policy_versions_output.versions();
let non_default_policy_versions =
policy_versions.iter().filter(|policy_version| {
!policy_version.is_default_version()
});
for policy_version in non_default_policy_versions {
let version_id = policy_version.version_id().expect(
"Expected policy version version ID to be Some.",
);
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from(
"deleting policy versions",
)));
client
.delete_policy_version()
.policy_arn(policy_id_arn_version.arn())
.version_id(version_id)
.send()
.await
.map_err(|error| {
#[cfg(feature = "error_reporting")]
let (aws_desc, aws_desc_span) =
crate::items::aws_error_desc!(&error);
let error = Box::new(error);
IamPolicyError::PolicyVersionDeleteError {
policy_name: name.to_string(),
policy_path: path.to_string(),
version: version_id.to_string(),
#[cfg(feature = "error_reporting")]
aws_desc,
#[cfg(feature = "error_reporting")]
aws_desc_span,
error,
}
})?;
#[cfg(feature = "output_progress")]
progress_sender.inc(
1,
ProgressMsgUpdate::Set(String::from(
"policy versions deleted",
)),
);
}
}
Err(error) => {
#[cfg(feature = "error_reporting")]
let (aws_desc, aws_desc_span) =
crate::items::aws_error_desc!(&error);
match &error {
SdkError::ServiceError(service_error) => {
match service_error.err() {
ListPolicyVersionsError::NoSuchEntityException(
_,
) => {
return Err(
IamPolicyError::PolicyNotFoundAfterList {
policy_name: name.to_string(),
policy_path: path.to_string(),
policy_id: policy_id_arn_version
.id()
.to_string(),
policy_arn: policy_id_arn_version
.arn()
.to_string(),
#[cfg(feature = "error_reporting")]
aws_desc,
#[cfg(feature = "error_reporting")]
aws_desc_span,
},
);
}
_ => {
let error = Box::new(error);
return Err(
IamPolicyError::PolicyVersionsListError {
policy_name: name.to_string(),
policy_path: path.to_string(),
#[cfg(feature = "error_reporting")]
aws_desc,
#[cfg(feature = "error_reporting")]
aws_desc_span,
error,
},
);
}
}
}
_ => {
let error = Box::new(error);
return Err(IamPolicyError::PolicyVersionsListError {
policy_name: name.to_string(),
policy_path: path.to_string(),
#[cfg(feature = "error_reporting")]
aws_desc,
#[cfg(feature = "error_reporting")]
aws_desc_span,
error,
});
}
}
}
};
// The default version is deleted along with the policy.
#[cfg(feature = "output_progress")]
progress_sender
.tick(ProgressMsgUpdate::Set(String::from("deleting policy")));
client
.delete_policy()
.policy_arn(policy_id_arn_version.arn())
.send()
.await
.map_err(|error| {
let policy_name = name.to_string();
let policy_path = path.to_string();
let policy_id = policy_id_arn_version.id().to_string();
let policy_arn = policy_id_arn_version.arn().to_string();
#[cfg(feature = "error_reporting")]
let (aws_desc, aws_desc_span) =
crate::items::aws_error_desc!(&error);
let error = Box::new(error);
IamPolicyError::PolicyDeleteError {
policy_name,
policy_path,
policy_id,
policy_arn,
#[cfg(feature = "error_reporting")]
aws_desc,
#[cfg(feature = "error_reporting")]
aws_desc_span,
error,
}
})?;
#[cfg(feature = "output_progress")]
progress_sender
.inc(1, ProgressMsgUpdate::Set(String::from("policy deleted")));
}
}
}
let state_applied = state_goal.clone();
Ok(state_applied)
}
IamPolicyStateDiff::DocumentModified { .. } => match state_goal {
IamPolicyState::None => {
panic!("`IamPolicyApplyFns::exec` called with state_goal being None.");
}
IamPolicyState::Some {
name,
path,
policy_document,
policy_id_arn_version: _,
} => {
let IamPolicyState::Some {
policy_id_arn_version: Generated::Value(policy_id_arn_version),
..
} = state_current
else {
panic!("Expected policy ID and ARN to exist when diff is modified.");
};
let policy_arn = policy_id_arn_version.arn();
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from(
"creating policy version",
)));
let create_policy_output = data
.client()
.create_policy_version()
.policy_arn(policy_arn)
.policy_document(policy_document)
.send()
.await
.map_err(|error| {
let policy_name = name.to_string();
let policy_path = path.to_string();
#[cfg(feature = "error_reporting")]
let (aws_desc, aws_desc_span) = crate::items::aws_error_desc!(&error);
let error = Box::new(error);
IamPolicyError::PolicyVersionCreateError {
policy_name,
policy_path,
#[cfg(feature = "error_reporting")]
aws_desc,
#[cfg(feature = "error_reporting")]
aws_desc_span,
error,
}
})?;
#[cfg(feature = "output_progress")]
progress_sender.inc(
1,
ProgressMsgUpdate::Set(String::from("policy version created")),
);
let policy_version = create_policy_output.policy_version().expect(
"Expected policy_version to be Some when create_policy is successful.",
);
let policy_id = policy_id_arn_version.id().to_string();
let policy_arn = policy_id_arn_version.arn().to_string();
let policy_version_id = policy_version
.version_id()
.expect("Expected policy_version version_id to be Some when create_policy is successful.")
.to_string();
let policy_id_arn_version =
PolicyIdArnVersion::new(policy_id, policy_arn, policy_version_id);
let state_applied = IamPolicyState::Some {
name: name.to_string(),
path: path.clone(),
policy_document: policy_document.clone(),
policy_id_arn_version: Generated::Value(policy_id_arn_version),
};
Ok(state_applied)
}
},
IamPolicyStateDiff::InSyncExists | IamPolicyStateDiff::InSyncDoesNotExist => {
unreachable!(
"`IamPolicyApplyFns::exec` should never be called when state is in sync."
);
}
IamPolicyStateDiff::NameOrPathModified {
name_diff,
path_diff,
} => Err(IamPolicyError::NameOrPathModificationNotSupported {
name_diff: name_diff.clone(),
path_diff: path_diff.clone(),
}),
}
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_policy/iam_policy_state_current_fn.rs | examples/envman/src/items/peace_aws_iam_policy/iam_policy_state_current_fn.rs | use std::marker::PhantomData;
use aws_sdk_iam::{error::SdkError, operation::get_policy::GetPolicyError};
use peace::{
cfg::{state::Generated, FnCtx},
params::Params,
};
use crate::items::peace_aws_iam_policy::{
model::PolicyIdArnVersion, IamPolicyData, IamPolicyError, IamPolicyParams, IamPolicyState,
};
#[cfg(feature = "output_progress")]
use peace::progress_model::ProgressMsgUpdate;
/// Reads the current state of the instance profile state.
#[derive(Debug)]
pub struct IamPolicyStateCurrentFn<Id>(PhantomData<Id>);
impl<Id> IamPolicyStateCurrentFn<Id> {
/// Finds a policy with the given name and path.
pub(crate) async fn policy_find(
#[cfg(not(feature = "output_progress"))] _fn_ctx: FnCtx<'_>,
#[cfg(feature = "output_progress")] fn_ctx: FnCtx<'_>,
client: &aws_sdk_iam::Client,
name: &str,
path: &str,
) -> Result<Option<(String, String)>, IamPolicyError> {
#[cfg(feature = "output_progress")]
let progress_sender = &fn_ctx.progress_sender;
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from("listing policies")));
let list_policies_output = client
.list_policies()
.scope(aws_sdk_iam::types::PolicyScopeType::Local)
.path_prefix(path)
.send()
.await
.map_err(|error| {
#[cfg(feature = "error_reporting")]
let (aws_desc, aws_desc_span) = crate::items::aws_error_desc!(&error);
let error = Box::new(error);
IamPolicyError::PoliciesListError {
path: path.to_string(),
#[cfg(feature = "error_reporting")]
aws_desc,
#[cfg(feature = "error_reporting")]
aws_desc_span,
error,
}
})?;
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from("finding policy")));
let policy_id_arn_version = {
list_policies_output
.policies()
.iter()
.find(|policy| {
let name_matches = policy
.policy_name()
.filter(|policy_name| *policy_name == name)
.is_some();
let path_matches = policy
.path()
.filter(|policy_path| *policy_path == path)
.is_some();
name_matches && path_matches
})
.map(|policy| {
let policy_id = policy
.policy_id()
.expect("Expected policy id to be Some.")
.to_string();
let policy_arn = policy.arn().expect("Expected ARN to be Some.").to_string();
(policy_id, policy_arn)
})
};
#[cfg(feature = "output_progress")]
{
let message = if policy_id_arn_version.is_some() {
"policy found"
} else {
"policy not found"
};
progress_sender.tick(ProgressMsgUpdate::Set(String::from(message)));
}
Ok(policy_id_arn_version)
}
}
impl<Id> IamPolicyStateCurrentFn<Id>
where
Id: Send + Sync,
{
pub async fn try_state_current(
fn_ctx: FnCtx<'_>,
params_partial: &<IamPolicyParams<Id> as Params>::Partial,
data: IamPolicyData<'_, Id>,
) -> Result<Option<IamPolicyState>, IamPolicyError> {
let name = params_partial.name();
let path = params_partial.path();
if let Some((name, path)) = name.zip(path) {
Self::state_current_internal(fn_ctx, data, name, path)
.await
.map(Some)
} else {
Ok(None)
}
}
pub async fn state_current(
fn_ctx: FnCtx<'_>,
params: &IamPolicyParams<Id>,
data: IamPolicyData<'_, Id>,
) -> Result<IamPolicyState, IamPolicyError> {
let name = params.name();
let path = params.path();
Self::state_current_internal(fn_ctx, data, name, path).await
}
async fn state_current_internal(
fn_ctx: FnCtx<'_>,
data: IamPolicyData<'_, Id>,
name: &str,
path: &str,
) -> Result<IamPolicyState, IamPolicyError> {
let client = data.client();
let policy_id_arn_version = Self::policy_find(fn_ctx, client, name, path).await?;
if let Some((policy_id, policy_arn)) = policy_id_arn_version {
#[cfg(feature = "output_progress")]
let progress_sender = &fn_ctx.progress_sender;
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from("fetching policy")));
let get_policy_result = client.get_policy().policy_arn(&policy_arn).send().await;
let (policy_name, policy_path, policy_id_arn_version) = match get_policy_result {
Ok(get_policy_output) => {
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from("policy fetched")));
let policy = get_policy_output
.policy()
.expect("Expected Policy to exist when get_policy is successful");
let policy_name = policy
.policy_name()
.expect("Expected policy name to be Some when get_policy is successful.")
.to_string();
let policy_path = policy
.path()
.expect("Expected path to be Some when get_policy is successful.")
.to_string();
let policy_id = policy
.policy_id()
.expect("Expected policy id to be Some when get_policy is successful.")
.to_string();
let policy_arn = policy
.arn()
.expect("Expected policy ARN to be Some when get_policy is successful.")
.to_string();
let policy_version = policy
.default_version_id()
.expect(
"Expected policy default version to be Some when \
get_policy is successful.",
)
.to_string();
let policy_id_arn_version =
PolicyIdArnVersion::new(policy_id, policy_arn, policy_version);
(policy_name, policy_path, policy_id_arn_version)
}
Err(error) => {
#[cfg(feature = "output_progress")]
progress_sender
.tick(ProgressMsgUpdate::Set(String::from("policy not fetched")));
#[cfg(feature = "error_reporting")]
let (aws_desc, aws_desc_span) = crate::items::aws_error_desc!(&error);
match &error {
SdkError::ServiceError(service_error) => match service_error.err() {
GetPolicyError::NoSuchEntityException(_) => {
return Err(IamPolicyError::PolicyNotFoundAfterList {
policy_name: name.to_string(),
policy_path: path.to_string(),
policy_id: policy_id.to_string(),
policy_arn: policy_arn.to_string(),
#[cfg(feature = "error_reporting")]
aws_desc,
#[cfg(feature = "error_reporting")]
aws_desc_span,
});
}
_ => {
let error = Box::new(error);
return Err(IamPolicyError::PolicyGetError {
policy_name: name.to_string(),
policy_path: path.to_string(),
#[cfg(feature = "error_reporting")]
aws_desc,
#[cfg(feature = "error_reporting")]
aws_desc_span,
error,
});
}
},
_ => {
let error = Box::new(error);
return Err(IamPolicyError::PolicyGetError {
policy_name: name.to_string(),
policy_path: path.to_string(),
#[cfg(feature = "error_reporting")]
aws_desc,
#[cfg(feature = "error_reporting")]
aws_desc_span,
error,
});
}
}
}
};
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from(
"fetching policy version",
)));
let get_policy_version_output = client
.get_policy_version()
.policy_arn(policy_arn)
.version_id(policy_id_arn_version.version())
.send()
.await
.map_err(|error| {
#[cfg(feature = "error_reporting")]
let (aws_desc, aws_desc_span) = crate::items::aws_error_desc!(&error);
let error = Box::new(error);
IamPolicyError::PolicyVersionGetError {
policy_name: policy_name.clone(),
policy_path: policy_path.clone(),
#[cfg(feature = "error_reporting")]
aws_desc,
#[cfg(feature = "error_reporting")]
aws_desc_span,
error,
}
})?;
#[cfg(feature = "output_progress")]
progress_sender.tick(ProgressMsgUpdate::Set(String::from(
"policy version fetched",
)));
let policy_document = get_policy_version_output
.policy_version()
.and_then(|policy_version| policy_version.document())
.map(|url_encoded_document| {
urlencoding::decode(url_encoded_document)
.map(|document| document.to_string())
.map_err(|error| IamPolicyError::PolicyDocumentNonUtf8 {
policy_name: policy_name.clone(),
policy_path: policy_path.clone(),
url_encoded_document: url_encoded_document.to_string(),
error,
})
})
.expect("Expected policy version document to exist.")?;
let state_current = IamPolicyState::Some {
name: policy_name,
path: policy_path,
policy_document,
policy_id_arn_version: Generated::Value(policy_id_arn_version),
};
Ok(state_current)
} else {
Ok(IamPolicyState::None)
}
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_policy/iam_policy_state_diff.rs | examples/envman/src/items/peace_aws_iam_policy/iam_policy_state_diff.rs | use std::fmt;
use serde::{Deserialize, Serialize};
/// Diff between current (dest) and goal (src) state.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub enum IamPolicyStateDiff {
/// Policy would be added.
Added,
/// Policy would be removed.
Removed,
/// Policy would be replaced.
///
/// AWS' SDK doesn't support modifying a policy's name or path.
NameOrPathModified {
/// Whether the name has been changed.
name_diff: Option<(String, String)>,
/// Whether the path has been changed.
path_diff: Option<(String, String)>,
},
/// The policy has been modified.
DocumentModified {
/// Current policy document.
document_current: String,
/// Goal policy document.
document_goal: String,
},
/// Policy exists and is up to date.
InSyncExists,
/// Policy does not exist, which is goal.
InSyncDoesNotExist,
}
impl fmt::Display for IamPolicyStateDiff {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
IamPolicyStateDiff::Added => {
write!(f, "will be created.")
}
IamPolicyStateDiff::Removed => {
write!(f, "will be removed.")
}
IamPolicyStateDiff::DocumentModified {
document_current: _,
document_goal: _,
} => write!(f, "policy will be updated."),
IamPolicyStateDiff::NameOrPathModified {
name_diff,
path_diff,
} => match (name_diff, path_diff) {
(None, None) => {
unreachable!(
"Modified is only valid when either name or path has changed.\n\
This is a bug."
)
}
(None, Some((path_current, path_goal))) => {
write!(f, "path changed from {path_current} to {path_goal}")
}
(Some((name_current, name_goal)), None) => {
write!(f, "name changed from {name_current} to {name_goal}")
}
(Some((name_current, name_goal)), Some((path_current, path_goal))) => write!(
f,
"name and path changed from {name_current}:{path_current} to {name_goal}:{path_goal}"
),
},
IamPolicyStateDiff::InSyncExists => {
write!(f, "exists and is up to date.")
}
IamPolicyStateDiff::InSyncDoesNotExist => {
write!(f, "does not exist as intended.")
}
}
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_policy/iam_policy_params.rs | examples/envman/src/items/peace_aws_iam_policy/iam_policy_params.rs | use std::marker::PhantomData;
use derivative::Derivative;
use peace::params::Params;
use serde::{Deserialize, Serialize};
/// IamPolicy item parameters.
///
/// The `Id` type parameter is needed for each instance profile params to be a
/// distinct type.
///
/// # Type Parameters
///
/// * `Id`: A zero-sized type used to distinguish different instance profile
/// parameters from each other.
#[derive(Derivative, Params, PartialEq, Eq, Deserialize, Serialize)]
#[derivative(Clone, Debug)]
#[serde(bound = "")]
pub struct IamPolicyParams<Id> {
/// Name for both the instance profile and role.
///
/// Alphanumeric characters and `_+=,.@-` are allowed.
///
/// TODO: newtype + proc macro.
name: String,
/// Namespace for both the instance profile and role.
///
/// String that begins and ends with a forward slash.
///
/// e.g. `/demo/`
#[serde(default = "path_default")]
path: String,
/// Policy document to use.
policy_document: String,
/// Marker for unique instance profile parameters type.
marker: PhantomData<Id>,
}
fn path_default() -> String {
String::from("/")
}
impl<Id> IamPolicyParams<Id> {
pub fn new(name: String, path: String, policy_document: String) -> Self {
Self {
name,
path,
policy_document,
marker: PhantomData,
}
}
/// Returns the name for both the instance profile and role.
///
/// Alphanumeric characters and `_+=,.@-` are allowed.
pub fn name(&self) -> &str {
self.name.as_ref()
}
/// Returns the namespace for both the instance profile and role.
///
/// String that begins and ends with a forward slash.
///
/// e.g. `/demo/`
pub fn path(&self) -> &str {
self.path.as_ref()
}
/// Returns the policy document to use.
///
/// e.g.
///
/// ```json
/// {
/// "Version": "2012-10-17",
/// "Statement": [
/// {
/// "Effect": "Allow",
/// "Action": [
/// "cloudformation:Describe*",
/// "cloudformation:List*",
/// "cloudformation:Get*"
/// ],
/// "Resource": "*"
/// }
/// ]
/// }
/// ```
pub fn policy_document(&self) -> &str {
self.policy_document.as_ref()
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_policy/model/policy_id_arn_version.rs | examples/envman/src/items/peace_aws_iam_policy/model/policy_id_arn_version.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct PolicyIdArnVersion {
/// The stable and unique string identifying the policy. For more
/// information about IDs, see [IAM identifiers] in the *IAM User
/// Guide*.
///
/// [IAM identifiers]: https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html
id: String,
/// The Amazon Resource Name (ARN) specifying the policy. For more
/// information about ARNs and how to use them in policies, see [IAM
/// identifiers] in the *IAM User Guide*.
///
/// [IAM identifiers]: https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html
arn: String,
/// Policy version.
version: String,
}
impl PolicyIdArnVersion {
pub fn new(id: String, arn: String, version: String) -> Self {
Self { id, arn, version }
}
pub fn id(&self) -> &str {
self.id.as_ref()
}
pub fn arn(&self) -> &str {
self.arn.as_ref()
}
pub fn version(&self) -> &str {
self.version.as_ref()
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/cmds/env_status_cmd.rs | examples/envman/src/cmds/env_status_cmd.rs | use futures::FutureExt;
use peace::{
cmd_ctx::{CmdCtxSpsf, CmdCtxSpsfFields},
cmd_model::CmdOutcome,
fmt::{
presentable::{Heading, HeadingLevel, ListNumberedAligned},
PresentableExt,
},
rt::cmds::StatesCurrentReadCmd,
rt_model::output::OutputWrite,
};
use crate::{
cmds::{
common::{env_man_flow, workspace},
AppUploadCmd, CmdOpts, EnvCmd,
},
model::{EnvManError, EnvManFlow},
rt_model::EnvmanCmdCtxTypes,
};
/// Shows the current stored state of the environment.
#[derive(Debug)]
pub struct EnvStatusCmd;
impl EnvStatusCmd {
/// Shows the current stored state of the environment.
///
/// # Parameters
///
/// * `output`: Output to write the execution outcome.
pub async fn run<O>(output: &mut O) -> Result<(), EnvManError>
where
O: OutputWrite + Send,
EnvManError: From<<O as OutputWrite>::Error>,
{
let workspace = workspace()?;
let env_man_flow = env_man_flow(output, &workspace).await?;
match env_man_flow {
EnvManFlow::AppUpload => run!(output, AppUploadCmd),
EnvManFlow::EnvDeploy => run!(output, EnvCmd),
}
Ok(())
}
}
macro_rules! run {
($output:ident, $flow_cmd:ident) => {{
$flow_cmd::run($output, CmdOpts::default(), |cmd_ctx| {
run_with_ctx(cmd_ctx).boxed_local()
})
.await?;
}};
}
async fn run_with_ctx<O>(
cmd_ctx: &mut CmdCtxSpsf<'_, EnvmanCmdCtxTypes<O>>,
) -> Result<(), EnvManError>
where
O: OutputWrite,
EnvManError: From<<O as OutputWrite>::Error>,
{
let states_current_stored_outcome = StatesCurrentReadCmd::exec(cmd_ctx).await?;
let CmdCtxSpsf {
output,
fields: CmdCtxSpsfFields { flow, .. },
..
} = cmd_ctx;
if let Some(states_current_stored) = states_current_stored_outcome.value() {
let states_current_stored_raw_map = &***states_current_stored;
let states_current_stored_presentables: ListNumberedAligned<_, _> = flow
.graph()
.iter_insertion()
.map(|item| {
let item_id = item.id();
let state_presentable = match states_current_stored_raw_map.get(item_id) {
Some(state_current_stored) => {
format!("{state_current_stored}").left_presentable()
}
None => "<unknown>".right_presentable(),
};
(item_id, state_presentable)
})
.collect::<Vec<_>>()
.into();
output
.present(&(
Heading::new(HeadingLevel::Level1, "Current States (Stored)"),
states_current_stored_presentables,
"\n",
))
.await?;
}
if let CmdOutcome::ItemError { errors, .. } = &states_current_stored_outcome {
crate::output::item_errors_present(&mut **output, errors).await?;
}
Ok(())
}
use run;
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/cmds/cmd_opts.rs | examples/envman/src/cmds/cmd_opts.rs | /// Options to configure a `Cmd`'s output.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CmdOpts {
/// Whether or not to print the active profile.
pub profile_print: bool,
}
impl CmdOpts {
/// Sets whether or not to print the active profile.
pub fn with_profile_print(mut self, profile_print: bool) -> Self {
self.profile_print = profile_print;
self
}
}
impl Default for CmdOpts {
fn default() -> Self {
Self {
profile_print: true,
}
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/cmds/profile_list_cmd.rs | examples/envman/src/cmds/profile_list_cmd.rs | use peace::{
cmd_ctx::{CmdCtxMpnf, CmdCtxMpnfFields},
fmt::presentable::{Heading, HeadingLevel},
rt_model::output::OutputWrite,
};
use crate::{
cmds::common::workspace,
model::{EnvManError, EnvManFlow, EnvType, ProfileParamsKey, WorkspaceParamsKey},
rt_model::EnvmanCmdCtxTypes,
};
/// Command to list initialized profiles.
#[derive(Debug)]
pub struct ProfileListCmd;
impl ProfileListCmd {
/// Lists all profiles.
///
/// # Parameters
///
/// * `output`: Output to write the execution outcome.
pub async fn run<O>(output: &mut O) -> Result<(), EnvManError>
where
O: OutputWrite,
EnvManError: From<<O as OutputWrite>::Error>,
{
let cmd_ctx_builder = CmdCtxMpnf::<EnvmanCmdCtxTypes<O>>::builder()
.with_output(output.into())
.with_workspace(workspace()?.into())
.with_workspace_param::<peace::profile_model::Profile>(
WorkspaceParamsKey::Profile,
None,
)
.with_workspace_param::<EnvManFlow>(WorkspaceParamsKey::Flow, None);
let mut cmd_ctx = cmd_ctx_builder.await?;
let CmdCtxMpnf {
ref mut output,
fields:
CmdCtxMpnfFields {
profile_to_profile_params,
..
},
} = cmd_ctx;
output
.present(Heading::new(HeadingLevel::Level1, String::from("Profiles")))
.await?;
let profiles_presentable = profile_to_profile_params
.iter()
.filter_map(|(profile, profile_params)| {
let env_type = profile_params.get::<EnvType, _>(&ProfileParamsKey::EnvType);
env_type.map(|env_type| (profile, " - type: ".to_string(), env_type))
})
.collect::<Vec<_>>();
output.present(&profiles_presentable).await?;
Ok(())
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/cmds/env_goal_cmd.rs | examples/envman/src/cmds/env_goal_cmd.rs | use futures::FutureExt;
use peace::{
cmd_ctx::{CmdCtxSpsf, CmdCtxSpsfFields},
cmd_model::CmdOutcome,
fmt::{
presentable::{Heading, HeadingLevel, ListNumberedAligned},
PresentableExt,
},
rt::cmds::StatesGoalReadCmd,
rt_model::output::OutputWrite,
};
use crate::{
cmds::{
common::{env_man_flow, workspace},
AppUploadCmd, CmdOpts, EnvCmd,
},
model::{EnvManError, EnvManFlow},
rt_model::EnvmanCmdCtxTypes,
};
/// Shows the goal state of the environment.
#[derive(Debug)]
pub struct EnvGoalCmd;
impl EnvGoalCmd {
/// Shows the goal state of the environment.
///
/// # Parameters
///
/// * `output`: Output to write the execution outcome.
pub async fn run<O>(output: &mut O) -> Result<(), EnvManError>
where
O: OutputWrite + Send,
EnvManError: From<<O as OutputWrite>::Error>,
{
let workspace = workspace()?;
let env_man_flow = env_man_flow(output, &workspace).await?;
match env_man_flow {
EnvManFlow::AppUpload => run!(output, AppUploadCmd),
EnvManFlow::EnvDeploy => run!(output, EnvCmd),
}
Ok(())
}
}
macro_rules! run {
($output:ident, $flow_cmd:ident) => {{
$flow_cmd::run($output, CmdOpts::default(), |cmd_ctx| {
run_with_ctx(cmd_ctx).boxed_local()
})
.await?;
}};
}
async fn run_with_ctx<O>(
cmd_ctx: &mut CmdCtxSpsf<'_, EnvmanCmdCtxTypes<O>>,
) -> Result<(), EnvManError>
where
O: OutputWrite,
EnvManError: From<<O as OutputWrite>::Error>,
{
let states_goal_outcome = StatesGoalReadCmd::exec(cmd_ctx).await?;
let CmdCtxSpsf {
output,
fields: CmdCtxSpsfFields { flow, .. },
..
} = cmd_ctx;
if let Some(states_goal) = states_goal_outcome.value() {
let states_goal_raw_map = &***states_goal;
let states_goal_presentables: ListNumberedAligned<_, _> = flow
.graph()
.iter_insertion()
.map(|item| {
let item_id = item.id();
let state_goal_presentable = match states_goal_raw_map.get(item_id) {
Some(state_goal) => format!("{state_goal}").left_presentable(),
None => "<unknown>".right_presentable(),
};
(item_id, state_goal_presentable)
})
.collect::<Vec<_>>()
.into();
output
.present(&(
Heading::new(HeadingLevel::Level1, "Goal States"),
states_goal_presentables,
"\n",
))
.await?;
}
if let CmdOutcome::ItemError { errors, .. } = &states_goal_outcome {
crate::output::item_errors_present(&mut **output, errors).await?;
}
Ok(())
}
use run;
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/cmds/profile_switch_cmd.rs | examples/envman/src/cmds/profile_switch_cmd.rs | use peace::{
cfg::app_name,
cmd_ctx::{CmdCtxMpnf, CmdCtxMpnfFields},
profile_model::Profile,
rt_model::output::OutputWrite,
};
use crate::{
cmds::{
common::{env_man_flow, workspace},
ProfileInitCmd,
},
model::{EnvManError, EnvManFlow, ProfileSwitch, WorkspaceParamsKey},
rt_model::EnvmanCmdCtxTypes,
};
/// Command to switch between profiles.
#[derive(Debug)]
pub struct ProfileSwitchCmd;
impl ProfileSwitchCmd {
/// Switches to another profile.
///
/// # Parameters
///
/// * `output`: Output to write the execution outcome.
pub async fn run<O>(output: &mut O, profile_switch: ProfileSwitch) -> Result<(), EnvManError>
where
O: OutputWrite,
EnvManError: From<<O as OutputWrite>::Error>,
{
let app_name = app_name!();
let workspace = workspace()?;
let env_man_flow = env_man_flow(output, &workspace).await?;
let cmd_ctx_builder = CmdCtxMpnf::<EnvmanCmdCtxTypes<O>>::builder()
.with_output(output.into())
.with_workspace((&workspace).into())
.with_workspace_param::<Profile>(WorkspaceParamsKey::Profile, None)
.with_workspace_param::<EnvManFlow>(WorkspaceParamsKey::Flow, None);
// .with_profile_param::<EnvType>(ProfileParamsKey::EnvType, None);
let mut cmd_ctx = cmd_ctx_builder.await?;
let CmdCtxMpnf {
ref mut output,
fields:
CmdCtxMpnfFields {
workspace,
profiles,
..
},
} = cmd_ctx;
match profile_switch {
ProfileSwitch::ToExisting {
profile: profile_to_switch_to,
} => {
if !profiles.contains(&profile_to_switch_to) {
return Err(EnvManError::ProfileSwitchToNonExistent {
profile_to_switch_to,
app_name,
});
} else {
// Switches profile
let _cmd_ctx = CmdCtxMpnf::<EnvmanCmdCtxTypes<O>>::builder()
.with_output(output.reborrow())
.with_workspace(workspace)
.with_workspace_param(
WorkspaceParamsKey::Profile,
Some(profile_to_switch_to.clone()),
)
.await?;
}
output
.present(&(
String::from("Switched to profile: "),
profile_to_switch_to,
String::from("\n"),
))
.await?;
}
ProfileSwitch::CreateNew {
profile: profile_to_create,
env_type,
slug,
version,
url,
} => {
ProfileInitCmd::run(
&mut **output,
profile_to_create.clone(),
env_man_flow,
env_type,
&slug,
&version,
url,
false,
)
.await?;
output
.present(&(
String::from("Switched to a new profile: "),
profile_to_create,
String::from("\n"),
))
.await?;
}
}
Ok(())
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/cmds/profile_show_cmd.rs | examples/envman/src/cmds/profile_show_cmd.rs | use peace::{
cmd_ctx::{CmdCtxSpnf, CmdCtxSpnfFields, ProfileSelection},
fmt::presentln,
profile_model::Profile,
rt_model::output::OutputWrite,
};
use crate::{
cmds::common::workspace,
model::{EnvManError, EnvType, ProfileParamsKey, WorkspaceParamsKey},
rt_model::EnvmanCmdCtxTypes,
};
/// Command to show the current profile.
#[derive(Debug)]
pub struct ProfileShowCmd;
impl ProfileShowCmd {
/// Shows the currently active profile.
///
/// The active profile is stored in workspace params.
///
/// # Parameters
///
/// * `output`: Output to write the execution outcome.
pub async fn run<O>(output: &mut O) -> Result<(), EnvManError>
where
O: OutputWrite,
EnvManError: From<<O as OutputWrite>::Error>,
{
let cmd_ctx_builder = CmdCtxSpnf::<EnvmanCmdCtxTypes<O>>::builder()
.with_output(output.into())
.with_workspace(workspace()?.into());
let profile_key = WorkspaceParamsKey::Profile;
let mut cmd_ctx = cmd_ctx_builder
.with_profile_selection(ProfileSelection::FromWorkspaceParam(profile_key.into()))
.await?;
let CmdCtxSpnf {
ref mut output,
fields:
CmdCtxSpnfFields {
workspace_params,
profile_params,
..
},
} = cmd_ctx;
let profile = workspace_params.get::<Profile, _>(&profile_key);
let env_type = profile_params.get::<EnvType, _>(&ProfileParamsKey::EnvType);
if let Some((profile, env_type)) = profile.zip(env_type) {
presentln!(output, ["Using profile ", profile]);
presentln!(output, ["Environment type: ", env_type]);
}
Ok(())
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/cmds/env_cmd.rs | examples/envman/src/cmds/env_cmd.rs | use futures::future::LocalBoxFuture;
use peace::{
cmd_ctx::{CmdCtxMpsf, CmdCtxSpsf, CmdCtxSpsfFields, ProfileSelection},
fmt::presentln,
profile_model::Profile,
rt_model::output::OutputWrite,
};
use crate::{
cmds::{common::workspace, CmdOpts},
flows::EnvDeployFlow,
model::{EnvManError, EnvManFlow, EnvType, ProfileParamsKey, WorkspaceParamsKey},
rt_model::EnvmanCmdCtxTypes,
};
/// Runs a `*Cmd` that accesses the environment.
#[derive(Debug)]
pub struct EnvCmd;
impl EnvCmd {
/// Returns the `CmdCtx` for the `EnvDeployFlow`.
pub async fn cmd_ctx<O>(
output: &mut O,
) -> Result<CmdCtxSpsf<'_, EnvmanCmdCtxTypes<O>>, EnvManError>
where
O: OutputWrite,
EnvManError: From<<O as OutputWrite>::Error>,
{
let flow = EnvDeployFlow::flow().await?;
let profile_key = WorkspaceParamsKey::Profile;
let cmd_ctx = {
let cmd_ctx_builder = CmdCtxSpsf::<EnvmanCmdCtxTypes<O>>::builder()
.with_output(output.into())
.with_workspace(workspace()?.into());
crate::cmds::interruptibility_augment!(cmd_ctx_builder);
cmd_ctx_builder
.with_profile_selection(ProfileSelection::FromWorkspaceParam(profile_key.into()))
.with_flow(flow.into())
.await?
};
Ok(cmd_ctx)
}
/// Runs a command on the environment with the active profile.
///
/// # Parameters
///
/// * `output`: Output to write the execution outcome.
/// * `cmd_opts`: Options to configure the `Cmd`'s output.
/// * `f`: The command to run.
pub async fn run<O, T, F>(output: &mut O, cmd_opts: CmdOpts, f: F) -> Result<T, EnvManError>
where
O: OutputWrite,
EnvManError: From<<O as OutputWrite>::Error>,
for<'fn_once> F: FnOnce(
&'fn_once mut CmdCtxSpsf<'_, EnvmanCmdCtxTypes<O>>,
) -> LocalBoxFuture<'fn_once, Result<T, EnvManError>>,
{
let mut cmd_ctx = Self::cmd_ctx(output).await?;
let CmdOpts { profile_print } = cmd_opts;
if profile_print {
Self::profile_print(&mut cmd_ctx).await?;
}
let t = f(&mut cmd_ctx).await?;
Ok(t)
}
/// Runs a multi-profile command using the `EnvDeploy` flow..
///
/// # Parameters
///
/// * `output`: Output to write the execution outcome.
/// * `f`: The command to run.
pub async fn multi_profile<O, T, F>(output: &mut O, f: F) -> Result<T, EnvManError>
where
O: OutputWrite,
EnvManError: From<<O as OutputWrite>::Error>,
for<'fn_once> F: FnOnce(
&'fn_once mut CmdCtxMpsf<EnvmanCmdCtxTypes<O>>,
) -> LocalBoxFuture<'fn_once, Result<T, EnvManError>>,
{
let flow = EnvDeployFlow::flow().await?;
let mut cmd_ctx = {
let cmd_ctx_builder = CmdCtxMpsf::<EnvmanCmdCtxTypes<O>>::builder()
.with_output(output.into())
.with_workspace(workspace()?.into())
.with_workspace_param::<peace::profile_model::Profile>(
WorkspaceParamsKey::Profile,
None,
)
.with_workspace_param::<EnvManFlow>(WorkspaceParamsKey::Flow, None);
crate::cmds::interruptibility_augment!(cmd_ctx_builder);
cmd_ctx_builder.with_flow((&flow).into()).await?
};
let t = f(&mut cmd_ctx).await?;
Ok(t)
}
async fn profile_print<O>(
cmd_ctx: &mut CmdCtxSpsf<'_, EnvmanCmdCtxTypes<O>>,
) -> Result<(), EnvManError>
where
O: OutputWrite,
EnvManError: From<<O as OutputWrite>::Error>,
{
let CmdCtxSpsf {
output,
fields:
CmdCtxSpsfFields {
workspace_params,
profile_params,
..
},
..
} = cmd_ctx;
let profile = workspace_params.get::<Profile, _>(&WorkspaceParamsKey::Profile);
let env_type = profile_params.get::<EnvType, _>(&ProfileParamsKey::EnvType);
if let Some((profile, env_type)) = profile.zip(env_type) {
presentln!(
output,
["Using profile ", profile, " -- type ", env_type, "\n"]
);
}
Ok(())
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/cmds/env_discover_cmd.rs | examples/envman/src/cmds/env_discover_cmd.rs | use futures::FutureExt;
use peace::{
cmd_ctx::{CmdCtxSpsf, CmdCtxSpsfFields},
cmd_model::CmdOutcome,
fmt::{
presentable::{Heading, HeadingLevel, ListNumberedAligned},
PresentableExt,
},
rt::cmds::StatesDiscoverCmd,
rt_model::output::OutputWrite,
};
use crate::{
cmds::{
common::{env_man_flow, workspace},
AppUploadCmd, CmdOpts, EnvCmd,
},
model::{EnvManError, EnvManFlow},
rt_model::EnvmanCmdCtxTypes,
};
/// Shows the goal state of the environment.
#[derive(Debug)]
pub struct EnvDiscoverCmd;
impl EnvDiscoverCmd {
/// Shows the goal state of the environment.
///
/// # Parameters
///
/// * `output`: Output to write the execution outcome.
/// * `debug`: Whether to print `CmdOutcome` debug info.
pub async fn run<O>(output: &mut O, debug: bool) -> Result<(), EnvManError>
where
O: OutputWrite + Send,
EnvManError: From<<O as OutputWrite>::Error>,
{
let workspace = workspace()?;
let env_man_flow = env_man_flow(output, &workspace).await?;
match env_man_flow {
EnvManFlow::AppUpload => run!(output, AppUploadCmd, debug),
EnvManFlow::EnvDeploy => run!(output, EnvCmd, debug),
}
Ok(())
}
}
macro_rules! run {
($output:ident, $flow_cmd:ident, $debug:expr) => {{
$flow_cmd::run($output, CmdOpts::default(), |cmd_ctx| {
run_with_ctx(cmd_ctx, $debug).boxed_local()
})
.await?;
}};
}
async fn run_with_ctx<O>(
cmd_ctx: &mut CmdCtxSpsf<'_, EnvmanCmdCtxTypes<O>>,
debug: bool,
) -> Result<(), EnvManError>
where
O: OutputWrite,
EnvManError: From<<O as OutputWrite>::Error>,
{
let states_discover_outcome = StatesDiscoverCmd::current_and_goal(cmd_ctx).await?;
let CmdCtxSpsf {
output,
fields: CmdCtxSpsfFields {
flow, resources, ..
},
..
} = cmd_ctx;
if let Some((states_current, states_goal)) = states_discover_outcome.value() {
let states_current_raw_map = &***states_current;
let states_goal_raw_map = &***states_goal;
let states_current_presentables: ListNumberedAligned<_, _> = flow
.graph()
.iter_insertion()
.map(|item| {
let item_id = item.id();
let state_current_presentable = match states_current_raw_map.get(item_id) {
Some(state_current) => format!("{state_current}").left_presentable(),
None => "<unknown>".right_presentable(),
};
(item_id, state_current_presentable)
})
.collect::<Vec<_>>()
.into();
let states_goal_presentables: ListNumberedAligned<_, _> = flow
.graph()
.iter_insertion()
.map(|item| {
let item_id = item.id();
let state_goal_presentable = match states_goal_raw_map.get(item_id) {
Some(state_goal) => format!("{state_goal}").left_presentable(),
None => "<unknown>".right_presentable(),
};
(item_id, state_goal_presentable)
})
.collect::<Vec<_>>()
.into();
output
.present(&(
Heading::new(HeadingLevel::Level1, "Current States"),
states_current_presentables,
"\n",
Heading::new(HeadingLevel::Level1, "Goal States"),
states_goal_presentables,
"\n",
))
.await?;
}
if let CmdOutcome::ItemError { errors, .. } = &states_discover_outcome {
crate::output::item_errors_present(&mut **output, errors).await?;
}
if debug {
crate::output::cmd_outcome_completion_present(
&mut **output,
resources,
states_discover_outcome,
)
.await?;
}
Ok(())
}
use run;
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/cmds/env_diff_cmd.rs | examples/envman/src/cmds/env_diff_cmd.rs | use futures::FutureExt;
use peace::{
cmd_ctx::{CmdCtxMpsf, CmdCtxMpsfFields, CmdCtxSpsf, CmdCtxSpsfFields},
flow_rt::Flow,
fmt::{
presentable::{Heading, HeadingLevel, ListNumberedAligned},
PresentableExt,
},
profile_model::Profile,
resource_rt::states::StateDiffs,
rt::cmds::DiffCmd,
rt_model::output::OutputWrite,
};
use crate::{
cmds::{
common::{env_man_flow, workspace},
AppUploadCmd, CmdOpts, EnvCmd,
},
model::{EnvDiffSelection, EnvManError, EnvManFlow},
};
/// Shows the diff between current and goal states of the environment.
#[derive(Debug)]
pub struct EnvDiffCmd;
impl EnvDiffCmd {
/// Shows the diff between current and goal states of the environment.
///
/// # Parameters
///
/// * `output`: Output to write the execution outcome.
/// * `env_diff_selection`: Profiles to compare.
pub async fn run<O>(
output: &mut O,
env_diff_selection: EnvDiffSelection,
) -> Result<(), EnvManError>
where
O: OutputWrite + Send,
EnvManError: From<<O as OutputWrite>::Error>,
{
let workspace = workspace()?;
let env_man_flow = env_man_flow(output, &workspace).await?;
match env_diff_selection {
EnvDiffSelection::CurrentAndGoal => {
Self::active_profile_current_vs_goal(output, env_man_flow).await
}
EnvDiffSelection::DiffProfilesCurrent {
profile_a,
profile_b,
} => Self::diff_stored(output, env_man_flow, profile_a, profile_b).await,
}
}
async fn active_profile_current_vs_goal<O>(
output: &mut O,
env_man_flow: EnvManFlow,
) -> Result<(), EnvManError>
where
O: OutputWrite + Send,
EnvManError: From<<O as OutputWrite>::Error>,
{
match env_man_flow {
EnvManFlow::AppUpload => run!(output, AppUploadCmd),
EnvManFlow::EnvDeploy => run!(output, EnvCmd),
}
}
async fn diff_stored<O>(
output: &mut O,
env_man_flow: EnvManFlow,
profile_a: Profile,
profile_b: Profile,
) -> Result<(), EnvManError>
where
O: OutputWrite + Send,
EnvManError: From<<O as OutputWrite>::Error>,
{
match env_man_flow {
EnvManFlow::AppUpload => {
run_multi!(output, AppUploadCmd, profile_a, profile_b)
}
EnvManFlow::EnvDeploy => run_multi!(output, EnvCmd, profile_a, profile_b),
};
Ok(())
}
async fn state_diffs_present<O>(
output: &mut O,
flow: &Flow<EnvManError>,
state_diffs: &StateDiffs,
) -> Result<(), EnvManError>
where
O: OutputWrite + Send,
EnvManError: From<<O as OutputWrite>::Error>,
{
let state_diffs_raw_map = &***state_diffs;
let states_diffs_presentables: ListNumberedAligned<_, _> = flow
.graph()
.iter_insertion()
.map(|item| {
let item_id = item.id();
let state_diff_presentable = match state_diffs_raw_map.get(item_id) {
Some(state_diff) => format!("{state_diff}").left_presentable(),
None => "<unknown>".right_presentable(),
};
(item_id, state_diff_presentable)
})
.collect::<Vec<_>>()
.into();
output
.present(&(
Heading::new(HeadingLevel::Level1, "State Diffs"),
states_diffs_presentables,
"\n",
))
.await?;
Ok(())
}
}
macro_rules! run {
($output:ident, $flow_cmd:ident) => {{
$flow_cmd::run($output, CmdOpts::default(), |ctx| {
async {
let state_diffs_outcome = DiffCmd::diff_stored(ctx).await?;
let CmdCtxSpsf {
output,
fields: CmdCtxSpsfFields { flow, .. },
..
} = ctx;
if let Some(state_diffs) = state_diffs_outcome.value() {
Self::state_diffs_present(&mut **output, flow, &state_diffs).await?;
}
Ok(())
}
.boxed_local()
})
.await
}};
}
macro_rules! run_multi {
($output:ident, $flow_cmd:ident, $profile_a:ident, $profile_b:ident) => {{
$flow_cmd::multi_profile($output, move |ctx| {
async move {
let state_diffs =
DiffCmd::diff_current_stored(ctx, &$profile_a, &$profile_b).await?;
let CmdCtxMpsf {
output,
fields: CmdCtxMpsfFields { flow, .. },
} = ctx;
Self::state_diffs_present(&mut **output, flow, &state_diffs).await?;
Ok(())
}
.boxed_local()
})
.await?;
}};
}
use run;
use run_multi;
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/cmds/env_clean_cmd.rs | examples/envman/src/cmds/env_clean_cmd.rs | use futures::FutureExt;
use peace::{
cmd_ctx::{CmdCtxSpsf, CmdCtxSpsfFields},
cmd_model::CmdOutcome,
fmt::{
presentable::{Heading, HeadingLevel, ListNumberedAligned},
PresentableExt,
},
rt::cmds::{ApplyStoredStateSync, CleanCmd},
rt_model::output::OutputWrite,
};
use crate::{
cmds::{
common::{env_man_flow, workspace},
AppUploadCmd, CmdOpts, EnvCmd,
},
model::{EnvManError, EnvManFlow},
rt_model::EnvmanCmdCtxTypes,
};
/// Cleans up (deletes) the environment.
#[derive(Debug)]
pub struct EnvCleanCmd;
impl EnvCleanCmd {
/// Cleans up (deletes) the environment.
///
/// # Parameters
///
/// * `output`: Output to write the execution outcome.
/// * `debug`: Whether to print `CmdOutcome` debug info.
pub async fn run<O>(output: &mut O, debug: bool) -> Result<(), EnvManError>
where
O: OutputWrite + Send,
EnvManError: From<<O as OutputWrite>::Error>,
{
let workspace = workspace()?;
let env_man_flow = env_man_flow(output, &workspace).await?;
match env_man_flow {
EnvManFlow::AppUpload => run!(output, AppUploadCmd, debug),
EnvManFlow::EnvDeploy => run!(output, EnvCmd, debug),
};
Ok(())
}
}
macro_rules! run {
($output:ident, $flow_cmd:ident, $debug:expr) => {{
$flow_cmd::run(
$output,
CmdOpts::default().with_profile_print(false),
|cmd_ctx| run_with_ctx(cmd_ctx, $debug).boxed_local(),
)
.await?;
}};
}
async fn run_with_ctx<O>(
cmd_ctx: &mut CmdCtxSpsf<'_, EnvmanCmdCtxTypes<O>>,
debug: bool,
) -> Result<(), EnvManError>
where
O: OutputWrite,
EnvManError: From<<O as OutputWrite>::Error>,
{
let states_cleaned_outcome =
CleanCmd::exec_with(cmd_ctx, ApplyStoredStateSync::Current).await?;
let CmdCtxSpsf {
output,
fields: CmdCtxSpsfFields {
flow, resources, ..
},
..
} = cmd_ctx;
if let Some(states_cleaned) = states_cleaned_outcome.value() {
let states_cleaned_raw_map = &***states_cleaned;
let states_cleaned_presentables: ListNumberedAligned<_, _> = flow
.graph()
.iter_insertion()
.map(|item| {
let item_id = item.id();
let state_cleaned_presentable = match states_cleaned_raw_map.get(item_id) {
Some(state_cleaned) => format!("{state_cleaned}").left_presentable(),
None => "<unknown>".right_presentable(),
};
(item_id, state_cleaned_presentable)
})
.collect::<Vec<_>>()
.into();
output
.present(&(
Heading::new(HeadingLevel::Level1, "States Cleaned"),
states_cleaned_presentables,
"\n",
))
.await?;
}
if let CmdOutcome::ItemError { errors, .. } = &states_cleaned_outcome {
crate::output::item_errors_present(&mut **output, errors).await?;
}
if debug {
crate::output::cmd_outcome_completion_present(
&mut **output,
resources,
states_cleaned_outcome,
)
.await?;
}
Ok(())
}
use run;
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/cmds/common.rs | examples/envman/src/cmds/common.rs | use peace::{
cfg::app_name,
cmd_ctx::CmdCtxNpnf,
rt_model::{output::OutputWrite, Workspace, WorkspaceSpec},
};
use crate::{
model::{EnvManError, EnvManFlow, WorkspaceParamsKey},
rt_model::EnvmanCmdCtxTypes,
};
/// Returns the `Workspace` for all commands.
pub fn workspace() -> Result<Workspace, EnvManError> {
Ok(Workspace::new(
app_name!(),
#[cfg(not(target_arch = "wasm32"))]
WorkspaceSpec::WorkingDir,
#[cfg(target_arch = "wasm32")]
WorkspaceSpec::SessionStorage,
)?)
}
// Reads the `EnvManFlow` used for this workspace.
pub async fn env_man_flow<O>(
output: &mut O,
workspace: &Workspace,
) -> Result<EnvManFlow, EnvManError>
where
O: OutputWrite,
EnvManError: From<<O as OutputWrite>::Error>,
{
let cmd_ctx = CmdCtxNpnf::<EnvmanCmdCtxTypes<O>>::builder()
.with_output(output.into())
.with_workspace(workspace.into())
.await?;
Ok(cmd_ctx
.fields()
.workspace_params()
.get(&WorkspaceParamsKey::Flow)
.copied()
.expect("Expected Flow to be set for this workspace."))
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/cmds/cmd_ctx_builder.rs | examples/envman/src/cmds/cmd_ctx_builder.rs | #[rustfmt::skip] // https://github.com/rust-lang/rustfmt/issues/4609
#[macro_export]
macro_rules! interruptibility_augment {
($cmd_ctx_builder:ident) => {
let (interrupt_tx, interrupt_rx) = tokio::sync::mpsc::channel::<
peace::cmd_ctx::interruptible::InterruptSignal
>(16);
tokio::spawn(async move {
tokio::signal::ctrl_c()
.await
.expect("Failed to listen for `SIGINT`.");
let _ = interrupt_tx.send(peace::cmd_ctx::interruptible::InterruptSignal).await;
});
let $cmd_ctx_builder = $cmd_ctx_builder
.with_interruptibility(peace::cmd_ctx::interruptible::Interruptibility::new(
interrupt_rx.into(),
peace::cmd_ctx::interruptible::InterruptStrategy::FinishCurrent,
));
};
}
pub use interruptibility_augment;
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/cmds/app_upload_cmd.rs | examples/envman/src/cmds/app_upload_cmd.rs | use futures::future::LocalBoxFuture;
use peace::{
cmd_ctx::{CmdCtxMpsf, CmdCtxSpsf, CmdCtxSpsfFields, ProfileSelection},
fmt::presentln,
profile_model::Profile,
rt_model::output::OutputWrite,
};
use crate::{
cmds::{common::workspace, CmdOpts},
flows::AppUploadFlow,
model::{EnvManError, EnvManFlow, EnvType, ProfileParamsKey, WorkspaceParamsKey},
rt_model::EnvmanCmdCtxTypes,
};
/// Runs a `*Cmd` that interacts with the application upload.
#[derive(Debug)]
pub struct AppUploadCmd;
impl AppUploadCmd {
/// Runs a command on the environment with the active profile.
///
/// # Parameters
///
/// * `output`: Output to write the execution outcome.
/// * `cmd_opts`: Options to configure the `Cmd`'s output.
/// * `f`: The command to run.
pub async fn run<O, T, F>(output: &mut O, cmd_opts: CmdOpts, f: F) -> Result<T, EnvManError>
where
O: OutputWrite,
EnvManError: From<<O as OutputWrite>::Error>,
for<'fn_once> F: FnOnce(
&'fn_once mut CmdCtxSpsf<'_, EnvmanCmdCtxTypes<O>>,
) -> LocalBoxFuture<'fn_once, Result<T, EnvManError>>,
{
let flow = AppUploadFlow::flow().await?;
let profile_key = WorkspaceParamsKey::Profile;
let mut cmd_ctx = CmdCtxSpsf::<EnvmanCmdCtxTypes<O>>::builder()
.with_output(output.into())
.with_workspace(workspace()?.into())
.with_profile_selection(ProfileSelection::FromWorkspaceParam(profile_key.into()))
.with_flow((&flow).into())
.await?;
let CmdOpts { profile_print } = cmd_opts;
if profile_print {
Self::profile_print(&mut cmd_ctx).await?;
}
let t = f(&mut cmd_ctx).await?;
Ok(t)
}
/// Runs a multi-profile command using the `EnvDeploy` flow..
///
/// # Parameters
///
/// * `output`: Output to write the execution outcome.
/// * `f`: The command to run.
pub async fn multi_profile<O, T, F>(output: &mut O, f: F) -> Result<T, EnvManError>
where
O: OutputWrite,
EnvManError: From<<O as OutputWrite>::Error>,
for<'fn_once> F: FnOnce(
&'fn_once mut CmdCtxMpsf<EnvmanCmdCtxTypes<O>>,
) -> LocalBoxFuture<'fn_once, Result<T, EnvManError>>,
{
let flow = AppUploadFlow::flow().await?;
let mut cmd_ctx = CmdCtxMpsf::<EnvmanCmdCtxTypes<O>>::builder()
.with_output(output.into())
.with_workspace(workspace()?.into())
.with_flow((&flow).into())
.with_workspace_param::<Profile>(WorkspaceParamsKey::Profile, None)
.with_workspace_param::<EnvManFlow>(WorkspaceParamsKey::Flow, None)
.await?;
let t = f(&mut cmd_ctx).await?;
Ok(t)
}
async fn profile_print<O>(
cmd_ctx: &mut CmdCtxSpsf<'_, EnvmanCmdCtxTypes<O>>,
) -> Result<(), EnvManError>
where
O: OutputWrite,
EnvManError: From<<O as OutputWrite>::Error>,
{
let CmdCtxSpsf {
output,
fields:
CmdCtxSpsfFields {
workspace_params,
profile_params,
..
},
..
} = cmd_ctx;
let profile = workspace_params.get::<Profile, _>(&WorkspaceParamsKey::Profile);
let env_type = profile_params.get::<EnvType, _>(&ProfileParamsKey::EnvType);
if let Some((profile, env_type)) = profile.zip(env_type) {
presentln!(
output,
["Using profile ", profile, " -- type ", env_type, "\n"]
);
}
Ok(())
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/cmds/profile_init_cmd.rs | examples/envman/src/cmds/profile_init_cmd.rs | use peace::{
cfg::app_name,
cmd_ctx::{CmdCtxMpnf, CmdCtxSpnf, CmdCtxSpsf, ProfileSelection},
cmd_model::CmdOutcome,
flow_rt::Flow,
fmt::{presentable::CodeInline, presentln},
item_model::item_id,
profile_model::Profile,
rt::cmds::StatesDiscoverCmd,
rt_model::{output::OutputWrite, Workspace, WorkspaceSpec},
};
use peace_items::file_download::FileDownloadItem;
use semver::Version;
use url::Url;
use crate::{
flows::{AppUploadFlow, AppUploadFlowParamsSpecs, EnvDeployFlow, EnvDeployFlowParamsSpecs},
items::{
peace_aws_iam_policy::IamPolicyItem, peace_aws_iam_role::IamRoleItem,
peace_aws_instance_profile::InstanceProfileItem, peace_aws_s3_bucket::S3BucketItem,
peace_aws_s3_object::S3ObjectItem,
},
model::{
EnvManError, EnvManFlow, EnvType, ProfileParamsKey, RepoSlug, WebApp, WorkspaceParamsKey,
},
rt_model::EnvmanCmdCtxTypes,
};
/// Flow to initialize and set the default profile.
#[derive(Debug)]
pub struct ProfileInitCmd;
impl ProfileInitCmd {
/// Stores profile init parameters.
///
/// # Parameters
///
/// * `output`: Output to write the execution outcome.
/// * `profile`: Name of the profile to create.
/// * `type`: Type of the environment.
#[allow(clippy::too_many_arguments)] // TODO: consolidate cmd ctx building.
pub async fn run<O>(
output: &mut O,
profile_to_create: Profile,
env_man_flow: EnvManFlow,
env_type: EnvType,
slug: &RepoSlug,
version: &Version,
url: Option<Url>,
profile_reinit_allowed: bool,
) -> Result<(), EnvManError>
where
O: OutputWrite,
EnvManError: From<<O as OutputWrite>::Error>,
{
let app_name = app_name!();
let workspace = Workspace::new(
app_name.clone(),
#[cfg(not(target_arch = "wasm32"))]
WorkspaceSpec::WorkingDir,
#[cfg(target_arch = "wasm32")]
WorkspaceSpec::SessionStorage,
)?;
if !profile_reinit_allowed {
let cmd_ctx_result = CmdCtxMpnf::<EnvmanCmdCtxTypes<O>>::builder()
.with_output(output.into())
.with_workspace((&workspace).into())
.await;
match cmd_ctx_result {
Ok(cmd_ctx_mpnf) => {
let profiles = cmd_ctx_mpnf.fields().profiles();
if profiles.contains(&profile_to_create) {
return Err(EnvManError::ProfileToCreateExists {
profile_to_create,
app_name,
});
}
}
Err(_e) => {
// On first invocation, the `.peace` app dir will not exist,
// so we won't be able to list any
// profiles.
}
}
}
let cmd_ctx_builder = CmdCtxSpnf::<EnvmanCmdCtxTypes<O>>::builder()
.with_output(output.into())
.with_workspace((&workspace).into());
crate::cmds::interruptibility_augment!(cmd_ctx_builder);
// Creating the `CmdCtx` writes the workspace and profile params.
// We don't need to run any flows with it.
let cmd_ctx = cmd_ctx_builder
.with_workspace_param(WorkspaceParamsKey::Profile, Some(profile_to_create.clone()))
.with_workspace_param(WorkspaceParamsKey::Flow, Some(env_man_flow))
.with_profile_param(ProfileParamsKey::EnvType, Some(env_type))
.with_profile_selection(ProfileSelection::Specified(profile_to_create.clone()))
.await?;
drop(cmd_ctx);
// --- //
let profile_key = WorkspaceParamsKey::Profile;
let flow = match env_man_flow {
EnvManFlow::AppUpload => AppUploadFlow::flow().await?,
EnvManFlow::EnvDeploy => EnvDeployFlow::flow().await?,
};
let mut cmd_ctx = match env_man_flow {
EnvManFlow::AppUpload => {
app_upload_flow_init(
&profile_to_create,
&profile_key,
&flow,
slug,
version,
url,
output,
&workspace,
)
.await?
}
EnvManFlow::EnvDeploy => {
env_deploy_flow_init(
&profile_to_create,
&profile_key,
&flow,
slug,
version,
url,
output,
&workspace,
)
.await?
}
};
let states_discover_outcome = StatesDiscoverCmd::current_and_goal(&mut cmd_ctx).await?;
let output = cmd_ctx.output_mut();
match states_discover_outcome {
CmdOutcome::Complete {
value: _,
cmd_blocks_processed: _,
} => {
presentln!(
output,
[
"Initialized profile ",
&profile_to_create,
" using ",
&CodeInline::new(format!("{slug}@{version}").into()),
"."
]
);
}
CmdOutcome::BlockInterrupted { .. } | CmdOutcome::ExecutionInterrupted { .. } => {
presentln!(
output,
["Profile ", &profile_to_create, "not fully initialized."]
);
presentln!(
output,
[
"Run the ",
&CodeInline::new("init".into()),
" command again to complete profile initialization."
]
);
}
CmdOutcome::ItemError {
item_stream_outcome: _,
cmd_blocks_processed: _,
cmd_blocks_not_processed: _,
errors,
} => crate::output::item_errors_present(output, &errors).await?,
}
Ok(())
}
}
#[allow(clippy::too_many_arguments)]
async fn app_upload_flow_init<'f, O>(
profile_to_create: &'f Profile,
profile_key: &'f WorkspaceParamsKey,
flow: &'f Flow<EnvManError>,
slug: &'f RepoSlug,
version: &'f Version,
url: Option<Url>,
output: &'f mut O,
workspace: &'f Workspace,
) -> Result<CmdCtxSpsf<'f, EnvmanCmdCtxTypes<O>>, EnvManError>
where
O: OutputWrite,
EnvManError: From<<O as OutputWrite>::Error>,
{
let AppUploadFlowParamsSpecs {
app_download_params_spec,
s3_bucket_params_spec,
s3_object_params_spec,
} = AppUploadFlow::params(profile_to_create, slug, version, url)?;
CmdCtxSpsf::<EnvmanCmdCtxTypes<O>>::builder()
.with_output(output.into())
.with_workspace(workspace.into())
.with_profile_selection(ProfileSelection::FromWorkspaceParam(profile_key.into()))
.with_flow(flow.into())
.with_item_params::<FileDownloadItem<WebApp>>(
item_id!("app_download"),
app_download_params_spec,
)
.with_item_params::<S3BucketItem<WebApp>>(item_id!("s3_bucket"), s3_bucket_params_spec)
.with_item_params::<S3ObjectItem<WebApp>>(item_id!("s3_object"), s3_object_params_spec)
.await
}
#[allow(clippy::too_many_arguments)]
async fn env_deploy_flow_init<'f, O>(
profile_to_create: &'f Profile,
profile_key: &'f WorkspaceParamsKey,
flow: &'f Flow<EnvManError>,
slug: &'f RepoSlug,
version: &'f Version,
url: Option<Url>,
output: &'f mut O,
workspace: &'f Workspace,
) -> Result<CmdCtxSpsf<'f, EnvmanCmdCtxTypes<O>>, EnvManError>
where
O: OutputWrite,
EnvManError: From<<O as OutputWrite>::Error>,
{
let EnvDeployFlowParamsSpecs {
app_download_params_spec,
iam_policy_params_spec,
iam_role_params_spec,
instance_profile_params_spec,
s3_bucket_params_spec,
s3_object_params_spec,
} = EnvDeployFlow::params(profile_to_create, slug, version, url)?;
CmdCtxSpsf::<EnvmanCmdCtxTypes<O>>::builder()
.with_output(output.into())
.with_workspace(workspace.into())
.with_profile_selection(ProfileSelection::FromWorkspaceParam(profile_key.into()))
.with_flow(flow.into())
.with_item_params::<FileDownloadItem<WebApp>>(
item_id!("app_download"),
app_download_params_spec,
)
.with_item_params::<IamPolicyItem<WebApp>>(item_id!("iam_policy"), iam_policy_params_spec)
.with_item_params::<IamRoleItem<WebApp>>(item_id!("iam_role"), iam_role_params_spec)
.with_item_params::<InstanceProfileItem<WebApp>>(
item_id!("instance_profile"),
instance_profile_params_spec,
)
.with_item_params::<S3BucketItem<WebApp>>(item_id!("s3_bucket"), s3_bucket_params_spec)
.with_item_params::<S3ObjectItem<WebApp>>(item_id!("s3_object"), s3_object_params_spec)
.await
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/cmds/env_deploy_cmd.rs | examples/envman/src/cmds/env_deploy_cmd.rs | use futures::FutureExt;
use peace::{
cmd_ctx::{CmdCtxSpsf, CmdCtxSpsfFields},
cmd_model::CmdOutcome,
fmt::{
presentable::{Heading, HeadingLevel, ListNumberedAligned},
PresentableExt,
},
rt::cmds::{ApplyStoredStateSync, EnsureCmd},
rt_model::output::OutputWrite,
};
use crate::{
cmds::{
common::{env_man_flow, workspace},
AppUploadCmd, CmdOpts, EnvCmd,
},
model::{EnvManError, EnvManFlow},
rt_model::EnvmanCmdCtxTypes,
};
/// Deploys or updates the environment.
#[derive(Debug)]
pub struct EnvDeployCmd;
impl EnvDeployCmd {
/// Deploys or updates the environment.
///
/// # Parameters
///
/// * `output`: Output to write the execution outcome.
/// * `debug`: Whether to print `CmdOutcome` debug info.
pub async fn run<O>(output: &mut O, debug: bool) -> Result<(), EnvManError>
where
O: OutputWrite + Send,
EnvManError: From<<O as OutputWrite>::Error>,
{
let workspace = workspace()?;
let env_man_flow = env_man_flow(output, &workspace).await?;
match env_man_flow {
EnvManFlow::AppUpload => run!(output, AppUploadCmd, debug),
EnvManFlow::EnvDeploy => run!(output, EnvCmd, debug),
};
Ok(())
}
}
macro_rules! run {
($output:ident, $flow_cmd:ident, $debug:expr) => {{
$flow_cmd::run(
$output,
CmdOpts::default().with_profile_print(false),
|cmd_ctx| run_with_ctx(cmd_ctx, $debug).boxed_local(),
)
.await?;
}};
}
async fn run_with_ctx<O>(
cmd_ctx: &mut CmdCtxSpsf<'_, EnvmanCmdCtxTypes<O>>,
debug: bool,
) -> Result<(), EnvManError>
where
O: OutputWrite,
EnvManError: From<<O as OutputWrite>::Error>,
{
let states_ensured_outcome =
EnsureCmd::exec_with(cmd_ctx, ApplyStoredStateSync::Current).await?;
let CmdCtxSpsf {
output,
fields: CmdCtxSpsfFields {
flow, resources, ..
},
..
} = cmd_ctx;
if let Some(states_ensured) = states_ensured_outcome.value() {
let states_ensured_raw_map = &***states_ensured;
let states_ensured_presentables: ListNumberedAligned<_, _> = flow
.graph()
.iter_insertion()
.map(|item| {
let item_id = item.id();
let state_ensured_presentable = match states_ensured_raw_map.get(item_id) {
Some(state_ensured) => format!("{state_ensured}").left_presentable(),
None => "<unknown>".right_presentable(),
};
(item_id, state_ensured_presentable)
})
.collect::<Vec<_>>()
.into();
output
.present(&(
Heading::new(HeadingLevel::Level1, "States Ensured"),
states_ensured_presentables,
"\n",
))
.await?;
}
if let CmdOutcome::ItemError { errors, .. } = &states_ensured_outcome {
crate::output::item_errors_present(&mut **output, errors).await?;
}
if debug {
crate::output::cmd_outcome_completion_present(
&mut **output,
resources,
states_ensured_outcome,
)
.await?;
}
Ok(())
}
use run;
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/download/src/file_id.rs | examples/download/src/file_id.rs | /// Marker type for `FileDownloadParams`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FileId;
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/download/src/download_cmd_ctx_types.rs | examples/download/src/download_cmd_ctx_types.rs | use std::marker::PhantomData;
use peace::{cmd_ctx::CmdCtxTypes, rt_model::output::OutputWrite};
use crate::DownloadError;
#[derive(Debug)]
pub struct DownloadCmdCtxTypes<Output>(PhantomData<Output>);
impl<Output> CmdCtxTypes for DownloadCmdCtxTypes<Output>
where
Output: OutputWrite,
DownloadError: From<<Output as OutputWrite>::Error>,
{
type AppError = DownloadError;
type FlowParamsKey = ();
type MappingFns = ();
type Output = Output;
type ProfileParamsKey = ();
type WorkspaceParamsKey = ();
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/download/src/lib.rs | examples/download/src/lib.rs | use peace::{
cfg::app_name,
cmd_ctx::{CmdCtxSpsf, ProfileSelection},
cmd_model::CmdOutcome,
flow_model::FlowId,
flow_rt::{Flow, ItemGraphBuilder},
item_model::{item_id, ItemId},
profile_model::Profile,
rt::cmds::{
CleanCmd, DiffCmd, EnsureCmd, StatesCurrentStoredDisplayCmd, StatesDiscoverCmd,
StatesGoalDisplayCmd,
},
rt_model::{output::OutputWrite, Workspace, WorkspaceSpec},
};
use peace_items::file_download::{FileDownloadItem, FileDownloadParams};
#[cfg(not(target_arch = "wasm32"))]
pub use crate::download_args::{DownloadArgs, DownloadCommand};
pub use crate::{
download_cmd_ctx_types::DownloadCmdCtxTypes, download_error::DownloadError, file_id::FileId,
};
#[cfg(not(target_arch = "wasm32"))]
mod download_args;
mod download_cmd_ctx_types;
mod download_error;
mod file_id;
#[cfg(target_arch = "wasm32")]
mod wasm;
#[derive(Debug)]
pub struct WorkspaceAndFlow {
workspace: Workspace,
flow: Flow<DownloadError>,
}
const FILE_ITEM_SPEC_ID: ItemId = item_id!("file");
/// Returns a default workspace and the Download item graph.
#[cfg(not(target_arch = "wasm32"))]
pub async fn workspace_and_flow_setup(
workspace_spec: WorkspaceSpec,
flow_id: FlowId,
) -> Result<WorkspaceAndFlow, DownloadError> {
let workspace = Workspace::new(app_name!(), workspace_spec)?;
let item_graph = {
let mut item_graph_builder = ItemGraphBuilder::<DownloadError>::new();
item_graph_builder.add_fn(FileDownloadItem::<FileId>::new(FILE_ITEM_SPEC_ID).into());
item_graph_builder.build()
};
let flow = Flow::new(flow_id, item_graph);
let workspace_and_flow = WorkspaceAndFlow { workspace, flow };
Ok(workspace_and_flow)
}
/// Returns a default workspace and the Download item graph.
#[cfg(target_arch = "wasm32")]
pub async fn workspace_and_flow_setup(
workspace_spec: WorkspaceSpec,
flow_id: FlowId,
) -> Result<WorkspaceAndFlow, DownloadError> {
let workspace = Workspace::new(app_name!(), workspace_spec)?;
let item_graph = {
let mut item_graph_builder = ItemGraphBuilder::<DownloadError>::new();
item_graph_builder.add_fn(FileDownloadItem::<FileId>::new(item_id!("file")).into());
item_graph_builder.build()
};
let flow = Flow::new(flow_id, item_graph);
let workspace_and_flow = WorkspaceAndFlow { workspace, flow };
Ok(workspace_and_flow)
}
pub type DownloadCmdCtx<'ctx, O> = CmdCtxSpsf<'ctx, DownloadCmdCtxTypes<O>>;
/// Returns a `CmdCtx` initialized from the workspace and item graph
pub async fn cmd_ctx<'ctx, O>(
workspace_and_flow: &'ctx WorkspaceAndFlow,
profile: Profile,
output: &'ctx mut O,
file_download_params: Option<FileDownloadParams<FileId>>,
) -> Result<DownloadCmdCtx<'ctx, O>, DownloadError>
where
O: OutputWrite,
DownloadError: From<<O as OutputWrite>::Error>,
{
let WorkspaceAndFlow { workspace, flow } = workspace_and_flow;
let mut cmd_ctx_builder = CmdCtxSpsf::builder()
.with_workspace(workspace.into())
.with_output(output.into())
.with_profile_selection(ProfileSelection::Specified(profile))
.with_flow(flow.into());
if let Some(file_download_params) = file_download_params {
cmd_ctx_builder = cmd_ctx_builder.with_item_params::<FileDownloadItem<FileId>>(
FILE_ITEM_SPEC_ID,
file_download_params.into(),
);
}
cmd_ctx_builder.await
}
pub async fn fetch<O>(cmd_ctx: &mut DownloadCmdCtx<'_, O>) -> Result<(), DownloadError>
where
O: OutputWrite,
DownloadError: From<<O as OutputWrite>::Error>,
{
let CmdOutcome::Complete {
value: (_states_current, _states_goal),
cmd_blocks_processed: _,
} = StatesDiscoverCmd::current_and_goal(cmd_ctx).await?
else {
panic!("Expected `StatesDiscoverCmd::current_and_goal` to complete successfully.");
};
Ok(())
}
pub async fn status<O>(cmd_ctx: &mut DownloadCmdCtx<'_, O>) -> Result<(), DownloadError>
where
O: OutputWrite,
DownloadError: From<<O as OutputWrite>::Error>,
{
// Already displayed by the command
let _states_current_stored = StatesCurrentStoredDisplayCmd::exec(cmd_ctx).await?;
Ok(())
}
pub async fn goal<O>(cmd_ctx: &mut DownloadCmdCtx<'_, O>) -> Result<(), DownloadError>
where
O: OutputWrite,
DownloadError: From<<O as OutputWrite>::Error>,
{
// Already displayed by the command
let _states_goal = StatesGoalDisplayCmd::exec(cmd_ctx).await?;
Ok(())
}
pub async fn diff<O>(cmd_ctx: &mut DownloadCmdCtx<'_, O>) -> Result<(), DownloadError>
where
O: OutputWrite,
DownloadError: From<<O as OutputWrite>::Error>,
{
let cmd_outcome = DiffCmd::diff_stored(cmd_ctx).await?;
let states_diff = cmd_outcome
.value()
.expect("Expected `states_diff` to exist.");
cmd_ctx.output_mut().present(states_diff).await?;
Ok(())
}
pub async fn ensure_dry<O>(cmd_ctx: &mut DownloadCmdCtx<'_, O>) -> Result<(), DownloadError>
where
O: OutputWrite,
DownloadError: From<<O as OutputWrite>::Error>,
{
let states_ensured_dry_outcome = EnsureCmd::exec_dry(cmd_ctx).await?;
let states_ensured_dry = states_ensured_dry_outcome
.value()
.expect("Expected `states_ensured_dry` to exist.");
cmd_ctx.output_mut().present(states_ensured_dry).await?;
Ok(())
}
pub async fn ensure<O>(cmd_ctx: &mut DownloadCmdCtx<'_, O>) -> Result<(), DownloadError>
where
O: OutputWrite,
DownloadError: From<<O as OutputWrite>::Error>,
{
let states_ensured_outcome = EnsureCmd::exec(cmd_ctx).await?;
let states_ensured = states_ensured_outcome
.value()
.expect("Expected `states_ensured` to exist.");
cmd_ctx.output_mut().present(states_ensured).await?;
Ok(())
}
pub async fn clean_dry<O>(cmd_ctx: &mut DownloadCmdCtx<'_, O>) -> Result<(), DownloadError>
where
O: OutputWrite,
DownloadError: From<<O as OutputWrite>::Error>,
{
let states_cleaned_dry_outcome = CleanCmd::exec_dry(cmd_ctx).await?;
let states_cleaned_dry = states_cleaned_dry_outcome
.value()
.expect("Expected `states_cleaned_dry` to exist.");
cmd_ctx.output_mut().present(states_cleaned_dry).await?;
Ok(())
}
pub async fn clean<O>(cmd_ctx: &mut DownloadCmdCtx<'_, O>) -> Result<(), DownloadError>
where
O: OutputWrite,
DownloadError: From<<O as OutputWrite>::Error>,
{
let states_cleaned_outcome = CleanCmd::exec(cmd_ctx).await?;
let states_cleaned = states_cleaned_outcome
.value()
.expect("Expected `states_cleaned` to exist.");
cmd_ctx.output_mut().present(states_cleaned).await?;
Ok(())
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/download/src/download_error.rs | examples/download/src/download_error.rs | #[cfg(feature = "error_reporting")]
use peace::miette;
/// Error while managing a file download.
#[cfg_attr(feature = "error_reporting", derive(peace::miette::Diagnostic))]
#[derive(Debug, thiserror::Error)]
pub enum DownloadError {
/// A `FileDownload` error occurred.
#[error("A `FileDownload` error occurred.")]
PeaceItemFileDownload(
#[cfg_attr(feature = "error_reporting", diagnostic_source)]
#[source]
#[from]
peace_items::file_download::FileDownloadError,
),
// === Framework errors === //
/// A `peace` runtime error occurred.
#[error("A `peace` runtime error occurred.")]
PeaceRtError(
#[cfg_attr(feature = "error_reporting", diagnostic_source)]
#[source]
#[from]
peace::rt_model::Error,
),
// === Scaffolding errors === //
#[error("Failed to initialize tokio runtime.")]
TokioRuntimeInit(#[source] std::io::Error),
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/download/src/download_args.rs | examples/download/src/download_args.rs | use std::path::PathBuf;
use clap::{Parser, Subcommand, ValueHint};
use peace::cli_model::OutputFormat;
use url::Url;
#[derive(Parser)]
#[clap(
author,
version,
about = "Downloads a file",
long_about = "Downloads a file from a URL only if the local copy is out of sync with the remote copy."
)]
pub struct DownloadArgs {
/// Command to run.
#[clap(subcommand)]
pub command: DownloadCommand,
/// Whether to output errors verbosely.
#[clap(short, long)]
pub verbose: bool,
/// The format of the command output.
///
/// At this level, this needs to be specified before the subcommand.
/// <https://github.com/clap-rs/clap/issues/3002> needs to be implemented
/// for the argument to be passed in after the subcommand.
#[clap(long)]
pub format: Option<OutputFormat>,
}
#[derive(Subcommand)]
pub enum DownloadCommand {
Init {
/// URL to download from.
#[clap(value_hint(ValueHint::Url))]
url: Url,
/// File path to write to.
#[clap(value_parser)]
dest: PathBuf,
},
/// Fetches the current state and goal state.
Fetch,
/// Shows the download state.
Status,
/// Shows the download state.
Goal,
/// Shows the diff between the remote file and local file state.
///
/// This may not be the full content diff if the file is large.
Diff,
/// Dry-run to execute the download if necessary.
EnsureDry,
/// Executes the download if necessary.
Ensure,
/// Dry-run to clean the downloaded file.
CleanDry,
/// Cleans the downloaded file.
Clean,
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/download/src/main.rs | examples/download/src/main.rs | use clap::Parser;
use peace::{cfg::profile, cli::output::CliOutput, flow_model::flow_id, rt_model::WorkspaceSpec};
use peace_items::file_download::FileDownloadParams;
use download::{
clean, clean_dry, cmd_ctx, diff, ensure, ensure_dry, fetch, goal, status,
workspace_and_flow_setup, DownloadArgs, DownloadCommand, DownloadError,
};
#[cfg(not(feature = "error_reporting"))]
pub fn main() {
run().unwrap();
}
#[cfg(feature = "error_reporting")]
pub fn main() -> peace::miette::Result<(), peace::miette::Report> {
// Important to return `peace::miette::Report` instead of calling
// `IntoDiagnostic::intoDiagnostic` on the `Error`, as that does not present the
// diagnostic contextual information to the user.
//
// See <https://docs.rs/miette/latest/miette/trait.IntoDiagnostic.html#warning>.
// The explicit mapping for `PeaceRtError` appears to be necessary to display
// the diagnostic information. i.e. `miette` does not automatically delegate to
// the #[diagnostic_source].
//
// This is fixed by <https://github.com/zkat/miette/pull/170>.
run().map_err(|file_download_error| match file_download_error {
DownloadError::PeaceItemFileDownload(err) => peace::miette::Report::from(err),
DownloadError::PeaceRtError(err) => peace::miette::Report::from(err),
other => peace::miette::Report::from(other),
})
}
pub fn run() -> Result<(), DownloadError> {
let runtime = tokio::runtime::Builder::new_current_thread()
.thread_name("main")
.thread_stack_size(3 * 1024 * 1024)
.enable_io()
.enable_time()
.build()
.map_err(DownloadError::TokioRuntimeInit)?;
let DownloadArgs {
command,
verbose,
format,
} = DownloadArgs::parse();
if !verbose {
#[cfg(feature = "error_reporting")]
peace::miette::set_hook(Box::new(|_| {
Box::new(
peace::miette::MietteHandlerOpts::new()
.without_cause_chain()
.build(),
)
}))
.expect("Failed to configure miette hook.");
}
runtime.block_on(async {
let workspace_spec = WorkspaceSpec::WorkingDir;
let profile = profile!("default");
let flow_id = flow_id!("file");
let mut cli_output = {
let mut builder = CliOutput::builder();
if let Some(format) = format {
builder = builder.with_outcome_format(format);
}
builder.build()
};
match command {
DownloadCommand::Init { url, dest } => {
let workspace_and_flow = workspace_and_flow_setup(workspace_spec, flow_id).await?;
let mut cmd_ctx = cmd_ctx(
&workspace_and_flow,
profile,
&mut cli_output,
Some(FileDownloadParams::new(url, dest)),
)
.await?;
fetch(&mut cmd_ctx).await?;
}
DownloadCommand::Fetch => {
let workspace_and_flow = workspace_and_flow_setup(workspace_spec, flow_id).await?;
let mut cmd_ctx =
cmd_ctx(&workspace_and_flow, profile, &mut cli_output, None).await?;
fetch(&mut cmd_ctx).await?;
}
DownloadCommand::Status => {
let workspace_and_flow = workspace_and_flow_setup(workspace_spec, flow_id).await?;
let mut cmd_ctx =
cmd_ctx(&workspace_and_flow, profile, &mut cli_output, None).await?;
status(&mut cmd_ctx).await?;
}
DownloadCommand::Goal => {
let workspace_and_flow = workspace_and_flow_setup(workspace_spec, flow_id).await?;
let mut cmd_ctx =
cmd_ctx(&workspace_and_flow, profile, &mut cli_output, None).await?;
goal(&mut cmd_ctx).await?;
}
DownloadCommand::Diff => {
let workspace_and_flow = workspace_and_flow_setup(workspace_spec, flow_id).await?;
let mut cmd_ctx =
cmd_ctx(&workspace_and_flow, profile, &mut cli_output, None).await?;
diff(&mut cmd_ctx).await?;
}
DownloadCommand::EnsureDry => {
let workspace_and_flow = workspace_and_flow_setup(workspace_spec, flow_id).await?;
let mut cmd_ctx =
cmd_ctx(&workspace_and_flow, profile, &mut cli_output, None).await?;
ensure_dry(&mut cmd_ctx).await?;
}
DownloadCommand::Ensure => {
let workspace_and_flow = workspace_and_flow_setup(workspace_spec, flow_id).await?;
let mut cmd_ctx =
cmd_ctx(&workspace_and_flow, profile, &mut cli_output, None).await?;
ensure(&mut cmd_ctx).await?;
}
DownloadCommand::CleanDry => {
let workspace_and_flow = workspace_and_flow_setup(workspace_spec, flow_id).await?;
let mut cmd_ctx =
cmd_ctx(&workspace_and_flow, profile, &mut cli_output, None).await?;
clean_dry(&mut cmd_ctx).await?;
}
DownloadCommand::Clean => {
let workspace_and_flow = workspace_and_flow_setup(workspace_spec, flow_id).await?;
let mut cmd_ctx =
cmd_ctx(&workspace_and_flow, profile, &mut cli_output, None).await?;
clean(&mut cmd_ctx).await?;
}
}
Ok::<_, DownloadError>(())
})
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/download/src/wasm.rs | examples/download/src/wasm.rs | use peace::{
flow_model::flow_id,
profile_model::profile,
rt_model::{InMemoryTextOutput, WorkspaceSpec},
};
use peace_items::file_download::{FileDownloadParams, StorageForm};
use url::Url;
use wasm_bindgen::prelude::*;
pub use crate::{
clean, clean_dry, cmd_ctx, diff, ensure, ensure_dry, fetch, goal, status,
workspace_and_flow_setup, WorkspaceAndFlow,
};
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
}
#[wasm_bindgen(getter_with_clone)]
pub struct WorkspaceAndOutput {
workspace_and_flow: WorkspaceAndFlow,
pub output: String,
}
#[wasm_bindgen]
pub async fn wasm_init(url: String, name: String) -> Result<WorkspaceAndOutput, JsValue> {
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
let workspace_and_output =
workspace_and_flow_setup(WorkspaceSpec::SessionStorage, flow_id!("file"))
.await
.map(|workspace_and_flow| async move {
let output = String::new();
Result::<_, JsValue>::Ok(WorkspaceAndOutput {
workspace_and_flow,
output,
})
})
.map_err(into_js_err_value)?
.await?;
// Store init params in storage.
let file_download_params = {
let url = Url::parse(&url).expect("Failed to parse URL.");
let dest = std::path::PathBuf::from(name);
FileDownloadParams::new(url, dest, StorageForm::Text)
};
// Building the command context currently serializes the init params to storage.
let WorkspaceAndOutput {
workspace_and_flow,
output: _,
} = workspace_and_output;
let mut in_memory_text_output = InMemoryTextOutput::new();
let _cmd_ctx = cmd_ctx(
&workspace_and_flow,
profile!("default"),
&mut in_memory_text_output,
Some(file_download_params),
)
.await
.map_err(into_js_err_value)?;
let output = in_memory_text_output.into_inner();
Ok(WorkspaceAndOutput {
workspace_and_flow,
output,
})
}
#[wasm_bindgen]
pub async fn wasm_fetch(
workspace_and_output: WorkspaceAndOutput,
) -> Result<WorkspaceAndOutput, JsValue> {
let WorkspaceAndOutput {
workspace_and_flow,
output: _,
} = workspace_and_output;
let mut in_memory_text_output = InMemoryTextOutput::new();
let mut cmd_ctx = cmd_ctx(
&workspace_and_flow,
profile!("default"),
&mut in_memory_text_output,
None,
)
.await
.map_err(into_js_err_value)?;
fetch(&mut cmd_ctx).await.map_err(into_js_err_value)?;
let output = in_memory_text_output.into_inner();
Ok(WorkspaceAndOutput {
workspace_and_flow,
output,
})
}
#[wasm_bindgen]
pub async fn wasm_status(
workspace_and_output: WorkspaceAndOutput,
) -> Result<WorkspaceAndOutput, JsValue> {
let WorkspaceAndOutput {
workspace_and_flow,
output: _,
} = workspace_and_output;
let mut in_memory_text_output = InMemoryTextOutput::new();
let mut cmd_ctx = cmd_ctx(
&workspace_and_flow,
profile!("default"),
&mut in_memory_text_output,
None,
)
.await
.map_err(into_js_err_value)?;
status(&mut cmd_ctx).await.map_err(into_js_err_value)?;
let output = in_memory_text_output.into_inner();
Ok(WorkspaceAndOutput {
workspace_and_flow,
output,
})
}
#[wasm_bindgen]
pub async fn wasm_goal(
workspace_and_output: WorkspaceAndOutput,
) -> Result<WorkspaceAndOutput, JsValue> {
let WorkspaceAndOutput {
workspace_and_flow,
output: _,
} = workspace_and_output;
let mut in_memory_text_output = InMemoryTextOutput::new();
let mut cmd_ctx = cmd_ctx(
&workspace_and_flow,
profile!("default"),
&mut in_memory_text_output,
None,
)
.await
.map_err(into_js_err_value)?;
goal(&mut cmd_ctx).await.map_err(into_js_err_value)?;
let output = in_memory_text_output.into_inner();
Ok(WorkspaceAndOutput {
workspace_and_flow,
output,
})
}
#[wasm_bindgen]
pub async fn wasm_diff(
workspace_and_output: WorkspaceAndOutput,
) -> Result<WorkspaceAndOutput, JsValue> {
let WorkspaceAndOutput {
workspace_and_flow,
output: _,
} = workspace_and_output;
let mut in_memory_text_output = InMemoryTextOutput::new();
let mut cmd_ctx = cmd_ctx(
&workspace_and_flow,
profile!("default"),
&mut in_memory_text_output,
None,
)
.await
.map_err(into_js_err_value)?;
diff(&mut cmd_ctx).await.map_err(into_js_err_value)?;
let output = in_memory_text_output.into_inner();
Ok(WorkspaceAndOutput {
workspace_and_flow,
output,
})
}
#[wasm_bindgen]
pub async fn wasm_ensure_dry(
workspace_and_output: WorkspaceAndOutput,
) -> Result<WorkspaceAndOutput, JsValue> {
let WorkspaceAndOutput {
workspace_and_flow,
output: _,
} = workspace_and_output;
let mut in_memory_text_output = InMemoryTextOutput::new();
let mut cmd_ctx = cmd_ctx(
&workspace_and_flow,
profile!("default"),
&mut in_memory_text_output,
None,
)
.await
.map_err(into_js_err_value)?;
ensure_dry(&mut cmd_ctx).await.map_err(into_js_err_value)?;
let output = in_memory_text_output.into_inner();
Ok(WorkspaceAndOutput {
workspace_and_flow,
output,
})
}
#[wasm_bindgen]
pub async fn wasm_ensure(
workspace_and_output: WorkspaceAndOutput,
) -> Result<WorkspaceAndOutput, JsValue> {
let WorkspaceAndOutput {
workspace_and_flow,
output: _,
} = workspace_and_output;
let mut in_memory_text_output = InMemoryTextOutput::new();
let mut cmd_ctx = cmd_ctx(
&workspace_and_flow,
profile!("default"),
&mut in_memory_text_output,
None,
)
.await
.map_err(into_js_err_value)?;
ensure(&mut cmd_ctx).await.map_err(into_js_err_value)?;
let output = in_memory_text_output.into_inner();
Ok(WorkspaceAndOutput {
workspace_and_flow,
output,
})
}
#[wasm_bindgen]
pub async fn wasm_clean_dry(
workspace_and_output: WorkspaceAndOutput,
) -> Result<WorkspaceAndOutput, JsValue> {
let WorkspaceAndOutput {
workspace_and_flow,
output: _,
} = workspace_and_output;
let mut in_memory_text_output = InMemoryTextOutput::new();
let mut cmd_ctx = cmd_ctx(
&workspace_and_flow,
profile!("default"),
&mut in_memory_text_output,
None,
)
.await
.map_err(into_js_err_value)?;
clean_dry(&mut cmd_ctx).await.map_err(into_js_err_value)?;
let output = in_memory_text_output.into_inner();
Ok(WorkspaceAndOutput {
workspace_and_flow,
output,
})
}
#[wasm_bindgen]
pub async fn wasm_clean(
workspace_and_output: WorkspaceAndOutput,
) -> Result<WorkspaceAndOutput, JsValue> {
let WorkspaceAndOutput {
workspace_and_flow,
output: _,
} = workspace_and_output;
let mut in_memory_text_output = InMemoryTextOutput::new();
let mut cmd_ctx = cmd_ctx(
&workspace_and_flow,
profile!("default"),
&mut in_memory_text_output,
None,
)
.await
.map_err(into_js_err_value)?;
clean(&mut cmd_ctx).await.map_err(into_js_err_value)?;
let output = in_memory_text_output.into_inner();
Ok(WorkspaceAndOutput {
workspace_and_flow,
output,
})
}
fn into_js_err_value<E>(e: E) -> JsValue
where
E: std::error::Error,
{
use std::{error::Error, fmt::Write};
let mut buffer = String::with_capacity(256);
writeln!(&mut buffer, "{e}").unwrap();
let mut source_opt: Option<&(dyn Error + 'static)> = e.source();
while let Some(source) = source_opt {
writeln!(&mut buffer, "Caused by:").unwrap();
writeln!(&mut buffer, "{source}").unwrap();
source_opt = source.source();
}
JsValue::from_str(&buffer)
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/file_download/src/file_download_state.rs | items/file_download/src/file_download_state.rs | use std::fmt;
use peace::cfg::{state::FetchedOpt, State};
use serde::{Deserialize, Serialize};
use crate::{ETag, FileDownloadStateLogical};
#[cfg(feature = "output_progress")]
use peace::item_interaction_model::ItemLocationState;
/// Newtype wrapper for `State<FileDownloadStatePhysical, FetchedOpt<ETag>>`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FileDownloadState(pub State<FileDownloadStateLogical, FetchedOpt<ETag>>);
impl FileDownloadState {
/// Returns a new `FileDownloadState`.
pub fn new(
file_download_state_logical: FileDownloadStateLogical,
etag: FetchedOpt<ETag>,
) -> Self {
Self(State::new(file_download_state_logical, etag))
}
}
impl From<State<FileDownloadStateLogical, FetchedOpt<ETag>>> for FileDownloadState {
fn from(state: State<FileDownloadStateLogical, FetchedOpt<ETag>>) -> Self {
Self(state)
}
}
impl fmt::Display for FileDownloadState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
#[cfg(feature = "output_progress")]
impl<'state> From<&'state FileDownloadState> for ItemLocationState {
fn from(state: &'state FileDownloadState) -> ItemLocationState {
match &state.0.logical {
FileDownloadStateLogical::None { .. } => ItemLocationState::NotExists,
FileDownloadStateLogical::StringContents { .. }
| FileDownloadStateLogical::Length { .. }
| FileDownloadStateLogical::Unknown { .. } => ItemLocationState::Exists,
}
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/file_download/src/file_download_state_current_fn.rs | items/file_download/src/file_download_state_current_fn.rs | use std::{marker::PhantomData, path::Path};
use peace::{
cfg::{state::FetchedOpt, FnCtx},
params::Params,
};
#[cfg(not(target_arch = "wasm32"))]
use tokio::{fs::File, io::AsyncReadExt};
#[cfg(target_arch = "wasm32")]
use peace::rt_model::Storage;
use crate::{
FileDownloadData, FileDownloadError, FileDownloadParams, FileDownloadState,
FileDownloadStateLogical,
};
/// Reads the current state of the file to download.
#[derive(Debug)]
pub struct FileDownloadStateCurrentFn<Id>(PhantomData<Id>);
impl<Id> FileDownloadStateCurrentFn<Id>
where
Id: Send + Sync,
{
pub async fn try_state_current(
_fn_ctx: FnCtx<'_>,
params_partial: &<FileDownloadParams<Id> as Params>::Partial,
data: FileDownloadData<'_, Id>,
) -> Result<Option<FileDownloadState>, FileDownloadError> {
if let Some(dest) = params_partial.dest() {
Self::state_current_internal(data, dest).await.map(Some)
} else {
Ok(None)
}
}
pub async fn state_current(
_fn_ctx: FnCtx<'_>,
params: &FileDownloadParams<Id>,
data: FileDownloadData<'_, Id>,
) -> Result<FileDownloadState, FileDownloadError> {
let dest = params.dest();
Self::state_current_internal(data, dest).await
}
async fn state_current_internal(
data: FileDownloadData<'_, Id>,
dest: &Path,
) -> Result<FileDownloadState, FileDownloadError> {
#[cfg(not(target_arch = "wasm32"))]
let file_exists = dest.exists();
#[cfg(target_arch = "wasm32")]
let file_exists = data.storage().get_item_opt(dest)?.is_some();
if !file_exists {
return Ok(FileDownloadState::new(
FileDownloadStateLogical::None {
path: Some(dest.to_path_buf()),
},
FetchedOpt::Tbd,
));
}
// Check file length
#[cfg(not(target_arch = "wasm32"))]
let file_state = Self::read_file_contents(dest).await?;
#[cfg(target_arch = "wasm32")]
let file_state = Self::read_file_contents(dest, data.storage()).await?;
let e_tag = data
.state_working()
.as_ref()
.map(|state_working| state_working.0.physical.clone())
.or_else(|| {
data.state_prev()
.get()
.map(|state_prev| state_prev.0.physical.clone())
})
.unwrap_or(if let FileDownloadStateLogical::None { .. } = &file_state {
FetchedOpt::Tbd
} else {
FetchedOpt::None
});
Ok(FileDownloadState::new(file_state, e_tag))
}
#[cfg(not(target_arch = "wasm32"))]
async fn read_file_contents(
dest: &std::path::Path,
) -> Result<FileDownloadStateLogical, FileDownloadError> {
let mut file = File::open(dest)
.await
.map_err(FileDownloadError::DestFileOpen)?;
let metadata = file
.metadata()
.await
.map_err(FileDownloadError::DestMetadataRead)?;
let file_state = if metadata.len() > crate::IN_MEMORY_CONTENTS_MAX {
FileDownloadStateLogical::Unknown {
path: dest.to_path_buf(),
}
} else {
let mut buffer = String::new();
file.read_to_string(&mut buffer)
.await
.map_err(FileDownloadError::DestFileRead)?;
FileDownloadStateLogical::StringContents {
path: dest.to_path_buf(),
contents: buffer,
}
};
Ok(file_state)
}
#[cfg(target_arch = "wasm32")]
async fn read_file_contents(
dest: &std::path::Path,
storage: &Storage,
) -> Result<FileDownloadStateLogical, FileDownloadError> {
let file_state = storage
.get_item_opt(dest)?
.map(|contents| {
contents
.bytes()
.len()
.try_into()
.map(|byte_count: u64| {
if byte_count > crate::IN_MEMORY_CONTENTS_MAX {
FileDownloadStateLogical::Unknown {
path: dest.to_path_buf(),
}
} else {
FileDownloadStateLogical::StringContents {
path: dest.to_path_buf(),
contents: contents.clone(),
}
}
})
.unwrap_or_else(|_| FileDownloadStateLogical::StringContents {
path: dest.to_path_buf(),
contents: contents.clone(),
})
})
.unwrap_or(FileDownloadStateLogical::None {
path: Some(dest.to_path_buf()),
});
Ok(file_state)
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/file_download/src/file_download_state_goal_fn.rs | items/file_download/src/file_download_state_goal_fn.rs | use std::{marker::PhantomData, path::Path};
use peace::{
cfg::{state::FetchedOpt, FnCtx},
params::Params,
};
use reqwest::{header::ETAG, Url};
use crate::{
ETag, FileDownloadData, FileDownloadError, FileDownloadParams, FileDownloadState,
FileDownloadStateLogical,
};
/// Reads the goal state of the file to download.
#[derive(Debug)]
pub struct FileDownloadStateGoalFn<Id>(PhantomData<Id>);
impl<Id> FileDownloadStateGoalFn<Id>
where
Id: Send + Sync + 'static,
{
pub async fn try_state_goal(
_fn_ctx: FnCtx<'_>,
params_partial: &<FileDownloadParams<Id> as Params>::Partial,
data: FileDownloadData<'_, Id>,
) -> Result<Option<FileDownloadState>, FileDownloadError> {
if let Some((src, dest)) = params_partial.src().zip(params_partial.dest()) {
Self::file_state_goal(&data, src, dest).await.map(Some)
} else {
Ok(None)
}
}
pub async fn state_goal(
_fn_ctx: FnCtx<'_>,
params: &FileDownloadParams<Id>,
data: FileDownloadData<'_, Id>,
) -> Result<FileDownloadState, FileDownloadError> {
let file_state_goal = Self::file_state_goal(&data, params.src(), params.dest()).await?;
Ok(file_state_goal)
}
async fn file_state_goal(
data: &FileDownloadData<'_, Id>,
src_url: &Url,
dest: &Path,
) -> Result<FileDownloadState, FileDownloadError> {
let client = data.client();
let response = client
.get(src_url.clone())
.send()
.await
.map_err(|error| FileDownloadError::src_get(src_url.clone(), error))?;
let status_code = response.status();
if status_code.is_success() {
let content_length = response.content_length();
let e_tag = response
.headers()
.get(ETAG)
.and_then(|header| header.to_str().ok())
.map(|header| ETag::new(header.to_string()))
.map(FetchedOpt::Value)
.unwrap_or(FetchedOpt::None);
let file_download_state = if let Some(remote_file_length) = content_length {
if remote_file_length <= crate::IN_MEMORY_CONTENTS_MAX {
// Download it now.
let remote_contents = async move {
let response_text = response.text();
response_text.await.map_err(FileDownloadError::SrcFileRead)
}
.await?;
FileDownloadStateLogical::StringContents {
path: dest.to_path_buf(),
contents: remote_contents,
}
} else {
// Stream it later.
FileDownloadStateLogical::Length {
path: dest.to_path_buf(),
byte_count: remote_file_length,
}
}
} else {
FileDownloadStateLogical::Unknown {
path: dest.to_path_buf(),
}
};
Ok(FileDownloadState::new(file_download_state, e_tag))
} else {
Err(FileDownloadError::SrcFileUndetermined { status_code })
}
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/file_download/src/file_download_apply_fns.rs | items/file_download/src/file_download_apply_fns.rs | use std::marker::PhantomData;
cfg_if::cfg_if! {
if #[cfg(not(target_arch = "wasm32"))] {
use bytes::Bytes;
use futures::{Stream, StreamExt, TryStreamExt};
use tokio::io::AsyncWriteExt;
use tokio::{fs::File, io::BufWriter};
} else if #[cfg(target_arch = "wasm32")] {
use std::path::Path;
use peace::rt_model::Storage;
}
}
use peace::cfg::{state::FetchedOpt, ApplyCheck, FnCtx, State};
use reqwest::header::ETAG;
use crate::{
ETag, FileDownloadData, FileDownloadError, FileDownloadParams, FileDownloadState,
FileDownloadStateDiff, FileDownloadStateLogical,
};
#[cfg(feature = "output_progress")]
use peace::{
diff::Tracked,
progress_model::{ProgressLimit, ProgressMsgUpdate},
};
/// ApplyFns for the file to download.
#[derive(Debug)]
pub struct FileDownloadApplyFns<Id>(PhantomData<Id>);
impl<Id> FileDownloadApplyFns<Id>
where
Id: Send + Sync + 'static,
{
async fn file_download(
#[cfg(not(feature = "output_progress"))] _fn_ctx: FnCtx<'_>,
#[cfg(feature = "output_progress")] fn_ctx: FnCtx<'_>,
params: &FileDownloadParams<Id>,
data: FileDownloadData<'_, Id>,
) -> Result<FetchedOpt<ETag>, FileDownloadError> {
let client = data.client();
let src_url = params.src();
#[cfg(feature = "output_progress")]
fn_ctx
.progress_sender
.tick(ProgressMsgUpdate::Set(String::from("starting download")));
let response = client
.get(src_url.clone())
.send()
.await
.map_err(|error| FileDownloadError::src_get(src_url.clone(), error))?;
let e_tag = response
.headers()
.get(ETAG)
.and_then(|header| header.to_str().ok())
.map(|header| ETag::new(header.to_string()))
.map(FetchedOpt::Value)
.unwrap_or(FetchedOpt::None);
#[cfg(not(target_arch = "wasm32"))]
{
Self::stream_write(
#[cfg(feature = "output_progress")]
fn_ctx,
params,
response.bytes_stream(),
)
.await?;
}
// reqwest in wasm doesn't support streams
// https://github.com/seanmonstar/reqwest/issues/1424
#[cfg(target_arch = "wasm32")]
{
Self::stream_write(
#[cfg(feature = "output_progress")]
fn_ctx,
params.dest(),
data.storage(),
params.storage_form(),
response,
)
.await?;
}
Ok(e_tag)
}
/// Streams the content to disk.
#[cfg(not(target_arch = "wasm32"))]
async fn stream_write(
#[cfg(feature = "output_progress")] fn_ctx: FnCtx<'_>,
file_download_params: &FileDownloadParams<Id>,
byte_stream: impl Stream<Item = reqwest::Result<Bytes>>,
) -> Result<(), FileDownloadError> {
use std::{fmt::Write, path::Component};
#[cfg(feature = "error_reporting")]
use peace::miette::{SourceOffset, SourceSpan};
let dest_path = file_download_params.dest();
if let Some(dest_parent) = dest_path.parent() {
// Ensure all parent directories are created
tokio::fs::create_dir_all(dest_parent)
.await
.map_err(|error| {
#[cfg(feature = "error_reporting")]
let dest_display = format!("{}", dest_path.display());
#[cfg(feature = "error_reporting")]
let parent_dirs_span = {
let start = 1usize;
SourceSpan::from((start, dest_display.len()))
};
FileDownloadError::DestParentDirsCreate {
dest: dest_path.to_path_buf(),
dest_parent: dest_parent.to_path_buf(),
#[cfg(feature = "error_reporting")]
dest_display,
#[cfg(feature = "error_reporting")]
parent_dirs_span,
error,
}
})?;
}
let dest_file = File::create(dest_path).await.or_else(|error| {
let mut init_command_approx = String::with_capacity(256);
let exe_path = std::env::current_exe().map_err(FileDownloadError::CurrentExeRead)?;
let exe_name =
if let Some(Component::Normal(exe_name)) = exe_path.components().next_back() {
exe_name
} else {
return Err(FileDownloadError::CurrentExeNameRead);
};
let exe_name = exe_name.to_string_lossy();
let src = file_download_params.src();
let dest = dest_path.to_path_buf();
let dest_display = dest.display();
write!(&mut init_command_approx, "{exe_name} init {src} ")
.map_err(FileDownloadError::FormatString)?;
#[cfg(feature = "error_reporting")]
let dest_offset_col = init_command_approx.len();
write!(&mut init_command_approx, "{dest_display}")
.map_err(FileDownloadError::FormatString)?;
#[cfg(feature = "error_reporting")]
let dest_span = {
let loc_line = 1;
// Add one to offset because we are 1-based, not 0-based?
let start = SourceOffset::from_location(
&init_command_approx,
loc_line,
dest_offset_col + 1,
);
// Add one to length because we are 1-based, not 0-based?
let length = init_command_approx.len() - dest_offset_col + 1;
SourceSpan::new(start, length)
};
Err(FileDownloadError::DestFileCreate {
init_command_approx,
#[cfg(feature = "error_reporting")]
dest_span,
dest,
error,
})
})?;
let buffer = BufWriter::new(dest_file);
#[cfg(feature = "output_progress")]
let progress_sender = &fn_ctx.progress_sender;
let mut buffer = byte_stream
.map(|bytes_result| bytes_result.map_err(FileDownloadError::ResponseBytesStream))
.try_fold(buffer, |mut buffer, bytes| async move {
buffer
.write_all(&bytes)
.await
.map_err(FileDownloadError::ResponseFileWrite)?;
#[cfg(feature = "output_progress")]
if let Ok(progress_inc) = u64::try_from(bytes.len()) {
progress_sender.inc(progress_inc, ProgressMsgUpdate::NoChange)
} else {
progress_sender.tick(ProgressMsgUpdate::NoChange)
};
Ok(buffer)
})
.await?;
buffer
.flush()
.await
.map_err(FileDownloadError::ResponseFileWrite)?;
Ok(())
}
/// Streams the content to disk.
#[cfg(target_arch = "wasm32")]
async fn stream_write(
#[cfg(feature = "output_progress")] _fn_ctx: FnCtx<'_>,
dest_path: &Path,
storage: &Storage,
storage_form: crate::StorageForm,
response: reqwest::Response,
) -> Result<(), FileDownloadError> {
use crate::StorageForm;
match storage_form {
StorageForm::Text => {
let value = response
.text()
.await
.map_err(FileDownloadError::ResponseTextRead)?;
storage.set_item(dest_path, &value)?;
}
StorageForm::Base64 => {
let bytes = response
.bytes()
.await
.map_err(FileDownloadError::ResponseBytesRead)?;
storage.set_item_b64(dest_path, &bytes)?;
}
}
Ok(())
}
}
impl<Id> FileDownloadApplyFns<Id>
where
Id: Send + Sync + 'static,
{
pub async fn apply_check(
_params: &FileDownloadParams<Id>,
_data: FileDownloadData<'_, Id>,
FileDownloadState(State {
logical: file_state_current,
physical: _e_tag,
}): &FileDownloadState,
_file_download_state_goal: &FileDownloadState,
diff: &FileDownloadStateDiff,
) -> Result<ApplyCheck, FileDownloadError> {
let apply_check = match diff {
FileDownloadStateDiff::Change {
#[cfg(feature = "output_progress")]
byte_len,
..
} => {
#[cfg(not(feature = "output_progress"))]
{
ApplyCheck::ExecRequired
}
#[cfg(feature = "output_progress")]
{
let progress_limit = match byte_len.to {
Tracked::None => ProgressLimit::Unknown,
Tracked::Known(len) => len
.try_into()
.map(ProgressLimit::Bytes)
.unwrap_or(ProgressLimit::Unknown),
Tracked::Unknown => ProgressLimit::Unknown,
};
ApplyCheck::ExecRequired { progress_limit }
}
}
FileDownloadStateDiff::Deleted { .. } => match file_state_current {
FileDownloadStateLogical::None { .. } => ApplyCheck::ExecNotRequired,
FileDownloadStateLogical::StringContents {
path: _,
#[cfg(not(feature = "output_progress"))]
contents: _,
#[cfg(feature = "output_progress")]
contents,
} => {
#[cfg(not(feature = "output_progress"))]
{
ApplyCheck::ExecRequired
}
#[cfg(feature = "output_progress")]
{
ApplyCheck::ExecRequired {
progress_limit: ProgressLimit::Bytes(
contents.len().try_into().unwrap(),
),
}
}
}
FileDownloadStateLogical::Length {
path: _,
#[cfg(not(feature = "output_progress"))]
byte_count: _,
#[cfg(feature = "output_progress")]
byte_count,
} => {
#[cfg(not(feature = "output_progress"))]
{
ApplyCheck::ExecRequired
}
#[cfg(feature = "output_progress")]
ApplyCheck::ExecRequired {
progress_limit: ProgressLimit::Bytes(*byte_count),
}
}
FileDownloadStateLogical::Unknown { path: _ } => {
#[cfg(not(feature = "output_progress"))]
{
ApplyCheck::ExecRequired
}
#[cfg(feature = "output_progress")]
ApplyCheck::ExecRequired {
progress_limit: ProgressLimit::Unknown,
}
}
},
FileDownloadStateDiff::NoChangeNotExists { .. }
| FileDownloadStateDiff::NoChangeSync { .. } => ApplyCheck::ExecNotRequired,
};
Ok(apply_check)
}
pub async fn apply_dry(
_fn_ctx: FnCtx<'_>,
_params: &FileDownloadParams<Id>,
_data: FileDownloadData<'_, Id>,
_file_download_state_current: &FileDownloadState,
file_download_state_goal: &FileDownloadState,
_diff: &FileDownloadStateDiff,
) -> Result<FileDownloadState, FileDownloadError> {
// TODO: fetch headers but don't write to file.
Ok(file_download_state_goal.clone())
}
pub async fn apply(
fn_ctx: FnCtx<'_>,
params: &FileDownloadParams<Id>,
data: FileDownloadData<'_, Id>,
_file_download_state_current: &FileDownloadState,
file_download_state_goal: &FileDownloadState,
diff: &FileDownloadStateDiff,
) -> Result<FileDownloadState, FileDownloadError> {
match diff {
FileDownloadStateDiff::Deleted { path } => {
#[cfg(feature = "output_progress")]
fn_ctx
.progress_sender
.tick(ProgressMsgUpdate::Set(String::from("removing file")));
#[cfg(not(target_arch = "wasm32"))]
tokio::fs::remove_file(path)
.await
.map_err(FileDownloadError::DestFileRemove)?;
#[cfg(target_arch = "wasm32")]
data.storage().remove_item(path)?;
Ok(file_download_state_goal.clone())
}
FileDownloadStateDiff::Change { .. } => {
let e_tag = Self::file_download(fn_ctx, params, data).await?;
let mut file_download_state_ensured = file_download_state_goal.clone();
file_download_state_ensured.0.physical = e_tag;
Ok(file_download_state_ensured)
}
FileDownloadStateDiff::NoChangeNotExists { .. }
| FileDownloadStateDiff::NoChangeSync { .. } => {
unreachable!("exec is never called when file is in sync.")
}
}
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/file_download/src/lib.rs | items/file_download/src/lib.rs | //! Manages downloading a file for the peace framework
pub use crate::{
e_tag::ETag,
file_download_apply_fns::FileDownloadApplyFns,
file_download_data::FileDownloadData,
file_download_error::FileDownloadError,
file_download_item::FileDownloadItem,
file_download_params::{
FileDownloadParams, FileDownloadParamsFieldWise, FileDownloadParamsPartial,
},
file_download_state::FileDownloadState,
file_download_state_current_fn::FileDownloadStateCurrentFn,
file_download_state_diff::FileDownloadStateDiff,
file_download_state_diff_fn::FileDownloadStateDiffFn,
file_download_state_goal_fn::FileDownloadStateGoalFn,
file_download_state_logical::FileDownloadStateLogical,
};
#[cfg(target_arch = "wasm32")]
pub use crate::storage_form::StorageForm;
mod e_tag;
mod file_download_apply_fns;
mod file_download_data;
mod file_download_error;
mod file_download_item;
mod file_download_params;
mod file_download_state;
mod file_download_state_current_fn;
mod file_download_state_diff;
mod file_download_state_diff_fn;
mod file_download_state_goal_fn;
mod file_download_state_logical;
#[cfg(target_arch = "wasm32")]
mod storage_form;
/// Read up to 1 kB in memory.
pub const IN_MEMORY_CONTENTS_MAX: u64 = 1024;
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/file_download/src/e_tag.rs | items/file_download/src/e_tag.rs | use serde::{Deserialize, Serialize};
/// Represents an ETag returned from a server.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct ETag(String);
impl ETag {
/// Returns a new `ETag`.
pub fn new<S>(s: S) -> Self
where
S: Into<String>,
{
Self(s.into())
}
}
impl std::ops::Deref for ETag {
type Target = str;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for ETag {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl std::fmt::Display for ETag {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/file_download/src/file_download_state_diff.rs | items/file_download/src/file_download_state_diff.rs | use std::{fmt, path::PathBuf};
use peace::diff::{Changeable, Tracked};
use serde::{Deserialize, Serialize};
/// Diff between the current and goal downloaded file.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum FileDownloadStateDiff {
/// File exists locally, but does not exist on server.
Deleted {
/// Path to the file.
path: PathBuf,
},
/// File does not exist both locally and on server.
NoChangeNotExists {
/// Path to the file.
path: Option<PathBuf>,
},
/// File exists both locally and on server, and they are in sync.
NoChangeSync {
/// Path to the file.
path: PathBuf,
},
/// There is a change.
Change {
/// Path to the file.
path: PathBuf,
/// Possible change in byte length.
byte_len: Changeable<usize>,
/// Possible change in contents.
contents: Changeable<String>,
},
}
impl fmt::Display for FileDownloadStateDiff {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Deleted { path } => write!(
f,
"resource does not exist on server; locally `{}` exists, but ensure will not delete it",
path.display()
),
Self::NoChangeNotExists { path } => {
write!(f, "resource does not exist on server",)?;
if let Some(path) = path {
write!(f, ", and `{}` does not exist locally", path.display())?;
}
Ok(())
}
Self::NoChangeSync { path } => write!(f, "`{}` in sync with server", path.display()),
Self::Change {
path,
byte_len,
contents: _,
} => {
write!(f, "`{}` will change", path.display())?;
match byte_len.from {
Tracked::None => {
write!(f, " from 0 bytes")?;
}
Tracked::Unknown => {}
Tracked::Known(byte_count) => {
write!(f, " from {byte_count} bytes")?;
}
}
match byte_len.to {
Tracked::None => {
write!(f, " to 0 bytes")?;
}
Tracked::Unknown => {
write!(f, " to unknown size")?;
}
Tracked::Known(byte_count) => {
write!(f, " to {byte_count} bytes")?;
}
}
Ok(())
}
}
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/file_download/src/file_download_state_diff_fn.rs | items/file_download/src/file_download_state_diff_fn.rs | use peace::{
cfg::{state::FetchedOpt, State},
diff::{Changeable, Tracked},
};
use crate::{
FileDownloadError, FileDownloadState, FileDownloadStateDiff, FileDownloadStateLogical,
};
/// Download status diff function.
#[derive(Debug)]
pub struct FileDownloadStateDiffFn;
impl FileDownloadStateDiffFn {
pub async fn state_diff(
state_current: &FileDownloadState,
state_goal: &FileDownloadState,
) -> Result<FileDownloadStateDiff, FileDownloadError> {
let FileDownloadState(State {
logical: file_state_current,
physical: e_tag_current,
}) = state_current;
let FileDownloadState(State {
logical: file_state_goal,
physical: e_tag_goal,
}) = state_goal;
let file_state_diff = {
match (file_state_current, file_state_goal) {
(
FileDownloadStateLogical::StringContents { path, .. }
| FileDownloadStateLogical::Length { path, .. }
| FileDownloadStateLogical::Unknown { path, .. },
FileDownloadStateLogical::None { .. },
) => FileDownloadStateDiff::Deleted {
path: path.to_path_buf(),
},
(
file_state_current @ (FileDownloadStateLogical::StringContents { .. }
| FileDownloadStateLogical::Length { .. }
| FileDownloadStateLogical::Unknown { .. }),
file_state_goal @ (FileDownloadStateLogical::StringContents { path, .. }
| FileDownloadStateLogical::Length { path, .. }
| FileDownloadStateLogical::Unknown { path, .. }),
)
| (
file_state_current @ FileDownloadStateLogical::None { .. },
file_state_goal @ (FileDownloadStateLogical::StringContents { path, .. }
| FileDownloadStateLogical::Length { path, .. }
| FileDownloadStateLogical::Unknown { path, .. }),
) => {
let path = path.to_path_buf();
let (from_bytes, from_content) = to_file_state_diff(file_state_current);
let (to_bytes, to_content) = to_file_state_diff(file_state_goal);
match (from_bytes == to_bytes, from_content == to_content) {
(_, false) => {
// File contents are either changed, or unknown
match (e_tag_current, e_tag_goal) {
(
FetchedOpt::Value(e_tag_current),
FetchedOpt::Value(e_tag_goal),
) if e_tag_current == e_tag_goal => {
FileDownloadStateDiff::NoChangeSync { path }
}
_ => FileDownloadStateDiff::Change {
path,
byte_len: Changeable::new(from_bytes, to_bytes),
contents: Changeable::new(from_content, to_content),
},
}
}
(false, true) => {
// File contents are the same, length is unknown
FileDownloadStateDiff::NoChangeSync { path }
}
(true, true) => FileDownloadStateDiff::NoChangeSync { path },
}
}
(
FileDownloadStateLogical::None { .. },
FileDownloadStateLogical::None { path },
) => FileDownloadStateDiff::NoChangeNotExists { path: path.clone() },
}
};
Ok(file_state_diff)
}
}
fn to_file_state_diff(file_state: &FileDownloadStateLogical) -> (Tracked<usize>, Tracked<String>) {
match file_state {
FileDownloadStateLogical::None { .. } => (Tracked::None, Tracked::None),
FileDownloadStateLogical::StringContents { path: _, contents } => (
Tracked::Known(contents.len()),
Tracked::Known(contents.to_owned()),
),
FileDownloadStateLogical::Length {
path: _,
byte_count,
} => (
(*byte_count)
.try_into()
.map(Tracked::Known)
.unwrap_or(Tracked::Unknown),
Tracked::Unknown,
),
FileDownloadStateLogical::Unknown { .. } => (Tracked::Unknown, Tracked::Unknown),
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/file_download/src/file_download_item.rs | items/file_download/src/file_download_item.rs | use std::{marker::PhantomData, path::Path};
use peace::{
cfg::{async_trait, state::FetchedOpt, ApplyCheck, FnCtx, Item},
item_model::ItemId,
params::Params,
resource_rt::{resources::ts::Empty, Resources},
};
use crate::{
FileDownloadApplyFns, FileDownloadData, FileDownloadError, FileDownloadParams,
FileDownloadState, FileDownloadStateCurrentFn, FileDownloadStateDiff, FileDownloadStateDiffFn,
FileDownloadStateGoalFn, FileDownloadStateLogical,
};
/// Item for downloading a file.
///
/// The `Id` type parameter is needed for each file download params to be a
/// distinct type.
///
/// # Type Parameters
///
/// * `Id`: A zero-sized type used to distinguish different file download
/// parameters from each other.
#[derive(Debug)]
pub struct FileDownloadItem<Id> {
/// ID of the item to download the file.
item_id: ItemId,
/// Marker for unique download parameters type.
marker: PhantomData<Id>,
}
impl<Id> Clone for FileDownloadItem<Id> {
fn clone(&self) -> Self {
Self {
item_id: self.item_id.clone(),
marker: PhantomData,
}
}
}
impl<Id> FileDownloadItem<Id> {
/// Returns a new `FileDownloadItem`.
pub fn new(item_id: ItemId) -> Self {
Self {
item_id,
marker: PhantomData,
}
}
}
#[async_trait(?Send)]
impl<Id> Item for FileDownloadItem<Id>
where
Id: Send + Sync + 'static,
{
type Data<'exec> = FileDownloadData<'exec, Id>;
type Error = FileDownloadError;
type Params<'exec> = FileDownloadParams<Id>;
type State = FileDownloadState;
type StateDiff = FileDownloadStateDiff;
fn id(&self) -> &ItemId {
&self.item_id
}
async fn setup(&self, resources: &mut Resources<Empty>) -> Result<(), FileDownloadError> {
resources.insert::<reqwest::Client>(reqwest::Client::new());
Ok(())
}
#[cfg(feature = "item_state_example")]
fn state_example(params: &Self::Params<'_>, _data: Self::Data<'_>) -> Self::State {
let dest = params.dest();
FileDownloadState::new(
FileDownloadStateLogical::StringContents {
path: dest.to_path_buf(),
contents: "example contents".to_string(),
},
FetchedOpt::None,
)
}
async fn try_state_current(
fn_ctx: FnCtx<'_>,
params_partial: &<Self::Params<'_> as Params>::Partial,
data: FileDownloadData<'_, Id>,
) -> Result<Option<Self::State>, FileDownloadError> {
FileDownloadStateCurrentFn::try_state_current(fn_ctx, params_partial, data).await
}
async fn state_current(
fn_ctx: FnCtx<'_>,
params: &Self::Params<'_>,
data: FileDownloadData<'_, Id>,
) -> Result<Self::State, FileDownloadError> {
FileDownloadStateCurrentFn::state_current(fn_ctx, params, data).await
}
async fn try_state_goal(
fn_ctx: FnCtx<'_>,
params_partial: &<Self::Params<'_> as Params>::Partial,
data: FileDownloadData<'_, Id>,
) -> Result<Option<Self::State>, FileDownloadError> {
FileDownloadStateGoalFn::try_state_goal(fn_ctx, params_partial, data).await
}
async fn state_goal(
fn_ctx: FnCtx<'_>,
params: &Self::Params<'_>,
data: FileDownloadData<'_, Id>,
) -> Result<Self::State, FileDownloadError> {
FileDownloadStateGoalFn::state_goal(fn_ctx, params, data).await
}
async fn state_diff(
_params_partial: &<Self::Params<'_> as Params>::Partial,
_data: Self::Data<'_>,
state_a: &Self::State,
state_b: &Self::State,
) -> Result<Self::StateDiff, FileDownloadError> {
FileDownloadStateDiffFn::state_diff(state_a, state_b).await
}
async fn state_clean(
params_partial: &<Self::Params<'_> as Params>::Partial,
_data: Self::Data<'_>,
) -> Result<Self::State, FileDownloadError> {
let path = params_partial.dest().map(Path::to_path_buf);
let state =
FileDownloadState::new(FileDownloadStateLogical::None { path }, FetchedOpt::Tbd);
Ok(state)
}
async fn apply_check(
params: &Self::Params<'_>,
data: Self::Data<'_>,
state_current: &Self::State,
state_target: &Self::State,
diff: &Self::StateDiff,
) -> Result<ApplyCheck, Self::Error> {
FileDownloadApplyFns::<Id>::apply_check(params, data, state_current, state_target, diff)
.await
}
async fn apply_dry(
fn_ctx: FnCtx<'_>,
params: &Self::Params<'_>,
data: Self::Data<'_>,
state_current: &Self::State,
state_target: &Self::State,
diff: &Self::StateDiff,
) -> Result<Self::State, Self::Error> {
FileDownloadApplyFns::<Id>::apply_dry(
fn_ctx,
params,
data,
state_current,
state_target,
diff,
)
.await
}
async fn apply(
fn_ctx: FnCtx<'_>,
params: &Self::Params<'_>,
data: Self::Data<'_>,
state_current: &Self::State,
state_target: &Self::State,
diff: &Self::StateDiff,
) -> Result<Self::State, Self::Error> {
FileDownloadApplyFns::<Id>::apply(fn_ctx, params, data, state_current, state_target, diff)
.await
}
#[cfg(feature = "item_interactions")]
fn interactions(
params: &Self::Params<'_>,
_data: Self::Data<'_>,
) -> Vec<peace::item_interaction_model::ItemInteraction> {
use peace::item_interaction_model::{
ItemInteractionPull, ItemLocation, ItemLocationAncestors,
};
let location_server: ItemLocationAncestors = vec![
ItemLocation::host_from_url(params.src()),
ItemLocation::path(params.src().to_string()),
]
.into();
let location_client: ItemLocationAncestors = vec![
ItemLocation::localhost(),
ItemLocation::path(format!("📄 {}", params.dest().display())),
]
.into();
let item_interaction = ItemInteractionPull {
location_client,
location_server,
}
.into();
vec![item_interaction]
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/file_download/src/storage_form.rs | items/file_download/src/storage_form.rs | use serde::{Deserialize, Serialize};
/// Form to store the response.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub enum StorageForm {
/// Download and store the response text as-is.
///
/// This must only be used if the response is valid UTF-8.
Text,
/// Base64 encode the response bytes.
///
/// This must be used if the response is binary.
Base64,
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/file_download/src/file_download_params.rs | items/file_download/src/file_download_params.rs | use std::{
fmt,
marker::PhantomData,
path::{Path, PathBuf},
};
use peace::params::Params;
use serde::{Deserialize, Serialize};
use url::Url;
/// File download parameters.
///
/// The `Id` type parameter is needed for each file download params to be a
/// distinct type.
///
/// # Type Parameters
///
/// * `Id`: A zero-sized type used to distinguish different file download
/// parameters from each other.
#[derive(Params, PartialEq, Eq, Deserialize, Serialize)]
#[serde(bound = "")]
pub struct FileDownloadParams<Id> {
/// Url of the file to download.
src: Url,
/// Path of the destination.
///
/// Must be a file path, and not a directory.
dest: PathBuf,
/// How to store the content of the download -- text or base64 encoded.
///
/// For URLs that return binary content, this must be `Base64` as browser
/// storage can only store text.
#[cfg(target_arch = "wasm32")]
#[value_spec(fieldless)]
storage_form: crate::StorageForm,
/// Marker for unique download parameters type.
marker: PhantomData<Id>,
}
impl<Id> Clone for FileDownloadParams<Id> {
fn clone(&self) -> Self {
Self {
src: self.src.clone(),
dest: self.dest.clone(),
#[cfg(target_arch = "wasm32")]
storage_form: self.storage_form.clone(),
marker: PhantomData,
}
}
}
impl<Id> fmt::Debug for FileDownloadParams<Id> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FileDownloadParams")
.field("src", &self.src)
.field("dest", &self.dest)
.finish()
}
}
impl<Id> FileDownloadParams<Id> {
/// Returns new `FileDownloadParams`.
pub fn new(
src: Url,
dest: PathBuf,
#[cfg(target_arch = "wasm32")] storage_form: crate::StorageForm,
) -> Self {
Self {
src,
dest,
#[cfg(target_arch = "wasm32")]
storage_form,
marker: PhantomData,
}
}
/// Returns the URL to download from.
pub fn src(&self) -> &Url {
&self.src
}
/// Returns the file path to write to.
pub fn dest(&self) -> &Path {
&self.dest
}
/// Returns the storage form for the response.
///
/// This only applies to the WASM target.
#[cfg(target_arch = "wasm32")]
pub fn storage_form(&self) -> crate::StorageForm {
self.storage_form
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/file_download/src/file_download_error.rs | items/file_download/src/file_download_error.rs | use std::path::PathBuf;
#[cfg(feature = "error_reporting")]
use peace::miette::{self, SourceSpan};
/// Error while managing a file download.
#[cfg_attr(feature = "error_reporting", derive(peace::miette::Diagnostic))]
#[derive(Debug, thiserror::Error)]
pub enum FileDownloadError {
#[error("Failed to open destination file.")]
DestFileOpen(#[source] std::io::Error),
#[error("Failed to read destination file metadata.")]
DestMetadataRead(#[source] std::io::Error),
#[error("Failed to read destination file contents.")]
DestFileRead(#[source] std::io::Error),
#[error("Failed to create directories: `{}`.", dest_parent.display())]
#[cfg_attr(
feature = "error_reporting",
diagnostic(
code(peace_item_file_download::dest_parent_dirs_create),
help(
"Ensure that `{}` is not a file, or rerun the command with a different path.",
dest_parent.display())),
)]
DestParentDirsCreate {
/// Destination file path.
dest: PathBuf,
/// Destination parent directory path.
dest_parent: PathBuf,
/// String representation of the destination path.
#[cfg(feature = "error_reporting")]
#[source_code]
dest_display: String,
#[cfg(feature = "error_reporting")]
#[label]
parent_dirs_span: SourceSpan,
/// Underlying IO error
#[source]
error: std::io::Error,
},
#[error("Failed to open `{}` for writing.", dest.display())]
#[cfg_attr(
feature = "error_reporting",
diagnostic(
code(peace_item_file_download::dest_file_create),
help(
"Ensure that `{}` is not a directory, or rerun the command with a different path.",
dest.display())),
)]
DestFileCreate {
/// Approximation of the init command that defined the destination path.
#[cfg_attr(feature = "error_reporting", source_code)]
init_command_approx: String,
/// Span of the destination path within the init command.
#[cfg(feature = "error_reporting")]
#[label = "defined here"]
dest_span: SourceSpan,
/// Destination file path.
dest: PathBuf,
/// Underlying IO error
#[source]
error: std::io::Error,
},
#[error("Failed to delete destination file.")]
DestFileRemove(#[source] std::io::Error),
#[error("Failed to parse source URL.")]
SrcUrlParse(url::ParseError),
#[cfg_attr(
feature = "error_reporting",
diagnostic(help(
"Check that the URL is reachable:\n\
{}\n\
Make sure you are connected to the internet and try again.",
src
))
)]
#[error("Failed to download file.")]
SrcGet {
/// Source URL.
src: url::Url,
/// Underlying error.
#[source]
error: reqwest::Error,
},
#[error("Failed to fetch source file metadata. Response status code: {status_code}")]
SrcFileUndetermined { status_code: reqwest::StatusCode },
#[error("Failed to read source file content.")]
SrcFileRead(#[source] reqwest::Error),
#[error("Failed to stream source file content.")]
ResponseBytesStream(#[source] reqwest::Error),
#[error("Failed to transfer source file content.")]
ResponseFileWrite(#[source] std::io::Error),
// Native errors
#[cfg(not(target_arch = "wasm32"))]
#[error("Failed to read current executable path.")]
CurrentExeRead(#[source] std::io::Error),
#[cfg(not(target_arch = "wasm32"))]
#[error("Failed to get current executable name from path.")]
CurrentExeNameRead,
/// This one should be relatively unreachable.
#[cfg(not(target_arch = "wasm32"))]
#[error("Failed to format string in memory.")]
FormatString(#[source] std::fmt::Error),
// WASM errors.
#[cfg(target_arch = "wasm32")]
#[error("Failed to read bytes from response.")]
ResponseBytesRead(#[source] reqwest::Error),
#[cfg(target_arch = "wasm32")]
#[error("Failed to read text from response.")]
ResponseTextRead(#[source] reqwest::Error),
// === Framework errors === //
/// A `peace` runtime error occurred.
#[error("A `peace` runtime error occurred.")]
PeaceRtError(
#[cfg_attr(feature = "error_reporting", diagnostic_source)]
#[source]
#[from]
peace::rt_model::Error,
),
}
impl FileDownloadError {
/// Returns `FileDownloadError::SrcGet` from a get request error.
pub(crate) fn src_get(src: url::Url, error: reqwest::Error) -> Self {
FileDownloadError::SrcGet { src, error }
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/file_download/src/file_download_data.rs | items/file_download/src/file_download_data.rs | use std::marker::PhantomData;
#[cfg(target_arch = "wasm32")]
use peace::rt_model::Storage;
use peace::{
cfg::accessors::Stored,
data::{accessors::R, marker::Current, Data},
};
use crate::FileDownloadState;
/// Data used to download a file.
///
/// # Type Parameters
///
/// * `Id`: A zero-sized type used to distinguish different file download
/// parameters from each other.
#[derive(Data, Debug)]
pub struct FileDownloadData<'exec, Id>
where
Id: Send + Sync + 'static,
{
/// Client to make web requests.
client: R<'exec, reqwest::Client>,
/// The previous file download state.
state_prev: Stored<'exec, FileDownloadState>,
/// The file state working copy in memory.
state_working: R<'exec, Current<FileDownloadState>>,
/// For wasm, we write to web storage through the `Storage` object.
///
/// If `rt_model_native::Storage` exposed similar API, then storage
/// operations for item implementations will be easier.
#[cfg(target_arch = "wasm32")]
storage: R<'exec, Storage>,
/// Marker.
marker: PhantomData<Id>,
}
impl<'exec, Id> FileDownloadData<'exec, Id>
where
Id: Send + Sync + 'static,
{
pub fn client(&self) -> &reqwest::Client {
&self.client
}
pub fn state_prev(&self) -> &Stored<'exec, FileDownloadState> {
&self.state_prev
}
pub fn state_working(&self) -> &Current<FileDownloadState> {
&self.state_working
}
#[cfg(target_arch = "wasm32")]
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/items/file_download/src/file_download_state_logical.rs | items/file_download/src/file_download_state_logical.rs | use std::{fmt, path::PathBuf};
use serde::{Deserialize, Serialize};
#[cfg(feature = "output_progress")]
use peace::item_interaction_model::ItemLocationState;
/// State of the contents of the file to download.
///
/// This is used to represent the state of the source file, as well as the
/// destination file.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum FileDownloadStateLogical {
/// File does not exist.
None {
/// Path to the tracked file, if any.
path: Option<PathBuf>,
},
/// String contents of the file.
///
/// Use this when:
///
/// * File contents is text.
/// * File is small enough to load in memory.
StringContents {
/// Path to the file.
path: PathBuf,
/// Contents of the file.
contents: String,
},
/// Length of the file.
///
/// Use this when:
///
/// * File is not practical to load in memory.
Length {
/// Path to the file.
path: PathBuf,
/// Number of bytes.
byte_count: u64,
},
/// Cannot determine file state.
///
/// May be used for the goal state
Unknown {
/// Path to the file.
path: PathBuf,
},
}
impl fmt::Display for FileDownloadStateLogical {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::None { path } => {
if let Some(path) = path {
let path = path.display();
write!(f, "`{path}` non-existent")
} else {
write!(f, "non-existent")
}
}
Self::StringContents { path, contents } => {
let path = path.display();
write!(f, "`{path}` containing \"{contents}\"")
}
Self::Length { path, byte_count } => {
let path = path.display();
write!(f, "`{path}` containing {byte_count} bytes")
}
Self::Unknown { path } => {
let path = path.display();
write!(f, "`{path}` (contents not tracked)")
}
}
}
}
#[cfg(feature = "output_progress")]
impl<'state> From<&'state FileDownloadStateLogical> for ItemLocationState {
fn from(file_download_state: &'state FileDownloadStateLogical) -> ItemLocationState {
match file_download_state {
FileDownloadStateLogical::None { .. } => ItemLocationState::NotExists,
FileDownloadStateLogical::StringContents { .. }
| FileDownloadStateLogical::Length { .. }
| FileDownloadStateLogical::Unknown { .. } => todo!(),
}
}
}
impl PartialEq for FileDownloadStateLogical {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(
FileDownloadStateLogical::None { path: path_self },
FileDownloadStateLogical::None { path: path_other },
) => path_self == path_other,
(
FileDownloadStateLogical::Unknown {
path: path_self, ..
},
FileDownloadStateLogical::StringContents {
path: path_other, ..
},
)
| (
FileDownloadStateLogical::Unknown {
path: path_self, ..
},
FileDownloadStateLogical::Length {
path: path_other, ..
},
)
| (
FileDownloadStateLogical::StringContents {
path: path_self, ..
},
FileDownloadStateLogical::Unknown {
path: path_other, ..
},
)
| (
FileDownloadStateLogical::Length {
path: path_self, ..
},
FileDownloadStateLogical::Unknown {
path: path_other, ..
},
)
| (
FileDownloadStateLogical::Unknown { path: path_self },
FileDownloadStateLogical::Unknown { path: path_other },
) => path_self == path_other,
(FileDownloadStateLogical::Unknown { .. }, FileDownloadStateLogical::None { .. })
| (FileDownloadStateLogical::None { .. }, FileDownloadStateLogical::Unknown { .. })
| (
FileDownloadStateLogical::None { .. },
FileDownloadStateLogical::StringContents { .. },
)
| (
FileDownloadStateLogical::StringContents { .. },
FileDownloadStateLogical::None { .. },
)
| (
FileDownloadStateLogical::StringContents { .. },
FileDownloadStateLogical::Length { .. },
)
| (FileDownloadStateLogical::Length { .. }, FileDownloadStateLogical::None { .. })
| (
FileDownloadStateLogical::Length { .. },
FileDownloadStateLogical::StringContents { .. },
)
| (FileDownloadStateLogical::None { .. }, FileDownloadStateLogical::Length { .. }) => {
false
}
(
FileDownloadStateLogical::StringContents {
path: path_self,
contents: contents_self,
},
FileDownloadStateLogical::StringContents {
path: path_other,
contents: contents_other,
},
) => path_self == path_other && contents_self == contents_other,
(
FileDownloadStateLogical::Length {
path: path_self,
byte_count: byte_count_self,
},
FileDownloadStateLogical::Length {
path: path_other,
byte_count: byte_count_other,
},
) => path_self == path_other && byte_count_self == byte_count_other,
}
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/sh_cmd/src/sh_cmd_apply_fns.rs | items/sh_cmd/src/sh_cmd_apply_fns.rs | use std::marker::PhantomData;
use peace::cfg::{ApplyCheck, FnCtx};
#[cfg(feature = "output_progress")]
use peace::progress_model::ProgressLimit;
use crate::{
ShCmd, ShCmdData, ShCmdError, ShCmdExecutor, ShCmdParams, ShCmdState, ShCmdStateDiff,
ShCmdStateLogical,
};
/// ApplyFns for the command to execute.
#[derive(Debug)]
pub struct ShCmdApplyFns<Id>(PhantomData<Id>);
impl<Id> ShCmdApplyFns<Id>
where
Id: Send + Sync + 'static,
{
pub async fn apply_check(
params: &ShCmdParams<Id>,
_data: ShCmdData<'_, Id>,
state_current: &ShCmdState<Id>,
state_goal: &ShCmdState<Id>,
state_diff: &ShCmdStateDiff,
) -> Result<ApplyCheck, ShCmdError> {
let state_current_arg = match &state_current.0.logical {
ShCmdStateLogical::None => "",
ShCmdStateLogical::Some { stdout, .. } => stdout.as_ref(),
};
let state_goal_arg = match &state_goal.0.logical {
ShCmdStateLogical::None => "",
ShCmdStateLogical::Some { stdout, .. } => stdout.as_ref(),
};
let apply_check_sh_cmd = params
.apply_check_sh_cmd()
.clone()
.arg(state_current_arg)
.arg(state_goal_arg)
.arg(&**state_diff);
ShCmdExecutor::<Id>::exec(&apply_check_sh_cmd)
.await
.and_then(|state| match state.0.logical {
ShCmdStateLogical::Some { stdout, .. } => match stdout.trim().lines().next_back() {
Some("true") => {
#[cfg(not(feature = "output_progress"))]
{
Ok(ApplyCheck::ExecRequired)
}
#[cfg(feature = "output_progress")]
Ok(ApplyCheck::ExecRequired {
progress_limit: ProgressLimit::Unknown,
})
}
Some("false") => Ok(ApplyCheck::ExecNotRequired),
_ => Err(ShCmdError::EnsureCheckValueNotBoolean {
sh_cmd: apply_check_sh_cmd.clone(),
#[cfg(feature = "error_reporting")]
sh_cmd_string: format!("{apply_check_sh_cmd}"),
stdout: Some(stdout),
}),
},
_ => Err(ShCmdError::EnsureCheckValueNotBoolean {
sh_cmd: apply_check_sh_cmd.clone(),
#[cfg(feature = "error_reporting")]
sh_cmd_string: format!("{apply_check_sh_cmd}"),
stdout: None,
}),
})
}
pub async fn apply_dry(
_fn_ctx: FnCtx<'_>,
params: &ShCmdParams<Id>,
_data: ShCmdData<'_, Id>,
state_current: &ShCmdState<Id>,
state_goal: &ShCmdState<Id>,
state_diff: &ShCmdStateDiff,
) -> Result<ShCmdState<Id>, ShCmdError> {
// TODO: implement properly
let state_current_arg = match &state_current.0.logical {
ShCmdStateLogical::None => "",
ShCmdStateLogical::Some { stdout, .. } => stdout.as_ref(),
};
let state_goal_arg = match &state_goal.0.logical {
ShCmdStateLogical::None => "",
ShCmdStateLogical::Some { stdout, .. } => stdout.as_ref(),
};
let apply_exec_sh_cmd = params
.apply_exec_sh_cmd()
.clone()
.arg(state_current_arg)
.arg(state_goal_arg)
.arg(&**state_diff);
ShCmdExecutor::<Id>::exec(&ShCmd::new("echo").arg(format!("{apply_exec_sh_cmd}"))).await
}
pub async fn apply(
_fn_ctx: FnCtx<'_>,
params: &ShCmdParams<Id>,
_data: ShCmdData<'_, Id>,
state_current: &ShCmdState<Id>,
state_goal: &ShCmdState<Id>,
state_diff: &ShCmdStateDiff,
) -> Result<ShCmdState<Id>, ShCmdError> {
let state_current_arg = match &state_current.0.logical {
ShCmdStateLogical::None => "",
ShCmdStateLogical::Some { stdout, .. } => stdout.as_ref(),
};
let state_goal_arg = match &state_goal.0.logical {
ShCmdStateLogical::None => "",
ShCmdStateLogical::Some { stdout, .. } => stdout.as_ref(),
};
let apply_exec_sh_cmd = params
.apply_exec_sh_cmd()
.clone()
.arg(state_current_arg)
.arg(state_goal_arg)
.arg(&**state_diff);
ShCmdExecutor::<Id>::exec(&apply_exec_sh_cmd).await?;
ShCmdExecutor::<Id>::exec(params.state_current_sh_cmd()).await
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/sh_cmd/src/sh_cmd_item.rs | items/sh_cmd/src/sh_cmd_item.rs | use std::marker::PhantomData;
use peace::{
cfg::{async_trait, ApplyCheck, FnCtx, Item},
item_model::ItemId,
params::Params,
resource_rt::{resources::ts::Empty, Resources},
};
use crate::{
ShCmdApplyFns, ShCmdData, ShCmdError, ShCmdExecutor, ShCmdParams, ShCmdState, ShCmdStateDiff,
ShCmdStateDiffFn,
};
/// Item for executing a shell command.
///
/// The `Id` type parameter is needed for each command execution params to be a
/// distinct type.
///
/// # Type Parameters
///
/// * `Id`: A zero-sized type used to distinguish different command execution
/// parameters from each other.
#[derive(Debug)]
pub struct ShCmdItem<Id> {
/// ID to easily tell what the item command is for.
item_id: ItemId,
/// Marker for unique command execution parameters type.
marker: PhantomData<Id>,
}
impl<Id> Clone for ShCmdItem<Id> {
fn clone(&self) -> Self {
Self {
item_id: self.item_id.clone(),
marker: PhantomData,
}
}
}
impl<Id> ShCmdItem<Id> {
/// Returns a new `ShCmdItem`.
///
/// # Parameters
///
/// * `item_id`: ID of this `ShCmdItem`.
pub fn new(item_id: ItemId) -> Self {
Self {
item_id,
marker: PhantomData,
}
}
}
#[async_trait(?Send)]
impl<Id> Item for ShCmdItem<Id>
where
Id: Send + Sync + 'static,
{
type Data<'exec> = ShCmdData<'exec, Id>;
type Error = ShCmdError;
type Params<'exec> = ShCmdParams<Id>;
type State = ShCmdState<Id>;
type StateDiff = ShCmdStateDiff;
fn id(&self) -> &ItemId {
&self.item_id
}
async fn setup(&self, _resources: &mut Resources<Empty>) -> Result<(), ShCmdError> {
Ok(())
}
#[cfg(feature = "item_state_example")]
fn state_example(params: &Self::Params<'_>, _data: Self::Data<'_>) -> Self::State {
let state_example_sh_cmd = params.state_example_sh_cmd();
ShCmdExecutor::exec_blocking(state_example_sh_cmd)
.expect("ShCmd failed to return example state.")
}
async fn try_state_current(
_fn_ctx: FnCtx<'_>,
params_partial: &<Self::Params<'_> as Params>::Partial,
_data: ShCmdData<'_, Id>,
) -> Result<Option<Self::State>, ShCmdError> {
if let Some(state_current_sh_cmd) = params_partial.state_current_sh_cmd() {
ShCmdExecutor::exec(state_current_sh_cmd).await.map(Some)
} else {
Ok(None)
}
}
async fn state_current(
_fn_ctx: FnCtx<'_>,
params: &Self::Params<'_>,
_data: ShCmdData<'_, Id>,
) -> Result<Self::State, ShCmdError> {
let state_current_sh_cmd = params.state_current_sh_cmd();
ShCmdExecutor::exec(state_current_sh_cmd).await
}
async fn try_state_goal(
_fn_ctx: FnCtx<'_>,
params_partial: &<Self::Params<'_> as Params>::Partial,
_data: ShCmdData<'_, Id>,
) -> Result<Option<Self::State>, ShCmdError> {
if let Some(state_goal_sh_cmd) = params_partial.state_goal_sh_cmd() {
ShCmdExecutor::exec(state_goal_sh_cmd).await.map(Some)
} else {
Ok(None)
}
}
async fn state_goal(
_fn_ctx: FnCtx<'_>,
params: &Self::Params<'_>,
_data: ShCmdData<'_, Id>,
) -> Result<Self::State, ShCmdError> {
let state_goal_sh_cmd = params.state_goal_sh_cmd();
// Maybe we should support reading different exit statuses for an `Ok(None)`
// value.
ShCmdExecutor::exec(state_goal_sh_cmd).await
}
async fn state_diff(
params_partial: &<Self::Params<'_> as Params>::Partial,
_data: Self::Data<'_>,
state_current: &Self::State,
state_goal: &Self::State,
) -> Result<Self::StateDiff, ShCmdError> {
let state_diff_sh_cmd =
params_partial
.state_diff_sh_cmd()
.ok_or(ShCmdError::CmdScriptNotResolved {
cmd_variant: crate::CmdVariant::StateDiff,
})?;
ShCmdStateDiffFn::state_diff(state_diff_sh_cmd.clone(), state_current, state_goal).await
}
async fn state_clean(
params_partial: &<Self::Params<'_> as Params>::Partial,
_data: Self::Data<'_>,
) -> Result<Self::State, ShCmdError> {
let state_clean_sh_cmd =
params_partial
.state_clean_sh_cmd()
.ok_or(ShCmdError::CmdScriptNotResolved {
cmd_variant: crate::CmdVariant::StateClean,
})?;
ShCmdExecutor::exec(state_clean_sh_cmd).await
}
async fn apply_check(
params: &Self::Params<'_>,
data: Self::Data<'_>,
state_current: &Self::State,
state_target: &Self::State,
diff: &Self::StateDiff,
) -> Result<ApplyCheck, Self::Error> {
ShCmdApplyFns::<Id>::apply_check(params, data, state_current, state_target, diff).await
}
async fn apply_dry(
fn_ctx: FnCtx<'_>,
params: &Self::Params<'_>,
data: Self::Data<'_>,
state_current: &Self::State,
state_target: &Self::State,
diff: &Self::StateDiff,
) -> Result<Self::State, Self::Error> {
ShCmdApplyFns::<Id>::apply_dry(fn_ctx, params, data, state_current, state_target, diff)
.await
}
async fn apply(
fn_ctx: FnCtx<'_>,
params: &Self::Params<'_>,
data: Self::Data<'_>,
state_current: &Self::State,
state_target: &Self::State,
diff: &Self::StateDiff,
) -> Result<Self::State, Self::Error> {
ShCmdApplyFns::<Id>::apply(fn_ctx, params, data, state_current, state_target, diff).await
}
#[cfg(feature = "item_interactions")]
fn interactions(
_params: &Self::Params<'_>,
_data: Self::Data<'_>,
) -> Vec<peace::item_interaction_model::ItemInteraction> {
use peace::item_interaction_model::{ItemInteractionWithin, ItemLocation};
let item_interaction =
ItemInteractionWithin::new(vec![ItemLocation::localhost()].into()).into();
vec![item_interaction]
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/sh_cmd/src/sh_cmd_error.rs | items/sh_cmd/src/sh_cmd_error.rs | #[cfg(feature = "error_reporting")]
use peace::miette::{self, SourceSpan};
use crate::{CmdVariant, ShCmd};
/// Error while managing command execution.
#[cfg_attr(feature = "error_reporting", derive(peace::miette::Diagnostic))]
#[derive(Debug, thiserror::Error)]
pub enum ShCmdError {
/// A command script was not resolved during execution.
///
/// This could be due to it not being provided, or it failed to be looked up
/// when needed.
#[error("Script not resolved for: `{cmd_variant}`.")]
#[cfg_attr(
feature = "error_reporting",
diagnostic(
code(peace_item_sh_cmd::cmd_script_not_exists),
help("Check if the `{cmd_variant}` is provided in params.")
)
)]
CmdScriptNotResolved {
/// The cmd variant that was not existent.
cmd_variant: CmdVariant,
},
/// Failed to execute command.
#[error("Failed to execute command: `{}`", sh_cmd)]
#[cfg_attr(
feature = "error_reporting",
diagnostic(code(peace_item_sh_cmd::cmd_exec_fail))
)]
CmdExecFail {
/// The command that failed to be executed.
sh_cmd: ShCmd,
/// The command that failed to be executed as a string.
#[cfg(feature = "error_reporting")]
#[source_code]
sh_cmd_string: String,
/// Underlying IO error.
#[source]
error: std::io::Error,
},
/// Command produced non-UTF-8 stdout output.
#[error("Command produced non-UTF-8 stdout output: `{}`", sh_cmd)]
#[cfg_attr(
feature = "error_reporting",
diagnostic(code(peace_item_sh_cmd::stdout_non_utf8)),
help(
"Update the command to something that outputs UTF8: `{}`\n\
Perhaps encode the output using `base64`",
sh_cmd
)
)]
StdoutNonUtf8 {
/// The command whose stdout is not a valid UTF-8 string.
sh_cmd: ShCmd,
/// Lossy UTF-8 conversion of stdout.
#[cfg_attr(feature = "error_reporting", source_code)]
stdout_lossy: String,
/// Span where the invalid bytes occur.
#[cfg(feature = "error_reporting")]
#[label]
invalid_span: SourceSpan,
/// Underlying Utf8 error.
#[source]
error: std::str::Utf8Error,
},
/// Command produced non-UTF-8 stderr output.
#[error("Command produced non-UTF-8 stderr output: `{}`", sh_cmd)]
#[cfg_attr(
feature = "error_reporting",
diagnostic(code(peace_item_sh_cmd::stderr_non_utf8)),
help(
"Update the command to something that outputs UTF8: `{}`\n\
Perhaps encode the output using `base64`",
sh_cmd
)
)]
StderrNonUtf8 {
/// The command whose stderr is not a valid UTF-8 string.
sh_cmd: ShCmd,
/// Lossy UTF-8 conversion of stderr.
#[cfg_attr(feature = "error_reporting", source_code)]
stderr_lossy: String,
/// Span where the invalid bytes occur.
#[cfg(feature = "error_reporting")]
#[label]
invalid_span: SourceSpan,
/// Underlying Utf8 error.
#[source]
error: std::str::Utf8Error,
},
/// Ensure check shell command did not output "true" or "false".
#[error(
r#"Ensure check shell command did not return "true" or "false": `{}`"#,
sh_cmd
)]
#[cfg_attr(
feature = "error_reporting",
diagnostic(code(peace_item_sh_cmd::ensure_check_value_not_boolean)),
help(
r#"Update the command to return "true" if execution is required, or "false" if not."#
)
)]
EnsureCheckValueNotBoolean {
/// The ensure check shell command.
sh_cmd: ShCmd,
/// The ensure check shell command as a string.
#[cfg(feature = "error_reporting")]
#[source_code]
sh_cmd_string: String,
/// Stdout.
stdout: Option<String>,
},
/// Clean check shell command did not output "true" or "false".
#[error(
r#"Clean check shell command did not return "true" or "false": `{}`"#,
sh_cmd
)]
#[cfg_attr(
feature = "error_reporting",
diagnostic(code(peace_item_sh_cmd::clean_check_value_not_boolean)),
help(
r#"Update the command to return "true" if execution is required, or "false" if not."#
)
)]
CleanCheckValueNotBoolean {
/// The clean check shell command.
sh_cmd: ShCmd,
/// The clean check shell command as a string.
#[cfg(feature = "error_reporting")]
#[source_code]
sh_cmd_string: String,
/// Stdout.
stdout: Option<String>,
},
// === Framework errors === //
/// A `peace` runtime error occurred.
#[error("A `peace` runtime error occurred.")]
PeaceRtError(
#[cfg_attr(feature = "error_reporting", diagnostic_source)]
#[source]
#[from]
peace::rt_model::Error,
),
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/sh_cmd/src/lib.rs | items/sh_cmd/src/lib.rs | //! Manages running a shell command for the peace framework.
//!
//! This item is designed to take in separate shell commands for each of
//! the following:
//!
//! * Current state logic, whose stdout defines the current state (`String`).
//! * Goal state logic, whose stdout defines the goal state (`String`).
//! * State diff logic, whose stdout defines the state difference.
//! * Ensure check, whose stdout defines if ensure execution needs to run --
//! `true` means execution is required, `false` means execution is required.
//! * Ensure execution, whose stdout defines state physical.
//! * Clean check, whose exit status defines if clean execution needs to run --
//! `true` means execution is required, `false` means execution is required.
//! * Clean execution.
pub use crate::{
cmd_variant::CmdVariant,
sh_cmd::ShCmd,
sh_cmd_apply_fns::ShCmdApplyFns,
sh_cmd_data::ShCmdData,
sh_cmd_error::ShCmdError,
sh_cmd_execution_record::ShCmdExecutionRecord,
sh_cmd_item::ShCmdItem,
sh_cmd_params::{ShCmdParams, ShCmdParamsFieldWise, ShCmdParamsPartial},
sh_cmd_state::ShCmdState,
sh_cmd_state_diff::ShCmdStateDiff,
sh_cmd_state_diff_fn::ShCmdStateDiffFn,
sh_cmd_state_logical::ShCmdStateLogical,
};
pub(crate) use sh_cmd_executor::ShCmdExecutor;
mod cmd_variant;
mod sh_cmd;
mod sh_cmd_apply_fns;
mod sh_cmd_data;
mod sh_cmd_error;
mod sh_cmd_execution_record;
mod sh_cmd_executor;
mod sh_cmd_item;
mod sh_cmd_params;
mod sh_cmd_state;
mod sh_cmd_state_diff;
mod sh_cmd_state_diff_fn;
mod sh_cmd_state_logical;
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/sh_cmd/src/sh_cmd_execution_record.rs | items/sh_cmd/src/sh_cmd_execution_record.rs | use std::fmt;
use chrono::{offset::Local, DateTime, Utc};
use serde::{Deserialize, Serialize};
/// Record of a shell command execution.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ShCmdExecutionRecord {
/// There is no execution record.
///
/// Represents when the command has either never been executed, or has been
/// cleaned up.
None,
/// Record of the command's last execution.
Some {
/// Timestamp of beginning of execution.
start_datetime: chrono::DateTime<Utc>,
/// Timestamp that the execution ended.
end_datetime: chrono::DateTime<Utc>,
/// Exit code of the process, if any.
///
/// See [`ExitStatus::code()`].
///
/// [`ExitStatus::code()`]: std::process::ExitStatus::code
exit_code: Option<i32>,
},
}
impl fmt::Display for ShCmdExecutionRecord {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::None => write!(f, "not executed"),
Self::Some {
start_datetime,
exit_code,
..
} => match exit_code {
Some(0) => {
let start_datetime_local = DateTime::<Local>::from(*start_datetime);
write!(f, "executed successfully at {start_datetime_local}")
}
Some(code) => write!(f, "execution failed with code: {code}"),
None => write!(f, "execution was interrupted"),
},
}
}
}
/// We don't compare timestamps of execution because we're concerned about
/// state of whatever the shell command is reading, rather than when the shell
/// command was run.
impl PartialEq for ShCmdExecutionRecord {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(ShCmdExecutionRecord::None, ShCmdExecutionRecord::None) => true,
(ShCmdExecutionRecord::None, ShCmdExecutionRecord::Some { .. })
| (ShCmdExecutionRecord::Some { .. }, ShCmdExecutionRecord::None) => false,
(
ShCmdExecutionRecord::Some {
start_datetime: _,
end_datetime: _,
exit_code: exit_code_self,
},
ShCmdExecutionRecord::Some {
start_datetime: _,
end_datetime: _,
exit_code: exit_code_other,
},
) => exit_code_self == exit_code_other,
}
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/sh_cmd/src/sh_cmd_state_diff.rs | items/sh_cmd/src/sh_cmd_state_diff.rs | use std::fmt;
use serde::{Deserialize, Serialize};
/// Diff between the current and goal file extraction.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ShCmdStateDiff {
/// stdout output.
stdout: String,
/// stderr output.
stderr: String,
}
impl ShCmdStateDiff {
/// Returns a new `ShCmdStateDiff`.
pub fn new(stdout: String, stderr: String) -> Self {
Self { stdout, stderr }
}
/// Returns the `stdout` string, representing the logical state difference.
pub fn stdout(&self) -> &str {
self.stdout.as_ref()
}
/// Returns the `stderr` string, representing the display string.
pub fn stderr(&self) -> &str {
self.stderr.as_ref()
}
}
impl std::ops::Deref for ShCmdStateDiff {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.stdout
}
}
impl std::ops::DerefMut for ShCmdStateDiff {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.stdout
}
}
impl fmt::Display for ShCmdStateDiff {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.stderr.fmt(f)
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/sh_cmd/src/sh_cmd_params.rs | items/sh_cmd/src/sh_cmd_params.rs | use std::marker::PhantomData;
use derivative::Derivative;
use peace::params::Params;
use serde::{Deserialize, Serialize};
use crate::ShCmd;
/// Grouping of commands to run a shell command idempotently.
///
/// The `Id` type parameter is needed for each command execution params to be a
/// distinct type.
///
/// # Type Parameters
///
/// * `Id`: A zero-sized type used to distinguish different command execution
/// parameters from each other.
#[derive(Derivative, Params, PartialEq, Eq, Deserialize, Serialize)]
#[derivative(Clone, Debug)]
#[serde(bound = "")]
pub struct ShCmdParams<Id> {
/// Shell command to run to discover the example state.
///
/// The command's stdout is used as the example state.
///
/// The command's stderr is used as the human readable description of the
/// state. This must be output as a single line.
#[cfg(feature = "item_state_example")]
state_example_sh_cmd: ShCmd,
/// Shell command to run to discover the clean state.
///
/// The command's stdout is used as the clean state.
///
/// The command's stderr is used as the human readable description of the
/// state. This must be output as a single line.
state_clean_sh_cmd: ShCmd,
/// Shell command to run to discover the current state.
///
/// The command's stdout is used as the current state.
///
/// The command's stderr is used as the human readable description of the
/// state. This must be output as a single line.
state_current_sh_cmd: ShCmd,
/// Shell command to run to discover the goal state.
///
/// The command's stdout is used as the goal state.
///
/// The command's stderr is used as the human readable description of the
/// state. This must be output as a single line.
state_goal_sh_cmd: ShCmd,
/// Shell command to run to show the state difference.
///
/// The command will be passed the following as two separate arguments:
///
/// * Current state string
/// * Goal state string
///
/// The command's stdout is used as the state difference.
///
/// The command's stderr is used as the human readable description of the
/// state difference. This must be output as a single line.
state_diff_sh_cmd: ShCmd,
/// Shell command to run in `ApplyFns::check`.
///
/// The command will be passed the following as three separate arguments:
///
/// * Current state string
/// * Goal state string
/// * State diff string
///
/// If the shell command returns the string `true` as its final line, then
/// it is taken to mean `ApplyFns::exec` needs to be run.
///
/// If the shell command returns the string `false` as its final line, then
/// it is taken to mean `ApplyFns::exec` does not need to be run.
apply_check_sh_cmd: ShCmd,
/// Shell command to run in `ApplyFns::exec`.
///
/// The command will be passed the following as three separate arguments:
///
/// * Current state string
/// * Goal state string
/// * State diff string
apply_exec_sh_cmd: ShCmd,
/// Marker for unique command execution parameters type.
marker: PhantomData<Id>,
}
impl<Id> ShCmdParams<Id> {
/// Returns new `ShCmdParams`.
#[allow(clippy::too_many_arguments)]
pub fn new(
#[cfg(feature = "item_state_example")] state_example_sh_cmd: ShCmd,
state_clean_sh_cmd: ShCmd,
state_current_sh_cmd: ShCmd,
state_goal_sh_cmd: ShCmd,
state_diff_sh_cmd: ShCmd,
apply_check_sh_cmd: ShCmd,
apply_exec_sh_cmd: ShCmd,
) -> Self {
Self {
#[cfg(feature = "item_state_example")]
state_example_sh_cmd,
state_clean_sh_cmd,
state_current_sh_cmd,
state_goal_sh_cmd,
state_diff_sh_cmd,
apply_check_sh_cmd,
apply_exec_sh_cmd,
marker: PhantomData,
}
}
/// Returns the shell command to run to discover the example state.
///
/// The command's stdout is used as the example state.
///
/// The command's stderr is used as the human readable description of the
/// state. This must be output as a single line.
#[cfg(feature = "item_state_example")]
pub fn state_example_sh_cmd(&self) -> &ShCmd {
&self.state_example_sh_cmd
}
/// Returns the shell command to run to discover the clean state.
///
/// The command's stdout is used as the clean state.
///
/// The command's stderr is used as the human readable description of the
/// state. This must be output as a single line.
pub fn state_clean_sh_cmd(&self) -> &ShCmd {
&self.state_clean_sh_cmd
}
/// Returns the shell command to run to discover the current state.
///
/// The command's stdout is used as the current state.
///
/// The command's stderr is used as the human readable description of the
/// state. This must be output as a single line.
pub fn state_current_sh_cmd(&self) -> &ShCmd {
&self.state_current_sh_cmd
}
/// Returns the shell command to run to discover the goal state.
///
/// The command's stdout is used as the goal state.
///
/// The command's stderr is used as the human readable description of the
/// state. This must be output as a single line.
pub fn state_goal_sh_cmd(&self) -> &ShCmd {
&self.state_goal_sh_cmd
}
/// Returns the shell command to run to show the state difference.
///
/// The command will be passed the following as three separate arguments:
///
/// * Current state string
/// * Goal state string
///
/// The command's stdout is used as the state difference.
///
/// The command's stderr is used as the human readable description of the
/// state difference. This must be output as a single line.
pub fn state_diff_sh_cmd(&self) -> &ShCmd {
&self.state_diff_sh_cmd
}
/// Returns the shell command to run in `ApplyFns::check`.
///
/// The command will be passed the following as three separate arguments:
///
/// * Current state string
/// * Goal state string
/// * State diff string
///
/// If the shell command returns the string `true` as its final line, then
/// it is taken to mean `ApplyFns::exec` needs to be run.
///
/// If the shell command returns the string `false` as its final line, then
/// it is taken to mean `ApplyFns::exec` does not need to be run.
pub fn apply_check_sh_cmd(&self) -> &ShCmd {
&self.apply_check_sh_cmd
}
/// Returns the shell command to run in `ApplyFns::exec`.
///
/// The command will be passed the following as three separate arguments:
///
/// * Current state string
/// * Goal state string
/// * State diff string
pub fn apply_exec_sh_cmd(&self) -> &ShCmd {
&self.apply_exec_sh_cmd
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/sh_cmd/src/cmd_variant.rs | items/sh_cmd/src/cmd_variant.rs | use std::fmt;
/// Command variants which take in scripts in `ShCmdParams`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CmdVariant {
/// The `state_clean` command.
StateClean,
/// The `state_current` command.
StateCurrent,
/// The `state_goal` command.
StateGoal,
/// The `state_diff` command.
StateDiff,
/// The `apply_check` command.
ApplyCheck,
/// The `apply_exec` command.
ApplyExec,
}
impl fmt::Display for CmdVariant {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::StateClean => "state_clean".fmt(f),
Self::StateCurrent => "state_current".fmt(f),
Self::StateGoal => "state_goal".fmt(f),
Self::StateDiff => "state_diff".fmt(f),
Self::ApplyCheck => "apply_check".fmt(f),
Self::ApplyExec => "apply_exec".fmt(f),
}
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/sh_cmd/src/sh_cmd_state.rs | items/sh_cmd/src/sh_cmd_state.rs | use std::fmt;
use derivative::Derivative;
use peace::cfg::State;
use serde::{Deserialize, Serialize};
use crate::{ShCmdExecutionRecord, ShCmdStateLogical};
#[cfg(feature = "output_progress")]
use peace::item_interaction_model::ItemLocationState;
/// Newtype wrapper for `State<ShCmdStatePhysical<Id>, ShCmdExecutionRecord>`.
#[derive(Derivative, Serialize, Deserialize)]
#[derivative(Clone(bound = ""), Debug(bound = ""), PartialEq(bound = ""))]
#[serde(bound(serialize = "", deserialize = ""))]
pub struct ShCmdState<Id>(pub State<ShCmdStateLogical<Id>, ShCmdExecutionRecord>);
impl<Id> ShCmdState<Id> {
/// Returns a new `ShCmdState<Id>`.
pub fn new(
sh_cmd_state_physical: ShCmdStateLogical<Id>,
execution_record: ShCmdExecutionRecord,
) -> Self {
Self(State::new(sh_cmd_state_physical, execution_record))
}
}
impl<Id> From<State<ShCmdStateLogical<Id>, ShCmdExecutionRecord>> for ShCmdState<Id> {
fn from(state: State<ShCmdStateLogical<Id>, ShCmdExecutionRecord>) -> Self {
Self(state)
}
}
impl<Id> fmt::Display for ShCmdState<Id> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
#[cfg(feature = "output_progress")]
impl<'state, Id> From<&'state ShCmdState<Id>> for ItemLocationState {
fn from(state: &'state ShCmdState<Id>) -> ItemLocationState {
match &state.0.logical {
ShCmdStateLogical::Some { .. } => ItemLocationState::Exists,
ShCmdStateLogical::None => ItemLocationState::NotExists,
}
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/sh_cmd/src/sh_cmd_executor.rs | items/sh_cmd/src/sh_cmd_executor.rs | use std::{marker::PhantomData, process::Stdio};
use chrono::Utc;
use tokio::process::Command;
use crate::{ShCmd, ShCmdError, ShCmdExecutionRecord, ShCmdState, ShCmdStateLogical};
/// Common code to run `ShCmd`s.
#[derive(Debug)]
pub(crate) struct ShCmdExecutor<Id>(PhantomData<Id>);
impl<Id> ShCmdExecutor<Id> {
/// Executes the provided `ShCmd` and returns execution information.
pub async fn exec(sh_cmd: &ShCmd) -> Result<ShCmdState<Id>, ShCmdError> {
let start_datetime = Utc::now();
let mut command: Command = sh_cmd.into();
let output = command
.stdin(Stdio::null())
.kill_on_drop(true)
.output()
.await
.map_err(|error| {
#[cfg(feature = "error_reporting")]
let sh_cmd_string = format!("{sh_cmd}");
ShCmdError::CmdExecFail {
sh_cmd: sh_cmd.clone(),
#[cfg(feature = "error_reporting")]
sh_cmd_string,
error,
}
})?;
let end_datetime = Utc::now();
let stdout = String::from_utf8(output.stdout).map_err(|from_utf8_error| {
let stdout_lossy = String::from_utf8_lossy(from_utf8_error.as_bytes()).to_string();
let error = from_utf8_error.utf8_error();
#[cfg(feature = "error_reporting")]
let invalid_span = {
let start = error.valid_up_to();
let len = error.error_len().unwrap_or(1);
peace::miette::SourceSpan::from((start, len))
};
ShCmdError::StdoutNonUtf8 {
sh_cmd: sh_cmd.clone(),
stdout_lossy,
#[cfg(feature = "error_reporting")]
invalid_span,
error,
}
})?;
let stderr = String::from_utf8(output.stderr)
.map_err(|from_utf8_error| {
let stderr_lossy = String::from_utf8_lossy(from_utf8_error.as_bytes()).to_string();
let error = from_utf8_error.utf8_error();
#[cfg(feature = "error_reporting")]
let invalid_span = {
let start = error.valid_up_to();
let len = error.error_len().unwrap_or(1);
peace::miette::SourceSpan::from((start, len))
};
ShCmdError::StderrNonUtf8 {
sh_cmd: sh_cmd.clone(),
stderr_lossy,
#[cfg(feature = "error_reporting")]
invalid_span,
error,
}
})?
.trim()
.to_string();
Ok(ShCmdState::new(
ShCmdStateLogical::Some {
stdout,
stderr,
marker: PhantomData,
},
ShCmdExecutionRecord::Some {
start_datetime,
end_datetime,
exit_code: output.status.code(),
},
))
}
/// Executes the provided `ShCmd` and returns execution information.
#[cfg(feature = "item_state_example")]
pub fn exec_blocking(sh_cmd: &ShCmd) -> Result<ShCmdState<Id>, ShCmdError> {
let start_datetime = Utc::now();
let mut command: std::process::Command = sh_cmd.into();
let output = command.stdin(Stdio::null()).output().map_err(|error| {
#[cfg(feature = "error_reporting")]
let sh_cmd_string = format!("{sh_cmd}");
ShCmdError::CmdExecFail {
sh_cmd: sh_cmd.clone(),
#[cfg(feature = "error_reporting")]
sh_cmd_string,
error,
}
})?;
let end_datetime = Utc::now();
let stdout = String::from_utf8(output.stdout).map_err(|from_utf8_error| {
let stdout_lossy = String::from_utf8_lossy(from_utf8_error.as_bytes()).to_string();
let error = from_utf8_error.utf8_error();
#[cfg(feature = "error_reporting")]
let invalid_span = {
let start = error.valid_up_to();
let len = error.error_len().unwrap_or(1);
peace::miette::SourceSpan::from((start, len))
};
ShCmdError::StdoutNonUtf8 {
sh_cmd: sh_cmd.clone(),
stdout_lossy,
#[cfg(feature = "error_reporting")]
invalid_span,
error,
}
})?;
let stderr = String::from_utf8(output.stderr)
.map_err(|from_utf8_error| {
let stderr_lossy = String::from_utf8_lossy(from_utf8_error.as_bytes()).to_string();
let error = from_utf8_error.utf8_error();
#[cfg(feature = "error_reporting")]
let invalid_span = {
let start = error.valid_up_to();
let len = error.error_len().unwrap_or(1);
peace::miette::SourceSpan::from((start, len))
};
ShCmdError::StderrNonUtf8 {
sh_cmd: sh_cmd.clone(),
stderr_lossy,
#[cfg(feature = "error_reporting")]
invalid_span,
error,
}
})?
.trim()
.to_string();
Ok(ShCmdState::new(
ShCmdStateLogical::Some {
stdout,
stderr,
marker: PhantomData,
},
ShCmdExecutionRecord::Some {
start_datetime,
end_datetime,
exit_code: output.status.code(),
},
))
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/sh_cmd/src/sh_cmd_data.rs | items/sh_cmd/src/sh_cmd_data.rs | use std::marker::PhantomData;
use peace::{
cfg::{accessors::Stored, State},
data::Data,
};
use crate::{ShCmdExecutionRecord, ShCmdStateLogical};
/// Data used to run a shell command.
///
/// # Type Parameters
///
/// * `Id`: A zero-sized type used to distinguish different command execution
/// parameters from each other.
#[derive(Data, Debug)]
pub struct ShCmdData<'exec, Id>
where
Id: Send + Sync + 'static,
{
/// Stored states of this item's previous execution.
state_current_stored: Stored<'exec, State<ShCmdStateLogical<Id>, ShCmdExecutionRecord>>,
/// Marker.
marker: PhantomData<Id>,
}
impl<Id> ShCmdData<'_, Id>
where
Id: Send + Sync + 'static,
{
/// Returns the previous states.
pub fn state_current_stored(
&self,
) -> Option<&State<ShCmdStateLogical<Id>, ShCmdExecutionRecord>> {
self.state_current_stored.get()
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/sh_cmd/src/sh_cmd.rs | items/sh_cmd/src/sh_cmd.rs | use std::{ffi::OsString, fmt};
use peace::params::Params;
use serde::{Deserialize, Serialize};
use tokio::process::Command;
/// Shell command to execute.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, Params)]
pub struct ShCmd {
/// Command to run.
program: OsString,
/// Arguments to pass to the command.
args: Vec<OsString>,
}
impl ShCmd {
/// Constructs a new `ShCmd` for launching the program at
/// path `program`, with the following default configuration:
///
/// * No arguments to the program
/// * Inherit the current process's environment
/// * Inherit the current process's working directory
/// * Inherit stdin/stdout/stderr for [`spawn`] or [`status`], but create
/// pipes for [`output`]
///
/// [`spawn`]: Self::spawn
/// [`status`]: Self::status
/// [`output`]: Self::output
///
/// Builder methods are provided to change these defaults and
/// otherwise configure the process.
///
/// If `program` is not an absolute path, the `PATH` will be searched in
/// an OS-defined way.
///
/// The search path to be used may be controlled by setting the
/// `PATH` environment variable on the ShCmd,
/// but this has some implementation limitations on Windows
/// (see issue #37519).
///
/// # Examples
///
/// Basic usage:
///
/// ```rust
/// use peace_item_sh_cmd::ShCmd;
///
/// let sh_cmd = ShCmd::new("sh");
/// ```
pub fn new<S: Into<OsString>>(program: S) -> Self {
Self {
program: program.into(),
args: Vec::new(),
}
}
/// Adds an argument to pass to the program.
///
/// Only one argument can be passed per use. So instead of:
///
/// ```rust,no_run
/// # peace_item_sh_cmd::ShCmd::new("sh")
/// .arg("-C /path/to/repo")
/// # ;
/// ```
///
/// usage would be:
///
/// ```rust,no_run
/// # peace_item_sh_cmd::ShCmd::new("sh")
/// .arg("-C")
/// .arg("/path/to/repo")
/// # ;
/// ```
///
/// To pass multiple arguments see [`args`].
///
/// [`args`]: ShCmd::args
///
/// Note that the argument is not passed through a shell, but given
/// literally to the program. This means that shell syntax like quotes,
/// escaped characters, word splitting, glob patterns, substitution, etc.
/// have no effect.
///
/// # Examples
///
/// Basic usage:
///
/// ```rust,no_run
/// use peace_item_sh_cmd::ShCmd;
///
/// let sh_cmd = ShCmd::new("ls").arg("-l").arg("-a");
/// ```
pub fn arg<S: Into<OsString>>(mut self, arg: S) -> Self {
self.args.push(arg.into());
self
}
/// Adds multiple arguments to pass to the program.
///
/// To pass a single argument see [`arg`].
///
/// [`arg`]: ShCmd::arg
///
/// Note that the arguments are not passed through a shell, but given
/// literally to the program. This means that shell syntax like quotes,
/// escaped characters, word splitting, glob patterns, substitution, etc.
/// have no effect.
///
/// # Examples
///
/// Basic usage:
///
/// ```rust,no_run
/// use peace_item_sh_cmd::ShCmd;
///
/// let sh_cmd = ShCmd::new("ls").args(["-l", "-a"]);
/// ```
pub fn args<I, S>(mut self, args: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<OsString>,
{
args.into_iter().for_each(|arg| {
self.args.push(arg.into());
});
self
}
}
impl From<&ShCmd> for Command {
fn from(sh_cmd: &ShCmd) -> Command {
let mut command = Command::new(&sh_cmd.program);
command.args(&sh_cmd.args);
command
}
}
#[cfg(feature = "item_state_example")]
impl From<&ShCmd> for std::process::Command {
fn from(sh_cmd: &ShCmd) -> std::process::Command {
let mut command = std::process::Command::new(&sh_cmd.program);
command.args(&sh_cmd.args);
command
}
}
impl fmt::Display for ShCmd {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.program.to_string_lossy().fmt(f)?;
self.args
.iter()
.map(|arg| arg.to_string_lossy())
.try_for_each(|arg| write!(f, " {arg}"))?;
Ok(())
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/sh_cmd/src/sh_cmd_state_logical.rs | items/sh_cmd/src/sh_cmd_state_logical.rs | use std::{fmt, marker::PhantomData};
use derivative::Derivative;
use serde::{Deserialize, Serialize};
#[cfg(feature = "output_progress")]
use peace::item_interaction_model::ItemLocationState;
/// State of the shell command execution.
///
/// * If the command has never been executed, this will be `None`.
/// * If it has been executed, this is `Some(String)` captured from stdout.
#[derive(Derivative, Serialize, Deserialize, Eq)]
#[derivative(Clone, Debug, PartialEq)]
pub enum ShCmdStateLogical<Id> {
/// The command is not executed.
///
/// Represents when the command has either never been executed, or has been
/// cleaned up.
None,
/// Command has not been executed since the source files have been updated.
Some {
/// stdout output.
stdout: String,
/// stderr output.
stderr: String,
/// Marker.
marker: PhantomData<Id>,
},
}
impl<Id> fmt::Display for ShCmdStateLogical<Id> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::None => write!(f, "<none>"),
Self::Some { stderr, .. } => stderr.fmt(f),
}
}
}
#[cfg(feature = "output_progress")]
impl<'state, Id> From<&'state ShCmdStateLogical<Id>> for ItemLocationState {
fn from(sh_cmd_state: &'state ShCmdStateLogical<Id>) -> ItemLocationState {
match sh_cmd_state {
ShCmdStateLogical::Some { .. } => ItemLocationState::Exists,
ShCmdStateLogical::None => ItemLocationState::NotExists,
}
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/sh_cmd/src/sh_cmd_state_diff_fn.rs | items/sh_cmd/src/sh_cmd_state_diff_fn.rs | use std::marker::PhantomData;
use crate::{ShCmd, ShCmdError, ShCmdExecutor, ShCmdState, ShCmdStateDiff, ShCmdStateLogical};
/// Runs a shell command to obtain the `ShCmd` diff.
#[derive(Debug)]
pub struct ShCmdStateDiffFn<Id>(PhantomData<Id>);
impl<Id> ShCmdStateDiffFn<Id>
where
Id: Send + Sync + 'static,
{
pub async fn state_diff(
state_diff_sh_cmd: ShCmd,
state_current: &ShCmdState<Id>,
state_goal: &ShCmdState<Id>,
) -> Result<ShCmdStateDiff, ShCmdError> {
let state_current_arg = match &state_current.0.logical {
ShCmdStateLogical::None => "",
ShCmdStateLogical::Some { stdout, .. } => stdout.as_ref(),
};
let state_goal_arg = match &state_goal.0.logical {
ShCmdStateLogical::None => "",
ShCmdStateLogical::Some { stdout, .. } => stdout.as_ref(),
};
let state_diff_sh_cmd = state_diff_sh_cmd.arg(state_current_arg).arg(state_goal_arg);
ShCmdExecutor::<Id>::exec(&state_diff_sh_cmd)
.await
.map(|state| match state.0.logical {
ShCmdStateLogical::None => ShCmdStateDiff::new(String::from(""), String::from("")),
ShCmdStateLogical::Some {
stdout,
stderr,
marker: _,
} => ShCmdStateDiff::new(stdout, stderr),
})
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/src/lib.rs | items/src/lib.rs | //! Collection of items the peace framework.
//!
//! Every item crate needs to be enabled with its own feature. Example:
//!
//! ```toml
//! peace_items = { version = "0.0.3", features = ["file_download"] }
//! ```
//!
//! In code:
//!
//! ```rust
//! #[cfg(feature = "file_download")]
//! # fn main() {
//! use peace::item_model::{item_id, ItemId};
//! use peace_items::file_download::FileDownloadItem;
//!
//! /// Marker type for `FileDownloadParams`.
//! #[derive(Clone, Copy, Debug, PartialEq, Eq)]
//! pub struct MyFileId;
//!
//! let file_download_item =
//! FileDownloadItem::<MyFileId>::new(item_id!("file_to_download"));
//! # }
//! #
//! #[cfg(not(feature = "file_download"))]
//! # fn main() {}
//! ```
// Re-exports
#[cfg(feature = "blank")]
pub use peace_item_blank as blank;
#[cfg(feature = "file_download")]
pub use peace_item_file_download as file_download;
#[cfg(feature = "sh_cmd")]
pub use peace_item_sh_cmd as sh_cmd;
#[cfg(feature = "tar_x")]
pub use peace_item_tar_x as tar_x;
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/tar_x/src/tar_x_error.rs | items/tar_x/src/tar_x_error.rs | use std::path::PathBuf;
#[cfg(feature = "error_reporting")]
use peace::miette;
/// Error while managing tar extraction.
#[cfg_attr(feature = "error_reporting", derive(peace::miette::Diagnostic))]
#[derive(Debug, thiserror::Error)]
pub enum TarXError {
/// Tar file to extract doesn't exist.
#[error(
r#"Tar file to extract doesn't exist: `{}`"#,
tar_path.display()
)]
#[cfg_attr(
feature = "error_reporting",
diagnostic(code(peace_item_tar_x::tar_file_not_exists)),
help("Make sure there is an item that downloads the tar file.")
)]
TarFileNotExists {
/// Path to the tar file to extract.
tar_path: PathBuf,
},
/// Failed to read tar entries.
#[error(
r#"Failed to read tar entries: `{}`"#,
tar_path.display()
)]
#[cfg_attr(
feature = "error_reporting",
diagnostic(code(peace_item_tar_x::tar_entry_read))
)]
TarEntryRead {
/// Path to the tar file.
tar_path: PathBuf,
/// Underlying error.
error: std::io::Error,
},
/// Failed to read tar entry path.
#[error(
r#"Failed to read tar entry path: `{}`"#,
tar_path.display()
)]
#[cfg_attr(
feature = "error_reporting",
diagnostic(code(peace_item_tar_x::tar_entry_path_read))
)]
TarEntryPathRead {
/// Path to the tar file.
tar_path: PathBuf,
/// Underlying error.
error: std::io::Error,
},
/// Failed to read tar entry modified time.
#[error(
r#"Failed to read tar entry modified time: `{}`"#,
tar_path.display()
)]
#[cfg_attr(
feature = "error_reporting",
diagnostic(code(peace_item_tar_x::tar_entry_m_time_read))
)]
TarEntryMTimeRead {
/// Path to the tar file.
tar_path: PathBuf,
/// Entry path in the tar file.
entry_path: PathBuf,
/// Underlying error.
error: std::io::Error,
},
/// Failed to read tar extraction destination path.
#[error(
r#"Failed to read directory within tar extraction destination path: `{}`"#,
dir.display()
)]
#[cfg_attr(
feature = "error_reporting",
diagnostic(code(peace_item_tar_x::tar_dest_read_dir))
)]
TarDestReadDir {
/// Path within the extraction directory.
dir: PathBuf,
/// Underlying error.
error: std::io::Error,
},
/// Failed to read destination file entry.
#[error(
r#"Failed to read destination file entry in `{}`"#,
dest.display()
)]
#[cfg_attr(
feature = "error_reporting",
diagnostic(code(peace_item_tar_x::tar_dest_entry_read))
)]
TarDestEntryRead {
/// Path to the destination directory.
dest: PathBuf,
/// Underlying error.
error: std::io::Error,
},
/// Failed to read destination file type.
#[error(
r#"Failed to read destination file type for `{}`"#,
entry_path.display()
)]
#[cfg_attr(
feature = "error_reporting",
diagnostic(code(peace_item_tar_x::tar_dest_entry_file_type_read))
)]
TarDestEntryFileTypeRead {
/// Path to the file in the destination directory.
entry_path: PathBuf,
/// Underlying error.
error: std::io::Error,
},
/// Failed to read destination file metadata.
#[cfg(not(target_arch = "wasm32"))]
#[error(
r#"Failed to read destination file metadata: `{}` in `{}`"#,
entry_path.display(),
dest.display()
)]
#[cfg_attr(
feature = "error_reporting",
diagnostic(code(peace_item_tar_x::tar_dest_file_metadata_read))
)]
TarDestFileMetadataRead {
/// Path to the destination directory.
dest: PathBuf,
/// Entry path in the tar file.
entry_path: PathBuf,
/// Underlying error.
error: std::io::Error,
},
/// Failed to read destination file modified time.
#[cfg(not(target_arch = "wasm32"))]
#[error(
r#"Failed to read destination file modified time: `{}` in `{}`"#,
entry_path.display(),
dest.display()
)]
#[cfg_attr(
feature = "error_reporting",
diagnostic(code(peace_item_tar_x::tar_entry_m_time_read))
)]
TarDestFileMTimeRead {
/// Path to the destination directory.
dest: PathBuf,
/// Entry path in the tar file.
entry_path: PathBuf,
/// Underlying error.
error: std::io::Error,
},
/// Failed to read destination file modified time system time.
#[cfg(not(target_arch = "wasm32"))]
#[error(
r#"Failed to read destination file modified time system time: `{}` in `{}`"#,
entry_path.display(),
dest.display()
)]
#[cfg_attr(
feature = "error_reporting",
diagnostic(code(peace_item_tar_x::tar_dest_file_m_time_system_time_read))
)]
TarDestFileMTimeSystemTimeRead {
/// Path to the destination directory.
dest: PathBuf,
/// Entry path in the tar file.
entry_path: PathBuf,
/// Underlying error.
error: std::time::SystemTimeError,
},
/// Failed to create tar extraction directory.
#[error(
r#"Failed to create tar extraction directory: `{}`"#,
dest.display()
)]
#[cfg_attr(
feature = "error_reporting",
diagnostic(code(peace_item_tar_x::tar_dest_dir_create))
)]
TarDestDirCreate {
/// Path to the destination directory.
dest: PathBuf,
/// Underlying error.
error: std::io::Error,
},
/// Failed to unpack tar.
#[error(
r#"Failed to unpack tar `{}` into `{}`"#,
tar_path.display(),
dest.display()
)]
#[cfg_attr(
feature = "error_reporting",
diagnostic(code(peace_item_tar_x::tar_unpack))
)]
TarUnpack {
/// Path to the tar file to extract.
tar_path: PathBuf,
/// Path to the destination directory.
dest: PathBuf,
/// Underlying error.
error: std::io::Error,
},
/// Failed to remove file in destination directory.
#[error(
r#"Failed to remove file `{}` in `{}`"#,
entry_path.display(),
dest.display()
)]
#[cfg_attr(
feature = "error_reporting",
diagnostic(code(peace_item_tar_x::tar_dest_file_remove))
)]
TarDestFileRemove {
/// Path to the destination directory.
dest: PathBuf,
/// Path to the file to remove, relative to the destination directory.
entry_path: PathBuf,
/// Underlying error.
error: std::io::Error,
},
// === Framework errors === //
/// A `peace` runtime error occurred.
#[error("A `peace` runtime error occurred.")]
PeaceRtError(
#[cfg_attr(feature = "error_reporting", diagnostic_source)]
#[source]
#[from]
peace::rt_model::Error,
),
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/tar_x/src/file_metadata.rs | items/tar_x/src/file_metadata.rs | use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
/// Metadata about a file in the tar.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct FileMetadata {
/// Path to the file, relative to either the tar root, or the extraction
/// directory root.
path: PathBuf,
/// Last modification time of the file.
///
/// Corresponds to [`mtime`] on Unix, and [`last_write_time`] on Windows.
///
/// [`mtime`]: https://doc.rust-lang.org/std/fs/struct.Metadata.html#method.mtime
/// [`last_write_time`]: https://doc.rust-lang.org/std/fs/struct.Metadata.html#method.last_write_time
modified_time: u64,
}
impl FileMetadata {
/// Returns a new `FileMetadata`.
pub fn new(path: PathBuf, modified_time: u64) -> Self {
Self {
path,
modified_time,
}
}
/// Returns the path of this file metadata.
pub fn path(&self) -> &Path {
&self.path
}
/// Returns the modified time of this file metadata.
///
/// This is the number of seconds since the [Unix epoch].
///
/// [Unix epoch]: https://doc.rust-lang.org/std/time/constant.UNIX_EPOCH.html
pub fn modified_time(&self) -> u64 {
self.modified_time
}
}
impl From<tar::Header> for FileMetadata {
fn from(_header: tar::Header) -> Self {
todo!()
}
}
impl From<std::fs::Metadata> for FileMetadata {
fn from(_metadata: std::fs::Metadata) -> Self {
todo!()
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/tar_x/src/tar_x_params.rs | items/tar_x/src/tar_x_params.rs | use std::{
marker::PhantomData,
path::{Path, PathBuf},
};
use derivative::Derivative;
use peace::params::Params;
use serde::{Deserialize, Serialize};
/// Tar extraction parameters.
///
/// The `Id` type parameter is needed for each tar extraction params to be a
/// distinct type.
///
/// # Type Parameters
///
/// * `Id`: A zero-sized type used to distinguish different tar extraction
/// parameters from each other.
// TODO: params for:
//
// * keep or remove unknown files
// * force re-extraction
#[derive(Derivative, Params, PartialEq, Eq, Deserialize, Serialize)]
#[derivative(Clone, Debug)]
#[serde(bound = "")]
pub struct TarXParams<Id> {
/// Path of the tar file to extract.
tar_path: PathBuf,
/// Directory path to extract the tar file to.
dest: PathBuf,
/// Marker for unique tar extraction parameters type.
marker: PhantomData<Id>,
}
impl<Id> TarXParams<Id> {
/// Returns new `TarXParams`.
pub fn new(tar_path: PathBuf, dest: PathBuf) -> Self {
Self {
tar_path,
dest,
marker: PhantomData,
}
}
/// Returns the path of the tar file to extract.
pub fn tar_path(&self) -> &Path {
&self.tar_path
}
/// Returns the directory path to extract the tar file to.
pub fn dest(&self) -> &Path {
&self.dest
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/tar_x/src/lib.rs | items/tar_x/src/lib.rs | #![cfg_attr(coverage_nightly, feature(coverage_attribute))]
//! Manages extracting a tar file for the peace framework
pub use crate::{
file_metadata::FileMetadata,
file_metadatas::FileMetadatas,
tar_x_apply_fns::TarXApplyFns,
tar_x_data::TarXData,
tar_x_error::TarXError,
tar_x_item::TarXItem,
tar_x_params::{TarXParams, TarXParamsFieldWise, TarXParamsPartial},
tar_x_state_current_fn::TarXStateCurrentFn,
tar_x_state_diff::TarXStateDiff,
tar_x_state_diff_fn::TarXStateDiffFn,
tar_x_state_goal_fn::TarXStateGoalFn,
};
mod file_metadata;
mod file_metadatas;
mod tar_x_apply_fns;
mod tar_x_data;
mod tar_x_error;
mod tar_x_item;
mod tar_x_params;
mod tar_x_state_current_fn;
mod tar_x_state_diff;
mod tar_x_state_diff_fn;
mod tar_x_state_goal_fn;
#[cfg(not(target_arch = "wasm32"))]
mod native;
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/tar_x/src/tar_x_item.rs | items/tar_x/src/tar_x_item.rs | use std::marker::PhantomData;
use peace::{
cfg::{async_trait, ApplyCheck, FnCtx, Item},
item_model::ItemId,
params::Params,
resource_rt::{resources::ts::Empty, Resources},
};
use crate::{
FileMetadatas, TarXApplyFns, TarXData, TarXError, TarXParams, TarXStateCurrentFn,
TarXStateDiff, TarXStateDiffFn, TarXStateGoalFn,
};
/// Item for extracting a tar file.
///
/// The `Id` type parameter is needed for each tar extraction params to be a
/// distinct type.
///
/// The following use cases are intended to be supported:
///
/// * A pristine directory with only the tar's contents and nothing else (in
/// progress).
/// * Extraction of a tar over an existing directory (not yet implemented).
///
/// # Type Parameters
///
/// * `Id`: A zero-sized type used to distinguish different tar extraction
/// parameters from each other.
#[derive(Debug)]
pub struct TarXItem<Id> {
/// ID of the item to extract the tar.
item_id: ItemId,
/// Marker for unique tar extraction parameters type.
marker: PhantomData<Id>,
}
impl<Id> Clone for TarXItem<Id> {
fn clone(&self) -> Self {
Self {
item_id: self.item_id.clone(),
marker: PhantomData,
}
}
}
impl<Id> TarXItem<Id> {
/// Returns a new `TarXItem`.
pub fn new(item_id: ItemId) -> Self {
Self {
item_id,
marker: PhantomData,
}
}
}
#[async_trait(?Send)]
impl<Id> Item for TarXItem<Id>
where
Id: Send + Sync + 'static,
{
type Data<'exec> = TarXData<'exec, Id>;
type Error = TarXError;
type Params<'exec> = TarXParams<Id>;
type State = FileMetadatas;
type StateDiff = TarXStateDiff;
fn id(&self) -> &ItemId {
&self.item_id
}
async fn setup(&self, _resources: &mut Resources<Empty>) -> Result<(), TarXError> {
Ok(())
}
#[cfg(feature = "item_state_example")]
fn state_example(_params: &Self::Params<'_>, _data: Self::Data<'_>) -> Self::State {
use std::{
path::PathBuf,
time::{Duration, SystemTime, UNIX_EPOCH},
};
use crate::FileMetadata;
let mtime = SystemTime::now()
.duration_since(UNIX_EPOCH)
.as_ref()
.map(Duration::as_secs)
.unwrap_or(0u64);
let files_extracted = vec![
FileMetadata::new(PathBuf::from(String::from("tar_x_example_1.txt")), mtime),
FileMetadata::new(PathBuf::from(String::from("tar_x_example_2.txt")), mtime),
];
FileMetadatas::from(files_extracted)
}
async fn try_state_current(
fn_ctx: FnCtx<'_>,
params_partial: &<Self::Params<'_> as Params>::Partial,
data: TarXData<'_, Id>,
) -> Result<Option<Self::State>, TarXError> {
TarXStateCurrentFn::try_state_current(fn_ctx, params_partial, data).await
}
async fn state_current(
fn_ctx: FnCtx<'_>,
params: &Self::Params<'_>,
data: TarXData<'_, Id>,
) -> Result<Self::State, TarXError> {
TarXStateCurrentFn::state_current(fn_ctx, params, data).await
}
async fn try_state_goal(
fn_ctx: FnCtx<'_>,
params_partial: &<Self::Params<'_> as Params>::Partial,
data: TarXData<'_, Id>,
) -> Result<Option<Self::State>, TarXError> {
TarXStateGoalFn::try_state_goal(fn_ctx, params_partial, data).await
}
async fn state_goal(
fn_ctx: FnCtx<'_>,
params: &Self::Params<'_>,
data: TarXData<'_, Id>,
) -> Result<Self::State, TarXError> {
TarXStateGoalFn::state_goal(fn_ctx, params, data).await
}
async fn state_diff(
_params_partial: &<Self::Params<'_> as Params>::Partial,
_data: Self::Data<'_>,
state_current: &Self::State,
state_goal: &Self::State,
) -> Result<Self::StateDiff, TarXError> {
TarXStateDiffFn::state_diff(state_current, state_goal).await
}
async fn state_clean(
_params_partial: &<Self::Params<'_> as Params>::Partial,
_data: Self::Data<'_>,
) -> Result<Self::State, TarXError> {
Ok(FileMetadatas::default())
}
async fn apply_check(
params: &Self::Params<'_>,
data: Self::Data<'_>,
state_current: &Self::State,
state_target: &Self::State,
diff: &Self::StateDiff,
) -> Result<ApplyCheck, Self::Error> {
TarXApplyFns::<Id>::apply_check(params, data, state_current, state_target, diff).await
}
async fn apply_dry(
fn_ctx: FnCtx<'_>,
params: &Self::Params<'_>,
data: Self::Data<'_>,
state_current: &Self::State,
state_target: &Self::State,
diff: &Self::StateDiff,
) -> Result<Self::State, Self::Error> {
TarXApplyFns::<Id>::apply_dry(fn_ctx, params, data, state_current, state_target, diff).await
}
async fn apply(
fn_ctx: FnCtx<'_>,
params: &Self::Params<'_>,
data: Self::Data<'_>,
state_current: &Self::State,
state_target: &Self::State,
diff: &Self::StateDiff,
) -> Result<Self::State, Self::Error> {
TarXApplyFns::<Id>::apply(fn_ctx, params, data, state_current, state_target, diff).await
}
#[cfg(feature = "item_interactions")]
fn interactions(
params: &Self::Params<'_>,
_data: Self::Data<'_>,
) -> Vec<peace::item_interaction_model::ItemInteraction> {
use peace::item_interaction_model::{
ItemInteractionWithin, ItemLocation, ItemLocationAncestors,
};
let location: ItemLocationAncestors = vec![
ItemLocation::localhost(),
ItemLocation::path(format!("📁 {}", params.dest().display())),
]
.into();
let item_interaction = ItemInteractionWithin::new(location).into();
vec![item_interaction]
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/tar_x/src/native.rs | items/tar_x/src/native.rs | pub(crate) use self::{dest_dir_entry::DestDirEntry, dir_unfold::DirUnfold};
mod dest_dir_entry;
mod dir_unfold;
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/tar_x/src/tar_x_data.rs | items/tar_x/src/tar_x_data.rs | use std::marker::PhantomData;
use peace::{
data::{accessors::R, Data},
rt_model::Storage,
};
/// Data used to extract a tar file.
///
/// # Type Parameters
///
/// * `Id`: A zero-sized type used to distinguish different tar extraction
/// parameters from each other.
#[derive(Data, Debug)]
pub struct TarXData<'exec, Id>
where
Id: Send + Sync + 'static,
{
/// Storage to interact with to read the tar file / extract to.
storage: R<'exec, Storage>,
/// Marker.
marker: PhantomData<Id>,
}
impl<Id> TarXData<'_, Id>
where
Id: Send + Sync + 'static,
{
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/items/tar_x/src/tar_x_state_diff_fn.rs | items/tar_x/src/tar_x_state_diff_fn.rs | use std::cmp::Ordering;
use crate::{FileMetadata, FileMetadatas, TarXError, TarXStateDiff};
/// Tar extraction status diff function.
#[derive(Debug)]
pub struct TarXStateDiffFn;
impl TarXStateDiffFn {
pub async fn state_diff(
file_metadatas_current: &FileMetadatas,
file_metadatas_goal: &FileMetadatas,
) -> Result<TarXStateDiff, TarXError> {
let mut current_metadata_iter = file_metadatas_current.iter();
let mut goal_metadata_iter = file_metadatas_goal.iter();
let mut added = Vec::<FileMetadata>::new();
let mut modified = Vec::<FileMetadata>::new();
let mut removed = Vec::<FileMetadata>::new();
let mut current_metadata_opt = current_metadata_iter.next();
let mut goal_metadata_opt = goal_metadata_iter.next();
loop {
match (current_metadata_opt, goal_metadata_opt) {
(Some(current_metadata), Some(goal_metadata)) => {
match current_metadata.path().cmp(goal_metadata.path()) {
Ordering::Less => {
// extracted file name is smaller than file name in tar
// meaning extracted file has been removed.
removed.push(current_metadata.clone());
current_metadata_opt = current_metadata_iter.next();
continue;
}
Ordering::Equal => {
match current_metadata
.modified_time()
.cmp(&goal_metadata.modified_time())
{
Ordering::Less | Ordering::Greater => {
// Should we not overwrite if destination file is greater?
modified.push(goal_metadata.clone());
current_metadata_opt = current_metadata_iter.next();
goal_metadata_opt = goal_metadata_iter.next();
}
Ordering::Equal => {
// don't include in the diff, it's in sync
current_metadata_opt = current_metadata_iter.next();
goal_metadata_opt = goal_metadata_iter.next();
}
}
}
Ordering::Greater => {
// extracted file name is greater than file name in tar
// meaning tar file is newly added.
added.push(goal_metadata.clone());
goal_metadata_opt = goal_metadata_iter.next();
continue;
}
}
}
(Some(current_metadata), None) => {
removed.push(current_metadata.clone());
removed.extend(current_metadata_iter.cloned());
break;
}
(None, Some(goal_metadata)) => {
added.push(goal_metadata.clone());
added.extend(goal_metadata_iter.cloned());
break;
}
(None, None) => break,
}
}
if added.is_empty() && modified.is_empty() && removed.is_empty() {
Ok(TarXStateDiff::ExtractionInSync)
} else {
let added = FileMetadatas::from(added);
let modified = FileMetadatas::from(modified);
let removed = FileMetadatas::from(removed);
Ok(TarXStateDiff::ExtractionOutOfSync {
added,
modified,
removed,
})
}
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/tar_x/src/file_metadatas.rs | items/tar_x/src/file_metadatas.rs | use std::fmt;
use serde::{Deserialize, Serialize};
use crate::FileMetadata;
#[cfg(feature = "output_progress")]
use peace::item_interaction_model::ItemLocationState;
/// Metadata of files to extract.
///
/// The `FileMetadata`s are sorted by their path.
///
/// This should be constructed using the `From<Vec<FileMetadata>>` function.
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct FileMetadatas(Vec<FileMetadata>);
impl FileMetadatas {
/// Returns the inner `Vec<FileMetadata>`.
pub fn into_inner(self) -> Vec<FileMetadata> {
self.0
}
/// Returns a mutable iterator over the file metadatas.
pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, FileMetadata> {
self.0.iter_mut()
}
}
impl std::ops::Deref for FileMetadatas {
type Target = Vec<FileMetadata>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl fmt::Display for FileMetadatas {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let len = self.len();
let s = if len == 1 { "" } else { "s" };
write!(f, "{len} file{s}")
}
}
impl From<Vec<FileMetadata>> for FileMetadatas {
fn from(mut file_metadatas: Vec<FileMetadata>) -> Self {
file_metadatas.sort_by(|file_metadata_a, file_metadata_b| {
file_metadata_a.path().cmp(file_metadata_b.path())
});
Self(file_metadatas)
}
}
#[cfg(feature = "output_progress")]
impl<'state> From<&'state FileMetadatas> for ItemLocationState {
fn from(file_metadatas: &'state FileMetadatas) -> ItemLocationState {
match file_metadatas.0.is_empty() {
true => ItemLocationState::NotExists,
false => ItemLocationState::Exists,
}
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
azriel91/peace | https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/items/tar_x/src/tar_x_state_diff.rs | items/tar_x/src/tar_x_state_diff.rs | use std::fmt;
use serde::{Deserialize, Serialize};
use crate::FileMetadatas;
/// Diff between the tar and extraction directory.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum TarXStateDiff {
/// Files in the tar are in sync with extraction directory.
ExtractionInSync,
/// Files in the tar are not in sync with extraction directory.
ExtractionOutOfSync {
/// Files that existx in the tar but not the extraction directory.
added: FileMetadatas,
/// Files that exist in both the tar and extraction directory, but
/// differ.
modified: FileMetadatas,
/// Files that exist in the extraction directory, but not in the tar.
removed: FileMetadatas,
},
}
impl fmt::Display for TarXStateDiff {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ExtractionInSync => write!(f, "files extracted and up to date"),
Self::ExtractionOutOfSync {
added,
modified,
removed,
} => {
let added = added.len();
let modified = modified.len();
let removed = removed.len();
write!(
f,
"extraction out of sync: {added} files added, {modified} modified, {removed} removed"
)
}
}
}
}
| rust | Apache-2.0 | 5e2c43f2c0b18672749d0902d2285c703e24de97 | 2026-01-04T20:22:52.922300Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.