store

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 13 Imported by: 2 modules, 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.

Documentation

Overview

Package store provides a generic, namespaced, directed graph store.

Kinds and relationship types are opaque consumer vocabulary. A store never assigns product meaning or authority to graph records.

The contract every implementation follows is written as data in res/graph/testdata/store/v1: the entities, the naming, secret and size rules, the error codes, the SQLite table layout and the operation cases. NewMemory is the in-memory implementation; res/graph/store/sqlite is the durable one.

Index

Constants

View Source
const (
	DefaultMaxChanges            = 4096
	DefaultMaxChangeBytes        = 16 << 20
	DefaultMaxTransactionRecords = 65536
	DefaultMaxRecordBytes        = 1 << 20
	DefaultMaxResults            = 65536
	DefaultMaxSnapshotRecords    = 1 << 20
	// MaxStringBytes bounds one string attribute value.
	MaxStringBytes = 4096
)

Variables

View Source
var (
	ErrInvalid         = errors.New("invalid graph record or transaction")
	ErrInvalidName     = errors.New("invalid namespace, kind, or relationship name")
	ErrLimitRequired   = errors.New("query limit must be positive")
	ErrSchemaViolation = errors.New("transaction violates the namespace schema")
	ErrIncidentEdges   = errors.New("vertex has incident edges")
	ErrNotFound        = errors.New("graph record not found")
	ErrNotRegistered   = errors.New("namespace is not registered")
	ErrDanglingEdge    = errors.New("edge endpoint does not exist")
	ErrConflict        = errors.New("graph revision conflict")
	ErrIdempotency     = errors.New("idempotency key reused with different transaction")
	ErrSchemaMismatch  = errors.New("namespace is registered with different rules at this schema version")
	ErrSecretValue     = errors.New("secret-like values are not allowed in graph attributes")
	ErrTooLarge        = errors.New("graph request exceeds a store bound")
	ErrCursorExpired   = errors.New("graph change cursor has expired; take a new snapshot")
	ErrUnsupported     = errors.New("graph store layout is not supported")
	ErrClosed          = errors.New("graph store is closed")
	ErrBusy            = errors.New("graph store is locked by another writer")
)

The sentinel errors of the store. Code maps each to its contract code.

Functions

func Canonical added in v0.3.0

func Canonical(v any) ([]byte, error)

Canonical encodes v as canonical JSON: the value's JSON form with object keys sorted by UTF-16 code units, no insignificant whitespace, numbers in the shortest form that round-trips (as ECMAScript prints them) and strings with only '"', '\\' and control characters escaped (RFC 8785). It is the form idempotency fingerprints, stored schemas and stored changes use.

func ChangeSize added in v0.3.0

func ChangeSize(change Change) (int, error)

ChangeSize is the size a change counts against MaxChangeBytes: the length of its canonical JSON.

func CheckTransaction added in v0.3.0

func CheckTransaction(tx Transaction, o Options) error

CheckTransaction applies the rules that need no stored state: the transaction's names, its size bound, and the naming, secret and size rules of every record. Backends call it before taking a write lock.

func Code added in v0.3.0

func Code(err error) string

Code returns the contract code of err: one of the codes in res/system/testdata/codes.json, or "" for a nil error. An error the store does not recognize is "io".

func Fingerprint added in v0.3.0

func Fingerprint(tx Transaction) (string, error)

Fingerprint is the lowercase hex SHA-256 of the transaction's canonical JSON. An idempotency key binds to it.

func SameSchema added in v0.3.0

func SameSchema(a, b Schema) bool

SameSchema reports whether a and b declare the same rules at the same version.

func ValidateAttributes

func ValidateAttributes(attrs map[string]any) error

ValidateAttributes checks ordinary graph metadata before projection. It applies the same secret-marker and size rules as Store.Apply.

func ValidateSchema added in v0.3.0

func ValidateSchema(schema Schema) error

ValidateSchema checks a schema's names: the namespace, and every kind and relationship type and endpoint kind under it.

Types

type Change

type Change struct {
	Cursor          uint64    `json:"cursor"`
	Namespace       string    `json:"namespace"`
	Revision        uint64    `json:"revision"`
	Committed       time.Time `json:"committed_at"`
	Vertices        []Vertex  `json:"vertices,omitempty"`
	Edges           []Edge    `json:"edges,omitempty"`
	DeletedVertices []string  `json:"deleted_vertices,omitempty"`
	DeletedEdges    []string  `json:"deleted_edges,omitempty"`
}

func Prepare added in v0.3.0

func Prepare(ctx context.Context, r Reader, schema Schema, revision uint64, now time.Time, tx Transaction) (Change, error)

Prepare computes the change a checked transaction makes to a namespace whose committed state r reads, at the next revision. It applies deletions, then vertex upserts, then edge upserts, checks that no edge dangles, and checks the namespace schema. The returned change has no cursor; the backend assigns it when it commits. Prepare writes nothing.

type Commit

type Commit struct {
	Namespace string    `json:"namespace"`
	Revision  uint64    `json:"revision"`
	Cursor    uint64    `json:"cursor"`
	Committed time.Time `json:"committed_at"`
	Replayed  bool      `json:"replayed,omitempty"`
}

type Edge

type Edge struct {
	Namespace  string            `json:"namespace,omitempty"`
	ID         string            `json:"id"`
	From       string            `json:"from"`
	To         string            `json:"to"`
	Type       string            `json:"type"`
	Revision   uint64            `json:"revision,omitempty"`
	CreatedAt  time.Time         `json:"created_at,omitzero"`
	UpdatedAt  time.Time         `json:"updated_at,omitzero"`
	Labels     map[string]string `json:"labels,omitempty"`
	Attributes map[string]any    `json:"attributes,omitempty"`
	Provenance Provenance        `json:"provenance,omitzero"`
}

Edge is a directed relationship from From to To.

type EdgeQuery

type EdgeQuery struct {
	Namespace string `json:"namespace"`
	Type      string `json:"type,omitempty"`
	From      string `json:"from,omitempty"`
	To        string `json:"to,omitempty"`
	Limit     int    `json:"limit"`
}

type EdgeRef

type EdgeRef struct {
	Namespace string `json:"namespace,omitempty"`
	ID        string `json:"id"`
}

type Options

type Options struct {
	MaxChanges            int `json:"max_changes,omitempty"`
	MaxChangeBytes        int `json:"max_change_bytes,omitempty"`
	MaxTransactionRecords int `json:"max_transaction_records,omitempty"`
	MaxRecordBytes        int `json:"max_record_bytes,omitempty"`
	MaxResults            int `json:"max_results,omitempty"`
	MaxSnapshotRecords    int `json:"max_snapshot_records,omitempty"`
}

Options sets the bounds of a store. Zero values take the defaults in res/graph/testdata/store/v1/rules.json. The latest commit is always kept, even when it alone exceeds MaxChangeBytes; idempotency records expire with their commit.

func (Options) WithDefaults added in v0.3.0

func (o Options) WithDefaults() Options

WithDefaults returns o with every zero bound set to its default.

type Path

type Path struct {
	Vertices []Vertex `json:"vertices"`
	Edges    []Edge   `json:"edges"`
}

func Traverse added in v0.3.0

func Traverse(ctx context.Context, t Traversal, start string, maxDepth, maxVertices int) ([]Path, error)

Traverse walks outgoing edges breadth first from start. It visits at most maxVertices vertices, including start, and follows paths of at most maxDepth edges. Each vertex is reached once, by the first path found; edges are taken in ID order. It returns one path per reached vertex other than start, in visiting order.

type Provenance

type Provenance struct {
	Source    string    `json:"source,omitempty"`
	Operation string    `json:"operation,omitempty"`
	At        time.Time `json:"at,omitzero"`
}

Provenance identifies the system or operation that produced a fact. It is descriptive metadata and grants no authority.

type Reader added in v0.3.0

type Reader interface {
	Vertex(ctx context.Context, id string) (Vertex, bool, error)
	Edge(ctx context.Context, id string) (Edge, bool, error)
	// IncidentEdges returns the edges whose From or To is id, at most limit of them.
	IncidentEdges(ctx context.Context, id string, limit int) ([]Edge, error)
}

Reader is the committed state of one namespace, as Prepare needs it. A backend implements it over its storage inside the transaction it commits in.

type Relationship added in v0.3.0

type Relationship struct {
	Type string `json:"type"`
	From string `json:"from,omitempty"`
	To   string `json:"to,omitempty"`
}

Relationship admits edges of Type. A non-empty From or To also requires the kind of that endpoint. Several rules may name one type; an edge must match one.

type Schema

type Schema struct {
	Namespace     string         `json:"namespace"`
	Version       string         `json:"version"`
	Kinds         []string       `json:"kinds,omitempty"`
	Relationships []Relationship `json:"relationships,omitempty"`
}

Schema declares the rules of one namespace. It is data, so a store keeps it with the graph and any implementation can check it. An empty Kinds admits every kind under the namespace; an empty Relationships admits every relationship type under it. The rules apply to the records a transaction writes.

func NormalizeSchema added in v0.3.0

func NormalizeSchema(schema Schema) Schema

NormalizeSchema sorts and deduplicates a schema's rules, so two schemas with the same rules have the same canonical form.

type Snapshot

type Snapshot struct {
	Namespace string `json:"namespace"`
	Revision  uint64 `json:"revision"`
	Cursor    uint64 `json:"cursor"`
	// HistoryFloor is the newest cursor that is no longer available from Changes or Watch.
	HistoryFloor uint64   `json:"history_floor,omitempty"`
	Vertices     []Vertex `json:"vertices"`
	Edges        []Edge   `json:"edges"`
}

type Store

type Store interface {
	// Register records a namespace schema. Registering the schema already
	// stored is a no-op; a new version replaces it; the same version with
	// different rules is ErrSchemaMismatch.
	Register(context.Context, Schema) error
	Apply(context.Context, Transaction) (Commit, error)
	GetVertex(ctx context.Context, namespace, id string) (Vertex, error)
	GetEdge(ctx context.Context, namespace, id string) (Edge, error)
	QueryVertices(context.Context, VertexQuery) ([]Vertex, error)
	QueryEdges(context.Context, EdgeQuery) ([]Edge, error)
	Traverse(ctx context.Context, namespace, start string, maxDepth, maxVertices int) ([]Path, error)
	Snapshot(ctx context.Context, namespace string) (Snapshot, error)
	Changes(ctx context.Context, namespace string, after uint64, limit int) ([]Change, error)
	Watch(ctx context.Context, namespace string, after uint64, buffer int) (<-chan Change, error)
	Close() error
}

func NewMemory

func NewMemory() Store

NewMemory creates an in-memory graph store with the default bounds.

func NewMemoryWithOptions

func NewMemoryWithOptions(options Options) Store

NewMemoryWithOptions creates an in-memory graph store with the given bounds.

type Transaction

type Transaction struct {
	Namespace           string      `json:"namespace"`
	IdempotencyKey      string      `json:"idempotency_key,omitempty"`
	ExpectedRevision    *uint64     `json:"expected_revision,omitempty"`
	Vertices            []Vertex    `json:"vertices,omitempty"`
	Edges               []Edge      `json:"edges,omitempty"`
	DeleteVertices      []VertexRef `json:"delete_vertices,omitempty"`
	DeleteEdges         []EdgeRef   `json:"delete_edges,omitempty"`
	DeleteIncidentEdges bool        `json:"delete_incident_edges,omitempty"`
}

Transaction is applied atomically within one namespace. A non-nil ExpectedRevision enables optimistic concurrency. DeleteVertices require DeleteIncidentEdges to explicitly detach incident edges.

type Traversal added in v0.3.0

type Traversal interface {
	Vertex(ctx context.Context, id string) (Vertex, bool, error)
	// Outgoing returns the edges whose From is id, ordered by ID.
	Outgoing(ctx context.Context, id string) ([]Edge, error)
}

Traversal is what Traverse reads from one namespace.

type Vertex

type Vertex struct {
	Namespace  string            `json:"namespace,omitempty"`
	ID         string            `json:"id"`
	Kind       string            `json:"kind"`
	Revision   uint64            `json:"revision,omitempty"`
	CreatedAt  time.Time         `json:"created_at,omitzero"`
	UpdatedAt  time.Time         `json:"updated_at,omitzero"`
	Labels     map[string]string `json:"labels,omitempty"`
	Attributes map[string]any    `json:"attributes,omitempty"`
	Provenance Provenance        `json:"provenance,omitzero"`
}

Vertex is a generic typed graph record. ID is supplied by the consumer and should remain stable for the lifetime of the logical object.

type VertexQuery

type VertexQuery struct {
	Namespace string `json:"namespace"`
	Kind      string `json:"kind,omitempty"`
	Limit     int    `json:"limit"`
}

type VertexRef

type VertexRef struct {
	Namespace string `json:"namespace,omitempty"`
	ID        string `json:"id"`
}

Directories

Path Synopsis
Package sqlite is the durable store.Store: the res/graph store contract over one SQLite database, in pure Go (modernc.org/sqlite, no cgo).
Package sqlite is the durable store.Store: the res/graph store contract over one SQLite database, in pure Go (modernc.org/sqlite, no cgo).
Package storetest runs the shared store fixtures in res/graph/testdata/store/v1 against a store.Store implementation.
Package storetest runs the shared store fixtures in res/graph/testdata/store/v1 against a store.Store implementation.

Jump to

Keyboard shortcuts

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