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

temporalio / sdk-java / #431

18 Nov 2026 09:28PM UTC coverage: 71.813% (+0.01%) from 71.8%
#431

push

github

web-flow
Include inherited fields in service stub options toString (#3152)

* Include inherited fields in service stub options toString

WorkflowServiceStubsOptions.toString rendered only the five fields
declared on the subclass, silently dropping every field inherited from
ServiceStubsOptions. Target, TLS settings, timeouts, and headers were
absent from the output, which is exactly the connection information
wanted when diagnosing a client from logs.

OperatorServiceStubsOptions and CloudServiceStubsOptions had no
toString at all and fell back to Object.toString, logging as an
unreadable identity hash.

Extract the field rendering on ServiceStubsOptions into a
package-private toStringFields helper and have each subclass inline it
alongside its own fields. The helper is package-private because all
four classes live in io.temporal.serviceclient, so this adds no public
API surface.

Also include apiKeyProvided, which already participates in equals and
hashCode but was omitted from toString. The API key itself is held by a
metadata provider and is still never rendered.

Fixes #2148.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* Render header names instead of header values in toString

Metadata.toString renders header values in the clear. The previous
commit propagated the inherited headers field into
WorkflowServiceStubsOptions, OperatorServiceStubsOptions, and
CloudServiceStubsOptions, which would have newly exposed any credential
supplied through setHeaders, such as a static Authorization header.

Render the header names only. This keeps the diagnostic signal that
matters when reading the output, whether a header is configured and
which ones, without printing what they contain.

Also add a regression test for the missing separator before
congestionInitialInterval in RpcRetryOptions.toString.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* Add changelog entry for service stub options toString

Co-Authored-By: Claude Opus 5.5 <noreply@anthro... (continued)

8779 of 14371 branches covered (61.09%)

Branch coverage included in aggregate %.

5 of 6 new or added lines in 4 files covered. (83.33%)

892 existing lines in 36 files now uncovered.

34625 of 46069 relevant lines covered (75.16%)

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 ✔
UNCOV
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 ✔
UNCOV
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 ✔
UNCOV
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 !
UNCOV
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);
×
UNCOV
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 !
UNCOV
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);
×
UNCOV
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
    executeLocalActivityOverLocalRetryThreshold(
1 ✔
469
        input.getActivityName(),
1 ✔
470
        input.getActivityId(),
1 ✔
471
        input.getOptions(),
1 ✔
472
        input.getHeader(),
1 ✔
473
        payloads,
474
        arguments,
475
        originalScheduledTime,
476
        1,
477
        null,
478
        localActivityResult);
479

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

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

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

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

577
  private CompletablePromise<LocalActivityCallback.Output> executeLocalActivityLocally(
578
      String activityTypeName,
579
      @Nullable String activityId,
580
      LocalActivityOptions options,
581
      Header header,
582
      Optional<Payloads> input,
583
      @Nullable LocalActivityArguments arguments,
584
      long originalScheduledTime,
585
      int attempt,
586
      @Nullable Failure previousExecutionFailure) {
587

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

611
  private ActivitySerializationContext activityContext(
612
      String name, String taskQueue, boolean local) {
613
    return new ActivitySerializationContext(
1 ✔
614
        replayContext.getNamespace(),
1 ✔
615
        replayContext.getWorkflowId(),
1 ✔
616
        replayContext.getWorkflowType().getName(),
1 ✔
617
        name,
618
        taskQueue,
619
        local);
620
  }
621

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

648
    if (activityId != null) {
1 ✔
649
      attributes.setActivityId(activityId);
1 ✔
650
    }
651

652
    input.ifPresent(attributes::setInput);
1 ✔
653
    RetryOptions retryOptions = options.getRetryOptions();
1 ✔
654
    if (retryOptions != null) {
1 ✔
655
      attributes.setRetryPolicy(toRetryPolicy(retryOptions));
1 ✔
656
    }
657

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

671
    if (options.getVersioningIntent() != null) {
1 !
672
      attributes.setUseWorkflowBuildId(
1 ✔
673
          options
674
              .getVersioningIntent()
1 ✔
675
              .determineUseCompatibleFlag(
1 ✔
676
                  replayContext.getTaskQueue().equals(options.getTaskQueue())));
1 ✔
677
    }
678

679
    @Nullable
680
    UserMetadata userMetadata =
1 ✔
681
        makeUserMetaData(options.getSummary(), null, dataConverterWithCurrentWorkflowContext);
1 ✔
682

683
    if (options.getPriority() != null) {
1 ✔
684
      attributes.setPriority(ProtoConverters.toProto(options.getPriority()));
1 ✔
685
    }
686

687
    return new ExecuteActivityParameters(
1 ✔
688
        attributes,
689
        options.getCancellationType(),
1 ✔
690
        userMetadata,
691
        eventGroupMarkers(options.getEventGroups()));
1 ✔
692
  }
693

694
  private ExecuteLocalActivityParameters constructExecuteLocalActivityParameters(
695
      String name,
696
      @Nullable String activityId,
697
      LocalActivityOptions options,
698
      Header header,
699
      Optional<Payloads> input,
700
      @Nullable LocalActivityArguments arguments,
701
      int attempt,
702
      long originalScheduledTime,
703
      @Nullable Failure previousExecutionFailure) {
704
    options = LocalActivityOptions.newBuilder(options).validateAndBuildWithDefaults();
1 ✔
705

706
    PollActivityTaskQueueResponse.Builder activityTask =
707
        PollActivityTaskQueueResponse.newBuilder()
1 ✔
708
            .setActivityId(
1 ✔
709
                activityId != null ? activityId : this.replayContext.randomUUID().toString())
1 ✔
710
            .setWorkflowNamespace(this.replayContext.getNamespace())
1 ✔
711
            .setWorkflowType(this.replayContext.getWorkflowType())
1 ✔
712
            .setWorkflowExecution(this.replayContext.getWorkflowExecution())
1 ✔
713
            // used to pass scheduled time to the local activity code inside
714
            // ActivityExecutionContext#getInfo
715
            // setCurrentAttemptScheduledTime is called inside LocalActivityWorker before submitting
716
            // into the LA queue
717
            .setScheduledTime(
1 ✔
718
                ProtobufTimeUtils.toProtoTimestamp(Instant.ofEpochMilli(originalScheduledTime)))
1 ✔
719
            .setActivityType(ActivityType.newBuilder().setName(name))
1 ✔
720
            .setAttempt(attempt);
1 ✔
721

722
    Duration scheduleToCloseTimeout = options.getScheduleToCloseTimeout();
1 ✔
723
    if (scheduleToCloseTimeout != null) {
1 ✔
724
      activityTask.setScheduleToCloseTimeout(
1 ✔
725
          ProtobufTimeUtils.toProtoDuration(scheduleToCloseTimeout));
1 ✔
726
    }
727

728
    Duration startToCloseTimeout = options.getStartToCloseTimeout();
1 ✔
729
    if (startToCloseTimeout != null) {
1 ✔
730
      activityTask.setStartToCloseTimeout(ProtobufTimeUtils.toProtoDuration(startToCloseTimeout));
1 ✔
731
    }
732

733
    io.temporal.api.common.v1.Header grpcHeader =
1 ✔
734
        toHeaderGrpc(
1 ✔
735
            header,
736
            HeaderUtils.fromContextPropagators(contextPropagators),
1 ✔
737
            HeaderUtils.withContext(
1 ✔
738
                headerCodec, activityContext(name, replayContext.getTaskQueue(), true)));
1 ✔
739
    activityTask.setHeader(grpcHeader);
1 ✔
740
    input.ifPresent(activityTask::setInput);
1 ✔
741
    RetryOptions retryOptions = options.getRetryOptions();
1 ✔
742
    activityTask.setRetryPolicy(
1 ✔
743
        toRetryPolicy(RetryOptions.newBuilder(retryOptions).validateBuildWithDefaults()));
1 ✔
744
    Duration localRetryThreshold = options.getLocalRetryThreshold();
1 ✔
745
    if (localRetryThreshold == null) {
1 ✔
746
      localRetryThreshold = replayContext.getWorkflowTaskTimeout().multipliedBy(3);
1 ✔
747
    }
748

749
    @Nullable
750
    UserMetadata userMetadata =
1 ✔
751
        makeUserMetaData(options.getSummary(), null, dataConverterWithCurrentWorkflowContext);
1 ✔
752

753
    return new ExecuteLocalActivityParameters(
1 ✔
754
        activityTask,
755
        options.getScheduleToStartTimeout(),
1 ✔
756
        originalScheduledTime,
757
        previousExecutionFailure,
758
        options.isDoNotIncludeArgumentsIntoMarker(),
1 ✔
759
        localRetryThreshold,
760
        userMetadata,
761
        eventGroupMarkers(options.getEventGroups()),
1 ✔
762
        arguments);
763
  }
764

765
  @Override
766
  public <R> ChildWorkflowOutput<R> executeChildWorkflow(ChildWorkflowInput<R> input) {
767
    if (CancellationScope.current().isCancelRequested()) {
1 ✔
768
      CanceledFailure canceledFailure = new CanceledFailure("execute called from a canceled scope");
1 ✔
769
      return new ChildWorkflowOutput<>(
1 ✔
770
          Workflow.newFailedPromise(canceledFailure), Workflow.newFailedPromise(canceledFailure));
1 ✔
771
    }
772

773
    CompletablePromise<WorkflowExecution> executionPromise = Workflow.newPromise();
1 ✔
774
    CompletablePromise<Optional<Payloads>> resultPromise = Workflow.newPromise();
1 ✔
775

776
    DataConverter dataConverterWithChildWorkflowContext =
1 ✔
777
        dataConverter.withContext(
1 ✔
778
            new WorkflowSerializationContext(replayContext.getNamespace(), input.getWorkflowId()));
1 ✔
779
    Optional<Payloads> payloads = dataConverterWithChildWorkflowContext.toPayloads(input.getArgs());
1 ✔
780

781
    @Nullable
782
    Memo memo =
783
        (input.getOptions().getMemo() != null)
1 ✔
784
            ? Memo.newBuilder()
1 ✔
785
                .putAllFields(
1 ✔
786
                    intoPayloadMap(
1 ✔
787
                        dataConverterWithChildWorkflowContext, input.getOptions().getMemo()))
1 ✔
788
                .build()
1 ✔
789
            : null;
1 ✔
790

791
    @Nullable
792
    UserMetadata userMetadata =
1 ✔
793
        makeUserMetaData(
1 ✔
794
            input.getOptions().getStaticSummary(),
1 ✔
795
            input.getOptions().getStaticDetails(),
1 ✔
796
            dataConverterWithChildWorkflowContext);
797

798
    StartChildWorkflowExecutionParameters parameters =
1 ✔
799
        createChildWorkflowParameters(
1 ✔
800
            input.getWorkflowId(),
1 ✔
801
            input.getWorkflowType(),
1 ✔
802
            input.getOptions(),
1 ✔
803
            input.getHeader(),
1 ✔
804
            payloads,
805
            memo,
806
            userMetadata);
807

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

848
    // Avoid passing the input to the output handle as it causes the input to be retained for the
849
    // duration of the operation.
850
    Type resultType = input.getResultType();
1 ✔
851
    Class<R> resultClass = input.getResultClass();
1 ✔
852
    Promise<R> result =
1 ✔
853
        resultPromise.thenApply(
1 ✔
854
            (b) ->
855
                dataConverterWithChildWorkflowContext.fromPayloads(0, b, resultClass, resultType));
1 ✔
856
    return new ChildWorkflowOutput<>(result, executionPromise);
1 ✔
857
  }
858

859
  @Override
860
  public <R> ExecuteNexusOperationOutput<R> executeNexusOperation(
861
      ExecuteNexusOperationInput<R> input) {
862
    Preconditions.checkArgument(
1 ✔
863
        input.getEndpoint() != null && !input.getEndpoint().isEmpty(), "endpoint must be set");
1 !
864
    Preconditions.checkArgument(
1 ✔
865
        input.getService() != null && !input.getService().isEmpty(), "service must be set");
1 !
866

867
    if (CancellationScope.current().isCancelRequested()) {
1 !
UNCOV
868
      CanceledFailure canceledFailure =
×
869
          new CanceledFailure("execute nexus operation called from a canceled scope");
UNCOV
870
      return new ExecuteNexusOperationOutput<>(
×
UNCOV
871
          Workflow.newFailedPromise(canceledFailure), Workflow.newFailedPromise(canceledFailure));
×
872
    }
873

874
    CompletablePromise<NexusOperationExecution> operationPromise = Workflow.newPromise();
1 ✔
875
    CompletablePromise<Optional<Payload>> resultPromise = Workflow.newPromise();
1 ✔
876

877
    // The caller workflow is not available to the operation handler, so Nexus payloads are
878
    // contextualized by the endpoint, service and operation instead. The same converter decodes the
879
    // result and converts failures, so each operation keeps the converter selected for it even when
880
    // several operations are in flight at once.
881
    DataConverter nexusDataConverter =
1 ✔
882
        dataConverter.withContext(
1 ✔
883
            new NexusSerializationContext(
884
                input.getEndpoint(), input.getService(), input.getOperation()));
1 ✔
885

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

888
    ScheduleNexusOperationCommandAttributes.Builder attributes =
889
        ScheduleNexusOperationCommandAttributes.newBuilder();
1 ✔
890
    payload.ifPresent(attributes::setInput);
1 ✔
891
    attributes.setOperation(input.getOperation());
1 ✔
892
    attributes.setService(input.getService());
1 ✔
893
    attributes.setEndpoint(input.getEndpoint());
1 ✔
894
    // Ensure that the headers are lowercase
895
    input.getHeaders().forEach((k, v) -> attributes.putNexusHeader(k.toLowerCase(), v));
1 ✔
896
    attributes.setScheduleToCloseTimeout(
1 ✔
897
        ProtobufTimeUtils.toProtoDuration(input.getOptions().getScheduleToCloseTimeout()));
1 ✔
898
    attributes.setScheduleToStartTimeout(
1 ✔
899
        ProtobufTimeUtils.toProtoDuration(input.getOptions().getScheduleToStartTimeout()));
1 ✔
900
    attributes.setStartToCloseTimeout(
1 ✔
901
        ProtobufTimeUtils.toProtoDuration(input.getOptions().getStartToCloseTimeout()));
1 ✔
902

903
    @Nullable
904
    UserMetadata userMetadata =
1 ✔
905
        makeUserMetaData(input.getOptions().getSummary(), null, nexusDataConverter);
1 ✔
906

907
    StartNexusOperationParameters parameters =
1 ✔
908
        new StartNexusOperationParameters(
909
            attributes,
910
            input.getOptions().getCancellationType(),
1 ✔
911
            userMetadata,
912
            eventGroupMarkers(input.getOptions().getEventGroups()));
1 ✔
913

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

968
  @SuppressWarnings("deprecation")
969
  private StartChildWorkflowExecutionParameters createChildWorkflowParameters(
970
      String workflowId,
971
      String name,
972
      ChildWorkflowOptions options,
973
      Header header,
974
      Optional<Payloads> input,
975
      @Nullable Memo memo,
976
      @Nullable UserMetadata metadata) {
977
    final StartChildWorkflowExecutionCommandAttributes.Builder attributes =
978
        StartChildWorkflowExecutionCommandAttributes.newBuilder()
1 ✔
979
            .setWorkflowType(WorkflowType.newBuilder().setName(name).build());
1 ✔
980
    attributes.setWorkflowId(workflowId);
1 ✔
981
    attributes.setNamespace(OptionsUtils.safeGet(options.getNamespace()));
1 ✔
982
    input.ifPresent(attributes::setInput);
1 ✔
983
    attributes.setWorkflowRunTimeout(
1 ✔
984
        ProtobufTimeUtils.toProtoDuration(options.getWorkflowRunTimeout()));
1 ✔
985
    attributes.setWorkflowExecutionTimeout(
1 ✔
986
        ProtobufTimeUtils.toProtoDuration(options.getWorkflowExecutionTimeout()));
1 ✔
987
    attributes.setWorkflowTaskTimeout(
1 ✔
988
        ProtobufTimeUtils.toProtoDuration(options.getWorkflowTaskTimeout()));
1 ✔
989
    String taskQueue = options.getTaskQueue();
1 ✔
990
    if (taskQueue != null) {
1 ✔
991
      attributes.setTaskQueue(TaskQueue.newBuilder().setName(taskQueue));
1 ✔
992
    }
993
    if (options.getWorkflowIdReusePolicy() != null) {
1 ✔
994
      attributes.setWorkflowIdReusePolicy(options.getWorkflowIdReusePolicy());
1 ✔
995
    }
996
    RetryOptions retryOptions = options.getRetryOptions();
1 ✔
997
    if (retryOptions != null) {
1 ✔
998
      attributes.setRetryPolicy(toRetryPolicy(retryOptions));
1 ✔
999
    }
1000
    attributes.setCronSchedule(OptionsUtils.safeGet(options.getCronSchedule()));
1 ✔
1001

1002
    if (memo != null) {
1 ✔
1003
      attributes.setMemo(memo);
1 ✔
1004
    }
1005

1006
    Map<String, Object> searchAttributes = options.getSearchAttributes();
1 ✔
1007
    if (searchAttributes != null && !searchAttributes.isEmpty()) {
1 !
1008
      if (options.getTypedSearchAttributes() != null) {
1 !
UNCOV
1009
        throw new IllegalArgumentException(
×
1010
            "Cannot have both typed search attributes and search attributes");
1011
      }
1012
      attributes.setSearchAttributes(SearchAttributesUtil.encode(searchAttributes));
1 ✔
1013
    } else if (options.getTypedSearchAttributes() != null
1 ✔
1014
        && options.getTypedSearchAttributes().size() > 0) {
1 !
1015
      attributes.setSearchAttributes(
1 ✔
1016
          SearchAttributesUtil.encodeTyped(options.getTypedSearchAttributes()));
1 ✔
1017
    }
1018

1019
    List<ContextPropagator> propagators = options.getContextPropagators();
1 ✔
1020
    if (propagators == null) {
1 !
1021
      propagators = this.contextPropagators;
1 ✔
1022
    }
1023
    io.temporal.api.common.v1.Header grpcHeader =
1 ✔
1024
        toHeaderGrpc(
1 ✔
1025
            header,
1026
            HeaderUtils.fromContextPropagators(propagators),
1 ✔
1027
            HeaderUtils.withContext(
1 ✔
1028
                headerCodec,
1029
                new WorkflowSerializationContext(
1030
                    Strings.isNullOrEmpty(options.getNamespace())
1 ✔
1031
                        ? replayContext.getNamespace()
1 ✔
1032
                        : options.getNamespace(),
1 ✔
1033
                    workflowId)));
1034
    attributes.setHeader(grpcHeader);
1 ✔
1035

1036
    ParentClosePolicy parentClosePolicy = options.getParentClosePolicy();
1 ✔
1037
    if (parentClosePolicy != null) {
1 ✔
1038
      attributes.setParentClosePolicy(parentClosePolicy);
1 ✔
1039
    }
1040

1041
    if (options.getVersioningIntent() != null) {
1 ✔
1042
      attributes.setInheritBuildId(
1 ✔
1043
          options
1044
              .getVersioningIntent()
1 ✔
1045
              .determineUseCompatibleFlag(
1 ✔
1046
                  replayContext.getTaskQueue().equals(options.getTaskQueue())));
1 ✔
1047
    }
1048
    if (options.getPriority() != null) {
1 ✔
1049
      attributes.setPriority(ProtoConverters.toProto(options.getPriority()));
1 ✔
1050
    }
1051
    if (options.getVersioningOverride() != null) {
1 !
UNCOV
1052
      attributes.setVersioningOverride(ProtoConverters.toProto(options.getVersioningOverride()));
×
1053
    }
1054
    return new StartChildWorkflowExecutionParameters(
1 ✔
1055
        attributes,
1056
        options.getCancellationType(),
1 ✔
1057
        metadata,
1058
        eventGroupMarkers(options.getEventGroups()));
1 ✔
1059
  }
1060

1061
  private static RuntimeException mapChildWorkflowException(
1062
      Exception failure, DataConverter dataConverterWithChildWorkflowContext) {
1063
    if (failure == null) {
1 !
UNCOV
1064
      return null;
×
1065
    }
1066
    if (failure instanceof TemporalFailure) {
1 ✔
1067
      ((TemporalFailure) failure).setDataConverter(dataConverterWithChildWorkflowContext);
1 ✔
1068
    }
1069
    if (failure instanceof CanceledFailure) {
1 ✔
1070
      return (CanceledFailure) failure;
1 ✔
1071
    }
1072
    if (failure instanceof WorkflowException) {
1 !
UNCOV
1073
      return (RuntimeException) failure;
×
1074
    }
1075
    if (failure instanceof ChildWorkflowFailure) {
1 ✔
1076
      return (ChildWorkflowFailure) failure;
1 ✔
1077
    }
1078
    if (!(failure instanceof ChildWorkflowTaskFailedException)) {
1 !
UNCOV
1079
      return new IllegalArgumentException("Unexpected exception type: ", failure);
×
1080
    }
1081
    ChildWorkflowTaskFailedException taskFailed = (ChildWorkflowTaskFailedException) failure;
1 ✔
1082
    Throwable cause =
1 ✔
1083
        dataConverterWithChildWorkflowContext.failureToException(
1 ✔
1084
            taskFailed.getOriginalCauseFailure());
1 ✔
1085
    ChildWorkflowFailure exception = taskFailed.getException();
1 ✔
1086
    return new ChildWorkflowFailure(
1 ✔
1087
        exception.getInitiatedEventId(),
1 ✔
1088
        exception.getStartedEventId(),
1 ✔
1089
        exception.getWorkflowType(),
1 ✔
1090
        exception.getExecution(),
1 ✔
1091
        exception.getNamespace(),
1 ✔
1092
        exception.getRetryState(),
1 ✔
1093
        cause);
1094
  }
1095

1096
  @Override
1097
  public Promise<Void> newTimer(Duration delay) {
1098
    return newTimer(delay, TimerOptions.newBuilder().build());
1 ✔
1099
  }
1100

1101
  @Override
1102
  public Promise<Void> newTimer(Duration delay, TimerOptions options) {
1103
    CompletablePromise<Void> p = Workflow.newPromise();
1 ✔
1104

1105
    @Nullable
1106
    UserMetadata userMetadata =
1 ✔
1107
        makeUserMetaData(options.getSummary(), null, dataConverterWithCurrentWorkflowContext);
1 ✔
1108

1109
    Functions.Proc1<RuntimeException> cancellationHandler =
1 ✔
1110
        replayContext.newTimer(
1 ✔
1111
            delay,
1112
            userMetadata,
1113
            eventGroupMarkers(options.getEventGroups()),
1 ✔
1114
            (e) ->
1115
                runner.executeInWorkflowThread(
1 ✔
1116
                    "timer-callback",
1117
                    () -> {
1118
                      if (e == null) {
1 ✔
1119
                        p.complete(null);
1 ✔
1120
                      } else {
1121
                        p.completeExceptionally(e);
1 ✔
1122
                      }
1123
                    }));
1 ✔
1124
    CancellationScope.current()
1 ✔
1125
        .getCancellationRequest()
1 ✔
1126
        .thenApply(
1 ✔
1127
            (r) -> {
1128
              cancellationHandler.apply(new CanceledFailure(r));
1 ✔
1129
              return r;
1 ✔
1130
            });
1131
    return p;
1 ✔
1132
  }
1133

1134
  @Override
1135
  public <R> R sideEffect(Class<R> resultClass, Type resultType, Func<R> func) {
1136
    return sideEffect(resultClass, resultType, func, SideEffectOptions.newBuilder().build());
1 ✔
1137
  }
1138

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

1172
  @Override
1173
  public <R> R mutableSideEffect(
1174
      String id, Class<R> resultClass, Type resultType, BiPredicate<R, R> updated, Func<R> func) {
1175
    return mutableSideEffect(
1 ✔
1176
        id, resultClass, resultType, updated, func, MutableSideEffectOptions.newBuilder().build());
1 ✔
1177
  }
1178

1179
  @Override
1180
  public <R> R mutableSideEffect(
1181
      String id,
1182
      Class<R> resultClass,
1183
      Type resultType,
1184
      BiPredicate<R, R> updated,
1185
      Func<R> func,
1186
      MutableSideEffectOptions options) {
1187
    @Nullable
1188
    UserMetadata userMetadata =
1 ✔
1189
        makeUserMetaData(options.getSummary(), null, dataConverterWithCurrentWorkflowContext);
1 ✔
1190
    List<EventGroupMarker> eventGroupMarkers = eventGroupMarkers(options.getEventGroups());
1 ✔
1191
    try {
1192
      return mutableSideEffectImpl(
1 ✔
1193
          id, userMetadata, eventGroupMarkers, resultClass, resultType, updated, func);
1194
    } catch (Exception e) {
1 ✔
1195
      // MutableSideEffect cannot throw normal exception as it can lead to non-deterministic
1196
      // behavior. So fail the workflow task by throwing an Error.
1197
      throw new Error(e);
1 ✔
1198
    }
1199
  }
1200

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

1239
    if (!result.get().isPresent()) {
1 !
UNCOV
1240
      throw new IllegalArgumentException("No value found for mutableSideEffectId=" + id);
×
1241
    }
1242
    // An optimization that avoids unnecessary deserialization of the result.
1243
    R unserialized = unserializedResult.get();
1 ✔
1244
    if (unserialized != null) {
1 ✔
1245
      return unserialized;
1 ✔
1246
    }
1247
    return dataConverterWithCurrentWorkflowContext.fromPayloads(
1 ✔
1248
        0, result.get(), resultClass, resultType);
1 ✔
1249
  }
1250

1251
  @Override
1252
  public int getVersion(String changeId, int minSupported, int maxSupported) {
1253
    return getVersion(changeId, minSupported, maxSupported, GetVersionOptions.getDefaultInstance());
1 ✔
1254
  }
1255

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

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

1322
  @Override
1323
  public void registerQuery(RegisterQueryInput request) {
1324
    queryDispatcher.registerQueryHandlers(request);
1 ✔
1325
  }
1 ✔
1326

1327
  @Override
1328
  public void registerSignalHandlers(RegisterSignalHandlersInput input) {
1329
    signalDispatcher.registerSignalHandlers(input);
1 ✔
1330
  }
1 ✔
1331

1332
  @Override
1333
  public void registerUpdateHandlers(RegisterUpdateHandlersInput input) {
1334
    updateDispatcher.registerUpdateHandlers(input);
1 ✔
1335
  }
1 ✔
1336

1337
  @Override
1338
  public void registerDynamicSignalHandler(RegisterDynamicSignalHandlerInput input) {
1339
    signalDispatcher.registerDynamicSignalHandler(input);
1 ✔
1340
  }
1 ✔
1341

1342
  @Override
1343
  public void registerDynamicQueryHandler(RegisterDynamicQueryHandlerInput input) {
1344
    queryDispatcher.registerDynamicQueryHandler(input);
1 ✔
1345
  }
1 ✔
1346

1347
  @Override
1348
  public void registerDynamicUpdateHandler(RegisterDynamicUpdateHandlerInput input) {
1349
    updateDispatcher.registerDynamicUpdateHandler(input);
1 ✔
1350
  }
1 ✔
1351

1352
  @Override
1353
  public UUID randomUUID() {
1354
    return replayContext.randomUUID();
1 ✔
1355
  }
1356

1357
  @Override
1358
  public Random newRandom() {
1359
    return replayContext.newRandom();
1 ✔
1360
  }
1361

1362
  public DataConverter getDataConverter() {
UNCOV
1363
    return dataConverter;
×
1364
  }
1365

1366
  public DataConverter getDataConverterWithCurrentWorkflowContext() {
1367
    return dataConverterWithCurrentWorkflowContext;
1 ✔
1368
  }
1369

1370
  /**
1371
   * Records the serialization context of the Nexus operation handler that started this workflow, as
1372
   * propagated by the server in the WorkflowExecutionStarted event.
1373
   */
1374
  void setPropagatedNexusSerializationContext(
1375
      @Nullable NexusSerializationContext propagatedNexusSerializationContext) {
1376
    this.dataConverterWithPropagatedNexusContext =
1 ✔
1377
        propagatedNexusSerializationContext == null
1 ✔
1378
            ? null
1 ✔
1379
            : dataConverter.withContext(propagatedNexusSerializationContext);
1 ✔
1380
  }
1 ✔
1381

1382
  /**
1383
   * The data converter for the workflow result and the failure that closes the workflow, which are
1384
   * returned to the Nexus caller: the propagated Nexus context if the workflow was started by a
1385
   * Nexus operation handler, otherwise the workflow context. Input, memo, signals and queries
1386
   * always use the workflow context. Updates use {@link #getDataConverterForUpdateOutcome}.
1387
   */
1388
  DataConverter getDataConverterForResult() {
1389
    return dataConverterWithPropagatedNexusContext != null
1 ✔
1390
        ? dataConverterWithPropagatedNexusContext
1 ✔
1391
        : dataConverterWithCurrentWorkflowContext;
1 ✔
1392
  }
1393

1394
  boolean isReplaying() {
1395
    return replayContext.isReplaying();
1 ✔
1396
  }
1397

1398
  boolean isReadOnly() {
1399
    return readOnly;
1 ✔
1400
  }
1401

1402
  void setReadOnly(boolean readOnly) {
1403
    this.readOnly = readOnly;
1 ✔
1404
  }
1 ✔
1405

1406
  @Override
1407
  public Map<Long, SignalHandlerInfo> getRunningSignalHandlers() {
1408
    return signalDispatcher.getRunningSignalHandlers();
1 ✔
1409
  }
1410

1411
  @Override
1412
  public Map<String, UpdateHandlerInfo> getRunningUpdateHandlers() {
1413
    return updateDispatcher.getRunningUpdateHandlers();
1 ✔
1414
  }
1415

1416
  @Override
1417
  public ReplayWorkflowContext getReplayContext() {
1418
    return replayContext;
1 ✔
1419
  }
1420

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

1469
  @Override
1470
  public void sleep(Duration duration) {
1471
    sleep(duration, TimerOptions.newBuilder().build());
1 ✔
1472
  }
1 ✔
1473

1474
  @Override
1475
  public void sleep(Duration duration, TimerOptions options) {
1476
    newTimer(duration, options).get();
1 ✔
1477
  }
1 ✔
1478

1479
  @Override
1480
  public boolean await(Duration timeout, String reason, Supplier<Boolean> unblockCondition) {
1481
    return await(timeout, TimerOptions.newBuilder().build(), reason, unblockCondition);
1 ✔
1482
  }
1483

1484
  @Override
1485
  public boolean await(
1486
      Duration timeout, TimerOptions options, String reason, Supplier<Boolean> unblockCondition) {
1487
    boolean cancelTimerOnCondition =
1 ✔
1488
        replayContext.tryUseSdkFlag(SdkFlag.CANCEL_AWAIT_TIMER_ON_CONDITION);
1 ✔
1489

1490
    if (cancelTimerOnCondition) {
1 ✔
1491
      // If condition is already satisfied, skip creating timer
1492
      if (unblockCondition.get()) {
1 ✔
1493
        return true;
1 ✔
1494
      }
1495
      // Create timer in a cancellation scope so we can cancel it when condition is satisfied
1496
      CompletablePromise<Void> timer = Workflow.newPromise();
1 ✔
1497
      CancellationScope timerScope =
1 ✔
1498
          Workflow.newCancellationScope(() -> timer.completeFrom(newTimer(timeout, options)));
1 ✔
1499
      timerScope.run();
1 ✔
1500

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

1503
      boolean conditionSatisfied = !timer.isCompleted();
1 ✔
1504
      if (conditionSatisfied) {
1 ✔
1505
        timerScope.cancel("await condition resolved");
1 ✔
1506
      }
1507
      return conditionSatisfied;
1 ✔
1508
    } else {
1509
      // Old behavior: timer is not cancelled when condition is satisfied
1510
      Promise<Void> timer = newTimer(timeout, options);
1 ✔
1511
      WorkflowThread.await(reason, () -> (timer.isCompleted() || unblockCondition.get()));
1 !
1512
      return !timer.isCompleted();
1 !
1513
    }
1514
  }
1515

1516
  @Override
1517
  public void await(String reason, Supplier<Boolean> unblockCondition) {
1518
    WorkflowThread.await(reason, unblockCondition);
1 ✔
1519
  }
1 ✔
1520

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

1599
    if (options == null && replayContext.getRetryOptions() != null) {
1 ✔
1600
      // Have to copy certain options as server doesn't copy them.
1601
      attributes.setRetryPolicy(toRetryPolicy(replayContext.getRetryOptions()));
1 ✔
1602
    }
1603

1604
    if (options == null && replayContext.getSearchAttributes() != null) {
1 ✔
1605
      // Carry over existing search attributes if none are specified.
1606
      SearchAttributes existing = replayContext.getSearchAttributes();
1 ✔
1607
      if (existing != null && !existing.getIndexedFieldsMap().isEmpty()) {
1 !
1608
        attributes.setSearchAttributes(existing);
1 ✔
1609
      }
1610
    }
1611

1612
    List<ContextPropagator> propagators =
1613
        options != null && options.getContextPropagators() != null
1 !
UNCOV
1614
            ? options.getContextPropagators()
×
1615
            : this.contextPropagators;
1 ✔
1616
    io.temporal.api.common.v1.Header grpcHeader =
1 ✔
1617
        toHeaderGrpc(
1 ✔
1618
            input.getHeader(),
1 ✔
1619
            HeaderUtils.fromContextPropagators(propagators),
1 ✔
1620
            HeaderUtils.withContext(
1 ✔
1621
                headerCodec,
1622
                new WorkflowSerializationContext(namespace, workflowExecution.getWorkflowId())));
1 ✔
1623
    attributes.setHeader(grpcHeader);
1 ✔
1624

1625
    Optional<Payloads> payloads =
1 ✔
1626
        dataConverterWithCurrentWorkflowContext.toPayloads(input.getArgs());
1 ✔
1627
    payloads.ifPresent(attributes::setInput);
1 ✔
1628

1629
    replayContext.continueAsNewOnCompletion(
1 ✔
1630
        new ContinueAsNewWorkflowParameters(
1631
            attributes.build(),
1 ✔
1632
            eventGroupMarkers(
1 ✔
1633
                options != null ? options.getEventGroups() : Collections.emptyList())));
1 ✔
UNCOV
1634
    WorkflowThread.exit();
×
UNCOV
1635
  }
×
1636

1637
  @Override
1638
  public CancelWorkflowOutput cancelWorkflow(CancelWorkflowInput input) {
1639
    CompletablePromise<Void> result = Workflow.newPromise();
1 ✔
1640
    replayContext.requestCancelExternalWorkflowExecution(
1 ✔
1641
        input.getExecution(),
1 ✔
1642
        input.getOptions().getReason(),
1 ✔
1643
        eventGroupMarkers(input.getOptions().getEventGroups()),
1 ✔
1644
        (r, exception) -> {
1645
          if (exception == null) {
1 !
1646
            result.complete(null);
1 ✔
1647
          } else {
UNCOV
1648
            result.completeExceptionally(exception);
×
1649
          }
1650
        });
1 ✔
1651
    return new CancelWorkflowOutput(result);
1 ✔
1652
  }
1653

1654
  @Override
1655
  public Scope getMetricsScope() {
1656
    return replayContext.getMetricsScope();
1 ✔
1657
  }
1658

1659
  public boolean isLoggingEnabledInReplay() {
1660
    return replayContext.getEnableLoggingInReplay();
1 ✔
1661
  }
1662

1663
  @Override
1664
  public void upsertSearchAttributes(Map<String, ?> searchAttributes) {
1665
    Preconditions.checkArgument(searchAttributes != null, "null search attributes");
1 !
1666
    Preconditions.checkArgument(!searchAttributes.isEmpty(), "empty search attributes");
1 ✔
1667
    SearchAttributes attr = SearchAttributesUtil.encode(searchAttributes);
1 ✔
1668
    replayContext.upsertSearchAttributes(attr, eventGroupMarkers(Collections.emptyList()));
1 ✔
1669
  }
1 ✔
1670

1671
  @Override
1672
  public void upsertTypedSearchAttributes(SearchAttributeUpdate<?>... searchAttributeUpdates) {
1673
    upsertTypedSearchAttributes(
1 ✔
1674
        UpsertSearchAttributesOptions.getDefaultInstance(), searchAttributeUpdates);
1 ✔
1675
  }
1 ✔
1676

1677
  @Override
1678
  public void upsertTypedSearchAttributes(
1679
      UpsertSearchAttributesOptions options, SearchAttributeUpdate<?>... searchAttributeUpdates) {
1680
    SearchAttributes attr = SearchAttributesUtil.encodeTypedUpdates(searchAttributeUpdates);
1 ✔
1681
    replayContext.upsertSearchAttributes(attr, eventGroupMarkers(options.getEventGroups()));
1 ✔
1682
  }
1 ✔
1683

1684
  @Override
1685
  public void upsertMemo(Map<String, Object> memo) {
1686
    upsertMemo(memo, UpsertMemoOptions.getDefaultInstance());
1 ✔
1687
  }
1 ✔
1688

1689
  @Override
1690
  public void upsertMemo(Map<String, Object> memo, UpsertMemoOptions options) {
1691
    Preconditions.checkArgument(memo != null, "null memo");
1 !
1692
    Preconditions.checkArgument(!memo.isEmpty(), "empty memo");
1 !
1693
    replayContext.upsertMemo(
1 ✔
1694
        Memo.newBuilder()
1 ✔
1695
            .putAllFields(intoPayloadMap(dataConverterWithCurrentWorkflowContext, memo))
1 ✔
1696
            .build(),
1 ✔
1697
        eventGroupMarkers(options.getEventGroups()));
1 ✔
1698
  }
1 ✔
1699

1700
  @Nonnull
1701
  public Object newWorkflowMethodThreadIntercepted(Runnable runnable, @Nullable String name) {
1702
    return runner.newWorkflowThread(runnable, false, name);
1 ✔
1703
  }
1704

1705
  @Nonnull
1706
  public Object newWorkflowCallbackThreadIntercepted(Runnable runnable, @Nullable String name) {
1707
    return runner.newCallbackThread(runnable, name);
1 ✔
1708
  }
1709

1710
  @Override
1711
  public Object newChildThread(Runnable runnable, boolean detached, String name) {
1712
    return runner.newWorkflowThread(runnable, detached, name);
1 ✔
1713
  }
1714

1715
  @Override
1716
  public long currentTimeMillis() {
1717
    return replayContext.currentTimeMillis();
1 ✔
1718
  }
1719

1720
  /**
1721
   * This WorkflowInboundCallsInterceptor is used during creation of the initial root workflow
1722
   * thread and should be replaced with another specific implementation during initialization stage
1723
   * {@code workflow.initialize()} performed inside the workflow root thread.
1724
   *
1725
   * @see SyncWorkflow#start(HistoryEvent, ReplayWorkflowContext)
1726
   */
1727
  private static final class InitialWorkflowInboundCallsInterceptor
1728
      extends BaseRootWorkflowInboundCallsInterceptor {
1729

1730
    public InitialWorkflowInboundCallsInterceptor(SyncWorkflowContext workflowContext) {
1731
      super(workflowContext);
1 ✔
1732
    }
1 ✔
1733

1734
    @Override
1735
    public WorkflowOutput execute(WorkflowInput input) {
UNCOV
1736
      throw new UnsupportedOperationException(
×
1737
          "SyncWorkflowContext should be initialized with a non-initial WorkflowInboundCallsInterceptor "
1738
              + "before #execute can be called");
1739
    }
1740
  }
1741

1742
  @Nonnull
1743
  @Override
1744
  public WorkflowImplementationOptions getWorkflowImplementationOptions() {
1745
    return workflowImplementationOptions;
1 ✔
1746
  }
1747

1748
  @Override
1749
  public Failure mapWorkflowExceptionToFailure(Throwable failure) {
1750
    return getDataConverterForResult().exceptionToFailure(failure);
1 ✔
1751
  }
1752

1753
  /**
1754
   * The data converter for an update's result, failure and rejection, which are returned to the
1755
   * update's caller: the Nexus context of the Nexus operation handler that sent the update, if it
1756
   * was sent by one, otherwise the workflow context. Unlike {@link #getDataConverterForResult},
1757
   * this doesn't depend on how the workflow was started, because the outcome belongs to the update
1758
   * rather than closing the workflow. The update's arguments always use the workflow context.
1759
   */
1760
  DataConverter getDataConverterForUpdateOutcome(
1761
      @Nullable NexusSerializationContext nexusSerializationContext) {
1762
    return nexusSerializationContext != null
1 ✔
1763
        ? dataConverter.withContext(nexusSerializationContext)
1 ✔
1764
        : dataConverterWithCurrentWorkflowContext;
1 ✔
1765
  }
1766

1767
  @Nullable
1768
  @Override
1769
  public <R> R getLastCompletionResult(Class<R> resultClass, Type resultType) {
1770
    return dataConverterWithCurrentWorkflowContext.fromPayloads(
1 ✔
1771
        0, Optional.ofNullable(replayContext.getLastCompletionResult()), resultClass, resultType);
1 ✔
1772
  }
1773

1774
  @Override
1775
  public List<ContextPropagator> getContextPropagators() {
1776
    return contextPropagators;
1 ✔
1777
  }
1778

1779
  Header headerWithCodec(io.temporal.api.common.v1.Header header) {
1780
    return new Header(
1 ✔
1781
        header,
1782
        HeaderUtils.withContext(
1 ✔
1783
            headerCodec,
1784
            new WorkflowSerializationContext(namespace, workflowExecution.getWorkflowId())));
1 ✔
1785
  }
1786

1787
  @Override
1788
  public Map<String, Object> getPropagatedContexts() {
1789
    if (contextPropagators == null || contextPropagators.isEmpty()) {
1 ✔
1790
      return new HashMap<>();
1 ✔
1791
    }
1792

1793
    Map<String, Object> contextData = new HashMap<>();
1 ✔
1794
    Header header =
1 ✔
1795
        headerWithCodec(
1 ✔
1796
            io.temporal.api.common.v1.Header.newBuilder()
1 ✔
1797
                .putAllFields(replayContext.getHeader())
1 ✔
1798
                .build());
1 ✔
1799
    for (ContextPropagator propagator : contextPropagators) {
1 ✔
1800
      Map<String, Payload> headerData =
1801
          propagator.encodeHeaders()
1 ✔
1802
              ? header.getCodecDecodedValues()
1 ✔
1803
              : new HashMap<>(header.getValues());
1 ✔
1804
      contextData.put(propagator.getName(), propagator.deserializeContext(headerData));
1 ✔
1805
    }
1 ✔
1806

1807
    return contextData;
1 ✔
1808
  }
1809

1810
  @Override
1811
  public VersioningBehavior getVersioningBehavior() {
1812
    return workflowDefinition.getVersioningBehavior();
1 ✔
1813
  }
1814

1815
  public void setCurrentUpdateInfo(UpdateInfo updateInfo) {
1816
    currentUpdateInfo.set(updateInfo);
1 ✔
1817
  }
1 ✔
1818

1819
  public void setCurrentDetails(String details) {
1820
    currentDetails = details;
1 ✔
1821
  }
1 ✔
1822

1823
  @Nullable
1824
  public Object getInstance() {
1825
    return workflowDefinition.getInstance();
1 ✔
1826
  }
1827

1828
  @Nullable
1829
  public String getCurrentDetails() {
1830
    return currentDetails;
1 ✔
1831
  }
1832

1833
  public Optional<UpdateInfo> getCurrentUpdateInfo() {
1834
    return Optional.ofNullable(currentUpdateInfo.get());
1 ✔
1835
  }
1836

1837
  private List<EventGroupMarker> eventGroupMarkers(List<EventGroup> directGroups) {
1838
    return EventGroupImpl.toMarkers(directGroups, dataConverterWithCurrentWorkflowContext);
1 ✔
1839
  }
1840

1841
  /** Simple wrapper over a failure just to allow completing the CompletablePromise as a failure */
1842
  private static class FailureWrapperException extends RuntimeException {
1843
    private final Failure failure;
1844

1845
    public FailureWrapperException(Failure failure) {
1 ✔
1846
      this.failure = failure;
1 ✔
1847
    }
1 ✔
1848

1849
    public Failure getFailure() {
1850
      return failure;
1 ✔
1851
    }
1852
  }
1853
}
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