• 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

90.54
/temporal-sdk/src/main/java/io/temporal/internal/sync/SyncWorkflowContext.java
1
package io.temporal.internal.sync;
2

3
import static io.temporal.client.WorkflowClient.QUERY_TYPE_STACK_TRACE;
4
import static io.temporal.client.WorkflowClient.QUERY_TYPE_WORKFLOW_METADATA;
5
import static io.temporal.internal.common.HeaderUtils.intoPayloadMap;
6
import static io.temporal.internal.common.HeaderUtils.toHeaderGrpc;
7
import static io.temporal.internal.common.RetryOptionsUtils.toRetryPolicy;
8
import static io.temporal.internal.common.WorkflowExecutionUtils.makeUserMetaData;
9
import static io.temporal.internal.sync.WorkflowInternal.DEFAULT_VERSION;
10

11
import com.google.common.base.MoreObjects;
12
import com.google.common.base.Preconditions;
13
import com.google.common.base.Strings;
14
import com.uber.m3.tally.Scope;
15
import io.temporal.activity.ActivityOptions;
16
import io.temporal.activity.LocalActivityOptions;
17
import io.temporal.api.command.v1.*;
18
import io.temporal.api.common.v1.ActivityType;
19
import io.temporal.api.common.v1.Memo;
20
import io.temporal.api.common.v1.Payload;
21
import io.temporal.api.common.v1.Payloads;
22
import io.temporal.api.common.v1.SearchAttributes;
23
import io.temporal.api.common.v1.WorkflowExecution;
24
import io.temporal.api.common.v1.WorkflowType;
25
import io.temporal.api.enums.v1.ParentClosePolicy;
26
import io.temporal.api.failure.v1.Failure;
27
import io.temporal.api.history.v1.HistoryEvent;
28
import io.temporal.api.sdk.v1.UserMetadata;
29
import io.temporal.api.sdk.v1.WorkflowDefinition;
30
import io.temporal.api.sdk.v1.WorkflowInteractionDefinition;
31
import io.temporal.api.sdk.v1.WorkflowMetadata;
32
import io.temporal.api.taskqueue.v1.TaskQueue;
33
import io.temporal.api.workflowservice.v1.PollActivityTaskQueueResponse;
34
import io.temporal.client.WorkflowException;
35
import io.temporal.common.RetryOptions;
36
import io.temporal.common.SearchAttributeUpdate;
37
import io.temporal.common.VersioningBehavior;
38
import io.temporal.common.context.ContextPropagator;
39
import io.temporal.common.converter.DataConverter;
40
import io.temporal.common.interceptors.Header;
41
import io.temporal.common.interceptors.WorkflowInboundCallsInterceptor;
42
import io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor;
43
import io.temporal.failure.*;
44
import io.temporal.internal.activity.LocalActivityArguments;
45
import io.temporal.internal.common.*;
46
import io.temporal.internal.replay.ChildWorkflowTaskFailedException;
47
import io.temporal.internal.replay.ReplayWorkflowContext;
48
import io.temporal.internal.replay.WorkflowContext;
49
import io.temporal.internal.statemachines.*;
50
import io.temporal.payload.codec.PayloadCodec;
51
import io.temporal.payload.context.ActivitySerializationContext;
52
import io.temporal.payload.context.NexusSerializationContext;
53
import io.temporal.payload.context.WorkflowSerializationContext;
54
import io.temporal.worker.WorkflowImplementationOptions;
55
import io.temporal.workflow.*;
56
import io.temporal.workflow.Functions.Func;
57
import java.lang.reflect.Type;
58
import java.time.Duration;
59
import java.time.Instant;
60
import java.util.*;
61
import java.util.concurrent.atomic.AtomicBoolean;
62
import java.util.concurrent.atomic.AtomicReference;
63
import java.util.function.BiPredicate;
64
import java.util.function.Supplier;
65
import javax.annotation.Nonnull;
66
import javax.annotation.Nullable;
67
import org.slf4j.Logger;
68
import org.slf4j.LoggerFactory;
69

70
// TODO separate WorkflowOutboundCallsInterceptor functionality from this class into
71
// RootWorkflowOutboundInterceptor
72

73
/**
74
 * Root, the most top level WorkflowContext that unites all relevant contexts, handlers, options,
75
 * states, etc. It's created when SyncWorkflow which represent a context of a workflow type
76
 * definition on the worker meets ReplayWorkflowContext which contains information from the
77
 * WorkflowTask
78
 */
79
final class SyncWorkflowContext implements WorkflowContext, WorkflowOutboundCallsInterceptor {
80
  private static final Logger log = LoggerFactory.getLogger(SyncWorkflowContext.class);
1 ✔
81

82
  private final String namespace;
83
  private final WorkflowExecution workflowExecution;
84
  private final SyncWorkflowDefinition workflowDefinition;
85
  private final WorkflowImplementationOptions workflowImplementationOptions;
86
  private final DataConverter dataConverter;
87
  private final @Nullable PayloadCodec headerCodec;
88
  // to be used in this class, should not be passed down. Pass the original #dataConverter instead
89
  private final DataConverter dataConverterWithCurrentWorkflowContext;
90
  private final List<ContextPropagator> contextPropagators;
91
  private final SignalDispatcher signalDispatcher;
92
  private final QueryDispatcher queryDispatcher;
93
  private final UpdateDispatcher updateDispatcher;
94

95
  // initialized later when these entities are created
96
  private ReplayWorkflowContext replayContext;
97
  private DeterministicRunner runner;
98

99
  private WorkflowInboundCallsInterceptor headInboundInterceptor;
100
  private WorkflowOutboundCallsInterceptor headOutboundInterceptor;
101

102
  private ActivityOptions defaultActivityOptions = null;
1 ✔
103
  private Map<String, ActivityOptions> activityOptionsMap;
104
  private LocalActivityOptions defaultLocalActivityOptions = null;
1 ✔
105
  private Map<String, LocalActivityOptions> localActivityOptionsMap;
106
  private NexusServiceOptions defaultNexusServiceOptions = null;
1 ✔
107
  private Map<String, NexusServiceOptions> nexusServiceOptionsMap;
108
  private boolean readOnly = false;
1 ✔
109
  private final WorkflowThreadLocal<UpdateInfo> currentUpdateInfo = new WorkflowThreadLocal<>();
1 ✔
110
  @Nullable private String currentDetails;
111
  // Set when the workflow was started by a Nexus operation handler. Its result and the failure that
112
  // closes it are returned to the Nexus caller, so they are serialized with the handler's Nexus
113
  // context instead of the workflow context. Everything else keeps the workflow context.
114
  @Nullable private DataConverter dataConverterWithPropagatedNexusContext;
115

116
  public SyncWorkflowContext(
117
      @Nonnull String namespace,
118
      @Nonnull WorkflowExecution workflowExecution,
119
      @Nullable SyncWorkflowDefinition workflowDefinition,
120
      SignalDispatcher signalDispatcher,
121
      QueryDispatcher queryDispatcher,
122
      UpdateDispatcher updateDispatcher,
123
      @Nullable WorkflowImplementationOptions workflowImplementationOptions,
124
      DataConverter dataConverter,
125
      List<ContextPropagator> contextPropagators) {
1 ✔
126
    this.namespace = namespace;
1 ✔
127
    this.workflowExecution = workflowExecution;
1 ✔
128
    this.workflowDefinition = workflowDefinition;
1 ✔
129
    this.dataConverter = dataConverter;
1 ✔
130
    this.headerCodec = HeaderUtils.resolveHeaderCodec(dataConverter);
1 ✔
131
    this.dataConverterWithCurrentWorkflowContext =
1 ✔
132
        dataConverter.withContext(
1 ✔
133
            new WorkflowSerializationContext(namespace, workflowExecution.getWorkflowId()));
1 ✔
134
    this.contextPropagators = contextPropagators;
1 ✔
135
    this.signalDispatcher = signalDispatcher;
1 ✔
136
    this.queryDispatcher = queryDispatcher;
1 ✔
137
    this.updateDispatcher = updateDispatcher;
1 ✔
138
    if (workflowImplementationOptions != null) {
1 ✔
139
      this.defaultActivityOptions = workflowImplementationOptions.getDefaultActivityOptions();
1 ✔
140
      this.activityOptionsMap = new HashMap<>(workflowImplementationOptions.getActivityOptions());
1 ✔
141
      this.defaultLocalActivityOptions =
1 ✔
142
          workflowImplementationOptions.getDefaultLocalActivityOptions();
1 ✔
143
      this.localActivityOptionsMap =
1 ✔
144
          new HashMap<>(workflowImplementationOptions.getLocalActivityOptions());
1 ✔
145
      this.defaultNexusServiceOptions =
1 ✔
146
          workflowImplementationOptions.getDefaultNexusServiceOptions();
1 ✔
147
      this.nexusServiceOptionsMap =
1 ✔
148
          new HashMap<>(workflowImplementationOptions.getNexusServiceOptions());
1 ✔
149
    }
150
    this.workflowImplementationOptions =
1 ✔
151
        workflowImplementationOptions == null
1 ✔
152
            ? WorkflowImplementationOptions.getDefaultInstance()
1 ✔
153
            : workflowImplementationOptions;
1 ✔
154
    // initial values for headInboundInterceptor and headOutboundInterceptor until they initialized
155
    // with actual interceptors through #initHeadInboundCallsInterceptor and
156
    // #initHeadOutboundCallsInterceptor during initialization phase.
157
    // See workflow.initialize() performed inside the workflow root thread inside
158
    // SyncWorkflow#start(HistoryEvent, ReplayWorkflowContext)
159
    this.headInboundInterceptor = new InitialWorkflowInboundCallsInterceptor(this);
1 ✔
160
    this.headOutboundInterceptor = this;
1 ✔
161
  }
1 ✔
162

163
  public void setReplayContext(ReplayWorkflowContext context) {
164
    this.replayContext = context;
1 ✔
165
  }
1 ✔
166

167
  /**
168
   * Using setter, as runner is initialized with this context, so it is not ready during
169
   * construction of this.
170
   */
171
  public void setRunner(DeterministicRunner runner) {
172
    this.runner = runner;
1 ✔
173
  }
1 ✔
174

175
  public DeterministicRunner getRunner() {
176
    return runner;
1 ✔
177
  }
178

179
  public WorkflowOutboundCallsInterceptor getWorkflowOutboundInterceptor() {
180
    return headOutboundInterceptor;
1 ✔
181
  }
182

183
  public WorkflowInboundCallsInterceptor getWorkflowInboundInterceptor() {
184
    return headInboundInterceptor;
1 ✔
185
  }
186

187
  public void initHeadOutboundCallsInterceptor(WorkflowOutboundCallsInterceptor head) {
188
    headOutboundInterceptor = head;
1 ✔
189
  }
1 ✔
190

191
  public void initHeadInboundCallsInterceptor(WorkflowInboundCallsInterceptor head) {
192
    headInboundInterceptor = head;
1 ✔
193
    signalDispatcher.setInboundCallsInterceptor(head);
1 ✔
194
    queryDispatcher.setInboundCallsInterceptor(head);
1 ✔
195
    updateDispatcher.setInboundCallsInterceptor(head);
1 ✔
196
  }
1 ✔
197

198
  public ActivityOptions getDefaultActivityOptions() {
199
    return defaultActivityOptions;
1 ✔
200
  }
201

202
  public @Nonnull Map<String, ActivityOptions> getActivityOptions() {
203
    return activityOptionsMap != null
1 !
204
        ? Collections.unmodifiableMap(activityOptionsMap)
1 ✔
UNCOV
205
        : Collections.emptyMap();
×
206
  }
207

208
  public LocalActivityOptions getDefaultLocalActivityOptions() {
209
    return defaultLocalActivityOptions;
1 ✔
210
  }
211

212
  public @Nonnull Map<String, LocalActivityOptions> getLocalActivityOptions() {
213
    return localActivityOptionsMap != null
1 !
214
        ? Collections.unmodifiableMap(localActivityOptionsMap)
1 ✔
UNCOV
215
        : Collections.emptyMap();
×
216
  }
217

218
  public NexusServiceOptions getDefaultNexusServiceOptions() {
219
    return defaultNexusServiceOptions;
1 ✔
220
  }
221

222
  public @Nonnull Map<String, NexusServiceOptions> getNexusServiceOptions() {
223
    return nexusServiceOptionsMap != null
1 !
224
        ? Collections.unmodifiableMap(nexusServiceOptionsMap)
1 ✔
UNCOV
225
        : Collections.emptyMap();
×
226
  }
227

228
  /**
229
   * Unlike the activity options above, the child workflow options have no runtime mutators, so they
230
   * are served directly from the immutable {@link WorkflowImplementationOptions}.
231
   */
232
  public ChildWorkflowOptions getDefaultChildWorkflowOptions() {
233
    return workflowImplementationOptions.getDefaultChildWorkflowOptions();
1 ✔
234
  }
235

236
  public @Nonnull Map<String, ChildWorkflowOptions> getChildWorkflowOptions() {
237
    return workflowImplementationOptions.getChildWorkflowOptions();
1 ✔
238
  }
239

240
  public void setDefaultActivityOptions(ActivityOptions defaultActivityOptions) {
241
    this.defaultActivityOptions =
1 ✔
242
        (this.defaultActivityOptions == null)
1 !
UNCOV
243
            ? defaultActivityOptions
×
244
            : this.defaultActivityOptions.toBuilder()
1 ✔
245
                .mergeActivityOptions(defaultActivityOptions)
1 ✔
246
                .build();
1 ✔
247
  }
1 ✔
248

249
  public void applyActivityOptions(Map<String, ActivityOptions> activityTypeToOption) {
250
    Objects.requireNonNull(activityTypeToOption);
1 ✔
251
    if (this.activityOptionsMap == null) {
1 !
252
      this.activityOptionsMap = new HashMap<>(activityTypeToOption);
×
UNCOV
253
      return;
×
254
    }
255
    ActivityOptionUtils.mergePredefinedActivityOptions(activityOptionsMap, activityTypeToOption);
1 ✔
256
  }
1 ✔
257

258
  public void setDefaultLocalActivityOptions(LocalActivityOptions defaultLocalActivityOptions) {
259
    this.defaultLocalActivityOptions =
1 ✔
260
        (this.defaultLocalActivityOptions == null)
1 !
UNCOV
261
            ? defaultLocalActivityOptions
×
262
            : this.defaultLocalActivityOptions.toBuilder()
1 ✔
263
                .mergeActivityOptions(defaultLocalActivityOptions)
1 ✔
264
                .build();
1 ✔
265
  }
1 ✔
266

267
  public void applyLocalActivityOptions(Map<String, LocalActivityOptions> activityTypeToOption) {
268
    Objects.requireNonNull(activityTypeToOption);
1 ✔
269
    if (this.localActivityOptionsMap == null) {
1 !
270
      this.localActivityOptionsMap = new HashMap<>(activityTypeToOption);
×
UNCOV
271
      return;
×
272
    }
273
    ActivityOptionUtils.mergePredefinedLocalActivityOptions(
1 ✔
274
        localActivityOptionsMap, activityTypeToOption);
275
  }
1 ✔
276

277
  @Override
278
  public <T> ActivityOutput<T> executeActivity(ActivityInput<T> input) {
279
    DataConverter dataConverterWithActivityContext =
1 ✔
280
        dataConverter.withContext(
1 ✔
281
            activityContext(
1 ✔
282
                input.getActivityName(),
1 ✔
283
                MoreObjects.firstNonNull(
1 ✔
284
                    input.getOptions().getTaskQueue(), replayContext.getTaskQueue()),
1 ✔
285
                false));
286
    Optional<Payloads> args = dataConverterWithActivityContext.toPayloads(input.getArgs());
1 ✔
287

288
    ActivityOutput<Optional<Payloads>> output =
1 ✔
289
        executeActivityOnce(
1 ✔
290
            input.getActivityName(),
1 ✔
291
            input.getActivityId(),
1 ✔
292
            input.getOptions(),
1 ✔
293
            input.getHeader(),
1 ✔
294
            args);
295

296
    // Avoid passing the input to the output handle as it causes the input to be retained for the
297
    // duration of the operation.
298
    Type resultType = input.getResultType();
1 ✔
299
    Class<T> resultClass = input.getResultClass();
1 ✔
300
    return new ActivityOutput<>(
1 ✔
301
        output.getActivityId(),
1 ✔
302
        output
303
            .getResult()
1 ✔
304
            .handle(
1 ✔
305
                (r, f) -> {
306
                  if (f == null) {
1 ✔
307
                    return resultType != Void.TYPE
1 ✔
308
                        ? dataConverterWithActivityContext.fromPayloads(
1 ✔
309
                            0, r, resultClass, resultType)
310
                        : null;
1 ✔
311
                  } else {
312
                    throw dataConverterWithActivityContext.failureToException(
1 ✔
313
                        ((FailureWrapperException) f).getFailure());
1 ✔
314
                  }
315
                }));
316
  }
317

318
  private ActivityOutput<Optional<Payloads>> executeActivityOnce(
319
      String activityTypeName,
320
      @Nullable String activityId,
321
      ActivityOptions options,
322
      Header header,
323
      Optional<Payloads> input) {
324
    ExecuteActivityParameters params =
1 ✔
325
        constructExecuteActivityParameters(activityTypeName, activityId, options, header, input);
1 ✔
326
    ActivityCallback callback = new ActivityCallback();
1 ✔
327
    ReplayWorkflowContext.ScheduleActivityTaskOutput activityOutput =
1 ✔
328
        replayContext.scheduleActivityTask(params, callback::invoke);
1 ✔
329
    CancellationScope.current()
1 ✔
330
        .getCancellationRequest()
1 ✔
331
        .thenApply(
1 ✔
332
            (reason) -> {
333
              activityOutput.getCancellationHandle().apply(new CanceledFailure(reason));
1 ✔
334
              return null;
1 ✔
335
            });
336
    return new ActivityOutput<>(activityOutput.getActivityId(), callback.result);
1 ✔
337
  }
338

339
  public void handleInterceptedSignal(WorkflowInboundCallsInterceptor.SignalInput input) {
340
    signalDispatcher.handleInterceptedSignal(input);
1 ✔
341
  }
1 ✔
342

343
  public void handleSignal(
344
      String signalName, Optional<Payloads> input, long eventId, Header header) {
345
    signalDispatcher.handleSignal(signalName, input, eventId, header);
1 ✔
346
  }
1 ✔
347

348
  public void handleValidateUpdate(
349
      String updateName, String updateId, Optional<Payloads> input, long eventId, Header header) {
350
    updateDispatcher.handleValidateUpdate(updateName, updateId, input, eventId, header);
1 ✔
351
  }
1 ✔
352

353
  public Optional<Payloads> handleExecuteUpdate(
354
      String updateName,
355
      String updateId,
356
      Optional<Payloads> input,
357
      long eventId,
358
      Header header,
359
      DataConverter resultDataConverter) {
360
    return updateDispatcher.handleExecuteUpdate(
1 ✔
361
        updateName, updateId, input, eventId, header, resultDataConverter);
362
  }
363

364
  public void handleInterceptedValidateUpdate(WorkflowInboundCallsInterceptor.UpdateInput input) {
365
    updateDispatcher.handleInterceptedValidateUpdate(input);
1 ✔
366
  }
1 ✔
367

368
  public WorkflowInboundCallsInterceptor.UpdateOutput handleInterceptedExecuteUpdate(
369
      WorkflowInboundCallsInterceptor.UpdateInput input) {
370
    return updateDispatcher.handleInterceptedExecuteUpdate(input);
1 ✔
371
  }
372

373
  public WorkflowInboundCallsInterceptor.QueryOutput handleInterceptedQuery(
374
      WorkflowInboundCallsInterceptor.QueryInput input) {
375
    return queryDispatcher.handleInterceptedQuery(input);
1 ✔
376
  }
377

378
  public Optional<Payloads> handleQuery(String queryName, Header header, Optional<Payloads> input) {
379
    return queryDispatcher.handleQuery(this, queryName, header, input);
1 ✔
380
  }
381

382
  public boolean isEveryHandlerFinished() {
383
    return updateDispatcher.getRunningUpdateHandlers().isEmpty()
1 ✔
384
        && signalDispatcher.getRunningSignalHandlers().isEmpty();
1 ✔
385
  }
386

387
  public WorkflowMetadata getWorkflowMetadata() {
388
    WorkflowMetadata.Builder workflowMetadata = WorkflowMetadata.newBuilder();
1 ✔
389
    WorkflowDefinition.Builder workflowDefinition = WorkflowDefinition.newBuilder();
1 ✔
390
    // Set the workflow type
391
    if (replayContext.getWorkflowType() != null) {
1 !
392
      workflowDefinition.setType(replayContext.getWorkflowType().getName());
1 ✔
393
    }
394
    // Set built in queries
395
    workflowDefinition.addQueryDefinitions(
1 ✔
396
        WorkflowInteractionDefinition.newBuilder()
1 ✔
397
            .setName(QUERY_TYPE_STACK_TRACE)
1 ✔
398
            .setDescription("Current stack trace")
1 ✔
399
            .build());
1 ✔
400
    workflowDefinition.addQueryDefinitions(
1 ✔
401
        WorkflowInteractionDefinition.newBuilder()
1 ✔
402
            .setName(QUERY_TYPE_WORKFLOW_METADATA)
1 ✔
403
            .setDescription("Metadata about the workflow")
1 ✔
404
            .build());
1 ✔
405
    // Add user defined queries
406
    workflowDefinition.addAllQueryDefinitions(queryDispatcher.getQueryHandlers());
1 ✔
407
    // Add user defined signals
408
    workflowDefinition.addAllSignalDefinitions(signalDispatcher.getSignalHandlers());
1 ✔
409
    // Add user defined update handlers
410
    workflowDefinition.addAllUpdateDefinitions(updateDispatcher.getUpdateHandlers());
1 ✔
411
    // Set the workflow definition
412
    workflowMetadata.setDefinition(workflowDefinition.build());
1 ✔
413
    // Add the current workflow details
414
    if (currentDetails != null) {
1 !
415
      workflowMetadata.setCurrentDetails(currentDetails);
1 ✔
416
    }
417
    return workflowMetadata.build();
1 ✔
418
  }
419

420
  private class ActivityCallback {
1 ✔
421
    private final CompletablePromise<Optional<Payloads>> result = Workflow.newPromise();
1 ✔
422

423
    public void invoke(Optional<Payloads> output, Failure failure) {
424
      if (failure != null) {
1 ✔
425
        runner.executeInWorkflowThread(
1 ✔
426
            "activity failure callback",
427
            () -> result.completeExceptionally(new FailureWrapperException(failure)));
1 ✔
428
      } else {
429
        runner.executeInWorkflowThread(
1 ✔
430
            "activity completion callback", () -> result.complete(output));
1 ✔
431
      }
432
    }
1 ✔
433
  }
434

435
  private class LocalActivityCallbackImpl implements LocalActivityCallback {
1 ✔
436
    private final CompletablePromise<LocalActivityCallback.Output> result = Workflow.newPromise();
1 ✔
437

438
    @Override
439
    public void apply(
440
        LocalActivityCallback.Output successOutput, LocalActivityFailedException exception) {
441
      if (exception != null) {
1 ✔
442
        runner.executeInWorkflowThread(
1 ✔
443
            "local activity failure callback", () -> result.completeExceptionally(exception));
1 ✔
444
      } else {
445
        runner.executeInWorkflowThread(
1 ✔
446
            "local activity completion callback", () -> result.complete(successOutput));
1 ✔
447
      }
448
    }
1 ✔
449
  }
450

451
  @Override
452
  public <R> LocalActivityOutput<R> executeLocalActivity(LocalActivityInput<R> input) {
453
    DataConverter dataConverterWithActivityContext =
1 ✔
454
        dataConverter.withContext(
1 ✔
455
            activityContext(input.getActivityName(), replayContext.getTaskQueue(), true));
1 ✔
456
    LocalActivityArguments arguments = LocalActivityArguments.capture(input.getArgs());
1 ✔
457
    Optional<Payloads> payloads =
458
        arguments == null
1 ✔
459
            ? dataConverterWithActivityContext.toPayloads(input.getArgs())
1 ✔
460
            : input.getOptions().isDoNotIncludeArgumentsIntoMarker()
1 ✔
461
                ? Optional.empty()
1 ✔
462
                : arguments.toPayloads(dataConverterWithActivityContext);
1 ✔
463

464
    long originalScheduledTime = System.currentTimeMillis();
1 ✔
465
    CompletablePromise<LocalActivityCallback.Output> localActivityResult =
466
        WorkflowInternal.newCompletablePromise();
1 ✔
467
    executeLocalActivityOverLocalRetryThreshold(
1 ✔
468
        input.getActivityName(),
1 ✔
469
        input.getActivityId(),
1 ✔
470
        input.getOptions(),
1 ✔
471
        input.getHeader(),
1 ✔
472
        payloads,
473
        arguments,
474
        originalScheduledTime,
475
        1,
476
        null,
477
        localActivityResult);
478

479
    // Avoid passing the input to the output handle as it causes the input to be retained for the
480
    // duration of the operation.
481
    Type resultType = input.getResultType();
1 ✔
482
    Class<R> resultClass = input.getResultClass();
1 ✔
483
    Promise<R> result =
1 ✔
484
        localActivityResult.handle(
1 ✔
485
            (r, f) -> {
486
              if (f == null) {
1 ✔
487
                if (resultClass == Void.TYPE) {
1 ✔
488
                  return null;
1 ✔
489
                }
490
                if (resultClass.isInstance(r.copiedResult)) {
1 ✔
491
                  return resultClass.cast(r.copiedResult);
1 ✔
492
                }
493
                return dataConverterWithActivityContext.fromPayloads(
1 ✔
494
                    0, r.payloads, resultClass, resultType);
495
              } else {
496
                throw dataConverterWithActivityContext.failureToException(
1 ✔
497
                    ((LocalActivityCallback.LocalActivityFailedException) f).getFailure());
1 ✔
498
              }
499
            });
500

501
    return new LocalActivityOutput<>(result);
1 ✔
502
  }
503

504
  private void executeLocalActivityOverLocalRetryThreshold(
505
      String activityTypeName,
506
      @Nullable String activityId,
507
      LocalActivityOptions options,
508
      Header header,
509
      Optional<Payloads> input,
510
      @Nullable LocalActivityArguments arguments,
511
      long originalScheduledTime,
512
      int attempt,
513
      @Nullable Failure previousExecutionFailure,
514
      CompletablePromise<LocalActivityCallback.Output> result) {
515
    CompletablePromise<LocalActivityCallback.Output> localExecutionResult =
1 ✔
516
        executeLocalActivityLocally(
1 ✔
517
            activityTypeName,
518
            activityId,
519
            options,
520
            header,
521
            input,
522
            arguments,
523
            originalScheduledTime,
524
            attempt,
525
            previousExecutionFailure);
526

527
    localExecutionResult.handle(
1 ✔
528
        (r, e) -> {
529
          if (e == null) {
1 ✔
530
            result.complete(r);
1 ✔
531
          } else {
532
            if ((e instanceof LocalActivityCallback.LocalActivityFailedException)) {
1 !
533
              LocalActivityCallback.LocalActivityFailedException laException =
1 ✔
534
                  (LocalActivityCallback.LocalActivityFailedException) e;
535
              @Nullable Duration backoff = laException.getBackoff();
1 ✔
536
              if (backoff != null) {
1 ✔
537
                WorkflowInternal.newTimer(backoff)
1 ✔
538
                    .thenApply(
1 ✔
539
                        unused -> {
540
                          executeLocalActivityOverLocalRetryThreshold(
1 ✔
541
                              activityTypeName,
542
                              activityId,
543
                              options,
544
                              header,
545
                              input,
546
                              arguments,
547
                              originalScheduledTime,
548
                              laException.getLastAttempt() + 1,
1 ✔
549
                              // Carry the attempt failure, not the local ActivityFailure wrapper.
550
                              laException.getFailure().getCause(),
1 ✔
551
                              result);
552
                          return null;
1 ✔
553
                        });
554
              } else {
555
                // final failure, report back
556
                result.completeExceptionally(laException);
1 ✔
557
              }
558
            } else {
1 ✔
559
              // Only LocalActivityFailedException is expected
UNCOV
560
              String exceptionMessage =
×
UNCOV
561
                  String.format(
×
562
                      "[BUG] Local Activity State Machine callback for activityType %s returned unexpected exception",
563
                      activityTypeName);
UNCOV
564
              log.warn(exceptionMessage, e);
×
UNCOV
565
              replayContext.failWorkflowTask(new IllegalStateException(exceptionMessage, e));
×
566
            }
567
          }
568
          return null;
1 ✔
569
        });
570
  }
1 ✔
571

572
  private CompletablePromise<LocalActivityCallback.Output> executeLocalActivityLocally(
573
      String activityTypeName,
574
      @Nullable String activityId,
575
      LocalActivityOptions options,
576
      Header header,
577
      Optional<Payloads> input,
578
      @Nullable LocalActivityArguments arguments,
579
      long originalScheduledTime,
580
      int attempt,
581
      @Nullable Failure previousExecutionFailure) {
582

583
    LocalActivityCallbackImpl callback = new LocalActivityCallbackImpl();
1 ✔
584
    ExecuteLocalActivityParameters params =
1 ✔
585
        constructExecuteLocalActivityParameters(
1 ✔
586
            activityTypeName,
587
            activityId,
588
            options,
589
            header,
590
            input,
591
            arguments,
592
            attempt,
593
            originalScheduledTime,
594
            previousExecutionFailure);
595
    Functions.Proc cancellationCallback = replayContext.scheduleLocalActivityTask(params, callback);
1 ✔
596
    CancellationScope.current()
1 ✔
597
        .getCancellationRequest()
1 ✔
598
        .thenApply(
1 ✔
599
            (reason) -> {
UNCOV
600
              cancellationCallback.apply();
×
UNCOV
601
              return null;
×
602
            });
603
    return callback.result;
1 ✔
604
  }
605

606
  private ActivitySerializationContext activityContext(
607
      String name, String taskQueue, boolean local) {
608
    return new ActivitySerializationContext(
1 ✔
609
        replayContext.getNamespace(),
1 ✔
610
        replayContext.getWorkflowId(),
1 ✔
611
        replayContext.getWorkflowType().getName(),
1 ✔
612
        name,
613
        taskQueue,
614
        local);
615
  }
616

617
  @SuppressWarnings("deprecation")
618
  private ExecuteActivityParameters constructExecuteActivityParameters(
619
      String name,
620
      @Nullable String activityId,
621
      ActivityOptions options,
622
      Header header,
623
      Optional<Payloads> input) {
624
    String taskQueue = options.getTaskQueue();
1 ✔
625
    if (taskQueue == null) {
1 ✔
626
      taskQueue = replayContext.getTaskQueue();
1 ✔
627
    }
628
    ScheduleActivityTaskCommandAttributes.Builder attributes =
629
        ScheduleActivityTaskCommandAttributes.newBuilder()
1 ✔
630
            .setActivityType(ActivityType.newBuilder().setName(name))
1 ✔
631
            .setTaskQueue(TaskQueue.newBuilder().setName(taskQueue))
1 ✔
632
            .setScheduleToStartTimeout(
1 ✔
633
                ProtobufTimeUtils.toProtoDuration(options.getScheduleToStartTimeout()))
1 ✔
634
            .setStartToCloseTimeout(
1 ✔
635
                ProtobufTimeUtils.toProtoDuration(options.getStartToCloseTimeout()))
1 ✔
636
            .setScheduleToCloseTimeout(
1 ✔
637
                ProtobufTimeUtils.toProtoDuration(options.getScheduleToCloseTimeout()))
1 ✔
638
            .setHeartbeatTimeout(ProtobufTimeUtils.toProtoDuration(options.getHeartbeatTimeout()))
1 ✔
639
            .setRequestEagerExecution(
1 ✔
640
                !options.isEagerExecutionDisabled()
1 ✔
641
                    && Objects.equals(taskQueue, replayContext.getTaskQueue()));
1 ✔
642

643
    if (activityId != null) {
1 ✔
644
      attributes.setActivityId(activityId);
1 ✔
645
    }
646

647
    input.ifPresent(attributes::setInput);
1 ✔
648
    RetryOptions retryOptions = options.getRetryOptions();
1 ✔
649
    if (retryOptions != null) {
1 ✔
650
      attributes.setRetryPolicy(toRetryPolicy(retryOptions));
1 ✔
651
    }
652

653
    // Set the context value.  Use the context propagators from the ActivityOptions
654
    // if present, otherwise use the ones configured on the WorkflowContext
655
    List<ContextPropagator> propagators = options.getContextPropagators();
1 ✔
656
    if (propagators == null) {
1 !
657
      propagators = this.contextPropagators;
1 ✔
658
    }
659
    io.temporal.api.common.v1.Header grpcHeader =
1 ✔
660
        toHeaderGrpc(
1 ✔
661
            header,
662
            HeaderUtils.fromContextPropagators(propagators),
1 ✔
663
            HeaderUtils.withContext(headerCodec, activityContext(name, taskQueue, false)));
1 ✔
664
    attributes.setHeader(grpcHeader);
1 ✔
665

666
    if (options.getVersioningIntent() != null) {
1 !
667
      attributes.setUseWorkflowBuildId(
1 ✔
668
          options
669
              .getVersioningIntent()
1 ✔
670
              .determineUseCompatibleFlag(
1 ✔
671
                  replayContext.getTaskQueue().equals(options.getTaskQueue())));
1 ✔
672
    }
673

674
    @Nullable
675
    UserMetadata userMetadata =
1 ✔
676
        makeUserMetaData(options.getSummary(), null, dataConverterWithCurrentWorkflowContext);
1 ✔
677

678
    if (options.getPriority() != null) {
1 ✔
679
      attributes.setPriority(ProtoConverters.toProto(options.getPriority()));
1 ✔
680
    }
681

682
    return new ExecuteActivityParameters(attributes, options.getCancellationType(), userMetadata);
1 ✔
683
  }
684

685
  private ExecuteLocalActivityParameters constructExecuteLocalActivityParameters(
686
      String name,
687
      @Nullable String activityId,
688
      LocalActivityOptions options,
689
      Header header,
690
      Optional<Payloads> input,
691
      @Nullable LocalActivityArguments arguments,
692
      int attempt,
693
      long originalScheduledTime,
694
      @Nullable Failure previousExecutionFailure) {
695
    options = LocalActivityOptions.newBuilder(options).validateAndBuildWithDefaults();
1 ✔
696

697
    PollActivityTaskQueueResponse.Builder activityTask =
698
        PollActivityTaskQueueResponse.newBuilder()
1 ✔
699
            .setActivityId(
1 ✔
700
                activityId != null ? activityId : this.replayContext.randomUUID().toString())
1 ✔
701
            .setWorkflowNamespace(this.replayContext.getNamespace())
1 ✔
702
            .setWorkflowType(this.replayContext.getWorkflowType())
1 ✔
703
            .setWorkflowExecution(this.replayContext.getWorkflowExecution())
1 ✔
704
            // used to pass scheduled time to the local activity code inside
705
            // ActivityExecutionContext#getInfo
706
            // setCurrentAttemptScheduledTime is called inside LocalActivityWorker before submitting
707
            // into the LA queue
708
            .setScheduledTime(
1 ✔
709
                ProtobufTimeUtils.toProtoTimestamp(Instant.ofEpochMilli(originalScheduledTime)))
1 ✔
710
            .setActivityType(ActivityType.newBuilder().setName(name))
1 ✔
711
            .setAttempt(attempt);
1 ✔
712

713
    Duration scheduleToCloseTimeout = options.getScheduleToCloseTimeout();
1 ✔
714
    if (scheduleToCloseTimeout != null) {
1 ✔
715
      activityTask.setScheduleToCloseTimeout(
1 ✔
716
          ProtobufTimeUtils.toProtoDuration(scheduleToCloseTimeout));
1 ✔
717
    }
718

719
    Duration startToCloseTimeout = options.getStartToCloseTimeout();
1 ✔
720
    if (startToCloseTimeout != null) {
1 ✔
721
      activityTask.setStartToCloseTimeout(ProtobufTimeUtils.toProtoDuration(startToCloseTimeout));
1 ✔
722
    }
723

724
    io.temporal.api.common.v1.Header grpcHeader =
1 ✔
725
        toHeaderGrpc(
1 ✔
726
            header,
727
            HeaderUtils.fromContextPropagators(contextPropagators),
1 ✔
728
            HeaderUtils.withContext(
1 ✔
729
                headerCodec, activityContext(name, replayContext.getTaskQueue(), true)));
1 ✔
730
    activityTask.setHeader(grpcHeader);
1 ✔
731
    input.ifPresent(activityTask::setInput);
1 ✔
732
    RetryOptions retryOptions = options.getRetryOptions();
1 ✔
733
    activityTask.setRetryPolicy(
1 ✔
734
        toRetryPolicy(RetryOptions.newBuilder(retryOptions).validateBuildWithDefaults()));
1 ✔
735
    Duration localRetryThreshold = options.getLocalRetryThreshold();
1 ✔
736
    if (localRetryThreshold == null) {
1 ✔
737
      localRetryThreshold = replayContext.getWorkflowTaskTimeout().multipliedBy(3);
1 ✔
738
    }
739

740
    @Nullable
741
    UserMetadata userMetadata =
1 ✔
742
        makeUserMetaData(options.getSummary(), null, dataConverterWithCurrentWorkflowContext);
1 ✔
743

744
    return new ExecuteLocalActivityParameters(
1 ✔
745
        activityTask,
746
        options.getScheduleToStartTimeout(),
1 ✔
747
        originalScheduledTime,
748
        previousExecutionFailure,
749
        options.isDoNotIncludeArgumentsIntoMarker(),
1 ✔
750
        localRetryThreshold,
751
        userMetadata,
752
        arguments);
753
  }
754

755
  @Override
756
  public <R> ChildWorkflowOutput<R> executeChildWorkflow(ChildWorkflowInput<R> input) {
757
    if (CancellationScope.current().isCancelRequested()) {
1 ✔
758
      CanceledFailure canceledFailure = new CanceledFailure("execute called from a canceled scope");
1 ✔
759
      return new ChildWorkflowOutput<>(
1 ✔
760
          Workflow.newFailedPromise(canceledFailure), Workflow.newFailedPromise(canceledFailure));
1 ✔
761
    }
762

763
    CompletablePromise<WorkflowExecution> executionPromise = Workflow.newPromise();
1 ✔
764
    CompletablePromise<Optional<Payloads>> resultPromise = Workflow.newPromise();
1 ✔
765

766
    DataConverter dataConverterWithChildWorkflowContext =
1 ✔
767
        dataConverter.withContext(
1 ✔
768
            new WorkflowSerializationContext(replayContext.getNamespace(), input.getWorkflowId()));
1 ✔
769
    Optional<Payloads> payloads = dataConverterWithChildWorkflowContext.toPayloads(input.getArgs());
1 ✔
770

771
    @Nullable
772
    Memo memo =
773
        (input.getOptions().getMemo() != null)
1 ✔
774
            ? Memo.newBuilder()
1 ✔
775
                .putAllFields(
1 ✔
776
                    intoPayloadMap(
1 ✔
777
                        dataConverterWithChildWorkflowContext, input.getOptions().getMemo()))
1 ✔
778
                .build()
1 ✔
779
            : null;
1 ✔
780

781
    @Nullable
782
    UserMetadata userMetadata =
1 ✔
783
        makeUserMetaData(
1 ✔
784
            input.getOptions().getStaticSummary(),
1 ✔
785
            input.getOptions().getStaticDetails(),
1 ✔
786
            dataConverterWithChildWorkflowContext);
787

788
    StartChildWorkflowExecutionParameters parameters =
1 ✔
789
        createChildWorkflowParameters(
1 ✔
790
            input.getWorkflowId(),
1 ✔
791
            input.getWorkflowType(),
1 ✔
792
            input.getOptions(),
1 ✔
793
            input.getHeader(),
1 ✔
794
            payloads,
795
            memo,
796
            userMetadata);
797

798
    Functions.Proc1<Exception> cancellationCallback =
1 ✔
799
        replayContext.startChildWorkflow(
1 ✔
800
            parameters,
801
            (execution, failure) -> {
802
              if (failure != null) {
1 ✔
803
                runner.executeInWorkflowThread(
1 ✔
804
                    "child workflow start failed callback",
805
                    () ->
806
                        executionPromise.completeExceptionally(
1 ✔
807
                            mapChildWorkflowException(
1 ✔
808
                                failure, dataConverterWithChildWorkflowContext)));
809
              } else {
810
                runner.executeInWorkflowThread(
1 ✔
811
                    "child workflow started callback", () -> executionPromise.complete(execution));
1 ✔
812
              }
813
            },
1 ✔
814
            (result, failure) -> {
815
              if (failure != null) {
1 ✔
816
                runner.executeInWorkflowThread(
1 ✔
817
                    "child workflow failure callback",
818
                    () ->
819
                        resultPromise.completeExceptionally(
1 ✔
820
                            mapChildWorkflowException(
1 ✔
821
                                failure, dataConverterWithChildWorkflowContext)));
822
              } else {
823
                runner.executeInWorkflowThread(
1 ✔
824
                    "child workflow completion callback", () -> resultPromise.complete(result));
1 ✔
825
              }
826
            });
1 ✔
827
    AtomicBoolean callbackCalled = new AtomicBoolean();
1 ✔
828
    CancellationScope.current()
1 ✔
829
        .getCancellationRequest()
1 ✔
830
        .thenApply(
1 ✔
831
            (reason) -> {
832
              if (!callbackCalled.getAndSet(true)) {
1 !
833
                cancellationCallback.apply(new CanceledFailure(reason));
1 ✔
834
              }
835
              return null;
1 ✔
836
            });
837

838
    // Avoid passing the input to the output handle as it causes the input to be retained for the
839
    // duration of the operation.
840
    Type resultType = input.getResultType();
1 ✔
841
    Class<R> resultClass = input.getResultClass();
1 ✔
842
    Promise<R> result =
1 ✔
843
        resultPromise.thenApply(
1 ✔
844
            (b) ->
845
                dataConverterWithChildWorkflowContext.fromPayloads(0, b, resultClass, resultType));
1 ✔
846
    return new ChildWorkflowOutput<>(result, executionPromise);
1 ✔
847
  }
848

849
  @Override
850
  public <R> ExecuteNexusOperationOutput<R> executeNexusOperation(
851
      ExecuteNexusOperationInput<R> input) {
852
    Preconditions.checkArgument(
1 ✔
853
        input.getEndpoint() != null && !input.getEndpoint().isEmpty(), "endpoint must be set");
1 !
854
    Preconditions.checkArgument(
1 ✔
855
        input.getService() != null && !input.getService().isEmpty(), "service must be set");
1 !
856

857
    if (CancellationScope.current().isCancelRequested()) {
1 !
UNCOV
858
      CanceledFailure canceledFailure =
×
859
          new CanceledFailure("execute nexus operation called from a canceled scope");
UNCOV
860
      return new ExecuteNexusOperationOutput<>(
×
UNCOV
861
          Workflow.newFailedPromise(canceledFailure), Workflow.newFailedPromise(canceledFailure));
×
862
    }
863

864
    CompletablePromise<NexusOperationExecution> operationPromise = Workflow.newPromise();
1 ✔
865
    CompletablePromise<Optional<Payload>> resultPromise = Workflow.newPromise();
1 ✔
866

867
    // The caller workflow is not available to the operation handler, so Nexus payloads are
868
    // contextualized by the endpoint, service and operation instead. The same converter decodes the
869
    // result and converts failures, so each operation keeps the converter selected for it even when
870
    // several operations are in flight at once.
871
    DataConverter nexusDataConverter =
1 ✔
872
        dataConverter.withContext(
1 ✔
873
            new NexusSerializationContext(
874
                input.getEndpoint(), input.getService(), input.getOperation()));
1 ✔
875

876
    Optional<Payload> payload = nexusDataConverter.toPayload(input.getArg());
1 ✔
877

878
    ScheduleNexusOperationCommandAttributes.Builder attributes =
879
        ScheduleNexusOperationCommandAttributes.newBuilder();
1 ✔
880
    payload.ifPresent(attributes::setInput);
1 ✔
881
    attributes.setOperation(input.getOperation());
1 ✔
882
    attributes.setService(input.getService());
1 ✔
883
    attributes.setEndpoint(input.getEndpoint());
1 ✔
884
    // Ensure that the headers are lowercase
885
    input.getHeaders().forEach((k, v) -> attributes.putNexusHeader(k.toLowerCase(), v));
1 ✔
886
    attributes.setScheduleToCloseTimeout(
1 ✔
887
        ProtobufTimeUtils.toProtoDuration(input.getOptions().getScheduleToCloseTimeout()));
1 ✔
888
    attributes.setScheduleToStartTimeout(
1 ✔
889
        ProtobufTimeUtils.toProtoDuration(input.getOptions().getScheduleToStartTimeout()));
1 ✔
890
    attributes.setStartToCloseTimeout(
1 ✔
891
        ProtobufTimeUtils.toProtoDuration(input.getOptions().getStartToCloseTimeout()));
1 ✔
892

893
    @Nullable
894
    UserMetadata userMetadata =
1 ✔
895
        makeUserMetaData(input.getOptions().getSummary(), null, nexusDataConverter);
1 ✔
896

897
    StartNexusOperationParameters parameters =
1 ✔
898
        new StartNexusOperationParameters(
899
            attributes, input.getOptions().getCancellationType(), userMetadata);
1 ✔
900

901
    Functions.Proc1<Exception> cancellationCallback =
1 ✔
902
        replayContext.startNexusOperation(
1 ✔
903
            parameters,
904
            (operationExec, failure) -> {
905
              if (failure != null) {
1 ✔
906
                runner.executeInWorkflowThread(
1 ✔
907
                    "nexus operation start failed callback",
908
                    () ->
909
                        operationPromise.completeExceptionally(
1 ✔
910
                            nexusDataConverter.failureToException(failure)));
1 ✔
911
              } else {
912
                runner.executeInWorkflowThread(
1 ✔
913
                    "nexus operation started callback",
914
                    () ->
915
                        operationPromise.complete(new NexusOperationExecutionImpl(operationExec)));
1 ✔
916
              }
917
            },
1 ✔
918
            (Optional<Payload> result, Failure failure) -> {
919
              if (failure != null) {
1 ✔
920
                runner.executeInWorkflowThread(
1 ✔
921
                    "nexus operation failure callback",
922
                    () ->
923
                        resultPromise.completeExceptionally(
1 ✔
924
                            nexusDataConverter.failureToException(failure)));
1 ✔
925
              } else {
926
                runner.executeInWorkflowThread(
1 ✔
927
                    "nexus operation completion callback", () -> resultPromise.complete(result));
1 ✔
928
              }
929
            });
1 ✔
930
    AtomicBoolean callbackCalled = new AtomicBoolean();
1 ✔
931
    CancellationScope.current()
1 ✔
932
        .getCancellationRequest()
1 ✔
933
        .thenApply(
1 ✔
934
            (reason) -> {
935
              if (!callbackCalled.getAndSet(true)) {
1 !
936
                cancellationCallback.apply(new CanceledFailure(reason));
1 ✔
937
              }
938
              return null;
1 ✔
939
            });
940
    Promise<R> result =
1 ✔
941
        resultPromise.thenApply(
1 ✔
942
            (b) ->
943
                input.getResultClass() != Void.class
1 ✔
944
                    ? nexusDataConverter.fromPayload(
1 ✔
945
                        b.get(), input.getResultClass(), input.getResultType())
1 ✔
946
                    : null);
1 ✔
947
    // We register an empty handler to make sure that this promise is always "accessed" and never
948
    // leads to a log about it being completed exceptionally and non-accessed.
949
    // The "main" operation promise is the one returned from the execute method and that
950
    // promise will always be logged if not accessed.
951
    operationPromise.handle((ex, failure) -> null);
1 ✔
952
    return new ExecuteNexusOperationOutput<>(result, operationPromise);
1 ✔
953
  }
954

955
  @SuppressWarnings("deprecation")
956
  private StartChildWorkflowExecutionParameters createChildWorkflowParameters(
957
      String workflowId,
958
      String name,
959
      ChildWorkflowOptions options,
960
      Header header,
961
      Optional<Payloads> input,
962
      @Nullable Memo memo,
963
      @Nullable UserMetadata metadata) {
964
    final StartChildWorkflowExecutionCommandAttributes.Builder attributes =
965
        StartChildWorkflowExecutionCommandAttributes.newBuilder()
1 ✔
966
            .setWorkflowType(WorkflowType.newBuilder().setName(name).build());
1 ✔
967
    attributes.setWorkflowId(workflowId);
1 ✔
968
    attributes.setNamespace(OptionsUtils.safeGet(options.getNamespace()));
1 ✔
969
    input.ifPresent(attributes::setInput);
1 ✔
970
    attributes.setWorkflowRunTimeout(
1 ✔
971
        ProtobufTimeUtils.toProtoDuration(options.getWorkflowRunTimeout()));
1 ✔
972
    attributes.setWorkflowExecutionTimeout(
1 ✔
973
        ProtobufTimeUtils.toProtoDuration(options.getWorkflowExecutionTimeout()));
1 ✔
974
    attributes.setWorkflowTaskTimeout(
1 ✔
975
        ProtobufTimeUtils.toProtoDuration(options.getWorkflowTaskTimeout()));
1 ✔
976
    String taskQueue = options.getTaskQueue();
1 ✔
977
    if (taskQueue != null) {
1 ✔
978
      attributes.setTaskQueue(TaskQueue.newBuilder().setName(taskQueue));
1 ✔
979
    }
980
    if (options.getWorkflowIdReusePolicy() != null) {
1 ✔
981
      attributes.setWorkflowIdReusePolicy(options.getWorkflowIdReusePolicy());
1 ✔
982
    }
983
    RetryOptions retryOptions = options.getRetryOptions();
1 ✔
984
    if (retryOptions != null) {
1 ✔
985
      attributes.setRetryPolicy(toRetryPolicy(retryOptions));
1 ✔
986
    }
987
    attributes.setCronSchedule(OptionsUtils.safeGet(options.getCronSchedule()));
1 ✔
988

989
    if (memo != null) {
1 ✔
990
      attributes.setMemo(memo);
1 ✔
991
    }
992

993
    Map<String, Object> searchAttributes = options.getSearchAttributes();
1 ✔
994
    if (searchAttributes != null && !searchAttributes.isEmpty()) {
1 !
995
      if (options.getTypedSearchAttributes() != null) {
1 !
UNCOV
996
        throw new IllegalArgumentException(
×
997
            "Cannot have both typed search attributes and search attributes");
998
      }
999
      attributes.setSearchAttributes(SearchAttributesUtil.encode(searchAttributes));
1 ✔
1000
    } else if (options.getTypedSearchAttributes() != null
1 ✔
1001
        && options.getTypedSearchAttributes().size() > 0) {
1 !
1002
      attributes.setSearchAttributes(
1 ✔
1003
          SearchAttributesUtil.encodeTyped(options.getTypedSearchAttributes()));
1 ✔
1004
    }
1005

1006
    List<ContextPropagator> propagators = options.getContextPropagators();
1 ✔
1007
    if (propagators == null) {
1 !
1008
      propagators = this.contextPropagators;
1 ✔
1009
    }
1010
    io.temporal.api.common.v1.Header grpcHeader =
1 ✔
1011
        toHeaderGrpc(
1 ✔
1012
            header,
1013
            HeaderUtils.fromContextPropagators(propagators),
1 ✔
1014
            HeaderUtils.withContext(
1 ✔
1015
                headerCodec,
1016
                new WorkflowSerializationContext(
1017
                    Strings.isNullOrEmpty(options.getNamespace())
1 ✔
1018
                        ? replayContext.getNamespace()
1 ✔
1019
                        : options.getNamespace(),
1 ✔
1020
                    workflowId)));
1021
    attributes.setHeader(grpcHeader);
1 ✔
1022

1023
    ParentClosePolicy parentClosePolicy = options.getParentClosePolicy();
1 ✔
1024
    if (parentClosePolicy != null) {
1 ✔
1025
      attributes.setParentClosePolicy(parentClosePolicy);
1 ✔
1026
    }
1027

1028
    if (options.getVersioningIntent() != null) {
1 ✔
1029
      attributes.setInheritBuildId(
1 ✔
1030
          options
1031
              .getVersioningIntent()
1 ✔
1032
              .determineUseCompatibleFlag(
1 ✔
1033
                  replayContext.getTaskQueue().equals(options.getTaskQueue())));
1 ✔
1034
    }
1035
    if (options.getPriority() != null) {
1 ✔
1036
      attributes.setPriority(ProtoConverters.toProto(options.getPriority()));
1 ✔
1037
    }
1038
    if (options.getVersioningOverride() != null) {
1 !
UNCOV
1039
      attributes.setVersioningOverride(ProtoConverters.toProto(options.getVersioningOverride()));
×
1040
    }
1041
    return new StartChildWorkflowExecutionParameters(
1 ✔
1042
        attributes, options.getCancellationType(), metadata);
1 ✔
1043
  }
1044

1045
  private static RuntimeException mapChildWorkflowException(
1046
      Exception failure, DataConverter dataConverterWithChildWorkflowContext) {
1047
    if (failure == null) {
1 !
UNCOV
1048
      return null;
×
1049
    }
1050
    if (failure instanceof TemporalFailure) {
1 ✔
1051
      ((TemporalFailure) failure).setDataConverter(dataConverterWithChildWorkflowContext);
1 ✔
1052
    }
1053
    if (failure instanceof CanceledFailure) {
1 ✔
1054
      return (CanceledFailure) failure;
1 ✔
1055
    }
1056
    if (failure instanceof WorkflowException) {
1 !
UNCOV
1057
      return (RuntimeException) failure;
×
1058
    }
1059
    if (failure instanceof ChildWorkflowFailure) {
1 ✔
1060
      return (ChildWorkflowFailure) failure;
1 ✔
1061
    }
1062
    if (!(failure instanceof ChildWorkflowTaskFailedException)) {
1 !
UNCOV
1063
      return new IllegalArgumentException("Unexpected exception type: ", failure);
×
1064
    }
1065
    ChildWorkflowTaskFailedException taskFailed = (ChildWorkflowTaskFailedException) failure;
1 ✔
1066
    Throwable cause =
1 ✔
1067
        dataConverterWithChildWorkflowContext.failureToException(
1 ✔
1068
            taskFailed.getOriginalCauseFailure());
1 ✔
1069
    ChildWorkflowFailure exception = taskFailed.getException();
1 ✔
1070
    return new ChildWorkflowFailure(
1 ✔
1071
        exception.getInitiatedEventId(),
1 ✔
1072
        exception.getStartedEventId(),
1 ✔
1073
        exception.getWorkflowType(),
1 ✔
1074
        exception.getExecution(),
1 ✔
1075
        exception.getNamespace(),
1 ✔
1076
        exception.getRetryState(),
1 ✔
1077
        cause);
1078
  }
1079

1080
  @Override
1081
  public Promise<Void> newTimer(Duration delay) {
1082
    return newTimer(delay, TimerOptions.newBuilder().build());
1 ✔
1083
  }
1084

1085
  @Override
1086
  public Promise<Void> newTimer(Duration delay, TimerOptions options) {
1087
    CompletablePromise<Void> p = Workflow.newPromise();
1 ✔
1088

1089
    @Nullable
1090
    UserMetadata userMetadata =
1 ✔
1091
        makeUserMetaData(options.getSummary(), null, dataConverterWithCurrentWorkflowContext);
1 ✔
1092

1093
    Functions.Proc1<RuntimeException> cancellationHandler =
1 ✔
1094
        replayContext.newTimer(
1 ✔
1095
            delay,
1096
            userMetadata,
1097
            (e) ->
1098
                runner.executeInWorkflowThread(
1 ✔
1099
                    "timer-callback",
1100
                    () -> {
1101
                      if (e == null) {
1 ✔
1102
                        p.complete(null);
1 ✔
1103
                      } else {
1104
                        p.completeExceptionally(e);
1 ✔
1105
                      }
1106
                    }));
1 ✔
1107
    CancellationScope.current()
1 ✔
1108
        .getCancellationRequest()
1 ✔
1109
        .thenApply(
1 ✔
1110
            (r) -> {
1111
              cancellationHandler.apply(new CanceledFailure(r));
1 ✔
1112
              return r;
1 ✔
1113
            });
1114
    return p;
1 ✔
1115
  }
1116

1117
  @Override
1118
  public <R> R sideEffect(Class<R> resultClass, Type resultType, Func<R> func) {
1119
    return sideEffect(resultClass, resultType, func, SideEffectOptions.newBuilder().build());
1 ✔
1120
  }
1121

1122
  @Override
1123
  public <R> R sideEffect(
1124
      Class<R> resultClass, Type resultType, Func<R> func, SideEffectOptions options) {
1125
    @Nullable
1126
    UserMetadata userMetadata =
1 ✔
1127
        makeUserMetaData(options.getSummary(), null, dataConverterWithCurrentWorkflowContext);
1 ✔
1128
    try {
1129
      CompletablePromise<Optional<Payloads>> result = Workflow.newPromise();
1 ✔
1130
      replayContext.sideEffect(
1 ✔
1131
          () -> {
1132
            try {
1133
              readOnly = true;
1 ✔
1134
              R r = func.apply();
1 ✔
1135
              return dataConverterWithCurrentWorkflowContext.toPayloads(r);
1 ✔
1136
            } finally {
1137
              readOnly = false;
1 ✔
1138
            }
1139
          },
1140
          userMetadata,
1141
          (p) ->
1142
              runner.executeInWorkflowThread(
1 ✔
1143
                  "side-effect-callback", () -> result.complete(Objects.requireNonNull(p))));
1 ✔
1144
      return dataConverterWithCurrentWorkflowContext.fromPayloads(
1 ✔
1145
          0, result.get(), resultClass, resultType);
1 ✔
1146
    } catch (Exception e) {
1 ✔
1147
      // SideEffect cannot throw normal exception as it can lead to non-deterministic behavior. So
1148
      // fail the workflow task by throwing an Error.
1149
      throw new Error(e);
1 ✔
1150
    }
1151
  }
1152

1153
  @Override
1154
  public <R> R mutableSideEffect(
1155
      String id, Class<R> resultClass, Type resultType, BiPredicate<R, R> updated, Func<R> func) {
1156
    return mutableSideEffect(
1 ✔
1157
        id, resultClass, resultType, updated, func, MutableSideEffectOptions.newBuilder().build());
1 ✔
1158
  }
1159

1160
  @Override
1161
  public <R> R mutableSideEffect(
1162
      String id,
1163
      Class<R> resultClass,
1164
      Type resultType,
1165
      BiPredicate<R, R> updated,
1166
      Func<R> func,
1167
      MutableSideEffectOptions options) {
1168
    @Nullable
1169
    UserMetadata userMetadata =
1 ✔
1170
        makeUserMetaData(options.getSummary(), null, dataConverterWithCurrentWorkflowContext);
1 ✔
1171
    try {
1172
      return mutableSideEffectImpl(id, userMetadata, resultClass, resultType, updated, func);
1 ✔
1173
    } catch (Exception e) {
1 ✔
1174
      // MutableSideEffect cannot throw normal exception as it can lead to non-deterministic
1175
      // behavior. So fail the workflow task by throwing an Error.
1176
      throw new Error(e);
1 ✔
1177
    }
1178
  }
1179

1180
  private <R> R mutableSideEffectImpl(
1181
      String id,
1182
      UserMetadata metadata,
1183
      Class<R> resultClass,
1184
      Type resultType,
1185
      BiPredicate<R, R> updated,
1186
      Func<R> func) {
1187
    CompletablePromise<Optional<Payloads>> result = Workflow.newPromise();
1 ✔
1188
    AtomicReference<R> unserializedResult = new AtomicReference<>();
1 ✔
1189
    replayContext.mutableSideEffect(
1 ✔
1190
        id,
1191
        metadata,
1192
        (storedBinary) -> {
1193
          Optional<R> stored =
1 ✔
1194
              storedBinary.map(
1 ✔
1195
                  (b) ->
1196
                      dataConverterWithCurrentWorkflowContext.fromPayloads(
1 ✔
1197
                          0, Optional.of(b), resultClass, resultType));
1 ✔
1198
          try {
1199
            readOnly = true;
1 ✔
1200
            R funcResult =
1 ✔
1201
                Objects.requireNonNull(
1 ✔
1202
                    func.apply(), "mutableSideEffect function " + "returned null");
1 ✔
1203
            if (!stored.isPresent() || updated.test(stored.get(), funcResult)) {
1 ✔
1204
              unserializedResult.set(funcResult);
1 ✔
1205
              return dataConverterWithCurrentWorkflowContext.toPayloads(funcResult);
1 ✔
1206
            }
1207
            return Optional.empty(); // returned only when value doesn't need to be updated
1 ✔
1208
          } finally {
1209
            readOnly = false;
1 ✔
1210
          }
1211
        },
1212
        (p) ->
1213
            runner.executeInWorkflowThread(
1 ✔
1214
                "mutable-side-effect-callback", () -> result.complete(Objects.requireNonNull(p))));
1 ✔
1215

1216
    if (!result.get().isPresent()) {
1 !
UNCOV
1217
      throw new IllegalArgumentException("No value found for mutableSideEffectId=" + id);
×
1218
    }
1219
    // An optimization that avoids unnecessary deserialization of the result.
1220
    R unserialized = unserializedResult.get();
1 ✔
1221
    if (unserialized != null) {
1 ✔
1222
      return unserialized;
1 ✔
1223
    }
1224
    return dataConverterWithCurrentWorkflowContext.fromPayloads(
1 ✔
1225
        0, result.get(), resultClass, resultType);
1 ✔
1226
  }
1227

1228
  @Override
1229
  public int getVersion(String changeId, int minSupported, int maxSupported) {
1230
    CompletablePromise<Integer> result = Workflow.newPromise();
1 ✔
1231
    Integer versionToUse;
1232
    try {
1233
      versionToUse =
1 ✔
1234
          replayContext.getVersion(
1 ✔
1235
              changeId,
1236
              minSupported,
1237
              maxSupported,
1238
              (v, e) ->
1239
                  runner.executeInWorkflowThread(
1 ✔
1240
                      "version-callback",
1241
                      () -> {
1242
                        if (v != null) {
1 !
1243
                          result.complete(v);
1 ✔
1244
                        } else {
UNCOV
1245
                          result.completeExceptionally(e);
×
1246
                        }
1247
                      }));
1 ✔
UNCOV
1248
    } catch (UnsupportedVersion.UnsupportedVersionException ex) {
×
UNCOV
1249
      throw new UnsupportedVersion(ex);
×
1250
    }
1 ✔
1251
    /*
1252
     * If we are replaying a workflow and encounter a getVersion call it is possible that this call did not exist
1253
     * on the original execution. If the call did not exist on the original execution then we cannot block on results
1254
     * because it can lead to non-deterministic scheduling.
1255
     * */
1256
    if (replayContext.isReplaying()
1 ✔
1257
        && versionToUse == null
1258
        && replayContext.tryUseSdkFlag(SdkFlag.SKIP_YIELD_ON_DEFAULT_VERSION)
1 ✔
1259
        && minSupported == DEFAULT_VERSION) {
1260
      return DEFAULT_VERSION;
1 ✔
1261
    }
1262

1263
    /*
1264
     * Previously the SDK would yield on the getVersion call to the scheduler. This is not ideal because it can lead to non-deterministic
1265
     * scheduling if the getVersion call was removed.
1266
     * */
1267
    if (replayContext.tryUseSdkFlag(SdkFlag.SKIP_YIELD_ON_VERSION)) {
1 ✔
1268
      // This can happen if we are replaying a workflow and encounter a getVersion call that did not
1269
      // exist on the original execution and the range does not include the default version.
1270
      if (versionToUse == null) {
1 ✔
1271
        versionToUse = DEFAULT_VERSION;
1 ✔
1272
      }
1273
      if (versionToUse < minSupported || versionToUse > maxSupported) {
1 !
1274
        throw new UnsupportedVersion(
1 ✔
1275
            new UnsupportedVersion.UnsupportedVersionException(
1276
                String.format(
1 ✔
1277
                    "Version %d of changeId %s is not supported. Supported v is between %d and %d.",
1278
                    versionToUse, changeId, minSupported, maxSupported)));
1 ✔
1279
      }
1280
      return versionToUse;
1 ✔
1281
    }
1282
    // Legacy behavior if SKIP_YIELD_ON_VERSION is not set. This means this thread will yield on the
1283
    // getVersion call.
1284
    // while it waits for the result.
1285
    try {
1286
      return result.get();
1 ✔
UNCOV
1287
    } catch (UnsupportedVersion.UnsupportedVersionException ex) {
×
UNCOV
1288
      throw new UnsupportedVersion(ex);
×
1289
    }
1290
  }
1291

1292
  @Override
1293
  public void registerQuery(RegisterQueryInput request) {
1294
    queryDispatcher.registerQueryHandlers(request);
1 ✔
1295
  }
1 ✔
1296

1297
  @Override
1298
  public void registerSignalHandlers(RegisterSignalHandlersInput input) {
1299
    signalDispatcher.registerSignalHandlers(input);
1 ✔
1300
  }
1 ✔
1301

1302
  @Override
1303
  public void registerUpdateHandlers(RegisterUpdateHandlersInput input) {
1304
    updateDispatcher.registerUpdateHandlers(input);
1 ✔
1305
  }
1 ✔
1306

1307
  @Override
1308
  public void registerDynamicSignalHandler(RegisterDynamicSignalHandlerInput input) {
1309
    signalDispatcher.registerDynamicSignalHandler(input);
1 ✔
1310
  }
1 ✔
1311

1312
  @Override
1313
  public void registerDynamicQueryHandler(RegisterDynamicQueryHandlerInput input) {
1314
    queryDispatcher.registerDynamicQueryHandler(input);
1 ✔
1315
  }
1 ✔
1316

1317
  @Override
1318
  public void registerDynamicUpdateHandler(RegisterDynamicUpdateHandlerInput input) {
1319
    updateDispatcher.registerDynamicUpdateHandler(input);
1 ✔
1320
  }
1 ✔
1321

1322
  @Override
1323
  public UUID randomUUID() {
1324
    return replayContext.randomUUID();
1 ✔
1325
  }
1326

1327
  @Override
1328
  public Random newRandom() {
1329
    return replayContext.newRandom();
1 ✔
1330
  }
1331

1332
  public DataConverter getDataConverter() {
UNCOV
1333
    return dataConverter;
×
1334
  }
1335

1336
  public DataConverter getDataConverterWithCurrentWorkflowContext() {
1337
    return dataConverterWithCurrentWorkflowContext;
1 ✔
1338
  }
1339

1340
  /**
1341
   * Records the serialization context of the Nexus operation handler that started this workflow, as
1342
   * propagated by the server in the WorkflowExecutionStarted event.
1343
   */
1344
  void setPropagatedNexusSerializationContext(
1345
      @Nullable NexusSerializationContext propagatedNexusSerializationContext) {
1346
    this.dataConverterWithPropagatedNexusContext =
1 ✔
1347
        propagatedNexusSerializationContext == null
1 ✔
1348
            ? null
1 ✔
1349
            : dataConverter.withContext(propagatedNexusSerializationContext);
1 ✔
1350
  }
1 ✔
1351

1352
  /**
1353
   * The data converter for the workflow result and the failure that closes the workflow, which are
1354
   * returned to the Nexus caller: the propagated Nexus context if the workflow was started by a
1355
   * Nexus operation handler, otherwise the workflow context. Input, memo, signals and queries
1356
   * always use the workflow context. Updates use {@link #getDataConverterForUpdateOutcome}.
1357
   */
1358
  DataConverter getDataConverterForResult() {
1359
    return dataConverterWithPropagatedNexusContext != null
1 ✔
1360
        ? dataConverterWithPropagatedNexusContext
1 ✔
1361
        : dataConverterWithCurrentWorkflowContext;
1 ✔
1362
  }
1363

1364
  boolean isReplaying() {
1365
    return replayContext.isReplaying();
1 ✔
1366
  }
1367

1368
  boolean isReadOnly() {
1369
    return readOnly;
1 ✔
1370
  }
1371

1372
  void setReadOnly(boolean readOnly) {
1373
    this.readOnly = readOnly;
1 ✔
1374
  }
1 ✔
1375

1376
  @Override
1377
  public Map<Long, SignalHandlerInfo> getRunningSignalHandlers() {
1378
    return signalDispatcher.getRunningSignalHandlers();
1 ✔
1379
  }
1380

1381
  @Override
1382
  public Map<String, UpdateHandlerInfo> getRunningUpdateHandlers() {
1383
    return updateDispatcher.getRunningUpdateHandlers();
1 ✔
1384
  }
1385

1386
  @Override
1387
  public ReplayWorkflowContext getReplayContext() {
1388
    return replayContext;
1 ✔
1389
  }
1390

1391
  @Override
1392
  public SignalExternalOutput signalExternalWorkflow(SignalExternalInput input) {
1393
    WorkflowExecution childExecution = input.getExecution();
1 ✔
1394
    DataConverter dataConverterWithChildWorkflowContext =
1 ✔
1395
        dataConverter.withContext(
1 ✔
1396
            new WorkflowSerializationContext(
1397
                replayContext.getNamespace(), childExecution.getWorkflowId()));
1 ✔
1398
    SignalExternalWorkflowExecutionCommandAttributes.Builder attributes =
1399
        SignalExternalWorkflowExecutionCommandAttributes.newBuilder();
1 ✔
1400
    attributes.setSignalName(input.getSignalName());
1 ✔
1401
    attributes.setExecution(childExecution);
1 ✔
1402
    attributes.setHeader(
1 ✔
1403
        HeaderUtils.toHeaderGrpc(
1 ✔
1404
            input.getHeader(),
1 ✔
1405
            null,
1406
            HeaderUtils.withContext(
1 ✔
1407
                headerCodec,
1408
                new WorkflowSerializationContext(
1409
                    replayContext.getNamespace(), childExecution.getWorkflowId()))));
1 ✔
1410
    Optional<Payloads> payloads = dataConverterWithChildWorkflowContext.toPayloads(input.getArgs());
1 ✔
1411
    payloads.ifPresent(attributes::setInput);
1 ✔
1412
    CompletablePromise<Void> result = Workflow.newPromise();
1 ✔
1413
    Functions.Proc1<Exception> cancellationCallback =
1 ✔
1414
        replayContext.signalExternalWorkflowExecution(
1 ✔
1415
            attributes,
1416
            (output, failure) -> {
1417
              if (failure != null) {
1 ✔
1418
                runner.executeInWorkflowThread(
1 ✔
1419
                    "child workflow failure callback",
1420
                    () ->
1421
                        result.completeExceptionally(
1 ✔
1422
                            dataConverterWithChildWorkflowContext.failureToException(failure)));
1 ✔
1423
              } else {
1424
                runner.executeInWorkflowThread(
1 ✔
1425
                    "child workflow completion callback", () -> result.complete(output));
1 ✔
1426
              }
1427
            });
1 ✔
1428
    CancellationScope.current()
1 ✔
1429
        .getCancellationRequest()
1 ✔
1430
        .thenApply(
1 ✔
1431
            (reason) -> {
1432
              cancellationCallback.apply(new CanceledFailure(reason));
1 ✔
1433
              return null;
1 ✔
1434
            });
1435
    return new SignalExternalOutput(result);
1 ✔
1436
  }
1437

1438
  @Override
1439
  public void sleep(Duration duration) {
1440
    sleep(duration, TimerOptions.newBuilder().build());
1 ✔
1441
  }
1 ✔
1442

1443
  @Override
1444
  public void sleep(Duration duration, TimerOptions options) {
1445
    newTimer(duration, options).get();
1 ✔
1446
  }
1 ✔
1447

1448
  @Override
1449
  public boolean await(Duration timeout, String reason, Supplier<Boolean> unblockCondition) {
1450
    return await(timeout, TimerOptions.newBuilder().build(), reason, unblockCondition);
1 ✔
1451
  }
1452

1453
  @Override
1454
  public boolean await(
1455
      Duration timeout, TimerOptions options, String reason, Supplier<Boolean> unblockCondition) {
1456
    boolean cancelTimerOnCondition =
1 ✔
1457
        replayContext.tryUseSdkFlag(SdkFlag.CANCEL_AWAIT_TIMER_ON_CONDITION);
1 ✔
1458

1459
    if (cancelTimerOnCondition) {
1 ✔
1460
      // If condition is already satisfied, skip creating timer
1461
      if (unblockCondition.get()) {
1 ✔
1462
        return true;
1 ✔
1463
      }
1464
      // Create timer in a cancellation scope so we can cancel it when condition is satisfied
1465
      CompletablePromise<Void> timer = Workflow.newPromise();
1 ✔
1466
      CancellationScope timerScope =
1 ✔
1467
          Workflow.newCancellationScope(() -> timer.completeFrom(newTimer(timeout, options)));
1 ✔
1468
      timerScope.run();
1 ✔
1469

1470
      WorkflowThread.await(reason, () -> (timer.isCompleted() || unblockCondition.get()));
1 ✔
1471

1472
      boolean conditionSatisfied = !timer.isCompleted();
1 ✔
1473
      if (conditionSatisfied) {
1 ✔
1474
        timerScope.cancel("await condition resolved");
1 ✔
1475
      }
1476
      return conditionSatisfied;
1 ✔
1477
    } else {
1478
      // Old behavior: timer is not cancelled when condition is satisfied
1479
      Promise<Void> timer = newTimer(timeout, options);
1 ✔
1480
      WorkflowThread.await(reason, () -> (timer.isCompleted() || unblockCondition.get()));
1 !
1481
      return !timer.isCompleted();
1 !
1482
    }
1483
  }
1484

1485
  @Override
1486
  public void await(String reason, Supplier<Boolean> unblockCondition) {
1487
    WorkflowThread.await(reason, unblockCondition);
1 ✔
1488
  }
1 ✔
1489

1490
  @SuppressWarnings("deprecation")
1491
  @Override
1492
  public void continueAsNew(ContinueAsNewInput input) {
1493
    ContinueAsNewWorkflowExecutionCommandAttributes.Builder attributes =
1494
        ContinueAsNewWorkflowExecutionCommandAttributes.newBuilder();
1 ✔
1495
    String workflowType = input.getWorkflowType();
1 ✔
1496
    if (workflowType != null) {
1 ✔
1497
      attributes.setWorkflowType(WorkflowType.newBuilder().setName(workflowType));
1 ✔
1498
    }
1499
    @Nullable ContinueAsNewOptions options = input.getOptions();
1 ✔
1500
    if (options != null) {
1 ✔
1501
      if (options.getWorkflowRunTimeout() != null) {
1 !
1502
        attributes.setWorkflowRunTimeout(
×
1503
            ProtobufTimeUtils.toProtoDuration(options.getWorkflowRunTimeout()));
×
1504
      }
1505
      if (options.getWorkflowTaskTimeout() != null) {
1 !
1506
        attributes.setWorkflowTaskTimeout(
×
UNCOV
1507
            ProtobufTimeUtils.toProtoDuration(options.getWorkflowTaskTimeout()));
×
1508
      }
1509
      if (options.getBackoffStartInterval() != null) {
1 ✔
1510
        attributes.setBackoffStartInterval(
1 ✔
1511
            ProtobufTimeUtils.toProtoDuration(options.getBackoffStartInterval()));
1 ✔
1512
      }
1513
      if (options.getTaskQueue() != null && !options.getTaskQueue().isEmpty()) {
1 ✔
1514
        attributes.setTaskQueue(TaskQueue.newBuilder().setName(options.getTaskQueue()));
1 ✔
1515
      }
1516
      if (options.getRetryOptions() != null) {
1 ✔
1517
        attributes.setRetryPolicy(toRetryPolicy(options.getRetryOptions()));
1 ✔
1518
      } else if (replayContext.getRetryOptions() != null) {
1 ✔
1519
        attributes.setRetryPolicy(toRetryPolicy(replayContext.getRetryOptions()));
1 ✔
1520
      }
1521
      Map<String, Object> searchAttributes = options.getSearchAttributes();
1 ✔
1522
      if (searchAttributes != null && !searchAttributes.isEmpty()) {
1 !
UNCOV
1523
        if (options.getTypedSearchAttributes() != null) {
×
UNCOV
1524
          throw new IllegalArgumentException(
×
1525
              "Cannot have typed search attributes and search attributes");
1526
        }
1527
        attributes.setSearchAttributes(SearchAttributesUtil.encode(searchAttributes));
×
1528
      } else if (options.getTypedSearchAttributes() != null
1 ✔
1529
          && options.getTypedSearchAttributes().size() > 0) {
1 !
1530
        attributes.setSearchAttributes(
1 ✔
1531
            SearchAttributesUtil.encodeTyped(options.getTypedSearchAttributes()));
1 ✔
1532
      } else if (options.getTypedSearchAttributes() == null && searchAttributes == null) {
1 !
1533
        // Carry over existing search attributes if none are specified.
1534
        SearchAttributes existing = replayContext.getSearchAttributes();
1 ✔
1535
        if (existing != null && !existing.getIndexedFieldsMap().isEmpty()) {
1 !
1536
          attributes.setSearchAttributes(existing);
1 ✔
1537
        }
1538
      }
1539
      Map<String, Object> memo = options.getMemo();
1 ✔
1540
      if (memo != null) {
1 ✔
1541
        attributes.setMemo(
1 ✔
1542
            Memo.newBuilder()
1 ✔
1543
                .putAllFields(intoPayloadMap(dataConverterWithCurrentWorkflowContext, memo)));
1 ✔
1544
      }
1545
      if (options.getVersioningIntent() != null) {
1 !
UNCOV
1546
        attributes.setInheritBuildId(
×
1547
            options
UNCOV
1548
                .getVersioningIntent()
×
UNCOV
1549
                .determineUseCompatibleFlag(
×
UNCOV
1550
                    replayContext.getTaskQueue().equals(options.getTaskQueue())));
×
1551
      }
1552
      if (options.getInitialVersioningBehavior() != null) {
1 !
UNCOV
1553
        switch (options.getInitialVersioningBehavior()) {
×
1554
          case AUTO_UPGRADE:
UNCOV
1555
            attributes.setInitialVersioningBehavior(
×
1556
                io.temporal.api.enums.v1.ContinueAsNewVersioningBehavior
1557
                    .CONTINUE_AS_NEW_VERSIONING_BEHAVIOR_AUTO_UPGRADE);
UNCOV
1558
            break;
×
1559
          case USE_RAMPING_VERSION:
UNCOV
1560
            attributes.setInitialVersioningBehavior(
×
1561
                io.temporal.api.enums.v1.ContinueAsNewVersioningBehavior
1562
                    .CONTINUE_AS_NEW_VERSIONING_BEHAVIOR_USE_RAMPING_VERSION);
1563
            break;
1564
        }
1565
      }
1566
    }
1567

1568
    if (options == null && replayContext.getRetryOptions() != null) {
1 ✔
1569
      // Have to copy certain options as server doesn't copy them.
1570
      attributes.setRetryPolicy(toRetryPolicy(replayContext.getRetryOptions()));
1 ✔
1571
    }
1572

1573
    if (options == null && replayContext.getSearchAttributes() != null) {
1 ✔
1574
      // Carry over existing search attributes if none are specified.
1575
      SearchAttributes existing = replayContext.getSearchAttributes();
1 ✔
1576
      if (existing != null && !existing.getIndexedFieldsMap().isEmpty()) {
1 !
1577
        attributes.setSearchAttributes(existing);
1 ✔
1578
      }
1579
    }
1580

1581
    List<ContextPropagator> propagators =
1582
        options != null && options.getContextPropagators() != null
1 !
UNCOV
1583
            ? options.getContextPropagators()
×
1584
            : this.contextPropagators;
1 ✔
1585
    io.temporal.api.common.v1.Header grpcHeader =
1 ✔
1586
        toHeaderGrpc(
1 ✔
1587
            input.getHeader(),
1 ✔
1588
            HeaderUtils.fromContextPropagators(propagators),
1 ✔
1589
            HeaderUtils.withContext(
1 ✔
1590
                headerCodec,
1591
                new WorkflowSerializationContext(namespace, workflowExecution.getWorkflowId())));
1 ✔
1592
    attributes.setHeader(grpcHeader);
1 ✔
1593

1594
    Optional<Payloads> payloads =
1 ✔
1595
        dataConverterWithCurrentWorkflowContext.toPayloads(input.getArgs());
1 ✔
1596
    payloads.ifPresent(attributes::setInput);
1 ✔
1597

1598
    replayContext.continueAsNewOnCompletion(attributes.build());
1 ✔
UNCOV
1599
    WorkflowThread.exit();
×
UNCOV
1600
  }
×
1601

1602
  @Override
1603
  public CancelWorkflowOutput cancelWorkflow(CancelWorkflowInput input) {
1604
    CompletablePromise<Void> result = Workflow.newPromise();
1 ✔
1605
    replayContext.requestCancelExternalWorkflowExecution(
1 ✔
1606
        input.getExecution(),
1 ✔
1607
        input.getReason(),
1 ✔
1608
        (r, exception) -> {
1609
          if (exception == null) {
1 !
1610
            result.complete(null);
1 ✔
1611
          } else {
UNCOV
1612
            result.completeExceptionally(exception);
×
1613
          }
1614
        });
1 ✔
1615
    return new CancelWorkflowOutput(result);
1 ✔
1616
  }
1617

1618
  @Override
1619
  public Scope getMetricsScope() {
1620
    return replayContext.getMetricsScope();
1 ✔
1621
  }
1622

1623
  public boolean isLoggingEnabledInReplay() {
1624
    return replayContext.getEnableLoggingInReplay();
1 ✔
1625
  }
1626

1627
  @Override
1628
  public void upsertSearchAttributes(Map<String, ?> searchAttributes) {
1629
    Preconditions.checkArgument(searchAttributes != null, "null search attributes");
1 !
1630
    Preconditions.checkArgument(!searchAttributes.isEmpty(), "empty search attributes");
1 ✔
1631
    SearchAttributes attr = SearchAttributesUtil.encode(searchAttributes);
1 ✔
1632
    replayContext.upsertSearchAttributes(attr);
1 ✔
1633
  }
1 ✔
1634

1635
  @Override
1636
  public void upsertTypedSearchAttributes(SearchAttributeUpdate<?>... searchAttributeUpdates) {
1637
    SearchAttributes attr = SearchAttributesUtil.encodeTypedUpdates(searchAttributeUpdates);
1 ✔
1638
    replayContext.upsertSearchAttributes(attr);
1 ✔
1639
  }
1 ✔
1640

1641
  @Override
1642
  public void upsertMemo(Map<String, Object> memo) {
1643
    Preconditions.checkArgument(memo != null, "null memo");
1 !
1644
    Preconditions.checkArgument(!memo.isEmpty(), "empty memo");
1 !
1645
    replayContext.upsertMemo(
1 ✔
1646
        Memo.newBuilder()
1 ✔
1647
            .putAllFields(intoPayloadMap(dataConverterWithCurrentWorkflowContext, memo))
1 ✔
1648
            .build());
1 ✔
1649
  }
1 ✔
1650

1651
  @Nonnull
1652
  public Object newWorkflowMethodThreadIntercepted(Runnable runnable, @Nullable String name) {
1653
    return runner.newWorkflowThread(runnable, false, name);
1 ✔
1654
  }
1655

1656
  @Nonnull
1657
  public Object newWorkflowCallbackThreadIntercepted(Runnable runnable, @Nullable String name) {
1658
    return runner.newCallbackThread(runnable, name);
1 ✔
1659
  }
1660

1661
  @Override
1662
  public Object newChildThread(Runnable runnable, boolean detached, String name) {
1663
    return runner.newWorkflowThread(runnable, detached, name);
1 ✔
1664
  }
1665

1666
  @Override
1667
  public long currentTimeMillis() {
1668
    return replayContext.currentTimeMillis();
1 ✔
1669
  }
1670

1671
  /**
1672
   * This WorkflowInboundCallsInterceptor is used during creation of the initial root workflow
1673
   * thread and should be replaced with another specific implementation during initialization stage
1674
   * {@code workflow.initialize()} performed inside the workflow root thread.
1675
   *
1676
   * @see SyncWorkflow#start(HistoryEvent, ReplayWorkflowContext)
1677
   */
1678
  private static final class InitialWorkflowInboundCallsInterceptor
1679
      extends BaseRootWorkflowInboundCallsInterceptor {
1680

1681
    public InitialWorkflowInboundCallsInterceptor(SyncWorkflowContext workflowContext) {
1682
      super(workflowContext);
1 ✔
1683
    }
1 ✔
1684

1685
    @Override
1686
    public WorkflowOutput execute(WorkflowInput input) {
UNCOV
1687
      throw new UnsupportedOperationException(
×
1688
          "SyncWorkflowContext should be initialized with a non-initial WorkflowInboundCallsInterceptor "
1689
              + "before #execute can be called");
1690
    }
1691
  }
1692

1693
  @Nonnull
1694
  @Override
1695
  public WorkflowImplementationOptions getWorkflowImplementationOptions() {
1696
    return workflowImplementationOptions;
1 ✔
1697
  }
1698

1699
  @Override
1700
  public Failure mapWorkflowExceptionToFailure(Throwable failure) {
1701
    return getDataConverterForResult().exceptionToFailure(failure);
1 ✔
1702
  }
1703

1704
  /**
1705
   * The data converter for an update's result, failure and rejection, which are returned to the
1706
   * update's caller: the Nexus context of the Nexus operation handler that sent the update, if it
1707
   * was sent by one, otherwise the workflow context. Unlike {@link #getDataConverterForResult},
1708
   * this doesn't depend on how the workflow was started, because the outcome belongs to the update
1709
   * rather than closing the workflow. The update's arguments always use the workflow context.
1710
   */
1711
  DataConverter getDataConverterForUpdateOutcome(
1712
      @Nullable NexusSerializationContext nexusSerializationContext) {
1713
    return nexusSerializationContext != null
1 ✔
1714
        ? dataConverter.withContext(nexusSerializationContext)
1 ✔
1715
        : dataConverterWithCurrentWorkflowContext;
1 ✔
1716
  }
1717

1718
  @Nullable
1719
  @Override
1720
  public <R> R getLastCompletionResult(Class<R> resultClass, Type resultType) {
1721
    return dataConverterWithCurrentWorkflowContext.fromPayloads(
1 ✔
1722
        0, Optional.ofNullable(replayContext.getLastCompletionResult()), resultClass, resultType);
1 ✔
1723
  }
1724

1725
  @Override
1726
  public List<ContextPropagator> getContextPropagators() {
1727
    return contextPropagators;
1 ✔
1728
  }
1729

1730
  Header headerWithCodec(io.temporal.api.common.v1.Header header) {
1731
    return new Header(
1 ✔
1732
        header,
1733
        HeaderUtils.withContext(
1 ✔
1734
            headerCodec,
1735
            new WorkflowSerializationContext(namespace, workflowExecution.getWorkflowId())));
1 ✔
1736
  }
1737

1738
  @Override
1739
  public Map<String, Object> getPropagatedContexts() {
1740
    if (contextPropagators == null || contextPropagators.isEmpty()) {
1 ✔
1741
      return new HashMap<>();
1 ✔
1742
    }
1743

1744
    Map<String, Object> contextData = new HashMap<>();
1 ✔
1745
    Header header =
1 ✔
1746
        headerWithCodec(
1 ✔
1747
            io.temporal.api.common.v1.Header.newBuilder()
1 ✔
1748
                .putAllFields(replayContext.getHeader())
1 ✔
1749
                .build());
1 ✔
1750
    for (ContextPropagator propagator : contextPropagators) {
1 ✔
1751
      Map<String, Payload> headerData =
1752
          propagator.encodeHeaders()
1 ✔
1753
              ? header.getCodecDecodedValues()
1 ✔
1754
              : new HashMap<>(header.getValues());
1 ✔
1755
      contextData.put(propagator.getName(), propagator.deserializeContext(headerData));
1 ✔
1756
    }
1 ✔
1757

1758
    return contextData;
1 ✔
1759
  }
1760

1761
  @Override
1762
  public VersioningBehavior getVersioningBehavior() {
1763
    return workflowDefinition.getVersioningBehavior();
1 ✔
1764
  }
1765

1766
  public void setCurrentUpdateInfo(UpdateInfo updateInfo) {
1767
    currentUpdateInfo.set(updateInfo);
1 ✔
1768
  }
1 ✔
1769

1770
  public void setCurrentDetails(String details) {
1771
    currentDetails = details;
1 ✔
1772
  }
1 ✔
1773

1774
  @Nullable
1775
  public Object getInstance() {
1776
    return workflowDefinition.getInstance();
1 ✔
1777
  }
1778

1779
  @Nullable
1780
  public String getCurrentDetails() {
1781
    return currentDetails;
1 ✔
1782
  }
1783

1784
  public Optional<UpdateInfo> getCurrentUpdateInfo() {
1785
    return Optional.ofNullable(currentUpdateInfo.get());
1 ✔
1786
  }
1787

1788
  /** Simple wrapper over a failure just to allow completing the CompletablePromise as a failure */
1789
  private static class FailureWrapperException extends RuntimeException {
1790
    private final Failure failure;
1791

1792
    public FailureWrapperException(Failure failure) {
1 ✔
1793
      this.failure = failure;
1 ✔
1794
    }
1 ✔
1795

1796
    public Failure getFailure() {
1797
      return failure;
1 ✔
1798
    }
1799
  }
1800
}
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