Documentation
¶
Overview ¶
Package flow is the Go SDK for clevix-worker, a durable workflow engine on Cloudflare. Its API follows Inngest's inngestgo.
Make a client with NewClient, add functions with CreateFunction, and serve them with client.Serve(), which returns an http.Handler for your app's one endpoint (for example /api/flow). Steps are in the step package, parallel steps in the group package.
Index ¶
- Constants
- Variables
- func BoolPtr(b bool) *bool
- func IntPtr(i int) *int
- func NoRetryError(err error) error
- func RetryAtError(err error, at time.Time) error
- func StrPtr(s string) *string
- type AppManifest
- type BatchEvents
- type CancelOn
- type CancelOpts
- type CancelResult
- type Client
- func (c *Client) AppID() string
- func (c *Client) Close()
- func (c *Client) Manifest(serveURL string) AppManifest
- func (c *Client) ManifestHash() string
- func (c *Client) Realtime() Realtime
- func (c *Client) Runs() Runs
- func (c *Client) Send(ctx context.Context, event Event) (string, error)
- func (c *Client) SendMany(ctx context.Context, events []Event) ([]string, error)
- func (c *Client) Serve() http.Handler
- func (c *Client) Start(ctx context.Context, functionID string, opts StartOpts) (StartResult, error)
- func (c *Client) Streams() Streams
- func (c *Client) Sync(ctx context.Context, serveURL string) (int, []byte, error)
- type ClientOpts
- type Concurrency
- type Debounce
- type Event
- type FailedEventData
- type FunctionConfig
- type FunctionOpts
- type GenericEvent
- type Handler
- type Input
- type InputCtx
- type ListRunsOpts
- type MultipleTriggers
- type Priority
- type RateLimit
- type Realtime
- func (r Realtime) Publish(ctx context.Context, channel, topic string, data any) error
- func (r Realtime) PublishMany(ctx context.Context, messages []RealtimeOut) error
- func (r Realtime) Subscribe(ctx context.Context, opts SubscribeOpts) (stop func(), err error)
- func (r Realtime) Token(ctx context.Context, channel string, topics ...string) (RealtimeToken, error)
- func (r Realtime) TokenMany(ctx context.Context, channels []string, topics ...string) (RealtimeToken, error)
- type RealtimeMessage
- type RealtimeOut
- type RealtimeState
- type RealtimeToken
- type RunCounts
- type RunPage
- type RunSummary
- type Runs
- func (r Runs) Cancel(ctx context.Context, opts CancelOpts) (CancelResult, error)
- func (r Runs) Counts(ctx context.Context, functionID string) (RunCounts, error)
- func (r Runs) List(ctx context.Context, opts ListRunsOpts) (RunPage, error)
- func (r Runs) Singleton(ctx context.Context, functionID string, key any) (SingletonRun, error)
- type SDKInfo
- type ServableFunction
- type Singleton
- type SingletonRun
- type StartOpts
- type StartResult
- type StepError
- type StreamItem
- type StreamOpenOpts
- type StreamSnapshot
- type StreamToken
- type Streams
- func (s Streams) Append(ctx context.Context, id string, items ...any) ([]string, error)
- func (s Streams) Close(ctx context.Context, id string, end any, grace time.Duration) (closed bool, err error)
- func (s Streams) Delete(ctx context.Context, id string) (deleted bool, err error)
- func (s Streams) Open(ctx context.Context, id string, opts StreamOpenOpts) (created bool, err error)
- func (s Streams) Read(ctx context.Context, id, after string) iter.Seq2[StreamItem, error]
- func (s Streams) Snapshot(ctx context.Context, id, after string) (*StreamSnapshot, error)
- func (s Streams) Token(ctx context.Context, id string) (StreamToken, error)
- type SubscribeOpts
- type Throttle
- type Timeouts
- type Trigger
- type Triggerable
Constants ¶
const DefaultBaseURL = "https://worker.flow.clevixstudio.com"
DefaultBaseURL is the engine URL when neither ClientOpts.BaseURL nor FLOW_BASE_URL is set. Self-hosters set FLOW_BASE_URL.
const Version = "0.7.0"
Version is this SDK's version, sent in the manifest.
Variables ¶
var ErrStreamClosed = errors.New("flow: stream is closed")
ErrStreamClosed is the error for an append to a closed stream. Check for it with errors.Is.
var ErrStreamGone = errors.New("flow: stream is gone")
ErrStreamGone is the error for a stream that does not exist: never opened, deleted, or past its TTL or grace time. Check for it with errors.Is.
Functions ¶
func NoRetryError ¶
NoRetryError wraps err so it is not retried. Returned from a step.Run callback, the step fails at once. Returned from the handler, the run fails at once.
func RetryAtError ¶
RetryAtError wraps err so the next attempt runs at the given time.
Types ¶
type AppManifest ¶
type AppManifest struct {
AppID string `json:"appId"`
// URL is left out of the sync at boot: the engine keeps the URL it has.
URL string `json:"url,omitempty"`
SDK *SDKInfo `json:"sdk,omitempty"`
Functions []FunctionConfig `json:"functions"`
// ManifestHash is the SDK's hash of SDK and Functions (see ManifestHash).
ManifestHash string `json:"manifestHash,omitempty"`
}
AppManifest is what the app sends on sync and returns on GET.
type BatchEvents ¶
BatchEvents runs the function with up to MaxSize events, or after Timeout.
type CancelOn ¶
type CancelOn struct {
Event string
// Match is a field path in both events, for example "data.orderId".
Match *string
// If is an expression over event (the trigger) and async (the new event).
If *string
// Timeout stops listening after this long. Zero means as long as the run lives.
Timeout time.Duration
}
CancelOn cancels a run when a matching event arrives.
type CancelOpts ¶ added in v0.7.0
type CancelOpts struct {
// RunID cancels one run.
RunID string
// Function is the function's own ID. Needed with SingletonKey and Tag.
Function string
// SingletonKey cancels the run that holds this singleton key. Set when
// not nil.
SingletonKey any
// Tag cancels the runs with this tag value: one name and its value.
Tag map[string]string
// Status, with Tag only, cancels only runs in these active statuses.
// Nil: every active status. Empty but not nil is an error.
Status []string
// Cursor, with Tag only, goes on after the page before: pass
// CancelResult.Next. Sent when not empty.
Cursor string
}
CancelOpts says which runs Runs().Cancel cancels. Set exactly one of RunID, SingletonKey and Tag.
type CancelResult ¶ added in v0.7.0
type CancelResult struct {
// Cancelled are the runs it cancelled.
Cancelled []string `json:"cancelled"`
// NotActive are runs that had ended already, or are not this app's.
NotActive []string `json:"notActive"`
// More is true when more runs match a Tag than one call cancels (500).
// Call again with Next as CancelOpts.Cursor.
More bool `json:"more"`
// Next is the cursor for the next call by Tag. Empty when there is no
// more.
Next string `json:"next"`
}
CancelResult says what Runs().Cancel did.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client holds an app's functions and talks to the engine.
func NewClient ¶
func NewClient(opts ClientOpts) (*Client, error)
NewClient makes a client. It fails if AppID or a signing key is not valid.
func (*Client) Close ¶ added in v0.6.5
func (c *Client) Close()
Close stops the sync checks that Serve started, and waits until a check on its way has ended. Call it when the server shuts down. Serve still answers after Close; it just checks no more.
func (*Client) Manifest ¶
func (c *Client) Manifest(serveURL string) AppManifest
Manifest builds the app's manifest with serveURL as the app URL.
func (*Client) ManifestHash ¶ added in v0.6.5
ManifestHash is the SDK's hash of the app's manifest: "v1:" and the sha256 of its SDK and functions as JSON with sorted keys. The URL is left out, so every copy of the app has the same hash. The engine stores it on sync, and the sync at boot syncs only when the engine has a different one.
func (*Client) Serve ¶
Serve returns the http.Handler for the app's one endpoint:
- POST runs a function (signed by the engine).
- PUT syncs: sends the manifest to the engine and returns its answer. Call it on deploy, for example: curl -X PUT https://app/api/flow
- GET returns the manifest (signed GET with an empty body).
Without a signing key, and not in dev mode, it answers every request with 500 NoSigningKey.
The first call also starts the sync at boot in the background (see ClientOpts.NoSyncOnBoot), so call Serve after the functions are made. The checks go on until Close.
func (*Client) Start ¶ added in v0.7.0
Start starts a run of one of this app's functions now, without an event name to match (POST /v1/functions/{id}/start). functionID is the function's own ID, as in FunctionOpts.ID. Singleton, throttle, concurrency and priority apply; rate limit, debounce and batching do not.
The run exists when Start returns, so a Runs().Cancel right after it can not miss it. Start does not fail when no run started: then Started is false and Reason says why. It fails for any answer other than 200 (for example 429 when the workspace sends too many events a second).
type ClientOpts ¶
type ClientOpts struct {
// AppID names the app. Required.
AppID string
// SigningKey checks calls from the engine and signs sync. Env: FLOW_SIGNING_KEY.
SigningKey *string
// SigningKeyFallback is the old key while rotating. Env: FLOW_SIGNING_KEY_FALLBACK.
SigningKeyFallback *string
// EventKey is used to send events. Env: FLOW_EVENT_KEY.
EventKey *string
// BaseURL is the engine URL. Env: FLOW_BASE_URL. Default: DefaultBaseURL.
BaseURL *string
// Dev turns off signature checks. Env: FLOW_DEV=1.
Dev *bool
// HTTPClient is used for every call to the engine, and for sockets
// (Subscribe, Streams().Read). Default: http.DefaultClient.
HTTPClient *http.Client
// NoStreaming turns off streamed answers: answers are sent whole at the end.
// By default a POST answer is streamed when the engine asks for it, so a
// proxy in front of the app does not end a long step (see docs/protocol.md).
NoStreaming bool
// HeartbeatInterval is the time between heartbeats in a streamed answer.
// Default: 20s. At least 1ms. It also moves the server's write deadline
// (http.Server.WriteTimeout) on, so that does not end a long step.
HeartbeatInterval time.Duration
// NoSyncOnBoot turns off the sync at boot. By default Serve checks in the
// background whether the engine has this app's manifest, and syncs when it
// changed, so a deploy needs no Resync. Then it checks again every
// checkEveryMs the engine gives (5 min) until Client.Close. It needs the
// signing key; without one it does nothing.
NoSyncOnBoot bool
}
ClientOpts configures a client. Fields left nil are read from environment variables; values set here win.
type Concurrency ¶
type Concurrency struct {
Limit int `json:"limit"`
Key *string `json:"key,omitempty"`
Scope string `json:"scope,omitempty"`
}
Concurrency limits how many steps of the function run at once. Key is an expression over event; Scope is "fn" (default), "env" or "account".
type Debounce ¶
Debounce waits for Period of quiet before running, with the last event. Timeout is the longest it may wait in all (zero: no limit).
type FailedEventData ¶ added in v0.7.0
type FailedEventData struct {
// FunctionID is the failed function's full ID, "<appId>-<id>".
FunctionID string `json:"function_id"`
RunID string `json:"run_id"`
// Error is why the run failed.
Error *StepError `json:"error"`
// Event is the failed run's trigger event, as JSON.
Event json.RawMessage `json:"event"`
// Attempts is how many times the step that failed the run was tried. It
// is 0 when no step try failed it (for example a finish timeout).
Attempts int `json:"attempts"`
}
FailedEventData is the data of an inngest/function.failed event. Use it as the T of a failure function (see CreateFunction).
type FunctionConfig ¶
type FunctionConfig struct {
ID string `json:"id"`
Name string `json:"name,omitempty"`
Triggers []Trigger `json:"triggers"`
Retries *int `json:"retries,omitempty"`
Timeouts *timeoutsJSON `json:"timeouts,omitempty"`
CancelOn []cancelOnJSON `json:"cancelOn,omitempty"`
Concurrency []Concurrency `json:"concurrency,omitempty"`
Throttle *throttleJSON `json:"throttle,omitempty"`
RateLimit *rateLimitJSON `json:"rateLimit,omitempty"`
Debounce *debounceJSON `json:"debounce,omitempty"`
BatchEvents *batchEventsJSON `json:"batchEvents,omitempty"`
Priority *Priority `json:"priority,omitempty"`
Idempotency *string `json:"idempotency,omitempty"`
Singleton *Singleton `json:"singleton,omitempty"`
Tags map[string]string `json:"tags,omitempty"`
}
FunctionConfig is one function in the manifest, with Inngest's key names.
type FunctionOpts ¶
type FunctionOpts struct {
ID string
Name string
Retries *int
Timeouts *Timeouts
CancelOn []CancelOn
Concurrency []Concurrency
Throttle *Throttle
RateLimit *RateLimit
Debounce *Debounce
BatchEvents *BatchEvents
Priority *Priority
// Idempotency is an expression over event; one run per value.
Idempotency *string
Singleton *Singleton
// Tags names up to 3 values of a run, each an expression over event, for
// example {"agentRun": "event.data.job.runId"}. The engine works them out
// once, when the run starts, and Runs().List and Runs().Cancel can find
// runs by them. A name is a letter, then letters, digits or _, up to 32.
// A value that is not a string, number or boolean, or is over 256
// characters, is left out.
Tags map[string]string
}
FunctionOpts configures a function. Only ID is required.
Durations are sent to the engine as "<n>s" when they are whole seconds, else as "<n>ms".
type GenericEvent ¶
type GenericEvent[T any] struct { ID string `json:"id"` Name string `json:"name"` Data T `json:"data"` Timestamp int64 `json:"ts"` User any `json:"user,omitempty"` }
GenericEvent is an event a function receives, with typed data.
type Input ¶
type Input[T any] struct { Event GenericEvent[T] Events []GenericEvent[T] InputCtx InputCtx }
Input is what a handler gets: the trigger event, the batch (one item unless batching) and the run details.
type InputCtx ¶
type InputCtx struct {
FunctionID string
RunID string
// Attempt counts from 0.
Attempt int
MaxAttempts int
}
InputCtx says which run and attempt this is.
type ListRunsOpts ¶ added in v0.7.0
type ListRunsOpts struct {
// Function is a function's own ID. Needed with Tags.
Function string
// Status keeps runs in these statuses, for example "queued", "running".
// Empty: every status.
Status []string
// Tags keeps runs with all these tag values (up to 3). See FunctionOpts.Tags.
Tags map[string]string
// Limit is the page size, 1 to 200. Default: 50.
Limit int
// Before is RunPage.Next of the page before, to read the next page.
Before string
}
ListRunsOpts filters Runs().List. Every field is optional.
type MultipleTriggers ¶
type MultipleTriggers []Trigger
MultipleTriggers starts a function from any of several triggers.
type Priority ¶
type Priority struct {
Run *string `json:"run,omitempty"`
}
Priority orders waiting runs. Run is an expression giving a boost in seconds (-600 to 600).
type Realtime ¶ added in v0.4.0
type Realtime struct {
// contains filtered or unexported fields
}
Realtime sends small live messages from functions to browsers. A message goes to the browsers connected right now; nothing is stored or replayed. A server can read them too, with Subscribe. Get it with Client.Realtime.
A publish is a plain call, not a step: if the step around it is retried, the message is sent again. Treat messages as hints (progress, logs), and keep anything that must happen once in a step's result.
func (Realtime) Publish ¶ added in v0.4.0
Publish sends data (any JSON value, up to about 64 KB) to the browsers subscribed to topic on channel. Log its error and go on: a realtime outage should not fail a run.
func (Realtime) PublishMany ¶ added in v0.7.0
func (r Realtime) PublishMany(ctx context.Context, messages []RealtimeOut) error
PublishMany sends 1 to 100 messages in one call. Each message's data is up to about 64 KB, and the whole call up to 1 MB. The engine checks them all first: if one is bad, none is sent.
func (Realtime) Subscribe ¶ added in v0.7.0
func (r Realtime) Subscribe(ctx context.Context, opts SubscribeOpts) (stop func(), err error)
Subscribe reads live messages on a server, the way the TypeScript subscribe does in a browser. It makes a new token (Token or TokenMany) before every connect, so no token route is needed. It connects to the client's base URL with the path of the token's URL, not to the host in the token. It sends "ping" every 30s. When the socket drops it connects again after a wait (1s, doubling up to 30s, with some random), and at once when the engine ends the socket at the end of its 1-hour life (close code 4001).
Messages are lost while the socket reconnects and at the 1-hour renewal. Treat them as hints: read missed state from your own store after a reconnect (OnState gets RealtimeOpen).
It runs until stop is called or ctx ends. stop waits until the subscription has ended, so no callback runs after it returns. It may be called more than once. Do not call stop from inside OnMessage or OnState: it would wait for itself. To end from a callback, cancel the ctx given to Subscribe, or call go stop(). err is only for bad options: no channel, no topics, or no OnMessage.
func (Realtime) Token ¶ added in v0.4.0
func (r Realtime) Token(ctx context.Context, channel string, topics ...string) (RealtimeToken, error)
Token makes a subscription token for channel and topics (1 to 10). Call it in your own HTTP handler, after you checked that the user may see that channel.
func (Realtime) TokenMany ¶ added in v0.7.0
func (r Realtime) TokenMany(ctx context.Context, channels []string, topics ...string) (RealtimeToken, error)
TokenMany makes one token for 1 to 100 channels, with at most 8,000 characters of names in all (so the token fits in a connect URL). The topics apply to every channel. One socket then gets the messages of all of them.
type RealtimeMessage ¶ added in v0.7.0
type RealtimeMessage struct {
Channel string `json:"channel"`
Topic string `json:"topic"`
Data json.RawMessage `json:"data"`
// TS is when the engine got the publish, ms since epoch.
TS int64 `json:"ts"`
}
RealtimeMessage is one message a subscription gets.
type RealtimeOut ¶ added in v0.7.0
type RealtimeOut struct {
Channel string `json:"channel"`
Topic string `json:"topic"`
Data any `json:"data"`
}
RealtimeOut is one message for PublishMany.
type RealtimeState ¶ added in v0.7.0
type RealtimeState string
RealtimeState is the state of a subscription, given to SubscribeOpts.OnState.
const ( RealtimeConnecting RealtimeState = "connecting" RealtimeOpen RealtimeState = "open" RealtimeClosed RealtimeState = "closed" RealtimeError RealtimeState = "error" )
The states of a subscription.
type RealtimeToken ¶ added in v0.4.0
type RealtimeToken struct {
Token string `json:"token"`
URL string `json:"url"`
// Channel is set for a token made by Token.
Channel string `json:"channel,omitempty"`
// Channels is set for a token made by TokenMany.
Channels []string `json:"channels,omitempty"`
Topics []string `json:"topics"`
// ExpiresAt is the connect deadline (ms since epoch), about a minute away.
ExpiresAt int64 `json:"expiresAt"`
}
RealtimeToken lets one browser (or server) connect to one channel, or to a list of channels, and read the listed topics. Hand it to the browser as JSON; the TypeScript client reads it.
type RunCounts ¶ added in v0.7.0
type RunCounts struct {
Queued int `json:"queued"`
Running int `json:"running"`
Sleeping int `json:"sleeping"`
Waiting int `json:"waiting"`
WaitingForApp int `json:"waiting_for_app"`
Paused int `json:"paused"`
Completed int `json:"completed"`
Failed int `json:"failed"`
Cancelled int `json:"cancelled"`
// Since is ms since epoch. Ended runs older than this may be gone from
// the counts already.
Since int64 `json:"since"`
}
RunCounts is how many of a function's runs are in each status.
type RunPage ¶ added in v0.7.0
type RunPage struct {
Items []RunSummary `json:"items"`
// Next reads the next page as ListRunsOpts.Before. Empty on the last page.
Next string `json:"next"`
}
RunPage is one page of runs, newest first.
type RunSummary ¶ added in v0.7.0
type RunSummary struct {
ID string `json:"id"`
// FunctionID is the function's own ID, without the app.
FunctionID string `json:"functionId"`
Status string `json:"status"`
// CreatedAt is ms since epoch.
CreatedAt int64 `json:"createdAt"`
// EndedAt is ms since epoch, or 0 while the run has not ended.
EndedAt int64 `json:"endedAt"`
// Tags are the run's tags; empty when it has none.
Tags map[string]string `json:"tags"`
}
RunSummary is one run in a RunPage.
type Runs ¶ added in v0.7.0
type Runs struct {
// contains filtered or unexported fields
}
Runs finds, counts and cancels this app's runs. Get it with Client.Runs.
func (Runs) Cancel ¶ added in v0.7.0
func (r Runs) Cancel(ctx context.Context, opts CancelOpts) (CancelResult, error)
Cancel cancels runs of this app (POST /v1/runs/cancel): one run by ID, the run that holds a singleton key, or the runs with a tag value. A run that has ended already is not an error: it is in NotActive. A cancel by tag cancels up to 500 runs; when More is true, call again with Next as Cursor.
func (Runs) Counts ¶ added in v0.7.0
Counts counts a function's runs by status (GET /v1/runs/counts). Like List, it is a few seconds behind the runs.
func (Runs) List ¶ added in v0.7.0
List lists this app's runs, newest first (GET /v1/runs). It reads the engine's run index, which is a few seconds behind the runs.
type ServableFunction ¶
type ServableFunction interface {
// ID is the function ID without the app prefix.
ID() string
// FullyQualifiedID is "<appId>-<id>", used by step.Invoke and in
// inngest/function.failed events.
FullyQualifiedID() string
// Config is the function's manifest entry.
Config() FunctionConfig
// contains filtered or unexported methods
}
ServableFunction is a function made by CreateFunction.
func CreateFunction ¶
func CreateFunction[T any](c *Client, opts FunctionOpts, trigger Triggerable, handler Handler[T]) (ServableFunction, error)
CreateFunction defines a function and adds it to the client.
For failure handling (onFailure in TypeScript), create a second function of type FailedEventData with trigger EventTrigger("inngest/function.failed", StrPtr("event.data.function_id == '<appId>-<id>'")). Its event data holds function_id, run_id, error, event (the original trigger event) and attempts (how many times the failed step was tried).
type SingletonRun ¶ added in v0.7.0
type SingletonRun struct {
// RunID is empty when no active run holds the key.
RunID string `json:"runId"`
// Status is the run's status, or empty with RunID.
Status string `json:"status"`
}
SingletonRun is the run that holds a singleton key.
type StartOpts ¶ added in v0.7.0
type StartOpts struct {
// Data is the run's event data. Default: {}.
Data any
// ID makes a retry safe: a second Start with the same ID (1 to 256
// characters) finds the same run, and does not start another. Optional.
ID string
// User is the event's user field. Optional.
User any
}
StartOpts is the input of Client.Start.
type StartResult ¶ added in v0.7.0
type StartResult struct {
Started bool `json:"started"`
RunID string `json:"runId,omitempty"`
EventID string `json:"eventId,omitempty"`
// Existed is true when a run with this StartOpts.ID was there already.
Existed bool `json:"existed,omitempty"`
// Reason says why no run started: "singleton", "paused" or "not_found".
Reason string `json:"reason,omitempty"`
// ActiveRunID is the run that holds the singleton when Reason is
// "singleton". It is empty if that run ended in between.
ActiveRunID string `json:"activeRunId,omitempty"`
}
StartResult says whether Start started a run.
type StreamItem ¶ added in v0.7.0
type StreamItem struct {
// Offset is the item's place in the stream. Treat it as opaque text: keep
// the last one you read, and read again after it.
Offset string `json:"offset"`
Item json.RawMessage `json:"item"`
// End is true for the end item, which Close writes. It is always last.
End bool `json:"end,omitempty"`
}
StreamItem is one item of a stream.
type StreamOpenOpts ¶ added in v0.7.0
type StreamOpenOpts struct {
// Meta is any JSON value (up to 4 KB) kept with the stream. Optional.
Meta any
// TTL deletes the stream this long after Open if it is not closed
// before. 1s to 7 days.
TTL time.Duration
}
StreamOpenOpts is the input of Streams().Open.
type StreamSnapshot ¶ added in v0.7.0
type StreamSnapshot struct {
Meta json.RawMessage `json:"meta"`
Items []StreamItem `json:"items"`
// Ended is true when the stream is closed. Then the last item is the
// end item.
Ended bool `json:"ended"`
}
StreamSnapshot is a stream as it is now.
type StreamToken ¶ added in v0.7.0
type StreamToken struct {
Token string `json:"token"`
URL string `json:"url"`
Stream string `json:"stream"`
// ExpiresAt is the connect deadline (ms since epoch), about a minute away.
ExpiresAt int64 `json:"expiresAt"`
}
StreamToken lets one reader (a browser, for example) connect to one stream. Hand it to the browser as JSON; the TypeScript readStream reads it.
type Streams ¶ added in v0.7.0
type Streams struct {
// contains filtered or unexported fields
}
Streams keeps short lists of items (for example the output of one run) that readers can read from any offset, then follow live. A stream belongs to this app. Get it with Client.Streams.
One writer per stream: Open it, Append to it, then Close it with an end item. Readers use Snapshot (what is there now) or Read (what is there, then new items, until the end item). See docs/limits.md for the limits.
func (Streams) Append ¶ added in v0.7.0
Append adds 1 to 100 items (each any JSON value, up to 64 KB) in order, and returns one offset for each. It fails with ErrStreamGone when the stream does not exist, and ErrStreamClosed after Close.
func (Streams) Close ¶ added in v0.7.0
func (s Streams) Close(ctx context.Context, id string, end any, grace time.Duration) (closed bool, err error)
Close writes end (any JSON value) as the stream's last item and closes the stream. The stream is deleted grace later (0 to 7 days), so late readers still get the end. closed is false when it was closed already; then nothing changes. It fails with ErrStreamGone when the stream does not exist.
func (Streams) Delete ¶ added in v0.7.0
Delete deletes a stream now. Its readers get ErrStreamGone. deleted is false when there was none.
func (Streams) Open ¶ added in v0.7.0
func (s Streams) Open(ctx context.Context, id string, opts StreamOpenOpts) (created bool, err error)
Open makes a stream. created is false when it exists already; then nothing changes.
func (Streams) Read ¶ added in v0.7.0
Read yields the items after the offset after ("" is from the start), then new items as they are appended, until the end item, which it yields too. It makes a new token (Token) before every connect, and connects to the client's base URL with the path of the token's URL, not to the host in the token.
When the socket drops, it connects again from the last offset it yielded, after a wait (1s, doubling up to 30s, with some random), or at once when the engine ends the socket at the end of its 1-hour life. So no item is lost or yielded twice.
It yields ErrStreamGone (and stops) when the stream does not exist, or is deleted while read. It stops with no error when ctx ends or the loop breaks, and closes the socket. It also stops with no error, and no item, when the stream is closed and has nothing after after (you had the end item already; the engine closes the socket with code 4100).
Other errors: a bad id or after, or a token call the engine refuses (4xx), is yielded, and Read stops. Anything else is tried again.
type SubscribeOpts ¶ added in v0.7.0
type SubscribeOpts struct {
// Channel is the one channel to read. Set Channel or Channels, not both.
Channel string
// Channels reads 1 to 100 channels over one socket, with at most 8,000
// characters of names in all.
Channels []string
// Topics are the topics to read (1 to 10), on every channel.
Topics []string
// OnMessage gets each message. Required. It runs on the subscription's
// own goroutine, one message at a time, so a slow OnMessage holds up the
// next ones.
OnMessage func(RealtimeMessage)
// OnState gets each change of state. err is set with RealtimeError, and
// says why the connect or the socket failed. Optional.
OnState func(state RealtimeState, err error)
}
SubscribeOpts says what Subscribe reads and where the messages go.
type Timeouts ¶
Timeouts sets time limits. Step is the longest one step's HTTP call may take. Finish is the longest the whole run may take, counted from its first step call (time spent queued does not count); a run still going then is cancelled. Zero means the engine's default (Step) or no limit (Finish).
type Trigger ¶
type Trigger struct {
Event string `json:"event,omitempty"`
If *string `json:"if,omitempty"`
Cron string `json:"cron,omitempty"`
}
Trigger starts a function: an event (with an optional "if" expression) or a cron schedule. Make one with EventTrigger or CronTrigger.
func CronTrigger ¶
CronTrigger runs the function on a cron schedule, for example "0 2 * * *" or "TZ=Africa/Lagos 0 2 * * *".
func EventTrigger ¶
EventTrigger runs the function for each event with this name. expr is an optional "if" expression over event, for example "event.data.plan == 'pro'".
type Triggerable ¶
type Triggerable interface {
// contains filtered or unexported methods
}
Triggerable is a Trigger or MultipleTriggers.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package group runs steps in parallel.
|
Package group runs steps in parallel. |
|
internal
|
|
|
core
Package core holds the parts shared by the flow, step and group packages: the wire types, the replay state of one call, and the error types.
|
Package core holds the parts shared by the flow, step and group packages: the wire types, the replay state of one call, and the error types. |
|
Package step has the durable steps a flow function calls: Run, Sleep, SleepUntil, WaitForEvent, Invoke and Send.
|
Package step has the durable steps a flow function calls: Run, Sleep, SleepUntil, WaitForEvent, Invoke and Send. |