-
Notifications
You must be signed in to change notification settings - Fork 106
/
ClockDecisionContext.java
443 lines (392 loc) · 17 KB
/
ClockDecisionContext.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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
/*
* Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Modifications copyright (C) 2017 Uber Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not
* use this file except in compliance with the License. A copy of the License is
* located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 com.uber.cadence.internal.replay;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.uber.cadence.ActivityType;
import com.uber.cadence.HistoryEvent;
import com.uber.cadence.MarkerRecordedEventAttributes;
import com.uber.cadence.SearchAttributes;
import com.uber.cadence.StartTimerDecisionAttributes;
import com.uber.cadence.TimerCanceledEventAttributes;
import com.uber.cadence.TimerFiredEventAttributes;
import com.uber.cadence.converter.DataConverter;
import com.uber.cadence.internal.common.LocalActivityMarkerData;
import com.uber.cadence.internal.sync.WorkflowInternal;
import com.uber.cadence.internal.worker.LocalActivityWorker;
import com.uber.cadence.workflow.ActivityFailureException;
import com.uber.cadence.workflow.Functions.Func;
import com.uber.cadence.workflow.Functions.Func1;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CancellationException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Predicate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Clock that must be used inside workflow definition code to ensure replay determinism. */
public final class ClockDecisionContext {
private static final String SIDE_EFFECT_MARKER_NAME = "SideEffect";
private static final String MUTABLE_SIDE_EFFECT_MARKER_NAME = "MutableSideEffect";
public static final String VERSION_MARKER_NAME = "Version";
public static final String LOCAL_ACTIVITY_MARKER_NAME = "LocalActivity";
private static final Logger log = LoggerFactory.getLogger(ClockDecisionContext.class);
private final class TimerCancellationHandler implements Consumer<Exception> {
private final long startEventId;
TimerCancellationHandler(long timerId) {
this.startEventId = timerId;
}
@Override
public void accept(Exception reason) {
decisions.cancelTimer(startEventId, () -> timerCancelled(startEventId, reason));
}
}
private final DecisionsHelper decisions;
// key is startedEventId
private final Map<Long, OpenRequestInfo<?, Long>> scheduledTimers = new HashMap<>();
private long replayCurrentTimeMilliseconds = -1;
// Local time when replayCurrentTimeMilliseconds was updated.
private long replayTimeUpdatedAtMillis = -1;
private boolean replaying = true;
// Key is side effect marker eventId
private final Map<Long, byte[]> sideEffectResults = new HashMap<>();
private final MarkerHandler mutableSideEffectHandler;
private final MarkerHandler versionHandler;
private final BiFunction<LocalActivityWorker.Task, Duration, Boolean> laTaskPoller;
private final Map<String, OpenRequestInfo<byte[], ActivityType>> pendingLaTasks = new HashMap<>();
private final Map<String, ExecuteLocalActivityParameters> unstartedLaTasks = new HashMap<>();
private final ReplayDecider replayDecider;
private final DataConverter dataConverter;
private final Condition taskCondition;
private boolean taskCompleted = false;
private final Map<String, Integer> versionMap = new HashMap<>();
static final class GetVersionResult {
private final int version;
private final boolean shouldUpdateCadenceChangeVersion;
private final Map<String, Object> searchAttributesForChangeVersion;
GetVersionResult(
final int version,
final boolean isNewlyAdded,
final Map<String, Object> searchAttributesForChangeVersion) {
this.version = version;
this.shouldUpdateCadenceChangeVersion = isNewlyAdded;
this.searchAttributesForChangeVersion = searchAttributesForChangeVersion;
}
public int getVersion() {
return version;
}
public boolean shouldUpdateCadenceChangeVersion() {
return shouldUpdateCadenceChangeVersion;
}
public Map<String, Object> getSearchAttributesForChangeVersion() {
return searchAttributesForChangeVersion;
}
}
ClockDecisionContext(
DecisionsHelper decisions,
BiFunction<LocalActivityWorker.Task, Duration, Boolean> laTaskPoller,
ReplayDecider replayDecider,
DataConverter dataConverter) {
this.decisions = decisions;
this.taskCondition = replayDecider.getLock().newCondition();
mutableSideEffectHandler =
new MarkerHandler(decisions, MUTABLE_SIDE_EFFECT_MARKER_NAME, () -> replaying);
versionHandler = new MarkerHandler(decisions, VERSION_MARKER_NAME, () -> replaying);
this.laTaskPoller = laTaskPoller;
this.replayDecider = replayDecider;
this.dataConverter = dataConverter;
}
public long currentTimeMillis() {
return replayCurrentTimeMilliseconds;
}
private long replayTimeUpdatedAtMillis() {
return replayTimeUpdatedAtMillis;
}
void setReplayCurrentTimeMilliseconds(long replayCurrentTimeMilliseconds) {
if (this.replayCurrentTimeMilliseconds < replayCurrentTimeMilliseconds) {
this.replayCurrentTimeMilliseconds = replayCurrentTimeMilliseconds;
this.replayTimeUpdatedAtMillis = System.currentTimeMillis();
}
}
boolean isReplaying() {
return replaying;
}
Consumer<Exception> createTimer(long delaySeconds, Consumer<Exception> callback) {
if (delaySeconds < 0) {
throw new IllegalArgumentException("Negative delaySeconds: " + delaySeconds);
}
if (delaySeconds == 0) {
callback.accept(null);
return null;
}
long firingTime = currentTimeMillis() + TimeUnit.SECONDS.toMillis(delaySeconds);
final OpenRequestInfo<?, Long> context = new OpenRequestInfo<>(firingTime);
final StartTimerDecisionAttributes timer = new StartTimerDecisionAttributes();
timer.setStartToFireTimeoutSeconds(delaySeconds);
timer.setTimerId(String.valueOf(decisions.getAndIncrementNextId()));
long startEventId = decisions.startTimer(timer);
context.setCompletionHandle((ctx, e) -> callback.accept(e));
scheduledTimers.put(startEventId, context);
return new TimerCancellationHandler(startEventId);
}
void setReplaying(boolean replaying) {
this.replaying = replaying;
}
void handleTimerFired(TimerFiredEventAttributes attributes) {
long startedEventId = attributes.getStartedEventId();
if (decisions.handleTimerClosed(attributes)) {
OpenRequestInfo<?, Long> scheduled = scheduledTimers.remove(startedEventId);
if (scheduled != null) {
// Server doesn't guarantee that the timer fire timestamp is larger or equal of the
// expected fire time. So fix the time or timer firing will be ignored.
long firingTime = scheduled.getUserContext();
if (replayCurrentTimeMilliseconds < firingTime) {
setReplayCurrentTimeMilliseconds(firingTime);
}
BiConsumer<?, Exception> completionCallback = scheduled.getCompletionCallback();
completionCallback.accept(null, null);
}
}
}
void handleTimerCanceled(HistoryEvent event) {
TimerCanceledEventAttributes attributes = event.getTimerCanceledEventAttributes();
long startedEventId = attributes.getStartedEventId();
if (decisions.handleTimerCanceled(event)) {
timerCancelled(startedEventId, null);
}
}
private void timerCancelled(long startEventId, Exception reason) {
OpenRequestInfo<?, ?> scheduled = scheduledTimers.remove(startEventId);
if (scheduled == null) {
return;
}
BiConsumer<?, Exception> context = scheduled.getCompletionCallback();
CancellationException exception = new CancellationException("Cancelled by request");
exception.initCause(reason);
context.accept(null, exception);
}
byte[] sideEffect(Func<byte[]> func) {
decisions.addAllMissingVersionMarker(false, Optional.empty());
long sideEffectEventId = decisions.getNextDecisionEventId();
byte[] result;
if (replaying) {
result = sideEffectResults.get(sideEffectEventId);
if (result == null) {
throw new Error("No cached result found for SideEffect EventID=" + sideEffectEventId);
}
} else {
try {
result = func.apply();
} catch (Error e) {
throw e;
} catch (Exception e) {
throw new Error("sideEffect function failed", e);
}
}
decisions.recordMarker(SIDE_EFFECT_MARKER_NAME, null, result);
return result;
}
/**
* @param id mutable side effect id
* @param func given the value from the last marker returns value to store. If result is empty
* nothing is recorded into the history.
* @return the latest value returned by func
*/
Optional<byte[]> mutableSideEffect(
String id, DataConverter converter, Func1<Optional<byte[]>, Optional<byte[]>> func) {
decisions.addAllMissingVersionMarker(false, Optional.empty());
final MarkerHandler.HandleResult results = mutableSideEffectHandler.handle(id, converter, func);
return results.getStoredData();
}
void upsertSearchAttributes(SearchAttributes searchAttributes) {
decisions.upsertSearchAttributes(searchAttributes);
}
void handleMarkerRecorded(HistoryEvent event) {
MarkerRecordedEventAttributes attributes = event.getMarkerRecordedEventAttributes();
String name = attributes.getMarkerName();
if (SIDE_EFFECT_MARKER_NAME.equals(name)) {
sideEffectResults.put(event.getEventId(), attributes.getDetails());
} else if (LOCAL_ACTIVITY_MARKER_NAME.equals(name)) {
handleLocalActivityMarker(attributes);
} else if (VERSION_MARKER_NAME.equals(name)) {
handleVersionMarker(attributes);
} else if (!MUTABLE_SIDE_EFFECT_MARKER_NAME.equals(name) && !VERSION_MARKER_NAME.equals(name)) {
if (log.isWarnEnabled()) {
log.warn("Unexpected marker: " + event);
}
}
}
private void handleLocalActivityMarker(MarkerRecordedEventAttributes attributes) {
LocalActivityMarkerData marker =
LocalActivityMarkerData.fromEventAttributes(attributes, dataConverter);
if (pendingLaTasks.containsKey(marker.getActivityId())) {
log.debug("Handle LocalActivityMarker for activity " + marker.getActivityId());
decisions.recordMarker(
LOCAL_ACTIVITY_MARKER_NAME, marker.getHeader(dataConverter), attributes.getDetails());
OpenRequestInfo<byte[], ActivityType> scheduled =
pendingLaTasks.remove(marker.getActivityId());
unstartedLaTasks.remove(marker.getActivityId());
Exception failure = null;
if (marker.getIsCancelled()) {
failure = new CancellationException(marker.getErrReason());
} else if (marker.getErrJson() != null) {
Throwable cause =
dataConverter.fromData(marker.getErrJson(), Throwable.class, Throwable.class);
ActivityType activityType = new ActivityType();
activityType.setName(marker.getActivityType());
failure =
new ActivityFailureException(
attributes.getDecisionTaskCompletedEventId(),
activityType,
marker.getActivityId(),
cause,
marker.getAttempt(),
marker.getBackoff());
}
BiConsumer<byte[], Exception> completionHandle = scheduled.getCompletionCallback();
completionHandle.accept(marker.getResult(), failure);
setReplayCurrentTimeMilliseconds(marker.getReplayTimeMillis());
taskCompleted = true;
// This method is already called under the lock.
taskCondition.signal();
}
}
private void handleVersionMarker(MarkerRecordedEventAttributes attributes) {
MarkerHandler.MarkerInterface markerData =
MarkerHandler.MarkerInterface.fromEventAttributes(attributes, dataConverter);
String versionID = markerData.getId();
int version = dataConverter.fromData(attributes.getDetails(), Integer.class, Integer.class);
versionMap.put(versionID, version);
}
GetVersionResult getVersion(
String changeId, DataConverter converter, int minSupported, int maxSupported) {
Predicate<MarkerRecordedEventAttributes> changeIdEquals =
(attributes) -> {
MarkerHandler.MarkerInterface markerData =
MarkerHandler.MarkerInterface.fromEventAttributes(attributes, converter);
return markerData.getId().equals(changeId);
};
decisions.addAllMissingVersionMarker(true, Optional.of(changeIdEquals));
final MarkerHandler.HandleResult result =
versionHandler.handle(
changeId,
converter,
(stored) -> {
if (stored.isPresent()) {
return Optional.empty();
}
return Optional.of(converter.toData(maxSupported));
});
final boolean isNewlyAdded = result.isNewlyStored();
Map<String, Object> searchAttributesForChangeVersion = null;
if (isNewlyAdded) {
searchAttributesForChangeVersion =
createSearchAttributesForChangeVersion(changeId, maxSupported, versionMap);
}
Integer version = versionMap.get(changeId);
if (version != null) {
validateVersion(changeId, version, minSupported, maxSupported);
return new GetVersionResult(version, isNewlyAdded, searchAttributesForChangeVersion);
}
if (!result.getStoredData().isPresent()) {
return new GetVersionResult(
WorkflowInternal.DEFAULT_VERSION, false, searchAttributesForChangeVersion);
}
version = converter.fromData(result.getStoredData().get(), Integer.class, Integer.class);
validateVersion(changeId, version, minSupported, maxSupported);
return new GetVersionResult(version, isNewlyAdded, searchAttributesForChangeVersion);
}
private void validateVersion(String changeID, int version, int minSupported, int maxSupported) {
if ((version < minSupported || version > maxSupported)
&& version != WorkflowInternal.DEFAULT_VERSION) {
throw new Error(
String.format(
"Version %d of changeID %s is not supported. Supported version is between %d and %d.",
version, changeID, minSupported, maxSupported));
}
}
private Map<String, Object> createSearchAttributesForChangeVersion(
String changeID, Integer version, Map<String, Integer> existingChangeVersions) {
return ImmutableMap.of(
WorkflowInternal.CADENCE_CHANGE_VERSION,
getChangeVersions(changeID, version, existingChangeVersions));
}
private List<String> getChangeVersions(
String changeID, Integer version, Map<String, Integer> existingChangeVersions) {
ArrayList<String> res = new ArrayList<>();
// as the convention, the first element is always the latest version
res.add(getChangeVersion(changeID, version));
for (Map.Entry<String, Integer> entry : existingChangeVersions.entrySet()) {
res.add(getChangeVersion(entry.getKey(), entry.getValue()));
}
return res;
}
private String getChangeVersion(String changeID, Integer version) {
return changeID + "-" + version;
}
Consumer<Exception> scheduleLocalActivityTask(
ExecuteLocalActivityParameters params, BiConsumer<byte[], Exception> callback) {
final OpenRequestInfo<byte[], ActivityType> context =
new OpenRequestInfo<>(params.getActivityType());
context.setCompletionHandle(callback);
if (Strings.isNullOrEmpty(params.getActivityId())) {
params.setActivityId(decisions.getAndIncrementNextId());
}
pendingLaTasks.put(params.getActivityId(), context);
unstartedLaTasks.put(params.getActivityId(), params);
return null;
}
boolean startUnstartedLaTasks(Duration maxWaitAllowed) {
long startTime = System.currentTimeMillis();
for (ExecuteLocalActivityParameters params : unstartedLaTasks.values()) {
long currTime = System.currentTimeMillis();
maxWaitAllowed = maxWaitAllowed.minus(Duration.ofMillis(currTime - startTime));
boolean applied =
laTaskPoller.apply(
new LocalActivityWorker.Task(
params,
replayDecider.getLocalActivityCompletionSink(),
replayDecider.getDecisionTimeoutSeconds(),
this::currentTimeMillis,
this::replayTimeUpdatedAtMillis),
maxWaitAllowed);
if (!applied) {
return false;
}
}
unstartedLaTasks.clear();
return true;
}
int numPendingLaTasks() {
return pendingLaTasks.size();
}
void awaitTaskCompletion(Duration duration) throws InterruptedException {
while (!taskCompleted) {
// This call is called from already locked object
taskCondition.awaitNanos(duration.toNanos());
}
taskCompleted = false;
}
}