client

package
v0.16.13 Latest Latest
Warning

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

Go to latest
Published: Jul 21, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Overview

Package client provides an HTTP client for the xolu REST API server.

xolu is a graph-enhanced document store that provides:

  • Entity CRUD operations
  • Graph relationships via REF objects
  • OQL (SQL-like) queries
  • Sulpher (graph path) queries
  • Full-text search

This client wraps the HTTP API and provides a convenient Go interface.

Declared surface (v0.16.0 stability)

The client covers xolu's data-plane and semantic-map surface: entity CRUD, Commit, Search, OQL, Sulpher, graph basics (neighbours, query, shortest path), schemas (get + list), named sequences and generators, the full FSM machine surface, event-definition reads, cal (check/openings/propose/confirm), and health/availability. This is the surface molu Parts 2–3 consume, and it is version-tied to the server.

Deliberately out of scope — documented exclusions, not omissions: timeseries, blob, meta, admin, dynconfig, stats, export, async-query polling, and the deep graph analytics (pathExists, commonNeighbors, per-node inspection, edges, admin rebuild/verify). See docs/CLIENT_STAGE6_PLAN.md for the audit that drew this line; a consumer needing an excluded family reopens the scope decision rather than finding an accidental gap.

Index

Constants

This section is empty.

Variables

AllGeneratorKinds enumerates the generator kinds a consumer can query. To build a complete generator listing, iterate this slice and call Client.ListGenerators for each kind.

View Source
var DefaultRetryPolicy = RetryPolicy{
	MaxAttempts:       3,
	InitialBackoff:    200 * time.Millisecond,
	MaxBackoff:        5 * time.Second,
	BackoffMultiplier: 2.0,
}

DefaultRetryPolicy is a sensible starting point: three attempts, 200 ms initial backoff, 5 s ceiling, doubling. Callers who want retries can pass this via WithRetryPolicy directly, or copy and modify it.

This is NOT the client's default when WithRetryPolicy is not supplied — that default is "no retries" (MaxAttempts=1) for backwards compatibility with pre-Stage-4 client versions.

Functions

func DefaultRetryOn

func DefaultRetryOn(resp *http.Response, err error) bool

DefaultRetryOn is the default retry-decision predicate: it returns true for transport-level errors (err != nil and not caused by context) and for HTTP 5xx responses.

It returns false on:

  • success responses (2xx)
  • client errors (4xx) including 401, 403, 404, 409, 422 — these are not transient and retrying will not fix them
  • context cancellation or deadline exceeded — the caller has decided the call should stop

Types

type AuthMode

type AuthMode int

AuthMode identifies which HTTP authentication mode the client uses when talking to xolu. See xolu's pkg/middleware/auth for the corresponding server-side handling.

const (
	// AuthNone sends no Authorization header. Used when the xolu server has
	// AuthType="" or when the client sits behind a trusted gateway.
	AuthNone AuthMode = iota
	// AuthAPIKey sends "Authorization: Bearer <key>" where the key is an
	// entry in the server's XOLU_API_KEYS list. See WithAPIKey.
	AuthAPIKey
	// AuthBearer sends "Authorization: Bearer <token>" where the token is a
	// server-issued opaque bearer token. See WithBearerToken.
	AuthBearer
	// AuthJWT sends "Authorization: Bearer <jwt>" where the JWT is signed
	// with the secret configured as XOLU_JWT_SECRET. See WithJWT.
	AuthJWT
)

type AvailableTransitions

type AvailableTransitions struct {
	State  string   `json:"state"`
	Inputs []string `json:"inputs"`
}

AvailableTransitions is the response of Client.GetMachineTransitions — the input symbols for which a transition from the current state exists.

Guards are not pre-evaluated at this endpoint; an input appears here if any transition names it from the current state, whether or not that transition's guard would currently permit the walk.

type CalBooking

type CalBooking struct {
	BookingID   string    `json:"booking_id"`
	CalendarID  string    `json:"calendar_id"`
	State       string    `json:"state"`
	Span        CalSpan   `json:"span"`
	Mode        string    `json:"mode"`
	Bearer      uint64    `json:"bearer"`
	BufferAfter time.Time `json:"buffer_after,omitempty"`
	CreatedAt   time.Time `json:"created_at,omitempty"`
	UpdatedAt   time.Time `json:"updated_at,omitempty"`
	DetailRef   string    `json:"detail_ref,omitempty"`
}

CalBooking is a booking record as the server returns it from CalPropose and CalConfirm.

type CalCheckResult

type CalCheckResult struct {
	Feasible        bool      `json:"feasible"`
	NearestOpenings []CalSpan `json:"nearest_openings"`
}

CalCheckResult is the response of CalCheck: whether the span is bookable, and if not, the nearest alternative openings.

type CalOpening

type CalOpening struct {
	Start    time.Time `json:"start"`
	End      time.Time `json:"end"`
	MarginMs int64     `json:"margin_ms"`
}

CalOpening is one candidate window returned by CalOpenings, carrying the clear margin around it in milliseconds.

type CalOpeningsResult

type CalOpeningsResult struct {
	Objective Objective    `json:"objective"`
	Openings  []CalOpening `json:"openings"`
}

CalOpeningsResult is the response of CalOpenings; Objective echoes the objective actually applied (the server substitutes "earliest" when the request omitted one).

type CalProposeRequest

type CalProposeRequest struct {
	BookingID   string     `json:"booking_id"`
	CalendarID  string     `json:"calendar_id"`
	Span        CalSpan    `json:"span"`
	Mode        string     `json:"mode,omitempty"`
	Bearer      uint64     `json:"bearer,omitempty"`
	BufferAfter *time.Time `json:"buffer_after,omitempty"`
	DetailRef   string     `json:"detail_ref,omitempty"`
}

CalProposeRequest creates a booking in the proposed state. BookingID is client-generated identity (e.g. a ULID) and required; Mode defaults to "exclusive", the only mode the occupancy engine honours.

type CalSpan

type CalSpan struct {
	Start time.Time `json:"start"`
	End   time.Time `json:"end"`
}

CalSpan is a half-open time span; Start must be strictly before End.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client provides access to the xolu REST API.

func New

func New(baseURL string, opts ...ClientOption) *Client

New creates a new xolu client.

func (*Client) CalCheck

func (c *Client) CalCheck(ctx context.Context, calendarID string, span CalSpan) (*CalCheckResult, error)

CalCheck asks whether span is bookable on the calendar right now, without creating anything. On infeasibility the result carries the nearest alternative openings.

Hits POST /api/v2/.../cal/check. Returns *client.Error on non-2xx.

func (*Client) CalConfirm

func (c *Client) CalConfirm(ctx context.Context, calendarID, bookingID string) (*CalBooking, error)

CalConfirm transitions a proposed booking to binding and returns the updated record.

Hits POST /api/v2/.../cal/confirm. Returns *client.Error on non-2xx — notably XOLU-CAL003 for an illegal state transition and XOLU-CAL005 for an unknown booking.

func (*Client) CalOpenings

func (c *Client) CalOpenings(ctx context.Context, calendarID string, from, to time.Time, duration time.Duration, objective Objective) (*CalOpeningsResult, error)

CalOpenings searches [from, to) for windows admitting duration, ranked by objective. The zero Objective lets the server default to ObjectiveEarliest; any other value is validated client-side against the four implemented objectives before the request is sent.

Hits POST /api/v2/.../cal/openings. Returns *client.Error on non-2xx.

func (*Client) CalPropose

func (c *Client) CalPropose(ctx context.Context, req CalProposeRequest) (*CalBooking, error)

CalPropose creates a booking in the proposed state. req.BookingID is client-generated identity (e.g. a ULID) and required; the returned booking carries the server-assigned fields (state, timestamps).

Hits POST /api/v2/.../cal/propose. Returns *client.Error on non-2xx — notably XOLU-CAL004 when the span conflicts with existing occupancy.

func (*Client) Commit

func (c *Client) Commit(ctx context.Context, req CommitRequest) (*CommitResult, error)

Commit performs an atomic upsert + one or more inserts in a single storage transaction. Use this when state-transition and audit-trail writes must land together or not at all. xolu endpoint: POST /commit (tenant-scoped: /api/v1/tenant/{t}/commit) Returns ErrConflict (wrapped) when the optimistic version check fails. Returns an error wrapping the xolu error message when an append entry uses an explicit ID that already exists. Maximum 25 entries in req.Append — enforced server-side (400 if exceeded).

func (*Client) Create

func (c *Client) Create(ctx context.Context, entity string, data map[string]any) (*Entity, error)

Create creates a new entity in the specified collection. xolu returns {"message":"…","id":N} on creation — the document is not echoed back. Data on the returned Entity is nil; call Get if the full document is needed.

func (*Client) CreateMachine

func (c *Client) CreateMachine(ctx context.Context, req CreateMachineRequest) (*Machine, error)

CreateMachine instantiates a new FSM machine from a definition. The definition must exist in the current tenant scope.

Hits POST /api/v2/fsm/machine. Returns *Machine on 201, *client.Error on non-2xx.

The response carries the machine's identity, initial state, and initial variable values (from the definition's declared defaults, further modified by any overrides supplied in the request).

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, entity string, id int64) error

Delete removes an entity by ID.

func (*Client) DeleteMachine

func (c *Client) DeleteMachine(ctx context.Context, id int64) error

DeleteMachine removes a machine and all its history from the current tenant scope.

Hits DELETE /api/v2/fsm/machine/{id}. Returns nil on 204, *client.Error on non-2xx (404 with XOLU-FSM003 when the machine does not exist).

func (*Client) Get

func (c *Client) Get(ctx context.Context, entity string, id int64) (*Entity, error)

Get retrieves a single entity by ID. xolu returns the flat document directly: {"id":1,"name":"Alice",…} The full document is stored in Entity.Data; ID is also extracted for convenience.

func (*Client) GetEntitySchema

func (c *Client) GetEntitySchema(ctx context.Context, entityType string) (*EntitySchema, error)

GetEntitySchema fetches the schema declaration for a single entity type.

Hits GET /api/v1/schema/{entity}. Returns *client.Error on non-2xx.

The returned EntitySchema carries the raw JSON Schema in `Schema` plus a field breakdown (`Fields`, `Refs`) extracted client-side by walking the schema. Consumers that need finer control over field extraction can decode `Schema` themselves — it is preserved verbatim.

func (*Client) GetEventDef

func (c *Client) GetEventDef(ctx context.Context, id int64) (*EventDef, error)

GetEventDef fetches a single event subscription by ID.

Hits GET /api/v2/event/def/{id}. Returns *client.Error on non-2xx.

func (*Client) GetMachine

func (c *Client) GetMachine(ctx context.Context, id int64) (*Machine, error)

GetMachine fetches a machine's full record — identity, current state, live variables.

Hits GET /api/v2/fsm/machine/{id}. Returns *client.Error with code XOLU-FSM* on non-2xx (including 404 when the machine does not exist).

func (*Client) GetMachineDef

func (c *Client) GetMachineDef(ctx context.Context, id int64) (*MachineDef, error)

GetMachineDef fetches the full definition body for a single FSM definition by ID.

Hits GET /api/v2/fsm/def/{id}. Returns *client.Error on non-2xx (including XOLU-FSM* codes when the definition is not found or is malformed).

func (*Client) GetMachineHistory

func (c *Client) GetMachineHistory(ctx context.Context, id int64) ([]HistoryEntry, error)

GetMachineHistory returns the ordered walk history for a machine, oldest first. The first entry records the machine's creation; each subsequent entry records one walk.

Hits GET /api/v2/fsm/machine/{id}/history. The wire envelope is {"machine": id, "entries": [...]} — this method returns the inner slice.

xolu v0.14.4 does not support pagination on this endpoint; the full history is returned in one response. Consumers of large history sets should design their access patterns around this.

func (*Client) GetMachineResult

func (c *Client) GetMachineResult(ctx context.Context, id int64) (*MachineResult, error)

GetMachineResult returns a convenience summary: current state, terminal flag, live vars, and (when terminal) the final transition's output.

Hits GET /api/v2/fsm/machine/{id}/result.

The FinalOutput field is nil until Terminal becomes true. A caller can poll this endpoint and act once Terminal flips.

func (*Client) GetMachineState

func (c *Client) GetMachineState(ctx context.Context, id int64) (*MachineState, error)

GetMachineState returns just the current state and terminal flag for a machine — a lightweight probe compared to GetMachine.

Hits GET /api/v2/fsm/machine/{id}/state.

func (*Client) GetMachineTransitions

func (c *Client) GetMachineTransitions(ctx context.Context, id int64) (*AvailableTransitions, error)

GetMachineTransitions returns the input symbols for which a transition from the machine's current state exists.

Hits GET /api/v2/fsm/machine/{id}/transitions.

Guards are not pre-evaluated: an input appears here if any transition names it from the current state, whether or not that transition's guard would currently permit the walk. Callers wanting a proven-permissible input must attempt the walk and handle the XOLU-FSM005 rejection.

func (*Client) GetMachineVars

func (c *Client) GetMachineVars(ctx context.Context, id int64) (map[string]VariableSnapshot, error)

GetMachineVars returns the machine's live variable snapshot: each variable's current value alongside its declared type and default.

Hits GET /api/v2/fsm/machine/{id}/vars. The response is a flat map (no envelope key) — the returned map is keyed by variable name.

func (*Client) GetSequence

func (c *Client) GetSequence(ctx context.Context, name string) (*Sequence, error)

GetSequence fetches a single named sequence's current metadata (start, step, current value, creation timestamp).

Hits GET /api/v2/gen/seq/{name} (equivalent to /api/v2/seq/{name}, xolu's permanent alias). Returns *client.Error on non-2xx.

Consumers cannot enumerate sequences today — this method retrieves a specific sequence when the name is known out of band.

func (*Client) GraphNeighbors

func (c *Client) GraphNeighbors(ctx context.Context, nodeID string, direction string) (*NeighborResult, error)

GraphNeighbors retrieves neighbors of a node in the graph. direction must be "out", "in", or "both" (default: "out"). xolu endpoint: POST /graph/neighbors with JSON body. Response: {"neighbors":{"outgoing":{node:label},"incoming":{node:label}}}

func (*Client) GraphQuery

func (c *Client) GraphQuery(ctx context.Context, query string, maxDepth int) (*GraphQueryResult, error)

GraphQuery executes a Sulpher graph path query. Previously named Sulpher; renamed to match the xolu endpoint. xolu endpoint: POST /graph/query maxDepth of 0 uses xolu's server default.

func (*Client) GraphShortestPath

func (c *Client) GraphShortestPath(ctx context.Context, from, to string, maxDepth int) (*PathResult, error)

GraphShortestPath finds the shortest path between two nodes. maxDepth of 0 uses xolu's server default. xolu endpoint: POST /graph/shortestPath with JSON body. Returns PathResult with Exists=false and empty Path when no path exists.

func (*Client) Health

func (c *Client) Health(ctx context.Context) error

Health checks if the xolu server is healthy.

Hits GET /health. Returns nil on 200 (server process is alive; storage layer's Ping succeeded within the server's 2-second timeout). Returns a non-nil error on any non-2xx response, transport failure, or timeout.

Health is appropriate for liveness probes (is the process alive?). For readiness probes (is the process ready to serve traffic?) use Ready instead.

func (*Client) List

func (c *Client) List(ctx context.Context, entity string, params *ListParams) (*ListResult, error)

List retrieves entities from a collection with optional pagination. xolu returns a PagedResponse envelope:

{"data":[…],"pagination":{"page":N,"per_page":N,"total_items":N,"total_pages":N}}

Pagination parameters: xolu uses page/per_page; Limit maps to per_page, Offset is converted to a page number (Offset/Limit + 1, floored at 1).

func (*Client) ListEntityTypes

func (c *Client) ListEntityTypes(ctx context.Context) ([]EntityTypeSummary, error)

ListMachineDefs returns summaries of every FSM definition registered in the current tenant scope. Each summary carries id, name, and creation timestamp only; use GetMachineDef to fetch the full spec.

Hits GET /api/v2/fsm/def. Requires xolu's v2 API to be enabled (XOLU_API_V2_ENABLED=true). Returns *client.Error on non-2xx. ListEntityTypes enumerates the entity types that currently have a registered schema, sorted by name.

Hits GET /api/v1/schemas (T-24). Returns *client.Error on non-2xx.

func (*Client) ListEventDefs

func (c *Client) ListEventDefs(ctx context.Context) ([]EventDef, error)

ListEventDefs returns every registered event subscription in the current tenant scope.

Hits GET /api/v2/event/def. Returns *client.Error on non-2xx.

The wire envelope key is "subscriptions" (not "events" or "definitions"); see xolu's pkg/server/v2_event_handlers.go handleEventList.

func (*Client) ListGenerators

func (c *Client) ListGenerators(ctx context.Context, kind GeneratorKind) ([]GeneratorDef, error)

ListGenerators returns the named generators registered under a single generator kind in the current tenant scope. Since xolu keeps a separate list per kind, a consumer building a full generator inventory must call this method for each of AllGeneratorKinds.

Hits GET /api/v2/gen/{kind}. Returns *client.Error on non-2xx.

Note: named sequences do NOT appear in this listing. Sequences live at a separate route (/api/v2/gen/seq) which xolu v0.14.3 exposes only per-name, not as a list. See the xolu technical-debt tracker.

func (*Client) ListMachineDefs

func (c *Client) ListMachineDefs(ctx context.Context) ([]MachineDefSummary, error)

ListMachineDefs enumerates every registered FSM definition in the current tenant scope.

Hits GET /api/v2/.../fsm/def. Returns *client.Error on non-2xx.

func (*Client) ListMachines

func (c *Client) ListMachines(ctx context.Context, filter *MachineFilter) ([]MachineSummary, error)

ListMachines returns every machine matching an optional filter. A nil filter (or a filter with all fields zero) returns every machine in the current tenant scope.

Hits GET /api/v2/fsm/machine?[filter query params].

The wire envelope key is "machines" per xolu's handleFSMMachineList.

func (*Client) ListSequences

func (c *Client) ListSequences(ctx context.Context) ([]SequenceSummary, error)

ListSequences enumerates the tenant's named sequences, sorted by name.

Hits GET /api/v2/.../gen/seq (T-25). Returns *client.Error on non-2xx. Returns SequenceSummary values (which match the list wire format), not the Sequence type used by GetSequence — see T-32 for the divergence.

func (*Client) OQL

func (c *Client) OQL(ctx context.Context, query string) (*OQLResult, error)

OQL executes an OQL (SQL-like) query.

func (*Client) Patch

func (c *Client) Patch(ctx context.Context, entity string, id int64, data map[string]any) (*Entity, error)

Patch partially updates an existing entity. xolu returns {"message":"…"} on success — no document echo. Data on the returned Entity is nil; call Get if the updated document is needed.

func (*Client) PatchMachine

func (c *Client) PatchMachine(ctx context.Context, id int64, req PatchMachineRequest) (*Machine, error)

PatchMachine applies overrides to a machine's spec snapshot. Live state, live variable values, and history are preserved unchanged.

Hits PATCH /api/v2/fsm/machine/{id}. Returns *client.Error carrying an XOLU-FSM* validation code on non-2xx.

The returned *Machine reflects the patched machine (identity, current state, live vars) — the underlying snapshot spec is not echoed back; callers who need the post-patch spec should re-fetch the machine's definition or read the snapshot from xolu's storage tier directly.

func (*Client) Ready

func (c *Client) Ready(ctx context.Context) error

Ready checks if the xolu server is ready to serve traffic.

Hits GET /ready. Returns nil on 200 (server is fully initialised and the storage layer's Ping succeeded). Returns a non-nil error on 503 (server is still initialising or storage is unreachable), any other non-2xx response, transport failure, or timeout.

Ready is the correct endpoint for readiness probes and for consumers that want to gate their own traffic on xolu's ability to serve — for example, molu's health probe in its gated-dispatch design.

Auth is not required to reach /ready; the endpoint is deliberately unauthenticated so probes work without credentials.

func (*Client) Save

func (c *Client) Save(ctx context.Context, entity string, id int64, data map[string]any) (created bool, err error)

Save upserts an entity with a caller-specified ID. xolu endpoint: POST /{entity}/save/{id} Returns created=true when a new record was inserted, false when an existing record was replaced. Use this for idempotent writes where the caller owns the ID (e.g. device registration keyed on hardware ID).

func (*Client) Search

func (c *Client) Search(ctx context.Context, entity string, params SearchParams) ([]Entity, error)

Search performs a full-text search on an entity collection. Search performs a full-text search across entities. xolu endpoint: GET /api/v1/search?q=…&entity={optional} Response: {"query":"…","entity":"…","count":N,"results":[flat docs…]} The entity argument is deprecated — populate SearchParams.Entity instead. If both are non-empty, SearchParams.Entity takes precedence.

func (*Client) Sulpher

func (c *Client) Sulpher(ctx context.Context, query string) (*GraphQueryResult, error)

Sulpher is a backward-compatible alias for GraphQuery with maxDepth=0. Deprecated: use GraphQuery.

func (*Client) Update

func (c *Client) Update(ctx context.Context, entity string, id int64, data map[string]any) (*Entity, error)

Update replaces an existing entity. xolu returns {"message":"…"} on success — no document echo. Data on the returned Entity is nil; call Get if the updated document is needed.

func (*Client) V2Availability

func (c *Client) V2Availability(ctx context.Context) (*V2Availability, error)

V2Availability fetches the v2 subsystem availability map — a consumer can use this to check whether xolu's v2 API is enabled on the target server and which subsystems are currently live.

Hits GET /api/v2/. This endpoint always exists when v2 is enabled and returns 404 when v2 is disabled. Does not require auth.

func (*Client) WalkMachine

func (c *Client) WalkMachine(ctx context.Context, id int64, req WalkRequest) (*WalkResult, error)

WalkMachine drives a machine through one transition. The input symbol is required; the payload is available to guards and set-clauses under the "payload." prefix during evaluation.

Hits POST /api/v2/fsm/machine/{id}/walk.

On success returns *WalkResult with the previous and current states, the terminal flag, any Mealy outputs emitted, the post-walk variable map, and the history row id.

On rejection returns *client.Error with an XOLU-FSM* code. Common rejection codes:

XOLU-FSM003  machine not found
XOLU-FSM004  no transition for (state, input)
XOLU-FSM005  guard rejected the transition
XOLU-FSM006  machine is in a terminal state (no further walks)
XOLU-FSM007  input query failed
XOLU-FSM008  storage error inside the walk transaction

Callers can dispatch on Error.Code to distinguish these.

func (*Client) WithTenantContext

func (c *Client) WithTenantContext(tenantID string) *Client

WithTenantContext returns a new client with the specified tenant ID. This is useful for per-request tenant context.

func (*Client) WithTimeout

func (c *Client) WithTimeout(timeout time.Duration) *Client

WithTimeout returns a shallow-copied client whose per-call timeout is set to the given value. Useful for one-off overrides:

err := client.WithTimeout(2*time.Second).Ready(ctx)

The parent client is not modified.

type ClientOption

type ClientOption func(*Client)

ClientOption configures the Client.

func WithAPIKey

func WithAPIKey(key string) ClientOption

WithAPIKey sets the API key sent as "Authorization: Bearer <key>" on every request. Corresponds to XOLU_AUTH_TYPE=apikey on the server and to entries in the server's XOLU_API_KEYS list.

Only one of WithAPIKey, WithBearerToken, WithJWT should be set. If more than one is set, the last one wins.

func WithBearerToken

func WithBearerToken(token string) ClientOption

WithBearerToken sets a server-issued bearer token sent as "Authorization: Bearer <token>" on every request. Corresponds to XOLU_AUTH_TYPE=bearertoken on the server.

Only one of WithAPIKey, WithBearerToken, WithJWT should be set. If more than one is set, the last one wins.

func WithCallTimeout

func WithCallTimeout(timeout time.Duration) ClientOption

WithCallTimeout sets the default per-call timeout. Every request's context is wrapped with context.WithTimeout(timeout) before dispatch, unless the caller's context already carries a tighter deadline (in which case the caller's deadline wins).

A zero timeout means "no per-call timeout" — the client relies on the caller's context deadline and on the httpClient's own Timeout field.

This complements rather than replaces WithHTTPClient's Timeout field. The httpClient's Timeout is a hard ceiling on total request duration including body read; WithCallTimeout is a per-call deadline on the whole operation (retries included).

func WithHTTPClient

func WithHTTPClient(c *http.Client) ClientOption

WithHTTPClient sets a custom HTTP client.

func WithJWT

func WithJWT(token string) ClientOption

WithJWT sets a JWT sent as "Authorization: Bearer <jwt>" on every request. The JWT must be signed with the secret configured as XOLU_JWT_SECRET on the server. Corresponds to XOLU_AUTH_TYPE=jwt on the server; JWT claims like tenants:[...] and tenant_admin:true are honoured by xolu's TenantAuthMode.

Only one of WithAPIKey, WithBearerToken, WithJWT should be set. If more than one is set, the last one wins.

func WithLogger

func WithLogger(logger *slog.Logger) ClientOption

WithLogger enables structured request telemetry via log/slog. Every completed HTTP attempt is logged at debug level (method, path, status, duration, attempt number); auth failures at info level; retries at warn level. Never any payload content.

The default (no option supplied) is a discarding logger — the client emits no telemetry unless the caller explicitly opts in. This avoids polluting the caller's log stream through slog.Default().

Passing nil is equivalent to omitting the option.

func WithRetryPolicy

func WithRetryPolicy(p RetryPolicy) ClientOption

WithRetryPolicy enables automatic retries for idempotent requests. See the RetryPolicy documentation for the semantics.

The default (no option supplied) is "no retries" — MaxAttempts=1 — matching pre-Stage-4 client behaviour. Callers must opt in explicitly.

Only GET, HEAD, PUT, DELETE, and OPTIONS retry. POST and PATCH never retry regardless of policy, per RFC 9110 §9.2.2 idempotency guarantees. If a caller needs to retry a POST or PATCH they consider replay-safe, they wrap the call themselves.

func WithTenant

func WithTenant(tenantID string) ClientOption

WithTenant sets the default tenant ID for all requests.

func WithTenantID

func WithTenantID(id uint16) ClientOption

WithTenantID sets the tenant for all requests, formatting the uint16 ID as the 4-digit uppercase hex prefix xolu requires (e.g. 1 -> "0001"). Prefer this over WithTenant when working with numeric tenant IDs.

type CommitAppend

type CommitAppend struct {
	Entity string         `json:"entity"`
	ID     *int64         `json:"id,omitempty"` // nil = auto-assign
	Data   map[string]any `json:"data"`
}

CommitAppend describes one record to insert in a Commit operation. If ID is nil xolu auto-assigns an ID. An explicit ID that already exists causes ErrAlreadyExists and rolls back the entire commit.

type CommitRequest

type CommitRequest struct {
	Update CommitUpdate   `json:"update"`
	Append []CommitAppend `json:"append"`
}

CommitRequest is the payload for Commit. Maximum 25 entries in Append.

type CommitResult

type CommitResult struct {
	Update struct {
		Entity  string `json:"entity"`
		ID      int64  `json:"id"`
		Created bool   `json:"created"`
		Version int    `json:"version"`
	} `json:"update"`
	Appended []struct {
		Entity string `json:"entity"`
		ID     int64  `json:"id"`
	} `json:"appended"`
}

CommitResult is returned on a successful Commit.

type CommitUpdate

type CommitUpdate struct {
	Entity  string         `json:"entity"`
	ID      int64          `json:"id"`
	Version *int           `json:"version,omitempty"` // nil = unconditional
	Data    map[string]any `json:"data"`
}

CommitUpdate describes the entity to upsert in a Commit operation. If Version is non-nil the write is conditional: it succeeds only when the stored _version matches *Version. A mismatch returns ErrConflict (409).

type CreateMachineRequest

type CreateMachineRequest struct {
	// Definition is the fsm_def_id to instantiate.
	Definition int64 `json:"definition"`
	// Ref is an optional external identifier bound to the machine.
	Ref string `json:"ref,omitempty"`
	// Overrides narrow variable defaults or guard expressions on a
	// per-machine basis. Nil means no overrides.
	Overrides *MachineOverrides `json:"overrides,omitempty"`
}

CreateMachineRequest is the body of Client.CreateMachine. The definition ID is required; Ref is optional and binds an external identifier to the machine (an entity URI, a business key, a slug — xolu does not interpret it beyond using it for lookup and filtering).

Overrides let the caller narrow variable defaults or guard expressions at instantiation time without editing the definition. The override map is applied to a snapshot copy of the definition and then re-validated as a whole; failure returns XOLU-FSM* validation errors.

Note that inline entity creation via the `entity` field is deferred in xolu v0.14.4 preview and is not exposed by the client. Bind with `ref` instead.

type Entity

type Entity struct {
	ID        int64
	Data      map[string]any
	CreatedAt time.Time
	UpdatedAt time.Time
}

Entity represents a document stored in xolu. Data holds the complete flat document as returned by the server, including the "id" field. ID is extracted for convenience.

After Create, Data is nil — xolu does not echo the document on creation. Call Get if the full document is needed after a write. After Update or Patch, Data is also nil for the same reason.

type EntitySchema

type EntitySchema struct {
	// Name is the entity type name (e.g. "users", "orders").
	Name string `json:"name"`
	// Schema is the raw JSON Schema document for the entity, exactly as
	// returned by xolu.
	Schema json.RawMessage `json:"schema"`
	// Fields lists the entity's declared fields with their JSON Schema types.
	Fields []FieldDef `json:"fields,omitempty"`
	// Refs lists the subset of Fields that carry `"format":"ref"` — the
	// reference edges that populate xolu's graph layer.
	Refs []RefFieldDef `json:"refs,omitempty"`
}

EntitySchema describes a registered entity type — its declared fields, its JSON Schema, and the subset of fields that carry REF references to other entities.

Returned by Client.GetEntitySchema.

The `Schema` field is the raw JSON Schema xolu holds for the entity type. Field-level extraction (`Fields`, `Refs`) is done client-side by walking the schema; consumers that need more sophisticated inspection can decode `Schema` themselves.

type EntityTypeSummary

type EntityTypeSummary struct {
	Name string `json:"name"`
}

EntityTypeSummary is one entry of GET /api/v1/schemas (T-24): an entity type with a registered schema. Name-only by design — the server tracks no registration timestamps.

type Error

type Error struct {
	// Code is the XOLU-<AREA><NUM> error code (e.g. "XOLU-ST001"). Empty when
	// the server did not return a structured error body.
	Code string
	// HTTPStatus is the HTTP status code (e.g. 400, 404, 500).
	HTTPStatus int
	// Message is the human-readable error message.
	Message string
	// Detail is the raw JSON body of the error response, preserved verbatim
	// so callers can extract server-specific fields the client does not
	// model. Nil when the response body was empty or not valid JSON.
	Detail json.RawMessage

	// StatusCode is preserved as an alias for HTTPStatus for backwards
	// compatibility with earlier client releases. New code should use
	// HTTPStatus.
	//
	// Deprecated: use HTTPStatus.
	StatusCode int
	// Details is preserved as a decoded map for backwards compatibility.
	// New code should use Detail (raw JSON) and decode as needed.
	//
	// Deprecated: use Detail.
	Details map[string]any
}

Error represents an error response from xolu.

xolu's server writes structured errors in the shape:

{"error":{"code":"XOLU-ST001","message":"...","status":400}}

The client parses that shape into Code, Message, and Status. When the server returns an error in the older flat shape ({"error":"message"}) or a non-JSON body, Code is left empty and Message carries the raw content.

Callers can dispatch on the code using errors.As:

var xerr *client.Error
if errors.As(err, &xerr) && xerr.Code == "XOLU-ST001" {
    // entity not found
}

func (*Error) Error

func (e *Error) Error() string

type EventDef

type EventDef struct {
	// ID is the subscription's numeric identifier, tenant-scoped.
	ID int64 `json:"id"`
	// EventType is the event type this subscription reacts to
	// (e.g. "entity.updated", "fsm.step", "commit.applied").
	EventType string `json:"event_type"`
	// ActionType names the delivery mechanism ("webhook", "oql").
	ActionType string `json:"action_type"`
	// Config is the raw action configuration.
	Config json.RawMessage `json:"config,omitempty"`
	// Execution declares the delivery mode ("async" today; "sync" is
	// accepted but silently downgraded — see the xolu changelog).
	Execution string `json:"execution"`
	// CreatedAt is the timestamp of subscription creation.
	CreatedAt string `json:"created_at,omitempty"`
}

EventDef is one registered event subscription, as returned by Client.ListEventDefs and Client.GetEventDef.

Wire shape verified against pkg/server/v2_event_handlers.go eventDef.

`Config` is the raw action configuration (webhook URL and headers, OQL query, etc.). Its shape depends on ActionType.

type FieldDef

type FieldDef struct {
	// Name is the field name as it appears in JSON documents.
	Name string `json:"name"`
	// Type is the JSON Schema type ("string", "integer", "number",
	// "boolean", "object", "array") or a xolu-specific format tag
	// ("decimal", "timestamp", "ref").
	Type string `json:"type"`
	// Required is true when the field is listed under the schema's
	// "required" array.
	Required bool `json:"required,omitempty"`
	// Format is the JSON Schema "format" declaration when present
	// (e.g. "email", "uuid", "date-time"). Empty when absent.
	Format string `json:"format,omitempty"`
}

FieldDef is a single declared field on an entity.

type GCPolicy

type GCPolicy struct {
	StalledAfter string `json:"stalled_after,omitempty"`
	DeadAfter    string `json:"dead_after,omitempty"`
	OnGCCollect  string `json:"on_gc_collect,omitempty"`
}

GCPolicy is the optional GC policy block on a definition.

type GeneratorDef

type GeneratorDef struct {
	Name   string          `json:"name"`
	Config json.RawMessage `json:"config,omitempty"`
}

GeneratorDef is one named generator instance under a given kind, as returned by Client.ListGenerators.

The `Config` field is the raw generator configuration; its shape depends on the kind and is documented in the xolu generator subsystem.

type GeneratorKind

type GeneratorKind string

GeneratorKind identifies one of xolu's stateless generator kinds. Named generators are per-kind lists queryable with Client.ListGenerators.

The four values below match the routes registered in pkg/server/v2_handlers.go under /api/v2/gen/{type}.

const (
	GeneratorUUIDv4 GeneratorKind = "uuid_v4"
	GeneratorUUIDv7 GeneratorKind = "uuid_v7"
	GeneratorCUID   GeneratorKind = "cuid"
	GeneratorULID   GeneratorKind = "ulid"
)

type GraphQueryResult

type GraphQueryResult struct {
	Status string           `json:"status"`
	Result []map[string]any `json:"result"` // xolu uses "result", not "data"
	Stats  GraphQueryStats  `json:"stats"`
}

GraphQueryResult represents the result of a Sulpher graph query. Previously named SulpherResult; renamed to match the xolu endpoint name.

type GraphQueryStats

type GraphQueryStats struct {
	NodesTraversed int   `json:"nodes_traversed"`
	PathsFound     int   `json:"paths_found"`
	ExecutionTime  int64 `json:"execution_time_ms"`
}

GraphQueryStats contains Sulpher execution statistics.

type HistoryEntry

type HistoryEntry struct {
	// ID is the numeric identifier of this history row.
	ID int64 `json:"id"`
	// From is the state the machine was in before this step. Nil for the
	// initial "machine created" entry.
	From *string `json:"from"`
	// To is the state the machine was in after this step. Always set,
	// including on the initial entry (equal to the initial state).
	To string `json:"to"`
	// Input is the input symbol that drove the transition. Nil for the
	// initial entry.
	Input *string `json:"input"`
	// Payload is the raw payload supplied by the walk caller. Preserved
	// as raw JSON because xolu emits arbitrary caller-supplied shapes.
	Payload json.RawMessage `json:"payload,omitempty"`
	// Vars is the live variable map after this step, preserved as raw
	// JSON for the same reason.
	Vars json.RawMessage `json:"vars"`
	// Outputs is the transition's Mealy output, preserved as raw JSON.
	// Omitted when the transition emitted nothing.
	Outputs json.RawMessage `json:"outputs,omitempty"`
	// Note is a human-readable annotation. Present on the initial
	// "machine created" entry; typically nil on walk entries.
	Note string `json:"note,omitempty"`
	// At is the timestamp of this step.
	At string `json:"at"`
}

HistoryEntry is one row of a machine's history, as returned by Client.GetMachineHistory. The list is ordered by history id (ascending).

The very first entry has From=nil, Input=nil, and Note="machine created"; subsequent entries record each walk with the emitting transition's input and payload.

type ListParams

type ListParams struct {
	Limit  int
	Offset int
	Sort   string // field name, prefix with - for descending
}

ListParams configures list queries.

type ListResult

type ListResult struct {
	Entities   []Entity
	Page       int
	PerPage    int
	TotalItems int
	TotalPages int
}

ListResult holds a page of entities and the pagination metadata returned by xolu's PagedResponse envelope.

type Machine

type Machine struct {
	// ID is the machine's numeric identifier, tenant-scoped.
	ID int64 `json:"id"`
	// Definition is the fsm_def_id the machine was instantiated from.
	Definition int64 `json:"definition"`
	// DefinitionName is the cached copy of the definition's name.
	DefinitionName string `json:"definition_name"`
	// DefinitionDeleted is true when the source definition has been
	// deleted since machine creation. The machine continues to operate
	// on its self-contained snapshot; this flag is informational.
	DefinitionDeleted bool `json:"definition_deleted"`
	// State is the machine's current state name.
	State string `json:"state"`
	// Vars is the current live variable map. Keys are variable names,
	// values are the raw JSON values as the FSM evaluator stores them.
	Vars map[string]interface{} `json:"vars"`
	// Ref is the optional external identifier bound at creation time,
	// echoed only when present.
	Ref string `json:"ref,omitempty"`
	// CreatedAt is the timestamp of machine creation.
	CreatedAt string `json:"created_at"`
}

Machine is the full record returned by Client.CreateMachine, Client.GetMachine, and Client.PatchMachine. It carries identity, current state, and live variable values.

Response shape identical for create/get/patch (verified from source).

type MachineDef

type MachineDef struct {
	// ID is the definition's numeric identifier, tenant-scoped.
	ID int64 `json:"id"`
	// CreatedAt is the timestamp of definition creation.
	CreatedAt string `json:"created_at"`
	// Spec is the definition body — states, transitions, variables.
	Spec MachineSpec `json:"spec"`
	// Analysis is xolu's structural-analysis output for the definition.
	// Kept opaque as json.RawMessage because the shape is server-internal.
	Analysis json.RawMessage `json:"analysis,omitempty"`
}

MachineDef is the full body of an FSM definition, as returned by Client.GetMachineDef.

Wire shape verified against pkg/server/v2_fsm_def_handlers.go handleFSMDefGet and the internal fsmDefinitionSpec / fsmStateSpec / fsmVariableSpec / fsmTransitionSpec types in pkg/server/v2_fsm_common.go.

The `Analysis` field is xolu's internal analysis output (reachability, determinism, and other structural properties). It is preserved as json.RawMessage because its shape is xolu-server-internal and may evolve.

type MachineDefSummary

type MachineDefSummary struct {
	ID        int64  `json:"id"`
	Name      string `json:"name"`
	CreatedAt string `json:"created_at"`
}

MachineDefSummary is one entry in the list returned by Client.ListMachineDefs. It carries only identity fields; the full definition body must be fetched with Client.GetMachineDef.

Wire shape verified against pkg/server/v2_fsm_def_handlers.go handleFSMDefList.

type MachineFilter

type MachineFilter struct {
	// Definition filters by fsm_def_id. Zero means no filter.
	Definition int64
	// State filters by current state name. Empty string means no filter.
	State string
	// Ref filters by the external identifier bound at creation. Empty
	// string means no filter.
	Ref string
}

MachineFilter is an optional set of query parameters for Client.ListMachines. A nil filter or a filter with all fields empty returns every machine in the current tenant scope.

The three filters map directly to the "definition", "state", and "ref" query parameters accepted by GET /api/v2/fsm/machine.

type MachineOverrides

type MachineOverrides struct {
	// Variables overrides variable declarations. Keyed by variable name.
	Variables map[string]VariableDef `json:"variables,omitempty"`
	// Transitions overrides transition guards. Keyed by transition input.
	Transitions map[string]TransitionOverride `json:"transitions,omitempty"`
}

MachineOverrides is the shape of the `overrides` block on CreateMachineRequest and PatchMachineRequest. Mirrors xolu's internal fsmOverrides in pkg/server/v2_fsm_common.go.

type MachineResult

type MachineResult struct {
	// Machine is the machine's numeric identifier.
	Machine int64 `json:"machine"`
	// State is the current state name.
	State string `json:"state"`
	// Terminal is true when State is a terminal state.
	Terminal bool `json:"terminal"`
	// Vars is the live variable map.
	Vars map[string]interface{} `json:"vars"`
	// FinalOutput is the output emitted by the transition that reached
	// the current state, but only meaningful once Terminal is true.
	// Preserved as raw JSON because xolu emits either a JSON array of
	// output names or an empty array; consumers can decode as needed.
	FinalOutput json.RawMessage `json:"final_output,omitempty"`
}

MachineResult is the response of Client.GetMachineResult — a convenience over state + vars + final transition output.

For a machine that has not yet reached a terminal state, Terminal is false and FinalOutput is nil; State and Vars still reflect the current non-final values, so a caller can poll this endpoint and act once Terminal becomes true.

type MachineSpec

type MachineSpec struct {
	Name           string                 `json:"name"`
	Description    string                 `json:"description,omitempty"`
	Initial        string                 `json:"initial"`
	Determinism    string                 `json:"determinism"`
	States         map[string]StateDef    `json:"states"`
	Variables      map[string]VariableDef `json:"variables,omitempty"`
	Transitions    []TransitionDef        `json:"transitions"`
	OutputAlphabet []string               `json:"output_alphabet,omitempty"`
	LinkedStates   map[string]int64       `json:"linked_states,omitempty"`
	GC             *GCPolicy              `json:"gc,omitempty"`
	// InputQueries associates an OQL SELECT with an input symbol. See the
	// xolu documentation for the exact semantics of the query-before-walk
	// evaluation pattern.
	InputQueries map[string]string `json:"input_queries,omitempty"`
}

MachineSpec is the wire-format definition body. It matches xolu's internal fsmDefinitionSpec byte-for-byte.

type MachineState

type MachineState struct {
	State    string `json:"state"`
	Terminal bool   `json:"terminal"`
}

MachineState is the response of Client.GetMachineState — a lightweight current-state snapshot without the full variable map. Use GetMachine for the richer view.

type MachineSummary

type MachineSummary struct {
	// ID is the machine's numeric identifier, tenant-scoped.
	ID int64 `json:"id"`
	// Definition is the fsm_def_id the machine was instantiated from.
	Definition int64 `json:"definition"`
	// DefinitionName is a cached copy of the definition's name at
	// creation time. Persists even if the definition is later renamed or
	// deleted.
	DefinitionName string `json:"definition_name"`
	// State is the machine's current state name.
	State string `json:"state"`
	// Ref is the optional external identifier bound at creation time,
	// e.g. an entity URI. Nil when the machine was created without a ref.
	Ref *string `json:"ref"`
	// CreatedAt is the timestamp of machine creation.
	CreatedAt string `json:"created_at"`
}

MachineSummary is one entry in the list returned by Client.ListMachines. The list envelope key is "machines" per xolu's handleFSMMachineList.

type NeighborResult

type NeighborResult struct {
	Outgoing map[string]string `json:"outgoing,omitempty"`
	Incoming map[string]string `json:"incoming,omitempty"`
}

NeighborResult is returned by GraphNeighbors. Outgoing and Incoming map neighbour node ID to relationship label.

type OQLResult

type OQLResult struct {
	Status string           `json:"status"`
	Data   []map[string]any `json:"data"`
	Stats  OQLStats         `json:"stats"`
}

OQLResult represents the result of an OQL query.

type OQLStats

type OQLStats struct {
	RowsScanned   int   `json:"rows_scanned"`
	RowsReturned  int   `json:"rows_returned"`
	RowsAffected  int   `json:"rows_affected,omitempty"`
	ExecutionTime int64 `json:"execution_time_ms"`
}

OQLStats contains OQL execution statistics.

type Objective

type Objective string

Objective selects how CalOpenings ranks candidate windows. The four values are the complete set the server implements; the zero value "" lets the server default to ObjectiveEarliest.

const (
	ObjectiveEarliest   Objective = "earliest"
	ObjectiveFirstFit   Objective = "first-fit"
	ObjectiveEmptiest   Objective = "emptiest"
	ObjectiveLongestClr Objective = "longest-clear-margin"
)

type PatchMachineRequest

type PatchMachineRequest struct {
	Overrides *MachineOverrides `json:"overrides,omitempty"`
}

PatchMachineRequest is the body of Client.PatchMachine.

A patch applies overrides to the machine's spec snapshot; live state, live variable values, and history are preserved unchanged. Re-validation of the resulting snapshot occurs as a whole; failure returns XOLU-FSM* errors and no persistent change is made.

type PathResult

type PathResult struct {
	From   string   `json:"from"`
	To     string   `json:"to"`
	Exists bool     `json:"exists"`
	Path   []string `json:"path"`
	Length int      `json:"length"`
}

PathResult is returned by GraphShortestPath.

type RefFieldDef

type RefFieldDef struct {
	// Name is the field name (e.g. "author_id").
	Name string `json:"name"`
	// Target is the entity type the reference points to
	// (e.g. "users"). Extracted from the schema's `"target"` extension
	// when present; empty when the target is polymorphic.
	Target string `json:"target,omitempty"`
}

RefFieldDef is a field whose value is a reference to another entity.

type RetryPolicy

type RetryPolicy struct {
	// MaxAttempts is the total number of attempts including the first.
	// MaxAttempts=1 means "no retry", MaxAttempts=3 means "up to two
	// retries after the first attempt". Values less than 1 are treated
	// as 1.
	MaxAttempts int

	// InitialBackoff is the wait before the second attempt. Subsequent
	// attempts wait InitialBackoff * BackoffMultiplier^(attempt-1),
	// capped at MaxBackoff.
	InitialBackoff time.Duration

	// MaxBackoff is the ceiling on backoff between attempts. Zero means
	// "no ceiling", which is rarely what a caller wants; the default
	// policy from DefaultRetryPolicy sets a sensible ceiling.
	MaxBackoff time.Duration

	// BackoffMultiplier is the factor by which backoff grows between
	// attempts. Values less than 1 (including zero) are treated as 1,
	// producing constant backoff.
	BackoffMultiplier float64

	// RetryOn decides whether a given attempt outcome is retryable.
	// If nil, DefaultRetryOn is used, which retries transport errors
	// and 5xx responses.
	//
	// The predicate MUST NOT return true for context cancellation or
	// deadline exceeded — the retry loop honours those errors as final
	// regardless of RetryOn's answer, but the predicate is called first
	// and should return false on them for clarity.
	RetryOn func(resp *http.Response, err error) bool
	// contains filtered or unexported fields
}

RetryPolicy configures automatic retries for idempotent requests. The zero value corresponds to "no retries" — the same behaviour as pre-Stage-4 clients.

A caller who wants retries builds the policy explicitly:

c := client.New(baseURL,
    client.WithRetryPolicy(client.RetryPolicy{
        MaxAttempts:       3,
        InitialBackoff:    200 * time.Millisecond,
        MaxBackoff:        5 * time.Second,
        BackoffMultiplier: 2.0,
    }))

A retry policy applies to a call only when:

  • the HTTP method is idempotent (GET, HEAD, PUT, DELETE, OPTIONS), and
  • the failure classifies as retryable via RetryOn (default: transport errors and 5xx responses; not 4xx; not context cancellation).

Retries are silent to the caller: telemetry emitted via WithLogger reports each retry at warn level, but the returned error and result reflect only the final attempt.

type SearchParams

type SearchParams struct {
	Query  string
	Entity string // optional entity type filter
	Limit  int
	Offset int
}

SearchParams configures search queries. Entity is optional — when set, xolu scopes the search to that entity type.

type Sequence

type Sequence struct {
	Name        string `json:"name"`
	Start       int64  `json:"start"`
	Current     int64  `json:"current"`
	IncrementBy int64  `json:"increment_by"`
	Cycle       bool   `json:"cycle"`
	MinVal      *int64 `json:"min_val,omitempty"`
	MaxVal      *int64 `json:"max_val,omitempty"`
}

Sequence is a single named monotonic sequence, as returned by Client.GetSequence.

Note that xolu v0.14.3 does not expose a "list all sequences" endpoint; consumers that need to enumerate sequences must know their names out of band. See the xolu debt tracker for the planned list endpoint. Sequence matches handleSeqGet's wire format. T-32: the earlier shape declared `step` and `created_at`, which the server never sends — Step was silently zero from Stage 2 through v0.15.3. Breaking change in v0.16.0: Step → IncrementBy, CreatedAt dropped, Cycle and the optional min/max bounds added.

type SequenceSummary

type SequenceSummary struct {
	Name        string `json:"name"`
	Current     int64  `json:"current"`
	IncrementBy int64  `json:"increment_by"`
	Cycle       bool   `json:"cycle"`
}

SequenceSummary is one entry of GET /api/v2/.../gen/seq (T-25). Field names match the wire exactly; note this differs from the Sequence type used by GetSequence, whose "step"/"created_at" tags do not match what the server actually sends (filed as register item T-32).

type StateDef

type StateDef struct {
	Terminal bool `json:"terminal"`
}

StateDef is a single state declaration.

type SulpherResult

type SulpherResult = GraphQueryResult

SulpherResult is an alias for GraphQueryResult for backward compatibility. Deprecated: use GraphQueryResult.

type TransitionDef

type TransitionDef struct {
	From   json.RawMessage   `json:"from"`
	Input  string            `json:"input"`
	To     string            `json:"to"`
	Guard  string            `json:"guard,omitempty"`
	Output string            `json:"output,omitempty"`
	Set    map[string]string `json:"set,omitempty"`
}

TransitionDef is a single transition. `From` is a json.RawMessage because xolu accepts either a single state name (JSON string) or a list of state names (JSON array) on the wire. Use FromStates() to normalise.

`Guard` and `Set` values are T-SQL expression fragments, evaluated at walk time by the FSM evaluator. They are returned verbatim so callers can display them, log them, or reason about them without re-fetching.

func (*TransitionDef) FromStates

func (t *TransitionDef) FromStates() ([]string, error)

FromStates normalises the From field into a slice of state names, accepting either a JSON string or a JSON array of strings.

type TransitionOverride

type TransitionOverride struct {
	// Guard is the new T-SQL guard expression. Nil means "leave the
	// existing guard in place"; the empty string means "clear the guard".
	Guard *string `json:"guard,omitempty"`
}

TransitionOverride carries the overridable fields of a transition. In xolu v0.14.4 only Guard is overridable.

type V2Availability

type V2Availability struct {
	Version    string          `json:"version"`
	Enabled    bool            `json:"enabled"`
	AsOf       time.Time       `json:"as_of"`
	Warning    string          `json:"warning,omitempty"`
	Subsystems json.RawMessage `json:"subsystems,omitempty"`
}

V2Availability is the response of GET /api/v2/ — the map of v2 subsystems and their current status. Useful for a consumer to check whether v2 is enabled on this server before attempting v2 calls.

The `Subsystems` map is left as json.RawMessage because the per-subsystem entries have evolved as new subsystems land; keeping it raw avoids version coupling.

type VariableDef

type VariableDef struct {
	Type    string      `json:"type"`
	Default interface{} `json:"default"`
}

VariableDef is a single machine-variable declaration.

type VariableSnapshot

type VariableSnapshot struct {
	Value   interface{} `json:"value"`
	Type    string      `json:"type,omitempty"`
	Default interface{} `json:"default,omitempty"`
}

VariableSnapshot is one entry in the map returned by Client.GetMachineVars. Each variable's live value is carried alongside its declared type and the default value from the machine's snapshot spec — a caller can distinguish "value equal to default" from "value has diverged" without re-fetching the definition.

type WalkRequest

type WalkRequest struct {
	// Input is the input symbol driving the transition. Required.
	Input string `json:"input"`
	// Payload provides arbitrary key/value data available to guards and
	// set-clauses under the "payload." prefix during evaluation. Nil is
	// permitted; the FSM will use only variables and (optionally) the
	// pre-walk query result.
	Payload map[string]interface{} `json:"payload,omitempty"`
}

WalkRequest is the body of Client.WalkMachine.

type WalkResult

type WalkResult struct {
	// Previous is the state the machine was in before the walk.
	Previous string `json:"previous"`
	// Current is the state the machine is in after the walk.
	Current string `json:"current"`
	// Terminal is true when Current is a terminal state.
	Terminal bool `json:"terminal"`
	// Outputs is the Mealy output emitted by the transition. Multi-valued
	// because a machine's output alphabet may name several outputs;
	// individual transitions typically emit at most one.
	Outputs []string `json:"outputs"`
	// Vars is the live variable map after set-clauses have applied.
	Vars map[string]interface{} `json:"vars"`
	// HistoryID is the id of the history row recording this walk.
	HistoryID int64 `json:"history_id"`
}

WalkResult is the response of Client.WalkMachine, returned on a successful transition.

A rejected walk (no matching transition, guard failed, terminal state, etc.) returns *client.Error carrying an XOLU-FSM* code — not a WalkResult with a diagnostic. Callers dispatch on the error code.

Jump to

Keyboard shortcuts

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