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

temporalio / sdk-java / #427

16 Nov 2026 04:17PM UTC coverage: 71.787% (+0.1%) from 71.675%
#427

push

github

web-flow
Provide the namespace to storage drivers (#3203)

8613 of 14069 branches covered (61.22%)

Branch coverage included in aggregate %.

13 of 22 new or added lines in 12 files covered. (59.09%)

140 existing lines in 13 files now uncovered.

34118 of 45456 relevant lines covered (75.06%)

0.75 hits per line

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

98.3
/temporal-sdk/src/main/java/io/temporal/internal/activity/ActivityTaskExecutors.java
1
package io.temporal.internal.activity;
2

3
import static io.temporal.internal.activity.ActivityTaskHandlerImpl.mapToActivityFailure;
4

5
import com.uber.m3.tally.Scope;
6
import io.temporal.activity.ActivityInfo;
7
import io.temporal.activity.DynamicActivity;
8
import io.temporal.api.common.v1.Payload;
9
import io.temporal.api.common.v1.Payloads;
10
import io.temporal.api.workflowservice.v1.RespondActivityTaskCompletedRequest;
11
import io.temporal.api.workflowservice.v1.RespondActivityTaskFailedRequest;
12
import io.temporal.client.ActivityCanceledException;
13
import io.temporal.common.Copyable;
14
import io.temporal.common.context.ContextPropagator;
15
import io.temporal.common.converter.DataConverter;
16
import io.temporal.common.interceptors.ActivityInboundCallsInterceptor;
17
import io.temporal.common.interceptors.ActivityInboundCallsInterceptor.ActivityOutput;
18
import io.temporal.common.interceptors.Header;
19
import io.temporal.common.interceptors.WorkerInterceptor;
20
import io.temporal.failure.ApplicationFailure;
21
import io.temporal.internal.common.CopyableUtils;
22
import io.temporal.internal.common.FailureUtils;
23
import io.temporal.internal.common.HeaderUtils;
24
import io.temporal.internal.payload.limits.PayloadLimitViolation;
25
import io.temporal.internal.worker.ActivityTaskHandler;
26
import io.temporal.payload.codec.PayloadCodec;
27
import io.temporal.payload.context.ActivitySerializationContext;
28
import io.temporal.payload.context.NexusSerializationContext;
29
import io.temporal.serviceclient.CheckedExceptionWrapper;
30
import java.lang.reflect.Method;
31
import java.util.HashMap;
32
import java.util.List;
33
import java.util.Map;
34
import java.util.Optional;
35
import javax.annotation.Nonnull;
36
import javax.annotation.Nullable;
37
import org.slf4j.Logger;
38
import org.slf4j.LoggerFactory;
39

UNCOV
40
final class ActivityTaskExecutors {
×
41
  static final Logger log = LoggerFactory.getLogger(ActivityTaskExecutor.class);
1 ✔
42

43
  interface ActivityTaskExecutor {
44
    ActivityTaskHandler.Result execute(ActivityInfoInternal info, Scope metricsScope);
45
  }
46

47
  abstract static class BaseActivityTaskExecutor implements ActivityTaskExecutor {
48
    private final DataConverter dataConverter;
49
    private final @Nullable PayloadCodec headerCodec;
50
    private final List<ContextPropagator> contextPropagators;
51
    private final WorkerInterceptor[] interceptors;
52
    private final ActivityExecutionContextFactory executionContextFactory;
53

54
    public BaseActivityTaskExecutor(
55
        DataConverter dataConverter,
56
        List<ContextPropagator> contextPropagators,
57
        WorkerInterceptor[] interceptors,
58
        ActivityExecutionContextFactory executionContextFactory) {
1 ✔
59
      this.dataConverter = dataConverter;
1 ✔
60
      this.headerCodec = HeaderUtils.resolveHeaderCodec(dataConverter);
1 ✔
61
      this.contextPropagators = contextPropagators;
1 ✔
62
      this.interceptors = interceptors;
1 ✔
63
      this.executionContextFactory = executionContextFactory;
1 ✔
64
    }
1 ✔
65

66
    @Override
67
    public ActivityTaskHandler.Result execute(ActivityInfoInternal info, Scope metricsScope) {
68
      InternalActivityExecutionContext context =
1 ✔
69
          executionContextFactory.createContext(info, getActivity(), metricsScope);
1 ✔
70
      ActivityInfo activityInfo = context.getInfo();
1 ✔
71
      ActivitySerializationContext serializationContext =
1 ✔
72
          new ActivitySerializationContext(
73
              activityInfo.getNamespace(),
1 ✔
74
              activityInfo.getWorkflowId(),
1 ✔
75
              activityInfo.getWorkflowType(),
1 ✔
76
              activityInfo.getActivityType(),
1 ✔
77
              activityInfo.getActivityTaskQueue(),
1 ✔
78
              activityInfo.isLocal());
1 ✔
79
      DataConverter dataConverterWithActivityContext =
1 ✔
80
          dataConverter.withContext(serializationContext);
1 ✔
81
      // The result and failure of a standalone activity started from a Nexus operation handler are
82
      // returned to the Nexus caller, so they use the handler's Nexus context. Heartbeat details
83
      // use it too, because the server puts them into the timeout failure.
84
      NexusSerializationContext nexusContext = info.getNexusSerializationContext();
1 ✔
85
      DataConverter resultDataConverter =
86
          nexusContext != null
1 ✔
87
              ? dataConverter.withContext(nexusContext)
1 ✔
88
              : dataConverterWithActivityContext;
1 ✔
89

90
      try {
91
        Header header =
1 ✔
92
            new Header(
93
                info.getHeader().orElse(io.temporal.api.common.v1.Header.getDefaultInstance()),
1 ✔
94
                HeaderUtils.withContext(headerCodec, serializationContext));
1 ✔
95
        if (info.getHeader().isPresent()) {
1 ✔
96
          deserializeAndPopulateContext(header, contextPropagators);
1 ✔
97
        }
98

99
        ActivityInboundCallsInterceptor inboundCallsInterceptor = createRootInboundInterceptor();
1 ✔
100
        for (WorkerInterceptor interceptor : interceptors) {
1 ✔
101
          inboundCallsInterceptor = interceptor.interceptActivity(inboundCallsInterceptor);
1 ✔
102
        }
103
        inboundCallsInterceptor.init(context);
1 ✔
104

105
        Object[] args = provideArgs(info.getInput(), dataConverterWithActivityContext);
1 ✔
106
        ActivityOutput result =
1 ✔
107
            inboundCallsInterceptor.execute(
1 ✔
108
                new ActivityInboundCallsInterceptor.ActivityInput(header, args));
109
        if (context.isDoNotCompleteOnReturn()) {
1 ✔
110
          return new ActivityTaskHandler.Result(
1 ✔
111
              info.getActivityId(), null, null, null, context.isUseLocalManualCompletion());
1 ✔
112
        }
113
        ActivityTaskHandler.Result payloadsTooLargeResult =
1 ✔
114
            resolvePayloadsTooLargeResult(context, info, resultDataConverter);
1 ✔
115
        if (payloadsTooLargeResult != null) {
1 ✔
116
          return payloadsTooLargeResult;
1 ✔
117
        }
118

119
        return this.constructSuccessfulResultValue(info, result, resultDataConverter);
1 ✔
120
      } catch (Throwable e) {
1 ✔
121
        Throwable ex = CheckedExceptionWrapper.unwrap(e);
1 ✔
122
        boolean local = info.isLocal();
1 ✔
123
        if (ex instanceof ActivityCanceledException) {
1 ✔
124
          // An oversized heartbeat cancels the activity only to fail it, and the payload limit
125
          // validator already logged why.
126
          if (context.getPayloadLimitViolation() == null) {
1 ✔
127
            log.info(
1 ✔
128
                "{} canceled. ActivityId={}, activityType={}, attempt={}",
129
                local ? "Local activity" : "Activity",
1 !
130
                info.getActivityId(),
1 ✔
131
                info.getActivityType(),
1 ✔
132
                info.getAttempt());
1 ✔
133
          }
134
        } else if (FailureUtils.isBenignApplicationFailure(ex)) {
1 ✔
135
          log.debug(
1 ✔
136
              "{} failure. ActivityId={}, activityType={}, attempt={}",
137
              local ? "Local activity" : "Activity",
1 ✔
138
              info.getActivityId(),
1 ✔
139
              info.getActivityType(),
1 ✔
140
              info.getAttempt(),
1 ✔
141
              ex);
142
        } else {
143
          log.warn(
1 ✔
144
              "{} failure. ActivityId={}, activityType={}, attempt={}",
145
              local ? "Local activity" : "Activity",
1 ✔
146
              info.getActivityId(),
1 ✔
147
              info.getActivityType(),
1 ✔
148
              info.getAttempt(),
1 ✔
149
              ex);
150
        }
151

152
        ActivityTaskHandler.Result payloadsTooLargeResult =
1 ✔
153
            resolvePayloadsTooLargeResult(context, info, resultDataConverter);
1 ✔
154
        if (payloadsTooLargeResult != null) {
1 ✔
155
          return payloadsTooLargeResult;
1 ✔
156
        }
157
        return mapToActivityFailure(
1 ✔
158
            ex,
159
            info.getActivityId(),
1 ✔
160
            context.getLastHeartbeatValue(),
1 ✔
161
            metricsScope,
162
            local,
163
            resultDataConverter);
164
      } finally {
165
        if (context.isDoNotCompleteOnReturn()) {
1 ✔
166
          if (!context.isUseLocalManualCompletion()) {
1 ✔
167
            context.asyncCompletionStarted();
1 ✔
168
          }
169
          executionContextFactory.cleanupContext(info.getTaskToken(), false);
1 ✔
170
        } else {
171
          // if the activity is completed, we need to cancel the heartbeat
172
          // to avoid sending it after the activity is completed
173
          context.cancelOutstandingHeartbeat();
1 ✔
174
        }
175
      }
176
    }
177

178
    /**
179
     * Returns the result to report when an oversized heartbeat decided the task's outcome, or null.
180
     */
181
    @Nullable
182
    private static ActivityTaskHandler.Result resolvePayloadsTooLargeResult(
183
        InternalActivityExecutionContext context,
184
        ActivityInfoInternal info,
185
        DataConverter resultDataConverter) {
186
      // Waits out a heartbeat being sent, so that a violation it finds decides the outcome.
187
      context.cancelOutstandingHeartbeat();
1 ✔
188
      if (context.awaitTaskReported()) {
1 ✔
189
        return new ActivityTaskHandler.Result(info.getActivityId(), null, null, null, false);
1 ✔
190
      }
191
      PayloadLimitViolation violation = context.getPayloadLimitViolation();
1 ✔
192
      if (violation == null) {
1 ✔
193
        return null;
1 ✔
194
      }
195
      ApplicationFailure failure = FailureUtils.newPayloadsTooLargeFailure(violation);
1 ✔
196
      RespondActivityTaskFailedRequest request =
197
          RespondActivityTaskFailedRequest.newBuilder()
1 ✔
198
              .setFailure(resultDataConverter.exceptionToFailure(failure))
1 ✔
199
              .build();
1 ✔
200
      return new ActivityTaskHandler.Result(
1 ✔
201
          info.getActivityId(),
1 ✔
202
          null,
203
          new ActivityTaskHandler.Result.TaskFailedResult(request, failure),
204
          null,
205
          false);
206
    }
207

208
    abstract ActivityInboundCallsInterceptor createRootInboundInterceptor();
209

210
    abstract Object getActivity();
211

212
    abstract Object[] provideArgs(
213
        ActivityInput input, DataConverter dataConverterWithActivityContext);
214

215
    protected abstract ActivityTaskHandler.Result constructSuccessfulResultValue(
216
        ActivityInfoInternal info, ActivityOutput result, DataConverter resultDataConverter);
217

218
    ActivityTaskHandler.Result constructResultValue(
219
        ActivityInfoInternal info,
220
        @Nullable ActivityOutput result,
221
        DataConverter resultDataConverter) {
222
      RespondActivityTaskCompletedRequest.Builder request =
223
          RespondActivityTaskCompletedRequest.newBuilder();
1 ✔
224
      Object copiedResult = null;
1 ✔
225
      if (result != null) {
1 ✔
226
        Object value = result.getResult();
1 ✔
227
        if (info.isLocal() && result.getResult() instanceof Copyable) {
1 ✔
228
          copiedResult = CopyableUtils.copy(value);
1 ✔
229
          value = copiedResult;
1 ✔
230
        }
231
        // Serialize the same snapshot delivered to the workflow, not the activity's retained value.
232
        Optional<Payloads> serialized = resultDataConverter.toPayloads(value);
1 ✔
233
        serialized.ifPresent(request::setResult);
1 ✔
234
      }
235
      return new ActivityTaskHandler.Result(
1 ✔
236
          info.getActivityId(), request.build(), null, null, false, copiedResult);
1 ✔
237
    }
238

239
    static void deserializeAndPopulateContext(
240
        @Nonnull Header header, @Nullable List<ContextPropagator> contextPropagatorList) {
241
      if (contextPropagatorList == null || contextPropagatorList.isEmpty()) {
1 !
242
        return;
1 ✔
243
      }
244

245
      for (ContextPropagator propagator : contextPropagatorList) {
1 ✔
246
        Map<String, Payload> headerData =
247
            propagator.encodeHeaders()
1 ✔
248
                ? header.getCodecDecodedValues()
1 ✔
249
                : new HashMap<>(header.getValues());
1 ✔
250
        propagator.setCurrentContext(propagator.deserializeContext(headerData));
1 ✔
251
      }
1 ✔
252
    }
1 ✔
253
  }
254

255
  static class POJOActivityImplementation extends BaseActivityTaskExecutor {
256
    private final Method method;
257
    private final Object activity;
258

259
    POJOActivityImplementation(
260
        Method interfaceMethod,
261
        Object activity,
262
        DataConverter dataConverter,
263
        List<ContextPropagator> contextPropagators,
264
        WorkerInterceptor[] interceptors,
265
        ActivityExecutionContextFactory executionContextFactory) {
266
      super(dataConverter, contextPropagators, interceptors, executionContextFactory);
1 ✔
267
      this.method = interfaceMethod;
1 ✔
268
      this.activity = activity;
1 ✔
269
    }
1 ✔
270

271
    @Override
272
    ActivityInboundCallsInterceptor createRootInboundInterceptor() {
273
      return new RootActivityInboundCallsInterceptor.POJOActivityInboundCallsInterceptor(
1 ✔
274
          activity, method);
275
    }
276

277
    @Override
278
    Object getActivity() {
279
      return activity;
1 ✔
280
    }
281

282
    @Override
283
    Object[] provideArgs(ActivityInput input, DataConverter dataConverterWithActivityContext) {
284
      return input.getArguments(
1 ✔
285
          method.getParameterTypes(),
1 ✔
286
          method.getGenericParameterTypes(),
1 ✔
287
          dataConverterWithActivityContext);
288
    }
289

290
    @Override
291
    protected ActivityTaskHandler.Result constructSuccessfulResultValue(
292
        ActivityInfoInternal info, ActivityOutput result, DataConverter resultDataConverter) {
293
      return constructResultValue(
1 ✔
294
          info,
295
          // if the expected result of the method is null, we don't publish result at all
296
          method.getReturnType() != Void.TYPE ? result : null,
1 ✔
297
          resultDataConverter);
298
    }
299
  }
300

301
  static class DynamicActivityImplementation extends BaseActivityTaskExecutor {
302
    private final DynamicActivity activity;
303

304
    DynamicActivityImplementation(
305
        DynamicActivity activity,
306
        DataConverter dataConverter,
307
        List<ContextPropagator> contextPropagators,
308
        WorkerInterceptor[] interceptors,
309
        ActivityExecutionContextFactory executionContextFactory) {
310
      super(dataConverter, contextPropagators, interceptors, executionContextFactory);
1 ✔
311
      this.activity = activity;
1 ✔
312
    }
1 ✔
313

314
    @Override
315
    ActivityInboundCallsInterceptor createRootInboundInterceptor() {
316
      return new RootActivityInboundCallsInterceptor.DynamicActivityInboundCallsInterceptor(
1 ✔
317
          activity);
318
    }
319

320
    @Override
321
    Object getActivity() {
322
      return activity;
1 ✔
323
    }
324

325
    @Override
326
    Object[] provideArgs(ActivityInput input, DataConverter dataConverterWithActivityContext) {
327
      return new Object[] {input.getEncodedValues(dataConverterWithActivityContext)};
1 ✔
328
    }
329

330
    @Override
331
    protected ActivityTaskHandler.Result constructSuccessfulResultValue(
332
        ActivityInfoInternal info, ActivityOutput result, DataConverter resultDataConverter) {
333
      return constructResultValue(info, result, resultDataConverter);
1 ✔
334
    }
335
  }
336
}
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