Documentation
¶
Overview ¶
Package events defines persisted event identities and immutable type catalogs.
Index ¶
- Constants
- Variables
- func Decode[T any](catalog *Catalog, appended Appended) (T, error)
- type Appended
- type Catalog
- func (c *Catalog) Descriptors() []Descriptor
- func (c *Catalog) Lookup(value any) (Descriptor, bool)
- func (c *Catalog) LookupID(id TypeID) (Descriptor, bool)
- func (c *Catalog) LookupRef(ref TypeRef) (Descriptor, bool)
- func (c *Catalog) Migrations() []MigrationDefinition
- func (c *Catalog) ValidateDeclarations() error
- func (c *Catalog) WithMigrations(declarations []MigrationDeclaration, validateChain bool) (*Catalog, error)
- type Context
- type Count
- type DeclarationError
- type Descriptor
- func (d Descriptor) CompensationFor() (TypeRef, bool)
- func (d Descriptor) EncodeOutgoing(request contentencoding.Request[EventContent]) ([]byte, error)
- func (d Descriptor) Fields() []serialization.Field
- func (d Descriptor) GoType() reflect.Type
- func (d Descriptor) IsHistorical() bool
- func (d Descriptor) IsTombstone() bool
- func (d Descriptor) Marshal(value any) ([]byte, error)
- func (d Descriptor) Ref() TypeRef
- func (d Descriptor) RemovedConstraints() []string
- func (d Descriptor) ResolveSubject(value any) (Subject, bool)
- func (d Descriptor) SameDeclaration(other Descriptor) bool
- func (d Descriptor) Schema() string
- func (d Descriptor) SourceStore() string
- func (d Descriptor) Tags() []Tag
- func (d Descriptor) UniqueDeclarations() []Unique
- func (d Descriptor) Unmarshal(data []byte, target any) error
- func (d Descriptor) ValidateUnique() error
- func (d Descriptor) WithNamingPolicy(policy serialization.NamingPolicy) (Descriptor, error)
- type EventContent
- type EventEnricher
- type EventRedacted
- type Generation
- type Migration
- type MigrationBuilder
- func (b *MigrationBuilder[T, S]) Combine(target Property[T], separator string, sources ...Property[S]) *MigrationBuilder[T, S]
- func (b *MigrationBuilder[T, S]) DefaultValue(target Property[T], value any) *MigrationBuilder[T, S]
- func (b *MigrationBuilder[T, S]) MapValues(target Property[T], source Property[S], mappings ...ValueMapping) *MigrationBuilder[T, S]
- func (b *MigrationBuilder[T, S]) RenamedFrom(target Property[T], source Property[S]) *MigrationBuilder[T, S]
- func (b *MigrationBuilder[T, S]) Split(target Property[T], source Property[S], separator string, part int) *MigrationBuilder[T, S]
- type MigrationDeclaration
- type MigrationDefinition
- type NamedTag
- type ObservationState
- type PreparationError
- type Property
- type RedactionCausation
- type RedactionReason
- type Revision
- type SequenceID
- type SequenceNumber
- func (n SequenceNumber) Add(delta uint64) (SequenceNumber, error)
- func (n SequenceNumber) IsActualValue() bool
- func (n SequenceNumber) IsBeforeFirst() bool
- func (n SequenceNumber) IsUnavailable() bool
- func (n SequenceNumber) Next() (SequenceNumber, error)
- func (n SequenceNumber) Subtract(delta uint64) (SequenceNumber, error)
- type SourceID
- type SourceType
- type StreamID
- type StreamType
- type Subject
- type Tag
- type Type
- type TypeID
- type TypeOption
- func WithCodecs(codecs *serialization.Codecs) TypeOption
- func WithCompensationFor[T any](event Type[T]) TypeOption
- func WithGeneration(generation Generation) TypeOption
- func WithID(id TypeID) TypeOption
- func WithProtection(declarations ...compliance.Declaration) TypeOption
- func WithRemoveConstraints(names ...string) TypeOption
- func WithSourceStore(name string) TypeOption
- func WithSubjectResolver[T any](resolver func(T) (Subject, bool)) TypeOption
- func WithTags(tags ...Tag) TypeOption
- func WithTombstone() TypeOption
- func WithUnique(declaration Unique) TypeOption
- type TypeRef
- type Unique
- type ValueMapBuilder
- type ValueMapping
Examples ¶
Constants ¶
const ( // UnspecifiedSequence is Chronicle's unspecified sequence identity. UnspecifiedSequence SequenceID = "[unspecified]" // SystemSequence contains system events. SystemSequence SequenceID = "system" // Outbox is the default outbox sequence. Outbox SequenceID = "outbox" // Inbox is the virtual sequence representing all inboxes. Inbox SequenceID = "inbox" // InboxPrefix prefixes per-source inbox sequence IDs. InboxPrefix = "inbox-" // UnspecifiedSourceType does not narrow concurrency or read scopes. UnspecifiedSourceType SourceType = "" )
const ( // EventLog is the primary event sequence. EventLog SequenceID = "event-log" // DefaultSourceType is the default append source classification. DefaultSourceType SourceType = "Default" // AllStreamTypes is the default stream type and a non-narrowing read sentinel. AllStreamTypes StreamType = "All" // DefaultStreamID is the default stream; it is not the event source ID. DefaultStreamID StreamID = "Default" // First is the first actual sequence position and the zero value. First SequenceNumber = 0 Unavailable SequenceNumber = ^SequenceNumber(0) // Max is a reserved system value, not the largest actual position. Max SequenceNumber = Unavailable - 1 // BeforeFirst represents a local expectation of no matching event. It is not // a wire position: use eventsequences.NoMatchingEvent for protected absence. BeforeFirst SequenceNumber = Unavailable - 2 )
Variables ¶
var ErrSequenceNumberRange = errors.New("sequence number outside actual range")
ErrSequenceNumberRange identifies actual-position overflow, underflow or a result crossing into the reserved values. Failed arithmetic returns Unavailable. Inspect this stable category with errors.Is.
Functions ¶
func Decode ¶
Decode selects T's registered generation from the kernel's alternate content, or uses Content when no alternate is supplied (C#'s raw fallback). It does not execute migrations locally or relabel the persisted context. T must be a registered non-pointer event struct (except the built-in EventRedacted). Use a Client.Catalogs/EventStore catalog to retain the selected naming policy. An unrelated ID is ErrProtocol.
Types ¶
type Appended ¶
type Appended struct {
// ID is the kernel's event identifier.
ID string
// Context describes the persisted event and selected store coordinates.
Context Context
// Content is the current JSON representation, independent of catalog registration.
Content json.RawMessage
// OriginalContent is the original JSON, or nil when absent on the wire.
OriginalContent json.RawMessage
// Revisions is the ordered revision history returned by the kernel.
Revisions []Revision
// GenerationalContent holds the available representations keyed by generation.
GenerationalContent map[Generation]json.RawMessage
}
Appended owns raw JSON and metadata returned by an event read. Reads do not guess a Go type or generation. Decode and Appended.Decode use a client catalog's generation codecs; original and alternate representations remain available.
func (Appended) Decode ¶
Decode selects the exact delivered generation's codec and returns a pointer to its Go event type. An unregistered generation fails explicitly rather than guessing the latest codec; use the generic Decode to request a known shape. The built-in EventRedacted marker is decoded without explicit registration.
func (Appended) Redaction ¶
func (a Appended) Redaction() (EventRedacted, error)
Redaction decodes the kernel marker without registering a user event codec. Non-marker events, malformed payloads and missing reasons/type IDs fail with ErrProtocol. The returned slices/maps are owned by the caller. Unknown original IDs are preserved, never decoded as a registered original event with zero data.
type Catalog ¶
type Catalog struct {
// contains filtered or unexported fields
}
Catalog is a frozen, concurrency-safe set of event descriptors. Use NewCatalog.
func NewCatalog ¶
func NewCatalog(descriptors ...Descriptor) (*Catalog, error)
NewCatalog validates and copies descriptors, rejecting duplicate Go types, (ID, generation) pairs and current IDs. Historical descriptors must reference the current descriptor in this catalog; their generation must be lower.
func (*Catalog) Descriptors ¶
func (c *Catalog) Descriptors() []Descriptor
Descriptors returns a defensive copy in registration order.
func (*Catalog) Lookup ¶
func (c *Catalog) Lookup(value any) (Descriptor, bool)
Lookup resolves values and non-nil pointers to registered structs. Nil and nil pointers do not match. It performs no serialization or I/O.
func (*Catalog) LookupID ¶
func (c *Catalog) LookupID(id TypeID) (Descriptor, bool)
LookupID returns the current (highest) registered generation for a persisted ID.
func (*Catalog) LookupRef ¶
func (c *Catalog) LookupRef(ref TypeRef) (Descriptor, bool)
LookupRef returns a descriptor only when both ID and generation match. Unlike C# GetClrTypeFor, an unknown generation never silently selects a codec for a different shape. LookupID explicitly requests the latest codec instead.
func (*Catalog) Migrations ¶
func (c *Catalog) Migrations() []MigrationDefinition
Migrations returns detached definitions in event ID and generation order.
func (*Catalog) ValidateDeclarations ¶
ValidateDeclarations validates catalog-relative descriptor references without I/O. NewClient calls it for every store registry before any connection work.
func (*Catalog) WithMigrations ¶
func (c *Catalog) WithMigrations(declarations []MigrationDeclaration, validateChain bool) (*Catalog, error)
WithMigrations compiles a detached catalog with frozen migration definitions. Paths, shared identities, adjacency and duplicates are always validated. When validateChain is true, every step from generation one to current is required. There are no placeholder codecs: both endpoint types must be in this catalog.
type Context ¶
type Context struct {
// Store identifies the logical event store.
Store metadata.StoreName
// Namespace identifies the isolated namespace.
Namespace metadata.Namespace
// Sequence identifies the event sequence.
Sequence SequenceID
// EventType identifies the persisted generation.
EventType TypeRef
// Tombstone preserves the kernel's tombstone type flag.
Tombstone bool
// SourceType classifies the event source.
SourceType SourceType
// SourceID identifies the event source.
SourceID SourceID
// StreamType classifies the stream.
StreamType StreamType
// StreamID identifies the stream independently of the source.
StreamID StreamID
// SequenceNumber is the sequence-wide position; zero is a valid first event.
SequenceNumber SequenceNumber
// Occurred is the persisted occurrence timestamp with its numeric offset.
Occurred time.Time
// CorrelationID identifies the operation that appended this event.
CorrelationID metadata.CorrelationID
// Causation is the ordered audit chain, including per-entry additions.
Causation []metadata.Causation
// CausedBy is the actor and its ordered on-behalf-of chain.
CausedBy identities.Identity
// Tags contains ordinary event tags.
Tags []Tag
// NamedTags preserves structured exact name/value pairs.
NamedTags []NamedTag
// Subject is the compliance subject, defaulting to SourceID if absent.
Subject Subject
// Hash is the kernel's persisted content hash.
Hash string
// ObservationState preserves the wire state, including future values.
ObservationState ObservationState
}
Context contains persisted event metadata. Its slices and maps belong to the read result, not shared client state; callers may modify their own result.
type Count ¶
type Count uint64
Count is a number of events, not a sequence position or a freshness guarantee.
type DeclarationError ¶
type DeclarationError = declarations.DeclarationError
DeclarationError locates invalid event metadata. Error text redacts literals.
type Descriptor ¶
type Descriptor struct {
// contains filtered or unexported fields
}
Descriptor is immutable event schema and serialization metadata. Its zero value is invalid.
func (Descriptor) CompensationFor ¶
func (d Descriptor) CompensationFor() (TypeRef, bool)
CompensationFor returns the referenced identity and whether it was declared.
func (Descriptor) EncodeOutgoing ¶
func (d Descriptor) EncodeOutgoing(request contentencoding.Request[EventContent]) ([]byte, error)
EncodeOutgoing is the module-private outgoing content bridge. Enrichment never changes Descriptor.Marshal or invokes incoming decoding/schema callbacks.
func (Descriptor) Fields ¶
func (d Descriptor) Fields() []serialization.Field
Fields returns detached metadata from the shared serialization/schema plan.
func (Descriptor) GoType ¶
func (d Descriptor) GoType() reflect.Type
GoType returns the normalized non-pointer Go struct type.
func (Descriptor) IsHistorical ¶
func (d Descriptor) IsHistorical() bool
IsHistorical reports whether this descriptor is a generation of another type.
func (Descriptor) IsTombstone ¶
func (d Descriptor) IsTombstone() bool
IsTombstone reports descriptor-only tombstone metadata, not the wire flag.
func (Descriptor) Marshal ¶
func (d Descriptor) Marshal(value any) ([]byte, error)
Marshal serializes a value or non-nil pointer of this descriptor's type.
func (Descriptor) Ref ¶
func (d Descriptor) Ref() TypeRef
Ref returns the persisted identity and generation.
func (Descriptor) RemovedConstraints ¶
func (d Descriptor) RemovedConstraints() []string
RemovedConstraints returns detached, ordered removal names.
func (Descriptor) ResolveSubject ¶
func (d Descriptor) ResolveSubject(value any) (Subject, bool)
ResolveSubject invokes the registered subject resolver for a matching value or non-nil pointer. False means no subject was resolved. It performs no I/O.
func (Descriptor) SameDeclaration ¶
func (d Descriptor) SameDeclaration(other Descriptor) bool
SameDeclaration reports exact declaration identity, not merely matching wire identities. Detached naming plans are distinct; use the original registered descriptor when declaring definition-factory output metadata.
func (Descriptor) Schema ¶
func (d Descriptor) Schema() string
Schema returns the JSON Schema registered with the kernel.
func (Descriptor) SourceStore ¶
func (d Descriptor) SourceStore() string
SourceStore returns the declared origin store; empty means unspecified/local. It affects observer inference, not append routing or subscription provisioning.
func (Descriptor) UniqueDeclarations ¶
func (d Descriptor) UniqueDeclarations() []Unique
UniqueDeclarations returns detached type-level lifecycle metadata.
func (Descriptor) Unmarshal ¶
func (d Descriptor) Unmarshal(data []byte, target any) error
Unmarshal decodes an object using this generation's configured serialization plan. target must be a non-nil pointer to the descriptor's Go type.
func (Descriptor) ValidateUnique ¶
func (d Descriptor) ValidateUnique() error
ValidateUnique validates copied type-level metadata before constraint compilation.
func (Descriptor) WithNamingPolicy ¶
func (d Descriptor) WithNamingPolicy(policy serialization.NamingPolicy) (Descriptor, error)
WithNamingPolicy compiles a detached descriptor for registry composition. It does not mutate this descriptor, its handles, or any existing catalog. Provider classifications are frozen by Go member identity for subsequent rebinding.
type EventContent ¶
type EventContent = serialization.EventContent
EventContent is an expiring editor over declared outgoing event properties. See serialization.EventContent for name, type, ownership and omission rules.
type EventEnricher ¶
type EventEnricher func(context.Context, TypeRef, *EventContent) error
EventEnricher runs synchronously after the entire original event is encoded. The context carries selected audit snapshots. Callbacks run in registration order (including duplicates), must support concurrent callers, and must not retain the editor. They are borrowed for the client lifetime, never closed. Errors and panics fail preparation without retaining their payloads. Callers own and must join outstanding preparation calls before disposing providers.
type EventRedacted ¶
type EventRedacted struct {
// Reason is the supplied explanation for removing the payload.
Reason RedactionReason `json:"reason"`
// OriginalEventType identifies the event before redaction, without a generation.
OriginalEventType TypeID `json:"originalEventType"`
// Occurred is when the original event occurred.
Occurred time.Time `json:"occurred"`
// CorrelationID identifies the original append, not the redaction request.
CorrelationID uuid.UUID `json:"correlationId"`
// Causation preserves the original audit chain as returned by the kernel.
Causation []RedactionCausation `json:"causation"`
// CausedBy contains original persisted identity IDs, not identity subjects.
CausedBy []uuid.UUID `json:"causedBy"`
}
EventRedacted is the replacement payload, not the redaction command. Its audit fields describe the ORIGINAL event. The enclosing Appended.Context describes the redaction operation. OriginalEventType retains the stable ID even when the original Go type is unknown. Register this type explicitly to handle markers in a reactor; direct reads decode it without registration.
func (EventRedacted) OriginalType ¶
func (r EventRedacted) OriginalType(catalog *Catalog) reflect.Type
OriginalType resolves the current registered Go type, or any for an unknown ID (C#'s object fallback). A nil catalog also returns any; no generation is guessed.
type Generation ¶
type Generation uint32
Generation identifies an event schema generation, beginning at one.
type Migration ¶
type Migration[Upgrade, Previous any] struct { Upcast func(*MigrationBuilder[Upgrade, Previous]) Downcast func(*MigrationBuilder[Previous, Upgrade]) MapValues func(*ValueMapBuilder[Upgrade, Previous]) }
Migration declares an adjacent event evolution. Both direction callbacks are required; an empty callback is an explicit identity transformation. Unmapped properties pass through in the kernel and are filtered by the target schema. MapValues, when supplied, runs before direction-specific operations, so the last directional operation on a property wins. No callback runs on payloads. Binary and declared serialization.Enum/Flags endpoints are not supported; authoring and catalog compilation reject them before generic JSON can bypass their codecs.
type MigrationBuilder ¶
type MigrationBuilder[Target, Source any] struct { // contains filtered or unexported fields }
MigrationBuilder describes one direction. Use the builder passed to a Migration callback; it is not concurrency-safe. Repeated targets use the last operation.
func (*MigrationBuilder[T, S]) Combine ¶
func (b *MigrationBuilder[T, S]) Combine(target Property[T], separator string, sources ...Property[S]) *MigrationBuilder[T, S]
Combine joins source properties in the supplied order using separator.
func (*MigrationBuilder[T, S]) DefaultValue ¶
func (b *MigrationBuilder[T, S]) DefaultValue(target Property[T], value any) *MigrationBuilder[T, S]
DefaultValue supplies value only when the target is absent, not present-null. Object literals must already use their serialized JSON names, as in C#.
func (*MigrationBuilder[T, S]) MapValues ¶
func (b *MigrationBuilder[T, S]) MapValues(target Property[T], source Property[S], mappings ...ValueMapping) *MigrationBuilder[T, S]
MapValues translates one direction. Unlisted values carry across unchanged. It overrides a shared map on the same target, even when declared with no pairs.
func (*MigrationBuilder[T, S]) RenamedFrom ¶
func (b *MigrationBuilder[T, S]) RenamedFrom(target Property[T], source Property[S]) *MigrationBuilder[T, S]
RenamedFrom copies a source property to its new target name.
func (*MigrationBuilder[T, S]) Split ¶
func (b *MigrationBuilder[T, S]) Split(target Property[T], source Property[S], separator string, part int) *MigrationBuilder[T, S]
Split selects a zero-based part of a source string separated by separator.
type MigrationDeclaration ¶
type MigrationDeclaration struct {
// contains filtered or unexported fields
}
MigrationDeclaration is immutable authoring metadata. Build with DefineMigration or chronicle.RegisterEventMigration; its zero value is invalid.
func DefineMigration ¶
func DefineMigration[U, P any](upgrade Type[U], previous Type[P], migration Migration[U, P]) (MigrationDeclaration, error)
DefineMigration snapshots callbacks and values without resolving catalog paths. Both callbacks are mandatory; registration errors never partially admit a map.
func (MigrationDeclaration) Previous ¶
func (d MigrationDeclaration) Previous() Descriptor
Previous returns the exact declared source generation descriptor.
func (MigrationDeclaration) Upgrade ¶
func (d MigrationDeclaration) Upgrade() Descriptor
Upgrade returns the exact declared target generation descriptor.
type MigrationDefinition ¶
type MigrationDefinition struct {
EventType TypeID
From, To Generation
UpcastJSON, DowncastJSON string
}
MigrationDefinition is a compiled kernel transformation, not executable Go. Strings are immutable JSON in the same vocabulary as C# EventMigrationBuilder.
type NamedTag ¶
type NamedTag struct {
// Name must be nonblank.
Name string
// Value is opaque and may be empty.
Value string
}
NamedTag preserves an exact name/value pair; an empty Value is valid.
type ObservationState ¶
type ObservationState int32
ObservationState is the kernel's observation classification.
const ( // ObservationNone represents no observation classification. ObservationNone ObservationState = iota // ObservationInitial represents ordinary observation. ObservationInitial // ObservationReplay represents replay observation. ObservationReplay )
type PreparationError ¶
type PreparationError = preparation.Error
PreparationError reports only the phase, zero-based provider and event indices, and whether a callback panicked. Index -1 means not applicable. It never wraps or retains application errors or panic values, including diagnostic hooks.
type Property ¶
Property is a dotted Go field path rooted in T, not a JSON path. NewClient resolves every segment through the serialization plan, honoring json tags and the client's naming policy. Collection traversal is not a property path. String literals are accepted directly by the typed builders.
type RedactionCausation ¶
type RedactionCausation struct {
// Occurred is when this cause occurred.
Occurred time.Time `json:"occurred"`
// Type is the kind of cause.
Type string `json:"type"`
// Properties contains any properties actually returned by the kernel.
Properties map[string]string `json:"properties"`
}
RedactionCausation preserves one original audit link from a marker. Newer kernels remove Properties; older kernels may retain them. Do not log payloads.
type RedactionReason ¶
type RedactionReason string
RedactionReason explains why event content must be removed. It must be nonblank and must not itself contain the personal data or secret being removed.
type Revision ¶
type Revision struct {
// Generation identifies the revision's schema generation.
Generation Generation
// CorrelationID identifies the revision operation.
CorrelationID metadata.CorrelationID
// CausedBy identifies the actor responsible for the revision.
CausedBy identities.Identity
// Occurred is the revision timestamp.
Occurred time.Time
// Content is the revision's JSON representation.
Content json.RawMessage
}
Revision preserves one historical revision without discarding its audit metadata.
type SequenceID ¶
type SequenceID string
SequenceID identifies a sequence within a store namespace.
func (SequenceID) IsEventLog ¶
func (id SequenceID) IsEventLog() bool
IsEventLog reports whether id identifies the primary event sequence.
type SequenceNumber ¶
type SequenceNumber uint64
SequenceNumber is a sequence-wide unsigned position, beginning at First (zero). Unavailable, Max and BeforeFirst are reserved, non-actual values. Use its checked methods rather than raw arithmetic to preserve sentinels and reject range errors.
func (SequenceNumber) Add ¶
func (n SequenceNumber) Add(delta uint64) (SequenceNumber, error)
Add adds an unsigned delta to an actual position without wrapping or entering the reserved range. A reserved receiver is returned unchanged with nil error, regardless of delta. A range failure returns Unavailable and ErrSequenceNumberRange. Reject negative signed amounts before converting them to uint64.
func (SequenceNumber) IsActualValue ¶
func (n SequenceNumber) IsActualValue() bool
IsActualValue reports whether n is an actual position, including First (zero). All three reserved values (Unavailable, Max and BeforeFirst) are non-actual.
func (SequenceNumber) IsBeforeFirst ¶
func (n SequenceNumber) IsBeforeFirst() bool
IsBeforeFirst reports whether n is the local BeforeFirst sentinel.
func (SequenceNumber) IsUnavailable ¶
func (n SequenceNumber) IsUnavailable() bool
IsUnavailable reports whether n is the Unavailable sentinel.
func (SequenceNumber) Next ¶
func (n SequenceNumber) Next() (SequenceNumber, error)
Next returns the next actual position, or preserves a reserved receiver. BeforeFirst.Next returns BeforeFirst, not First. A range failure returns Unavailable and ErrSequenceNumberRange. This pure operation performs no I/O; it is distinct from eventsequences.Sequence.Next(ctx), which queries the tail.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/cratis/chronicle.go/events"
)
func main() {
position, err := events.First.Add(2)
if err != nil {
fmt.Println("add:", err)
return
}
next, err := position.Next()
if err != nil {
fmt.Println("next:", err)
return
}
previous, err := next.Subtract(1)
if err != nil {
fmt.Println("subtract:", err)
return
}
fmt.Println(position, next, previous, next.IsActualValue())
beforeFirst, err := events.BeforeFirst.Next()
if err != nil {
fmt.Println("sentinel:", err)
return
}
fmt.Println("still before first:", beforeFirst.IsBeforeFirst())
unavailable, err := (events.BeforeFirst - 1).Next()
if errors.Is(err, events.ErrSequenceNumberRange) {
fmt.Println("range exhausted:", unavailable.IsUnavailable())
} else if err != nil {
fmt.Println("unexpected:", err)
return
}
}
Output: 2 3 2 true still before first: true range exhausted: true
func (SequenceNumber) Subtract ¶
func (n SequenceNumber) Subtract(delta uint64) (SequenceNumber, error)
Subtract subtracts an unsigned delta from an actual position without wrapping. A reserved receiver is returned unchanged with nil error, regardless of delta. Underflow returns Unavailable and ErrSequenceNumberRange. Reject negative signed amounts before converting them to uint64.
type SourceID ¶
type SourceID string
SourceID identifies the entity or subject whose event is appended.
type SourceType ¶
type SourceType string
SourceType classifies an event source independently of its identity.
type Type ¶
type Type[T any] struct { // contains filtered or unexported fields }
Type is a typed immutable descriptor returned by chronicle.RegisterEvent.
func Define ¶
func Define[T any](options ...TypeOption) (Type[T], error)
Define builds an immutable event descriptor without registration or I/O. Most callers use chronicle.RegisterEvent instead. T must be a named non-pointer struct.
func DefineGeneration ¶
func DefineGeneration[Previous, Current any](current Type[Current], generation Generation, options ...TypeOption) (Type[Previous], error)
DefineGeneration builds a historical descriptor referring to a current event. Its ID cannot be overridden, and generation must be positive and lower than current. Options configure the historical shape; WithID and WithGeneration may only repeat the derived identity. Most callers use RegisterEventGeneration.
func (Type[T]) Descriptor ¶
func (t Type[T]) Descriptor() Descriptor
Descriptor returns the immutable untyped descriptor.
type TypeID ¶
type TypeID string
TypeID is a stable persisted event identifier, not necessarily a UUID.
const RedactedTypeID TypeID = "EventRedacted"
RedactedTypeID is the kernel's synthetic replacement event type.
type TypeOption ¶
type TypeOption func(*typeConfig)
TypeOption configures an event declaration. Scalar options are last-wins; nil options and invalid final values fail declaration. Tag inputs are copied.
func WithCodecs ¶
func WithCodecs(codecs *serialization.Codecs) TypeOption
WithCodecs selects an immutable, explicit derived codec set. The last option wins; nil clears it. No global discovery or registration callbacks are used.
func WithCompensationFor ¶
func WithCompensationFor[T any](event Type[T]) TypeOption
WithCompensationFor adds the target's persisted ID as top-level compensationFor schema metadata. It never performs compensation. Last option wins; the handle must belong to the same frozen registry, validated by NewClient.
func WithGeneration ¶
func WithGeneration(generation Generation) TypeOption
WithGeneration selects a positive schema generation (default one). Like C#, clients default to disabling generation validation, allowing a current generation above one without migrations. Enabling client generation validation requires a complete adjacent migration chain starting at generation one.
func WithID ¶
func WithID(id TypeID) TypeOption
WithID overrides the default simple Go type name; use a stable ID across languages.
func WithProtection ¶
func WithProtection(declarations ...compliance.Declaration) TypeOption
WithProtection adds type or property classifications and metadata providers. Declarations are copied; duplicates and conflicts fail registration. Field tags need no option. PII is erasable; confidentiality is a separate schema category.
func WithRemoveConstraints ¶
func WithRemoveConstraints(names ...string) TypeOption
WithRemoveConstraints declares names released by this event for its source. Calls accumulate, duplicate names are ignored, and blank/unknown names fail at NewClient. Names refer to model-bound constraints; for explicit definitions use the builder's RemovedWith method instead.
func WithSourceStore ¶
func WithSourceStore(name string) TypeOption
WithSourceStore declares the origin store for projection inbox inference. Empty resets to unspecified. This never reroutes appends or provisions an inbox.
func WithSubjectResolver ¶
func WithSubjectResolver[T any](resolver func(T) (Subject, bool)) TypeOption
WithSubjectResolver declares the compliance subject policy for T. Returning false falls back to the append source ID; an explicit append subject wins. The callback receives a value even when appending *T. It must be non-nil, match the declared event type and support concurrent calls. Last option wins. The resolver is borrowed by the descriptor and is invoked during serialization snapshots, not again at unit-of-work commit. Empty resolved subjects are invalid for append, like empty explicit subjects; false represents absence.
Example ¶
package main
import (
"fmt"
chronicle "github.com/cratis/chronicle.go"
"github.com/cratis/chronicle.go/events"
)
type CustomerChanged struct{ CustomerID string }
func main() {
registry := chronicle.NewRegistry()
registered, err := chronicle.RegisterEvent[CustomerChanged](registry,
events.WithSubjectResolver(func(event CustomerChanged) (events.Subject, bool) {
return events.Subject(event.CustomerID), event.CustomerID != ""
}))
if err != nil {
panic(err)
}
subject, found := registered.Descriptor().ResolveSubject(CustomerChanged{CustomerID: "customer-42"})
fmt.Println(subject, found)
}
Output: customer-42 true
func WithTags ¶
func WithTags(tags ...Tag) TypeOption
WithTags sets static tags merged distinctly with append tags, in input order.
func WithTombstone ¶
func WithTombstone() TypeOption
WithTombstone records descriptor-only metadata, matching C#'s inert attribute. It does not set the wire Tombstone flag, erase data or change append routing.
func WithUnique ¶
func WithUnique(declaration Unique) TypeOption
WithUnique declares event-type uniqueness. Only one declaration is allowed per type, matching Unique. Inputs are copied; NewClient validates the frozen graph.
type TypeRef ¶
type TypeRef struct {
// ID is the stable event identifier.
ID TypeID
// Generation is the positive generation number.
Generation Generation
}
TypeRef identifies one exact persisted event generation.
type Unique ¶
type Unique struct {
// Name is the stable shared constraint name, or empty for the Go type name.
Name string
// Message is a client-side violation template; empty preserves kernel text.
Message string
// EventSequences restricts enforcement; empty means every sequence.
EventSequences []SequenceID
}
Unique declares one event-type lifecycle constraint (not property uniqueness). Events sharing Name are mutually exclusive per source until a remover occurs. Empty Name defaults to the Go type name; empty EventSequences means all sequences. Message is selected for the violating event type, then the first nonempty message.
type ValueMapBuilder ¶
type ValueMapBuilder[Upgrade, Previous any] struct { // contains filtered or unexported fields }
ValueMapBuilder declares shared maps. Downcast inversion chooses the first previous value declared for each upgraded value, matching C# lossy inversion.
func (*ValueMapBuilder[U, P]) For ¶
func (b *ValueMapBuilder[U, P]) For(upgrade Property[U], previous Property[P], mappings ...ValueMapping) *ValueMapBuilder[U, P]
For declares a bidirectional map for the two generation properties.
type ValueMapping ¶
type ValueMapping struct{ From, To any }
ValueMapping declares a previous/source value followed by its upgraded/target value. Values use their JSON representation (including ordinary named integers and Fundamentals concepts). Inputs are serialized and copied during registration. Closed enum codec endpoints are explicitly unsupported.