use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;
use futures_util::future::BoxFuture;
use super::Upload;
use crate::validation::Errors;
use crate::{AppState, Result};
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum StepOutcome {
Keep,
Reject(String),
Derived(String, Upload),
}
#[derive(Clone)]
#[non_exhaustive]
pub struct UploadContext {
field: String,
state: AppState,
}
impl UploadContext {
pub(crate) fn new(field: impl Into<String>, state: &AppState) -> Self {
Self {
field: field.into(),
state: state.clone(),
}
}
pub fn field(&self) -> &str {
&self.field
}
pub fn state(&self) -> &AppState {
&self.state
}
}
impl fmt::Debug for UploadContext {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("UploadContext")
.field("field", &self.field)
.finish_non_exhaustive()
}
}
pub trait UploadStep: Send + Sync + 'static {
fn process<'a>(
&'a self,
file: &'a mut Upload,
ctx: &'a UploadContext,
) -> BoxFuture<'a, Result<StepOutcome>>;
}
#[derive(Clone, Default)]
pub struct Pipeline {
steps: Vec<Arc<dyn UploadStep>>,
}
impl Pipeline {
pub fn new() -> Self {
Self::default()
}
pub fn step(mut self, step: impl UploadStep) -> Self {
self.steps.push(Arc::new(step));
self
}
pub fn is_empty(&self) -> bool {
self.steps.is_empty()
}
pub(crate) async fn run(
&self,
file: &mut Upload,
ctx: &UploadContext,
) -> Result<Option<String>> {
for step in &self.steps {
match step.process(file, ctx).await? {
StepOutcome::Keep => {}
StepOutcome::Reject(message) => return Ok(Some(message)),
StepOutcome::Derived(name, derived) => file.derive(&name, derived),
}
}
Ok(None)
}
pub(crate) async fn run_form(
&self,
state: &AppState,
fields: &[(String, String)],
uploads: &mut HashMap<String, Upload>,
errors: &mut Errors,
) -> Result<bool> {
let mut changed = false;
for (field, token) in fields {
let Some(file) = uploads.get_mut(token) else {
continue;
};
let field = field_name(field);
let ctx = UploadContext::new(field.clone(), state);
let before = file.fingerprint();
if let Some(message) = self.run(file, &ctx).await? {
errors.add(&field, message);
}
changed |= before != file.fingerprint();
}
Ok(changed)
}
}
impl fmt::Debug for Pipeline {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Pipeline")
.field("steps", &self.steps.len())
.finish()
}
}
fn field_name(field: &str) -> String {
let field = field.strip_suffix("[]").unwrap_or(field);
crate::validation::nested::normalize(field)
}