internal

package
v1.29.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 11, 2024 License: MIT Imports: 81 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultNamespace is the namespace name which is used if not passed with options.
	DefaultNamespace = "default"

	// QueryTypeStackTrace is the build in query type for Client.QueryWorkflow() call. Use this query type to get the call
	// stack of the workflow. The result will be a string encoded in the EncodedValue.
	QueryTypeStackTrace string = "__stack_trace"

	// QueryTypeOpenSessions is the build in query type for Client.QueryWorkflow() call. Use this query type to get all open
	// sessions in the workflow. The result will be a list of SessionInfo encoded in the EncodedValue.
	QueryTypeOpenSessions string = "__open_sessions"

	// QueryTypeWorkflowMetadata is the query name for the workflow metadata.
	QueryTypeWorkflowMetadata string = "__temporal_workflow_metadata"
)
View Source
const (
	SDKFlagUnset sdkFlag = 0
	// LimitChangeVersionSASize will limit the search attribute size of TemporalChangeVersion to 2048 when
	// calling GetVersion. If the limit is exceeded the search attribute is not updated.
	SDKFlagLimitChangeVersionSASize = 1
	// SDKFlagChildWorkflowErrorExecution return errors to child workflow execution future if the child workflow would
	// fail in the synchronous path.
	SDKFlagChildWorkflowErrorExecution = 2
	// SDKFlagProtocolMessageCommand uses ProtocolMessageCommands inserted into
	// a workflow task response's command set to order messages with respect to
	// commands.
	SDKFlagProtocolMessageCommand = 3
	// SDKPriorityUpdateHandling will cause update request to be handled before the main workflow method.
	// It will also cause the SDK to immediately handle updates when a handler is registered.
	SDKPriorityUpdateHandling = 4
	SDKFlagUnknown            = math.MaxUint32
)
View Source
const (
	// TaskQueueTypeUnspecified indicates the task queue type was not specified.
	TaskQueueTypeUnspecified = iota
	// TaskQueueTypeWorkflow indicates the task queue is used for dispatching workflow tasks.
	TaskQueueTypeWorkflow
	// TaskQueueTypeActivity indicates the task queue is used for delivering activity tasks.
	TaskQueueTypeActivity
	// TaskQueueTypeNexus indicates the task queue is used for dispatching Nexus requests.
	TaskQueueTypeNexus
)
View Source
const (
	// BuildIDTaskReachabilityUnspecified indicates that task reachability was not reported.
	BuildIDTaskReachabilityUnspecified = iota
	// BuildIDTaskReachabilityReachable indicates that this Build ID may be used by new workflows or activities
	// (based on versioning rules), or there are open workflows or backlogged activities assigned to it.
	BuildIDTaskReachabilityReachable
	// BuildIDTaskReachabilityClosedWorkflowsOnly specifies that this Build ID does not have open workflows
	// and is not reachable by new workflows, but MAY have closed workflows within the namespace retention period.
	// Not applicable to activity-only task queues.
	BuildIDTaskReachabilityClosedWorkflowsOnly
	// BuildIDTaskReachabilityUnreachable indicates that this Build ID is not used for new executions, nor
	// it has been used by any existing execution within the retention period.
	BuildIDTaskReachabilityUnreachable
)
View Source
const (
	// SDKVersion is a semver (https://semver.org/) that represents the version of this Temporal GoSDK.
	// Server validates if SDKVersion fits its supported range and rejects request if it doesn't.
	SDKVersion = "1.29.1"

	// SDKName represents the name of the SDK.
	SDKName = clientNameHeaderValue

	// SupportedServerVersions is a semver rages (https://github.com/blang/semver#ranges) of server versions that
	// are supported by this Temporal SDK.
	// Server validates if its version fits into SupportedServerVersions range and rejects request if it doesn't.
	SupportedServerVersions = ">=1.0.0 <2.0.0"
)
View Source
const (
	// TaskReachabilityUnspecified indicates the reachability was not specified
	TaskReachabilityUnspecified = iota
	// TaskReachabilityNewWorkflows indicates the Build Id might be used by new workflows
	TaskReachabilityNewWorkflows
	// TaskReachabilityExistingWorkflows indicates the Build Id might be used by open workflows
	// and/or closed workflows.
	TaskReachabilityExistingWorkflows
	// TaskReachabilityOpenWorkflows indicates the Build Id might be used by open workflows.
	TaskReachabilityOpenWorkflows
	// TaskReachabilityClosedWorkflows indicates the Build Id might be used by closed workflows
	TaskReachabilityClosedWorkflows
)
View Source
const (
	// LocalHostPort is a default host:port for worker and client to connect to.
	LocalHostPort = "localhost:7233"
)
View Source
const ReplayNamespace = "ReplayNamespace"

ReplayNamespace is namespace for replay because startEvent doesn't contain it

View Source
const TemporalChangeVersion = "TemporalChangeVersion"

TemporalChangeVersion is used as search attributes key to find workflows with specific change version.

View Source
const UnversionedBuildID = ""

A stand-in for a Build Id for unversioned Workers.

Variables

View Source
var (

	// ErrNoData is returned when trying to extract strong typed data while there is no data available.
	ErrNoData = errors.New("no data available")

	// ErrTooManyArg is returned when trying to extract strong typed data with more arguments than available data.
	ErrTooManyArg = errors.New("too many arguments")

	// ErrActivityResultPending is returned from activity's implementation to indicate the activity is not completed when
	// activity method returns. Activity needs to be completed by Client.CompleteActivity() separately. For example, if an
	// activity require human interaction (like approve an expense report), the activity could return activity.ErrResultPending
	// which indicate the activity is not done yet. Then, when the waited human action happened, it needs to trigger something
	// that could report the activity completed event to temporal server via Client.CompleteActivity() API.
	ErrActivityResultPending = errors.New("not error: do not autocomplete, using Client.CompleteActivity() to complete")

	// ErrScheduleAlreadyRunning is returned if there's already a running (not deleted) Schedule with the same ID
	ErrScheduleAlreadyRunning = errors.New("schedule with this ID is already registered")

	// ErrSkipScheduleUpdate is used by a user if they want to skip updating a schedule.
	ErrSkipScheduleUpdate = errors.New("skip schedule update")
)
View Source
var (
	// ErrUnknownMarkerName is returned if there is unknown marker name in the history.
	ErrUnknownMarkerName = errors.New("unknown marker name")
	// ErrMissingMarkerDetails is returned when marker details are nil.
	ErrMissingMarkerDetails = errors.New("marker details are nil")
	// ErrMissingMarkerDataKey is returned when marker details doesn't have data key.
	ErrMissingMarkerDataKey = errors.New("marker key is missing in details")
	// ErrUnknownHistoryEvent is returned if there is an unknown event in history and the SDK needs to handle it
	ErrUnknownHistoryEvent = errors.New("unknown history event")
)
View Source
var ErrCanceled = NewCanceledError()

ErrCanceled is the error returned by Context.Err when the context is canceled.

View Source
var ErrDeadlineExceeded = NewTimeoutError("deadline exceeded", enumspb.TIMEOUT_TYPE_SCHEDULE_TO_CLOSE, nil)

ErrDeadlineExceeded is the error returned by Context.Err when the context's deadline passes.

View Source
var ErrMockStartChildWorkflowFailed = fmt.Errorf("start child workflow failed: %v", enumspb.START_CHILD_WORKFLOW_EXECUTION_FAILED_CAUSE_WORKFLOW_ALREADY_EXISTS)

ErrMockStartChildWorkflowFailed is special error used to indicate the mocked child workflow should fail to start. This error is also exposed as public as testsuite.ErrMockStartChildWorkflowFailed

View Source
var (
	// ErrSessionFailed is the error returned when user tries to execute an activity but the
	// session it belongs to has already failed
	ErrSessionFailed = errors.New("session has failed")
)
View Source
var IsWorkflowRunOpContextKey = isWorkflowRunOpContextKeyType{}

IsWorkflowRunOpContextKey is a key to mark that the current context is used within a workflow run operation. The fake test env client verifies this key is set on the context to decide whether it should execute a method or panic as we don't want to expose a partial client to sync operations.

Functions

func AllHandlersFinished added in v1.28.0

func AllHandlersFinished(ctx Context) bool

func Await

func Await(ctx Context, condition func() bool) error

Await blocks the calling thread until condition() returns true Returns CanceledError if the ctx is canceled.

func AwaitWithOptions added in v1.29.1

func AwaitWithOptions(ctx Context, options AwaitOptions, condition func() bool) (ok bool, err error)

AwaitWithOptions blocks the calling thread until condition() returns true Returns ok equals to false if timed out and err equals to CanceledError if the ctx is canceled.

func AwaitWithTimeout

func AwaitWithTimeout(ctx Context, timeout time.Duration, condition func() bool) (ok bool, err error)

AwaitWithTimeout blocks the calling thread until condition() returns true Returns ok equals to false if timed out and err equals to CanceledError if the ctx is canceled.

func CompleteSession

func CompleteSession(ctx Context)

CompleteSession completes a session. It releases worker resources, so other sessions can be created. CompleteSession won't do anything if the context passed in doesn't contain any session information or the session has already completed or failed.

After a session has completed, user can continue to use the context, but the activities will be scheduled on the normal taskQueue (as user specified in ActivityOptions) and may be picked up by another worker since it's not in a session.

func DataConverterWithoutDeadlockDetection added in v1.15.0

func DataConverterWithoutDeadlockDetection(c converter.DataConverter) converter.DataConverter

DataConverterWithoutDeadlockDetection returns a data converter that disables workflow deadlock detection for each call on the data converter. This should be used for advanced data converters that may perform remote calls or otherwise intentionally execute longer than the default deadlock detection timeout.

func DeterministicKeys added in v1.26.0

func DeterministicKeys[K constraints.Ordered, V any](m map[K]V) []K

DeterministicKeys returns the keys of a map in deterministic (sorted) order. To be used in for loops in workflows for deterministic iteration.

func DeterministicKeysFunc added in v1.26.0

func DeterministicKeysFunc[K comparable, V any](m map[K]V, cmp func(a K, b K) int) []K

DeterministicKeysFunc returns the keys of a map in a deterministic (sorted) order. cmp(a, b) should return a negative number when a < b, a positive number when a > b and zero when a == b. Keys are sorted by cmp. To be used in for loops in workflows for deterministic iteration.

func EnableVerboseLogging

func EnableVerboseLogging(enable bool)

EnableVerboseLogging enable or disable verbose logging. This is for internal use only.

func GetActivityLogger

func GetActivityLogger(ctx context.Context) log.Logger

GetActivityLogger returns a logger that can be used in the activity.

func GetActivityMetricsHandler added in v1.12.0

func GetActivityMetricsHandler(ctx context.Context) metrics.Handler

GetActivityMetricsHandler returns a metrics handler that can be used in the activity.

func GetCurrentDetails added in v1.29.0

func GetCurrentDetails(ctx Context) string

GetCurrentDetails gets the previously-set current details.

NOTE: Experimental

func GetDefaultFailureConverter added in v1.18.0

func GetDefaultFailureConverter() converter.FailureConverter

GetDefaultFailureConverter returns the default failure converter used by Temporal.

func GetHeartbeatDetails

func GetHeartbeatDetails(ctx context.Context, d ...interface{}) error

GetHeartbeatDetails extracts heartbeat details from the last failed attempt. This is used in combination with the retry policy. An activity could be scheduled with an optional retry policy on ActivityOptions. If the activity failed, then server would attempt to dispatch another activity task to retry according to the retry policy. If there were heartbeat details reported by activity from the failed attempt, the details would be delivered along with the activity task for the retry attempt. An activity can extract the details from GetHeartbeatDetails() and resume progress from there.

Note: Values should not be reused for extraction here because merging on top of existing values may result in unexpected behavior similar to json.Unmarshal.

func GetLastCompletionResult

func GetLastCompletionResult(ctx Context, d ...interface{}) error

GetLastCompletionResult extract last completion result from previous run for this cron workflow. This is used in combination with cron schedule. A workflow can be started with an optional cron schedule. If a cron workflow wants to pass some data to next schedule, it can return any data and that data will become available when next run starts. This GetLastCompletionResult() extract the data into expected data structure.

Note, values should not be reused for extraction here because merging on top of existing values may result in unexpected behavior similar to json.Unmarshal.

func GetLastCompletionResultFromWorkflowInfo added in v1.4.0

func GetLastCompletionResultFromWorkflowInfo(info *WorkflowInfo) *commonpb.Payloads

GetLastCompletionResultFromWorkflowInfo returns value of last completion result.

func GetLastError added in v1.3.0

func GetLastError(ctx Context) error

GetLastError extracts the latest failure from any from previous run for this workflow, if one has failed. If none have failed, nil is returned.

See TestWorkflowEnvironment.SetLastError() for unit test support.

func GetLogger

func GetLogger(ctx Context) log.Logger

GetLogger returns a logger to be used in workflow's context

func GetMetricsHandler added in v1.12.0

func GetMetricsHandler(ctx Context) metrics.Handler

GetMetricsHandler returns a metrics handler to be used in workflow's context

func GetUnhandledSignalNames added in v1.20.0

func GetUnhandledSignalNames(ctx Context) []string

GetUnhandledSignalNames returns signal names that have unconsumed signals.

func GetWorkerStopChannel

func GetWorkerStopChannel(ctx context.Context) <-chan struct{}

GetWorkerStopChannel returns a read-only channel. The closure of this channel indicates the activity worker is stopping. When the worker is stopping, it will close this channel and wait until the worker stop timeout finishes. After the timeout hits, the worker will cancel the activity context and then exit. The timeout can be defined by worker option: WorkerStopTimeout. Use this channel to handle a graceful activity exit when the activity worker stops.

func Go

func Go(ctx Context, f func(ctx Context))

Go creates a new coroutine. It has similar semantic to goroutine in a context of the workflow.

func GoNamed

func GoNamed(ctx Context, name string, f func(ctx Context))

GoNamed creates a new coroutine with a given human readable name. It has similar semantic to goroutine in a context of the workflow. Name appears in stack traces that are blocked on this Channel.

func HasHeartbeatDetails

func HasHeartbeatDetails(ctx context.Context) bool

HasHeartbeatDetails checks if there are heartbeat details from last attempt.

func HasLastCompletionResult

func HasLastCompletionResult(ctx Context) bool

HasLastCompletionResult checks if there is completion result from previous runs. This is used in combination with cron schedule. A workflow can be started with an optional cron schedule. If a cron workflow wants to pass some data to next schedule, it can return any data and that data will become available when next run starts. This HasLastCompletionResult() checks if there is such data available passing down from previous successful run.

func Header(ctx context.Context) map[string]*commonpb.Payload

Header provides Temporal header information from the context for reading or writing during specific interceptor calls. See documentation in the interceptor package for more details.

func HistoryFromJSON added in v1.16.0

func HistoryFromJSON(r io.Reader, lastEventID int64) (*historypb.History, error)

HistoryFromJSON deserializes history from a reader of JSON bytes. This does not close the reader if it is closeable.

func InterruptCh added in v0.28.0

func InterruptCh() <-chan interface{}

InterruptCh returns channel which will get data when system receives interrupt signal. Pass it to worker.Run() func to stop worker with Ctrl+C.

func IsActivity added in v1.24.0

func IsActivity(ctx context.Context) bool

IsActivity checks if the context is an activity context from a normal or local activity.

func IsCanceledError

func IsCanceledError(err error) bool

IsCanceledError returns whether error in CanceledError.

func IsReplayNamespace

func IsReplayNamespace(dn string) bool

IsReplayNamespace checks if the namespace is from replay

func IsReplaying

func IsReplaying(ctx Context) bool

IsReplaying returns whether the current workflow code is replaying.

Warning! Never make commands, like schedule activity/childWorkflow/timer or send/wait on future/channel, based on this flag as it is going to break workflow determinism requirement. The only reasonable use case for this flag is to avoid some external actions during replay, like custom logging or metric reporting. Please note that Temporal already provide standard logging/metric via workflow.GetLogger(ctx) and workflow.GetMetricsHandler(ctx), and those standard mechanism are replay-aware and it will automatically suppress during replay. Only use this flag if you need custom logging/metrics reporting, for example if you want to log to kafka.

Warning! Any action protected by this flag should not fail or if it does fail should ignore that failure or panic on the failure. If workflow don't want to be blocked on those failure, it should ignore those failure; if workflow do want to make sure it proceed only when that action succeed then it should panic on that failure. Panic raised from a workflow causes workflow task to fail and temporal server will rescheduled later to retry.

func IsRetryable

func IsRetryable(err error, nonRetryableTypes []string) bool

IsRetryable returns if error retryable or not.

func MutableSideEffect

func MutableSideEffect(ctx Context, id string, f func(ctx Context) interface{}, equals func(a, b interface{}) bool) converter.EncodedValue

MutableSideEffect executes the provided function once, then it looks up the history for the value with the given id. If there is no existing value, then it records the function result as a value with the given id on history; otherwise, it compares whether the existing value from history has changed from the new function result by calling the provided equals function. If they are equal, it returns the value without recording a new one in history;

otherwise, it records the new value with the same id on history.

Caution: do not use MutableSideEffect to modify closures. Always retrieve result from MutableSideEffect's encoded return value.

The difference between MutableSideEffect() and SideEffect() is that every new SideEffect() call in non-replay will result in a new marker being recorded on history. However, MutableSideEffect() only records a new marker if the value changed. During 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 dynamically changing config without breaking determinism.

func NewActivityNotRegisteredError added in v1.8.0

func NewActivityNotRegisteredError(activityType string, supportedTypes []string) error

NewActivityNotRegisteredError creates a new ActivityNotRegisteredError.

func NewApplicationError

func NewApplicationError(msg string, errType string, nonRetryable bool, cause error, details ...interface{}) error

NewApplicationError create new instance of *ApplicationError with message, type, and optional details.

func NewApplicationErrorWithOptions added in v1.26.0

func NewApplicationErrorWithOptions(msg string, errType string, options ApplicationErrorOptions) error

func NewCanceledError

func NewCanceledError(details ...interface{}) error

NewCanceledError creates CanceledError instance.

func NewContinueAsNewError

func NewContinueAsNewError(ctx Context, wfn interface{}, args ...interface{}) error

NewContinueAsNewError creates ContinueAsNewError instance If the workflow main function returns this error then the current execution is ended and the new execution with same workflow ID is started automatically with options provided to this function.

 ctx - use context to override any options for the new workflow like run timeout, task timeout, task queue.
	  if not mentioned it would use the defaults that the current workflow is using.
       ctx := WithWorkflowRunTimeout(ctx, 30 * time.Minute)
       ctx := WithWorkflowTaskTimeout(ctx, 5 * time.Second)
	  ctx := WithWorkflowTaskQueue(ctx, "example-group")
 wfn - workflow function. for new execution it can be different from the currently running.
 args - arguments for the new workflow.

func NewContinueAsNewErrorWithOptions added in v1.26.0

func NewContinueAsNewErrorWithOptions(ctx Context, options ContinueAsNewErrorOptions, wfn interface{}, args ...interface{}) error

NewContinueAsNewErrorWithOptions creates ContinueAsNewError instance with additional options.

func NewDisconnectedContext

func NewDisconnectedContext(parent Context) (ctx Context, cancel CancelFunc)

NewDisconnectedContext returns a new context that won't propagate parent's cancellation to the new child context. One common use case is to do cleanup work after workflow is canceled.

err := workflow.ExecuteActivity(ctx, ActivityFoo).Get(ctx, &activityFooResult)
if err != nil && temporal.IsCanceledError(ctx.Err()) {
  // activity failed, and workflow context is canceled
  disconnectedCtx, _ := workflow.NewDisconnectedContext(ctx);
  workflow.ExecuteActivity(disconnectedCtx, handleCancellationActivity).Get(disconnectedCtx, nil)
  return err // workflow return CanceledError
}

func NewFuture

func NewFuture(ctx Context) (Future, Settable)

NewFuture creates a new future as well as associated Settable that is used to set its value.

func NewHeartbeatTimeoutError

func NewHeartbeatTimeoutError(details ...interface{}) error

NewHeartbeatTimeoutError creates TimeoutError instance.

func NewServerError

func NewServerError(msg string, nonRetryable bool, cause error) error

NewServerError create new instance of *ServerError with message.

func NewTimeoutError

func NewTimeoutError(msg string, timeoutType enumspb.TimeoutType, cause error, lastHeartbeatDetails ...interface{}) error

NewTimeoutError creates TimeoutError instance. Use NewHeartbeatTimeoutError to create heartbeat TimeoutError.

func NewValue

func NewValue(data *commonpb.Payloads) converter.EncodedValue

NewValue creates a new converter.EncodedValue which can be used to decode binary data returned by Temporal. For example: User had Activity.RecordHeartbeat(ctx, "my-heartbeat") and then got response from calling Client.DescribeWorkflowExecution. The response contains binary field PendingActivityInfo.HeartbeatDetails, which can be decoded by using:

var result string // This need to be same type as the one passed to RecordHeartbeat
NewValue(data).Get(&result)

func NewValues

func NewValues(data *commonpb.Payloads) converter.EncodedValues

NewValues creates a new converter.EncodedValues which can be used to decode binary data returned by Temporal. For example: User had Activity.RecordHeartbeat(ctx, "my-heartbeat", 123) and then got response from calling Client.DescribeWorkflowExecution. The response contains binary field PendingActivityInfo.HeartbeatDetails, which can be decoded by using:

var result1 string
var result2 int // These need to be same type as those arguments passed to RecordHeartbeat
NewValues(data).Get(&result1, &result2)

func Now

func Now(ctx Context) time.Time

Now returns the current time in UTC. It corresponds to the time when the workflow task is started or replayed. Workflow needs to use this method to get the wall clock time instead of the one from the golang library.

func PauseDeadlockDetector added in v1.15.0

func PauseDeadlockDetector(ctx Context)

PauseDeadlockDetector pauses the deadlock detector for all coroutines.

func PurgeStickyWorkflowCache added in v1.3.0

func PurgeStickyWorkflowCache()

PurgeStickyWorkflowCache resets the sticky workflow cache. This must be called only when all workers are stopped.

func RecordActivityHeartbeat

func RecordActivityHeartbeat(ctx context.Context, details ...interface{})

RecordActivityHeartbeat sends a heartbeat for the currently executing activity. If the activity is either canceled or workflow/activity doesn't exist, then we would cancel the context with error context.Canceled.

TODO: we don't have a way to distinguish between the two cases when context is canceled because
context doesn't support overriding value of ctx.Error.
TODO: Implement automatic heartbeating with cancellation through ctx.

details - The details that you provided here can be seen in the workflow when it receives TimeoutError. You can check error TimeoutType()/Details().

func ResumeDeadlockDetector added in v1.15.0

func ResumeDeadlockDetector(ctx Context)

ResumeDeadlockDetector resumes the deadlock detector for all coroutines.

func SetBinaryChecksum

func SetBinaryChecksum(checksum string)

SetBinaryChecksum sets the identifier of the binary(aka BinaryChecksum). The identifier is mainly used in recording reset points when respondWorkflowTaskCompleted. For each workflow, the very first workflow task completed by a binary will be associated as a auto-reset point for the binary. So that when a customer wants to mark the binary as bad, the workflow will be reset to that point -- which means workflow will forget all progress generated by the binary. On another hand, once the binary is marked as bad, the bad binary cannot poll workflow queue and make any progress any more.

func SetCallbacksOnStartWorkflowOptions added in v1.28.0

func SetCallbacksOnStartWorkflowOptions(opts *StartWorkflowOptions, callbacks []*commonpb.Callback)

SetCallbacksOnStartWorkflowOptions is an internal only method for setting callbacks on StartWorkflowOptions. Callbacks are purposefully not exposed to users for the time being.

func SetCurrentDetails added in v1.29.0

func SetCurrentDetails(ctx Context, details string)

SetCurrentDetails sets the current details.

NOTE: Experimental

func SetLinksOnStartWorkflowOptions added in v1.29.0

func SetLinksOnStartWorkflowOptions(opts *StartWorkflowOptions, links []*commonpb.Link)

SetLinksOnStartWorkflowOptions is an internal only method for setting links on StartWorkflowOptions. Links are purposefully not exposed to users for the time being.

func SetQueryHandler

func SetQueryHandler(ctx Context, queryType string, handler interface{}) error

SetQueryHandler sets the query handler to handle workflow query. The queryType specify which query type this handler should handle. The handler must be a function that returns 2 values. The first return value must be a serializable result. The second return value must be an error. The handler function could receive any number of input parameters. All the input parameter must be serializable. You should call workflow.SetQueryHandler() at the beginning of the workflow code. When client calls Client.QueryWorkflow() to temporal server, a task will be generated on server that will be dispatched to a workflow worker, which will replay the history events and then execute a query handler based on the query type. The query handler will be invoked out of the context of the workflow, meaning that the handler code must not use temporal context to do things like workflow.NewChannel(), workflow.Go() or to call any workflow blocking functions like Channel.Get() or Future.Get(). Trying to do so in query handler code will fail the query and client will receive QueryFailedError. Example of workflow code that support query type "current_state":

func MyWorkflow(ctx workflow.Context, input string) error {
  currentState := "started" // this could be any serializable struct
  err := workflow.SetQueryHandler(ctx, "current_state", func() (string, error) {
    return currentState, nil
  })
  if err != nil {
    currentState = "failed to register query handler"
    return err
  }
  // your normal workflow code begins here, and you update the currentState as the code makes progress.
  currentState = "waiting timer"
  err = NewTimer(ctx, time.Hour).Get(ctx, nil)
  if err != nil {
    currentState = "timer failed"
    return err
  }

  currentState = "waiting activity"
  ctx = WithActivityOptions(ctx, myActivityOptions)
  err = ExecuteActivity(ctx, MyActivity, "my_input").Get(ctx, nil)
  if err != nil {
    currentState = "activity failed"
    return err
  }
  currentState = "done"
  return nil
}

See SetQueryHandlerWithOptions to set additional options.

func SetQueryHandlerWithOptions added in v1.29.0

func SetQueryHandlerWithOptions(ctx Context, queryType string, handler interface{}, options QueryHandlerOptions) error

SetQueryHandlerWithOptions is SetQueryHandler with extra options. See SetQueryHandler documentation for details.

NOTE: Experimental

func SetRequestIDOnStartWorkflowOptions added in v1.28.0

func SetRequestIDOnStartWorkflowOptions(opts *StartWorkflowOptions, requestID string)

SetRequestIDOnStartWorkflowOptions is an internal only method for setting a requestID on StartWorkflowOptions. RequestID is purposefully not exposed to users for the time being.

func SetRetryLongPollGracePeriod added in v1.21.1

func SetRetryLongPollGracePeriod(period time.Duration)

SetRetryLongPollGracePeriod sets the amount of time a long poller retries on fatal errors before it actually fails. For test use only, not safe to call with a running worker.

func SetStickyWorkflowCacheSize

func SetStickyWorkflowCacheSize(cacheSize int)

SetStickyWorkflowCacheSize sets the cache size for sticky workflow cache. Sticky workflow execution is the affinity between workflow tasks of a specific workflow execution to a specific worker. The benefit of sticky execution is that the workflow does not have to reconstruct state by replaying history from the beginning. The cache is shared between workers running within same process. This must be called before any worker is started. If not called, the default size of 10K (which may change) will be used.

func SetUpdateHandler added in v1.16.0

func SetUpdateHandler(ctx Context, updateName string, handler interface{}, opts UpdateHandlerOptions) error

SetUpdateHandler binds an update handler function to the specified name such that update invocations specifying that name will invoke the handler. The handler function can take as input any number of parameters so long as they can be serialized/deserialized by the system. The handler can take a workflow.Context as its first parameter but this is not required. The update handler must return either a single error or a single serializable object along with a single error. The update handler function is invoked in the context of the workflow and thus is subject to the same restrictions as workflow code, namely, the update handler must be deterministic. As with other workflow code, update code is free to invoke and wait on the results of activities. Update handler code is free to mutate workflow state.

This registration can optionally specify (through UpdateHandlerOptions) an update validation function. If provided, this function will be invoked before the update handler itself is invoked and if this function returns an error, the update request will be considered to have been rejected and as such will not occupy any space in the workflow history. Validation functions must take as inputs the same parameters as the associated update handler but may vary from said handler by the presence/absence of a workflow.Context as the first parameter. Validation handlers must only return a single error. Validation handlers must be deterministic and can observe workflow state but must not mutate workflow state in any way.

NOTE: Experimental

func SideEffect

func SideEffect(ctx Context, f func(ctx Context) interface{}) converter.EncodedValue

SideEffect 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 panic which causes workflow task failure. The workflow task after timeout is rescheduled and re-executed giving SideEffect another chance to succeed.

Caution: do not use SideEffect to modify closures. Always retrieve result from SideEffect's encoded return value. For example this code is BROKEN:

// Bad example:
var random int
workflow.SideEffect(func(ctx workflow.Context) interface{} {
       random = rand.Intn(100)
       return nil
})
// random will always be 0 in replay, thus this code is non-deterministic
if random < 50 {
       ....
} else {
       ....
}

On replay the provided function is not executed, the random will always be 0, and the workflow could takes a different path breaking the determinism.

Here is the correct way to use SideEffect:

// Good example:
encodedRandom := SideEffect(func(ctx workflow.Context) interface{} {
      return rand.Intn(100)
})
var random int
encodedRandom.Get(&random)
if random < 50 {
       ....
} else {
       ....
}

func Sleep

func Sleep(ctx Context, d time.Duration) (err error)

Sleep pauses the current workflow for at least the duration d. A negative or zero duration causes Sleep to return immediately. Workflow code needs to use this Sleep() to sleep instead of the Go lang library one(timer.Sleep()). You can cancel the pending sleep by cancel the Context (using context from workflow.WithCancel(ctx)). Sleep() returns nil if the duration d is passed, or it returns *CanceledError if the ctx is canceled. There are 2 reasons the ctx could be canceled: 1) your workflow code cancel the ctx (with workflow.WithCancel(ctx)); 2) your workflow itself is canceled by external request.

func UpsertMemo added in v1.17.0

func UpsertMemo(ctx Context, memo map[string]interface{}) error

UpsertMemo is used to add or update workflow memo. UpsertMemo will merge keys to the existing map in workflow. For example:

func MyWorkflow(ctx workflow.Context, input string) error {
	memo1 := map[string]interface{}{
		"Key1": 1,
		"Key2": true,
	}
	workflow.UpsertMemo(ctx, memo1)

	memo2 := map[string]interface{}{
		"Key1": 2,
		"Key3": "seattle",
	}
	workflow.UpsertMemo(ctx, memo2)
}

The workflow memo will eventually be:

map[string]interface{}{
	"Key1": 2,
	"Key2": true,
	"Key3": "seattle",
}

This is only supported with Temporal Server 1.18+

func UpsertSearchAttributes deprecated

func UpsertSearchAttributes(ctx Context, attributes map[string]interface{}) error

UpsertSearchAttributes is used to add or update workflow search attributes. The search attributes can be used in query of List/Scan/Count workflow APIs. The key and value type must be registered on temporal server side; The value has to be Json serializable. UpsertSearchAttributes will merge attributes to existing map in workflow, for example workflow code:

  func MyWorkflow(ctx workflow.Context, input string) error {
	   attr1 := map[string]interface{}{
		   "CustomIntField": 1,
		   "CustomBoolField": true,
	   }
	   workflow.UpsertSearchAttributes(ctx, attr1)

	   attr2 := map[string]interface{}{
		   "CustomIntField": 2,
		   "CustomKeywordField": "seattle",
	   }
	   workflow.UpsertSearchAttributes(ctx, attr2)
  }

will eventually have search attributes:

map[string]interface{}{
	"CustomIntField": 2,
	"CustomBoolField": true,
	"CustomKeywordField": "seattle",
}

For supported operations on different server versions see Visibility.

Deprecated: Use UpsertTypedSearchAttributes instead.

func UpsertTypedSearchAttributes added in v1.26.0

func UpsertTypedSearchAttributes(ctx Context, attributes ...SearchAttributeUpdate) error

func WithActivityTask

func WithActivityTask(
	ctx context.Context,
	task *workflowservice.PollActivityTaskQueueResponse,
	taskQueue string,
	invoker ServiceInvoker,
	logger log.Logger,
	metricsHandler metrics.Handler,
	dataConverter converter.DataConverter,
	workerStopChannel <-chan struct{},
	contextPropagators []ContextPropagator,
	interceptors []WorkerInterceptor,
) (context.Context, error)

WithActivityTask adds activity specific information into context. Use this method to unit test activity implementations that use context extractor methodshared.

func WithCancel

func WithCancel(parent Context) (ctx Context, cancel CancelFunc)

WithCancel returns a copy of parent with a new Done channel. The returned context's Done channel is closed when the returned cancel function is called or when the parent context's Done channel is closed, whichever happens first.

Canceling this context releases resources associated with it, so code should call cancel as soon as the operations running in this Context complete.

func WithContext added in v1.6.0

WithContext returns a new DataConverter tailored to the passed Workflow/Activity context if the DataConverter implements the ContextAware interface. Otherwise the DataConverter is returned as-is. This is generally used for Activity context but can be context for a Workflow if we're not yet executing the workflow so do not have a workflow.Context.

func WithLocalActivityTask added in v1.9.0

func WithLocalActivityTask(
	ctx context.Context,
	task *localActivityTask,
	logger log.Logger,
	metricsHandler metrics.Handler,
	dataConverter converter.DataConverter,
	interceptors []WorkerInterceptor,
) (context.Context, error)

WithLocalActivityTask adds local activity specific information into context.

func WithWorkflowContext added in v1.6.0

func WithWorkflowContext(ctx Context, dc converter.DataConverter) converter.DataConverter

WithWorkflowContext returns a new DataConverter tailored to the passed Workflow context if the DataConverter implements the ContextAware interface. Otherwise the DataConverter is returned as-is.

func WorkflowHeader added in v1.12.0

func WorkflowHeader(ctx Context) map[string]*commonpb.Payload

WorkflowHeader provides Temporal header information from the workflow context for reading or writing during specific interceptor calls. See documentation in the interceptor package for more details.

Types

type ActivityError

type ActivityError struct {
	// contains filtered or unexported fields
}

ActivityError is returned from workflow when activity returned an error. Unwrap this error to get actual cause.

func NewActivityError

func NewActivityError(
	scheduledEventID int64,
	startedEventID int64,
	identity string,
	activityType *commonpb.ActivityType,
	activityID string,
	retryState enumspb.RetryState,
	cause error,
) *ActivityError

NewActivityError creates ActivityError instance.

func (*ActivityError) ActivityID added in v1.9.0

func (e *ActivityError) ActivityID() string

ActivityID return assigned identifier for the activity.

func (*ActivityError) ActivityType added in v1.9.0

func (e *ActivityError) ActivityType() *commonpb.ActivityType

ActivityType returns declared type of the activity.

func (*ActivityError) Error

func (e *ActivityError) Error() string

func (*ActivityError) Identity added in v1.9.0

func (e *ActivityError) Identity() string

Identity returns identity of the worker that attempted activity execution.

func (*ActivityError) RetryState added in v1.9.0

func (e *ActivityError) RetryState() enumspb.RetryState

RetryState returns details on why activity failed.

func (*ActivityError) ScheduledEventID added in v1.9.0

func (e *ActivityError) ScheduledEventID() int64

ScheduledEventID returns event id of the scheduled workflow task corresponding to the activity.

func (*ActivityError) StartedEventID added in v1.9.0

func (e *ActivityError) StartedEventID() int64

StartedEventID returns event id of the started workflow task corresponding to the activity.

func (*ActivityError) Unwrap

func (e *ActivityError) Unwrap() error

type ActivityID

type ActivityID struct {
	// contains filtered or unexported fields
}

ActivityID uniquely identifies an activity execution

func ParseActivityID added in v1.3.0

func ParseActivityID(id string) (ActivityID, error)

ParseActivityID returns ActivityID constructed from its string representation. The string representation should be obtained through ActivityID.String()

func (ActivityID) String added in v1.3.0

func (i ActivityID) String() string

type ActivityInboundInterceptor added in v1.12.0

type ActivityInboundInterceptor interface {
	// Init is the first call of this interceptor. Implementations can change/wrap
	// the outbound interceptor before calling Init on the next interceptor.
	Init(outbound ActivityOutboundInterceptor) error

	// ExecuteActivity is called when an activity is to be run on this worker.
	// interceptor.Header will return a non-nil map for this context.
	ExecuteActivity(ctx context.Context, in *ExecuteActivityInput) (interface{}, error)
	// contains filtered or unexported methods
}

ActivityInboundInterceptor is an interface for all activity calls originating from the server. See documentation in the interceptor package for more details.

type ActivityInboundInterceptorBase added in v1.12.0

type ActivityInboundInterceptorBase struct {
	Next ActivityInboundInterceptor
}

ActivityInboundInterceptorBase is a default implementation of ActivityInboundInterceptor meant for embedding. See documentation in the interceptor package for more details.

func (*ActivityInboundInterceptorBase) ExecuteActivity added in v1.12.0

func (a *ActivityInboundInterceptorBase) ExecuteActivity(
	ctx context.Context,
	in *ExecuteActivityInput,
) (interface{}, error)

ExecuteActivity implements ActivityInboundInterceptor.ExecuteActivity.

func (*ActivityInboundInterceptorBase) Init added in v1.12.0

Init implements ActivityInboundInterceptor.Init.

type ActivityInfo

type ActivityInfo struct {
	TaskToken         []byte
	WorkflowType      *WorkflowType
	WorkflowNamespace string
	WorkflowExecution WorkflowExecution
	ActivityID        string
	ActivityType      ActivityType
	TaskQueue         string
	HeartbeatTimeout  time.Duration // Maximum time between heartbeats. 0 means no heartbeat needed.
	ScheduledTime     time.Time     // Time of activity scheduled by a workflow
	StartedTime       time.Time     // Time of activity start
	Deadline          time.Time     // Time of activity timeout
	Attempt           int32         // Attempt starts from 1, and increased by 1 for every retry if retry policy is specified.
	IsLocalActivity   bool          // true if it is a local activity
}

ActivityInfo contains information about a currently executing activity.

func GetActivityInfo

func GetActivityInfo(ctx context.Context) ActivityInfo

GetActivityInfo returns information about the currently executing activity.

type ActivityNotRegisteredError added in v1.8.0

type ActivityNotRegisteredError struct {
	// contains filtered or unexported fields
}

ActivityNotRegisteredError is returned if worker doesn't support activity type.

func (*ActivityNotRegisteredError) Error added in v1.8.0

type ActivityOptions

type ActivityOptions struct {
	// TaskQueue - Name of the task queue that the activity needs to be scheduled on.
	// Optional: The default task queue with the same name as the workflow task queue.
	TaskQueue string

	// ScheduleToCloseTimeout - Total time that a workflow is willing to wait for an Activity to complete.
	// ScheduleToCloseTimeout limits the total time of an Activity's execution including retries
	// 		(use StartToCloseTimeout to limit the time of a single attempt).
	// The zero value of this uses default value.
	// Either this option or StartToCloseTimeout is required: Defaults to unlimited.
	ScheduleToCloseTimeout time.Duration

	// ScheduleToStartTimeout - Time that the Activity Task can stay in the Task Queue before it is picked up by
	// a Worker. Do not specify this timeout unless using host specific Task Queues for Activity Tasks are being
	// used for routing. In almost all situations that don't involve routing activities to specific hosts, it is
	// better to rely on the default value.
	// ScheduleToStartTimeout is always non-retryable. Retrying after this timeout doesn't make sense, as it would
	// just put the Activity Task back into the same Task Queue.
	// Optional: Defaults to unlimited.
	ScheduleToStartTimeout time.Duration

	// StartToCloseTimeout - Maximum time of a single Activity execution attempt.
	// Note that the Temporal Server doesn't detect Worker process failures directly. It relies on this timeout
	// to detect that an Activity that didn't complete on time. So this timeout should be as short as the longest
	// possible execution of the Activity body. Potentially long running Activities must specify HeartbeatTimeout
	// and call Activity.RecordHeartbeat(ctx, "my-heartbeat") periodically for timely failure detection.
	// Either this option or ScheduleToCloseTimeout is required: Defaults to the ScheduleToCloseTimeout value.
	StartToCloseTimeout time.Duration

	// HeartbeatTimeout - Heartbeat interval. Activity must call Activity.RecordHeartbeat(ctx, "my-heartbeat")
	// before this interval passes after the last heartbeat or the Activity starts.
	HeartbeatTimeout time.Duration

	// WaitForCancellation - Whether to wait for canceled activity to be completed(
	// activity can be failed, completed, cancel accepted)
	// Optional: default false
	WaitForCancellation bool

	// ActivityID - Business level activity ID, this is not needed for most of the cases if you have
	// to specify this then talk to the temporal team. This is something will be done in the future.
	// Optional: default empty string
	ActivityID string

	// RetryPolicy - Specifies how to retry an Activity if an error occurs.
	// More details are available at docs.temporal.io.
	// RetryPolicy is optional. If one is not specified, a default RetryPolicy is provided by the server.
	// The default RetryPolicy provided by the server specifies:
	// - InitialInterval of 1 second
	// - BackoffCoefficient of 2.0
	// - MaximumInterval of 100 x InitialInterval
	// - MaximumAttempts of 0 (unlimited)
	// To disable retries, set MaximumAttempts to 1.
	// The default RetryPolicy provided by the server can be overridden by the dynamic config.
	RetryPolicy *RetryPolicy

	// If true, eager execution will not be requested, regardless of worker settings.
	// If false, eager execution may still be disabled at the worker level or
	// may not be requested due to lack of available slots.
	//
	// Eager activity execution means the server returns requested eager
	// activities directly from the workflow task back to this worker. This is
	// faster than non-eager, which may be dispatched to a separate worker.
	DisableEagerExecution bool

	// VersioningIntent - Specifies whether this activity should run on a worker with a compatible
	// build ID or not. See temporal.VersioningIntent.
	// WARNING: Worker versioning is currently experimental
	VersioningIntent VersioningIntent
}

ActivityOptions stores all activity-specific parameters that will be stored inside of a context. The current timeout resolution implementation is in seconds and uses math.Ceil(d.Seconds()) as the duration. But is subjected to change in the future.

func GetActivityOptions added in v1.6.0

func GetActivityOptions(ctx Context) ActivityOptions

GetActivityOptions returns all activity options present on the context.

type ActivityOutboundInterceptor added in v1.12.0

type ActivityOutboundInterceptor interface {
	// GetInfo intercepts activity.GetInfo.
	GetInfo(ctx context.Context) ActivityInfo

	// GetLogger intercepts activity.GetLogger.
	GetLogger(ctx context.Context) log.Logger

	// GetMetricsHandler intercepts activity.GetMetricsHandler.
	GetMetricsHandler(ctx context.Context) metrics.Handler

	// RecordHeartbeat intercepts activity.RecordHeartbeat.
	RecordHeartbeat(ctx context.Context, details ...interface{})

	// HasHeartbeatDetails intercepts activity.HasHeartbeatDetails.
	HasHeartbeatDetails(ctx context.Context) bool

	// GetHeartbeatDetails intercepts activity.GetHeartbeatDetails.
	GetHeartbeatDetails(ctx context.Context, d ...interface{}) error

	// GetWorkerStopChannel intercepts activity.GetWorkerStopChannel.
	GetWorkerStopChannel(ctx context.Context) <-chan struct{}
	// contains filtered or unexported methods
}

ActivityOutboundInterceptor is an interface for all activity calls originating from the SDK. See documentation in the interceptor package for more details.

type ActivityOutboundInterceptorBase added in v1.12.0

type ActivityOutboundInterceptorBase struct {
	Next ActivityOutboundInterceptor
}

ActivityOutboundInterceptorBase is a default implementation of ActivityOutboundInterceptor meant for embedding. See documentation in the interceptor package for more details.

func (*ActivityOutboundInterceptorBase) GetHeartbeatDetails added in v1.12.0

func (a *ActivityOutboundInterceptorBase) GetHeartbeatDetails(ctx context.Context, d ...interface{}) error

GetHeartbeatDetails implements ActivityOutboundInterceptor.GetHeartbeatDetails.

func (*ActivityOutboundInterceptorBase) GetInfo added in v1.12.0

GetInfo implements ActivityOutboundInterceptor.GetInfo.

func (*ActivityOutboundInterceptorBase) GetLogger added in v1.12.0

GetLogger implements ActivityOutboundInterceptor.GetLogger.

func (*ActivityOutboundInterceptorBase) GetMetricsHandler added in v1.12.0

GetMetricsHandler implements ActivityOutboundInterceptor.GetMetricsHandler.

func (*ActivityOutboundInterceptorBase) GetWorkerStopChannel added in v1.12.0

func (a *ActivityOutboundInterceptorBase) GetWorkerStopChannel(ctx context.Context) <-chan struct{}

GetWorkerStopChannel implements ActivityOutboundInterceptor.GetWorkerStopChannel.

func (*ActivityOutboundInterceptorBase) HasHeartbeatDetails added in v1.12.0

func (a *ActivityOutboundInterceptorBase) HasHeartbeatDetails(ctx context.Context) bool

HasHeartbeatDetails implements ActivityOutboundInterceptor.HasHeartbeatDetails.

func (*ActivityOutboundInterceptorBase) RecordHeartbeat added in v1.12.0

func (a *ActivityOutboundInterceptorBase) RecordHeartbeat(ctx context.Context, details ...interface{})

RecordHeartbeat implements ActivityOutboundInterceptor.RecordHeartbeat.

type ActivityTaskHandler

type ActivityTaskHandler interface {
	// Executes the activity task
	// The response is one of the types:
	// - RespondActivityTaskCompletedRequest
	// - RespondActivityTaskFailedRequest
	// - RespondActivityTaskCanceledRequest
	Execute(taskQueue string, task *workflowservice.PollActivityTaskQueueResponse) (interface{}, error)
}

ActivityTaskHandler represents activity task handlers.

type ActivityType

type ActivityType struct {
	Name string
}

ActivityType identifies an activity type.

type AggregatedWorker

type AggregatedWorker struct {
	// contains filtered or unexported fields
}

AggregatedWorker combines management of both workflowWorker and activityWorker worker lifecycle.

func NewAggregatedWorker

func NewAggregatedWorker(client *WorkflowClient, taskQueue string, options WorkerOptions) *AggregatedWorker

NewAggregatedWorker returns an instance to manage both activity and workflow workers

func NewWorker

func NewWorker(
	client Client,
	taskQueue string,
	options WorkerOptions,
) *AggregatedWorker

NewWorker creates an instance of worker for managing workflow and activity executions. client - client created with client.Dial() or client.NewLazyClient(). taskQueue - is the task queue name you use to identify your client worker, also identifies group of workflow and activity implementations that are hosted by a single worker process.

options - configure any worker specific options.

func (*AggregatedWorker) RegisterActivity

func (aw *AggregatedWorker) RegisterActivity(a interface{})

RegisterActivity registers activity implementation with the AggregatedWorker

func (*AggregatedWorker) RegisterActivityWithOptions

func (aw *AggregatedWorker) RegisterActivityWithOptions(a interface{}, options RegisterActivityOptions)

RegisterActivityWithOptions registers activity implementation with the AggregatedWorker

func (*AggregatedWorker) RegisterNexusService added in v1.28.0

func (aw *AggregatedWorker) RegisterNexusService(service *nexus.Service)

func (*AggregatedWorker) RegisterWorkflow

func (aw *AggregatedWorker) RegisterWorkflow(w interface{})

RegisterWorkflow registers workflow implementation with the AggregatedWorker

func (*AggregatedWorker) RegisterWorkflowWithOptions

func (aw *AggregatedWorker) RegisterWorkflowWithOptions(w interface{}, options RegisterWorkflowOptions)

RegisterWorkflowWithOptions registers workflow implementation with the AggregatedWorker

func (*AggregatedWorker) Run

func (aw *AggregatedWorker) Run(interruptCh <-chan interface{}) error

Run the worker in a blocking fashion. Stop the worker when interruptCh receives signal. Pass worker.InterruptCh() to stop the worker with SIGINT or SIGTERM. Pass nil to stop the worker with external Stop() call. Pass any other `<-chan interface{}` and Run will wait for signal from that channel. Returns error if the worker fails to start or there is a fatal error during execution.

func (*AggregatedWorker) Start

func (aw *AggregatedWorker) Start() error

Start the worker in a non-blocking fashion. The actual work is done in the memoized "start" function to ensure duplicate calls are returned a consistent error.

func (*AggregatedWorker) Stop

func (aw *AggregatedWorker) Stop()

Stop the worker.

type ApplicationError

type ApplicationError struct {
	// contains filtered or unexported fields
}

ApplicationError returned from activity implementations with message and optional details.

func (*ApplicationError) Details

func (e *ApplicationError) Details(d ...interface{}) error

Details extracts strong typed detail data of this custom error. If there is no details, it will return ErrNoData.

func (*ApplicationError) Error

func (e *ApplicationError) Error() string

Error from error interface.

func (*ApplicationError) HasDetails

func (e *ApplicationError) HasDetails() bool

HasDetails return if this error has strong typed detail data.

func (*ApplicationError) Message added in v1.15.0

func (e *ApplicationError) Message() string

Message contains just the message string without extras added by Error().

func (*ApplicationError) NextRetryDelay added in v1.26.0

func (e *ApplicationError) NextRetryDelay() time.Duration

NextRetryDelay returns the delay to wait before retrying the activity. a zero value means to use the activities retry policy.

func (*ApplicationError) NonRetryable

func (e *ApplicationError) NonRetryable() bool

NonRetryable indicated if error is not retryable.

func (*ApplicationError) Type

func (e *ApplicationError) Type() string

Type returns error type represented as string. This type can be passed explicitly to ApplicationError constructor. Also any other Go error is converted to ApplicationError and type is set automatically using reflection. For example instance of "MyCustomError struct" will be converted to ApplicationError and Type() will return "MyCustomError" string.

func (*ApplicationError) Unwrap

func (e *ApplicationError) Unwrap() error

type ApplicationErrorOptions added in v1.26.0

type ApplicationErrorOptions struct {
	// NonRetryable indicates if the error should not be retried regardless of the retry policy.
	NonRetryable bool
	// Cause is the original error that caused this error.
	Cause error
	// Details is a list of arbitrary values that can be used to provide additional context to the error.
	Details []interface{}
	// NextRetryInterval is a request from server to override retry interval calculated by the
	// server according to the RetryPolicy set by the Workflow.
	// It is impossible to specify immediate retry as it is indistinguishable from the default value. As a
	// workaround you could set NextRetryDelay to some small value.
	// NOTE: This option is supported by Temporal Server >= v1.24.2 older version will ignore this value.
	NextRetryDelay time.Duration
}

ApplicationErrorOptions represents a combination of error attributes and additional requests. All fields are optional, providing flexibility in error customization.

type AsyncActivityClient

type AsyncActivityClient interface {
	// The ExecuteActivity schedules an activity with a callback handler.
	// If the activity failed to complete the callback error would indicate the failure
	// and it can be one of ActivityTaskFailedError, ActivityTaskTimeoutError, ActivityTaskCanceledError
	ExecuteActivity(parameters ExecuteActivityParams, callback ResultHandler) ActivityID

	// This only initiates cancel request for activity. if the activity is configured to not WaitForCancellation then
	// it would invoke the callback handler immediately with error code ActivityTaskCanceledError.
	// If the activity is not running(either scheduled or started) then it is a no-operation.
	RequestCancelActivity(activityID ActivityID)
}

AsyncActivityClient for requesting activity execution

type AwaitOptions added in v1.29.1

type AwaitOptions struct {
	// Timeout is the await timeout if the await condition is not met.
	//
	// NOTE: Experimental
	Timeout time.Duration
	// TimerOptions are options set for the underlying timer created.
	//
	// NOTE: Experimental
	TimerOptions TimerOptions
}

AwaitOptions are options set when creating an await.

NOTE: Experimental

type BuildIDOpAddNewCompatibleVersion added in v1.23.0

type BuildIDOpAddNewCompatibleVersion struct {
	BuildID                   string
	ExistingCompatibleBuildID string
	MakeSetDefault            bool
}

type BuildIDOpAddNewIDInNewDefaultSet added in v1.23.0

type BuildIDOpAddNewIDInNewDefaultSet struct {
	BuildID string
}

type BuildIDOpPromoteIDWithinSet added in v1.23.0

type BuildIDOpPromoteIDWithinSet struct {
	BuildID string
}

type BuildIDOpPromoteSet added in v1.23.0

type BuildIDOpPromoteSet struct {
	BuildID string
}

type BuildIDReachability added in v1.25.0

type BuildIDReachability struct {
	// TaskQueueReachable map of task queues and their reachability information.
	TaskQueueReachable map[string]*TaskQueueReachability
	// UnretrievedTaskQueues is a list of task queues not retrieved because the server limits
	// the number that can be queried at once.
	UnretrievedTaskQueues []string
}

type BuildIDTaskReachability added in v1.27.0

type BuildIDTaskReachability int

BuildIDTaskReachability specifies which category of tasks may reach a versioned worker of a certain Build ID.

Note: future activities who inherit their workflow's Build ID but not its task queue will not be accounted for reachability as server cannot know if they'll happen as they do not use assignment rules of their task queue. Same goes for Child Workflows or Continue-As-New Workflows who inherit the parent/previous workflow's Build ID but not its task queue. In those cases, make sure to query reachability for the parent/previous workflow's task queue as well.

type CancelFunc

type CancelFunc func()

A CancelFunc tells an operation to abandon its work. A CancelFunc does not wait for the work to stop. After the first call, subsequent calls to a CancelFunc do nothing.

type CanceledError

type CanceledError struct {
	// contains filtered or unexported fields
}

CanceledError returned when operation was canceled.

func (*CanceledError) Details

func (e *CanceledError) Details(d ...interface{}) error

Details extracts strong typed detail data of this error.

func (*CanceledError) Error

func (e *CanceledError) Error() string

Error from error interface

func (*CanceledError) HasDetails

func (e *CanceledError) HasDetails() bool

HasDetails return if this error has strong typed detail data.

type Channel

type Channel interface {
	SendChannel
	ReceiveChannel
}

Channel must be used instead of native go channel by workflow code. Use workflow.NewChannel(ctx) method to create Channel instance.

func NewBufferedChannel

func NewBufferedChannel(ctx Context, size int) Channel

NewBufferedChannel create new buffered Channel instance

func NewChannel

func NewChannel(ctx Context) Channel

NewChannel create new Channel instance

func NewNamedBufferedChannel

func NewNamedBufferedChannel(ctx Context, name string, size int) Channel

NewNamedBufferedChannel create new BufferedChannel instance with a given human readable name. Name appears in stack traces that are blocked on this Channel.

func NewNamedChannel

func NewNamedChannel(ctx Context, name string) Channel

NewNamedChannel create new Channel instance with a given human readable name. Name appears in stack traces that are blocked on this channel.

type CheckHealthRequest added in v1.15.0

type CheckHealthRequest struct{}

CheckHealthRequest is a request for Client.CheckHealth.

type CheckHealthResponse added in v1.15.0

type CheckHealthResponse struct{}

CheckHealthResponse is a response for Client.CheckHealth.

type ChildWorkflowExecutionAlreadyStartedError added in v1.11.0

type ChildWorkflowExecutionAlreadyStartedError struct{}

ChildWorkflowExecutionAlreadyStartedError is set as the cause of ChildWorkflowExecutionError when failure is due the child workflow having already started.

func (*ChildWorkflowExecutionAlreadyStartedError) Error added in v1.11.0

Error from error interface

type ChildWorkflowExecutionError

type ChildWorkflowExecutionError struct {
	// contains filtered or unexported fields
}

ChildWorkflowExecutionError is returned from workflow when child workflow returned an error. Unwrap this error to get actual cause.

func NewChildWorkflowExecutionError

func NewChildWorkflowExecutionError(
	namespace string,
	workflowID string,
	runID string,
	workflowType string,
	initiatedEventID int64,
	startedEventID int64,
	retryState enumspb.RetryState,
	cause error,
) *ChildWorkflowExecutionError

NewChildWorkflowExecutionError creates ChildWorkflowExecutionError instance.

func (*ChildWorkflowExecutionError) Error

Error from error interface

func (*ChildWorkflowExecutionError) Unwrap

func (e *ChildWorkflowExecutionError) Unwrap() error

type ChildWorkflowFuture

type ChildWorkflowFuture interface {
	Future
	// GetChildWorkflowExecution returns a future that will be ready when child workflow execution started. You can
	// get the WorkflowExecution of the child workflow from the future. Then you can use Workflow ID and RunID of
	// child workflow to cancel or send signal to child workflow.
	//  childWorkflowFuture := workflow.ExecuteChildWorkflow(ctx, child, ...)
	//  var childWE workflow.Execution
	//  if err := childWorkflowFuture.GetChildWorkflowExecution().Get(ctx, &childWE); err == nil {
	//      // child workflow started, you can use childWE to get the WorkflowID and RunID of child workflow
	//  }
	GetChildWorkflowExecution() Future

	// SignalChildWorkflow sends a signal to the child workflow. This call will block until child workflow is started.
	SignalChildWorkflow(ctx Context, signalName string, data interface{}) Future
}

ChildWorkflowFuture represents the result of a child workflow execution

func ExecuteChildWorkflow

func ExecuteChildWorkflow(ctx Context, childWorkflow interface{}, args ...interface{}) ChildWorkflowFuture

ExecuteChildWorkflow requests child workflow execution in the context of a workflow. Context can be used to pass the settings for the child workflow. For example: task queue that this child workflow should be routed, timeouts that need to be configured. Use ChildWorkflowOptions to pass down the options.

 cwo := ChildWorkflowOptions{
	    WorkflowExecutionTimeout: 10 * time.Minute,
	    WorkflowTaskTimeout: time.Minute,
	}
 ctx := WithChildWorkflowOptions(ctx, cwo)

Input childWorkflow is either a workflow name or a workflow function that is getting scheduled. Input args are the arguments that need to be passed to the child workflow function represented by childWorkflow.

If the child workflow failed to complete then the future get error would indicate the failure. The error will be of type *ChildWorkflowExecutionError. It will have important child workflow information and actual error that caused child workflow failure. Use errors.Unwrap to get this error or errors.As to check it type which can be one of *ApplicationError, *TimeoutError, or *CanceledError.

You can cancel the pending child workflow using context(workflow.WithCancel(ctx)) and that will fail the workflow with *CanceledError set as cause for *ChildWorkflowExecutionError.

ExecuteChildWorkflow returns ChildWorkflowFuture.

type ChildWorkflowOptions

type ChildWorkflowOptions struct {
	// Namespace of the child workflow.
	// Optional: the current workflow (parent)'s namespace will be used if this is not provided.
	Namespace string

	// WorkflowID of the child workflow to be scheduled.
	// Optional: an auto generated workflowID will be used if this is not provided.
	WorkflowID string

	// TaskQueue that the child workflow needs to be scheduled on.
	// Optional: the parent workflow task queue will be used if this is not provided.
	TaskQueue string

	// WorkflowExecutionTimeout - The end to end timeout for the child workflow execution including retries
	// and continue as new.
	// Optional: defaults to unlimited.
	WorkflowExecutionTimeout time.Duration

	// WorkflowRunTimeout - The timeout for a single run of the child workflow execution. Each retry or
	// continue as new should obey this timeout. Use WorkflowExecutionTimeout to specify how long the parent
	// is willing to wait for the child completion.
	// Optional: defaults to WorkflowExecutionTimeout
	WorkflowRunTimeout time.Duration

	// WorkflowTaskTimeout - Maximum execution time of a single Workflow Task. In the majority of cases there is
	// no need to change this timeout. Note that this timeout is not related to the overall Workflow duration in
	// any way. It defines for how long the Workflow can get blocked in the case of a Workflow Worker crash.
	// Default is 10 seconds. Maximum value allowed by the Temporal Server is 1 minute.
	WorkflowTaskTimeout time.Duration

	// WaitForCancellation - Whether to wait for canceled child workflow to be ended (child workflow can be ended
	// as: completed/failed/timedout/terminated/canceled)
	// Optional: default false
	WaitForCancellation bool

	// WorkflowIDReusePolicy - Whether server allow reuse of workflow ID, can be useful
	// for dedup logic if set to WorkflowIdReusePolicyRejectDuplicate
	WorkflowIDReusePolicy enumspb.WorkflowIdReusePolicy

	// RetryPolicy specify how to retry child workflow if error happens.
	// Optional: default is no retry
	RetryPolicy *RetryPolicy

	// CronSchedule - Optional cron schedule for workflow. If a cron schedule is specified, the workflow will run
	// as a cron based on the schedule. The scheduling will be based on UTC time. Schedule for next run only happen
	// after the current run is completed/failed/timeout. If a RetryPolicy is also supplied, and the workflow failed
	// or timeout, the workflow will be retried based on the retry policy. While the workflow is retrying, it won't
	// schedule its next run. If next schedule is due while workflow is running (or retrying), then it will skip that
	// schedule. Cron workflow will not stop until it is terminated or canceled (by returning temporal.CanceledError).
	// The cron spec is as following:
	// ┌───────────── minute (0 - 59)
	// │ ┌───────────── hour (0 - 23)
	// │ │ ┌───────────── day of the month (1 - 31)
	// │ │ │ ┌───────────── month (1 - 12)
	// │ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday)
	// │ │ │ │ │
	// │ │ │ │ │
	// * * * * *
	CronSchedule string

	// Memo - Optional non-indexed info that will be shown in list workflow.
	Memo map[string]interface{}

	// SearchAttributes - Optional indexed info that can be used in query of List/Scan/Count workflow APIs. The key and value type must be registered on Temporal server side.
	// Use GetSearchAttributes API to get valid key and corresponding value type.
	// For supported operations on different server versions see [Visibility].
	//
	// Deprecated: Use TypedSearchAttributes instead.
	//
	// [Visibility]: https://docs.temporal.io/visibility
	SearchAttributes map[string]interface{}

	// TypedSearchAttributes - Specifies Search Attributes that will be attached to the Workflow. Search Attributes are
	// additional indexed information attributed to workflow and used for search and visibility. The search attributes
	// can be used in query of List/Scan/Count workflow APIs. The key and its value type must be registered on Temporal
	// server side. For supported operations on different server versions see [Visibility].
	//
	// Optional: default to none.
	//
	// [Visibility]: https://docs.temporal.io/visibility
	TypedSearchAttributes SearchAttributes

	// ParentClosePolicy - Optional policy to decide what to do for the child.
	// Default is Terminate (if onboarded to this feature)
	ParentClosePolicy enumspb.ParentClosePolicy

	// VersioningIntent specifies whether this child workflow should run on a worker with a
	// compatible build ID or not. See VersioningIntent.
	// WARNING: Worker versioning is currently experimental
	VersioningIntent VersioningIntent
	// contains filtered or unexported fields
}

ChildWorkflowOptions stores all child workflow specific parameters that will be stored inside of a Context. The current timeout resolution implementation is in seconds and uses math.Ceil(d.Seconds()) as the duration. But is subjected to change in the future.

func GetChildWorkflowOptions added in v1.6.0

func GetChildWorkflowOptions(ctx Context) ChildWorkflowOptions

GetChildWorkflowOptions returns all workflow options present on the context.

type Client

type Client interface {
	// ExecuteWorkflow starts a workflow execution and return a WorkflowRun instance and error
	// The user can use this to start using a function or workflow type name.
	// Either by
	//     ExecuteWorkflow(ctx, options, "workflowTypeName", arg1, arg2, arg3)
	//     or
	//     ExecuteWorkflow(ctx, options, workflowExecuteFn, arg1, arg2, arg3)
	// The errors it can return:
	//  - serviceerror.NamespaceNotFound, if namespace does not exist
	//  - serviceerror.InvalidArgument
	//  - serviceerror.Internal
	//  - serviceerror.Unavailable
	//
	// The current timeout resolution implementation is in seconds and uses math.Ceil(d.Seconds()) as the duration. But is
	// subjected to change in the future.
	//
	// WorkflowRun has three methods:
	//  - GetID() string: which return workflow ID (which is same as StartWorkflowOptions.ID if provided)
	//  - GetRunID() string: which return the first started workflow run ID (please see below)
	//  - Get(ctx context.Context, valuePtr interface{}) error: which will fill the workflow
	//    execution result to valuePtr, if workflow execution is a success, or return corresponding
	//    error. This is a blocking API.
	// NOTE: if the started workflow return ContinueAsNewError during the workflow execution, the
	// return result of GetRunID() will be the started workflow run ID, not the new run ID caused by ContinueAsNewError,
	// however, Get(ctx context.Context, valuePtr interface{}) will return result from the run which did not return ContinueAsNewError.
	// Say ExecuteWorkflow started a workflow, in its first run, has run ID "run ID 1", and returned ContinueAsNewError,
	// the second run has run ID "run ID 2" and return some result other than ContinueAsNewError:
	// GetRunID() will always return "run ID 1" and  Get(ctx context.Context, valuePtr interface{}) will return the result of second run.
	// NOTE: DO NOT USE THIS API INSIDE A WORKFLOW, USE workflow.ExecuteChildWorkflow instead
	ExecuteWorkflow(ctx context.Context, options StartWorkflowOptions, workflow interface{}, args ...interface{}) (WorkflowRun, error)

	// GetWorkflow retrieves a workflow execution and return a WorkflowRun instance
	// - workflow ID of the workflow.
	// - runID can be default(empty string). if empty string then it will pick the last running execution of that workflow ID.
	//
	// WorkflowRun has three methods:
	//  - GetID() string: which return workflow ID (which is same as StartWorkflowOptions.ID if provided)
	//  - GetRunID() string: which return the first started workflow run ID (please see below)
	//  - Get(ctx context.Context, valuePtr interface{}) error: which will fill the workflow
	//    execution result to valuePtr, if workflow execution is a success, or return corresponding
	//    error. This is a blocking API.
	// NOTE: if the retrieved workflow returned ContinueAsNewError during the workflow execution, the
	// return result of GetRunID() will be the retrieved workflow run ID, not the new run ID caused by ContinueAsNewError,
	// however, Get(ctx context.Context, valuePtr interface{}) will return result from the run which did not return ContinueAsNewError.
	GetWorkflow(ctx context.Context, workflowID string, runID string) WorkflowRun

	// SignalWorkflow sends a signals to a workflow in execution
	// - workflow ID of the workflow.
	// - runID can be default(empty string). if empty string then it will pick the running execution of that workflow ID.
	// - signalName name to identify the signal.
	// The errors it can return:
	//  - serviceerror.NotFound
	//  - serviceerror.Internal
	//  - serviceerror.Unavailable
	SignalWorkflow(ctx context.Context, workflowID string, runID string, signalName string, arg interface{}) error

	// SignalWithStartWorkflow sends a signal to a running workflow.
	// If the workflow is not running or not found, it starts the workflow and then sends the signal in transaction.
	// - workflowID, signalName, signalArg are same as SignalWorkflow's parameters
	// - options, workflow, workflowArgs are same as StartWorkflow's parameters
	// - the workflowID parameter is used instead of options.ID. If the latter is present, it must match the workflowID.
	// Note: options.WorkflowIDReusePolicy is default to AllowDuplicate.
	// The errors it can return:
	//  - serviceerror.NotFound
	//  - serviceerror.InvalidArgument
	//  - serviceerror.Internal
	//  - serviceerror.Unavailable
	SignalWithStartWorkflow(ctx context.Context, workflowID string, signalName string, signalArg interface{},
		options StartWorkflowOptions, workflow interface{}, workflowArgs ...interface{}) (WorkflowRun, error)

	// CancelWorkflow cancels a workflow in execution
	// - workflow ID of the workflow.
	// - runID can be default(empty string). if empty string then it will pick the running execution of that workflow ID.
	// The errors it can return:
	//  - serviceerror.NotFound
	//  - serviceerror.InvalidArgument
	//  - serviceerror.Internal
	//  - serviceerror.Unavailable
	CancelWorkflow(ctx context.Context, workflowID string, runID string) error

	// TerminateWorkflow terminates a workflow execution.
	// workflowID is required, other parameters are optional.
	// - workflow ID of the workflow.
	// - runID can be default(empty string). if empty string then it will pick the running execution of that workflow ID.
	// The errors it can return:
	//  - serviceerror.NotFound
	//  - serviceerror.InvalidArgument
	//  - serviceerror.Internal
	//  - serviceerror.Unavailable
	TerminateWorkflow(ctx context.Context, workflowID string, runID string, reason string, details ...interface{}) error

	// GetWorkflowHistory gets history events of a particular workflow
	// - workflow ID of the workflow.
	// - runID can be default(empty string). if empty string then it will pick the last running execution of that workflow ID.
	// - whether use long poll for tracking new events: when the workflow is running, there can be new events generated during iteration
	//    of HistoryEventIterator, if isLongPoll == true, then iterator will do long poll, tracking new history event, i.e. the iteration
	//   will not be finished until workflow is finished; if isLongPoll == false, then iterator will only return current history events.
	// - whether return all history events or just the last event, which contains the workflow execution end result
	// Example:-
	//  To iterate all events,
	//    iter := GetWorkflowHistory(ctx, workflowID, runID, isLongPoll, filterType)
	//    events := []*shared.HistoryEvent{}
	//    for iter.HasNext() {
	//      event, err := iter.Next()
	//      if err != nil {
	//        return err
	//      }
	//      events = append(events, event)
	//    }
	GetWorkflowHistory(ctx context.Context, workflowID string, runID string, isLongPoll bool, filterType enumspb.HistoryEventFilterType) HistoryEventIterator

	// CompleteActivity reports activity completed.
	// activity Execute method can return activity.ErrResultPending to
	// indicate the activity is not completed when it's Execute method returns. In that case, this CompleteActivity() method
	// should be called when that activity is completed with the actual result and error. If err is nil, activity task
	// completed event will be reported; if err is CanceledError, activity task canceled event will be reported; otherwise,
	// activity task failed event will be reported.
	// An activity implementation should use GetActivityInfo(ctx).TaskToken function to get task token to use for completion.
	// Example:-
	//  To complete with a result.
	//    CompleteActivity(token, "Done", nil)
	//  To fail the activity with an error.
	//      CompleteActivity(token, nil, temporal.NewApplicationError("reason", details)
	// The activity can fail with below errors ApplicationError, TimeoutError, CanceledError.
	CompleteActivity(ctx context.Context, taskToken []byte, result interface{}, err error) error

	// CompleteActivityByID reports activity completed.
	// Similar to CompleteActivity, but may save user from keeping taskToken info.
	// activity Execute method can return activity.ErrResultPending to
	// indicate the activity is not completed when it's Execute method returns. In that case, this CompleteActivityById() method
	// should be called when that activity is completed with the actual result and error. If err is nil, activity task
	// completed event will be reported; if err is CanceledError, activity task canceled event will be reported; otherwise,
	// activity task failed event will be reported.
	// An activity implementation should use activityID provided in ActivityOption to use for completion.
	// namespace name, workflowID, activityID are required, runID is optional.
	// The errors it can return:
	//  - ApplicationError
	//  - TimeoutError
	//  - CanceledError
	CompleteActivityByID(ctx context.Context, namespace, workflowID, runID, activityID string, result interface{}, err error) error

	// RecordActivityHeartbeat records heartbeat for an activity.
	// details - is the progress you want to record along with heart beat for this activity.
	// The errors it can return:
	//  - serviceerror.NotFound
	//  - serviceerror.Internal
	//  - serviceerror.Unavailable
	RecordActivityHeartbeat(ctx context.Context, taskToken []byte, details ...interface{}) error

	// RecordActivityHeartbeatByID records heartbeat for an activity.
	// details - is the progress you want to record along with heart beat for this activity.
	// The errors it can return:
	//  - serviceerror.NotFound
	//  - serviceerror.Internal
	//  - serviceerror.Unavailable
	RecordActivityHeartbeatByID(ctx context.Context, namespace, workflowID, runID, activityID string, details ...interface{}) error

	// ListClosedWorkflow gets closed workflow executions based on request filters
	// The errors it can return:
	//  - serviceerror.InvalidArgument
	//  - serviceerror.Internal
	//  - serviceerror.Unavailable
	//  - serviceerror.NamespaceNotFound
	ListClosedWorkflow(ctx context.Context, request *workflowservice.ListClosedWorkflowExecutionsRequest) (*workflowservice.ListClosedWorkflowExecutionsResponse, error)

	// ListOpenWorkflow gets open workflow executions based on request filters
	// The errors it can return:
	//  - serviceerror.InvalidArgument
	//  - serviceerror.Internal
	//  - serviceerror.Unavailable
	//  - serviceerror.NamespaceNotFound
	ListOpenWorkflow(ctx context.Context, request *workflowservice.ListOpenWorkflowExecutionsRequest) (*workflowservice.ListOpenWorkflowExecutionsResponse, error)

	// ListWorkflow gets workflow executions based on query.The query is basically the SQL WHERE clause,
	// examples:
	//  - "(WorkflowID = 'wid1' or (WorkflowType = 'type2' and WorkflowID = 'wid2'))".
	//  - "CloseTime between '2019-08-27T15:04:05+00:00' and '2019-08-28T15:04:05+00:00'".
	//  - to list only open workflow use "CloseTime is null"
	// Retrieved workflow executions are sorted by StartTime in descending order when list open workflow,
	// and sorted by CloseTime in descending order for other queries.
	// For supported operations on different server versions see [Visibility].
	// The errors it can return:
	//  - serviceerror.InvalidArgument
	//  - serviceerror.Internal
	//  - serviceerror.Unavailable
	//
	// [Visibility]: https://docs.temporal.io/visibility
	ListWorkflow(ctx context.Context, request *workflowservice.ListWorkflowExecutionsRequest) (*workflowservice.ListWorkflowExecutionsResponse, error)

	// ListArchivedWorkflow gets archived workflow executions based on query. This API will return BadRequest if Temporal
	// cluster or target namespace is not configured for visibility archival or read is not enabled. The query is basically the SQL WHERE clause.
	// However, different visibility archivers have different limitations on the query. Please check the documentation of the visibility archiver used
	// by your namespace to see what kind of queries are accept and whether retrieved workflow executions are ordered or not.
	// The errors it can return:
	//  - serviceerror.InvalidArgument
	//  - serviceerror.Internal
	//  - serviceerror.Unavailable
	ListArchivedWorkflow(ctx context.Context, request *workflowservice.ListArchivedWorkflowExecutionsRequest) (*workflowservice.ListArchivedWorkflowExecutionsResponse, error)

	// ScanWorkflow gets workflow executions based on query. The query is basically the SQL WHERE clause
	// (see ListWorkflow for query examples).
	// ScanWorkflow should be used when retrieving large amount of workflows and order is not needed.
	// It will use more resources than ListWorkflow, but will be several times faster
	// when retrieving millions of workflows.
	// For supported operations on different server versions see [Visibility].
	// The errors it can return:
	//  - serviceerror.InvalidArgument
	//  - serviceerror.Internal
	//  - serviceerror.Unavailable
	// [Visibility]: https://docs.temporal.io/visibility
	ScanWorkflow(ctx context.Context, request *workflowservice.ScanWorkflowExecutionsRequest) (*workflowservice.ScanWorkflowExecutionsResponse, error)

	// CountWorkflow gets number of workflow executions based on query. The query is basically the SQL WHERE clause
	// (see ListWorkflow for query examples).
	// For supported operations on different server versions see [Visibility].
	// The errors it can return:
	//  - serviceerror.InvalidArgument
	//  - serviceerror.Internal
	//  - serviceerror.Unavailable
	//
	// [Visibility]: https://docs.temporal.io/visibility
	CountWorkflow(ctx context.Context, request *workflowservice.CountWorkflowExecutionsRequest) (*workflowservice.CountWorkflowExecutionsResponse, error)

	// GetSearchAttributes returns valid search attributes keys and value types.
	// The search attributes can be used in query of List/Scan/Count APIs. Adding new search attributes requires temporal server
	// to update dynamic config ValidSearchAttributes.
	GetSearchAttributes(ctx context.Context) (*workflowservice.GetSearchAttributesResponse, error)

	// QueryWorkflow queries a given workflow execution and returns the query result synchronously. Parameter workflowID
	// and queryType are required, other parameters are optional. The workflowID and runID (optional) identify the
	// target workflow execution that this query will be send to. If runID is not specified (empty string), server will
	// use the currently running execution of that workflowID. The queryType specifies the type of query you want to
	// run. By default, temporal supports "__stack_trace" as a standard query type, which will return string value
	// representing the call stack of the target workflow. The target workflow could also setup different query handler
	// to handle custom query types.
	// See comments at workflow.SetQueryHandler(ctx Context, queryType string, handler interface{}) for more details
	// on how to setup query handler within the target workflow.
	// - workflowID is required.
	// - runID can be default(empty string). if empty string then it will pick the running execution of that workflow ID.
	// - queryType is the type of the query.
	// - args... are the optional query parameters.
	// The errors it can return:
	//  - serviceerror.InvalidArgument
	//  - serviceerror.Internal
	//  - serviceerror.Unavailable
	//  - serviceerror.NotFound
	//  - serviceerror.QueryFailed
	QueryWorkflow(ctx context.Context, workflowID string, runID string, queryType string, args ...interface{}) (converter.EncodedValue, error)

	// QueryWorkflowWithOptions queries a given workflow execution and returns the query result synchronously.
	// See QueryWorkflowWithOptionsRequest and QueryWorkflowWithOptionsResponse for more information.
	// The errors it can return:
	//  - serviceerror.InvalidArgument
	//  - serviceerror.Internal
	//  - serviceerror.Unavailable
	//  - serviceerror.NotFound
	//  - serviceerror.QueryFailed
	QueryWorkflowWithOptions(ctx context.Context, request *QueryWorkflowWithOptionsRequest) (*QueryWorkflowWithOptionsResponse, error)

	// DescribeWorkflowExecution returns information about the specified workflow execution.
	// The errors it can return:
	//  - serviceerror.InvalidArgument
	//  - serviceerror.Internal
	//  - serviceerror.Unavailable
	//  - serviceerror.NotFound
	DescribeWorkflowExecution(ctx context.Context, workflowID, runID string) (*workflowservice.DescribeWorkflowExecutionResponse, error)

	// DescribeTaskQueue returns information about the target taskqueue, right now this API returns the
	// pollers which polled this taskqueue in last few minutes.
	// The errors it can return:
	//  - serviceerror.InvalidArgument
	//  - serviceerror.Internal
	//  - serviceerror.Unavailable
	//  - serviceerror.NotFound
	DescribeTaskQueue(ctx context.Context, taskqueue string, taskqueueType enumspb.TaskQueueType) (*workflowservice.DescribeTaskQueueResponse, error)

	// ResetWorkflowExecution reset an existing workflow execution to WorkflowTaskFinishEventId(exclusive).
	// And it will immediately terminating the current execution instance.
	// RequestId is used to deduplicate requests. It will be autogenerated if not set.
	ResetWorkflowExecution(ctx context.Context, request *workflowservice.ResetWorkflowExecutionRequest) (*workflowservice.ResetWorkflowExecutionResponse, error)

	// UpdateWorkerBuildIdCompatibility allows you to update the worker-build-id based version sets for a particular
	// task queue. This is used in conjunction with workers who specify their build id and thus opt into the
	// feature.
	UpdateWorkerBuildIdCompatibility(ctx context.Context, options *UpdateWorkerBuildIdCompatibilityOptions) error

	// GetWorkerBuildIdCompatibility returns the worker-build-id based version sets for a particular task queue.
	GetWorkerBuildIdCompatibility(ctx context.Context, options *GetWorkerBuildIdCompatibilityOptions) (*WorkerBuildIDVersionSets, error)

	// GetWorkerTaskReachability returns which versions are is still in use by open or closed workflows.
	GetWorkerTaskReachability(ctx context.Context, options *GetWorkerTaskReachabilityOptions) (*WorkerTaskReachability, error)

	// DescribeTaskQueueEnhanced returns information about the target task queue, broken down by Build Id:
	//   - List of pollers
	//   - Workflow Reachability status
	//   - Backlog info for Workflow and/or Activity tasks
	// When not supported by the server, it returns an empty [TaskQueueDescription] if there is no information
	// about the task queue, or an error when the response identifies an unsupported server.
	// Note that using a sticky queue as target is not supported.
	// Also, workflow reachability status is eventually consistent, and it could take a few minutes to update.
	// WARNING: Worker versioning is currently experimental, and requires server 1.24+
	DescribeTaskQueueEnhanced(ctx context.Context, options DescribeTaskQueueEnhancedOptions) (TaskQueueDescription, error)

	// UpdateWorkerVersioningRules allows updating the worker-build-id based assignment and redirect rules for a given
	// task queue. This is used in conjunction with workers who specify their build id and thus opt into the feature.
	// The errors it can return:
	//  - serviceerror.FailedPrecondition when the conflict token is invalid
	// WARNING: Worker versioning is currently experimental, and requires server 1.24+
	UpdateWorkerVersioningRules(ctx context.Context, options UpdateWorkerVersioningRulesOptions) (*WorkerVersioningRules, error)

	// GetWorkerVersioningRules returns the worker-build-id assignment and redirect rules for a task queue.
	// WARNING: Worker versioning is currently experimental, and requires server 1.24+
	GetWorkerVersioningRules(ctx context.Context, options GetWorkerVersioningOptions) (*WorkerVersioningRules, error)

	// CheckHealth performs a server health check using the gRPC health check
	// API. If the check fails, an error is returned.
	CheckHealth(ctx context.Context, request *CheckHealthRequest) (*CheckHealthResponse, error)

	// UpdateWorkflow issues an update request to the
	// specified workflow execution and returns a handle to the update that
	// is running in in parallel with the calling thread. Errors returned
	// from the server will be exposed through the return value of
	// WorkflowExecutionUpdateHandle.Get(). Errors that occur before the
	// update is requested (e.g. if the required workflow ID field is
	// missing from the UpdateWorkflowOptions) are returned
	// directly from this function call.
	// NOTE: Experimental
	UpdateWorkflow(ctx context.Context, options UpdateWorkflowOptions) (WorkflowUpdateHandle, error)

	// GetWorkflowUpdateHandle creates a handle to the referenced update
	// which can be polled for an outcome. Note that runID is optional and
	// if not specified the most recent runID will be used.
	// NOTE: Experimental
	GetWorkflowUpdateHandle(GetWorkflowUpdateHandleOptions) WorkflowUpdateHandle

	// WorkflowService provides access to the underlying gRPC service. This should only be used for advanced use cases
	// that cannot be accomplished via other Client methods. Unlike calls to other Client methods, calls directly to the
	// service are not configured with internal semantics such as automatic retries.
	WorkflowService() workflowservice.WorkflowServiceClient

	// OperatorService creates a new operator service client with the same gRPC connection as this client.
	OperatorService() operatorservice.OperatorServiceClient

	// Schedule creates a new shedule client with the same gRPC connection as this client.
	ScheduleClient() ScheduleClient

	// Close client and clean up underlying resources.
	Close()
}

Client is the client for starting and getting information about a workflow executions as well as completing activities asynchronously.

func DialClient added in v1.15.0

func DialClient(ctx context.Context, options ClientOptions) (Client, error)

DialClient creates a client and attempts to connect to the server.

func NewClient deprecated

func NewClient(ctx context.Context, options ClientOptions) (Client, error)

NewClient creates an instance of a workflow client

Deprecated: Use DialClient or NewLazyClient instead.

func NewClientFromExisting added in v1.17.0

func NewClientFromExisting(ctx context.Context, existingClient Client, options ClientOptions) (Client, error)

NewClientFromExisting creates a new client using the same connection as the existing client.

func NewLazyClient added in v1.15.0

func NewLazyClient(options ClientOptions) (Client, error)

NewLazyClient creates a client and does not attempt to connect to the server.

type ClientCancelWorkflowInput added in v1.12.0

type ClientCancelWorkflowInput struct {
	WorkflowID string
	RunID      string
}

ClientCancelWorkflowInput is the input to ClientOutboundInterceptor.CancelWorkflow.

type ClientExecuteWorkflowInput added in v1.12.0

type ClientExecuteWorkflowInput struct {
	Options      *StartWorkflowOptions
	WorkflowType string
	Args         []interface{}
}

ClientExecuteWorkflowInput is the input to ClientOutboundInterceptor.ExecuteWorkflow.

type ClientInterceptor added in v1.12.0

type ClientInterceptor interface {
	// This is called on client creation if set via client options
	InterceptClient(next ClientOutboundInterceptor) ClientOutboundInterceptor
	// contains filtered or unexported methods
}

ClientInterceptor for providing a ClientOutboundInterceptor to intercept certain workflow-specific client calls from the SDK. See documentation in the interceptor package for more details.

type ClientInterceptorBase added in v1.12.0

type ClientInterceptorBase struct{}

ClientInterceptorBase is a default implementation of ClientInterceptor meant for embedding. See documentation in the interceptor package for more details.

func (*ClientInterceptorBase) InterceptClient added in v1.12.0

InterceptClient implements ClientInterceptor.InterceptClient.

type ClientOptions

type ClientOptions struct {
	// Optional: To set the host:port for this client to connect to.
	// default: localhost:7233
	//
	// This is a gRPC address and therefore can also support a special-formatted address of "<resolver>:///<value>" that
	// will use a registered resolver. By default all hosts returned from the resolver will be used in a round-robin
	// fashion.
	//
	// The "dns" resolver is registered by and used by default.
	//
	// A custom resolver can be created to provide multiple hosts in other ways. For example, to manually provide
	// multiple IPs to round-robin across, a google.golang.org/grpc/resolver/manual resolver can be created and
	// registered with google.golang.org/grpc/resolver with a custom scheme:
	//    builder := manual.NewBuilderWithScheme("myresolver")
	//    builder.InitialState(resolver.State{Addresses: []resolver.Address{{Addr: "1.2.3.4:1234"}, {Addr: "2.3.4.5:2345"}}})
	//    resolver.Register(builder)
	//    c, err := client.Dial(client.Options{HostPort: "myresolver:///ignoredvalue"})
	// Other more advanced resolvers can also be registered.
	HostPort string

	// Optional: To set the namespace name for this client to work with.
	// default: default
	Namespace string

	// Optional: Set the credentials for this client.
	Credentials Credentials

	// Optional: Logger framework can use to log.
	// default: default logger provided.
	Logger log.Logger

	// Optional: Metrics handler for reporting metrics.
	// default: no metrics.
	MetricsHandler metrics.Handler

	// Optional: Sets an identify that can be used to track this host for debugging.
	// default: default identity that include hostname, groupName and process ID.
	Identity string

	// Optional: Sets DataConverter to customize serialization/deserialization of arguments in Temporal
	// default: defaultDataConverter, an combination of google protobuf converter, gogo protobuf converter and json converter
	DataConverter converter.DataConverter

	// Optional: Sets FailureConverter to customize serialization/deserialization of errors.
	// default: temporal.DefaultFailureConverter, does not encode any fields of the error. Use temporal.NewDefaultFailureConverter
	// options to configure or create a custom converter.
	FailureConverter converter.FailureConverter

	// Optional: Sets ContextPropagators that allows users to control the context information passed through a workflow
	// default: nil
	ContextPropagators []ContextPropagator

	// Optional: Sets options for server connection that allow users to control features of connections such as TLS settings.
	// default: no extra options
	ConnectionOptions ConnectionOptions

	// Optional: HeadersProvider will be invoked on every outgoing gRPC request and gives user ability to
	// set custom request headers. This can be used to set auth headers for example.
	HeadersProvider HeadersProvider

	// Optional parameter that is designed to be used *in tests*. It gets invoked last in
	// the gRPC interceptor chain and can be used to induce artificial failures in test scenarios.
	TrafficController TrafficController

	// Interceptors to apply to some calls of the client. Earlier interceptors
	// wrap later interceptors.
	//
	// Any interceptors that also implement Interceptor (meaning they implement
	// WorkerInterceptor in addition to ClientInterceptor) will be used for
	// worker interception as well. When worker interceptors are here and in
	// worker options, the ones here wrap the ones in worker options. The same
	// interceptor should not be set here and in worker options.
	Interceptors []ClientInterceptor

	// If set true, error code labels will not be included on request failure metrics.
	DisableErrorCodeMetricTags bool
}

ClientOptions are optional parameters for Client creation.

type ClientOutboundInterceptor added in v1.12.0

type ClientOutboundInterceptor interface {
	// ExecuteWorkflow intercepts client.Client.ExecuteWorkflow.
	// interceptor.Header will return a non-nil map for this context.
	ExecuteWorkflow(context.Context, *ClientExecuteWorkflowInput) (WorkflowRun, error)

	// CreateSchedule - Intercept a service call to CreateSchedule
	CreateSchedule(ctx context.Context, options *ScheduleClientCreateInput) (ScheduleHandle, error)

	// SignalWorkflow intercepts client.Client.SignalWorkflow.
	// interceptor.Header will return a non-nil map for this context.
	SignalWorkflow(context.Context, *ClientSignalWorkflowInput) error

	// SignalWithStartWorkflow intercepts client.Client.SignalWithStartWorkflow.
	// interceptor.Header will return a non-nil map for this context.
	SignalWithStartWorkflow(context.Context, *ClientSignalWithStartWorkflowInput) (WorkflowRun, error)

	// CancelWorkflow intercepts client.Client.CancelWorkflow.
	CancelWorkflow(context.Context, *ClientCancelWorkflowInput) error

	// TerminateWorkflow intercepts client.Client.TerminateWorkflow.
	TerminateWorkflow(context.Context, *ClientTerminateWorkflowInput) error

	// QueryWorkflow intercepts client.Client.QueryWorkflow.
	// If the query is rejected, QueryWorkflow will return an QueryRejectedError
	// interceptor.Header will return a non-nil map for this context.
	QueryWorkflow(context.Context, *ClientQueryWorkflowInput) (converter.EncodedValue, error)

	// UpdateWorkflow intercepts client.Client.UpdateWorkflow
	// interceptor.Header will return a non-nil map for this context.
	//
	// NOTE: Experimental
	UpdateWorkflow(context.Context, *ClientUpdateWorkflowInput) (WorkflowUpdateHandle, error)

	// PollWorkflowUpdate requests the outcome of a specific update from the
	// server.
	//
	// NOTE: Experimental
	PollWorkflowUpdate(context.Context, *ClientPollWorkflowUpdateInput) (*ClientPollWorkflowUpdateOutput, error)
	// contains filtered or unexported methods
}

ClientOutboundInterceptor is an interface for certain workflow-specific calls originating from the SDK. See documentation in the interceptor package for more details.

type ClientOutboundInterceptorBase added in v1.12.0

type ClientOutboundInterceptorBase struct {
	Next ClientOutboundInterceptor
}

ClientOutboundInterceptorBase is a default implementation of ClientOutboundInterceptor meant for embedding. See documentation in the interceptor package for more details.

func (*ClientOutboundInterceptorBase) CancelWorkflow added in v1.12.0

CancelWorkflow implements ClientOutboundInterceptor.CancelWorkflow.

func (*ClientOutboundInterceptorBase) CreateSchedule added in v1.18.0

ExecuteWorkflow implements ClientOutboundInterceptor.CreateSchedule.

func (*ClientOutboundInterceptorBase) ExecuteWorkflow added in v1.12.0

ExecuteWorkflow implements ClientOutboundInterceptor.ExecuteWorkflow.

func (*ClientOutboundInterceptorBase) PollWorkflowUpdate added in v1.22.2

func (*ClientOutboundInterceptorBase) QueryWorkflow added in v1.12.0

QueryWorkflow implements ClientOutboundInterceptor.QueryWorkflow.

func (*ClientOutboundInterceptorBase) SignalWithStartWorkflow added in v1.12.0

SignalWithStartWorkflow implements ClientOutboundInterceptor.SignalWithStartWorkflow.

func (*ClientOutboundInterceptorBase) SignalWorkflow added in v1.12.0

SignalWorkflow implements ClientOutboundInterceptor.SignalWorkflow.

func (*ClientOutboundInterceptorBase) TerminateWorkflow added in v1.12.0

TerminateWorkflow implements ClientOutboundInterceptor.TerminateWorkflow.

func (*ClientOutboundInterceptorBase) UpdateWorkflow added in v1.20.0

type ClientPollWorkflowUpdateInput added in v1.22.2

type ClientPollWorkflowUpdateInput struct {
	UpdateRef *updatepb.UpdateRef
}

ClientPollWorkflowUpdateInput is the input to ClientOutboundInterceptor.PollWorkflowUpdate.

type ClientPollWorkflowUpdateOutput added in v1.27.0

type ClientPollWorkflowUpdateOutput struct {
	// Result is the result of the update, if it has completed successfully.
	Result converter.EncodedValue
	// Error is the result of a failed update.
	Error error
}

ClientPollWorkflowUpdateOutput is the output to ClientOutboundInterceptor.PollWorkflowUpdate.

type ClientQueryWorkflowInput added in v1.12.0

type ClientQueryWorkflowInput struct {
	WorkflowID           string
	RunID                string
	QueryType            string
	Args                 []interface{}
	QueryRejectCondition enumspb.QueryRejectCondition
}

ClientQueryWorkflowInput is the input to ClientOutboundInterceptor.QueryWorkflow.

type ClientSignalWithStartWorkflowInput added in v1.12.0

type ClientSignalWithStartWorkflowInput struct {
	SignalName   string
	SignalArg    interface{}
	Options      *StartWorkflowOptions
	WorkflowType string
	Args         []interface{}
}

ClientSignalWithStartWorkflowInput is the input to ClientOutboundInterceptor.SignalWithStartWorkflow.

type ClientSignalWorkflowInput added in v1.12.0

type ClientSignalWorkflowInput struct {
	WorkflowID string
	RunID      string
	SignalName string
	Arg        interface{}
}

ClientSignalWorkflowInput is the input to ClientOutboundInterceptor.SignalWorkflow.

type ClientTerminateWorkflowInput added in v1.12.0

type ClientTerminateWorkflowInput struct {
	WorkflowID string
	RunID      string
	Reason     string
	Details    []interface{}
}

ClientTerminateWorkflowInput is the input to ClientOutboundInterceptor.TerminateWorkflow.

type ClientUpdateWorkflowInput added in v1.20.0

type ClientUpdateWorkflowInput struct {
	UpdateID            string
	WorkflowID          string
	UpdateName          string
	Args                []interface{}
	RunID               string
	FirstExecutionRunID string
	WaitForStage        WorkflowUpdateStage
}

ClientUpdateWorkflowInput is the input to ClientOutboundInterceptor.UpdateWorkflow

NOTE: Experimental

type CloudOperationsClient added in v1.28.0

type CloudOperationsClient interface {
	CloudService() cloudservice.CloudServiceClient
	Close()
}

func DialCloudOperationsClient added in v1.28.0

func DialCloudOperationsClient(ctx context.Context, options CloudOperationsClientOptions) (CloudOperationsClient, error)

DialCloudOperationsClient creates a cloud client to perform cloud-management operations.

type CloudOperationsClientOptions added in v1.28.0

type CloudOperationsClientOptions struct {
	// Optional: The credentials for this client. This is essentially required.
	// See [go.temporal.io/sdk/client.NewAPIKeyStaticCredentials],
	// [go.temporal.io/sdk/client.NewAPIKeyDynamicCredentials], and
	// [go.temporal.io/sdk/client.NewMTLSCredentials].
	// Default: No credentials.
	Credentials Credentials

	// Optional: Version header for safer mutations. May or may not be required
	// depending on cloud settings.
	// Default: No header.
	Version string

	// Optional: Advanced server connection options such as TLS settings. Not
	// usually needed.
	ConnectionOptions ConnectionOptions

	// Optional: Logger framework can use to log.
	// Default: Default logger provided.
	Logger log.Logger

	// Optional: Metrics handler for reporting metrics.
	// Default: No metrics
	MetricsHandler metrics.Handler

	// Optional: Overrides the specific host to connect to. Not usually needed.
	// Default: saas-api.tmprl.cloud:443
	HostPort string

	// Optional: Disable TLS.
	// Default: false (i.e. TLS enabled)
	DisableTLS bool
}

CloudOperationsClientOptions are parameters for CloudOperationsClient creation.

WARNING: Cloud operations client is currently experimental.

type CompatibleVersionSet added in v1.22.0

type CompatibleVersionSet struct {
	BuildIDs []string
}

CompatibleVersionSet represents a set of worker build ids which are compatible with each other.

type CompositeTuner added in v1.29.0

type CompositeTuner struct {
	// contains filtered or unexported fields
}

CompositeTuner allows you to build a tuner from multiple slot suppliers.

WARNING: Custom implementations of SlotSupplier are currently experimental.

func (*CompositeTuner) GetActivityTaskSlotSupplier added in v1.29.0

func (c *CompositeTuner) GetActivityTaskSlotSupplier() SlotSupplier

func (*CompositeTuner) GetLocalActivitySlotSupplier added in v1.29.0

func (c *CompositeTuner) GetLocalActivitySlotSupplier() SlotSupplier

func (*CompositeTuner) GetNexusSlotSupplier added in v1.29.0

func (c *CompositeTuner) GetNexusSlotSupplier() SlotSupplier

func (*CompositeTuner) GetWorkflowTaskSlotSupplier added in v1.29.0

func (c *CompositeTuner) GetWorkflowTaskSlotSupplier() SlotSupplier

type CompositeTunerOptions added in v1.29.0

type CompositeTunerOptions struct {
	// WorkflowSlotSupplier is the SlotSupplier used for workflow tasks.
	WorkflowSlotSupplier SlotSupplier
	// ActivitySlotSupplier is the SlotSupplier used for activity tasks.
	ActivitySlotSupplier SlotSupplier
	// LocalActivitySlotSupplier is the SlotSupplier used for local activities.
	LocalActivitySlotSupplier SlotSupplier
	// NexusSlotSupplier is the SlotSupplier used for nexus tasks.
	NexusSlotSupplier SlotSupplier
}

CompositeTunerOptions are the options used by NewCompositeTuner.

type ConnectionOptions

type ConnectionOptions struct {
	// TLS configures connection level security credentials.
	TLS *tls.Config

	// Authority specifies the value to be used as the :authority pseudo-header.
	// This value only used when TLS is nil.
	Authority string

	// Disable keep alive ping from client to the server.
	DisableKeepAliveCheck bool

	// After a duration of this time if the client doesn't see any activity it
	// pings the server to see if the transport is still alive.
	// If set below 10s, a minimum value of 10s will be used instead.
	// default: 30s
	KeepAliveTime time.Duration

	// After having pinged for keepalive check, the client waits for a duration
	// of Timeout and if no activity is seen even after that the connection is
	// closed.
	// default: 15s
	KeepAliveTimeout time.Duration

	// GetSystemInfoTimeout is the timeout for the RPC made by the
	// client to fetch server capabilities.
	GetSystemInfoTimeout time.Duration

	// if true, when there are no active RPCs, Time and Timeout will be ignored and no
	// keepalive pings will be sent.
	// If false, client sends keepalive pings even with no active RPCs
	// default: false
	DisableKeepAlivePermitWithoutStream bool

	// MaxPayloadSize is a number of bytes that gRPC would allow to travel to and from server. Defaults to 128 MB.
	MaxPayloadSize int

	// Advanced dial options for gRPC connections. These are applied after the internal default dial options are
	// applied. Therefore any dial options here may override internal ones. Dial options WithBlock, WithTimeout,
	// WithReturnConnectionError, and FailOnNonTempDialError are ignored since [grpc.NewClient] is used.
	//
	// For gRPC interceptors, internal interceptors such as error handling, metrics, and retrying are done via
	// grpc.WithChainUnaryInterceptor. Therefore to add inner interceptors that are wrapped by those, a
	// grpc.WithChainUnaryInterceptor can be added as an option here. To add a single outer interceptor, a
	// grpc.WithUnaryInterceptor option can be added since grpc.WithUnaryInterceptor is prepended to chains set with
	// grpc.WithChainUnaryInterceptor.
	DialOptions []grpc.DialOption
	// contains filtered or unexported fields
}

ConnectionOptions is provided by SDK consumers to control optional connection params.

type Context

type Context interface {
	// Deadline returns the time when work done on behalf of this context
	// should be canceled.  Deadline returns ok==false when no deadline is
	// set.  Successive calls to Deadline return the same results.
	Deadline() (deadline time.Time, ok bool)

	// Done returns a channel that's closed when work done on behalf of this
	// context should be canceled.  Done may return nil if this context can
	// never be canceled.  Successive calls to Done return the same value.
	//
	// WithCancel arranges for Done to be closed when cancel is called;
	// WithDeadline arranges for Done to be closed when the deadline
	// expires; WithTimeout arranges for Done to be closed when the timeout
	// elapses.
	//
	// Done is provided for use in select statements:
	//
	//  // Stream generates values with DoSomething and sends them to out
	//  // until DoSomething returns an error or ctx.Done is closed.
	//  func Stream(ctx Context, out Channel) (err error) {
	//	for {
	//		v, err := DoSomething(ctx)
	//		if err != nil {
	//			return err
	//		}
	//		s := NewSelector(ctx)
	//		s.AddReceive(ctx.Done(),  func(v interface{}) { err = ctx.Err() })
	//		s.AddReceive(v, func(v interface{}, more bool) { out.Send(ctx, v) })
	//		s.Select(ctx)
	//		if err != nil {
	//			return err
	//		}
	//	}
	//  }
	//
	// See http://blog.golang.org/pipelines for more examples of how to use
	// a Done channel for cancellation.
	Done() Channel

	// Err returns a non-nil error value after Done is closed.  Err returns
	// Canceled if the context was canceled or DeadlineExceeded if the
	// context's deadline passed.  No other values for Err are defined.
	// After Done is closed, successive calls to Err return the same value.
	Err() error

	// Value returns the value associated with this context for key, or nil
	// if no value is associated with key.  Successive calls to Value with
	// the same key returns the same result.
	//
	// Use context values only for request-scoped data that transits
	// processes and API boundaries, not for passing optional parameters to
	// functions.
	//
	// A key identifies a specific value in a Context.  Functions that wish
	// to store values in Context typically allocate a key in a global
	// variable then use that key as the argument to context.WithValue and
	// Context.Value.  A key can be any type that supports equality;
	// packages should define keys as an unexported type to avoid
	// collisions.
	//
	// Packages that define a Context key should provide type-safe accessors
	// for the values stores using that key:
	//
	// 	// Package user defines a User type that's stored in Contexts.
	// 	package user
	//
	// 	import "context"
	//
	// 	// User is the type of value stored in the Contexts.
	// 	type User struct {...}
	//
	// 	// key is an unexported type for keys defined in this package.
	// 	// This prevents collisions with keys defined in other packages.
	// 	type key int
	//
	// 	// userKey is the key for user.User values in Contexts.  It is
	// 	// unexported; clients use user.NewContext and user.FromContext
	// 	// instead of using this key directly.
	// 	var userKey key = 0
	//
	// 	// NewContext returns a new Context that carries value u.
	// 	func NewContext(ctx context.Context, u *User) context.Context {
	// 		return context.WithValue(ctx, userKey, u)
	// 	}
	//
	// 	// FromContext returns the User value stored in ctx, if any.
	// 	func FromContext(ctx context.Context) (*User, bool) {
	// 		u, ok := ctx.Value(userKey).(*User)
	// 		return u, ok
	// 	}
	Value(key interface{}) interface{}
}

Context is a clone of context.Context with Done() returning Channel instead of native channel. A Context carries a deadline, a cancellation signal, and other values across API boundaries.

Context's methods may be called by multiple goroutines simultaneously.

func Background

func Background() Context

Background returns a non-nil, empty Context. It is never canceled, has no values, and has no deadline

func CreateSession

func CreateSession(ctx Context, sessionOptions *SessionOptions) (Context, error)

CreateSession creates a session and returns a new context which contains information of the created session. The session will be created on the taskqueue user specified in ActivityOptions. If none is specified, the default one will be used.

CreationSession will fail in the following situations:

  1. The context passed in already contains a session which is still open (not closed and failed).
  2. All the workers are busy (number of sessions currently running on all the workers have reached MaxConcurrentSessionExecutionSize, which is specified when starting the workers) and session cannot be created within a specified timeout.

If an activity is executed using the returned context, it's regarded as part of the session. All activities within the same session will be executed by the same worker. User still needs to handle the error returned when executing an activity. Session will not be marked as failed if an activity within it returns an error. Only when the worker executing the session is down, that session will be marked as failed. Executing an activity within a failed session will return ErrSessionFailed immediately without scheduling that activity.

The returned session Context will be canceled if the session fails (worker died) or CompleteSession() is called. This means that in these two cases, all user activities scheduled using the returned session Context will also be canceled.

If user wants to end a session since activity returns some error, use CompleteSession API below. New session can be created if necessary to retry the whole session.

Example:

   so := &SessionOptions{
	      ExecutionTimeout: time.Minute,
	      CreationTimeout:  time.Minute,
   }
   sessionCtx, err := CreateSession(ctx, so)
   if err != nil {
		    // Creation failed. Wrong ctx or too many outstanding sessions.
   }
   defer CompleteSession(sessionCtx)
   err = ExecuteActivity(sessionCtx, someActivityFunc, activityInput).Get(sessionCtx, nil)
   if err == ErrSessionFailed {
       // Session has failed
   } else {
       // Handle activity error
   }
   ... // execute more activities using sessionCtx

func RecreateSession

func RecreateSession(ctx Context, recreateToken []byte, sessionOptions *SessionOptions) (Context, error)

RecreateSession recreate a session based on the sessionInfo passed in. Activities executed within the recreated session will be executed by the same worker as the previous session. RecreateSession() returns an error under the same situation as CreateSession() or the token passed in is invalid. It also has the same usage as CreateSession().

The main usage of RecreateSession is for long sessions that are split into multiple runs. At the end of one run, complete the current session, get recreateToken from sessionInfo by calling SessionInfo.GetRecreateToken() and pass the token to the next run. In the new run, session can be recreated using that token.

func WithActivityOptions

func WithActivityOptions(ctx Context, options ActivityOptions) Context

WithActivityOptions adds all options to the copy of the context. The current timeout resolution implementation is in seconds and uses math.Ceil(d.Seconds()) as the duration. But is subjected to change in the future.

func WithChildWorkflowOptions

func WithChildWorkflowOptions(ctx Context, cwo ChildWorkflowOptions) Context

WithChildWorkflowOptions adds all workflow options to the context. The current timeout resolution implementation is in seconds and uses math.Ceil(d.Seconds()) as the duration. But is subjected to change in the future.

func WithDataConverter

func WithDataConverter(ctx Context, dc converter.DataConverter) Context

WithDataConverter adds DataConverter to the context.

func WithHeartbeatTimeout

func WithHeartbeatTimeout(ctx Context, d time.Duration) Context

WithHeartbeatTimeout adds a timeout to the copy of the context. The current timeout resolution implementation is in seconds and uses math.Ceil(d.Seconds()) as the duration. But is subjected to change in the future.

func WithLocalActivityOptions

func WithLocalActivityOptions(ctx Context, options LocalActivityOptions) Context

WithLocalActivityOptions adds local activity options to the copy of the context. The current timeout resolution implementation is in seconds and uses math.Ceil(d.Seconds()) as the duration. But is subjected to change in the future.

func WithRetryPolicy

func WithRetryPolicy(ctx Context, retryPolicy RetryPolicy) Context

WithRetryPolicy adds retry policy to the copy of the context

func WithScheduleToCloseTimeout

func WithScheduleToCloseTimeout(ctx Context, d time.Duration) Context

WithScheduleToCloseTimeout adds a timeout to the copy of the context. The current timeout resolution implementation is in seconds and uses math.Ceil(d.Seconds()) as the duration. But is subjected to change in the future.

func WithScheduleToStartTimeout

func WithScheduleToStartTimeout(ctx Context, d time.Duration) Context

WithScheduleToStartTimeout adds a timeout to the copy of the context. The current timeout resolution implementation is in seconds and uses math.Ceil(d.Seconds()) as the duration. But is subjected to change in the future.

func WithStartToCloseTimeout

func WithStartToCloseTimeout(ctx Context, d time.Duration) Context

WithStartToCloseTimeout adds a timeout to the copy of the context. The current timeout resolution implementation is in seconds and uses math.Ceil(d.Seconds()) as the duration. But is subjected to change in the future.

func WithTaskQueue

func WithTaskQueue(ctx Context, name string) Context

WithTaskQueue adds a task queue to the copy of the context.

func WithTypedSearchAttributes added in v1.26.0

func WithTypedSearchAttributes(ctx Context, searchAttributes SearchAttributes) Context

WithTypedSearchAttributes add these search attribute to the context

func WithValue

func WithValue(parent Context, key interface{}, val interface{}) Context

WithValue returns a copy of parent in which the value associated with key is val.

Use context Values only for request-scoped data that transits processes and APIs, not for passing optional parameters to functions.

func WithWaitForCancellation

func WithWaitForCancellation(ctx Context, wait bool) Context

WithWaitForCancellation adds wait for the cacellation to the copy of the context.

func WithWorkflowID

func WithWorkflowID(ctx Context, workflowID string) Context

WithWorkflowID adds a workflowID to the context.

func WithWorkflowNamespace

func WithWorkflowNamespace(ctx Context, name string) Context

WithWorkflowNamespace adds a namespace to the context.

func WithWorkflowRunTimeout

func WithWorkflowRunTimeout(ctx Context, d time.Duration) Context

WithWorkflowRunTimeout adds a run timeout to the context. The current timeout resolution implementation is in seconds and uses math.Ceil(d.Seconds()) as the duration. But is subjected to change in the future.

func WithWorkflowTaskQueue

func WithWorkflowTaskQueue(ctx Context, name string) Context

WithWorkflowTaskQueue adds a task queue to the context.

func WithWorkflowTaskTimeout

func WithWorkflowTaskTimeout(ctx Context, d time.Duration) Context

WithWorkflowTaskTimeout adds a workflow task timeout to the context. The current timeout resolution implementation is in seconds and uses math.Ceil(d.Seconds()) as the duration. But is subjected to change in the future.

func WithWorkflowVersioningIntent added in v1.23.0

func WithWorkflowVersioningIntent(ctx Context, intent VersioningIntent) Context

WithWorkflowVersioningIntent is used to set the VersioningIntent before constructing a ContinueAsNewError with NewContinueAsNewError. WARNING: Worker versioning is currently experimental

type ContextAware added in v1.6.0

type ContextAware interface {
	WithWorkflowContext(ctx Context) converter.DataConverter
	WithContext(ctx context.Context) converter.DataConverter
}

ContextAware is an optional interface that can be implemented alongside DataConverter. This interface allows Temporal to pass Workflow/Activity contexts to the DataConverter so that it may tailor it's behaviour.

Note that data converters may be called in non-context-aware situations to convert payloads that may not be customized per context. Data converter implementers should not expect or require contextual data be present.

type ContextPropagator

type ContextPropagator interface {
	// Inject injects information from a Go Context into headers
	Inject(context.Context, HeaderWriter) error

	// Extract extracts context information from headers and returns a context
	// object
	Extract(context.Context, HeaderReader) (context.Context, error)

	// InjectFromWorkflow injects information from workflow context into headers
	InjectFromWorkflow(Context, HeaderWriter) error

	// ExtractToWorkflow extracts context information from headers and returns
	// a workflow context
	ExtractToWorkflow(Context, HeaderReader) (Context, error)
}

ContextPropagator is an interface that determines what information from context to pass along

type ContinueAsNewError

type ContinueAsNewError struct {
	// params *ExecuteWorkflowParams
	WorkflowType        *WorkflowType
	Input               *commonpb.Payloads
	Header              *commonpb.Header
	TaskQueueName       string
	WorkflowRunTimeout  time.Duration
	WorkflowTaskTimeout time.Duration

	// Deprecated: WorkflowExecutionTimeout is deprecated and is never set or
	// used internally.
	WorkflowExecutionTimeout time.Duration

	// VersioningIntent specifies whether the continued workflow should run on a worker with a
	// compatible build ID or not. See VersioningIntent.
	VersioningIntent VersioningIntent

	// This is by default nil but may be overridden using NewContinueAsNewErrorWithOptions.
	// It specifies the retry policy which gets carried over to the next run.
	// If not set, the current workflow's retry policy will be carried over automatically.
	//
	// NOTES:
	// 1. This is always nil when returned from a client as a workflow response.
	// 2. Unlike other options that can be overridden using WithWorkflowTaskQueue, WithWorkflowRunTimeout, etc.
	//    we can't introduce an option, say WithWorkflowRetryPolicy, for backward compatibility.
	//    See #676 or IntegrationTestSuite::TestContinueAsNewWithWithChildWF for more details.
	RetryPolicy *RetryPolicy
}

ContinueAsNewError contains information about how to continue the workflow as new.

func (*ContinueAsNewError) Error

func (e *ContinueAsNewError) Error() string

Error from error interface

type ContinueAsNewErrorOptions added in v1.26.0

type ContinueAsNewErrorOptions struct {
	// RetryPolicy specifies the retry policy to be used for the next run.
	// If nil, the current workflow's retry policy will be used.
	RetryPolicy *RetryPolicy
}

ContinueAsNewErrorOptions specifies optional attributes to be carried over to the next run.

type Credentials added in v1.26.0

type Credentials interface {
	// contains filtered or unexported methods
}

Credentials are optional credentials that can be specified in ClientOptions.

func NewAPIKeyDynamicCredentials added in v1.26.0

func NewAPIKeyDynamicCredentials(apiKeyCallback func(context.Context) (string, error)) Credentials

func NewAPIKeyStaticCredentials added in v1.26.0

func NewAPIKeyStaticCredentials(apiKey string) Credentials

func NewMTLSCredentials added in v1.26.0

func NewMTLSCredentials(certificate tls.Certificate) Credentials

type DefaultFailureConverter added in v1.18.0

type DefaultFailureConverter struct {
	// contains filtered or unexported fields
}

DefaultFailureConverter seralizes errors with the option to encode common parameters under Failure.EncodedAttributes

func NewDefaultFailureConverter added in v1.18.0

func NewDefaultFailureConverter(opt DefaultFailureConverterOptions) *DefaultFailureConverter

NewDefaultFailureConverter creates new instance of DefaultFailureConverter.

func (*DefaultFailureConverter) ErrorToFailure added in v1.18.0

func (dfc *DefaultFailureConverter) ErrorToFailure(err error) *failurepb.Failure

ErrorToFailure converts an error to a Failure

func (*DefaultFailureConverter) FailureToError added in v1.18.0

func (dfc *DefaultFailureConverter) FailureToError(failure *failurepb.Failure) error

FailureToError converts an Failure to an error

type DefaultFailureConverterOptions added in v1.18.0

type DefaultFailureConverterOptions struct {
	// Optional: Sets DataConverter to customize serialization/deserialization of fields.
	// default: Default data converter
	DataConverter converter.DataConverter

	// Optional: Whether to encode error messages and stack traces.
	// default: false
	EncodeCommonAttributes bool
}

DefaultFailureConverterOptions are optional parameters for DefaultFailureConverter creation.

type DescribeTaskQueueEnhancedOptions added in v1.27.0

type DescribeTaskQueueEnhancedOptions struct {
	// Name of the task queue. Sticky queues are not supported.
	TaskQueue string
	// An optional queue selector based on versioning. If not provided,
	// the result for the default Build ID will be returned. The default
	// Build ID is the one mentioned in the first unconditional Assignment Rule.
	// If there is no default Build ID, the result for the
	// unversioned queue will be returned.
	Versions *TaskQueueVersionSelection
	// Task queue types to report info about. If not specified, all types are considered.
	TaskQueueTypes []TaskQueueType
	// Include list of pollers for requested task queue types and versions.
	ReportPollers bool
	// Include task reachability for the requested versions and all task types
	// (task reachability is not reported per task type).
	ReportTaskReachability bool
	// Include task queue stats for requested task queue types and versions.
	ReportStats bool
}

DescribeTaskQueueEnhancedOptions is the input to [Client.DescribeTaskQueueEnhanced].

type EncodedValue

type EncodedValue struct {
	// contains filtered or unexported fields
}

EncodedValue is type used to encapsulate/extract encoded result from workflow/activity.

func (EncodedValue) Get

func (b EncodedValue) Get(valuePtr interface{}) error

Get extract data from encoded data to desired value type. valuePtr is pointer to the actual value type.

func (EncodedValue) HasValue

func (b EncodedValue) HasValue() bool

HasValue return whether there is value

type EncodedValues

type EncodedValues struct {
	// contains filtered or unexported fields
}

EncodedValues is a type alias used to encapsulate/extract encoded arguments from workflow/activity.

func (EncodedValues) Get

func (b EncodedValues) Get(valuePtr ...interface{}) error

Get extract data from encoded data to desired value type. valuePtr is pointer to the actual value type.

func (EncodedValues) HasValues

func (b EncodedValues) HasValues() bool

HasValues return whether there are values

type ErrorDetailsValues

type ErrorDetailsValues []interface{}

ErrorDetailsValues is a type alias used hold error details objects.

func (ErrorDetailsValues) Get

func (b ErrorDetailsValues) Get(valuePtr ...interface{}) error

Get extract data from encoded data to desired value type. valuePtr is pointer to the actual value type.

func (ErrorDetailsValues) HasValues

func (b ErrorDetailsValues) HasValues() bool

HasValues return whether there are values.

type EventLevelResetter added in v1.18.0

type EventLevelResetter func(int64)

type ExecuteActivityInput added in v1.12.0

type ExecuteActivityInput struct {
	Args []interface{}
}

ExecuteActivityInput is the input to ActivityInboundInterceptor.ExecuteActivity.

type ExecuteActivityOptions

type ExecuteActivityOptions struct {
	ActivityID             string // Users can choose IDs but our framework makes it optional to decrease the crust.
	TaskQueueName          string
	ScheduleToCloseTimeout time.Duration
	ScheduleToStartTimeout time.Duration
	StartToCloseTimeout    time.Duration
	HeartbeatTimeout       time.Duration
	WaitForCancellation    bool
	OriginalTaskQueueName  string
	RetryPolicy            *commonpb.RetryPolicy
	DisableEagerExecution  bool
	VersioningIntent       VersioningIntent
}

ExecuteActivityOptions option for executing an activity

type ExecuteActivityParams

type ExecuteActivityParams struct {
	ExecuteActivityOptions
	ActivityType  ActivityType
	Input         *commonpb.Payloads
	DataConverter converter.DataConverter
	Header        *commonpb.Header
}

ExecuteActivityParams parameters for executing an activity

type ExecuteLocalActivityOptions

type ExecuteLocalActivityOptions struct {
	ScheduleToCloseTimeout time.Duration
	StartToCloseTimeout    time.Duration
	RetryPolicy            *RetryPolicy
}

ExecuteLocalActivityOptions options for executing a local activity

type ExecuteLocalActivityParams

type ExecuteLocalActivityParams struct {
	ExecuteLocalActivityOptions
	ActivityFn    interface{} // local activity function pointer
	ActivityType  string      // local activity type
	InputArgs     []interface{}
	WorkflowInfo  *WorkflowInfo
	DataConverter converter.DataConverter
	Attempt       int32
	ScheduledTime time.Time
	Header        *commonpb.Header
}

ExecuteLocalActivityParams parameters for executing a local activity

type ExecuteNexusOperationInput added in v1.29.0

type ExecuteNexusOperationInput struct {
	// Client to start the operation with.
	Client NexusClient
	// Operation name or OperationReference from the Nexus SDK.
	Operation any
	// Operation input.
	Input any
	// Options for starting the operation.
	Options NexusOperationOptions
	// Header to attach to the request.
	NexusHeader nexus.Header
}

ExecuteNexusOperationInput is the input to WorkflowOutboundInterceptor.ExecuteNexusOperation.

NOTE: Experimental

type ExecuteWorkflowInput added in v1.12.0

type ExecuteWorkflowInput struct {
	Args []interface{}
}

ExecuteWorkflowInput is the input to WorkflowInboundInterceptor.ExecuteWorkflow.

type ExecuteWorkflowParams

type ExecuteWorkflowParams struct {
	WorkflowOptions
	WorkflowType *WorkflowType
	Input        *commonpb.Payloads
	Header       *commonpb.Header
	// contains filtered or unexported fields
}

ExecuteWorkflowParams parameters of the workflow invocation

type FixedSizeSlotSupplier added in v1.29.0

type FixedSizeSlotSupplier struct {
	// contains filtered or unexported fields
}

FixedSizeSlotSupplier is a slot supplier that will only ever issue at most a fixed number of slots.

func NewFixedSizeSlotSupplier added in v1.29.0

func NewFixedSizeSlotSupplier(numSlots int) (*FixedSizeSlotSupplier, error)

NewFixedSizeSlotSupplier creates a new FixedSizeSlotSupplier with the given number of slots.

func (*FixedSizeSlotSupplier) MarkSlotUsed added in v1.29.0

func (f *FixedSizeSlotSupplier) MarkSlotUsed(SlotMarkUsedInfo)

func (*FixedSizeSlotSupplier) MaxSlots added in v1.29.0

func (f *FixedSizeSlotSupplier) MaxSlots() int

func (*FixedSizeSlotSupplier) ReleaseSlot added in v1.29.0

func (f *FixedSizeSlotSupplier) ReleaseSlot(SlotReleaseInfo)

func (*FixedSizeSlotSupplier) ReserveSlot added in v1.29.0

func (*FixedSizeSlotSupplier) TryReserveSlot added in v1.29.0

type FixedSizeTunerOptions added in v1.29.0

type FixedSizeTunerOptions struct {
	// NumWorkflowSlots is the number of slots available for workflow tasks.
	NumWorkflowSlots int
	// NumActivitySlots is the number of slots available for activity tasks.
	NumActivitySlots int
	// NumLocalActivitySlots is the number of slots available for local activities.
	NumLocalActivitySlots int
	// NumNexusSlots is the number of slots available for nexus tasks.
	NumNexusSlots int
}

FixedSizeTunerOptions are the options used by NewFixedSizeTuner.

type Future

type Future interface {
	// Get blocks until the future is ready. When ready it either returns non nil error or assigns result value to
	// the provided pointer.
	// Example:
	//  var v string
	//  if err := f.Get(ctx, &v); err != nil {
	//      return err
	//  }
	//
	// The valuePtr parameter can be nil when the encoded result value is not needed.
	// Example:
	//  err = f.Get(ctx, nil)
	//
	// Note, values should not be reused for extraction here because merging on
	// top of existing values may result in unexpected behavior similar to
	// json.Unmarshal.
	Get(ctx Context, valuePtr interface{}) error

	// When true Get is guaranteed to not block
	IsReady() bool
}

Future represents the result of an asynchronous computation.

func ExecuteActivity

func ExecuteActivity(ctx Context, activity interface{}, args ...interface{}) Future

ExecuteActivity requests activity execution in the context of a workflow. Context can be used to pass the settings for this activity. For example: task queue that this need to be routed, timeouts that need to be configured. Use ActivityOptions to pass down the options.

 ao := ActivityOptions{
	    TaskQueue: "exampleTaskQueue",
	    ScheduleToStartTimeout: 10 * time.Second,
	    StartToCloseTimeout: 5 * time.Second,
	    ScheduleToCloseTimeout: 10 * time.Second,
	    HeartbeatTimeout: 0,
	}
	ctx := WithActivityOptions(ctx, ao)

Or to override a single option

ctx := WithTaskQueue(ctx, "exampleTaskQueue")

Input activity is either an activity name (string) or a function representing an activity that is getting scheduled. Input args are the arguments that need to be passed to the scheduled activity.

If the activity failed to complete then the future get error would indicate the failure. The error will be of type *ActivityError. It will have important activity information and actual error that caused activity failure. Use errors.Unwrap to get this error or errors.As to check it type which can be one of *ApplicationError, *TimeoutError, *CanceledError, or *PanicError.

You can cancel the pending activity using context(workflow.WithCancel(ctx)) and that will fail the activity with *CanceledError set as cause for *ActivityError.

ExecuteActivity returns Future with activity result or failure.

func ExecuteLocalActivity

func ExecuteLocalActivity(ctx Context, activity interface{}, args ...interface{}) Future

ExecuteLocalActivity requests to run a local activity. A local activity is like a regular activity with some key differences: * Local activity is scheduled and run by the workflow worker locally. * Local activity does not need Temporal server to schedule activity task and does not rely on activity worker. * No need to register local activity. * Local activity is for short living activities (usually finishes within seconds). * Local activity cannot heartbeat.

Context can be used to pass the settings for this local activity. For now there is only one setting for timeout to be set:

 lao := LocalActivityOptions{
	    ScheduleToCloseTimeout: 5 * time.Second,
	}
	ctx := WithLocalActivityOptions(ctx, lao)

The timeout here should be relative shorter than the WorkflowTaskTimeout of the workflow. If you need a longer timeout, you probably should not use local activity and instead should use regular activity. Local activity is designed to be used for short living activities (usually finishes within seconds).

Input args are the arguments that will to be passed to the local activity. The input args will be hand over directly to local activity function without serialization/deserialization because we don't need to pass the input across process boundary. However, the result will still go through serialization/deserialization because we need to record the result as history to temporal server so if the workflow crashes, a different worker can replay the history without running the local activity again.

If the activity failed to complete then the future get error would indicate the failure. The error will be of type *ActivityError. It will have important activity information and actual error that caused activity failure. Use errors.Unwrap to get this error or errors.As to check it type which can be one of *ApplicationError, *TimeoutError, *CanceledError, or *PanicError.

You can cancel the pending activity using context(workflow.WithCancel(ctx)) and that will fail the activity with *CanceledError set as cause for *ActivityError.

ExecuteLocalActivity returns Future with local activity result or failure.

func NewTimer

func NewTimer(ctx Context, d time.Duration) Future

NewTimer returns immediately and the future becomes ready after the specified duration d. The workflow needs to use this NewTimer() to get the timer instead of the Go lang library one(timer.NewTimer()). You can cancel the pending timer by cancel the Context (using context from workflow.WithCancel(ctx)) and that will cancel the timer. After timer is canceled, the returned Future become ready, and Future.Get() will return *CanceledError.

To be able to set options like timer summary, use NewTimerWithOptions.

func NewTimerWithOptions added in v1.29.0

func NewTimerWithOptions(ctx Context, d time.Duration, options TimerOptions) Future

NewTimerWithOptions returns immediately and the future becomes ready after the specified duration d. The workflow needs to use this NewTimerWithOptions() to get the timer instead of the Go lang library one(timer.NewTimer()). You can cancel the pending timer by cancel the Context (using context from workflow.WithCancel(ctx)) and that will cancel the timer. After timer is canceled, the returned Future become ready, and Future.Get() will return *CanceledError.

func RequestCancelExternalWorkflow

func RequestCancelExternalWorkflow(ctx Context, workflowID, runID string) Future

RequestCancelExternalWorkflow can be used to request cancellation of an external workflow. Input workflowID is the workflow ID of target workflow. Input runID indicates the instance of a workflow. Input runID is optional (default is ""). When runID is not specified, then the currently running instance of that workflowID will be used. By default, the current workflow's namespace will be used as target namespace. However, you can specify a different namespace of the target workflow using the context like:

ctx := WithWorkflowNamespace(ctx, "namespace")

RequestCancelExternalWorkflow return Future with failure or empty success result.

func SignalExternalWorkflow

func SignalExternalWorkflow(ctx Context, workflowID, runID, signalName string, arg interface{}) Future

SignalExternalWorkflow can be used to send signal info to an external workflow. Input workflowID is the workflow ID of target workflow. Input runID indicates the instance of a workflow. Input runID is optional (default is ""). When runID is not specified, then the currently running instance of that workflowID will be used. By default, the current workflow's namespace will be used as target namespace. However, you can specify a different namespace of the target workflow using the context like:

ctx := WithWorkflowNamespace(ctx, "namespace")

SignalExternalWorkflow return Future with failure or empty success result.

type GetWorkerBuildIdCompatibilityOptions added in v1.22.0

type GetWorkerBuildIdCompatibilityOptions struct {
	TaskQueue string
	MaxSets   int
}

type GetWorkerTaskReachabilityOptions added in v1.25.0

type GetWorkerTaskReachabilityOptions struct {
	// BuildIDs - The build IDs to query the reachability of. At least one build ID must be provided.
	BuildIDs []string
	// TaskQueues - The task queues with Build IDs defined on them that the request is
	// concerned with.
	// Optional: defaults to all task queues
	TaskQueues []string
	// Reachability - The reachability this request is concerned with.
	// Optional: defaults to all types of reachability
	Reachability TaskReachability
}

type GetWorkerVersioningOptions added in v1.27.0

type GetWorkerVersioningOptions struct {
	// The task queue to get the versioning rules from.
	TaskQueue string
}

GetWorkerVersioningOptions is the input to [Client.GetWorkerVersioningRules]. WARNING: Worker versioning is currently experimental

type GetWorkflowUpdateHandleOptions added in v1.22.2

type GetWorkflowUpdateHandleOptions struct {
	// WorkflowID of the target update
	WorkflowID string

	// RunID of the target workflow. If blank, use the most recent run
	RunID string

	// UpdateID of the target update
	UpdateID string
}

GetWorkflowUpdateHandleOptions encapsulates the parameters needed to unambiguously refer to a Workflow Update. NOTE: Experimental

type HandleQueryInput added in v1.12.0

type HandleQueryInput struct {
	QueryType string
	Args      []interface{}
}

HandleQueryInput is the input to WorkflowInboundInterceptor.HandleQuery.

type HandleSignalInput added in v1.12.0

type HandleSignalInput struct {
	SignalName string
	// Arg is the signal argument. It is presented as a primitive payload since
	// the type needed for decode is not available at the time of interception.
	Arg *commonpb.Payloads
}

HandleSignalInput is the input to WorkflowInboundInterceptor.HandleSignal.

type HandlerUnfinishedPolicy added in v1.28.0

type HandlerUnfinishedPolicy int

HandlerUnfinishedPolicy actions taken if a workflow completes with running handlers.

Policy defining actions taken when a workflow exits while update or signal handlers are running. The workflow exit may be due to successful return, cancellation, or continue-as-new

const (
	// WarnAndAbandon issues a warning in addition to abandoning.
	HandlerUnfinishedPolicyWarnAndAbandon HandlerUnfinishedPolicy = iota
	// ABANDON abandons the handler.
	HandlerUnfinishedPolicyAbandon
)

type HeaderReader

type HeaderReader interface {
	Get(string) (*commonpb.Payload, bool)
	ForEachKey(handler func(string, *commonpb.Payload) error) error
}

HeaderReader is an interface to read information from temporal headers

func NewHeaderReader

func NewHeaderReader(header *commonpb.Header) HeaderReader

NewHeaderReader returns a header reader interface

type HeaderWriter

type HeaderWriter interface {
	Set(string, *commonpb.Payload)
}

HeaderWriter is an interface to write information to temporal headers

func NewHeaderWriter

func NewHeaderWriter(header *commonpb.Header) HeaderWriter

NewHeaderWriter returns a header writer interface

type HeadersProvider added in v1.5.0

type HeadersProvider interface {
	GetHeaders(ctx context.Context) (map[string]string, error)
}

HeadersProvider returns a map of gRPC headers that should be used on every request.

type HistoryEventIterator

type HistoryEventIterator interface {
	// HasNext return whether this iterator has next value
	HasNext() bool
	// Next returns the next history events and error
	// The errors it can return:
	//	- serviceerror.NotFound
	//	- serviceerror.InvalidArgument
	//	- serviceerror.Internal
	//	- serviceerror.Unavailable
	Next() (*historypb.HistoryEvent, error)
}

HistoryEventIterator represents the interface for history event iterator

type HistoryIterator

type HistoryIterator interface {
	// GetNextPage returns next page of history events
	GetNextPage() (*historypb.History, error)
	// Reset resets the internal state so next GetNextPage() call will return first page of events from beginning.
	Reset()
	// HasNextPage returns if there are more page of events
	HasNextPage() bool
}

HistoryIterator iterator through history events

type HistoryJSONOptions added in v1.26.0

type HistoryJSONOptions struct {
	// LastEventID, if set, will only load history up to this ID (inclusive).
	LastEventID int64
}

HistoryJSONOptions are options for HistoryFromJSON.

type Interceptor added in v1.12.0

type Interceptor interface {
	ClientInterceptor
	WorkerInterceptor
}

Interceptor is a common interface for all interceptors. See documentation in the interceptor package for more details.

type InterceptorBase added in v1.12.0

type InterceptorBase struct {
	ClientInterceptorBase
	WorkerInterceptorBase
}

InterceptorBase is a default implementation of Interceptor meant for embedding. See documentation in the interceptor package for more details.

type LocalActivityClient

type LocalActivityClient interface {
	ExecuteLocalActivity(params ExecuteLocalActivityParams, callback LocalActivityResultHandler) LocalActivityID

	RequestCancelLocalActivity(activityID LocalActivityID)
}

LocalActivityClient for requesting local activity execution

type LocalActivityID

type LocalActivityID struct {
	// contains filtered or unexported fields
}

LocalActivityID uniquely identifies a local activity execution

func ParseLocalActivityID added in v1.3.0

func ParseLocalActivityID(v string) (LocalActivityID, error)

ParseLocalActivityID returns LocalActivityID constructed from its string representation. The string representation should be obtained through LocalActivityID.String()

func (LocalActivityID) String added in v1.3.0

func (i LocalActivityID) String() string

type LocalActivityOptions

type LocalActivityOptions struct {
	// ScheduleToCloseTimeout - The end to end timeout for the local activity, including retries.
	// At least one of ScheduleToCloseTimeout or StartToCloseTimeout is required.
	// Defaults to StartToCloseTimeout if not set.
	ScheduleToCloseTimeout time.Duration

	// StartToCloseTimeout - The timeout for a single execution of the local activity.
	// At least one of ScheduleToCloseTimeout or StartToCloseTimeout is required.
	// Defaults to ScheduleToCloseTimeout if not set.
	StartToCloseTimeout time.Duration

	// RetryPolicy - Specify how to retry activity if error happens.
	// Optional: default is to retry according to the default retry policy up to ScheduleToCloseTimeout
	// with 1sec initial delay between retries and 2x backoff.
	RetryPolicy *RetryPolicy
}

LocalActivityOptions stores local activity specific parameters that will be stored inside of a context.

func GetLocalActivityOptions added in v1.6.0

func GetLocalActivityOptions(ctx Context) LocalActivityOptions

GetLocalActivityOptions returns all local activity options present on the context.

type LocalActivityResultHandler

type LocalActivityResultHandler func(lar *LocalActivityResultWrapper)

LocalActivityResultHandler that returns local activity result

type LocalActivityResultWrapper

type LocalActivityResultWrapper struct {
	Err     error
	Result  *commonpb.Payloads
	Attempt int32
	Backoff time.Duration
}

LocalActivityResultWrapper contains result of a local activity

type MockCallWrapper

type MockCallWrapper struct {
	// contains filtered or unexported fields
}

MockCallWrapper is a wrapper to mock.Call. It offers the ability to wait on workflow's clock instead of wall clock.

func (*MockCallWrapper) After

After sets how long to wait on workflow's clock before the mock call returns.

func (*MockCallWrapper) AfterFn

func (c *MockCallWrapper) AfterFn(fn func() time.Duration) *MockCallWrapper

AfterFn sets a function which will tell how long to wait on workflow's clock before the mock call returns.

func (*MockCallWrapper) Maybe added in v1.9.0

func (c *MockCallWrapper) Maybe() *MockCallWrapper

Maybe indicates that the mock call is optional. Not calling an optional method will not cause an error while asserting expectations.

func (*MockCallWrapper) Never added in v1.7.0

func (c *MockCallWrapper) Never() *MockCallWrapper

Never indicates that the mock should not be called.

func (*MockCallWrapper) NotBefore added in v1.26.0

func (c *MockCallWrapper) NotBefore(calls ...*MockCallWrapper) *MockCallWrapper

NotBefore indicates that a call to this mock must not happen before the given calls have happened as expected. It calls `NotBefore` on the wrapped mock call.

func (*MockCallWrapper) Once

func (c *MockCallWrapper) Once() *MockCallWrapper

Once indicates that the mock should only return the value once.

func (*MockCallWrapper) Panic added in v1.2.0

func (c *MockCallWrapper) Panic(msg string) *MockCallWrapper

Panic specifies if the function call should fail and the panic message

func (*MockCallWrapper) Return

func (c *MockCallWrapper) Return(returnArguments ...interface{}) *MockCallWrapper

Return specifies the return arguments for the expectation.

func (*MockCallWrapper) Run

func (c *MockCallWrapper) Run(fn func(args mock.Arguments)) *MockCallWrapper

Run sets a handler to be called before returning. It can be used when mocking a method such as unmarshalers that takes a pointer to a struct and sets properties in such struct.

func (*MockCallWrapper) Times

func (c *MockCallWrapper) Times(i int) *MockCallWrapper

Times indicates that the mock should only return the indicated number of times.

func (*MockCallWrapper) Twice

func (c *MockCallWrapper) Twice() *MockCallWrapper

Twice indicates that the mock should only return the value twice.

type Mutex added in v1.28.0

type Mutex interface {
	// Lock blocks until the mutex is acquired.
	// Returns CanceledError if the ctx is canceled.
	Lock(ctx Context) error
	// TryLock tries to acquire the mutex without blocking.
	// Returns true if the mutex was acquired, otherwise false.
	TryLock(ctx Context) bool
	// Unlock releases the mutex.
	// It is a run-time error if the mutex is not locked on entry to Unlock.
	Unlock()
	// IsLocked returns true if the mutex is currently locked.
	IsLocked() bool
}

Mutex must be used instead of native go sync.Mutex by workflow code. Use workflow.NewMutex(ctx) method to create a new Mutex instance

func NewMutex added in v1.28.0

func NewMutex(ctx Context) Mutex

NewMutex creates a new Mutex instance.

type NamespaceClient

type NamespaceClient interface {
	// Register a namespace with temporal server
	// The errors it can throw:
	//  - NamespaceAlreadyExistsError
	//  - serviceerror.InvalidArgument
	//  - serviceerror.Internal
	//  - serviceerror.Unavailable
	Register(ctx context.Context, request *workflowservice.RegisterNamespaceRequest) error

	// Describe a namespace. The namespace has 3 part of information
	// NamespaceInfo - Which has Name, Status, Description, Owner Email
	// NamespaceConfiguration - Configuration like Workflow Execution Retention Period In Days, Whether to emit metrics.
	// ReplicationConfiguration - replication config like clusters and active cluster name
	// The errors it can throw:
	//  - serviceerror.NamespaceNotFound
	//  - serviceerror.InvalidArgument
	//  - serviceerror.Internal
	//  - serviceerror.Unavailable
	Describe(ctx context.Context, name string) (*workflowservice.DescribeNamespaceResponse, error)

	// Update a namespace.
	// The errors it can throw:
	//  - serviceerror.NamespaceNotFound
	//  - serviceerror.InvalidArgument
	//  - serviceerror.Internal
	//  - serviceerror.Unavailable
	Update(ctx context.Context, request *workflowservice.UpdateNamespaceRequest) error

	// Close client and clean up underlying resources.
	Close()
}

NamespaceClient is the client for managing operations on the namespace. CLI, tools, ... can use this layer to manager operations on namespace.

func NewNamespaceClient

func NewNamespaceClient(options ClientOptions) (NamespaceClient, error)

NewNamespaceClient creates an instance of a namespace client, to manager lifecycle of namespaces.

type NamespaceNotFoundError added in v1.15.0

type NamespaceNotFoundError struct{}

NamespaceNotFoundError is set as the cause when failure is due namespace not found.

func (*NamespaceNotFoundError) Error added in v1.15.0

func (*NamespaceNotFoundError) Error() string

Error from error interface

type NexusClient added in v1.28.0

type NexusClient interface {
	// The endpoint name this client uses.
	//
	// NOTE: Experimental
	Endpoint() string
	// The service name this client uses.
	//
	// NOTE: Experimental
	Service() string

	// ExecuteOperation executes a Nexus Operation.
	// The operation argument can be a string, a [nexus.Operation] or a [nexus.OperationReference].
	//
	// NOTE: Experimental
	ExecuteOperation(ctx Context, operation any, input any, options NexusOperationOptions) NexusOperationFuture
}

NexusClient is a client for executing Nexus Operations from a workflow. NOTE to maintainers, this interface definition is duplicated in the workflow package to provide a better UX.

func NewNexusClient added in v1.28.0

func NewNexusClient(endpoint, service string) NexusClient

Create a NexusClient from an endpoint name and a service name.

NOTE: Experimental

type NexusOperationContext added in v1.28.0

type NexusOperationContext struct {
	Client         Client
	Namespace      string
	TaskQueue      string
	MetricsHandler metrics.Handler
	Log            log.Logger
}

NexusOperationContext is an internal only struct that holds fields used by the temporalnexus functions.

func NexusOperationContextFromGoContext added in v1.28.0

func NexusOperationContextFromGoContext(ctx context.Context) (nctx *NexusOperationContext, ok bool)

NexusOperationContextFromGoContext gets the NexusOperationContext associated with the given context.Context.

type NexusOperationError added in v1.28.0

type NexusOperationError struct {
	// The raw proto failure object this error was created from.
	Failure *failurepb.Failure
	// Error message.
	Message string
	// ID of the NexusOperationScheduled event.
	ScheduledEventID int64
	// Endpoint name.
	Endpoint string
	// Service name.
	Service string
	// Operation name.
	Operation string
	// Operation ID - may be empty if the operation completed synchronously.
	OperationID string
	// Chained cause - typically an ApplicationError or a CanceledError.
	Cause error
}

NexusOperationError is an error returned when a Nexus Operation has failed.

NOTE: Experimental

func (*NexusOperationError) Error added in v1.28.0

func (e *NexusOperationError) Error() string

Error implements the error interface.

func (*NexusOperationError) Unwrap added in v1.28.0

func (e *NexusOperationError) Unwrap() error

Unwrap returns the Cause associated with this error.

type NexusOperationExecution added in v1.28.0

type NexusOperationExecution struct {
	// Operation ID as set by the Operation's handler. May be empty if the operation hasn't started yet or completed
	// synchronously.
	OperationID string
}

NexusOperationExecution is the result of NexusOperationFuture.GetNexusOperationExecution.

type NexusOperationFuture added in v1.28.0

type NexusOperationFuture interface {
	Future
	// GetNexusOperationExecution returns a future that is resolved when the operation reaches the STARTED state.
	// For synchronous operations, this will be resolved at the same as the containing [NexusOperationFuture]. For
	// asynchronous operations, this future is resolved independently.
	// If the operation is unsuccessful, this future will contain the same error as the [NexusOperationFuture].
	// Use this method to extract the Operation ID of an asynchronous operation. OperationID will be empty for
	// synchronous operations.
	//
	// NOTE: Experimental
	//
	//  fut := nexusClient.ExecuteOperation(ctx, op, ...)
	//  var exec workflow.NexusOperationExecution
	//  if err := fut.GetNexusOperationExecution().Get(ctx, &exec); err == nil {
	//      // Nexus Operation started, OperationID is optionally set.
	//  }
	GetNexusOperationExecution() Future
}

NexusOperationFuture represents the result of a Nexus Operation.

type NexusOperationOptions added in v1.28.0

type NexusOperationOptions struct {
	ScheduleToCloseTimeout time.Duration
}

NexusOperationOptions are options for starting a Nexus Operation from a Workflow.

type PanicError

type PanicError struct {
	// contains filtered or unexported fields
}

PanicError contains information about panicked workflow/activity.

func (*PanicError) Error

func (e *PanicError) Error() string

Error from error interface

func (*PanicError) StackTrace

func (e *PanicError) StackTrace() string

StackTrace return stack trace of the panic

type QueryHandlerOptions added in v1.29.0

type QueryHandlerOptions struct {
	// Description is a short description for this query.
	//
	// NOTE: Experimental
	Description string
}

QueryHandlerOptions consists of options for a query handler.

NOTE: Experimental

type QueryRejectedError added in v1.29.0

type QueryRejectedError struct {
	// contains filtered or unexported fields
}

QueryRejectedError is a wrapper for QueryRejected

func (*QueryRejectedError) Error added in v1.29.0

func (q *QueryRejectedError) Error() string

func (*QueryRejectedError) QueryRejected added in v1.29.0

func (q *QueryRejectedError) QueryRejected() *querypb.QueryRejected

type QueryWorkflowWithOptionsRequest

type QueryWorkflowWithOptionsRequest struct {
	// WorkflowID is a required field indicating the workflow which should be queried.
	WorkflowID string

	// RunID is an optional field used to identify a specific run of the queried workflow.
	// If RunID is not provided the latest run will be used.
	RunID string

	// QueryType is a required field which specifies the query you want to run.
	// By default, temporal supports "__stack_trace" as a standard query type, which will return string value
	// representing the call stack of the target workflow. The target workflow could also setup different query handler to handle custom query types.
	// See comments at workflow.SetQueryHandler(ctx Context, queryType string, handler interface{}) for more details on how to setup query handler within the target workflow.
	QueryType string

	// Args is an optional field used to identify the arguments passed to the query.
	Args []interface{}

	// QueryRejectCondition is an optional field used to reject queries based on workflow state.
	// QUERY_REJECT_CONDITION_NONE indicates that query should not be rejected.
	// QUERY_REJECT_CONDITION_NOT_OPEN indicates that query should be rejected if workflow is not open.
	// QUERY_REJECT_CONDITION_NOT_COMPLETED_CLEANLY indicates that query should be rejected if workflow did not complete cleanly (e.g. terminated, canceled timeout etc...).
	QueryRejectCondition enumspb.QueryRejectCondition

	// Header is an optional header to include with the query.
	Header *commonpb.Header
}

QueryWorkflowWithOptionsRequest is the request to QueryWorkflowWithOptions

type QueryWorkflowWithOptionsResponse

type QueryWorkflowWithOptionsResponse struct {
	// QueryResult contains the result of executing the query.
	// This will only be set if the query was completed successfully and not rejected.
	QueryResult converter.EncodedValue

	// QueryRejected contains information about the query rejection.
	QueryRejected *querypb.QueryRejected
}

QueryWorkflowWithOptionsResponse is the response to QueryWorkflowWithOptions

type ReceiveChannel

type ReceiveChannel interface {
	// Name returns the name of the Channel.
	// If the Channel was retrieved from a GetSignalChannel call, Name returns the signal name.
	//
	// A Channel created without an explicit name will use a generated name by the SDK and
	// is not deterministic.
	Name() string

	// Receive blocks until it receives a value, and then assigns the received value to the provided pointer.
	// Returns false when Channel is closed.
	// Parameter valuePtr is a pointer to the expected data structure to be received. For example:
	//  var v string
	//  c.Receive(ctx, &v)
	//
	// Note, values should not be reused for extraction here because merging on
	// top of existing values may result in unexpected behavior similar to
	// json.Unmarshal.
	Receive(ctx Context, valuePtr interface{}) (more bool)

	// ReceiveWithTimeout blocks up to timeout until it receives a value, and then assigns the received value to the
	// provided pointer.
	// Returns more value of false when Channel is closed.
	// Returns ok value of false when no value was found in the channel for the duration of timeout or
	// the ctx was canceled.
	// The valuePtr is not modified if ok is false.
	// Parameter valuePtr is a pointer to the expected data structure to be received. For example:
	//  var v string
	//  c.ReceiveWithTimeout(ctx, time.Minute, &v)
	//
	// Note, values should not be reused for extraction here because merging on
	// top of existing values may result in unexpected behavior similar to
	// json.Unmarshal.
	ReceiveWithTimeout(ctx Context, timeout time.Duration, valuePtr interface{}) (ok, more bool)

	// ReceiveAsync try to receive from Channel without blocking. If there is data available from the Channel, it
	// assign the data to valuePtr and returns true. Otherwise, it returns false immediately.
	//
	// Note, values should not be reused for extraction here because merging on
	// top of existing values may result in unexpected behavior similar to
	// json.Unmarshal.
	ReceiveAsync(valuePtr interface{}) (ok bool)

	// ReceiveAsyncWithMoreFlag is same as ReceiveAsync with extra return value more to indicate if there could be
	// more value from the Channel. The more is false when Channel is closed.
	//
	// Note, values should not be reused for extraction here because merging on
	// top of existing values may result in unexpected behavior similar to
	// json.Unmarshal.
	ReceiveAsyncWithMoreFlag(valuePtr interface{}) (ok bool, more bool)

	// Len returns the number of buffered messages plus the number of blocked Send calls.
	Len() int
}

ReceiveChannel is a read only view of the Channel

func GetSignalChannel

func GetSignalChannel(ctx Context, signalName string) ReceiveChannel

GetSignalChannel returns channel corresponding to the signal name.

func GetSignalChannelWithOptions added in v1.29.0

func GetSignalChannelWithOptions(ctx Context, signalName string, options SignalChannelOptions) ReceiveChannel

GetSignalChannelWithOptions returns channel corresponding to the signal name.

NOTE: Experimental

type RegisterActivityOptions

type RegisterActivityOptions struct {
	// When an activity is a function the name is an actual activity type name.
	// When an activity is part of a structure then each member of the structure becomes an activity with
	// this Name as a prefix + activity function name.
	//
	// If this is set, users are strongly recommended to set
	// worker.Options.DisableRegistrationAliasing at the worker level to prevent
	// ambiguity between string names and function references. Also users should
	// always use this string name when executing this activity.
	Name                          string
	DisableAlreadyRegisteredCheck bool

	// When registering a struct with activities, skip functions that are not valid activities. If false,
	// registration panics.
	SkipInvalidStructFunctions bool
}

RegisterActivityOptions consists of options for registering an activity.

type RegisterWorkflowOptions

type RegisterWorkflowOptions struct {
	// Custom name for this workflow instead of the function name.
	//
	// If this is set, users are strongly recommended to set
	// worker.Options.DisableRegistrationAliasing at the worker level to prevent
	// ambiguity between string names and function references. Also users should
	// always use this string name when executing this workflow from a client or
	// inside a workflow as a child workflow.
	Name                          string
	DisableAlreadyRegisteredCheck bool
}

RegisterWorkflowOptions consists of options for registering a workflow

type ReplayWorkflowHistoryOptions added in v1.20.0

type ReplayWorkflowHistoryOptions struct {
	// OriginalExecution - Overide the workflow execution details used for replay.
	// Optional
	OriginalExecution WorkflowExecution
}

ReplayWorkflowHistoryOptions are options for replaying a workflow.

type RequestCancelNexusOperationInput added in v1.28.0

type RequestCancelNexusOperationInput struct {
	// Client that was used to start the operation.
	Client NexusClient
	// Operation name or OperationReference from the Nexus SDK.
	Operation any
	// Operation ID. May be empty if the operation is synchronous or has not started yet.
	ID string
	// contains filtered or unexported fields
}

RequestCancelNexusOperationInput is the input to WorkflowOutboundInterceptor.RequestCancelNexusOperation.

NOTE: Experimental

type ResultHandler

type ResultHandler func(result *commonpb.Payloads, err error)

ResultHandler that returns result

type RetryPolicy

type RetryPolicy struct {
	// Backoff interval for the first retry. If BackoffCoefficient is 1.0 then it is used for all retries.
	// If not set or set to 0, a default interval of 1s will be used.
	InitialInterval time.Duration

	// Coefficient used to calculate the next retry backoff interval.
	// The next retry interval is previous interval multiplied by this coefficient.
	// Must be 1 or larger. Default is 2.0.
	BackoffCoefficient float64

	// Maximum backoff interval between retries. Exponential backoff leads to interval increase.
	// This value is the cap of the interval. Default is 100x of initial interval.
	MaximumInterval time.Duration

	// Maximum number of attempts. When exceeded the retries stop even if not expired yet.
	// If not set or set to 0, it means unlimited, and rely on activity ScheduleToCloseTimeout to stop.
	MaximumAttempts int32

	// Non-Retriable errors. This is optional. Temporal server will stop retry if error type matches this list.
	// Note:
	//  - cancellation is not a failure, so it won't be retried,
	//  - only StartToClose or Heartbeat timeouts are retryable.
	NonRetryableErrorTypes []string
}

RetryPolicy defines the retry policy. Note that the history of activity with retry policy will be different: the started event will be written down into history only when the activity completes or "finally" timeouts/fails. And the started event only records the last started time. Because of that, to check an activity has started or not, you cannot rely on history events. Instead, you can use CLI to describe the workflow to see the status of the activity:

tctl --ns <namespace> wf desc -w <wf-id>

type Schedule added in v1.18.0

type Schedule struct {
	// Action - Which Action to take
	Action ScheduleAction

	// Schedule - Describes when Actions should be taken.
	Spec *ScheduleSpec

	// SchedulePolicies - this schedules policies
	Policy *SchedulePolicies

	// State - this schedules state
	State *ScheduleState
}

Schedule describes a created schedule.

type ScheduleAction added in v1.18.0

type ScheduleAction interface {
	// contains filtered or unexported methods
}

ScheduleAction represents an action a schedule can take.

type ScheduleActionResult added in v1.18.0

type ScheduleActionResult struct {
	// ScheduleTime - Time that the Action was scheduled for, including jitter.
	ScheduleTime time.Time

	// ActualTime - Time that the Action was actually taken.
	ActualTime time.Time

	// StartWorkflowResult - If action was ScheduleWorkflowAction, returns the
	// ID of the workflow.
	StartWorkflowResult *ScheduleWorkflowExecution
}

ScheduleActionResult describes when a schedule action took place

type ScheduleBackfill added in v1.18.0

type ScheduleBackfill struct {
	// Start - start of the range to evaluate schedule in.
	Start time.Time

	// End - end of the range to evaluate schedule in.
	End time.Time

	// Overlap - Override the Overlap Policy for this request.
	Overlap enumspb.ScheduleOverlapPolicy
}

ScheduleBackfill desribes a time periods and policy and takes Actions as if that time passed by right now, all at once.

type ScheduleBackfillOptions added in v1.18.0

type ScheduleBackfillOptions struct {
	// Backfill  - Time periods to backfill the schedule.
	Backfill []ScheduleBackfill
}

ScheduleBackfillOptions configure the parameters for backfilling a schedule.

type ScheduleCalendarSpec added in v1.18.0

type ScheduleCalendarSpec struct {
	// Second range to match (0-59).
	//
	// default: matches 0
	Second []ScheduleRange

	// Minute range to match (0-59).
	//
	// default: matches 0
	Minute []ScheduleRange

	// Hour range to match (0-23).
	//
	// default: matches 0
	Hour []ScheduleRange

	// DayOfMonth range to match (1-31)
	//
	// default: matches all days
	DayOfMonth []ScheduleRange

	// Month range to match (1-12)
	//
	// default: matches all months
	Month []ScheduleRange

	// Year range to match.
	//
	// default: empty that matches all years
	Year []ScheduleRange

	// DayOfWeek range to match (0-6; 0 is Sunday)
	//
	// default: matches all days of the week
	DayOfWeek []ScheduleRange

	// Comment - Description of the intention of this schedule.
	Comment string
}

ScheduleCalendarSpec is an event specification relative to the calendar, similar to a traditional cron specification. A timestamp matches if at least one range of each field matches the corresponding fields of the timestamp, except for year: if year is missing, that means all years match. For all fields besides year, at least one Range must be present to match anything.

type ScheduleClient added in v1.18.0

type ScheduleClient interface {
	// Create a new Schedule.
	Create(ctx context.Context, options ScheduleOptions) (ScheduleHandle, error)

	// List returns an iterator to list all schedules
	//
	// Note: When using advanced visibility List is eventually consistent.
	List(ctx context.Context, options ScheduleListOptions) (ScheduleListIterator, error)

	// GetHandle returns a handle to a Schedule
	//
	// This method does not validate scheduleID. If there is no Schedule with the given scheduleID, handle
	// methods like ScheduleHandle.Describe() will return an error.
	GetHandle(ctx context.Context, scheduleID string) ScheduleHandle
}

Client for creating Schedules and creating Schedule handles

type ScheduleClientCreateInput added in v1.18.0

type ScheduleClientCreateInput struct {
	Options *ScheduleOptions
}

ScheduleClientCreateInput is the input to ClientOutboundInterceptor.CreateSchedule.

type ScheduleDescription added in v1.18.0

type ScheduleDescription struct {
	// Schedule - Describes the modifiable fields of a schedule.
	Schedule Schedule

	// Info - Extra information about the schedule.
	Info ScheduleInfo

	// Memo - Non-indexed user supplied information.
	Memo *commonpb.Memo

	// SearchAttributes - Additional indexed information used for search and visibility. The key and its value type
	// are registered on Temporal server side.
	// For supported operations on different server versions see [Visibility].
	//
	// [Visibility]: https://docs.temporal.io/visibility
	SearchAttributes *commonpb.SearchAttributes

	// TypedSearchAttributes - Additional indexed information used for search and visibility. The key and its value
	// type are registered on Temporal server side.
	// For supported operations on different server versions see [Visibility].
	//
	// [Visibility]: https://docs.temporal.io/visibility
	TypedSearchAttributes SearchAttributes
}

ScheduleDescription describes the current Schedule details from ScheduleHandle.Describe.

type ScheduleHandle added in v1.18.0

type ScheduleHandle interface {
	// GetID returns the schedule ID associated with this handle.
	GetID() string

	// Delete the Schedule
	Delete(ctx context.Context) error

	// Backfill the schedule by going though the specified time periods and taking Actions as if that time passed by right now, all at once.
	Backfill(ctx context.Context, options ScheduleBackfillOptions) error

	// Update the Schedule.
	//
	// NOTE: If two Update calls are made in parallel to the same Schedule there is the potential
	// for a race condition.
	Update(ctx context.Context, options ScheduleUpdateOptions) error

	// Describe fetches the Schedule's description from the Server
	Describe(ctx context.Context) (*ScheduleDescription, error)

	// Trigger an Action to be taken immediately. Will override the schedules default policy
	// with the one specified here. If overlap is SCHEDULE_OVERLAP_POLICY_UNSPECIFIED the schedule
	// policy will be used.
	Trigger(ctx context.Context, options ScheduleTriggerOptions) error

	// Pause the Schedule will also overwrite the Schedules current note with the new note.
	Pause(ctx context.Context, options SchedulePauseOptions) error

	// Unpause the Schedule will also overwrite the Schedules current note with the new note.
	Unpause(ctx context.Context, options ScheduleUnpauseOptions) error
}

ScheduleHandle represents a created schedule.

type ScheduleInfo added in v1.18.0

type ScheduleInfo struct {
	// NumActions - Number of actions taken by this schedule.
	NumActions int

	// NumActionsMissedCatchupWindow - Number of times a scheduled Action was skipped due to missing the catchup window.
	NumActionsMissedCatchupWindow int

	// NumActionsSkippedOverlap - Number of Actions skipped due to overlap.
	NumActionsSkippedOverlap int

	// RunningWorkflows - Currently-running workflows started by this schedule. (There might be
	// more than one if the overlap policy allows overlaps.)
	RunningWorkflows []ScheduleWorkflowExecution

	// RecentActions- Most recent 10 Actions started (including manual triggers).
	//
	// Sorted from older start time to newer.
	RecentActions []ScheduleActionResult

	// NextActionTimes - Next 10 scheduled Action times.
	NextActionTimes []time.Time

	// CreatedAt -  When the schedule was created
	CreatedAt time.Time

	// LastUpdateAt - When a schedule was last updated
	LastUpdateAt time.Time
}

ScheduleInfo describes other information about a schedule.

type ScheduleIntervalSpec added in v1.18.0

type ScheduleIntervalSpec struct {
	// Every - describes the period to repeat the interval.
	Every time.Duration

	// Offset - is a fixed offset added to the intervals period.
	// Optional: Defaulted to 0
	Offset time.Duration
}

ScheduleIntervalSpec - matches times that can be expressed as:

Epoch + (n * every) + offset

where n is all integers ≥ 0.

For example, an `every` of 1 hour with `offset` of zero would match every hour, on the hour. The same `every` but an `offset` of 19 minutes would match every `xx:19:00`. An `every` of 28 days with `offset` zero would match `2022-02-17T00:00:00Z` (among other times). The same `every` with `offset` of 3 days, 5 hours, and 23 minutes would match `2022-02-20T05:23:00Z` instead.

type ScheduleListEntry added in v1.18.0

type ScheduleListEntry struct {
	// ID - The business identifier of the schedule.
	ID string

	// Spec - Describes when Actions should be taken.
	Spec *ScheduleSpec

	// Note - Informative human-readable message with contextual notes, e.g. the reason
	// a Schedule is paused. The system may overwrite this message on certain
	// conditions, e.g. when pause-on-failure happens.
	Note string

	// Paused - True if the schedule is paused.
	Paused bool

	// WorkflowType - If the schedule action is a Wokrflow then
	// describes what workflow is run.
	WorkflowType WorkflowType

	// RecentActions- Most recent 5 Actions started (including manual triggers).
	//
	// Sorted from older start time to newer.
	RecentActions []ScheduleActionResult

	// NextActionTimes - Next 5 scheduled Action times.
	NextActionTimes []time.Time

	// Memo - Non-indexed user supplied information.
	Memo *commonpb.Memo

	// SearchAttributes - Indexed info that can be used in query of List schedules APIs. The key and value type must be registered on Temporal server side.
	// Use GetSearchAttributes API to get valid key and corresponding value type.
	// For supported operations on different server versions see [Visibility].
	//
	// [Visibility]: https://docs.temporal.io/visibility
	SearchAttributes *commonpb.SearchAttributes
}

ScheduleListEntry

type ScheduleListIterator added in v1.18.0

type ScheduleListIterator interface {
	// HasNext return whether this iterator has next value
	HasNext() bool

	// Next returns the next schedule and error
	Next() (*ScheduleListEntry, error)
}

ScheduleListIterator represents the interface for schedule iterator

type ScheduleListOptions added in v1.18.0

type ScheduleListOptions struct {
	// PageSize - How many results to fetch from the Server at a time.
	// Optional: defaulted to 1000
	PageSize int

	// Query - Filter results using a SQL-like query.
	// Optional
	Query string
}

ScheduleListOptions are the parameters for configuring listing schedules

type ScheduleOptions added in v1.18.0

type ScheduleOptions struct {
	// ID - The business identifier of the schedule.
	ID string

	// Schedule - Describes when Actions should be taken.
	Spec ScheduleSpec

	// Action - Which Action to take.
	Action ScheduleAction

	// Overlap - Controls what happens when an Action would be started by a Schedule at the same time that an older Action is still
	// running. This can be changed after a Schedule has taken some Actions, and some changes might produce
	// unintuitive results. In general, the later policy overrides the earlier policy.
	//
	// Optional: defaulted to SCHEDULE_OVERLAP_POLICY_SKIP
	Overlap enumspb.ScheduleOverlapPolicy

	// CatchupWindow - The Temporal Server might be down or unavailable at the time when a Schedule should take an Action.
	// When the Server comes back up, CatchupWindow controls which missed Actions should be taken at that point. The default is one
	// minute, which means that the Schedule attempts to take any Actions that wouldn't be more than one minute late. It
	// takes those Actions according to the Overlap. An outage that lasts longer than the Catchup
	// Window could lead to missed Actions.
	// Optional: defaulted to 1 minute
	CatchupWindow time.Duration

	// PauseOnFailure - When an Action times out or reaches the end of its Retry Policy the Schedule will pause.
	//
	// With SCHEDULE_OVERLAP_POLICY_ALLOW_ALL, this pause might not apply to the next Action, because the next Action
	// might have already started previous to the failed one finishing. Pausing applies only to Actions that are scheduled
	// to start after the failed one finishes.
	// Optional: defaulted to false
	PauseOnFailure bool

	// Note - Informative human-readable message with contextual notes, e.g. the reason
	// a Schedule is paused. The system may overwrite this message on certain
	// conditions, e.g. when pause-on-failure happens.
	Note string

	// Paused - Start in paused state.
	// Optional: defaulted to false
	Paused bool

	// RemainingActions - limit the number of Actions to take.
	//
	// This number is decremented after each Action is taken, and Actions are not
	// taken when the number is `0` (unless ScheduleHandle.Trigger is called).
	//
	// Optional: defaulted to zero
	RemainingActions int

	// TriggerImmediately - Trigger one Action immediately on creating the schedule.
	// Optional: defaulted to false
	TriggerImmediately bool

	// ScheduleBackfill - Runs though the specified time periods and takes Actions as if that time passed by right now, all at once. The
	// overlap policy can be overridden for the scope of the ScheduleBackfill.
	ScheduleBackfill []ScheduleBackfill

	// Memo - Optional non-indexed info that will be shown in list schedules.
	Memo map[string]interface{}

	// SearchAttributes - Optional indexed info that can be used in query of List schedules APIs. The key and value type must be registered on Temporal server side.
	// Use GetSearchAttributes API to get valid key and corresponding value type.
	// For supported operations on different server versions see [Visibility].
	//
	// Deprecated: use TypedSearchAttributes instead.
	//
	// [Visibility]: https://docs.temporal.io/visibility
	SearchAttributes map[string]interface{}

	// TypedSearchAttributes - Specifies Search Attributes that will be attached to the Workflow. Search Attributes are
	// additional indexed information attributed to workflow and used for search and visibility. The search attributes
	// can be used in query of List/Scan/Count workflow APIs. The key and its value type must be registered on Temporal
	// server side. For supported operations on different server versions see [Visibility].
	//
	// Optional: default to none.
	//
	// [Visibility]: https://docs.temporal.io/visibility
	TypedSearchAttributes SearchAttributes
}

ScheduleOptions configure the parameters for creating a schedule.

type SchedulePauseOptions added in v1.18.0

type SchedulePauseOptions struct {
	// Note - Informative human-readable message with contextual notes.
	// Optional: defaulted to 'Paused via Go SDK'
	Note string
}

SchedulePauseOptions configure the parameters for pausing a schedule.

type SchedulePolicies added in v1.18.0

type SchedulePolicies struct {
	// Overlap - Controls what happens when an Action would be started by a Schedule at the same time that an older Action is still
	// running.
	Overlap enumspb.ScheduleOverlapPolicy

	// CatchupWindow - The Temporal Server might be down or unavailable at the time when a Schedule should take an Action. When the Server
	// comes back up, CatchupWindow controls which missed Actions should be taken at that point.
	CatchupWindow time.Duration

	// PauseOnFailure - When an Action times out or reaches the end of its Retry Policy.
	PauseOnFailure bool
}

SchedulePolicies describes the current polcies of a schedule.

type ScheduleRange added in v1.18.0

type ScheduleRange struct {
	// Start of the range (inclusive)
	Start int

	// End of the range (inclusive)
	// Optional: defaulted to Start
	End int

	// Step to be take between each value
	// Optional: defaulted to 1
	Step int
}

ScheduleRange represents a set of integer values, used to match fields of a calendar time in StructuredCalendarSpec. If end < start, then end is interpreted as equal to start. This means you can use a Range with start set to a value, and end and step unset (defaulting to 0) to represent a single value.

type ScheduleSpec added in v1.18.0

type ScheduleSpec struct {
	// Calendars - Calendar-based specifications of times
	Calendars []ScheduleCalendarSpec

	// Intervals - Interval-based specifications of times.
	Intervals []ScheduleIntervalSpec

	// CronExpressions -  CronExpressions-based specifications of times. CronExpressions is provided for easy migration from legacy Cron Workflows. For new
	// use cases, we recommend using ScheduleSpec.Calendars or ScheduleSpec.Intervals for readability and maintainability. Once a schedule is created all
	// expressions in CronExpressions will be translated to ScheduleSpec.Calendars on the server.
	//
	// For example, `0 12 * * MON-WED,FRI` is every M/Tu/W/F at noon, and is equivalent to this ScheduleCalendarSpec:
	//
	// client.ScheduleCalendarSpec{
	// 		Second: []ScheduleRange{{}},
	// 		Minute: []ScheduleRanges{{}},
	// 		Hour: []ScheduleRange{{
	// 			Start: 12,
	// 		}},
	// 		DayOfMonth: []ScheduleRange{
	// 			{
	// 				Start: 1,
	// 				End:   31,
	// 			},
	// 		},
	// 		Month: []ScheduleRange{
	// 			{
	// 				Start: 1,
	// 				End:   12,
	// 			},
	// 		},
	// 		DayOfWeek: []ScheduleRange{
	// 			{
	// 				Start: 1,
	//				End: 3,
	// 			},
	// 			{
	// 				Start: 5,
	// 			},
	// 		},
	// 	}
	//
	//
	// The string can have 5, 6, or 7 fields, separated by spaces, and they are interpreted in the
	// same way as a ScheduleCalendarSpec:
	//	- 5 fields:         Minute, Hour, DayOfMonth, Month, DayOfWeek
	//	- 6 fields:         Minute, Hour, DayOfMonth, Month, DayOfWeek, Year
	//	- 7 fields: Second, Minute, Hour, DayOfMonth, Month, DayOfWeek, Year
	//
	// Notes:
	//	- If Year is not given, it defaults to *.
	//	- If Second is not given, it defaults to 0.
	//	- Shorthands @yearly, @monthly, @weekly, @daily, and @hourly are also
	//		accepted instead of the 5-7 time fields.
	//	- @every <interval>[/<phase>] is accepted and gets compiled into an
	//		IntervalSpec instead. <interval> and <phase> should be a decimal integer
	//		with a unit suffix s, m, h, or d.
	//	- Optionally, the string can be preceded by CRON_TZ=<time zone name> or
	//		TZ=<time zone name>, which will get copied to ScheduleSpec.TimeZoneName. (In which case the ScheduleSpec.TimeZone field should be left empty.)
	//	- Optionally, "#" followed by a comment can appear at the end of the string.
	//	- Note that the special case that some cron implementations have for
	//		treating DayOfMonth and DayOfWeek as "or" instead of "and" when both
	//		are set is not implemented.
	CronExpressions []string

	// Skip - Any matching times will be skipped.
	//
	// All fields of the ScheduleCalendarSpec—including seconds—must match a time for the time to be skipped.
	Skip []ScheduleCalendarSpec

	// StartAt - Any times before `startAt` will be skipped. Together, `startAt` and `endAt` make an inclusive interval.
	// Optional: Defaulted to the beginning of time
	StartAt time.Time

	// EndAt - Any times after `endAt` will be skipped.
	// Optional: Defaulted to the end of time
	EndAt time.Time

	// Jitter - All times will be incremented by a random value from 0 to this amount of jitter, capped
	// by the time until the next schedule.
	// Optional: Defaulted to 0
	Jitter time.Duration

	// TimeZoneName - IANA time zone name, for example `US/Pacific`.
	//
	// The definition will be loaded by Temporal Server from the environment it runs in.
	//
	// Calendar spec matching is based on literal matching of the clock time
	// with no special handling of DST: if you write a calendar spec that fires
	// at 2:30am and specify a time zone that follows DST, that action will not
	// be triggered on the day that has no 2:30am. Similarly, an action that
	// fires at 1:30am will be triggered twice on the day that has two 1:30s.
	//
	// Note: No actions are taken on leap-seconds (e.g. 23:59:60 UTC).
	// Optional: Defaulted to UTC
	TimeZoneName string
}

ScheduleSpec is a complete description of a set of absolute times (possibly infinite) that a action should occur at. The times are the union of Calendars, Intervals, and CronExpressions, minus the Skip times. These times never change, except that the definition of a time zone can change over time (most commonly, when daylight saving time policy changes for an area). To create a totally self-contained ScheduleSpec, use UTC.

type ScheduleState added in v1.18.0

type ScheduleState struct {
	// Note - Informative human-readable message with contextual notes, e.g. the reason
	// a Schedule is paused. The system may overwrite this message on certain
	// conditions, e.g. when pause-on-failure happens.
	Note string

	// Paused - True if the schedule is paused.
	Paused bool

	// LimitedActions - While true RemainingActions will be decremented for each action taken.
	// Skipped actions (due to overlap policy) do not count against remaining actions.
	LimitedActions bool

	// RemainingActions - The Actions remaining in this Schedule. Once this number hits 0, no further Actions are taken.
	// manual actions through backfill or ScheduleHandle.Trigger still run.
	RemainingActions int
}

ScheduleState describes the current state of a schedule.

type ScheduleTriggerOptions added in v1.18.0

type ScheduleTriggerOptions struct {
	// Overlap - If specified, policy to override the schedules default overlap policy.
	Overlap enumspb.ScheduleOverlapPolicy
}

ScheduleTriggerOptions configure the parameters for triggering a schedule.

type ScheduleUnpauseOptions added in v1.18.0

type ScheduleUnpauseOptions struct {
	// Note - Informative human-readable message with contextual notes.
	// Optional: defaulted to 'Unpaused via Go SDK'
	Note string
}

ScheduleUnpauseOptions configure the parameters for unpausing a schedule.

type ScheduleUpdate added in v1.18.0

type ScheduleUpdate struct {
	// Schedule - New schedule to replace the existing schedule with
	Schedule *Schedule

	// TypedSearchAttributes - Optional indexed info that can be used for querying via the List schedules APIs.
	// The key and value type must be registered on Temporal server side.
	//
	// nil: leave any pre-existing assigned search attributes intact
	// empty: remove any and all pre-existing assigned search attributes
	// attributes present: replace any and all pre-existing assigned search attributes with the defined search
	//                     attributes, i.e. upsert
	TypedSearchAttributes *SearchAttributes
}

ScheduleUpdate describes the desired new schedule from ScheduleHandle.Update.

type ScheduleUpdateInput added in v1.18.0

type ScheduleUpdateInput struct {
	// Description - current description of the schedule
	Description ScheduleDescription
}

ScheduleUpdateInput describes the current state of the schedule to be updated.

type ScheduleUpdateOptions added in v1.18.0

type ScheduleUpdateOptions struct {
	// DoUpdate - Takes a description of the schedule and returns the new desired schedule.
	// If update returns ErrSkipScheduleUpdate response and no update will occur.
	// Any other error will be passed through.
	DoUpdate func(ScheduleUpdateInput) (*ScheduleUpdate, error)
}

ScheduleUpdateOptions configure the parameters for updating a schedule.

type ScheduleWorkflowAction added in v1.18.0

type ScheduleWorkflowAction struct {
	// ID - The business identifier of the workflow execution.
	// The workflow ID of the started workflow may not match this exactly,
	// it may have a timestamp appended for uniqueness.
	// Optional: defaulted to a uuid.
	ID string

	// Workflow - What workflow to run.
	// Workflow can either be the function or workflow type name as a string.
	// On ScheduleHandle.Describe() or ScheduleHandle.Update() it will be the workflow type name.
	Workflow interface{}

	// Args - Arguments to pass to the workflow.
	// On ScheduleHandle.Describe() or ScheduleHandle.Update() Args will be returned as *commonpb.Payload.
	Args []interface{}

	// TaskQueue - The workflow tasks of the workflow are scheduled on the queue with this name.
	// This is also the name of the activity task queue on which activities are scheduled.
	TaskQueue string

	// WorkflowExecutionTimeout - The timeout for duration of workflow execution.
	WorkflowExecutionTimeout time.Duration

	// WorkflowRunTimeout - The timeout for duration of a single workflow run.
	WorkflowRunTimeout time.Duration

	// WorkflowTaskTimeout - The timeout for processing workflow task from the time the worker
	// pulled this task.
	WorkflowTaskTimeout time.Duration

	// RetryPolicy - Retry policy for workflow. If a retry policy is specified, in case of workflow failure
	// server will start new workflow execution if needed based on the retry policy.
	RetryPolicy *RetryPolicy

	// Memo - Optional non-indexed info that will be shown in list workflow.
	// On ScheduleHandle.Describe() or ScheduleHandle.Update() Memo will be returned as *commonpb.Payload.
	Memo map[string]interface{}

	// TypedSearchAttributes - Optional indexed info that can be used in query of List/Scan/Count workflow APIs. The key
	// and value type must be registered on Temporal server side. For supported operations on different server versions
	// see [Visibility].
	//
	// [Visibility]: https://docs.temporal.io/visibility
	TypedSearchAttributes SearchAttributes

	// UntypedSearchAttributes - These are set upon update for older schedules that did not have typed attributes. This
	// should never be used for create.
	//
	// Deprecated - This is only for update of older search attributes. This may be removed in a future version.
	UntypedSearchAttributes map[string]*commonpb.Payload
	// contains filtered or unexported fields
}

ScheduleWorkflowAction implements ScheduleAction to launch a workflow.

type ScheduleWorkflowExecution added in v1.18.0

type ScheduleWorkflowExecution struct {
	// WorkflowID - The ID of the workflow execution
	WorkflowID string

	// FirstExecutionRunID - The Run Id of the original execution that was started by the Schedule. If the Workflow retried, did
	// Continue-As-New, or was Reset, the following runs would have different Run Ids.
	FirstExecutionRunID string
}

ScheduleWorkflowExecution contains details on a workflows execution stared by a schedule.

type SearchAttributeKey added in v1.26.0

type SearchAttributeKey interface {
	// GetName of the search attribute.
	GetName() string
	// GetValueType of the search attribute.
	GetValueType() enumspb.IndexedValueType
	// GetReflectType of the search attribute.
	GetReflectType() reflect.Type
}

SearchAttributeKey represents a typed search attribute key.

type SearchAttributeKeyBool added in v1.26.0

type SearchAttributeKeyBool struct {
	// contains filtered or unexported fields
}

SearchAttributeKeyBool represents a search attribute key for a boolean attribute type.

func NewSearchAttributeKeyBool added in v1.26.0

func NewSearchAttributeKeyBool(name string) SearchAttributeKeyBool

func (SearchAttributeKeyBool) GetName added in v1.26.0

func (bk SearchAttributeKeyBool) GetName() string

GetName of the search attribute.

func (SearchAttributeKeyBool) GetReflectType added in v1.26.0

func (bk SearchAttributeKeyBool) GetReflectType() reflect.Type

GetReflectType of the search attribute.

func (SearchAttributeKeyBool) GetValueType added in v1.26.0

func (bk SearchAttributeKeyBool) GetValueType() enumspb.IndexedValueType

GetValueType of the search attribute.

func (SearchAttributeKeyBool) ValueSet added in v1.26.0

ValueSet creates an update to set the value of the attribute.

func (SearchAttributeKeyBool) ValueUnset added in v1.26.0

ValueUnset creates an update to remove the attribute.

type SearchAttributeKeyFloat64 added in v1.26.0

type SearchAttributeKeyFloat64 struct {
	// contains filtered or unexported fields
}

SearchAttributeKeyFloat64 represents a search attribute key for a float attribute type.

func NewSearchAttributeKeyFloat64 added in v1.26.0

func NewSearchAttributeKeyFloat64(name string) SearchAttributeKeyFloat64

func (SearchAttributeKeyFloat64) GetName added in v1.26.0

func (bk SearchAttributeKeyFloat64) GetName() string

GetName of the search attribute.

func (SearchAttributeKeyFloat64) GetReflectType added in v1.26.0

func (bk SearchAttributeKeyFloat64) GetReflectType() reflect.Type

GetReflectType of the search attribute.

func (SearchAttributeKeyFloat64) GetValueType added in v1.26.0

func (bk SearchAttributeKeyFloat64) GetValueType() enumspb.IndexedValueType

GetValueType of the search attribute.

func (SearchAttributeKeyFloat64) ValueSet added in v1.26.0

ValueSet creates an update to set the value of the attribute.

func (SearchAttributeKeyFloat64) ValueUnset added in v1.26.0

ValueUnset creates an update to remove the attribute.

type SearchAttributeKeyInt64 added in v1.26.0

type SearchAttributeKeyInt64 struct {
	// contains filtered or unexported fields
}

SearchAttributeKeyInt64 represents a search attribute key for a integer attribute type.

func NewSearchAttributeKeyInt64 added in v1.26.0

func NewSearchAttributeKeyInt64(name string) SearchAttributeKeyInt64

func (SearchAttributeKeyInt64) GetName added in v1.26.0

func (bk SearchAttributeKeyInt64) GetName() string

GetName of the search attribute.

func (SearchAttributeKeyInt64) GetReflectType added in v1.26.0

func (bk SearchAttributeKeyInt64) GetReflectType() reflect.Type

GetReflectType of the search attribute.

func (SearchAttributeKeyInt64) GetValueType added in v1.26.0

func (bk SearchAttributeKeyInt64) GetValueType() enumspb.IndexedValueType

GetValueType of the search attribute.

func (SearchAttributeKeyInt64) ValueSet added in v1.26.0

ValueSet creates an update to set the value of the attribute.

func (SearchAttributeKeyInt64) ValueUnset added in v1.26.0

ValueUnset creates an update to remove the attribute.

type SearchAttributeKeyKeyword added in v1.26.0

type SearchAttributeKeyKeyword struct {
	// contains filtered or unexported fields
}

SearchAttributeKeyKeyword represents a search attribute key for a keyword attribute type.

func NewSearchAttributeKeyKeyword added in v1.26.0

func NewSearchAttributeKeyKeyword(name string) SearchAttributeKeyKeyword

func (SearchAttributeKeyKeyword) GetName added in v1.26.0

func (bk SearchAttributeKeyKeyword) GetName() string

GetName of the search attribute.

func (SearchAttributeKeyKeyword) GetReflectType added in v1.26.0

func (bk SearchAttributeKeyKeyword) GetReflectType() reflect.Type

GetReflectType of the search attribute.

func (SearchAttributeKeyKeyword) GetValueType added in v1.26.0

func (bk SearchAttributeKeyKeyword) GetValueType() enumspb.IndexedValueType

GetValueType of the search attribute.

func (SearchAttributeKeyKeyword) ValueSet added in v1.26.0

ValueSet creates an update to set the value of the attribute.

func (SearchAttributeKeyKeyword) ValueUnset added in v1.26.0

ValueUnset creates an update to remove the attribute.

type SearchAttributeKeyKeywordList added in v1.26.0

type SearchAttributeKeyKeywordList struct {
	// contains filtered or unexported fields
}

SearchAttributeKeyKeywordList represents a search attribute key for a list of keyword attribute type.

func NewSearchAttributeKeyKeywordList added in v1.26.0

func NewSearchAttributeKeyKeywordList(name string) SearchAttributeKeyKeywordList

func (SearchAttributeKeyKeywordList) GetName added in v1.26.0

func (bk SearchAttributeKeyKeywordList) GetName() string

GetName of the search attribute.

func (SearchAttributeKeyKeywordList) GetReflectType added in v1.26.0

func (bk SearchAttributeKeyKeywordList) GetReflectType() reflect.Type

GetReflectType of the search attribute.

func (SearchAttributeKeyKeywordList) GetValueType added in v1.26.0

func (bk SearchAttributeKeyKeywordList) GetValueType() enumspb.IndexedValueType

GetValueType of the search attribute.

func (SearchAttributeKeyKeywordList) ValueSet added in v1.26.0

ValueSet creates an update to set the value of the attribute.

func (SearchAttributeKeyKeywordList) ValueUnset added in v1.26.0

ValueUnset creates an update to remove the attribute.

type SearchAttributeKeyString added in v1.26.0

type SearchAttributeKeyString struct {
	// contains filtered or unexported fields
}

SearchAttributeKeyString represents a search attribute key for a text attribute type.

func NewSearchAttributeKeyString added in v1.26.0

func NewSearchAttributeKeyString(name string) SearchAttributeKeyString

func (SearchAttributeKeyString) GetName added in v1.26.0

func (bk SearchAttributeKeyString) GetName() string

GetName of the search attribute.

func (SearchAttributeKeyString) GetReflectType added in v1.26.0

func (bk SearchAttributeKeyString) GetReflectType() reflect.Type

GetReflectType of the search attribute.

func (SearchAttributeKeyString) GetValueType added in v1.26.0

func (bk SearchAttributeKeyString) GetValueType() enumspb.IndexedValueType

GetValueType of the search attribute.

func (SearchAttributeKeyString) ValueSet added in v1.26.0

ValueSet creates an update to set the value of the attribute.

func (SearchAttributeKeyString) ValueUnset added in v1.26.0

ValueUnset creates an update to remove the attribute.

type SearchAttributeKeyTime added in v1.26.0

type SearchAttributeKeyTime struct {
	// contains filtered or unexported fields
}

SearchAttributeKeyTime represents a search attribute key for a date time attribute type.

func NewSearchAttributeKeyTime added in v1.26.0

func NewSearchAttributeKeyTime(name string) SearchAttributeKeyTime

func (SearchAttributeKeyTime) GetName added in v1.26.0

func (bk SearchAttributeKeyTime) GetName() string

GetName of the search attribute.

func (SearchAttributeKeyTime) GetReflectType added in v1.26.0

func (bk SearchAttributeKeyTime) GetReflectType() reflect.Type

GetReflectType of the search attribute.

func (SearchAttributeKeyTime) GetValueType added in v1.26.0

func (bk SearchAttributeKeyTime) GetValueType() enumspb.IndexedValueType

GetValueType of the search attribute.

func (SearchAttributeKeyTime) ValueSet added in v1.26.0

ValueSet creates an update to set the value of the attribute.

func (SearchAttributeKeyTime) ValueUnset added in v1.26.0

ValueUnset creates an update to remove the attribute.

type SearchAttributeUpdate added in v1.26.0

type SearchAttributeUpdate func(*SearchAttributes)

SearchAttributeUpdate represents a change to SearchAttributes

type SearchAttributes added in v1.26.0

type SearchAttributes struct {
	// contains filtered or unexported fields
}

SearchAttributes represents a collection of typed search attributes

func GetTypedSearchAttributes added in v1.26.0

func GetTypedSearchAttributes(ctx Context) SearchAttributes

func NewSearchAttributes added in v1.26.0

func NewSearchAttributes(attributes ...SearchAttributeUpdate) SearchAttributes

func (SearchAttributes) ContainsKey added in v1.26.0

func (sa SearchAttributes) ContainsKey(key SearchAttributeKey) bool

ContainsKey gets whether a key is present.

func (SearchAttributes) Copy added in v1.26.0

Copy creates an update that copies existing values.

func (SearchAttributes) GetBool added in v1.26.0

func (sa SearchAttributes) GetBool(key SearchAttributeKeyBool) (bool, bool)

GetBool gets a value for the given key and whether it was present.

func (SearchAttributes) GetFloat64 added in v1.26.0

GetFloat64 gets a value for the given key and whether it was present.

func (SearchAttributes) GetInt64 added in v1.26.0

func (sa SearchAttributes) GetInt64(key SearchAttributeKeyInt64) (int64, bool)

GetInt64 gets a value for the given key and whether it was present.

func (SearchAttributes) GetKeyword added in v1.26.0

func (sa SearchAttributes) GetKeyword(key SearchAttributeKeyKeyword) (string, bool)

GetKeyword gets a value for the given key and whether it was present.

func (SearchAttributes) GetKeywordList added in v1.26.0

func (sa SearchAttributes) GetKeywordList(key SearchAttributeKeyKeywordList) ([]string, bool)

GetKeywordList gets a value for the given key and whether it was present.

func (SearchAttributes) GetString added in v1.26.0

GetString gets a value for the given key and whether it was present.

func (SearchAttributes) GetTime added in v1.26.0

GetTime gets a value for the given key and whether it was present.

func (SearchAttributes) GetUntypedValues added in v1.26.0

func (sa SearchAttributes) GetUntypedValues() map[SearchAttributeKey]interface{}

GetUntypedValues gets a copy of the collection with raw types.

func (SearchAttributes) Size added in v1.26.0

func (sa SearchAttributes) Size() int

Size gets the size of the attribute collection.

type Selector

type Selector interface {
	// AddReceive registers a callback function to be called when a channel has a message to receive.
	// The callback is called when Select(ctx) is called.
	// The message is expected be consumed by the callback function.
	// The branch is automatically removed after the channel is closed and callback function is called once
	// with more parameter set to false.
	AddReceive(c ReceiveChannel, f func(c ReceiveChannel, more bool)) Selector
	// AddSend registers a callback function to be called when a message is sent on a channel.
	// The callback is called after the message is sent to the channel and Select(ctx) is called
	AddSend(c SendChannel, v interface{}, f func()) Selector
	// AddFuture registers a callback function to be called when a future is ready.
	// The callback is called when Select(ctx) is called.
	// The callback is called once per ready future even if Select is called multiple times for the same
	// Selector instance.
	AddFuture(future Future, f func(f Future)) Selector
	// AddDefault register callback function to be called if none of other branches matched.
	// The callback is called when Select(ctx) is called.
	// When the default branch is registered Select never blocks.
	AddDefault(f func())
	// Select checks if any of the registered branches satisfies its condition blocking if necessary.
	// When a branch becomes eligible its callback is invoked.
	// If multiple branches are eligible only one of them (picked randomly) is invoked per Select call.
	// It is OK to call Select multiple times for the same Selector instance.
	Select(ctx Context)
	// HasPending returns true if call to Select is guaranteed to not block.
	HasPending() bool
}

Selector must be used instead of native go select by workflow code. Create through workflow.NewSelector(ctx).

func NewNamedSelector

func NewNamedSelector(ctx Context, name string) Selector

NewNamedSelector creates a new Selector instance with a given human readable name. Name appears in stack traces that are blocked on this Selector.

func NewSelector

func NewSelector(ctx Context) Selector

NewSelector creates a new Selector instance.

type Semaphore added in v1.28.0

type Semaphore interface {
	// Acquire acquires the semaphore with a weight of n.
	// On success, returns nil. On failure, returns CanceledError and leaves the semaphore unchanged.
	Acquire(ctx Context, n int64) error
	// TryAcquire acquires the semaphore with a weight of n without blocking.
	// On success, returns true. On failure, returns false and leaves the semaphore unchanged.
	TryAcquire(ctx Context, n int64) bool
	// Release releases the semaphore with a weight of n.
	Release(n int64)
}

Semaphore must be used instead of semaphore.Weighted by workflow code. Use workflow.NewSemaphore(ctx) method to create a new Semaphore instance

func NewSemaphore added in v1.28.0

func NewSemaphore(ctx Context, n int64) Semaphore

NewSemaphore creates a new Semaphore instance with an initial weight.

type SendChannel

type SendChannel interface {
	// Name returns the name of the Channel.
	// If the Channel was retrieved from a GetSignalChannel call, Name returns the signal name.
	//
	// A Channel created without an explicit name will use a generated name by the SDK and
	// is not deterministic.
	Name() string

	// Send blocks until the data is sent.
	Send(ctx Context, v interface{})

	// SendAsync try to send without blocking. It returns true if the data was sent, otherwise it returns false.
	SendAsync(v interface{}) (ok bool)

	// Close close the Channel, and prohibit subsequent sends.
	Close()
}

SendChannel is a write only view of the Channel

type ServerError

type ServerError struct {
	// contains filtered or unexported fields
}

ServerError can be returned from server.

func (*ServerError) Error

func (e *ServerError) Error() string

Error from error interface

func (*ServerError) Message added in v1.15.0

func (e *ServerError) Message() string

Message contains just the message string without extras added by Error().

func (*ServerError) Unwrap

func (e *ServerError) Unwrap() error

type ServiceInvoker

type ServiceInvoker interface {
	// Returns ActivityTaskCanceledError if activity is canceled
	Heartbeat(ctx context.Context, details *commonpb.Payloads, skipBatching bool) error
	Close(ctx context.Context, flushBufferedHeartbeat bool)
	GetClient(options ClientOptions) Client
}

ServiceInvoker abstracts calls to the Temporal service from an activity implementation. Implement to unit test activities.

type SessionInfo

type SessionInfo struct {
	SessionID    string
	HostName     string
	SessionState SessionState
	// contains filtered or unexported fields
}

SessionInfo contains information of a created session. For now, exported fields are SessionID and HostName. SessionID is a uuid generated when CreateSession() or RecreateSession() is called and can be used to uniquely identify a session. HostName specifies which host is executing the session

func GetSessionInfo

func GetSessionInfo(ctx Context) *SessionInfo

GetSessionInfo returns the sessionInfo stored in the context. If there are multiple sessions in the context, (for example, the same context is used to create, complete, create another session. Then user found that the session has failed, and created a new one on it), the most recent sessionInfo will be returned.

This API will return nil if there's no sessionInfo in the context.

func (*SessionInfo) GetRecreateToken

func (s *SessionInfo) GetRecreateToken() []byte

GetRecreateToken returns the token needed to recreate a session. The returned value should be passed to RecreateSession() API.

type SessionOptions

type SessionOptions struct {
	ExecutionTimeout time.Duration
	CreationTimeout  time.Duration
	HeartbeatTimeout time.Duration
}

SessionOptions specifies metadata for a session. ExecutionTimeout: required, no default

Specifies the maximum amount of time the session can run

CreationTimeout: required, no default

Specifies how long session creation can take before returning an error

HeartbeatTimeout: optional, default 20s

Specifies the heartbeat timeout. If heartbeat is not received by server
within the timeout, the session will be declared as failed

type SessionState added in v1.21.0

type SessionState int
const (
	SessionStateOpen SessionState = iota
	SessionStateFailed
	SessionStateClosed
)

Session State enum

type Settable

type Settable interface {
	Set(value interface{}, err error)
	SetValue(value interface{})
	SetError(err error)
	Chain(future Future) // EncodedValue (or error) of the future become the same of the chained one.
}

Settable is used to set value or error on a future. See more: workflow.NewFuture(ctx).

type SignalChannelOptions added in v1.29.0

type SignalChannelOptions struct {
	// Description is a short description for this signal.
	//
	// NOTE: Experimental
	Description string
}

SignalChannelOptions consists of options for a signal channel.

NOTE: Experimental

type SlotMarkUsedInfo added in v1.29.0

type SlotMarkUsedInfo interface {
	// Permit returns the permit that is being marked as used.
	Permit() *SlotPermit
	// Logger returns an appropriately tagged logger.
	Logger() log.Logger
	// MetricsHandler returns an appropriately tagged metrics handler that can be used to record
	// custom metrics.
	MetricsHandler() metrics.Handler
}

SlotMarkUsedInfo contains information that SlotSupplier instances can use during SlotSupplier.MarkSlotUsed calls.

type SlotPermit added in v1.29.0

type SlotPermit struct {
	// UserData is a field that can be used to store arbitrary on a permit by SlotSupplier
	// implementations.
	UserData any
	// contains filtered or unexported fields
}

SlotPermit is a permit to use a slot.

WARNING: Custom implementations of SlotSupplier are currently experimental.

type SlotReleaseInfo added in v1.29.0

type SlotReleaseInfo interface {
	// Permit returns the permit that is being released.
	Permit() *SlotPermit
	// Reason returns the reason that the slot is being released.
	Reason() SlotReleaseReason
	// Logger returns an appropriately tagged logger.
	Logger() log.Logger
	// MetricsHandler returns an appropriately tagged metrics handler that can be used to record
	// custom metrics.
	MetricsHandler() metrics.Handler
}

SlotReleaseInfo contains information that SlotSupplier instances can use during SlotSupplier.ReleaseSlot calls.

type SlotReleaseReason added in v1.29.0

type SlotReleaseReason int

SlotReleaseReason describes the reason that a slot is being released.

const (
	SlotReleaseReasonTaskProcessed SlotReleaseReason = iota
	SlotReleaseReasonUnused
)

type SlotReservationInfo added in v1.29.0

type SlotReservationInfo interface {
	// TaskQueue returns the task queue for which a slot is being reserved. In the case of local
	// activities, this is the same as the workflow's task queue.
	TaskQueue() string
	// WorkerBuildId returns the build ID of the worker that is reserving the slot.
	WorkerBuildId() string
	// WorkerBuildId returns the build ID of the worker that is reserving the slot.
	WorkerIdentity() string
	// NumIssuedSlots returns the number of slots that have already been issued by the supplier.
	NumIssuedSlots() int
	// Logger returns an appropriately tagged logger.
	Logger() log.Logger
	// MetricsHandler returns an appropriately tagged metrics handler that can be used to record
	// custom metrics.
	MetricsHandler() metrics.Handler
}

SlotReservationInfo contains information that SlotSupplier instances can use during reservation calls. It embeds a standard Context.

type SlotSupplier added in v1.29.0

type SlotSupplier interface {
	// ReserveSlot is called before polling for new tasks. The implementation should block until
	// a slot is available, then return a permit to use that slot. Implementations must be
	// thread-safe.
	//
	// Any returned error besides context.Canceled will be logged and the function will be retried.
	ReserveSlot(ctx context.Context, info SlotReservationInfo) (*SlotPermit, error)

	// TryReserveSlot is called when attempting to reserve slots for eager workflows and activities.
	// It should return a permit if a slot is available, and nil otherwise. Implementations must be
	// thread-safe.
	TryReserveSlot(info SlotReservationInfo) *SlotPermit

	// MarkSlotUsed is called once a slot is about to be used for actually processing a task.
	// Because slots are reserved before task polling, not all reserved slots will be used.
	// Implementations must be thread-safe.
	MarkSlotUsed(info SlotMarkUsedInfo)

	// ReleaseSlot is called when a slot is no longer needed, which is typically after the task
	// has been processed, but may also be called upon shutdown or other situations where the
	// slot is no longer needed. Implementations must be thread-safe.
	ReleaseSlot(info SlotReleaseInfo)

	// MaxSlots returns the maximum number of slots that this supplier will ever issue.
	// Implementations may return 0 if there is no well-defined upper limit. In such cases the
	// available task slots metric will not be emitted.
	MaxSlots() int
}

SlotSupplier controls how slots are handed out for workflow and activity tasks as well as local activities when used in conjunction with a WorkerTuner.

WARNING: Custom implementations of SlotSupplier are currently experimental.

type StartWorkflowOptions

type StartWorkflowOptions struct {
	// ID - The business identifier of the workflow execution.
	// Optional: defaulted to a uuid.
	ID string

	// TaskQueue - The workflow tasks of the workflow are scheduled on the queue with this name.
	// This is also the name of the activity task queue on which activities are scheduled.
	// The workflow author can choose to override this using activity options.
	// Mandatory: No default.
	TaskQueue string

	// WorkflowExecutionTimeout - The timeout for duration of workflow execution.
	// It includes retries and continue as new. Use WorkflowRunTimeout to limit execution time
	// of a single workflow run.
	// The resolution is seconds.
	// Optional: defaulted to unlimited.
	WorkflowExecutionTimeout time.Duration

	// WorkflowRunTimeout - The timeout for duration of a single workflow run.
	// The resolution is seconds.
	// Optional: defaulted to WorkflowExecutionTimeout.
	WorkflowRunTimeout time.Duration

	// WorkflowTaskTimeout - The timeout for processing workflow task from the time the worker
	// pulled this task. If a workflow task is lost, it is retried after this timeout.
	// The resolution is seconds.
	// Optional: defaulted to 10 secs.
	WorkflowTaskTimeout time.Duration

	// WorkflowIDReusePolicy - Specifies server behavior if a *completed* workflow with the same id exists.
	// This can be useful for dedupe logic if set to RejectDuplicate
	// Optional: defaulted to AllowDuplicate.
	WorkflowIDReusePolicy enumspb.WorkflowIdReusePolicy

	// WorkflowIDConflictPolicy - Specifies server behavior if a *running* workflow with the same id exists.
	// This cannot be set if WorkflowIDReusePolicy is set to TerminateIfRunning.
	// Optional: defaulted to Fail.
	WorkflowIDConflictPolicy enumspb.WorkflowIdConflictPolicy

	// WithStartOperation - Operation to execute with Workflow Start.
	// For example, see NewUpdateWithStartWorkflowOperation to perform Update-with-Start. Note that if the workflow is
	// already running and WorkflowIDConflictPolicy is set to UseExisting, the start is skipped and only the
	// operation is executed. If instead the policy is set to Fail (the default), nothing is executed and
	// an error will be returned (i.e. the option WorkflowExecutionErrorWhenAlreadyStarted is ignored).
	// This option will be ignored when used with Client.SignalWithStartWorkflow.
	//
	// Optional: defaults to nil.
	//
	// NOTE: Experimental
	WithStartOperation WithStartWorkflowOperation

	// When WorkflowExecutionErrorWhenAlreadyStarted is true, Client.ExecuteWorkflow will return an error if the
	// workflow id has already been used and WorkflowIDReusePolicy or WorkflowIDConflictPolicy would
	// disallow a re-run. If it is set to false, rather than erroring a WorkflowRun instance representing
	// the current or last run will be returned. However, when WithStartOperation is set, this field is ignored and
	// the WorkflowIDConflictPolicy UseExisting must be used instead to prevent erroring.
	//
	// Optional: defaults to false
	WorkflowExecutionErrorWhenAlreadyStarted bool

	// RetryPolicy - Optional retry policy for workflow. If a retry policy is specified, in case of workflow failure
	// server will start new workflow execution if needed based on the retry policy.
	RetryPolicy *RetryPolicy

	// CronSchedule - Optional cron schedule for workflow. If a cron schedule is specified, the workflow will run
	// as a cron based on the schedule. The scheduling will be based on UTC time. Schedule for next run only happen
	// after the current run is completed/failed/timeout. If a RetryPolicy is also supplied, and the workflow failed
	// or timeout, the workflow will be retried based on the retry policy. While the workflow is retrying, it won't
	// schedule its next run. If next schedule is due while workflow is running (or retrying), then it will skip that
	// schedule. Cron workflow will not stop until it is terminated or canceled (by returning temporal.CanceledError).
	// The cron spec is as following:
	// ┌───────────── minute (0 - 59)
	// │ ┌───────────── hour (0 - 23)
	// │ │ ┌───────────── day of the month (1 - 31)
	// │ │ │ ┌───────────── month (1 - 12)
	// │ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday)
	// │ │ │ │ │
	// │ │ │ │ │
	// * * * * *
	CronSchedule string

	// Memo - Optional non-indexed info that will be shown in list workflow.
	Memo map[string]interface{}

	// SearchAttributes - Optional indexed info that can be used in query of List/Scan/Count workflow APIs. The key and value type must be registered on Temporal server side.
	// Use GetSearchAttributes API to get valid key and corresponding value type.
	// For supported operations on different server versions see [Visibility].
	//
	// Deprecated: use TypedSearchAttributes instead.
	//
	// [Visibility]: https://docs.temporal.io/visibility
	SearchAttributes map[string]interface{}

	// TypedSearchAttributes - Specifies Search Attributes that will be attached to the Workflow. Search Attributes are
	// additional indexed information attributed to workflow and used for search and visibility. The search attributes
	// can be used in query of List/Scan/Count workflow APIs. The key and its value type must be registered on Temporal
	// server side. For supported operations on different server versions see [Visibility].
	//
	// Optional: default to none.
	//
	// [Visibility]: https://docs.temporal.io/visibility
	TypedSearchAttributes SearchAttributes

	// EnableEagerStart - request eager execution for this workflow, if a local worker is available.
	//
	// WARNING: Eager start does not respect worker versioning. An eagerly started workflow may run on
	// any available local worker even if that worker is not in the default build ID set.
	//
	// NOTE: Experimental
	EnableEagerStart bool

	// StartDelay - Time to wait before dispatching the first workflow task.
	// A signal from signal with start will not trigger a workflow task.
	// Cannot be set the same time as a CronSchedule.
	StartDelay time.Duration

	// StaticSummary - Single-line fixed summary for this workflow execution that will appear in UI/CLI. This can be
	// in single-line Temporal markdown format.
	//
	// Optional: defaults to none/empty.
	//
	// NOTE: Experimental
	StaticSummary string

	// Details - General fixed details for this workflow execution that will appear in UI/CLI. This can be in
	// Temporal markdown format and can span multiple lines. This is a fixed value on the workflow that cannot be
	// updated. For details that can be updated, use SetCurrentDetails within the workflow.
	//
	// Optional: defaults to none/empty.
	//
	// NOTE: Experimental
	StaticDetails string
	// contains filtered or unexported fields
}

StartWorkflowOptions configuration parameters for starting a workflow execution. The current timeout resolution implementation is in seconds and uses math.Ceil(d.Seconds()) as the duration. But is subjected to change in the future.

type TaskQueueDescription added in v1.27.0

type TaskQueueDescription struct {
	// Task queue information for each Build ID. Empty string as key value means unversioned.
	VersionsInfo map[string]TaskQueueVersionInfo
}

TaskQueueDescription is the response to [Client.DescribeTaskQueueEnhanced].

type TaskQueuePollerInfo added in v1.27.0

type TaskQueuePollerInfo struct {
	// Time of the last poll. A value of zero means it was not set.
	LastAccessTime time.Time
	// The identity of the worker/client who is polling this task queue.
	Identity string
	// Polling rate. A value of zero means it was not set.
	RatePerSecond float64
	// Optional poller versioning capabilities. Available when a worker has opted into the worker versioning feature.
	WorkerVersionCapabilities *WorkerVersionCapabilities
}

TaskQueuePollerInfo provides information about a worker/client polling a task queue. It is used by TaskQueueTypeInfo.

type TaskQueueReachability added in v1.25.0

type TaskQueueReachability struct {
	// TaskQueueReachability for a worker in a single task queue.
	// If TaskQueueReachability is empty, this worker is considered unreachable in this task queue.
	TaskQueueReachability []TaskReachability
}

type TaskQueueStats added in v1.29.0

type TaskQueueStats struct {
	// The approximate number of tasks backlogged in this task queue. May count expired tasks but eventually
	// converges to the right value. Can be relied upon for scaling decisions.
	//
	// Special note for workflow task queue type: this metric does not count sticky queue tasks. However, because
	// those tasks only remain valid for a few seconds, the inaccuracy becomes less significant as the backlog size
	// grows.
	ApproximateBacklogCount int64
	// Approximate age of the oldest task in the backlog based on the creation time of the task at the head of
	// the queue. Can be relied upon for scaling decisions.
	//
	// Special note for workflow task queue type: this metric does not count sticky queue tasks. However, because
	// those tasks only remain valid for a few seconds, they should not affect the result when backlog is older than
	// few seconds.
	ApproximateBacklogAge time.Duration
	// Approximate *net* tasks per second added to the backlog, averaging the last 30 seconds. This is calculated as
	// `TasksAddRate - TasksDispatchRate`.
	// A positive value of `X` means the backlog is growing by about `X` tasks per second. A negative `-X` value means the
	// backlog is shrinking by about `X` tasks per second.
	//
	// Special note for workflow task queue type: this metric does not count sticky queue tasks. However, because
	// those tasks only remain valid for a few seconds, the inaccuracy becomes less significant as the backlog size
	// or age grow.
	BacklogIncreaseRate float32
	// Approximate tasks per second added to the task queue, averaging the last 30 seconds. This includes both
	// backlogged and sync-matched tasks, but excludes the Eagerly dispatched workflow and activity tasks (see
	// documentation for `client.StartWorkflowOptions.EnableEagerStart` and `worker.Options.DisableEagerActivities`.)
	//
	// The difference between `TasksAddRate` and `TasksDispatchRate` is a reliable metric for the rate at which
	// backlog grows/shrinks. See `BacklogIncreaseRate`.
	//
	// Special note for workflow task queue type: this metric does not count sticky queue tasks. Hence, the reported
	// value may be significantly lower than the actual number of workflow tasks added. Note that typically, only
	// the first workflow task of each workflow goes to a normal queue, and the rest workflow tasks go to the sticky
	// queue associated with a specific worker instance. Activity tasks always go to normal queues.
	TasksAddRate float32
	// Approximate tasks per second dispatched to workers, averaging the last 30 seconds. This includes both
	// backlogged and sync-matched tasks, but excludes the Eagerly dispatched workflow and activity tasks (see
	// documentation for `client.StartWorkflowOptions.EnableEagerStart` and `worker.Options.DisableEagerActivities`.)
	//
	// The difference between `TasksAddRate` and `TasksDispatchRate` is a reliable metric for the rate at which
	// backlog grows/shrinks. See `BacklogIncreaseRate`.
	//
	// Special note for workflow task queue type: this metric does not count sticky queue tasks. Hence, the reported
	// value may be significantly lower than the actual number of workflow tasks dispatched. Note that typically, only
	// the first workflow task of each workflow goes to a normal queue, and the rest workflow tasks go to the sticky
	// queue associated with a specific worker instance. Activity tasks always go to normal queues.
	TasksDispatchRate float32
}

TaskQueueStats contains statistics about task queue backlog and activity.

For workflow task queue type, this result is partial because tasks sent to sticky queues are not included. Read comments above each metric to understand the impact of sticky queue exclusion on that metric accuracy.

type TaskQueueType added in v1.27.0

type TaskQueueType int

TaskQueueType specifies which category of tasks are associated with a queue.

type TaskQueueTypeInfo added in v1.27.0

type TaskQueueTypeInfo struct {
	// Poller details for this task queue category.
	Pollers []TaskQueuePollerInfo
	Stats   *TaskQueueStats
}

TaskQueueTypeInfo specifies task queue information per task type and Build ID. It is included in TaskQueueVersionInfo.

type TaskQueueVersionInfo added in v1.27.0

type TaskQueueVersionInfo struct {
	// Task queue info per task type.
	TypesInfo map[TaskQueueType]TaskQueueTypeInfo
	// The category of tasks that may reach a versioned worker of a certain Build ID.
	TaskReachability BuildIDTaskReachability
}

TaskQueueVersionInfo includes task queue information per Build ID. It is part of TaskQueueDescription.

type TaskQueueVersionSelection added in v1.27.0

type TaskQueueVersionSelection struct {
	// Include specific Build IDs.
	BuildIDs []string
	// Include the unversioned queue.
	Unversioned bool
	// Include all active versions. A version is considered active if, in the last few minutes,
	// it has had new tasks or polls, or it has been the subject of certain task queue API calls.
	AllActive bool
}

TaskQueueVersionSelection is a task queue filter based on versioning. It is an optional component of DescribeTaskQueueEnhancedOptions.

type TaskReachability added in v1.25.0

type TaskReachability int

TaskReachability specifies which category of tasks may reach a worker on a versioned task queue. Used both in a reachability query and its response.

type TerminatedError

type TerminatedError struct {
	// contains filtered or unexported fields
}

TerminatedError returned when workflow was terminated.

func (*TerminatedError) Error

func (e *TerminatedError) Error() string

Error from error interface

type TestActivityEnvironment

type TestActivityEnvironment struct {
	// contains filtered or unexported fields
}

TestActivityEnvironment is the environment that you use to test activity

func (*TestActivityEnvironment) ExecuteActivity

func (t *TestActivityEnvironment) ExecuteActivity(activityFn interface{}, args ...interface{}) (converter.EncodedValue, error)

ExecuteActivity executes an activity. The tested activity will be executed synchronously in the calling goroutinue. Caller should use EncodedValue.Get() to extract strong typed result value.

func (*TestActivityEnvironment) ExecuteLocalActivity

func (t *TestActivityEnvironment) ExecuteLocalActivity(activityFn interface{}, args ...interface{}) (val converter.EncodedValue, err error)

ExecuteLocalActivity executes a local activity. The tested activity will be executed synchronously in the calling goroutinue. Caller should use EncodedValue.Get() to extract strong typed result value.

func (*TestActivityEnvironment) RegisterActivity

func (t *TestActivityEnvironment) RegisterActivity(a interface{})

RegisterActivity registers activity implementation with TestWorkflowEnvironment

func (*TestActivityEnvironment) RegisterActivityWithOptions

func (t *TestActivityEnvironment) RegisterActivityWithOptions(a interface{}, options RegisterActivityOptions)

RegisterActivityWithOptions registers activity implementation with TestWorkflowEnvironment

func (*TestActivityEnvironment) SetContextPropagators

func (t *TestActivityEnvironment) SetContextPropagators(contextPropagators []ContextPropagator) *TestActivityEnvironment

SetContextPropagators sets context propagators.

func (*TestActivityEnvironment) SetDataConverter

func (t *TestActivityEnvironment) SetDataConverter(dataConverter converter.DataConverter) *TestActivityEnvironment

SetDataConverter sets data converter.

func (*TestActivityEnvironment) SetFailureConverter added in v1.27.0

func (t *TestActivityEnvironment) SetFailureConverter(failureConverter converter.FailureConverter) *TestActivityEnvironment

SetFailureConverter sets the failure converter.

func (*TestActivityEnvironment) SetHeader added in v1.1.0

func (t *TestActivityEnvironment) SetHeader(header *commonpb.Header)

SetHeader sets header.

func (*TestActivityEnvironment) SetHeartbeatDetails

func (t *TestActivityEnvironment) SetHeartbeatDetails(details interface{})

SetHeartbeatDetails sets the heartbeat details to be returned from activity.GetHeartbeatDetails()

func (*TestActivityEnvironment) SetIdentity

func (t *TestActivityEnvironment) SetIdentity(identity string) *TestActivityEnvironment

SetIdentity sets identity.

func (*TestActivityEnvironment) SetOnActivityHeartbeatListener added in v1.15.0

func (t *TestActivityEnvironment) SetOnActivityHeartbeatListener(
	listener func(activityInfo *ActivityInfo, details converter.EncodedValues)) *TestActivityEnvironment

SetOnActivityHeartbeatListener sets a listener that will be called when activity heartbeat is called. ActivityInfo is defined in internal package, use public type activity.Info instead.

Note: Due to internal caching by the activity system, this may not get called for every heartbeat recorded. This is only called when the heartbeat would be sent to the server (periodic batch and at the end only on failure). Interceptors can be used to intercept/check every heartbeat call.

func (*TestActivityEnvironment) SetTestTimeout

func (t *TestActivityEnvironment) SetTestTimeout(idleTimeout time.Duration) *TestActivityEnvironment

SetTestTimeout sets the wall clock timeout for this activity test run. When test timeout happen, it means activity is taking too long.

func (*TestActivityEnvironment) SetWorkerOptions

func (t *TestActivityEnvironment) SetWorkerOptions(options WorkerOptions) *TestActivityEnvironment

SetWorkerOptions sets the WorkerOptions that will be use by TestActivityEnvironment. TestActivityEnvironment will use options of BackgroundActivityContext, MaxConcurrentSessionExecutionSize, and WorkflowInterceptorChainFactories on the WorkerOptions. Other options are ignored. Note: WorkerOptions is defined in internal package, use public type worker.Options instead.

func (*TestActivityEnvironment) SetWorkerStopChannel

func (t *TestActivityEnvironment) SetWorkerStopChannel(c chan struct{})

SetWorkerStopChannel sets the worker stop channel to be returned from activity.GetWorkerStopChannel(context) To test your activity on worker stop, you can provide a go channel with this function and call ExecuteActivity(). Then call close(channel) to test the activity worker stop logic.

type TestWorkflowEnvironment

type TestWorkflowEnvironment struct {
	// contains filtered or unexported fields
}

TestWorkflowEnvironment is the environment that you use to test workflow

func (*TestWorkflowEnvironment) AssertActivityCalled added in v1.26.0

func (e *TestWorkflowEnvironment) AssertActivityCalled(t mock.TestingT, methodName string, arguments ...interface{}) bool

AssertActivityCalled asserts that the activity method was called with the supplied arguments. Special method for activities, doesn't assert workflow calls.

func (*TestWorkflowEnvironment) AssertActivityNotCalled added in v1.26.0

func (e *TestWorkflowEnvironment) AssertActivityNotCalled(t mock.TestingT, methodName string, arguments ...interface{}) bool

AssertActivityNotCalled asserts that the activity method was not called with the given arguments. Special method for activities, doesn't assert workflow calls. See AssertCalled for more info.

func (*TestWorkflowEnvironment) AssertActivityNumberOfCalls added in v1.26.0

func (e *TestWorkflowEnvironment) AssertActivityNumberOfCalls(t mock.TestingT, methodName string, expectedCalls int) bool

AssertActivityNumberOfCalls asserts that a activity method was called expectedCalls times. Special method for activities, doesn't assert workflow calls.

func (*TestWorkflowEnvironment) AssertCalled added in v1.14.0

func (e *TestWorkflowEnvironment) AssertCalled(t mock.TestingT, methodName string, arguments ...interface{}) bool

AssertCalled asserts that the method was called with the supplied arguments. Useful to assert that an Activity was called from within a workflow with the expected arguments. Since the first argument is a context, consider using mock.Anything for that argument.

env.OnActivity(namedActivity, mock.Anything, mock.Anything).Return("mock_result", nil)
env.ExecuteWorkflow(workflowThatCallsActivityWithItsArgument, "Hello")
env.AssertCalled(t, "namedActivity", mock.Anything, "Hello")

It can produce a false result when an argument is a pointer type and the underlying value changed after calling the mocked method.

func (*TestWorkflowEnvironment) AssertExpectations

func (e *TestWorkflowEnvironment) AssertExpectations(t mock.TestingT) bool

AssertExpectations asserts that everything specified with OnActivity in fact called as expected. Calls may have occurred in any order.

func (*TestWorkflowEnvironment) AssertNotCalled added in v1.14.0

func (e *TestWorkflowEnvironment) AssertNotCalled(t mock.TestingT, methodName string, arguments ...interface{}) bool

AssertNotCalled asserts that the method was not called with the given arguments. See AssertCalled for more info.

func (*TestWorkflowEnvironment) AssertNumberOfCalls added in v1.14.0

func (e *TestWorkflowEnvironment) AssertNumberOfCalls(t mock.TestingT, methodName string, expectedCalls int) bool

AssertNumberOfCalls asserts that a method was called expectedCalls times.

func (*TestWorkflowEnvironment) AssertWorkflowCalled added in v1.26.0

func (e *TestWorkflowEnvironment) AssertWorkflowCalled(t mock.TestingT, methodName string, arguments ...interface{}) bool

AssertWorkflowCalled asserts that the workflow method was called with the supplied arguments. Special method for workflows, doesn't assert activity calls.

func (*TestWorkflowEnvironment) AssertWorkflowNotCalled added in v1.26.0

func (e *TestWorkflowEnvironment) AssertWorkflowNotCalled(t mock.TestingT, methodName string, arguments ...interface{}) bool

AssertWorkflowNotCalled asserts that the workflow method was not called with the given arguments. Special method for workflows, doesn't assert activity calls. See AssertCalled for more info.

func (*TestWorkflowEnvironment) AssertWorkflowNumberOfCalls added in v1.26.0

func (e *TestWorkflowEnvironment) AssertWorkflowNumberOfCalls(t mock.TestingT, methodName string, expectedCalls int) bool

AssertWorkflowNumberOfCalls asserts that a workflow method was called expectedCalls times. Special method for workflows, doesn't assert activity calls.

func (*TestWorkflowEnvironment) CancelWorkflow

func (e *TestWorkflowEnvironment) CancelWorkflow()

CancelWorkflow requests cancellation (through workflow Context) to the currently running test workflow.

func (*TestWorkflowEnvironment) CancelWorkflowByID added in v1.26.0

func (e *TestWorkflowEnvironment) CancelWorkflowByID(workflowID string, runID string)

CancelWorkflowByID requests cancellation (through workflow Context) to the specified workflow.

func (*TestWorkflowEnvironment) CompleteActivity

func (e *TestWorkflowEnvironment) CompleteActivity(taskToken []byte, result interface{}, err error) error

CompleteActivity complete an activity that had returned activity.ErrResultPending error

func (*TestWorkflowEnvironment) ExecuteWorkflow

func (e *TestWorkflowEnvironment) ExecuteWorkflow(workflowFn interface{}, args ...interface{})

ExecuteWorkflow executes a workflow, wait until workflow complete. It will fail the test if workflow is blocked and cannot complete within TestTimeout (set by SetTestTimeout()).

func (*TestWorkflowEnvironment) GetWorkflowError

func (e *TestWorkflowEnvironment) GetWorkflowError() error

GetWorkflowError return the error from test workflow

func (*TestWorkflowEnvironment) GetWorkflowErrorByID added in v1.8.0

func (e *TestWorkflowEnvironment) GetWorkflowErrorByID(workflowID string) error

GetWorkflowErrorByID return the error from test workflow

func (*TestWorkflowEnvironment) GetWorkflowResult

func (e *TestWorkflowEnvironment) GetWorkflowResult(valuePtr interface{}) error

GetWorkflowResult extracts the encoded result from test workflow, it returns error if the extraction failed.

func (*TestWorkflowEnvironment) GetWorkflowResultByID added in v1.8.0

func (e *TestWorkflowEnvironment) GetWorkflowResultByID(workflowID string, valuePtr interface{}) error

GetWorkflowResultByID extracts the encoded result from workflow by ID, it returns error if the extraction failed.

func (*TestWorkflowEnvironment) IsWorkflowCompleted

func (e *TestWorkflowEnvironment) IsWorkflowCompleted() bool

IsWorkflowCompleted check if test is completed or not

func (*TestWorkflowEnvironment) Now

Now returns the current workflow time (a.k.a workflow.Now() time) of this TestWorkflowEnvironment.

func (*TestWorkflowEnvironment) OnActivity

func (e *TestWorkflowEnvironment) OnActivity(activity interface{}, args ...interface{}) *MockCallWrapper

OnActivity setup a mock call for activity. Parameter activity must be activity function (func) or activity name (string). You must call Return() with appropriate parameters on the returned *MockCallWrapper instance. The supplied parameters to the Return() call should either be a function that has exact same signature as the mocked activity, or it should be mock values with the same types as the mocked activity function returns. Example: assume the activity you want to mock has function signature as:

func MyActivity(ctx context.Context, msg string) (string, error)

You can mock it by return a function with exact same signature:

t.OnActivity(MyActivity, mock.Anything, mock.Anything).Return(func(ctx context.Context, msg string) (string, error) {
   // your mock function implementation
   return "", nil
})

OR return mock values with same types as activity function's return types:

t.OnActivity(MyActivity, mock.Anything, mock.Anything).Return("mock_result", nil)

Note, when using a method reference with a receiver as an activity, the receiver must be an instance the same as if it was being using in RegisterActivity so the parameter types are accurate. In Go, a method reference of (*MyStruct).MyFunc makes the first parameter *MyStruct which will not work, whereas a method reference of new(MyStruct).MyFunc will.

Mock callbacks here are run on a separate goroutine than the workflow and therefore are not concurrency-safe with workflow code.

func (*TestWorkflowEnvironment) OnGetVersion

func (e *TestWorkflowEnvironment) OnGetVersion(changeID string, minSupported, maxSupported Version) *MockCallWrapper

OnGetVersion setup a mock for workflow.GetVersion() call. By default, if mock is not setup, the GetVersion call from workflow code will always return the maxSupported version. Make it not possible to test old version branch. With this mock support, it is possible to test code branch for different versions.

Note: mock can be setup for a specific changeID. Or if mock.Anything is used as changeID then all calls to GetVersion will be mocked. Mock for a specific changeID has higher priority over mock.Anything.

func (*TestWorkflowEnvironment) OnRequestCancelExternalWorkflow

func (e *TestWorkflowEnvironment) OnRequestCancelExternalWorkflow(namespace, workflowID, runID string) *MockCallWrapper

OnRequestCancelExternalWorkflow setup a mock for cancellation of external workflow. This TestWorkflowEnvironment handles cancellation of workflows that are started from the root workflow. For example, cancellation sent from parent to child workflows. Or cancellation between 2 child workflows. However, it does not know what to do if your tested workflow code is sending cancellation to external unknown workflows. In that case, you will need to setup mock for those cancel calls. Some examples of how to setup mock:

  • mock for specific target workflow that matches specific workflow ID and run ID env.OnRequestCancelExternalWorkflow("test-namespace", "test-workflow-id1", "test-runid1").Return(nil).Once()
  • mock for anything and succeed the cancellation env.OnRequestCancelExternalWorkflow(mock.Anything, mock.Anything, mock.Anything).Return(nil).Once()
  • mock for anything and fail the cancellation env.OnRequestCancelExternalWorkflow(mock.Anything, mock.Anything, mock.Anything).Return(errors.New("unknown external workflow")).Once()
  • mock function for RequestCancelExternalWorkflow env.OnRequestCancelExternalWorkflow(mock.Anything, mock.Anything, mock.Anything).Return( func(namespace, workflowID, runID) error { // you can do differently based on the parameters return nil })

Mock callbacks here are run on a separate goroutine than the workflow and therefore are not concurrency-safe with workflow code.

func (*TestWorkflowEnvironment) OnSignalExternalWorkflow

func (e *TestWorkflowEnvironment) OnSignalExternalWorkflow(namespace, workflowID, runID, signalName, arg interface{}) *MockCallWrapper

OnSignalExternalWorkflow setup a mock for sending signal to external workflow. This TestWorkflowEnvironment handles sending signals between the workflows that are started from the root workflow. For example, sending signals between parent and child workflows. Or sending signals between 2 child workflows. However, it does not know what to do if your tested workflow code is sending signal to external unknown workflows. In that case, you will need to setup mock for those signal calls. Some examples of how to setup mock:

  • mock for specific target workflow that matches specific signal name and signal data env.OnSignalExternalWorkflow("test-namespace", "test-workflow-id1", "test-runid1", "test-signal", "test-data").Return(nil).Once()
  • mock for anything and succeed the send env.OnSignalExternalWorkflow(mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil).Once()
  • mock for anything and fail the send env.OnSignalExternalWorkflow(mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(errors.New("unknown external workflow")).Once()
  • mock function for SignalExternalWorkflow env.OnSignalExternalWorkflow(mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return( func(namespace, workflowID, runID, signalName string, arg interface{}) error { // you can do differently based on the parameters return nil })

Mock callbacks here are run on a separate goroutine than the workflow and therefore are not concurrency-safe with workflow code.

func (*TestWorkflowEnvironment) OnUpsertMemo added in v1.17.0

func (e *TestWorkflowEnvironment) OnUpsertMemo(attributes interface{}) *MockCallWrapper

OnUpsertMemo setup a mock for workflow.UpsertMemo call. If mock is not setup, the UpsertMemo call will only validate input attributes. If mock is setup, all UpsertMemo calls in workflow have to be mocked.

func (*TestWorkflowEnvironment) OnUpsertSearchAttributes deprecated

func (e *TestWorkflowEnvironment) OnUpsertSearchAttributes(attributes interface{}) *MockCallWrapper

OnUpsertSearchAttributes setup a mock for workflow.UpsertSearchAttributes call. If mock is not setup, the UpsertSearchAttributes call will only validate input attributes. If mock is setup, all UpsertSearchAttributes calls in workflow have to be mocked.

Deprecated: use OnUpsertTypedSearchAttributes instead.

func (*TestWorkflowEnvironment) OnUpsertTypedSearchAttributes added in v1.26.0

func (e *TestWorkflowEnvironment) OnUpsertTypedSearchAttributes(attributes interface{}) *MockCallWrapper

OnUpsertTypedSearchAttributes setup a mock for workflow.UpsertTypedSearchAttributes call. If mock is not setup, the UpsertTypedSearchAttributes call will only validate input attributes. If mock is setup, all UpsertTypedSearchAttributes calls in workflow have to be mocked. Note: The mock is called with a temporal.SearchAttributes constructed from the inputs to workflow.UpsertTypedSearchAttributes.

func (*TestWorkflowEnvironment) OnWorkflow

func (e *TestWorkflowEnvironment) OnWorkflow(workflow interface{}, args ...interface{}) *MockCallWrapper

OnWorkflow setup a mock call for workflow. Parameter workflow must be workflow function (func) or workflow name (string). You must call Return() with appropriate parameters on the returned *MockCallWrapper instance. The supplied parameters to the Return() call should either be a function that has exact same signature as the mocked workflow, or it should be mock values with the same types as the mocked workflow function returns. Example: assume the workflow you want to mock has function signature as:

func MyChildWorkflow(ctx workflow.Context, msg string) (string, error)

You can mock it by return a function with exact same signature:

t.OnWorkflow(MyChildWorkflow, mock.Anything, mock.Anything).Return(func(ctx workflow.Context, msg string) (string, error) {
   // your mock function implementation
   return "", nil
})

OR return mock values with same types as workflow function's return types:

t.OnWorkflow(MyChildWorkflow, mock.Anything, mock.Anything).Return("mock_result", nil)

You could also setup mock to simulate start child workflow failure case by returning ErrMockStartChildWorkflowFailed as error.

Mock callbacks here are run on a separate goroutine than the workflow and therefore are not concurrency-safe with workflow code.

func (*TestWorkflowEnvironment) QueryWorkflow

func (e *TestWorkflowEnvironment) QueryWorkflow(queryType string, args ...interface{}) (converter.EncodedValue, error)

QueryWorkflow queries to the currently running test workflow and returns result synchronously.

func (*TestWorkflowEnvironment) QueryWorkflowByID added in v1.6.0

func (e *TestWorkflowEnvironment) QueryWorkflowByID(workflowID, queryType string, args ...interface{}) (converter.EncodedValue, error)

QueryWorkflowByID queries a child workflow by its ID and returns the result synchronously

func (*TestWorkflowEnvironment) RegisterActivity

func (e *TestWorkflowEnvironment) RegisterActivity(a interface{})

RegisterActivity registers activity implementation with TestWorkflowEnvironment

func (*TestWorkflowEnvironment) RegisterActivityWithOptions

func (e *TestWorkflowEnvironment) RegisterActivityWithOptions(a interface{}, options RegisterActivityOptions)

RegisterActivityWithOptions registers activity implementation with TestWorkflowEnvironment

func (*TestWorkflowEnvironment) RegisterDelayedCallback

func (e *TestWorkflowEnvironment) RegisterDelayedCallback(callback func(), delayDuration time.Duration)

RegisterDelayedCallback creates a new timer with specified delayDuration using workflow clock (not wall clock). When the timer fires, the callback will be called. By default, this test suite uses mock clock which automatically move forward to fire next timer when workflow is blocked. Use this API to make some event (like activity completion, signal or workflow cancellation) at desired time.

Use 0 delayDuration to send a signal to simulate SignalWithStart. Note that a 0 duration delay will *not* work with Queries, as the workflow will not have had a chance to register any query handlers.

func (*TestWorkflowEnvironment) RegisterNexusService added in v1.28.0

func (e *TestWorkflowEnvironment) RegisterNexusService(s *nexus.Service)

RegisterWorkflow registers a Nexus Service with the TestWorkflowEnvironment.

func (*TestWorkflowEnvironment) RegisterWorkflow

func (e *TestWorkflowEnvironment) RegisterWorkflow(w interface{})

RegisterWorkflow registers workflow implementation with the TestWorkflowEnvironment

func (*TestWorkflowEnvironment) RegisterWorkflowWithOptions

func (e *TestWorkflowEnvironment) RegisterWorkflowWithOptions(w interface{}, options RegisterWorkflowOptions)

RegisterWorkflowWithOptions registers workflow implementation with the TestWorkflowEnvironment

func (*TestWorkflowEnvironment) SetActivityTaskQueue

func (e *TestWorkflowEnvironment) SetActivityTaskQueue(taskqueue string, activityFn ...interface{})

SetActivityTaskQueue set the affinity between activity and taskqueue. By default, activity can be invoked by any taskqueue in this test environment. Use this SetActivityTaskQueue() to set affinity between activity and a taskqueue. Once activity is set to a particular taskqueue, that activity will only be available to that taskqueue.

func (*TestWorkflowEnvironment) SetContextPropagators added in v1.1.0

func (e *TestWorkflowEnvironment) SetContextPropagators(contextPropagators []ContextPropagator) *TestWorkflowEnvironment

SetContextPropagators sets context propagators.

func (*TestWorkflowEnvironment) SetContinueAsNewSuggested added in v1.25.0

func (e *TestWorkflowEnvironment) SetContinueAsNewSuggested(suggest bool)

SetContinueAsNewSuggested set sets the value that is returned from GetInfo(ctx).GetContinueAsNewSuggested().

Note: this value may not be up to date if accessed inside a query.

func (*TestWorkflowEnvironment) SetContinuedExecutionRunID added in v1.25.0

func (e *TestWorkflowEnvironment) SetContinuedExecutionRunID(rid string)

SetContinuedExecutionRunID sets the value that is returned from GetInfo(ctx).ContinuedExecutionRunID

func (*TestWorkflowEnvironment) SetCurrentHistoryLength added in v1.16.0

func (e *TestWorkflowEnvironment) SetCurrentHistoryLength(length int)

SetCurrentHistoryLength sets the value that is returned from GetInfo(ctx).GetCurrentHistoryLength().

Note: this value may not be up to date if accessed inside a query.

func (*TestWorkflowEnvironment) SetCurrentHistorySize added in v1.25.0

func (e *TestWorkflowEnvironment) SetCurrentHistorySize(length int)

setCurrentHistoryLength sets the value that is returned from GetInfo(ctx).GetCurrentHistorySize().

Note: this value may not be up to date if accessed inside a query.

func (*TestWorkflowEnvironment) SetDataConverter

func (e *TestWorkflowEnvironment) SetDataConverter(dataConverter converter.DataConverter) *TestWorkflowEnvironment

SetDataConverter sets data converter.

func (*TestWorkflowEnvironment) SetDetachedChildWait added in v1.12.0

func (e *TestWorkflowEnvironment) SetDetachedChildWait(detachedChildWait bool) *TestWorkflowEnvironment

SetDetachedChildWait, if true, will make ExecuteWorkflow wait on all child workflows to complete even if their close policy is set to abandon or request cancel, meaning they are "detached". If false, ExecuteWorkflow will block until only all attached child workflows have completed. This is useful when testing endless detached child workflows, as without it ExecuteWorkflow may not return while detached children are still running.

Default is true.

func (*TestWorkflowEnvironment) SetFailureConverter added in v1.27.0

func (t *TestWorkflowEnvironment) SetFailureConverter(failureConverter converter.FailureConverter) *TestWorkflowEnvironment

SetFailureConverter sets the failure converter.

func (*TestWorkflowEnvironment) SetHeader added in v1.1.0

func (e *TestWorkflowEnvironment) SetHeader(header *commonpb.Header)

SetHeader sets header.

func (*TestWorkflowEnvironment) SetIdentity

func (e *TestWorkflowEnvironment) SetIdentity(identity string) *TestWorkflowEnvironment

SetIdentity sets identity.

func (*TestWorkflowEnvironment) SetLastCompletionResult

func (e *TestWorkflowEnvironment) SetLastCompletionResult(result interface{})

SetLastCompletionResult sets the result to be returned from workflow.GetLastCompletionResult().

func (*TestWorkflowEnvironment) SetLastError added in v1.3.0

func (e *TestWorkflowEnvironment) SetLastError(err error)

SetLastError sets the result to be returned from workflow.GetLastError().

func (*TestWorkflowEnvironment) SetMemoOnStart

func (e *TestWorkflowEnvironment) SetMemoOnStart(memo map[string]interface{}) error

SetMemoOnStart sets the memo when start workflow.

func (*TestWorkflowEnvironment) SetOnActivityCanceledListener

func (e *TestWorkflowEnvironment) SetOnActivityCanceledListener(
	listener func(activityInfo *ActivityInfo)) *TestWorkflowEnvironment

SetOnActivityCanceledListener sets a listener that will be called after an activity is canceled. Note: ActivityInfo is defined in internal package, use public type activity.Info instead.

func (*TestWorkflowEnvironment) SetOnActivityCompletedListener

func (e *TestWorkflowEnvironment) SetOnActivityCompletedListener(
	listener func(activityInfo *ActivityInfo, result converter.EncodedValue, err error)) *TestWorkflowEnvironment

SetOnActivityCompletedListener sets a listener that will be called after an activity is completed. Note: ActivityInfo is defined in internal package, use public type activity.Info instead.

func (*TestWorkflowEnvironment) SetOnActivityHeartbeatListener

func (e *TestWorkflowEnvironment) SetOnActivityHeartbeatListener(
	listener func(activityInfo *ActivityInfo, details converter.EncodedValues)) *TestWorkflowEnvironment

SetOnActivityHeartbeatListener sets a listener that will be called when activity heartbeat. Note: ActivityInfo is defined in internal package, use public type activity.Info instead.

Note: Due to internal caching by the activity system, this may not get called for every heartbeat recorded. This is only called when the heartbeat would be sent to the server (periodic batch and at the end only on failure). Interceptors can be used to intercept/check every heartbeat call.

func (*TestWorkflowEnvironment) SetOnActivityStartedListener

func (e *TestWorkflowEnvironment) SetOnActivityStartedListener(
	listener func(activityInfo *ActivityInfo, ctx context.Context, args converter.EncodedValues)) *TestWorkflowEnvironment

SetOnActivityStartedListener sets a listener that will be called before activity starts execution. Note: ActivityInfo is defined in internal package, use public type activity.Info instead.

func (*TestWorkflowEnvironment) SetOnChildWorkflowCanceledListener

func (e *TestWorkflowEnvironment) SetOnChildWorkflowCanceledListener(
	listener func(workflowInfo *WorkflowInfo)) *TestWorkflowEnvironment

SetOnChildWorkflowCanceledListener sets a listener that will be called when a child workflow is canceled. Note: WorkflowInfo is defined in internal package, use public type workflow.Info instead.

func (*TestWorkflowEnvironment) SetOnChildWorkflowCompletedListener

func (e *TestWorkflowEnvironment) SetOnChildWorkflowCompletedListener(
	listener func(workflowInfo *WorkflowInfo, result converter.EncodedValue, err error)) *TestWorkflowEnvironment

SetOnChildWorkflowCompletedListener sets a listener that will be called after a child workflow is completed. Note: WorkflowInfo is defined in internal package, use public type workflow.Info instead.

func (*TestWorkflowEnvironment) SetOnChildWorkflowStartedListener

func (e *TestWorkflowEnvironment) SetOnChildWorkflowStartedListener(
	listener func(workflowInfo *WorkflowInfo, ctx Context, args converter.EncodedValues)) *TestWorkflowEnvironment

SetOnChildWorkflowStartedListener sets a listener that will be called before a child workflow starts execution. Note: WorkflowInfo is defined in internal package, use public type workflow.Info instead.

func (*TestWorkflowEnvironment) SetOnLocalActivityCanceledListener

func (e *TestWorkflowEnvironment) SetOnLocalActivityCanceledListener(
	listener func(activityInfo *ActivityInfo)) *TestWorkflowEnvironment

SetOnLocalActivityCanceledListener sets a listener that will be called after local activity is canceled. Note: ActivityInfo is defined in internal package, use public type activity.Info instead.

func (*TestWorkflowEnvironment) SetOnLocalActivityCompletedListener

func (e *TestWorkflowEnvironment) SetOnLocalActivityCompletedListener(
	listener func(activityInfo *ActivityInfo, result converter.EncodedValue, err error)) *TestWorkflowEnvironment

SetOnLocalActivityCompletedListener sets a listener that will be called after local activity is completed. Note: ActivityInfo is defined in internal package, use public type activity.Info instead.

func (*TestWorkflowEnvironment) SetOnLocalActivityStartedListener

func (e *TestWorkflowEnvironment) SetOnLocalActivityStartedListener(
	listener func(activityInfo *ActivityInfo, ctx context.Context, args []interface{})) *TestWorkflowEnvironment

SetOnLocalActivityStartedListener sets a listener that will be called before local activity starts execution. Note: ActivityInfo is defined in internal package, use public type activity.Info instead.

func (*TestWorkflowEnvironment) SetOnTimerCanceledListener added in v0.28.2

func (e *TestWorkflowEnvironment) SetOnTimerCanceledListener(listener func(timerID string)) *TestWorkflowEnvironment

SetOnTimerCanceledListener sets a listener that will be called after a timer is canceled

func (*TestWorkflowEnvironment) SetOnTimerFiredListener

func (e *TestWorkflowEnvironment) SetOnTimerFiredListener(listener func(timerID string)) *TestWorkflowEnvironment

SetOnTimerFiredListener sets a listener that will be called after a timer is fired.

func (*TestWorkflowEnvironment) SetOnTimerScheduledListener

func (e *TestWorkflowEnvironment) SetOnTimerScheduledListener(
	listener func(timerID string, duration time.Duration)) *TestWorkflowEnvironment

SetOnTimerScheduledListener sets a listener that will be called before a timer is scheduled.

func (*TestWorkflowEnvironment) SetSearchAttributesOnStart deprecated

func (e *TestWorkflowEnvironment) SetSearchAttributesOnStart(searchAttributes map[string]interface{}) error

SetSearchAttributesOnStart sets the search attributes when start workflow.

Deprecated: Use SetTypedSearchAttributes instead.

func (*TestWorkflowEnvironment) SetStartTime

func (e *TestWorkflowEnvironment) SetStartTime(startTime time.Time)

SetStartTime sets the start time of the workflow. This is optional, default start time will be the wall clock time when workflow starts. Start time is the workflow.Now(ctx) time at the beginning of the workflow.

func (*TestWorkflowEnvironment) SetStartWorkflowOptions

func (e *TestWorkflowEnvironment) SetStartWorkflowOptions(options StartWorkflowOptions) *TestWorkflowEnvironment

SetStartWorkflowOptions sets StartWorkflowOptions used to specify workflow execution timeout and task queue. Note that StartWorkflowOptions is defined in an internal package, use client.StartWorkflowOptions instead.

func (*TestWorkflowEnvironment) SetTestTimeout

func (e *TestWorkflowEnvironment) SetTestTimeout(idleTimeout time.Duration) *TestWorkflowEnvironment

SetTestTimeout sets the idle timeout based on wall clock for this tested workflow. Idle is when workflow is blocked waiting on events (including timer, activity, child workflow, signal etc). If there is no event happening longer than this idle timeout, the test framework would stop the workflow and return timeout error. This is based on real wall clock time, not the workflow time (a.k.a workflow.Now() time).

func (*TestWorkflowEnvironment) SetTypedSearchAttributesOnStart added in v1.26.0

func (e *TestWorkflowEnvironment) SetTypedSearchAttributesOnStart(searchAttributes SearchAttributes) error

SetTypedSearchAttributesOnStart sets the search attributes when start workflow.

func (*TestWorkflowEnvironment) SetWorkerOptions

func (e *TestWorkflowEnvironment) SetWorkerOptions(options WorkerOptions) *TestWorkflowEnvironment

SetWorkerOptions sets the WorkerOptions that will be use by TestActivityEnvironment. TestActivityEnvironment will use options of BackgroundActivityContext, MaxConcurrentSessionExecutionSize, and WorkflowInterceptorChainFactories on the WorkerOptions. Other options are ignored. Note: WorkerOptions is defined in internal package, use public type worker.Options instead.

func (*TestWorkflowEnvironment) SetWorkerStopChannel

func (e *TestWorkflowEnvironment) SetWorkerStopChannel(c chan struct{})

SetWorkerStopChannel sets the activity worker stop channel to be returned from activity.GetWorkerStopChannel(context) You can use this function to set the activity worker stop channel and use close(channel) to test your activity execution from workflow execution.

func (*TestWorkflowEnvironment) SetWorkflowRunTimeout

func (e *TestWorkflowEnvironment) SetWorkflowRunTimeout(runTimeout time.Duration) *TestWorkflowEnvironment

SetWorkflowRunTimeout sets the run timeout for this tested workflow. This test framework uses mock clock internally and when workflow is blocked on timer, it will auto forward the mock clock. Use SetWorkflowRunTimeout() to enforce a workflow run timeout to return timeout error when the workflow mock clock is moved head of the timeout. This is based on the workflow time (a.k.a workflow.Now() time).

func (*TestWorkflowEnvironment) SignalWorkflow

func (e *TestWorkflowEnvironment) SignalWorkflow(name string, input interface{})

SignalWorkflow sends signal to the currently running test workflow.

func (*TestWorkflowEnvironment) SignalWorkflowByID

func (e *TestWorkflowEnvironment) SignalWorkflowByID(workflowID, signalName string, input interface{}) error

SignalWorkflowByID signals a workflow by its ID.

func (*TestWorkflowEnvironment) SignalWorkflowSkippingWorkflowTask

func (e *TestWorkflowEnvironment) SignalWorkflowSkippingWorkflowTask(name string, input interface{})

SignalWorkflowSkippingWorkflowTask sends signal to the currently running test workflow without invoking workflow code. Used to test processing of multiple buffered signals before completing workflow. It must be followed by SignalWorkflow, CancelWorkflow or CompleteActivity to force a workflow task.

func (*TestWorkflowEnvironment) UpdateWorkflow added in v1.16.0

func (e *TestWorkflowEnvironment) UpdateWorkflow(updateName, updateID string, uc UpdateCallbacks, args ...interface{})

UpdateWorkflow sends an update to the currently running workflow.

func (*TestWorkflowEnvironment) UpdateWorkflowByID added in v1.25.1

func (e *TestWorkflowEnvironment) UpdateWorkflowByID(workflowID, updateName, updateID string, uc UpdateCallbacks, args interface{}) error

UpdateWorkflowByID sends an update to a running workflow by its ID.

type TimeoutError

type TimeoutError struct {
	// contains filtered or unexported fields
}

TimeoutError returned when activity or child workflow timed out.

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

Error from error interface

func (*TimeoutError) HasLastHeartbeatDetails

func (e *TimeoutError) HasLastHeartbeatDetails() bool

HasLastHeartbeatDetails return if this error has strong typed detail data.

func (*TimeoutError) LastHeartbeatDetails

func (e *TimeoutError) LastHeartbeatDetails(d ...interface{}) error

LastHeartbeatDetails extracts strong typed detail data of this error. If there is no details, it will return ErrNoData.

func (*TimeoutError) Message added in v1.15.0

func (e *TimeoutError) Message() string

Message contains just the message string without extras added by Error().

func (*TimeoutError) TimeoutType

func (e *TimeoutError) TimeoutType() enumspb.TimeoutType

TimeoutType return timeout type of this error

func (*TimeoutError) Unwrap

func (e *TimeoutError) Unwrap() error

type TimerID added in v1.3.0

type TimerID struct {
	// contains filtered or unexported fields
}

TimerID contains id of the timer

func ParseTimerID added in v1.3.0

func ParseTimerID(id string) (TimerID, error)

ParseTimerID returns TimerID constructed from its string representation. The string representation should be obtained through TimerID.String()

func (TimerID) String added in v1.3.0

func (i TimerID) String() string

type TimerOptions added in v1.29.0

type TimerOptions struct {
	// Summary is a simple string identifying this timer. While it can be
	// normal text, it is best to treat as a timer ID. This value will be
	// visible in UI and CLI.
	//
	// NOTE: Experimental
	Summary string
}

TimerOptions are options set when creating a timer.

NOTE: Experimental

type TrafficController added in v1.7.0

type TrafficController interface {
	CheckCallAllowed(ctx context.Context, method string, req, reply interface{}) error
}

TrafficController is getting called in the interceptor chain with API invocation parameters. Result is either nil if API call is allowed or an error, in which case request would be interrupted and the error will be propagated back through the interceptor chain.

type UnknownExternalWorkflowExecutionError

type UnknownExternalWorkflowExecutionError struct{}

UnknownExternalWorkflowExecutionError can be returned when external workflow doesn't exist

func (*UnknownExternalWorkflowExecutionError) Error

Error from error interface

type UpdateBuildIDOp added in v1.23.0

type UpdateBuildIDOp interface {
	// contains filtered or unexported methods
}

UpdateBuildIDOp is an interface for the different operations that can be performed when updating the worker build ID compatibility sets for a task queue.

Possible operations are:

  • BuildIDOpAddNewIDInNewDefaultSet
  • BuildIDOpAddNewCompatibleVersion
  • BuildIDOpPromoteSet
  • BuildIDOpPromoteIDWithinSet

type UpdateCallbacks added in v1.16.0

type UpdateCallbacks interface {
	// Accept is called for an update after it has passed validation an
	// before execution has started.
	Accept()

	// Reject is called for an update if validation fails.
	Reject(err error)

	// Complete is called for an update with the result of executing the
	// update function. If the provided error is non-nil then the overall
	// outcome is understood to be a failure.
	Complete(success interface{}, err error)
}

UpdateCallbacks supplies callbacks for the different stages of processing a workflow update.

type UpdateHandlerOptions added in v1.20.0

type UpdateHandlerOptions struct {
	// Validator is an optional (i.e. can be left nil) func with exactly the
	// same type signature as the required update handler func but returning
	// only a single value of type error. The implementation of this
	// function MUST NOT alter workflow state in any way however it need not
	// be pure - it is permissible to observe workflow state without
	// mutating it as part of performing validation. The prohibition against
	// mutating workflow state includes normal variable mutation/assignment
	// as well as workflow actions such as scheduling activities and
	// performing side-effects. A panic from this function will be treated
	// as equivalent to returning an error.
	Validator interface{}
	// UnfinishedPolicy is the policy to apply when a workflow exits while
	// the update handler is still running.
	UnfinishedPolicy HandlerUnfinishedPolicy
	// Description is a short description for this update.
	//
	// NOTE: Experimental
	Description string
}

UpdateHandlerOptions consists of options for executing a named workflow update.

NOTE: Experimental

type UpdateInfo added in v1.24.0

type UpdateInfo struct {
	// ID of the update
	ID string
	// Name of the update
	Name string
}

UpdateInfo information about a currently running update

func GetCurrentUpdateInfo added in v1.27.0

func GetCurrentUpdateInfo(ctx Context) *UpdateInfo

GetUpdateInfo extracts info of a currently running update from a context.

type UpdateInput added in v1.16.0

type UpdateInput struct {
	Name string
	Args []interface{}
}

UpdateInput carries the name and arguments of a workflow update invocation.

type UpdateScheduler added in v1.21.0

type UpdateScheduler interface {
	// Spawn starts a new named coroutine, executing the given function f.
	Spawn(ctx Context, name string, highPriority bool, f func(ctx Context)) Context

	// Yield returns control to the scheduler.
	Yield(ctx Context, status string)
}

UpdateScheduler allows an update state machine to spawn coroutines and yield itself as necessary.

type UpdateWithStartWorkflowOperation added in v1.29.0

type UpdateWithStartWorkflowOperation struct {
	// contains filtered or unexported fields
}

UpdateWithStartWorkflowOperation is used to perform Update-with-Start. See NewUpdateWithStartWorkflowOperation for details.

func NewUpdateWithStartWorkflowOperation added in v1.29.0

func NewUpdateWithStartWorkflowOperation(options UpdateWorkflowOptions) *UpdateWithStartWorkflowOperation

NewUpdateWithStartWorkflowOperation returns an UpdateWithStartWorkflowOperation that can be used to perform Update-with-Start.

func (*UpdateWithStartWorkflowOperation) Get added in v1.29.0

Get blocks until a server response has been received; or the context deadline is exceeded.

type UpdateWorkerBuildIdCompatibilityOptions added in v1.22.0

type UpdateWorkerBuildIdCompatibilityOptions struct {
	// The task queue to update the version sets of.
	TaskQueue string
	Operation UpdateBuildIDOp
}

UpdateWorkerBuildIdCompatibilityOptions is the input to Client.UpdateWorkerBuildIdCompatibility.

type UpdateWorkerVersioningRulesOptions added in v1.27.0

type UpdateWorkerVersioningRulesOptions struct {
	// The task queue to update the versioning rules of.
	TaskQueue string
	// A conflict token to serialize updates.
	ConflictToken VersioningConflictToken
	Operation     VersioningOperation
}

UpdateWorkerVersioningRulesOptions is the input to [Client.UpdateWorkerVersioningRules]. WARNING: Worker versioning is currently experimental

type UpdateWorkflowOptions added in v1.27.0

type UpdateWorkflowOptions struct {
	// UpdateID is an application-layer identifier for the requested update. It
	// must be unique within the scope of a Namespace+WorkflowID+RunID.
	UpdateID string

	// WorkflowID is a required field indicating the workflow which should be
	// updated. However, it is optional when using UpdateWithStartWorkflowOperation.
	WorkflowID string

	// RunID is an optional field used to identify a specific run of the target
	// workflow.  If RunID is not provided the latest run will be used.
	// Note that it is incompatible with UpdateWithStartWorkflowOperation.
	RunID string

	// UpdateName is a required field which specifies the update you want to run.
	// See comments at workflow.SetUpdateHandler(ctx Context, updateName string, handler interface{}, opts UpdateHandlerOptions)
	// for more details on how to setup update handlers within the target workflow.
	UpdateName string

	// Args is an optional field used to identify the arguments passed to the
	// update.
	Args []interface{}

	// WaitForStage is a required field which specifies which stage to wait until returning.
	// See https://docs.temporal.io/workflows#update for more details.
	// NOTE: Specifying WorkflowUpdateStageAdmitted is not supported.
	WaitForStage WorkflowUpdateStage

	// FirstExecutionRunID specifies the RunID expected to identify the first
	// run in the workflow execution chain. If this expectation does not match
	// then the server will reject the update request with an error.
	// Note that it is incompatible with UpdateWithStartWorkflowOperation.
	FirstExecutionRunID string
}

UpdateWorkflowOptions is the request to UpdateWorkflow

type Version

type Version int

Version represents a change version. See GetVersion call.

const DefaultVersion Version = -1

DefaultVersion is a version returned by GetVersion for code that wasn't versioned before

func GetVersion

func GetVersion(ctx Context, changeID string, minSupported, maxSupported Version) Version

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 as well as the new one that is used when it is executed for the first time. GetVersion returns maxSupported version when is 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. For example initially workflow has the following code:

err = workflow.ExecuteActivity(ctx, foo).Get(ctx, nil)

it should be updated to

err = workflow.ExecuteActivity(ctx, bar).Get(ctx, nil)

The backwards compatible way to execute the update is

v :=  GetVersion(ctx, "fooChange", DefaultVersion, 0)
if v  == DefaultVersion {
    err = workflow.ExecuteActivity(ctx, foo).Get(ctx, nil)
} else {
    err = workflow.ExecuteActivity(ctx, bar).Get(ctx, nil)
}

Then bar has to be changed to baz:

v :=  GetVersion(ctx, "fooChange", DefaultVersion, 1)
if v  == DefaultVersion {
    err = workflow.ExecuteActivity(ctx, foo).Get(ctx, nil)
} else if v == 0 {
    err = workflow.ExecuteActivity(ctx, bar).Get(ctx, nil)
} else {
    err = workflow.ExecuteActivity(ctx, baz).Get(ctx, nil)
}

Later when there are no workflow executions running DefaultVersion the correspondent branch can be removed:

v :=  GetVersion(ctx, "fooChange", 0, 1)
if v == 0 {
    err = workflow.ExecuteActivity(ctx, bar).Get(ctx, nil)
} else {
    err = workflow.ExecuteActivity(ctx, baz).Get(ctx, nil)
}

It is recommended to keep the GetVersion() call even if single branch is left:

GetVersion(ctx, "fooChange", 1, 1)
err = workflow.ExecuteActivity(ctx, baz).Get(ctx, nil)

The reason to keep it is: 1) it ensures that if there is older version execution still running, it will fail here and not proceed; 2) if you ever need to make more changes for “fooChange”, for example change activity from baz to qux, you just need to update the maxVersion from 1 to 2.

Note that, you only need to preserve the first call to GetVersion() for each changeID. All subsequent call to GetVersion() with same changeID are safe to remove. However, if you really want to get rid of the first GetVersion() call as well, you can do so, but you need to make sure: 1) all older version executions are completed; 2) you can no longer use “fooChange” as changeID. If you ever need to make changes to that same part like change from baz to qux, you would need to use a different changeID like “fooChange-fix2”, and start minVersion from DefaultVersion again. The code would looks like:

v := workflow.GetVersion(ctx, "fooChange-fix2", workflow.DefaultVersion, 0)
if v == workflow.DefaultVersion {
  err = workflow.ExecuteActivity(ctx, baz, data).Get(ctx, nil)
} else {
  err = workflow.ExecuteActivity(ctx, qux, data).Get(ctx, nil)
}

type VersioningAssignmentRule added in v1.27.0

type VersioningAssignmentRule struct {
	// The BuildID of new workflows affected by this rule.
	TargetBuildID string
	// A strategy for gradual workflow deployment.
	Ramp VersioningRamp
}

VersioningAssignmentRule is a BuildID assigment rule for a task queue. Assignment rules only affect new workflows. WARNING: Worker versioning is currently experimental

type VersioningAssignmentRuleWithTimestamp added in v1.27.0

type VersioningAssignmentRuleWithTimestamp struct {
	Rule VersioningAssignmentRule
	// The time when the server created this rule.
	CreateTime time.Time
}

VersioningAssignmentRuleWithTimestamp contains an assignment rule annotated by the server with its creation time. WARNING: Worker versioning is currently experimental

type VersioningConflictToken added in v1.27.0

type VersioningConflictToken struct {
	// contains filtered or unexported fields
}

VersioningConflictToken is a conflict token to serialize updates. An update with an old token fails with `serviceerror.FailedPrecondition`. The current token can be obtained with [GetWorkerVersioningRules], or returned by a successful [UpdateWorkerVersioningRules]. WARNING: Worker versioning is currently experimental

func (*VersioningConflictToken) Token added in v1.27.0

func (c *VersioningConflictToken) Token() []byte

Token Returns an internal representation of this token, mostly for debugging purposes. WARNING: Worker versioning is currently experimental

type VersioningIntent added in v1.23.0

type VersioningIntent int

VersioningIntent indicates whether the user intends certain commands to be run on a compatible worker build ID version or not.

const (
	// VersioningIntentUnspecified indicates that the SDK should choose the most sensible default
	// behavior for the type of command, accounting for whether the command will be run on the same
	// task queue as the current worker.
	VersioningIntentUnspecified VersioningIntent = iota
	// VersioningIntentCompatible indicates that the command should run on a worker with compatible
	// version if possible. It may not be possible if the target task queue does not also have
	// knowledge of the current worker's build ID.
	//
	// Deprecated: This has the same effect as [VersioningIntentInheritBuildID], use that instead.
	VersioningIntentCompatible
	// VersioningIntentDefault indicates that the command should run on the target task queue's
	// current overall-default build ID.
	//
	// Deprecated: This has the same effect as [VersioningIntentUseAssignmentRules], use that instead.
	VersioningIntentDefault
	// VersioningIntentInheritBuildID indicates the command should inherit the current Build ID of the
	// Workflow triggering it, and not use Assignment Rules. (Redirect Rules are still applicable)
	// This is the default behavior for commands running on the same Task Queue as the current worker.
	VersioningIntentInheritBuildID
	// VersioningIntentUseAssignmentRules indicates the command should use the latest Assignment Rules
	// to select a Build ID independently of the workflow triggering it.
	// This is the default behavior for commands not running on the same Task Queue as the current worker.
	VersioningIntentUseAssignmentRules
)

type VersioningOperation added in v1.27.0

type VersioningOperation interface {
	// contains filtered or unexported methods
}

VersioningOperation is an interface for the different operations that can be performed when updating the worker versioning rules for a task queue.

Possible operations are:

type VersioningOperationAddRedirectRule added in v1.27.0

type VersioningOperationAddRedirectRule struct {
	Rule VersioningRedirectRule
}

VersioningOperationAddRedirectRule is an operation for UpdateWorkerVersioningRulesOptions that adds the rule to the list of redirect rules for this Task Queue. There can be at most one redirect rule for each distinct Source BuildID. WARNING: Worker versioning is currently experimental

type VersioningOperationCommitBuildID added in v1.27.0

type VersioningOperationCommitBuildID struct {
	TargetBuildID string
	Force         bool
}

VersioningOperationCommitBuildID is an operation for UpdateWorkerVersioningRulesOptions that completes the rollout of a BuildID and cleanup unnecessary rules possibly created during a gradual rollout. Specifically, this command will make the following changes atomically:

  1. Adds an assignment rule (with full ramp) for the target Build ID at the end of the list.
  2. Removes all previously added assignment rules to the given target Build ID (if any).
  3. Removes any fully-ramped assignment rule for other Build IDs.

To prevent committing invalid Build IDs, we reject the request if no pollers have been seen recently for this Build ID. Use the `force` option to disable this validation. WARNING: Worker versioning is currently experimental

type VersioningOperationDeleteAssignmentRule added in v1.27.0

type VersioningOperationDeleteAssignmentRule struct {
	RuleIndex int32
	Force     bool
}

VersioningOperationDeleteAssignmentRule is an operation for UpdateWorkerVersioningRulesOptions that deletes the assignment rule at a given index. By default presence of one unconditional rule, i.e., no hint filter or ramp, is enforced, otherwise the delete operation will be rejected. Set `force` to true to bypass this validation. WARNING: Worker versioning is currently experimental

type VersioningOperationDeleteRedirectRule added in v1.27.0

type VersioningOperationDeleteRedirectRule struct {
	SourceBuildID string
}

VersioningOperationDeleteRedirectRule is an operation for UpdateWorkerVersioningRulesOptions that deletes the routing rule with the given source Build ID. WARNING: Worker versioning is currently experimental

type VersioningOperationInsertAssignmentRule added in v1.27.0

type VersioningOperationInsertAssignmentRule struct {
	RuleIndex int32
	Rule      VersioningAssignmentRule
}

VersioningOperationInsertAssignmentRule is an operation for UpdateWorkerVersioningRulesOptions that inserts the rule to the list of assignment rules for this Task Queue. The rules are evaluated in order, starting from index 0. The first applicable rule will be applied and the rest will be ignored. By default, the new rule is inserted at the beginning of the list (index 0). If the given index is too larger the rule will be inserted at the end of the list. WARNING: Worker versioning is currently experimental

type VersioningOperationReplaceAssignmentRule added in v1.27.0

type VersioningOperationReplaceAssignmentRule struct {
	RuleIndex int32
	Rule      VersioningAssignmentRule
	Force     bool
}

VersioningOperationReplaceAssignmentRule is an operation for UpdateWorkerVersioningRulesOptions that replaces the assignment rule at a given index. By default presence of one unconditional rule, i.e., no hint filter or ramp, is enforced, otherwise the delete operation will be rejected. Set `force` to true to bypass this validation. WARNING: Worker versioning is currently experimental

type VersioningOperationReplaceRedirectRule added in v1.27.0

type VersioningOperationReplaceRedirectRule struct {
	Rule VersioningRedirectRule
}

VersioningOperationReplaceRedirectRule is an operation for UpdateWorkerVersioningRulesOptions that replaces the routing rule with the given source BuildID. WARNING: Worker versioning is currently experimental

type VersioningRamp added in v1.27.0

type VersioningRamp interface {
	// contains filtered or unexported methods
}

VersioningRamp is an interface for the different strategies of gradual workflow deployments.

type VersioningRampByPercentage added in v1.27.0

type VersioningRampByPercentage struct {
	// Percentage of traffic with a value in [0,100)
	Percentage float32
}

VersioningRampByPercentage sends a proportion of the traffic to the target Build ID. WARNING: Worker versioning is currently experimental

type VersioningRedirectRule added in v1.27.0

type VersioningRedirectRule struct {
	SourceBuildID string
	TargetBuildID string
}

VersioningAssignmentRule is a BuildID redirect rule for a task queue. It changes the behavior of currently running workflows and new ones. WARNING: Worker versioning is currently experimental

type VersioningRedirectRuleWithTimestamp added in v1.27.0

type VersioningRedirectRuleWithTimestamp struct {
	Rule VersioningRedirectRule
	// The time when the server created this rule.
	CreateTime time.Time
}

VersioningRedirectRuleWithTimestamp contains a redirect rule annotated by the server with its creation time. WARNING: Worker versioning is currently experimental

type WaitGroup

type WaitGroup interface {
	Add(delta int)
	Done()
	Wait(ctx Context)
}

WaitGroup must be used instead of native go sync.WaitGroup by workflow code. Use workflow.NewWaitGroup(ctx) method to create a new WaitGroup instance

func NewWaitGroup

func NewWaitGroup(ctx Context) WaitGroup

NewWaitGroup creates a new WaitGroup instance.

type WithStartWorkflowOperation added in v1.29.0

type WithStartWorkflowOperation interface {
	// contains filtered or unexported methods
}

WithStartWorkflowOperation is a type of operation that can be executed as part of a workflow start.

type WorkerBuildIDVersionSets added in v1.22.0

type WorkerBuildIDVersionSets struct {
	Sets []*CompatibleVersionSet
}

WorkerBuildIDVersionSets is the response for Client.GetWorkerBuildIdCompatibility and represents the sets of worker build id based versions.

func (*WorkerBuildIDVersionSets) Default added in v1.22.0

func (s *WorkerBuildIDVersionSets) Default() string

Default returns the current overall default version. IE: The one that will be used to start new workflows. Returns the empty string if there are no versions present.

type WorkerCache added in v1.3.0

type WorkerCache struct {
	// contains filtered or unexported fields
}

A WorkerCache instance is held by each worker to hold cached data. The contents of this struct should always be pointers for any data shared with other workers, and owned values for any instance-specific caches.

func NewWorkerCache added in v1.3.0

func NewWorkerCache() *WorkerCache

NewWorkerCache Creates a new WorkerCache, and increases workerRefcount by one. Instances of WorkerCache decrement the refcounter as a hook to runtime.SetFinalizer (ie: When they are freed by the GC). When there are no reachable instances of WorkerCache, shared caches will be cleared

func (*WorkerCache) MaxWorkflowCacheSize added in v1.3.0

func (wc *WorkerCache) MaxWorkflowCacheSize() int

MaxWorkflowCacheSize returns the maximum allowed size of the sticky cache

type WorkerInterceptor added in v1.12.0

type WorkerInterceptor interface {
	// InterceptActivity is called before each activity interception needed with
	// the next interceptor in the chain.
	InterceptActivity(ctx context.Context, next ActivityInboundInterceptor) ActivityInboundInterceptor

	// InterceptWorkflow is called before each workflow interception needed with
	// the next interceptor in the chain.
	InterceptWorkflow(ctx Context, next WorkflowInboundInterceptor) WorkflowInboundInterceptor
	// contains filtered or unexported methods
}

WorkerInterceptor is a common interface for all interceptors. See documentation in the interceptor package for more details.

type WorkerInterceptorBase added in v1.12.0

type WorkerInterceptorBase struct{}

WorkerInterceptorBase is a default implementation of WorkerInterceptor meant for embedding. See documentation in the interceptor package for more details.

func (*WorkerInterceptorBase) InterceptActivity added in v1.12.0

InterceptActivity implements WorkerInterceptor.InterceptActivity.

func (*WorkerInterceptorBase) InterceptWorkflow added in v1.12.0

InterceptWorkflow implements WorkerInterceptor.InterceptWorkflow.

type WorkerOptions

type WorkerOptions struct {
	// Optional: To set the maximum concurrent activity executions this worker can have.
	// The zero value of this uses the default value.
	// default: defaultMaxConcurrentActivityExecutionSize(1k)
	MaxConcurrentActivityExecutionSize int

	// Optional: Sets the rate limiting on number of activities that can be executed per second per
	// worker. This can be used to limit resources used by the worker.
	// Notice that the number is represented in float, so that you can set it to less than
	// 1 if needed. For example, set the number to 0.1 means you want your activity to be executed
	// once for every 10 seconds. This can be used to protect down stream services from flooding.
	// The zero value of this uses the default value
	// default: 100k
	WorkerActivitiesPerSecond float64

	// Optional: To set the maximum concurrent local activity executions this worker can have.
	// The zero value of this uses the default value.
	// default: 1k
	MaxConcurrentLocalActivityExecutionSize int

	// Optional: Sets the rate limiting on number of local activities that can be executed per second per
	// worker. This can be used to limit resources used by the worker.
	// Notice that the number is represented in float, so that you can set it to less than
	// 1 if needed. For example, set the number to 0.1 means you want your local activity to be executed
	// once for every 10 seconds. This can be used to protect down stream services from flooding.
	// The zero value of this uses the default value
	// default: 100k
	WorkerLocalActivitiesPerSecond float64

	// Optional: Sets the rate limiting on number of activities that can be executed per second.
	// This is managed by the server and controls activities per second for your entire taskqueue
	// whereas WorkerActivityTasksPerSecond controls activities only per worker.
	// Notice that the number is represented in float, so that you can set it to less than
	// 1 if needed. For example, set the number to 0.1 means you want your activity to be executed
	// once for every 10 seconds. This can be used to protect down stream services from flooding.
	// The zero value of this uses the default value.
	// default: 100k
	//
	// Note: Setting this to a non zero value will also disable eager activities.
	TaskQueueActivitiesPerSecond float64

	// Optional: Sets the maximum number of goroutines that will concurrently poll the
	// temporal-server to retrieve activity tasks. Changing this value will affect the
	// rate at which the worker is able to consume tasks from a task queue.
	// default: 2
	MaxConcurrentActivityTaskPollers int

	// Optional: To set the maximum concurrent workflow task executions this worker can have.
	// The zero value of this uses the default value. Due to internal logic where pollers
	// alternate between stick and non-sticky queues, this
	// value cannot be 1 and will panic if set to that value.
	// default: defaultMaxConcurrentTaskExecutionSize(1k)
	MaxConcurrentWorkflowTaskExecutionSize int

	// Optional: Sets the maximum number of goroutines that will concurrently poll the
	// temporal-server to retrieve workflow tasks. Changing this value will affect the
	// rate at which the worker is able to consume tasks from a task queue. Due to
	// internal logic where pollers alternate between stick and non-sticky queues, this
	// value cannot be 1 and will panic if set to that value.
	// default: 2
	MaxConcurrentWorkflowTaskPollers int

	// Optional: Sets the maximum concurrent nexus task executions this worker can have.
	// The zero value of this uses the default value.
	// default: defaultMaxConcurrentTaskExecutionSize(1k)
	MaxConcurrentNexusTaskExecutionSize int

	// Optional: Sets the maximum number of goroutines that will concurrently poll the
	// temporal-server to retrieve nexus tasks. Changing this value will affect the
	// rate at which the worker is able to consume tasks from a task queue.
	// default: 2
	MaxConcurrentNexusTaskPollers int

	// Optional: Enable logging in replay.
	// In the workflow code you can use workflow.GetLogger(ctx) to write logs. By default, the logger will skip log
	// entry during replay mode so you won't see duplicate logs. This option will enable the logging in replay mode.
	// This is only useful for debugging purpose.
	// default: false
	EnableLoggingInReplay bool

	// Optional: Sticky schedule to start timeout.
	// The resolution is seconds.
	//
	// Sticky Execution is to run the workflow tasks for one workflow execution on same worker host. This is an
	// optimization for workflow execution. When sticky execution is enabled, worker keeps the workflow state in
	// memory. New workflow task contains the new history events will be dispatched to the same worker. If this
	// worker crashes, the sticky workflow task will timeout after StickyScheduleToStartTimeout, and temporal server
	// will clear the stickiness for that workflow execution and automatically reschedule a new workflow task that
	// is available for any worker to pick up and resume the progress.
	//
	// default: 5s
	StickyScheduleToStartTimeout time.Duration

	// Optional: sets root context for all activities. The context can be used to pass external dependencies
	// like DB connections to activity functions.
	// Note that this method of passing dependencies is not recommended anymore.
	// Instead, use a structure with fields that contain dependencies and activities
	// as the structure member functions. Then pass all the dependencies on the structure initialization.
	BackgroundActivityContext context.Context

	// Optional: Sets how workflow worker deals with non-deterministic history events
	// (presumably arising from non-deterministic workflow definitions or non-backward compatible workflow
	// definition changes) and other panics raised from workflow code.
	// default: BlockWorkflow, which just logs error but doesn't fail workflow.
	WorkflowPanicPolicy WorkflowPanicPolicy

	// Optional: worker graceful stop timeout
	// default: 0s
	WorkerStopTimeout time.Duration

	// Optional: Enable running session workers.
	// Session workers is for activities within a session.
	// Enable this option to allow worker to process sessions.
	// default: false
	EnableSessionWorker bool

	// Optional: Sets the maximum number of concurrently running sessions the resource supports.
	// default: 1000
	MaxConcurrentSessionExecutionSize int

	// Optional: If set to true, a workflow worker is not started for this
	// worker and workflows cannot be registered with this worker. Use this if
	// you only want your worker to execute activities.
	// default: false
	DisableWorkflowWorker bool

	// Optional: If set to true worker will only handle workflow tasks and local activities.
	// Non-local activities will not be executed by this worker.
	// default: false
	LocalActivityWorkerOnly bool

	// Optional: If set overwrites the client level Identity value.
	// default: client identity
	Identity string

	// Optional: If set defines maximum amount of time that workflow task will be allowed to run. Defaults to 1 sec.
	DeadlockDetectionTimeout time.Duration

	// Optional: The maximum amount of time between sending each pending heartbeat to the server. Regardless of
	// heartbeat timeout, no pending heartbeat will wait longer than this amount of time to send. To effectively disable
	// heartbeat throttling, this can be set to something like 1 nanosecond, but it is not recommended.
	// default: 60 seconds
	MaxHeartbeatThrottleInterval time.Duration

	// Optional: The default amount of time between sending each pending heartbeat to the server. This is used if the
	// ActivityOptions do not provide a HeartbeatTimeout. Otherwise, the interval becomes a value a bit smaller than the
	// given HeartbeatTimeout.
	// default: 30 seconds
	DefaultHeartbeatThrottleInterval time.Duration

	// Interceptors to apply to the worker. Earlier interceptors wrap later
	// interceptors.
	//
	// When worker interceptors are here and in client options, the ones in
	// client options wrap the ones here. The same interceptor should not be set
	// here and in client options.
	Interceptors []WorkerInterceptor

	// Optional: Callback invoked on fatal error. Immediately after this
	// returns, Worker.Stop() will be called.
	OnFatalError func(error)

	// Optional: Disable eager activities. If set to true, activities will not
	// be requested to execute eagerly from the same workflow regardless of
	// MaxConcurrentEagerActivityExecutionSize.
	//
	// Eager activity execution means the server returns requested eager
	// activities directly from the workflow task back to this worker which is
	// faster than non-eager which may be dispatched to a separate worker.
	//
	// Note: Eager activities will automatically be disabled if TaskQueueActivitiesPerSecond is set.
	DisableEagerActivities bool

	// Optional: Maximum number of eager activities that can be running.
	//
	// When non-zero, eager activity execution will not be requested for
	// activities schedule by the workflow if it would cause the total number of
	// running eager activities to exceed this value. For example, if this is
	// set to 1000 and there are already 998 eager activities executing and a
	// workflow task schedules 3 more, only the first 2 will request eager
	// execution.
	//
	// The default of 0 means unlimited and therefore only bound by
	// MaxConcurrentActivityExecutionSize.
	//
	// See DisableEagerActivities for a description of eager activity execution.
	MaxConcurrentEagerActivityExecutionSize int

	// Optional: Disable allowing workflow and activity functions that are
	// registered with custom names from being able to be called with their
	// function references.
	//
	// Users are strongly recommended to set this as true if they register any
	// workflow or activity functions with custom names. By leaving this as
	// false, the historical default, ambiguity can occur between function names
	// and aliased names when not using string names when executing child
	// workflow or activities.
	DisableRegistrationAliasing bool

	// Assign a BuildID to this worker. This replaces the deprecated binary checksum concept,
	// and is used to provide a unique identifier for a set of worker code, and is necessary
	// to opt in to the Worker Versioning feature. See UseBuildIDForVersioning.
	// NOTE: Experimental
	BuildID string

	// Optional: If set, opts this worker into the Worker Versioning feature. It will only
	// operate on workflows it claims to be compatible with. You must set BuildID if this flag
	// is true.
	// NOTE: Experimental
	// Note: Cannot be enabled at the same time as EnableSessionWorker
	UseBuildIDForVersioning bool

	// Optional: If set, use a custom tuner for this worker. See WorkerTuner for more.
	// Mutually exclusive with MaxConcurrentWorkflowTaskExecutionSize,
	// MaxConcurrentActivityExecutionSize, and MaxConcurrentLocalActivityExecutionSize.
	// NOTE: Experimental
	Tuner WorkerTuner
}

WorkerOptions is used to configure a worker instance. The current timeout resolution implementation is in seconds and uses math.Ceil(d.Seconds()) as the duration. But is subjected to change in the future.

type WorkerTaskReachability added in v1.25.0

type WorkerTaskReachability struct {
	// BuildIDReachability - map of build IDs and their reachability information
	// May contain an entry with UnversionedBuildID for an unversioned worker
	BuildIDReachability map[string]*BuildIDReachability
}

type WorkerTuner added in v1.29.0

type WorkerTuner interface {
	// GetWorkflowTaskSlotSupplier returns the SlotSupplier used for workflow tasks.
	GetWorkflowTaskSlotSupplier() SlotSupplier
	// GetActivityTaskSlotSupplier returns the SlotSupplier used for activity tasks.
	GetActivityTaskSlotSupplier() SlotSupplier
	// GetLocalActivitySlotSupplier returns the SlotSupplier used for local activities.
	GetLocalActivitySlotSupplier() SlotSupplier
	// GetNexusSlotSupplier returns the SlotSupplier used for nexus tasks.
	GetNexusSlotSupplier() SlotSupplier
}

WorkerTuner allows for the dynamic customization of some aspects of worker behavior.

WARNING: Custom implementations of SlotSupplier are currently experimental.

func NewCompositeTuner added in v1.29.0

func NewCompositeTuner(options CompositeTunerOptions) (WorkerTuner, error)

NewCompositeTuner creates a WorkerTuner that uses a combination of slot suppliers.

WARNING: Custom implementations of SlotSupplier are currently experimental.

func NewFixedSizeTuner added in v1.29.0

func NewFixedSizeTuner(options FixedSizeTunerOptions) (WorkerTuner, error)

NewFixedSizeTuner creates a WorkerTuner that uses fixed size slot suppliers.

type WorkerVersionCapabilities added in v1.27.0

type WorkerVersionCapabilities struct {
	// Build ID of the worker.
	BuildID string
	// Whether the worker is using the versioning feature.
	UseVersioning bool
}

WorkerVersionCapabilities includes a worker's build identifier and whether it is choosing to use the versioning feature. It is an optional component of TaskQueuePollerInfo.

type WorkerVersioningRules added in v1.27.0

type WorkerVersioningRules struct {
	AssignmentRules []*VersioningAssignmentRuleWithTimestamp
	RedirectRules   []*VersioningRedirectRuleWithTimestamp
	ConflictToken   VersioningConflictToken
}

WorkerVersioningRules is the response for [Client.GetWorkerVersioningRules]. WARNING: Worker versioning is currently experimental

type WorkflowClient

type WorkflowClient struct {
	// contains filtered or unexported fields
}

WorkflowClient is the client for starting a workflow execution.

func NewServiceClient

func NewServiceClient(workflowServiceClient workflowservice.WorkflowServiceClient, conn *grpc.ClientConn, options ClientOptions) *WorkflowClient

NewServiceClient creates workflow client from workflowservice.WorkflowServiceClient. Must be used internally in unit tests only.

func (*WorkflowClient) CancelWorkflow

func (wc *WorkflowClient) CancelWorkflow(ctx context.Context, workflowID string, runID string) error

CancelWorkflow cancels a workflow in execution. It allows workflow to properly clean up and gracefully close. workflowID is required, other parameters are optional. If runID is omit, it will terminate currently running workflow (if there is one) based on the workflowID.

func (*WorkflowClient) CheckHealth added in v1.15.0

func (wc *WorkflowClient) CheckHealth(ctx context.Context, request *CheckHealthRequest) (*CheckHealthResponse, error)

CheckHealth performs a server health check using the gRPC health check API. If the check fails, an error is returned.

func (*WorkflowClient) Close

func (wc *WorkflowClient) Close()

Close client and clean up underlying resources.

func (*WorkflowClient) CompleteActivity

func (wc *WorkflowClient) CompleteActivity(ctx context.Context, taskToken []byte, result interface{}, err error) error

CompleteActivity reports activity completed. activity Execute method can return activity.ErrResultPending to indicate the activity is not completed when it's Execute method returns. In that case, this CompleteActivity() method should be called when that activity is completed with the actual result and error. If err is nil, activity task completed event will be reported; if err is CanceledError, activity task canceled event will be reported; otherwise, activity task failed event will be reported.

func (*WorkflowClient) CompleteActivityByID

func (wc *WorkflowClient) CompleteActivityByID(ctx context.Context, namespace, workflowID, runID, activityID string,
	result interface{}, err error,
) error

CompleteActivityByID reports activity completed. Similar to CompleteActivity It takes namespace name, workflowID, runID, activityID as arguments.

func (*WorkflowClient) CountWorkflow

func (wc *WorkflowClient) CountWorkflow(ctx context.Context, request *workflowservice.CountWorkflowExecutionsRequest) (*workflowservice.CountWorkflowExecutionsResponse, error)

CountWorkflow implementation

func (*WorkflowClient) DescribeTaskQueue

func (wc *WorkflowClient) DescribeTaskQueue(ctx context.Context, taskQueue string, taskQueueType enumspb.TaskQueueType) (*workflowservice.DescribeTaskQueueResponse, error)

DescribeTaskQueue returns information about the target taskqueue, right now this API returns the pollers which polled this taskqueue in last few minutes. - taskqueue name of taskqueue - taskqueueType type of taskqueue, can be workflow or activity The errors it can return:

  • serviceerror.InvalidArgument
  • serviceerror.Internal
  • serviceerror.Unavailable
  • serviceerror.NotFound

func (*WorkflowClient) DescribeTaskQueueEnhanced added in v1.27.0

func (wc *WorkflowClient) DescribeTaskQueueEnhanced(ctx context.Context, options DescribeTaskQueueEnhancedOptions) (TaskQueueDescription, error)

DescribeTaskQueueEnhanced returns information about the target task queue, broken down by Build Id:

  • List of pollers
  • Workflow Reachability status
  • Backlog info for Workflow and/or Activity tasks

WARNING: Worker versioning is currently experimental, and requires server 1.24+

func (*WorkflowClient) DescribeWorkflowExecution

func (wc *WorkflowClient) DescribeWorkflowExecution(ctx context.Context, workflowID, runID string) (*workflowservice.DescribeWorkflowExecutionResponse, error)

DescribeWorkflowExecution returns information about the specified workflow execution. The errors it can return:

  • serviceerror.InvalidArgument
  • serviceerror.Internal
  • serviceerror.Unavailable
  • serviceerror.NotFound

func (*WorkflowClient) ExecuteWorkflow

func (wc *WorkflowClient) ExecuteWorkflow(ctx context.Context, options StartWorkflowOptions, workflow interface{}, args ...interface{}) (WorkflowRun, error)

ExecuteWorkflow starts a workflow execution and returns a WorkflowRun that will allow you to wait until this workflow reaches the end state, such as workflow finished successfully or timeout. The user can use this to start using a functor like below and get the workflow execution result, as EncodedValue Either by

ExecuteWorkflow(options, "workflowTypeName", arg1, arg2, arg3)
or
ExecuteWorkflow(options, workflowExecuteFn, arg1, arg2, arg3)

The current timeout resolution implementation is in seconds and uses math.Ceil(d.Seconds()) as the duration. But is subjected to change in the future. NOTE: the context.Context should have a fairly large timeout, since workflow execution may take a while to be finished

func (*WorkflowClient) GetSearchAttributes

func (wc *WorkflowClient) GetSearchAttributes(ctx context.Context) (*workflowservice.GetSearchAttributesResponse, error)

GetSearchAttributes implementation

func (*WorkflowClient) GetWorkerBuildIdCompatibility added in v1.22.0

func (wc *WorkflowClient) GetWorkerBuildIdCompatibility(ctx context.Context, options *GetWorkerBuildIdCompatibilityOptions) (*WorkerBuildIDVersionSets, error)

GetWorkerBuildIdCompatibility returns the worker-build-id based version sets for a particular task queue.

func (*WorkflowClient) GetWorkerTaskReachability added in v1.25.0

func (wc *WorkflowClient) GetWorkerTaskReachability(ctx context.Context, options *GetWorkerTaskReachabilityOptions) (*WorkerTaskReachability, error)

GetWorkerTaskReachability returns which versions are is still in use by open or closed workflows.

func (*WorkflowClient) GetWorkerVersioningRules added in v1.27.0

func (wc *WorkflowClient) GetWorkerVersioningRules(ctx context.Context, options GetWorkerVersioningOptions) (*WorkerVersioningRules, error)

GetWorkerVersioningRules returns the worker-build-id assignment and redirect rules for a task queue.

func (*WorkflowClient) GetWorkflow

func (wc *WorkflowClient) GetWorkflow(ctx context.Context, workflowID string, runID string) WorkflowRun

GetWorkflow gets a workflow execution and returns a WorkflowRun that will allow you to wait until this workflow reaches the end state, such as workflow finished successfully or timeout. The current timeout resolution implementation is in seconds and uses math.Ceil(d.Seconds()) as the duration. But is subjected to change in the future.

func (*WorkflowClient) GetWorkflowHistory

func (wc *WorkflowClient) GetWorkflowHistory(
	ctx context.Context,
	workflowID string,
	runID string,
	isLongPoll bool,
	filterType enumspb.HistoryEventFilterType,
) HistoryEventIterator

GetWorkflowHistory return a channel which contains the history events of a given workflow

func (*WorkflowClient) GetWorkflowUpdateHandle added in v1.22.2

func (wc *WorkflowClient) GetWorkflowUpdateHandle(ref GetWorkflowUpdateHandleOptions) WorkflowUpdateHandle

func (*WorkflowClient) ListArchivedWorkflow

func (wc *WorkflowClient) ListArchivedWorkflow(ctx context.Context, request *workflowservice.ListArchivedWorkflowExecutionsRequest) (*workflowservice.ListArchivedWorkflowExecutionsResponse, error)

ListArchivedWorkflow implementation

func (*WorkflowClient) ListClosedWorkflow

func (wc *WorkflowClient) ListClosedWorkflow(ctx context.Context, request *workflowservice.ListClosedWorkflowExecutionsRequest) (*workflowservice.ListClosedWorkflowExecutionsResponse, error)

ListClosedWorkflow gets closed workflow executions based on request filters The errors it can throw:

  • serviceerror.InvalidArgument
  • serviceerror.Internal
  • serviceerror.Unavailable
  • serviceerror.NamespaceNotFound

func (*WorkflowClient) ListOpenWorkflow

func (wc *WorkflowClient) ListOpenWorkflow(ctx context.Context, request *workflowservice.ListOpenWorkflowExecutionsRequest) (*workflowservice.ListOpenWorkflowExecutionsResponse, error)

ListOpenWorkflow gets open workflow executions based on request filters The errors it can throw:

  • serviceerror.InvalidArgument
  • serviceerror.Internal
  • serviceerror.Unavailable
  • serviceerror.NamespaceNotFound

func (*WorkflowClient) ListWorkflow

func (wc *WorkflowClient) ListWorkflow(ctx context.Context, request *workflowservice.ListWorkflowExecutionsRequest) (*workflowservice.ListWorkflowExecutionsResponse, error)

ListWorkflow implementation

func (*WorkflowClient) OperatorService added in v1.17.0

func (wc *WorkflowClient) OperatorService() operatorservice.OperatorServiceClient

OperatorService implements Client.OperatorService.

func (*WorkflowClient) PollWorkflowUpdate added in v1.22.2

func (wc *WorkflowClient) PollWorkflowUpdate(
	ctx context.Context,
	ref *updatepb.UpdateRef,
) (*ClientPollWorkflowUpdateOutput, error)

PollWorkflowUpdate sends a request for the outcome of the specified update through the interceptor chain.

func (*WorkflowClient) QueryWorkflow

func (wc *WorkflowClient) QueryWorkflow(ctx context.Context, workflowID string, runID string, queryType string, args ...interface{}) (converter.EncodedValue, error)

QueryWorkflow queries a given workflow execution workflowID and queryType are required, other parameters are optional. - workflow ID of the workflow. - runID can be default(empty string). if empty string then it will pick the running execution of that workflow ID. - taskQueue can be default(empty string). If empty string then it will pick the taskQueue of the running execution of that workflow ID. - queryType is the type of the query. - args... are the optional query parameters. The errors it can return:

  • serviceerror.InvalidArgument
  • serviceerror.Internal
  • serviceerror.Unavailable
  • serviceerror.NotFound
  • serviceerror.QueryFailed

func (*WorkflowClient) QueryWorkflowWithOptions

QueryWorkflowWithOptions queries a given workflow execution and returns the query result synchronously. See QueryWorkflowWithOptionsRequest and QueryWorkflowWithOptionsResult for more information. The errors it can return:

  • serviceerror.InvalidArgument
  • serviceerror.Internal
  • serviceerror.Unavailable
  • serviceerror.NotFound
  • serviceerror.QueryFailed

func (*WorkflowClient) RecordActivityHeartbeat

func (wc *WorkflowClient) RecordActivityHeartbeat(ctx context.Context, taskToken []byte, details ...interface{}) error

RecordActivityHeartbeat records heartbeat for an activity.

func (*WorkflowClient) RecordActivityHeartbeatByID

func (wc *WorkflowClient) RecordActivityHeartbeatByID(ctx context.Context,
	namespace, workflowID, runID, activityID string, details ...interface{},
) error

RecordActivityHeartbeatByID records heartbeat for an activity.

func (*WorkflowClient) ResetWorkflowExecution added in v1.6.0

func (wc *WorkflowClient) ResetWorkflowExecution(ctx context.Context, request *workflowservice.ResetWorkflowExecutionRequest) (*workflowservice.ResetWorkflowExecutionResponse, error)

ResetWorkflowExecution reset an existing workflow execution to WorkflowTaskFinishEventId(exclusive). And it will immediately terminating the current execution instance. RequestId is used to deduplicate requests. It will be autogenerated if not set.

func (*WorkflowClient) ScanWorkflow

func (wc *WorkflowClient) ScanWorkflow(ctx context.Context, request *workflowservice.ScanWorkflowExecutionsRequest) (*workflowservice.ScanWorkflowExecutionsResponse, error)

ScanWorkflow implementation

func (*WorkflowClient) ScheduleClient added in v1.18.0

func (wc *WorkflowClient) ScheduleClient() ScheduleClient

ScheduleClient implements Client.ScheduleClient.

func (*WorkflowClient) SignalWithStartWorkflow

func (wc *WorkflowClient) SignalWithStartWorkflow(ctx context.Context, workflowID string, signalName string, signalArg interface{},
	options StartWorkflowOptions, workflowFunc interface{}, workflowArgs ...interface{},
) (WorkflowRun, error)

SignalWithStartWorkflow sends a signal to a running workflow. If the workflow is not running or not found, it starts the workflow and then sends the signal in transaction.

func (*WorkflowClient) SignalWorkflow

func (wc *WorkflowClient) SignalWorkflow(ctx context.Context, workflowID string, runID string, signalName string, arg interface{}) error

SignalWorkflow signals a workflow in execution.

func (*WorkflowClient) TerminateWorkflow

func (wc *WorkflowClient) TerminateWorkflow(ctx context.Context, workflowID string, runID string, reason string, details ...interface{}) error

TerminateWorkflow terminates a workflow execution. workflowID is required, other parameters are optional. If runID is omit, it will terminate currently running workflow (if there is one) based on the workflowID.

func (*WorkflowClient) UpdateWorkerBuildIdCompatibility added in v1.22.0

func (wc *WorkflowClient) UpdateWorkerBuildIdCompatibility(ctx context.Context, options *UpdateWorkerBuildIdCompatibilityOptions) error

UpdateWorkerBuildIdCompatibility allows you to update the worker-build-id based version sets for a particular task queue. This is used in conjunction with workers who specify their build id and thus opt into the feature.

func (*WorkflowClient) UpdateWorkerVersioningRules added in v1.27.0

func (wc *WorkflowClient) UpdateWorkerVersioningRules(ctx context.Context, options UpdateWorkerVersioningRulesOptions) (*WorkerVersioningRules, error)

UpdateWorkerVersioningRules allows updating the worker-build-id based assignment and redirect rules for a given task queue. This is used in conjunction with workers who specify their build id and thus opt into the feature. The errors it can return:

  • serviceerror.FailedPrecondition when the conflict token is invalid

func (*WorkflowClient) UpdateWorkflow added in v1.20.0

func (wc *WorkflowClient) UpdateWorkflow(
	ctx context.Context,
	options UpdateWorkflowOptions,
) (WorkflowUpdateHandle, error)

func (*WorkflowClient) WorkflowService added in v1.12.0

func (wc *WorkflowClient) WorkflowService() workflowservice.WorkflowServiceClient

WorkflowService implements Client.WorkflowService.

type WorkflowContextManager added in v1.24.0

type WorkflowContextManager interface {
	// GetOrCreateWorkflowContext finds an existing cached context object
	// for the provided task's run ID or creates a new object, adds it to
	// cache, and returns it. In all non-error cases the returned context
	// object is in a locked state (i.e.
	// workflowExecutionContextImpl.Lock() has been called).
	GetOrCreateWorkflowContext(
		task *workflowservice.PollWorkflowTaskQueueResponse,
		historyIterator HistoryIterator,
	) (*workflowExecutionContextImpl, error)
}

type WorkflowDefinition

type WorkflowDefinition interface {
	// Execute implementation must be asynchronous.
	Execute(env WorkflowEnvironment, header *commonpb.Header, input *commonpb.Payloads)
	// OnWorkflowTaskStarted is called for each non timed out startWorkflowTask event.
	// Executed after all history events since the previous commands are applied to WorkflowDefinition
	// Application level code must be executed from this function only.
	// Execute call as well as callbacks called from WorkflowEnvironment functions can only schedule callbacks
	// which can be executed from OnWorkflowTaskStarted().
	OnWorkflowTaskStarted(deadlockDetectionTimeout time.Duration)
	// StackTrace of all coroutines owned by the Dispatcher instance.
	StackTrace() string
	// Close destroys all coroutines without waiting for their completion
	Close()
}

WorkflowDefinition wraps the code that can execute a workflow.

type WorkflowDefinitionFactory

type WorkflowDefinitionFactory interface {
	// NewWorkflowDefinition must return a new instance of WorkflowDefinition on each call.
	NewWorkflowDefinition() WorkflowDefinition
}

WorkflowDefinitionFactory factory for creating WorkflowDefinition instances.

type WorkflowEnvironment

type WorkflowEnvironment interface {
	AsyncActivityClient
	LocalActivityClient
	WorkflowTimerClient
	SideEffect(f func() (*commonpb.Payloads, error), callback ResultHandler)
	GetVersion(changeID string, minSupported, maxSupported Version) Version
	WorkflowInfo() *WorkflowInfo
	TypedSearchAttributes() SearchAttributes
	Complete(result *commonpb.Payloads, err error)
	RegisterCancelHandler(handler func())
	RequestCancelChildWorkflow(namespace, workflowID string)
	RequestCancelExternalWorkflow(namespace, workflowID, runID string, callback ResultHandler)
	ExecuteChildWorkflow(params ExecuteWorkflowParams, callback ResultHandler, startedHandler func(r WorkflowExecution, e error))
	ExecuteNexusOperation(params executeNexusOperationParams, callback func(*commonpb.Payload, error), startedHandler func(opID string, e error)) int64
	RequestCancelNexusOperation(seq int64)
	GetLogger() log.Logger
	GetMetricsHandler() metrics.Handler
	// Must be called before WorkflowDefinition.Execute returns
	RegisterSignalHandler(
		handler func(name string, input *commonpb.Payloads, header *commonpb.Header) error,
	)
	SignalExternalWorkflow(
		namespace string,
		workflowID string,
		runID string,
		signalName string,
		input *commonpb.Payloads,
		arg interface{},
		header *commonpb.Header,
		childWorkflowOnly bool,
		callback ResultHandler,
	)
	RegisterQueryHandler(
		handler func(queryType string, queryArgs *commonpb.Payloads, header *commonpb.Header) (*commonpb.Payloads, error),
	)
	RegisterUpdateHandler(
		handler func(string, string, *commonpb.Payloads, *commonpb.Header, UpdateCallbacks),
	)
	IsReplaying() bool
	MutableSideEffect(id string, f func() interface{}, equals func(a, b interface{}) bool) converter.EncodedValue
	GetDataConverter() converter.DataConverter
	GetFailureConverter() converter.FailureConverter
	AddSession(sessionInfo *SessionInfo)
	RemoveSession(sessionID string)
	GetContextPropagators() []ContextPropagator
	UpsertSearchAttributes(attributes map[string]interface{}) error
	UpsertTypedSearchAttributes(attributes SearchAttributes) error
	UpsertMemo(memoMap map[string]interface{}) error
	GetRegistry() *registry
	// QueueUpdate request of type name
	QueueUpdate(name string, f func())
	// HandleQueuedUpdates unblocks all queued updates of type name
	HandleQueuedUpdates(name string)
	// DrainUnhandledUpdates unblocks all updates, meant to be used to drain
	// all unhandled updates at the end of a workflow task
	// returns true if any update was unblocked
	DrainUnhandledUpdates() bool
	// TryUse returns true if this flag may currently be used.
	TryUse(flag sdkFlag) bool
}

WorkflowEnvironment Represents the environment for workflow. Should only be used within the scope of workflow definition.

type WorkflowExecution

type WorkflowExecution struct {
	ID    string
	RunID string
}

WorkflowExecution details.

type WorkflowExecutionContext

type WorkflowExecutionContext interface {
	Lock()
	Unlock(err error)
	ProcessWorkflowTask(workflowTask *workflowTask) (completeRequest interface{}, err error)
	ProcessLocalActivityResult(workflowTask *workflowTask, lar *localActivityResult) (interface{}, error)
	// CompleteWorkflowTask try to complete current workflow task and get response that needs to be sent back to server.
	// The waitLocalActivity is used to control if we should wait for outstanding local activities.
	// If there is no outstanding local activities or if waitLocalActivity is false, the complete will return response
	// which will be one of following:
	// - RespondWorkflowTaskCompletedRequest
	// - RespondWorkflowTaskFailedRequest
	// - RespondQueryTaskCompletedRequest
	// If waitLocalActivity is true, and there is outstanding local activities, this call will return nil.
	CompleteWorkflowTask(workflowTask *workflowTask, waitLocalActivity bool) interface{}
	// GetWorkflowTaskTimeout returns the WorkflowTaskTimeout
	GetWorkflowTaskTimeout() time.Duration
	GetCurrentWorkflowTask() *workflowservice.PollWorkflowTaskQueueResponse
	IsDestroyed() bool
	StackTrace() string
}

WorkflowExecutionContext represents one instance of workflow execution state in memory. Lock must be obtained before calling into any methods.

type WorkflowExecutionError

type WorkflowExecutionError struct {
	// contains filtered or unexported fields
}

WorkflowExecutionError is returned from workflow. Unwrap this error to get actual cause.

func NewWorkflowExecutionError

func NewWorkflowExecutionError(
	workflowID string,
	runID string,
	workflowType string,
	cause error,
) *WorkflowExecutionError

NewWorkflowExecutionError creates WorkflowExecutionError instance.

func (*WorkflowExecutionError) Error

func (e *WorkflowExecutionError) Error() string

Error from error interface

func (*WorkflowExecutionError) Unwrap

func (e *WorkflowExecutionError) Unwrap() error

type WorkflowInboundInterceptor added in v1.12.0

type WorkflowInboundInterceptor interface {
	// Init is the first call of this interceptor. Implementations can change/wrap
	// the outbound interceptor before calling Init on the next interceptor.
	Init(outbound WorkflowOutboundInterceptor) error

	// ExecuteWorkflow is called when a workflow is to be run on this worker.
	// interceptor.WorkflowHeader will return a non-nil map for this context.
	ExecuteWorkflow(ctx Context, in *ExecuteWorkflowInput) (interface{}, error)

	// HandleSignal is called when a signal is sent to a workflow on this worker.
	// interceptor.WorkflowHeader will return a non-nil map for this context.
	HandleSignal(ctx Context, in *HandleSignalInput) error

	// HandleQuery is called when a query is sent to a workflow on this worker.
	// interceptor.WorkflowHeader will return a non-nil map for this context.
	HandleQuery(ctx Context, in *HandleQueryInput) (interface{}, error)

	// ValidateUpdate is always called prior to executing an update, even if the
	// update handler for in.Name was not registered with a validation function
	// as part of its optional configuration. The same prohibition against
	// mutating workflow state that is demanded of UpdateOptions.Validator
	// functions also applies to this function.
	//
	// NOTE: Experimental
	ValidateUpdate(ctx Context, in *UpdateInput) error

	// ExecuteUpdate is called after ValidateUpdate if and only if the latter
	// returns nil. interceptor.WorkflowHeader will return a non-nil map for
	// this context. ExecuteUpdate is allowed to mutate workflow state and
	// perform workflow actions such as scheduling activities, timers, etc.
	//
	// NOTE: Experimental
	ExecuteUpdate(ctx Context, in *UpdateInput) (interface{}, error)
	// contains filtered or unexported methods
}

WorkflowInboundInterceptor is an interface for all workflow calls originating from the server. See documentation in the interceptor package for more details.

type WorkflowInboundInterceptorBase added in v1.12.0

type WorkflowInboundInterceptorBase struct {
	Next WorkflowInboundInterceptor
}

WorkflowInboundInterceptorBase is a default implementation of WorkflowInboundInterceptor meant for embedding. See documentation in the interceptor package for more details.

func (*WorkflowInboundInterceptorBase) ExecuteUpdate added in v1.16.0

func (w *WorkflowInboundInterceptorBase) ExecuteUpdate(ctx Context, in *UpdateInput) (interface{}, error)

ExecuteUpdate implements WorkflowInboundInterceptor.ExecuteUpdate.

func (*WorkflowInboundInterceptorBase) ExecuteWorkflow added in v1.12.0

func (w *WorkflowInboundInterceptorBase) ExecuteWorkflow(ctx Context, in *ExecuteWorkflowInput) (interface{}, error)

ExecuteWorkflow implements WorkflowInboundInterceptor.ExecuteWorkflow.

func (*WorkflowInboundInterceptorBase) HandleQuery added in v1.12.0

func (w *WorkflowInboundInterceptorBase) HandleQuery(ctx Context, in *HandleQueryInput) (interface{}, error)

HandleQuery implements WorkflowInboundInterceptor.HandleQuery.

func (*WorkflowInboundInterceptorBase) HandleSignal added in v1.12.0

HandleSignal implements WorkflowInboundInterceptor.HandleSignal.

func (*WorkflowInboundInterceptorBase) Init added in v1.12.0

Init implements WorkflowInboundInterceptor.Init.

func (*WorkflowInboundInterceptorBase) ValidateUpdate added in v1.16.0

func (w *WorkflowInboundInterceptorBase) ValidateUpdate(ctx Context, in *UpdateInput) error

ValidateUpdate implements WorkflowInboundInterceptor.ValidateUpdate.

type WorkflowInfo

type WorkflowInfo struct {
	WorkflowExecution WorkflowExecution
	// The original runID before resetting. Using it instead of current runID can make workflow decision deterministic after reset. See also FirstRunId
	OriginalRunID string
	// 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.
	FirstRunID               string
	WorkflowType             WorkflowType
	TaskQueueName            string
	WorkflowExecutionTimeout time.Duration
	WorkflowRunTimeout       time.Duration
	WorkflowTaskTimeout      time.Duration
	Namespace                string
	Attempt                  int32 // Attempt starts from 1 and increased by 1 for every retry if retry policy is specified.
	// Time of the workflow start.
	// workflow.Now at the beginning of a workflow can return a later time if the Workflow Worker was down.
	WorkflowStartTime time.Time

	CronSchedule            string
	ContinuedExecutionRunID string
	ParentWorkflowNamespace string
	ParentWorkflowExecution *WorkflowExecution
	Memo                    *commonpb.Memo // Value can be decoded using data converter (defaultDataConverter, or custom one if set).
	// Deprecated: use [Workflow.GetTypedSearchAttributes] instead.
	SearchAttributes *commonpb.SearchAttributes // Value can be decoded using defaultDataConverter.
	RetryPolicy      *RetryPolicy
	// BinaryChecksum represents the value persisted by the last worker to complete a task in this workflow. It may be
	// an explicitly set or implicitly derived binary checksum of the worker binary, or, if this worker has opted into
	// build-id based versioning, is the explicitly set worker build id. If this is the first worker to operate on the
	// workflow, it is this worker's current value.
	BinaryChecksum string
	// contains filtered or unexported fields
}

WorkflowInfo information about currently executing workflow

func GetWorkflowInfo

func GetWorkflowInfo(ctx Context) *WorkflowInfo

GetWorkflowInfo extracts info of a current workflow from a context.

func (*WorkflowInfo) GetBinaryChecksum

func (wInfo *WorkflowInfo) GetBinaryChecksum() string

GetBinaryChecksum returns the binary checksum of the last worker to complete a task for this workflow, or if this is the first task, this worker's checksum.

func (*WorkflowInfo) GetContinueAsNewSuggested added in v1.25.0

func (wInfo *WorkflowInfo) GetContinueAsNewSuggested() bool

GetContinueAsNewSuggested returns true if the server is configured to suggest continue as new and it is suggested. This value may change throughout the life of the workflow.

func (*WorkflowInfo) GetCurrentBuildID added in v1.26.0

func (wInfo *WorkflowInfo) GetCurrentBuildID() string

GetCurrentBuildID returns the Build ID of the worker that processed this task, which may be empty. During replay this id may not equal the id of the replaying worker. If not replaying and this worker has a defined Build ID, it will equal that ID. It is safe to use for branching. When used inside a query, the ID of the worker that processed the task which last affected the workflow will be returned.

func (*WorkflowInfo) GetCurrentHistoryLength added in v1.16.0

func (wInfo *WorkflowInfo) GetCurrentHistoryLength() int

GetCurrentHistoryLength returns the current length of history when called. This value may change throughout the life of the workflow.

func (*WorkflowInfo) GetCurrentHistorySize added in v1.25.0

func (wInfo *WorkflowInfo) GetCurrentHistorySize() int

GetCurrentHistorySize returns the current byte size of history when called. This value may change throughout the life of the workflow.

type WorkflowOptions

type WorkflowOptions struct {
	TaskQueueName            string
	WorkflowExecutionTimeout time.Duration
	WorkflowRunTimeout       time.Duration
	WorkflowTaskTimeout      time.Duration
	Namespace                string
	WorkflowID               string
	WaitForCancellation      bool
	WorkflowIDReusePolicy    enumspb.WorkflowIdReusePolicy
	WorkflowIDConflictPolicy enumspb.WorkflowIdConflictPolicy
	DataConverter            converter.DataConverter
	RetryPolicy              *commonpb.RetryPolicy
	CronSchedule             string
	ContextPropagators       []ContextPropagator
	Memo                     map[string]interface{}
	SearchAttributes         map[string]interface{}
	TypedSearchAttributes    SearchAttributes
	ParentClosePolicy        enumspb.ParentClosePolicy

	VersioningIntent VersioningIntent
	// contains filtered or unexported fields
}

WorkflowOptions options passed to the workflow function The current timeout resolution implementation is in seconds and uses math.Ceil() as the duration. But is subjected to change in the future.

type WorkflowOutboundInterceptor added in v1.12.0

type WorkflowOutboundInterceptor interface {
	// Go intercepts workflow.Go.
	Go(ctx Context, name string, f func(ctx Context)) Context

	// Await intercepts workflow.Await.
	Await(ctx Context, condition func() bool) error

	// AwaitWithTimeout intercepts workflow.AwaitWithTimeout.
	AwaitWithTimeout(ctx Context, timeout time.Duration, condition func() bool) (bool, error)

	// AwaitWithOptions intercepts workflow.AwaitWithOptions.
	//
	// NOTE: Experimental
	AwaitWithOptions(ctx Context, options AwaitOptions, condition func() bool) (bool, error)

	// ExecuteActivity intercepts workflow.ExecuteActivity.
	// interceptor.WorkflowHeader will return a non-nil map for this context.
	ExecuteActivity(ctx Context, activityType string, args ...interface{}) Future

	// ExecuteLocalActivity intercepts workflow.ExecuteLocalActivity.
	// interceptor.WorkflowHeader will return a non-nil map for this context.
	ExecuteLocalActivity(ctx Context, activityType string, args ...interface{}) Future

	// ExecuteChildWorkflow intercepts workflow.ExecuteChildWorkflow.
	// interceptor.WorkflowHeader will return a non-nil map for this context.
	ExecuteChildWorkflow(ctx Context, childWorkflowType string, args ...interface{}) ChildWorkflowFuture

	// GetInfo intercepts workflow.GetInfo.
	GetInfo(ctx Context) *WorkflowInfo

	// GetTypedSearchAttributes intercepts workflow.GetTypedSearchAttributes.
	GetTypedSearchAttributes(ctx Context) SearchAttributes

	// GetCurrentUpdateInfo intercepts workflow.GetCurrentUpdateInfo.
	//
	// NOTE: Experimental
	GetCurrentUpdateInfo(ctx Context) *UpdateInfo

	// GetLogger intercepts workflow.GetLogger.
	GetLogger(ctx Context) log.Logger

	// GetMetricsHandler intercepts workflow.GetMetricsHandler.
	GetMetricsHandler(ctx Context) metrics.Handler

	// Now intercepts workflow.Now.
	Now(ctx Context) time.Time

	// NewTimer intercepts workflow.NewTimer.
	NewTimer(ctx Context, d time.Duration) Future

	// NewTimer intercepts workflow.NewTimerWithOptions.
	//
	// NOTE: Experimental
	NewTimerWithOptions(ctx Context, d time.Duration, options TimerOptions) Future

	// Sleep intercepts workflow.Sleep.
	Sleep(ctx Context, d time.Duration) (err error)

	// RequestCancelExternalWorkflow intercepts
	// workflow.RequestCancelExternalWorkflow.
	RequestCancelExternalWorkflow(ctx Context, workflowID, runID string) Future

	// SignalExternalWorkflow intercepts workflow.SignalExternalWorkflow.
	// interceptor.WorkflowHeader will return a non-nil map for this context.
	SignalExternalWorkflow(ctx Context, workflowID, runID, signalName string, arg interface{}) Future

	// SignalChildWorkflow intercepts
	// workflow.ChildWorkflowFuture.SignalChildWorkflow.
	// interceptor.WorkflowHeader will return a non-nil map for this context.
	SignalChildWorkflow(ctx Context, workflowID, signalName string, arg interface{}) Future

	// UpsertSearchAttributes intercepts workflow.UpsertSearchAttributes.
	UpsertSearchAttributes(ctx Context, attributes map[string]interface{}) error

	// UpsertTypedSearchAttributes intercepts workflow.UpsertTypedSearchAttributes.
	UpsertTypedSearchAttributes(ctx Context, attributes ...SearchAttributeUpdate) error

	// UpsertMemo intercepts workflow.UpsertMemo.
	UpsertMemo(ctx Context, memo map[string]interface{}) error

	// GetSignalChannel intercepts workflow.GetSignalChannel.
	GetSignalChannel(ctx Context, signalName string) ReceiveChannel

	// GetSignalChannelWithOptions intercepts workflow.GetSignalChannelWithOptions.
	//
	// NOTE: Experimental
	GetSignalChannelWithOptions(ctx Context, signalName string, options SignalChannelOptions) ReceiveChannel

	// SideEffect intercepts workflow.SideEffect.
	SideEffect(ctx Context, f func(ctx Context) interface{}) converter.EncodedValue

	// MutableSideEffect intercepts workflow.MutableSideEffect.
	MutableSideEffect(
		ctx Context,
		id string,
		f func(ctx Context) interface{},
		equals func(a, b interface{}) bool,
	) converter.EncodedValue

	// GetVersion intercepts workflow.GetVersion.
	GetVersion(ctx Context, changeID string, minSupported, maxSupported Version) Version

	// SetQueryHandler intercepts workflow.SetQueryHandler.
	SetQueryHandler(ctx Context, queryType string, handler interface{}) error

	// SetQueryHandlerWithOptions intercepts workflow.SetQueryHandlerWithOptions.
	//
	// NOTE: Experimental
	SetQueryHandlerWithOptions(ctx Context, queryType string, handler interface{}, options QueryHandlerOptions) error

	// SetUpdateHandler intercepts workflow.SetUpdateHandler.
	//
	// NOTE: Experimental
	SetUpdateHandler(ctx Context, updateName string, handler interface{}, opts UpdateHandlerOptions) error

	// IsReplaying intercepts workflow.IsReplaying.
	IsReplaying(ctx Context) bool

	// HasLastCompletionResult intercepts workflow.HasLastCompletionResult.
	HasLastCompletionResult(ctx Context) bool

	// GetLastCompletionResult intercepts workflow.GetLastCompletionResult.
	GetLastCompletionResult(ctx Context, d ...interface{}) error

	// GetLastError intercepts workflow.GetLastError.
	GetLastError(ctx Context) error

	// NewContinueAsNewError intercepts workflow.NewContinueAsNewError.
	// interceptor.WorkflowHeader will return a non-nil map for this context.
	NewContinueAsNewError(ctx Context, wfn interface{}, args ...interface{}) error

	// ExecuteNexusOperation intercepts NexusClient.ExecuteOperation.
	//
	// NOTE: Experimental
	ExecuteNexusOperation(ctx Context, input ExecuteNexusOperationInput) NexusOperationFuture

	// RequestCancelNexusOperation intercepts Nexus Operation cancellation via context.
	//
	// NOTE: Experimental
	RequestCancelNexusOperation(ctx Context, input RequestCancelNexusOperationInput)
	// contains filtered or unexported methods
}

WorkflowOutboundInterceptor is an interface for all workflow calls originating from the SDK. See documentation in the interceptor package for more details.

type WorkflowOutboundInterceptorBase added in v1.12.0

type WorkflowOutboundInterceptorBase struct {
	Next WorkflowOutboundInterceptor
}

WorkflowOutboundInterceptorBase is a default implementation of WorkflowOutboundInterceptor meant for embedding. See documentation in the interceptor package for more details.

func (*WorkflowOutboundInterceptorBase) Await added in v1.24.0

func (w *WorkflowOutboundInterceptorBase) Await(ctx Context, condition func() bool) error

Await implements WorkflowOutboundInterceptor.Await.

func (*WorkflowOutboundInterceptorBase) AwaitWithOptions added in v1.29.1

func (w *WorkflowOutboundInterceptorBase) AwaitWithOptions(ctx Context, options AwaitOptions, condition func() bool) (bool, error)

AwaitWithOptions implements WorkflowOutboundInterceptor.AwaitWithOptions.

NOTE: Experimental

func (*WorkflowOutboundInterceptorBase) AwaitWithTimeout added in v1.24.0

func (w *WorkflowOutboundInterceptorBase) AwaitWithTimeout(ctx Context, timeout time.Duration, condition func() bool) (bool, error)

AwaitWithTimeout implements WorkflowOutboundInterceptor.AwaitWithTimeout.

func (*WorkflowOutboundInterceptorBase) ExecuteActivity added in v1.12.0

func (w *WorkflowOutboundInterceptorBase) ExecuteActivity(ctx Context, activityType string, args ...interface{}) Future

ExecuteActivity implements WorkflowOutboundInterceptor.ExecuteActivity.

func (*WorkflowOutboundInterceptorBase) ExecuteChildWorkflow added in v1.12.0

func (w *WorkflowOutboundInterceptorBase) ExecuteChildWorkflow(
	ctx Context,
	childWorkflowType string,
	args ...interface{},
) ChildWorkflowFuture

ExecuteChildWorkflow implements WorkflowOutboundInterceptor.ExecuteChildWorkflow.

func (*WorkflowOutboundInterceptorBase) ExecuteLocalActivity added in v1.12.0

func (w *WorkflowOutboundInterceptorBase) ExecuteLocalActivity(
	ctx Context,
	activityType string,
	args ...interface{},
) Future

ExecuteLocalActivity implements WorkflowOutboundInterceptor.ExecuteLocalActivity.

func (*WorkflowOutboundInterceptorBase) ExecuteNexusOperation added in v1.28.0

ExecuteNexusOperation implements WorkflowOutboundInterceptor.ExecuteNexusOperation.

func (*WorkflowOutboundInterceptorBase) GetCurrentUpdateInfo added in v1.27.0

func (w *WorkflowOutboundInterceptorBase) GetCurrentUpdateInfo(ctx Context) *UpdateInfo

GetCurrentUpdateInfo implements WorkflowOutboundInterceptor.GetCurrentUpdateInfo.

func (*WorkflowOutboundInterceptorBase) GetInfo added in v1.12.0

GetInfo implements WorkflowOutboundInterceptor.GetInfo.

func (*WorkflowOutboundInterceptorBase) GetLastCompletionResult added in v1.12.0

func (w *WorkflowOutboundInterceptorBase) GetLastCompletionResult(ctx Context, d ...interface{}) error

GetLastCompletionResult implements WorkflowOutboundInterceptor.GetLastCompletionResult.

func (*WorkflowOutboundInterceptorBase) GetLastError added in v1.12.0

func (w *WorkflowOutboundInterceptorBase) GetLastError(ctx Context) error

GetLastError implements WorkflowOutboundInterceptor.GetLastError.

func (*WorkflowOutboundInterceptorBase) GetLogger added in v1.12.0

GetLogger implements WorkflowOutboundInterceptor.GetLogger.

func (*WorkflowOutboundInterceptorBase) GetMetricsHandler added in v1.12.0

func (w *WorkflowOutboundInterceptorBase) GetMetricsHandler(ctx Context) metrics.Handler

GetMetricsHandler implements WorkflowOutboundInterceptor.GetMetricsHandler.

func (*WorkflowOutboundInterceptorBase) GetSignalChannel added in v1.12.0

func (w *WorkflowOutboundInterceptorBase) GetSignalChannel(ctx Context, signalName string) ReceiveChannel

GetSignalChannel implements WorkflowOutboundInterceptor.GetSignalChannel.

func (*WorkflowOutboundInterceptorBase) GetSignalChannelWithOptions added in v1.29.0

func (w *WorkflowOutboundInterceptorBase) GetSignalChannelWithOptions(
	ctx Context,
	signalName string,
	options SignalChannelOptions,
) ReceiveChannel

GetSignalChannelWithOptions implements WorkflowOutboundInterceptor.GetSignalChannelWithOptions.

NOTE: Experimental

func (*WorkflowOutboundInterceptorBase) GetTypedSearchAttributes added in v1.26.0

func (w *WorkflowOutboundInterceptorBase) GetTypedSearchAttributes(ctx Context) SearchAttributes

GetTypedSearchAttributes implements WorkflowOutboundInterceptor.GetTypedSearchAttributes.

func (*WorkflowOutboundInterceptorBase) GetVersion added in v1.12.0

func (w *WorkflowOutboundInterceptorBase) GetVersion(
	ctx Context,
	changeID string,
	minSupported Version,
	maxSupported Version,
) Version

GetVersion implements WorkflowOutboundInterceptor.GetVersion.

func (*WorkflowOutboundInterceptorBase) Go added in v1.12.0

func (w *WorkflowOutboundInterceptorBase) Go(ctx Context, name string, f func(ctx Context)) Context

Go implements WorkflowOutboundInterceptor.Go.

func (*WorkflowOutboundInterceptorBase) HasLastCompletionResult added in v1.12.0

func (w *WorkflowOutboundInterceptorBase) HasLastCompletionResult(ctx Context) bool

HasLastCompletionResult implements WorkflowOutboundInterceptor.HasLastCompletionResult.

func (*WorkflowOutboundInterceptorBase) IsReplaying added in v1.12.0

func (w *WorkflowOutboundInterceptorBase) IsReplaying(ctx Context) bool

IsReplaying implements WorkflowOutboundInterceptor.IsReplaying.

func (*WorkflowOutboundInterceptorBase) MutableSideEffect added in v1.12.0

func (w *WorkflowOutboundInterceptorBase) MutableSideEffect(
	ctx Context,
	id string,
	f func(ctx Context) interface{},
	equals func(a, b interface{}) bool,
) converter.EncodedValue

MutableSideEffect implements WorkflowOutboundInterceptor.MutableSideEffect.

func (*WorkflowOutboundInterceptorBase) NewContinueAsNewError added in v1.12.0

func (w *WorkflowOutboundInterceptorBase) NewContinueAsNewError(
	ctx Context,
	wfn interface{},
	args ...interface{},
) error

NewContinueAsNewError implements WorkflowOutboundInterceptor.NewContinueAsNewError.

func (*WorkflowOutboundInterceptorBase) NewTimer added in v1.12.0

NewTimer implements WorkflowOutboundInterceptor.NewTimer.

func (*WorkflowOutboundInterceptorBase) NewTimerWithOptions added in v1.29.0

func (w *WorkflowOutboundInterceptorBase) NewTimerWithOptions(
	ctx Context,
	d time.Duration,
	options TimerOptions,
) Future

NewTimerWithOptions implements WorkflowOutboundInterceptor.NewTimerWithOptions.

NOTE: Experimental

func (*WorkflowOutboundInterceptorBase) Now added in v1.12.0

Now implements WorkflowOutboundInterceptor.Now.

func (*WorkflowOutboundInterceptorBase) RequestCancelExternalWorkflow added in v1.12.0

func (w *WorkflowOutboundInterceptorBase) RequestCancelExternalWorkflow(
	ctx Context,
	workflowID string,
	runID string,
) Future

RequestCancelExternalWorkflow implements WorkflowOutboundInterceptor.RequestCancelExternalWorkflow.

func (*WorkflowOutboundInterceptorBase) RequestCancelNexusOperation added in v1.28.0

func (w *WorkflowOutboundInterceptorBase) RequestCancelNexusOperation(ctx Context, input RequestCancelNexusOperationInput)

RequestCancelNexusOperation implements WorkflowOutboundInterceptor.RequestCancelNexusOperation.

func (*WorkflowOutboundInterceptorBase) SetQueryHandler added in v1.12.0

func (w *WorkflowOutboundInterceptorBase) SetQueryHandler(ctx Context, queryType string, handler interface{}) error

SetQueryHandler implements WorkflowOutboundInterceptor.SetQueryHandler.

func (*WorkflowOutboundInterceptorBase) SetQueryHandlerWithOptions added in v1.29.0

func (w *WorkflowOutboundInterceptorBase) SetQueryHandlerWithOptions(
	ctx Context,
	queryType string,
	handler interface{},
	options QueryHandlerOptions,
) error

SetQueryHandlerWithOptions implements WorkflowOutboundInterceptor.SetQueryHandlerWithOptions.

NOTE: Experimental

func (*WorkflowOutboundInterceptorBase) SetUpdateHandler added in v1.16.0

func (w *WorkflowOutboundInterceptorBase) SetUpdateHandler(ctx Context, updateName string, handler interface{}, opts UpdateHandlerOptions) error

SetUpdateHandler implements WorkflowOutboundInterceptor.SetUpdateHandler.

func (*WorkflowOutboundInterceptorBase) SideEffect added in v1.12.0

func (w *WorkflowOutboundInterceptorBase) SideEffect(
	ctx Context,
	f func(ctx Context) interface{},
) converter.EncodedValue

SideEffect implements WorkflowOutboundInterceptor.SideEffect.

func (*WorkflowOutboundInterceptorBase) SignalChildWorkflow added in v1.13.0

func (w *WorkflowOutboundInterceptorBase) SignalChildWorkflow(
	ctx Context,
	workflowID string,
	signalName string,
	arg interface{},
) Future

SignalChildWorkflow implements WorkflowOutboundInterceptor.SignalChildWorkflow.

func (*WorkflowOutboundInterceptorBase) SignalExternalWorkflow added in v1.12.0

func (w *WorkflowOutboundInterceptorBase) SignalExternalWorkflow(
	ctx Context,
	workflowID string,
	runID string,
	signalName string,
	arg interface{},
) Future

SignalExternalWorkflow implements WorkflowOutboundInterceptor.SignalExternalWorkflow.

func (*WorkflowOutboundInterceptorBase) Sleep added in v1.12.0

Sleep implements WorkflowOutboundInterceptor.Sleep.

func (*WorkflowOutboundInterceptorBase) UpsertMemo added in v1.17.0

func (w *WorkflowOutboundInterceptorBase) UpsertMemo(ctx Context, memo map[string]interface{}) error

UpsertMemo implements WorkflowOutboundInterceptor.UpsertMemo.

func (*WorkflowOutboundInterceptorBase) UpsertSearchAttributes added in v1.12.0

func (w *WorkflowOutboundInterceptorBase) UpsertSearchAttributes(ctx Context, attributes map[string]interface{}) error

UpsertSearchAttributes implements WorkflowOutboundInterceptor.UpsertSearchAttributes.

func (*WorkflowOutboundInterceptorBase) UpsertTypedSearchAttributes added in v1.26.0

func (w *WorkflowOutboundInterceptorBase) UpsertTypedSearchAttributes(ctx Context, attributes ...SearchAttributeUpdate) error

UpsertTypedSearchAttributes implements WorkflowOutboundInterceptor.UpsertTypedSearchAttributes.

type WorkflowPanicPolicy

type WorkflowPanicPolicy int

WorkflowPanicPolicy is used for configuring how worker deals with workflow code panicking which includes non backwards compatible changes to the workflow code without appropriate versioning (see workflow.GetVersion). The default behavior is to block workflow execution until the problem is fixed.

const (
	// BlockWorkflow is the default policy for handling workflow panics and detected non-determinism.
	// This option causes workflow to get stuck in the workflow task retry loop.
	// It is expected that after the problem is discovered and fixed the workflows are going to continue
	// without any additional manual intervention.
	BlockWorkflow WorkflowPanicPolicy = iota
	// FailWorkflow immediately fails workflow execution if workflow code throws panic or detects non-determinism.
	// This feature is convenient during development.
	// WARNING: enabling this in production can cause all open workflows to fail on a single bug or bad deployment.
	FailWorkflow
)

type WorkflowReplayer

type WorkflowReplayer struct {
	// contains filtered or unexported fields
}

WorkflowReplayer is used to replay workflow code from an event history

func NewWorkflowReplayer

func NewWorkflowReplayer(options WorkflowReplayerOptions) (*WorkflowReplayer, error)

NewWorkflowReplayer creates an instance of the WorkflowReplayer.

func (*WorkflowReplayer) GetWorkflowResult added in v1.22.0

func (aw *WorkflowReplayer) GetWorkflowResult(workflowID string, valuePtr interface{}) error

GetWorkflowResult get the result of a succesfully replayed workflow.

func (*WorkflowReplayer) RegisterWorkflow

func (aw *WorkflowReplayer) RegisterWorkflow(w interface{})

RegisterWorkflow registers workflow function to replay

func (*WorkflowReplayer) RegisterWorkflowWithOptions

func (aw *WorkflowReplayer) RegisterWorkflowWithOptions(w interface{}, options RegisterWorkflowOptions)

RegisterWorkflowWithOptions registers workflow function with custom workflow name to replay

func (*WorkflowReplayer) ReplayPartialWorkflowHistoryFromJSONFile

func (aw *WorkflowReplayer) ReplayPartialWorkflowHistoryFromJSONFile(logger log.Logger, jsonfileName string, lastEventID int64) error

ReplayPartialWorkflowHistoryFromJSONFile executes a single workflow task for the given json history file upto provided lastEventID(inclusive). Use for testing the backwards compatibility of code changes and troubleshooting workflows in a debugger. The logger is an optional parameter. Defaults to the noop logger.

func (*WorkflowReplayer) ReplayWorkflowExecution

func (aw *WorkflowReplayer) ReplayWorkflowExecution(ctx context.Context, service workflowservice.WorkflowServiceClient, logger log.Logger, namespace string, execution WorkflowExecution) error

ReplayWorkflowExecution replays workflow execution loading it from Temporal service.

func (*WorkflowReplayer) ReplayWorkflowHistory

func (aw *WorkflowReplayer) ReplayWorkflowHistory(logger log.Logger, history *historypb.History) error

ReplayWorkflowHistory executes a single workflow task for the given history. Use for testing the backwards compatibility of code changes and troubleshooting workflows in a debugger. The logger is an optional parameter. Defaults to the noop logger.

func (*WorkflowReplayer) ReplayWorkflowHistoryFromJSONFile

func (aw *WorkflowReplayer) ReplayWorkflowHistoryFromJSONFile(logger log.Logger, jsonfileName string) error

ReplayWorkflowHistoryFromJSONFile executes a single workflow task for the given json history file. Use for testing the backwards compatibility of code changes and troubleshooting workflows in a debugger. The logger is an optional parameter. Defaults to the noop logger.

func (*WorkflowReplayer) ReplayWorkflowHistoryWithOptions added in v1.20.0

func (aw *WorkflowReplayer) ReplayWorkflowHistoryWithOptions(logger log.Logger, history *historypb.History, options ReplayWorkflowHistoryOptions) error

ReplayWorkflowHistoryWithOptions executes a single workflow task for the given history. Use for testing the backwards compatibility of code changes and troubleshooting workflows in a debugger. The logger is an optional parameter. Defaults to the noop logger.

type WorkflowReplayerOptions added in v1.11.0

type WorkflowReplayerOptions struct {
	// Optional custom data converter to provide for replay. If not set, the
	// default converter is used.
	DataConverter converter.DataConverter

	FailureConverter converter.FailureConverter

	// Optional: Sets ContextPropagators that allows users to control the context information passed through a workflow
	// default: nil
	ContextPropagators []ContextPropagator

	// Interceptors to apply to the worker. Earlier interceptors wrap later
	// interceptors.
	Interceptors []WorkerInterceptor

	// Disable aliasing during registration. This should be set if it was set on
	// worker.Options.DisableRegistrationAliasing when originally run. See
	// documentation for that field for more information.
	DisableRegistrationAliasing bool

	// Optional: Enable logging in replay.
	// In the workflow code you can use workflow.GetLogger(ctx) to write logs. By default, the logger will skip log
	// entry during replay mode so you won't see duplicate logs. This option will enable the logging in replay mode.
	// This is only useful for debugging purpose.
	// default: false
	EnableLoggingInReplay bool

	// Optional: Disable the default 1 second deadlock detection timeout. This option can be used to step through
	// workflow code with multiple breakpoints in a debugger.
	DisableDeadlockDetection bool
}

WorkflowReplayerOptions are options for creating a workflow replayer.

type WorkflowRun

type WorkflowRun interface {
	// GetID return workflow ID, which will be same as StartWorkflowOptions.ID if provided.
	GetID() string

	// GetRunID return the first started workflow run ID (please see below) -
	// empty string if no such run. Note, this value may change after Get is
	// called if there was a later run for this run.
	GetRunID() string

	// Get will fill the workflow execution result to valuePtr, if workflow
	// execution is a success, or return corresponding error. If valuePtr is
	// nil, valuePtr will be ignored and only the corresponding error of the
	// workflow will be returned (nil on workflow execution success).
	// This is a blocking API.
	//
	// This call will follow execution runs to the latest result for this run
	// instead of strictly returning this run's result. This means that if the
	// workflow returned ContinueAsNewError, has a more recent cron execution,
	// or has a new run ID on failure (i.e. a retry), this will wait and return
	// the result for the latest run in the chain. To strictly get the result
	// for this run without following to the latest, use GetWithOptions and set
	// the DisableFollowingRuns option to true.
	//
	// Note, values should not be reused for extraction here because merging on
	// top of existing values may result in unexpected behavior similar to
	// json.Unmarshal.
	Get(ctx context.Context, valuePtr interface{}) error

	// GetWithOptions will fill the workflow execution result to valuePtr, if
	// workflow execution is a success, or return corresponding error. If
	// valuePtr is nil, valuePtr will be ignored and only the corresponding
	// error of the workflow will be returned (nil on workflow execution success).
	// This is a blocking API.
	//
	// Note, values should not be reused for extraction here because merging on
	// top of existing values may result in unexpected behavior similar to
	// json.Unmarshal.
	GetWithOptions(ctx context.Context, valuePtr interface{}, options WorkflowRunGetOptions) error
}

WorkflowRun represents a started non child workflow

type WorkflowRunGetOptions added in v1.15.0

type WorkflowRunGetOptions struct {
	// DisableFollowingRuns, if true, will not follow execution chains to the
	// latest run. By default when this is false, getting the result of a
	// workflow may not use the literal run ID but instead follow to later runs
	// if the workflow returned a ContinueAsNewError, has a later cron, or is
	// retried on failure.
	DisableFollowingRuns bool
}

WorkflowRunGetOptions are options for WorkflowRun.GetWithOptions.

type WorkflowTaskHandler

type WorkflowTaskHandler interface {
	WorkflowContextManager

	// Processes the workflow task
	// The response could be:
	// - RespondWorkflowTaskCompletedRequest
	// - RespondWorkflowTaskFailedRequest
	// - RespondQueryTaskCompletedRequest
	ProcessWorkflowTask(
		task *workflowTask,
		ctx *workflowExecutionContextImpl,
		f workflowTaskHeartbeatFunc,
	) (response interface{}, err error)
}

WorkflowTaskHandler represents workflow task handlers.

type WorkflowTestSuite

type WorkflowTestSuite struct {
	// contains filtered or unexported fields
}

WorkflowTestSuite is the test suite to run unit tests for workflow/activity.

func (*WorkflowTestSuite) GetLogger

func (s *WorkflowTestSuite) GetLogger() log.Logger

GetLogger gets the logger for this WorkflowTestSuite.

func (*WorkflowTestSuite) NewTestActivityEnvironment

func (s *WorkflowTestSuite) NewTestActivityEnvironment() *TestActivityEnvironment

NewTestActivityEnvironment creates a new instance of TestActivityEnvironment. Use the returned TestActivityEnvironment to run your activity in the test environment.

func (*WorkflowTestSuite) NewTestWorkflowEnvironment

func (s *WorkflowTestSuite) NewTestWorkflowEnvironment() *TestWorkflowEnvironment

NewTestWorkflowEnvironment creates a new instance of TestWorkflowEnvironment. Use the returned TestWorkflowEnvironment to run your workflow in the test environment.

func (*WorkflowTestSuite) SetContextPropagators

func (s *WorkflowTestSuite) SetContextPropagators(ctxProps []ContextPropagator)

SetContextPropagators sets the context propagators for this WorkflowTestSuite. If you don't set context propagators, test suite will not use context propagators

func (*WorkflowTestSuite) SetDisableRegistrationAliasing added in v1.16.0

func (s *WorkflowTestSuite) SetDisableRegistrationAliasing(disableRegistrationAliasing bool)

SetDisableRegistrationAliasing disables registration aliasing the same way it is disabled when set for worker.Options.DisableRegistrationAliasing. This value should be set to true if it is expected to be set on the worker when running (which is strongly recommended for custom-named workflows and activities). See the documentation on worker.Options.DisableRegistrationAliasing for more details.

This must be set before obtaining new test workflow or activity environments.

func (*WorkflowTestSuite) SetHeader

func (s *WorkflowTestSuite) SetHeader(header *commonpb.Header)

SetHeader sets the headers for this WorkflowTestSuite. If you don't set header, test suite will not pass headers to the workflow

func (*WorkflowTestSuite) SetLogger

func (s *WorkflowTestSuite) SetLogger(logger log.Logger)

SetLogger sets the logger for this WorkflowTestSuite. If you don't set logger, test suite will create a default logger with Debug level logging enabled.

func (*WorkflowTestSuite) SetMetricsHandler added in v1.12.0

func (s *WorkflowTestSuite) SetMetricsHandler(metricsHandler metrics.Handler)

SetMetricsHandler sets the metrics handler for this WorkflowTestSuite. If you don't set handler, test suite will use a noop handler.

type WorkflowTimerClient

type WorkflowTimerClient interface {

	// Now - Current time when the workflow task is started or replayed.
	// the workflow need to use this for wall clock to make the flow logic deterministic.
	Now() time.Time

	// NewTimer - Creates a new timer that will fire callback after d(resolution is in seconds).
	// The callback indicates the error(TimerCanceledError) if the timer is canceled.
	NewTimer(d time.Duration, options TimerOptions, callback ResultHandler) *TimerID

	// RequestCancelTimer - Requests cancel of a timer, this one doesn't wait for cancellation request
	// to complete, instead invokes the ResultHandler with TimerCanceledError
	// If the timer is not started then it is a no-operation.
	RequestCancelTimer(timerID TimerID)
}

WorkflowTimerClient wraps the async workflow timer functionality.

type WorkflowType

type WorkflowType struct {
	Name string
}

WorkflowType identifies a workflow type.

type WorkflowUpdateHandle added in v1.20.0

type WorkflowUpdateHandle interface {
	// WorkflowID observes the update's workflow ID.
	WorkflowID() string

	// RunID observes the update's run ID.
	RunID() string

	// UpdateID observes the update's ID.
	UpdateID() string

	// Get blocks on the outcome of the update.
	Get(ctx context.Context, valuePtr interface{}) error
}

WorkflowUpdateHandle is a handle to a workflow execution update process. The update may or may not have completed so an instance of this type functions similar to a Future with respect to the outcome of the update. If the update is rejected or returns an error, the Get function on this type will return that error through the output valuePtr. NOTE: Experimental

type WorkflowUpdateServiceTimeoutOrCanceledError added in v1.28.0

type WorkflowUpdateServiceTimeoutOrCanceledError struct {
	// contains filtered or unexported fields
}

WorkflowUpdateServiceTimeoutOrCanceledError is an error that occurs when an update call times out or is cancelled.

Note, this is not related to any general concept of timing out or cancelling a running update, this is only related to the client call itself.

func NewWorkflowUpdateServiceTimeoutOrCanceledError added in v1.28.0

func NewWorkflowUpdateServiceTimeoutOrCanceledError(err error) *WorkflowUpdateServiceTimeoutOrCanceledError

NewWorkflowUpdateServiceTimeoutOrCanceledError creates a new WorkflowUpdateServiceTimeoutOrCanceledError.

func (*WorkflowUpdateServiceTimeoutOrCanceledError) Error added in v1.28.0

func (*WorkflowUpdateServiceTimeoutOrCanceledError) Unwrap added in v1.28.0

type WorkflowUpdateStage added in v1.27.0

type WorkflowUpdateStage int

WorkflowUpdateStage indicates the stage of an update request.

const (
	// WorkflowUpdateStageUnspecified indicates the wait stage was not specified
	WorkflowUpdateStageUnspecified WorkflowUpdateStage = iota
	// WorkflowUpdateStageAdmitted indicates the update is admitted
	WorkflowUpdateStageAdmitted
	// WorkflowUpdateStageAccepted indicates the update is accepted
	WorkflowUpdateStageAccepted
	// WorkflowUpdateStageCompleted indicates the update is completed
	WorkflowUpdateStageCompleted
)

Directories

Path Synopsis
cmd
common
Package interceptortest contains internal utilities for testing interceptors.
Package interceptortest contains internal utilities for testing interceptors.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL