mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
This commit is contained in:
1 parent
37026b75f1
commit
18bee5b278
7 files changed
+802
-39
No files matched your search
@@ -18,6 +18,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.NullNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
@@ -25,6 +26,9 @@ import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
@@ -46,6 +50,7 @@ public class AslExecutor {
|
||||
private final DynamoDbJsonHandler dynamoDbJsonHandler;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final JsonataEvaluator jsonataEvaluator;
|
||||
private final Instance<StepFunctionsService> sfnService;
|
||||
private final ExecutorService executor = Executors.newCachedThreadPool(r -> {
|
||||
Thread t = new Thread(r, "sfn-executor");
|
||||
t.setDaemon(true);
|
||||
@@ -55,13 +60,15 @@ public class AslExecutor {
|
||||
@Inject
|
||||
public AslExecutor(LambdaExecutorService lambdaExecutor, LambdaFunctionStore functionStore,
|
||||
DynamoDbService dynamoDbService, DynamoDbJsonHandler dynamoDbJsonHandler,
|
||||
ObjectMapper objectMapper, JsonataEvaluator jsonataEvaluator) {
|
||||
ObjectMapper objectMapper, JsonataEvaluator jsonataEvaluator,
|
||||
Instance<StepFunctionsService> sfnService) {
|
||||
this.lambdaExecutor = lambdaExecutor;
|
||||
this.functionStore = functionStore;
|
||||
this.dynamoDbService = dynamoDbService;
|
||||
this.dynamoDbJsonHandler = dynamoDbJsonHandler;
|
||||
this.objectMapper = objectMapper;
|
||||
this.jsonataEvaluator = jsonataEvaluator;
|
||||
this.sfnService = sfnService;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -207,36 +214,74 @@ public class AslExecutor {
|
||||
private StateResult executeTaskState(String stateName, JsonNode stateDef, JsonNode input,
|
||||
List<HistoryEvent> history, AtomicLong eventId, StateMachine sm,
|
||||
boolean jsonata, JsonNode context) throws Exception {
|
||||
String resource = stateDef.path("Resource").asText();
|
||||
boolean isWaitForToken = resource.endsWith(".waitForTaskToken");
|
||||
String effectiveResource = isWaitForToken
|
||||
? resource.substring(0, resource.length() - ".waitForTaskToken".length())
|
||||
: resource;
|
||||
boolean isActivity = isActivityArn(effectiveResource);
|
||||
boolean needsToken = isWaitForToken || isActivity;
|
||||
|
||||
String taskToken = null;
|
||||
CompletableFuture<JsonNode> tokenFuture = null;
|
||||
if (needsToken) {
|
||||
taskToken = UUID.randomUUID().toString();
|
||||
((ObjectNode) context.get("Task")).put("Token", taskToken);
|
||||
tokenFuture = sfnService.get().registerPendingToken(taskToken);
|
||||
}
|
||||
|
||||
JsonNode taskResult;
|
||||
if (jsonata) {
|
||||
JsonNode effectiveInput = input;
|
||||
if (stateDef.has("Arguments")) {
|
||||
JsonNode statesVar = buildStatesVar(input, null, context);
|
||||
effectiveInput = jsonataEvaluator.resolveTemplate(stateDef.get("Arguments"), statesVar);
|
||||
}
|
||||
taskResult = invokeResource(effectiveResource, effectiveInput, sm, taskToken);
|
||||
} else {
|
||||
JsonNode effectiveInput = applyInputPath(stateDef, input);
|
||||
if (stateDef.has("Parameters")) {
|
||||
effectiveInput = resolveParameters(stateDef.get("Parameters"), effectiveInput, context);
|
||||
}
|
||||
taskResult = invokeResource(effectiveResource, effectiveInput, sm, taskToken);
|
||||
}
|
||||
|
||||
String resource = stateDef.path("Resource").asText();
|
||||
JsonNode taskResult = invokeResource(resource, effectiveInput, stateDef, sm);
|
||||
if (tokenFuture != null) {
|
||||
taskResult = awaitToken(tokenFuture, stateDef);
|
||||
}
|
||||
|
||||
if (jsonata) {
|
||||
JsonNode output = applyJsonataOutput(stateDef, input, taskResult, context);
|
||||
|
||||
return new StateResult(output, stateDef.path("Next").asText(null));
|
||||
} else {
|
||||
JsonNode output = mergeResult(stateDef, input, taskResult);
|
||||
output = applyOutputPath(stateDef, input, output);
|
||||
return new StateResult(output, stateDef.path("Next").asText(null));
|
||||
}
|
||||
|
||||
JsonNode effectiveInput = applyInputPath(stateDef, input);
|
||||
if (stateDef.has("Parameters")) {
|
||||
effectiveInput = resolveParameters(stateDef.get("Parameters"), effectiveInput);
|
||||
}
|
||||
|
||||
String resource = stateDef.path("Resource").asText();
|
||||
JsonNode taskResult = invokeResource(resource, effectiveInput, stateDef, sm);
|
||||
|
||||
JsonNode output = mergeResult(stateDef, input, taskResult);
|
||||
output = applyOutputPath(stateDef, input, output);
|
||||
|
||||
String next = stateDef.path("Next").asText(null);
|
||||
return new StateResult(output, next);
|
||||
}
|
||||
|
||||
private JsonNode invokeResource(String resource, JsonNode input, JsonNode stateDef, StateMachine sm) throws Exception {
|
||||
private JsonNode awaitToken(CompletableFuture<JsonNode> future, JsonNode stateDef) throws Exception {
|
||||
int timeout = stateDef.path("HeartbeatSeconds").asInt(0);
|
||||
if (timeout <= 0) {
|
||||
timeout = 300;
|
||||
}
|
||||
try {
|
||||
return future.get(timeout, TimeUnit.SECONDS);
|
||||
} catch (java.util.concurrent.TimeoutException e) {
|
||||
future.cancel(true);
|
||||
throw new FailStateException("States.HeartbeatTimeout",
|
||||
"Task timed out after " + timeout + " seconds");
|
||||
} catch (ExecutionException e) {
|
||||
Throwable cause = e.getCause();
|
||||
if (cause instanceof FailStateException fse) {
|
||||
throw fse;
|
||||
}
|
||||
throw new FailStateException("States.TaskFailed",
|
||||
cause != null ? cause.getMessage() : "Task failed");
|
||||
}
|
||||
}
|
||||
|
||||
private JsonNode invokeResource(String resource, JsonNode input, StateMachine sm, String taskToken) throws Exception {
|
||||
// Support Lambda resources: direct ARN or optimized integration
|
||||
String functionName = null;
|
||||
JsonNode lambdaPayload = input;
|
||||
@@ -244,22 +289,15 @@ public class AslExecutor {
|
||||
if (resource.contains(":lambda:") && resource.contains(":function:")) {
|
||||
// Direct Lambda ARN: arn:aws:lambda:region:account:function:name
|
||||
functionName = resource.substring(resource.lastIndexOf(':') + 1);
|
||||
} else if (resource.equals("arn:aws:states:::lambda:invoke") ||
|
||||
resource.equals("arn:aws:states:::lambda:invoke.waitForTaskToken")) {
|
||||
// Optimized Lambda integration — function name comes from Parameters
|
||||
if (stateDef.has("Parameters")) {
|
||||
JsonNode params = stateDef.get("Parameters");
|
||||
String fnRef = params.path("FunctionName").asText(null);
|
||||
if (fnRef == null) fnRef = params.path("FunctionName.$").asText(null);
|
||||
if (fnRef != null) {
|
||||
functionName = fnRef.contains(":") ? fnRef.substring(fnRef.lastIndexOf(':') + 1) : fnRef;
|
||||
}
|
||||
// Payload comes from Payload or Payload.$
|
||||
if (params.has("Payload.$")) {
|
||||
lambdaPayload = resolvePath(params.path("Payload.$").asText(), input);
|
||||
} else if (params.has("Payload")) {
|
||||
lambdaPayload = params.get("Payload");
|
||||
}
|
||||
} else if (resource.equals("arn:aws:states:::lambda:invoke")) {
|
||||
// Optimized Lambda integration — function name and payload come from resolved input
|
||||
String fnRef = input.path("FunctionName").asText(null);
|
||||
if (fnRef != null) {
|
||||
functionName = fnRef.contains(":") ? fnRef.substring(fnRef.lastIndexOf(':') + 1) : fnRef;
|
||||
}
|
||||
JsonNode payload = input.path("Payload");
|
||||
if (!payload.isMissingNode()) {
|
||||
lambdaPayload = payload;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -303,10 +341,102 @@ public class AslExecutor {
|
||||
return invokeAwsSdkDynamoDb(camelCaseAction, input, region);
|
||||
}
|
||||
|
||||
// Nested state machine integration
|
||||
if (resource.startsWith("arn:aws:states:::states:startExecution")) {
|
||||
String mode = resource.substring("arn:aws:states:::states:startExecution".length());
|
||||
String region = extractRegionFromArn(sm.getStateMachineArn());
|
||||
return invokeNestedStateMachine(mode, input, region);
|
||||
}
|
||||
|
||||
// Activity resource: arn:aws:states:{region}:{account}:activity:{name}
|
||||
if (isActivityArn(resource)) {
|
||||
if (taskToken == null) {
|
||||
throw new FailStateException("States.TaskFailed",
|
||||
"Activity resource requires waitForTaskToken: " + resource);
|
||||
}
|
||||
String inputStr = objectMapper.writeValueAsString(input);
|
||||
sfnService.get().enqueueActivityTask(resource, taskToken, inputStr);
|
||||
return NullNode.getInstance(); // caller blocks via token future
|
||||
}
|
||||
|
||||
throw new FailStateException("States.TaskFailed",
|
||||
"Unsupported resource: " + resource);
|
||||
}
|
||||
|
||||
private JsonNode invokeNestedStateMachine(String mode, JsonNode input, String region) throws Exception {
|
||||
String smArn = input.path("StateMachineArn").asText(null);
|
||||
if (smArn == null || smArn.isBlank()) {
|
||||
throw new FailStateException("States.TaskFailed",
|
||||
"StateMachineArn is required for nested state machine execution");
|
||||
}
|
||||
JsonNode inputNode = input.path("Input");
|
||||
String childInput = inputNode.isMissingNode() ? "{}" : objectMapper.writeValueAsString(inputNode);
|
||||
|
||||
io.github.hectorvent.floci.services.stepfunctions.model.Execution exec =
|
||||
sfnService.get().startExecution(smArn, null, childInput, region);
|
||||
String execArn = exec.getExecutionArn();
|
||||
|
||||
if ("".equals(mode)) {
|
||||
// Fire-and-forget: return { executionArn, startDate }
|
||||
ObjectNode result = objectMapper.createObjectNode();
|
||||
result.put("executionArn", execArn);
|
||||
result.put("startDate", exec.getStartDate());
|
||||
return result;
|
||||
}
|
||||
|
||||
// .sync or .sync:2 — poll until terminal
|
||||
for (int i = 0; i < 600; i++) {
|
||||
Thread.sleep(100);
|
||||
io.github.hectorvent.floci.services.stepfunctions.model.Execution current =
|
||||
sfnService.get().describeExecution(execArn);
|
||||
String status = current.getStatus();
|
||||
if ("RUNNING".equals(status)) {
|
||||
continue;
|
||||
}
|
||||
if ("SUCCEEDED".equals(status)) {
|
||||
if (".sync:2".equals(mode)) {
|
||||
String out = current.getOutput();
|
||||
return objectMapper.readTree(out != null ? out : "null");
|
||||
}
|
||||
// .sync — full execution envelope; output field is a JSON string
|
||||
ObjectNode envelope = objectMapper.createObjectNode();
|
||||
envelope.put("executionArn", current.getExecutionArn());
|
||||
envelope.put("stateMachineArn", current.getStateMachineArn());
|
||||
envelope.put("name", current.getName());
|
||||
envelope.put("status", current.getStatus());
|
||||
envelope.put("startDate", current.getStartDate());
|
||||
if (current.getStopDate() != null) {
|
||||
envelope.put("stopDate", current.getStopDate());
|
||||
}
|
||||
if (current.getInput() != null) {
|
||||
envelope.put("input", current.getInput());
|
||||
}
|
||||
if (current.getOutput() != null) {
|
||||
envelope.put("output", current.getOutput());
|
||||
}
|
||||
return envelope;
|
||||
}
|
||||
throw new FailStateException(
|
||||
current.getError() != null ? current.getError() : "States.TaskFailed",
|
||||
current.getCause() != null ? current.getCause()
|
||||
: "Nested execution ended with status: " + status);
|
||||
}
|
||||
throw new FailStateException("States.TaskFailed",
|
||||
"Nested execution timed out: " + execArn);
|
||||
}
|
||||
|
||||
private boolean isActivityArn(String resource) {
|
||||
// arn:aws:states:{region}:{account}:activity:{name}
|
||||
// Distinguish from integration ARNs like arn:aws:states:::lambda:invoke (empty region/account)
|
||||
String[] parts = resource.split(":");
|
||||
return parts.length >= 7
|
||||
&& "arn".equals(parts[0])
|
||||
&& "states".equals(parts[2])
|
||||
&& "activity".equals(parts[5])
|
||||
&& !parts[3].isEmpty()
|
||||
&& !parts[4].isEmpty();
|
||||
}
|
||||
|
||||
private JsonNode invokeDynamoDb(String operation, JsonNode input, String region) {
|
||||
String tableName = input.path("TableName").asText();
|
||||
switch (operation) {
|
||||
@@ -729,6 +859,10 @@ public class AslExecutor {
|
||||
stateMachine.put("Id", sm.getStateMachineArn());
|
||||
stateMachine.put("Name", sm.getName());
|
||||
context.set("StateMachine", stateMachine);
|
||||
// Task node — Token is populated by executeTaskState when waitForTaskToken is active
|
||||
ObjectNode task = objectMapper.createObjectNode();
|
||||
task.putNull("Token");
|
||||
context.set("Task", task);
|
||||
return context;
|
||||
}
|
||||
|
||||
@@ -797,7 +931,7 @@ public class AslExecutor {
|
||||
return resolvePath(path, output);
|
||||
}
|
||||
|
||||
private JsonNode resolveParameters(JsonNode parameters, JsonNode input) throws Exception {
|
||||
private JsonNode resolveParameters(JsonNode parameters, JsonNode input, JsonNode context) throws Exception {
|
||||
if (parameters.isObject()) {
|
||||
ObjectNode resolved = objectMapper.createObjectNode();
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = parameters.fields();
|
||||
@@ -807,7 +941,17 @@ public class AslExecutor {
|
||||
JsonNode val = entry.getValue();
|
||||
if (key.endsWith(".$")) {
|
||||
String realKey = key.substring(0, key.length() - 2);
|
||||
resolved.set(realKey, resolvePath(val.asText(), input));
|
||||
String path = val.asText();
|
||||
if (path.startsWith("$$.")) {
|
||||
// Context reference: $$. → resolve against context as $.
|
||||
resolved.set(realKey, resolvePath("$." + path.substring(3), context));
|
||||
} else if ("$$".equals(path)) {
|
||||
resolved.set(realKey, context);
|
||||
} else {
|
||||
resolved.set(realKey, resolvePath(path, input));
|
||||
}
|
||||
} else if (val.isObject()) {
|
||||
resolved.set(key, resolveParameters(val, input, context));
|
||||
} else {
|
||||
resolved.set(key, val);
|
||||
}
|
||||
|
||||
+54
@@ -5,6 +5,8 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
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.StateMachine;
|
||||
@@ -41,6 +43,11 @@ public class StepFunctionsJsonHandler {
|
||||
case "SendTaskSuccess" -> handleSendTaskSuccess(request);
|
||||
case "SendTaskFailure" -> handleSendTaskFailure(request);
|
||||
case "SendTaskHeartbeat" -> handleSendTaskHeartbeat(request);
|
||||
case "CreateActivity" -> handleCreateActivity(request, region);
|
||||
case "DeleteActivity" -> handleDeleteActivity(request);
|
||||
case "DescribeActivity" -> handleDescribeActivity(request);
|
||||
case "ListActivities" -> handleListActivities(request, region);
|
||||
case "GetActivityTask" -> handleGetActivityTask(request);
|
||||
default -> Response.status(400)
|
||||
.entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported."))
|
||||
.build();
|
||||
@@ -206,4 +213,51 @@ public class StepFunctionsJsonHandler {
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleCreateActivity(JsonNode request, String region) {
|
||||
Activity activity = service.createActivity(request.path("name").asText(), region);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("activityArn", activity.getActivityArn());
|
||||
response.put("creationDate", activity.getCreationDate());
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteActivity(JsonNode request) {
|
||||
service.deleteActivity(request.path("activityArn").asText());
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleDescribeActivity(JsonNode request) {
|
||||
Activity activity = service.describeActivity(request.path("activityArn").asText());
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("activityArn", activity.getActivityArn());
|
||||
response.put("name", activity.getName());
|
||||
response.put("creationDate", activity.getCreationDate());
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleListActivities(JsonNode request, String region) {
|
||||
List<Activity> list = service.listActivities(region);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode array = response.putArray("activities");
|
||||
for (Activity a : list) {
|
||||
ObjectNode item = array.addObject();
|
||||
item.put("activityArn", a.getActivityArn());
|
||||
item.put("name", a.getName());
|
||||
item.put("creationDate", a.getCreationDate());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleGetActivityTask(JsonNode request) {
|
||||
String activityArn = request.path("activityArn").asText();
|
||||
String workerName = request.path("workerName").asText(null);
|
||||
ActivityTask task = service.getActivityTask(activityArn, workerName);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
if (task != null) {
|
||||
response.put("taskToken", task.getTaskToken());
|
||||
response.put("input", task.getInput());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
}
|
||||
+85
-2
@@ -7,6 +7,8 @@ import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
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.StateMachine;
|
||||
@@ -18,7 +20,11 @@ import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@ApplicationScoped
|
||||
public class StepFunctionsService {
|
||||
@@ -27,7 +33,10 @@ public class StepFunctionsService {
|
||||
|
||||
private final StorageBackend<String, StateMachine> stateMachineStore;
|
||||
private final StorageBackend<String, Execution> executionStore;
|
||||
private final StorageBackend<String, Activity> activityStore;
|
||||
private final Map<String, List<HistoryEvent>> historyCache = new ConcurrentHashMap<>();
|
||||
private final Map<String, BlockingQueue<ActivityTask>> activityQueues = new ConcurrentHashMap<>();
|
||||
private final Map<String, CompletableFuture<JsonNode>> pendingTaskTokens = new ConcurrentHashMap<>();
|
||||
private final RegionResolver regionResolver;
|
||||
private final AslExecutor aslExecutor;
|
||||
private final ObjectMapper objectMapper;
|
||||
@@ -44,6 +53,8 @@ public class StepFunctionsService {
|
||||
new TypeReference<Map<String, StateMachine>>() {});
|
||||
this.executionStore = storageFactory.create("stepfunctions", "sfn-executions.json",
|
||||
new TypeReference<Map<String, Execution>>() {});
|
||||
this.activityStore = storageFactory.create("stepfunctions", "sfn-activities.json",
|
||||
new TypeReference<Map<String, Activity>>() {});
|
||||
this.regionResolver = regionResolver;
|
||||
this.aslExecutor = aslExecutor;
|
||||
this.objectMapper = objectMapper;
|
||||
@@ -200,14 +211,86 @@ public class StepFunctionsService {
|
||||
return historyCache.getOrDefault(arn, Collections.emptyList());
|
||||
}
|
||||
|
||||
// ──────────────────────────── Activities ────────────────────────────
|
||||
|
||||
public Activity createActivity(String name, String region) {
|
||||
String arn = regionResolver.buildArn("states", region, "activity:" + name);
|
||||
if (activityStore.get(arn).isPresent()) {
|
||||
throw new AwsException("ActivityAlreadyExists", "Activity already exists: " + arn, 400);
|
||||
}
|
||||
Activity activity = new Activity();
|
||||
activity.setActivityArn(arn);
|
||||
activity.setName(name);
|
||||
activityStore.put(arn, activity);
|
||||
LOG.infov("Created activity: {0}", arn);
|
||||
return activity;
|
||||
}
|
||||
|
||||
public Activity describeActivity(String arn) {
|
||||
return activityStore.get(arn)
|
||||
.orElseThrow(() -> new AwsException("ActivityDoesNotExist", "Activity does not exist: " + arn, 400));
|
||||
}
|
||||
|
||||
public List<Activity> listActivities(String region) {
|
||||
String prefix = "arn:aws:states:" + region + ":";
|
||||
return activityStore.scan(k -> k.startsWith(prefix) && k.contains(":activity:"));
|
||||
}
|
||||
|
||||
public void deleteActivity(String arn) {
|
||||
activityStore.delete(arn);
|
||||
activityQueues.remove(arn);
|
||||
}
|
||||
|
||||
/**
|
||||
* Long-poll: blocks up to 60 seconds waiting for a task to be enqueued for this activity.
|
||||
* Returns null if no task arrives within the timeout.
|
||||
*/
|
||||
public ActivityTask getActivityTask(String activityArn, String workerName) {
|
||||
describeActivity(activityArn); // validate exists
|
||||
BlockingQueue<ActivityTask> queue = activityQueues.computeIfAbsent(activityArn,
|
||||
k -> new LinkedBlockingQueue<>());
|
||||
try {
|
||||
return queue.poll(60, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void enqueueActivityTask(String activityArn, String taskToken, String input) {
|
||||
BlockingQueue<ActivityTask> queue = activityQueues.computeIfAbsent(activityArn,
|
||||
k -> new LinkedBlockingQueue<>());
|
||||
queue.add(new ActivityTask(taskToken, input));
|
||||
}
|
||||
|
||||
public CompletableFuture<JsonNode> registerPendingToken(String token) {
|
||||
CompletableFuture<JsonNode> future = new CompletableFuture<>();
|
||||
pendingTaskTokens.put(token, future);
|
||||
return future;
|
||||
}
|
||||
|
||||
// ──────────────────────────── Tasks ────────────────────────────
|
||||
|
||||
public void sendTaskSuccess(String taskToken, String output) {
|
||||
LOG.infov("Task success received for token {0}", taskToken);
|
||||
CompletableFuture<JsonNode> future = pendingTaskTokens.remove(taskToken);
|
||||
if (future != null) {
|
||||
try {
|
||||
future.complete(objectMapper.readTree(output));
|
||||
} catch (Exception e) {
|
||||
future.completeExceptionally(new RuntimeException("Invalid JSON output: " + e.getMessage()));
|
||||
}
|
||||
} else {
|
||||
LOG.warnv("SendTaskSuccess: no pending task for token {0}", taskToken);
|
||||
}
|
||||
}
|
||||
|
||||
public void sendTaskFailure(String taskToken, String cause, String error) {
|
||||
LOG.infov("Task failure received for token {0}: {1}", taskToken, error);
|
||||
CompletableFuture<JsonNode> future = pendingTaskTokens.remove(taskToken);
|
||||
if (future != null) {
|
||||
future.completeExceptionally(new AslExecutor.FailStateException(error, cause));
|
||||
} else {
|
||||
LOG.warnv("SendTaskFailure: no pending task for token {0}", taskToken);
|
||||
}
|
||||
}
|
||||
|
||||
public void sendTaskHeartbeat(String taskToken) {
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package io.github.hectorvent.floci.services.stepfunctions.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Activity {
|
||||
private String activityArn;
|
||||
private String name;
|
||||
private double creationDate;
|
||||
|
||||
public Activity() {
|
||||
this.creationDate = System.currentTimeMillis() / 1000.0;
|
||||
}
|
||||
|
||||
public String getActivityArn() { return activityArn; }
|
||||
public void setActivityArn(String activityArn) { this.activityArn = activityArn; }
|
||||
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
|
||||
public double getCreationDate() { return creationDate; }
|
||||
public void setCreationDate(double creationDate) { this.creationDate = creationDate; }
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package io.github.hectorvent.floci.services.stepfunctions.model;
|
||||
|
||||
/**
|
||||
* In-memory only — not persisted. Represents a task queued for an activity worker.
|
||||
*/
|
||||
public class ActivityTask {
|
||||
private final String taskToken;
|
||||
private final String input;
|
||||
|
||||
public ActivityTask(String taskToken, String input) {
|
||||
this.taskToken = taskToken;
|
||||
this.input = input;
|
||||
}
|
||||
|
||||
public String getTaskToken() { return taskToken; }
|
||||
public String getInput() { return input; }
|
||||
}
|
||||
Reference in new issue
Block a user