mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(sfn): support mocked service integrations (SFN_MOCK_CONFIG) (#2452)
* feat(sfn): support mocked service integrations (SFN_MOCK_CONFIG) StartExecution accepts a state machine ARN with a test case suffix in the Step Functions Local format. The test case comes from the mock configuration file named by SFN_MOCK_CONFIG. A mocked Task state returns the configured Return payload or fails with the configured Throw error instead of calling the integrated service. The mocked error and cause reach Retry and Catch unchanged. States not named in the test case still call their real integration, so mocked and real calls combine in one execution. Behavior was verified against Step Functions Local 2.0.0. Closes #2283 * fix(sfn): never retry or catch States.Runtime even when named explicitly * fix(sfn): keep a bare trailing '#' unstripped on StartSyncExecution
This commit is contained in:
1 parent
a68bfc4e68
commit
b6418dbfee
13 files changed
+1245
-32
No files matched your search
@@ -1162,6 +1162,16 @@ public interface EmulatorConfig {
|
||||
/** Allows invoking plain HTTP endpoints. By default, AWS only allows HTTPS. */
|
||||
@WithDefault("true")
|
||||
boolean allowPlaintextHttp();
|
||||
|
||||
/**
|
||||
* Path to a Step Functions Local compatible mock configuration file
|
||||
* ({@code MockConfigFile.json}). When set, {@code StartExecution} on
|
||||
* {@code <stateMachineArn>#<testCaseName>} runs the state machine with that test
|
||||
* case's mocked service integration responses. The main application.yml defaults
|
||||
* this to the {@code SFN_MOCK_CONFIG} environment variable for drop-in
|
||||
* compatibility with Step Functions Local.
|
||||
*/
|
||||
Optional<String> mockConfigFile();
|
||||
}
|
||||
|
||||
interface SwfServiceConfig {
|
||||
|
||||
@@ -28,6 +28,8 @@ import io.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsJsonHandler;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.Execution;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.HistoryEvent;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.MockedResponseStep;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.MockedTestCase;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
@@ -71,6 +73,7 @@ import java.util.UUID;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
@@ -154,6 +157,7 @@ public class AslExecutor {
|
||||
private final Instance<StepFunctionsService> sfnService;
|
||||
private final WebClient webClient;
|
||||
private final EmulatorConfig config;
|
||||
private final Map<String, MockedTestCase> activeMocks = new ConcurrentHashMap<>();
|
||||
private final ExecutorService executor = Executors.newCachedThreadPool(r -> {
|
||||
Thread t = new Thread(r, "sfn-executor");
|
||||
t.setDaemon(true);
|
||||
@@ -201,6 +205,18 @@ public class AslExecutor {
|
||||
*/
|
||||
public void executeAsync(StateMachine sm, Execution exec, List<HistoryEvent> history,
|
||||
BiConsumer<Execution, List<HistoryEvent>> onUpdate) {
|
||||
executeAsync(sm, exec, history, null, onUpdate);
|
||||
}
|
||||
|
||||
/**
|
||||
* Variant of {@link #executeAsync(StateMachine, Execution, List, BiConsumer)} that runs the
|
||||
* execution with a mock test case: Task states named in the test case return their mocked
|
||||
* response instead of calling the integrated service.
|
||||
*/
|
||||
public void executeAsync(StateMachine sm, Execution exec, List<HistoryEvent> history,
|
||||
MockedTestCase mockedTestCase,
|
||||
BiConsumer<Execution, List<HistoryEvent>> onUpdate) {
|
||||
registerMocks(exec, mockedTestCase);
|
||||
executor.submit(() -> runUnderExecutionAccount(sm, () -> doExecute(sm, exec, history, onUpdate)));
|
||||
}
|
||||
|
||||
@@ -209,6 +225,17 @@ public class AslExecutor {
|
||||
*/
|
||||
public void executeSync(StateMachine sm, Execution exec, List<HistoryEvent> history,
|
||||
BiConsumer<Execution, List<HistoryEvent>> onUpdate) {
|
||||
executeSync(sm, exec, history, null, onUpdate);
|
||||
}
|
||||
|
||||
/**
|
||||
* Variant of {@link #executeSync(StateMachine, Execution, List, BiConsumer)} that runs the
|
||||
* execution with a mock test case.
|
||||
*/
|
||||
public void executeSync(StateMachine sm, Execution exec, List<HistoryEvent> history,
|
||||
MockedTestCase mockedTestCase,
|
||||
BiConsumer<Execution, List<HistoryEvent>> onUpdate) {
|
||||
registerMocks(exec, mockedTestCase);
|
||||
try {
|
||||
Future<?> f = executor.submit(() ->
|
||||
runUnderExecutionAccount(sm, () -> doExecute(sm, exec, history, onUpdate)));
|
||||
@@ -371,6 +398,14 @@ public class AslExecutor {
|
||||
exec.setStopDate(System.currentTimeMillis() / 1000.0);
|
||||
exec.setStatus("FAILED");
|
||||
onUpdate.accept(exec, history);
|
||||
} finally {
|
||||
activeMocks.remove(exec.getExecutionArn());
|
||||
}
|
||||
}
|
||||
|
||||
private void registerMocks(Execution exec, MockedTestCase mockedTestCase) {
|
||||
if (mockedTestCase != null) {
|
||||
activeMocks.put(exec.getExecutionArn(), mockedTestCase);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -390,7 +425,7 @@ public class AslExecutor {
|
||||
while (true) {
|
||||
try {
|
||||
return executeState(name, type, stateDef, input, history, eventId, sm, jsonata,
|
||||
topLevelQueryLanguage, context, variables);
|
||||
topLevelQueryLanguage, context, variables, attempt);
|
||||
} catch (FailStateException e) {
|
||||
var retrierIndex = findMatchingRetrier(retriers, e);
|
||||
if (retrierIndex < 0) {
|
||||
@@ -455,10 +490,11 @@ public class AslExecutor {
|
||||
private StateResult executeState(String name, String type, JsonNode stateDef, JsonNode input,
|
||||
List<HistoryEvent> history, AtomicLong eventId, StateMachine sm,
|
||||
boolean jsonata, String topLevelQueryLanguage, JsonNode context,
|
||||
ObjectNode variables) throws Exception {
|
||||
ObjectNode variables, int attempt) throws Exception {
|
||||
return switch (type) {
|
||||
case "Pass" -> executePassState(stateDef, input, jsonata, context, variables);
|
||||
case "Task" -> executeTaskState(name, stateDef, input, history, eventId, sm, jsonata, context, variables);
|
||||
case "Task" -> executeTaskState(name, stateDef, input, history, eventId, sm, jsonata, context,
|
||||
variables, attempt);
|
||||
case "Choice" -> executeChoiceState(stateDef, input, jsonata, context, variables);
|
||||
case "Wait" -> executeWaitState(stateDef, input, jsonata, context, variables);
|
||||
case "Succeed" -> executeSucceedState(stateDef, input, jsonata, context, variables);
|
||||
@@ -496,14 +532,18 @@ public class AslExecutor {
|
||||
|
||||
private StateResult executeTaskState(String stateName, JsonNode stateDef, JsonNode input,
|
||||
List<HistoryEvent> history, AtomicLong eventId, StateMachine sm,
|
||||
boolean jsonata, JsonNode context, ObjectNode variables) throws Exception {
|
||||
String resource = stateDef.path("Resource").asText();
|
||||
boolean isWaitForToken = resource.endsWith(".waitForTaskToken");
|
||||
String effectiveResource = isWaitForToken
|
||||
boolean jsonata, JsonNode context, ObjectNode variables,
|
||||
int attempt) throws Exception {
|
||||
var resource = stateDef.path("Resource").asText();
|
||||
var isWaitForToken = resource.endsWith(".waitForTaskToken");
|
||||
var effectiveResource = isWaitForToken
|
||||
? resource.substring(0, resource.length() - ".waitForTaskToken".length())
|
||||
: resource;
|
||||
boolean isActivity = isActivityArn(effectiveResource);
|
||||
boolean needsToken = isWaitForToken || isActivity;
|
||||
var isActivity = isActivityArn(effectiveResource);
|
||||
var mockedSteps = findMockedResponses(context, stateName);
|
||||
// A mocked task never calls the integrated service, so it neither registers a task token
|
||||
// nor waits for one; the mocked response stands in for the whole interaction.
|
||||
var needsToken = mockedSteps == null && (isWaitForToken || isActivity);
|
||||
|
||||
String taskToken = null;
|
||||
CompletableFuture<JsonNode> tokenFuture = null;
|
||||
@@ -515,18 +555,22 @@ public class AslExecutor {
|
||||
|
||||
JsonNode taskResult;
|
||||
if (jsonata) {
|
||||
JsonNode effectiveInput = input;
|
||||
var effectiveInput = input;
|
||||
if (stateDef.has("Arguments")) {
|
||||
JsonNode statesVar = buildStatesVar(input, null, context);
|
||||
var statesVar = buildStatesVar(input, null, context);
|
||||
effectiveInput = jsonataEvaluator.resolveTemplate(stateDef.get("Arguments"), statesVar, variables);
|
||||
}
|
||||
taskResult = invokeResource(effectiveResource, effectiveInput, sm, taskToken);
|
||||
taskResult = mockedSteps != null
|
||||
? mockedTaskResult(mockedSteps, stateName, attempt)
|
||||
: invokeResource(effectiveResource, effectiveInput, sm, taskToken);
|
||||
} else {
|
||||
JsonNode effectiveInput = applyInputPath(stateDef, input);
|
||||
var effectiveInput = applyInputPath(stateDef, input);
|
||||
if (stateDef.has("Parameters")) {
|
||||
effectiveInput = resolveParameters(stateDef.get("Parameters"), effectiveInput, context);
|
||||
}
|
||||
taskResult = invokeResource(effectiveResource, effectiveInput, sm, taskToken);
|
||||
taskResult = mockedSteps != null
|
||||
? mockedTaskResult(mockedSteps, stateName, attempt)
|
||||
: invokeResource(effectiveResource, effectiveInput, sm, taskToken);
|
||||
}
|
||||
|
||||
if (tokenFuture != null) {
|
||||
@@ -547,6 +591,34 @@ public class AslExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
private List<MockedResponseStep> findMockedResponses(JsonNode context, String stateName) {
|
||||
if (activeMocks.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
var executionArn = context.path("Execution").path("Id").asText(null);
|
||||
if (executionArn == null) {
|
||||
return null;
|
||||
}
|
||||
var testCase = activeMocks.get(executionArn);
|
||||
return testCase != null ? testCase.stateResponses().get(stateName) : null;
|
||||
}
|
||||
|
||||
private JsonNode mockedTaskResult(List<MockedResponseStep> steps, String stateName, int attempt) {
|
||||
for (var step : steps) {
|
||||
if (step.covers(attempt)) {
|
||||
if (step.isThrow()) {
|
||||
// The mocked Error and Cause must reach Retry/Catch unchanged; routing them
|
||||
// through integration error translation would rewrite the error name that
|
||||
// catchers match on.
|
||||
throw new FailStateException(step.errorName(), step.errorCause());
|
||||
}
|
||||
return step.returnResult().deepCopy();
|
||||
}
|
||||
}
|
||||
throw new FailStateException("States.Runtime",
|
||||
"No mocked response defined for attempt " + attempt + " of state '" + stateName + "'");
|
||||
}
|
||||
|
||||
private JsonNode awaitToken(CompletableFuture<JsonNode> future, JsonNode stateDef) throws Exception {
|
||||
int timeout = stateDef.path("HeartbeatSeconds").asInt(0);
|
||||
if (timeout <= 0) {
|
||||
@@ -3081,22 +3153,25 @@ public class AslExecutor {
|
||||
}
|
||||
|
||||
private boolean catchMatches(JsonNode catcher, String error) {
|
||||
JsonNode errors = catcher.path("ErrorEquals");
|
||||
var errors = catcher.path("ErrorEquals");
|
||||
if (!errors.isArray()) {
|
||||
return false;
|
||||
}
|
||||
// States.Runtime is never retried or caught, even when named explicitly in
|
||||
// ErrorEquals. Verified against real AWS: the execution fails immediately.
|
||||
if ("States.Runtime".equals(error)) {
|
||||
return false;
|
||||
}
|
||||
for (JsonNode candidate : errors) {
|
||||
String expected = candidate.asText();
|
||||
var expected = candidate.asText();
|
||||
if (expected.equals(error)) {
|
||||
return true;
|
||||
}
|
||||
if ("States.TaskFailed".equals(expected)
|
||||
&& !"States.Timeout".equals(error)
|
||||
&& !"States.Runtime".equals(error)) {
|
||||
&& !"States.Timeout".equals(error)) {
|
||||
return true;
|
||||
}
|
||||
if ("States.ALL".equals(expected)
|
||||
&& !"States.Runtime".equals(error)
|
||||
&& !"States.DataLimitExceeded".equals(error)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
package io.github.hectorvent.floci.services.stepfunctions;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.MockedResponseStep;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.MockedTestCase;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Loads the Step Functions Local compatible mock configuration file
|
||||
* ({@code MockConfigFile.json}) referenced by {@code SFN_MOCK_CONFIG} or
|
||||
* {@code floci.services.stepfunctions.mock-config-file}. The file is re-read when its
|
||||
* modification time changes, so it can be edited without restarting the emulator.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class SfnMockLoader {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(SfnMockLoader.class);
|
||||
|
||||
private final Optional<String> configuredPath;
|
||||
private final ObjectMapper objectMapper;
|
||||
private volatile CachedMockFile cache;
|
||||
|
||||
private record CachedMockFile(String path, long lastModified, JsonNode root) {
|
||||
}
|
||||
|
||||
@Inject
|
||||
public SfnMockLoader(EmulatorConfig config, ObjectMapper objectMapper) {
|
||||
this(config.services().stepfunctions().mockConfigFile(), objectMapper);
|
||||
}
|
||||
|
||||
SfnMockLoader(Optional<String> configuredPath, ObjectMapper objectMapper) {
|
||||
this.configuredPath = configuredPath.filter(path -> !path.isBlank());
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a test case selected via {@code StartExecution} on
|
||||
* {@code <stateMachineArn>#<testCaseName>}. Throws {@code ValidationException} when no
|
||||
* mock configuration is configured or the test case cannot be resolved from it.
|
||||
*/
|
||||
public MockedTestCase requireTestCase(String stateMachineName, String testCaseName) {
|
||||
var path = configuredPath.orElseThrow(() -> new AwsException("ValidationException",
|
||||
"Cannot run test case '" + testCaseName + "': no mock configuration file is configured. "
|
||||
+ "Set SFN_MOCK_CONFIG to the path of a mock configuration file.", 400));
|
||||
var root = load(path);
|
||||
var testCases = root.path("StateMachines").path(stateMachineName).path("TestCases");
|
||||
if (!testCases.isObject()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"State machine '" + stateMachineName + "' has no test cases in mock configuration file "
|
||||
+ path, 400);
|
||||
}
|
||||
var testCase = testCases.path(testCaseName);
|
||||
if (!testCase.isObject()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Test case '" + testCaseName + "' is not defined for state machine '" + stateMachineName
|
||||
+ "' in mock configuration file " + path, 400);
|
||||
}
|
||||
var mockedResponses = root.path("MockedResponses");
|
||||
var stateResponses = new LinkedHashMap<String, List<MockedResponseStep>>();
|
||||
testCase.fields().forEachRemaining(entry -> {
|
||||
var stateName = entry.getKey();
|
||||
var responseKey = entry.getValue();
|
||||
if (!responseKey.isTextual()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Test case '" + testCaseName + "' state '" + stateName
|
||||
+ "' must reference a MockedResponses entry by name", 400);
|
||||
}
|
||||
var responseNode = mockedResponses.path(responseKey.asText());
|
||||
if (!responseNode.isObject()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Mocked response '" + responseKey.asText() + "' referenced by test case '"
|
||||
+ testCaseName + "' state '" + stateName + "' is not defined", 400);
|
||||
}
|
||||
stateResponses.put(stateName, parseSteps(responseKey.asText(), responseNode));
|
||||
});
|
||||
LOG.debugv("Resolved mock test case {0}#{1} covering states {2}",
|
||||
stateMachineName, testCaseName, stateResponses.keySet());
|
||||
return new MockedTestCase(stateMachineName, testCaseName, Map.copyOf(stateResponses));
|
||||
}
|
||||
|
||||
private JsonNode load(String path) {
|
||||
var file = Path.of(path);
|
||||
long lastModified;
|
||||
try {
|
||||
lastModified = Files.getLastModifiedTime(file).toMillis();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Mock configuration file not found: " + path, 400);
|
||||
}
|
||||
var cached = cache;
|
||||
if (cached != null && cached.path().equals(path) && cached.lastModified() == lastModified) {
|
||||
return cached.root();
|
||||
}
|
||||
JsonNode root;
|
||||
try {
|
||||
root = objectMapper.readTree(Files.readAllBytes(file));
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Failed to read mock configuration file " + path + ": " + e.getMessage(), 400);
|
||||
}
|
||||
if (root == null || !root.isObject()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Mock configuration file " + path + " must contain a JSON object", 400);
|
||||
}
|
||||
cache = new CachedMockFile(path, lastModified, root);
|
||||
return root;
|
||||
}
|
||||
|
||||
private List<MockedResponseStep> parseSteps(String responseKey, JsonNode responseNode) {
|
||||
var steps = new ArrayList<MockedResponseStep>();
|
||||
responseNode.fields().forEachRemaining(
|
||||
entry -> steps.add(parseStep(responseKey, entry.getKey(), entry.getValue())));
|
||||
if (steps.isEmpty()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Mocked response '" + responseKey + "' must define at least one attempt entry", 400);
|
||||
}
|
||||
steps.sort(Comparator.comparingInt(MockedResponseStep::fromAttempt));
|
||||
return List.copyOf(steps);
|
||||
}
|
||||
|
||||
private MockedResponseStep parseStep(String responseKey, String attemptRange, JsonNode step) {
|
||||
var range = parseAttemptRange(responseKey, attemptRange);
|
||||
var returnNode = step.get("Return");
|
||||
var throwNode = step.get("Throw");
|
||||
if ((returnNode == null) == (throwNode == null)) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Mocked response '" + responseKey + "' attempt '" + attemptRange
|
||||
+ "' must contain exactly one of Return or Throw", 400);
|
||||
}
|
||||
if (returnNode != null) {
|
||||
return new MockedResponseStep(range[0], range[1], returnNode, null, null);
|
||||
}
|
||||
var error = throwNode.path("Error").asText(null);
|
||||
if (error == null || error.isBlank()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Mocked response '" + responseKey + "' attempt '" + attemptRange
|
||||
+ "' Throw must contain a non-empty Error", 400);
|
||||
}
|
||||
return new MockedResponseStep(range[0], range[1], null, error, throwNode.path("Cause").asText(""));
|
||||
}
|
||||
|
||||
private int[] parseAttemptRange(String responseKey, String attemptRange) {
|
||||
try {
|
||||
var separator = attemptRange.indexOf('-');
|
||||
int from;
|
||||
int to;
|
||||
if (separator < 0) {
|
||||
from = Integer.parseInt(attemptRange.trim());
|
||||
to = from;
|
||||
} else {
|
||||
from = Integer.parseInt(attemptRange.substring(0, separator).trim());
|
||||
to = Integer.parseInt(attemptRange.substring(separator + 1).trim());
|
||||
}
|
||||
if (from < 0 || to < from) {
|
||||
throw new NumberFormatException(attemptRange);
|
||||
}
|
||||
return new int[] {from, to};
|
||||
} catch (NumberFormatException e) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Mocked response '" + responseKey + "' has an invalid attempt key '" + attemptRange
|
||||
+ "'; expected a number like \"0\" or a range like \"1-2\"", 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
+83
-13
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.stepfunctions.model.Activity;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.ActivityTask;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.Execution;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.HistoryEvent;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.MockedTestCase;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.StateMachineVersion;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
@@ -45,6 +46,7 @@ public class StepFunctionsService implements Resettable {
|
||||
private final RegionResolver regionResolver;
|
||||
private final AslExecutor aslExecutor;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final SfnMockLoader mockLoader;
|
||||
|
||||
// Fields that are valid only in JSONPath mode. Validated against real AWS:
|
||||
// creating a JSONata state machine with any of these fields returns SCHEMA_VALIDATION_FAILED.
|
||||
@@ -62,7 +64,8 @@ public class StepFunctionsService implements Resettable {
|
||||
|
||||
@Inject
|
||||
public StepFunctionsService(StorageFactory storageFactory, RegionResolver regionResolver,
|
||||
AslExecutor aslExecutor, ObjectMapper objectMapper) {
|
||||
AslExecutor aslExecutor, ObjectMapper objectMapper,
|
||||
SfnMockLoader mockLoader) {
|
||||
this.stateMachineStore = storageFactory.create("stepfunctions", "sfn-state-machines.json",
|
||||
new TypeReference<Map<String, StateMachine>>() {});
|
||||
this.executionStore = storageFactory.create("stepfunctions", "sfn-executions.json",
|
||||
@@ -72,6 +75,7 @@ public class StepFunctionsService implements Resettable {
|
||||
this.regionResolver = regionResolver;
|
||||
this.aslExecutor = aslExecutor;
|
||||
this.objectMapper = objectMapper;
|
||||
this.mockLoader = mockLoader;
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
@@ -457,25 +461,27 @@ public class StepFunctionsService implements Resettable {
|
||||
// ──────────────────────────── Executions ────────────────────────────
|
||||
|
||||
public Execution startExecution(String stateMachineArn, String name, String input, String region) {
|
||||
StateMachine sm = describeStateMachine(stateMachineArn);
|
||||
String execName = (name != null && !name.isBlank()) ? name : UUID.randomUUID().toString();
|
||||
String arn = regionResolver.buildArn("states", region, "execution:" + sm.getName() + ":" + execName);
|
||||
var selection = splitTestCaseSuffix(stateMachineArn);
|
||||
var sm = describeStateMachine(selection.stateMachineArn());
|
||||
var mockedTestCase = resolveMockedTestCase(sm, selection);
|
||||
var execName = (name != null && !name.isBlank()) ? name : UUID.randomUUID().toString();
|
||||
var arn = regionResolver.buildArn("states", region, "execution:" + sm.getName() + ":" + execName);
|
||||
|
||||
if (executionStore.get(arn).isPresent()) {
|
||||
throw new AwsException("ExecutionAlreadyExists", "Execution already exists: " + arn, 400);
|
||||
}
|
||||
|
||||
Execution exec = new Execution();
|
||||
var exec = new Execution();
|
||||
exec.setExecutionArn(arn);
|
||||
exec.setStateMachineArn(stateMachineArn);
|
||||
exec.setStateMachineArn(selection.stateMachineArn());
|
||||
exec.setName(execName);
|
||||
exec.setInput(input);
|
||||
exec.setStatus("RUNNING");
|
||||
|
||||
executionStore.put(arn, exec);
|
||||
|
||||
List<HistoryEvent> history = new ArrayList<>();
|
||||
HistoryEvent startEvent = new HistoryEvent();
|
||||
var history = new ArrayList<HistoryEvent>();
|
||||
var startEvent = new HistoryEvent();
|
||||
startEvent.setId(1L);
|
||||
startEvent.setType("ExecutionStarted");
|
||||
startEvent.setDetails(Map.of("input", input != null ? input : "{}",
|
||||
@@ -485,7 +491,7 @@ public class StepFunctionsService implements Resettable {
|
||||
|
||||
LOG.infov("Started execution: {0}", arn);
|
||||
|
||||
aslExecutor.executeAsync(sm, exec, history, (updatedExec, updatedHistory) -> {
|
||||
aslExecutor.executeAsync(sm, exec, history, mockedTestCase, (updatedExec, updatedHistory) -> {
|
||||
executionStore.put(updatedExec.getExecutionArn(), updatedExec);
|
||||
historyCache.put(updatedExec.getExecutionArn(), updatedHistory);
|
||||
LOG.infov("Execution {0} completed with status {1}", updatedExec.getExecutionArn(), updatedExec.getStatus());
|
||||
@@ -495,7 +501,16 @@ public class StepFunctionsService implements Resettable {
|
||||
}
|
||||
|
||||
public Execution startSyncExecution(String stateMachineArn, String name, String input, String region) {
|
||||
StateMachine sm = describeStateMachine(stateMachineArn);
|
||||
var selection = splitTestCaseSuffix(stateMachineArn);
|
||||
if (selection.testCaseName() != null) {
|
||||
// Matches Step Functions Local, which rejects a test case suffix here.
|
||||
throw new AwsException("UnsupportedOperation",
|
||||
"Service integration mocking is not supported for the StartSyncExecution operation.",
|
||||
400);
|
||||
}
|
||||
// A bare trailing '#' is not stripped on this operation: Step Functions Local looks up
|
||||
// the raw ARN and fails with StateMachineDoesNotExist, so Floci does the same.
|
||||
var sm = describeStateMachine(stateMachineArn);
|
||||
if (!"EXPRESS".equals(sm.getType())) {
|
||||
throw new AwsException("StateMachineTypeNotSupported",
|
||||
"StartSyncExecution is only supported for EXPRESS state machines", 400);
|
||||
@@ -510,15 +525,15 @@ public class StepFunctionsService implements Resettable {
|
||||
String arn = regionResolver.buildArn("states", region,
|
||||
"express:" + sm.getName() + ":" + startDate + ":" + execName);
|
||||
|
||||
Execution exec = new Execution();
|
||||
var exec = new Execution();
|
||||
exec.setExecutionArn(arn);
|
||||
exec.setStateMachineArn(stateMachineArn);
|
||||
exec.setName(execName);
|
||||
exec.setInput(input);
|
||||
exec.setStatus("RUNNING");
|
||||
|
||||
List<HistoryEvent> history = new ArrayList<>();
|
||||
HistoryEvent startEvent = new HistoryEvent();
|
||||
var history = new ArrayList<HistoryEvent>();
|
||||
var startEvent = new HistoryEvent();
|
||||
startEvent.setId(1L);
|
||||
startEvent.setType("ExecutionStarted");
|
||||
startEvent.setDetails(Map.of("input", input != null ? input : "{}",
|
||||
@@ -532,6 +547,61 @@ public class StepFunctionsService implements Resettable {
|
||||
return exec;
|
||||
}
|
||||
|
||||
private record TestCaseSelection(String stateMachineArn, String testCaseName) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits the Step Functions Local mocked service integration suffix off a
|
||||
* {@code StartExecution} ARN: {@code <stateMachineArn>#<testCaseName>} selects the named
|
||||
* test case from the configured mock configuration file. A bare trailing {@code #} selects
|
||||
* no test case and the execution runs unmocked, matching Step Functions Local.
|
||||
*/
|
||||
private static TestCaseSelection splitTestCaseSuffix(String stateMachineArn) {
|
||||
var separator = stateMachineArn != null ? stateMachineArn.indexOf('#') : -1;
|
||||
if (separator < 0) {
|
||||
return new TestCaseSelection(stateMachineArn, null);
|
||||
}
|
||||
var testCaseName = stateMachineArn.substring(separator + 1);
|
||||
return new TestCaseSelection(stateMachineArn.substring(0, separator),
|
||||
testCaseName.isBlank() ? null : testCaseName);
|
||||
}
|
||||
|
||||
private MockedTestCase resolveMockedTestCase(StateMachine sm, TestCaseSelection selection) {
|
||||
if (selection.testCaseName() == null) {
|
||||
return null;
|
||||
}
|
||||
var mockedTestCase = mockLoader.requireTestCase(sm.getName(), selection.testCaseName());
|
||||
warnOnMockedStatesMissingFromDefinition(sm, mockedTestCase);
|
||||
return mockedTestCase;
|
||||
}
|
||||
|
||||
private void warnOnMockedStatesMissingFromDefinition(StateMachine sm, MockedTestCase testCase) {
|
||||
try {
|
||||
var stateNames = new HashSet<String>();
|
||||
collectStateNames(objectMapper.readTree(sm.getDefinition()), stateNames);
|
||||
for (var stateName : testCase.stateResponses().keySet()) {
|
||||
if (!stateNames.contains(stateName)) {
|
||||
LOG.warnv("Mock test case {0} references state {1} which does not exist in state machine {2}",
|
||||
testCase.testCaseName(), stateName, sm.getName());
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Could not check mocked state names for {0}: {1}", sm.getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static void collectStateNames(JsonNode node, Set<String> names) {
|
||||
if (node.isObject()) {
|
||||
var states = node.get("States");
|
||||
if (states != null && states.isObject()) {
|
||||
states.fieldNames().forEachRemaining(names::add);
|
||||
}
|
||||
node.forEach(child -> collectStateNames(child, names));
|
||||
} else if (node.isArray()) {
|
||||
node.forEach(child -> collectStateNames(child, names));
|
||||
}
|
||||
}
|
||||
|
||||
public Execution describeExecution(String arn) {
|
||||
return executionStore.get(arn)
|
||||
.orElseThrow(() -> new AwsException("ExecutionDoesNotExist", "Execution does not exist", 400));
|
||||
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package io.github.hectorvent.floci.services.stepfunctions.model;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
|
||||
/**
|
||||
* One attempt-keyed entry of a mocked service integration response, parsed from the
|
||||
* Step Functions Local {@code MockConfigFile.json} format. The attempt key {@code "0"}
|
||||
* becomes the range 0..0 and {@code "1-2"} becomes 1..2. Exactly one of
|
||||
* {@code returnResult} (a {@code Return} payload) or {@code errorName}/{@code errorCause}
|
||||
* (a {@code Throw}) is set.
|
||||
*/
|
||||
public record MockedResponseStep(
|
||||
int fromAttempt,
|
||||
int toAttempt,
|
||||
JsonNode returnResult,
|
||||
String errorName,
|
||||
String errorCause) {
|
||||
|
||||
public boolean covers(int attempt) {
|
||||
return attempt >= fromAttempt && attempt <= toAttempt;
|
||||
}
|
||||
|
||||
public boolean isThrow() {
|
||||
return errorName != null;
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package io.github.hectorvent.floci.services.stepfunctions.model;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A resolved mock test case for one execution: state name to the attempt-keyed mocked
|
||||
* responses that replace that Task state's service call. States not present here run
|
||||
* their real integration.
|
||||
*/
|
||||
public record MockedTestCase(
|
||||
String stateMachineName,
|
||||
String testCaseName,
|
||||
Map<String, List<MockedResponseStep>> stateResponses) {
|
||||
}
|
||||
Reference in new issue
Block a user