Skip to main content

fakecloud_stepfunctions/service/
mod.rs

1use std::collections::BTreeMap;
2use std::sync::Arc;
3
4use async_trait::async_trait;
5use chrono::Utc;
6use http::StatusCode;
7use serde_json::{json, Value};
8use tokio::sync::Mutex as AsyncMutex;
9
10use fakecloud_core::delivery::DeliveryBus;
11use fakecloud_core::pagination::paginate_checked;
12use fakecloud_core::registry::ServiceRegistry;
13use fakecloud_core::service::{AwsRequest, AwsResponse, AwsService, AwsServiceError};
14use fakecloud_core::validation::*;
15use fakecloud_dynamodb::SharedDynamoDbState;
16use fakecloud_persistence::SnapshotStore;
17
18use crate::interpreter;
19use crate::state::{
20    Execution, ExecutionStatus, SharedStepFunctionsState, StateMachine, StateMachineStatus,
21    StateMachineType, StepFunctionsSnapshot, StepFunctionsState,
22    STEPFUNCTIONS_SNAPSHOT_SCHEMA_VERSION,
23};
24
25const SUPPORTED: &[&str] = &[
26    "CreateStateMachine",
27    "DescribeStateMachine",
28    "ListStateMachines",
29    "DeleteStateMachine",
30    "UpdateStateMachine",
31    "TagResource",
32    "UntagResource",
33    "ListTagsForResource",
34    "StartExecution",
35    "StopExecution",
36    "DescribeExecution",
37    "ListExecutions",
38    "GetExecutionHistory",
39    "DescribeStateMachineForExecution",
40    "CreateActivity",
41    "DeleteActivity",
42    "DescribeActivity",
43    "ListActivities",
44    "GetActivityTask",
45    "SendTaskFailure",
46    "SendTaskHeartbeat",
47    "SendTaskSuccess",
48    "PublishStateMachineVersion",
49    "DeleteStateMachineVersion",
50    "ListStateMachineVersions",
51    "CreateStateMachineAlias",
52    "DeleteStateMachineAlias",
53    "DescribeStateMachineAlias",
54    "ListStateMachineAliases",
55    "UpdateStateMachineAlias",
56    "DescribeMapRun",
57    "ListMapRuns",
58    "UpdateMapRun",
59    "RedriveExecution",
60    "StartSyncExecution",
61    "TestState",
62    "ValidateStateMachineDefinition",
63];
64
65/// Handle to the central service registry, set by `main.rs` after every service
66/// has been registered. Wrapped in `OnceLock` so `StepFunctionsService` can be
67/// constructed (and registered into the very registry it later reads back) before
68/// the registry itself is finalized. The interpreter snapshots the inner `Arc`
69/// when it needs to dispatch generic `aws-sdk:*` Task integrations.
70pub type SharedServiceRegistry = Arc<std::sync::OnceLock<Arc<ServiceRegistry>>>;
71
72pub struct StepFunctionsService {
73    state: SharedStepFunctionsState,
74    delivery: Option<Arc<DeliveryBus>>,
75    dynamodb_state: Option<SharedDynamoDbState>,
76    registry: Option<SharedServiceRegistry>,
77    snapshot_store: Option<Arc<dyn SnapshotStore>>,
78    snapshot_lock: Arc<AsyncMutex<()>>,
79}
80
81mod activities;
82mod executions;
83mod map_runs;
84mod state_machines;
85mod tags;
86mod tasks;
87mod validation;
88
89impl StepFunctionsService {
90    pub fn new(state: SharedStepFunctionsState) -> Self {
91        Self {
92            state,
93            delivery: None,
94            dynamodb_state: None,
95            registry: None,
96            snapshot_store: None,
97            snapshot_lock: Arc::new(AsyncMutex::new(())),
98        }
99    }
100
101    pub fn with_delivery(mut self, delivery: Arc<DeliveryBus>) -> Self {
102        self.delivery = Some(delivery);
103        self
104    }
105
106    pub fn with_dynamodb(mut self, dynamodb_state: SharedDynamoDbState) -> Self {
107        self.dynamodb_state = Some(dynamodb_state);
108        self
109    }
110
111    /// Hand the service a deferred-fill handle to the central [`ServiceRegistry`].
112    /// `main.rs` calls [`OnceLock::set`] on the inner cell after every service
113    /// has been registered; until then the interpreter falls back to its
114    /// hand-coded SDK integrations (lambda invoke, sqs sendMessage, …).
115    pub fn with_registry(mut self, registry: SharedServiceRegistry) -> Self {
116        self.registry = Some(registry);
117        self
118    }
119
120    pub fn with_snapshot_store(mut self, store: Arc<dyn SnapshotStore>) -> Self {
121        self.snapshot_store = Some(store);
122        self
123    }
124
125    async fn save_snapshot(&self) {
126        save_stepfunctions_snapshot(
127            &self.state,
128            self.snapshot_store.clone(),
129            &self.snapshot_lock,
130        )
131        .await;
132    }
133
134    /// Build a hook that persists the current Step Functions state when invoked,
135    /// or `None` in memory mode (no snapshot store). The CloudFormation
136    /// provisioner mutates `state` directly and uses this to write a
137    /// CFN-provisioned resource through to disk, the same way a direct mutating
138    /// API call would.
139    pub fn snapshot_hook(&self) -> Option<fakecloud_persistence::SnapshotHook> {
140        let store = self.snapshot_store.clone()?;
141        let state = self.state.clone();
142        let lock = self.snapshot_lock.clone();
143        Some(Arc::new(move || {
144            let state = state.clone();
145            let store = store.clone();
146            let lock = lock.clone();
147            Box::pin(async move {
148                save_stepfunctions_snapshot(&state, Some(store), &lock).await;
149            })
150        }))
151    }
152}
153
154/// Persist the current Step Functions state as a snapshot. Offloads the serde +
155/// blocking file write to the Tokio blocking pool. Noop when `store` is `None`
156/// (memory mode). Shared by `StepFunctionsService::save_snapshot` and the
157/// CloudFormation provisioner's post-provision persist hook so both route
158/// through the same serialize-and-write path.
159pub async fn save_stepfunctions_snapshot(
160    state: &SharedStepFunctionsState,
161    store: Option<Arc<dyn SnapshotStore>>,
162    lock: &AsyncMutex<()>,
163) {
164    let Some(store) = store else {
165        return;
166    };
167    let _guard = lock.lock().await;
168    let snapshot = StepFunctionsSnapshot {
169        schema_version: STEPFUNCTIONS_SNAPSHOT_SCHEMA_VERSION,
170        state: None,
171        accounts: Some(state.read().clone()),
172    };
173    let join = tokio::task::spawn_blocking(move || -> std::io::Result<()> {
174        let bytes = serde_json::to_vec(&snapshot)
175            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()))?;
176        store.save(&bytes)
177    })
178    .await;
179    match join {
180        Ok(Ok(())) => {}
181        Ok(Err(err)) => tracing::error!(%err, "failed to write stepfunctions snapshot"),
182        Err(err) => tracing::error!(%err, "stepfunctions snapshot task panicked"),
183    }
184}
185
186/// Abort executions that were RUNNING (or PENDING_REDRIVE) when the server
187/// stopped, called once after a persistence snapshot is loaded on startup.
188///
189/// The in-memory interpreter that was driving each one is gone after a restart,
190/// so the execution can never advance. Real Step Functions resumes from durable
191/// interpreter state; fakecloud can't, so leaving them RUNNING would strand them
192/// forever (DescribeExecution would report RUNNING with no way to ever finish).
193/// Aborting with a terminal stop date + error/cause is the honest outcome
194/// (bug-audit 2026-06-20, 0.A2). Returns the number reconciled.
195pub fn reconcile_interrupted_executions(state: &SharedStepFunctionsState) -> usize {
196    let now = Utc::now();
197    let mut count = 0;
198    let mut accounts = state.write();
199    let account_ids: Vec<String> = accounts.iter().map(|(id, _)| id.to_string()).collect();
200    for account_id in account_ids {
201        let Some(s) = accounts.get_mut(&account_id) else {
202            continue;
203        };
204        for exec in s.executions.values_mut() {
205            if matches!(
206                exec.status,
207                ExecutionStatus::Running | ExecutionStatus::PendingRedrive
208            ) {
209                exec.status = ExecutionStatus::Aborted;
210                exec.stop_date = Some(now);
211                exec.error = Some("Fakecloud.Restart".to_string());
212                exec.cause = Some(
213                    "Execution was interrupted by a fakecloud restart and cannot be resumed"
214                        .to_string(),
215                );
216                count += 1;
217            }
218        }
219    }
220    count
221}
222
223fn is_mutating_action(action: &str) -> bool {
224    matches!(
225        action,
226        "CreateStateMachine"
227            | "DeleteStateMachine"
228            | "UpdateStateMachine"
229            | "TagResource"
230            | "UntagResource"
231            | "StartExecution"
232            | "StopExecution"
233            | "CreateActivity"
234            | "DeleteActivity"
235            | "GetActivityTask"
236            | "SendTaskFailure"
237            | "SendTaskHeartbeat"
238            | "SendTaskSuccess"
239            | "PublishStateMachineVersion"
240            | "DeleteStateMachineVersion"
241            | "CreateStateMachineAlias"
242            | "DeleteStateMachineAlias"
243            | "UpdateStateMachineAlias"
244            | "UpdateMapRun"
245            | "RedriveExecution"
246            | "StartSyncExecution"
247    )
248}
249
250#[async_trait]
251impl AwsService for StepFunctionsService {
252    fn service_name(&self) -> &str {
253        "states"
254    }
255
256    async fn handle(&self, req: AwsRequest) -> Result<AwsResponse, AwsServiceError> {
257        let mutates = is_mutating_action(req.action.as_str());
258        let result = match req.action.as_str() {
259            "CreateStateMachine" => self.create_state_machine(&req),
260            "DescribeStateMachine" => self.describe_state_machine(&req),
261            "ListStateMachines" => self.list_state_machines(&req),
262            "DeleteStateMachine" => self.delete_state_machine(&req),
263            "UpdateStateMachine" => self.update_state_machine(&req),
264            "TagResource" => self.tag_resource(&req),
265            "UntagResource" => self.untag_resource(&req),
266            "ListTagsForResource" => self.list_tags_for_resource(&req),
267            "StartExecution" => self.start_execution(&req),
268            "StopExecution" => self.stop_execution(&req),
269            "DescribeExecution" => self.describe_execution(&req),
270            "ListExecutions" => self.list_executions(&req),
271            "GetExecutionHistory" => self.get_execution_history(&req),
272            "DescribeStateMachineForExecution" => self.describe_state_machine_for_execution(&req),
273            "CreateActivity" => self.create_activity(&req),
274            "DeleteActivity" => self.delete_activity(&req),
275            "DescribeActivity" => self.describe_activity(&req),
276            "ListActivities" => self.list_activities(&req),
277            "GetActivityTask" => self.get_activity_task(&req).await,
278            "SendTaskFailure" => self.send_task_failure(&req),
279            "SendTaskHeartbeat" => self.send_task_heartbeat(&req),
280            "SendTaskSuccess" => self.send_task_success(&req),
281            "PublishStateMachineVersion" => self.publish_state_machine_version(&req),
282            "DeleteStateMachineVersion" => self.delete_state_machine_version(&req),
283            "ListStateMachineVersions" => self.list_state_machine_versions(&req),
284            "CreateStateMachineAlias" => self.create_state_machine_alias(&req),
285            "DeleteStateMachineAlias" => self.delete_state_machine_alias(&req),
286            "DescribeStateMachineAlias" => self.describe_state_machine_alias(&req),
287            "ListStateMachineAliases" => self.list_state_machine_aliases(&req),
288            "UpdateStateMachineAlias" => self.update_state_machine_alias(&req),
289            "DescribeMapRun" => self.describe_map_run(&req),
290            "ListMapRuns" => self.list_map_runs(&req),
291            "UpdateMapRun" => self.update_map_run(&req),
292            "RedriveExecution" => self.redrive_execution(&req),
293            "StartSyncExecution" => self.start_sync_execution(&req).await,
294            "TestState" => self.test_state(&req),
295            "ValidateStateMachineDefinition" => self.validate_state_machine_definition(&req),
296            _ => Err(AwsServiceError::action_not_implemented(
297                "states",
298                &req.action,
299            )),
300        };
301        if mutates && matches!(result.as_ref(), Ok(resp) if resp.status.is_success()) {
302            self.save_snapshot().await;
303        }
304        result
305    }
306
307    fn supported_actions(&self) -> &[&str] {
308        SUPPORTED
309    }
310}
311
312impl StepFunctionsService {
313    fn list_activities(&self, req: &AwsRequest) -> Result<AwsResponse, AwsServiceError> {
314        let body = req.json_body();
315        let raw_max_results = body["maxResults"].as_i64();
316        if let Some(mr) = raw_max_results {
317            validate_max_results(mr)?;
318        }
319        let next_token = body["nextToken"].as_str();
320        if let Some(t) = next_token {
321            validate_page_token(t)?;
322        }
323        // Smithy default: maxResults=0 means "use the service default"
324        // (100 for Step Functions), which we honour by treating both
325        // `None` and `0` as 100.
326        let max_results = match raw_max_results.unwrap_or(0) {
327            0 => 100,
328            n => n as usize,
329        };
330        let accounts = self.state.read();
331        let empty = crate::state::StepFunctionsState::new(&req.account_id, &req.region);
332        let state = accounts.get(&req.account_id).unwrap_or(&empty);
333        let mut activities: Vec<&crate::state::Activity> = state.activities.values().collect();
334        activities.sort_by(|a, b| a.name.cmp(&b.name));
335        let items: Vec<Value> = activities
336            .iter()
337            .map(|a| {
338                json!({
339                    "activityArn": a.arn,
340                    "name": a.name,
341                    "creationDate": a.creation_date.timestamp(),
342                })
343            })
344            .collect();
345        let (page, token) =
346            paginate_checked(&items, next_token, max_results).map_err(|_| invalid_token())?;
347        let mut resp = json!({ "activities": page });
348        if let Some(t) = token {
349            resp["nextToken"] = json!(t);
350        }
351        Ok(AwsResponse::ok_json(resp))
352    }
353}
354
355fn state_machine_alias_to_json(alias: &crate::state::StateMachineAlias) -> Value {
356    json!({
357        "stateMachineAliasArn": alias.arn,
358        "name": alias.name,
359        "description": alias.description,
360        "routingConfiguration": alias.routing_configuration.iter().map(|r| json!({
361            "stateMachineVersionArn": r.state_machine_version_arn,
362            "weight": r.weight,
363        })).collect::<Vec<_>>(),
364        "creationDate": alias.creation_date.timestamp(),
365        "updateDate": alias.update_date.timestamp(),
366    })
367}
368
369fn map_run_to_json(mr: &crate::state::MapRun) -> Value {
370    // Iterations still in flight while the map run is RUNNING; zero once it has
371    // reached a terminal status.
372    let accounted = mr.succeeded_count + mr.failed_count;
373    let running = if mr.status == "RUNNING" {
374        (mr.total_count - accounted).max(0)
375    } else {
376        0
377    };
378    // AWS reports parallel `itemCounts` and `executionCounts` maps; with one
379    // child execution per item they carry identical tallies here.
380    let counts = json!({
381        "pending": 0,
382        "running": running,
383        "succeeded": mr.succeeded_count,
384        "failed": mr.failed_count,
385        "timedOut": 0,
386        "aborted": 0,
387        "results": mr.succeeded_count,
388        "total": mr.total_count,
389        "failuresNotRedrivable": 0,
390        "pendingRedrive": 0,
391    });
392    json!({
393        "mapRunArn": mr.map_run_arn,
394        "executionArn": mr.execution_arn,
395        "maxConcurrency": mr.max_concurrency,
396        "toleratedFailurePercentage": mr.tolerated_failure_percentage,
397        "toleratedFailureCount": mr.tolerated_failure_count,
398        "status": mr.status,
399        "startDate": mr.start_date.timestamp(),
400        "stopDate": mr.stop_date.map(|d| d.timestamp()),
401        "itemCounts": counts,
402        "executionCounts": counts,
403    })
404}
405
406// ─── Helpers ────────────────────────────────────────────────────────────
407
408fn state_machine_to_json(sm: &StateMachine) -> Value {
409    let mut resp = json!({
410        "name": sm.name,
411        "stateMachineArn": sm.arn,
412        "definition": sm.definition,
413        "roleArn": sm.role_arn,
414        "type": sm.machine_type.as_str(),
415        "status": sm.status.as_str(),
416        "creationDate": sm.creation_date.timestamp() as f64,
417        "updateDate": sm.update_date.timestamp() as f64,
418        "revisionId": sm.revision_id,
419        "label": sm.name,
420    });
421
422    if !sm.description.is_empty() {
423        resp["description"] = json!(sm.description);
424    }
425
426    if let Some(ref logging) = sm.logging_configuration {
427        resp["loggingConfiguration"] = logging.clone();
428    } else {
429        resp["loggingConfiguration"] = json!({
430            "level": "OFF",
431            "includeExecutionData": false,
432            "destinations": [],
433        });
434    }
435
436    if let Some(ref tracing) = sm.tracing_configuration {
437        resp["tracingConfiguration"] = tracing.clone();
438    } else {
439        resp["tracingConfiguration"] = json!({
440            "enabled": false,
441        });
442    }
443
444    if let Some(ref enc) = sm.encryption_configuration {
445        resp["encryptionConfiguration"] = enc.clone();
446    }
447
448    resp
449}
450
451fn missing(name: &str) -> AwsServiceError {
452    AwsServiceError::aws_error(
453        StatusCode::BAD_REQUEST,
454        "ValidationException",
455        format!("The request must contain the parameter {name}."),
456    )
457}
458
459fn state_machine_not_found(arn: &str) -> AwsServiceError {
460    AwsServiceError::aws_error(
461        StatusCode::BAD_REQUEST,
462        "StateMachineDoesNotExist",
463        format!("State Machine Does Not Exist: '{arn}'"),
464    )
465}
466
467fn activity_not_found(arn: &str) -> AwsServiceError {
468    AwsServiceError::aws_error(
469        StatusCode::BAD_REQUEST,
470        "ActivityDoesNotExist",
471        format!("Activity does not exist: {arn}"),
472    )
473}
474
475fn task_does_not_exist(token: &str) -> AwsServiceError {
476    AwsServiceError::aws_error(
477        StatusCode::BAD_REQUEST,
478        "TaskDoesNotExist",
479        format!("Task does not exist: {token}"),
480    )
481}
482
483fn resource_not_found(arn: &str) -> AwsServiceError {
484    AwsServiceError::aws_error(
485        StatusCode::BAD_REQUEST,
486        "ResourceNotFound",
487        format!("Resource not found: '{arn}'"),
488    )
489}
490
491/// Parse + validate an alias `routingConfiguration` array.
492///
493/// AWS rules: 1 or 2 routes; weights are 0-100 and sum to 100; each
494/// route must include `stateMachineVersionArn`.
495fn parse_routing_configuration(
496    routes: &[serde_json::Value],
497) -> Result<Vec<crate::state::AliasRoute>, AwsServiceError> {
498    if routes.is_empty() || routes.len() > 2 {
499        return Err(AwsServiceError::aws_error(
500            StatusCode::BAD_REQUEST,
501            "ValidationException",
502            "routingConfiguration must contain 1 or 2 routes.",
503        ));
504    }
505    let parsed: Vec<crate::state::AliasRoute> = routes
506        .iter()
507        .map(|r| {
508            let arn = r["stateMachineVersionArn"].as_str().ok_or_else(|| {
509                AwsServiceError::aws_error(
510                    StatusCode::BAD_REQUEST,
511                    "ValidationException",
512                    "routingConfiguration entries must contain stateMachineVersionArn.",
513                )
514            })?;
515            let weight = r["weight"].as_i64().ok_or_else(|| {
516                AwsServiceError::aws_error(
517                    StatusCode::BAD_REQUEST,
518                    "ValidationException",
519                    "routingConfiguration entries must contain a numeric weight.",
520                )
521            })?;
522            if !(0..=100).contains(&weight) {
523                return Err(AwsServiceError::aws_error(
524                    StatusCode::BAD_REQUEST,
525                    "ValidationException",
526                    format!("Invalid routing weight {weight}; must be 0-100."),
527                ));
528            }
529            Ok(crate::state::AliasRoute {
530                state_machine_version_arn: arn.to_string(),
531                weight: weight as i32,
532            })
533        })
534        .collect::<Result<_, _>>()?;
535    let total: i32 = parsed.iter().map(|r| r.weight).sum();
536    if total != 100 {
537        return Err(AwsServiceError::aws_error(
538            StatusCode::BAD_REQUEST,
539            "ValidationException",
540            format!("routingConfiguration weights must sum to 100, got {total}."),
541        ));
542    }
543    Ok(parsed)
544}
545
546fn validate_name(name: &str) -> Result<(), AwsServiceError> {
547    if name.is_empty() || name.len() > 80 {
548        return Err(AwsServiceError::aws_error(
549            StatusCode::BAD_REQUEST,
550            "InvalidName",
551            format!("Invalid Name: '{name}' (length must be between 1 and 80 characters)"),
552        ));
553    }
554    // Only allow alphanumeric, hyphens, and underscores
555    if !name
556        .chars()
557        .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
558    {
559        return Err(AwsServiceError::aws_error(
560            StatusCode::BAD_REQUEST,
561            "InvalidName",
562            format!(
563                "Invalid Name: '{name}' (must only contain alphanumeric characters, hyphens, and underscores)"
564            ),
565        ));
566    }
567    Ok(())
568}
569
570fn validate_definition(definition: &str) -> Result<(), AwsServiceError> {
571    let parsed: Value = serde_json::from_str(definition).map_err(|e| {
572        AwsServiceError::aws_error(
573            StatusCode::BAD_REQUEST,
574            "InvalidDefinition",
575            format!("Invalid State Machine Definition: '{e}'"),
576        )
577    })?;
578
579    if parsed.get("StartAt").and_then(|v| v.as_str()).is_none() {
580        return Err(AwsServiceError::aws_error(
581            StatusCode::BAD_REQUEST,
582            "InvalidDefinition",
583            "Invalid State Machine Definition: 'MISSING_START_AT' (StartAt field is required)"
584                .to_string(),
585        ));
586    }
587
588    let states_obj = parsed
589        .get("States")
590        .and_then(|v| v.as_object())
591        .ok_or_else(|| {
592            AwsServiceError::aws_error(
593                StatusCode::BAD_REQUEST,
594                "InvalidDefinition",
595                "Invalid State Machine Definition: 'MISSING_STATES' (States field is required)"
596                    .to_string(),
597            )
598        })?;
599
600    let start_at = parsed["StartAt"].as_str().ok_or_else(|| {
601        AwsServiceError::aws_error(
602            StatusCode::BAD_REQUEST,
603            "InvalidDefinition",
604            "Invalid State Machine Definition: 'MISSING_START_AT' (StartAt field is required)"
605                .to_string(),
606        )
607    })?;
608    if !states_obj.contains_key(start_at) {
609        return Err(AwsServiceError::aws_error(
610            StatusCode::BAD_REQUEST,
611            "InvalidDefinition",
612            format!(
613                "Invalid State Machine Definition: 'MISSING_TRANSITION_TARGET' \
614                 (StartAt '{start_at}' does not reference a valid state)"
615            ),
616        ));
617    }
618
619    // Reject malformed JSONPath reference fields. AWS rejects bad reference
620    // paths at CreateStateMachine; accepting them here lets a panic-inducing
621    // path reach the interpreter at execution time.
622    for (state_name, state_val) in states_obj {
623        validate_state_paths(state_name, state_val)?;
624    }
625
626    Ok(())
627}
628
629/// Validate the JSONPath reference fields of a single state. Recurses into the
630/// `Choices` array of Choice states, the `Branches` of Parallel states, and the
631/// `Iterator`/`ItemProcessor` of Map states. Returns an `InvalidDefinition`
632/// error for any syntactically malformed path or payload-template key.
633fn validate_state_paths(state_name: &str, state: &Value) -> Result<(), AwsServiceError> {
634    for field in ["InputPath", "OutputPath", "ResultPath"] {
635        if let Some(p) = state.get(field).and_then(|v| v.as_str()) {
636            // `InputPath`/`OutputPath` accept the literal "null" to mean "no
637            // value"; `ResultPath` accepts JSON null (handled separately) but
638            // not the string "null". Both accept "$"-rooted reference paths.
639            if (field != "ResultPath" && p == "null") || is_valid_reference_path(p) {
640                continue;
641            }
642            return Err(invalid_reference_path(state_name, field, p));
643        }
644    }
645
646    // Reference-path fields that select a value from the input (or the context
647    // object). Unlike Input/Output/ResultPath they do not accept the literal
648    // "null", but they may reference the context object via `$$`.
649    for field in [
650        "SecondsPath",
651        "TimestampPath",
652        "ItemsPath",
653        "MaxConcurrencyPath",
654        "ToleratedFailureCountPath",
655        "ToleratedFailurePercentagePath",
656    ] {
657        if let Some(p) = state.get(field).and_then(|v| v.as_str()) {
658            if is_reference_or_context_path(p) {
659                continue;
660            }
661            return Err(invalid_reference_path(state_name, field, p));
662        }
663    }
664
665    // Payload templates: every key ending in `.$` must carry a string value
666    // that is either a JSONPath reference (`$`/`$$`) or an intrinsic call. AWS
667    // rejects non-string and bare-literal `.$` values at CreateStateMachine.
668    for field in ["Parameters", "ResultSelector", "ItemSelector"] {
669        if let Some(template) = state.get(field) {
670            validate_payload_template(state_name, field, template)?;
671        }
672    }
673
674    match state.get("Type").and_then(|v| v.as_str()) {
675        Some("Choice") => {
676            if let Some(choices) = state.get("Choices").and_then(|v| v.as_array()) {
677                for rule in choices {
678                    validate_choice_variables(state_name, rule)?;
679                }
680            }
681        }
682        Some("Parallel") => {
683            if let Some(branches) = state.get("Branches").and_then(|v| v.as_array()) {
684                for branch in branches {
685                    validate_nested_definition(state_name, branch)?;
686                }
687            }
688        }
689        Some("Map") => {
690            // Distributed Map uses `ItemProcessor`; legacy inline Map uses
691            // `Iterator`. Both carry a nested `States` block.
692            for key in ["ItemProcessor", "Iterator"] {
693                if let Some(processor) = state.get(key) {
694                    validate_nested_definition(state_name, processor)?;
695                }
696            }
697        }
698        _ => {}
699    }
700
701    Ok(())
702}
703
704/// Validate every state inside a nested definition (a Parallel branch or a Map
705/// processor). Errors are attributed to the enclosing state so the message
706/// still points at a real state name.
707fn validate_nested_definition(parent: &str, def: &Value) -> Result<(), AwsServiceError> {
708    if let Some(states) = def.get("States").and_then(|v| v.as_object()) {
709        for (name, state) in states {
710            validate_state_paths(&format!("{parent}/{name}"), state)?;
711        }
712    }
713    Ok(())
714}
715
716/// Recursively validate a payload template (Parameters / ResultSelector /
717/// ItemSelector). Any object key ending in `.$` must map to a string that is a
718/// JSONPath reference or an intrinsic-function invocation.
719fn validate_payload_template(
720    state_name: &str,
721    field: &str,
722    template: &Value,
723) -> Result<(), AwsServiceError> {
724    match template {
725        Value::Object(map) => {
726            for (key, value) in map {
727                if let Some(stripped) = key.strip_suffix(".$") {
728                    let expr = value.as_str().ok_or_else(|| {
729                        invalid_payload_template(
730                            state_name,
731                            field,
732                            &format!(
733                                "the '{key}' field must be a JSONPath or intrinsic string, \
734                                 not {value}"
735                            ),
736                        )
737                    })?;
738                    let is_ref = expr.starts_with('$');
739                    if !is_ref && !crate::intrinsics::is_intrinsic_call(expr) {
740                        return Err(invalid_payload_template(
741                            state_name,
742                            field,
743                            &format!(
744                                "the '{stripped}.$' field value '{expr}' is neither a JSONPath \
745                                 reference nor an intrinsic function"
746                            ),
747                        ));
748                    }
749                } else {
750                    validate_payload_template(state_name, field, value)?;
751                }
752            }
753        }
754        Value::Array(arr) => {
755            for v in arr {
756                validate_payload_template(state_name, field, v)?;
757            }
758        }
759        _ => {}
760    }
761    Ok(())
762}
763
764/// A `*Path` field value: either a `$`-rooted reference path the interpreter can
765/// parse, or a `$$`-rooted context-object reference.
766fn is_reference_or_context_path(p: &str) -> bool {
767    if let Some(rest) = p.strip_prefix("$$") {
768        // "$$" alone, or "$$.Foo.Bar" — accept any context reference.
769        return rest.is_empty() || rest.starts_with('.') || rest.starts_with('[');
770    }
771    is_valid_reference_path(p)
772}
773
774fn invalid_payload_template(state_name: &str, field: &str, detail: &str) -> AwsServiceError {
775    AwsServiceError::aws_error(
776        StatusCode::BAD_REQUEST,
777        "InvalidDefinition",
778        format!(
779            "Invalid State Machine Definition: 'SCHEMA_VALIDATION_FAILED' \
780             (The {field} of state '{state_name}' is invalid: {detail})"
781        ),
782    )
783}
784
785/// Validate `Variable` reference paths inside a Choice rule, recursing through
786/// nested `And` / `Or` / `Not` boolean combinators.
787fn validate_choice_variables(state_name: &str, rule: &Value) -> Result<(), AwsServiceError> {
788    if let Some(v) = rule.get("Variable").and_then(|v| v.as_str()) {
789        if !is_valid_reference_path(v) {
790            return Err(invalid_reference_path(state_name, "Variable", v));
791        }
792    }
793    for combinator in ["And", "Or"] {
794        if let Some(nested) = rule.get(combinator).and_then(|v| v.as_array()) {
795            for n in nested {
796                validate_choice_variables(state_name, n)?;
797            }
798        }
799    }
800    if let Some(n) = rule.get("Not") {
801        validate_choice_variables(state_name, n)?;
802    }
803    Ok(())
804}
805
806/// A reference path must start with `$` and every `[...]` index segment must be
807/// a balanced, non-empty, decimal-integer index. This mirrors the subset of
808/// JSONPath the interpreter understands; anything it cannot parse is rejected.
809fn is_valid_reference_path(path: &str) -> bool {
810    if path != "$" && !path.starts_with("$.") && !path.starts_with("$[") {
811        return false;
812    }
813    let body = path
814        .strip_prefix("$.")
815        .or_else(|| path.strip_prefix('$'))
816        .unwrap_or(path);
817    for part in body.split('.') {
818        if !segment_is_valid(part) {
819            return false;
820        }
821    }
822    true
823}
824
825fn segment_is_valid(part: &str) -> bool {
826    match part.find('[') {
827        None => !part.contains(']'),
828        Some(open) => {
829            if !part.ends_with(']') {
830                return false;
831            }
832            let inner = &part[open + 1..part.len() - 1];
833            // Empty `[]` or non-integer (incl. multibyte/garbage) indices are invalid.
834            !inner.is_empty() && inner.parse::<usize>().is_ok()
835        }
836    }
837}
838
839fn invalid_reference_path(state_name: &str, field: &str, path: &str) -> AwsServiceError {
840    AwsServiceError::aws_error(
841        StatusCode::BAD_REQUEST,
842        "InvalidDefinition",
843        format!(
844            "Invalid State Machine Definition: 'SCHEMA_VALIDATION_FAILED' \
845             (The {field} field of state '{state_name}' is not a valid reference path: '{path}')"
846        ),
847    )
848}
849
850fn execution_not_found(arn: &str) -> AwsServiceError {
851    AwsServiceError::aws_error(
852        StatusCode::BAD_REQUEST,
853        "ExecutionDoesNotExist",
854        format!("Execution Does Not Exist: '{arn}'"),
855    )
856}
857
858fn execution_to_json(exec: &Execution) -> Value {
859    let mut resp = json!({
860        "executionArn": exec.execution_arn,
861        "stateMachineArn": exec.state_machine_arn,
862        "name": exec.name,
863        "status": exec.status.as_str(),
864        "startDate": exec.start_date.timestamp() as f64,
865    });
866
867    if let Some(ref input) = exec.input {
868        resp["input"] = json!(input);
869    }
870    if let Some(ref output) = exec.output {
871        resp["output"] = json!(output);
872    }
873    if let Some(stop) = exec.stop_date {
874        resp["stopDate"] = json!(stop.timestamp() as f64);
875    }
876    if let Some(ref error) = exec.error {
877        resp["error"] = json!(error);
878    }
879    if let Some(ref cause) = exec.cause {
880        resp["cause"] = json!(cause);
881    }
882
883    resp
884}
885
886/// Convert an event type to the JSON key prefix used in the `HistoryEvent`
887/// shape (the full key is `<prefix>EventDetails`).
888///
889/// AWS collapses every `*StateEntered` event type (Pass/Task/Choice/Wait/Map/
890/// Parallel/Succeed/...) into a single `stateEnteredEventDetails` member, and
891/// every `*StateExited` into `stateExitedEventDetails`. All other event types
892/// map by lowercasing the first character (`TaskScheduled` ->
893/// `taskScheduledEventDetails`). Without the collapse, SDK deserializers see an
894/// unknown key like `passStateEnteredEventDetails` and return null name/input.
895fn camel_to_details_key(event_type: &str) -> String {
896    if event_type.ends_with("StateEntered") {
897        return "stateEntered".to_string();
898    }
899    if event_type.ends_with("StateExited") {
900        return "stateExited".to_string();
901    }
902    let mut chars = event_type.chars();
903    match chars.next() {
904        None => String::new(),
905        Some(c) => c.to_lowercase().to_string() + chars.as_str(),
906    }
907}
908
909/// Compare two StartExecution inputs for STANDARD idempotency. A missing input
910/// defaults to `{}` (AWS's default execution input). Comparison is structural
911/// (parsed JSON), so insignificant whitespace differences still dedup; inputs
912/// that fail to parse fall back to an exact string match.
913fn execution_input_matches(stored: Option<&str>, incoming: Option<&str>) -> bool {
914    let stored = stored.unwrap_or("{}");
915    let incoming = incoming.unwrap_or("{}");
916    match (
917        serde_json::from_str::<Value>(stored),
918        serde_json::from_str::<Value>(incoming),
919    ) {
920        (Ok(a), Ok(b)) => a == b,
921        _ => stored == incoming,
922    }
923}
924
925fn validate_arn(arn: &str) -> Result<(), AwsServiceError> {
926    if !arn.starts_with("arn:") {
927        return Err(AwsServiceError::aws_error(
928            StatusCode::BAD_REQUEST,
929            "InvalidArn",
930            format!("Invalid Arn: '{arn}'"),
931        ));
932    }
933    Ok(())
934}
935
936/// Enforce the Smithy @length on an ARN-typed field (`Arn` = 1..=256,
937/// `LongArn` = 1..=2000). Empty / oversize ARNs map to `InvalidArn`, which
938/// every ARN-bearing Step Functions operation declares.
939fn validate_arn_length(field: &str, value: &str, max: usize) -> Result<(), AwsServiceError> {
940    if value.is_empty() || value.len() > max {
941        return Err(AwsServiceError::aws_error(
942            StatusCode::BAD_REQUEST,
943            "InvalidArn",
944            format!("Invalid Arn at '{field}': must be 1..={max} characters"),
945        ));
946    }
947    Ok(())
948}
949
950/// Shared error for a malformed (unparseable) `nextToken` reaching the
951/// pagination helper — `InvalidToken` is the only pagination error code
952/// declared on every list op.
953pub(super) fn invalid_token() -> AwsServiceError {
954    AwsServiceError::aws_error(StatusCode::BAD_REQUEST, "InvalidToken", "Invalid nextToken")
955}
956
957/// `nextToken` is declared as `PageToken` (length 1..=1024). The only
958/// error code declared on every paginated list op is `InvalidToken`, so
959/// route both empty and oversize tokens through it.
960fn validate_page_token(value: &str) -> Result<(), AwsServiceError> {
961    if value.is_empty() || value.len() > 1024 {
962        return Err(AwsServiceError::aws_error(
963            StatusCode::BAD_REQUEST,
964            "InvalidToken",
965            "nextToken must be 1..=1024 characters",
966        ));
967    }
968    Ok(())
969}
970
971/// `maxResults` is typed as `PageSize` (range 0..=1000). The negative
972/// probes flip below-min / above-max; since the only error declared on
973/// `ListActivities` is `InvalidToken`, we map page-size violations to
974/// the same code (matches how AWS surfaces malformed pagination input
975/// for ops that don't model a separate `ValidationException`).
976fn validate_max_results(value: i64) -> Result<(), AwsServiceError> {
977    if !(0..=1000).contains(&value) {
978        return Err(AwsServiceError::aws_error(
979            StatusCode::BAD_REQUEST,
980            "InvalidToken",
981            format!("maxResults '{value}' is outside 0..=1000"),
982        ));
983    }
984    Ok(())
985}
986
987/// Start a Step Functions execution from a cross-service delivery (e.g. EventBridge).
988///
989/// This is the public entry point used by `StepFunctionsDeliveryImpl` in the server crate.
990/// It mirrors the logic from `StartExecution` but without the AWS request/response wrapper.
991/// Start a Step Functions execution from a cross-service delivery (e.g. EventBridge).
992///
993/// This is the public entry point used by `StepFunctionsDeliveryImpl` in the server crate.
994/// It mirrors the logic from `StartExecution` but without the AWS request/response wrapper.
995pub fn start_execution_from_delivery(
996    state: &SharedStepFunctionsState,
997    delivery: &Option<Arc<DeliveryBus>>,
998    dynamodb_state: &Option<SharedDynamoDbState>,
999    registry: &Option<SharedServiceRegistry>,
1000    state_machine_arn: &str,
1001    input: &str,
1002) {
1003    // Validate input is valid JSON
1004    if serde_json::from_str::<serde_json::Value>(input).is_err() {
1005        tracing::warn!(
1006            state_machine_arn,
1007            "Step Functions delivery: invalid JSON input, skipping execution"
1008        );
1009        return;
1010    }
1011
1012    let execution_name = uuid::Uuid::new_v4().to_string();
1013
1014    // Extract account_id from the state machine ARN
1015    let account_id = state_machine_arn
1016        .split(':')
1017        .nth(4)
1018        .unwrap_or("000000000000")
1019        .to_string();
1020
1021    let mut accounts = state.write();
1022    let st = accounts.get_or_create(&account_id);
1023    let sm = match st.state_machines.get(state_machine_arn) {
1024        Some(sm) => sm,
1025        None => {
1026            tracing::warn!(
1027                state_machine_arn,
1028                "Step Functions delivery: state machine not found"
1029            );
1030            return;
1031        }
1032    };
1033
1034    let sm_name = sm.name.clone();
1035    let definition = sm.definition.clone();
1036    let exec_arn = st.execution_arn(&sm_name, &execution_name);
1037
1038    let now = Utc::now();
1039    let execution = Execution {
1040        execution_arn: exec_arn.clone(),
1041        state_machine_arn: state_machine_arn.to_string(),
1042        state_machine_name: sm_name,
1043        name: execution_name,
1044        status: ExecutionStatus::Running,
1045        input: Some(input.to_string()),
1046        output: None,
1047        start_date: now,
1048        stop_date: None,
1049        error: None,
1050        cause: None,
1051        history_events: vec![],
1052        parent_execution_arn: None,
1053        is_sync: false,
1054        billed_duration_ms: None,
1055        billed_memory_mb: None,
1056    };
1057
1058    st.executions.insert(exec_arn.clone(), execution);
1059    let logging_config = sm.logging_configuration.clone();
1060    drop(accounts);
1061
1062    let shared_state = state.clone();
1063    let delivery = delivery.clone();
1064    let dynamodb_state = dynamodb_state.clone();
1065    let registry = registry.clone();
1066    let input = Some(input.to_string());
1067    tokio::spawn(async move {
1068        interpreter::execute_state_machine(
1069            shared_state,
1070            exec_arn,
1071            definition,
1072            input,
1073            delivery,
1074            dynamodb_state,
1075            registry,
1076            logging_config,
1077        )
1078        .await;
1079    });
1080}
1081
1082#[cfg(test)]
1083mod tests {
1084    use super::*;
1085    use http::{HeaderMap, Method};
1086    use parking_lot::RwLock;
1087    use serde_json::Value;
1088    use std::collections::HashMap;
1089    use std::sync::Arc;
1090
1091    fn make_state() -> SharedStepFunctionsState {
1092        Arc::new(RwLock::new(
1093            fakecloud_core::multi_account::MultiAccountState::new("123456789012", "us-east-1", ""),
1094        ))
1095    }
1096
1097    fn make_request(action: &str, body: &str) -> AwsRequest {
1098        AwsRequest {
1099            service: "states".to_string(),
1100            action: action.to_string(),
1101            region: "us-east-1".to_string(),
1102            account_id: "123456789012".to_string(),
1103            request_id: "test-id".to_string(),
1104            headers: HeaderMap::new(),
1105            query_params: HashMap::new(),
1106            body: body.as_bytes().to_vec().into(),
1107            body_stream: parking_lot::Mutex::new(None),
1108            path_segments: vec![],
1109            raw_path: "/".to_string(),
1110            raw_query: String::new(),
1111            method: Method::POST,
1112            is_query_protocol: false,
1113            access_key_id: None,
1114            principal: None,
1115        }
1116    }
1117
1118    fn body_json(resp: &AwsResponse) -> Value {
1119        serde_json::from_slice(resp.body.expect_bytes()).unwrap()
1120    }
1121
1122    fn expect_err(result: Result<AwsResponse, AwsServiceError>) -> AwsServiceError {
1123        match result {
1124            Err(e) => e,
1125            Ok(_) => panic!("expected error, got Ok"),
1126        }
1127    }
1128
1129    const VALID_DEF: &str = r#"{"StartAt":"Pass","States":{"Pass":{"Type":"Pass","End":true}}}"#;
1130
1131    fn create_sm(svc: &StepFunctionsService, name: &str) -> String {
1132        let body = json!({
1133            "name": name,
1134            "definition": VALID_DEF,
1135            "roleArn": "arn:aws:iam::123456789012:role/test",
1136        });
1137        let req = make_request("CreateStateMachine", &body.to_string());
1138        let resp = svc.create_state_machine(&req).unwrap();
1139        let b = body_json(&resp);
1140        b["stateMachineArn"].as_str().unwrap().to_string()
1141    }
1142
1143    // ── CreateStateMachine ──
1144
1145    #[test]
1146    fn create_state_machine_basic() {
1147        let svc = StepFunctionsService::new(make_state());
1148        let arn = create_sm(&svc, "test-sm");
1149        assert!(arn.contains("test-sm"));
1150    }
1151
1152    // bug-hunt 2026-07-19: CreateStateMachine with publish=true creates a real
1153    // version that ListStateMachineVersions returns; without publish, no version
1154    // ARN is returned and no version exists.
1155    #[test]
1156    fn create_state_machine_publish_creates_listable_version() {
1157        let svc = StepFunctionsService::new(make_state());
1158        let body = json!({
1159            "name": "pub-sm",
1160            "definition": VALID_DEF,
1161            "roleArn": "arn:aws:iam::123456789012:role/r",
1162            "publish": true,
1163            "versionDescription": "first",
1164        });
1165        let req = make_request("CreateStateMachine", &body.to_string());
1166        let resp = svc.create_state_machine(&req).unwrap();
1167        let b = body_json(&resp);
1168        let arn = b["stateMachineArn"].as_str().unwrap().to_string();
1169        let version_arn = b["stateMachineVersionArn"].as_str().unwrap().to_string();
1170        assert_eq!(version_arn, format!("{arn}:1"));
1171
1172        let list_req = make_request(
1173            "ListStateMachineVersions",
1174            &json!({ "stateMachineArn": arn }).to_string(),
1175        );
1176        let list = body_json(&svc.list_state_machine_versions(&list_req).unwrap());
1177        let versions = list["stateMachineVersions"].as_array().unwrap();
1178        assert_eq!(versions.len(), 1);
1179        assert_eq!(versions[0]["stateMachineVersionArn"], version_arn);
1180    }
1181
1182    #[test]
1183    fn create_state_machine_no_publish_has_no_version() {
1184        let svc = StepFunctionsService::new(make_state());
1185        let arn = create_sm(&svc, "nopub-sm");
1186        // No version ARN is returned when publish is absent.
1187        let body = json!({
1188            "name": "nopub-sm2",
1189            "definition": VALID_DEF,
1190            "roleArn": "arn:aws:iam::123456789012:role/r",
1191        });
1192        let req = make_request("CreateStateMachine", &body.to_string());
1193        let b = body_json(&svc.create_state_machine(&req).unwrap());
1194        assert!(b.get("stateMachineVersionArn").is_none());
1195
1196        let list_req = make_request(
1197            "ListStateMachineVersions",
1198            &json!({ "stateMachineArn": arn }).to_string(),
1199        );
1200        let list = body_json(&svc.list_state_machine_versions(&list_req).unwrap());
1201        assert!(list["stateMachineVersions"].as_array().unwrap().is_empty());
1202    }
1203
1204    // bug-hunt 2026-07-19: UpdateStateMachine with publish=true publishes the
1205    // next version, and encryptionConfiguration persists + round-trips on
1206    // Describe.
1207    #[test]
1208    fn update_state_machine_publish_and_encryption_round_trip() {
1209        let svc = StepFunctionsService::new(make_state());
1210        let create = json!({
1211            "name": "enc-sm",
1212            "definition": VALID_DEF,
1213            "roleArn": "arn:aws:iam::123456789012:role/r",
1214            "encryptionConfiguration": { "type": "CUSTOMER_MANAGED_KMS_KEY", "kmsKeyId": "key-123" },
1215        });
1216        let req = make_request("CreateStateMachine", &create.to_string());
1217        let arn = body_json(&svc.create_state_machine(&req).unwrap())["stateMachineArn"]
1218            .as_str()
1219            .unwrap()
1220            .to_string();
1221
1222        // encryptionConfiguration round-trips on Describe.
1223        let desc_req = make_request(
1224            "DescribeStateMachine",
1225            &json!({ "stateMachineArn": arn }).to_string(),
1226        );
1227        let desc = body_json(&svc.describe_state_machine(&desc_req).unwrap());
1228        assert_eq!(
1229            desc["encryptionConfiguration"]["type"],
1230            "CUSTOMER_MANAGED_KMS_KEY"
1231        );
1232        assert_eq!(desc["encryptionConfiguration"]["kmsKeyId"], "key-123");
1233
1234        // Update with publish creates version 1.
1235        let upd = json!({
1236            "stateMachineArn": arn,
1237            "definition": VALID_DEF,
1238            "publish": true,
1239            "versionDescription": "v via update",
1240        });
1241        let upd_req = make_request("UpdateStateMachine", &upd.to_string());
1242        let upd_body = body_json(&svc.update_state_machine(&upd_req).unwrap());
1243        assert_eq!(
1244            upd_body["stateMachineVersionArn"].as_str().unwrap(),
1245            format!("{arn}:1")
1246        );
1247
1248        let list_req = make_request(
1249            "ListStateMachineVersions",
1250            &json!({ "stateMachineArn": arn }).to_string(),
1251        );
1252        let list = body_json(&svc.list_state_machine_versions(&list_req).unwrap());
1253        assert_eq!(list["stateMachineVersions"].as_array().unwrap().len(), 1);
1254    }
1255
1256    #[test]
1257    fn create_state_machine_with_express_type() {
1258        let svc = StepFunctionsService::new(make_state());
1259        let body = json!({
1260            "name": "express-sm",
1261            "definition": VALID_DEF,
1262            "roleArn": "arn:aws:iam::123456789012:role/r",
1263            "type": "EXPRESS",
1264        });
1265        let req = make_request("CreateStateMachine", &body.to_string());
1266        let resp = svc.create_state_machine(&req).unwrap();
1267        let b = body_json(&resp);
1268        assert!(b["stateMachineArn"].as_str().is_some());
1269    }
1270
1271    #[test]
1272    fn create_state_machine_duplicate_fails() {
1273        let svc = StepFunctionsService::new(make_state());
1274        create_sm(&svc, "dup-sm");
1275        let body = json!({
1276            "name": "dup-sm",
1277            "definition": VALID_DEF,
1278            "roleArn": "arn:aws:iam::123456789012:role/r",
1279        });
1280        let req = make_request("CreateStateMachine", &body.to_string());
1281        let err = expect_err(svc.create_state_machine(&req));
1282        assert!(err.to_string().contains("StateMachineAlreadyExists"));
1283    }
1284
1285    #[test]
1286    fn create_state_machine_missing_name() {
1287        let svc = StepFunctionsService::new(make_state());
1288        let body = json!({
1289            "definition": VALID_DEF,
1290            "roleArn": "arn:aws:iam::123456789012:role/r",
1291        });
1292        let req = make_request("CreateStateMachine", &body.to_string());
1293        assert!(svc.create_state_machine(&req).is_err());
1294    }
1295
1296    #[test]
1297    fn create_state_machine_invalid_definition() {
1298        let svc = StepFunctionsService::new(make_state());
1299        let body = json!({
1300            "name": "bad-def",
1301            "definition": "not json",
1302            "roleArn": "arn:aws:iam::123456789012:role/r",
1303        });
1304        let req = make_request("CreateStateMachine", &body.to_string());
1305        let err = expect_err(svc.create_state_machine(&req));
1306        assert!(err.to_string().contains("InvalidDefinition"));
1307    }
1308
1309    #[test]
1310    fn create_state_machine_definition_missing_start_at() {
1311        let svc = StepFunctionsService::new(make_state());
1312        let body = json!({
1313            "name": "no-start",
1314            "definition": r#"{"States":{"S":{"Type":"Pass","End":true}}}"#,
1315            "roleArn": "arn:aws:iam::123456789012:role/r",
1316        });
1317        let req = make_request("CreateStateMachine", &body.to_string());
1318        let err = expect_err(svc.create_state_machine(&req));
1319        assert!(err.to_string().contains("InvalidDefinition"));
1320    }
1321
1322    #[test]
1323    fn create_state_machine_definition_missing_states() {
1324        let svc = StepFunctionsService::new(make_state());
1325        let body = json!({
1326            "name": "no-states",
1327            "definition": r#"{"StartAt":"S"}"#,
1328            "roleArn": "arn:aws:iam::123456789012:role/r",
1329        });
1330        let req = make_request("CreateStateMachine", &body.to_string());
1331        let err = expect_err(svc.create_state_machine(&req));
1332        assert!(err.to_string().contains("InvalidDefinition"));
1333    }
1334
1335    #[test]
1336    fn create_state_machine_definition_start_at_not_in_states() {
1337        let svc = StepFunctionsService::new(make_state());
1338        let body = json!({
1339            "name": "bad-start",
1340            "definition": r#"{"StartAt":"Missing","States":{"S":{"Type":"Pass","End":true}}}"#,
1341            "roleArn": "arn:aws:iam::123456789012:role/r",
1342        });
1343        let req = make_request("CreateStateMachine", &body.to_string());
1344        let err = expect_err(svc.create_state_machine(&req));
1345        assert!(err.to_string().contains("MISSING_TRANSITION_TARGET"));
1346    }
1347
1348    #[test]
1349    fn create_state_machine_invalid_type() {
1350        let svc = StepFunctionsService::new(make_state());
1351        let body = json!({
1352            "name": "bad-type",
1353            "definition": VALID_DEF,
1354            "roleArn": "arn:aws:iam::123456789012:role/r",
1355            "type": "INVALID",
1356        });
1357        let req = make_request("CreateStateMachine", &body.to_string());
1358        assert!(svc.create_state_machine(&req).is_err());
1359    }
1360
1361    #[test]
1362    fn create_state_machine_invalid_arn() {
1363        let svc = StepFunctionsService::new(make_state());
1364        let body = json!({
1365            "name": "bad-arn",
1366            "definition": VALID_DEF,
1367            "roleArn": "not-an-arn",
1368        });
1369        let req = make_request("CreateStateMachine", &body.to_string());
1370        let err = expect_err(svc.create_state_machine(&req));
1371        assert!(err.to_string().contains("InvalidArn"));
1372    }
1373
1374    #[test]
1375    fn create_state_machine_invalid_name() {
1376        let svc = StepFunctionsService::new(make_state());
1377        let body = json!({
1378            "name": "has spaces!",
1379            "definition": VALID_DEF,
1380            "roleArn": "arn:aws:iam::123456789012:role/r",
1381        });
1382        let req = make_request("CreateStateMachine", &body.to_string());
1383        let err = expect_err(svc.create_state_machine(&req));
1384        assert!(err.to_string().contains("InvalidName"));
1385    }
1386
1387    #[test]
1388    fn create_state_machine_name_too_long() {
1389        let svc = StepFunctionsService::new(make_state());
1390        let long_name = "a".repeat(81);
1391        let body = json!({
1392            "name": long_name,
1393            "definition": VALID_DEF,
1394            "roleArn": "arn:aws:iam::123456789012:role/r",
1395        });
1396        let req = make_request("CreateStateMachine", &body.to_string());
1397        let err = expect_err(svc.create_state_machine(&req));
1398        assert!(err.to_string().contains("InvalidName"));
1399    }
1400
1401    // ── DescribeStateMachine ──
1402
1403    #[test]
1404    fn describe_state_machine_found() {
1405        let svc = StepFunctionsService::new(make_state());
1406        let arn = create_sm(&svc, "desc-sm");
1407
1408        let req = make_request(
1409            "DescribeStateMachine",
1410            &json!({"stateMachineArn": arn}).to_string(),
1411        );
1412        let resp = svc.describe_state_machine(&req).unwrap();
1413        let b = body_json(&resp);
1414        assert_eq!(b["name"], "desc-sm");
1415        assert_eq!(b["status"], "ACTIVE");
1416        assert!(b["definition"].as_str().is_some());
1417    }
1418
1419    #[test]
1420    fn describe_state_machine_not_found() {
1421        let svc = StepFunctionsService::new(make_state());
1422        let req = make_request(
1423            "DescribeStateMachine",
1424            &json!({"stateMachineArn": "arn:aws:states:us-east-1:123456789012:stateMachine:nope"})
1425                .to_string(),
1426        );
1427        let err = expect_err(svc.describe_state_machine(&req));
1428        assert!(err.to_string().contains("StateMachineDoesNotExist"));
1429    }
1430
1431    // ── ListStateMachines ──
1432
1433    #[test]
1434    fn list_state_machines_empty() {
1435        let svc = StepFunctionsService::new(make_state());
1436        let req = make_request("ListStateMachines", "{}");
1437        let resp = svc.list_state_machines(&req).unwrap();
1438        let b = body_json(&resp);
1439        assert!(b["stateMachines"].as_array().unwrap().is_empty());
1440    }
1441
1442    #[test]
1443    fn list_state_machines_returns_created() {
1444        let svc = StepFunctionsService::new(make_state());
1445        create_sm(&svc, "sm-1");
1446        create_sm(&svc, "sm-2");
1447
1448        let req = make_request("ListStateMachines", "{}");
1449        let resp = svc.list_state_machines(&req).unwrap();
1450        let b = body_json(&resp);
1451        assert_eq!(b["stateMachines"].as_array().unwrap().len(), 2);
1452    }
1453
1454    // ── DeleteStateMachine ──
1455
1456    #[test]
1457    fn delete_state_machine() {
1458        let svc = StepFunctionsService::new(make_state());
1459        let arn = create_sm(&svc, "del-sm");
1460
1461        let req = make_request(
1462            "DeleteStateMachine",
1463            &json!({"stateMachineArn": arn}).to_string(),
1464        );
1465        svc.delete_state_machine(&req).unwrap();
1466
1467        // Describe should fail
1468        let req = make_request(
1469            "DescribeStateMachine",
1470            &json!({"stateMachineArn": arn}).to_string(),
1471        );
1472        assert!(svc.describe_state_machine(&req).is_err());
1473    }
1474
1475    #[test]
1476    fn delete_state_machine_nonexistent_succeeds() {
1477        let svc = StepFunctionsService::new(make_state());
1478        let req = make_request(
1479            "DeleteStateMachine",
1480            &json!({"stateMachineArn": "arn:aws:states:us-east-1:123456789012:stateMachine:nope"})
1481                .to_string(),
1482        );
1483        // AWS returns success even for nonexistent
1484        svc.delete_state_machine(&req).unwrap();
1485    }
1486
1487    // ── UpdateStateMachine ──
1488
1489    #[test]
1490    fn update_state_machine() {
1491        let svc = StepFunctionsService::new(make_state());
1492        let arn = create_sm(&svc, "upd-sm");
1493
1494        let new_def = r#"{"StartAt":"NewPass","States":{"NewPass":{"Type":"Pass","End":true}}}"#;
1495        let body = json!({
1496            "stateMachineArn": arn,
1497            "definition": new_def,
1498            "description": "updated",
1499        });
1500        let req = make_request("UpdateStateMachine", &body.to_string());
1501        let resp = svc.update_state_machine(&req).unwrap();
1502        let b = body_json(&resp);
1503        assert!(b["updateDate"].as_f64().is_some());
1504
1505        // Verify
1506        let req = make_request(
1507            "DescribeStateMachine",
1508            &json!({"stateMachineArn": arn}).to_string(),
1509        );
1510        let resp = svc.describe_state_machine(&req).unwrap();
1511        let b = body_json(&resp);
1512        assert!(b["definition"].as_str().unwrap().contains("NewPass"));
1513        assert_eq!(b["description"], "updated");
1514    }
1515
1516    #[test]
1517    fn update_state_machine_not_found() {
1518        let svc = StepFunctionsService::new(make_state());
1519        let body = json!({
1520            "stateMachineArn": "arn:aws:states:us-east-1:123456789012:stateMachine:nope",
1521            "definition": VALID_DEF,
1522        });
1523        let req = make_request("UpdateStateMachine", &body.to_string());
1524        let err = expect_err(svc.update_state_machine(&req));
1525        assert!(err.to_string().contains("StateMachineDoesNotExist"));
1526    }
1527
1528    // ── StartExecution ──
1529
1530    #[tokio::test]
1531    async fn start_execution_basic() {
1532        let svc = StepFunctionsService::new(make_state());
1533        let arn = create_sm(&svc, "exec-sm");
1534
1535        let body = json!({
1536            "stateMachineArn": arn,
1537            "input": r#"{"key":"value"}"#,
1538        });
1539        let req = make_request("StartExecution", &body.to_string());
1540        let resp = svc.start_execution(&req).unwrap();
1541        let b = body_json(&resp);
1542        assert!(b["executionArn"].as_str().is_some());
1543        assert!(b["startDate"].as_f64().is_some());
1544    }
1545
1546    #[tokio::test]
1547    async fn start_execution_with_name() {
1548        let svc = StepFunctionsService::new(make_state());
1549        let arn = create_sm(&svc, "named-exec");
1550
1551        let body = json!({
1552            "stateMachineArn": arn,
1553            "name": "my-execution",
1554        });
1555        let req = make_request("StartExecution", &body.to_string());
1556        let resp = svc.start_execution(&req).unwrap();
1557        let b = body_json(&resp);
1558        assert!(b["executionArn"].as_str().unwrap().contains("my-execution"));
1559    }
1560
1561    #[tokio::test]
1562    async fn start_execution_sm_not_found() {
1563        let svc = StepFunctionsService::new(make_state());
1564        let body = json!({
1565            "stateMachineArn": "arn:aws:states:us-east-1:123456789012:stateMachine:nope",
1566        });
1567        let req = make_request("StartExecution", &body.to_string());
1568        let err = expect_err(svc.start_execution(&req));
1569        assert!(err.to_string().contains("StateMachineDoesNotExist"));
1570    }
1571
1572    #[tokio::test]
1573    async fn start_execution_invalid_input() {
1574        let svc = StepFunctionsService::new(make_state());
1575        let arn = create_sm(&svc, "bad-input");
1576
1577        let body = json!({
1578            "stateMachineArn": arn,
1579            "input": "not json",
1580        });
1581        let req = make_request("StartExecution", &body.to_string());
1582        let err = expect_err(svc.start_execution(&req));
1583        assert!(err.to_string().contains("InvalidExecutionInput"));
1584    }
1585
1586    #[tokio::test]
1587    async fn start_execution_same_name_same_input_is_idempotent() {
1588        let svc = StepFunctionsService::new(make_state());
1589        let arn = create_sm(&svc, "dup-exec");
1590
1591        let body = json!({
1592            "stateMachineArn": arn,
1593            "name": "same-name",
1594            "input": "{\"a\":1}",
1595        });
1596        let req = make_request("StartExecution", &body.to_string());
1597        let first = body_json(&svc.start_execution(&req).unwrap());
1598
1599        // Same name AND same input -> 200 with the existing executionArn.
1600        let req = make_request("StartExecution", &body.to_string());
1601        let second = body_json(&svc.start_execution(&req).unwrap());
1602        assert_eq!(first["executionArn"], second["executionArn"]);
1603        assert_eq!(first["startDate"], second["startDate"]);
1604    }
1605
1606    #[tokio::test]
1607    async fn start_execution_same_name_different_input_conflicts() {
1608        let svc = StepFunctionsService::new(make_state());
1609        let arn = create_sm(&svc, "dup-exec-diff");
1610
1611        let req = make_request(
1612            "StartExecution",
1613            &json!({
1614                "stateMachineArn": arn,
1615                "name": "same-name",
1616                "input": "{\"a\":1}",
1617            })
1618            .to_string(),
1619        );
1620        svc.start_execution(&req).unwrap();
1621
1622        // Same name, DIFFERENT input -> 400 ExecutionAlreadyExists.
1623        let req = make_request(
1624            "StartExecution",
1625            &json!({
1626                "stateMachineArn": arn,
1627                "name": "same-name",
1628                "input": "{\"a\":2}",
1629            })
1630            .to_string(),
1631        );
1632        let err = expect_err(svc.start_execution(&req));
1633        assert!(err.to_string().contains("ExecutionAlreadyExists"));
1634    }
1635
1636    #[tokio::test]
1637    async fn start_execution_express_name_collision_never_idempotent() {
1638        let svc = StepFunctionsService::new(make_state());
1639        let arn = create_express_sm(&svc, "dup-exec-express");
1640
1641        let body = json!({
1642            "stateMachineArn": arn,
1643            "name": "same-name",
1644            "input": "{\"a\":1}",
1645        });
1646        let req = make_request("StartExecution", &body.to_string());
1647        svc.start_execution(&req).unwrap();
1648
1649        // EXPRESS has no idempotency: even an identical re-issue conflicts.
1650        let req = make_request("StartExecution", &body.to_string());
1651        let err = expect_err(svc.start_execution(&req));
1652        assert!(err.to_string().contains("ExecutionAlreadyExists"));
1653    }
1654
1655    // ── DescribeExecution ──
1656
1657    #[tokio::test]
1658    async fn describe_execution_found() {
1659        let svc = StepFunctionsService::new(make_state());
1660        let sm_arn = create_sm(&svc, "desc-exec");
1661
1662        let body = json!({"stateMachineArn": sm_arn, "name": "e1"});
1663        let req = make_request("StartExecution", &body.to_string());
1664        let resp = svc.start_execution(&req).unwrap();
1665        let exec_arn = body_json(&resp)["executionArn"]
1666            .as_str()
1667            .unwrap()
1668            .to_string();
1669
1670        let req = make_request(
1671            "DescribeExecution",
1672            &json!({"executionArn": exec_arn}).to_string(),
1673        );
1674        let resp = svc.describe_execution(&req).unwrap();
1675        let b = body_json(&resp);
1676        assert_eq!(b["name"], "e1");
1677        assert_eq!(b["status"], "RUNNING");
1678    }
1679
1680    #[tokio::test]
1681    async fn describe_execution_not_found() {
1682        let svc = StepFunctionsService::new(make_state());
1683        let req = make_request(
1684            "DescribeExecution",
1685            &json!({"executionArn": "arn:aws:states:us-east-1:123456789012:execution:sm:nope"})
1686                .to_string(),
1687        );
1688        let err = expect_err(svc.describe_execution(&req));
1689        assert!(err.to_string().contains("ExecutionDoesNotExist"));
1690    }
1691
1692    // ── StopExecution ──
1693
1694    #[tokio::test]
1695    async fn stop_execution() {
1696        let svc = StepFunctionsService::new(make_state());
1697        let sm_arn = create_sm(&svc, "stop-sm");
1698
1699        let body = json!({"stateMachineArn": sm_arn, "name": "stop-e"});
1700        let req = make_request("StartExecution", &body.to_string());
1701        let resp = svc.start_execution(&req).unwrap();
1702        let exec_arn = body_json(&resp)["executionArn"]
1703            .as_str()
1704            .unwrap()
1705            .to_string();
1706
1707        let body = json!({
1708            "executionArn": exec_arn,
1709            "error": "UserAborted",
1710            "cause": "test stop",
1711        });
1712        let req = make_request("StopExecution", &body.to_string());
1713        let resp = svc.stop_execution(&req).unwrap();
1714        let b = body_json(&resp);
1715        assert!(b["stopDate"].as_f64().is_some());
1716
1717        // Verify aborted
1718        let req = make_request(
1719            "DescribeExecution",
1720            &json!({"executionArn": exec_arn}).to_string(),
1721        );
1722        let resp = svc.describe_execution(&req).unwrap();
1723        let b = body_json(&resp);
1724        assert_eq!(b["status"], "ABORTED");
1725        assert_eq!(b["error"], "UserAborted");
1726    }
1727
1728    #[tokio::test]
1729    async fn redrive_execution_reruns_to_terminal() {
1730        let svc = StepFunctionsService::new(make_state());
1731        let sm_arn = create_sm(&svc, "redrive-sm");
1732
1733        let body = json!({"stateMachineArn": sm_arn, "name": "redrive-e"});
1734        let req = make_request("StartExecution", &body.to_string());
1735        let resp = svc.start_execution(&req).unwrap();
1736        let exec_arn = body_json(&resp)["executionArn"]
1737            .as_str()
1738            .unwrap()
1739            .to_string();
1740
1741        // Stop before the spawned interpreter runs -> terminal ABORTED.
1742        let req = make_request(
1743            "StopExecution",
1744            &json!({"executionArn": exec_arn, "error": "UserAborted", "cause": "stop"}).to_string(),
1745        );
1746        svc.stop_execution(&req).unwrap();
1747
1748        // Redrive: must reset to RUNNING and re-spawn the interpreter.
1749        let req = make_request(
1750            "RedriveExecution",
1751            &json!({"executionArn": exec_arn}).to_string(),
1752        );
1753        let resp = svc.redrive_execution(&req).unwrap();
1754        assert!(body_json(&resp)["redriveDate"].as_i64().is_some());
1755
1756        // The redriven Pass-state execution must reach a terminal state
1757        // (SUCCEEDED) instead of hanging RUNNING forever.
1758        let mut status = String::new();
1759        for _ in 0..100 {
1760            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
1761            let req = make_request(
1762                "DescribeExecution",
1763                &json!({"executionArn": exec_arn}).to_string(),
1764            );
1765            let b = body_json(&svc.describe_execution(&req).unwrap());
1766            status = b["status"].as_str().unwrap().to_string();
1767            if status != "RUNNING" {
1768                break;
1769            }
1770        }
1771        assert_eq!(
1772            status, "SUCCEEDED",
1773            "redriven execution must run to completion"
1774        );
1775    }
1776
1777    #[tokio::test]
1778    async fn redrive_execution_running_rejected() {
1779        let svc = StepFunctionsService::new(make_state());
1780        let sm_arn = create_sm(&svc, "redrive-running-sm");
1781        let body = json!({"stateMachineArn": sm_arn, "name": "still-running"});
1782        let req = make_request("StartExecution", &body.to_string());
1783        let exec_arn = body_json(&svc.start_execution(&req).unwrap())["executionArn"]
1784            .as_str()
1785            .unwrap()
1786            .to_string();
1787
1788        // A still-RUNNING execution is not redrivable (it already has a driver).
1789        let req = make_request(
1790            "RedriveExecution",
1791            &json!({"executionArn": exec_arn}).to_string(),
1792        );
1793        let err = expect_err(svc.redrive_execution(&req));
1794        assert!(err.to_string().contains("ExecutionNotRedrivable"));
1795    }
1796
1797    #[tokio::test]
1798    async fn stop_execution_not_found() {
1799        let svc = StepFunctionsService::new(make_state());
1800        let req = make_request(
1801            "StopExecution",
1802            &json!({"executionArn": "arn:aws:states:us-east-1:123456789012:execution:sm:nope"})
1803                .to_string(),
1804        );
1805        let err = expect_err(svc.stop_execution(&req));
1806        assert!(err.to_string().contains("ExecutionDoesNotExist"));
1807    }
1808
1809    // ── ListExecutions ──
1810
1811    #[tokio::test]
1812    async fn list_executions() {
1813        let svc = StepFunctionsService::new(make_state());
1814        let sm_arn = create_sm(&svc, "list-exec");
1815
1816        for i in 0..3 {
1817            let body = json!({"stateMachineArn": sm_arn, "name": format!("e{i}")});
1818            let req = make_request("StartExecution", &body.to_string());
1819            svc.start_execution(&req).unwrap();
1820        }
1821
1822        let req = make_request(
1823            "ListExecutions",
1824            &json!({"stateMachineArn": sm_arn}).to_string(),
1825        );
1826        let resp = svc.list_executions(&req).unwrap();
1827        let b = body_json(&resp);
1828        assert_eq!(b["executions"].as_array().unwrap().len(), 3);
1829    }
1830
1831    #[tokio::test]
1832    async fn list_executions_sm_not_found() {
1833        let svc = StepFunctionsService::new(make_state());
1834        let req = make_request(
1835            "ListExecutions",
1836            &json!({"stateMachineArn": "arn:aws:states:us-east-1:123456789012:stateMachine:nope"})
1837                .to_string(),
1838        );
1839        let err = expect_err(svc.list_executions(&req));
1840        assert!(err.to_string().contains("StateMachineDoesNotExist"));
1841    }
1842
1843    // ── GetExecutionHistory ──
1844
1845    #[tokio::test]
1846    async fn get_execution_history_not_found() {
1847        let svc = StepFunctionsService::new(make_state());
1848        let req = make_request(
1849            "GetExecutionHistory",
1850            &json!({"executionArn": "arn:aws:states:us-east-1:123456789012:execution:sm:nope"})
1851                .to_string(),
1852        );
1853        let err = expect_err(svc.get_execution_history(&req));
1854        assert!(err.to_string().contains("ExecutionDoesNotExist"));
1855    }
1856
1857    // ── DescribeStateMachineForExecution ──
1858
1859    #[tokio::test]
1860    async fn describe_sm_for_execution() {
1861        let svc = StepFunctionsService::new(make_state());
1862        let sm_arn = create_sm(&svc, "sm-for-exec");
1863
1864        let body = json!({"stateMachineArn": sm_arn, "name": "e1"});
1865        let req = make_request("StartExecution", &body.to_string());
1866        let resp = svc.start_execution(&req).unwrap();
1867        let exec_arn = body_json(&resp)["executionArn"]
1868            .as_str()
1869            .unwrap()
1870            .to_string();
1871
1872        let req = make_request(
1873            "DescribeStateMachineForExecution",
1874            &json!({"executionArn": exec_arn}).to_string(),
1875        );
1876        let resp = svc.describe_state_machine_for_execution(&req).unwrap();
1877        let b = body_json(&resp);
1878        assert_eq!(b["name"], "sm-for-exec");
1879    }
1880
1881    // ── Tags ──
1882
1883    #[test]
1884    fn tag_untag_list_tags() {
1885        let svc = StepFunctionsService::new(make_state());
1886        let arn = create_sm(&svc, "tagged-sm");
1887
1888        // Tag
1889        let body = json!({
1890            "resourceArn": arn,
1891            "tags": [{"key": "env", "value": "prod"}],
1892        });
1893        let req = make_request("TagResource", &body.to_string());
1894        svc.tag_resource(&req).unwrap();
1895
1896        // List
1897        let req = make_request(
1898            "ListTagsForResource",
1899            &json!({"resourceArn": arn}).to_string(),
1900        );
1901        let resp = svc.list_tags_for_resource(&req).unwrap();
1902        let b = body_json(&resp);
1903        let tags = b["tags"].as_array().unwrap();
1904        assert_eq!(tags.len(), 1);
1905        assert_eq!(tags[0]["key"], "env");
1906
1907        // Untag
1908        let body = json!({
1909            "resourceArn": arn,
1910            "tagKeys": ["env"],
1911        });
1912        let req = make_request("UntagResource", &body.to_string());
1913        svc.untag_resource(&req).unwrap();
1914
1915        // Verify empty
1916        let req = make_request(
1917            "ListTagsForResource",
1918            &json!({"resourceArn": arn}).to_string(),
1919        );
1920        let resp = svc.list_tags_for_resource(&req).unwrap();
1921        let b = body_json(&resp);
1922        assert!(b["tags"].as_array().unwrap().is_empty());
1923    }
1924
1925    #[test]
1926    fn tag_resource_not_found() {
1927        let svc = StepFunctionsService::new(make_state());
1928        let body = json!({
1929            "resourceArn": "arn:aws:states:us-east-1:123456789012:stateMachine:nope",
1930            "tags": [{"key": "k", "value": "v"}],
1931        });
1932        let req = make_request("TagResource", &body.to_string());
1933        let err = expect_err(svc.tag_resource(&req));
1934        assert!(err.to_string().contains("ResourceNotFound"));
1935    }
1936
1937    // ── Helper function tests ──
1938
1939    #[test]
1940    fn test_validate_name() {
1941        assert!(validate_name("valid-name").is_ok());
1942        assert!(validate_name("under_score").is_ok());
1943        assert!(validate_name("").is_err());
1944        assert!(validate_name("has spaces").is_err());
1945        assert!(validate_name(&"a".repeat(81)).is_err());
1946    }
1947
1948    #[test]
1949    fn test_validate_definition() {
1950        assert!(validate_definition(VALID_DEF).is_ok());
1951        assert!(validate_definition("not json").is_err());
1952        assert!(validate_definition(r#"{"States":{}}"#).is_err()); // missing StartAt
1953        assert!(validate_definition(r#"{"StartAt":"S"}"#).is_err()); // missing States
1954    }
1955
1956    #[test]
1957    fn test_validate_definition_rejects_malformed_paths() {
1958        // Unterminated bracket in InputPath.
1959        let def =
1960            r#"{"StartAt":"P","States":{"P":{"Type":"Pass","InputPath":"$.arr[","End":true}}}"#;
1961        assert!(validate_definition(def).is_err());
1962
1963        // Multibyte char where the close bracket would be, in OutputPath.
1964        let def =
1965            "{\"StartAt\":\"P\",\"States\":{\"P\":{\"Type\":\"Pass\",\"OutputPath\":\"$.x[\u{00e9}\",\"End\":true}}}";
1966        assert!(validate_definition(def).is_err());
1967
1968        // Malformed Choice Variable.
1969        let def = r#"{"StartAt":"C","States":{"C":{"Type":"Choice","Choices":[{"Variable":"$.n[","NumericEquals":1,"Next":"P"}]},"P":{"Type":"Pass","End":true}}}"#;
1970        assert!(validate_definition(def).is_err());
1971
1972        // Path not rooted at $.
1973        let def =
1974            r#"{"StartAt":"P","States":{"P":{"Type":"Pass","InputPath":"foo.bar","End":true}}}"#;
1975        assert!(validate_definition(def).is_err());
1976
1977        // Empty index brackets.
1978        let def =
1979            r#"{"StartAt":"P","States":{"P":{"Type":"Pass","ResultPath":"$.x[]","End":true}}}"#;
1980        assert!(validate_definition(def).is_err());
1981    }
1982
1983    #[test]
1984    fn test_validate_definition_accepts_well_formed_paths() {
1985        // Valid reference paths, the literal "null" for Input/OutputPath, and
1986        // nested Choice combinators must all be accepted.
1987        let def = r#"{"StartAt":"P","States":{
1988            "P":{"Type":"Pass","InputPath":"$.a.b[0].c","OutputPath":"$","ResultPath":"$.out","Next":"C"},
1989            "C":{"Type":"Choice","Choices":[
1990                {"And":[{"Variable":"$.items[2]","NumericEquals":1},{"Variable":"$.flag","BooleanEquals":true}],"Next":"S"}
1991            ],"Default":"S"},
1992            "S":{"Type":"Succeed","InputPath":"null"}
1993        }}"#;
1994        assert!(validate_definition(def).is_ok());
1995    }
1996
1997    // M5: malformed paths nested inside Parallel branches and Map processors
1998    // must be rejected.
1999    #[test]
2000    fn test_validate_definition_recurses_into_parallel_and_map() {
2001        let par = r#"{"StartAt":"Par","States":{"Par":{"Type":"Parallel","End":true,
2002            "Branches":[{"StartAt":"I","States":{"I":{"Type":"Pass","InputPath":"nope","End":true}}}]}}}"#;
2003        assert!(validate_definition(par).is_err());
2004
2005        let map = r#"{"StartAt":"M","States":{"M":{"Type":"Map","End":true,
2006            "ItemProcessor":{"StartAt":"E","States":{"E":{"Type":"Pass","OutputPath":"nope","End":true}}}}}}"#;
2007        assert!(validate_definition(map).is_err());
2008
2009        // Legacy inline Map uses `Iterator`.
2010        let iter = r#"{"StartAt":"M","States":{"M":{"Type":"Map","End":true,
2011            "Iterator":{"StartAt":"E","States":{"E":{"Type":"Pass","ResultPath":"$.x[]","End":true}}}}}}"#;
2012        assert!(validate_definition(iter).is_err());
2013
2014        // A well-formed Parallel/Map still validates.
2015        let ok = r#"{"StartAt":"M","States":{"M":{"Type":"Map","ItemsPath":"$.items","End":true,
2016            "ItemProcessor":{"StartAt":"E","States":{"E":{"Type":"Pass","InputPath":"$.a","End":true}}}}}}"#;
2017        assert!(validate_definition(ok).is_ok());
2018    }
2019
2020    // L7: `.$` payload-template keys must carry a JSONPath/intrinsic string.
2021    #[test]
2022    fn test_validate_definition_payload_template_dollar_keys() {
2023        // Bare literal value.
2024        let lit = r#"{"StartAt":"P","States":{"P":{"Type":"Pass",
2025            "Parameters":{"v.$":"just text"},"End":true}}}"#;
2026        assert!(validate_definition(lit).is_err());
2027
2028        // Non-string value.
2029        let num = r#"{"StartAt":"P","States":{"P":{"Type":"Pass",
2030            "Parameters":{"v.$":42},"End":true}}}"#;
2031        assert!(validate_definition(num).is_err());
2032
2033        // Valid: JSONPath reference, context-object ref, and intrinsic.
2034        let ok = r#"{"StartAt":"P","States":{"P":{"Type":"Pass","Parameters":{
2035            "a.$":"$.input","b.$":"$$.Execution.Id","c.$":"States.Format('{}',$.n)",
2036            "nested":{"d.$":"$.x"},"plain":"literal-ok"},"End":true}}}"#;
2037        assert!(validate_definition(ok).is_ok());
2038
2039        // A bad `.$` nested inside an array under a plain key is also caught.
2040        let arr = r#"{"StartAt":"P","States":{"P":{"Type":"Pass",
2041            "ResultSelector":{"items":[{"bad.$":"literal"}]},"End":true}}}"#;
2042        assert!(validate_definition(arr).is_err());
2043    }
2044
2045    #[test]
2046    fn test_is_valid_reference_path() {
2047        assert!(is_valid_reference_path("$"));
2048        assert!(is_valid_reference_path("$.foo"));
2049        assert!(is_valid_reference_path("$.foo.bar[3].baz"));
2050        assert!(is_valid_reference_path("$[0]"));
2051        assert!(!is_valid_reference_path("$.arr["));
2052        assert!(!is_valid_reference_path("$.x[\u{00e9}"));
2053        assert!(!is_valid_reference_path("$.x[]"));
2054        assert!(!is_valid_reference_path("$.x[abc]"));
2055        assert!(!is_valid_reference_path("foo.bar"));
2056        assert!(!is_valid_reference_path(""));
2057    }
2058
2059    #[test]
2060    fn test_validate_arn() {
2061        assert!(validate_arn("arn:aws:states:us-east-1:123:sm:test").is_ok());
2062        assert!(validate_arn("not-an-arn").is_err());
2063    }
2064
2065    #[test]
2066    fn test_camel_to_details_key() {
2067        // All *StateEntered / *StateExited types collapse to one key each.
2068        assert_eq!(camel_to_details_key("PassStateEntered"), "stateEntered");
2069        assert_eq!(camel_to_details_key("TaskStateEntered"), "stateEntered");
2070        assert_eq!(camel_to_details_key("ChoiceStateExited"), "stateExited");
2071        assert_eq!(camel_to_details_key("MapStateExited"), "stateExited");
2072        // Other event types keep first-char-lowercased prefix.
2073        assert_eq!(camel_to_details_key("TaskScheduled"), "taskScheduled");
2074        assert_eq!(camel_to_details_key("ExecutionStarted"), "executionStarted");
2075        assert_eq!(camel_to_details_key(""), "");
2076    }
2077
2078    #[test]
2079    fn test_is_mutating_action() {
2080        assert!(is_mutating_action("CreateStateMachine"));
2081        assert!(is_mutating_action("StartExecution"));
2082        assert!(!is_mutating_action("DescribeStateMachine"));
2083        assert!(!is_mutating_action("ListStateMachines"));
2084    }
2085
2086    // ── StartSyncExecution ──
2087
2088    fn create_express_sm(svc: &StepFunctionsService, name: &str) -> String {
2089        let body = json!({
2090            "name": name,
2091            "definition": VALID_DEF,
2092            "roleArn": "arn:aws:iam::123456789012:role/test",
2093            "type": "EXPRESS",
2094        });
2095        let req = make_request("CreateStateMachine", &body.to_string());
2096        let resp = svc.create_state_machine(&req).unwrap();
2097        let b = body_json(&resp);
2098        b["stateMachineArn"].as_str().unwrap().to_string()
2099    }
2100
2101    #[tokio::test]
2102    async fn start_sync_execution_basic() {
2103        let svc = StepFunctionsService::new(make_state());
2104        let arn = create_express_sm(&svc, "sync-sm");
2105
2106        let body = json!({
2107            "stateMachineArn": arn,
2108            "input": r#"{"key":"value"}"#,
2109        });
2110        let req = make_request("StartSyncExecution", &body.to_string());
2111        let resp = svc.start_sync_execution(&req).await.unwrap();
2112        let b = body_json(&resp);
2113        assert!(b["executionArn"]
2114            .as_str()
2115            .unwrap()
2116            .contains("express:sync-sm"));
2117        assert_eq!(b["stateMachineArn"], arn);
2118        assert_eq!(b["status"], "SUCCEEDED");
2119        assert!(b["startDate"].as_i64().is_some());
2120        assert!(b["stopDate"].as_i64().is_some());
2121        assert!(b["output"].as_str().is_some());
2122        assert!(b["billingDetails"]["billedDurationInMilliseconds"]
2123            .as_i64()
2124            .is_some());
2125    }
2126
2127    #[tokio::test]
2128    async fn start_sync_execution_not_express() {
2129        let svc = StepFunctionsService::new(make_state());
2130        let arn = create_sm(&svc, "std-sm");
2131
2132        let body = json!({"stateMachineArn": arn});
2133        let req = make_request("StartSyncExecution", &body.to_string());
2134        let err = expect_err(svc.start_sync_execution(&req).await);
2135        assert!(err.to_string().contains("StateMachineTypeNotSupported"));
2136    }
2137
2138    #[tokio::test]
2139    async fn start_sync_execution_sm_not_found() {
2140        let svc = StepFunctionsService::new(make_state());
2141        let body = json!({
2142            "stateMachineArn": "arn:aws:states:us-east-1:123456789012:stateMachine:nope",
2143        });
2144        let req = make_request("StartSyncExecution", &body.to_string());
2145        let err = expect_err(svc.start_sync_execution(&req).await);
2146        assert!(err.to_string().contains("StateMachineDoesNotExist"));
2147    }
2148
2149    #[tokio::test]
2150    async fn start_sync_execution_records_introspection_fields() {
2151        let svc = StepFunctionsService::new(make_state());
2152        let arn = create_express_sm(&svc, "sync-introspect");
2153
2154        let body = json!({"stateMachineArn": arn, "input": "{}"});
2155        let req = make_request("StartSyncExecution", &body.to_string());
2156        let resp = svc.start_sync_execution(&req).await.unwrap();
2157        let b = body_json(&resp);
2158        let exec_arn = b["executionArn"].as_str().unwrap().to_string();
2159
2160        let accounts = svc.state.read();
2161        let state = accounts.get("123456789012").unwrap();
2162        let stored = state
2163            .executions
2164            .get(&exec_arn)
2165            .expect("sync execution should be persisted for introspection");
2166        assert!(stored.is_sync, "sync executions must be marked is_sync");
2167        assert_eq!(stored.billed_memory_mb, Some(64));
2168        assert!(
2169            stored.billed_duration_ms.is_some(),
2170            "billed_duration_ms must be populated after sync run"
2171        );
2172        assert!(
2173            stored.parent_execution_arn.is_none(),
2174            "top-level sync execution has no parent"
2175        );
2176    }
2177
2178    #[tokio::test]
2179    async fn start_sync_execution_invalid_input() {
2180        let svc = StepFunctionsService::new(make_state());
2181        let arn = create_express_sm(&svc, "bad-input-sync");
2182
2183        let body = json!({
2184            "stateMachineArn": arn,
2185            "input": "not json",
2186        });
2187        let req = make_request("StartSyncExecution", &body.to_string());
2188        let err = expect_err(svc.start_sync_execution(&req).await);
2189        assert!(err.to_string().contains("InvalidExecutionInput"));
2190    }
2191
2192    /// No snapshot store (memory mode) -> no persist hook for the CFN provisioner.
2193    #[test]
2194    fn snapshot_hook_is_none_without_store() {
2195        let svc = StepFunctionsService::new(make_state());
2196        assert!(svc.snapshot_hook().is_none());
2197    }
2198
2199    /// With a store, the hook is present and invoking it runs the whole-state
2200    /// persist path the CloudFormation provisioner uses after mutating Step
2201    /// Functions state directly.
2202    #[tokio::test]
2203    async fn snapshot_hook_fires_with_store() {
2204        let store: Arc<dyn fakecloud_persistence::SnapshotStore> =
2205            Arc::new(fakecloud_persistence::MemorySnapshotStore::new());
2206        let svc = StepFunctionsService::new(make_state()).with_snapshot_store(store);
2207        let hook = svc
2208            .snapshot_hook()
2209            .expect("hook present when a store is set");
2210        hook().await;
2211    }
2212
2213    fn make_execution(arn: &str, status: ExecutionStatus) -> Execution {
2214        Execution {
2215            execution_arn: arn.to_string(),
2216            state_machine_arn: "arn:aws:states:us-east-1:123456789012:stateMachine:sm".to_string(),
2217            state_machine_name: "sm".to_string(),
2218            name: arn.to_string(),
2219            status,
2220            input: None,
2221            output: None,
2222            start_date: Utc::now(),
2223            stop_date: None,
2224            error: None,
2225            cause: None,
2226            history_events: vec![],
2227            parent_execution_arn: None,
2228            is_sync: false,
2229            billed_duration_ms: None,
2230            billed_memory_mb: None,
2231        }
2232    }
2233
2234    #[test]
2235    fn reconcile_aborts_running_executions_on_restart() {
2236        // After a restart a RUNNING execution has no interpreter driving it, so
2237        // it must be aborted rather than left RUNNING forever (0.A2). A
2238        // completed execution is untouched.
2239        let state = make_state();
2240        {
2241            let mut accounts = state.write();
2242            let s = accounts.get_or_create("123456789012");
2243            s.executions.insert(
2244                "running".into(),
2245                make_execution("running", ExecutionStatus::Running),
2246            );
2247            s.executions.insert(
2248                "done".into(),
2249                make_execution("done", ExecutionStatus::Succeeded),
2250            );
2251        }
2252
2253        let n = reconcile_interrupted_executions(&state);
2254        assert_eq!(n, 1, "only the RUNNING execution is reconciled");
2255
2256        let accounts = state.read();
2257        let s = accounts.get("123456789012").unwrap();
2258        let running = &s.executions["running"];
2259        assert_eq!(running.status, ExecutionStatus::Aborted);
2260        assert!(running.stop_date.is_some());
2261        assert_eq!(running.error.as_deref(), Some("Fakecloud.Restart"));
2262        assert_eq!(s.executions["done"].status, ExecutionStatus::Succeeded);
2263    }
2264
2265    // ── Distributed Map -> MapRun population (bug-hunt read-shape) ──
2266
2267    #[tokio::test]
2268    async fn distributed_map_populates_map_run() {
2269        let state = make_state();
2270        let svc = StepFunctionsService::new(state.clone());
2271        let execution_arn =
2272            "arn:aws:states:us-east-1:123456789012:execution:dist-sm:exec-1".to_string();
2273
2274        let def = json!({
2275            "StartAt": "M",
2276            "States": {
2277                "M": {
2278                    "Type": "Map",
2279                    "ItemsPath": "$.items",
2280                    "ItemProcessor": {
2281                        "ProcessorConfig": { "Mode": "DISTRIBUTED", "ExecutionType": "STANDARD" },
2282                        "StartAt": "Item",
2283                        "States": { "Item": { "Type": "Pass", "End": true } }
2284                    },
2285                    "End": true
2286                }
2287            }
2288        });
2289
2290        interpreter::execute_state_machine(
2291            state.clone(),
2292            execution_arn.clone(),
2293            def.to_string(),
2294            Some(r#"{"items":[1,2,3]}"#.to_string()),
2295            None,
2296            None,
2297            None,
2298            None,
2299        )
2300        .await;
2301
2302        // ListMapRuns(executionArn) surfaces the newly created MapRun.
2303        let req = make_request(
2304            "ListMapRuns",
2305            &json!({ "executionArn": execution_arn }).to_string(),
2306        );
2307        let listed = body_json(&svc.list_map_runs(&req).unwrap());
2308        let runs = listed["mapRuns"].as_array().unwrap();
2309        assert_eq!(
2310            runs.len(),
2311            1,
2312            "distributed map must create exactly one MapRun"
2313        );
2314        let map_run_arn = runs[0]["mapRunArn"].as_str().unwrap().to_string();
2315        assert!(map_run_arn.contains(":mapRun:"));
2316        assert_eq!(runs[0]["executionArn"], execution_arn);
2317
2318        // DescribeMapRun(mapRunArn) returns the record with real counts.
2319        let req = make_request(
2320            "DescribeMapRun",
2321            &json!({ "mapRunArn": map_run_arn }).to_string(),
2322        );
2323        let mr = body_json(&svc.describe_map_run(&req).unwrap());
2324        assert_eq!(mr["status"], "SUCCEEDED");
2325        assert_eq!(mr["itemCounts"]["total"], 3);
2326        assert_eq!(mr["itemCounts"]["succeeded"], 3);
2327        assert_eq!(mr["itemCounts"]["failed"], 0);
2328        assert_eq!(mr["executionCounts"]["succeeded"], 3);
2329    }
2330
2331    #[tokio::test]
2332    async fn inline_map_does_not_create_map_run() {
2333        let state = make_state();
2334        let svc = StepFunctionsService::new(state.clone());
2335        let execution_arn =
2336            "arn:aws:states:us-east-1:123456789012:execution:inline-sm:exec-1".to_string();
2337
2338        // No ProcessorConfig.Mode => inline Map: AWS creates no MapRun.
2339        let def = json!({
2340            "StartAt": "M",
2341            "States": {
2342                "M": {
2343                    "Type": "Map",
2344                    "ItemsPath": "$.items",
2345                    "ItemProcessor": {
2346                        "StartAt": "Item",
2347                        "States": { "Item": { "Type": "Pass", "End": true } }
2348                    },
2349                    "End": true
2350                }
2351            }
2352        });
2353
2354        interpreter::execute_state_machine(
2355            state.clone(),
2356            execution_arn.clone(),
2357            def.to_string(),
2358            Some(r#"{"items":[1,2]}"#.to_string()),
2359            None,
2360            None,
2361            None,
2362            None,
2363        )
2364        .await;
2365
2366        let req = make_request(
2367            "ListMapRuns",
2368            &json!({ "executionArn": execution_arn }).to_string(),
2369        );
2370        let listed = body_json(&svc.list_map_runs(&req).unwrap());
2371        assert!(listed["mapRuns"].as_array().unwrap().is_empty());
2372    }
2373}
2374
2375#[cfg(test)]
2376mod pagination_reject_test {
2377    #[test]
2378    fn paginate_checked_rejects_invalid_token() {
2379        use fakecloud_core::pagination::paginate_checked;
2380        let items: Vec<i32> = (0..5).collect();
2381        assert!(paginate_checked(&items, Some("bad"), 3).is_err());
2382        assert!(paginate_checked(&items, Some("2"), 3).is_ok());
2383    }
2384}