• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

localstack / localstack / 19809586398

28 Nov 2025 05:40PM UTC coverage: 86.863% (-0.02%) from 86.879%
19809586398

push

github

web-flow
[SFN] Add new TestState API capabilities (#13418)

New capabilities have recently been added to TestState API. This commit adds the following support for the new capabilities:

- Add mocking support – Mock state outputs and errors without invoking downstream services
- Add support for Map (inline and distributed) states
- Add support to test specific states within a full state machine definition using the new stateName parameter.
- Add support for Catch and Retry fields
- Add new inspection data
- Rename `mocking` package to l`ocal_mocking`: clearly mark mocking functionality related to Step Functions Local. This helps to distinguish between Local mocks and TestState mocks.



Co-authored-by: Greg Furman <gregfurman99@gmail.com>
Co-authored-by: Greg Furman <31275503+gregfurman@users.noreply.github.com>

618 of 728 new or added lines in 25 files covered. (84.89%)

99 existing lines in 8 files now uncovered.

69469 of 79975 relevant lines covered (86.86%)

0.87 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

92.61
/localstack-core/localstack/services/stepfunctions/provider.py
1
import copy
1✔
2
import datetime
1✔
3
import json
1✔
4
import logging
1✔
5
import re
1✔
6
import time
1✔
7
from typing import Final
1✔
8

9
from localstack.aws.api import CommonServiceException, RequestContext
1✔
10
from localstack.aws.api.stepfunctions import (
1✔
11
    ActivityDoesNotExist,
12
    AliasDescription,
13
    Arn,
14
    CharacterRestrictedName,
15
    ConflictException,
16
    CreateActivityOutput,
17
    CreateStateMachineAliasOutput,
18
    CreateStateMachineInput,
19
    CreateStateMachineOutput,
20
    Definition,
21
    DeleteActivityOutput,
22
    DeleteStateMachineAliasOutput,
23
    DeleteStateMachineOutput,
24
    DeleteStateMachineVersionOutput,
25
    DescribeActivityOutput,
26
    DescribeExecutionOutput,
27
    DescribeMapRunOutput,
28
    DescribeStateMachineAliasOutput,
29
    DescribeStateMachineForExecutionOutput,
30
    DescribeStateMachineOutput,
31
    EncryptionConfiguration,
32
    ExecutionDoesNotExist,
33
    ExecutionList,
34
    ExecutionRedriveFilter,
35
    ExecutionStatus,
36
    GetActivityTaskOutput,
37
    GetExecutionHistoryOutput,
38
    IncludedData,
39
    IncludeExecutionDataGetExecutionHistory,
40
    InspectionLevel,
41
    InvalidArn,
42
    InvalidDefinition,
43
    InvalidExecutionInput,
44
    InvalidLoggingConfiguration,
45
    InvalidName,
46
    InvalidToken,
47
    ListActivitiesOutput,
48
    ListExecutionsOutput,
49
    ListExecutionsPageToken,
50
    ListMapRunsOutput,
51
    ListStateMachineAliasesOutput,
52
    ListStateMachinesOutput,
53
    ListStateMachineVersionsOutput,
54
    ListTagsForResourceOutput,
55
    LoggingConfiguration,
56
    LogLevel,
57
    LongArn,
58
    MaxConcurrency,
59
    MissingRequiredParameter,
60
    MockInput,
61
    Name,
62
    PageSize,
63
    PageToken,
64
    Publish,
65
    PublishStateMachineVersionOutput,
66
    ResourceNotFound,
67
    ReverseOrder,
68
    RevisionId,
69
    RoutingConfigurationList,
70
    SendTaskFailureOutput,
71
    SendTaskHeartbeatOutput,
72
    SendTaskSuccessOutput,
73
    SensitiveCause,
74
    SensitiveData,
75
    SensitiveError,
76
    StartExecutionOutput,
77
    StartSyncExecutionOutput,
78
    StateMachineAliasList,
79
    StateMachineAlreadyExists,
80
    StateMachineDoesNotExist,
81
    StateMachineList,
82
    StateMachineType,
83
    StateMachineTypeNotSupported,
84
    StepfunctionsApi,
85
    StopExecutionOutput,
86
    TagKeyList,
87
    TagList,
88
    TagResourceOutput,
89
    TaskDoesNotExist,
90
    TaskTimedOut,
91
    TaskToken,
92
    TestStateInput,
93
    TestStateOutput,
94
    ToleratedFailureCount,
95
    ToleratedFailurePercentage,
96
    TraceHeader,
97
    TracingConfiguration,
98
    UntagResourceOutput,
99
    UpdateMapRunOutput,
100
    UpdateStateMachineAliasOutput,
101
    UpdateStateMachineOutput,
102
    ValidateStateMachineDefinitionDiagnostic,
103
    ValidateStateMachineDefinitionDiagnosticList,
104
    ValidateStateMachineDefinitionInput,
105
    ValidateStateMachineDefinitionOutput,
106
    ValidateStateMachineDefinitionResultCode,
107
    ValidateStateMachineDefinitionSeverity,
108
    ValidationException,
109
    VersionDescription,
110
)
111
from localstack.services.plugins import ServiceLifecycleHook
1✔
112
from localstack.services.stepfunctions.asl.component.state.state_execution.state_map.iteration.itemprocessor.map_run_record import (
1✔
113
    MapRunRecord,
114
)
115
from localstack.services.stepfunctions.asl.eval.callback.callback import (
1✔
116
    ActivityCallbackEndpoint,
117
    CallbackConsumerTimeout,
118
    CallbackNotifyConsumerError,
119
    CallbackOutcomeFailure,
120
    CallbackOutcomeSuccess,
121
)
122
from localstack.services.stepfunctions.asl.eval.event.logging import (
1✔
123
    CloudWatchLoggingConfiguration,
124
    CloudWatchLoggingSession,
125
)
126
from localstack.services.stepfunctions.asl.parse.asl_parser import (
1✔
127
    ASLParserException,
128
)
129
from localstack.services.stepfunctions.asl.static_analyser.express_static_analyser import (
1✔
130
    ExpressStaticAnalyser,
131
)
132
from localstack.services.stepfunctions.asl.static_analyser.static_analyser import (
1✔
133
    StaticAnalyser,
134
)
135
from localstack.services.stepfunctions.asl.static_analyser.test_state.test_state_analyser import (
1✔
136
    TestStateStaticAnalyser,
137
)
138
from localstack.services.stepfunctions.asl.static_analyser.usage_metrics_static_analyser import (
1✔
139
    UsageMetricsStaticAnalyser,
140
)
141
from localstack.services.stepfunctions.backend.activity import Activity, ActivityTask
1✔
142
from localstack.services.stepfunctions.backend.alias import Alias
1✔
143
from localstack.services.stepfunctions.backend.execution import Execution, SyncExecution
1✔
144
from localstack.services.stepfunctions.backend.state_machine import (
1✔
145
    StateMachineInstance,
146
    StateMachineRevision,
147
    StateMachineVersion,
148
    TestStateMachine,
149
)
150
from localstack.services.stepfunctions.backend.store import SFNStore, sfn_stores
1✔
151
from localstack.services.stepfunctions.backend.test_state.execution import (
1✔
152
    TestStateExecution,
153
)
154
from localstack.services.stepfunctions.backend.test_state.test_state_mock import TestStateMock
1✔
155
from localstack.services.stepfunctions.local_mocking.mock_config import (
1✔
156
    LocalMockTestCase,
157
    load_local_mock_test_case_for,
158
)
159
from localstack.services.stepfunctions.stepfunctions_utils import (
1✔
160
    assert_pagination_parameters_valid,
161
    get_next_page_token_from_arn,
162
    normalise_max_results,
163
)
164
from localstack.state import StateVisitor
1✔
165
from localstack.utils.aws.arns import (
1✔
166
    ARN_PARTITION_REGEX,
167
    stepfunctions_activity_arn,
168
    stepfunctions_express_execution_arn,
169
    stepfunctions_standard_execution_arn,
170
    stepfunctions_state_machine_arn,
171
)
172
from localstack.utils.collections import PaginatedList
1✔
173
from localstack.utils.strings import long_uid, short_uid
1✔
174

175
LOG = logging.getLogger(__name__)
1✔
176

177

178
class StepFunctionsProvider(StepfunctionsApi, ServiceLifecycleHook):
1✔
179
    _TEST_STATE_MAX_TIMEOUT_SECONDS: Final[int] = 300  # 5 minutes.
1✔
180

181
    @staticmethod
1✔
182
    def get_store(context: RequestContext) -> SFNStore:
1✔
183
        return sfn_stores[context.account_id][context.region]
1✔
184

185
    def accept_state_visitor(self, visitor: StateVisitor):
1✔
186
        visitor.visit(sfn_stores)
×
187

188
    _STATE_MACHINE_ARN_REGEX: Final[re.Pattern] = re.compile(
1✔
189
        rf"{ARN_PARTITION_REGEX}:states:[a-z0-9-]+:[0-9]{{12}}:stateMachine:[a-zA-Z0-9-_.]+(:\d+)?(:[a-zA-Z0-9-_.]+)*(?:#[a-zA-Z0-9-_]+)?$"
190
    )
191

192
    _STATE_MACHINE_EXECUTION_ARN_REGEX: Final[re.Pattern] = re.compile(
1✔
193
        rf"{ARN_PARTITION_REGEX}:states:[a-z0-9-]+:[0-9]{{12}}:(stateMachine|execution|express):[a-zA-Z0-9-_.]+(:\d+)?(:[a-zA-Z0-9-_.]+)*$"
194
    )
195

196
    _ACTIVITY_ARN_REGEX: Final[re.Pattern] = re.compile(
1✔
197
        rf"{ARN_PARTITION_REGEX}:states:[a-z0-9-]+:[0-9]{{12}}:activity:[a-zA-Z0-9-_\.]{{1,80}}$"
198
    )
199

200
    _ALIAS_ARN_REGEX: Final[re.Pattern] = re.compile(
1✔
201
        rf"{ARN_PARTITION_REGEX}:states:[a-z0-9-]+:[0-9]{{12}}:stateMachine:[A-Za-z0-9_.-]+:[A-Za-z_.-]+[A-Za-z0-9_.-]{{0,80}}$"
202
    )
203

204
    _ALIAS_NAME_REGEX: Final[re.Pattern] = re.compile(r"^(?=.*[a-zA-Z_\-\.])[a-zA-Z0-9_\-\.]+$")
1✔
205

206
    @staticmethod
1✔
207
    def _validate_state_machine_arn(state_machine_arn: str) -> None:
1✔
208
        # TODO: InvalidArn exception message do not communicate which part of the ARN is incorrect.
209
        if not StepFunctionsProvider._STATE_MACHINE_ARN_REGEX.match(state_machine_arn):
1✔
210
            raise InvalidArn(f"Invalid arn: '{state_machine_arn}'")
1✔
211

212
    @staticmethod
1✔
213
    def _raise_state_machine_does_not_exist(state_machine_arn: str) -> None:
1✔
214
        raise StateMachineDoesNotExist(f"State Machine Does Not Exist: '{state_machine_arn}'")
1✔
215

216
    @staticmethod
1✔
217
    def _validate_state_machine_execution_arn(execution_arn: str) -> None:
1✔
218
        # TODO: InvalidArn exception message do not communicate which part of the ARN is incorrect.
219
        if not StepFunctionsProvider._STATE_MACHINE_EXECUTION_ARN_REGEX.match(execution_arn):
1✔
220
            raise InvalidArn(f"Invalid arn: '{execution_arn}'")
1✔
221

222
    @staticmethod
1✔
223
    def _validate_activity_arn(activity_arn: str) -> None:
1✔
224
        # TODO: InvalidArn exception message do not communicate which part of the ARN is incorrect.
225
        if not StepFunctionsProvider._ACTIVITY_ARN_REGEX.match(activity_arn):
1✔
226
            raise InvalidArn(f"Invalid arn: '{activity_arn}'")
1✔
227

228
    @staticmethod
1✔
229
    def _validate_state_machine_alias_arn(state_machine_alias_arn: Arn) -> None:
1✔
230
        if not StepFunctionsProvider._ALIAS_ARN_REGEX.match(state_machine_alias_arn):
1✔
231
            raise InvalidArn(f"Invalid arn: '{state_machine_alias_arn}'")
×
232

233
    def _raise_state_machine_type_not_supported(self):
1✔
234
        raise StateMachineTypeNotSupported(
1✔
235
            "This operation is not supported by this type of state machine"
236
        )
237

238
    @staticmethod
1✔
239
    def _raise_resource_type_not_in_context(resource_type: str) -> None:
1✔
240
        lower_resource_type = resource_type.lower()
1✔
241
        raise InvalidArn(
1✔
242
            f"Invalid Arn: 'Resource type not valid in this context: {lower_resource_type}'"
243
        )
244

245
    @staticmethod
1✔
246
    def _validate_test_state_mock_input(mock_input: MockInput) -> None:
1✔
247
        if {"result", "errorOutput"} <= mock_input.keys():
1✔
248
            # FIXME create proper error
NEW
249
            raise ValidationException("Cannot define both 'result' and 'errorOutput'")
×
250

251
    @staticmethod
1✔
252
    def _validate_activity_name(name: str) -> None:
1✔
253
        # The activity name is validated according to the AWS StepFunctions documentation, the name should not contain:
254
        # - white space
255
        # - brackets < > { } [ ]
256
        # - wildcard characters ? *
257
        # - special characters " # % \ ^ | ~ ` $ & , ; : /
258
        # - control characters (U+0000-001F, U+007F-009F)
259
        # https://docs.aws.amazon.com/step-functions/latest/apireference/API_CreateActivity.html#API_CreateActivity_RequestSyntax
260
        if not (1 <= len(name) <= 80):
1✔
261
            raise InvalidName(f"Invalid Name: '{name}'")
×
262
        invalid_chars = set(' <>{}[]?*"#%\\^|~`$&,;:/')
1✔
263
        control_chars = {chr(i) for i in range(32)} | {chr(i) for i in range(127, 160)}
1✔
264
        invalid_chars |= control_chars
1✔
265
        for char in name:
1✔
266
            if char in invalid_chars:
1✔
267
                raise InvalidName(f"Invalid Name: '{name}'")
1✔
268

269
    @staticmethod
1✔
270
    def _validate_state_machine_alias_name(name: CharacterRestrictedName) -> None:
1✔
271
        len_name = len(name)
1✔
272
        if len_name > 80:
1✔
273
            raise ValidationException(
1✔
274
                f"1 validation error detected: Value '{name}' at 'name' failed to satisfy constraint: "
275
                f"Member must have length less than or equal to 80"
276
            )
277
        if not StepFunctionsProvider._ALIAS_NAME_REGEX.match(name):
1✔
278
            raise ValidationException(
1✔
279
                # TODO: explore more error cases in which more than one validation error may occur which results
280
                #  in the counter below being greater than 1.
281
                f"1 validation error detected: Value '{name}' at 'name' failed to satisfy constraint: "
282
                f"Member must satisfy regular expression pattern: ^(?=.*[a-zA-Z_\\-\\.])[a-zA-Z0-9_\\-\\.]+$"
283
            )
284

285
    def _get_execution(self, context: RequestContext, execution_arn: Arn) -> Execution:
1✔
286
        execution: Execution | None = self.get_store(context).executions.get(execution_arn)
1✔
287
        if not execution:
1✔
288
            raise ExecutionDoesNotExist(f"Execution Does Not Exist: '{execution_arn}'")
1✔
289
        return execution
1✔
290

291
    def _get_executions(
1✔
292
        self,
293
        context: RequestContext,
294
        execution_status: ExecutionStatus | None = None,
295
    ):
296
        store = self.get_store(context)
1✔
297
        execution: list[Execution] = list(store.executions.values())
1✔
298
        if execution_status:
1✔
299
            execution = list(
1✔
300
                filter(
301
                    lambda e: e.exec_status == execution_status,
302
                    store.executions.values(),
303
                )
304
            )
305
        return execution
1✔
306

307
    def _get_activity(self, context: RequestContext, activity_arn: Arn) -> Activity:
1✔
308
        maybe_activity: Activity | None = self.get_store(context).activities.get(activity_arn, None)
1✔
309
        if maybe_activity is None:
1✔
310
            raise ActivityDoesNotExist(f"Activity Does Not Exist: '{activity_arn}'")
1✔
311
        return maybe_activity
1✔
312

313
    def _idempotent_revision(
1✔
314
        self,
315
        context: RequestContext,
316
        name: str,
317
        definition: Definition,
318
        state_machine_type: StateMachineType,
319
        logging_configuration: LoggingConfiguration,
320
        tracing_configuration: TracingConfiguration,
321
    ) -> StateMachineRevision | None:
322
        # CreateStateMachine's idempotency check is based on the state machine name, definition, type,
323
        # LoggingConfiguration and TracingConfiguration.
324
        # If a following request has a different roleArn or tags, Step Functions will ignore these differences and
325
        # treat it as an idempotent request of the previous. In this case, roleArn and tags will not be updated, even
326
        # if they are different.
327
        state_machines: list[StateMachineInstance] = list(
1✔
328
            self.get_store(context).state_machines.values()
329
        )
330
        revisions = filter(lambda sm: isinstance(sm, StateMachineRevision), state_machines)
1✔
331
        for state_machine in revisions:
1✔
332
            check = all(
1✔
333
                [
334
                    state_machine.name == name,
335
                    state_machine.definition == definition,
336
                    state_machine.sm_type == state_machine_type,
337
                    state_machine.logging_config == logging_configuration,
338
                    state_machine.tracing_config == tracing_configuration,
339
                ]
340
            )
341
            if check:
1✔
342
                return state_machine
1✔
343
        return None
1✔
344

345
    def _idempotent_start_execution(
1✔
346
        self,
347
        execution: Execution | None,
348
        state_machine: StateMachineInstance,
349
        name: Name,
350
        input_data: SensitiveData,
351
    ) -> Execution | None:
352
        # StartExecution is idempotent for STANDARD workflows. For a STANDARD workflow,
353
        # if you call StartExecution with the same name and input as a running execution,
354
        # the call succeeds and return the same response as the original request.
355
        # If the execution is closed or if the input is different,
356
        # it returns a 400 ExecutionAlreadyExists error. You can reuse names after 90 days.
357

358
        if not execution:
1✔
359
            return None
×
360

361
        match (name, input_data, execution.exec_status, state_machine.sm_type):
1✔
362
            case (
1✔
363
                execution.name,
364
                execution.input_data,
365
                ExecutionStatus.RUNNING,
366
                StateMachineType.STANDARD,
367
            ):
368
                return execution
1✔
369

370
        raise CommonServiceException(
1✔
371
            code="ExecutionAlreadyExists",
372
            message=f"Execution Already Exists: '{execution.exec_arn}'",
373
        )
374

375
    def _revision_by_name(self, context: RequestContext, name: str) -> StateMachineInstance | None:
1✔
376
        state_machines: list[StateMachineInstance] = list(
1✔
377
            self.get_store(context).state_machines.values()
378
        )
379
        for state_machine in state_machines:
1✔
380
            if isinstance(state_machine, StateMachineRevision) and state_machine.name == name:
1✔
381
                return state_machine
1✔
382
        return None
1✔
383

384
    @staticmethod
1✔
385
    def _validate_definition(definition: str, static_analysers: list[StaticAnalyser]) -> None:
1✔
386
        try:
1✔
387
            for static_analyser in static_analysers:
1✔
388
                static_analyser.analyse(definition)
1✔
389
        except ASLParserException as asl_parser_exception:
1✔
390
            invalid_definition = InvalidDefinition()
1✔
391
            invalid_definition.message = repr(asl_parser_exception)
1✔
392
            raise invalid_definition
1✔
393
        except Exception as exception:
1✔
394
            exception_name = exception.__class__.__name__
1✔
395
            exception_args = list(exception.args)
1✔
396
            invalid_definition = InvalidDefinition()
1✔
397
            invalid_definition.message = (
1✔
398
                f"Error={exception_name} Args={exception_args} in definition '{definition}'."
399
            )
400
            raise invalid_definition
1✔
401

402
    @staticmethod
1✔
403
    def _sanitise_logging_configuration(
1✔
404
        logging_configuration: LoggingConfiguration,
405
    ) -> None:
406
        level = logging_configuration.get("level")
1✔
407
        destinations = logging_configuration.get("destinations")
1✔
408

409
        if destinations is not None and len(destinations) > 1:
1✔
410
            raise InvalidLoggingConfiguration(
1✔
411
                "Invalid Logging Configuration: Must specify exactly one Log Destination."
412
            )
413

414
        # A LogLevel that is not OFF, should have a destination.
415
        if level is not None and level != LogLevel.OFF and not destinations:
1✔
416
            raise InvalidLoggingConfiguration(
1✔
417
                "Invalid Logging Configuration: Must specify exactly one Log Destination."
418
            )
419

420
        # Default for level is OFF.
421
        level = level or LogLevel.OFF
1✔
422

423
        # Default for includeExecutionData is False.
424
        include_flag = logging_configuration.get("includeExecutionData", False)
1✔
425

426
        # Update configuration object.
427
        logging_configuration["level"] = level
1✔
428
        logging_configuration["includeExecutionData"] = include_flag
1✔
429

430
    def create_state_machine(
1✔
431
        self, context: RequestContext, request: CreateStateMachineInput, **kwargs
432
    ) -> CreateStateMachineOutput:
433
        if not request.get("publish", False) and request.get("versionDescription"):
1✔
434
            raise ValidationException("Version description can only be set when publish is true")
1✔
435

436
        # Extract parameters and set defaults.
437
        state_machine_name = request["name"]
1✔
438
        state_machine_role_arn = request["roleArn"]
1✔
439
        state_machine_definition = request["definition"]
1✔
440
        state_machine_type = request.get("type") or StateMachineType.STANDARD
1✔
441
        state_machine_tracing_configuration = request.get("tracingConfiguration")
1✔
442
        state_machine_tags = request.get("tags")
1✔
443
        state_machine_logging_configuration = request.get(
1✔
444
            "loggingConfiguration", LoggingConfiguration()
445
        )
446
        self._sanitise_logging_configuration(
1✔
447
            logging_configuration=state_machine_logging_configuration
448
        )
449

450
        # CreateStateMachine is an idempotent API. Subsequent requests won't create a duplicate resource if it was
451
        # already created.
452
        idem_state_machine: StateMachineRevision | None = self._idempotent_revision(
1✔
453
            context=context,
454
            name=state_machine_name,
455
            definition=state_machine_definition,
456
            state_machine_type=state_machine_type,
457
            logging_configuration=state_machine_logging_configuration,
458
            tracing_configuration=state_machine_tracing_configuration,
459
        )
460
        if idem_state_machine is not None:
1✔
461
            return CreateStateMachineOutput(
1✔
462
                stateMachineArn=idem_state_machine.arn,
463
                creationDate=idem_state_machine.create_date,
464
            )
465

466
        # Assert this state machine name is unique.
467
        state_machine_with_name: StateMachineRevision | None = self._revision_by_name(
1✔
468
            context=context, name=state_machine_name
469
        )
470
        if state_machine_with_name is not None:
1✔
471
            raise StateMachineAlreadyExists(
1✔
472
                f"State Machine Already Exists: '{state_machine_with_name.arn}'"
473
            )
474

475
        # Compute the state machine's Arn.
476
        state_machine_arn = stepfunctions_state_machine_arn(
1✔
477
            name=state_machine_name,
478
            account_id=context.account_id,
479
            region_name=context.region,
480
        )
481
        state_machines = self.get_store(context).state_machines
1✔
482

483
        # Reduce the logging configuration to a usable cloud watch representation, and validate the destinations
484
        # if any were given.
485
        cloud_watch_logging_configuration = (
1✔
486
            CloudWatchLoggingConfiguration.from_logging_configuration(
487
                state_machine_arn=state_machine_arn,
488
                logging_configuration=state_machine_logging_configuration,
489
            )
490
        )
491
        if cloud_watch_logging_configuration is not None:
1✔
492
            cloud_watch_logging_configuration.validate()
1✔
493

494
        # Run static analysers on the definition given.
495
        if state_machine_type == StateMachineType.EXPRESS:
1✔
496
            StepFunctionsProvider._validate_definition(
1✔
497
                definition=state_machine_definition,
498
                static_analysers=[ExpressStaticAnalyser()],
499
            )
500
        else:
501
            StepFunctionsProvider._validate_definition(
1✔
502
                definition=state_machine_definition, static_analysers=[StaticAnalyser()]
503
            )
504

505
        # Create the state machine and add it to the store.
506
        state_machine = StateMachineRevision(
1✔
507
            name=state_machine_name,
508
            arn=state_machine_arn,
509
            role_arn=state_machine_role_arn,
510
            definition=state_machine_definition,
511
            sm_type=state_machine_type,
512
            logging_config=state_machine_logging_configuration,
513
            cloud_watch_logging_configuration=cloud_watch_logging_configuration,
514
            tracing_config=state_machine_tracing_configuration,
515
            tags=state_machine_tags,
516
        )
517
        state_machines[state_machine_arn] = state_machine
1✔
518

519
        create_output = CreateStateMachineOutput(
1✔
520
            stateMachineArn=state_machine.arn, creationDate=state_machine.create_date
521
        )
522

523
        # Create the first version if the 'publish' flag is used.
524
        if request.get("publish", False):
1✔
525
            version_description = request.get("versionDescription")
1✔
526
            state_machine_version = state_machine.create_version(description=version_description)
1✔
527
            if state_machine_version is not None:
1✔
528
                state_machine_version_arn = state_machine_version.arn
1✔
529
                state_machines[state_machine_version_arn] = state_machine_version
1✔
530
                create_output["stateMachineVersionArn"] = state_machine_version_arn
1✔
531

532
        # Run static analyser on definition and collect usage metrics
533
        UsageMetricsStaticAnalyser.process(state_machine_definition)
1✔
534

535
        return create_output
1✔
536

537
    def _validate_state_machine_alias_routing_configuration(
1✔
538
        self, context: RequestContext, routing_configuration_list: RoutingConfigurationList
539
    ) -> None:
540
        # TODO: to match AWS's approach best validation exceptions could be
541
        #  built in a process decoupled from the provider.
542

543
        routing_configuration_list_len = len(routing_configuration_list)
1✔
544
        if not (1 <= routing_configuration_list_len <= 2):
1✔
545
            # Replicate the object string dump format:
546
            # [RoutingConfigurationListItem(stateMachineVersionArn=arn_no_quotes, weight=int), ...]
547
            routing_configuration_serialization_parts = []
1✔
548
            for routing_configuration in routing_configuration_list:
1✔
549
                routing_configuration_serialization_parts.append(
1✔
550
                    "".join(
551
                        [
552
                            "RoutingConfigurationListItem(stateMachineVersionArn=",
553
                            routing_configuration["stateMachineVersionArn"],
554
                            ", weight=",
555
                            str(routing_configuration["weight"]),
556
                            ")",
557
                        ]
558
                    )
559
                )
560
            routing_configuration_serialization_list = (
1✔
561
                f"[{', '.join(routing_configuration_serialization_parts)}]"
562
            )
563
            raise ValidationException(
1✔
564
                f"1 validation error detected: Value '{routing_configuration_serialization_list}' "
565
                "at 'routingConfiguration' failed to "
566
                "satisfy constraint: Member must have length less than or equal to 2"
567
            )
568

569
        routing_configuration_arn_list = [
1✔
570
            routing_configuration["stateMachineVersionArn"]
571
            for routing_configuration in routing_configuration_list
572
        ]
573
        if len(set(routing_configuration_arn_list)) < routing_configuration_list_len:
1✔
574
            arn_list_string = f"[{', '.join(routing_configuration_arn_list)}]"
1✔
575
            raise ValidationException(
1✔
576
                "Routing configuration must contain distinct state machine version ARNs. "
577
                f"Received: {arn_list_string}"
578
            )
579

580
        routing_weights = [
1✔
581
            routing_configuration["weight"] for routing_configuration in routing_configuration_list
582
        ]
583
        for i, weight in enumerate(routing_weights):
1✔
584
            # TODO: check for weight type.
585
            if weight < 0:
1✔
586
                raise ValidationException(
×
587
                    f"Invalid value for parameter routingConfiguration[{i + 1}].weight, value: {weight}, valid min value: 0"
588
                )
589
            if weight > 100:
1✔
590
                raise ValidationException(
1✔
591
                    f"1 validation error detected: Value '{weight}' at 'routingConfiguration.{i + 1}.member.weight' "
592
                    "failed to satisfy constraint: Member must have value less than or equal to 100"
593
                )
594
        routing_weights_sum = sum(routing_weights)
1✔
595
        if not routing_weights_sum == 100:
1✔
596
            raise ValidationException(
1✔
597
                f"Sum of routing configuration weights must equal 100. Received: {json.dumps(routing_weights)}"
598
            )
599

600
        store = self.get_store(context=context)
1✔
601
        state_machines = store.state_machines
1✔
602

603
        first_routing_qualified_arn = routing_configuration_arn_list[0]
1✔
604
        shared_state_machine_revision_arn = self._get_state_machine_arn_from_qualified_arn(
1✔
605
            qualified_arn=first_routing_qualified_arn
606
        )
607
        for routing_configuration_arn in routing_configuration_arn_list:
1✔
608
            maybe_state_machine_version = state_machines.get(routing_configuration_arn)
1✔
609
            if not isinstance(maybe_state_machine_version, StateMachineVersion):
1✔
610
                arn_list_string = f"[{', '.join(routing_configuration_arn_list)}]"
1✔
611
                raise ValidationException(
1✔
612
                    f"Routing configuration must contain state machine version ARNs. Received: {arn_list_string}"
613
                )
614
            state_machine_revision_arn = self._get_state_machine_arn_from_qualified_arn(
1✔
615
                qualified_arn=routing_configuration_arn
616
            )
617
            if state_machine_revision_arn != shared_state_machine_revision_arn:
1✔
618
                raise ValidationException("TODO")
×
619

620
    @staticmethod
1✔
621
    def _get_state_machine_arn_from_qualified_arn(qualified_arn: Arn) -> Arn:
1✔
622
        last_colon_index = qualified_arn.rfind(":")
1✔
623
        base_arn = qualified_arn[:last_colon_index]
1✔
624
        return base_arn
1✔
625

626
    def create_state_machine_alias(
1✔
627
        self,
628
        context: RequestContext,
629
        name: CharacterRestrictedName,
630
        routing_configuration: RoutingConfigurationList,
631
        description: AliasDescription = None,
632
        **kwargs,
633
    ) -> CreateStateMachineAliasOutput:
634
        # Validate the inputs.
635
        self._validate_state_machine_alias_name(name=name)
1✔
636
        self._validate_state_machine_alias_routing_configuration(
1✔
637
            context=context, routing_configuration_list=routing_configuration
638
        )
639

640
        # Determine the state machine arn this alias maps to,
641
        # do so unsafely as validation already took place before initialisation.
642
        first_routing_qualified_arn = routing_configuration[0]["stateMachineVersionArn"]
1✔
643
        state_machine_revision_arn = self._get_state_machine_arn_from_qualified_arn(
1✔
644
            qualified_arn=first_routing_qualified_arn
645
        )
646
        alias = Alias(
1✔
647
            state_machine_arn=state_machine_revision_arn,
648
            name=name,
649
            description=description,
650
            routing_configuration_list=routing_configuration,
651
        )
652
        state_machine_alias_arn = alias.state_machine_alias_arn
1✔
653

654
        store = self.get_store(context=context)
1✔
655

656
        aliases = store.aliases
1✔
657
        if maybe_idempotent_alias := aliases.get(state_machine_alias_arn):
1✔
658
            if alias.is_idempotent(maybe_idempotent_alias):
1✔
659
                return CreateStateMachineAliasOutput(
1✔
660
                    stateMachineAliasArn=state_machine_alias_arn, creationDate=alias.create_date
661
                )
662
            else:
663
                # CreateStateMachineAlias is an idempotent API. Idempotent requests won't create duplicate resources.
664
                raise ConflictException(
1✔
665
                    "Failed to create alias because an alias with the same name and a "
666
                    "different routing configuration already exists."
667
                )
668
        aliases[state_machine_alias_arn] = alias
1✔
669

670
        state_machine_revision = store.state_machines.get(state_machine_revision_arn)
1✔
671
        if not isinstance(state_machine_revision, StateMachineRevision):
1✔
672
            # The state machine was deleted but not the version referenced in this context.
673
            raise RuntimeError(f"No state machine revision for arn '{state_machine_revision_arn}'")
×
674
        state_machine_revision.aliases.add(alias)
1✔
675

676
        return CreateStateMachineAliasOutput(
1✔
677
            stateMachineAliasArn=state_machine_alias_arn, creationDate=alias.create_date
678
        )
679

680
    def describe_state_machine(
1✔
681
        self,
682
        context: RequestContext,
683
        state_machine_arn: Arn,
684
        included_data: IncludedData = None,
685
        **kwargs,
686
    ) -> DescribeStateMachineOutput:
687
        self._validate_state_machine_arn(state_machine_arn)
1✔
688
        state_machine = self.get_store(context).state_machines.get(state_machine_arn)
1✔
689
        if state_machine is None:
1✔
690
            self._raise_state_machine_does_not_exist(state_machine_arn)
1✔
691
        return state_machine.describe()
1✔
692

693
    def describe_state_machine_alias(
1✔
694
        self, context: RequestContext, state_machine_alias_arn: Arn, **kwargs
695
    ) -> DescribeStateMachineAliasOutput:
696
        self._validate_state_machine_alias_arn(state_machine_alias_arn=state_machine_alias_arn)
1✔
697
        alias: Alias | None = self.get_store(context=context).aliases.get(state_machine_alias_arn)
1✔
698
        if alias is None:
1✔
699
            # TODO: assemble the correct exception
700
            raise ValidationException()
×
701
        description = alias.to_description()
1✔
702
        return description
1✔
703

704
    def describe_state_machine_for_execution(
1✔
705
        self,
706
        context: RequestContext,
707
        execution_arn: Arn,
708
        included_data: IncludedData = None,
709
        **kwargs,
710
    ) -> DescribeStateMachineForExecutionOutput:
711
        self._validate_state_machine_execution_arn(execution_arn)
1✔
712
        execution: Execution = self._get_execution(context=context, execution_arn=execution_arn)
1✔
713
        return execution.to_describe_state_machine_for_execution_output()
1✔
714

715
    def send_task_heartbeat(
1✔
716
        self, context: RequestContext, task_token: TaskToken, **kwargs
717
    ) -> SendTaskHeartbeatOutput:
718
        running_executions: list[Execution] = self._get_executions(context, ExecutionStatus.RUNNING)
1✔
719
        for execution in running_executions:
1✔
720
            try:
1✔
721
                if execution.exec_worker.env.callback_pool_manager.heartbeat(
1✔
722
                    callback_id=task_token
723
                ):
724
                    return SendTaskHeartbeatOutput()
1✔
725
            except CallbackNotifyConsumerError as consumer_error:
×
726
                if isinstance(consumer_error, CallbackConsumerTimeout):
×
727
                    raise TaskTimedOut()
×
728
                else:
729
                    raise TaskDoesNotExist()
×
730
        raise InvalidToken()
×
731

732
    def send_task_success(
1✔
733
        self,
734
        context: RequestContext,
735
        task_token: TaskToken,
736
        output: SensitiveData,
737
        **kwargs,
738
    ) -> SendTaskSuccessOutput:
739
        outcome = CallbackOutcomeSuccess(callback_id=task_token, output=output)
1✔
740
        running_executions: list[Execution] = self._get_executions(context, ExecutionStatus.RUNNING)
1✔
741
        for execution in running_executions:
1✔
742
            try:
1✔
743
                if execution.exec_worker.env.callback_pool_manager.notify(
1✔
744
                    callback_id=task_token, outcome=outcome
745
                ):
746
                    return SendTaskSuccessOutput()
1✔
747
            except CallbackNotifyConsumerError as consumer_error:
×
748
                if isinstance(consumer_error, CallbackConsumerTimeout):
×
749
                    raise TaskTimedOut()
×
750
                else:
751
                    raise TaskDoesNotExist()
×
752
        raise InvalidToken("Invalid token")
1✔
753

754
    def send_task_failure(
1✔
755
        self,
756
        context: RequestContext,
757
        task_token: TaskToken,
758
        error: SensitiveError = None,
759
        cause: SensitiveCause = None,
760
        **kwargs,
761
    ) -> SendTaskFailureOutput:
762
        outcome = CallbackOutcomeFailure(callback_id=task_token, error=error, cause=cause)
1✔
763
        store = self.get_store(context)
1✔
764
        for execution in store.executions.values():
1✔
765
            try:
1✔
766
                if execution.exec_worker.env.callback_pool_manager.notify(
1✔
767
                    callback_id=task_token, outcome=outcome
768
                ):
769
                    return SendTaskFailureOutput()
1✔
770
            except CallbackNotifyConsumerError as consumer_error:
×
771
                if isinstance(consumer_error, CallbackConsumerTimeout):
×
772
                    raise TaskTimedOut()
×
773
                else:
774
                    raise TaskDoesNotExist()
×
775
        raise InvalidToken("Invalid token")
1✔
776

777
    @staticmethod
1✔
778
    def _get_state_machine_arn(state_machine_arn: str) -> str:
1✔
779
        """Extract the state machine ARN by removing the test case suffix."""
780
        return state_machine_arn.split("#")[0]
1✔
781

782
    @staticmethod
1✔
783
    def _get_local_mock_test_case(
1✔
784
        state_machine_arn: str, state_machine_name: str
785
    ) -> LocalMockTestCase | None:
786
        """Extract and load a mock test case from a state machine ARN if present."""
787
        parts = state_machine_arn.split("#")
1✔
788
        if len(parts) != 2:
1✔
789
            return None
1✔
790

791
        mock_test_case_name = parts[1]
1✔
792
        mock_test_case = load_local_mock_test_case_for(
1✔
793
            state_machine_name=state_machine_name, test_case_name=mock_test_case_name
794
        )
795
        if mock_test_case is None:
1✔
796
            raise InvalidName(
×
797
                f"Invalid mock test case name '{mock_test_case_name}' "
798
                f"for state machine '{state_machine_name}'."
799
                "Either the test case is not defined or the mock configuration file "
800
                "could not be loaded. See logs for details."
801
            )
802
        return mock_test_case
1✔
803

804
    def start_execution(
1✔
805
        self,
806
        context: RequestContext,
807
        state_machine_arn: Arn,
808
        name: Name = None,
809
        input: SensitiveData = None,
810
        trace_header: TraceHeader = None,
811
        **kwargs,
812
    ) -> StartExecutionOutput:
813
        self._validate_state_machine_arn(state_machine_arn)
1✔
814

815
        base_arn = self._get_state_machine_arn(state_machine_arn)
1✔
816
        store = self.get_store(context=context)
1✔
817

818
        alias: Alias | None = store.aliases.get(base_arn)
1✔
819
        alias_sample_state_machine_version_arn = alias.sample() if alias is not None else None
1✔
820
        unsafe_state_machine: StateMachineInstance | None = store.state_machines.get(
1✔
821
            alias_sample_state_machine_version_arn or base_arn
822
        )
823
        if not unsafe_state_machine:
1✔
824
            self._raise_state_machine_does_not_exist(base_arn)
1✔
825

826
        # Update event change parameters about the state machine and should not affect those about this execution.
827
        state_machine_clone = copy.deepcopy(unsafe_state_machine)
1✔
828

829
        if input is None:
1✔
830
            input_data = {}
1✔
831
        else:
832
            try:
1✔
833
                input_data = json.loads(input)
1✔
834
            except Exception as ex:
1✔
835
                raise InvalidExecutionInput(str(ex))  # TODO: report parsing error like AWS.
1✔
836

837
        normalised_state_machine_arn = (
1✔
838
            state_machine_clone.source_arn
839
            if isinstance(state_machine_clone, StateMachineVersion)
840
            else state_machine_clone.arn
841
        )
842
        exec_name = name or long_uid()  # TODO: validate name format
1✔
843
        if state_machine_clone.sm_type == StateMachineType.STANDARD:
1✔
844
            exec_arn = stepfunctions_standard_execution_arn(normalised_state_machine_arn, exec_name)
1✔
845
        else:
846
            # Exhaustive check on STANDARD and EXPRESS type, validated on creation.
847
            exec_arn = stepfunctions_express_execution_arn(normalised_state_machine_arn, exec_name)
1✔
848

849
        if execution := store.executions.get(exec_arn):
1✔
850
            # Return already running execution if name and input match
851
            existing_execution = self._idempotent_start_execution(
1✔
852
                execution=execution,
853
                state_machine=state_machine_clone,
854
                name=name,
855
                input_data=input_data,
856
            )
857

858
            if existing_execution:
1✔
859
                return existing_execution.to_start_output()
1✔
860

861
        # Create the execution logging session, if logging is configured.
862
        cloud_watch_logging_session = None
1✔
863
        if state_machine_clone.cloud_watch_logging_configuration is not None:
1✔
864
            cloud_watch_logging_session = CloudWatchLoggingSession(
1✔
865
                execution_arn=exec_arn,
866
                configuration=state_machine_clone.cloud_watch_logging_configuration,
867
            )
868

869
        local_mock_test_case = self._get_local_mock_test_case(
1✔
870
            state_machine_arn, state_machine_clone.name
871
        )
872

873
        execution = Execution(
1✔
874
            name=exec_name,
875
            sm_type=state_machine_clone.sm_type,
876
            role_arn=state_machine_clone.role_arn,
877
            exec_arn=exec_arn,
878
            account_id=context.account_id,
879
            region_name=context.region,
880
            state_machine=state_machine_clone,
881
            state_machine_alias_arn=alias.state_machine_alias_arn if alias is not None else None,
882
            start_date=datetime.datetime.now(tz=datetime.UTC),
883
            cloud_watch_logging_session=cloud_watch_logging_session,
884
            input_data=input_data,
885
            trace_header=trace_header,
886
            activity_store=self.get_store(context).activities,
887
            local_mock_test_case=local_mock_test_case,
888
        )
889

890
        store.executions[exec_arn] = execution
1✔
891

892
        execution.start()
1✔
893
        return execution.to_start_output()
1✔
894

895
    def start_sync_execution(
1✔
896
        self,
897
        context: RequestContext,
898
        state_machine_arn: Arn,
899
        name: Name = None,
900
        input: SensitiveData = None,
901
        trace_header: TraceHeader = None,
902
        included_data: IncludedData = None,
903
        **kwargs,
904
    ) -> StartSyncExecutionOutput:
905
        self._validate_state_machine_arn(state_machine_arn)
1✔
906

907
        base_arn = self._get_state_machine_arn(state_machine_arn)
1✔
908
        unsafe_state_machine: StateMachineInstance | None = self.get_store(
1✔
909
            context
910
        ).state_machines.get(base_arn)
911
        if not unsafe_state_machine:
1✔
912
            self._raise_state_machine_does_not_exist(base_arn)
1✔
913

914
        if unsafe_state_machine.sm_type == StateMachineType.STANDARD:
1✔
915
            self._raise_state_machine_type_not_supported()
1✔
916

917
        # Update event change parameters about the state machine and should not affect those about this execution.
918
        state_machine_clone = copy.deepcopy(unsafe_state_machine)
1✔
919

920
        if input is None:
1✔
921
            input_data = {}
×
922
        else:
923
            try:
1✔
924
                input_data = json.loads(input)
1✔
925
            except Exception as ex:
×
926
                raise InvalidExecutionInput(str(ex))  # TODO: report parsing error like AWS.
×
927

928
        normalised_state_machine_arn = (
1✔
929
            state_machine_clone.source_arn
930
            if isinstance(state_machine_clone, StateMachineVersion)
931
            else state_machine_clone.arn
932
        )
933
        exec_name = name or long_uid()  # TODO: validate name format
1✔
934
        exec_arn = stepfunctions_express_execution_arn(normalised_state_machine_arn, exec_name)
1✔
935

936
        if exec_arn in self.get_store(context).executions:
1✔
937
            raise InvalidName()  # TODO
×
938

939
        # Create the execution logging session, if logging is configured.
940
        cloud_watch_logging_session = None
1✔
941
        if state_machine_clone.cloud_watch_logging_configuration is not None:
1✔
942
            cloud_watch_logging_session = CloudWatchLoggingSession(
×
943
                execution_arn=exec_arn,
944
                configuration=state_machine_clone.cloud_watch_logging_configuration,
945
            )
946

947
        local_mock_test_case = self._get_local_mock_test_case(
1✔
948
            state_machine_arn, state_machine_clone.name
949
        )
950

951
        execution = SyncExecution(
1✔
952
            name=exec_name,
953
            sm_type=state_machine_clone.sm_type,
954
            role_arn=state_machine_clone.role_arn,
955
            exec_arn=exec_arn,
956
            account_id=context.account_id,
957
            region_name=context.region,
958
            state_machine=state_machine_clone,
959
            start_date=datetime.datetime.now(tz=datetime.UTC),
960
            cloud_watch_logging_session=cloud_watch_logging_session,
961
            input_data=input_data,
962
            trace_header=trace_header,
963
            activity_store=self.get_store(context).activities,
964
            local_mock_test_case=local_mock_test_case,
965
        )
966
        self.get_store(context).executions[exec_arn] = execution
1✔
967

968
        execution.start()
1✔
969
        return execution.to_start_sync_execution_output()
1✔
970

971
    def describe_execution(
1✔
972
        self,
973
        context: RequestContext,
974
        execution_arn: Arn,
975
        included_data: IncludedData = None,
976
        **kwargs,
977
    ) -> DescribeExecutionOutput:
978
        self._validate_state_machine_execution_arn(execution_arn)
1✔
979
        execution: Execution = self._get_execution(context=context, execution_arn=execution_arn)
1✔
980

981
        # Action only compatible with STANDARD workflows.
982
        if execution.sm_type != StateMachineType.STANDARD:
1✔
983
            self._raise_resource_type_not_in_context(resource_type=execution.sm_type)
1✔
984

985
        return execution.to_describe_output()
1✔
986

987
    @staticmethod
1✔
988
    def _list_execution_filter(
1✔
989
        ex: Execution, state_machine_arn: str, status_filter: str | None
990
    ) -> bool:
991
        state_machine_reference_arn_set = {ex.state_machine_arn, ex.state_machine_version_arn}
1✔
992
        if state_machine_arn not in state_machine_reference_arn_set:
1✔
993
            return False
1✔
994

995
        if not status_filter:
1✔
996
            return True
1✔
997
        return ex.exec_status == status_filter
1✔
998

999
    def list_executions(
1✔
1000
        self,
1001
        context: RequestContext,
1002
        state_machine_arn: Arn = None,
1003
        status_filter: ExecutionStatus = None,
1004
        max_results: PageSize = None,
1005
        next_token: ListExecutionsPageToken = None,
1006
        map_run_arn: LongArn = None,
1007
        redrive_filter: ExecutionRedriveFilter = None,
1008
        **kwargs,
1009
    ) -> ListExecutionsOutput:
1010
        self._validate_state_machine_arn(state_machine_arn)
1✔
1011
        assert_pagination_parameters_valid(
1✔
1012
            max_results=max_results,
1013
            next_token=next_token,
1014
            next_token_length_limit=3096,
1015
        )
1016
        max_results = normalise_max_results(max_results)
1✔
1017

1018
        state_machine = self.get_store(context).state_machines.get(state_machine_arn)
1✔
1019
        if state_machine is None:
1✔
1020
            self._raise_state_machine_does_not_exist(state_machine_arn)
1✔
1021

1022
        if state_machine.sm_type != StateMachineType.STANDARD:
1✔
1023
            self._raise_state_machine_type_not_supported()
1✔
1024

1025
        # TODO: add support for paging
1026

1027
        allowed_execution_status = [
1✔
1028
            ExecutionStatus.SUCCEEDED,
1029
            ExecutionStatus.TIMED_OUT,
1030
            ExecutionStatus.PENDING_REDRIVE,
1031
            ExecutionStatus.ABORTED,
1032
            ExecutionStatus.FAILED,
1033
            ExecutionStatus.RUNNING,
1034
        ]
1035

1036
        validation_errors = []
1✔
1037

1038
        if status_filter and status_filter not in allowed_execution_status:
1✔
1039
            validation_errors.append(
1✔
1040
                f"Value '{status_filter}' at 'statusFilter' failed to satisfy constraint: Member must satisfy enum value set: [{', '.join(allowed_execution_status)}]"
1041
            )
1042

1043
        if not state_machine_arn and not map_run_arn:
1✔
1044
            validation_errors.append("Must provide a StateMachine ARN or MapRun ARN")
×
1045

1046
        if validation_errors:
1✔
1047
            errors_message = "; ".join(validation_errors)
1✔
1048
            message = f"{len(validation_errors)} validation {'errors' if len(validation_errors) > 1 else 'error'} detected: {errors_message}"
1✔
1049
            raise CommonServiceException(message=message, code="ValidationException")
1✔
1050

1051
        executions: ExecutionList = [
1✔
1052
            execution.to_execution_list_item()
1053
            for execution in self.get_store(context).executions.values()
1054
            if self._list_execution_filter(
1055
                execution,
1056
                state_machine_arn=state_machine_arn,
1057
                status_filter=status_filter,
1058
            )
1059
        ]
1060

1061
        executions.sort(key=lambda item: item["startDate"], reverse=True)
1✔
1062

1063
        paginated_executions = PaginatedList(executions)
1✔
1064
        page, token_for_next_page = paginated_executions.get_page(
1✔
1065
            token_generator=lambda item: get_next_page_token_from_arn(item.get("executionArn")),
1066
            page_size=max_results,
1067
            next_token=next_token,
1068
        )
1069

1070
        return ListExecutionsOutput(executions=page, nextToken=token_for_next_page)
1✔
1071

1072
    def list_state_machines(
1✔
1073
        self,
1074
        context: RequestContext,
1075
        max_results: PageSize = None,
1076
        next_token: PageToken = None,
1077
        **kwargs,
1078
    ) -> ListStateMachinesOutput:
1079
        assert_pagination_parameters_valid(max_results, next_token)
1✔
1080
        max_results = normalise_max_results(max_results)
1✔
1081

1082
        state_machines: StateMachineList = [
1✔
1083
            sm.itemise()
1084
            for sm in self.get_store(context).state_machines.values()
1085
            if isinstance(sm, StateMachineRevision)
1086
        ]
1087
        state_machines.sort(key=lambda item: item["name"])
1✔
1088

1089
        paginated_state_machines = PaginatedList(state_machines)
1✔
1090
        page, token_for_next_page = paginated_state_machines.get_page(
1✔
1091
            token_generator=lambda item: get_next_page_token_from_arn(item.get("stateMachineArn")),
1092
            page_size=max_results,
1093
            next_token=next_token,
1094
        )
1095

1096
        return ListStateMachinesOutput(stateMachines=page, nextToken=token_for_next_page)
1✔
1097

1098
    def list_state_machine_aliases(
1✔
1099
        self,
1100
        context: RequestContext,
1101
        state_machine_arn: Arn,
1102
        next_token: PageToken = None,
1103
        max_results: PageSize = None,
1104
        **kwargs,
1105
    ) -> ListStateMachineAliasesOutput:
1106
        assert_pagination_parameters_valid(max_results, next_token)
1✔
1107

1108
        self._validate_state_machine_arn(state_machine_arn)
1✔
1109
        state_machines = self.get_store(context).state_machines
1✔
1110
        state_machine_revision = state_machines.get(state_machine_arn)
1✔
1111
        if not isinstance(state_machine_revision, StateMachineRevision):
1✔
1112
            raise InvalidArn(f"Invalid arn: {state_machine_arn}")
×
1113

1114
        state_machine_aliases: StateMachineAliasList = []
1✔
1115
        valid_token_found = next_token is None
1✔
1116

1117
        for alias in state_machine_revision.aliases:
1✔
1118
            state_machine_aliases.append(alias.to_item())
1✔
1119
            if alias.tokenized_state_machine_alias_arn == next_token:
1✔
1120
                valid_token_found = True
1✔
1121

1122
        if not valid_token_found:
1✔
1123
            raise InvalidToken("Invalid Token: 'Invalid token'")
1✔
1124

1125
        state_machine_aliases.sort(key=lambda item: item["creationDate"])
1✔
1126

1127
        paginated_list = PaginatedList(state_machine_aliases)
1✔
1128

1129
        paginated_aliases, next_token = paginated_list.get_page(
1✔
1130
            token_generator=lambda item: get_next_page_token_from_arn(
1131
                item.get("stateMachineAliasArn")
1132
            ),
1133
            next_token=next_token,
1134
            page_size=100 if max_results == 0 or max_results is None else max_results,
1135
        )
1136

1137
        return ListStateMachineAliasesOutput(
1✔
1138
            stateMachineAliases=paginated_aliases, nextToken=next_token
1139
        )
1140

1141
    def list_state_machine_versions(
1✔
1142
        self,
1143
        context: RequestContext,
1144
        state_machine_arn: Arn,
1145
        next_token: PageToken = None,
1146
        max_results: PageSize = None,
1147
        **kwargs,
1148
    ) -> ListStateMachineVersionsOutput:
1149
        self._validate_state_machine_arn(state_machine_arn)
1✔
1150
        assert_pagination_parameters_valid(max_results, next_token)
1✔
1151
        max_results = normalise_max_results(max_results)
1✔
1152

1153
        state_machines = self.get_store(context).state_machines
1✔
1154
        state_machine_revision = state_machines.get(state_machine_arn)
1✔
1155
        if not isinstance(state_machine_revision, StateMachineRevision):
1✔
1156
            raise InvalidArn(f"Invalid arn: {state_machine_arn}")
×
1157

1158
        state_machine_version_items = []
1✔
1159
        for version_arn in state_machine_revision.versions.values():
1✔
1160
            state_machine_version = state_machines[version_arn]
1✔
1161
            if isinstance(state_machine_version, StateMachineVersion):
1✔
1162
                state_machine_version_items.append(state_machine_version.itemise())
1✔
1163
            else:
1164
                raise RuntimeError(
×
1165
                    f"Expected {version_arn} to be a StateMachine Version, but got '{type(state_machine_version)}'."
1166
                )
1167

1168
        state_machine_version_items.sort(key=lambda item: item["creationDate"], reverse=True)
1✔
1169

1170
        paginated_state_machine_versions = PaginatedList(state_machine_version_items)
1✔
1171
        page, token_for_next_page = paginated_state_machine_versions.get_page(
1✔
1172
            token_generator=lambda item: get_next_page_token_from_arn(
1173
                item.get("stateMachineVersionArn")
1174
            ),
1175
            page_size=max_results,
1176
            next_token=next_token,
1177
        )
1178

1179
        return ListStateMachineVersionsOutput(
1✔
1180
            stateMachineVersions=page, nextToken=token_for_next_page
1181
        )
1182

1183
    def get_execution_history(
1✔
1184
        self,
1185
        context: RequestContext,
1186
        execution_arn: Arn,
1187
        max_results: PageSize = None,
1188
        reverse_order: ReverseOrder = None,
1189
        next_token: PageToken = None,
1190
        include_execution_data: IncludeExecutionDataGetExecutionHistory = None,
1191
        **kwargs,
1192
    ) -> GetExecutionHistoryOutput:
1193
        # TODO: add support for paging, ordering, and other manipulations.
1194
        self._validate_state_machine_execution_arn(execution_arn)
1✔
1195
        execution: Execution = self._get_execution(context=context, execution_arn=execution_arn)
1✔
1196

1197
        # Action only compatible with STANDARD workflows.
1198
        if execution.sm_type != StateMachineType.STANDARD:
1✔
1199
            self._raise_resource_type_not_in_context(resource_type=execution.sm_type)
1✔
1200

1201
        history: GetExecutionHistoryOutput = execution.to_history_output()
1✔
1202
        if reverse_order:
1✔
1203
            history["events"].reverse()
1✔
1204
        return history
1✔
1205

1206
    def delete_state_machine(
1✔
1207
        self, context: RequestContext, state_machine_arn: Arn, **kwargs
1208
    ) -> DeleteStateMachineOutput:
1209
        # TODO: halt executions?
1210
        self._validate_state_machine_arn(state_machine_arn)
1✔
1211
        state_machines = self.get_store(context).state_machines
1✔
1212
        state_machine = state_machines.get(state_machine_arn)
1✔
1213
        if isinstance(state_machine, StateMachineRevision):
1✔
1214
            state_machines.pop(state_machine_arn)
1✔
1215
            for version_arn in state_machine.versions.values():
1✔
1216
                state_machines.pop(version_arn, None)
1✔
1217
        return DeleteStateMachineOutput()
1✔
1218

1219
    def delete_state_machine_alias(
1✔
1220
        self, context: RequestContext, state_machine_alias_arn: Arn, **kwargs
1221
    ) -> DeleteStateMachineAliasOutput:
1222
        self._validate_state_machine_alias_arn(state_machine_alias_arn=state_machine_alias_arn)
1✔
1223
        store = self.get_store(context=context)
1✔
1224
        aliases = store.aliases
1✔
1225
        if (alias := aliases.pop(state_machine_alias_arn, None)) is not None:
1✔
1226
            state_machines = store.state_machines
1✔
1227
            for routing_configuration in alias.get_routing_configuration_list():
1✔
1228
                state_machine_version_arn = routing_configuration["stateMachineVersionArn"]
1✔
1229
                if (
1✔
1230
                    state_machine_version := state_machines.get(state_machine_version_arn)
1231
                ) is None or not isinstance(state_machine_version, StateMachineVersion):
1232
                    continue
1✔
1233
                if (
1✔
1234
                    state_machine_revision := state_machines.get(state_machine_version.source_arn)
1235
                ) is None or not isinstance(state_machine_revision, StateMachineRevision):
1236
                    continue
×
1237
                state_machine_revision.aliases.discard(alias)
1✔
1238
        return DeleteStateMachineOutput()
1✔
1239

1240
    def delete_state_machine_version(
1✔
1241
        self, context: RequestContext, state_machine_version_arn: LongArn, **kwargs
1242
    ) -> DeleteStateMachineVersionOutput:
1243
        self._validate_state_machine_arn(state_machine_version_arn)
1✔
1244
        state_machines = self.get_store(context).state_machines
1✔
1245

1246
        if not (
1✔
1247
            state_machine_version := state_machines.get(state_machine_version_arn)
1248
        ) or not isinstance(state_machine_version, StateMachineVersion):
1249
            return DeleteStateMachineVersionOutput()
1✔
1250

1251
        if (
1✔
1252
            state_machine_revision := state_machines.get(state_machine_version.source_arn)
1253
        ) and isinstance(state_machine_revision, StateMachineRevision):
1254
            referencing_alias_names: list[str] = []
1✔
1255
            for alias in state_machine_revision.aliases:
1✔
1256
                if alias.is_router_for(state_machine_version_arn=state_machine_version_arn):
1✔
1257
                    referencing_alias_names.append(alias.name)
1✔
1258
            if referencing_alias_names:
1✔
1259
                referencing_alias_names_list_body = ", ".join(referencing_alias_names)
1✔
1260
                raise ConflictException(
1✔
1261
                    "Version to be deleted must not be referenced by an alias. "
1262
                    f"Current list of aliases referencing this version: [{referencing_alias_names_list_body}]"
1263
                )
1264
            state_machine_revision.delete_version(state_machine_version_arn)
1✔
1265

1266
        state_machines.pop(state_machine_version.arn, None)
1✔
1267
        return DeleteStateMachineVersionOutput()
1✔
1268

1269
    def stop_execution(
1✔
1270
        self,
1271
        context: RequestContext,
1272
        execution_arn: Arn,
1273
        error: SensitiveError = None,
1274
        cause: SensitiveCause = None,
1275
        **kwargs,
1276
    ) -> StopExecutionOutput:
1277
        self._validate_state_machine_execution_arn(execution_arn)
1✔
1278
        execution: Execution = self._get_execution(context=context, execution_arn=execution_arn)
1✔
1279

1280
        # Action only compatible with STANDARD workflows.
1281
        if execution.sm_type != StateMachineType.STANDARD:
1✔
1282
            self._raise_resource_type_not_in_context(resource_type=execution.sm_type)
1✔
1283

1284
        stop_date = datetime.datetime.now(tz=datetime.UTC)
1✔
1285
        execution.stop(stop_date=stop_date, cause=cause, error=error)
1✔
1286
        return StopExecutionOutput(stopDate=stop_date)
1✔
1287

1288
    def update_state_machine(
1✔
1289
        self,
1290
        context: RequestContext,
1291
        state_machine_arn: Arn,
1292
        definition: Definition = None,
1293
        role_arn: Arn = None,
1294
        logging_configuration: LoggingConfiguration = None,
1295
        tracing_configuration: TracingConfiguration = None,
1296
        publish: Publish = None,
1297
        version_description: VersionDescription = None,
1298
        encryption_configuration: EncryptionConfiguration = None,
1299
        **kwargs,
1300
    ) -> UpdateStateMachineOutput:
1301
        self._validate_state_machine_arn(state_machine_arn)
1✔
1302
        state_machines = self.get_store(context).state_machines
1✔
1303

1304
        state_machine = state_machines.get(state_machine_arn)
1✔
1305
        if not isinstance(state_machine, StateMachineRevision):
1✔
1306
            self._raise_state_machine_does_not_exist(state_machine_arn)
1✔
1307

1308
        # TODO: Add logic to handle metrics for when SFN definitions update
1309
        if not any([definition, role_arn, logging_configuration]):
1✔
1310
            raise MissingRequiredParameter(
1✔
1311
                "Either the definition, the role ARN, the LoggingConfiguration, "
1312
                "or the TracingConfiguration must be specified"
1313
            )
1314

1315
        if definition is not None:
1✔
1316
            self._validate_definition(definition=definition, static_analysers=[StaticAnalyser()])
1✔
1317

1318
        if logging_configuration is not None:
1✔
1319
            self._sanitise_logging_configuration(logging_configuration=logging_configuration)
1✔
1320

1321
        revision_id = state_machine.create_revision(
1✔
1322
            definition=definition,
1323
            role_arn=role_arn,
1324
            logging_configuration=logging_configuration,
1325
        )
1326

1327
        version_arn = None
1✔
1328
        if publish:
1✔
1329
            version = state_machine.create_version(description=version_description)
1✔
1330
            if version is not None:
1✔
1331
                version_arn = version.arn
1✔
1332
                state_machines[version_arn] = version
1✔
1333
            else:
1334
                target_revision_id = revision_id or state_machine.revision_id
1✔
1335
                version_arn = state_machine.versions[target_revision_id]
1✔
1336

1337
        update_output = UpdateStateMachineOutput(updateDate=datetime.datetime.now(tz=datetime.UTC))
1✔
1338
        if revision_id is not None:
1✔
1339
            update_output["revisionId"] = revision_id
1✔
1340
        if version_arn is not None:
1✔
1341
            update_output["stateMachineVersionArn"] = version_arn
1✔
1342
        return update_output
1✔
1343

1344
    def update_state_machine_alias(
1✔
1345
        self,
1346
        context: RequestContext,
1347
        state_machine_alias_arn: Arn,
1348
        description: AliasDescription = None,
1349
        routing_configuration: RoutingConfigurationList = None,
1350
        **kwargs,
1351
    ) -> UpdateStateMachineAliasOutput:
1352
        self._validate_state_machine_alias_arn(state_machine_alias_arn=state_machine_alias_arn)
1✔
1353
        if not any([description, routing_configuration]):
1✔
1354
            raise MissingRequiredParameter(
×
1355
                "Either the description or the RoutingConfiguration must be specified"
1356
            )
1357
        if routing_configuration is not None:
1✔
1358
            self._validate_state_machine_alias_routing_configuration(
1✔
1359
                context=context, routing_configuration_list=routing_configuration
1360
            )
1361
        store = self.get_store(context=context)
1✔
1362
        alias = store.aliases.get(state_machine_alias_arn)
1✔
1363
        if alias is None:
1✔
1364
            raise ResourceNotFound("Request references a resource that does not exist.")
1✔
1365

1366
        alias.update(description=description, routing_configuration_list=routing_configuration)
1✔
1367
        return UpdateStateMachineAliasOutput(updateDate=alias.update_date)
1✔
1368

1369
    def publish_state_machine_version(
1✔
1370
        self,
1371
        context: RequestContext,
1372
        state_machine_arn: Arn,
1373
        revision_id: RevisionId = None,
1374
        description: VersionDescription = None,
1375
        **kwargs,
1376
    ) -> PublishStateMachineVersionOutput:
1377
        self._validate_state_machine_arn(state_machine_arn)
1✔
1378
        state_machines = self.get_store(context).state_machines
1✔
1379

1380
        state_machine_revision = state_machines.get(state_machine_arn)
1✔
1381
        if not isinstance(state_machine_revision, StateMachineRevision):
1✔
1382
            self._raise_state_machine_does_not_exist(state_machine_arn)
1✔
1383

1384
        if revision_id is not None and state_machine_revision.revision_id != revision_id:
1✔
1385
            raise ConflictException(
1✔
1386
                f"Failed to publish the State Machine version for revision {revision_id}. "
1387
                f"The current State Machine revision is {state_machine_revision.revision_id}."
1388
            )
1389

1390
        state_machine_version = state_machine_revision.create_version(description=description)
1✔
1391
        if state_machine_version is not None:
1✔
1392
            state_machines[state_machine_version.arn] = state_machine_version
1✔
1393
        else:
1394
            target_revision_id = revision_id or state_machine_revision.revision_id
1✔
1395
            state_machine_version_arn = state_machine_revision.versions.get(target_revision_id)
1✔
1396
            state_machine_version = state_machines[state_machine_version_arn]
1✔
1397

1398
        return PublishStateMachineVersionOutput(
1✔
1399
            creationDate=state_machine_version.create_date,
1400
            stateMachineVersionArn=state_machine_version.arn,
1401
        )
1402

1403
    def tag_resource(
1✔
1404
        self, context: RequestContext, resource_arn: Arn, tags: TagList, **kwargs
1405
    ) -> TagResourceOutput:
1406
        # TODO: add tagging for activities.
1407
        state_machines = self.get_store(context).state_machines
1✔
1408
        state_machine = state_machines.get(resource_arn)
1✔
1409
        if not isinstance(state_machine, StateMachineRevision):
1✔
1410
            raise ResourceNotFound(f"Resource not found: '{resource_arn}'")
1✔
1411

1412
        state_machine.tag_manager.add_all(tags)
1✔
1413
        return TagResourceOutput()
1✔
1414

1415
    def untag_resource(
1✔
1416
        self, context: RequestContext, resource_arn: Arn, tag_keys: TagKeyList, **kwargs
1417
    ) -> UntagResourceOutput:
1418
        # TODO: add untagging for activities.
1419
        state_machines = self.get_store(context).state_machines
1✔
1420
        state_machine = state_machines.get(resource_arn)
1✔
1421
        if not isinstance(state_machine, StateMachineRevision):
1✔
1422
            raise ResourceNotFound(f"Resource not found: '{resource_arn}'")
×
1423

1424
        state_machine.tag_manager.remove_all(tag_keys)
1✔
1425
        return UntagResourceOutput()
1✔
1426

1427
    def list_tags_for_resource(
1✔
1428
        self, context: RequestContext, resource_arn: Arn, **kwargs
1429
    ) -> ListTagsForResourceOutput:
1430
        # TODO: add untagging for activities.
1431
        state_machines = self.get_store(context).state_machines
1✔
1432
        state_machine = state_machines.get(resource_arn)
1✔
1433
        if not isinstance(state_machine, StateMachineRevision):
1✔
1434
            raise ResourceNotFound(f"Resource not found: '{resource_arn}'")
×
1435

1436
        tags: TagList = state_machine.tag_manager.to_tag_list()
1✔
1437
        return ListTagsForResourceOutput(tags=tags)
1✔
1438

1439
    def describe_map_run(
1✔
1440
        self, context: RequestContext, map_run_arn: LongArn, **kwargs
1441
    ) -> DescribeMapRunOutput:
1442
        store = self.get_store(context)
1✔
1443
        for execution in store.executions.values():
1✔
1444
            map_run_record: MapRunRecord | None = (
1✔
1445
                execution.exec_worker.env.map_run_record_pool_manager.get(map_run_arn)
1446
            )
1447
            if map_run_record is not None:
1✔
1448
                return map_run_record.describe()
1✔
1449
        raise ResourceNotFound()
×
1450

1451
    def list_map_runs(
1✔
1452
        self,
1453
        context: RequestContext,
1454
        execution_arn: Arn,
1455
        max_results: PageSize = None,
1456
        next_token: PageToken = None,
1457
        **kwargs,
1458
    ) -> ListMapRunsOutput:
1459
        # TODO: add support for paging.
1460
        execution = self._get_execution(context=context, execution_arn=execution_arn)
1✔
1461
        map_run_records: list[MapRunRecord] = (
1✔
1462
            execution.exec_worker.env.map_run_record_pool_manager.get_all()
1463
        )
1464
        return ListMapRunsOutput(
1✔
1465
            mapRuns=[map_run_record.list_item() for map_run_record in map_run_records]
1466
        )
1467

1468
    def update_map_run(
1✔
1469
        self,
1470
        context: RequestContext,
1471
        map_run_arn: LongArn,
1472
        max_concurrency: MaxConcurrency = None,
1473
        tolerated_failure_percentage: ToleratedFailurePercentage = None,
1474
        tolerated_failure_count: ToleratedFailureCount = None,
1475
        **kwargs,
1476
    ) -> UpdateMapRunOutput:
1477
        if tolerated_failure_percentage is not None or tolerated_failure_count is not None:
×
1478
            raise NotImplementedError(
1479
                "Updating of ToleratedFailureCount and ToleratedFailurePercentage is currently unsupported."
1480
            )
1481
        # TODO: investigate behaviour of empty requests.
1482
        store = self.get_store(context)
×
1483
        for execution in store.executions.values():
×
1484
            map_run_record: MapRunRecord | None = (
×
1485
                execution.exec_worker.env.map_run_record_pool_manager.get(map_run_arn)
1486
            )
1487
            if map_run_record is not None:
×
1488
                map_run_record.update(
×
1489
                    max_concurrency=max_concurrency,
1490
                    tolerated_failure_count=tolerated_failure_count,
1491
                    tolerated_failure_percentage=tolerated_failure_percentage,
1492
                )
1493
                LOG.warning(
×
1494
                    "StepFunctions UpdateMapRun changes are currently not being reflected in the MapRun instances."
1495
                )
1496
                return UpdateMapRunOutput()
×
1497
        raise ResourceNotFound()
×
1498

1499
    def test_state(
1✔
1500
        self, context: RequestContext, request: TestStateInput, **kwargs
1501
    ) -> TestStateOutput:
1502
        state_name = request.get("stateName")
1✔
1503
        definition = request["definition"]
1✔
1504

1505
        StepFunctionsProvider._validate_definition(
1✔
1506
            definition=definition,
1507
            static_analysers=[TestStateStaticAnalyser(state_name)],
1508
        )
1509

1510
        # if StateName is present, we need to ensure the state being referenced exists in full definition.
1511
        if state_name and not TestStateStaticAnalyser.is_state_in_definition(
1✔
1512
            definition=definition, state_name=state_name
1513
        ):
1514
            raise ValidationException("State not found in definition")
1✔
1515

1516
        mock_input = request.get("mock")
1✔
1517
        if mock_input is not None:
1✔
1518
            self._validate_test_state_mock_input(mock_input)
1✔
1519
            TestStateStaticAnalyser.validate_mock(
1✔
1520
                mock_input=mock_input, definition=definition, state_name=state_name
1521
            )
1522

1523
        if state_configuration := request.get("stateConfiguration"):
1✔
1524
            # TODO: Add validations for this i.e assert len(input) <= failureCount
1525
            pass
1✔
1526

1527
        if state_context := request.get("context"):
1✔
1528
            # TODO: Add validation ensuring only present if 'mock' is specified
1529
            # An error occurred (ValidationException) when calling the TestState operation: State type 'Pass' is not supported when a mock is specified
1530
            pass
1✔
1531

1532
        try:
1✔
1533
            state_mock = TestStateMock(
1✔
1534
                mock_input=mock_input,
1535
                state_configuration=state_configuration,
1536
                context=state_context,
1537
            )
1538
        except ValueError as e:
1✔
1539
            LOG.error(e)
1✔
1540
            raise ValidationException(f"Invalid Context object provided: {e}")
1✔
1541

1542
        name: Name | None = f"TestState-{short_uid()}"
1✔
1543
        arn = stepfunctions_state_machine_arn(
1✔
1544
            name=name, account_id=context.account_id, region_name=context.region
1545
        )
1546
        state_machine = TestStateMachine(
1✔
1547
            name=name,
1548
            arn=arn,
1549
            role_arn=request["roleArn"],
1550
            definition=request["definition"],
1551
        )
1552

1553
        # HACK(gregfurman): The ARN that gets generated has a duplicate 'name' field in the
1554
        # resource ARN. Just replace this duplication and extract the execution ID.
1555
        exec_arn = stepfunctions_express_execution_arn(state_machine.arn, name)
1✔
1556
        exec_arn = exec_arn.replace(f":{name}:{name}:", f":{name}:", 1)
1✔
1557
        _, exec_name = exec_arn.rsplit(":", 1)
1✔
1558

1559
        if input_json := request.get("input", {}):
1✔
1560
            input_json = json.loads(input_json)
1✔
1561

1562
        execution = TestStateExecution(
1✔
1563
            name=exec_name,
1564
            role_arn=request["roleArn"],
1565
            exec_arn=exec_arn,
1566
            account_id=context.account_id,
1567
            region_name=context.region,
1568
            state_machine=state_machine,
1569
            start_date=datetime.datetime.now(tz=datetime.UTC),
1570
            input_data=input_json,
1571
            state_name=state_name,
1572
            activity_store=self.get_store(context).activities,
1573
            mock=state_mock,
1574
        )
1575
        execution.start()
1✔
1576

1577
        test_state_output = execution.to_test_state_output(
1✔
1578
            inspection_level=request.get("inspectionLevel", InspectionLevel.INFO)
1579
        )
1580

1581
        return test_state_output
1✔
1582

1583
    def create_activity(
1✔
1584
        self,
1585
        context: RequestContext,
1586
        name: Name,
1587
        tags: TagList = None,
1588
        encryption_configuration: EncryptionConfiguration = None,
1589
        **kwargs,
1590
    ) -> CreateActivityOutput:
1591
        self._validate_activity_name(name=name)
1✔
1592

1593
        activity_arn = stepfunctions_activity_arn(
1✔
1594
            name=name, account_id=context.account_id, region_name=context.region
1595
        )
1596
        activities = self.get_store(context).activities
1✔
1597
        if activity_arn not in activities:
1✔
1598
            activity = Activity(arn=activity_arn, name=name)
1✔
1599
            activities[activity_arn] = activity
1✔
1600
        else:
1601
            activity = activities[activity_arn]
1✔
1602

1603
        return CreateActivityOutput(activityArn=activity.arn, creationDate=activity.creation_date)
1✔
1604

1605
    def delete_activity(
1✔
1606
        self, context: RequestContext, activity_arn: Arn, **kwargs
1607
    ) -> DeleteActivityOutput:
1608
        self._validate_activity_arn(activity_arn)
1✔
1609
        self.get_store(context).activities.pop(activity_arn, None)
1✔
1610
        return DeleteActivityOutput()
1✔
1611

1612
    def describe_activity(
1✔
1613
        self, context: RequestContext, activity_arn: Arn, **kwargs
1614
    ) -> DescribeActivityOutput:
1615
        self._validate_activity_arn(activity_arn)
1✔
1616
        activity = self._get_activity(context=context, activity_arn=activity_arn)
1✔
1617
        return activity.to_describe_activity_output()
1✔
1618

1619
    def list_activities(
1✔
1620
        self,
1621
        context: RequestContext,
1622
        max_results: PageSize = None,
1623
        next_token: PageToken = None,
1624
        **kwargs,
1625
    ) -> ListActivitiesOutput:
1626
        activities: list[Activity] = list(self.get_store(context).activities.values())
1✔
1627
        return ListActivitiesOutput(
1✔
1628
            activities=[activity.to_activity_list_item() for activity in activities]
1629
        )
1630

1631
    def _send_activity_task_started(
1✔
1632
        self,
1633
        context: RequestContext,
1634
        task_token: TaskToken,
1635
        worker_name: Name | None,
1636
    ) -> None:
1637
        executions: list[Execution] = self._get_executions(context)
1✔
1638
        for execution in executions:
1✔
1639
            callback_endpoint = execution.exec_worker.env.callback_pool_manager.get(
1✔
1640
                callback_id=task_token
1641
            )
1642
            if isinstance(callback_endpoint, ActivityCallbackEndpoint):
1✔
1643
                callback_endpoint.notify_activity_task_start(worker_name=worker_name)
1✔
1644
                return
1✔
1645
        raise InvalidToken()
×
1646

1647
    @staticmethod
1✔
1648
    def _pull_activity_task(activity: Activity) -> ActivityTask | None:
1✔
1649
        seconds_left = 60
1✔
1650
        while seconds_left > 0:
1✔
1651
            try:
1✔
1652
                return activity.get_task()
1✔
1653
            except IndexError:
1✔
1654
                time.sleep(1)
1✔
1655
                seconds_left -= 1
1✔
1656
        return None
×
1657

1658
    def get_activity_task(
1✔
1659
        self,
1660
        context: RequestContext,
1661
        activity_arn: Arn,
1662
        worker_name: Name = None,
1663
        **kwargs,
1664
    ) -> GetActivityTaskOutput:
1665
        self._validate_activity_arn(activity_arn)
1✔
1666

1667
        activity = self._get_activity(context=context, activity_arn=activity_arn)
1✔
1668
        maybe_task: ActivityTask | None = self._pull_activity_task(activity=activity)
1✔
1669
        if maybe_task is not None:
1✔
1670
            self._send_activity_task_started(
1✔
1671
                context, maybe_task.task_token, worker_name=worker_name
1672
            )
1673
            return GetActivityTaskOutput(
1✔
1674
                taskToken=maybe_task.task_token, input=maybe_task.task_input
1675
            )
1676

1677
        return GetActivityTaskOutput(taskToken=None, input=None)
×
1678

1679
    def validate_state_machine_definition(
1✔
1680
        self, context: RequestContext, request: ValidateStateMachineDefinitionInput, **kwargs
1681
    ) -> ValidateStateMachineDefinitionOutput:
1682
        # TODO: increase parity of static analysers, current implementation is an unblocker for this API action.
1683
        # TODO: add support for ValidateStateMachineDefinitionSeverity
1684
        # TODO: add support for ValidateStateMachineDefinitionMaxResult
1685

1686
        state_machine_type: StateMachineType = request.get("type", StateMachineType.STANDARD)
1✔
1687
        definition: str = request["definition"]
1✔
1688

1689
        static_analysers = []
1✔
1690
        if state_machine_type == StateMachineType.STANDARD:
1✔
1691
            static_analysers.append(StaticAnalyser())
1✔
1692
        else:
1693
            static_analysers.append(ExpressStaticAnalyser())
1✔
1694

1695
        diagnostics: ValidateStateMachineDefinitionDiagnosticList = []
1✔
1696
        try:
1✔
1697
            StepFunctionsProvider._validate_definition(
1✔
1698
                definition=definition, static_analysers=static_analysers
1699
            )
1700
            validation_result = ValidateStateMachineDefinitionResultCode.OK
1✔
1701
        except InvalidDefinition as invalid_definition:
1✔
1702
            validation_result = ValidateStateMachineDefinitionResultCode.FAIL
1✔
1703
            diagnostics.append(
1✔
1704
                ValidateStateMachineDefinitionDiagnostic(
1705
                    severity=ValidateStateMachineDefinitionSeverity.ERROR,
1706
                    code="SCHEMA_VALIDATION_FAILED",
1707
                    message=invalid_definition.message,
1708
                )
1709
            )
1710
        except Exception as ex:
×
1711
            validation_result = ValidateStateMachineDefinitionResultCode.FAIL
×
1712
            LOG.error("Unknown error during validation %s", ex)
×
1713

1714
        return ValidateStateMachineDefinitionOutput(
1✔
1715
            result=validation_result, diagnostics=diagnostics, truncated=False
1716
        )
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc