Logo
Logo

Go SDK

Install and use the official Go client for GenesisDB.

The official Go client for GenesisDB. Standard library only, no dependencies.

Source on GitHub, Package

Version 2.0.0 of the SDK targets GenesisDB 2.0 and uses the 2.0 routes. Existing 1.x clients keep working against a 2.0 server through the unchanged 1.x API under `/api/v1`.
bash
go get github.com/genesisdb-io/genesisdb-io-client-go/v2

Quick start

go
import "github.com/genesisdb-io/genesisdb-io-client-go/v2/genesisdb"

db, err := genesisdb.New(genesisdb.Config{URL: "http://localhost:8080", Token: os.Getenv("GENESISDB_AUTH_TOKEN")})

stored, err := db.Commit(ctx, []genesisdb.NewEvent{
    {Source: "io.example.shop", Subject: "/customer/42", Type: "io.example.shop.customer-registered", Data: map[string]any{"name": "Bruce Wayne"}},
})

events, err := db.Fetch(ctx, "/customer/42", nil)

URL and Token fall back to GENESISDB_URL and GENESISDB_AUTH_TOKEN, so genesisdb.New(genesisdb.Config{}) works in an environment that sets both. Every method takes a context.Context.

Events

go
// Commit a batch atomically. The server assigns ID, time and hashes and returns the stored events.
stored, err := db.Commit(ctx, []genesisdb.NewEvent{
    {Source: "io.example.shop", Subject: "/order/1", Type: "io.example.shop.order-placed", Data: Order{Total: 99.5}},
    {Source: "io.example.shop", Subject: "/order/1/item/1", Type: "io.example.shop.item-added", Data: Item{SKU: "A1", Qty: 2}},
})
stored[0].ID   // "3f2c..."
stored[0].Hash // "a9b1..."

// Data is any value that encodes to a JSON object: a struct, a map or json.RawMessage.
// Decode a stored payload with DataAs.
var order Order
err = stored[0].DataAs(&order)

// Fetch a subject with all descendants, in commit order.
all, err := db.Fetch(ctx, "/order/1", nil)

// Resume after a known event, or stop at one.
since, err := db.Fetch(ctx, "/order", &genesisdb.FetchOptions{LowerBound: lastSeenID})
until, err := db.Fetch(ctx, "/order", &genesisdb.FetchOptions{UpperBound: someID, IncludeUpperBoundEvent: true})

// Only the newest event of a type below the subject.
latest, err := db.Fetch(ctx, "/order/1", &genesisdb.FetchOptions{LatestByEventType: "io.example.shop.order-placed"})

Preconditions

Preconditions are checked atomically with the commit. A failed precondition returns *PreconditionFailedError and writes nothing.

go
_, err := db.Commit(ctx, events,
    genesisdb.IsSubjectNew("/customer/42"),
    genesisdb.IsQueryResultTrue("STREAM e FROM events WHERE e.data.email == 'bruce@example.com' MAP COUNT() == 0"),
)

var failed *genesisdb.PreconditionFailedError
if errors.As(err, &failed) {
    log.Println(failed.Type, failed.Reason) // "isSubjectNew" "subject /customer/42 already has events"
}

IsSubjectNew, IsSubjectExisting, IsQueryResultTrue.

Subscriptions

Subscribe delivers the existing history first, then new events as they are committed. It calls the handler for every event and returns when the context is done, when the handler returns an error, or when the server ends the stream.

go
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

err := db.Subscribe(ctx, "/order", &genesisdb.SubscribeOptions{Interval: 500 * time.Millisecond}, func(event genesisdb.Event) error {
    log.Println(event.Type, string(event.Data))
    return nil
})

The FetchOptions bounds work here as well, so a consumer that persists the last processed event ID resumes with LowerBound.

Queries

GDBQL runs on the server. Query returns raw JSON rows, QueryInto decodes them into a slice.

go
var rows []struct {
    Name  string  `json:"name"`
    Total float64 `json:"total"`
}
err := db.QueryInto(ctx, "STREAM e FROM events WHERE e.subject UNDER '/customer' MAP { name: e.data.name, total: e.data.total }", &rows)

var counts []int
err = db.QueryInto(ctx, "STREAM e FROM events WHERE e.type == 'io.example.shop.order-placed' MAP COUNT()", &counts)
// counts[0] is the count

GDPR: reference payloads and erasure

Store a payload as reference data and it can be erased later. The event, its hash and the chain stay intact, the payload becomes {}.

go
db.Commit(ctx, []genesisdb.NewEvent{{
    Source: "io.example.shop", Subject: "/customer/42", Type: "io.example.shop.customer-registered",
    Data:    map[string]any{"name": "Bruce", "email": "bruce@example.com"},
    Options: &genesisdb.CommitOptions{StoreDataAsReference: true},
}})

_, err := db.Erase(ctx, "/customer/42") // administrator token

Inline payloads are immutable. Erase on a subject without reference payloads returns an error matching ErrUnprocessable, on a subject without events ErrNotFound.

Schemas

go
err := db.RegisterSchema(ctx, "io.example.shop.order-placed", genesisdb.Schema{
    "type":       "object",
    "properties": map[string]any{"total": map[string]any{"type": "number"}},
    "required":   []string{"total"},
})

schemas, err := db.Schemas(ctx)

Commits of that type are validated. A violation returns *Error with status 400. Registering a type twice returns ErrConflict.

Catalog, status, administration

go
subjects, err := db.Subjects(ctx)  // ["/customer", "/order"]
types, err := db.Types(ctx)        // ["io.example.shop.customer-registered", ...]
status, err := db.Status(ctx)      // engine version, event counts, storage, readiness
pong, err := db.Ping(ctx)          // "Pong", no token required

audit, err := db.Audit(ctx)        // "Audit passed. All 1234 events integrity checks succeeded."

Audit, erase and schema registration need the administrator token. Everything else works with a reader token (GENESISDB_READ_TOKEN), commit additionally with a writer token.

Errors

Every non-2xx answer returns *Error with Operation, Status and Body. errors.Is works with the sentinels ErrUnauthorized, ErrForbidden, ErrNotFound, ErrConflict, ErrPreconditionFailed, ErrUnprocessable and ErrNotReady. A 412 returns *PreconditionFailedError with Type and Reason, which also matches ErrPreconditionFailed.

Configuration

go
genesisdb.New(genesisdb.Config{
    URL:        "http://localhost:8080", // or GENESISDB_URL
    Token:      "...",                   // or GENESISDB_AUTH_TOKEN
    HTTPClient: &http.Client{Timeout: 10 * time.Second}, // optional, default 30 s; subscriptions never time out
})