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 Detail

      • getWorkflowExecution

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

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

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

        @Nonnull
        java.lang.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

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

        java.lang.String getTaskQueue()
        Workflow task queue name.
      • getNamespace

        java.lang.String getNamespace()
        Workflow namespace.
      • getWorkflowId

        java.lang.String getWorkflowId()
      • getRunStartedTimestampMillis

        long getRunStartedTimestampMillis()
      • getWorkflowTaskTimeout

        @Nonnull
        java.time.Duration getWorkflowTaskTimeout()
      • getMemo

        io.temporal.api.common.v1.Payload getMemo​(java.lang.String key)
      • startChildWorkflow

        Functions.Proc1<java.lang.Exception> startChildWorkflow​(StartChildWorkflowExecutionParameters parameters,
                                                                Functions.Proc2<io.temporal.api.common.v1.WorkflowExecution,​java.lang.Exception> startCallback,
                                                                Functions.Proc2<java.util.Optional<io.temporal.api.common.v1.Payloads>,​java.lang.Exception> completionCallback)
        Start 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.
      • signalExternalWorkflowExecution

        Functions.Proc1<java.lang.Exception> signalExternalWorkflowExecution​(io.temporal.api.command.v1.SignalExternalWorkflowExecutionCommandAttributes.Builder attributes,
                                                                             Functions.Proc2<java.lang.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,
                                                    Functions.Proc2<java.lang.Void,​java.lang.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.
        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<java.lang.RuntimeException> newTimer​(java.time.Duration delay,
                                                             Functions.Proc1<java.lang.RuntimeException> callback)
        Create a Value that becomes ready after the specified delay.
        Parameters:
        delay - time-interval after which the Value becomes ready.
        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<java.util.Optional<io.temporal.api.common.v1.Payloads>> func,
                        Functions.Proc1<java.util.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.
        callback - function that accepts the result of the side effect.
      • mutableSideEffect

        void mutableSideEffect​(java.lang.String id,
                               Functions.Func1<java.util.Optional<io.temporal.api.common.v1.Payloads>,​java.util.Optional<io.temporal.api.common.v1.Payloads>> func,
                               Functions.Proc1<java.util.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.
        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

        boolean getVersion​(java.lang.String changeId,
                           int minSupported,
                           int maxSupported,
                           Functions.Proc2<java.lang.Integer,​java.lang.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

        java.util.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

        java.util.UUID randomUUID()
        Returns:
        replay safe UUID
      • getAttempt

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

        java.lang.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
        java.lang.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

        java.util.Map<java.lang.String,​io.temporal.api.common.v1.Payload> getHeader()
        Returns:
        workflow header
      • getCurrentWorkflowTaskStartedEventId

        long getCurrentWorkflowTaskStartedEventId()
        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.
      • 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

        java.lang.Throwable getWorkflowTaskFailure()
      • failWorkflowTask

        void failWorkflowTask​(java.lang.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.
      • tryUseSdkFlag

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