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    // No request in this delivery path; the execution inherits the region its
1037    // state machine ARN was minted in (the request region at CreateStateMachine).
1038    let region = state_machine_arn
1039        .split(':')
1040        .nth(3)
1041        .unwrap_or("us-east-1")
1042        .to_string();
1043    let exec_arn = st.execution_arn(&region, &sm_name, &execution_name);
1044
1045    let now = Utc::now();
1046    let execution = Execution {
1047        execution_arn: exec_arn.clone(),
1048        state_machine_arn: state_machine_arn.to_string(),
1049        state_machine_name: sm_name,
1050        name: execution_name,
1051        status: ExecutionStatus::Running,
1052        input: Some(input.to_string()),
1053        output: None,
1054        start_date: now,
1055        stop_date: None,
1056        error: None,
1057        cause: None,
1058        history_events: vec![],
1059        parent_execution_arn: None,
1060        is_sync: false,
1061        billed_duration_ms: None,
1062        billed_memory_mb: None,
1063    };
1064
1065    st.executions.insert(exec_arn.clone(), execution);
1066    let logging_config = sm.logging_configuration.clone();
1067    drop(accounts);
1068
1069    let shared_state = state.clone();
1070    let delivery = delivery.clone();
1071    let dynamodb_state = dynamodb_state.clone();
1072    let registry = registry.clone();
1073    let input = Some(input.to_string());
1074    tokio::spawn(async move {
1075        interpreter::execute_state_machine(
1076            shared_state,
1077            exec_arn,
1078            definition,
1079            input,
1080            delivery,
1081            dynamodb_state,
1082            registry,
1083            logging_config,
1084        )
1085        .await;
1086    });
1087}
1088
1089#[cfg(test)]
1090mod tests {
1091    use super::*;
1092    use http::{HeaderMap, Method};
1093    use parking_lot::RwLock;
1094    use serde_json::Value;
1095    use std::collections::HashMap;
1096    use std::sync::Arc;
1097
1098    fn make_state() -> SharedStepFunctionsState {
1099        Arc::new(RwLock::new(
1100            fakecloud_core::multi_account::MultiAccountState::new("123456789012", "us-east-1", ""),
1101        ))
1102    }
1103
1104    fn make_request(action: &str, body: &str) -> AwsRequest {
1105        AwsRequest {
1106            service: "states".to_string(),
1107            action: action.to_string(),
1108            region: "us-east-1".to_string(),
1109            account_id: "123456789012".to_string(),
1110            request_id: "test-id".to_string(),
1111            headers: HeaderMap::new(),
1112            query_params: HashMap::new(),
1113            body: body.as_bytes().to_vec().into(),
1114            body_stream: parking_lot::Mutex::new(None),
1115            path_segments: vec![],
1116            raw_path: "/".to_string(),
1117            raw_query: String::new(),
1118            method: Method::POST,
1119            is_query_protocol: false,
1120            access_key_id: None,
1121            principal: None,
1122        }
1123    }
1124
1125    fn body_json(resp: &AwsResponse) -> Value {
1126        serde_json::from_slice(resp.body.expect_bytes()).unwrap()
1127    }
1128
1129    fn expect_err(result: Result<AwsResponse, AwsServiceError>) -> AwsServiceError {
1130        match result {
1131            Err(e) => e,
1132            Ok(_) => panic!("expected error, got Ok"),
1133        }
1134    }
1135
1136    const VALID_DEF: &str = r#"{"StartAt":"Pass","States":{"Pass":{"Type":"Pass","End":true}}}"#;
1137
1138    fn create_sm(svc: &StepFunctionsService, name: &str) -> String {
1139        let body = json!({
1140            "name": name,
1141            "definition": VALID_DEF,
1142            "roleArn": "arn:aws:iam::123456789012:role/test",
1143        });
1144        let req = make_request("CreateStateMachine", &body.to_string());
1145        let resp = svc.create_state_machine(&req).unwrap();
1146        let b = body_json(&resp);
1147        b["stateMachineArn"].as_str().unwrap().to_string()
1148    }
1149
1150    // ── CreateStateMachine ──
1151
1152    #[test]
1153    fn create_state_machine_basic() {
1154        let svc = StepFunctionsService::new(make_state());
1155        let arn = create_sm(&svc, "test-sm");
1156        assert!(arn.contains("test-sm"));
1157    }
1158
1159    // bug-hunt 2026-07-19: CreateStateMachine with publish=true creates a real
1160    // version that ListStateMachineVersions returns; without publish, no version
1161    // ARN is returned and no version exists.
1162    #[test]
1163    fn create_state_machine_publish_creates_listable_version() {
1164        let svc = StepFunctionsService::new(make_state());
1165        let body = json!({
1166            "name": "pub-sm",
1167            "definition": VALID_DEF,
1168            "roleArn": "arn:aws:iam::123456789012:role/r",
1169            "publish": true,
1170            "versionDescription": "first",
1171        });
1172        let req = make_request("CreateStateMachine", &body.to_string());
1173        let resp = svc.create_state_machine(&req).unwrap();
1174        let b = body_json(&resp);
1175        let arn = b["stateMachineArn"].as_str().unwrap().to_string();
1176        let version_arn = b["stateMachineVersionArn"].as_str().unwrap().to_string();
1177        assert_eq!(version_arn, format!("{arn}:1"));
1178
1179        let list_req = make_request(
1180            "ListStateMachineVersions",
1181            &json!({ "stateMachineArn": arn }).to_string(),
1182        );
1183        let list = body_json(&svc.list_state_machine_versions(&list_req).unwrap());
1184        let versions = list["stateMachineVersions"].as_array().unwrap();
1185        assert_eq!(versions.len(), 1);
1186        assert_eq!(versions[0]["stateMachineVersionArn"], version_arn);
1187    }
1188
1189    #[test]
1190    fn create_state_machine_no_publish_has_no_version() {
1191        let svc = StepFunctionsService::new(make_state());
1192        let arn = create_sm(&svc, "nopub-sm");
1193        // No version ARN is returned when publish is absent.
1194        let body = json!({
1195            "name": "nopub-sm2",
1196            "definition": VALID_DEF,
1197            "roleArn": "arn:aws:iam::123456789012:role/r",
1198        });
1199        let req = make_request("CreateStateMachine", &body.to_string());
1200        let b = body_json(&svc.create_state_machine(&req).unwrap());
1201        assert!(b.get("stateMachineVersionArn").is_none());
1202
1203        let list_req = make_request(
1204            "ListStateMachineVersions",
1205            &json!({ "stateMachineArn": arn }).to_string(),
1206        );
1207        let list = body_json(&svc.list_state_machine_versions(&list_req).unwrap());
1208        assert!(list["stateMachineVersions"].as_array().unwrap().is_empty());
1209    }
1210
1211    // bug-hunt 2026-07-19: UpdateStateMachine with publish=true publishes the
1212    // next version, and encryptionConfiguration persists + round-trips on
1213    // Describe.
1214    #[test]
1215    fn update_state_machine_publish_and_encryption_round_trip() {
1216        let svc = StepFunctionsService::new(make_state());
1217        let create = json!({
1218            "name": "enc-sm",
1219            "definition": VALID_DEF,
1220            "roleArn": "arn:aws:iam::123456789012:role/r",
1221            "encryptionConfiguration": { "type": "CUSTOMER_MANAGED_KMS_KEY", "kmsKeyId": "key-123" },
1222        });
1223        let req = make_request("CreateStateMachine", &create.to_string());
1224        let arn = body_json(&svc.create_state_machine(&req).unwrap())["stateMachineArn"]
1225            .as_str()
1226            .unwrap()
1227            .to_string();
1228
1229        // encryptionConfiguration round-trips on Describe.
1230        let desc_req = make_request(
1231            "DescribeStateMachine",
1232            &json!({ "stateMachineArn": arn }).to_string(),
1233        );
1234        let desc = body_json(&svc.describe_state_machine(&desc_req).unwrap());
1235        assert_eq!(
1236            desc["encryptionConfiguration"]["type"],
1237            "CUSTOMER_MANAGED_KMS_KEY"
1238        );
1239        assert_eq!(desc["encryptionConfiguration"]["kmsKeyId"], "key-123");
1240
1241        // Update with publish creates version 1.
1242        let upd = json!({
1243            "stateMachineArn": arn,
1244            "definition": VALID_DEF,
1245            "publish": true,
1246            "versionDescription": "v via update",
1247        });
1248        let upd_req = make_request("UpdateStateMachine", &upd.to_string());
1249        let upd_body = body_json(&svc.update_state_machine(&upd_req).unwrap());
1250        assert_eq!(
1251            upd_body["stateMachineVersionArn"].as_str().unwrap(),
1252            format!("{arn}:1")
1253        );
1254
1255        let list_req = make_request(
1256            "ListStateMachineVersions",
1257            &json!({ "stateMachineArn": arn }).to_string(),
1258        );
1259        let list = body_json(&svc.list_state_machine_versions(&list_req).unwrap());
1260        assert_eq!(list["stateMachineVersions"].as_array().unwrap().len(), 1);
1261    }
1262
1263    #[test]
1264    fn create_state_machine_with_express_type() {
1265        let svc = StepFunctionsService::new(make_state());
1266        let body = json!({
1267            "name": "express-sm",
1268            "definition": VALID_DEF,
1269            "roleArn": "arn:aws:iam::123456789012:role/r",
1270            "type": "EXPRESS",
1271        });
1272        let req = make_request("CreateStateMachine", &body.to_string());
1273        let resp = svc.create_state_machine(&req).unwrap();
1274        let b = body_json(&resp);
1275        assert!(b["stateMachineArn"].as_str().is_some());
1276    }
1277
1278    #[test]
1279    fn create_state_machine_duplicate_fails() {
1280        let svc = StepFunctionsService::new(make_state());
1281        create_sm(&svc, "dup-sm");
1282        let body = json!({
1283            "name": "dup-sm",
1284            "definition": VALID_DEF,
1285            "roleArn": "arn:aws:iam::123456789012:role/r",
1286        });
1287        let req = make_request("CreateStateMachine", &body.to_string());
1288        let err = expect_err(svc.create_state_machine(&req));
1289        assert!(err.to_string().contains("StateMachineAlreadyExists"));
1290    }
1291
1292    #[test]
1293    fn create_state_machine_missing_name() {
1294        let svc = StepFunctionsService::new(make_state());
1295        let body = json!({
1296            "definition": VALID_DEF,
1297            "roleArn": "arn:aws:iam::123456789012:role/r",
1298        });
1299        let req = make_request("CreateStateMachine", &body.to_string());
1300        assert!(svc.create_state_machine(&req).is_err());
1301    }
1302
1303    #[test]
1304    fn create_state_machine_invalid_definition() {
1305        let svc = StepFunctionsService::new(make_state());
1306        let body = json!({
1307            "name": "bad-def",
1308            "definition": "not json",
1309            "roleArn": "arn:aws:iam::123456789012:role/r",
1310        });
1311        let req = make_request("CreateStateMachine", &body.to_string());
1312        let err = expect_err(svc.create_state_machine(&req));
1313        assert!(err.to_string().contains("InvalidDefinition"));
1314    }
1315
1316    #[test]
1317    fn create_state_machine_definition_missing_start_at() {
1318        let svc = StepFunctionsService::new(make_state());
1319        let body = json!({
1320            "name": "no-start",
1321            "definition": r#"{"States":{"S":{"Type":"Pass","End":true}}}"#,
1322            "roleArn": "arn:aws:iam::123456789012:role/r",
1323        });
1324        let req = make_request("CreateStateMachine", &body.to_string());
1325        let err = expect_err(svc.create_state_machine(&req));
1326        assert!(err.to_string().contains("InvalidDefinition"));
1327    }
1328
1329    #[test]
1330    fn create_state_machine_definition_missing_states() {
1331        let svc = StepFunctionsService::new(make_state());
1332        let body = json!({
1333            "name": "no-states",
1334            "definition": r#"{"StartAt":"S"}"#,
1335            "roleArn": "arn:aws:iam::123456789012:role/r",
1336        });
1337        let req = make_request("CreateStateMachine", &body.to_string());
1338        let err = expect_err(svc.create_state_machine(&req));
1339        assert!(err.to_string().contains("InvalidDefinition"));
1340    }
1341
1342    #[test]
1343    fn create_state_machine_definition_start_at_not_in_states() {
1344        let svc = StepFunctionsService::new(make_state());
1345        let body = json!({
1346            "name": "bad-start",
1347            "definition": r#"{"StartAt":"Missing","States":{"S":{"Type":"Pass","End":true}}}"#,
1348            "roleArn": "arn:aws:iam::123456789012:role/r",
1349        });
1350        let req = make_request("CreateStateMachine", &body.to_string());
1351        let err = expect_err(svc.create_state_machine(&req));
1352        assert!(err.to_string().contains("MISSING_TRANSITION_TARGET"));
1353    }
1354
1355    #[test]
1356    fn create_state_machine_invalid_type() {
1357        let svc = StepFunctionsService::new(make_state());
1358        let body = json!({
1359            "name": "bad-type",
1360            "definition": VALID_DEF,
1361            "roleArn": "arn:aws:iam::123456789012:role/r",
1362            "type": "INVALID",
1363        });
1364        let req = make_request("CreateStateMachine", &body.to_string());
1365        assert!(svc.create_state_machine(&req).is_err());
1366    }
1367
1368    #[test]
1369    fn create_state_machine_invalid_arn() {
1370        let svc = StepFunctionsService::new(make_state());
1371        let body = json!({
1372            "name": "bad-arn",
1373            "definition": VALID_DEF,
1374            "roleArn": "not-an-arn",
1375        });
1376        let req = make_request("CreateStateMachine", &body.to_string());
1377        let err = expect_err(svc.create_state_machine(&req));
1378        assert!(err.to_string().contains("InvalidArn"));
1379    }
1380
1381    #[test]
1382    fn create_state_machine_invalid_name() {
1383        let svc = StepFunctionsService::new(make_state());
1384        let body = json!({
1385            "name": "has spaces!",
1386            "definition": VALID_DEF,
1387            "roleArn": "arn:aws:iam::123456789012:role/r",
1388        });
1389        let req = make_request("CreateStateMachine", &body.to_string());
1390        let err = expect_err(svc.create_state_machine(&req));
1391        assert!(err.to_string().contains("InvalidName"));
1392    }
1393
1394    #[test]
1395    fn create_state_machine_name_too_long() {
1396        let svc = StepFunctionsService::new(make_state());
1397        let long_name = "a".repeat(81);
1398        let body = json!({
1399            "name": long_name,
1400            "definition": VALID_DEF,
1401            "roleArn": "arn:aws:iam::123456789012:role/r",
1402        });
1403        let req = make_request("CreateStateMachine", &body.to_string());
1404        let err = expect_err(svc.create_state_machine(&req));
1405        assert!(err.to_string().contains("InvalidName"));
1406    }
1407
1408    // ── DescribeStateMachine ──
1409
1410    #[test]
1411    fn describe_state_machine_found() {
1412        let svc = StepFunctionsService::new(make_state());
1413        let arn = create_sm(&svc, "desc-sm");
1414
1415        let req = make_request(
1416            "DescribeStateMachine",
1417            &json!({"stateMachineArn": arn}).to_string(),
1418        );
1419        let resp = svc.describe_state_machine(&req).unwrap();
1420        let b = body_json(&resp);
1421        assert_eq!(b["name"], "desc-sm");
1422        assert_eq!(b["status"], "ACTIVE");
1423        assert!(b["definition"].as_str().is_some());
1424    }
1425
1426    #[test]
1427    fn describe_state_machine_not_found() {
1428        let svc = StepFunctionsService::new(make_state());
1429        let req = make_request(
1430            "DescribeStateMachine",
1431            &json!({"stateMachineArn": "arn:aws:states:us-east-1:123456789012:stateMachine:nope"})
1432                .to_string(),
1433        );
1434        let err = expect_err(svc.describe_state_machine(&req));
1435        assert!(err.to_string().contains("StateMachineDoesNotExist"));
1436    }
1437
1438    // ── ListStateMachines ──
1439
1440    #[test]
1441    fn list_state_machines_empty() {
1442        let svc = StepFunctionsService::new(make_state());
1443        let req = make_request("ListStateMachines", "{}");
1444        let resp = svc.list_state_machines(&req).unwrap();
1445        let b = body_json(&resp);
1446        assert!(b["stateMachines"].as_array().unwrap().is_empty());
1447    }
1448
1449    #[test]
1450    fn list_state_machines_returns_created() {
1451        let svc = StepFunctionsService::new(make_state());
1452        create_sm(&svc, "sm-1");
1453        create_sm(&svc, "sm-2");
1454
1455        let req = make_request("ListStateMachines", "{}");
1456        let resp = svc.list_state_machines(&req).unwrap();
1457        let b = body_json(&resp);
1458        assert_eq!(b["stateMachines"].as_array().unwrap().len(), 2);
1459    }
1460
1461    // ── DeleteStateMachine ──
1462
1463    #[test]
1464    fn delete_state_machine() {
1465        let svc = StepFunctionsService::new(make_state());
1466        let arn = create_sm(&svc, "del-sm");
1467
1468        let req = make_request(
1469            "DeleteStateMachine",
1470            &json!({"stateMachineArn": arn}).to_string(),
1471        );
1472        svc.delete_state_machine(&req).unwrap();
1473
1474        // Describe should fail
1475        let req = make_request(
1476            "DescribeStateMachine",
1477            &json!({"stateMachineArn": arn}).to_string(),
1478        );
1479        assert!(svc.describe_state_machine(&req).is_err());
1480    }
1481
1482    #[test]
1483    fn delete_state_machine_nonexistent_succeeds() {
1484        let svc = StepFunctionsService::new(make_state());
1485        let req = make_request(
1486            "DeleteStateMachine",
1487            &json!({"stateMachineArn": "arn:aws:states:us-east-1:123456789012:stateMachine:nope"})
1488                .to_string(),
1489        );
1490        // AWS returns success even for nonexistent
1491        svc.delete_state_machine(&req).unwrap();
1492    }
1493
1494    // ── UpdateStateMachine ──
1495
1496    #[test]
1497    fn update_state_machine() {
1498        let svc = StepFunctionsService::new(make_state());
1499        let arn = create_sm(&svc, "upd-sm");
1500
1501        let new_def = r#"{"StartAt":"NewPass","States":{"NewPass":{"Type":"Pass","End":true}}}"#;
1502        let body = json!({
1503            "stateMachineArn": arn,
1504            "definition": new_def,
1505            "description": "updated",
1506        });
1507        let req = make_request("UpdateStateMachine", &body.to_string());
1508        let resp = svc.update_state_machine(&req).unwrap();
1509        let b = body_json(&resp);
1510        assert!(b["updateDate"].as_f64().is_some());
1511
1512        // Verify
1513        let req = make_request(
1514            "DescribeStateMachine",
1515            &json!({"stateMachineArn": arn}).to_string(),
1516        );
1517        let resp = svc.describe_state_machine(&req).unwrap();
1518        let b = body_json(&resp);
1519        assert!(b["definition"].as_str().unwrap().contains("NewPass"));
1520        assert_eq!(b["description"], "updated");
1521    }
1522
1523    #[test]
1524    fn update_state_machine_not_found() {
1525        let svc = StepFunctionsService::new(make_state());
1526        let body = json!({
1527            "stateMachineArn": "arn:aws:states:us-east-1:123456789012:stateMachine:nope",
1528            "definition": VALID_DEF,
1529        });
1530        let req = make_request("UpdateStateMachine", &body.to_string());
1531        let err = expect_err(svc.update_state_machine(&req));
1532        assert!(err.to_string().contains("StateMachineDoesNotExist"));
1533    }
1534
1535    // ── StartExecution ──
1536
1537    #[tokio::test]
1538    async fn start_execution_basic() {
1539        let svc = StepFunctionsService::new(make_state());
1540        let arn = create_sm(&svc, "exec-sm");
1541
1542        let body = json!({
1543            "stateMachineArn": arn,
1544            "input": r#"{"key":"value"}"#,
1545        });
1546        let req = make_request("StartExecution", &body.to_string());
1547        let resp = svc.start_execution(&req).unwrap();
1548        let b = body_json(&resp);
1549        assert!(b["executionArn"].as_str().is_some());
1550        assert!(b["startDate"].as_f64().is_some());
1551    }
1552
1553    #[tokio::test]
1554    async fn start_execution_with_name() {
1555        let svc = StepFunctionsService::new(make_state());
1556        let arn = create_sm(&svc, "named-exec");
1557
1558        let body = json!({
1559            "stateMachineArn": arn,
1560            "name": "my-execution",
1561        });
1562        let req = make_request("StartExecution", &body.to_string());
1563        let resp = svc.start_execution(&req).unwrap();
1564        let b = body_json(&resp);
1565        assert!(b["executionArn"].as_str().unwrap().contains("my-execution"));
1566    }
1567
1568    #[tokio::test]
1569    async fn start_execution_sm_not_found() {
1570        let svc = StepFunctionsService::new(make_state());
1571        let body = json!({
1572            "stateMachineArn": "arn:aws:states:us-east-1:123456789012:stateMachine:nope",
1573        });
1574        let req = make_request("StartExecution", &body.to_string());
1575        let err = expect_err(svc.start_execution(&req));
1576        assert!(err.to_string().contains("StateMachineDoesNotExist"));
1577    }
1578
1579    #[tokio::test]
1580    async fn start_execution_invalid_input() {
1581        let svc = StepFunctionsService::new(make_state());
1582        let arn = create_sm(&svc, "bad-input");
1583
1584        let body = json!({
1585            "stateMachineArn": arn,
1586            "input": "not json",
1587        });
1588        let req = make_request("StartExecution", &body.to_string());
1589        let err = expect_err(svc.start_execution(&req));
1590        assert!(err.to_string().contains("InvalidExecutionInput"));
1591    }
1592
1593    #[tokio::test]
1594    async fn start_execution_same_name_same_input_is_idempotent() {
1595        let svc = StepFunctionsService::new(make_state());
1596        let arn = create_sm(&svc, "dup-exec");
1597
1598        let body = json!({
1599            "stateMachineArn": arn,
1600            "name": "same-name",
1601            "input": "{\"a\":1}",
1602        });
1603        let req = make_request("StartExecution", &body.to_string());
1604        let first = body_json(&svc.start_execution(&req).unwrap());
1605
1606        // Same name AND same input -> 200 with the existing executionArn.
1607        let req = make_request("StartExecution", &body.to_string());
1608        let second = body_json(&svc.start_execution(&req).unwrap());
1609        assert_eq!(first["executionArn"], second["executionArn"]);
1610        assert_eq!(first["startDate"], second["startDate"]);
1611    }
1612
1613    #[tokio::test]
1614    async fn start_execution_same_name_different_input_conflicts() {
1615        let svc = StepFunctionsService::new(make_state());
1616        let arn = create_sm(&svc, "dup-exec-diff");
1617
1618        let req = make_request(
1619            "StartExecution",
1620            &json!({
1621                "stateMachineArn": arn,
1622                "name": "same-name",
1623                "input": "{\"a\":1}",
1624            })
1625            .to_string(),
1626        );
1627        svc.start_execution(&req).unwrap();
1628
1629        // Same name, DIFFERENT input -> 400 ExecutionAlreadyExists.
1630        let req = make_request(
1631            "StartExecution",
1632            &json!({
1633                "stateMachineArn": arn,
1634                "name": "same-name",
1635                "input": "{\"a\":2}",
1636            })
1637            .to_string(),
1638        );
1639        let err = expect_err(svc.start_execution(&req));
1640        assert!(err.to_string().contains("ExecutionAlreadyExists"));
1641    }
1642
1643    #[tokio::test]
1644    async fn start_execution_express_name_collision_never_idempotent() {
1645        let svc = StepFunctionsService::new(make_state());
1646        let arn = create_express_sm(&svc, "dup-exec-express");
1647
1648        let body = json!({
1649            "stateMachineArn": arn,
1650            "name": "same-name",
1651            "input": "{\"a\":1}",
1652        });
1653        let req = make_request("StartExecution", &body.to_string());
1654        svc.start_execution(&req).unwrap();
1655
1656        // EXPRESS has no idempotency: even an identical re-issue conflicts.
1657        let req = make_request("StartExecution", &body.to_string());
1658        let err = expect_err(svc.start_execution(&req));
1659        assert!(err.to_string().contains("ExecutionAlreadyExists"));
1660    }
1661
1662    // ── DescribeExecution ──
1663
1664    #[tokio::test]
1665    async fn describe_execution_found() {
1666        let svc = StepFunctionsService::new(make_state());
1667        let sm_arn = create_sm(&svc, "desc-exec");
1668
1669        let body = json!({"stateMachineArn": sm_arn, "name": "e1"});
1670        let req = make_request("StartExecution", &body.to_string());
1671        let resp = svc.start_execution(&req).unwrap();
1672        let exec_arn = body_json(&resp)["executionArn"]
1673            .as_str()
1674            .unwrap()
1675            .to_string();
1676
1677        let req = make_request(
1678            "DescribeExecution",
1679            &json!({"executionArn": exec_arn}).to_string(),
1680        );
1681        let resp = svc.describe_execution(&req).unwrap();
1682        let b = body_json(&resp);
1683        assert_eq!(b["name"], "e1");
1684        assert_eq!(b["status"], "RUNNING");
1685    }
1686
1687    #[tokio::test]
1688    async fn describe_execution_not_found() {
1689        let svc = StepFunctionsService::new(make_state());
1690        let req = make_request(
1691            "DescribeExecution",
1692            &json!({"executionArn": "arn:aws:states:us-east-1:123456789012:execution:sm:nope"})
1693                .to_string(),
1694        );
1695        let err = expect_err(svc.describe_execution(&req));
1696        assert!(err.to_string().contains("ExecutionDoesNotExist"));
1697    }
1698
1699    // ── StopExecution ──
1700
1701    #[tokio::test]
1702    async fn stop_execution() {
1703        let svc = StepFunctionsService::new(make_state());
1704        let sm_arn = create_sm(&svc, "stop-sm");
1705
1706        let body = json!({"stateMachineArn": sm_arn, "name": "stop-e"});
1707        let req = make_request("StartExecution", &body.to_string());
1708        let resp = svc.start_execution(&req).unwrap();
1709        let exec_arn = body_json(&resp)["executionArn"]
1710            .as_str()
1711            .unwrap()
1712            .to_string();
1713
1714        let body = json!({
1715            "executionArn": exec_arn,
1716            "error": "UserAborted",
1717            "cause": "test stop",
1718        });
1719        let req = make_request("StopExecution", &body.to_string());
1720        let resp = svc.stop_execution(&req).unwrap();
1721        let b = body_json(&resp);
1722        assert!(b["stopDate"].as_f64().is_some());
1723
1724        // Verify aborted
1725        let req = make_request(
1726            "DescribeExecution",
1727            &json!({"executionArn": exec_arn}).to_string(),
1728        );
1729        let resp = svc.describe_execution(&req).unwrap();
1730        let b = body_json(&resp);
1731        assert_eq!(b["status"], "ABORTED");
1732        assert_eq!(b["error"], "UserAborted");
1733    }
1734
1735    #[tokio::test]
1736    async fn redrive_execution_reruns_to_terminal() {
1737        let svc = StepFunctionsService::new(make_state());
1738        let sm_arn = create_sm(&svc, "redrive-sm");
1739
1740        let body = json!({"stateMachineArn": sm_arn, "name": "redrive-e"});
1741        let req = make_request("StartExecution", &body.to_string());
1742        let resp = svc.start_execution(&req).unwrap();
1743        let exec_arn = body_json(&resp)["executionArn"]
1744            .as_str()
1745            .unwrap()
1746            .to_string();
1747
1748        // Stop before the spawned interpreter runs -> terminal ABORTED.
1749        let req = make_request(
1750            "StopExecution",
1751            &json!({"executionArn": exec_arn, "error": "UserAborted", "cause": "stop"}).to_string(),
1752        );
1753        svc.stop_execution(&req).unwrap();
1754
1755        // Redrive: must reset to RUNNING and re-spawn the interpreter.
1756        let req = make_request(
1757            "RedriveExecution",
1758            &json!({"executionArn": exec_arn}).to_string(),
1759        );
1760        let resp = svc.redrive_execution(&req).unwrap();
1761        assert!(body_json(&resp)["redriveDate"].as_i64().is_some());
1762
1763        // The redriven Pass-state execution must reach a terminal state
1764        // (SUCCEEDED) instead of hanging RUNNING forever.
1765        let mut status = String::new();
1766        for _ in 0..100 {
1767            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
1768            let req = make_request(
1769                "DescribeExecution",
1770                &json!({"executionArn": exec_arn}).to_string(),
1771            );
1772            let b = body_json(&svc.describe_execution(&req).unwrap());
1773            status = b["status"].as_str().unwrap().to_string();
1774            if status != "RUNNING" {
1775                break;
1776            }
1777        }
1778        assert_eq!(
1779            status, "SUCCEEDED",
1780            "redriven execution must run to completion"
1781        );
1782    }
1783
1784    #[tokio::test]
1785    async fn redrive_execution_running_rejected() {
1786        let svc = StepFunctionsService::new(make_state());
1787        let sm_arn = create_sm(&svc, "redrive-running-sm");
1788        let body = json!({"stateMachineArn": sm_arn, "name": "still-running"});
1789        let req = make_request("StartExecution", &body.to_string());
1790        let exec_arn = body_json(&svc.start_execution(&req).unwrap())["executionArn"]
1791            .as_str()
1792            .unwrap()
1793            .to_string();
1794
1795        // A still-RUNNING execution is not redrivable (it already has a driver).
1796        let req = make_request(
1797            "RedriveExecution",
1798            &json!({"executionArn": exec_arn}).to_string(),
1799        );
1800        let err = expect_err(svc.redrive_execution(&req));
1801        assert!(err.to_string().contains("ExecutionNotRedrivable"));
1802    }
1803
1804    #[tokio::test]
1805    async fn stop_execution_not_found() {
1806        let svc = StepFunctionsService::new(make_state());
1807        let req = make_request(
1808            "StopExecution",
1809            &json!({"executionArn": "arn:aws:states:us-east-1:123456789012:execution:sm:nope"})
1810                .to_string(),
1811        );
1812        let err = expect_err(svc.stop_execution(&req));
1813        assert!(err.to_string().contains("ExecutionDoesNotExist"));
1814    }
1815
1816    // ── ListExecutions ──
1817
1818    #[tokio::test]
1819    async fn list_executions() {
1820        let svc = StepFunctionsService::new(make_state());
1821        let sm_arn = create_sm(&svc, "list-exec");
1822
1823        for i in 0..3 {
1824            let body = json!({"stateMachineArn": sm_arn, "name": format!("e{i}")});
1825            let req = make_request("StartExecution", &body.to_string());
1826            svc.start_execution(&req).unwrap();
1827        }
1828
1829        let req = make_request(
1830            "ListExecutions",
1831            &json!({"stateMachineArn": sm_arn}).to_string(),
1832        );
1833        let resp = svc.list_executions(&req).unwrap();
1834        let b = body_json(&resp);
1835        assert_eq!(b["executions"].as_array().unwrap().len(), 3);
1836    }
1837
1838    #[tokio::test]
1839    async fn list_executions_sm_not_found() {
1840        let svc = StepFunctionsService::new(make_state());
1841        let req = make_request(
1842            "ListExecutions",
1843            &json!({"stateMachineArn": "arn:aws:states:us-east-1:123456789012:stateMachine:nope"})
1844                .to_string(),
1845        );
1846        let err = expect_err(svc.list_executions(&req));
1847        assert!(err.to_string().contains("StateMachineDoesNotExist"));
1848    }
1849
1850    // ── GetExecutionHistory ──
1851
1852    #[tokio::test]
1853    async fn get_execution_history_not_found() {
1854        let svc = StepFunctionsService::new(make_state());
1855        let req = make_request(
1856            "GetExecutionHistory",
1857            &json!({"executionArn": "arn:aws:states:us-east-1:123456789012:execution:sm:nope"})
1858                .to_string(),
1859        );
1860        let err = expect_err(svc.get_execution_history(&req));
1861        assert!(err.to_string().contains("ExecutionDoesNotExist"));
1862    }
1863
1864    // ── DescribeStateMachineForExecution ──
1865
1866    #[tokio::test]
1867    async fn describe_sm_for_execution() {
1868        let svc = StepFunctionsService::new(make_state());
1869        let sm_arn = create_sm(&svc, "sm-for-exec");
1870
1871        let body = json!({"stateMachineArn": sm_arn, "name": "e1"});
1872        let req = make_request("StartExecution", &body.to_string());
1873        let resp = svc.start_execution(&req).unwrap();
1874        let exec_arn = body_json(&resp)["executionArn"]
1875            .as_str()
1876            .unwrap()
1877            .to_string();
1878
1879        let req = make_request(
1880            "DescribeStateMachineForExecution",
1881            &json!({"executionArn": exec_arn}).to_string(),
1882        );
1883        let resp = svc.describe_state_machine_for_execution(&req).unwrap();
1884        let b = body_json(&resp);
1885        assert_eq!(b["name"], "sm-for-exec");
1886    }
1887
1888    // ── Tags ──
1889
1890    #[test]
1891    fn tag_untag_list_tags() {
1892        let svc = StepFunctionsService::new(make_state());
1893        let arn = create_sm(&svc, "tagged-sm");
1894
1895        // Tag
1896        let body = json!({
1897            "resourceArn": arn,
1898            "tags": [{"key": "env", "value": "prod"}],
1899        });
1900        let req = make_request("TagResource", &body.to_string());
1901        svc.tag_resource(&req).unwrap();
1902
1903        // List
1904        let req = make_request(
1905            "ListTagsForResource",
1906            &json!({"resourceArn": arn}).to_string(),
1907        );
1908        let resp = svc.list_tags_for_resource(&req).unwrap();
1909        let b = body_json(&resp);
1910        let tags = b["tags"].as_array().unwrap();
1911        assert_eq!(tags.len(), 1);
1912        assert_eq!(tags[0]["key"], "env");
1913
1914        // Untag
1915        let body = json!({
1916            "resourceArn": arn,
1917            "tagKeys": ["env"],
1918        });
1919        let req = make_request("UntagResource", &body.to_string());
1920        svc.untag_resource(&req).unwrap();
1921
1922        // Verify empty
1923        let req = make_request(
1924            "ListTagsForResource",
1925            &json!({"resourceArn": arn}).to_string(),
1926        );
1927        let resp = svc.list_tags_for_resource(&req).unwrap();
1928        let b = body_json(&resp);
1929        assert!(b["tags"].as_array().unwrap().is_empty());
1930    }
1931
1932    #[test]
1933    fn tag_resource_not_found() {
1934        let svc = StepFunctionsService::new(make_state());
1935        let body = json!({
1936            "resourceArn": "arn:aws:states:us-east-1:123456789012:stateMachine:nope",
1937            "tags": [{"key": "k", "value": "v"}],
1938        });
1939        let req = make_request("TagResource", &body.to_string());
1940        let err = expect_err(svc.tag_resource(&req));
1941        assert!(err.to_string().contains("ResourceNotFound"));
1942    }
1943
1944    // ── Helper function tests ──
1945
1946    #[test]
1947    fn test_validate_name() {
1948        assert!(validate_name("valid-name").is_ok());
1949        assert!(validate_name("under_score").is_ok());
1950        assert!(validate_name("").is_err());
1951        assert!(validate_name("has spaces").is_err());
1952        assert!(validate_name(&"a".repeat(81)).is_err());
1953    }
1954
1955    #[test]
1956    fn test_validate_definition() {
1957        assert!(validate_definition(VALID_DEF).is_ok());
1958        assert!(validate_definition("not json").is_err());
1959        assert!(validate_definition(r#"{"States":{}}"#).is_err()); // missing StartAt
1960        assert!(validate_definition(r#"{"StartAt":"S"}"#).is_err()); // missing States
1961    }
1962
1963    #[test]
1964    fn test_validate_definition_rejects_malformed_paths() {
1965        // Unterminated bracket in InputPath.
1966        let def =
1967            r#"{"StartAt":"P","States":{"P":{"Type":"Pass","InputPath":"$.arr[","End":true}}}"#;
1968        assert!(validate_definition(def).is_err());
1969
1970        // Multibyte char where the close bracket would be, in OutputPath.
1971        let def =
1972            "{\"StartAt\":\"P\",\"States\":{\"P\":{\"Type\":\"Pass\",\"OutputPath\":\"$.x[\u{00e9}\",\"End\":true}}}";
1973        assert!(validate_definition(def).is_err());
1974
1975        // Malformed Choice Variable.
1976        let def = r#"{"StartAt":"C","States":{"C":{"Type":"Choice","Choices":[{"Variable":"$.n[","NumericEquals":1,"Next":"P"}]},"P":{"Type":"Pass","End":true}}}"#;
1977        assert!(validate_definition(def).is_err());
1978
1979        // Path not rooted at $.
1980        let def =
1981            r#"{"StartAt":"P","States":{"P":{"Type":"Pass","InputPath":"foo.bar","End":true}}}"#;
1982        assert!(validate_definition(def).is_err());
1983
1984        // Empty index brackets.
1985        let def =
1986            r#"{"StartAt":"P","States":{"P":{"Type":"Pass","ResultPath":"$.x[]","End":true}}}"#;
1987        assert!(validate_definition(def).is_err());
1988    }
1989
1990    #[test]
1991    fn test_validate_definition_accepts_well_formed_paths() {
1992        // Valid reference paths, the literal "null" for Input/OutputPath, and
1993        // nested Choice combinators must all be accepted.
1994        let def = r#"{"StartAt":"P","States":{
1995            "P":{"Type":"Pass","InputPath":"$.a.b[0].c","OutputPath":"$","ResultPath":"$.out","Next":"C"},
1996            "C":{"Type":"Choice","Choices":[
1997                {"And":[{"Variable":"$.items[2]","NumericEquals":1},{"Variable":"$.flag","BooleanEquals":true}],"Next":"S"}
1998            ],"Default":"S"},
1999            "S":{"Type":"Succeed","InputPath":"null"}
2000        }}"#;
2001        assert!(validate_definition(def).is_ok());
2002    }
2003
2004    // M5: malformed paths nested inside Parallel branches and Map processors
2005    // must be rejected.
2006    #[test]
2007    fn test_validate_definition_recurses_into_parallel_and_map() {
2008        let par = r#"{"StartAt":"Par","States":{"Par":{"Type":"Parallel","End":true,
2009            "Branches":[{"StartAt":"I","States":{"I":{"Type":"Pass","InputPath":"nope","End":true}}}]}}}"#;
2010        assert!(validate_definition(par).is_err());
2011
2012        let map = r#"{"StartAt":"M","States":{"M":{"Type":"Map","End":true,
2013            "ItemProcessor":{"StartAt":"E","States":{"E":{"Type":"Pass","OutputPath":"nope","End":true}}}}}}"#;
2014        assert!(validate_definition(map).is_err());
2015
2016        // Legacy inline Map uses `Iterator`.
2017        let iter = r#"{"StartAt":"M","States":{"M":{"Type":"Map","End":true,
2018            "Iterator":{"StartAt":"E","States":{"E":{"Type":"Pass","ResultPath":"$.x[]","End":true}}}}}}"#;
2019        assert!(validate_definition(iter).is_err());
2020
2021        // A well-formed Parallel/Map still validates.
2022        let ok = r#"{"StartAt":"M","States":{"M":{"Type":"Map","ItemsPath":"$.items","End":true,
2023            "ItemProcessor":{"StartAt":"E","States":{"E":{"Type":"Pass","InputPath":"$.a","End":true}}}}}}"#;
2024        assert!(validate_definition(ok).is_ok());
2025    }
2026
2027    // L7: `.$` payload-template keys must carry a JSONPath/intrinsic string.
2028    #[test]
2029    fn test_validate_definition_payload_template_dollar_keys() {
2030        // Bare literal value.
2031        let lit = r#"{"StartAt":"P","States":{"P":{"Type":"Pass",
2032            "Parameters":{"v.$":"just text"},"End":true}}}"#;
2033        assert!(validate_definition(lit).is_err());
2034
2035        // Non-string value.
2036        let num = r#"{"StartAt":"P","States":{"P":{"Type":"Pass",
2037            "Parameters":{"v.$":42},"End":true}}}"#;
2038        assert!(validate_definition(num).is_err());
2039
2040        // Valid: JSONPath reference, context-object ref, and intrinsic.
2041        let ok = r#"{"StartAt":"P","States":{"P":{"Type":"Pass","Parameters":{
2042            "a.$":"$.input","b.$":"$$.Execution.Id","c.$":"States.Format('{}',$.n)",
2043            "nested":{"d.$":"$.x"},"plain":"literal-ok"},"End":true}}}"#;
2044        assert!(validate_definition(ok).is_ok());
2045
2046        // A bad `.$` nested inside an array under a plain key is also caught.
2047        let arr = r#"{"StartAt":"P","States":{"P":{"Type":"Pass",
2048            "ResultSelector":{"items":[{"bad.$":"literal"}]},"End":true}}}"#;
2049        assert!(validate_definition(arr).is_err());
2050    }
2051
2052    #[test]
2053    fn test_is_valid_reference_path() {
2054        assert!(is_valid_reference_path("$"));
2055        assert!(is_valid_reference_path("$.foo"));
2056        assert!(is_valid_reference_path("$.foo.bar[3].baz"));
2057        assert!(is_valid_reference_path("$[0]"));
2058        assert!(!is_valid_reference_path("$.arr["));
2059        assert!(!is_valid_reference_path("$.x[\u{00e9}"));
2060        assert!(!is_valid_reference_path("$.x[]"));
2061        assert!(!is_valid_reference_path("$.x[abc]"));
2062        assert!(!is_valid_reference_path("foo.bar"));
2063        assert!(!is_valid_reference_path(""));
2064    }
2065
2066    #[test]
2067    fn test_validate_arn() {
2068        assert!(validate_arn("arn:aws:states:us-east-1:123:sm:test").is_ok());
2069        assert!(validate_arn("not-an-arn").is_err());
2070    }
2071
2072    #[test]
2073    fn test_camel_to_details_key() {
2074        // All *StateEntered / *StateExited types collapse to one key each.
2075        assert_eq!(camel_to_details_key("PassStateEntered"), "stateEntered");
2076        assert_eq!(camel_to_details_key("TaskStateEntered"), "stateEntered");
2077        assert_eq!(camel_to_details_key("ChoiceStateExited"), "stateExited");
2078        assert_eq!(camel_to_details_key("MapStateExited"), "stateExited");
2079        // Other event types keep first-char-lowercased prefix.
2080        assert_eq!(camel_to_details_key("TaskScheduled"), "taskScheduled");
2081        assert_eq!(camel_to_details_key("ExecutionStarted"), "executionStarted");
2082        assert_eq!(camel_to_details_key(""), "");
2083    }
2084
2085    #[test]
2086    fn test_is_mutating_action() {
2087        assert!(is_mutating_action("CreateStateMachine"));
2088        assert!(is_mutating_action("StartExecution"));
2089        assert!(!is_mutating_action("DescribeStateMachine"));
2090        assert!(!is_mutating_action("ListStateMachines"));
2091    }
2092
2093    // ── StartSyncExecution ──
2094
2095    fn create_express_sm(svc: &StepFunctionsService, name: &str) -> String {
2096        let body = json!({
2097            "name": name,
2098            "definition": VALID_DEF,
2099            "roleArn": "arn:aws:iam::123456789012:role/test",
2100            "type": "EXPRESS",
2101        });
2102        let req = make_request("CreateStateMachine", &body.to_string());
2103        let resp = svc.create_state_machine(&req).unwrap();
2104        let b = body_json(&resp);
2105        b["stateMachineArn"].as_str().unwrap().to_string()
2106    }
2107
2108    #[tokio::test]
2109    async fn start_sync_execution_basic() {
2110        let svc = StepFunctionsService::new(make_state());
2111        let arn = create_express_sm(&svc, "sync-sm");
2112
2113        let body = json!({
2114            "stateMachineArn": arn,
2115            "input": r#"{"key":"value"}"#,
2116        });
2117        let req = make_request("StartSyncExecution", &body.to_string());
2118        let resp = svc.start_sync_execution(&req).await.unwrap();
2119        let b = body_json(&resp);
2120        assert!(b["executionArn"]
2121            .as_str()
2122            .unwrap()
2123            .contains("express:sync-sm"));
2124        assert_eq!(b["stateMachineArn"], arn);
2125        assert_eq!(b["status"], "SUCCEEDED");
2126        assert!(b["startDate"].as_i64().is_some());
2127        assert!(b["stopDate"].as_i64().is_some());
2128        assert!(b["output"].as_str().is_some());
2129        assert!(b["billingDetails"]["billedDurationInMilliseconds"]
2130            .as_i64()
2131            .is_some());
2132    }
2133
2134    #[tokio::test]
2135    async fn start_sync_execution_not_express() {
2136        let svc = StepFunctionsService::new(make_state());
2137        let arn = create_sm(&svc, "std-sm");
2138
2139        let body = json!({"stateMachineArn": arn});
2140        let req = make_request("StartSyncExecution", &body.to_string());
2141        let err = expect_err(svc.start_sync_execution(&req).await);
2142        assert!(err.to_string().contains("StateMachineTypeNotSupported"));
2143    }
2144
2145    #[tokio::test]
2146    async fn start_sync_execution_sm_not_found() {
2147        let svc = StepFunctionsService::new(make_state());
2148        let body = json!({
2149            "stateMachineArn": "arn:aws:states:us-east-1:123456789012:stateMachine:nope",
2150        });
2151        let req = make_request("StartSyncExecution", &body.to_string());
2152        let err = expect_err(svc.start_sync_execution(&req).await);
2153        assert!(err.to_string().contains("StateMachineDoesNotExist"));
2154    }
2155
2156    #[tokio::test]
2157    async fn start_sync_execution_records_introspection_fields() {
2158        let svc = StepFunctionsService::new(make_state());
2159        let arn = create_express_sm(&svc, "sync-introspect");
2160
2161        let body = json!({"stateMachineArn": arn, "input": "{}"});
2162        let req = make_request("StartSyncExecution", &body.to_string());
2163        let resp = svc.start_sync_execution(&req).await.unwrap();
2164        let b = body_json(&resp);
2165        let exec_arn = b["executionArn"].as_str().unwrap().to_string();
2166
2167        let accounts = svc.state.read();
2168        let state = accounts.get("123456789012").unwrap();
2169        let stored = state
2170            .executions
2171            .get(&exec_arn)
2172            .expect("sync execution should be persisted for introspection");
2173        assert!(stored.is_sync, "sync executions must be marked is_sync");
2174        assert_eq!(stored.billed_memory_mb, Some(64));
2175        assert!(
2176            stored.billed_duration_ms.is_some(),
2177            "billed_duration_ms must be populated after sync run"
2178        );
2179        assert!(
2180            stored.parent_execution_arn.is_none(),
2181            "top-level sync execution has no parent"
2182        );
2183    }
2184
2185    #[tokio::test]
2186    async fn start_sync_execution_invalid_input() {
2187        let svc = StepFunctionsService::new(make_state());
2188        let arn = create_express_sm(&svc, "bad-input-sync");
2189
2190        let body = json!({
2191            "stateMachineArn": arn,
2192            "input": "not json",
2193        });
2194        let req = make_request("StartSyncExecution", &body.to_string());
2195        let err = expect_err(svc.start_sync_execution(&req).await);
2196        assert!(err.to_string().contains("InvalidExecutionInput"));
2197    }
2198
2199    /// No snapshot store (memory mode) -> no persist hook for the CFN provisioner.
2200    #[test]
2201    fn snapshot_hook_is_none_without_store() {
2202        let svc = StepFunctionsService::new(make_state());
2203        assert!(svc.snapshot_hook().is_none());
2204    }
2205
2206    /// With a store, the hook is present and invoking it runs the whole-state
2207    /// persist path the CloudFormation provisioner uses after mutating Step
2208    /// Functions state directly.
2209    #[tokio::test]
2210    async fn snapshot_hook_fires_with_store() {
2211        let store: Arc<dyn fakecloud_persistence::SnapshotStore> =
2212            Arc::new(fakecloud_persistence::MemorySnapshotStore::new());
2213        let svc = StepFunctionsService::new(make_state()).with_snapshot_store(store);
2214        let hook = svc
2215            .snapshot_hook()
2216            .expect("hook present when a store is set");
2217        hook().await;
2218    }
2219
2220    fn make_execution(arn: &str, status: ExecutionStatus) -> Execution {
2221        Execution {
2222            execution_arn: arn.to_string(),
2223            state_machine_arn: "arn:aws:states:us-east-1:123456789012:stateMachine:sm".to_string(),
2224            state_machine_name: "sm".to_string(),
2225            name: arn.to_string(),
2226            status,
2227            input: None,
2228            output: None,
2229            start_date: Utc::now(),
2230            stop_date: None,
2231            error: None,
2232            cause: None,
2233            history_events: vec![],
2234            parent_execution_arn: None,
2235            is_sync: false,
2236            billed_duration_ms: None,
2237            billed_memory_mb: None,
2238        }
2239    }
2240
2241    #[test]
2242    fn reconcile_aborts_running_executions_on_restart() {
2243        // After a restart a RUNNING execution has no interpreter driving it, so
2244        // it must be aborted rather than left RUNNING forever (0.A2). A
2245        // completed execution is untouched.
2246        let state = make_state();
2247        {
2248            let mut accounts = state.write();
2249            let s = accounts.get_or_create("123456789012");
2250            s.executions.insert(
2251                "running".into(),
2252                make_execution("running", ExecutionStatus::Running),
2253            );
2254            s.executions.insert(
2255                "done".into(),
2256                make_execution("done", ExecutionStatus::Succeeded),
2257            );
2258        }
2259
2260        let n = reconcile_interrupted_executions(&state);
2261        assert_eq!(n, 1, "only the RUNNING execution is reconciled");
2262
2263        let accounts = state.read();
2264        let s = accounts.get("123456789012").unwrap();
2265        let running = &s.executions["running"];
2266        assert_eq!(running.status, ExecutionStatus::Aborted);
2267        assert!(running.stop_date.is_some());
2268        assert_eq!(running.error.as_deref(), Some("Fakecloud.Restart"));
2269        assert_eq!(s.executions["done"].status, ExecutionStatus::Succeeded);
2270    }
2271
2272    // ── Distributed Map -> MapRun population (bug-hunt read-shape) ──
2273
2274    #[tokio::test]
2275    async fn distributed_map_populates_map_run() {
2276        let state = make_state();
2277        let svc = StepFunctionsService::new(state.clone());
2278        let execution_arn =
2279            "arn:aws:states:us-east-1:123456789012:execution:dist-sm:exec-1".to_string();
2280
2281        let def = json!({
2282            "StartAt": "M",
2283            "States": {
2284                "M": {
2285                    "Type": "Map",
2286                    "ItemsPath": "$.items",
2287                    "ItemProcessor": {
2288                        "ProcessorConfig": { "Mode": "DISTRIBUTED", "ExecutionType": "STANDARD" },
2289                        "StartAt": "Item",
2290                        "States": { "Item": { "Type": "Pass", "End": true } }
2291                    },
2292                    "End": true
2293                }
2294            }
2295        });
2296
2297        interpreter::execute_state_machine(
2298            state.clone(),
2299            execution_arn.clone(),
2300            def.to_string(),
2301            Some(r#"{"items":[1,2,3]}"#.to_string()),
2302            None,
2303            None,
2304            None,
2305            None,
2306        )
2307        .await;
2308
2309        // ListMapRuns(executionArn) surfaces the newly created MapRun.
2310        let req = make_request(
2311            "ListMapRuns",
2312            &json!({ "executionArn": execution_arn }).to_string(),
2313        );
2314        let listed = body_json(&svc.list_map_runs(&req).unwrap());
2315        let runs = listed["mapRuns"].as_array().unwrap();
2316        assert_eq!(
2317            runs.len(),
2318            1,
2319            "distributed map must create exactly one MapRun"
2320        );
2321        let map_run_arn = runs[0]["mapRunArn"].as_str().unwrap().to_string();
2322        assert!(map_run_arn.contains(":mapRun:"));
2323        assert_eq!(runs[0]["executionArn"], execution_arn);
2324
2325        // DescribeMapRun(mapRunArn) returns the record with real counts.
2326        let req = make_request(
2327            "DescribeMapRun",
2328            &json!({ "mapRunArn": map_run_arn }).to_string(),
2329        );
2330        let mr = body_json(&svc.describe_map_run(&req).unwrap());
2331        assert_eq!(mr["status"], "SUCCEEDED");
2332        assert_eq!(mr["itemCounts"]["total"], 3);
2333        assert_eq!(mr["itemCounts"]["succeeded"], 3);
2334        assert_eq!(mr["itemCounts"]["failed"], 0);
2335        assert_eq!(mr["executionCounts"]["succeeded"], 3);
2336    }
2337
2338    #[tokio::test]
2339    async fn inline_map_does_not_create_map_run() {
2340        let state = make_state();
2341        let svc = StepFunctionsService::new(state.clone());
2342        let execution_arn =
2343            "arn:aws:states:us-east-1:123456789012:execution:inline-sm:exec-1".to_string();
2344
2345        // No ProcessorConfig.Mode => inline Map: AWS creates no MapRun.
2346        let def = json!({
2347            "StartAt": "M",
2348            "States": {
2349                "M": {
2350                    "Type": "Map",
2351                    "ItemsPath": "$.items",
2352                    "ItemProcessor": {
2353                        "StartAt": "Item",
2354                        "States": { "Item": { "Type": "Pass", "End": true } }
2355                    },
2356                    "End": true
2357                }
2358            }
2359        });
2360
2361        interpreter::execute_state_machine(
2362            state.clone(),
2363            execution_arn.clone(),
2364            def.to_string(),
2365            Some(r#"{"items":[1,2]}"#.to_string()),
2366            None,
2367            None,
2368            None,
2369            None,
2370        )
2371        .await;
2372
2373        let req = make_request(
2374            "ListMapRuns",
2375            &json!({ "executionArn": execution_arn }).to_string(),
2376        );
2377        let listed = body_json(&svc.list_map_runs(&req).unwrap());
2378        assert!(listed["mapRuns"].as_array().unwrap().is_empty());
2379    }
2380}
2381
2382#[cfg(test)]
2383mod pagination_reject_test {
2384    #[test]
2385    fn paginate_checked_rejects_invalid_token() {
2386        use fakecloud_core::pagination::paginate_checked;
2387        let items: Vec<i32> = (0..5).collect();
2388        assert!(paginate_checked(&items, Some("bad"), 3).is_err());
2389        assert!(paginate_checked(&items, Some("2"), 3).is_ok());
2390    }
2391}