Skip to content

Commit 37affd2

Browse files
committed
feat: Implement correlation on event filter
- Add CorrelationPredicate for evaluating correlation expressions - Add correlate support in AbstractEventFilterBuilder and AbstractEventFilterSpec - Update TypeEventRegistration and TypeEventRegistrationBuilder with correlation predicates - Implement correlation matching in AbstractTypeConsumer - Add CorrelationTest and listen-correlate.yaml - Add correlate tests in WorkflowBuilderTest and DSLTest Signed-off-by: Matheus André <matheusandr2@gmail.com>
1 parent fcd26da commit 37affd2

16 files changed

Lines changed: 550 additions & 19 deletions

File tree

fluent/spec/src/main/java/io/serverlessworkflow/fluent/spec/AbstractEventFilterBuilder.java

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,11 @@ public SELF with(Consumer<P> c) {
3737
}
3838

3939
public SELF correlate(String key, Consumer<ListenTaskBuilder.CorrelatePropertyBuilder> c) {
40-
throw new UnsupportedOperationException(
41-
"correlate is not supported in the engine level: https://github.com/serverlessworkflow/sdk-java/issues/1206");
40+
ListenTaskBuilder.CorrelatePropertyBuilder cb =
41+
new ListenTaskBuilder.CorrelatePropertyBuilder();
42+
c.accept(cb);
43+
correlate.setAdditionalProperty(key, cb.build());
44+
return self();
4245
}
4346

4447
public EventFilter build() {

fluent/spec/src/main/java/io/serverlessworkflow/fluent/spec/dsl/AbstractEventFilterSpec.java

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
import io.serverlessworkflow.fluent.spec.AbstractEventFilterBuilder;
1919
import io.serverlessworkflow.fluent.spec.AbstractEventPropertiesBuilder;
20+
import io.serverlessworkflow.fluent.spec.AbstractListenTaskBuilder;
2021
import java.util.ArrayList;
2122
import java.util.List;
2223
import java.util.function.Consumer;
@@ -41,13 +42,17 @@ protected List<Consumer<EVENT_FILTER>> getFilterSteps() {
4142
return filterSteps;
4243
}
4344

44-
// TODO: "correlate is not supported in the engine level:
45-
// https://github.com/serverlessworkflow/sdk-java/issues/1206". Keeping the code for a future
46-
// reference.
47-
// public SELF correlate(String key, Consumer<ListenTaskBuilder.CorrelatePropertyBuilder> c) {
48-
// filterSteps.add(f -> f.correlate(key, c));
49-
// return self();
50-
// }
45+
public SELF correlate(
46+
String key, Consumer<? super AbstractListenTaskBuilder.CorrelatePropertyBuilder> c) {
47+
addFilterStep(f -> f.correlate(key, bridgeCorrelatePropertyConsumer(c)));
48+
return self();
49+
}
50+
51+
@SuppressWarnings({"rawtypes", "unchecked"})
52+
private Consumer bridgeCorrelatePropertyConsumer(
53+
Consumer<? super AbstractListenTaskBuilder.CorrelatePropertyBuilder> c) {
54+
return (Consumer) c;
55+
}
5156

5257
@Override
5358
public void accept(EVENT_FILTER filterBuilder) {

fluent/spec/src/test/java/io/serverlessworkflow/fluent/spec/WorkflowBuilderTest.java

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
import io.serverlessworkflow.api.types.AuthenticationPolicyUnion;
3838
import io.serverlessworkflow.api.types.CallHTTP;
3939
import io.serverlessworkflow.api.types.CatchErrors;
40+
import io.serverlessworkflow.api.types.CorrelateProperty;
4041
import io.serverlessworkflow.api.types.Document;
4142
import io.serverlessworkflow.api.types.EmitEventDefinition;
4243
import io.serverlessworkflow.api.types.EmitTask;
@@ -310,8 +311,12 @@ void testDoTaskListenOne() {
310311
to ->
311312
to.one(
312313
f ->
313-
f.with(
314-
p -> p.type("com.fake.pet").source("mySource"))))))
314+
f.with(p -> p.type("com.fake.pet").source("mySource"))
315+
.correlate(
316+
"orderId",
317+
c ->
318+
c.from("$.data.orderId")
319+
.expect("$.input.orderId"))))))
315320
.build();
316321

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

332341
@Test

fluent/spec/src/test/java/io/serverlessworkflow/fluent/spec/dsl/DSLTest.java

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
import static io.serverlessworkflow.fluent.spec.dsl.DSL.workflow;
3131
import static org.assertj.core.api.Assertions.assertThat;
3232

33+
import io.serverlessworkflow.api.types.CorrelateProperty;
3334
import io.serverlessworkflow.api.types.HTTPArguments;
3435
import io.serverlessworkflow.api.types.ListenTaskConfiguration;
3536
import io.serverlessworkflow.api.types.RunTaskConfiguration;
@@ -166,7 +167,15 @@ public void when_listen_any_with_until() {
166167
public void when_listen_one() {
167168
Workflow wf =
168169
WorkflowBuilder.workflow("f", "ns", "1")
169-
.tasks(t -> t.listen(to().one(event().type("only-once"))))
170+
.tasks(
171+
t ->
172+
t.listen(
173+
to().one(
174+
event()
175+
.type("only-once")
176+
.correlate(
177+
"workflowInstanceId",
178+
c -> c.from("$.metadata.instanceId")))))
170179
.build();
171180

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

183196
@Test

impl/core/src/main/java/io/serverlessworkflow/impl/CollectionConversionUtils.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,4 +92,8 @@ private static <T> Collection<T> iterableToCollection(Iterable<T> t) {
9292
public static <T> Optional<T> as(Collection<?> elements, Class<T> clazz) {
9393
return as(elements, clazz, (item, type) -> item);
9494
}
95+
96+
public static <T> List<T> unmodifiableCopyOf(Collection<T> collection) {
97+
return collection == null ? List.of() : List.copyOf(collection);
98+
}
9599
}

impl/core/src/main/java/io/serverlessworkflow/impl/CompositeExpressionFactory.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,11 @@ public WorkflowValueResolver<String> resolveString(ExpressionDescriptor desc) {
4949
return processFactories(desc, f -> f.resolveString(desc));
5050
}
5151

52+
@Override
53+
public WorkflowValueResolver<Object> resolveValue(ExpressionDescriptor desc) {
54+
return processFactories(desc, f -> f.resolveValue(desc));
55+
}
56+
5257
@Override
5358
public WorkflowValueResolver<OffsetDateTime> resolveDate(ExpressionDescriptor desc) {
5459
return processFactories(desc, f -> f.resolveDate(desc));

impl/core/src/main/java/io/serverlessworkflow/impl/events/AbstractTypeConsumer.java

Lines changed: 71 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,17 @@
1616
package io.serverlessworkflow.impl.events;
1717

1818
import io.cloudevents.CloudEvent;
19+
import io.serverlessworkflow.api.types.CorrelateProperty;
1920
import io.serverlessworkflow.api.types.EventFilter;
21+
import io.serverlessworkflow.api.types.EventFilterCorrelate;
2022
import io.serverlessworkflow.api.types.EventProperties;
2123
import io.serverlessworkflow.impl.TaskContext;
2224
import io.serverlessworkflow.impl.WorkflowApplication;
2325
import io.serverlessworkflow.impl.WorkflowContext;
26+
import io.serverlessworkflow.impl.WorkflowModel;
27+
import io.serverlessworkflow.impl.WorkflowModelFactory;
2428
import java.util.AbstractCollection;
29+
import java.util.ArrayList;
2530
import java.util.Collection;
2631
import java.util.Iterator;
2732
import java.util.List;
@@ -52,8 +57,24 @@ public TypeEventRegistrationBuilder listen(
5257
EventFilter register, WorkflowApplication application) {
5358
EventProperties properties = register.getWith();
5459
String type = properties.getType();
55-
return new TypeEventRegistrationBuilder(
56-
type, application.cloudEventPredicateFactory().build(application, properties));
60+
CloudEventPredicate cePredicate =
61+
application.cloudEventPredicateFactory().build(application, properties);
62+
Collection<CloudEventPredicate> correlationPredicates =
63+
buildCorrelationPredicates(register.getCorrelate(), application);
64+
return new TypeEventRegistrationBuilder(type, cePredicate, correlationPredicates);
65+
}
66+
67+
private Collection<CloudEventPredicate> buildCorrelationPredicates(
68+
EventFilterCorrelate correlate, WorkflowApplication application) {
69+
if (correlate == null || correlate.getAdditionalProperties().isEmpty()) {
70+
return List.of();
71+
}
72+
Collection<CloudEventPredicate> predicates = new ArrayList<>();
73+
for (Map.Entry<String, CorrelateProperty> entry :
74+
correlate.getAdditionalProperties().entrySet()) {
75+
predicates.add(CorrelationPredicate.from(entry.getValue(), application));
76+
}
77+
return predicates;
5778
}
5879

5980
@Override
@@ -63,18 +84,56 @@ public Collection<TypeEventRegistrationBuilder> listenToAll(WorkflowApplication
6384

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

90+
CloudEventConsumer(WorkflowModelFactory modelFactory) {
91+
this.modelFactory = modelFactory;
92+
}
93+
6894
@Override
6995
public void accept(CloudEvent ce) {
7096
logger.debug("Received cloud event {}", ce);
97+
WorkflowModel eventModel = null;
7198
for (TypeEventRegistration registration : registrations) {
7299
if (registration.predicate().test(ce, registration.workflow(), registration.task())) {
100+
Collection<CloudEventPredicate> predicates = registration.correlationPredicates();
101+
if (!predicates.isEmpty()) {
102+
if (eventModel == null) {
103+
if (modelFactory == null) {
104+
continue;
105+
}
106+
eventModel = modelFactory.from(ce);
107+
}
108+
if (!testCorrelation(ce, registration, eventModel)) {
109+
continue;
110+
}
111+
}
73112
registration.consumer().accept(ce);
74113
}
75114
}
76115
}
77116

117+
private boolean testCorrelation(
118+
CloudEvent ce, TypeEventRegistration registration, WorkflowModel eventModel) {
119+
Collection<CloudEventPredicate> predicates = registration.correlationPredicates();
120+
if (predicates.isEmpty()) {
121+
return true;
122+
}
123+
for (CloudEventPredicate pred : predicates) {
124+
if (pred instanceof ModelAwareCloudEventPredicate ma) {
125+
if (!ma.test(eventModel, registration.workflow(), registration.task())) {
126+
return false;
127+
}
128+
} else {
129+
if (!pred.test(ce, registration.workflow(), registration.task())) {
130+
return false;
131+
}
132+
}
133+
}
134+
return true;
135+
}
136+
78137
@Override
79138
public boolean add(TypeEventRegistration registration) {
80139
return registrations.add(registration);
@@ -107,12 +166,20 @@ public TypeEventRegistration register(
107166
return new TypeEventRegistration(null, ce, null, workflow, task);
108167
} else {
109168
TypeEventRegistration registration =
110-
new TypeEventRegistration(builder.type(), ce, builder.cePredicate(), workflow, task);
169+
new TypeEventRegistration(
170+
builder.type(),
171+
ce,
172+
builder.cePredicate(),
173+
builder.correlationPredicates(),
174+
workflow,
175+
task);
111176
registrations
112177
.computeIfAbsent(
113178
registration.type(),
114179
k -> {
115-
CloudEventConsumer consumer = new CloudEventConsumer();
180+
WorkflowModelFactory factory =
181+
workflow != null ? workflow.definition().application().modelFactory() : null;
182+
CloudEventConsumer consumer = new CloudEventConsumer(factory);
116183
register(k, consumer);
117184
return consumer;
118185
})
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/*
2+
* Copyright 2020-Present The Serverless Workflow Specification Authors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package io.serverlessworkflow.impl.events;
17+
18+
import io.cloudevents.CloudEvent;
19+
import io.serverlessworkflow.api.types.CorrelateProperty;
20+
import io.serverlessworkflow.impl.TaskContext;
21+
import io.serverlessworkflow.impl.WorkflowApplication;
22+
import io.serverlessworkflow.impl.WorkflowContext;
23+
import io.serverlessworkflow.impl.WorkflowModel;
24+
import io.serverlessworkflow.impl.WorkflowValueResolver;
25+
import io.serverlessworkflow.impl.expressions.ExpressionDescriptor;
26+
import java.util.Objects;
27+
import org.slf4j.Logger;
28+
import org.slf4j.LoggerFactory;
29+
30+
class CorrelationPredicate implements ModelAwareCloudEventPredicate {
31+
32+
private static final Logger logger = LoggerFactory.getLogger(CorrelationPredicate.class);
33+
34+
private final WorkflowValueResolver<Object> fromResolver;
35+
private final WorkflowValueResolver<Object> expectResolver;
36+
37+
private CorrelationPredicate(
38+
WorkflowValueResolver<Object> fromResolver, WorkflowValueResolver<Object> expectResolver) {
39+
this.fromResolver = fromResolver;
40+
this.expectResolver = expectResolver;
41+
}
42+
43+
public static CorrelationPredicate from(CorrelateProperty prop, WorkflowApplication app) {
44+
WorkflowValueResolver<Object> fromResolver =
45+
app.expressionFactory().resolveValue(ExpressionDescriptor.from(prop.getFrom()));
46+
WorkflowValueResolver<Object> expectResolver =
47+
prop.getExpect() != null
48+
? app.expressionFactory().resolveValue(ExpressionDescriptor.from(prop.getExpect()))
49+
: null;
50+
return new CorrelationPredicate(fromResolver, expectResolver);
51+
}
52+
53+
@Override
54+
public boolean test(CloudEvent cloudEvent, WorkflowContext workflow, TaskContext task) {
55+
WorkflowModel eventModel = workflow.definition().application().modelFactory().from(cloudEvent);
56+
return test(eventModel, workflow, task);
57+
}
58+
59+
@Override
60+
public boolean test(WorkflowModel eventModel, WorkflowContext workflow, TaskContext task) {
61+
Object eventValue = fromResolver.apply(workflow, task, eventModel);
62+
if (eventValue == null) {
63+
logger.debug("Correlation from expression returned null");
64+
return false;
65+
}
66+
67+
if (expectResolver == null) {
68+
logger.debug("Correlation no expect expression, accepting event value '{}'", eventValue);
69+
return true;
70+
}
71+
72+
Object expectedValue = expectResolver.apply(workflow, task, task.input());
73+
boolean result = Objects.equals(eventValue, expectedValue);
74+
logger.debug(
75+
"Correlation eventValue='{}', expectedValue='{}', match={}",
76+
eventValue,
77+
expectedValue,
78+
result);
79+
return result;
80+
}
81+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/*
2+
* Copyright 2020-Present The Serverless Workflow Specification Authors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package io.serverlessworkflow.impl.events;
17+
18+
import io.serverlessworkflow.impl.TaskContext;
19+
import io.serverlessworkflow.impl.WorkflowContext;
20+
import io.serverlessworkflow.impl.WorkflowModel;
21+
22+
public interface ModelAwareCloudEventPredicate extends CloudEventPredicate {
23+
24+
boolean test(WorkflowModel eventModel, WorkflowContext workflow, TaskContext task);
25+
}

0 commit comments

Comments
 (0)