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

temporalio / sdk-java / #433

20 Nov 2026 11:28PM UTC coverage: 71.886% (+0.05%) from 71.837%
#433

push

github

web-flow
Report storage driver types in worker heartbeats (#3230)

8791 of 14383 branches covered (61.12%)

Branch coverage included in aggregate %.

9 of 9 new or added lines in 1 file covered. (100.0%)

146 existing lines in 21 files now uncovered.

34692 of 46106 relevant lines covered (75.24%)

0.75 hits per line

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

90.77
/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.EventGroupMarker;
29
import io.temporal.api.sdk.v1.UserMetadata;
30
import io.temporal.api.sdk.v1.WorkflowDefinition;
31
import io.temporal.api.sdk.v1.WorkflowInteractionDefinition;
32
import io.temporal.api.sdk.v1.WorkflowMetadata;
33
import io.temporal.api.taskqueue.v1.TaskQueue;
34
import io.temporal.api.workflowservice.v1.PollActivityTaskQueueResponse;
35
import io.temporal.client.WorkflowException;
36
import io.temporal.common.RetryOptions;
37
import io.temporal.common.SearchAttributeUpdate;
38
import io.temporal.common.VersioningBehavior;
39
import io.temporal.common.context.ContextPropagator;
40
import io.temporal.common.converter.DataConverter;
41
import io.temporal.common.interceptors.Header;
42
import io.temporal.common.interceptors.WorkflowInboundCallsInterceptor;
43
import io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor;
44
import io.temporal.failure.*;
45
import io.temporal.internal.activity.LocalActivityArguments;
46
import io.temporal.internal.common.*;
47
import io.temporal.internal.replay.ChildWorkflowTaskFailedException;
48
import io.temporal.internal.replay.ReplayWorkflowContext;
49
import io.temporal.internal.replay.WorkflowContext;
50
import io.temporal.internal.statemachines.*;
51
import io.temporal.payload.codec.PayloadCodec;
52
import io.temporal.payload.context.ActivitySerializationContext;
53
import io.temporal.payload.context.NexusSerializationContext;
54
import io.temporal.payload.context.WorkflowSerializationContext;
55
import io.temporal.worker.WorkflowImplementationOptions;
56
import io.temporal.workflow.*;
57
import io.temporal.workflow.Functions.Func;
58
import java.lang.reflect.Type;
59
import java.time.Duration;
60
import java.time.Instant;
61
import java.util.*;
62
import java.util.concurrent.atomic.AtomicBoolean;
63
import java.util.concurrent.atomic.AtomicReference;
64
import java.util.function.BiPredicate;
65
import java.util.function.Supplier;
66
import javax.annotation.Nonnull;
67
import javax.annotation.Nullable;
68
import org.slf4j.Logger;
69
import org.slf4j.LoggerFactory;
70

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

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

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

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

100
  private WorkflowInboundCallsInterceptor headInboundInterceptor;
101
  private WorkflowOutboundCallsInterceptor headOutboundInterceptor;
102

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

465
    long originalScheduledTime = System.currentTimeMillis();
1 ✔
466
    CompletablePromise<LocalActivityCallback.Output> localActivityResult =
467
        WorkflowInternal.newCompletablePromise();
1 ✔
468

469
    // Retries and backoff timers are issued from callback threads, which don't inherit
470
    // the active EG scope from this thread. Capture the current scope (merging in direct
471
    // assignments passed to this LA), and reuse it for the backoff timers and later attempts.
472
    EventGroupScope eventGroupScope =
473
        EventGroupScope.current().withExplicitGroups(input.getOptions().getEventGroups());
1 ✔
474

475
    executeLocalActivityOverLocalRetryThreshold(
1 ✔
476
        input.getActivityName(),
1 ✔
477
        input.getActivityId(),
1 ✔
478
        input.getOptions(),
1 ✔
479
        input.getHeader(),
1 ✔
480
        payloads,
481
        arguments,
482
        originalScheduledTime,
483
        1,
484
        null,
485
        eventGroupScope,
486
        localActivityResult);
487

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

510
    return new LocalActivityOutput<>(result);
1 ✔
511
  }
512

513
  private void executeLocalActivityOverLocalRetryThreshold(
514
      String activityTypeName,
515
      @Nullable String activityId,
516
      LocalActivityOptions options,
517
      Header header,
518
      Optional<Payloads> input,
519
      @Nullable LocalActivityArguments arguments,
520
      long originalScheduledTime,
521
      int attempt,
522
      @Nullable Failure previousExecutionFailure,
523
      EventGroupScope eventGroupScope,
524
      CompletablePromise<LocalActivityCallback.Output> result) {
525
    CompletablePromise<LocalActivityCallback.Output> localExecutionResult =
1 ✔
526
        executeLocalActivityLocally(
1 ✔
527
            activityTypeName,
528
            activityId,
529
            options,
530
            header,
531
            input,
532
            arguments,
533
            originalScheduledTime,
534
            attempt,
535
            previousExecutionFailure,
536
            eventGroupScope);
537

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

585
  private CompletablePromise<LocalActivityCallback.Output> executeLocalActivityLocally(
586
      String activityTypeName,
587
      @Nullable String activityId,
588
      LocalActivityOptions options,
589
      Header header,
590
      Optional<Payloads> input,
591
      @Nullable LocalActivityArguments arguments,
592
      long originalScheduledTime,
593
      int attempt,
594
      @Nullable Failure previousExecutionFailure,
595
      EventGroupScope eventGroupScope) {
596

597
    LocalActivityCallbackImpl callback = new LocalActivityCallbackImpl();
1 ✔
598
    ExecuteLocalActivityParameters params =
1 ✔
599
        constructExecuteLocalActivityParameters(
1 ✔
600
            activityTypeName,
601
            activityId,
602
            options,
603
            header,
604
            input,
605
            arguments,
606
            attempt,
607
            originalScheduledTime,
608
            previousExecutionFailure,
609
            eventGroupScope);
610
    Functions.Proc cancellationCallback = replayContext.scheduleLocalActivityTask(params, callback);
1 ✔
611
    CancellationScope.current()
1 ✔
612
        .getCancellationRequest()
1 ✔
613
        .thenApply(
1 ✔
614
            (reason) -> {
UNCOV
615
              cancellationCallback.apply();
×
UNCOV
616
              return null;
×
617
            });
618
    return callback.result;
1 ✔
619
  }
620

621
  private ActivitySerializationContext activityContext(
622
      String name, String taskQueue, boolean local) {
623
    return new ActivitySerializationContext(
1 ✔
624
        replayContext.getNamespace(),
1 ✔
625
        replayContext.getWorkflowId(),
1 ✔
626
        replayContext.getWorkflowType().getName(),
1 ✔
627
        name,
628
        taskQueue,
629
        local);
630
  }
631

632
  @SuppressWarnings("deprecation")
633
  private ExecuteActivityParameters constructExecuteActivityParameters(
634
      String name,
635
      @Nullable String activityId,
636
      ActivityOptions options,
637
      Header header,
638
      Optional<Payloads> input) {
639
    String taskQueue = options.getTaskQueue();
1 ✔
640
    if (taskQueue == null) {
1 ✔
641
      taskQueue = replayContext.getTaskQueue();
1 ✔
642
    }
643
    ScheduleActivityTaskCommandAttributes.Builder attributes =
644
        ScheduleActivityTaskCommandAttributes.newBuilder()
1 ✔
645
            .setActivityType(ActivityType.newBuilder().setName(name))
1 ✔
646
            .setTaskQueue(TaskQueue.newBuilder().setName(taskQueue))
1 ✔
647
            .setScheduleToStartTimeout(
1 ✔
648
                ProtobufTimeUtils.toProtoDuration(options.getScheduleToStartTimeout()))
1 ✔
649
            .setStartToCloseTimeout(
1 ✔
650
                ProtobufTimeUtils.toProtoDuration(options.getStartToCloseTimeout()))
1 ✔
651
            .setScheduleToCloseTimeout(
1 ✔
652
                ProtobufTimeUtils.toProtoDuration(options.getScheduleToCloseTimeout()))
1 ✔
653
            .setHeartbeatTimeout(ProtobufTimeUtils.toProtoDuration(options.getHeartbeatTimeout()))
1 ✔
654
            .setRequestEagerExecution(
1 ✔
655
                !options.isEagerExecutionDisabled()
1 ✔
656
                    && Objects.equals(taskQueue, replayContext.getTaskQueue()));
1 ✔
657

658
    if (activityId != null) {
1 ✔
659
      attributes.setActivityId(activityId);
1 ✔
660
    }
661

662
    input.ifPresent(attributes::setInput);
1 ✔
663
    RetryOptions retryOptions = options.getRetryOptions();
1 ✔
664
    if (retryOptions != null) {
1 ✔
665
      attributes.setRetryPolicy(toRetryPolicy(retryOptions));
1 ✔
666
    }
667

668
    // Set the context value.  Use the context propagators from the ActivityOptions
669
    // if present, otherwise use the ones configured on the WorkflowContext
670
    List<ContextPropagator> propagators = options.getContextPropagators();
1 ✔
671
    if (propagators == null) {
1 !
672
      propagators = this.contextPropagators;
1 ✔
673
    }
674
    io.temporal.api.common.v1.Header grpcHeader =
1 ✔
675
        toHeaderGrpc(
1 ✔
676
            header,
677
            HeaderUtils.fromContextPropagators(propagators),
1 ✔
678
            HeaderUtils.withContext(headerCodec, activityContext(name, taskQueue, false)));
1 ✔
679
    attributes.setHeader(grpcHeader);
1 ✔
680

681
    if (options.getVersioningIntent() != null) {
1 !
682
      attributes.setUseWorkflowBuildId(
1 ✔
683
          options
684
              .getVersioningIntent()
1 ✔
685
              .determineUseCompatibleFlag(
1 ✔
686
                  replayContext.getTaskQueue().equals(options.getTaskQueue())));
1 ✔
687
    }
688

689
    @Nullable
690
    UserMetadata userMetadata =
1 ✔
691
        makeUserMetaData(options.getSummary(), null, dataConverterWithCurrentWorkflowContext);
1 ✔
692

693
    if (options.getPriority() != null) {
1 ✔
694
      attributes.setPriority(ProtoConverters.toProto(options.getPriority()));
1 ✔
695
    }
696

697
    return new ExecuteActivityParameters(
1 ✔
698
        attributes,
699
        options.getCancellationType(),
1 ✔
700
        userMetadata,
701
        eventGroupMarkers(options.getEventGroups()));
1 ✔
702
  }
703

704
  private ExecuteLocalActivityParameters constructExecuteLocalActivityParameters(
705
      String name,
706
      @Nullable String activityId,
707
      LocalActivityOptions options,
708
      Header header,
709
      Optional<Payloads> input,
710
      @Nullable LocalActivityArguments arguments,
711
      int attempt,
712
      long originalScheduledTime,
713
      @Nullable Failure previousExecutionFailure,
714
      EventGroupScope eventGroupScope) {
715
    options = LocalActivityOptions.newBuilder(options).validateAndBuildWithDefaults();
1 ✔
716

717
    PollActivityTaskQueueResponse.Builder activityTask =
718
        PollActivityTaskQueueResponse.newBuilder()
1 ✔
719
            .setActivityId(
1 ✔
720
                activityId != null ? activityId : this.replayContext.randomUUID().toString())
1 ✔
721
            .setWorkflowNamespace(this.replayContext.getNamespace())
1 ✔
722
            .setWorkflowType(this.replayContext.getWorkflowType())
1 ✔
723
            .setWorkflowExecution(this.replayContext.getWorkflowExecution())
1 ✔
724
            // used to pass scheduled time to the local activity code inside
725
            // ActivityExecutionContext#getInfo
726
            // setCurrentAttemptScheduledTime is called inside LocalActivityWorker before submitting
727
            // into the LA queue
728
            .setScheduledTime(
1 ✔
729
                ProtobufTimeUtils.toProtoTimestamp(Instant.ofEpochMilli(originalScheduledTime)))
1 ✔
730
            .setActivityType(ActivityType.newBuilder().setName(name))
1 ✔
731
            .setAttempt(attempt);
1 ✔
732

733
    Duration scheduleToCloseTimeout = options.getScheduleToCloseTimeout();
1 ✔
734
    if (scheduleToCloseTimeout != null) {
1 ✔
735
      activityTask.setScheduleToCloseTimeout(
1 ✔
736
          ProtobufTimeUtils.toProtoDuration(scheduleToCloseTimeout));
1 ✔
737
    }
738

739
    Duration startToCloseTimeout = options.getStartToCloseTimeout();
1 ✔
740
    if (startToCloseTimeout != null) {
1 ✔
741
      activityTask.setStartToCloseTimeout(ProtobufTimeUtils.toProtoDuration(startToCloseTimeout));
1 ✔
742
    }
743

744
    io.temporal.api.common.v1.Header grpcHeader =
1 ✔
745
        toHeaderGrpc(
1 ✔
746
            header,
747
            HeaderUtils.fromContextPropagators(contextPropagators),
1 ✔
748
            HeaderUtils.withContext(
1 ✔
749
                headerCodec, activityContext(name, replayContext.getTaskQueue(), true)));
1 ✔
750
    activityTask.setHeader(grpcHeader);
1 ✔
751
    input.ifPresent(activityTask::setInput);
1 ✔
752
    RetryOptions retryOptions = options.getRetryOptions();
1 ✔
753
    activityTask.setRetryPolicy(
1 ✔
754
        toRetryPolicy(RetryOptions.newBuilder(retryOptions).validateBuildWithDefaults()));
1 ✔
755
    Duration localRetryThreshold = options.getLocalRetryThreshold();
1 ✔
756
    if (localRetryThreshold == null) {
1 ✔
757
      localRetryThreshold = replayContext.getWorkflowTaskTimeout().multipliedBy(3);
1 ✔
758
    }
759

760
    @Nullable
761
    UserMetadata userMetadata =
1 ✔
762
        makeUserMetaData(options.getSummary(), null, dataConverterWithCurrentWorkflowContext);
1 ✔
763

764
    return new ExecuteLocalActivityParameters(
1 ✔
765
        activityTask,
766
        options.getScheduleToStartTimeout(),
1 ✔
767
        originalScheduledTime,
768
        previousExecutionFailure,
769
        options.isDoNotIncludeArgumentsIntoMarker(),
1 ✔
770
        localRetryThreshold,
771
        userMetadata,
772
        eventGroupScope.toMarkers(
1 ✔
773
            // Direct assignments have already been applied to the eventGroupScope, hence
774
            // emptyList() here
775
            Collections.emptyList(), dataConverterWithCurrentWorkflowContext),
1 ✔
776
        arguments);
777
  }
778

779
  @Override
780
  public <R> ChildWorkflowOutput<R> executeChildWorkflow(ChildWorkflowInput<R> input) {
781
    if (CancellationScope.current().isCancelRequested()) {
1 ✔
782
      CanceledFailure canceledFailure = new CanceledFailure("execute called from a canceled scope");
1 ✔
783
      return new ChildWorkflowOutput<>(
1 ✔
784
          Workflow.newFailedPromise(canceledFailure), Workflow.newFailedPromise(canceledFailure));
1 ✔
785
    }
786

787
    CompletablePromise<WorkflowExecution> executionPromise = Workflow.newPromise();
1 ✔
788
    CompletablePromise<Optional<Payloads>> resultPromise = Workflow.newPromise();
1 ✔
789

790
    DataConverter dataConverterWithChildWorkflowContext =
1 ✔
791
        dataConverter.withContext(
1 ✔
792
            new WorkflowSerializationContext(replayContext.getNamespace(), input.getWorkflowId()));
1 ✔
793
    Optional<Payloads> payloads = dataConverterWithChildWorkflowContext.toPayloads(input.getArgs());
1 ✔
794

795
    @Nullable
796
    Memo memo =
797
        (input.getOptions().getMemo() != null)
1 ✔
798
            ? Memo.newBuilder()
1 ✔
799
                .putAllFields(
1 ✔
800
                    intoPayloadMap(
1 ✔
801
                        dataConverterWithChildWorkflowContext, input.getOptions().getMemo()))
1 ✔
802
                .build()
1 ✔
803
            : null;
1 ✔
804

805
    @Nullable
806
    UserMetadata userMetadata =
1 ✔
807
        makeUserMetaData(
1 ✔
808
            input.getOptions().getStaticSummary(),
1 ✔
809
            input.getOptions().getStaticDetails(),
1 ✔
810
            dataConverterWithChildWorkflowContext);
811

812
    StartChildWorkflowExecutionParameters parameters =
1 ✔
813
        createChildWorkflowParameters(
1 ✔
814
            input.getWorkflowId(),
1 ✔
815
            input.getWorkflowType(),
1 ✔
816
            input.getOptions(),
1 ✔
817
            input.getHeader(),
1 ✔
818
            payloads,
819
            memo,
820
            userMetadata);
821

822
    Functions.Proc1<Exception> cancellationCallback =
1 ✔
823
        replayContext.startChildWorkflow(
1 ✔
824
            parameters,
825
            (execution, failure) -> {
826
              if (failure != null) {
1 ✔
827
                runner.executeInWorkflowThread(
1 ✔
828
                    "child workflow start failed callback",
829
                    () ->
830
                        executionPromise.completeExceptionally(
1 ✔
831
                            mapChildWorkflowException(
1 ✔
832
                                failure, dataConverterWithChildWorkflowContext)));
833
              } else {
834
                runner.executeInWorkflowThread(
1 ✔
835
                    "child workflow started callback", () -> executionPromise.complete(execution));
1 ✔
836
              }
837
            },
1 ✔
838
            (result, failure) -> {
839
              if (failure != null) {
1 ✔
840
                runner.executeInWorkflowThread(
1 ✔
841
                    "child workflow failure callback",
842
                    () ->
843
                        resultPromise.completeExceptionally(
1 ✔
844
                            mapChildWorkflowException(
1 ✔
845
                                failure, dataConverterWithChildWorkflowContext)));
846
              } else {
847
                runner.executeInWorkflowThread(
1 ✔
848
                    "child workflow completion callback", () -> resultPromise.complete(result));
1 ✔
849
              }
850
            });
1 ✔
851
    AtomicBoolean callbackCalled = new AtomicBoolean();
1 ✔
852
    CancellationScope.current()
1 ✔
853
        .getCancellationRequest()
1 ✔
854
        .thenApply(
1 ✔
855
            (reason) -> {
856
              if (!callbackCalled.getAndSet(true)) {
1 !
857
                cancellationCallback.apply(new CanceledFailure(reason));
1 ✔
858
              }
859
              return null;
1 ✔
860
            });
861

862
    // Avoid passing the input to the output handle as it causes the input to be retained for the
863
    // duration of the operation.
864
    Type resultType = input.getResultType();
1 ✔
865
    Class<R> resultClass = input.getResultClass();
1 ✔
866
    Promise<R> result =
1 ✔
867
        resultPromise.thenApply(
1 ✔
868
            (b) ->
869
                dataConverterWithChildWorkflowContext.fromPayloads(0, b, resultClass, resultType));
1 ✔
870
    return new ChildWorkflowOutput<>(result, executionPromise);
1 ✔
871
  }
872

873
  @Override
874
  public <R> ExecuteNexusOperationOutput<R> executeNexusOperation(
875
      ExecuteNexusOperationInput<R> input) {
876
    Preconditions.checkArgument(
1 ✔
877
        input.getEndpoint() != null && !input.getEndpoint().isEmpty(), "endpoint must be set");
1 !
878
    Preconditions.checkArgument(
1 ✔
879
        input.getService() != null && !input.getService().isEmpty(), "service must be set");
1 !
880

881
    if (CancellationScope.current().isCancelRequested()) {
1 !
UNCOV
882
      CanceledFailure canceledFailure =
×
883
          new CanceledFailure("execute nexus operation called from a canceled scope");
UNCOV
884
      return new ExecuteNexusOperationOutput<>(
×
UNCOV
885
          Workflow.newFailedPromise(canceledFailure), Workflow.newFailedPromise(canceledFailure));
×
886
    }
887

888
    CompletablePromise<NexusOperationExecution> operationPromise = Workflow.newPromise();
1 ✔
889
    CompletablePromise<Optional<Payload>> resultPromise = Workflow.newPromise();
1 ✔
890

891
    // The caller workflow is not available to the operation handler, so Nexus payloads are
892
    // contextualized by the endpoint, service and operation instead. The same converter decodes the
893
    // result and converts failures, so each operation keeps the converter selected for it even when
894
    // several operations are in flight at once.
895
    DataConverter nexusDataConverter =
1 ✔
896
        dataConverter.withContext(
1 ✔
897
            new NexusSerializationContext(
898
                input.getEndpoint(), input.getService(), input.getOperation()));
1 ✔
899

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

902
    ScheduleNexusOperationCommandAttributes.Builder attributes =
903
        ScheduleNexusOperationCommandAttributes.newBuilder();
1 ✔
904
    payload.ifPresent(attributes::setInput);
1 ✔
905
    attributes.setOperation(input.getOperation());
1 ✔
906
    attributes.setService(input.getService());
1 ✔
907
    attributes.setEndpoint(input.getEndpoint());
1 ✔
908
    // Ensure that the headers are lowercase
909
    input.getHeaders().forEach((k, v) -> attributes.putNexusHeader(k.toLowerCase(), v));
1 ✔
910
    attributes.setScheduleToCloseTimeout(
1 ✔
911
        ProtobufTimeUtils.toProtoDuration(input.getOptions().getScheduleToCloseTimeout()));
1 ✔
912
    attributes.setScheduleToStartTimeout(
1 ✔
913
        ProtobufTimeUtils.toProtoDuration(input.getOptions().getScheduleToStartTimeout()));
1 ✔
914
    attributes.setStartToCloseTimeout(
1 ✔
915
        ProtobufTimeUtils.toProtoDuration(input.getOptions().getStartToCloseTimeout()));
1 ✔
916

917
    @Nullable
918
    UserMetadata userMetadata =
1 ✔
919
        makeUserMetaData(input.getOptions().getSummary(), null, nexusDataConverter);
1 ✔
920

921
    StartNexusOperationParameters parameters =
1 ✔
922
        new StartNexusOperationParameters(
923
            attributes,
924
            input.getOptions().getCancellationType(),
1 ✔
925
            userMetadata,
926
            eventGroupMarkers(input.getOptions().getEventGroups()));
1 ✔
927

928
    Functions.Proc1<Exception> cancellationCallback =
1 ✔
929
        replayContext.startNexusOperation(
1 ✔
930
            parameters,
931
            (operationExec, failure) -> {
932
              if (failure != null) {
1 ✔
933
                runner.executeInWorkflowThread(
1 ✔
934
                    "nexus operation start failed callback",
935
                    () ->
936
                        operationPromise.completeExceptionally(
1 ✔
937
                            nexusDataConverter.failureToException(failure)));
1 ✔
938
              } else {
939
                runner.executeInWorkflowThread(
1 ✔
940
                    "nexus operation started callback",
941
                    () ->
942
                        operationPromise.complete(new NexusOperationExecutionImpl(operationExec)));
1 ✔
943
              }
944
            },
1 ✔
945
            (Optional<Payload> result, Failure failure) -> {
946
              if (failure != null) {
1 ✔
947
                runner.executeInWorkflowThread(
1 ✔
948
                    "nexus operation failure callback",
949
                    () ->
950
                        resultPromise.completeExceptionally(
1 ✔
951
                            nexusDataConverter.failureToException(failure)));
1 ✔
952
              } else {
953
                runner.executeInWorkflowThread(
1 ✔
954
                    "nexus operation completion callback", () -> resultPromise.complete(result));
1 ✔
955
              }
956
            });
1 ✔
957
    AtomicBoolean callbackCalled = new AtomicBoolean();
1 ✔
958
    CancellationScope.current()
1 ✔
959
        .getCancellationRequest()
1 ✔
960
        .thenApply(
1 ✔
961
            (reason) -> {
962
              if (!callbackCalled.getAndSet(true)) {
1 !
963
                cancellationCallback.apply(new CanceledFailure(reason));
1 ✔
964
              }
965
              return null;
1 ✔
966
            });
967
    Promise<R> result =
1 ✔
968
        resultPromise.thenApply(
1 ✔
969
            (b) ->
970
                input.getResultClass() != Void.class
1 ✔
971
                    ? nexusDataConverter.fromPayload(
1 ✔
972
                        b.get(), input.getResultClass(), input.getResultType())
1 ✔
973
                    : null);
1 ✔
974
    // We register an empty handler to make sure that this promise is always "accessed" and never
975
    // leads to a log about it being completed exceptionally and non-accessed.
976
    // The "main" operation promise is the one returned from the execute method and that
977
    // promise will always be logged if not accessed.
978
    operationPromise.handle((ex, failure) -> null);
1 ✔
979
    return new ExecuteNexusOperationOutput<>(result, operationPromise);
1 ✔
980
  }
981

982
  @SuppressWarnings("deprecation")
983
  private StartChildWorkflowExecutionParameters createChildWorkflowParameters(
984
      String workflowId,
985
      String name,
986
      ChildWorkflowOptions options,
987
      Header header,
988
      Optional<Payloads> input,
989
      @Nullable Memo memo,
990
      @Nullable UserMetadata metadata) {
991
    final StartChildWorkflowExecutionCommandAttributes.Builder attributes =
992
        StartChildWorkflowExecutionCommandAttributes.newBuilder()
1 ✔
993
            .setWorkflowType(WorkflowType.newBuilder().setName(name).build());
1 ✔
994
    attributes.setWorkflowId(workflowId);
1 ✔
995
    attributes.setNamespace(OptionsUtils.safeGet(options.getNamespace()));
1 ✔
996
    input.ifPresent(attributes::setInput);
1 ✔
997
    attributes.setWorkflowRunTimeout(
1 ✔
998
        ProtobufTimeUtils.toProtoDuration(options.getWorkflowRunTimeout()));
1 ✔
999
    attributes.setWorkflowExecutionTimeout(
1 ✔
1000
        ProtobufTimeUtils.toProtoDuration(options.getWorkflowExecutionTimeout()));
1 ✔
1001
    attributes.setWorkflowTaskTimeout(
1 ✔
1002
        ProtobufTimeUtils.toProtoDuration(options.getWorkflowTaskTimeout()));
1 ✔
1003
    String taskQueue = options.getTaskQueue();
1 ✔
1004
    if (taskQueue != null) {
1 ✔
1005
      attributes.setTaskQueue(TaskQueue.newBuilder().setName(taskQueue));
1 ✔
1006
    }
1007
    if (options.getWorkflowIdReusePolicy() != null) {
1 ✔
1008
      attributes.setWorkflowIdReusePolicy(options.getWorkflowIdReusePolicy());
1 ✔
1009
    }
1010
    RetryOptions retryOptions = options.getRetryOptions();
1 ✔
1011
    if (retryOptions != null) {
1 ✔
1012
      attributes.setRetryPolicy(toRetryPolicy(retryOptions));
1 ✔
1013
    }
1014
    attributes.setCronSchedule(OptionsUtils.safeGet(options.getCronSchedule()));
1 ✔
1015

1016
    if (memo != null) {
1 ✔
1017
      attributes.setMemo(memo);
1 ✔
1018
    }
1019

1020
    Map<String, Object> searchAttributes = options.getSearchAttributes();
1 ✔
1021
    if (searchAttributes != null && !searchAttributes.isEmpty()) {
1 !
1022
      if (options.getTypedSearchAttributes() != null) {
1 !
UNCOV
1023
        throw new IllegalArgumentException(
×
1024
            "Cannot have both typed search attributes and search attributes");
1025
      }
1026
      attributes.setSearchAttributes(SearchAttributesUtil.encode(searchAttributes));
1 ✔
1027
    } else if (options.getTypedSearchAttributes() != null
1 ✔
1028
        && options.getTypedSearchAttributes().size() > 0) {
1 !
1029
      attributes.setSearchAttributes(
1 ✔
1030
          SearchAttributesUtil.encodeTyped(options.getTypedSearchAttributes()));
1 ✔
1031
    }
1032

1033
    List<ContextPropagator> propagators = options.getContextPropagators();
1 ✔
1034
    if (propagators == null) {
1 !
1035
      propagators = this.contextPropagators;
1 ✔
1036
    }
1037
    io.temporal.api.common.v1.Header grpcHeader =
1 ✔
1038
        toHeaderGrpc(
1 ✔
1039
            header,
1040
            HeaderUtils.fromContextPropagators(propagators),
1 ✔
1041
            HeaderUtils.withContext(
1 ✔
1042
                headerCodec,
1043
                new WorkflowSerializationContext(
1044
                    Strings.isNullOrEmpty(options.getNamespace())
1 ✔
1045
                        ? replayContext.getNamespace()
1 ✔
1046
                        : options.getNamespace(),
1 ✔
1047
                    workflowId)));
1048
    attributes.setHeader(grpcHeader);
1 ✔
1049

1050
    ParentClosePolicy parentClosePolicy = options.getParentClosePolicy();
1 ✔
1051
    if (parentClosePolicy != null) {
1 ✔
1052
      attributes.setParentClosePolicy(parentClosePolicy);
1 ✔
1053
    }
1054

1055
    if (options.getVersioningIntent() != null) {
1 ✔
1056
      attributes.setInheritBuildId(
1 ✔
1057
          options
1058
              .getVersioningIntent()
1 ✔
1059
              .determineUseCompatibleFlag(
1 ✔
1060
                  replayContext.getTaskQueue().equals(options.getTaskQueue())));
1 ✔
1061
    }
1062
    if (options.getPriority() != null) {
1 ✔
1063
      attributes.setPriority(ProtoConverters.toProto(options.getPriority()));
1 ✔
1064
    }
1065
    if (options.getVersioningOverride() != null) {
1 !
UNCOV
1066
      attributes.setVersioningOverride(ProtoConverters.toProto(options.getVersioningOverride()));
×
1067
    }
1068
    return new StartChildWorkflowExecutionParameters(
1 ✔
1069
        attributes,
1070
        options.getCancellationType(),
1 ✔
1071
        metadata,
1072
        eventGroupMarkers(options.getEventGroups()));
1 ✔
1073
  }
1074

1075
  private static RuntimeException mapChildWorkflowException(
1076
      Exception failure, DataConverter dataConverterWithChildWorkflowContext) {
1077
    if (failure == null) {
1 !
UNCOV
1078
      return null;
×
1079
    }
1080
    if (failure instanceof TemporalFailure) {
1 ✔
1081
      ((TemporalFailure) failure).setDataConverter(dataConverterWithChildWorkflowContext);
1 ✔
1082
    }
1083
    if (failure instanceof CanceledFailure) {
1 ✔
1084
      return (CanceledFailure) failure;
1 ✔
1085
    }
1086
    if (failure instanceof WorkflowException) {
1 !
UNCOV
1087
      return (RuntimeException) failure;
×
1088
    }
1089
    if (failure instanceof ChildWorkflowFailure) {
1 ✔
1090
      return (ChildWorkflowFailure) failure;
1 ✔
1091
    }
1092
    if (!(failure instanceof ChildWorkflowTaskFailedException)) {
1 !
UNCOV
1093
      return new IllegalArgumentException("Unexpected exception type: ", failure);
×
1094
    }
1095
    ChildWorkflowTaskFailedException taskFailed = (ChildWorkflowTaskFailedException) failure;
1 ✔
1096
    Throwable cause =
1 ✔
1097
        dataConverterWithChildWorkflowContext.failureToException(
1 ✔
1098
            taskFailed.getOriginalCauseFailure());
1 ✔
1099
    ChildWorkflowFailure exception = taskFailed.getException();
1 ✔
1100
    return new ChildWorkflowFailure(
1 ✔
1101
        exception.getInitiatedEventId(),
1 ✔
1102
        exception.getStartedEventId(),
1 ✔
1103
        exception.getWorkflowType(),
1 ✔
1104
        exception.getExecution(),
1 ✔
1105
        exception.getNamespace(),
1 ✔
1106
        exception.getRetryState(),
1 ✔
1107
        cause);
1108
  }
1109

1110
  @Override
1111
  public Promise<Void> newTimer(Duration delay) {
1112
    return newTimer(delay, TimerOptions.newBuilder().build());
1 ✔
1113
  }
1114

1115
  @Override
1116
  public Promise<Void> newTimer(Duration delay, TimerOptions options) {
1117
    CompletablePromise<Void> p = Workflow.newPromise();
1 ✔
1118

1119
    @Nullable
1120
    UserMetadata userMetadata =
1 ✔
1121
        makeUserMetaData(options.getSummary(), null, dataConverterWithCurrentWorkflowContext);
1 ✔
1122

1123
    Functions.Proc1<RuntimeException> cancellationHandler =
1 ✔
1124
        replayContext.newTimer(
1 ✔
1125
            delay,
1126
            userMetadata,
1127
            eventGroupMarkers(options.getEventGroups()),
1 ✔
1128
            (e) ->
1129
                runner.executeInWorkflowThread(
1 ✔
1130
                    "timer-callback",
1131
                    () -> {
1132
                      if (e == null) {
1 ✔
1133
                        p.complete(null);
1 ✔
1134
                      } else {
1135
                        p.completeExceptionally(e);
1 ✔
1136
                      }
1137
                    }));
1 ✔
1138
    CancellationScope.current()
1 ✔
1139
        .getCancellationRequest()
1 ✔
1140
        .thenApply(
1 ✔
1141
            (r) -> {
1142
              cancellationHandler.apply(new CanceledFailure(r));
1 ✔
1143
              return r;
1 ✔
1144
            });
1145
    return p;
1 ✔
1146
  }
1147

1148
  @Override
1149
  public <R> R sideEffect(Class<R> resultClass, Type resultType, Func<R> func) {
1150
    return sideEffect(resultClass, resultType, func, SideEffectOptions.newBuilder().build());
1 ✔
1151
  }
1152

1153
  @Override
1154
  public <R> R sideEffect(
1155
      Class<R> resultClass, Type resultType, Func<R> func, SideEffectOptions options) {
1156
    @Nullable
1157
    UserMetadata userMetadata =
1 ✔
1158
        makeUserMetaData(options.getSummary(), null, dataConverterWithCurrentWorkflowContext);
1 ✔
1159
    List<EventGroupMarker> eventGroupMarkers = eventGroupMarkers(options.getEventGroups());
1 ✔
1160
    try {
1161
      CompletablePromise<Optional<Payloads>> result = Workflow.newPromise();
1 ✔
1162
      replayContext.sideEffect(
1 ✔
1163
          () -> {
1164
            try {
1165
              readOnly = true;
1 ✔
1166
              R r = func.apply();
1 ✔
1167
              return dataConverterWithCurrentWorkflowContext.toPayloads(r);
1 ✔
1168
            } finally {
1169
              readOnly = false;
1 ✔
1170
            }
1171
          },
1172
          userMetadata,
1173
          eventGroupMarkers,
1174
          (p) ->
1175
              runner.executeInWorkflowThread(
1 ✔
1176
                  "side-effect-callback", () -> result.complete(Objects.requireNonNull(p))));
1 ✔
1177
      return dataConverterWithCurrentWorkflowContext.fromPayloads(
1 ✔
1178
          0, result.get(), resultClass, resultType);
1 ✔
1179
    } catch (Exception e) {
1 ✔
1180
      // SideEffect cannot throw normal exception as it can lead to non-deterministic behavior. So
1181
      // fail the workflow task by throwing an Error.
1182
      throw new Error(e);
1 ✔
1183
    }
1184
  }
1185

1186
  @Override
1187
  public <R> R mutableSideEffect(
1188
      String id, Class<R> resultClass, Type resultType, BiPredicate<R, R> updated, Func<R> func) {
1189
    return mutableSideEffect(
1 ✔
1190
        id, resultClass, resultType, updated, func, MutableSideEffectOptions.newBuilder().build());
1 ✔
1191
  }
1192

1193
  @Override
1194
  public <R> R mutableSideEffect(
1195
      String id,
1196
      Class<R> resultClass,
1197
      Type resultType,
1198
      BiPredicate<R, R> updated,
1199
      Func<R> func,
1200
      MutableSideEffectOptions options) {
1201
    @Nullable
1202
    UserMetadata userMetadata =
1 ✔
1203
        makeUserMetaData(options.getSummary(), null, dataConverterWithCurrentWorkflowContext);
1 ✔
1204
    List<EventGroupMarker> eventGroupMarkers = eventGroupMarkers(options.getEventGroups());
1 ✔
1205
    try {
1206
      return mutableSideEffectImpl(
1 ✔
1207
          id, userMetadata, eventGroupMarkers, resultClass, resultType, updated, func);
1208
    } catch (Exception e) {
1 ✔
1209
      // MutableSideEffect cannot throw normal exception as it can lead to non-deterministic
1210
      // behavior. So fail the workflow task by throwing an Error.
1211
      throw new Error(e);
1 ✔
1212
    }
1213
  }
1214

1215
  private <R> R mutableSideEffectImpl(
1216
      String id,
1217
      UserMetadata metadata,
1218
      List<EventGroupMarker> eventGroupMarkers,
1219
      Class<R> resultClass,
1220
      Type resultType,
1221
      BiPredicate<R, R> updated,
1222
      Func<R> func) {
1223
    CompletablePromise<Optional<Payloads>> result = Workflow.newPromise();
1 ✔
1224
    AtomicReference<R> unserializedResult = new AtomicReference<>();
1 ✔
1225
    replayContext.mutableSideEffect(
1 ✔
1226
        id,
1227
        metadata,
1228
        eventGroupMarkers,
1229
        (storedBinary) -> {
1230
          Optional<R> stored =
1 ✔
1231
              storedBinary.map(
1 ✔
1232
                  (b) ->
1233
                      dataConverterWithCurrentWorkflowContext.fromPayloads(
1 ✔
1234
                          0, Optional.of(b), resultClass, resultType));
1 ✔
1235
          try {
1236
            readOnly = true;
1 ✔
1237
            R funcResult =
1 ✔
1238
                Objects.requireNonNull(
1 ✔
1239
                    func.apply(), "mutableSideEffect function " + "returned null");
1 ✔
1240
            if (!stored.isPresent() || updated.test(stored.get(), funcResult)) {
1 ✔
1241
              unserializedResult.set(funcResult);
1 ✔
1242
              return dataConverterWithCurrentWorkflowContext.toPayloads(funcResult);
1 ✔
1243
            }
1244
            return Optional.empty(); // returned only when value doesn't need to be updated
1 ✔
1245
          } finally {
1246
            readOnly = false;
1 ✔
1247
          }
1248
        },
1249
        (p) ->
1250
            runner.executeInWorkflowThread(
1 ✔
1251
                "mutable-side-effect-callback", () -> result.complete(Objects.requireNonNull(p))));
1 ✔
1252

1253
    if (!result.get().isPresent()) {
1 !
UNCOV
1254
      throw new IllegalArgumentException("No value found for mutableSideEffectId=" + id);
×
1255
    }
1256
    // An optimization that avoids unnecessary deserialization of the result.
1257
    R unserialized = unserializedResult.get();
1 ✔
1258
    if (unserialized != null) {
1 ✔
1259
      return unserialized;
1 ✔
1260
    }
1261
    return dataConverterWithCurrentWorkflowContext.fromPayloads(
1 ✔
1262
        0, result.get(), resultClass, resultType);
1 ✔
1263
  }
1264

1265
  @Override
1266
  public int getVersion(String changeId, int minSupported, int maxSupported) {
1267
    return getVersion(changeId, minSupported, maxSupported, GetVersionOptions.getDefaultInstance());
1 ✔
1268
  }
1269

1270
  @Override
1271
  public int getVersion(
1272
      String changeId, int minSupported, int maxSupported, GetVersionOptions options) {
1273
    CompletablePromise<Integer> result = Workflow.newPromise();
1 ✔
1274
    Integer versionToUse;
1275
    try {
1276
      versionToUse =
1 ✔
1277
          replayContext.getVersion(
1 ✔
1278
              changeId,
1279
              minSupported,
1280
              maxSupported,
1281
              eventGroupMarkers(options.getEventGroups()),
1 ✔
1282
              (v, e) ->
1283
                  runner.executeInWorkflowThread(
1 ✔
1284
                      "version-callback",
1285
                      () -> {
1286
                        if (v != null) {
1 !
1287
                          result.complete(v);
1 ✔
1288
                        } else {
UNCOV
1289
                          result.completeExceptionally(e);
×
1290
                        }
1291
                      }));
1 ✔
UNCOV
1292
    } catch (UnsupportedVersion.UnsupportedVersionException ex) {
×
UNCOV
1293
      throw new UnsupportedVersion(ex);
×
1294
    }
1 ✔
1295
    /*
1296
     * If we are replaying a workflow and encounter a getVersion call it is possible that this call did not exist
1297
     * on the original execution. If the call did not exist on the original execution then we cannot block on results
1298
     * because it can lead to non-deterministic scheduling.
1299
     * */
1300
    if (replayContext.isReplaying()
1 ✔
1301
        && versionToUse == null
1302
        && replayContext.tryUseSdkFlag(SdkFlag.SKIP_YIELD_ON_DEFAULT_VERSION)
1 ✔
1303
        && minSupported == DEFAULT_VERSION) {
1304
      return DEFAULT_VERSION;
1 ✔
1305
    }
1306

1307
    /*
1308
     * Previously the SDK would yield on the getVersion call to the scheduler. This is not ideal because it can lead to non-deterministic
1309
     * scheduling if the getVersion call was removed.
1310
     * */
1311
    if (replayContext.tryUseSdkFlag(SdkFlag.SKIP_YIELD_ON_VERSION)) {
1 ✔
1312
      // This can happen if we are replaying a workflow and encounter a getVersion call that did not
1313
      // exist on the original execution and the range does not include the default version.
1314
      if (versionToUse == null) {
1 ✔
1315
        versionToUse = DEFAULT_VERSION;
1 ✔
1316
      }
1317
      if (versionToUse < minSupported || versionToUse > maxSupported) {
1 !
1318
        throw new UnsupportedVersion(
1 ✔
1319
            new UnsupportedVersion.UnsupportedVersionException(
1320
                String.format(
1 ✔
1321
                    "Version %d of changeId %s is not supported. Supported v is between %d and %d.",
1322
                    versionToUse, changeId, minSupported, maxSupported)));
1 ✔
1323
      }
1324
      return versionToUse;
1 ✔
1325
    }
1326
    // Legacy behavior if SKIP_YIELD_ON_VERSION is not set. This means this thread will yield on the
1327
    // getVersion call.
1328
    // while it waits for the result.
1329
    try {
1330
      return result.get();
1 ✔
UNCOV
1331
    } catch (UnsupportedVersion.UnsupportedVersionException ex) {
×
UNCOV
1332
      throw new UnsupportedVersion(ex);
×
1333
    }
1334
  }
1335

1336
  @Override
1337
  public void registerQuery(RegisterQueryInput request) {
1338
    queryDispatcher.registerQueryHandlers(request);
1 ✔
1339
  }
1 ✔
1340

1341
  @Override
1342
  public void registerSignalHandlers(RegisterSignalHandlersInput input) {
1343
    signalDispatcher.registerSignalHandlers(input);
1 ✔
1344
  }
1 ✔
1345

1346
  @Override
1347
  public void registerUpdateHandlers(RegisterUpdateHandlersInput input) {
1348
    updateDispatcher.registerUpdateHandlers(input);
1 ✔
1349
  }
1 ✔
1350

1351
  @Override
1352
  public void registerDynamicSignalHandler(RegisterDynamicSignalHandlerInput input) {
1353
    signalDispatcher.registerDynamicSignalHandler(input);
1 ✔
1354
  }
1 ✔
1355

1356
  @Override
1357
  public void registerDynamicQueryHandler(RegisterDynamicQueryHandlerInput input) {
1358
    queryDispatcher.registerDynamicQueryHandler(input);
1 ✔
1359
  }
1 ✔
1360

1361
  @Override
1362
  public void registerDynamicUpdateHandler(RegisterDynamicUpdateHandlerInput input) {
1363
    updateDispatcher.registerDynamicUpdateHandler(input);
1 ✔
1364
  }
1 ✔
1365

1366
  @Override
1367
  public UUID randomUUID() {
1368
    return replayContext.randomUUID();
1 ✔
1369
  }
1370

1371
  @Override
1372
  public Random newRandom() {
1373
    return replayContext.newRandom();
1 ✔
1374
  }
1375

1376
  public DataConverter getDataConverter() {
UNCOV
1377
    return dataConverter;
×
1378
  }
1379

1380
  public DataConverter getDataConverterWithCurrentWorkflowContext() {
1381
    return dataConverterWithCurrentWorkflowContext;
1 ✔
1382
  }
1383

1384
  /**
1385
   * Records the serialization context of the Nexus operation handler that started this workflow, as
1386
   * propagated by the server in the WorkflowExecutionStarted event.
1387
   */
1388
  void setPropagatedNexusSerializationContext(
1389
      @Nullable NexusSerializationContext propagatedNexusSerializationContext) {
1390
    this.dataConverterWithPropagatedNexusContext =
1 ✔
1391
        propagatedNexusSerializationContext == null
1 ✔
1392
            ? null
1 ✔
1393
            : dataConverter.withContext(propagatedNexusSerializationContext);
1 ✔
1394
  }
1 ✔
1395

1396
  /**
1397
   * The data converter for the workflow result and the failure that closes the workflow, which are
1398
   * returned to the Nexus caller: the propagated Nexus context if the workflow was started by a
1399
   * Nexus operation handler, otherwise the workflow context. Input, memo, signals and queries
1400
   * always use the workflow context. Updates use {@link #getDataConverterForUpdateOutcome}.
1401
   */
1402
  DataConverter getDataConverterForResult() {
1403
    return dataConverterWithPropagatedNexusContext != null
1 ✔
1404
        ? dataConverterWithPropagatedNexusContext
1 ✔
1405
        : dataConverterWithCurrentWorkflowContext;
1 ✔
1406
  }
1407

1408
  boolean isReplaying() {
1409
    return replayContext.isReplaying();
1 ✔
1410
  }
1411

1412
  boolean isReadOnly() {
1413
    return readOnly;
1 ✔
1414
  }
1415

1416
  void setReadOnly(boolean readOnly) {
1417
    this.readOnly = readOnly;
1 ✔
1418
  }
1 ✔
1419

1420
  @Override
1421
  public Map<Long, SignalHandlerInfo> getRunningSignalHandlers() {
1422
    return signalDispatcher.getRunningSignalHandlers();
1 ✔
1423
  }
1424

1425
  @Override
1426
  public Map<String, UpdateHandlerInfo> getRunningUpdateHandlers() {
1427
    return updateDispatcher.getRunningUpdateHandlers();
1 ✔
1428
  }
1429

1430
  @Override
1431
  public ReplayWorkflowContext getReplayContext() {
1432
    return replayContext;
1 ✔
1433
  }
1434

1435
  @Override
1436
  public SignalExternalOutput signalExternalWorkflow(SignalExternalInput input) {
1437
    WorkflowExecution childExecution = input.getExecution();
1 ✔
1438
    DataConverter dataConverterWithChildWorkflowContext =
1 ✔
1439
        dataConverter.withContext(
1 ✔
1440
            new WorkflowSerializationContext(
1441
                replayContext.getNamespace(), childExecution.getWorkflowId()));
1 ✔
1442
    SignalExternalWorkflowExecutionCommandAttributes.Builder attributes =
1443
        SignalExternalWorkflowExecutionCommandAttributes.newBuilder();
1 ✔
1444
    attributes.setSignalName(input.getSignalName());
1 ✔
1445
    attributes.setExecution(childExecution);
1 ✔
1446
    attributes.setHeader(
1 ✔
1447
        HeaderUtils.toHeaderGrpc(
1 ✔
1448
            input.getHeader(),
1 ✔
1449
            null,
1450
            HeaderUtils.withContext(
1 ✔
1451
                headerCodec,
1452
                new WorkflowSerializationContext(
1453
                    replayContext.getNamespace(), childExecution.getWorkflowId()))));
1 ✔
1454
    Optional<Payloads> payloads = dataConverterWithChildWorkflowContext.toPayloads(input.getArgs());
1 ✔
1455
    payloads.ifPresent(attributes::setInput);
1 ✔
1456
    CompletablePromise<Void> result = Workflow.newPromise();
1 ✔
1457
    Functions.Proc1<Exception> cancellationCallback =
1 ✔
1458
        replayContext.signalExternalWorkflowExecution(
1 ✔
1459
            attributes,
1460
            eventGroupMarkers(input.getOptions().getEventGroups()),
1 ✔
1461
            (output, failure) -> {
1462
              if (failure != null) {
1 ✔
1463
                runner.executeInWorkflowThread(
1 ✔
1464
                    "child workflow failure callback",
1465
                    () ->
1466
                        result.completeExceptionally(
1 ✔
1467
                            dataConverterWithChildWorkflowContext.failureToException(failure)));
1 ✔
1468
              } else {
1469
                runner.executeInWorkflowThread(
1 ✔
1470
                    "child workflow completion callback", () -> result.complete(output));
1 ✔
1471
              }
1472
            });
1 ✔
1473
    CancellationScope.current()
1 ✔
1474
        .getCancellationRequest()
1 ✔
1475
        .thenApply(
1 ✔
1476
            (reason) -> {
1477
              cancellationCallback.apply(new CanceledFailure(reason));
1 ✔
1478
              return null;
1 ✔
1479
            });
1480
    return new SignalExternalOutput(result);
1 ✔
1481
  }
1482

1483
  @Override
1484
  public void sleep(Duration duration) {
1485
    sleep(duration, TimerOptions.newBuilder().build());
1 ✔
1486
  }
1 ✔
1487

1488
  @Override
1489
  public void sleep(Duration duration, TimerOptions options) {
1490
    newTimer(duration, options).get();
1 ✔
1491
  }
1 ✔
1492

1493
  @Override
1494
  public boolean await(Duration timeout, String reason, Supplier<Boolean> unblockCondition) {
1495
    return await(timeout, TimerOptions.newBuilder().build(), reason, unblockCondition);
1 ✔
1496
  }
1497

1498
  @Override
1499
  public boolean await(
1500
      Duration timeout, TimerOptions options, String reason, Supplier<Boolean> unblockCondition) {
1501
    boolean cancelTimerOnCondition =
1 ✔
1502
        replayContext.tryUseSdkFlag(SdkFlag.CANCEL_AWAIT_TIMER_ON_CONDITION);
1 ✔
1503

1504
    if (cancelTimerOnCondition) {
1 ✔
1505
      // If condition is already satisfied, skip creating timer
1506
      if (unblockCondition.get()) {
1 ✔
1507
        return true;
1 ✔
1508
      }
1509
      // Create timer in a cancellation scope so we can cancel it when condition is satisfied
1510
      CompletablePromise<Void> timer = Workflow.newPromise();
1 ✔
1511
      CancellationScope timerScope =
1 ✔
1512
          Workflow.newCancellationScope(() -> timer.completeFrom(newTimer(timeout, options)));
1 ✔
1513
      timerScope.run();
1 ✔
1514

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

1517
      boolean conditionSatisfied = !timer.isCompleted();
1 ✔
1518
      if (conditionSatisfied) {
1 ✔
1519
        timerScope.cancel("await condition resolved");
1 ✔
1520
      }
1521
      return conditionSatisfied;
1 ✔
1522
    } else {
1523
      // Old behavior: timer is not cancelled when condition is satisfied
1524
      Promise<Void> timer = newTimer(timeout, options);
1 ✔
1525
      WorkflowThread.await(reason, () -> (timer.isCompleted() || unblockCondition.get()));
1 !
1526
      return !timer.isCompleted();
1 !
1527
    }
1528
  }
1529

1530
  @Override
1531
  public void await(String reason, Supplier<Boolean> unblockCondition) {
1532
    WorkflowThread.await(reason, unblockCondition);
1 ✔
1533
  }
1 ✔
1534

1535
  @SuppressWarnings("deprecation")
1536
  @Override
1537
  public void continueAsNew(ContinueAsNewInput input) {
1538
    ContinueAsNewWorkflowExecutionCommandAttributes.Builder attributes =
1539
        ContinueAsNewWorkflowExecutionCommandAttributes.newBuilder();
1 ✔
1540
    String workflowType = input.getWorkflowType();
1 ✔
1541
    if (workflowType != null) {
1 ✔
1542
      attributes.setWorkflowType(WorkflowType.newBuilder().setName(workflowType));
1 ✔
1543
    }
1544
    @Nullable ContinueAsNewOptions options = input.getOptions();
1 ✔
1545
    if (options != null) {
1 ✔
1546
      if (options.getWorkflowRunTimeout() != null) {
1 !
UNCOV
1547
        attributes.setWorkflowRunTimeout(
×
UNCOV
1548
            ProtobufTimeUtils.toProtoDuration(options.getWorkflowRunTimeout()));
×
1549
      }
1550
      if (options.getWorkflowTaskTimeout() != null) {
1 !
UNCOV
1551
        attributes.setWorkflowTaskTimeout(
×
UNCOV
1552
            ProtobufTimeUtils.toProtoDuration(options.getWorkflowTaskTimeout()));
×
1553
      }
1554
      if (options.getBackoffStartInterval() != null) {
1 ✔
1555
        attributes.setBackoffStartInterval(
1 ✔
1556
            ProtobufTimeUtils.toProtoDuration(options.getBackoffStartInterval()));
1 ✔
1557
      }
1558
      if (options.getTaskQueue() != null && !options.getTaskQueue().isEmpty()) {
1 ✔
1559
        attributes.setTaskQueue(TaskQueue.newBuilder().setName(options.getTaskQueue()));
1 ✔
1560
      }
1561
      if (options.getRetryOptions() != null) {
1 ✔
1562
        attributes.setRetryPolicy(toRetryPolicy(options.getRetryOptions()));
1 ✔
1563
      } else if (replayContext.getRetryOptions() != null) {
1 ✔
1564
        attributes.setRetryPolicy(toRetryPolicy(replayContext.getRetryOptions()));
1 ✔
1565
      }
1566
      Map<String, Object> searchAttributes = options.getSearchAttributes();
1 ✔
1567
      if (searchAttributes != null && !searchAttributes.isEmpty()) {
1 !
UNCOV
1568
        if (options.getTypedSearchAttributes() != null) {
×
UNCOV
1569
          throw new IllegalArgumentException(
×
1570
              "Cannot have typed search attributes and search attributes");
1571
        }
UNCOV
1572
        attributes.setSearchAttributes(SearchAttributesUtil.encode(searchAttributes));
×
1573
      } else if (options.getTypedSearchAttributes() != null
1 ✔
1574
          && options.getTypedSearchAttributes().size() > 0) {
1 !
1575
        attributes.setSearchAttributes(
1 ✔
1576
            SearchAttributesUtil.encodeTyped(options.getTypedSearchAttributes()));
1 ✔
1577
      } else if (options.getTypedSearchAttributes() == null && searchAttributes == null) {
1 !
1578
        // Carry over existing search attributes if none are specified.
1579
        SearchAttributes existing = replayContext.getSearchAttributes();
1 ✔
1580
        if (existing != null && !existing.getIndexedFieldsMap().isEmpty()) {
1 !
1581
          attributes.setSearchAttributes(existing);
1 ✔
1582
        }
1583
      }
1584
      Map<String, Object> memo = options.getMemo();
1 ✔
1585
      if (memo != null) {
1 ✔
1586
        attributes.setMemo(
1 ✔
1587
            Memo.newBuilder()
1 ✔
1588
                .putAllFields(intoPayloadMap(dataConverterWithCurrentWorkflowContext, memo)));
1 ✔
1589
      }
1590
      if (options.getVersioningIntent() != null) {
1 !
1591
        attributes.setInheritBuildId(
×
1592
            options
UNCOV
1593
                .getVersioningIntent()
×
UNCOV
1594
                .determineUseCompatibleFlag(
×
UNCOV
1595
                    replayContext.getTaskQueue().equals(options.getTaskQueue())));
×
1596
      }
1597
      if (options.getInitialVersioningBehavior() != null) {
1 !
UNCOV
1598
        switch (options.getInitialVersioningBehavior()) {
×
1599
          case AUTO_UPGRADE:
UNCOV
1600
            attributes.setInitialVersioningBehavior(
×
1601
                io.temporal.api.enums.v1.ContinueAsNewVersioningBehavior
1602
                    .CONTINUE_AS_NEW_VERSIONING_BEHAVIOR_AUTO_UPGRADE);
UNCOV
1603
            break;
×
1604
          case USE_RAMPING_VERSION:
UNCOV
1605
            attributes.setInitialVersioningBehavior(
×
1606
                io.temporal.api.enums.v1.ContinueAsNewVersioningBehavior
1607
                    .CONTINUE_AS_NEW_VERSIONING_BEHAVIOR_USE_RAMPING_VERSION);
1608
            break;
1609
        }
1610
      }
1611
    }
1612

1613
    if (options == null && replayContext.getRetryOptions() != null) {
1 ✔
1614
      // Have to copy certain options as server doesn't copy them.
1615
      attributes.setRetryPolicy(toRetryPolicy(replayContext.getRetryOptions()));
1 ✔
1616
    }
1617

1618
    if (options == null && replayContext.getSearchAttributes() != null) {
1 ✔
1619
      // Carry over existing search attributes if none are specified.
1620
      SearchAttributes existing = replayContext.getSearchAttributes();
1 ✔
1621
      if (existing != null && !existing.getIndexedFieldsMap().isEmpty()) {
1 !
1622
        attributes.setSearchAttributes(existing);
1 ✔
1623
      }
1624
    }
1625

1626
    List<ContextPropagator> propagators =
1627
        options != null && options.getContextPropagators() != null
1 !
UNCOV
1628
            ? options.getContextPropagators()
×
1629
            : this.contextPropagators;
1 ✔
1630
    io.temporal.api.common.v1.Header grpcHeader =
1 ✔
1631
        toHeaderGrpc(
1 ✔
1632
            input.getHeader(),
1 ✔
1633
            HeaderUtils.fromContextPropagators(propagators),
1 ✔
1634
            HeaderUtils.withContext(
1 ✔
1635
                headerCodec,
1636
                new WorkflowSerializationContext(namespace, workflowExecution.getWorkflowId())));
1 ✔
1637
    attributes.setHeader(grpcHeader);
1 ✔
1638

1639
    Optional<Payloads> payloads =
1 ✔
1640
        dataConverterWithCurrentWorkflowContext.toPayloads(input.getArgs());
1 ✔
1641
    payloads.ifPresent(attributes::setInput);
1 ✔
1642

1643
    replayContext.continueAsNewOnCompletion(
1 ✔
1644
        new ContinueAsNewWorkflowParameters(
1645
            attributes.build(),
1 ✔
1646
            eventGroupMarkers(
1 ✔
1647
                options != null ? options.getEventGroups() : Collections.emptyList())));
1 ✔
1648
    WorkflowThread.exit();
×
UNCOV
1649
  }
×
1650

1651
  @Override
1652
  public CancelWorkflowOutput cancelWorkflow(CancelWorkflowInput input) {
1653
    CompletablePromise<Void> result = Workflow.newPromise();
1 ✔
1654
    replayContext.requestCancelExternalWorkflowExecution(
1 ✔
1655
        input.getExecution(),
1 ✔
1656
        input.getOptions().getReason(),
1 ✔
1657
        eventGroupMarkers(input.getOptions().getEventGroups()),
1 ✔
1658
        (r, exception) -> {
1659
          if (exception == null) {
1 !
1660
            result.complete(null);
1 ✔
1661
          } else {
UNCOV
1662
            result.completeExceptionally(exception);
×
1663
          }
1664
        });
1 ✔
1665
    return new CancelWorkflowOutput(result);
1 ✔
1666
  }
1667

1668
  @Override
1669
  public Scope getMetricsScope() {
1670
    return replayContext.getMetricsScope();
1 ✔
1671
  }
1672

1673
  public boolean isLoggingEnabledInReplay() {
1674
    return replayContext.getEnableLoggingInReplay();
1 ✔
1675
  }
1676

1677
  @Override
1678
  public void upsertSearchAttributes(Map<String, ?> searchAttributes) {
1679
    Preconditions.checkArgument(searchAttributes != null, "null search attributes");
1 !
1680
    Preconditions.checkArgument(!searchAttributes.isEmpty(), "empty search attributes");
1 ✔
1681
    SearchAttributes attr = SearchAttributesUtil.encode(searchAttributes);
1 ✔
1682
    replayContext.upsertSearchAttributes(attr, eventGroupMarkers(Collections.emptyList()));
1 ✔
1683
  }
1 ✔
1684

1685
  @Override
1686
  public void upsertTypedSearchAttributes(SearchAttributeUpdate<?>... searchAttributeUpdates) {
1687
    upsertTypedSearchAttributes(
1 ✔
1688
        UpsertSearchAttributesOptions.getDefaultInstance(), searchAttributeUpdates);
1 ✔
1689
  }
1 ✔
1690

1691
  @Override
1692
  public void upsertTypedSearchAttributes(
1693
      UpsertSearchAttributesOptions options, SearchAttributeUpdate<?>... searchAttributeUpdates) {
1694
    SearchAttributes attr = SearchAttributesUtil.encodeTypedUpdates(searchAttributeUpdates);
1 ✔
1695
    replayContext.upsertSearchAttributes(attr, eventGroupMarkers(options.getEventGroups()));
1 ✔
1696
  }
1 ✔
1697

1698
  @Override
1699
  public void upsertMemo(Map<String, Object> memo) {
1700
    upsertMemo(memo, UpsertMemoOptions.getDefaultInstance());
1 ✔
1701
  }
1 ✔
1702

1703
  @Override
1704
  public void upsertMemo(Map<String, Object> memo, UpsertMemoOptions options) {
1705
    Preconditions.checkArgument(memo != null, "null memo");
1 !
1706
    Preconditions.checkArgument(!memo.isEmpty(), "empty memo");
1 !
1707
    replayContext.upsertMemo(
1 ✔
1708
        Memo.newBuilder()
1 ✔
1709
            .putAllFields(intoPayloadMap(dataConverterWithCurrentWorkflowContext, memo))
1 ✔
1710
            .build(),
1 ✔
1711
        eventGroupMarkers(options.getEventGroups()));
1 ✔
1712
  }
1 ✔
1713

1714
  @Nonnull
1715
  public Object newWorkflowMethodThreadIntercepted(Runnable runnable, @Nullable String name) {
1716
    return runner.newWorkflowThread(runnable, false, name);
1 ✔
1717
  }
1718

1719
  @Nonnull
1720
  public Object newWorkflowCallbackThreadIntercepted(Runnable runnable, @Nullable String name) {
1721
    return runner.newCallbackThread(runnable, name);
1 ✔
1722
  }
1723

1724
  @Override
1725
  public Object newChildThread(Runnable runnable, boolean detached, String name) {
1726
    return runner.newWorkflowThread(runnable, detached, name);
1 ✔
1727
  }
1728

1729
  @Override
1730
  public long currentTimeMillis() {
1731
    return replayContext.currentTimeMillis();
1 ✔
1732
  }
1733

1734
  /**
1735
   * This WorkflowInboundCallsInterceptor is used during creation of the initial root workflow
1736
   * thread and should be replaced with another specific implementation during initialization stage
1737
   * {@code workflow.initialize()} performed inside the workflow root thread.
1738
   *
1739
   * @see SyncWorkflow#start(HistoryEvent, ReplayWorkflowContext)
1740
   */
1741
  private static final class InitialWorkflowInboundCallsInterceptor
1742
      extends BaseRootWorkflowInboundCallsInterceptor {
1743

1744
    public InitialWorkflowInboundCallsInterceptor(SyncWorkflowContext workflowContext) {
1745
      super(workflowContext);
1 ✔
1746
    }
1 ✔
1747

1748
    @Override
1749
    public WorkflowOutput execute(WorkflowInput input) {
UNCOV
1750
      throw new UnsupportedOperationException(
×
1751
          "SyncWorkflowContext should be initialized with a non-initial WorkflowInboundCallsInterceptor "
1752
              + "before #execute can be called");
1753
    }
1754
  }
1755

1756
  @Nonnull
1757
  @Override
1758
  public WorkflowImplementationOptions getWorkflowImplementationOptions() {
1759
    return workflowImplementationOptions;
1 ✔
1760
  }
1761

1762
  @Override
1763
  public Failure mapWorkflowExceptionToFailure(Throwable failure) {
1764
    return getDataConverterForResult().exceptionToFailure(failure);
1 ✔
1765
  }
1766

1767
  /**
1768
   * The data converter for an update's result, failure and rejection, which are returned to the
1769
   * update's caller: the Nexus context of the Nexus operation handler that sent the update, if it
1770
   * was sent by one, otherwise the workflow context. Unlike {@link #getDataConverterForResult},
1771
   * this doesn't depend on how the workflow was started, because the outcome belongs to the update
1772
   * rather than closing the workflow. The update's arguments always use the workflow context.
1773
   */
1774
  DataConverter getDataConverterForUpdateOutcome(
1775
      @Nullable NexusSerializationContext nexusSerializationContext) {
1776
    return nexusSerializationContext != null
1 ✔
1777
        ? dataConverter.withContext(nexusSerializationContext)
1 ✔
1778
        : dataConverterWithCurrentWorkflowContext;
1 ✔
1779
  }
1780

1781
  @Nullable
1782
  @Override
1783
  public <R> R getLastCompletionResult(Class<R> resultClass, Type resultType) {
1784
    return dataConverterWithCurrentWorkflowContext.fromPayloads(
1 ✔
1785
        0, Optional.ofNullable(replayContext.getLastCompletionResult()), resultClass, resultType);
1 ✔
1786
  }
1787

1788
  @Override
1789
  public List<ContextPropagator> getContextPropagators() {
1790
    return contextPropagators;
1 ✔
1791
  }
1792

1793
  Header headerWithCodec(io.temporal.api.common.v1.Header header) {
1794
    return new Header(
1 ✔
1795
        header,
1796
        HeaderUtils.withContext(
1 ✔
1797
            headerCodec,
1798
            new WorkflowSerializationContext(namespace, workflowExecution.getWorkflowId())));
1 ✔
1799
  }
1800

1801
  @Override
1802
  public Map<String, Object> getPropagatedContexts() {
1803
    if (contextPropagators == null || contextPropagators.isEmpty()) {
1 ✔
1804
      return new HashMap<>();
1 ✔
1805
    }
1806

1807
    Map<String, Object> contextData = new HashMap<>();
1 ✔
1808
    Header header =
1 ✔
1809
        headerWithCodec(
1 ✔
1810
            io.temporal.api.common.v1.Header.newBuilder()
1 ✔
1811
                .putAllFields(replayContext.getHeader())
1 ✔
1812
                .build());
1 ✔
1813
    for (ContextPropagator propagator : contextPropagators) {
1 ✔
1814
      Map<String, Payload> headerData =
1815
          propagator.encodeHeaders()
1 ✔
1816
              ? header.getCodecDecodedValues()
1 ✔
1817
              : new HashMap<>(header.getValues());
1 ✔
1818
      contextData.put(propagator.getName(), propagator.deserializeContext(headerData));
1 ✔
1819
    }
1 ✔
1820

1821
    return contextData;
1 ✔
1822
  }
1823

1824
  @Override
1825
  public VersioningBehavior getVersioningBehavior() {
1826
    return workflowDefinition.getVersioningBehavior();
1 ✔
1827
  }
1828

1829
  public void setCurrentUpdateInfo(UpdateInfo updateInfo) {
1830
    currentUpdateInfo.set(updateInfo);
1 ✔
1831
  }
1 ✔
1832

1833
  public void setCurrentDetails(String details) {
1834
    currentDetails = details;
1 ✔
1835
  }
1 ✔
1836

1837
  @Nullable
1838
  public Object getInstance() {
1839
    return workflowDefinition.getInstance();
1 ✔
1840
  }
1841

1842
  @Nullable
1843
  public String getCurrentDetails() {
1844
    return currentDetails;
1 ✔
1845
  }
1846

1847
  public Optional<UpdateInfo> getCurrentUpdateInfo() {
1848
    return Optional.ofNullable(currentUpdateInfo.get());
1 ✔
1849
  }
1850

1851
  private List<EventGroupMarker> eventGroupMarkers(List<EventGroup> directGroups) {
1852
    return EventGroupScope.current()
1 ✔
1853
        .toMarkers(directGroups, dataConverterWithCurrentWorkflowContext);
1 ✔
1854
  }
1855

1856
  /** Simple wrapper over a failure just to allow completing the CompletablePromise as a failure */
1857
  private static class FailureWrapperException extends RuntimeException {
1858
    private final Failure failure;
1859

1860
    public FailureWrapperException(Failure failure) {
1 ✔
1861
      this.failure = failure;
1 ✔
1862
    }
1 ✔
1863

1864
    public Failure getFailure() {
1865
      return failure;
1 ✔
1866
    }
1867
  }
1868
}
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