Skip to content

Commit e56c2a8

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 cb713b5 commit e56c2a8

16 files changed

Lines changed: 550 additions & 20 deletions

File tree

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

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,13 @@ public SELF with(Consumer<P> c) {
3636
return self();
3737
}
3838

39-
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");
39+
public SELF correlate(
40+
String key, Consumer<? super AbstractListenTaskBuilder.CorrelatePropertyBuilder> c) {
41+
AbstractListenTaskBuilder.CorrelatePropertyBuilder cb =
42+
new AbstractListenTaskBuilder.CorrelatePropertyBuilder();
43+
c.accept(cb);
44+
correlate.setAdditionalProperty(key, cb.build());
45+
return self();
4246
}
4347

4448
public EventFilter build() {

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

Lines changed: 6 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,11 @@ 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, c));
48+
return self();
49+
}
5150

5251
@Override
5352
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/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/WorkflowMutableInstance.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -355,6 +355,10 @@ public <T> T addMetadataIfAbsent(String key, Supplier<T> supplier) {
355355
return (T) additionalObjects.computeIfAbsent(key, k -> supplier.get());
356356
}
357357

358+
public Object computeCorrelationValue(String key, Object value) {
359+
return additionalObjects.computeIfAbsent(key, k -> value);
360+
}
361+
358362
@Override
359363
public <T> Optional<T> findMetadata(String key, Class<T> objectClass) {
360364
Object value = additionalObjects.get(key);

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

Lines changed: 67 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,29 +57,81 @@ public TypeEventRegistrationBuilder listen(
5257
EventFilter register, WorkflowApplication application) {
5358
EventProperties properties = register.getWith();
5459
String type = properties.getType();
60+
CloudEventPredicate cePredicate =
61+
application.cloudEventPredicateFactory().build(application, properties);
62+
Collection<CloudEventPredicate> correlationPredicates =
63+
buildCorrelationPredicates(register.getCorrelate(), application);
5564
return new TypeEventRegistrationBuilder(
56-
type, application.cloudEventPredicateFactory().build(application, properties));
65+
type, cePredicate, correlationPredicates, application.modelFactory());
66+
}
67+
68+
private Collection<CloudEventPredicate> buildCorrelationPredicates(
69+
EventFilterCorrelate correlate, WorkflowApplication application) {
70+
if (correlate == null) {
71+
return List.of();
72+
}
73+
Map<String, CorrelateProperty> additionalProperties = correlate.getAdditionalProperties();
74+
if (additionalProperties == null || additionalProperties.isEmpty()) {
75+
return List.of();
76+
}
77+
Collection<CloudEventPredicate> predicates = new ArrayList<>();
78+
for (Map.Entry<String, CorrelateProperty> entry : additionalProperties.entrySet()) {
79+
predicates.add(CorrelationPredicate.from(entry.getKey(), entry.getValue(), application));
80+
}
81+
return predicates;
5782
}
5883

5984
@Override
6085
public Collection<TypeEventRegistrationBuilder> listenToAll(WorkflowApplication application) {
61-
return List.of(new TypeEventRegistrationBuilder(null, null));
86+
return List.of(
87+
new TypeEventRegistrationBuilder(null, null, List.of(), application.modelFactory()));
6288
}
6389

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

95+
CloudEventConsumer(WorkflowModelFactory modelFactory) {
96+
this.modelFactory = modelFactory;
97+
}
98+
6899
@Override
69100
public void accept(CloudEvent ce) {
70101
logger.debug("Received cloud event {}", ce);
71102
for (TypeEventRegistration registration : registrations) {
72103
if (registration.predicate().test(ce, registration.workflow(), registration.task())) {
104+
if (!testCorrelation(ce, registration)) {
105+
continue;
106+
}
73107
registration.consumer().accept(ce);
74108
}
75109
}
76110
}
77111

112+
private boolean testCorrelation(CloudEvent ce, TypeEventRegistration registration) {
113+
Collection<CloudEventPredicate> predicates = registration.correlationPredicates();
114+
if (predicates.isEmpty()) {
115+
return true;
116+
}
117+
WorkflowModel eventModel = null;
118+
for (CloudEventPredicate pred : predicates) {
119+
if (pred instanceof ModelAwareCloudEventPredicate ma) {
120+
if (eventModel == null) {
121+
eventModel = modelFactory.from(ce);
122+
}
123+
if (!ma.test(eventModel, registration.workflow(), registration.task())) {
124+
return false;
125+
}
126+
} else {
127+
if (!pred.test(ce, registration.workflow(), registration.task())) {
128+
return false;
129+
}
130+
}
131+
}
132+
return true;
133+
}
134+
78135
@Override
79136
public boolean add(TypeEventRegistration registration) {
80137
return registrations.add(registration);
@@ -107,12 +164,18 @@ public TypeEventRegistration register(
107164
return new TypeEventRegistration(null, ce, null, workflow, task);
108165
} else {
109166
TypeEventRegistration registration =
110-
new TypeEventRegistration(builder.type(), ce, builder.cePredicate(), workflow, task);
167+
new TypeEventRegistration(
168+
builder.type(),
169+
ce,
170+
builder.cePredicate(),
171+
builder.correlationPredicates(),
172+
workflow,
173+
task);
111174
registrations
112175
.computeIfAbsent(
113176
registration.type(),
114177
k -> {
115-
CloudEventConsumer consumer = new CloudEventConsumer();
178+
CloudEventConsumer consumer = new CloudEventConsumer(builder.modelFactory());
116179
register(k, consumer);
117180
return consumer;
118181
})
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
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 String correlationKey;
35+
private final WorkflowValueResolver<Object> fromResolver;
36+
private final WorkflowValueResolver<Object> expectResolver;
37+
38+
private CorrelationPredicate(
39+
String correlationKey,
40+
WorkflowValueResolver<Object> fromResolver,
41+
WorkflowValueResolver<Object> expectResolver) {
42+
this.correlationKey = correlationKey;
43+
this.fromResolver = fromResolver;
44+
this.expectResolver = expectResolver;
45+
}
46+
47+
public static CorrelationPredicate from(
48+
String key, CorrelateProperty prop, WorkflowApplication app) {
49+
WorkflowValueResolver<Object> fromResolver =
50+
app.expressionFactory().resolveValue(ExpressionDescriptor.from(prop.getFrom()));
51+
WorkflowValueResolver<Object> expectResolver =
52+
prop.getExpect() != null
53+
? app.expressionFactory().resolveValue(ExpressionDescriptor.from(prop.getExpect()))
54+
: null;
55+
return new CorrelationPredicate(key, fromResolver, expectResolver);
56+
}
57+
58+
private String correlationStateKey(TaskContext task) {
59+
return "correlation:" + task.position().jsonPointer() + ":" + correlationKey;
60+
}
61+
62+
@Override
63+
public boolean test(CloudEvent cloudEvent, WorkflowContext workflow, TaskContext task) {
64+
WorkflowModel eventModel = workflow.definition().application().modelFactory().from(cloudEvent);
65+
return test(eventModel, workflow, task);
66+
}
67+
68+
@Override
69+
public boolean test(WorkflowModel eventModel, WorkflowContext workflow, TaskContext task) {
70+
Object eventValue = fromResolver.apply(workflow, task, eventModel);
71+
if (eventValue == null) {
72+
logger.debug("Correlation from expression returned null");
73+
return false;
74+
}
75+
76+
if (expectResolver == null) {
77+
String stateKey = correlationStateKey(task);
78+
Object firstValue = workflow.instance().computeCorrelationValue(stateKey, eventValue);
79+
boolean result = Objects.equals(eventValue, firstValue);
80+
logger.debug(
81+
"Correlation no expect, eventValue='{}', firstValue='{}', match={}",
82+
eventValue,
83+
firstValue,
84+
result);
85+
return result;
86+
}
87+
88+
Object expectedValue = expectResolver.apply(workflow, task, task.input());
89+
boolean result = Objects.equals(eventValue, expectedValue);
90+
logger.debug(
91+
"Correlation eventValue='{}', expectedValue='{}', match={}",
92+
eventValue,
93+
expectedValue,
94+
result);
95+
return result;
96+
}
97+
}
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)