restate

package module
v0.25.0 Latest Latest
Warning

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

Go to latest
Published: Jun 30, 2026 License: MIT Imports: 15 Imported by: 63

README

Go Reference Go

Restate Go SDK

Restate is a system for easily building resilient applications using distributed durable async/await. This repository contains the Restate SDK for writing services in Golang.

Community

Prerequisites

  • Go: >= 1.24.0

Examples

This repo contains an example based on the Ticket Reservation Service.

You can also check a list of examples available here: https://github.com/restatedev/examples?tab=readme-ov-file#go

How to use the example

Download and run restate, as described here v1.x

restate-server

In another terminal run the example

cd restate-sdk-go/example
go run .

In a third terminal register:

restate deployments register http://localhost:9080

And do the following steps

  • Add tickets to basket
curl -v localhost:8080/UserSession/azmy/AddTicket \
    -H 'content-type: application/json' \
    -d '"ticket-1"'

# true
curl -v localhost:8080/UserSession/azmy/AddTicket \
    -H 'content-type: application/json' \
    -d '"ticket-2"'
# true

Trying adding the same tickets again should return false since they are already reserved. If you didn't check out the tickets in 15min (if you are impatient change the delay in code to make it shorter)

  • Check out
curl localhost:8080/UserSession/azmy/Checkout
# true

Ingress SDK

When you need to call restate handlers or attach to invocations from outside the restate context, use the ingress SDK.

Versions

This library follows Semantic Versioning.

Upgrading from 0.x? See the migration guide.

Compatibility with Restate Server:

Restate Server sdk-go 1.0
< 1.3
1.3 (1)(2)
1.4 (2)
1.5
1.6
1.7

(1) WithAbortTimeout, WithEnableLazyState, WithIdempotencyRetention, WithInactivityTimeout, WithIngressPrivate, WithJournalRetention and WithWorkflowRetention require Restate Server >= 1.4. Check the in-code documentation for more details.

(2) WithInvocationRetryPolicy requires Restate Server >= 1.5. Check the in-code documentation for more details.

Older 0.x SDK releases are legacy and deprecated; see the Restate 1.5 release notes for their compatibility and deprecation details.

Contributing

We’re excited if you join the Restate community and start contributing! Whether it is feature requests, bug reports, ideas & feedback or PRs, we appreciate any and all contributions. We know that your time is precious and, therefore, deeply value any effort to contribute!

Documentation

Index

Constants

This section is empty.

Variables

WithBinary is an option to specify the use of encoding.BinaryCodec for (de)serialisation

WithJSON is an option to specify the use of encoding.JSONCodec for (de)serialisation

WithProto is an option to specify the use of encoding.ProtoCodec for (de)serialisation

WithProtoJSON is an option to specify the use of encoding.ProtoJSONCodec for (de)serialisation

Functions

func CancelInvocation added in v0.16.0

func CancelInvocation(ctx Context, invocationId string)

CancelInvocation cancels the invocation with the given invocationId. For more info about cancellations, see https://docs.restate.dev/operate/invocation/#cancelling-invocations

func Clear added in v0.11.0

func Clear(ctx ObjectContext, key string)

Clear deletes a key

func ClearAll added in v0.11.0

func ClearAll(ctx ObjectContext)

ClearAll drops all stored state associated with this Object key

func IsRetryableError added in v0.25.0

func IsRetryableError(err error) bool

IsRetryableError reports whether err is, or wraps, a RetryableError.

func IsTerminalError

func IsTerminalError(err error) bool

IsTerminalError reports whether err is, or wraps, a TerminalError - ie, that returning it in a handler or Run function will finish the invocation with the error as a result.

func Key added in v0.11.0

func Key(ctx ObjectSharedContext) string

Key retrieves the key for this virtual object invocation or this workflow invocation.

func KillOnMaxAttempts added in v0.20.0

func KillOnMaxAttempts() withOnMaxAttempts

KillOnMaxAttempts kills the invocation when the maximum number of attempts is reached.

func NewObject added in v0.10.0

func NewObject(name string, opts ...options.ServiceDefinitionOption) *object

NewObject creates a new named Virtual Object

func NewObjectHandler

func NewObjectHandler[I any, O any](fn ObjectHandlerFn[I, O], opts ...options.HandlerOption) *objectHandler[I, O]

NewObjectHandler converts a function of signature ObjectHandlerFn into an exclusive-mode handler on a Virtual Object. The handler will have access to a full ObjectContext which may mutate state.

func NewObjectSharedHandler

func NewObjectSharedHandler[I any, O any](fn ObjectSharedHandlerFn[I, O], opts ...options.HandlerOption) *objectHandler[I, O]

NewObjectSharedHandler converts a function of signature ObjectSharedHandlerFn into a shared-mode handler on a Virtual Object. The handler will only have access to a ObjectSharedContext which can only read a snapshot of state.

func NewService added in v0.10.0

func NewService(name string, opts ...options.ServiceDefinitionOption) *service

NewService creates a new named Service

func NewServiceHandler

func NewServiceHandler[I any, O any](fn ServiceHandlerFn[I, O], opts ...options.HandlerOption) *serviceHandler[I, O]

NewServiceHandler converts a function of signature ServiceHandlerFn into a handler on a Restate service.

func NewWorkflow added in v0.12.0

func NewWorkflow(name string, opts ...options.ServiceDefinitionOption) *workflow

NewWorkflow creates a new named Workflow

func NewWorkflowHandler added in v0.12.0

func NewWorkflowHandler[I any, O any](fn WorkflowHandlerFn[I, O], opts ...options.HandlerOption) *workflowHandler[I, O]

NewWorkflowHandler converts a function of signature WorkflowHandlerFn into the 'Run' handler on a Workflow. The handler will have access to a full WorkflowContext which may mutate state.

func NewWorkflowSharedHandler added in v0.12.0

func NewWorkflowSharedHandler[I any, O any](fn WorkflowSharedHandlerFn[I, O], opts ...options.HandlerOption) *workflowHandler[I, O]

NewWorkflowSharedHandler converts a function of signature ObjectSharedHandlerFn into a shared-mode handler on a Workflow. The handler will only have access to a WorkflowSharedContext which can only read a snapshot of state.

func PauseOnMaxAttempts added in v0.20.0

func PauseOnMaxAttempts() withOnMaxAttempts

PauseOnMaxAttempts pauses the invocation when the maximum number of attempts is reached.

func Rand added in v0.11.0

func Rand(ctx Context) *rand2.Rand

Rand returns a random source which will give deterministic results for a given invocation

This rand instance is not safe for use inside .Run()

func RandSource added in v0.21.0

func RandSource(ctx Context) rand2.Source

RandSource returns a random source to be used with math/rand/v2 implementations.

To create a random implementation, use `rand2.New(RandSource(ctx))`

This source instance is not safe for use inside .Run()

func RejectAwakeable added in v0.11.0

func RejectAwakeable(ctx Context, id string, reason error)

RejectAwakeable allows an awakeable (not necessarily from this service) to be rejected with a particular error.

func RejectSignal added in v0.25.0

func RejectSignal(ctx Context, invocationID string, name string, reason error)

RejectSignal rejects a signal on an invocation with a particular error.

func ResolveAwakeable added in v0.11.0

func ResolveAwakeable[T any](ctx Context, id string, value T, options ...options.ResolveAwakeableOption)

ResolveAwakeable allows an awakeable (not necessarily from this service) to be resolved with a particular value.

func ResolveSignal added in v0.25.0

func ResolveSignal[T any](ctx Context, invocationID string, name string, value T, options ...options.ResolveSignalOption)

ResolveSignal resolves a signal on an invocation with a particular value.

func Set added in v0.11.0

func Set[T any](ctx ObjectContext, key string, value T, options ...options.SetOption)

Set sets a value against a key, using the provided codec (defaults to JSON)

func UUID added in v0.21.0

func UUID(ctx Context) uuid.UUID

UUID returns a random UUID seeded deterministically for a given invocation.

This method should not be used inside .Run()

func Wait added in v0.21.0

func Wait(ctx Context, futs ...Future) iter.Seq2[Future, TerminalError]

Wait returns an iterator that yields Futures as they complete in order of completion. The iterator continues until all Futures have completed or a cancellation error occurs. If a cancellation error occurs, it is yielded as the final element with a nil Future.

Example:

func MyHandler(ctx restate.Context, input string) ([]string, error) {
	fut1 := restate.Service[string](ctx, "service1", "method1").RequestFuture(input)
	fut2 := restate.Service[string](ctx, "service2", "method2").RequestFuture(input)
	fut3 := restate.Service[string](ctx, "service3", "method3").RequestFuture(input)

	results := []string{}
	for fut, err := range restate.Wait(ctx, fut1, fut2, fut3) {
		if err != nil {
			return nil, err
		}
		result, err := fut.(restate.ResponseFuture[string]).Response()
		if err != nil {
			return nil, err
		}
		results = append(results, result)
	}
	return results, nil
}

func WaitFirst added in v0.21.0

func WaitFirst(ctx Context, futs ...Future) (resultFut Future, cancellationError TerminalError)

WaitFirst waits for the first Future to complete among the provided Futures and returns it. If the invocation is canceled, a cancellation error is returned.

Example:

func MyHandler(ctx restate.Context, input string) (string, error) {
	fut1 := restate.Service[string](ctx, "service1", "method1").RequestFuture(input)
	fut2 := restate.After(ctx, 5 * time.Second)
	fut3 := restate.Service[string](ctx, "service2", "method2").RequestFuture(input)

	firstComplete, err := restate.WaitFirst(ctx, fut1, fut2, fut3)
	if err != nil {
		return "", err
	}
	// Handle the first completed future
	switch firstComplete {
	case fut1:
		return fut1.Response()
	case fut2:
		return "", fmt.Errorf("timeout")
	case fut3:
		return fut3.Response()
	default:
		return "", fmt.Errorf("unknown future")
	}
}

func WithAbortTimeout added in v0.18.0

func WithAbortTimeout(abortTimeout time.Duration) withAbortTimeout

WithAbortTimeout sets the abort timeout duration for a service/handler.

This timer guards against stalled service/handler invocations that are supposed to terminate. The abort timeout is started after the inactivity timeout has expired and the service/handler invocation has been asked to gracefully terminate. Once the timer expires, it will abort the service/handler invocation.

This timer potentially *interrupts* user code. If the user code needs longer to gracefully terminate, then this value needs to be set accordingly.

This overrides the default abort timeout configured in the restate-server for all invocations to this service.

NOTE: You can set this field only if you register this service against restate-server >= 1.4, otherwise the service discovery will fail.

func WithCodec

func WithCodec(codec encoding.Codec) withCodec

WithCodec sets the encoding.Codec used to (de)serialise values. It applies to any operation that (de)serialises; on handlers and calls it sets both the input and output codec (override one with WithInputCodec / WithOutputCodec).

See also WithProto, WithBinary, WithJSON, WithProtoJSON.

func WithDelay added in v0.11.0

func WithDelay(delay time.Duration) withDelay

WithDelay is an SendOption to specify the duration to delay the request

func WithDocumentation added in v0.16.0

func WithDocumentation(documentation string) withDocumentation

WithDocumentation sets the handler/service documentation, shown in the UI and other Restate observability tools.

func WithEnableLazyState added in v0.18.0

func WithEnableLazyState(enableLazyState bool) withEnableLazyState

WithEnableLazyState enables or disables lazy state for a service/handler.

When set to true, lazy state will be enabled for all invocations to this service/handler. This is relevant only for workflows and virtual objects.

NOTE: You can set this field only if you register this service against restate-server >= 1.4, otherwise the service discovery will fail.

func WithHeaders added in v0.10.0

func WithHeaders(headers map[string]string) withHeaders

WithHeaders is an option to specify outgoing headers when making a call

func WithIdempotencyKey added in v0.16.0

func WithIdempotencyKey(idempotencyKey string) withIdempotencyKey

WithIdempotencyKey is an option to specify the idempotency key to set when making a call

func WithIdempotencyRetention added in v0.18.0

func WithIdempotencyRetention(idempotencyRetention time.Duration) withIdempotencyRetention

WithIdempotencyRetention sets the idempotency retention duration for a service/handler.

NOTE: You can set this field only if you register this service against restate-server >= 1.4, otherwise the service discovery will fail.

func WithInactivityTimeout added in v0.18.0

func WithInactivityTimeout(inactivityTimeout time.Duration) withInactivityTimeout

WithInactivityTimeout sets the inactivity timeout duration for a service/handler.

This timer guards against stalled invocations. Once it expires, Restate triggers a graceful termination by asking the invocation to suspend (which preserves intermediate progress).

The abort timeout is used to abort the invocation, in case it doesn't react to the request to suspend.

This overrides the default inactivity timeout configured in the restate-server for all invocations to this service.

NOTE: You can set this field only if you register this service against restate-server >= 1.4, otherwise the service discovery will fail.

func WithIngressPrivate added in v0.18.0

func WithIngressPrivate(ingressPrivate bool) withIngressPrivate

WithIngressPrivate sets whether the service/handler is private (not accessible from HTTP or Kafka ingress).

When set to true this service/handler cannot be invoked from the restate-server HTTP and Kafka ingress, but only from other services.

NOTE: You can set this field only if you register this service against restate-server >= 1.4, otherwise the service discovery will fail.

func WithInitialRetryInterval added in v0.16.0

func WithInitialRetryInterval(d time.Duration) withInitialRetryInterval

WithInitialRetryInterval sets the delay before the first retry attempt. The interval then grows by the factor set with WithRetryIntervalFactor, capped by WithMaxRetryInterval.

func WithInputCodec added in v0.25.0

func WithInputCodec(codec encoding.Codec) withInputCodec

WithInputCodec sets the encoding.Codec used to (de)serialise the input of a handler or call, independently of the output.

func WithInvocationRetryPolicy added in v0.20.0

func WithInvocationRetryPolicy(opts ...InvocationRetryPolicyOption) withInvocationRetryPolicy

WithInvocationRetryPolicy sets the invocation retry policy used by Restate when invoking this service/handler.

NOTE: You can set this field only if you register this service against restate-server >= 1.5, otherwise the service discovery will fail.

Unset fields inherit server defaults. The policy controls an exponential backoff with optional capping and a terminal action:

  • initial interval before the first retry attempt
  • exponentiation factor to compute the next retry delay
  • maximum interval cap
  • maximum attempts (initial call counts as the first attempt)
  • behavior when max attempts is reached (OnMaxAttempts: PAUSE | KILL)

func WithJournalRetention added in v0.18.0

func WithJournalRetention(journalRetention time.Duration) withJournalRetention

WithJournalRetention sets the journal retention duration for a service/handler.

The journal retention for invocations to this service/handler.

In case the request has an idempotency key, the idempotency retention caps the journal retention time.

NOTE: You can set this field only if you register this service against restate-server >= 1.4, otherwise the service discovery will fail.

func WithLimitKey added in v0.25.0

func WithLimitKey(limitKey string) withLimitKey

WithLimitKey sets the concurrency limit key when making a call.

func WithMaxRetryAttempts added in v0.16.0

func WithMaxRetryAttempts(maxAttempts uint) withMaxRetryAttempts

WithMaxRetryAttempts sets the maximum number of attempts before giving up retrying. The initial call counts as the first attempt.

func WithMaxRetryDuration added in v0.16.0

func WithMaxRetryDuration(d time.Duration) withMaxRetryDuration

WithMaxRetryDuration sets the maximum total time spent retrying before giving up.

func WithMaxRetryInterval added in v0.16.0

func WithMaxRetryInterval(d time.Duration) withMaxRetryInterval

WithMaxRetryInterval caps the delay between retry attempts.

func WithMetadata added in v0.16.0

func WithMetadata(metadataKey string, metadataValue string) errors.MetadataOption

WithMetadata adds the given key/value as metadata. It applies anywhere metadata is accepted: service/handler definitions (shown in the Admin API) and ToTerminalError. Multiple metadata options merge.

func WithMetadataMap added in v0.16.0

func WithMetadataMap(metadata map[string]string) errors.MetadataOption

WithMetadataMap adds the given metadata. It applies anywhere metadata is accepted: service/handler definitions (shown in the Admin API) and ToTerminalError. Multiple metadata options merge.

func WithMockContext added in v0.15.0

func WithMockContext(ctx MockableContext) ctxWrapper

WithMockContext wraps a MockableContext. To be used with *MockContext from the github.com/restatedev/sdk-go/x/mocks module.

func WithName added in v0.16.0

func WithName(name string) withName

WithName sets the operation name, shown in the UI and other Restate observability tools.

func WithOutputCodec added in v0.25.0

func WithOutputCodec(codec encoding.Codec) withOutputCodec

WithOutputCodec sets the encoding.Codec used to (de)serialise the output of a handler or call, independently of the input.

func WithRetryIntervalFactor added in v0.16.0

func WithRetryIntervalFactor(f float32) withRetryIntervalFactor

WithRetryIntervalFactor sets the multiplier applied to the retry interval after each attempt (e.g. 2 doubles the interval each time).

func WithScope added in v0.25.0

func WithScope(scope string) withScope

WithScope sets the scope within which invocations made through this client are routed.

It is a client-level option: pass it when constructing a client (e.g. via Service, Object or Workflow, or the equivalent ingress constructors) and it applies to every Request, RequestFuture and Send made through that client. An empty scope is a no-op, leaving the invocation unscoped.

func WithValue added in v0.23.0

func WithValue[T Context](restateCtx T, key, val any) T

WithValue is like context.WithValue, but wrapping the restate context

func WithWorkflowRetention added in v0.18.0

func WithWorkflowRetention(workflowCompletionRetention time.Duration) withWorkflowRetention

WithWorkflowRetention sets the workflow completion retention duration for a handler.

The retention duration for this workflow handler.

This is only valid when HandlerType == WORKFLOW.

NOTE: You can set this field only if you register this service against restate-server >= 1.4, otherwise the service discovery will fail.

func WrapContext added in v0.23.0

func WrapContext[T Context](restateCtx T, wrappedCtx context.Context) T

WrapContext wraps the provided Restate context with a context.Context, making sure all Context.Values from the wrappedCtx are accessible from the Restate context.

Types

type AfterFuture added in v0.11.0

type AfterFuture = restatecontext.AfterFuture

AfterFuture is returned by the After operation which allows you to do other work concurrently with the sleep.

func After

func After(ctx Context, d time.Duration, opts ...options.SleepOption) AfterFuture

After is an alternative to Sleep which allows you to complete other tasks concurrently with the sleep. This is particularly useful when combined with WaitFirst to race between the sleep and other Future operations.

type AttachFuture added in v0.16.0

type AttachFuture[O any] interface {
	// Response blocks on the response to the call and returns it or the associated error
	// It is *not* safe to call this in a goroutine - use Context.Select if you
	// want to wait on multiple results at once.
	Response() (O, TerminalError)
	restatecontext.Future
}

AttachFuture is a handle on a potentially not-yet completed call.

func AttachInvocation added in v0.16.0

func AttachInvocation[T any](ctx Context, invocationId string, options ...options.AttachOption) AttachFuture[T]

AttachInvocation attaches to the invocation with the given invocation id.

type AttachOption added in v0.19.0

type AttachOption = options.AttachOption

AttachOption is an option for AttachInvocation.

type AwakeableFuture added in v0.11.0

type AwakeableFuture[T any] interface {
	// Id returns the awakeable ID, which can be stored or sent to a another service
	Id() string
	// Result blocks on receiving the result of the awakeable, returning the value it was
	// resolved or otherwise returning the error it was rejected with.
	// It is *not* safe to call this in a goroutine - use Context.Select if you
	// want to wait on multiple results at once.
	Result() (T, TerminalError)
	restatecontext.Future
}

AwakeableFuture is a 'promise' to a future value or error, that can be resolved or rejected by other services.

func Awakeable

func Awakeable[T any](ctx Context, options ...options.AwakeableOption) AwakeableFuture[T]

Awakeable returns a Restate awakeable; a 'promise' to a future value or error, that can be resolved or rejected by other services.

type AwakeableOption added in v0.19.0

type AwakeableOption = options.AwakeableOption

AwakeableOption is an option for Awakeable.

type Client added in v0.11.0

type Client[I any, O any] interface {
	// RequestFuture makes a call and returns a handle on a future response
	RequestFuture(input I, options ...options.RequestOption) ResponseFuture[O]
	// Request makes a call and blocks on getting the response
	Request(input I, options ...options.RequestOption) (O, TerminalError)
	SendClient[I]
}

Client represents all the different ways you can invoke a particular service-method.

func Object

func Object[O any](ctx Context, service string, key string, method string, options ...options.ClientOption) Client[any, O]

Object gets an Object request client by service name, key and method name

func Service

func Service[O any](ctx Context, service string, method string, options ...options.ClientOption) Client[any, O]

Service gets a Service request client by service and method name

func WithRequestType added in v0.11.0

func WithRequestType[I any, O any](inner Client[any, O]) Client[I, O]

WithRequestType is primarily intended to be called from generated code, to provide type safety of input types. In other contexts it's generally less cumbersome to use Object and Service, as the output type can be inferred.

func Workflow added in v0.12.0

func Workflow[O any](ctx Context, service string, workflowID string, method string, options ...options.ClientOption) Client[any, O]

Workflow gets a Workflow request client by service name, workflow ID and method name

type ClientOption added in v0.11.0

type ClientOption = options.ClientOption

ClientOption is an option for a request/send client, applied at construction (e.g. via Service, Object or Workflow).

type Code added in v0.9.1

type Code = errors.Code

Code is a numeric status code for an error, matching HTTP status code semantics.

type Context

type Context interface {
	RunContext
	// contains filtered or unexported methods
}

Context is an extension of RunContext which is passed to Restate service handlers and enables interaction with Restate

type DurablePromise added in v0.12.0

type DurablePromise[T any] interface {
	// Result blocks on receiving the result of the Promise, returning the value it was
	// resolved or otherwise returning the error it was rejected with or a cancellation error.
	// It is *not* safe to call this in a goroutine - use Context.Select if you
	// want to wait on multiple results at once.
	Result() (T, TerminalError)
	// Peek returns the value of the promise if it has been resolved. If it has not been resolved,
	// the zero value of T is returned. To check explicitly for this case pass a pointer eg *string as T.
	// If the promise was rejected or the invocation was cancelled, an error is returned.
	Peek() (T, TerminalError)
	// Resolve resolves the promise with a value, returning an error if it was already completed
	// or if the invocation was cancelled.
	Resolve(value T) TerminalError
	// Reject rejects the promise with an error, returning an error if it was already completed
	// or if the invocation was cancelled.
	Reject(reason error) TerminalError
	restatecontext.Future
}

func Promise added in v0.12.0

func Promise[T any](ctx WorkflowSharedContext, name string, options ...options.PromiseOption) DurablePromise[T]

Promise returns a named Restate durable Promise that can be resolved or rejected during the workflow execution. The promise is bound to the workflow and will be persisted across suspensions and retries.

type ErrorCodeOption added in v0.25.0

type ErrorCodeOption = errors.CodeOption

ErrorCodeOption sets the Code on an error. It is shared: pass it to either ToTerminalError or ToRetryableError.

func WithErrorCode

func WithErrorCode(code Code) ErrorCodeOption

WithErrorCode sets the Code of a terminal or retryable error. Pass it to ToTerminalError or ToRetryableError.

type Future added in v0.21.0

type Future = restatecontext.Future

Future is a marker interface for futures.

type GetOption added in v0.19.0

type GetOption = options.GetOption

GetOption is an option for Get.

type HandlerOption added in v0.19.0

type HandlerOption = options.HandlerOption

HandlerOption is an option applied to a single handler at registration.

type Invocation added in v0.16.0

type Invocation = restatecontext.Invocation

type InvocationRetryPolicy added in v0.20.0

type InvocationRetryPolicy = options.InvocationRetryPolicy

Retry policy types

type InvocationRetryPolicyOption added in v0.20.0

type InvocationRetryPolicyOption = options.InvocationRetryPolicyOption

InvocationRetryPolicyOption configures an InvocationRetryPolicy.

type MockableContext added in v0.25.0

type MockableContext = restatecontext.Context

MockableContext is the context interface that test mocks implement. To be used with *MockContext from the github.com/restatedev/sdk-go/x/mocks module.

type ObjectContext

type ObjectContext interface {
	ObjectSharedContext
	// contains filtered or unexported methods
}

ObjectContext is an extension of ObjectSharedContext which is passed to exclusive-mode Virtual Object handlers. giving mutable access to state.

type ObjectHandlerFn

type ObjectHandlerFn[I any, O any] func(ctx ObjectContext, input I) (O, error)

ObjectHandlerFn is the signature for a Virtual Object exclusive handler function

type ObjectSharedContext

type ObjectSharedContext interface {
	Context
	// contains filtered or unexported methods
}

ObjectSharedContext is an extension of Context which is passed to shared-mode Virtual Object handlers, giving read-only access to a snapshot of state.

type ObjectSharedHandlerFn

type ObjectSharedHandlerFn[I any, O any] func(ctx ObjectSharedContext, input I) (O, error)

ObjectSharedHandlerFn is the signature for a Virtual Object shared-mode handler function

type OnMaxAttempts added in v0.20.0

type OnMaxAttempts = options.OnMaxAttempts

type PromiseOption added in v0.19.0

type PromiseOption = options.PromiseOption

PromiseOption is an option for Promise.

type Request added in v0.9.1

type Request = restatecontext.Request

Request contains a set of information about the request that started an invocation

type RequestOption added in v0.19.0

type RequestOption = options.RequestOption

RequestOption is an option for a Client.Request or Client.RequestFuture call.

type ResolveAwakeableOption added in v0.19.0

type ResolveAwakeableOption = options.ResolveAwakeableOption

ResolveAwakeableOption is an option for ResolveAwakeable.

type ResolveSignalOption added in v0.25.0

type ResolveSignalOption = options.ResolveSignalOption

ResolveSignalOption is an option for ResolveSignal.

type ResponseFuture

type ResponseFuture[O any] interface {
	// Response blocks on the response to the call and returns it or the associated error
	// It is *not* safe to call this in a goroutine - use Context.Select if you
	// want to wait on multiple results at once.
	Response() (O, TerminalError)
	Invocation
	restatecontext.Future
}

ResponseFuture is a handle on a potentially not-yet completed outbound call.

type RetryableError added in v0.25.0

type RetryableError = errors.RetryableError

RetryableError finishes an attempt with a non-terminal failure: the invocation (or a Run closure) is retried rather than completed. It carries a Code and a message, wraps the underlying error, and implements the error interface. Returning one from a handler or Run closure is equivalent to returning any non-terminal error - Restate retries - except that its code is carried through. Use RetryableErrorf or ToRetryableError to construct one.

func AsRetryableError added in v0.25.0

func AsRetryableError(err error) RetryableError

AsRetryableError casts the current error to RetryableError if any.

func RetryableErrorf added in v0.25.0

func RetryableErrorf(format string, a ...any) RetryableError

RetryableErrorf builds a RetryableError whose message is fmt.Sprintf(format, a...). To attach a code, build the message with fmt.Errorf and pass it to ToRetryableError with WithErrorCode.

func ToRetryableError added in v0.25.0

func ToRetryableError(err error, opts ...RetryableErrorOption) RetryableError

ToRetryableError converts err into a RetryableError. It returns nil if err is nil; if err already is, or wraps, a RetryableError and no options are given, that RetryableError is returned unchanged; otherwise err is wrapped (errors.Unwrap, errors.Is and errors.As reach err through the result). The code defaults to 500 unless set with WithErrorCode.

type RetryableErrorOption added in v0.25.0

type RetryableErrorOption = errors.RetryableErrorOption

RetryableErrorOption customizes a RetryableError. Pass it to ToRetryableError.

type RunAsyncFuture added in v0.17.0

type RunAsyncFuture[T any] interface {
	// Result blocks on receiving the RunAsync result, returning the value it was
	// resolved or otherwise returning the error it was rejected with.
	// It is *not* safe to call this in a goroutine - use Context.Select if you
	// want to wait on multiple results at once.
	Result() (T, TerminalError)
	restatecontext.Future
}

RunAsyncFuture is a 'promise' for a RunAsync operation.

func RunAsync added in v0.17.0

func RunAsync[T any](ctx Context, fn func(ctx RunContext) (T, error), options ...options.RunOption) RunAsyncFuture[T]

RunAsync runs the function (fn), storing final results (including terminal errors) durably in the journal, or otherwise for transient errors stopping execution so Restate can retry the invocation. Replays will produce the same value, so all non-deterministic operations (eg, generating a unique ID) *must* happen inside Run blocks.

This is similar to Run, but it returns a RunAsyncFuture instead that can be used within a WaitFirst, Wait.

IMPORTANT: Only use the RunContext parameter provided to the function, NOT the handler's Context. See the Run function documentation for detailed examples and guidelines.

type RunContext

type RunContext = restatecontext.RunContext

RunContext is passed to Run closures and provides the limited set of Restate operations that are safe to use there.

type RunOption added in v0.19.0

type RunOption = options.RunOption

RunOption is an option for Run, RunAsync and RunVoid.

type SendClient

type SendClient[I any] interface {
	// Send makes a one-way call which is executed in the background
	Send(input I, options ...options.SendOption) Invocation
}

SendClient allows making one-way invocations

func ObjectSend added in v0.11.0

func ObjectSend(ctx Context, service string, key string, method string, options ...options.ClientOption) SendClient[any]

ObjectSend gets an Object send client by service name, key and method name

func ServiceSend added in v0.11.0

func ServiceSend(ctx Context, service string, method string, options ...options.ClientOption) SendClient[any]

ServiceSend gets a Service send client by service and method name

func WorkflowSend added in v0.12.0

func WorkflowSend(ctx Context, service string, workflowID string, method string, options ...options.ClientOption) SendClient[any]

WorkflowSend gets a Workflow send client by service name, workflow ID and method name

type SendOption added in v0.19.0

type SendOption = options.SendOption

SendOption is an option for a SendClient.Send call.

type ServiceDefinition added in v0.10.0

type ServiceDefinition interface {
	// Name returns the name of the service described in this definition
	Name() string
	// Type returns the type of this service definition (Service or Virtual Object)
	Type() internal.ServiceType
	// Handlers returns the set of handlers associated with this service definition
	Handlers() map[string]restatecontext.Handler
	// GetOptions returns the configured options
	GetOptions() *options.ServiceDefinitionOptions
	// ConfigureHandler lets you customize the handler configuration, adding per handler options.
	// Panics if the handler doesn't exist.
	ConfigureHandler(name string, opts ...options.HandlerOption) ServiceDefinition
}

ServiceDefinition is the set of methods implemented by both services and virtual objects

func Reflect added in v0.10.0

Reflect converts a struct with methods into a service definition where each correctly-typed and exported method of the struct will become a handler in the definition. The service name defaults to the name of the struct, but this can be overidden by providing a `ServiceName() string` method. The handler name is the name of the method. Handler methods should have one of the following signatures: - (ctx, I) (O, error) - (ctx, I) (O) - (ctx, I) (error) - (ctx, I) - (ctx) - (ctx) (error) - (ctx) (O) - (ctx) (O, error) Where ctx is WorkflowContext, WorkflowSharedContext, ObjectContext, ObjectSharedContext or Context. Other signatures are ignored. Signatures without an I or O type will be treated as if Void was provided. This function will panic if a mixture of object service and workflow method signatures or opts are provided, or if multiple WorkflowContext methods are defined.

Input types will be deserialised with the provided codec (defaults to JSON) except when they are Void, in which case no input bytes or content type may be sent. Output types will be serialised with the provided codec (defaults to JSON) except when they are Void, in which case no data will be sent and no content type set.

type ServiceDefinitionOption added in v0.10.0

type ServiceDefinitionOption = options.ServiceDefinitionOption

ServiceDefinitionOption is an option applied to a whole service/object/workflow at registration.

type ServiceHandlerFn

type ServiceHandlerFn[I any, O any] func(ctx Context, input I) (O, error)

ServiceHandlerFn is the signature for a Service handler function

type SetOption added in v0.19.0

type SetOption = options.SetOption

SetOption is an option for Set.

type SignalFuture added in v0.25.0

type SignalFuture[T any] interface {
	// Result blocks on receiving the result of the signal, returning the value it was
	// resolved with or the error it was rejected with.
	// It is *not* safe to call this in a goroutine - use Context.Select if you
	// want to wait on multiple results at once.
	Result() (T, TerminalError)
	restatecontext.Future
}

SignalFuture is a promise to a future signal value or error.

func Signal added in v0.25.0

func Signal[T any](ctx Context, name string, options ...options.SignalOption) SignalFuture[T]

Signal returns a future for a signal by name.

type SignalOption added in v0.25.0

type SignalOption = options.SignalOption

SignalOption is an option for Signal.

type SleepOption added in v0.19.0

type SleepOption = options.SleepOption

SleepOption is an option for Sleep and After.

type StringMap added in v0.25.0

type StringMap = stringmap.Map

StringMap is a read-only, deterministically-ordered view over string key/value pairs.

Iterating a StringMap is deterministic (key-sorted), unlike ranging over a Go map. Use ToMap when you need a plain map to hand to external code.

type TerminalError

type TerminalError = errors.TerminalError

TerminalError finishes an invocation (or a Run function) with a failure result instead of being retried. By default, Restate retries the invocation or Run function forever unless a terminal error is returned.

It carries a status code, a message and optional metadata, accessible via the Code, Message and Metadata methods, and implements the error interface. Use TerminalErrorf or ToTerminalError to construct one.

func AsTerminalError added in v0.25.0

func AsTerminalError(err error) TerminalError

AsTerminalError casts the current error to TerminalError if any.

func Get added in v0.11.0

func Get[T any](ctx ObjectSharedContext, key string, options ...options.GetOption) (output T, err TerminalError)

Get gets the value for a key. If there is no associated value with key, the zero value is returned. To check explicitly for this case pass a pointer eg *string as T. If the invocation was cancelled while obtaining the state (only possible if eager state is disabled), a cancellation error is returned.

func Keys added in v0.11.0

Keys retrieves all the state keys set inside a virtual object instance.

func Run added in v0.11.0

func Run[T any](ctx Context, fn func(ctx RunContext) (T, error), options ...options.RunOption) (output T, err TerminalError)

Run runs the function (fn), storing final results (including terminal errors) durably in the journal, or otherwise for transient errors stopping execution so Restate can retry the invocation. Replays will produce the same value, so all non-deterministic operations (eg, generating a unique ID) *must* happen inside Run blocks.

Inside Run blocks, you can only:

  • Perform non-deterministic operations (random number generation, external API calls, etc.)
  • Use standard Go operations (math, string manipulation, etc.)

You CANNOT use inside Run blocks:

  • Any Restate SDK operations that require the handler Context

See: https://docs.restate.dev/develop/go/durable-steps

IMPORTANT: Only use the RunContext parameter provided to the function, NOT the handler's Context. The RunContext parameter intentionally shadows the handler context to prevent accidental misuse. Using the handler context inside Run leads to concurrency issues and undefined behavior.

Example:

func (s *Service) MyHandler(ctx restate.Context, input string) (string, error) {
	result, err := restate.Run(ctx, func(ctx restate.RunContext) (string, error) {
		// Use the RunContext parameter 'ctx' here - it shadows the handler context
		return doNonDeterministicOperation(ctx)
	})
	return result, err
}

Example (INCORRECT - DO NOT DO THIS):

func (s *Service) MyHandler(ctx restate.Context, input string) (string, error) {
	result, err := restate.Run(ctx, func(runCtx restate.RunContext) (string, error) {
		// WRONG: Using handler context 'ctx' instead of 'runCtx'
		return doNonDeterministicOperation(ctx)  // This will cause concurrency issues!
	})
	return result, err
}

func RunVoid added in v0.22.0

func RunVoid(ctx Context, fn func(ctx RunContext) error, options ...options.RunOption) TerminalError

RunVoid runs the function (fn), storing final results (including terminal errors) durably in the journal, or otherwise for transient errors stopping execution so Restate can retry the invocation. Replays will produce the same value, so all non-deterministic operations (eg, generating a unique ID) *must* happen inside RunVoid blocks.

This is similar to Run, but for functions that don't return a value.

IMPORTANT: Only use the RunContext parameter provided to the function, NOT the handler's Context. See the Run function documentation for detailed examples and guidelines.

func Sleep added in v0.11.0

func Sleep(ctx Context, d time.Duration, opts ...options.SleepOption) TerminalError

Sleep for the duration d. Can return a terminal error in the case where the invocation was cancelled mid-sleep.

func TerminalErrorf added in v0.11.0

func TerminalErrorf(format string, a ...any) TerminalError

TerminalErrorf builds a TerminalError whose message is fmt.Sprintf(format, a...). To attach a code or metadata, build the message with fmt.Errorf and pass it to ToTerminalError with the relevant options.

func ToTerminalError added in v0.25.0

func ToTerminalError(err error, opts ...TerminalErrorOption) TerminalError

ToTerminalError converts err into a TerminalError, so that returning it from a handler or Run finishes the invocation with a failure result instead of being retried.

IMPORTANT: this does NOT wrap err. A TerminalError carries no nested error and is not part of err's chain: errors.Unwrap, errors.Is and errors.As will not reach err through the result. Only the message, err.Error(), is copied.

It returns nil if err is nil; if err already is, or wraps, a TerminalError and no options are given, that TerminalError is returned unchanged. The code defaults to 500 unless set with WithErrorCode; metadata can be attached with WithMetadata.

type TerminalErrorOption added in v0.25.0

type TerminalErrorOption = errors.TerminalErrorOption

TerminalErrorOption customizes a TerminalError. Pass it to ToTerminalError.

type Void

type Void = encoding.Void

Void is a placeholder to signify 'no value' where a type is otherwise needed. It can be used in several contexts:

  1. Input types for handlers - the request payload codec will reject input at the ingress
  2. Output types for handlers - the response payload codec will send no bytes and set no content-type
  3. Input for a outgoing Request or Send - no bytes will be sent
  4. The output type for an outgoing Request - the response body will be ignored. A pointer is also accepted.
  5. The output type for an awakeable - the result body will be ignored. A pointer is also accepted.

type WaitIterator added in v0.21.0

type WaitIterator = restatecontext.WaitIterator

WaitIterator is an iterator over a list of blocking Restate operations that are running in the background. See WaitIter for more details.

func WaitIter added in v0.21.0

func WaitIter(ctx Context, futs ...Future) WaitIterator

WaitIter returns an iterator that allows manual control over waiting for multiple Futures to complete. This is the low-level primitive that WaitFirst and Wait are built on top of. Call Next() to wait for the next Future to complete, then use Value() to retrieve it and Err() to check for errors.

Example:

func MyHandler(ctx restate.Context, input string) (string, error) {
	fut1 := restate.Service[string](ctx, "service1", "method1").RequestFuture(input)
	fut2 := restate.Service[string](ctx, "service2", "method2").RequestFuture(input)

	iter := restate.WaitIter(ctx, fut1, fut2)
	for iter.Next() {
		fut := iter.Value()
		// Process each future as it completes
		if fut == fut1 {
			result, _ := fut1.Response()
			fmt.Printf("fut1 completed with: %s\n", result)
		}
	}
	if err := iter.Err(); err != nil {
		return "", err
	}
	return "all done", nil
}

type WorkflowContext added in v0.12.0

type WorkflowContext interface {
	WorkflowSharedContext
	ObjectContext
	// contains filtered or unexported methods
}

WorkflowContext is an extension of WorkflowSharedContext and ObjectContext which is passed to Workflow 'run' handlers, giving mutable access to state.

type WorkflowHandlerFn added in v0.12.0

type WorkflowHandlerFn[I any, O any] func(ctx WorkflowContext, input I) (O, error)

ObjectHandlerFn is the signature for a Workflow 'Run' handler function

type WorkflowSharedContext added in v0.12.0

type WorkflowSharedContext interface {
	ObjectSharedContext
	// contains filtered or unexported methods
}

WorkflowSharedContext is an extension of ObjectSharedContext which is passed to shared-mode Workflow handlers, giving read-only access to a snapshot of state.

type WorkflowSharedHandlerFn added in v0.12.0

type WorkflowSharedHandlerFn[I any, O any] func(ctx WorkflowSharedContext, input I) (O, error)

WorkflowSharedHandlerFn is the signature for a Workflow shared handler function

Directories

Path Synopsis
examples
otel module
errors
Package errors holds the SDK's error model.
Package errors holds the SDK's error model.
log
stringmap
Package stringmap provides a read-only, deterministically-ordered view over a set of string key/value pairs.
Package stringmap provides a read-only, deterministically-ordered view over a set of string key/value pairs.
testing module
x
mocks module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL