# Go SDK

> Write services, virtual objects and workflows in Go with the cairn package, serve them, and call them with the Go client.

Source: https://cairnflow.dev/docs/develop/go

The Go SDK, module `github.com/cairnflowdev/cairnflow/sdk/go` (package `cairn`), has the same model
as the TypeScript SDK: handlers replay from a journal, side effects go through `cairn.Run`, and
results reach your code in the order they were recorded. It needs Go 1.25 or newer and has no
dependencies: `go.mod` has no `require`. It is licensed under Apache-2.0 and is in beta.

The rest of these docs show TypeScript. The concepts, limits, error codes and HTTP routes are the
same in Go; this page lists what is spelled differently.

## Install

```sh
go get github.com/cairnflowdev/cairnflow/sdk/go
```

Releases are tagged `sdk/go/vX.Y.Z` (the current beta is `v0.1.0-beta.0`:
`go get github.com/cairnflowdev/cairnflow/sdk/go@v0.1.0-beta.0`). To work against a local checkout
instead:

```sh
go mod edit -replace=github.com/cairnflowdev/cairnflow/sdk/go=../cairnflow/sdk/go
```

```go
import (
	cairn "github.com/cairnflowdev/cairnflow/sdk/go"
	"github.com/cairnflowdev/cairnflow/sdk/go/client" // calling services from an app or a script
)
```

## A first service

```go title="main.go"
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"

	cairn "github.com/cairnflowdev/cairnflow/sdk/go"
)

type Order struct {
	Amount int `json:"amount"`
}

type Receipt struct {
	Receipt string `json:"receipt"`
	Total   int    `json:"total"`
}

// charge is the side effect: a payment provider in real life.
func charge(ctx context.Context, amount int) (string, error) {
	log.Printf("charging %d", amount)
	return fmt.Sprintf("receipt-%d", amount), ctx.Err()
}

func submit(ctx cairn.ObjectContext, order Order) (Receipt, error) {
	if order.Amount <= 0 {
		return Receipt{}, cairn.TerminalErrorf(400, "amount must be positive") // bad data: retrying is useless
	}
	total, _, err := cairn.Get[int](ctx, "total") // false (and 0) = the key does not exist
	if err != nil {
		return Receipt{}, err
	}
	if err := cairn.Sleep(ctx, time.Second); err != nil { // durable: the timer lives in the store
		return Receipt{}, err
	}
	receipt, err := cairn.Run(ctx, "charge", func(rc cairn.RunContext) (string, error) {
		return charge(rc, order.Amount) // runs once per durable result; rc is a context.Context
	})
	if err != nil {
		return Receipt{}, err
	}
	if err := cairn.Set(ctx, "total", total+order.Amount); err != nil {
		return Receipt{}, err
	}
	return Receipt{Receipt: receipt, Total: total + order.Amount}, nil
}

// total runs in parallel with other handlers of the same key and only reads state.
func total(ctx cairn.ObjectSharedContext) (int, error) {
	t, _, err := cairn.Get[int](ctx, "total")
	return t, err
}

var orders = cairn.NewObject("OrderService",
	cairn.Exclusive("submit", submit),
	cairn.Shared("total", cairn.NoInput(total)))

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	// Listens on every interface; 127.0.0.1:9080 is unreachable from outside a container.
	err := cairn.Serve(ctx, ":9080", orders,
		cairn.IdentityKeys(os.Getenv("CAIRN_IDENTITY_KEY")))
	if err != nil {
		log.Fatal(err)
	}
}
```

Register and invoke it exactly as in the [Quickstart](/docs/quickstart): `POST /deployments` with
the service's public `https://` URL, then `POST /invoke/OrderService/submit?key=order-42`.

Every durable step is a function of the package that takes the context (`cairn.Get(ctx, …)`,
`cairn.Run(ctx, …)`), so it can be generic in the type of its value. A step that can fail returns
an `error`: return it from the handler as it is.

## Services and handlers

| Declared with | Kind |
|---|---|
| `cairn.NewService(name, handlers...)` | A plain service: no key, no state. Handlers are `cairn.Handler(name, fn)` with `fn func(cairn.Context, I) (O, error)` |
| `cairn.NewObject(name, handlers...)` | A virtual object: state per key. `cairn.Exclusive(name, fn)` takes a `cairn.ObjectContext`; `cairn.Shared(name, fn)` takes a `cairn.ObjectSharedContext` and only reads state |
| `cairn.NewWorkflow(name, handlers...)` | A workflow: exactly one `cairn.Main(name, fn)` taking a `cairn.WorkflowContext`, which runs once per workflow ID, plus any number of `cairn.Shared` handlers. Name the main handler `run`, as the other SDKs do by default |

- A handler without input is wrapped with `cairn.NoInput(fn)`; one without output returns
  `cairn.Void`.
- Input and output are JSON through `encoding/json`. An input that does not decode into the
  handler's input type fails the invocation with a terminal error `400` before the handler runs.
- Writing state from a shared handler does not compile, and neither does `cairn.Get` on a plain
  service's context.
- A mistake in a declaration (no handler, two handlers with one name, a workflow without one
  `Main`) panics at declaration time.

Handler options are trailing arguments of a handler, or `.With(...)` on the whole service:
`WithRetryPolicy`, `WithInactivityTimeout`, `WithJournalRetention`, `WithLogLevel`,
`WithRuntimeTrace` and `WithLogFlush`. Durations are `time.Duration` values. Their meaning is in
[Handler options](/docs/develop/services#handler-options). As in TypeScript, a service that sets
no inactivity timeout declares 15 minutes.

```go
signup := cairn.NewWorkflow("Signup",
	cairn.Main("run", func(ctx cairn.WorkflowContext, email string) (string, error) {
		// Waits, durably, until the shared handler below completes the promise.
		return cairn.Promise[string](ctx, "code").Get()
	}),
	cairn.Shared("verify", func(ctx cairn.WorkflowSharedContext, code string) (cairn.Void, error) {
		return cairn.Void{}, cairn.Promise[string](ctx, "code").Resolve(code)
	}),
).With(cairn.WithRetryPolicy(cairn.RetryPolicy{
	InitialInterval:      time.Second,
	MaxInterval:          time.Minute,
	ExponentiationFactor: 2,
	MaxAttempts:          10,
	OnMaxAttempts:        cairn.PauseOnMaxAttempts,
}))
```

## The context

| | Go |
|---|---|
| State | `cairn.Get[T](ctx, k)` returns `(value, found, err)`; `cairn.Set(ctx, k, v)`, `cairn.Clear(ctx, k)`, `cairn.ClearAll(ctx)`, `cairn.StateKeys(ctx)` |
| Steps | `cairn.Run(ctx, name, func(rc cairn.RunContext) (T, error))`, `cairn.RunAsync(...)` (a future); option `cairn.Cancellable()` |
| Timers | `cairn.Sleep(ctx, d)`, `cairn.After(ctx, d)` (a future) |
| Calls | `cairn.Service[O](ctx, svc, handler)`, `cairn.Object[O](ctx, svc, key, handler)`, `cairn.Workflow[O](ctx, svc, id, handler)`, then `.Request(in)`, `.RequestFuture(in)` or `.Send(in, cairn.WithDelay(d))`; options `WithIdempotencyKey`, `WithScope`, `WithLimitKey`, `WithSpread` |
| Signals | `cairn.Signal[T](ctx, name)` (a future), `cairn.SendSignal(ctx, invocationID, name, v)` |
| Awakeables | `awk := cairn.Awakeable[T](ctx)`, `awk.ID()` for the outside system, then `awk.Result()` |
| Promises | `p := cairn.Promise[T](ctx, name)`: `p.Get()`, `p.GetFuture()`, `p.Peek()`, `p.Resolve(v)`, `p.Reject(code, msg)` |
| Other invocations | `cairn.Attach[T](ctx, invocationID)` (a future), `cairn.GetOutput[T](ctx, invocationID)`, `cairn.ContinueAsNew(ctx, input)` |
| Combinators | `cairn.WaitFirst(ctx, futs...)`, `cairn.Wait(ctx, futs...)`, `cairn.All(ctx, futs...)`, `cairn.Race(ctx, futs...)`; on a future, `f.Result()` and `f.Done()` |
| Streams, logs, traces | `s, err := ctx.Stream(name)` (`cairn.Durable()` to keep it), `s.Append(record)`, `s.Close()`; `ctx.Log()` is a `*slog.Logger`; `cairn.WithSpan(ctx, name, fn, attrs...)` |
| Artifacts | `ref, err := rc.Artifacts().Put(bytes, contentType)` inside a `Run` closure, `ctx.Artifacts().Get(ref.SHA256)` |
| Identity | `ctx.Key()`, `ctx.InvocationID()`, `ctx.Attempt()`, `ctx.Schedule()`, `ctx.Rand()`, `ctx.Random()`, `cairn.UUID(ctx)` |

A command is journaled when its future is created; waiting happens only in `Result` or in a
combinator. That is how several steps run at once on one goroutine. When several futures are
ready, the combinators pick by journal order, never by arrival time, so a replay takes the same
path.

The rules of handler code are the same as in TypeScript. In Go they read as follows, with two
additions (rules 1 and 4):

1. **Stay on the handler's goroutine.** No `go` statements, channels, `sync` or `time.Sleep` in
   handler code to coordinate durable work: parallel work is futures plus a combinator.
   Concurrency inside a `Run` closure is fine.
2. Use `ctx.Rand()`, `ctx.Random()` or `cairn.UUID(ctx)`, not `math/rand`, `crypto/rand` or
   `time.Now`. Read the clock only inside `cairn.Run`.
3. **Do all I/O inside `cairn.Run`.** A `cairn.Context` is not a `context.Context`; a `Run`
   closure gets one, and must not touch the handler's `ctx`.
4. **Issue the same commands in the same order.** Ranging over a map visits keys in a random
   order, so sort the keys before a loop that issues commands.

## Errors

| Returned from a handler | What happens |
|---|---|
| `cairn.TerminalErrorf(code, format, args...)` | The invocation fails without a retry |
| `cairn.PauseErrorf(format, args...)` | The invocation pauses until someone resumes it |
| `cairn.RetryableErrorf(code, format, args...)` | Retried like any other error, with a code |
| Any other `error`, or a panic | The turn fails and is retried with backoff |

Returned from a `Run` closure, a `*cairn.TerminalError` is recorded as the step's result: the
closure does not run again, and `cairn.Run` returns the same error on every replay. Check for one
with `errors.As` or `cairn.IsTerminalError(err)`.

See [Errors and retries](/docs/develop/errors-retries) for codes and retry policies.

## Serving

| Entry point | Where |
|---|---|
| `cairn.Serve(ctx, addr, services...)` | The built-in server, until `ctx` ends. It serves HTTP/1.1 and cleartext HTTP/2 on one port |
| `cairn.HTTPHandler(services...)` | An `http.Handler` for a server of your own |
| `cairn.LambdaHandler(services...)` | AWS Lambda (Function URL or API Gateway HTTP API, payload v2), request-response mode only. Pass the handler to `lambda.Start` in your own `main` |

Unlike `serve()` in TypeScript, these default to request-response mode. For streaming mode pass
`cairn.Bidi()`. On Cairnflow Cloud an `https://` endpoint is called in request-response mode
unless you register it with `"transport": "declared"`
([Deployments](/docs/cloud/deployments#transport)).

Services and options are passed together, in any order:

| Option | Default | Meaning |
|---|---|---|
| `cairn.IdentityKeys(keys...)` | none | Identity keys of your environment; unsigned requests get `401`. Required by Cairnflow Cloud. Without it, a warning is logged once and the endpoint keeps no replay cache |
| `cairn.IdentityHosts(hosts...)` | none | The public hosts you registered, as `identityHosts` in [serve() options](/docs/develop/services#serve-options) |
| `cairn.Bidi()` | off | Declare streaming mode |
| `cairn.WithoutCompression()` | compression on | Stop accepting gzip request bodies and compressing large responses |
| `cairn.ReplayCache(...)`, `cairn.WithoutReplayCache()` | on with `IdentityKeys` (off on Lambda) | Keep the journal of running invocations in memory so only new entries are sent |
| `cairn.MaxProtocolVersion(v)` | `6` with `IdentityKeys`, else `5` | Pin an older protocol version |
| `cairn.SegmentOrigins(...)`, `cairn.ValueCacheBytes(n)`, `cairn.MaxValueBytes(n)`, `cairn.MaxTurnValueBytes(n)` | as in TypeScript | Downloading large values stored as segments |

## Client

```go title="app.go"
c := client.Connect(os.Getenv("CAIRN_URL"), client.WithAPIKey(os.Getenv("CAIRN_KEY")))

// Waits for the result.
r, err := client.Call[Receipt](ctx, c.Object("OrderService", "order-42"), "submit", Order{Amount: 100})

// Returns once the invocation is durable.
h, err := client.Send(ctx, c.Object("OrderService", "order-42"), "submit", Order{Amount: 5})
out, err := client.Attach[Receipt](ctx, h, client.Timeout(time.Minute))
```

- Targets: `c.Service(name)`, `c.Object(name, key)`, `c.Workflow(name, workflowID)`,
  `c.Awakeable(id)`, `c.Promise(service, key, name)`, `c.Schedules()`.
- `client.Call` waits; `client.Send` returns an invocation handle with `Status`, `Signal` and
  `Cancel`; `client.RunWorkflow` starts a workflow and waits for it.
- Every call carries a generated `Idempotency-Key`, kept across the client's own retries
  (`client.IdempotencyKey(k)` sets one, `client.NoIdempotencyKey()` sends none). The client
  follows the `leader` of a `503` and waits for the `Retry-After` of a `429`.
- A handler's terminal error arrives as `*client.InvocationFailed`; a wait that runs out is a
  `*client.AttachTimeout`, and the invocation keeps running.
- `c.ReadStream(ctx, invocationID, name)` iterates over a stream's events and reconnects on its
  own, like `readStream` in [Streams, logs and traces](/docs/develop/streams-logs).

## Testing handlers

The package `github.com/cairnflowdev/cairnflow/sdk/go/cairntest` runs a handler in the test
process over the SDK's real turn machine, with no runtime. Every turn replays the whole journal
so far, so a test exercises replay too:

```go
inv := cairntest.New(orders, "submit", Order{Amount: 100}, cairntest.Key("o-1"))
st, err := inv.Run() // cairntest.Completed, Waiting, Failed, Paused or ContinuedAsNew
if err != nil || st != cairntest.Completed {
	t.Fatal(st, err)
}
var r Receipt
if err := inv.Output(&r); err != nil {
	t.Fatal(err)
}
```

## Not in the Go SDK

- The Vercel AI SDK adapter (`chatObject`, `cairnMiddleware`, `cairnTools`,
  `cairnChatTransport`): it is specific to that TypeScript library.
