• 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

59.06
/temporal-sdk/src/main/java/io/temporal/workflow/Workflow.java
1
package io.temporal.workflow;
2

3
import com.uber.m3.tally.Scope;
4
import io.temporal.activity.ActivityOptions;
5
import io.temporal.activity.LocalActivityOptions;
6
import io.temporal.api.common.v1.WorkflowExecution;
7
import io.temporal.common.Experimental;
8
import io.temporal.common.RetryOptions;
9
import io.temporal.common.SearchAttributeUpdate;
10
import io.temporal.common.SearchAttributes;
11
import io.temporal.common.converter.DataConverter;
12
import io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor;
13
import io.temporal.failure.ActivityFailure;
14
import io.temporal.failure.CanceledFailure;
15
import io.temporal.failure.ChildWorkflowFailure;
16
import io.temporal.internal.sync.WorkflowInternal;
17
import io.temporal.serviceclient.WorkflowServiceStubsOptions;
18
import io.temporal.worker.WorkerFactoryOptions;
19
import io.temporal.worker.WorkflowImplementationOptions;
20
import io.temporal.workflow.Functions.Func;
21
import io.temporal.workflow.unsafe.WorkflowUnsafe;
22
import java.lang.reflect.Type;
23
import java.time.Duration;
24
import java.time.OffsetDateTime;
25
import java.util.*;
26
import java.util.function.BiPredicate;
27
import java.util.function.Supplier;
28
import javax.annotation.Nonnull;
29
import javax.annotation.Nullable;
30
import org.slf4j.Logger;
31

32
/**
33
 * This class contains methods exposing Temporal API for Workflows, like
34
 *
35
 * <ul>
36
 *   <li>Creation and scheduling of activities, child workflows, external workflows, continue-as-new
37
 *       runs
38
 *   <li>Operations over workflow elements, like Side Effects, Timers, Versions, {@link
39
 *       CancellationScope}
40
 *   <li>Accessing and updating of the workflow data, like {@link WorkflowInfo}, Memos and Search
41
 *       Attributes
42
 *   <li>Deterministic implementation of popular non-deterministic API working with time, logging
43
 *       and generation of random values
44
 * </ul>
45
 *
46
 * Methods of this class are intended to be called from a workflow method only until explicitly
47
 * stated otherwise on the specific method's javadoc.
48
 *
49
 * <p>For an overview of Temporal JavaSDK Workflows, see {@link io.temporal.workflow}
50
 *
51
 * <p>For methods providing Temporal Workflow alternatives to threading and asynchronous
52
 * invocations, see {@link Async}
53
 *
54
 * @see io.temporal.workflow
55
 */
56
public final class Workflow {
57
  public static final int DEFAULT_VERSION = WorkflowInternal.DEFAULT_VERSION;
58

59
  /**
60
   * Creates client stub to activities that implement given interface. `
61
   *
62
   * @param activityInterface interface type implemented by activities
63
   */
64
  public static <T> T newActivityStub(Class<T> activityInterface) {
65
    return WorkflowInternal.newActivityStub(activityInterface, null, null);
1 ✔
66
  }
67

68
  /**
69
   * Creates client stub to activities that implement given interface
70
   *
71
   * @param activityInterface interface type implemented by activities.
72
   * @param options options that together with the properties of {@link
73
   *     io.temporal.activity.ActivityMethod} specify the activity invocation parameters
74
   */
75
  public static <T> T newActivityStub(Class<T> activityInterface, ActivityOptions options) {
76
    return WorkflowInternal.newActivityStub(activityInterface, options, null);
1 ✔
77
  }
78

79
  /**
80
   * Creates client stub to activities that implement given interface.
81
   *
82
   * @param activityInterface interface type implemented by activities
83
   * @param options options that together with the properties of {@link
84
   *     io.temporal.activity.ActivityMethod} specify the activity invocation parameters
85
   * @param activityMethodOptions activity method-specific invocation parameters
86
   */
87
  public static <T> T newActivityStub(
88
      Class<T> activityInterface,
89
      ActivityOptions options,
90
      Map<String, ActivityOptions> activityMethodOptions) {
91
    return WorkflowInternal.newActivityStub(activityInterface, options, activityMethodOptions);
×
92
  }
93

94
  /**
95
   * Creates non typed client stub to activities. Allows executing activities by their string name.
96
   *
97
   * @param options specify the activity invocation parameters.
98
   */
99
  public static ActivityStub newUntypedActivityStub(ActivityOptions options) {
100
    return WorkflowInternal.newUntypedActivityStub(options);
1 ✔
101
  }
102

103
  /** Executes an Activity with options that apply only to this invocation. */
104
  @Experimental
105
  public static <R> R executeActivity(
106
      Functions.Func<R> activity, ActivityInvocationOptions options) {
107
    return WorkflowInternal.executeActivity(options, activity::apply);
1 ✔
108
  }
109

110
  /** Executes an Activity with options that apply only to this invocation. */
111
  @Experimental
112
  public static <A1, R> R executeActivity(
113
      Functions.Func1<A1, R> activity, ActivityInvocationOptions options, A1 arg1) {
114
    return WorkflowInternal.executeActivity(options, () -> activity.apply(arg1));
×
115
  }
116

117
  /** Executes an Activity with options that apply only to this invocation. */
118
  @Experimental
119
  public static <A1, A2, R> R executeActivity(
120
      Functions.Func2<A1, A2, R> activity, ActivityInvocationOptions options, A1 arg1, A2 arg2) {
121
    return WorkflowInternal.executeActivity(options, () -> activity.apply(arg1, arg2));
×
122
  }
123

124
  /** Executes an Activity with options that apply only to this invocation. */
125
  @Experimental
126
  public static <A1, A2, A3, R> R executeActivity(
127
      Functions.Func3<A1, A2, A3, R> activity,
128
      ActivityInvocationOptions options,
129
      A1 arg1,
130
      A2 arg2,
131
      A3 arg3) {
132
    return WorkflowInternal.executeActivity(options, () -> activity.apply(arg1, arg2, arg3));
×
133
  }
134

135
  /** Executes an Activity with options that apply only to this invocation. */
136
  @Experimental
137
  public static <A1, A2, A3, A4, R> R executeActivity(
138
      Functions.Func4<A1, A2, A3, A4, R> activity,
139
      ActivityInvocationOptions options,
140
      A1 arg1,
141
      A2 arg2,
142
      A3 arg3,
143
      A4 arg4) {
144
    return WorkflowInternal.executeActivity(options, () -> activity.apply(arg1, arg2, arg3, arg4));
×
145
  }
146

147
  /** Executes an Activity with options that apply only to this invocation. */
148
  @Experimental
149
  public static <A1, A2, A3, A4, A5, R> R executeActivity(
150
      Functions.Func5<A1, A2, A3, A4, A5, R> activity,
151
      ActivityInvocationOptions options,
152
      A1 arg1,
153
      A2 arg2,
154
      A3 arg3,
155
      A4 arg4,
156
      A5 arg5) {
157
    return WorkflowInternal.executeActivity(
×
158
        options, () -> activity.apply(arg1, arg2, arg3, arg4, arg5));
×
159
  }
160

161
  /** Executes an Activity with options that apply only to this invocation. */
162
  @Experimental
163
  public static <A1, A2, A3, A4, A5, A6, R> R executeActivity(
164
      Functions.Func6<A1, A2, A3, A4, A5, A6, R> activity,
165
      ActivityInvocationOptions options,
166
      A1 arg1,
167
      A2 arg2,
168
      A3 arg3,
169
      A4 arg4,
170
      A5 arg5,
171
      A6 arg6) {
172
    return WorkflowInternal.executeActivity(
×
173
        options, () -> activity.apply(arg1, arg2, arg3, arg4, arg5, arg6));
×
174
  }
175

176
  /** Executes a void Activity with options that apply only to this invocation. */
177
  @Experimental
178
  public static void executeActivity(Functions.Proc activity, ActivityInvocationOptions options) {
179
    WorkflowInternal.executeActivity(options, activity);
1 ✔
180
  }
1 ✔
181

182
  /** Executes a void Activity with options that apply only to this invocation. */
183
  @Experimental
184
  public static <A1> void executeActivity(
185
      Functions.Proc1<A1> activity, ActivityInvocationOptions options, A1 arg1) {
186
    WorkflowInternal.executeActivity(options, () -> activity.apply(arg1));
×
187
  }
×
188

189
  /** Executes a void Activity with options that apply only to this invocation. */
190
  @Experimental
191
  public static <A1, A2> void executeActivity(
192
      Functions.Proc2<A1, A2> activity, ActivityInvocationOptions options, A1 arg1, A2 arg2) {
193
    WorkflowInternal.executeActivity(options, () -> activity.apply(arg1, arg2));
×
194
  }
×
195

196
  /** Executes a void Activity with options that apply only to this invocation. */
197
  @Experimental
198
  public static <A1, A2, A3> void executeActivity(
199
      Functions.Proc3<A1, A2, A3> activity,
200
      ActivityInvocationOptions options,
201
      A1 arg1,
202
      A2 arg2,
203
      A3 arg3) {
204
    WorkflowInternal.executeActivity(options, () -> activity.apply(arg1, arg2, arg3));
×
205
  }
×
206

207
  /** Executes a void Activity with options that apply only to this invocation. */
208
  @Experimental
209
  public static <A1, A2, A3, A4> void executeActivity(
210
      Functions.Proc4<A1, A2, A3, A4> activity,
211
      ActivityInvocationOptions options,
212
      A1 arg1,
213
      A2 arg2,
214
      A3 arg3,
215
      A4 arg4) {
216
    WorkflowInternal.executeActivity(options, () -> activity.apply(arg1, arg2, arg3, arg4));
×
217
  }
×
218

219
  /** Executes a void Activity with options that apply only to this invocation. */
220
  @Experimental
221
  public static <A1, A2, A3, A4, A5> void executeActivity(
222
      Functions.Proc5<A1, A2, A3, A4, A5> activity,
223
      ActivityInvocationOptions options,
224
      A1 arg1,
225
      A2 arg2,
226
      A3 arg3,
227
      A4 arg4,
228
      A5 arg5) {
229
    WorkflowInternal.executeActivity(options, () -> activity.apply(arg1, arg2, arg3, arg4, arg5));
×
230
  }
×
231

232
  /** Executes a void Activity with options that apply only to this invocation. */
233
  @Experimental
234
  public static <A1, A2, A3, A4, A5, A6> void executeActivity(
235
      Functions.Proc6<A1, A2, A3, A4, A5, A6> activity,
236
      ActivityInvocationOptions options,
237
      A1 arg1,
238
      A2 arg2,
239
      A3 arg3,
240
      A4 arg4,
241
      A5 arg5,
242
      A6 arg6) {
243
    WorkflowInternal.executeActivity(
×
244
        options, () -> activity.apply(arg1, arg2, arg3, arg4, arg5, arg6));
×
245
  }
×
246

247
  /** Starts an Activity with options that apply only to this invocation. */
248
  @Experimental
249
  public static <R> Promise<R> executeActivityAsync(
250
      Functions.Func<R> activity, ActivityInvocationOptions options) {
251
    return WorkflowInternal.executeActivityAsync(options, activity::apply);
1 ✔
252
  }
253

254
  /** Starts an Activity with options that apply only to this invocation. */
255
  @Experimental
256
  public static <A1, R> Promise<R> executeActivityAsync(
257
      Functions.Func1<A1, R> activity, ActivityInvocationOptions options, A1 arg1) {
258
    return WorkflowInternal.executeActivityAsync(options, () -> activity.apply(arg1));
1 ✔
259
  }
260

261
  /** Starts an Activity with options that apply only to this invocation. */
262
  @Experimental
263
  public static <A1, A2, R> Promise<R> executeActivityAsync(
264
      Functions.Func2<A1, A2, R> activity, ActivityInvocationOptions options, A1 arg1, A2 arg2) {
265
    return WorkflowInternal.executeActivityAsync(options, () -> activity.apply(arg1, arg2));
×
266
  }
267

268
  /** Starts an Activity with options that apply only to this invocation. */
269
  @Experimental
270
  public static <A1, A2, A3, R> Promise<R> executeActivityAsync(
271
      Functions.Func3<A1, A2, A3, R> activity,
272
      ActivityInvocationOptions options,
273
      A1 arg1,
274
      A2 arg2,
275
      A3 arg3) {
276
    return WorkflowInternal.executeActivityAsync(options, () -> activity.apply(arg1, arg2, arg3));
×
277
  }
278

279
  /** Starts an Activity with options that apply only to this invocation. */
280
  @Experimental
281
  public static <A1, A2, A3, A4, R> Promise<R> executeActivityAsync(
282
      Functions.Func4<A1, A2, A3, A4, R> activity,
283
      ActivityInvocationOptions options,
284
      A1 arg1,
285
      A2 arg2,
286
      A3 arg3,
287
      A4 arg4) {
288
    return WorkflowInternal.executeActivityAsync(
×
289
        options, () -> activity.apply(arg1, arg2, arg3, arg4));
×
290
  }
291

292
  /** Starts an Activity with options that apply only to this invocation. */
293
  @Experimental
294
  public static <A1, A2, A3, A4, A5, R> Promise<R> executeActivityAsync(
295
      Functions.Func5<A1, A2, A3, A4, A5, R> activity,
296
      ActivityInvocationOptions options,
297
      A1 arg1,
298
      A2 arg2,
299
      A3 arg3,
300
      A4 arg4,
301
      A5 arg5) {
302
    return WorkflowInternal.executeActivityAsync(
×
303
        options, () -> activity.apply(arg1, arg2, arg3, arg4, arg5));
×
304
  }
305

306
  /** Starts an Activity with options that apply only to this invocation. */
307
  @Experimental
308
  public static <A1, A2, A3, A4, A5, A6, R> Promise<R> executeActivityAsync(
309
      Functions.Func6<A1, A2, A3, A4, A5, A6, R> activity,
310
      ActivityInvocationOptions options,
311
      A1 arg1,
312
      A2 arg2,
313
      A3 arg3,
314
      A4 arg4,
315
      A5 arg5,
316
      A6 arg6) {
317
    return WorkflowInternal.executeActivityAsync(
×
318
        options, () -> activity.apply(arg1, arg2, arg3, arg4, arg5, arg6));
×
319
  }
320

321
  /** Starts a void Activity with options that apply only to this invocation. */
322
  @Experimental
323
  public static Promise<Void> executeActivityAsync(
324
      Functions.Proc activity, ActivityInvocationOptions options) {
325
    return WorkflowInternal.executeActivityAsync(options, activity);
×
326
  }
327

328
  /** Starts a void Activity with options that apply only to this invocation. */
329
  @Experimental
330
  public static <A1> Promise<Void> executeActivityAsync(
331
      Functions.Proc1<A1> activity, ActivityInvocationOptions options, A1 arg1) {
332
    return WorkflowInternal.executeActivityAsync(options, () -> activity.apply(arg1));
×
333
  }
334

335
  /** Starts a void Activity with options that apply only to this invocation. */
336
  @Experimental
337
  public static <A1, A2> Promise<Void> executeActivityAsync(
338
      Functions.Proc2<A1, A2> activity, ActivityInvocationOptions options, A1 arg1, A2 arg2) {
339
    return WorkflowInternal.executeActivityAsync(options, () -> activity.apply(arg1, arg2));
×
340
  }
341

342
  /** Starts a void Activity with options that apply only to this invocation. */
343
  @Experimental
344
  public static <A1, A2, A3> Promise<Void> executeActivityAsync(
345
      Functions.Proc3<A1, A2, A3> activity,
346
      ActivityInvocationOptions options,
347
      A1 arg1,
348
      A2 arg2,
349
      A3 arg3) {
350
    return WorkflowInternal.executeActivityAsync(options, () -> activity.apply(arg1, arg2, arg3));
×
351
  }
352

353
  /** Starts a void Activity with options that apply only to this invocation. */
354
  @Experimental
355
  public static <A1, A2, A3, A4> Promise<Void> executeActivityAsync(
356
      Functions.Proc4<A1, A2, A3, A4> activity,
357
      ActivityInvocationOptions options,
358
      A1 arg1,
359
      A2 arg2,
360
      A3 arg3,
361
      A4 arg4) {
362
    return WorkflowInternal.executeActivityAsync(
×
363
        options, () -> activity.apply(arg1, arg2, arg3, arg4));
×
364
  }
365

366
  /** Starts a void Activity with options that apply only to this invocation. */
367
  @Experimental
368
  public static <A1, A2, A3, A4, A5> Promise<Void> executeActivityAsync(
369
      Functions.Proc5<A1, A2, A3, A4, A5> activity,
370
      ActivityInvocationOptions options,
371
      A1 arg1,
372
      A2 arg2,
373
      A3 arg3,
374
      A4 arg4,
375
      A5 arg5) {
376
    return WorkflowInternal.executeActivityAsync(
×
377
        options, () -> activity.apply(arg1, arg2, arg3, arg4, arg5));
×
378
  }
379

380
  /** Starts a void Activity with options that apply only to this invocation. */
381
  @Experimental
382
  public static <A1, A2, A3, A4, A5, A6> Promise<Void> executeActivityAsync(
383
      Functions.Proc6<A1, A2, A3, A4, A5, A6> activity,
384
      ActivityInvocationOptions options,
385
      A1 arg1,
386
      A2 arg2,
387
      A3 arg3,
388
      A4 arg4,
389
      A5 arg5,
390
      A6 arg6) {
391
    return WorkflowInternal.executeActivityAsync(
×
392
        options, () -> activity.apply(arg1, arg2, arg3, arg4, arg5, arg6));
×
393
  }
394

395
  /**
396
   * Creates client stub to local activities that implement given interface.
397
   *
398
   * @param activityInterface interface type implemented by activities
399
   */
400
  public static <T> T newLocalActivityStub(Class<T> activityInterface) {
401
    return WorkflowInternal.newLocalActivityStub(activityInterface, null, null);
1 ✔
402
  }
403

404
  /**
405
   * Creates client stub to local activities that implement given interface. A local activity is
406
   * similar to a regular activity, but with some key differences: 1. Local activity is scheduled
407
   * and run by the workflow worker locally. 2. Local activity does not need Temporal server to
408
   * schedule activity task and does not rely on activity worker. 3. Local activity is for short
409
   * living activities (usually finishes within seconds). 4. Local activity cannot heartbeat.
410
   *
411
   * @param activityInterface interface type implemented by activities
412
   * @param options options that together with the properties of {@link
413
   *     io.temporal.activity.ActivityMethod} specify the activity invocation parameters.
414
   */
415
  public static <T> T newLocalActivityStub(
416
      Class<T> activityInterface, LocalActivityOptions options) {
417
    return WorkflowInternal.newLocalActivityStub(activityInterface, options, null);
1 ✔
418
  }
419

420
  /**
421
   * Creates client stub to local activities that implement given interface.
422
   *
423
   * @param activityInterface interface type implemented by activities
424
   * @param options options that together with the properties of {@link
425
   *     io.temporal.activity.ActivityMethod} specify the activity invocation parameters
426
   * @param activityMethodOptions activity method-specific invocation parameters
427
   */
428
  public static <T> T newLocalActivityStub(
429
      Class<T> activityInterface,
430
      LocalActivityOptions options,
431
      Map<String, LocalActivityOptions> activityMethodOptions) {
432
    return WorkflowInternal.newLocalActivityStub(activityInterface, options, activityMethodOptions);
×
433
  }
434

435
  /**
436
   * Creates non typed client stub to local activities. Allows executing activities by their string
437
   * name.
438
   *
439
   * @param options specify the local activity invocation parameters.
440
   */
441
  public static ActivityStub newUntypedLocalActivityStub(LocalActivityOptions options) {
442
    return WorkflowInternal.newUntypedLocalActivityStub(options);
1 ✔
443
  }
444

445
  /**
446
   * Creates client stub that can be used to start a child workflow that implements the given
447
   * interface using parent options. Child workflow options predefined through {@link
448
   * io.temporal.worker.WorkflowImplementationOptions.Builder#setChildWorkflowOptions(Map)} and
449
   * {@link io.temporal.worker.WorkflowImplementationOptions.Builder#setDefaultChildWorkflowOptions(
450
   * ChildWorkflowOptions)} are applied. Use {@link #newExternalWorkflowStub(Class, String)} to get
451
   * a stub to signal a workflow without starting it.
452
   *
453
   * @param workflowInterface interface type implemented by activities
454
   */
455
  public static <T> T newChildWorkflowStub(Class<T> workflowInterface) {
456
    return WorkflowInternal.newChildWorkflowStub(workflowInterface, null);
1 ✔
457
  }
458

459
  /**
460
   * Creates client stub that can be used to start a child workflow that implements given interface.
461
   * Use {@link #newExternalWorkflowStub(Class, String)} to get a stub to signal a workflow without
462
   * starting it.
463
   *
464
   * @param workflowInterface interface type implemented by activities
465
   * @param options options passed to the child workflow. Each non-null field overrides the
466
   *     corresponding field of the child workflow options predefined through {@link
467
   *     io.temporal.worker.WorkflowImplementationOptions.Builder#setChildWorkflowOptions(Map)} and
468
   *     {@link
469
   *     io.temporal.worker.WorkflowImplementationOptions.Builder#setDefaultChildWorkflowOptions(
470
   *     ChildWorkflowOptions)}.
471
   */
472
  public static <T> T newChildWorkflowStub(
473
      Class<T> workflowInterface, ChildWorkflowOptions options) {
474
    return WorkflowInternal.newChildWorkflowStub(workflowInterface, options);
1 ✔
475
  }
476

477
  /**
478
   * Creates client stub that can be used to communicate to an existing workflow execution.
479
   *
480
   * @param workflowInterface interface type implemented by activities
481
   * @param workflowId id of the workflow to communicate with.
482
   */
483
  public static <R> R newExternalWorkflowStub(
484
      Class<? extends R> workflowInterface, String workflowId) {
485
    WorkflowExecution execution = WorkflowExecution.newBuilder().setWorkflowId(workflowId).build();
1 ✔
486
    return WorkflowInternal.newExternalWorkflowStub(workflowInterface, execution);
1 ✔
487
  }
488

489
  /**
490
   * Creates client stub that can be used to communicate to an existing workflow execution.
491
   *
492
   * @param workflowInterface interface type implemented by activities
493
   * @param execution execution of the workflow to communicate with.
494
   */
495
  public static <R> R newExternalWorkflowStub(
496
      Class<? extends R> workflowInterface, WorkflowExecution execution) {
497
    return WorkflowInternal.newExternalWorkflowStub(workflowInterface, execution);
1 ✔
498
  }
499

500
  /**
501
   * Extracts workflow execution from a stub created through {@link #newChildWorkflowStub(Class,
502
   * ChildWorkflowOptions)} or {@link #newExternalWorkflowStub(Class, String)}. Wrapped in a Promise
503
   * as child workflow start is asynchronous. For an external workflow the returned promise is
504
   * already completed.
505
   */
506
  public static Promise<WorkflowExecution> getWorkflowExecution(Object workflowStub) {
507
    return WorkflowInternal.getWorkflowExecution(workflowStub);
1 ✔
508
  }
509

510
  /**
511
   * Creates untyped client stub that can be used to start and signal a child workflow.
512
   *
513
   * @param workflowType name of the workflow type to start.
514
   * @param options options passed to the child workflow. Each non-null field overrides the
515
   *     corresponding field of the child workflow options predefined through {@link
516
   *     io.temporal.worker.WorkflowImplementationOptions.Builder#setChildWorkflowOptions(Map)} and
517
   *     {@link
518
   *     io.temporal.worker.WorkflowImplementationOptions.Builder#setDefaultChildWorkflowOptions(
519
   *     ChildWorkflowOptions)}.
520
   */
521
  public static ChildWorkflowStub newUntypedChildWorkflowStub(
522
      String workflowType, ChildWorkflowOptions options) {
523
    return WorkflowInternal.newUntypedChildWorkflowStub(workflowType, options);
1 ✔
524
  }
525

526
  /**
527
   * Creates untyped client stub that can be used to start and signal a child workflow. All options
528
   * are inherited from the parent, except for the child workflow options predefined through {@link
529
   * io.temporal.worker.WorkflowImplementationOptions.Builder#setChildWorkflowOptions(Map)} and
530
   * {@link io.temporal.worker.WorkflowImplementationOptions.Builder#setDefaultChildWorkflowOptions(
531
   * ChildWorkflowOptions)}, which are applied.
532
   *
533
   * @param workflowType name of the workflow type to start.
534
   */
535
  public static ChildWorkflowStub newUntypedChildWorkflowStub(String workflowType) {
536
    return WorkflowInternal.newUntypedChildWorkflowStub(workflowType, null);
1 ✔
537
  }
538

539
  /**
540
   * Creates untyped client stub that can be used to signal or cancel an existing workflow
541
   * execution.
542
   *
543
   * @param execution execution of the workflow to communicate with.
544
   */
545
  public static ExternalWorkflowStub newUntypedExternalWorkflowStub(WorkflowExecution execution) {
546
    return WorkflowInternal.newUntypedExternalWorkflowStub(execution);
1 ✔
547
  }
548

549
  /**
550
   * Creates untyped client stub that can be used to signal or cancel an existing workflow
551
   * execution.
552
   *
553
   * @param workflowId id of the workflow to communicate with.
554
   */
555
  public static ExternalWorkflowStub newUntypedExternalWorkflowStub(String workflowId) {
556
    WorkflowExecution execution = WorkflowExecution.newBuilder().setWorkflowId(workflowId).build();
1 ✔
557
    return Workflow.newUntypedExternalWorkflowStub(execution);
1 ✔
558
  }
559

560
  /**
561
   * Creates a client stub that can be used to continue this workflow as a new run.
562
   *
563
   * @param workflowInterface an interface type implemented by the next run of the workflow
564
   */
565
  public static <T> T newContinueAsNewStub(
566
      Class<T> workflowInterface, ContinueAsNewOptions options) {
567
    return WorkflowInternal.newContinueAsNewStub(workflowInterface, options);
1 ✔
568
  }
569

570
  /**
571
   * Creates a client stub that can be used to continue this workflow as a new run.
572
   *
573
   * @param workflowInterface an interface type implemented by the next run of the workflow
574
   */
575
  public static <T> T newContinueAsNewStub(Class<T> workflowInterface) {
576
    return WorkflowInternal.newContinueAsNewStub(workflowInterface, null);
1 ✔
577
  }
578

579
  /**
580
   * Continues the current workflow execution as a new run with the same options.
581
   *
582
   * @param args arguments of the next run.
583
   * @see #newContinueAsNewStub(Class)
584
   */
585
  public static void continueAsNew(Object... args) {
586
    Workflow.continueAsNew(null, args);
×
587
  }
×
588

589
  /**
590
   * Continues the current workflow execution as a new run with the same workflowType and overridden
591
   * {@code options}.
592
   *
593
   * @param options option overrides for the next run, can contain null if no overrides are needed
594
   * @param args arguments of the next run.
595
   * @see #newContinueAsNewStub(Class, ContinueAsNewOptions)
596
   */
597
  public static void continueAsNew(@Nullable ContinueAsNewOptions options, Object... args) {
598
    Workflow.continueAsNew(null, options, args);
×
599
  }
×
600

601
  /**
602
   * Continues the current workflow execution as a new run possibly overriding the workflow type and
603
   * options.
604
   *
605
   * @param workflowType workflow type override for the next run, can contain null if no override is
606
   *     needed
607
   * @param options option overrides for the next run, can contain null if no overrides are needed
608
   * @param args arguments of the next run.
609
   * @see #newContinueAsNewStub(Class)
610
   * @deprecated use {@link #continueAsNew(String, ContinueAsNewOptions, Object...)}
611
   */
612
  @Deprecated
613
  public static void continueAsNew(
614
      Optional<String> workflowType, Optional<ContinueAsNewOptions> options, Object... args) {
615
    WorkflowInternal.continueAsNew(workflowType.orElse(null), options.orElse(null), args);
×
616
  }
×
617

618
  /**
619
   * Continues the current workflow execution as a new run possibly overriding the workflow type and
620
   * options.
621
   *
622
   * @param workflowType workflow type override for the next run, can be null of no override is
623
   *     needed
624
   * @param options option overrides for the next run, can be null if no overrides are needed
625
   * @param args arguments of the next run.
626
   * @see #newContinueAsNewStub(Class)
627
   */
628
  public static void continueAsNew(
629
      @Nullable String workflowType, @Nullable ContinueAsNewOptions options, Object... args) {
630
    WorkflowInternal.continueAsNew(workflowType, options, args);
×
631
  }
×
632

633
  /**
634
   * Returns information about current workflow execution.
635
   *
636
   * <p>Note: Can only be called within the context of a workflow. Will throw an error if called
637
   * outside a workflow context.
638
   *
639
   * @return current workflow info.
640
   */
641
  public static WorkflowInfo getInfo() {
642
    return WorkflowInternal.getWorkflowInfo();
1 ✔
643
  }
644

645
  /**
646
   * Returns information about current workflow update.
647
   *
648
   * <p>Note: Should only be called within the context of an update handler thread in a workflow.
649
   * Will return an empty Optional if called outside an update handler thread inside a workflow
650
   * context. Will throw an error if called outside a workflow context.
651
   *
652
   * @return current workflow update info.
653
   */
654
  public static Optional<UpdateInfo> getCurrentUpdateInfo() {
655
    return WorkflowInternal.getCurrentUpdateInfo();
1 ✔
656
  }
657

658
  /**
659
   * Extract deserialized Memo associated with given key
660
   *
661
   * @param key memo key
662
   * @param valueClass Java class to deserialize into
663
   * @return deserialized Memo or null if the key is not present in the memo
664
   */
665
  public static <T> Object getMemo(String key, Class<T> valueClass) {
666
    return getMemo(key, valueClass, valueClass);
1 ✔
667
  }
668

669
  /**
670
   * Extract Memo associated with the given key and deserialized into an object of generic type as
671
   * is done here: {@link DataConverter#fromPayloads(int, java.util.Optional, java.lang.Class,
672
   * java.lang.reflect.Type)} Ex: To deserialize into {@code HashMap<String, Integer>} {@code
673
   * Workflow.getMemo(key, Map.class, new TypeToken<HashMap<String, Integer>>() {}.getType())}
674
   *
675
   * @param key memo key
676
   * @param valueClass Java class to deserialize into
677
   * @param genericType type parameter for the generic class
678
   * @return deserialized Memo or null if the key is not present in the memo
679
   */
680
  public static <T> T getMemo(String key, Class<T> valueClass, Type genericType) {
681
    return WorkflowInternal.getMemo(key, valueClass, genericType);
1 ✔
682
  }
683

684
  /**
685
   * Wraps the Runnable method argument in a {@link CancellationScope}. The {@link
686
   * CancellationScope#run()} calls {@link Runnable#run()} on the wrapped Runnable. The returned
687
   * CancellationScope can be used to cancel the wrapped code. The cancellation semantic depends on
688
   * the operation the code is blocked on. For example activity or child workflow is first canceled
689
   * then throws a {@link CanceledFailure}. The same applies for {@link Workflow#sleep(long)}
690
   * operation. When an activity or a child workflow is invoked asynchronously then they get
691
   * canceled and a {@link Promise} that contains their result will throw {@link CanceledFailure}
692
   * when {@link Promise#get()} is called.
693
   *
694
   * <p>The new cancellation scope {@link CancellationScope#current()} is linked to the parent one.
695
   * If the parent one is canceled then all the children scopes are wrapped within a root
696
   * cancellation scope which gets canceled when a workflow is canceled through the Temporal
697
   * CancelWorkflowExecution API. To perform cleanup operations that require blocking after the
698
   * current scope is canceled use a scope created through {@link
699
   * #newDetachedCancellationScope(Runnable)}.
700
   *
701
   * <p>Example of running activities in parallel and cancelling them after a specified timeout.
702
   *
703
   * <pre><code>
704
   *     List&lt;Promise&lt;String&gt;&gt; results = new ArrayList&lt;&gt;();
705
   *     CancellationScope scope = Workflow.newDetachedCancellationScope(() -&gt; {
706
   *        Async.function(activities::a1);
707
   *        Async.function(activities::a2);
708
   *     });
709
   *     scope.run(); // returns immediately as the activities are invoked asynchronously
710
   *     Workflow.sleep(Duration.ofHours(1));
711
   *     // Cancels any activity in the scope that is still running
712
   *     scope.cancel("one hour passed");
713
   *
714
   * </code></pre>
715
   *
716
   * @param runnable parameter to wrap in a cancellation scope.
717
   * @return wrapped parameter.
718
   */
719
  public static CancellationScope newCancellationScope(Runnable runnable) {
720
    return WorkflowInternal.newCancellationScope(false, runnable);
1 ✔
721
  }
722

723
  /**
724
   * Wraps a procedure in a CancellationScope. The procedure receives the wrapping CancellationScope
725
   * as a parameter. Useful when cancellation is requested from within the wrapped code. The
726
   * following example cancels the sibling activity on any failure.
727
   *
728
   * <pre><code>
729
   *               Workflow.newCancellationScope(
730
   *                   (scope) -&gt; {
731
   *                     Promise<Void> p1 = Async.proc(activities::a1).exceptionally(ex-&gt;
732
   *                        {
733
   *                           scope.cancel("a1 failed");
734
   *                           return null;
735
   *                        });
736
   *
737
   *                     Promise<Void> p2 = Async.proc(activities::a2).exceptionally(ex-&gt;
738
   *                        {
739
   *                           scope.cancel("a2 failed");
740
   *                           return null;
741
   *                        });
742
   *                     Promise.allOf(p1, p2).get();
743
   *                   })
744
   *               .run();
745
   * </code></pre>
746
   *
747
   * @param proc code to wrap in the cancellation scope
748
   * @return wrapped proc
749
   */
750
  public static CancellationScope newCancellationScope(Functions.Proc1<CancellationScope> proc) {
751
    return WorkflowInternal.newCancellationScope(false, proc);
1 ✔
752
  }
753

754
  /**
755
   * Creates a CancellationScope {@link CancellationScope#run()} that is not linked to a parent
756
   * scope must be called to execute the code the scope wraps. The detached scope is needed to
757
   * execute cleanup code after a workflow is canceled which cancels the root scope that wraps
758
   * the @WorkflowMethod invocation. Here is an example usage:
759
   *
760
   * <pre><code>
761
   *  try {
762
   *     // workflow logic
763
   *  } catch (CanceledFailure e) {
764
   *     CancellationScope detached = Workflow.newDetachedCancellationScope(() -&gt; {
765
   *         // cleanup logic
766
   *     });
767
   *     detached.run();
768
   *  }
769
   * </code></pre>
770
   *
771
   * @param runnable parameter to wrap in a cancellation scope.
772
   * @return wrapped parameter.
773
   * @see #newCancellationScope(Runnable)
774
   */
775
  public static CancellationScope newDetachedCancellationScope(Runnable runnable) {
776
    return WorkflowInternal.newCancellationScope(true, runnable);
1 ✔
777
  }
778

779
  /**
780
   * Create new timer. Note that Temporal service time resolution is in seconds. So all durations
781
   * are rounded <b>up</b> to the nearest second.
782
   *
783
   * @return feature that becomes ready when at least specified number of seconds passes. promise is
784
   *     failed with {@link CanceledFailure} if enclosing scope is canceled.
785
   */
786
  public static Promise<Void> newTimer(Duration delay) {
787
    return WorkflowInternal.newTimer(delay);
1 ✔
788
  }
789

790
  /**
791
   * Create new timer with options. Note that Temporal service time resolution is in seconds. So all
792
   * durations are rounded <b>up</b> to the nearest second.
793
   *
794
   * @return feature that becomes ready when at least specified number of seconds passes. promise is
795
   *     failed with {@link CanceledFailure} if enclosing scope is canceled.
796
   */
797
  public static Promise<Void> newTimer(Duration delay, TimerOptions options) {
798
    return WorkflowInternal.newTimer(delay, options);
1 ✔
799
  }
800

801
  /**
802
   * @deprecated use {@link #newWorkflowQueue(int)} instead. An implementation returned by this
803
   *     method has a bug.
804
   */
805
  @Deprecated
806
  public static <E> WorkflowQueue<E> newQueue(int capacity) {
807
    return WorkflowInternal.newQueue(capacity);
×
808
  }
809

810
  /**
811
   * Create a new instance of a {@link WorkflowQueue} implementation that is adapted to be used from
812
   * a workflow code.
813
   *
814
   * @param capacity the maximum size of the queue
815
   * @return new instance of {@link WorkflowQueue}
816
   */
817
  public static <E> WorkflowQueue<E> newWorkflowQueue(int capacity) {
818
    return WorkflowInternal.newWorkflowQueue(capacity);
×
819
  }
820

821
  public static <E> CompletablePromise<E> newPromise() {
822
    return WorkflowInternal.newCompletablePromise();
1 ✔
823
  }
824

825
  public static <E> Promise<E> newPromise(E value) {
826
    return WorkflowInternal.newPromise(value);
1 ✔
827
  }
828

829
  public static <E> Promise<E> newFailedPromise(Exception failure) {
830
    return WorkflowInternal.newFailedPromise(failure);
1 ✔
831
  }
832

833
  /**
834
   * Creates an {@link EventGroup}, which can be used to associate related workflow commands so that
835
   * their resulting history events can be presented together in UI/CLI.
836
   *
837
   * @param id ID of the group. Must not be empty. Commands associated with groups that have the
838
   *     same ID are presented together, even if they were associated with distinct {@link
839
   *     EventGroup} instances.
840
   * @see EventGroup
841
   */
842
  @Experimental
843
  public static EventGroup newEventGroup(String id) {
844
    return WorkflowInternal.newEventGroup(id, null);
1 ✔
845
  }
846

847
  /**
848
   * Creates an {@link EventGroup} with options, such as a display label.
849
   *
850
   * @param id ID of the group. Must not be empty. Commands associated with groups that have the
851
   *     same ID are presented together, even if they were associated with distinct {@link
852
   *     EventGroup} instances, or have different labels.
853
   * @param options options of the group.
854
   * @see #newEventGroup(String)
855
   */
856
  @Experimental
857
  public static EventGroup newEventGroup(String id, EventGroupOptions options) {
858
    return WorkflowInternal.newEventGroup(id, options);
1 ✔
859
  }
860

861
  /**
862
   * Creates a {@link WorkflowLock} implementation that can be used from workflow code.
863
   *
864
   * <p>Note: The lock returned is not reentrant. If a workflow thread tries to acquire a lock that
865
   * it already holds, the call will block indefinitely.
866
   *
867
   * @return new instance of {@link WorkflowLock}
868
   */
869
  public static WorkflowLock newWorkflowLock() {
UNCOV
870
    return WorkflowInternal.newWorkflowLock();
×
871
  }
872

873
  /**
874
   * Creates a {@link WorkflowSemaphore} implementation that can be used from workflow code.
875
   *
876
   * @param permits the given number of permits for the semaphore.
877
   * @return new instance of {@link WorkflowSemaphore}
878
   */
879
  public static WorkflowSemaphore newWorkflowSemaphore(int permits) {
UNCOV
880
    return WorkflowInternal.newWorkflowSemaphore(permits);
×
881
  }
882

883
  /**
884
   * Registers an implementation object. The object must implement at least one interface annotated
885
   * with {@link WorkflowInterface}. All its methods annotated with @{@link SignalMethod}
886
   * and @{@link QueryMethod} are registered.
887
   *
888
   * <p>There is no need to register the top level workflow implementation object as it is done
889
   * implicitly by the framework on object startup.
890
   *
891
   * <p>An attempt to register a duplicated query is going to fail with {@link
892
   * IllegalArgumentException}
893
   */
894
  public static void registerListener(Object listener) {
895
    WorkflowInternal.registerListener(listener);
1 ✔
896
  }
1 ✔
897

898
  /**
899
   * Must be used to get current time instead of {@link System#currentTimeMillis()} to guarantee
900
   * determinism.
901
   */
902
  public static long currentTimeMillis() {
903
    return WorkflowInternal.currentTimeMillis();
1 ✔
904
  }
905

906
  /** Must be called instead of {@link Thread#sleep(long)} to guarantee determinism. */
907
  public static void sleep(Duration duration) {
908
    WorkflowInternal.sleep(duration);
1 ✔
909
  }
1 ✔
910

911
  /** Must be called instead of {@link Thread#sleep(long)} to guarantee determinism. */
912
  public static void sleep(long millis) {
913
    WorkflowInternal.sleep(Duration.ofMillis(millis));
1 ✔
914
  }
1 ✔
915

916
  /**
917
   * Must be called instead of {@link Thread#sleep(long)} to guarantee determinism.
918
   *
919
   * @param duration time to sleep.
920
   * @param options options for the underlying timer, such as its summary.
921
   * @see #newTimer(Duration, TimerOptions)
922
   */
923
  public static void sleep(Duration duration, TimerOptions options) {
924
    WorkflowInternal.sleep(duration, options);
1 ✔
925
  }
1 ✔
926

927
  /**
928
   * Must be called instead of {@link Thread#sleep(long)} to guarantee determinism.
929
   *
930
   * @param millis time to sleep, in milliseconds.
931
   * @param options options for the underlying timer, such as its summary.
932
   * @see #newTimer(Duration, TimerOptions)
933
   */
934
  public static void sleep(long millis, TimerOptions options) {
UNCOV
935
    WorkflowInternal.sleep(Duration.ofMillis(millis), options);
×
UNCOV
936
  }
×
937

938
  /**
939
   * Block current thread until unblockCondition is evaluated to true.
940
   *
941
   * @param unblockCondition condition that should return true to indicate that thread should
942
   *     unblock. The condition is called on every state transition, so it should never call any
943
   *     blocking operations or contain code that mutates any workflow state. It should also not
944
   *     contain any time based conditions. Use {@link #await(Duration, Supplier)} for those
945
   *     instead.
946
   * @throws CanceledFailure if thread (or current {@link CancellationScope} was canceled).
947
   */
948
  public static void await(Supplier<Boolean> unblockCondition) {
949
    WorkflowInternal.await(
1 ✔
950
        "await",
951
        () -> {
952
          CancellationScope.throwCanceled();
1 ✔
953
          return unblockCondition.get();
1 ✔
954
        });
955
  }
1 ✔
956

957
  /**
958
   * Block current workflow thread until unblockCondition is evaluated to true or timeoutMillis
959
   * passes.
960
   *
961
   * @param timeout time to unblock even if unblockCondition is not satisfied.
962
   * @param unblockCondition condition that should return true to indicate that thread should
963
   *     unblock. The condition is called on every state transition, so it should not contain any
964
   *     code that mutates any workflow state. It should also not contain any time based conditions.
965
   *     Use timeout parameter for those.
966
   * @return false if timed out.
967
   * @throws CanceledFailure if thread (or current {@link CancellationScope} was canceled).
968
   */
969
  public static boolean await(Duration timeout, Supplier<Boolean> unblockCondition) {
970
    return WorkflowInternal.await(
1 ✔
971
        timeout,
972
        "await",
973
        () -> {
974
          CancellationScope.throwCanceled();
1 ✔
975
          return unblockCondition.get();
1 ✔
976
        });
977
  }
978

979
  /**
980
   * Block current workflow thread until unblockCondition is evaluated to true or timeout passes.
981
   *
982
   * @param timeout time to unblock even if unblockCondition is not satisfied.
983
   * @param options options for the timer that implements the timeout, such as its summary.
984
   * @param unblockCondition condition that should return true to indicate that thread should
985
   *     unblock. The condition is called on every state transition, so it should not contain any
986
   *     code that mutates any workflow state. It should also not contain any time based conditions.
987
   *     Use timeout parameter for those.
988
   * @return false if timed out.
989
   * @throws CanceledFailure if thread (or current {@link CancellationScope} was canceled).
990
   * @see #newTimer(Duration, TimerOptions)
991
   */
992
  public static boolean await(
993
      Duration timeout, TimerOptions options, Supplier<Boolean> unblockCondition) {
994
    return WorkflowInternal.await(
1 ✔
995
        timeout,
996
        options,
997
        "await",
998
        () -> {
999
          CancellationScope.throwCanceled();
1 ✔
1000
          return unblockCondition.get();
1 ✔
1001
        });
1002
  }
1003

1004
  /**
1005
   * Invokes function retrying in case of failures according to retry options. Synchronous variant.
1006
   * Use {@link Async#retry(RetryOptions, Optional, Functions.Func)} for asynchronous functions.
1007
   *
1008
   * @param options retry options that specify retry policy
1009
   * @param expiration stop retrying after this interval if provided
1010
   * @param fn function to invoke and retry
1011
   * @return result of the function or the last failure.
1012
   */
1013
  public static <R> R retry(
1014
      RetryOptions options, Optional<Duration> expiration, Functions.Func<R> fn) {
UNCOV
1015
    return WorkflowInternal.retry(options, expiration, fn);
×
1016
  }
1017

1018
  /**
1019
   * Invokes function retrying in case of failures according to retry options. Synchronous variant.
1020
   * Use {@link Async#retry(RetryOptions, Optional, Functions.Func)} for asynchronous functions.
1021
   *
1022
   * @param options retry options that specify retry policy
1023
   * @param expiration if specified stop retrying after this interval
1024
   * @param proc procedure to invoke and retry
1025
   */
1026
  public static void retry(
1027
      RetryOptions options, Optional<Duration> expiration, Functions.Proc proc) {
UNCOV
1028
    WorkflowInternal.retry(
×
1029
        options,
1030
        expiration,
1031
        () -> {
UNCOV
1032
          proc.apply();
×
UNCOV
1033
          return null;
×
1034
        });
UNCOV
1035
  }
×
1036

1037
  /**
1038
   * If there is a need to return a checked exception from a workflow implementation do not add the
1039
   * exception to a method signature but wrap it using this method before rethrowing. The library
1040
   * code will unwrap it automatically using when propagating exception to a remote caller. {@link
1041
   * RuntimeException} are just returned from this method without modification.
1042
   *
1043
   * <p>The reason for such design is that returning originally thrown exception from a remote call
1044
   * (which child workflow and activity invocations are ) would not allow adding context information
1045
   * about a failure, like activity and child workflow id. So stubs always throw a subclass of
1046
   * {@link ActivityFailure} from calls to an activity and subclass of {@link ChildWorkflowFailure}
1047
   * from calls to a child workflow. The original exception is attached as a cause to these wrapper
1048
   * exceptions. So as exceptions are always wrapped adding checked ones to method signature causes
1049
   * more pain than benefit.
1050
   *
1051
   * <pre>
1052
   * try {
1053
   *     return someCall();
1054
   * } catch (Exception e) {
1055
   *     throw Workflow.wrap(e);
1056
   * }
1057
   * </pre>
1058
   *
1059
   * @return CheckedExceptionWrapper if e is checked or original exception if e extends
1060
   *     RuntimeException.
1061
   */
1062
  public static RuntimeException wrap(Exception e) {
1063
    return WorkflowInternal.wrap(e);
1 ✔
1064
  }
1065

1066
  /**
1067
   * Replay safe way to generate UUID.
1068
   *
1069
   * <p>Must be used instead of {@link UUID#randomUUID()} which relies on a random generator, thus
1070
   * leads to non-deterministic code which is prohibited inside a workflow.
1071
   */
1072
  public static UUID randomUUID() {
1073
    return WorkflowInternal.randomUUID();
1 ✔
1074
  }
1075

1076
  /** Replay safe random numbers generator. Seeded differently for each workflow instance. */
1077
  public static Random newRandom() {
1078
    return WorkflowInternal.newRandom();
1 ✔
1079
  }
1080

1081
  /**
1082
   * True if workflow code is being replayed.
1083
   *
1084
   * <p><b>Warning!</b> Never make workflow logic depend on this flag as it is going to break
1085
   * determinism. The only reasonable uses for this flag are deduping external never failing side
1086
   * effects like logging or metric reporting.
1087
   *
1088
   * <p>This method always returns false if called from a non workflow thread.
1089
   *
1090
   * @deprecated use {@link WorkflowUnsafe#isReplaying()}
1091
   */
1092
  @Deprecated
1093
  public static boolean isReplaying() {
UNCOV
1094
    return WorkflowUnsafe.isReplaying();
×
1095
  }
1096

1097
  /**
1098
   * Executes the provided function once, records its result into the workflow history. The recorded
1099
   * result on history will be returned without executing the provided function during replay. This
1100
   * guarantees the deterministic requirement for workflow as the exact same result will be returned
1101
   * in replay. Common use case is to run some short non-deterministic code in workflow, like
1102
   * getting random number. The only way to fail SideEffect is to panic which causes workflow task
1103
   * failure. The workflow task after timeout is rescheduled and re-executed giving SideEffect
1104
   * another chance to succeed.
1105
   *
1106
   * <p>Caution: do not use sideEffect function to modify any workflow state. Only use the
1107
   * SideEffect's return value. For example this code is BROKEN:
1108
   *
1109
   * <pre><code>
1110
   *  // Bad example:
1111
   *  AtomicInteger random = new AtomicInteger();
1112
   *  Workflow.sideEffect(() -&gt; {
1113
   *         random.set(random.nextInt(100));
1114
   *         return null;
1115
   *  });
1116
   *  // random will always be 0 in replay, thus this code is non-deterministic
1117
   *  if random.get() &lt; 50 {
1118
   *         ....
1119
   *  } else {
1120
   *         ....
1121
   *  }
1122
   * </code></pre>
1123
   *
1124
   * On replay the provided function is not executed, the random will always be 0, and the workflow
1125
   * could take a different path breaking the determinism.
1126
   *
1127
   * <p>Here is the correct way to use sideEffect:
1128
   *
1129
   * <pre><code>
1130
   *  // Good example:
1131
   *  int random = Workflow.sideEffect(Integer.class, () -&gt; random.nextInt(100));
1132
   *  if random &lt; 50 {
1133
   *         ....
1134
   *  } else {
1135
   *         ....
1136
   *  }
1137
   * </code></pre>
1138
   *
1139
   * If function throws any exception it is not delivered to the workflow code. It is wrapped in
1140
   * {@link Error} causing failure of the current workflow task.
1141
   *
1142
   * @param resultClass type of the side effect
1143
   * @param func function that returns side effect value
1144
   * @return value of the side effect
1145
   * @see #mutableSideEffect(String, Class, BiPredicate, Functions.Func)
1146
   */
1147
  public static <R> R sideEffect(Class<R> resultClass, Func<R> func) {
1148
    return WorkflowInternal.sideEffect(resultClass, resultClass, func);
1 ✔
1149
  }
1150

1151
  /**
1152
   * Executes the provided function once, records its result into the workflow history. The recorded
1153
   * result on history will be returned without executing the provided function during replay. This
1154
   * guarantees the deterministic requirement for workflow as the exact same result will be returned
1155
   * in replay. Common use case is to run some short non-deterministic code in workflow, like
1156
   * getting random number. The only way to fail SideEffect is to panic which causes workflow task
1157
   * failure. The workflow task after timeout is rescheduled and re-executed giving SideEffect
1158
   * another chance to succeed.
1159
   *
1160
   * <p>Caution: do not use sideEffect function to modify any workflow state. Only use the
1161
   * SideEffect's return value. For example this code is BROKEN:
1162
   *
1163
   * <pre><code>
1164
   *  // Bad example:
1165
   *  AtomicInteger random = new AtomicInteger();
1166
   *  Workflow.sideEffect(() -&gt; {
1167
   *         random.set(random.nextInt(100));
1168
   *         return null;
1169
   *  });
1170
   *  // random will always be 0 in replay, thus this code is non-deterministic
1171
   *  if random.get() &lt; 50 {
1172
   *         ....
1173
   *  } else {
1174
   *         ....
1175
   *  }
1176
   * </code></pre>
1177
   *
1178
   * On replay the provided function is not executed, the random will always be 0, and the workflow
1179
   * could take a different path breaking the determinism.
1180
   *
1181
   * <p>Here is the correct way to use sideEffect:
1182
   *
1183
   * <pre><code>
1184
   *  // Good example:
1185
   *  int random = Workflow.sideEffect(Integer.class, () -&gt; random.nextInt(100));
1186
   *  if random &lt; 50 {
1187
   *         ....
1188
   *  } else {
1189
   *         ....
1190
   *  }
1191
   * </code></pre>
1192
   *
1193
   * If function throws any exception it is not delivered to the workflow code. It is wrapped in
1194
   * {@link Error} causing failure of the current workflow task.
1195
   *
1196
   * @param resultClass class of the side effect
1197
   * @param resultType type of the side effect. Differs from resultClass for generic types.
1198
   * @param func function that returns side effect value
1199
   * @return value of the side effect
1200
   * @see #mutableSideEffect(String, Class, BiPredicate, Functions.Func)
1201
   */
1202
  public static <R> R sideEffect(Class<R> resultClass, Type resultType, Func<R> func) {
UNCOV
1203
    return WorkflowInternal.sideEffect(resultClass, resultType, func);
×
1204
  }
1205

1206
  /**
1207
   * Executes the provided function once, records its result into the workflow history. The recorded
1208
   * result on history will be returned without executing the provided function during replay. This
1209
   * guarantees the deterministic requirement for workflow as the exact same result will be returned
1210
   * in replay. Common use case is to run some short non-deterministic code in workflow, like
1211
   * getting random number. The only way to fail SideEffect is to panic which causes workflow task
1212
   * failure. The workflow task after timeout is rescheduled and re-executed giving SideEffect
1213
   * another chance to succeed.
1214
   *
1215
   * <p>Caution: do not use sideEffect function to modify any workflow state. Only use the
1216
   * SideEffect's return value. For example this code is BROKEN:
1217
   *
1218
   * <pre><code>
1219
   *  // Bad example:
1220
   *  AtomicInteger random = new AtomicInteger();
1221
   *  Workflow.sideEffect(() -&gt; {
1222
   *         random.set(random.nextInt(100));
1223
   *         return null;
1224
   *  });
1225
   *  // random will always be 0 in replay, thus this code is non-deterministic
1226
   *  if random.get() &lt; 50 {
1227
   *         ....
1228
   *  } else {
1229
   *         ....
1230
   *  }
1231
   * </code></pre>
1232
   *
1233
   * On replay the provided function is not executed, the random will always be 0, and the workflow
1234
   * could take a different path breaking the determinism.
1235
   *
1236
   * <p>Here is the correct way to use sideEffect:
1237
   *
1238
   * <pre><code>
1239
   *  // Good example:
1240
   *  int random = Workflow.sideEffect(Integer.class, () -&gt; random.nextInt(100));
1241
   *  if random &lt; 50 {
1242
   *         ....
1243
   *  } else {
1244
   *         ....
1245
   *  }
1246
   * </code></pre>
1247
   *
1248
   * If function throws any exception it is not delivered to the workflow code. It is wrapped in
1249
   * {@link Error} causing failure of the current workflow task.
1250
   *
1251
   * @param resultClass class of the side effect
1252
   * @param func function that returns side effect value
1253
   * @param options side effect options
1254
   * @return value of the side effect
1255
   * @see #mutableSideEffect(String, Class, BiPredicate, Functions.Func)
1256
   */
1257
  public static <R> R sideEffect(Class<R> resultClass, Func<R> func, SideEffectOptions options) {
1258
    return WorkflowInternal.sideEffect(resultClass, resultClass, func, options);
1 ✔
1259
  }
1260

1261
  /**
1262
   * Executes the provided function once, records its result into the workflow history. The recorded
1263
   * result on history will be returned without executing the provided function during replay. This
1264
   * guarantees the deterministic requirement for workflow as the exact same result will be returned
1265
   * in replay. Common use case is to run some short non-deterministic code in workflow, like
1266
   * getting random number. The only way to fail SideEffect is to panic which causes workflow task
1267
   * failure. The workflow task after timeout is rescheduled and re-executed giving SideEffect
1268
   * another chance to succeed.
1269
   *
1270
   * <p>Caution: do not use sideEffect function to modify any workflow state. Only use the
1271
   * SideEffect's return value. For example this code is BROKEN:
1272
   *
1273
   * <pre><code>
1274
   *  // Bad example:
1275
   *  AtomicInteger random = new AtomicInteger();
1276
   *  Workflow.sideEffect(() -&gt; {
1277
   *         random.set(random.nextInt(100));
1278
   *         return null;
1279
   *  });
1280
   *  // random will always be 0 in replay, thus this code is non-deterministic
1281
   *  if random.get() &lt; 50 {
1282
   *         ....
1283
   *  } else {
1284
   *         ....
1285
   *  }
1286
   * </code></pre>
1287
   *
1288
   * On replay the provided function is not executed, the random will always be 0, and the workflow
1289
   * could take a different path breaking the determinism.
1290
   *
1291
   * <p>Here is the correct way to use sideEffect:
1292
   *
1293
   * <pre><code>
1294
   *  // Good example:
1295
   *  int random = Workflow.sideEffect(Integer.class, () -&gt; random.nextInt(100));
1296
   *  if random &lt; 50 {
1297
   *         ....
1298
   *  } else {
1299
   *         ....
1300
   *  }
1301
   * </code></pre>
1302
   *
1303
   * If function throws any exception it is not delivered to the workflow code. It is wrapped in
1304
   * {@link Error} causing failure of the current workflow task.
1305
   *
1306
   * @param resultClass class of the side effect
1307
   * @param resultType type of the side effect. Differs from resultClass for generic types.
1308
   * @param func function that returns side effect value
1309
   * @param options side effect options
1310
   * @return value of the side effect
1311
   * @see #mutableSideEffect(String, Class, BiPredicate, Functions.Func)
1312
   */
1313
  public static <R> R sideEffect(
1314
      Class<R> resultClass, Type resultType, Func<R> func, SideEffectOptions options) {
UNCOV
1315
    return WorkflowInternal.sideEffect(resultClass, resultType, func, options);
×
1316
  }
1317

1318
  /**
1319
   * {@code mutableSideEffect} is similar to {@link #sideEffect(Class, Functions.Func)} in allowing
1320
   * calls of non-deterministic functions from workflow code.
1321
   *
1322
   * <p>The difference between {@code mutableSideEffect} and {@link #sideEffect(Class,
1323
   * Functions.Func)} is that every new {@code sideEffect} call in non-replay mode results in a new
1324
   * marker event recorded into the history. However, {@code mutableSideEffect} only records a new
1325
   * marker if a value has changed. During the replay, {@code mutableSideEffect} will not execute
1326
   * the function again, but it will return the exact same value as it was returning during the
1327
   * non-replay run.
1328
   *
1329
   * <p>One good use case of {@code mutableSideEffect} is to access a dynamically changing config
1330
   * without breaking determinism. Even if called very frequently the config value is recorded only
1331
   * when it changes not causing any performance degradation due to a large history size.
1332
   *
1333
   * <p>Caution: do not use {@code mutableSideEffect} function to modify any workflow state. Only
1334
   * use the mutableSideEffect's return value.
1335
   *
1336
   * <p>If function throws any exception it is not delivered to the workflow code. It is wrapped in
1337
   * {@link Error} causing failure of the current workflow task.
1338
   *
1339
   * @param id unique identifier of this side effect
1340
   * @param updated used to decide if a new value should be recorded. A func result is recorded only
1341
   *     if call to updated with stored and a new value as arguments returns true. It is not called
1342
   *     for the first value.
1343
   * @param resultClass class of the side effect
1344
   * @param func function that produces a value. This function can contain non-deterministic code.
1345
   * @see #sideEffect(Class, Functions.Func)
1346
   */
1347
  public static <R> R mutableSideEffect(
1348
      String id, Class<R> resultClass, BiPredicate<R, R> updated, Func<R> func) {
1349
    return WorkflowInternal.mutableSideEffect(id, resultClass, resultClass, updated, func);
1 ✔
1350
  }
1351

1352
  /**
1353
   * {@code mutableSideEffect} is similar to {@link #sideEffect(Class, Functions.Func)} in allowing
1354
   * calls of non-deterministic functions from workflow code.
1355
   *
1356
   * <p>The difference between {@code mutableSideEffect} and {@link #sideEffect(Class,
1357
   * Functions.Func)} is that every new {@code sideEffect} call in non-replay mode results in a new
1358
   * marker event recorded into the history. However, {@code mutableSideEffect} only records a new
1359
   * marker if a value has changed. During the replay, {@code mutableSideEffect} will not execute
1360
   * the function again, but it will return the exact same value as it was returning during the
1361
   * non-replay run.
1362
   *
1363
   * <p>One good use case of {@code mutableSideEffect} is to access a dynamically changing config
1364
   * without breaking determinism. Even if called very frequently the config value is recorded only
1365
   * when it changes not causing any performance degradation due to a large history size.
1366
   *
1367
   * <p>Caution: do not use {@code mutableSideEffect} function to modify any workflow state. Only
1368
   * use the mutableSideEffect's return value.
1369
   *
1370
   * <p>If function throws any exception it is not delivered to the workflow code. It is wrapped in
1371
   * {@link Error} causing failure of the current workflow task.
1372
   *
1373
   * @param id unique identifier of this side effect
1374
   * @param updated used to decide if a new value should be recorded. A func result is recorded only
1375
   *     if call to updated with stored and a new value as arguments returns true. It is not called
1376
   *     for the first value.
1377
   * @param resultClass class of the side effect
1378
   * @param resultType type of the side effect. Differs from resultClass for generic types.
1379
   * @param func function that produces a value. This function can contain non-deterministic code.
1380
   * @see #sideEffect(Class, Functions.Func)
1381
   */
1382
  public static <R> R mutableSideEffect(
1383
      String id, Class<R> resultClass, Type resultType, BiPredicate<R, R> updated, Func<R> func) {
UNCOV
1384
    return WorkflowInternal.mutableSideEffect(id, resultClass, resultType, updated, func);
×
1385
  }
1386

1387
  /**
1388
   * {@code mutableSideEffect} is similar to {@link #sideEffect(Class, Functions.Func)} in allowing
1389
   * calls of non-deterministic functions from workflow code.
1390
   *
1391
   * <p>The difference between {@code mutableSideEffect} and {@link #sideEffect(Class,
1392
   * Functions.Func)} is that every new {@code sideEffect} call in non-replay mode results in a new
1393
   * marker event recorded into the history. However, {@code mutableSideEffect} only records a new
1394
   * marker if a value has changed. During the replay, {@code mutableSideEffect} will not execute
1395
   * the function again, but it will return the exact same value as it was returning during the
1396
   * non-replay run.
1397
   *
1398
   * <p>One good use case of {@code mutableSideEffect} is to access a dynamically changing config
1399
   * without breaking determinism. Even if called very frequently the config value is recorded only
1400
   * when it changes not causing any performance degradation due to a large history size.
1401
   *
1402
   * <p>Caution: do not use {@code mutableSideEffect} function to modify any workflow state. Only
1403
   * use the mutableSideEffect's return value.
1404
   *
1405
   * <p>If function throws any exception it is not delivered to the workflow code. It is wrapped in
1406
   * {@link Error} causing failure of the current workflow task.
1407
   *
1408
   * @param id unique identifier of this side effect
1409
   * @param updated used to decide if a new value should be recorded. A func result is recorded only
1410
   *     if call to updated with stored and a new value as arguments returns true. It is not called
1411
   *     for the first value.
1412
   * @param resultClass class of the side effect
1413
   * @param func function that produces a value. This function can contain non-deterministic code.
1414
   * @param options options for mutable side effect
1415
   * @see #sideEffect(Class, Functions.Func)
1416
   */
1417
  public static <R> R mutableSideEffect(
1418
      String id,
1419
      Class<R> resultClass,
1420
      BiPredicate<R, R> updated,
1421
      Func<R> func,
1422
      MutableSideEffectOptions options) {
1423
    return WorkflowInternal.mutableSideEffect(id, resultClass, resultClass, updated, func, options);
1 ✔
1424
  }
1425

1426
  /**
1427
   * {@code mutableSideEffect} is similar to {@link #sideEffect(Class, Functions.Func)} in allowing
1428
   * calls of non-deterministic functions from workflow code.
1429
   *
1430
   * <p>The difference between {@code mutableSideEffect} and {@link #sideEffect(Class,
1431
   * Functions.Func)} is that every new {@code sideEffect} call in non-replay mode results in a new
1432
   * marker event recorded into the history. However, {@code mutableSideEffect} only records a new
1433
   * marker if a value has changed. During the replay, {@code mutableSideEffect} will not execute
1434
   * the function again, but it will return the exact same value as it was returning during the
1435
   * non-replay run.
1436
   *
1437
   * <p>One good use case of {@code mutableSideEffect} is to access a dynamically changing config
1438
   * without breaking determinism. Even if called very frequently the config value is recorded only
1439
   * when it changes not causing any performance degradation due to a large history size.
1440
   *
1441
   * <p>Caution: do not use {@code mutableSideEffect} function to modify any workflow state. Only
1442
   * use the mutableSideEffect's return value.
1443
   *
1444
   * <p>If function throws any exception it is not delivered to the workflow code. It is wrapped in
1445
   * {@link Error} causing failure of the current workflow task.
1446
   *
1447
   * @param id unique identifier of this side effect
1448
   * @param updated used to decide if a new value should be recorded. A func result is recorded only
1449
   *     if call to updated with stored and a new value as arguments returns true. It is not called
1450
   *     for the first value.
1451
   * @param resultClass class of the side effect
1452
   * @param resultType type of the side effect. Differs from resultClass for generic types.
1453
   * @param func function that produces a value. This function can contain non-deterministic code.
1454
   * @param options options for mutable side effect
1455
   * @see #sideEffect(Class, Functions.Func)
1456
   */
1457
  public static <R> R mutableSideEffect(
1458
      String id,
1459
      Class<R> resultClass,
1460
      Type resultType,
1461
      BiPredicate<R, R> updated,
1462
      Func<R> func,
1463
      MutableSideEffectOptions options) {
UNCOV
1464
    return WorkflowInternal.mutableSideEffect(id, resultClass, resultType, updated, func, options);
×
1465
  }
1466

1467
  /**
1468
   * {@code getVersion} is used to safely perform backwards incompatible changes to workflow
1469
   * definitions. It is not allowed to update workflow code while there are workflows running as it
1470
   * is going to break determinism. The solution is to have both old code that is used to replay
1471
   * existing workflows as well as the new one that is used when it is executed for the first time.\
1472
   *
1473
   * <p>{@code getVersion} returns maxSupported version when it is executed for the first time,
1474
   * unless the worker has a {@link io.temporal.worker.PreferredVersionProvider} configured. This
1475
   * version is recorded into the workflow history as a marker event. Even if maxSupported version
1476
   * or the worker preference is changed, the version that was recorded is returned on replay.
1477
   * DefaultVersion constant contains version of code that wasn't versioned before.
1478
   *
1479
   * <p>For example initially workflow has the following code:
1480
   *
1481
   * <pre><code>
1482
   * result = testActivities.activity1();
1483
   * </code></pre>
1484
   *
1485
   * it should be updated to
1486
   *
1487
   * <pre><code>
1488
   * result = testActivities.activity2();
1489
   * </code></pre>
1490
   *
1491
   * The backwards compatible way to execute the update is
1492
   *
1493
   * <pre><code>
1494
   * int version = Workflow.getVersion("fooChange", Workflow.DEFAULT_VERSION, 1);
1495
   * String result;
1496
   * if (version == Workflow.DEFAULT_VERSION) {
1497
   *   result = testActivities.activity1();
1498
   * } else {
1499
   *   result = testActivities.activity2();
1500
   * }
1501
   * </code></pre>
1502
   *
1503
   * Then later if we want to have another change:
1504
   *
1505
   * <pre><code>
1506
   * int version = Workflow.getVersion("fooChange", Workflow.DEFAULT_VERSION, 2);
1507
   * String result;
1508
   * if (version == Workflow.DEFAULT_VERSION) {
1509
   *   result = testActivities.activity1();
1510
   * } else if (version == 1) {
1511
   *   result = testActivities.activity2();
1512
   * } else {
1513
   *   result = testActivities.activity3();
1514
   * }
1515
   * </code></pre>
1516
   *
1517
   * Later when there are no workflow executions running DefaultVersion the correspondent branch can
1518
   * be removed:
1519
   *
1520
   * <pre><code>
1521
   * int version = Workflow.getVersion("fooChange", 1, 2);
1522
   * String result;
1523
   * if (version == 1) {
1524
   *   result = testActivities.activity2();
1525
   * } else {
1526
   *   result = testActivities.activity3();
1527
   * }
1528
   * </code></pre>
1529
   *
1530
   * It is recommended to keep the GetVersion() call even if single branch is left:
1531
   *
1532
   * <pre><code>
1533
   * Workflow.getVersion("fooChange", 2, 2);
1534
   * result = testActivities.activity3();
1535
   * </code></pre>
1536
   *
1537
   * The reason to keep it is: 1) it ensures that if there is older version execution still running,
1538
   * it will fail here and not proceed; 2) if you ever need to make more changes for “fooChange”,
1539
   * for example change activity3 to activity4, you just need to update the maxVersion from 2 to 3.
1540
   *
1541
   * <p>Note that, you only need to preserve the first call to GetVersion() for each changeId. All
1542
   * subsequent calls to GetVersion() with same changeId are safe to remove. However, if you really
1543
   * want to get rid of the first GetVersion() call as well, you can do so, but you need to make
1544
   * sure: 1) all older version executions are completed; 2) you can no longer use “fooChange” as
1545
   * changeId. If you ever need to make changes to that same part, you would need to use a different
1546
   * changeId like “fooChange-fix2”, and start minVersion from DefaultVersion again.
1547
   *
1548
   * @param changeId identifier of a particular change. All calls to getVersion that share a
1549
   *     changeId are guaranteed to return the same version number. Use this to perform multiple
1550
   *     coordinated changes that should be enabled together.
1551
   * @param minSupported min version supported for the change
1552
   * @param maxSupported max version supported for the change, this version is used as the current
1553
   *     one during the original execution.
1554
   * @return {@code maxSupported} when is originally executed. Original version recorded in the
1555
   *     history on replays.
1556
   */
1557
  public static int getVersion(String changeId, int minSupported, int maxSupported) {
1558
    return WorkflowInternal.getVersion(changeId, minSupported, maxSupported);
1 ✔
1559
  }
1560

1561
  /**
1562
   * Same as {@link #getVersion(String, int, int)}, with options such as Event Groups to associate
1563
   * with the version marker and with the associated search attribute update.
1564
   *
1565
   * @param changeId identifier of a particular change. All calls to getVersion that share a
1566
   *     changeId are guaranteed to return the same version number. Use this to perform multiple
1567
   *     coordinated changes that should be enabled together.
1568
   * @param minSupported min version supported for the change
1569
   * @param maxSupported max version supported for the change
1570
   * @param options options of the call
1571
   * @return {@code maxSupported} when is originally executed. Original version recorded in the
1572
   *     history on replays.
1573
   */
1574
  public static int getVersion(
1575
      String changeId, int minSupported, int maxSupported, GetVersionOptions options) {
1576
    return WorkflowInternal.getVersion(changeId, minSupported, maxSupported, options);
1 ✔
1577
  }
1578

1579
  /**
1580
   * Get scope for reporting business metrics in workflow logic. This should be used instead of
1581
   * creating new metrics scopes as it is able to dedupe metrics during replay.
1582
   *
1583
   * <p>The original metrics scope is set through {@link
1584
   * WorkflowServiceStubsOptions.Builder#setMetricsScope(Scope)} when a worker starts up.
1585
   */
1586
  public static Scope getMetricsScope() {
1587
    return WorkflowInternal.getMetricsScope();
1 ✔
1588
  }
1589

1590
  /**
1591
   * Get logger to use inside workflow. Logs in replay mode are omitted unless {@link
1592
   * WorkerFactoryOptions.Builder#setEnableLoggingInReplay(boolean)} is set to {@code true}.
1593
   *
1594
   * @param clazz class name to appear in logging.
1595
   * @return logger to use in workflow logic.
1596
   */
1597
  public static Logger getLogger(Class<?> clazz) {
1598
    return WorkflowInternal.getLogger(clazz);
1 ✔
1599
  }
1600

1601
  /**
1602
   * Get logger to use inside workflow. Logs in replay mode are omitted unless {@link
1603
   * WorkerFactoryOptions.Builder#setEnableLoggingInReplay(boolean)} is set to {@code true}.
1604
   *
1605
   * @param name name to appear in logging.
1606
   * @return logger to use in workflow logic.
1607
   */
1608
  public static Logger getLogger(String name) {
UNCOV
1609
    return WorkflowInternal.getLogger(name);
×
1610
  }
1611

1612
  /**
1613
   * GetLastCompletionResult extract last completion result from previous run for this cron
1614
   * workflow. This is used in combination with cron schedule. A workflow can be started with an
1615
   * optional cron schedule. If a cron workflow wants to pass some data to next schedule, it can
1616
   * return any data and that data will become available when next run starts.
1617
   *
1618
   * @param resultClass class of the return data from last run
1619
   * @return result of last run
1620
   * @see io.temporal.client.WorkflowOptions.Builder#setCronSchedule(String)
1621
   */
1622
  public static <R> R getLastCompletionResult(Class<R> resultClass) {
1623
    return WorkflowInternal.getLastCompletionResult(resultClass, resultClass);
1 ✔
1624
  }
1625

1626
  /**
1627
   * Extract the latest failure from a previous run of this workflow. If any previous run of this
1628
   * workflow has failed, this function returns that failure. If no previous runs have failed, an
1629
   * empty optional is returned. The run you are calling this from may have been created as a retry
1630
   * of the previous failed run or as a next cron invocation for cron workflows.
1631
   *
1632
   * @return The last {@link Exception} that occurred in this workflow, if there has been one.
1633
   */
1634
  public static Optional<Exception> getPreviousRunFailure() {
1635
    return WorkflowInternal.getPreviousRunFailure();
1 ✔
1636
  }
1637

1638
  /**
1639
   * GetLastCompletionResult extract last completion result from previous run for this cron
1640
   * workflow. This is used in combination with cron schedule. A workflow can be started with an
1641
   * optional cron schedule. If a cron workflow wants to pass some data to next schedule, it can
1642
   * return any data and that data will become available when next run starts.
1643
   *
1644
   * @param resultClass class of the return data from last run
1645
   * @param resultType type of the return data from last run. Differs from resultClass for generic
1646
   *     types.
1647
   * @return result of last run
1648
   */
1649
  public static <R> R getLastCompletionResult(Class<R> resultClass, Type resultType) {
UNCOV
1650
    return WorkflowInternal.getLastCompletionResult(resultClass, resultType);
×
1651
  }
1652

1653
  /**
1654
   * Get a single search attribute.
1655
   *
1656
   * @param name search attribute name
1657
   * @return deserialized search attribute value
1658
   * @throws IllegalStateException if the search attribute value is a collection of multiple (&gt;
1659
   *     1) elements
1660
   * @deprecated use {@link #getTypedSearchAttributes} instead.
1661
   */
1662
  @Deprecated
1663
  @Nullable
1664
  public static <T> T getSearchAttribute(String name) {
1665
    return WorkflowInternal.getSearchAttribute(name);
1 ✔
1666
  }
1667

1668
  /**
1669
   * Collection returned from this method is immutable. To modify search attributes associated with
1670
   * this workflow use {@link #upsertSearchAttributes(Map)}.
1671
   *
1672
   * <p>Note: This method never returns an empty list. Empty list is considered an absent value for
1673
   * search attributes and will be returned as {@code null}.
1674
   *
1675
   * @param name search attribute name
1676
   * @return immutable list of deserialized search attribute values
1677
   * @deprecated use {@link #getTypedSearchAttributes} instead.
1678
   */
1679
  @Deprecated
1680
  @Nullable
1681
  public static <T> List<T> getSearchAttributeValues(String name) {
UNCOV
1682
    return WorkflowInternal.getSearchAttributeValues(name);
×
1683
  }
1684

1685
  /**
1686
   * Map returned from this method is immutable. To modify search attributes associated with this
1687
   * workflow use {@link #upsertSearchAttributes(Map)}.
1688
   *
1689
   * @return immutable map of search attribute names to deserialized values.
1690
   * @deprecated use {@link #getTypedSearchAttributes} instead.
1691
   */
1692
  @Deprecated
1693
  @Nonnull
1694
  public static Map<String, List<?>> getSearchAttributes() {
1695
    return WorkflowInternal.getSearchAttributes();
1 ✔
1696
  }
1697

1698
  /**
1699
   * Get immutable set of search attributes. To modify search attributes associated with this
1700
   * workflow use {@link #upsertTypedSearchAttributes}.
1701
   *
1702
   * @return immutable set of search attributes.
1703
   */
1704
  @Nonnull
1705
  public static SearchAttributes getTypedSearchAttributes() {
1706
    return WorkflowInternal.getTypedSearchAttributes();
1 ✔
1707
  }
1708

1709
  /**
1710
   * Updates Workflow Search Attributes by merging {@code searchAttributes} to the existing Search
1711
   * Attributes map attached to the workflow. Search Attributes are additional indexed information
1712
   * attributed to workflow and used for search and visibility.
1713
   *
1714
   * <p>The search attributes can be used in query of List/Scan/Count workflow APIs. The key and its
1715
   * value type must be registered on Temporal server side.
1716
   *
1717
   * <p>Supported Java types of the value:
1718
   *
1719
   * <ul>
1720
   *   <li>{@link String}
1721
   *   <li>{@link Long}, {@link Integer}, {@link Short}, {@link Byte}
1722
   *   <li>{@link Boolean}
1723
   *   <li>{@link Double}
1724
   *   <li>{@link OffsetDateTime}
1725
   *   <li>{@link Collection} of the types above
1726
   *   <li>{@link io.temporal.common.SearchAttribute#UNSET_VALUE} can be used to unset or remove the
1727
   *       search attribute
1728
   * </ul>
1729
   *
1730
   * For example, workflow code:
1731
   *
1732
   * <pre><code>
1733
   *     Map&lt;String, Object&gt; attr1 = new HashMap&lt;&gt;();
1734
   *     attr1.put("CustomIntField", 1);
1735
   *     attr1.put("CustomBoolField", true);
1736
   *     Workflow.upsertSearchAttributes(attr1);
1737
   *
1738
   *     Map&lt;String, Object&gt; attr2 = new HashMap&lt;&gt;();
1739
   *     attr2.put("CustomIntField", Lists.newArrayList(1, 2));
1740
   *     attr2.put("CustomKeywordField", "Seattle");
1741
   *     Workflow.upsertSearchAttributes(attr2);
1742
   * </pre></code> will eventually have search attributes as:
1743
   *
1744
   * <pre><code>
1745
   *     {
1746
   *       "CustomIntField": 1, 2,
1747
   *       "CustomBoolField": true,
1748
   *       "CustomKeywordField": "Seattle",
1749
   *     }
1750
   * </pre></code>
1751
   *
1752
   * @param searchAttributes map of String to Object value that can be used to search in list APIs
1753
   * @deprecated use {@link #upsertTypedSearchAttributes} instead.
1754
   */
1755
  // WorkflowOptions#setSearchAttributes docs needs to be kept in sync with this method
1756
  @Deprecated
1757
  public static void upsertSearchAttributes(Map<String, ?> searchAttributes) {
1758
    WorkflowInternal.upsertSearchAttributes(searchAttributes);
1 ✔
1759
  }
1 ✔
1760

1761
  /**
1762
   * Updates Workflow Search Attributes by applying {@code searchAttributeUpdates} to the existing
1763
   * Search Attributes set attached to the workflow. Search Attributes are additional indexed
1764
   * information attributed to workflow and used for search and visibility.
1765
   *
1766
   * <p>The search attributes can be used in query of List/Scan/Count workflow APIs. The key and its
1767
   * value type must be registered on Temporal server side.
1768
   *
1769
   * @param searchAttributeUpdates set of updates to apply to search attributes.
1770
   */
1771
  public static void upsertTypedSearchAttributes(
1772
      SearchAttributeUpdate<?>... searchAttributeUpdates) {
1773
    WorkflowInternal.upsertTypedSearchAttributes(searchAttributeUpdates);
1 ✔
1774
  }
1 ✔
1775

1776
  /**
1777
   * Same as {@link #upsertTypedSearchAttributes(SearchAttributeUpdate[])}, with options such as
1778
   * Event Groups to associate with the update.
1779
   *
1780
   * @param options options of the update.
1781
   * @param searchAttributeUpdates set of updates to apply to search attributes.
1782
   */
1783
  public static void upsertTypedSearchAttributes(
1784
      UpsertSearchAttributesOptions options, SearchAttributeUpdate<?>... searchAttributeUpdates) {
1785
    WorkflowInternal.upsertTypedSearchAttributes(options, searchAttributeUpdates);
1 ✔
1786
  }
1 ✔
1787

1788
  /**
1789
   * Updates a Workflow Memos by applying {@code memoUpdates} to the existing Memos set attached to
1790
   * the workflow. Memos are additional non-indexed information attributed to workflow and can
1791
   * return by describing or listing a workflow. The type of value can be any object that are
1792
   * serializable by {@link io.temporal.common.converter.DataConverter}. To remove a memo set the
1793
   * value null.
1794
   */
1795
  public static void upsertMemo(Map<String, Object> memo) {
1796
    WorkflowInternal.upsertMemo(memo);
1 ✔
1797
  }
1 ✔
1798

1799
  /**
1800
   * Same as {@link #upsertMemo(Map)}, with options such as Event Groups to associate with the
1801
   * update.
1802
   */
1803
  public static void upsertMemo(Map<String, Object> memo, UpsertMemoOptions options) {
1804
    WorkflowInternal.upsertMemo(memo, options);
1 ✔
1805
  }
1 ✔
1806

1807
  /**
1808
   * Sets the default activity options that will be used for activity stubs that have no {@link
1809
   * ActivityOptions} specified.<br>
1810
   * This overrides a value provided by {@link
1811
   * WorkflowImplementationOptions#getDefaultActivityOptions}.<br>
1812
   * A more specific per-activity-type option specified in {@link
1813
   * WorkflowImplementationOptions#getActivityOptions} or {@link #applyActivityOptions(Map)} takes
1814
   * precedence over this setting.
1815
   *
1816
   * @param defaultActivityOptions {@link ActivityOptions} to be used as a default
1817
   */
1818
  public static void setDefaultActivityOptions(ActivityOptions defaultActivityOptions) {
1819
    WorkflowInternal.setDefaultActivityOptions(defaultActivityOptions);
1 ✔
1820
  }
1 ✔
1821

1822
  /**
1823
   * @deprecated use {@link #applyActivityOptions(Map)}
1824
   */
1825
  @Deprecated
1826
  public static void setActivityOptions(Map<String, ActivityOptions> activityMethodOptions) {
UNCOV
1827
    WorkflowInternal.applyActivityOptions(activityMethodOptions);
×
UNCOV
1828
  }
×
1829

1830
  /**
1831
   * Adds activity options per activity type that will be used for an activity stub that has no
1832
   * {@link ActivityOptions} specified.<br>
1833
   * This method refines an original set of {@code Map<String, ActivityOptions>} provided by {@link
1834
   * WorkflowImplementationOptions#getActivityOptions()}<br>
1835
   * These more specific options take precedence over more generic setting {@link
1836
   * #setDefaultActivityOptions}
1837
   *
1838
   * <p>If an activity type already has a {@link ActivityOptions} set by an earlier call to this
1839
   * method or from {@link WorkflowImplementationOptions#getDefaultActivityOptions}, new {@link
1840
   * ActivityOptions} from {@code activityTypeToOptions} will be merged into the old ones using
1841
   * {@link ActivityOptions.Builder#mergeActivityOptions(ActivityOptions)}
1842
   *
1843
   * @param activityTypeToOptions a map of activity types to {@link ActivityOptions}
1844
   */
1845
  public static void applyActivityOptions(Map<String, ActivityOptions> activityTypeToOptions) {
1846
    WorkflowInternal.applyActivityOptions(activityTypeToOptions);
1 ✔
1847
  }
1 ✔
1848

1849
  /**
1850
   * Sets the default local activity options that will be used for activity stubs that have no
1851
   * {@link LocalActivityOptions} specified.<br>
1852
   * This overrides a value provided by {@link
1853
   * WorkflowImplementationOptions#getDefaultLocalActivityOptions}.<br>
1854
   * A more specific per-activity-type option specified in {@link
1855
   * WorkflowImplementationOptions#getLocalActivityOptions} or {@link
1856
   * #applyLocalActivityOptions(Map)} takes precedence over this setting.
1857
   *
1858
   * @param defaultLocalActivityOptions {@link LocalActivityOptions} to be used as a default
1859
   */
1860
  public static void setDefaultLocalActivityOptions(
1861
      LocalActivityOptions defaultLocalActivityOptions) {
1862
    WorkflowInternal.setDefaultLocalActivityOptions(defaultLocalActivityOptions);
1 ✔
1863
  }
1 ✔
1864

1865
  /**
1866
   * Adds local activity options per activity type that will be used for a local activity stub that
1867
   * has no {@link LocalActivityOptions} specified.<br>
1868
   * This method refines an original set of {@code Map<String, LocalActivityOptions>} provided by
1869
   * {@link WorkflowImplementationOptions#getLocalActivityOptions()}<br>
1870
   * These more specific options take precedence over more generic setting {@link
1871
   * #setDefaultLocalActivityOptions}
1872
   *
1873
   * <p>If an activity type already has a {@link LocalActivityOptions} set by an earlier call to
1874
   * this method or from {@link WorkflowImplementationOptions#getDefaultLocalActivityOptions}, new
1875
   * {@link LocalActivityOptions} from {@code activityTypeToOptions} will be merged into the old
1876
   * ones using {@link LocalActivityOptions.Builder#mergeActivityOptions(LocalActivityOptions)}
1877
   *
1878
   * @param activityTypeToOptions a map of activity types to {@link LocalActivityOptions}
1879
   */
1880
  public static void applyLocalActivityOptions(
1881
      Map<String, LocalActivityOptions> activityTypeToOptions) {
1882
    WorkflowInternal.applyLocalActivityOptions(activityTypeToOptions);
1 ✔
1883
  }
1 ✔
1884

1885
  /**
1886
   * Checks if all update and signal handlers have finished executing.
1887
   *
1888
   * <p>Consider waiting on this condition before workflow return or continue-as-new, to prevent
1889
   * interruption of in-progress handlers by workflow return:
1890
   *
1891
   * <pre><code>
1892
   *    Workflow.await(() -&gt; Workflow.isEveryHandlerFinished());
1893
   *  </pre></code> will eventually have search attributes as:
1894
   *
1895
   * @return true if all handlers are finished, false otherwise.
1896
   */
1897
  public static boolean isEveryHandlerFinished() {
1898
    return WorkflowInternal.isEveryHandlerFinished();
1 ✔
1899
  }
1900

1901
  /**
1902
   * Creates a Nexus service stub that can be used to start Nexus operations on the given service
1903
   * interface.
1904
   *
1905
   * @param service interface that given service implements.
1906
   */
1907
  public static <T> T newNexusServiceStub(Class<T> service) {
1908
    return WorkflowInternal.newNexusServiceStub(service, null);
1 ✔
1909
  }
1910

1911
  /**
1912
   * Creates a Nexus service stub that can be used to start Nexus operations on the given service
1913
   * interface.
1914
   *
1915
   * @param service interface that given service implements.
1916
   * @param options options passed to the Nexus service.
1917
   */
1918
  public static <T> T newNexusServiceStub(Class<T> service, NexusServiceOptions options) {
1919
    return WorkflowInternal.newNexusServiceStub(service, options);
1 ✔
1920
  }
1921

1922
  /**
1923
   * Creates untyped nexus service stub that can be used to execute Nexus operations.
1924
   *
1925
   * @param service name of the service the operation is part of.
1926
   * @param options options passed to the Nexus service.
1927
   */
1928
  public static NexusServiceStub newUntypedNexusServiceStub(
1929
      String service, NexusServiceOptions options) {
1930
    return WorkflowInternal.newUntypedNexusServiceStub(service, options);
1 ✔
1931
  }
1932

1933
  /**
1934
   * Start a nexus operation.
1935
   *
1936
   * @param operation The only supported value is method reference to a proxy created through {@link
1937
   *     #newNexusServiceStub(Class)}.
1938
   * @param arg operation argument
1939
   * @return OperationHandle a handle to the operation.
1940
   */
1941
  public static <T, R> NexusOperationHandle<R> startNexusOperation(
1942
      Functions.Func1<T, R> operation, T arg) {
1943
    return WorkflowInternal.startNexusOperation(operation, arg);
1 ✔
1944
  }
1945

1946
  /**
1947
   * Start a Nexus operation.
1948
   *
1949
   * @param operation The only supported value is method reference to a proxy created through {@link
1950
   *     #newNexusServiceStub(Class)}.
1951
   * @return OperationHandle a handle to the operation.
1952
   */
1953
  public static <R> NexusOperationHandle<R> startNexusOperation(Functions.Func<R> operation) {
1954
    return WorkflowInternal.startNexusOperation(operation);
1 ✔
1955
  }
1956

1957
  /**
1958
   * Sets the current workflows details.
1959
   *
1960
   * @param details details to set
1961
   */
1962
  public static void setCurrentDetails(String details) {
1963
    WorkflowInternal.setCurrentDetails(details);
1 ✔
1964
  }
1 ✔
1965

1966
  /**
1967
   * Get the current workflows details.
1968
   *
1969
   * @return details of the current workflow
1970
   */
1971
  @Nullable
1972
  public static String getCurrentDetails() {
1973
    return WorkflowInternal.getCurrentDetails();
1 ✔
1974
  }
1975

1976
  /**
1977
   * Get the currently running workflow instance.
1978
   *
1979
   * <p>Note: The instance is only available after it has been initialized. This function will
1980
   * return null if called before the workflow has been initialized. For example, this could happen
1981
   * if the function is called from a {@link WorkflowInit} constructor or {@link
1982
   * io.temporal.common.interceptors.WorkflowInboundCallsInterceptor#init(WorkflowOutboundCallsInterceptor)}.
1983
   */
1984
  @Experimental
1985
  @Nullable
1986
  public static Object getInstance() {
1987
    return WorkflowInternal.getInstance();
1 ✔
1988
  }
1989

1990
  /** Prohibit instantiation. */
1991
  private Workflow() {}
1992
}
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