Go SDK
Record and replay Go handlers with github.com/kavachlabs/kavach/sdk/go. No dependencies, a shared-memory ring by default, and kavachtest for go test.
go get github.com/kavachlabs/kavach@latestimport kavach "github.com/kavachlabs/kavach/sdk/go"Go 1.23 or later. No third-party dependencies.
Handler#
type Handler interface {
Handle(env Env, in Input) error
}
type Input struct {
Source string // e.g. "kafka:wallet-events"
Position string // e.g. "3:1042"
Data []byte // the event exactly as received
}kavach.HandlerFunc adapts a plain function. Handlers are called from one goroutine at a time and must be deterministic given the env.
Env#
type Env interface {
Now() time.Time // instead of time.Now
Read(p []byte) (int, error) // instead of crypto/rand; always fills p
Query(gateway string, request []byte) ([]byte, error) // an external system, by a stable name
Config(key string) (value []byte, ok bool) // a flag or limit
Emit(sink string, data []byte) // delivered after the step succeeds
}Optional interfaces#
type Snapshotter interface {
Snapshot() ([]byte, error)
Restore(data []byte) error
}
type Checker interface {
Invariants() []Invariant // Invariant{Name string; Check func() error}
}A handler that implements Snapshotter lets the recorder start new journal segments, so fixtures start from recent state. A Checker's invariants run after every step that returns nil.
Recording#
rec := kavach.NewRecorder(NewLedger(), kavach.Options{
Service: "ledger",
Dir: "kavach",
Gateway: func(gw string, req []byte) ([]byte, error) { return gateways.Call(gw, req) },
Deliver: func(outs []kavach.Output) error { return sinks.WriteAll(outs) },
OnFixture: func(file, failure string) { alert(file, failure) },
})
defer rec.Close()
for msg := range messages {
err := rec.Step(kavach.Input{Source: "kafka:wallet-events", Position: msg.Pos, Data: msg.Value})
if err != nil {
log.Print(err) // the step failed and a fixture was written
}
}Step writes the input before calling the handler, records every env call, checks invariants, then delivers outputs if the step succeeded. A handler that panics is recorded and then re-panics, so the service dies as it would without Kavach; set RecoverPanics to get a *kavach.PanicError back instead. A broken invariant returns a *kavach.InvariantError.
rec.Flush(true) blocks until the journal is durable on disk. rec.Close() waits for the recorder to finish. rec.File() is the current journal's path.
Options#
| Field | Default | Meaning |
|---|---|---|
Service |
executable name | Names the service in journal headers and file names. |
Dir |
kavach |
Journal directory; fixtures go to Dir/fixtures/. |
RecorderCommand |
$KAVACH_RECORDER, then kavach-recorder on PATH |
Argument vector that starts the recorder. |
Start |
journal.StartGenesis |
journal.StartSnapshot begins the journal from the handler's state. |
NoSnapshots |
false |
Do not start new segments. |
Clock, Rand |
time.Now, crypto/rand.Reader |
Live sources of time and randomness. |
Gateway |
every query fails | Makes live queries. |
Config |
environment variables | Returns a config value and where it came from. |
Flags |
none | Feature flags (flag.<name>) for the environment record. |
Deliver |
record only | Executes a step's outputs after it succeeds. |
RecoverPanics |
false |
Return *PanicError instead of re-panicking. |
NoRing, RingBytes |
ring, 8 MiB | Use the pipe instead of the shared-memory ring, or size the ring. |
OnFixture |
none | Called with the path and failure of every fixture written. |
Compression, Level, BlockBytes, FlushMS, SegmentBytes, SegmentSeconds, RetainSegments, SecretKeys |
recorder defaults | The recorder's own journal settings. |
If the recorder cannot start or stops, the SDK logs it and keeps stepping; Flush returns kavach.ErrNotRecording.
Replay host#
func main() {
kavach.MaybeReplay(func() kavach.Handler { return NewLedger() })
// ... normal startup
}When the last argument is kavach-host, MaybeReplay serves the host protocol on stdin and stdout with fresh handlers and exits. Anything the handler prints goes to stderr. Otherwise it returns.
go build -o /tmp/ledger ./cmd/ledger
kavach replay incident.kavach --bin /tmp/ledgerSelect builds with build tags or flags (go build -tags fix), never environment variables.
Tests#
kavachtest replays fixtures as subtests of go test, in process, with no host binary:
import "github.com/kavachlabs/kavach/sdk/go/kavachtest"
func TestFixtures(t *testing.T) {
kavachtest.Run(t, "testdata/*.kavach", func() kavach.Handler { return NewLedger() })
}A fixture passes when replay reports ok or fixed.
Example#
The quickstart ledger is the Go SDK's example: examples/ledger/sdk in the Kavach repository, with -tags ledgerfix for the correct fix and -tags ledgerpartialfix for a too-narrow one. It reads from a file or from Kafka.
Something wrong or missing on this page? Report it on GitHub, or write to hello@thekavachlabs.com.