• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

FIWARE / contract-management / #117

04 Nov 2026 08:15AM UTC coverage: 7.885% (+3.4%) from 4.488%
#117

push

web-flow
Merge pull request #31 from FIWARE/ticket-100/work

 subscriptions, webhook handshake and delivery

1035 of 1054 new or added lines in 36 files covered. (98.2%)

2927 of 37120 relevant lines covered (7.89%)

0.08 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

95.0
/src/main/java/org/fiware/iam/dataspace/EventListener.java
1
package org.fiware.iam.dataspace;
2

3
import io.micrometer.core.instrument.MeterRegistry;
4
import io.micrometer.core.instrument.composite.CompositeMeterRegistry;
5
import io.micronaut.context.annotation.Requires;
6
import io.micronaut.core.annotation.Nullable;
7
import io.micronaut.http.HttpHeaders;
8
import io.micronaut.http.HttpMethod;
9
import io.micronaut.http.HttpResponse;
10
import io.micronaut.http.HttpStatus;
11
import io.micronaut.http.MutableHttpResponse;
12
import io.micronaut.http.annotation.Controller;
13
import io.micronaut.http.context.ServerRequestContext;
14
import lombok.extern.slf4j.Slf4j;
15
import org.fiware.iam.configuration.DataSpaceEventsProperties;
16
import org.fiware.iam.events.api.EventsApi;
17
import org.fiware.iam.events.model.DataSpaceEventVO;
18
import org.fiware.iam.logging.DownstreamError;
19
import reactor.core.publisher.Flux;
20
import reactor.core.publisher.Mono;
21

22
import java.time.Duration;
23
import java.util.List;
24
import java.util.Optional;
25

26
/**
27
 * Receiving endpoint of data space events: authorizes, deduplicates and dispatches them to the {@link DataSpaceEventHandler}s.
28
 * Every request is counted in {@value #METRIC_NAME}, tagged with the event type (if known) and the outcome.
29
 */
30
@Slf4j
1 ✔
31
@Controller("${general.basepath:/}")
32
@Requires(condition = DataSpaceEventsProperties.ListenerCondition.class)
33
public class EventListener implements EventsApi {
34

35
    static final String METRIC_NAME = "dataspace.events.received";
36
    static final String TYPE_TAG = "type";
37
    static final String OUTCOME_TAG = "outcome";
38
    // types no handler supports share one tag value, so callers cannot create unbounded series
39
    static final String OTHER_TYPE = "other";
40
    static final String DUPLICATE = "duplicate";
41
    static final String IN_FLIGHT = "in_flight";
42
    static final String INVALID = "invalid";
43
    static final String HANDLER_FAILED = "handler_failed";
44
    static final Duration RETRY_AFTER = Duration.ofSeconds(5);
1 ✔
45

46
    private final List<DataSpaceEventHandler> handlers;
47
    private final ParticipantResolver participantResolver;
48
    private final EventAuthorizer authorizer;
49
    private final EventDeduplicator deduplicator;
50
    private final MeterRegistry meterRegistry;
51
    private final DataSpaceEventsProperties properties;
52

53
    public EventListener(List<DataSpaceEventHandler> handlers, ParticipantResolver participantResolver, EventAuthorizer authorizer,
54
                         EventDeduplicator deduplicator, Optional<MeterRegistry> meterRegistry,
55
                         DataSpaceEventsProperties properties) {
1 ✔
56
        this.handlers = handlers;
1 ✔
57
        this.properties = properties;
1 ✔
58
        this.participantResolver = participantResolver;
1 ✔
59
        this.authorizer = authorizer;
1 ✔
60
        this.deduplicator = deduplicator;
1 ✔
61
        // without micronaut.metrics.enabled there is no registry; an empty composite counts nothing
62
        this.meterRegistry = meterRegistry.orElseGet(CompositeMeterRegistry::new);
1 ✔
63
    }
1 ✔
64

65
    @Override
66
    public Mono<HttpResponse<Object>> receiveEvent(DataSpaceEventVO event) {
67
        String identity = ServerRequestContext.currentRequest()
1 ✔
68
                .map(request -> request.getHeaders().get(participantResolver.headerName()))
1 ✔
69
                .orElse(null);
1 ✔
70
        return receive(identity, event);
1 ✔
71
    }
72

73
    @Override
74
    public Mono<HttpResponse<Object>> validateWebhook(@Nullable String webHookRequestOrigin) {
75
        // unauthenticated by the CloudEvents webhook spec; it only tells the sender whether to deliver at all
76
        MutableHttpResponse<Object> response = HttpResponse.ok().header(HttpHeaders.ALLOW, HttpMethod.POST.name());
1 ✔
77
        properties.allowedOrigin(webHookRequestOrigin)
1 ✔
78
                .ifPresent(origin -> response.header(WebhookHeaders.ALLOWED_ORIGIN, origin));
1 ✔
79
        return Mono.just(response);
1 ✔
80
    }
81

82
    Mono<HttpResponse<Object>> receive(@Nullable String identity, DataSpaceEventVO event) {
83
        String metricType = isKnownType(event.getType()) ? event.getType() : OTHER_TYPE;
1 ✔
84
        return process(participantResolver.participantIdOf(identity), event, metricType);
1 ✔
85
    }
86

87
    private Mono<HttpResponse<Object>> process(Optional<String> participantId, DataSpaceEventVO event, String metricType) {
88
        EventDecision decision = authorizer.authorize(participantId, event, this::isKnownType);
1 ✔
89
        if (decision.isRejected()) {
1 ✔
90
            log.warn("Rejected data space event {} from {} of type {}: {}.",
1 ✔
91
                    event.getId(), event.getSource(), event.getType(), decision.getOutcome());
1 ✔
92
            return respond(decision.getStatus(), metricType, decision.getOutcome());
1 ✔
93
        }
94
        if (!isComplete(event)) {
1 ✔
NEW
95
            log.warn("Rejected data space event {} from {} of type {}: specversion, id, source and type are required.",
×
NEW
96
                    event.getId(), event.getSource(), event.getType());
×
NEW
97
            return respond(HttpStatus.BAD_REQUEST, metricType, INVALID);
×
98
        }
99
        if (decision == EventDecision.UNKNOWN_TYPE) {
1 ✔
100
            log.debug("Data space event {} from {} has the unsupported type {}, dropped.", event.getId(), event.getSource(), event.getType());
1 ✔
101
            return respond(decision.getStatus(), metricType, decision.getOutcome());
1 ✔
102
        }
103
        EventDeduplicator.Key key = new EventDeduplicator.Key(event.getSource(), event.getId());
1 ✔
104
        return switch (deduplicator.begin(key)) {
1 ✔
105
            case DONE -> respond(HttpStatus.ACCEPTED, metricType, DUPLICATE);
1 ✔
106
            case IN_FLIGHT -> retryLater(metricType, IN_FLIGHT);
1 ✔
107
            case NEW -> decision == EventDecision.SELF ? skipSelf(key, event, metricType) : dispatch(key, event, metricType);
1 ✔
108
        };
109
    }
110

111
    private Mono<HttpResponse<Object>> skipSelf(EventDeduplicator.Key key, DataSpaceEventVO event, String metricType) {
112
        log.info("Data space event {} from {} is about this participant, not acted on.", event.getId(), event.getSource());
1 ✔
113
        deduplicator.complete(key);
1 ✔
114
        return respond(EventDecision.SELF.getStatus(), metricType, EventDecision.SELF.getOutcome());
1 ✔
115
    }
116

117
    private Mono<HttpResponse<Object>> dispatch(EventDeduplicator.Key key, DataSpaceEventVO event, String metricType) {
118
        // settled before the response is emitted, so a retry after the answer never sees the event in flight
119
        return Flux.fromIterable(handlers)
1 ✔
120
                .filter(handler -> handler.isEventTypeSupported(event.getType()))
1 ✔
121
                .concatMap(handler -> handler.handleEvent(event))
1 ✔
122
                .then()
1 ✔
123
                .doOnSuccess(ignored -> deduplicator.complete(key))
1 ✔
124
                .doOnError(e -> deduplicator.forget(key))
1 ✔
125
                .doOnCancel(() -> deduplicator.forget(key))
1 ✔
126
                .then(respond(EventDecision.ACCEPT.getStatus(), metricType, EventDecision.ACCEPT.getOutcome()))
1 ✔
127
                .onErrorResume(e -> {
1 ✔
128
                    log.warn("Data space event {} from {} of type {} could not be handled: {}",
1 ✔
129
                            event.getId(), event.getSource(), event.getType(), DownstreamError.reason(e), e);
1 ✔
130
                    return respond(HttpStatus.INTERNAL_SERVER_ERROR, metricType, HANDLER_FAILED);
1 ✔
131
                });
132
    }
133

134
    private Mono<HttpResponse<Object>> retryLater(String metricType, String outcome) {
135
        return Mono.fromSupplier(() -> counted(HttpStatus.SERVICE_UNAVAILABLE, metricType, outcome)
1 ✔
136
                .header(HttpHeaders.RETRY_AFTER, String.valueOf(RETRY_AFTER.toSeconds())));
1 ✔
137
    }
138

139
    private Mono<HttpResponse<Object>> respond(HttpStatus status, String metricType, String outcome) {
140
        return Mono.fromSupplier(() -> counted(status, metricType, outcome));
1 ✔
141
    }
142

143
    private MutableHttpResponse<Object> counted(HttpStatus status, String metricType, String outcome) {
144
        meterRegistry.counter(METRIC_NAME, TYPE_TAG, metricType, OUTCOME_TAG, outcome).increment();
1 ✔
145
        return HttpResponse.status(status);
1 ✔
146
    }
147

148
    private boolean isKnownType(@Nullable String type) {
149
        return type != null && handlers.stream().anyMatch(handler -> handler.isEventTypeSupported(type));
1 ✔
150
    }
151

152
    private static boolean isComplete(DataSpaceEventVO event) {
153
        return event.getSpecversion() != null && !isBlank(event.getId()) && !isBlank(event.getSource()) && !isBlank(event.getType());
1 ✔
154
    }
155

156
    private static boolean isBlank(@Nullable String value) {
157
        return value == null || value.isBlank();
1 ✔
158
    }
159
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc