Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

feat: Step Functions Task state service integrations (SQS, SNS, DynamoDB, ECS) (#8)

Mickael Abdealy87e52df0e19f
diff --git a/services/stepfunctions.py b/services/stepfunctions.py
index 74eaadf9..3d05704e 100644
--- a/services/stepfunctions.py
+++ b/services/stepfunctions.py
@@ -699,6 +699,12 @@ def _invoke_resource(resource, input_data):
if func_name:
return _call_lambda(func_name, input_data)
+ # Service integration dispatch
+ clean = resource.replace(".sync", "").replace(".waitForTaskToken", "")
+ for prefix, handler in _SERVICE_DISPATCH.items():
+ if clean.startswith(prefix):
+ return handler(resource, input_data)
+
return input_data
@@ -1220,6 +1226,137 @@ def _parse_ts(v):
return None
+# ===================================================================
+# Service integrations (Task state dispatch)
+# ===================================================================
+
+
+def _invoke_sqs_send_message(resource, input_data):
+ """arn:aws:states:::sqs:sendMessage"""
+ try:
+ from services import sqs
+ except ImportError:
+ logger.warning("sqs module unavailable; returning passthrough")
+ return input_data
+ try:
+ url = input_data.get("QueueUrl", "")
+ result = sqs._act_send_message(input_data, url)
+ return result
+ except sqs._Err as e:
+ raise _ExecutionError(f"SQS.{e.code}", e.message)
+
+
+def _invoke_sns_publish(resource, input_data):
+ """arn:aws:states:::sns:publish"""
+ try:
+ from services import sns
+ except ImportError:
+ logger.warning("sns module unavailable; returning passthrough")
+ return input_data
+ status, _, body = sns._publish(input_data)
+ if status >= 400:
+ raise _ExecutionError(
+ "SNS.PublishFailed",
+ body.decode("utf-8", "replace") if isinstance(body, bytes) else str(body),
+ )
+ decoded = body.decode() if isinstance(body, bytes) else body
+ m = re.search(r"<MessageId>(.+?)</MessageId>", decoded)
+ msg_id = m.group(1) if m else new_uuid()
+ return {"MessageId": msg_id}
+
+
+def _invoke_dynamodb(op_name, input_data):
+ """arn:aws:states:::dynamodb:{putItem,getItem,deleteItem,updateItem}"""
+ try:
+ from services import dynamodb
+ except ImportError:
+ logger.warning("dynamodb module unavailable; returning passthrough")
+ return input_data
+ fn_map = {
+ "putItem": dynamodb._put_item,
+ "getItem": dynamodb._get_item,
+ "deleteItem": dynamodb._delete_item,
+ "updateItem": dynamodb._update_item,
+ }
+ fn = fn_map.get(op_name)
+ if not fn:
+ raise _ExecutionError(
+ "States.Runtime", f"Unsupported DynamoDB operation: {op_name}"
+ )
+ status, _, body = fn(input_data)
+ result = json.loads(body) if body else {}
+ if status >= 400:
+ error_type = result.get("__type", "DynamoDB.AmazonDynamoDBException")
+ raise _ExecutionError(error_type, result.get("message", ""))
+ return result
+
+
+def _invoke_ecs_run_task(resource, input_data):
+ """arn:aws:states:::ecs:runTask[.sync]"""
+ try:
+ from services import ecs
+ except ImportError:
+ logger.warning("ecs module unavailable; returning passthrough")
+ return input_data
+ ecs_data = _pascal_to_camel(input_data)
+ status, _, body = ecs._run_task(ecs_data)
+ result = json.loads(body) if body else {}
+ if status >= 400:
+ raise _ExecutionError("ECS.RunTaskFailed", result.get("message", str(result)))
+
+ is_sync = resource.rstrip("/").endswith(".sync")
+ if is_sync and result.get("tasks"):
+ task_arns = [t["taskArn"] for t in result["tasks"]]
+ cluster = ecs_data.get("cluster", "default")
+ result = _poll_ecs_tasks(cluster, task_arns)
+
+ return result
+
+
+def _poll_ecs_tasks(cluster, task_arns):
+ """Poll DescribeTasks until all tasks are STOPPED (max 10 min).
+
+ Returns the full DescribeTasks result including exit codes — the state
+ machine definition decides how to handle success/failure via Choice or Catch.
+ """
+ from services import ecs
+
+ for _ in range(600):
+ time.sleep(1)
+ status, _, body = ecs._describe_tasks({"cluster": cluster, "tasks": task_arns})
+ result = json.loads(body) if body else {}
+ tasks = result.get("tasks", [])
+ if tasks and all(t.get("lastStatus") == "STOPPED" for t in tasks):
+ return result
+ raise _ExecutionError("States.Timeout", "ECS tasks did not complete in time")
+
+
+def _pascal_to_camel(d):
+ """Convert top-level PascalCase keys to camelCase for ECS internals."""
+ if not isinstance(d, dict):
+ return d
+ out = {}
+ for k, v in d.items():
+ new_key = k[0].lower() + k[1:] if k else k
+ out[new_key] = v
+ return out
+
+
+_SERVICE_DISPATCH = {
+ "arn:aws:states:::sqs:sendMessage": _invoke_sqs_send_message,
+ "arn:aws:states:::sns:publish": _invoke_sns_publish,
+ "arn:aws:states:::dynamodb:putItem": lambda r, d: _invoke_dynamodb("putItem", d),
+ "arn:aws:states:::dynamodb:getItem": lambda r, d: _invoke_dynamodb("getItem", d),
+ "arn:aws:states:::dynamodb:deleteItem": lambda r, d: _invoke_dynamodb(
+ "deleteItem", d
+ ),
+ "arn:aws:states:::dynamodb:updateItem": lambda r, d: _invoke_dynamodb(
+ "updateItem", d
+ ),
+ "arn:aws:states:::ecs:runTask": _invoke_ecs_run_task,
+}
+
+
def reset():
_state_machines.clear()
_executions.clear()
diff --git a/tests/test_services.py b/tests/test_services.py
index 7c156d7a..26a88d77 100644
--- a/tests/test_services.py
+++ b/tests/test_services.py
@@ -5799,3 +5799,426 @@ def test_lambda_function_url_config(lam):
with pytest.raises(ClientError) as exc:
lam.get_function_url_config(FunctionName=fn)
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+# -----------------------------------------------------------------------
+# Step Functions — Service Integration Tests
+# -----------------------------------------------------------------------
+
+
+def _wait_sfn(sfn, exec_arn, timeout=10):
+ """Poll DescribeExecution until terminal state."""
+ for _ in range(int(timeout / 0.1)):
+ time.sleep(0.1)
+ desc = sfn.describe_execution(executionArn=exec_arn)
+ if desc["status"] != "RUNNING":
+ return desc
+ return desc
+
+
+def test_sfn_integration_sqs_send_message(sfn, sqs):
+ """Task state sends a message to SQS via arn:aws:states:::sqs:sendMessage."""
+ queue_name = "sfn-integ-sqs-test"
+ q = sqs.create_queue(QueueName=queue_name)
+ queue_url = q["QueueUrl"]
+
+ definition = json.dumps(
+ {
+ "StartAt": "Send",
+ "States": {
+ "Send": {
+ "Type": "Task",
+ "Resource": "arn:aws:states:::sqs:sendMessage",
+ "Parameters": {
+ "QueueUrl": queue_url,
+ "MessageBody.$": "$.body",
+ },
+ "End": True,
+ },
+ },
+ }
+ )
+ sm = sfn.create_state_machine(
+ name="sfn-sqs-integ",
+ definition=definition,
+ roleArn="arn:aws:iam::000000000000:role/R",
+ )
+ ex = sfn.start_execution(
+ stateMachineArn=sm["stateMachineArn"],
+ input=json.dumps({"body": "hello from sfn"}),
+ )
+
+ desc = _wait_sfn(sfn, ex["executionArn"])
+ assert desc["status"] == "SUCCEEDED"
+ output = json.loads(desc["output"])
+ assert "MessageId" in output
+
+ # Verify the message actually landed in the queue
+ msgs = sqs.receive_message(QueueUrl=queue_url, MaxNumberOfMessages=1)
+ assert len(msgs.get("Messages", [])) == 1
+ assert msgs["Messages"][0]["Body"] == "hello from sfn"
+
+
+def test_sfn_integration_sns_publish(sfn, sns):
+ """Task state publishes to SNS via arn:aws:states:::sns:publish."""
+ topic = sns.create_topic(Name="sfn-integ-sns-test")
+ topic_arn = topic["TopicArn"]
+
+ definition = json.dumps(
+ {
+ "StartAt": "Publish",
+ "States": {
+ "Publish": {
+ "Type": "Task",
+ "Resource": "arn:aws:states:::sns:publish",
+ "Parameters": {
+ "TopicArn": topic_arn,
+ "Message.$": "$.msg",
+ },
+ "End": True,
+ },
+ },
+ }
+ )
+ sm = sfn.create_state_machine(
+ name="sfn-sns-integ",
+ definition=definition,
+ roleArn="arn:aws:iam::000000000000:role/R",
+ )
+ ex = sfn.start_execution(
+ stateMachineArn=sm["stateMachineArn"],
+ input=json.dumps({"msg": "hello from sfn"}),
+ )
+
+ desc = _wait_sfn(sfn, ex["executionArn"])
+ assert desc["status"] == "SUCCEEDED"
+ output = json.loads(desc["output"])
+ assert "MessageId" in output
+
+
+def test_sfn_integration_dynamodb_put_get(sfn, ddb):
+ """Task states write and read from DynamoDB."""
+ table_name = "sfn-integ-ddb-test"
+ ddb.create_table(
+ TableName=table_name,
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+
+ # State machine: PutItem then GetItem
+ definition = json.dumps(
+ {
+ "StartAt": "Put",
+ "States": {
+ "Put": {
+ "Type": "Task",
+ "Resource": "arn:aws:states:::dynamodb:putItem",
+ "Parameters": {
+ "TableName": table_name,
+ "Item": {
+ "pk": {"S.$": "$.id"},
+ "data": {"S.$": "$.value"},
+ },
+ },
+ "ResultPath": "$.putResult",
+ "Next": "Get",
+ },
+ "Get": {
+ "Type": "Task",
+ "Resource": "arn:aws:states:::dynamodb:getItem",
+ "Parameters": {
+ "TableName": table_name,
+ "Key": {"pk": {"S.$": "$.id"}},
+ },
+ "ResultPath": "$.getResult",
+ "End": True,
+ },
+ },
+ }
+ )
+ sm = sfn.create_state_machine(
+ name="sfn-ddb-integ",
+ definition=definition,
+ roleArn="arn:aws:iam::000000000000:role/R",
+ )
+ ex = sfn.start_execution(
+ stateMachineArn=sm["stateMachineArn"],
+ input=json.dumps({"id": "item-1", "value": "test-value"}),
+ )
+
+ desc = _wait_sfn(sfn, ex["executionArn"])
+ assert desc["status"] == "SUCCEEDED"
+ output = json.loads(desc["output"])
+ item = output["getResult"]["Item"]
+ assert item["pk"]["S"] == "item-1"
+ assert item["data"]["S"] == "test-value"
+
+
+def test_sfn_integration_dynamodb_error_catch(sfn, ddb):
+ """Task state catches DynamoDB error and routes to fallback."""
+ definition = json.dumps(
+ {
+ "StartAt": "GetMissing",
+ "States": {
+ "GetMissing": {
+ "Type": "Task",
+ "Resource": "arn:aws:states:::dynamodb:getItem",
+ "Parameters": {
+ "TableName": "nonexistent-table-sfn",
+ "Key": {"pk": {"S": "x"}},
+ },
+ "Catch": [
+ {
+ "ErrorEquals": ["States.ALL"],
+ "Next": "Fallback",
+ "ResultPath": "$.error",
+ }
+ ],
+ "End": True,
+ },
+ "Fallback": {
+ "Type": "Pass",
+ "Result": "caught",
+ "ResultPath": "$.recovered",
+ "End": True,
+ },
+ },
+ }
+ )
+ sm = sfn.create_state_machine(
+ name="sfn-ddb-catch",
+ definition=definition,
+ roleArn="arn:aws:iam::000000000000:role/R",
+ )
+ ex = sfn.start_execution(stateMachineArn=sm["stateMachineArn"], input="{}")
+
+ desc = _wait_sfn(sfn, ex["executionArn"])
+ assert desc["status"] == "SUCCEEDED"
+ output = json.loads(desc["output"])
+ assert output["recovered"] == "caught"
+ assert "Error" in output["error"]
+
+
+def test_sfn_integration_ecs_run_task(sfn, ecs):
+ """Task state triggers ecs:runTask (fire-and-forget, no Docker needed)."""
+ ecs.create_cluster(clusterName="sfn-ecs-test")
+ ecs.register_task_definition(
+ family="sfn-task",
+ containerDefinitions=[
+ {
+ "name": "main",
+ "image": "alpine:latest",
+ "command": ["echo", "hi"],
+ "memory": 128,
+ }
+ ],
+ )
+
+ definition = json.dumps(
+ {
+ "StartAt": "RunTask",
+ "States": {
+ "RunTask": {
+ "Type": "Task",
+ "Resource": "arn:aws:states:::ecs:runTask",
+ "Parameters": {
+ "Cluster": "sfn-ecs-test",
+ "TaskDefinition": "sfn-task",
+ "LaunchType": "FARGATE",
+ },
+ "End": True,
+ },
+ },
+ }
+ )
+ sm = sfn.create_state_machine(
+ name="sfn-ecs-integ",
+ definition=definition,
+ roleArn="arn:aws:iam::000000000000:role/R",
+ )
+ ex = sfn.start_execution(stateMachineArn=sm["stateMachineArn"], input="{}")
+
+ desc = _wait_sfn(sfn, ex["executionArn"])
+ assert desc["status"] == "SUCCEEDED"
+ output = json.loads(desc["output"])
+ assert "tasks" in output
+
+
+def test_sfn_integration_ecs_run_task_sync_success(sfn, ecs):
+ """ecs:runTask.sync waits for task STOPPED, then returns task result."""
+ import threading
+
+ ecs.create_cluster(clusterName="sfn-ecs-sync-ok")
+ ecs.register_task_definition(
+ family="sfn-sync-ok",
+ containerDefinitions=[{
+ "name": "main", "image": "alpine", "memory": 128,
+ }])
+
+ definition = json.dumps({
+ "StartAt": "Run",
+ "States": {
+ "Run": {
+ "Type": "Task",
+ "Resource": "arn:aws:states:::ecs:runTask.sync",
+ "Parameters": {
+ "Cluster": "sfn-ecs-sync-ok",
+ "TaskDefinition": "sfn-sync-ok",
+ "LaunchType": "FARGATE",
+ },
+ "End": True,
+ },
+ },
+ })
+ sm = sfn.create_state_machine(
+ name="sfn-ecs-sync-ok", definition=definition,
+ roleArn="arn:aws:iam::000000000000:role/R")
+
+ # Background thread: poll list_tasks until task appears, then stop it
+ def stop_task_when_ready():
+ for _ in range(30):
+ time.sleep(0.5)
+ try:
+ tasks = ecs.list_tasks(cluster="sfn-ecs-sync-ok")
+ if tasks.get("taskArns"):
+ ecs.stop_task(
+ cluster="sfn-ecs-sync-ok",
+ task=tasks["taskArns"][0],
+ reason="Test: simulating completion")
+ return
+ except Exception:
+ pass
+
+ stopper = threading.Thread(target=stop_task_when_ready, daemon=True)
+ stopper.start()
+
+ ex = sfn.start_execution(stateMachineArn=sm["stateMachineArn"], input="{}")
+
+ desc = _wait_sfn(sfn, ex["executionArn"], timeout=20)
+ stopper.join(timeout=5)
+ assert desc["status"] == "SUCCEEDED"
+ output = json.loads(desc["output"])
+ assert "tasks" in output
+ task_out = output["tasks"][0]
+ assert task_out["lastStatus"] == "STOPPED"
+ # Containers should have exitCode 0 (stop_task sets this)
+ for c in task_out.get("containers", []):
+ assert c.get("exitCode") == 0
+
+
+def test_sfn_integration_ecs_run_task_output_contains_status(sfn, ecs):
+ """Fire-and-forget ecs:runTask output contains task status and container info."""
+ ecs.create_cluster(clusterName="sfn-ecs-status")
+ ecs.register_task_definition(
+ family="sfn-status-task",
+ containerDefinitions=[{
+ "name": "app", "image": "nginx:latest", "memory": 256,
+ }])
+
+ definition = json.dumps({
+ "StartAt": "Run",
+ "States": {
+ "Run": {
+ "Type": "Task",
+ "Resource": "arn:aws:states:::ecs:runTask",
+ "Parameters": {
+ "Cluster": "sfn-ecs-status",
+ "TaskDefinition": "sfn-status-task",
+ "LaunchType": "FARGATE",
+ },
+ "End": True,
+ },
+ },
+ })
+ sm = sfn.create_state_machine(
+ name="sfn-ecs-status", definition=definition,
+ roleArn="arn:aws:iam::000000000000:role/R")
+ ex = sfn.start_execution(stateMachineArn=sm["stateMachineArn"], input="{}")
+
+ desc = _wait_sfn(sfn, ex["executionArn"])
+ assert desc["status"] == "SUCCEEDED"
+ output = json.loads(desc["output"])
+ assert "tasks" in output
+ assert len(output["tasks"]) == 1
+ task_out = output["tasks"][0]
+ assert "taskArn" in task_out
+ assert "containers" in task_out
+ assert task_out["containers"][0]["name"] == "app"
+ assert task_out["lastStatus"] == "RUNNING"
+ assert "failures" in output
+
+
+def test_sfn_integration_multi_service_pipeline(sfn, sqs, ddb):
+ """End-to-end: Pass → DynamoDB putItem → SQS sendMessage → Succeed."""
+ table_name = "sfn-pipeline-test"
+ ddb.create_table(
+ TableName=table_name,
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+
+ queue_name = "sfn-pipeline-queue"
+ q = sqs.create_queue(QueueName=queue_name)
+ queue_url = q["QueueUrl"]
+
+ definition = json.dumps(
+ {
+ "StartAt": "Enrich",
+ "States": {
+ "Enrich": {
+ "Type": "Pass",
+ "Result": "enriched",
+ "ResultPath": "$.status",
+ "Next": "SaveToDB",
+ },
+ "SaveToDB": {
+ "Type": "Task",
+ "Resource": "arn:aws:states:::dynamodb:putItem",
+ "Parameters": {
+ "TableName": table_name,
+ "Item": {
+ "pk": {"S.$": "$.id"},
+ "status": {"S.$": "$.status"},
+ },
+ },
+ "ResultPath": "$.dbResult",
+ "Next": "Notify",
+ },
+ "Notify": {
+ "Type": "Task",
+ "Resource": "arn:aws:states:::sqs:sendMessage",
+ "Parameters": {
+ "QueueUrl": queue_url,
+ "MessageBody.$": "$.id",
+ },
+ "ResultPath": "$.sqsResult",
+ "Next": "Done",
+ },
+ "Done": {
+ "Type": "Succeed",
+ },
+ },
+ }
+ )
+ sm = sfn.create_state_machine(
+ name="sfn-pipeline",
+ definition=definition,
+ roleArn="arn:aws:iam::000000000000:role/R",
+ )
+ ex = sfn.start_execution(
+ stateMachineArn=sm["stateMachineArn"], input=json.dumps({"id": "order-42"})
+ )
+
+ desc = _wait_sfn(sfn, ex["executionArn"])
+ assert desc["status"] == "SUCCEEDED"
+
+ # Verify DynamoDB
+ item = ddb.get_item(TableName=table_name, Key={"pk": {"S": "order-42"}})
+ assert item["Item"]["status"]["S"] == "enriched"
+
+ # Verify SQS
+ msgs = sqs.receive_message(QueueUrl=queue_url, MaxNumberOfMessages=1)
+ assert len(msgs.get("Messages", [])) == 1
+ assert msgs["Messages"][0]["Body"] == "order-42"