-
Notifications
You must be signed in to change notification settings - Fork 561
/
LongPollingActivateJobsHandler.java
318 lines (275 loc) · 11.5 KB
/
LongPollingActivateJobsHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under
* one or more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
* Licensed under the Zeebe Community License 1.1. You may not use this file
* except in compliance with the Zeebe Community License 1.1.
*/
package io.camunda.zeebe.gateway.impl.job;
import static io.camunda.zeebe.util.sched.clock.ActorClock.currentTimeMillis;
import com.google.rpc.Code;
import com.google.rpc.Status;
import io.camunda.zeebe.gateway.Loggers;
import io.camunda.zeebe.gateway.grpc.ServerStreamObserver;
import io.camunda.zeebe.gateway.impl.broker.BrokerClient;
import io.camunda.zeebe.gateway.impl.broker.cluster.BrokerClusterState;
import io.camunda.zeebe.gateway.metrics.LongPollingMetrics;
import io.camunda.zeebe.gateway.protocol.GatewayOuterClass.ActivateJobsRequest;
import io.camunda.zeebe.gateway.protocol.GatewayOuterClass.ActivateJobsResponse;
import io.camunda.zeebe.util.sched.Actor;
import io.camunda.zeebe.util.sched.ScheduledTimer;
import io.grpc.protobuf.StatusProto;
import java.time.Duration;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
/**
* Adds long polling to the handling of activate job requests. When there are no jobs available to
* activate, the response will be kept open.
*/
public final class LongPollingActivateJobsHandler extends Actor implements ActivateJobsHandler {
private static final String JOBS_AVAILABLE_TOPIC = "jobsAvailable";
private static final Logger LOG = Loggers.GATEWAY_LOGGER;
private static final String ERROR_MSG_ACTIVATED_EXHAUSTED =
"Expected to activate jobs of type '%s', but no jobs available and at least one broker returned 'RESOURCE_EXHAUSTED'. Please try again later.";
private final RoundRobinActivateJobsHandler activateJobsHandler;
private final BrokerClient brokerClient;
// jobType -> state
private final Map<String, InFlightLongPollingActivateJobsRequestsState> jobTypeState =
new ConcurrentHashMap<>();
private final Duration longPollingTimeout;
private final long probeTimeoutMillis;
private final int failedAttemptThreshold;
private final LongPollingMetrics metrics;
private LongPollingActivateJobsHandler(
final BrokerClient brokerClient,
final long longPollingTimeout,
final long probeTimeoutMillis,
final int failedAttemptThreshold) {
this.brokerClient = brokerClient;
activateJobsHandler = new RoundRobinActivateJobsHandler(brokerClient);
this.longPollingTimeout = Duration.ofMillis(longPollingTimeout);
this.probeTimeoutMillis = probeTimeoutMillis;
this.failedAttemptThreshold = failedAttemptThreshold;
metrics = new LongPollingMetrics();
}
@Override
public String getName() {
return "GatewayLongPollingJobHandler";
}
@Override
protected void onActorStarted() {
brokerClient.subscribeJobAvailableNotification(JOBS_AVAILABLE_TOPIC, this::onNotification);
actor.runAtFixedRate(Duration.ofMillis(probeTimeoutMillis), this::probe);
}
@Override
public void activateJobs(
final ActivateJobsRequest request,
final ServerStreamObserver<ActivateJobsResponse> responseObserver) {
final LongPollingActivateJobsRequest longPollingRequest =
new LongPollingActivateJobsRequest(request, responseObserver);
activateJobs(longPollingRequest);
}
public void activateJobs(final LongPollingActivateJobsRequest request) {
actor.run(
() -> {
final InFlightLongPollingActivateJobsRequestsState state =
getJobTypeState(request.getType());
if (state.getFailedAttempts() < failedAttemptThreshold) {
activateJobsUnchecked(state, request);
} else {
completeOrEnqueueRequest(state, request);
}
});
}
private InFlightLongPollingActivateJobsRequestsState getJobTypeState(final String jobType) {
return jobTypeState.computeIfAbsent(
jobType, type -> new InFlightLongPollingActivateJobsRequestsState(type, metrics));
}
private void activateJobsUnchecked(
final InFlightLongPollingActivateJobsRequestsState state,
final LongPollingActivateJobsRequest request) {
final BrokerClusterState topology = brokerClient.getTopologyManager().getTopology();
if (topology != null) {
state.addActiveRequest(request);
final int partitionsCount = topology.getPartitionsCount();
activateJobsHandler.activateJobs(
partitionsCount,
request.getRequest(),
request.getMaxJobsToActivate(),
request.getType(),
response -> onResponse(request, response),
error -> onError(request, error),
(remainingAmount, containedResourceExhaustedResponse) ->
onCompleted(state, request, remainingAmount, containedResourceExhaustedResponse));
}
}
private void onNotification(final String jobType) {
LOG.trace("Received jobs available notification for type {}.", jobType);
// instead of calling #getJobTypeState(), do only a
// get to avoid the creation of a state instance.
final var state = jobTypeState.get(jobType);
if (state != null && state.shouldNotifyAndStartNotification()) {
LOG.trace("Handle jobs available notification for type {}.", jobType);
actor.run(
() -> {
resetFailedAttemptsAndHandlePendingRequests(jobType);
state.completeNotification();
});
} else {
LOG.trace("Ignore jobs available notification for type {}.", jobType);
}
}
private void onCompleted(
final InFlightLongPollingActivateJobsRequestsState state,
final LongPollingActivateJobsRequest request,
final int remainingAmount,
final boolean containedResourceExhaustedResponse) {
if (remainingAmount == request.getMaxJobsToActivate()) {
if (containedResourceExhaustedResponse) {
actor.submit(
() -> {
state.removeActiveRequest(request);
final var type = request.getType();
final var errorMsg = String.format(ERROR_MSG_ACTIVATED_EXHAUSTED, type);
final var status =
Status.newBuilder()
.setCode(Code.RESOURCE_EXHAUSTED_VALUE)
.setMessage(errorMsg)
.build();
request.getResponseObserver().onError(StatusProto.toStatusException(status));
});
} else {
actor.submit(
() -> {
state.incrementFailedAttempts(currentTimeMillis());
final boolean shouldBeRepeated = state.shouldBeRepeated(request);
state.removeActiveRequest(request);
if (shouldBeRepeated) {
activateJobs(request);
} else {
completeOrEnqueueRequest(getJobTypeState(request.getType()), request);
}
});
}
} else {
actor.submit(
() -> {
request.complete();
state.removeActiveRequest(request);
resetFailedAttemptsAndHandlePendingRequests(request.getType());
});
}
}
private void onResponse(
final LongPollingActivateJobsRequest request,
final ActivateJobsResponse activateJobsResponse) {
actor.submit(() -> request.onResponse(activateJobsResponse));
}
private void onError(final LongPollingActivateJobsRequest request, final Throwable error) {
actor.submit(() -> request.onError(error));
}
private void resetFailedAttemptsAndHandlePendingRequests(final String jobType) {
final InFlightLongPollingActivateJobsRequestsState state = getJobTypeState(jobType);
state.resetFailedAttempts();
final Queue<LongPollingActivateJobsRequest> pendingRequests = state.getPendingRequests();
if (!pendingRequests.isEmpty()) {
pendingRequests.forEach(
nextPendingRequest -> {
LOG.trace("Unblocking ActivateJobsRequest {}", nextPendingRequest.getRequest());
activateJobs(nextPendingRequest);
});
} else {
if (!state.hasActiveRequests()) {
jobTypeState.remove(jobType);
}
}
}
private void completeOrEnqueueRequest(
final InFlightLongPollingActivateJobsRequestsState state,
final LongPollingActivateJobsRequest request) {
if (request.isLongPollingDisabled()) {
request.complete();
return;
}
if (!request.isTimedOut()) {
LOG.trace(
"Worker '{}' asked for '{}' jobs of type '{}', but none are available. This request will"
+ " be kept open until a new job of this type is created or until timeout of '{}'.",
request.getWorker(),
request.getMaxJobsToActivate(),
request.getType(),
request.getLongPollingTimeout(longPollingTimeout));
state.enqueueRequest(request);
if (!request.hasScheduledTimer()) {
addTimeOut(state, request);
}
}
}
private void addTimeOut(
final InFlightLongPollingActivateJobsRequestsState state,
final LongPollingActivateJobsRequest request) {
final Duration requestTimeout = request.getLongPollingTimeout(longPollingTimeout);
final ScheduledTimer timeout =
actor.runDelayed(
requestTimeout,
() -> {
state.removeRequest(request);
request.timeout();
});
request.setScheduledTimer(timeout);
}
private void probe() {
final long now = currentTimeMillis();
jobTypeState.forEach(
(type, state) -> {
if (state.getLastUpdatedTime() < (now - probeTimeoutMillis)) {
final LongPollingActivateJobsRequest probeRequest = state.getNextPendingRequest();
if (probeRequest != null) {
activateJobsUnchecked(state, probeRequest);
} else {
// there are no blocked requests, so use next request as probe
if (state.getFailedAttempts() >= failedAttemptThreshold) {
state.setFailedAttempts(failedAttemptThreshold - 1);
}
}
}
});
}
public static Builder newBuilder() {
return new Builder();
}
public static class Builder {
private static final long DEFAULT_LONG_POLLING_TIMEOUT = 10_000; // 10 seconds
private static final long DEFAULT_PROBE_TIMEOUT = 10_000; // 10 seconds
// Minimum number of responses with jobCount 0 to infer that no jobs are available
private static final int EMPTY_RESPONSE_THRESHOLD = 3;
private BrokerClient brokerClient;
private long longPollingTimeout = DEFAULT_LONG_POLLING_TIMEOUT;
private long probeTimeoutMillis = DEFAULT_PROBE_TIMEOUT;
private int minEmptyResponses = EMPTY_RESPONSE_THRESHOLD;
public Builder setBrokerClient(final BrokerClient brokerClient) {
this.brokerClient = brokerClient;
return this;
}
public Builder setLongPollingTimeout(final long longPollingTimeout) {
this.longPollingTimeout = longPollingTimeout;
return this;
}
public Builder setProbeTimeoutMillis(final long probeTimeoutMillis) {
this.probeTimeoutMillis = probeTimeoutMillis;
return this;
}
public Builder setMinEmptyResponses(final int minEmptyResponses) {
this.minEmptyResponses = minEmptyResponses;
return this;
}
public LongPollingActivateJobsHandler build() {
Objects.requireNonNull(brokerClient, "brokerClient");
return new LongPollingActivateJobsHandler(
brokerClient, longPollingTimeout, probeTimeoutMillis, minEmptyResponses);
}
}
}