flow

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: MIT Imports: 21 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

flow-sdk

SDKs for clevix-worker, a durable workflow engine on Cloudflare. You write functions made of steps. The engine runs them, saves each step's result, and retries steps that fail. Sleeps and waits can last days.

There are two SDKs. They speak the same protocol, so one app can call a function in the other language.

Language Install Guide
Go go get github.com/eadwinCode/flow-sdk@latest docs/go.md
TypeScript npm install <.tgz URL from the release> docs/typescript.md

The API follows Inngest (inngestgo for Go, inngest for TypeScript).

Guides

New here? Start with Getting started: keys, install, add your app, your first function, deploy, connect, and your first event.

Guide What is in it
Getting started From nothing to a running function, and working on your laptop
Functions and steps Triggers, steps (run, sleep, waitForEvent, sendEvent, invoke), parallel steps, errors and retries, cancelling, failure handlers, expressions
Events What an event holds, sending from apps, functions and HTTP, sending once, delayed runs
Scheduling Cron triggers and time zones, sleeps, runs at a set time
Flow control Concurrency, throttle, rate limit, debounce, batching, priority, idempotency, singleton
Realtime Live messages from functions to the browser: publish, tokens, subscribe, the React hook
Local development A local engine on your machine (Docker or bun run dev), pointing your app at it, or the hosted engine through a tunnel
Production Syncing in CI, key rotation, the dashboard, limits, troubleshooting
TypeScript reference Install, framework adapters (Workers, Hono, Next.js, Express), settings
Go reference Install, the API, Go-specific notes
Protocol How SDKs talk to the engine (for SDK authors)

How it fits together

  1. Your app defines functions with the SDK.
  2. It serves one HTTP endpoint (for example /api/flow). The engine calls it to run your steps. Every call is signed, and the SDK checks the signature.
  3. After each deploy, sync the app so the engine knows your functions: curl -X PUT https://your-app/api/flow.
  4. Send events to the engine. Functions whose trigger matches start a run.

Quick start: Go

go get github.com/eadwinCode/flow-sdk@latest
package main

import (
	"context"
	"net/http"
	"time"

	flow "github.com/eadwinCode/flow-sdk"
	"github.com/eadwinCode/flow-sdk/step"
)

type SignedUp struct {
	UserID string `json:"userId"`
}

func main() {
	client, err := flow.NewClient(flow.ClientOpts{AppID: "billing-service"})
	if err != nil {
		panic(err)
	}

	_, err = flow.CreateFunction(client,
		flow.FunctionOpts{ID: "welcome"},
		flow.EventTrigger("user/signed-up", nil),
		func(ctx context.Context, in flow.Input[SignedUp]) (any, error) {
			_, err := step.Run(ctx, "send-email", func(ctx context.Context) (string, error) {
				return "sent", nil // call your mailer here
			})
			if err != nil {
				return nil, err
			}
			step.Sleep(ctx, "wait-a-day", 24*time.Hour)
			return "done", nil
		},
	)
	if err != nil {
		panic(err)
	}

	http.Handle("/api/flow", client.Serve())
	_ = http.ListenAndServe(":8080", nil)
}

Quick start: TypeScript

Take the .tgz link from the newest release:

npm install https://github.com/eadwinCode/flow-sdk/releases/download/v0.6.0/clevix-flow-0.6.0.tgz
import { Flow } from "@clevix/flow";
import { serve } from "@clevix/flow/cloudflare";

const flow = new Flow({ id: "shop" });

const welcome = flow.createFunction(
  { id: "welcome" },
  { event: "user/signed-up" },
  async ({ event, step }) => {
    await step.run("send-email", () => sendEmail(event.data.userId));
    await step.sleep("wait-a-day", "1d");
    return "done";
  },
);

export default serve({ client: flow, functions: [welcome] });

There are also adapters for Hono, Next.js and Express. See docs/typescript.md.

Settings

Both SDKs read the same env vars. Values passed in code win.

Variable Use
FLOW_SIGNING_KEY Your app's own signing key, from Add app in the dashboard. Checks calls from the engine and signs sync. Required unless dev mode.
FLOW_SIGNING_KEY_FALLBACK The app's old key while you rotate it.
FLOW_EVENT_KEY For sending events from your app.
FLOW_BASE_URL The engine's URL. Default: https://worker.clevixstudio.com. Set it only if you run your own engine.
FLOW_DEV 1 turns off signature checks. For local work only.

Versions

Both SDKs share one version number. Each release has a git tag vX.Y.Z (used by Go) and a GitHub release with the TypeScript .tgz. To hear about new versions, use Watch → Custom → Releases on this repo.

What is in this repo

Path What
*.go, step/, group/, internal/ The Go SDK (module github.com/eadwinCode/flow-sdk)
packages/flow The TypeScript SDK, @clevix/flow
packages/protocol @clevix/protocol: wire types, signing, IDs and durations. Shared with the engine; @clevix/flow bundles it
testdata/vectors.json Test vectors both SDKs must match
docs/ The Go, TypeScript and protocol guides

Develop

Needs Go 1.27+, Node 22+ and pnpm 9.

pnpm install
pnpm typecheck
pnpm test
go test ./...

The engine pins a release of this repo. When a change needs the engine too (for example a protocol change), see "Working with the engine" in RELEASING.md.

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

View Source
const DefaultBaseURL = "https://worker.clevixstudio.com"

DefaultBaseURL is the engine URL when neither ClientOpts.BaseURL nor FLOW_BASE_URL is set. Self-hosters set FLOW_BASE_URL.

View Source
const Version = "0.6.0"

Version is this SDK's version, sent in the manifest.

Variables

This section is empty.

Functions

func BoolPtr

func BoolPtr(b bool) *bool

BoolPtr returns a pointer to b.

func IntPtr

func IntPtr(i int) *int

IntPtr returns a pointer to i.

func NoRetryError

func NoRetryError(err error) error

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

func RetryAtError(err error, at time.Time) error

RetryAtError wraps err so the next attempt runs at the given time.

func StrPtr

func StrPtr(s string) *string

StrPtr returns a pointer to s.

Types

type AppManifest

type AppManifest struct {
	AppID     string           `json:"appId"`
	URL       string           `json:"url"`
	SDK       *SDKInfo         `json:"sdk,omitempty"`
	Functions []FunctionConfig `json:"functions"`
}

AppManifest is what the app sends on sync and returns on GET.

type BatchEvents

type BatchEvents struct {
	MaxSize int
	Timeout time.Duration
	Key     *string
	If      *string
}

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

func (c *Client) AppID() string

AppID returns the app's ID.

func (*Client) Manifest

func (c *Client) Manifest(serveURL string) AppManifest

Manifest builds the app's manifest with serveURL as the app URL.

func (*Client) Realtime added in v0.4.0

func (c *Client) Realtime() Realtime

Realtime returns the client's realtime API.

func (*Client) Send

func (c *Client) Send(ctx context.Context, event Event) (string, error)

Send sends one event and returns its ID.

func (*Client) SendMany

func (c *Client) SendMany(ctx context.Context, events []Event) ([]string, error)

SendMany sends up to 100 events in one request and returns their IDs.

func (*Client) Serve

func (c *Client) Serve() http.Handler

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.

func (*Client) Sync

func (c *Client) Sync(ctx context.Context, serveURL string) (int, []byte, error)

Sync sends the manifest to the engine (PUT {base}/apps/{appId}/sync) and returns the engine's status code and body.

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 sync and sending events. 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
}

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

type Debounce struct {
	Period  time.Duration
	Key     *string
	Timeout time.Duration
}

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 Event

type Event = core.Event

Event is an event to send with client.Send or step.Send.

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"`
}

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
}

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 Handler

type Handler[T any] func(ctx context.Context, input Input[T]) (any, error)

Handler is a function's code.

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

type RateLimit struct {
	Limit  int
	Period time.Duration
	Key    *string
}

RateLimit drops events over Limit per Period.

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

func (r Realtime) Publish(ctx context.Context, channel, topic string, data any) error

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

type RealtimeToken added in v0.4.0

type RealtimeToken struct {
	Token   string   `json:"token"`
	URL     string   `json:"url"`
	Channel string   `json:"channel"`
	Topics  []string `json:"topics"`
	// ExpiresAt is the connect deadline (ms since epoch), about a minute away.
	ExpiresAt int64 `json:"expiresAt"`
}

RealtimeToken lets one browser connect to one channel and read the listed topics. Hand it to the browser as JSON; the TypeScript client reads it.

type SDKInfo

type SDKInfo struct {
	Language string `json:"language"`
	Version  string `json:"version"`
}

SDKInfo names the SDK in the manifest.

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 with trigger EventTrigger("inngest/function.failed", StrPtr("event.data.function_id == '<appId>-<id>'")). Its event data holds function_id, run_id, error and event (the original trigger event).

type Singleton

type Singleton struct {
	Key  *string `json:"key,omitempty"`
	Mode string  `json:"mode"`
}

Singleton keeps one active run per key. Mode is "skip" or "cancel".

type StepError

type StepError = core.StepError

StepError is what a step returns when its stored result is an error.

type Throttle

type Throttle struct {
	Limit  int
	Period time.Duration
	Burst  int
	Key    *string
}

Throttle delays runs over Limit per Period (plus Burst).

type Timeouts

type Timeouts struct {
	Step   time.Duration
	Finish time.Duration
}

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

func CronTrigger(cron string) Trigger

CronTrigger runs the function on a cron schedule, for example "0 2 * * *" or "TZ=Africa/Lagos 0 2 * * *".

func EventTrigger

func EventTrigger(name string, expr *string) Trigger

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.

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.

Jump to

Keyboard shortcuts

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