Interface ReplayWorkflowContext

All Superinterfaces:
ReplayAware

public interface ReplayWorkflowContext extends ReplayAware
Represents the context of workflow for workflow code. Should only be used within the scope of workflow code, meaning any code which is not part of activity implementations. Provides access to state machine operations and information that should be accessible to the workflow code. Accumulates some state from the workflow execution like search attributes, continue-as-new.

TODO(maxim): Get rid of any Exceptions in the callbacks. They should only return Failure.

  • Method Details

    • getWorkflowExecution

      io.temporal.api.common.v1.WorkflowExecution getWorkflowExecution()
    • getParentWorkflowExecution

      io.temporal.api.common.v1.WorkflowExecution getParentWorkflowExecution()
    • getRootWorkflowExecution

      io.temporal.api.common.v1.WorkflowExecution getRootWorkflowExecution()
    • getWorkflowType

      io.temporal.api.common.v1.WorkflowType getWorkflowType()
    • getRunId

      @Nonnull String getRunId()
      Note: RunId is unique identifier of one workflow code execution. Reset changes RunId.
      Returns:
      Workflow Run ID that is handled by the current workflow code execution.
      See Also:
    • getFirstExecutionRunId

      @Nonnull String getFirstExecutionRunId()
      Returns:
      The very first original RunId of the current Workflow Execution preserved along the chain of ContinueAsNew, Retry, Cron and Reset. Identifies the whole Runs chain of Workflow Execution.
    • getContinuedExecutionRunId

      Optional<String> getContinuedExecutionRunId()
      Returns:
      Run ID of the previous Workflow Run which continued-as-new or retried or cron-scheduled into the current Workflow Run.
    • getOriginalExecutionRunId

      @Nonnull String getOriginalExecutionRunId()
      Note: This value is NOT preserved by continue-as-new, retries or cron Runs. They are separate Runs of one Workflow Execution Chain.
      Returns:
      original RunId of the current Workflow Run. This value is preserved during Reset which changes RunID.
      See Also:
    • getTaskQueue

      String getTaskQueue()
      Workflow task queue name.
    • getRetryOptions

      @Nullable RetryOptions getRetryOptions()
    • getNamespace

      String getNamespace()
      Workflow namespace.
    • getWorkflowId

      String getWorkflowId()
    • getWorkflowRunTimeout

      Duration getWorkflowRunTimeout()
      Returns:
      Timeout for a Workflow Run specified during Workflow start in WorkflowOptions.Builder.setWorkflowRunTimeout(Duration)
    • getWorkflowExecutionTimeout

      Duration getWorkflowExecutionTimeout()
      Returns:
      Timeout for the Workflow Execution specified during Workflow start in WorkflowOptions.Builder.setWorkflowExecutionTimeout(Duration)
    • getRunStartedTimestampMillis

      long getRunStartedTimestampMillis()
    • getWorkflowTaskTimeout

      @Nonnull Duration getWorkflowTaskTimeout()
    • getMemo

      io.temporal.api.common.v1.Payload getMemo(String key)
    • scheduleActivityTask

      ReplayWorkflowContext.ScheduleActivityTaskOutput scheduleActivityTask(ExecuteActivityParameters parameters, Functions.Proc2<Optional<io.temporal.api.common.v1.Payloads>,io.temporal.api.failure.v1.Failure> callback)
      Requests an activity execution.
      Parameters:
      parameters - An object which encapsulates all the information required to schedule an activity for execution
      callback - Callback that is called upon activity completion or failure.
      Returns:
      cancellation handle. Invoke Functions.Proc1.apply(Object) to cancel activity task.
    • scheduleLocalActivityTask

      Functions.Proc scheduleLocalActivityTask(ExecuteLocalActivityParameters parameters, LocalActivityCallback callback)
    • startChildWorkflow

      Functions.Proc1<Exception> startChildWorkflow(StartChildWorkflowExecutionParameters parameters, Functions.Proc2<io.temporal.api.common.v1.WorkflowExecution,Exception> startCallback, Functions.Proc2<Optional<io.temporal.api.common.v1.Payloads>,Exception> completionCallback)
      Start a child workflow.
      Parameters:
      parameters - encapsulates all the information required to schedule a child workflow for execution
      startCallback - callback that is called upon child start or failure to start
      completionCallback - callback that is called upon child workflow completion or failure
      Returns:
      cancellation handle. Invoke Functions.Proc1.apply(Object) to cancel activity task.
    • startNexusOperation

      Functions.Proc1<Exception> startNexusOperation(StartNexusOperationParameters parameters, Functions.Proc2<Optional<String>,io.temporal.api.failure.v1.Failure> startedCallback, Functions.Proc2<Optional<io.temporal.api.common.v1.Payload>,io.temporal.api.failure.v1.Failure> completionCallback)
      Start a Nexus operation.
      Parameters:
      parameters - encapsulates all the information required to schedule a Nexus operation
      startedCallback - callback that is called when the operation is start if async, or completes if it is sync.
      completionCallback - callback that is called upon child workflow completion or failure
      Returns:
      cancellation handle. Invoke Functions.Proc1.apply(Object) to cancel activity task.
    • signalExternalWorkflowExecution

      Functions.Proc1<Exception> signalExternalWorkflowExecution(io.temporal.api.command.v1.SignalExternalWorkflowExecutionCommandAttributes.Builder attributes, Functions.Proc2<Void,io.temporal.api.failure.v1.Failure> callback)
      Signal a workflow execution by WorkflowId and optionally RunId.
      Parameters:
      attributes - signal information
      callback - callback notified about the operation result
      Returns:
      cancellation handler that should be calle to cancel the operation.
    • requestCancelExternalWorkflowExecution

      void requestCancelExternalWorkflowExecution(io.temporal.api.common.v1.WorkflowExecution execution, @Nullable String reason, Functions.Proc2<Void,RuntimeException> callback)
      Request cancellation of a workflow execution by WorkflowId and optionally RunId.
      Parameters:
      execution - contains WorkflowId and optional RunId of the workflow to send request to.
      reason - optional reason for cancellation.
      callback - callback notified about the operation result
    • currentTimeMillis

      long currentTimeMillis()
      Returns:
      time of the PollWorkflowTaskQueueResponse start event of the workflow task being processed or replayed.
    • newTimer

      Functions.Proc1<RuntimeException> newTimer(Duration delay, io.temporal.api.sdk.v1.UserMetadata metadata, Functions.Proc1<RuntimeException> callback)
      Create a Value that becomes ready after the specified delay.
      Parameters:
      delay - time-interval after which the Value becomes ready.
      metadata - user metadata to be associated with the timer.
      callback - Callback that is called with null parameter after the specified delay. CanceledException is passed as a parameter in case of a cancellation.
      Returns:
      cancellation handle. Invoke Functions.Proc1.apply(Object) to cancel timer.
    • sideEffect

      void sideEffect(Functions.Func<Optional<io.temporal.api.common.v1.Payloads>> func, io.temporal.api.sdk.v1.UserMetadata userMetadata, Functions.Proc1<Optional<io.temporal.api.common.v1.Payloads>> callback)
      Executes the provided function once, records its result into the workflow history. The recorded result on history will be returned without executing the provided function during replay. This guarantees the deterministic requirement for workflow as the exact same result will be returned in replay. Common use case is to run some short non-deterministic code in workflow, like getting random number or new UUID. The only way to fail SideEffect is to throw Error which causes workflow task failure. The workflow task after timeout is rescheduled and re-executed giving SideEffect another chance to succeed. Use scheduleLocalActivityTask(ExecuteLocalActivityParameters, LocalActivityCallback) for executing operations that rely on non-global dependencies and can fail.
      Parameters:
      func - function that is called once to return a value.
      userMetadata - user metadata to be associated with the side effect.
      callback - function that accepts the result of the side effect.
    • mutableSideEffect

      void mutableSideEffect(String id, io.temporal.api.sdk.v1.UserMetadata userMetadata, Functions.Func1<Optional<io.temporal.api.common.v1.Payloads>,Optional<io.temporal.api.common.v1.Payloads>> func, Functions.Proc1<Optional<io.temporal.api.common.v1.Payloads>> callback)
      mutableSideEffect is similar to sideEffect in allowing calls of non-deterministic functions from workflow code.

      The difference between mutableSideEffect and sideEffect is that every new sideEffect call in non-replay mode results in a new marker event recorded into the history. However, mutableSideEffect only records a new marker if a value has changed. During the replay, mutableSideEffect will not execute the function again, but it will return the exact same value as it was returning during the non-replay run.

      One good use case of mutableSideEffect is to access a dynamically changing config without breaking determinism. Even if called very frequently the config value is recorded only when it changes not causing any performance degradation due to a large history size.

      Caution: do not use mutableSideEffect function to modify any workflow state. Only use the mutableSideEffect's return value.

      Parameters:
      id - id of the side effect call. It links multiple calls together. Calls with different ids are completely independent.
      userMetadata - user metadata to attach to the marker event.
      func - function that gets as input a result of a previous mutableSideEffect call. The function executes its business logic (like checking config value) and if value didn't change returns Optional.empty(). If value has changed and needs to be recorded in the history then it is returned instead.
      callback - function that accepts the result of the mutable side effect which is current or cached result of the func.
    • getVersion

      Integer getVersion(String changeId, int minSupported, int maxSupported, Functions.Proc2<Integer,RuntimeException> callback)
      GetVersion is used to safely perform backwards incompatible changes to workflow definitions. It is not allowed to update workflow code while there are workflows running as it is going to break determinism. The solution is to have both old code that is used to replay existing workflows and the new one that is used when it is executed for the first time. GetVersion returns maxSupported version when executed for the first time. This version is recorded into the workflow history as a marker event. Even if maxSupported version is changed the version that was recorded is returned on replay. DefaultVersion constant contains version of code that wasn't versioned before.
      Parameters:
      changeId - identifier of a particular change
      minSupported - min version supported for the change
      maxSupported - max version supported for the change
      callback - used to return version
      Returns:
      True if the identifier is not present in history
    • newRandom

      Random newRandom()
      Replay safe random.
    • getMetricsScope

      com.uber.m3.tally.Scope getMetricsScope()
      Returns:
      scope to be used for metrics reporting.
    • getEnableLoggingInReplay

      boolean getEnableLoggingInReplay()
      Returns:
      whether we do logging during workflow code replay.
    • randomUUID

      UUID randomUUID()
      Returns:
      replay safe UUID
    • getAttempt

      int getAttempt()
      Returns:
      workflow retry attempt. Starts on "1".
    • getCronSchedule

      String getCronSchedule()
      Returns:
      workflow cron schedule
    • getLastCompletionResult

      @Nullable io.temporal.api.common.v1.Payloads getLastCompletionResult()
      Returns:
      Completion result of the last cron workflow run
    • getPreviousRunFailure

      @Nullable io.temporal.api.failure.v1.Failure getPreviousRunFailure()
      Returns:
      Failure of the previous run of this workflow
    • getFullReplayDirectQueryName

      @Nullable String getFullReplayDirectQueryName()
      This method is mostly used to decrease logging verbosity for replay-only scenarios.
      Returns:
      query name if an execution is a full replay caused by a direct query, null otherwise
    • getHeader

      Map<String,io.temporal.api.common.v1.Payload> getHeader()
      Returns:
      workflow header
    • getLastWorkflowTaskStartedEventId

      long getLastWorkflowTaskStartedEventId()
      Returns:
      eventId of the last / currently active workflow task of this workflow
    • getHistorySize

      long getHistorySize()
      Returns:
      size of Workflow history in bytes up until the current moment of execution. This value changes during the lifetime of a Workflow Execution.
    • isContinueAsNewSuggested

      boolean isContinueAsNewSuggested()
      Returns:
      true if the server is configured to suggest continue as new and it is suggested. This value changes during the lifetime of a Workflow Execution.
    • getSuggestContinueAsNewReasons

      List<SuggestContinueAsNewReason> getSuggestContinueAsNewReasons()
      Returns:
      the reasons why continue-as-new is suggested, or an empty list if not suggested. This value changes during the lifetime of a Workflow Execution.
    • isTargetWorkerDeploymentVersionChanged

      boolean isTargetWorkerDeploymentVersionChanged()
      Returns:
      true if the target worker deployment version has changed for this workflow.
    • isCancelRequested

      boolean isCancelRequested()
      Returns:
      true if cancellation of the workflow is requested.
    • setCancelRequested

      void setCancelRequested()
    • isWorkflowMethodCompleted

      boolean isWorkflowMethodCompleted()
      Returns:
      true if the worker's execution or a or replay of the workflow method finished or failed
    • setWorkflowMethodCompleted

      void setWorkflowMethodCompleted()
    • getContinueAsNewOnCompletion

      io.temporal.api.command.v1.ContinueAsNewWorkflowExecutionCommandAttributes getContinueAsNewOnCompletion()
      When these attributes are present upon completion of the workflow code the ContinueAsNew command is emitted instead of the workflow completion.
    • continueAsNewOnCompletion

      void continueAsNewOnCompletion(io.temporal.api.command.v1.ContinueAsNewWorkflowExecutionCommandAttributes attributes)
    • getWorkflowTaskFailure

      Throwable getWorkflowTaskFailure()
    • failWorkflowTask

      void failWorkflowTask(Throwable failure)
      Can be used by any code (both control and executing in workflow threads) to communicate that something is off, correct handling of Workflow Task is no possible and the worker should fail the Workflow Task.

      Note that this method is created to be from callback and other places where it may be tricky to propagate an exception. If you usecase is in the main synchronous code of WFT processing worker executor control thread - prefer direct exception throwing or return over using this indirect way.

      Parameters:
      failure - cause of the workflow task failure, this exception will be propagated by rethrowing in Workflow Executor thread
    • getSearchAttributes

      @Nullable io.temporal.api.common.v1.SearchAttributes getSearchAttributes()
      Returns:
      search attributes collected during the workflow execution up to the current moment as a non-deserialized protobuf, null if empty
    • upsertSearchAttributes

      void upsertSearchAttributes(@Nonnull io.temporal.api.common.v1.SearchAttributes searchAttributes)
      Updates or inserts search attributes used to index workflows.
    • upsertMemo

      void upsertMemo(@Nonnull io.temporal.api.common.v1.Memo memo)
      Updates or inserts memos.
    • tryUseSdkFlag

      boolean tryUseSdkFlag(SdkFlag flag)
      Returns:
      true if this flag may currently be used.
    • checkSdkFlag

      boolean checkSdkFlag(SdkFlag flag)
      Returns:
      true if this flag is currently set.
    • getCurrentBuildId

      Optional<String> getCurrentBuildId()
      Returns:
      The Build ID of the worker which executed the current Workflow Task. May be empty the task was completed by a worker without a Build ID. If this worker is the one executing this task for the first time and has a Build ID set, then its ID will be used. This value may change over the lifetime of the workflow run, but is deterministic and safe to use for branching.
    • getPriority

      io.temporal.api.common.v1.Priority getPriority()
      Returns:
      the priority of the workflow task