restate

package module
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2024 License: MIT Imports: 13 Imported by: 32

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. This SDK has not yet seen a stable release and APIs are subject to change. Feedback is welcome via issues and in Discord.

Features implemented

  • Log replay (resume of execution on failure)
  • State (set/get/clear/clear-all/keys)
  • Remote service call over restate runtime
  • Delayed execution of remote services
  • Sleep
  • Run
  • Awakeable
  • Shared object handlers
  • Workflows

Basic usage

Please check example for a fully working example based on the [TypeScript ticket reservation example] (https://github.com/restatedev/examples/tree/main/patterns-use-cases/ticket-reservation/ticket-reservation-typescript)

How to use the example

Download and run restate 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 --force -y 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

Versions

This library follows Semantic Versioning.

The compatibility with Restate is described in the following table:

Restate Server\sdk-go 0.9
1.0

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 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 ErrorCode

func ErrorCode(err error) errors.Code

ErrorCode returns Code associated with error, defaulting to 500

func Get added in v0.11.0

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

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 IsTerminalError

func IsTerminalError(err error) bool

IsTerminalError checks if err is terminal - 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. This is a no-op and is always safe to call.

func Keys added in v0.11.0

func Keys(ctx ObjectSharedContext) ([]string, error)

If the invocation was cancelled while obtaining the state (only possible if eager state is disabled), a cancellation error is returned.

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 Rand added in v0.11.0

func Rand(ctx Context) *rand.Rand

Rand returns a random source which will give deterministic results for a given invocation The source wraps the stdlib rand.Rand but with some extra helper methods This source is not safe for use inside .Run()

func RejectAwakeable added in v0.11.0

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

ResolveAwakeable allows an awakeable (not necessarily from this service) to be rejected 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 Run added in v0.11.0

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

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.

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 Sleep added in v0.11.0

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

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

func TerminalError

func TerminalError(err error, code ...errors.Code) error

TerminalError returns a terminal error with optional code. Code is optional but only one code is allowed. By default, restate will retry the invocation or Run function forever unless a terminal error is returned

func TerminalErrorf added in v0.11.0

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

TerminalErrorf is a shorthand for combining fmt.Errorf with TerminalError

func WithCodec

func WithCodec(codec encoding.Codec) withCodec

WithCodec is an option that can be provided to many different functions that perform (de)serialisation in order to specify a custom codec with which to (de)serialise instead of the default of JSON.

See also WithProto, WithBinary, WithJSON.

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 WithErrorCode

func WithErrorCode(err error, code Code) error

WithErrorCode returns an error with specific Code attached.

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 WithPayloadCodec

func WithPayloadCodec(codec encoding.PayloadCodec) withPayloadCodec

WithPayloadCodec is an option that can be provided to handler/service options in order to specify a custom encoding.PayloadCodec with which to (de)serialise and set content-types instead of the default of JSON.

See also WithProto, WithBinary, WithJSON.

Types

type AfterFuture added in v0.11.0

type AfterFuture interface {
	// Done blocks waiting on the remaining duration of the sleep.
	// It is *not* safe to call this in a goroutine - use Context.Select if you want to wait on multiple
	// results at once. Can return a terminal error in the case where the invocation was cancelled mid-sleep,
	// hence Done() should always be called, even after using Context.Select.
	Done() error
	futures.Selectable
}

After is a handle on a Sleep operation which allows you to do other work concurrently with the sleep.

func After

func After(ctx Context, d time.Duration) 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 Select to race between the sleep and other Selectable operations.

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, storing the value it was
	// resolved with in output 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, error)
	futures.Selectable
}

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 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, error)
	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.

type ClientOption added in v0.11.0

type ClientOption = options.ClientOption

re-export for use in generated code

type Code added in v0.9.1

type Code = errors.Code

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

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 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-mode handler function

type ObjectSharedContext

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

ObjectContext 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)

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

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, error)
	futures.Selectable
}

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

type RunContext

type RunContext interface {
	context.Context

	// Log obtains a handle on a slog.Logger which already has some useful fields (invocationID and method)
	// By default, this logger will not output messages if the invocation is currently replaying
	// The log handler can be set with `.WithLogger()` on the server object
	Log() *slog.Logger

	// Request gives extra information about the request that started this invocation
	Request() *state.Request
}

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

type Selectable

type Selectable = futures.Selectable

type Selector

type Selector interface {
	// Remaining returns whether there are still operations that haven't been returned by Select().
	// There will always be exactly the same number of results as there were operations
	// given to Context.Select
	Remaining() bool
	// Select blocks on the next completed operation or returns nil if there are none left
	Select() futures.Selectable
}

Selector is an iterator over a list of blocking Restate operations that are running in the background.

func Select added in v0.11.0

func Select(ctx Context, futs ...futures.Selectable) Selector

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)
}

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]

Service gets a Service send client by service and method name

type ServiceDefinition added in v0.10.0

type ServiceDefinition interface {
	Name() string
	Type() internal.ServiceType
	// Set of handlers associated with this service definition
	Handlers() map[string]state.Handler
}

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 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 and service method signatures or opts are provided.

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

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

Directories

Path Synopsis
examples
codegen command
otel module
generated
log
wire
wire implements the grpc wire protocol that is used later on by the state machine to communicate with restate runtime.
wire implements the grpc wire protocol that is used later on by the state machine to communicate with restate runtime.
protoc-gen-go-restate is a plugin for the Google protocol buffer compiler to generate Restate servers and clients.
protoc-gen-go-restate is a plugin for the Google protocol buffer compiler to generate Restate servers and clients.

Jump to

Keyboard shortcuts

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