Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,13 @@ public SELF with(Consumer<P> c) {
return self();
}

public SELF correlate(String key, Consumer<ListenTaskBuilder.CorrelatePropertyBuilder> c) {
throw new UnsupportedOperationException(
"correlate is not supported in the engine level: https://github.com/serverlessworkflow/sdk-java/issues/1206");
public SELF correlate(
String key, Consumer<? super AbstractListenTaskBuilder.CorrelatePropertyBuilder> c) {
AbstractListenTaskBuilder.CorrelatePropertyBuilder cb =
new AbstractListenTaskBuilder.CorrelatePropertyBuilder();
c.accept(cb);
correlate.setAdditionalProperty(key, cb.build());
return self();
}

public EventFilter build() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import io.serverlessworkflow.fluent.spec.AbstractEventFilterBuilder;
import io.serverlessworkflow.fluent.spec.AbstractEventPropertiesBuilder;
import io.serverlessworkflow.fluent.spec.AbstractListenTaskBuilder;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
Expand All @@ -41,13 +42,11 @@ protected List<Consumer<EVENT_FILTER>> getFilterSteps() {
return filterSteps;
}

// TODO: "correlate is not supported in the engine level:
// https://github.com/serverlessworkflow/sdk-java/issues/1206". Keeping the code for a future
// reference.
// public SELF correlate(String key, Consumer<ListenTaskBuilder.CorrelatePropertyBuilder> c) {
// filterSteps.add(f -> f.correlate(key, c));
// return self();
// }
public SELF correlate(
String key, Consumer<? super AbstractListenTaskBuilder.CorrelatePropertyBuilder> c) {
addFilterStep(f -> f.correlate(key, c));
return self();
}

@Override
public void accept(EVENT_FILTER filterBuilder) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import io.serverlessworkflow.api.types.AuthenticationPolicyUnion;
import io.serverlessworkflow.api.types.CallHTTP;
import io.serverlessworkflow.api.types.CatchErrors;
import io.serverlessworkflow.api.types.CorrelateProperty;
import io.serverlessworkflow.api.types.Document;
import io.serverlessworkflow.api.types.EmitEventDefinition;
import io.serverlessworkflow.api.types.EmitTask;
Expand Down Expand Up @@ -310,8 +311,12 @@ void testDoTaskListenOne() {
to ->
to.one(
f ->
f.with(
p -> p.type("com.fake.pet").source("mySource"))))))
f.with(p -> p.type("com.fake.pet").source("mySource"))
.correlate(
"orderId",
c ->
c.from("$.data.orderId")
.expect("$.input.orderId"))))))
.build();

List<TaskItem> items = wf.getDo();
Expand All @@ -327,6 +332,10 @@ void testDoTaskListenOne() {
EventFilter filter = one.getOne();
assertNotNull(filter, "EventFilter should be present");
assertEquals("com.fake.pet", filter.getWith().getType(), "Filter type should match");
CorrelateProperty correlate = filter.getCorrelate().getAdditionalProperties().get("orderId");
assertNotNull(correlate, "Correlate property should be present");
assertEquals("$.data.orderId", correlate.getFrom(), "Correlate from should match");
assertEquals("$.input.orderId", correlate.getExpect(), "Correlate expect should match");
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import static io.serverlessworkflow.fluent.spec.dsl.DSL.workflow;
import static org.assertj.core.api.Assertions.assertThat;

import io.serverlessworkflow.api.types.CorrelateProperty;
import io.serverlessworkflow.api.types.HTTPArguments;
import io.serverlessworkflow.api.types.ListenTaskConfiguration;
import io.serverlessworkflow.api.types.RunTaskConfiguration;
Expand Down Expand Up @@ -166,7 +167,15 @@ public void when_listen_any_with_until() {
public void when_listen_one() {
Workflow wf =
WorkflowBuilder.workflow("f", "ns", "1")
.tasks(t -> t.listen(to().one(event().type("only-once"))))
.tasks(
t ->
t.listen(
to().one(
event()
.type("only-once")
.correlate(
"workflowInstanceId",
c -> c.from("$.metadata.instanceId")))))
.build();

var to = wf.getDo().get(0).getTask().getListenTask().getListen().getTo();
Expand All @@ -178,6 +187,10 @@ public void when_listen_one() {
var one = to.getOneEventConsumptionStrategy().getOne();
assertThat(one.getWith()).isNotNull();
assertThat(one.getWith().getType()).isEqualTo("only-once");
CorrelateProperty correlate =
one.getCorrelate().getAdditionalProperties().get("workflowInstanceId");
assertThat(correlate).isNotNull();
assertThat(correlate.getFrom()).isEqualTo("$.metadata.instanceId");
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,4 +92,8 @@ private static <T> Collection<T> iterableToCollection(Iterable<T> t) {
public static <T> Optional<T> as(Collection<?> elements, Class<T> clazz) {
return as(elements, clazz, (item, type) -> item);
}

public static <T> List<T> unmodifiableCopyOf(Collection<T> collection) {
return collection == null ? List.of() : List.copyOf(collection);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ public WorkflowValueResolver<String> resolveString(ExpressionDescriptor desc) {
return processFactories(desc, f -> f.resolveString(desc));
}

@Override
public WorkflowValueResolver<Object> resolveValue(ExpressionDescriptor desc) {
return processFactories(desc, f -> f.resolveValue(desc));
}

@Override
public WorkflowValueResolver<OffsetDateTime> resolveDate(ExpressionDescriptor desc) {
return processFactories(desc, f -> f.resolveDate(desc));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,17 @@
package io.serverlessworkflow.impl.events;

import io.cloudevents.CloudEvent;
import io.serverlessworkflow.api.types.CorrelateProperty;
import io.serverlessworkflow.api.types.EventFilter;
import io.serverlessworkflow.api.types.EventFilterCorrelate;
import io.serverlessworkflow.api.types.EventProperties;
import io.serverlessworkflow.impl.TaskContext;
import io.serverlessworkflow.impl.WorkflowApplication;
import io.serverlessworkflow.impl.WorkflowContext;
import io.serverlessworkflow.impl.WorkflowModel;
import io.serverlessworkflow.impl.WorkflowModelFactory;
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
Expand Down Expand Up @@ -52,8 +57,24 @@ public TypeEventRegistrationBuilder listen(
EventFilter register, WorkflowApplication application) {
EventProperties properties = register.getWith();
String type = properties.getType();
return new TypeEventRegistrationBuilder(
type, application.cloudEventPredicateFactory().build(application, properties));
CloudEventPredicate cePredicate =
application.cloudEventPredicateFactory().build(application, properties);
Collection<CloudEventPredicate> correlationPredicates =
buildCorrelationPredicates(register.getCorrelate(), application);
return new TypeEventRegistrationBuilder(type, cePredicate, correlationPredicates);
}

private Collection<CloudEventPredicate> buildCorrelationPredicates(
EventFilterCorrelate correlate, WorkflowApplication application) {
if (correlate == null || correlate.getAdditionalProperties().isEmpty()) {
return List.of();
}
Collection<CloudEventPredicate> predicates = new ArrayList<>();
for (Map.Entry<String, CorrelateProperty> entry :
correlate.getAdditionalProperties().entrySet()) {
predicates.add(CorrelationPredicate.from(entry.getValue(), application));
}
return predicates;
}

@Override
Expand All @@ -63,18 +84,49 @@ public Collection<TypeEventRegistrationBuilder> listenToAll(WorkflowApplication

private static class CloudEventConsumer extends AbstractCollection<TypeEventRegistration>
implements Consumer<CloudEvent> {
private final WorkflowModelFactory modelFactory;
private Collection<TypeEventRegistration> registrations = new CopyOnWriteArrayList<>();

CloudEventConsumer(WorkflowModelFactory modelFactory) {
this.modelFactory = modelFactory;
}
Comment thread
matheusandre1 marked this conversation as resolved.

@Override
public void accept(CloudEvent ce) {
logger.debug("Received cloud event {}", ce);
for (TypeEventRegistration registration : registrations) {
if (registration.predicate().test(ce, registration.workflow(), registration.task())) {
if (!testCorrelation(ce, registration)) {
continue;
}
registration.consumer().accept(ce);
}
}
}
Comment thread
matheusandre1 marked this conversation as resolved.

private boolean testCorrelation(CloudEvent ce, TypeEventRegistration registration) {
Collection<CloudEventPredicate> predicates = registration.correlationPredicates();
if (predicates.isEmpty()) {
return true;
}
WorkflowModel eventModel = null;
for (CloudEventPredicate pred : predicates) {
if (pred instanceof ModelAwareCloudEventPredicate ma) {
if (eventModel == null) {
eventModel = modelFactory.from(ce);
}
if (!ma.test(eventModel, registration.workflow(), registration.task())) {
return false;
Comment on lines +118 to +119
Copy link
Copy Markdown
Collaborator

@fjtirado fjtirado May 21, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (!ma.test(eventModel, registration.workflow(), registration.task())) {
return false;
return ma.test(eventModel, registration.workflow(), registration.task());

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The loop needs to return false when any predicate fails and true when all pass; this recommendation would only return the first predicate, ignoring the others.

}
} else {
if (!pred.test(ce, registration.workflow(), registration.task())) {
return false;
}
Comment thread
matheusandre1 marked this conversation as resolved.
}
}
return true;
}

@Override
public boolean add(TypeEventRegistration registration) {
return registrations.add(registration);
Expand Down Expand Up @@ -107,12 +159,20 @@ public TypeEventRegistration register(
return new TypeEventRegistration(null, ce, null, workflow, task);
} else {
TypeEventRegistration registration =
new TypeEventRegistration(builder.type(), ce, builder.cePredicate(), workflow, task);
new TypeEventRegistration(
builder.type(),
ce,
builder.cePredicate(),
builder.correlationPredicates(),
workflow,
task);
registrations
.computeIfAbsent(
registration.type(),
k -> {
CloudEventConsumer consumer = new CloudEventConsumer();
WorkflowModelFactory factory =
workflow != null ? workflow.definition().application().modelFactory() : null;
CloudEventConsumer consumer = new CloudEventConsumer(factory);
register(k, consumer);
return consumer;
})
Expand Down
Comment thread
matheusandre1 marked this conversation as resolved.
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/*
* Copyright 2020-Present The Serverless Workflow Specification Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.serverlessworkflow.impl.events;

import io.cloudevents.CloudEvent;
import io.serverlessworkflow.api.types.CorrelateProperty;
import io.serverlessworkflow.impl.TaskContext;
import io.serverlessworkflow.impl.WorkflowApplication;
import io.serverlessworkflow.impl.WorkflowContext;
import io.serverlessworkflow.impl.WorkflowModel;
import io.serverlessworkflow.impl.WorkflowValueResolver;
import io.serverlessworkflow.impl.expressions.ExpressionDescriptor;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class CorrelationPredicate implements ModelAwareCloudEventPredicate {

private static final Logger logger = LoggerFactory.getLogger(CorrelationPredicate.class);

private final WorkflowValueResolver<Object> fromResolver;
private final WorkflowValueResolver<Object> expectResolver;

private CorrelationPredicate(
WorkflowValueResolver<Object> fromResolver, WorkflowValueResolver<Object> expectResolver) {
this.fromResolver = fromResolver;
this.expectResolver = expectResolver;
}

public static CorrelationPredicate from(CorrelateProperty prop, WorkflowApplication app) {
WorkflowValueResolver<Object> fromResolver =
app.expressionFactory().resolveValue(ExpressionDescriptor.from(prop.getFrom()));
WorkflowValueResolver<Object> expectResolver =
prop.getExpect() != null
? app.expressionFactory().resolveValue(ExpressionDescriptor.from(prop.getExpect()))
: null;
return new CorrelationPredicate(fromResolver, expectResolver);
}

@Override
public boolean test(CloudEvent cloudEvent, WorkflowContext workflow, TaskContext task) {
WorkflowModel eventModel = workflow.definition().application().modelFactory().from(cloudEvent);
return test(eventModel, workflow, task);
}

@Override
public boolean test(WorkflowModel eventModel, WorkflowContext workflow, TaskContext task) {
Object eventValue = fromResolver.apply(workflow, task, eventModel);
Comment thread
matheusandre1 marked this conversation as resolved.
if (eventValue == null) {
logger.debug("Correlation from expression returned null");
return false;
}
Comment thread
matheusandre1 marked this conversation as resolved.

if (expectResolver == null) {
logger.debug("Correlation no expect expression, accepting event value '{}'", eventValue);
return true;
}
Comment thread
matheusandre1 marked this conversation as resolved.

Object expectedValue = expectResolver.apply(workflow, task, task.input());
boolean result = Objects.equals(eventValue, expectedValue);
logger.debug(
"Correlation eventValue='{}', expectedValue='{}', match={}",
eventValue,
expectedValue,
result);
return result;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* Copyright 2020-Present The Serverless Workflow Specification Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.serverlessworkflow.impl.events;

import io.serverlessworkflow.impl.TaskContext;
import io.serverlessworkflow.impl.WorkflowContext;
import io.serverlessworkflow.impl.WorkflowModel;

public interface ModelAwareCloudEventPredicate extends CloudEventPredicate {

boolean test(WorkflowModel eventModel, WorkflowContext workflow, TaskContext task);
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,25 @@
import io.cloudevents.CloudEvent;
import io.serverlessworkflow.impl.TaskContext;
import io.serverlessworkflow.impl.WorkflowContext;
import java.util.Collection;
import java.util.Collections;
import java.util.function.Consumer;

public record TypeEventRegistration(
String type,
Consumer<CloudEvent> consumer,
CloudEventPredicate predicate,
Collection<CloudEventPredicate> correlationPredicates,
WorkflowContext workflow,
TaskContext task)
implements EventRegistration {}
implements EventRegistration {

public TypeEventRegistration(
String type,
Consumer<CloudEvent> consumer,
CloudEventPredicate predicate,
WorkflowContext workflow,
TaskContext task) {
this(type, consumer, predicate, Collections.emptyList(), workflow, task);
}
}
Loading
Loading