entity

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2026 License: Apache-2.0 Imports: 39 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrEntityNotFound      = errors.New("entity not found")
	ErrEntityAlreadyExists = errors.New("entity already exists")
	ErrAttributeNotFound   = errors.New("attribute not found")
	ErrInvalidAttribute    = errors.New("invalid attribute")
	ErrSchemaNotFound      = errors.New("schema not found")
)

Common errors

View Source
var ErrNotFound = errors.New("entity not found")

Functions

func As

func As[
	T any,
	P interface {
		*T
		EntityAs
	},
](ent AttrGetter) (P, bool)

func Decode

func Decode(data []byte, v any) error

Decode decodes CBOR data into a value

func Empty

func Empty[T comparable](x T) bool

func Encode

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

Encode encodes a value to CBOR format

func InitSystemEntities

func InitSystemEntities(save func(*Entity) error) error

func Is

func Is(ent AttrGetter, kind Id) bool

func MigrateEntityStore

func MigrateEntityStore(ctx context.Context, log *slog.Logger, client *clientv3.Client, opts MigrateOptions) (migrated int, skipped int, err error)

MigrateEntityStore migrates entities from the old CBOR format (with struct fields) to the new format (with attribute-based metadata).

This migration:

  • Reads all entities from etcd under the given prefix
  • Detects entities in the old format (ID/Revision/CreatedAt/UpdatedAt as struct fields)
  • Converts them to the new format (ID/Revision/CreatedAt/UpdatedAt as attributes)
  • Writes the migrated entities back to etcd

Returns the number of entities migrated, skipped, and any error encountered.

func MustKeyword

func MustKeyword(str string) types.Keyword

MustKeyword converts a string to a Keyword, panicking if it's not valid

func TryAs

func TryAs(ent AttrGetter, ea EntityAs) bool

func ValidKeyword

func ValidKeyword(str string) bool

ValidKeyword checks if a string is a valid keyword

func WithOverwrite

func WithOverwrite(opts *entityOpts)

Types

type Attr

type Attr struct {
	ID    Id    `json:"id" cbor:"id"`
	Value Value `json:"v" cbor:"v"`
}

func Any

func Any(id Id, v any) Attr

func Bool

func Bool(id Id, v bool) Attr

Bool returns an Attr for a bool.

func Bytes

func Bytes(id Id, b []byte) Attr

func Component

func Component(id Id, attrs []Attr) Attr

func Diff

func Diff(a, b *Entity) []Attr

Diff returns the difference between two entities. Returns attributes that are in entity 'a' but not in entity 'b'

func Duration

func Duration(id Id, v time.Duration) Attr

func Float64

func Float64(id Id, v float64) Attr

Float64 returns an Attr for a floating-point number.

func Int

func Int(id Id, value int) Attr

Int converts an int to an int64 and returns an Attr with that value.

func Int64

func Int64(id Id, value int64) Attr

Int64 returns an Attr for an int64.

func Keyword

func Keyword[T Keywordable](id Id, v T) Attr

func Label

func Label(id Id, key, val string) Attr

func MustGet

func MustGet(e AttrGetter, name Id) Attr

func Named

func Named[T Keywordable](v T) Attr

func Pair

func Pair(id Id, x, y Value) Attr

func Ref

func Ref(id Id, v Id) Attr

func SortedAttrs

func SortedAttrs(attrs []Attr) []Attr

func String

func String(id Id, value string) Attr

String returns an Attr for a string value.

func Time

func Time(id Id, v time.Time) Attr

Time returns an Attr for a time.Time. It discards the monotonic portion.

func Uint64

func Uint64(id Id, v uint64) Attr

Uint64 returns an Attr for a uint64.

func (Attr) CAS

func (a Attr) CAS() string

func (Attr) Clone

func (a Attr) Clone() Attr

func (Attr) Compare

func (a Attr) Compare(b Attr) int

func (Attr) Equal

func (a Attr) Equal(b Attr) bool

func (Attr) Kind

func (a Attr) Kind() any

func (Attr) Sum

func (a Attr) Sum(h io.Writer)

type AttrGetter

type AttrGetter interface {
	Get(name Id) (Attr, bool)
	GetAll(name Id) []Attr

	Attrs() []Attr
}

type AttrOp

type AttrOp struct {
	Op AttrOpCode

	Attr Attr
}

func AttrAdd

func AttrAdd(a Attr) AttrOp

func AttrRemove

func AttrRemove(a Attr) AttrOp

type AttrOpCode

type AttrOpCode int
const (
	AttrOpCodeNone AttrOpCode = iota
	AttrOpCodeAdd
	AttrOpCodeRemove
)

type AttrOps

type AttrOps []AttrOp

type AttributeSchema

type AttributeSchema struct {
	ID         Id
	Doc        string
	Type       Id
	ElemType   Id
	Unique     uniq
	EnumValues []Value
	AllowMany  bool
	Index      bool
	Session    bool
	Predicate  []*Entity
	CheckProgs []string
	Tags       []string
}

AttributeSchema defines the schema for an attribute

func GetAttributeSchemasByTag

func GetAttributeSchemasByTag(ctx context.Context, store Store, tag string) ([]AttributeSchema, error)

GetAttributeSchemasByTag queries all attributes that have the specified tag and returns their schemas

type EncodedDomain

type EncodedDomain struct {
	Name       string                    `json:"name" cbor:"name"`
	Version    string                    `json:"version" cbor:"version"`
	Kinds      map[string]*EncodedSchema `json:"kinds" cbor:"kinds"`
	ShortKinds map[string]string         `json:"short_kinds" cbor:"short_kinds"`
}

type EncodedSchema

type EncodedSchema struct {
	Domain  string         `json:"domain" cbor:"domain"`
	Name    string         `json:"name" cbor:"name"`
	Version string         `json:"version" cbor:"version"`
	Kinds   []string       `json:"kinds" cbor:"kinds"`
	Fields  []*SchemaField `json:"fields" cbor:"fields"`

	PrimaryKind string `json:"primary_kind" cbor:"primary_kind"`
}

func (*EncodedSchema) GetField

func (es *EncodedSchema) GetField(name string) *SchemaField

type Entity

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

Entity represents an entity with a set of attributes

func Blank

func Blank() *Entity

Blank creates a new empty entity

func New

func New(vals ...any) *Entity

New constructs a slice of attributes from a variadic list of Attr, []Attr, func() []Attr, or key-value pairs.

func (*Entity) Attrs

func (e *Entity) Attrs() []Attr

Attrs returns a clone of the entity's attributes

func (*Entity) Clone

func (e *Entity) Clone() *Entity

func (*Entity) Compare

func (e *Entity) Compare(other *Entity) int

func (*Entity) Fixup

func (e *Entity) Fixup() error

func (*Entity) ForceID

func (e *Entity) ForceID()

func (*Entity) Get

func (e *Entity) Get(name Id) (Attr, bool)

func (*Entity) GetAll

func (e *Entity) GetAll(name Id) []Attr

func (*Entity) GetCreatedAt

func (e *Entity) GetCreatedAt() time.Time

func (*Entity) GetRevision

func (e *Entity) GetRevision() int64

func (*Entity) GetUpdatedAt

func (e *Entity) GetUpdatedAt() time.Time

func (*Entity) Id

func (e *Entity) Id() Id

func (*Entity) MarshalCBOR

func (e *Entity) MarshalCBOR() ([]byte, error)

func (*Entity) MarshalJSON

func (e *Entity) MarshalJSON() ([]byte, error)

func (*Entity) Merge

func (e *Entity) Merge(other *Entity) error

func (*Entity) ReadInfo

func (e *Entity) ReadInfo(val any) error

func (*Entity) Remove

func (e *Entity) Remove(id Id) bool

func (*Entity) Set

func (e *Entity) Set(newAttr Attr) bool

func (*Entity) SetCreatedAt

func (e *Entity) SetCreatedAt(ts time.Time) bool

func (*Entity) SetID

func (e *Entity) SetID(id Id) bool

SetID sets the entity ID (db/id attribute) and returns true if it replaced an existing ID

func (*Entity) SetRevision

func (e *Entity) SetRevision(rev int64)

func (*Entity) SetUpdatedAt

func (e *Entity) SetUpdatedAt(ts time.Time) bool

func (*Entity) Timeless

func (e *Entity) Timeless() *Entity

Timeless returns a copy of the entity without CreatedAt, UpdatedAt and Revision attributes

func (*Entity) UnmarshalCBOR

func (e *Entity) UnmarshalCBOR(data []byte) error

func (*Entity) UnmarshalJSON

func (e *Entity) UnmarshalJSON(data []byte) error

func (*Entity) Update

func (e *Entity) Update(attrs []Attr) error

type EntityAs

type EntityAs interface {
	Is(ag AttrGetter) bool
	Decode(ag AttrGetter)
}

type EntityComponent

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

func (*EntityComponent) Attrs

func (e *EntityComponent) Attrs() []Attr

Attrs returns a clone of the component's attributes

func (*EntityComponent) Compare

func (e *EntityComponent) Compare(other *EntityComponent) int

func (*EntityComponent) Equal

func (e *EntityComponent) Equal(other *EntityComponent) bool

func (*EntityComponent) Get

func (e *EntityComponent) Get(name Id) (Attr, bool)

func (*EntityComponent) GetAll

func (e *EntityComponent) GetAll(name Id) []Attr

func (*EntityComponent) MarshalCBOR

func (e *EntityComponent) MarshalCBOR() ([]byte, error)

func (*EntityComponent) MarshalJSON

func (e *EntityComponent) MarshalJSON() ([]byte, error)

func (*EntityComponent) ReadInfo

func (e *EntityComponent) ReadInfo(val any) error

func (*EntityComponent) UnmarshalCBOR

func (e *EntityComponent) UnmarshalCBOR(data []byte) error

func (*EntityComponent) UnmarshalJSON

func (e *EntityComponent) UnmarshalJSON(data []byte) error

type EntityGetter

type EntityGetter interface {
	GetEntity(ctx context.Context, name Id) (*Entity, error)
}

type EntityOp

type EntityOp struct {
	Type EntityOpType
	*Entity
}

type EntityOpType

type EntityOpType int
const (
	EntityOpCreate EntityOpType = iota
	EntityOpUpdate
	EntityOpDelete
	EntityOpStated
)

type EntityOption

type EntityOption func(*entityOpts)

func BondToSession

func BondToSession(session []byte) EntityOption

func WithFromRevision

func WithFromRevision(revision int64) EntityOption

func WithSession

func WithSession(session []byte) EntityOption

type EntityStore

type EntityStore interface {
	GetEntity(ctx context.Context, id Id) (*Entity, error)
	GetAttributeSchema(ctx context.Context, name Id) (*AttributeSchema, error)
	CreateEntity(ctx context.Context, entity *Entity, opts ...EntityOption) (*Entity, error)
	UpdateEntity(ctx context.Context, id Id, entity *Entity, opts ...EntityOption) (*Entity, error)
	DeleteEntity(ctx context.Context, id Id) error
	ListIndex(ctx context.Context, attr Attr) ([]Id, error)
	ListCollection(ctx context.Context, collection string) ([]Id, error)
}

type EtcdStore

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

EtcdStore implements Store using etcd

func NewEtcdStore

func NewEtcdStore(ctx context.Context, log *slog.Logger, client *clientv3.Client, prefix string) (*EtcdStore, error)

NewEtcdStore creates a new etcd-backed entity store

func (*EtcdStore) AssertLease

func (s *EtcdStore) AssertLease(ctx context.Context, lease int64) error

func (*EtcdStore) ClearSchemaCache added in v0.4.0

func (s *EtcdStore) ClearSchemaCache()

ClearSchemaCache clears the in-memory schema cache, forcing subsequent GetAttributeSchema calls to re-read from etcd. This is used before reindexing to ensure fresh schema definitions are used.

func (*EtcdStore) Client

func (s *EtcdStore) Client() *clientv3.Client

Client returns the underlying etcd client

func (*EtcdStore) CollectionPrefix

func (s *EtcdStore) CollectionPrefix(ctx context.Context, collection string) (string, error)

func (*EtcdStore) CreateEntity

func (s *EtcdStore) CreateEntity(
	ctx context.Context,
	entity *Entity,
	opts ...EntityOption,
) (*Entity, error)

CreateEntity implements Store interface

func (*EtcdStore) CreateLease

func (s *EtcdStore) CreateLease(ctx context.Context, ttl int64) (int64, error)

func (*EtcdStore) CreateSession

func (s *EtcdStore) CreateSession(ctx context.Context, ttl int64) ([]byte, error)

func (*EtcdStore) DeleteEntity

func (s *EtcdStore) DeleteEntity(ctx context.Context, id Id) error

DeleteEntity implements Store interface

func (*EtcdStore) DeletePrefixCount

func (s *EtcdStore) DeletePrefixCount(ctx context.Context, prefix string) (int64, error)

DeletePrefixCount deletes all keys with prefix and returns count

func (*EtcdStore) EnsureEntity

func (s *EtcdStore) EnsureEntity(
	ctx context.Context,
	entity *Entity,
	opts ...EntityOption,
) (*Entity, bool, error)

EnsureEntity creates an entity only if it doesn't already exist (idempotent create) The db/id attribute must be present in the attributes to identify the entity Returns (entity, true, nil) if created, (entity, false, nil) if already exists

func (*EtcdStore) GetAttributeSchema

func (s *EtcdStore) GetAttributeSchema(ctx context.Context, id Id) (*AttributeSchema, error)

GetAttributeSchema implements Store interface

func (*EtcdStore) GetEntities

func (s *EtcdStore) GetEntities(ctx context.Context, ids []Id) ([]*Entity, error)

func (*EtcdStore) GetEntity

func (s *EtcdStore) GetEntity(ctx context.Context, id Id) (*Entity, error)

GetEntity implements Store interface

func (*EtcdStore) GetEntityAtRevision added in v0.4.0

func (s *EtcdStore) GetEntityAtRevision(ctx context.Context, id Id, rev int64) (*Entity, error)

GetEntityAtRevision reads an entity at a specific etcd revision. This is used to retrieve entity data for delete events where the entity may no longer exist at the current revision.

func (*EtcdStore) IndexPrefix

func (s *EtcdStore) IndexPrefix(ctx context.Context, attr Attr) (string, error)

func (*EtcdStore) ListAllEntityIDs

func (s *EtcdStore) ListAllEntityIDs(ctx context.Context) ([]Id, error)

ListAllEntityIDs returns all entity IDs in the store

func (*EtcdStore) ListCollection

func (s *EtcdStore) ListCollection(ctx context.Context, collection string) ([]Id, error)

func (*EtcdStore) ListIndex

func (s *EtcdStore) ListIndex(ctx context.Context, attr Attr) ([]Id, error)

func (*EtcdStore) ListSessionEntities

func (s *EtcdStore) ListSessionEntities(ctx context.Context, session []byte) ([]Id, error)

func (*EtcdStore) PatchEntity

func (s *EtcdStore) PatchEntity(
	ctx context.Context,
	current *Entity,
	opts ...EntityOption,
) (*Entity, error)

PatchEntity merges attributes into an existing entity For cardinality=one attributes, replaces the value For cardinality=many attributes, adds to existing values The db/id attribute must be present in the attributes to identify the entity

func (*EtcdStore) PingSession

func (s *EtcdStore) PingSession(ctx context.Context, session []byte) error

func (*EtcdStore) Prefix

func (s *EtcdStore) Prefix() string

Prefix returns the etcd prefix used by this store

func (*EtcdStore) Reindex added in v0.4.0

func (s *EtcdStore) Reindex(ctx context.Context, log *slog.Logger, opts ReindexOptions) (*ReindexStats, error)

Reindex rebuilds all index (collection) entries for every entity in the store. If opts.CleanupStale is true, it also scans for and removes stale collection entries that point to non-existent entities.

func (*EtcdStore) ReplaceEntity

func (s *EtcdStore) ReplaceEntity(
	ctx context.Context,
	current *Entity,
	opts ...EntityOption,
) (*Entity, error)

ReplaceEntity atomically replaces all attributes of an entity The db/id attribute must be present in the attributes to identify the entity

func (*EtcdStore) RevokeLease

func (s *EtcdStore) RevokeLease(ctx context.Context, lease int64) error

func (*EtcdStore) RevokeSession

func (s *EtcdStore) RevokeSession(ctx context.Context, session []byte) error

func (*EtcdStore) UpdateEntity

func (s *EtcdStore) UpdateEntity(
	ctx context.Context,
	id Id,
	changes *Entity,
	opts ...EntityOption,
) (*Entity, error)

UpdateEntity implements Store interface

func (*EtcdStore) WatchEntity

func (s *EtcdStore) WatchEntity(ctx context.Context, id Id) (chan EntityOp, error)

func (*EtcdStore) WatchIndex

func (s *EtcdStore) WatchIndex(ctx context.Context, attr Attr) (clientv3.WatchChan, error)

type FileStore

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

FileStore provides CRUD operations for entities

func NewFileStore

func NewFileStore(basePath string) (*FileStore, error)

NewFileStore creates a new entity store with the given base path

func (*FileStore) CreateEntity

func (s *FileStore) CreateEntity(ctx context.Context, entity *Entity, opts ...EntityOption) (*Entity, error)

CreateEntity creates a new entity with the given type and attributes

func (*FileStore) DeleteEntity

func (s *FileStore) DeleteEntity(_ context.Context, id Id) error

DeleteEntity deletes an entity by ID

func (*FileStore) GetAttributeSchema

func (s *FileStore) GetAttributeSchema(ctx context.Context, id Id) (*AttributeSchema, error)

GetAttributeSchema retrieves an attribute schema by ID

func (*FileStore) GetEntities

func (s *FileStore) GetEntities(_ context.Context, ids []Id) ([]*Entity, error)

GetEntities retrieves multiple entities by their IDs

func (*FileStore) GetEntity

func (s *FileStore) GetEntity(_ context.Context, id Id) (*Entity, error)

GetEntity retrieves an entity by ID

func (*FileStore) ListCollection

func (s *FileStore) ListCollection(_ context.Context, collection string) ([]Id, error)

func (*FileStore) ListIndex

func (s *FileStore) ListIndex(ctx context.Context, attr Attr) ([]Id, error)

func (*FileStore) UpdateEntity

func (s *FileStore) UpdateEntity(ctx context.Context, id Id, updates *Entity, opts ...EntityOption) (*Entity, error)

UpdateEntity updates an existing entity

type Id

type Id = types.Id
const (
	DBId           Id = "db/id"
	Ident          Id = "db/ident"
	Doc            Id = "db/doc"
	Uniq           Id = "db/uniq"
	Cardinality    Id = "db/cardinality"
	Type           Id = "db/type"
	EnumValues     Id = "db/enumValues"
	EntityElemType Id = "db/elementType"

	UniqueId    Id = "db/unique.identity"
	UniqueValue Id = "db/unique.value"

	CardinalityOne  Id = "db/cardinality.one"
	CardinalityMany Id = "db/cardinality.many"

	TypeAny       Id = "db/type.any"
	TypeRef       Id = "db/type.ref"
	TypeStr       Id = "db/type.str"
	TypeKeyword   Id = "db/type.keyword"
	TypeInt       Id = "db/type.int"
	TypeFloat     Id = "db/type.float"
	TypeBool      Id = "db/type.bool"
	TypeTime      Id = "db/type.time"
	TypeEnum      Id = "db/type.enum"
	TypeArray     Id = "db/type.array"
	TypeDuration  Id = "db/type.duration"
	TypeComponent Id = "db/type.component"
	TypeLabel     Id = "db/type.label"
	TypeBytes     Id = "db/type.bytes"

	Index   Id = "db/index"
	Session Id = "db/session"
	Tag     Id = "db/tag"

	AttrSession Id = "db/attr.session"

	EntityAttrs Id = "db/entity.attrs"
	EntityPreds Id = "db/entity.preds"

	Ensure Id = "db/ensure"

	AttrPred Id = "db/attr.pred"
	Program  Id = "db/program"

	EntityKind   Id = "entity/kind"
	EntitySchema Id = "entity/schema"

	SchemaKind Id = "schema/kind"

	PredIP   Id = "db/pred.ip"
	PredCIDR Id = "db/pred.cidr"

	Schema Id = "db/schema"

	TTL Id = "db/entity.ttl"

	Revision  Id = "db/entity.revision"
	CreatedAt Id = "db/entity.created"
	UpdatedAt Id = "db/entity.updated"
)

type Keywordable

type Keywordable interface {
	string | types.Keyword
}

type Meta

type Meta struct {
	*Entity `json:"entity" cbor:"entity"`

	Revision int64 `json:"version" cbor:"version"`
	Previous int64 `json:"previous" cbor:"previous"`
}

func MigrateMetaFromBytes

func MigrateMetaFromBytes(data []byte) (*Meta, error)

MigrateMetaFromBytes attempts to decode CBOR bytes as Meta, automatically migrating from old format if needed. This is used for read-time migration of persisted entity files.

func (*Meta) GetRevision

func (m *Meta) GetRevision() int64

func (*Meta) MarshalCBOR

func (m *Meta) MarshalCBOR() ([]byte, error)

func (*Meta) MarshalJSON

func (m *Meta) MarshalJSON() ([]byte, error)

func (*Meta) UnmarshalCBOR

func (m *Meta) UnmarshalCBOR(data []byte) error

func (*Meta) UnmarshalJSON

func (m *Meta) UnmarshalJSON(data []byte) error

type MigrateOptions

type MigrateOptions struct {
	// DryRun prevents writing changes back to etcd
	DryRun bool
	// Prefix is the etcd key prefix to scan (default: "/entity/")
	Prefix string
}

MigrateOptions configures the migration behavior

type MockStore

type MockStore struct {
	Entities map[Id]*Entity

	OnWatchIndex    func(ctx context.Context, attr Attr) (clientv3.WatchChan, error)
	GetEntitiesFunc func(ctx context.Context, ids []Id) ([]*Entity, error)
	OnListIndex     func(ctx context.Context, attr Attr) ([]Id, error) // Hook to track ListIndex calls

	NowFunc func() time.Time // Optional function to override current time
	// contains filtered or unexported fields
}

func NewMockStore

func NewMockStore() *MockStore

func (*MockStore) AddEntity

func (m *MockStore) AddEntity(id Id, entity *Entity)

AddEntity is a thread-safe helper to directly add an entity to the mock store

func (*MockStore) CreateEntity

func (m *MockStore) CreateEntity(ctx context.Context, entity *Entity, opts ...EntityOption) (*Entity, error)

func (*MockStore) CreateSession

func (m *MockStore) CreateSession(ctx context.Context, id int64) ([]byte, error)

func (*MockStore) DeleteEntity

func (m *MockStore) DeleteEntity(ctx context.Context, id Id) error

func (*MockStore) EnsureEntity

func (m *MockStore) EnsureEntity(ctx context.Context, entity *Entity, opts ...EntityOption) (*Entity, bool, error)

func (*MockStore) GetAttributeSchema

func (m *MockStore) GetAttributeSchema(ctx context.Context, id Id) (*AttributeSchema, error)

func (*MockStore) GetEntities

func (m *MockStore) GetEntities(ctx context.Context, ids []Id) ([]*Entity, error)

func (*MockStore) GetEntity

func (m *MockStore) GetEntity(ctx context.Context, id Id) (*Entity, error)

func (*MockStore) GetEntityAtRevision added in v0.4.0

func (m *MockStore) GetEntityAtRevision(ctx context.Context, id Id, rev int64) (*Entity, error)

func (*MockStore) ListCollection

func (m *MockStore) ListCollection(ctx context.Context, collection string) ([]Id, error)

func (*MockStore) ListIndex

func (m *MockStore) ListIndex(ctx context.Context, attr Attr) ([]Id, error)

func (*MockStore) ListSessionEntities

func (m *MockStore) ListSessionEntities(ctx context.Context, id []byte) ([]Id, error)

ListSessionEntities

func (*MockStore) Now

func (m *MockStore) Now() time.Time

func (*MockStore) PatchEntity

func (m *MockStore) PatchEntity(ctx context.Context, entity *Entity, opts ...EntityOption) (*Entity, error)

func (*MockStore) PingSession

func (m *MockStore) PingSession(ctx context.Context, id []byte) error

PingSession

func (*MockStore) RemoveEntity

func (m *MockStore) RemoveEntity(id Id)

RemoveEntity is a thread-safe helper to directly remove an entity from the mock store

func (*MockStore) ReplaceEntity

func (m *MockStore) ReplaceEntity(ctx context.Context, entity *Entity, opts ...EntityOption) (*Entity, error)

func (*MockStore) RevokeSession

func (m *MockStore) RevokeSession(ctx context.Context, id []byte) error

RevokeSession

func (*MockStore) UpdateEntity

func (m *MockStore) UpdateEntity(ctx context.Context, id Id, entity *Entity, opts ...EntityOption) (*Entity, error)

func (*MockStore) WaitForEntityWatcher added in v0.4.0

func (m *MockStore) WaitForEntityWatcher(ctx context.Context, id Id) error

WaitForEntityWatcher blocks until at least one watcher is registered for the given entity ID, or the context is cancelled.

func (*MockStore) WaitForIndexWatcher added in v0.3.0

func (m *MockStore) WaitForIndexWatcher(ctx context.Context, attr Attr) error

WaitForIndexWatcher blocks until at least one watcher is registered for the given attribute, or the context is cancelled. This is useful in tests to ensure a watch is established before performing operations that should trigger watch notifications.

func (*MockStore) WatchEntity

func (m *MockStore) WatchEntity(ctx context.Context, id Id) (chan EntityOp, error)

WatchEntity registers a watcher for an entity and returns a channel that receives updates

func (*MockStore) WatchIndex

func (m *MockStore) WatchIndex(ctx context.Context, attr Attr) (clientv3.WatchChan, error)

type OldEntity

type OldEntity struct {
	ID        types.Id `cbor:"id"`
	Revision  int64    `cbor:"revision,omitempty"`
	CreatedAt int64    `cbor:"created_at"` // milliseconds since epoch
	UpdatedAt int64    `cbor:"updated_at"` // milliseconds since epoch
	Attrs     []Attr   `cbor:"attrs"`
}

OldEntity represents the entity format before the migration to attribute-based metadata. In the old format, ID, Revision, CreatedAt, and UpdatedAt were struct fields in the CBOR encoding.

func (*OldEntity) Get

func (e *OldEntity) Get(attr Id) (Attr, bool)

type OldMeta

type OldMeta struct {
	Entity   OldEntity `cbor:"entity"`
	Revision int64     `cbor:"version"`
	Previous int64     `cbor:"previous"`
}

OldMeta represents the Meta format before the entity migration where the embedded Entity might be in OldEntity format

type ReindexOptions added in v0.4.0

type ReindexOptions struct {
	DryRun       bool
	CleanupStale bool
}

ReindexOptions controls the behavior of a reindex operation.

type ReindexStats added in v0.4.0

type ReindexStats struct {
	EntitiesProcessed        int64
	IndexesRebuilt           int64
	CollectionEntriesScanned int64
	StaleEntriesFound        int64
	StaleEntriesRemoved      int64
}

ReindexStats holds statistics about a reindex operation.

type SchemaCache

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

func NewSchemaCache

func NewSchemaCache(store Store) (*SchemaCache, error)

func (*SchemaCache) GetKindSchema

func (f *SchemaCache) GetKindSchema(ctx context.Context, id Id) (*EncodedSchema, error)

func (*SchemaCache) GetSchema

func (f *SchemaCache) GetSchema(ctx context.Context, schemaId Id) (*EncodedDomain, error)

type SchemaField

type SchemaField struct {
	Name string `json:"name" cbor:"name"`
	Type string `json:"type" cbor:"type"`

	Id Id `json:"id" cbor:"id"`

	Many bool `json:"many,omitempty" cbor:"many,omitempty"`

	EnumValues map[string]Id  `json:"enum_values,omitempty" cbor:"enum_values,omitempty"`
	Component  *EncodedSchema `json:"component,omitempty" cbor:"component,omitempty"`
}

type Store

type Store interface {
	GetEntity(ctx context.Context, id Id) (*Entity, error)
	GetEntityAtRevision(ctx context.Context, id Id, rev int64) (*Entity, error)
	GetEntities(ctx context.Context, ids []Id) ([]*Entity, error)
	WatchEntity(ctx context.Context, id Id) (chan EntityOp, error)
	GetAttributeSchema(ctx context.Context, name Id) (*AttributeSchema, error)
	CreateEntity(ctx context.Context, entity *Entity, opts ...EntityOption) (*Entity, error)
	UpdateEntity(ctx context.Context, id Id, entity *Entity, opts ...EntityOption) (*Entity, error)
	ReplaceEntity(ctx context.Context, entity *Entity, opts ...EntityOption) (*Entity, error)
	PatchEntity(ctx context.Context, entity *Entity, opts ...EntityOption) (*Entity, error)
	EnsureEntity(ctx context.Context, entity *Entity, opts ...EntityOption) (*Entity, bool, error)
	DeleteEntity(ctx context.Context, id Id) error
	WatchIndex(ctx context.Context, attr Attr) (clientv3.WatchChan, error)
	ListIndex(ctx context.Context, attr Attr) ([]Id, error)
	ListCollection(ctx context.Context, collection string) ([]Id, error)

	CreateSession(ctx context.Context, ttl int64) ([]byte, error)
	RevokeSession(ctx context.Context, session []byte) error
	PingSession(ctx context.Context, session []byte) error
	ListSessionEntities(ctx context.Context, session []byte) ([]Id, error)
}

type Validator

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

Validator provides methods to validate attribute values against their schemas

func NewValidator

func NewValidator(store EntityStore) *Validator

NewValidator creates a new attribute validator

func (*Validator) ValidateAttribute

func (v *Validator) ValidateAttribute(ctx context.Context, attr *Attr) error

ValidateAttribute validates a single attribute against its schema

func (*Validator) ValidateAttributes

func (v *Validator) ValidateAttributes(ctx context.Context, attrs []Attr) error

func (*Validator) ValidateEntity

func (v *Validator) ValidateEntity(ctx context.Context, entity *Entity) error

ValidateEntity validates all attributes in an entity against their schemas

type Value

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

func AnyValue

func AnyValue(v any) Value

AnyValue returns a Value for the supplied value.

If the supplied value is of type Value, it is returned unmodified.

Given a value of one of Go's predeclared string, bool, or (non-complex) numeric types, AnyValue returns a Value of kind KindString, KindBool, KindUint64, KindInt64, or KindFloat64. The width of the original numeric type is not preserved.

Given a time.Time or time.Duration value, AnyValue returns a Value of kind KindTime or KindDuration. The monotonic time is not preserved.

For nil, or values of all other types, including named types whose underlying type is numeric, AnyValue returns a value of kind KindAny.

func ArrayValue

func ArrayValue(values ...any) Value

func BoolValue

func BoolValue(v bool) Value

BoolValue returns a Value for a bool.

func BytesValue

func BytesValue(b []byte) Value

func ComponentValue

func ComponentValue(vals ...any) Value

func DurationValue

func DurationValue(v time.Duration) Value

DurationValue returns a Value for a time.Duration.

func Float64Value

func Float64Value(v float64) Value

Float64Value returns a Value for a floating-point number.

func Int64Value

func Int64Value(v int64) Value

Int64Value returns a Value for an int64.

func IntValue

func IntValue(v int) Value

IntValue returns a Value for an int.

func KeywordValue

func KeywordValue[T Keywordable](v T) Value

func LabelValue

func LabelValue(key, val string) Value

func RefValue

func RefValue(v Id) Value

func StringValue

func StringValue(value string) Value

StringValue returns a new Value for a string.

func TimeValue

func TimeValue(v time.Time) Value

TimeValue returns a Value for a time.Time. It discards the monotonic portion.

func Uint64Value

func Uint64Value(v uint64) Value

Uint64Value returns a Value for a uint64.

func (Value) Any

func (v Value) Any() any

Any returns v's value as an any.

func (Value) Array

func (v Value) Array() []Value

func (Value) Bool

func (v Value) Bool() bool

Bool returns v's value as a bool. It panics if v is not a bool.

func (Value) Bytes

func (v Value) Bytes() []byte

func (Value) Clone

func (v Value) Clone() Value

Clone returns a deep copy of the Value. For bytes, arrays, and components, this creates new copies of the underlying data. For other types (strings, primitives, immutable types), a shallow copy is sufficient.

func (Value) Compare

func (v Value) Compare(w Value) int

Equal reports whether v and w represent the same Go value.

func (Value) Component

func (v Value) Component() *EntityComponent

func (Value) Duration

func (v Value) Duration() time.Duration

Duration returns v's value as a time.Duration. It panics if v is not a time.Duration.

func (Value) Equal

func (v Value) Equal(w Value) bool

Equal reports whether v and w represent the same Go value.

func (Value) Float64

func (v Value) Float64() float64

Float64 returns v's value as a float64. It panics if v is not a float64.

func (Value) Id

func (v Value) Id() types.Id

func (Value) Int64

func (v Value) Int64() int64

Int64 returns v's value as an int64. It panics if v is not a signed integer.

func (Value) Keyword

func (v Value) Keyword() types.Keyword

func (Value) Kind

func (v Value) Kind() ValueKind

Kind returns v's Kind.

func (Value) Label

func (v Value) Label() types.Label

func (*Value) MarshalCBOR

func (v *Value) MarshalCBOR() ([]byte, error)

func (Value) MarshalJSON

func (v Value) MarshalJSON() ([]byte, error)

func (Value) MarshalYAML

func (v Value) MarshalYAML() (any, error)

func (Value) String

func (v Value) String() string

String returns Value's value as a string, formatted like fmt.Sprint. Unlike the methods Int64, Float64, and so on, which panic if v is of the wrong kind, String never panics.

func (Value) Time

func (v Value) Time() time.Time

Time returns v's value as a time.Time. It panics if v is not a time.Time.

func (Value) Uint64

func (v Value) Uint64() uint64

Uint64 returns v's value as a uint64. It panics if v is not an unsigned integer.

func (*Value) UnmarshalCBOR

func (v *Value) UnmarshalCBOR(b []byte) error

func (*Value) UnmarshalJSON

func (v *Value) UnmarshalJSON(b []byte) error

func (*Value) UnmarshalYAML

func (v *Value) UnmarshalYAML(node *yaml.Node) error

type ValueKind

type ValueKind int

ValueKind is the kind of a Value.

const (
	KindAny ValueKind = iota
	KindBool
	KindDuration
	KindFloat64
	KindInt64
	KindString
	KindTime
	KindUint64
	KindId
	KindKeyword
	KindArray
	KindComponent
	KindLabel
	KindBytes
)

func (ValueKind) ShortString

func (k ValueKind) ShortString() string

func (ValueKind) String

func (k ValueKind) String() string

Directories

Path Synopsis
cmd
schemagen command

Jump to

Keyboard shortcuts

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