-
Notifications
You must be signed in to change notification settings - Fork 113
/
Copy pathPOJOActivityTaskHandler.java
272 lines (245 loc) · 10.7 KB
/
POJOActivityTaskHandler.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
/*
* 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.sync;
import com.google.common.base.Joiner;
import com.google.common.reflect.TypeToken;
import com.uber.cadence.PollForActivityTaskResponse;
import com.uber.cadence.RespondActivityTaskCompletedRequest;
import com.uber.cadence.RespondActivityTaskFailedRequest;
import com.uber.cadence.activity.ActivityHelper;
import com.uber.cadence.activity.ActivityMethod;
import com.uber.cadence.client.ActivityCancelledException;
import com.uber.cadence.common.MethodRetry;
import com.uber.cadence.converter.DataConverter;
import com.uber.cadence.internal.common.CheckedExceptionWrapper;
import com.uber.cadence.internal.common.InternalUtils;
import com.uber.cadence.internal.metrics.MetricsTag;
import com.uber.cadence.internal.metrics.MetricsType;
import com.uber.cadence.internal.worker.ActivityTaskHandler;
import com.uber.cadence.serviceclient.IWorkflowService;
import com.uber.cadence.testing.SimulatedTimeoutException;
import com.uber.m3.tally.Scope;
import com.uber.m3.util.ImmutableMap;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.BiFunction;
class POJOActivityTaskHandler implements ActivityTaskHandler {
private final DataConverter dataConverter;
private final ScheduledExecutorService heartbeatExecutor;
private final Map<String, ActivityTaskExecutor> activities =
Collections.synchronizedMap(new HashMap<>());
private IWorkflowService service;
private final String domain;
POJOActivityTaskHandler(
IWorkflowService service,
String domain,
DataConverter dataConverter,
ScheduledExecutorService heartbeatExecutor) {
this.service = service;
this.domain = domain;
this.dataConverter = dataConverter;
this.heartbeatExecutor = heartbeatExecutor;
}
private void addActivityImplementation(
Object activity, BiFunction<Method, Object, ActivityTaskExecutor> newTaskExecutor) {
if (activity instanceof Class) {
throw new IllegalArgumentException("Activity object instance expected, not the class");
}
Class<?> cls = activity.getClass();
for (Method method : cls.getMethods()) {
if (method.getAnnotation(ActivityMethod.class) != null) {
throw new IllegalArgumentException(
"Found @ActivityMethod annotation on \""
+ method
+ "\" This annotation can be used only on the interface method it implements.");
}
if (method.getAnnotation(MethodRetry.class) != null) {
throw new IllegalArgumentException(
"Found @MethodRetry annotation on \""
+ method
+ "\" This annotation can be used only on the interface method it implements.");
}
}
TypeToken<?>.TypeSet interfaces = TypeToken.of(cls).getTypes().interfaces();
if (interfaces.isEmpty()) {
throw new IllegalArgumentException("Activity must implement at least one interface");
}
for (TypeToken<?> i : interfaces) {
if (i.getType().getTypeName().startsWith("org.mockito")) {
continue;
}
for (Method method : i.getRawType().getMethods()) {
ActivityMethod annotation = method.getAnnotation(ActivityMethod.class);
String activityType;
ActivityHelper helper = i.getRawType().getAnnotation(ActivityHelper.class);
if (helper != null) {
continue;
}
if (annotation != null && !annotation.name().isEmpty()) {
activityType = annotation.name();
} else {
activityType = InternalUtils.getSimpleName(method);
}
if (activities.containsKey(activityType)) {
throw new IllegalStateException(
activityType + " activity type is already registered with the worker");
}
ActivityTaskExecutor implementation = newTaskExecutor.apply(method, activity);
activities.put(activityType, implementation);
}
}
}
private ActivityTaskHandler.Result mapToActivityFailure(
String activityType, Throwable failure, Scope metricsScope) {
if (failure instanceof ActivityCancelledException) {
throw new CancellationException(failure.getMessage());
}
// Only expected during unit tests.
if (failure instanceof SimulatedTimeoutException) {
SimulatedTimeoutException timeoutException = (SimulatedTimeoutException) failure;
failure =
new SimulatedTimeoutExceptionInternal(
timeoutException.getTimeoutType(),
dataConverter.toData(timeoutException.getDetails()));
}
Map<String, String> activityTypeTag =
new ImmutableMap.Builder<String, String>(1)
.put(MetricsTag.ACTIVITY_TYPE, activityType)
.build();
if (failure instanceof Error) {
metricsScope.tagged(activityTypeTag).counter(MetricsType.ACTIVITY_TASK_ERROR_COUNTER).inc(1);
throw (Error) failure;
}
metricsScope.tagged(activityTypeTag).counter(MetricsType.ACTIVITY_EXEC_FAILED_COUNTER).inc(1);
RespondActivityTaskFailedRequest result = new RespondActivityTaskFailedRequest();
failure = CheckedExceptionWrapper.unwrap(failure);
result.setReason(failure.getClass().getName());
result.setDetails(dataConverter.toData(failure));
return new ActivityTaskHandler.Result(
null, new Result.TaskFailedResult(result, failure), null, null);
}
@Override
public boolean isAnyTypeSupported() {
return !activities.isEmpty();
}
void setActivitiesImplementation(Object[] activitiesImplementation) {
activities.clear();
for (Object activity : activitiesImplementation) {
addActivityImplementation(activity, POJOActivityImplementation::new);
}
}
void setLocalActivitiesImplementation(Object[] activitiesImplementation) {
activities.clear();
for (Object activity : activitiesImplementation) {
addActivityImplementation(activity, POJOLocalActivityImplementation::new);
}
}
@Override
public Result handle(
String taskList, PollForActivityTaskResponse pollResponse, Scope metricsScope) {
String activityType = pollResponse.getActivityType().getName();
ActivityTaskImpl activityTask = new ActivityTaskImpl(pollResponse, taskList);
ActivityTaskExecutor activity = activities.get(activityType);
if (activity == null) {
String knownTypes = Joiner.on(", ").join(activities.keySet());
return mapToActivityFailure(
activityType,
new IllegalArgumentException(
"Activity Type \""
+ activityType
+ "\" is not registered with a worker. Known types are: "
+ knownTypes),
metricsScope);
}
return activity.execute(activityTask, metricsScope);
}
interface ActivityTaskExecutor {
ActivityTaskHandler.Result execute(ActivityTaskImpl task, Scope metricsScope);
}
private class POJOActivityImplementation implements ActivityTaskExecutor {
private final Method method;
private final Object activity;
POJOActivityImplementation(Method interfaceMethod, Object activity) {
this.method = interfaceMethod;
this.activity = activity;
}
@Override
public ActivityTaskHandler.Result execute(ActivityTaskImpl task, Scope metricsScope) {
ActivityExecutionContext context =
new ActivityExecutionContextImpl(service, domain, task, dataConverter, heartbeatExecutor);
byte[] input = task.getInput();
Object[] args = dataConverter.fromDataArray(input, method.getGenericParameterTypes());
CurrentActivityExecutionContext.set(context);
try {
Object result = method.invoke(activity, args);
RespondActivityTaskCompletedRequest request = new RespondActivityTaskCompletedRequest();
if (context.isDoNotCompleteOnReturn()) {
return new ActivityTaskHandler.Result(null, null, null, null);
}
if (method.getReturnType() != Void.TYPE) {
request.setResult(dataConverter.toData(result));
}
return new ActivityTaskHandler.Result(request, null, null, null);
} catch (RuntimeException | IllegalAccessException e) {
return mapToActivityFailure(task.getActivityType(), e, metricsScope);
} catch (InvocationTargetException e) {
return mapToActivityFailure(task.getActivityType(), e.getTargetException(), metricsScope);
} finally {
CurrentActivityExecutionContext.unset();
}
}
}
private class POJOLocalActivityImplementation implements ActivityTaskExecutor {
private final Method method;
private final Object activity;
POJOLocalActivityImplementation(Method interfaceMethod, Object activity) {
this.method = interfaceMethod;
this.activity = activity;
}
@Override
public ActivityTaskHandler.Result execute(ActivityTaskImpl task, Scope metricsScope) {
ActivityExecutionContext context =
new LocalActivityExecutionContextImpl(service, domain, task);
CurrentActivityExecutionContext.set(context);
byte[] input = task.getInput();
Object[] args = dataConverter.fromDataArray(input, method.getGenericParameterTypes());
try {
Object result = method.invoke(activity, args);
RespondActivityTaskCompletedRequest request = new RespondActivityTaskCompletedRequest();
if (method.getReturnType() != Void.TYPE) {
request.setResult(dataConverter.toData(result));
}
return new ActivityTaskHandler.Result(request, null, null, null);
} catch (RuntimeException | IllegalAccessException e) {
return mapToActivityFailure(task.getActivityType(), e, metricsScope);
} catch (InvocationTargetException e) {
return mapToActivityFailure(task.getActivityType(), e.getTargetException(), metricsScope);
} finally {
CurrentActivityExecutionContext.unset();
}
}
}
// This is only for unit test to mock service and set expectations.
void setWorkflowService(IWorkflowService service) {
this.service = service;
}
}