Documentation
¶
Overview ¶
DST (Deterministic Simulation Testing) provides a game-logic-agnostic fuzzer and structural state checker for Cardinal. It generates random commands by introspecting registered command types (via reflection), injects engine operations (tick, restart, snapshot/restore) with randomized weights, and validates structural ECS invariants after every tick. Game logic correctness is irrelevant — only engine correctness matters.
Usage from a game shard's test directory:
func TestDST(t *testing.T) {
cardinal.RunDST(t, func(w *cardinal.World) {
w.RegisterComponent[component.MyComponent]()
w.RegisterSystem(&system.MySystem{})
// ... register all components and systems
}, []cardinal.Command{system.BootstrapCommand{Seed: 42}})
}
E2E test helper with real (in-memory) NATS. Similar to the DST harness in dst.go, but runs the full World.run loop (ticking, snapshotting, restoring) while a separate goroutine sends randomized commands through the real ConnectRPC service.
Index ¶
- Constants
- Variables
- func RunDST(t *testing.T, setup DSTSetupFunc, preTestCommands []Command)
- func RunE2E(t *testing.T, setup E2ESetupFunc)
- type AuthMode
- type Command
- type CommandContext
- type DSTSetupFunc
- type E2ESetupFunc
- type Entity
- type EntityID
- type Event
- type OtherWorld
- type Plugin
- type Search
- type SearchResult
- type Slice
- type System
- type SystemHook
- type SystemOption
- type Tick
- type User
- type World
- func (w *World) Broadcast[T Event](evt T)
- func (w *World) Commands[T Command]() iter.Seq[CommandContext[T]]
- func (w *World) Contains[T any]() Search
- func (w *World) Create[T any]() Entity
- func (w *World) EmitSystemEvent[T ecs.SystemEvent](systemEvent T)
- func (w *World) Entity(id EntityID) Entity
- func (w *World) Exact[T any]() Search
- func (w *World) Logger() *zerolog.Logger
- func (w *World) RegisterCommand[T Command]()
- func (w *World) RegisterComponent[T ecs.Component]()
- func (w *World) RegisterEvent[T Event]()
- func (w *World) RegisterPlugin(plugin Plugin)
- func (w *World) RegisterSystem(s System, opts ...SystemOption)
- func (w *World) RegisterSystemEvent[T ecs.SystemEvent]()
- func (w *World) SendTo[T Event](recipient string, evt T)
- func (w *World) SendToShard(to OtherWorld, cmd command.Payload)
- func (w *World) StartGame()
- func (w *World) SystemEvents[T ecs.SystemEvent]() iter.Seq[T]
- func (w *World) Tick(timestamp time.Time)
- func (w *World) TickHeight() uint64
- func (w *World) Timestamp() time.Time
- type WorldOptions
Constants ¶
const ( // PreUpdate runs before the main update. PreUpdate = ecs.PreUpdate // Update runs during the main update phase. Update = ecs.Update // PostUpdate runs after the main update. PostUpdate = ecs.PostUpdate // Init runs once during world initialization. Init = ecs.Init )
const MinEpochFrequency = 10
Variables ¶
var ( ErrSingleNoResult = eris.New("expected exactly 1 result, got 0") ErrSingleMultipleResult = eris.New("expected exactly 1 result, got more than 1") )
var ErrWorldStarted = eris.New(
"cannot register after the world has started; register before StartGame and outside systems")
ErrWorldStarted is the panic value of every Register* method once init has run the first system. Registration mutates tables that systems read (component IDs, command queues, event and system event registries), so it must finish before StartGame and cannot happen inside a system. This is a plain panic, not assert.That, so it also fires in release builds.
Functions ¶
func RunDST ¶ added in v0.10.2
func RunDST(t *testing.T, setup DSTSetupFunc, preTestCommands []Command)
RunDST executes a deterministic simulation test. The setup function registers game-specific systems; the harness handles everything else: randomized engine config, command generation, ticking, restart/restore operations, and structural invariant checking.
preTestCommands are enqueued before randomized fuzz operations begin. This supports worlds that require deterministic bootstrap commands before entering an active state.
The number of ticks defaults to 1000 and can be overridden with -dst.ticks:
go test ./pkg/cardinal/... -dst.ticks=5000
func RunE2E ¶ added in v0.10.2
func RunE2E(t *testing.T, setup E2ESetupFunc)
RunE2E executes an end-to-end test. The setup function creates the world the same way production does; the harness transparently injects the in-memory test NATS URL. The harness starts the world's run loop in a background goroutine and sends randomized commands over ConnectRPC from the test goroutine.
E2E tests are skipped by default. Use the -e2e.run flag to enable them:
go test ./pkg/cardinal/... -e2e.run
The run duration defaults to 30s and can be overridden with -e2e.duration:
go test ./pkg/cardinal/... -e2e.run -e2e.duration=2m
Types ¶
type AuthMode ¶ added in v0.12.0
type AuthMode uint8
AuthMode selects the authentication mode for the client-facing ConnectRPC service.
func ParseAuthMode ¶ added in v0.12.0
type CommandContext ¶ added in v0.10.0
type DSTSetupFunc ¶ added in v0.10.2
type DSTSetupFunc func(w *World)
DSTSetupFunc registers systems, components, and commands on a World. It is called once during fixture creation, before the first tick.
type E2ESetupFunc ¶ added in v0.10.2
type E2ESetupFunc func() *World
E2ESetupFunc builds and returns the world used by the E2E harness. The harness injects a test NATS URL via environment variables before invoking setup.
type Entity ¶ added in v0.16.9
type Entity struct {
// contains filtered or unexported fields
}
Entity is a runtime handle to an entity in one world. Store ID() in components, commands, and snapshots, then bind that ID with World.Entity when needed. Like EntityID, a handle must not be retained after destruction or a world reset: numeric IDs can be reused. Entity methods must run on the world's system goroutine.
func (Entity) Alive ¶ added in v0.16.9
Alive reports whether the entity exists in its world. A zero handle is not alive.
func (Entity) Destroy ¶ added in v0.16.9
Destroy removes the entity and all its components. It returns false if absent.
func (Entity) Get ¶ added in v0.16.9
Get returns a copy of a component. It panics if the entity or component is absent. Use Has when the component is optional, and Set to write a modified copy back.
func (Entity) ID ¶ added in v0.16.9
ID returns the numeric identifier used by storage, commands, and physics.
type OtherWorld ¶
OtherWorld is a type that represents the address of an external service.
type Plugin ¶ added in v0.11.0
type Plugin interface {
Register(w *World)
}
Plugin defines a self-contained extension that can register systems, components, commands, and events with a World. Plugins allow reusable game logic to be packaged and shared across projects.
Nothing registers implicitly: a plugin's Register method must call RegisterComponent, RegisterCommand, RegisterEvent, and RegisterSystemEvent for everything its systems use, including types that belong to another plugin. Registering a type twice is a no-op.
Example:
type MyPlugin struct{ config MyConfig }
func (p *MyPlugin) Register(w *cardinal.World) {
w.RegisterComponent[MyComponent]()
w.RegisterCommand[MyCommand]()
w.RegisterEvent[MyEvent]()
w.RegisterSystem(&MyInitSystem{}, cardinal.WithHook(cardinal.Init))
w.RegisterSystem(&MyTickSystem{})
}
type Search ¶ added in v0.17.0
type Search struct {
// contains filtered or unexported fields
}
Search is a resolved, world-bound query returned by World.Contains and World.Exact. It holds component IDs, not entity data, so it remains valid as entities change.
func (Search) Create ¶ added in v0.17.0
Create returns a new entity with the query's components, initialized to zero.
func (Search) GetByID ¶ added in v0.17.0
GetByID returns a handle if the entity matches the query's archetype.
func (Search) Iter ¶ added in v0.17.0
func (q Search) Iter() SearchResult
Iter yields each matching entity as a world-bound handle.
type SearchResult ¶ added in v0.11.0
SearchResult is a chainable iterator over entities.
func (SearchResult) Filter ¶ added in v0.11.0
func (s SearchResult) Filter(predicate func(Entity) bool) SearchResult
Filter returns a new iterator that only yields values that satisfy predicate. A nil predicate returns the original iterator unchanged.
func (SearchResult) Limit ¶ added in v0.11.0
func (s SearchResult) Limit(limit uint32) SearchResult
Limit returns a new iterator that yields at most limit values. A limit <= 0 yields no values.
func (SearchResult) Single ¶ added in v0.11.0
func (s SearchResult) Single() (Entity, error)
Single returns the single value in the iterator. It returns an error if the iterator yields zero or more than one result.
type Slice ¶ added in v0.16.7
Slice is world-engine's sequence with a private backing array, re-exported so a component can declare one without a second import. It is an alias, so cardinal.Slice[T] and immutable.Slice[T] are the same type and either spelling works.
Its derivations edit in place; see immutable.Slice for what that means at a call site.
type System ¶ added in v0.16.5
type System interface {
Run(w *World)
}
System is a unit of game logic that runs once per tick phase. Run receives the world it was registered with; use it for searches, commands, events, entities, and the current tick. Any other state a system needs (a runtime, a config) lives on the implementing struct.
type SystemHook ¶ added in v0.10.0
type SystemHook = ecs.SystemHook
SystemHook defines when a system should be executed in the update cycle.
type SystemOption ¶ added in v0.10.0
type SystemOption func(*systemConfig)
SystemOption is a function that configures a SystemConfig.
func WithHook ¶
func WithHook(hook SystemHook) SystemOption
WithHook returns an option to set the system hook.
type User ¶ added in v0.12.0
type User struct {
jwt.RegisteredClaims
ID string `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
func UserFromContext ¶ added in v0.12.0
type World ¶
type World struct {
// contains filtered or unexported fields
}
World contains the game state and is the main Cardinal API.
func NewWorld ¶
func NewWorld(opts WorldOptions) (*World, error)
NewWorld creates a game world with the specified options.
func (*World) Broadcast ¶ added in v0.17.0
Broadcast enqueues an event delivered to every open event stream at the end of the tick. It panics if T was not registered with RegisterEvent.
func (*World) Commands ¶ added in v0.17.0
func (w *World) Commands[T Command]() iter.Seq[CommandContext[T]]
Commands yields the commands of type T received for the current tick. It panics if T was not registered with RegisterCommand. Like ErrWorldStarted this is a plain panic, not assert.That: registration is explicit, so a missing RegisterCommand is a user error that must also fail in release builds instead of reading another command's queue.
func (*World) Contains ¶ added in v0.17.0
Contains returns a search for entities with every component in T, allowing extras. T is an archetype: a struct whose fields are registered component types. It panics if any component in T was not registered with RegisterComponent.
func (*World) Create ¶ added in v0.17.0
Create creates an entity with the zero-valued components declared by T, an archetype struct whose fields are component types. It panics if any of them was not registered with World.RegisterComponent.
func (*World) EmitSystemEvent ¶ added in v0.17.0
func (w *World) EmitSystemEvent[T ecs.SystemEvent](systemEvent T)
EmitSystemEvent emits a system event for systems later in the tick. It panics if T was not registered with RegisterSystemEvent, in release builds too: an unregistered emit dropped silently would leave every later SystemEvents reader empty.
func (*World) Entity ¶ added in v0.17.0
Entity binds a numeric ID to this world. It does not require the entity to exist. Use Alive or Has to check before accessing an optional entity.
func (*World) Exact ¶ added in v0.17.0
Exact returns a search for entities with exactly the components in T. T is an archetype: a struct whose fields are registered component types. It panics if any component in T was not registered with RegisterComponent.
func (*World) RegisterCommand ¶ added in v0.17.0
RegisterCommand registers a command type before world startup. Registering it again is a no-op. The service accepts a command from clients only once it is registered here.
func (*World) RegisterComponent ¶ added in v0.17.0
RegisterComponent registers a component type before world startup. Every component used by a system, archetype, or snapshot must be registered here; nothing registers components implicitly. Register components before StartGame.
func (*World) RegisterEvent ¶ added in v0.17.0
RegisterEvent registers an event type before world startup so it appears in introspection metadata and can be sent. Registering it again is a no-op.
func (*World) RegisterPlugin ¶ added in v0.16.8
RegisterPlugin registers a plugin with the world. Must be called before StartGame(). Panics if the plugin fails to register, consistent with other registration functions.
func (*World) RegisterSystem ¶ added in v0.16.8
func (w *World) RegisterSystem(s System, opts ...SystemOption)
RegisterSystem registers a system for the hook in opts (Update by default). Register the components, commands, events, and system events a system uses before StartGame.
func (*World) RegisterSystemEvent ¶ added in v0.17.0
func (w *World) RegisterSystemEvent[T ecs.SystemEvent]()
RegisterSystemEvent registers a system event type before world startup. System events carry data between systems within one tick. Registering it again is a no-op.
Example:
// Define a system event for player deaths.
type PlayerDeath struct{ Nickname string }
func (PlayerDeath) Name() string { return "player-death" }
w.RegisterSystemEvent[PlayerDeath]()
// One system emits it.
func (s *CombatSystem) Run(w *cardinal.World) {
w.EmitSystemEvent(PlayerDeath{Nickname: "Player1"})
}
// Another system, later in the tick, receives it.
func (s *GraveyardSystem) Run(w *cardinal.World) {
for death := range w.SystemEvents[PlayerDeath]() {
// Process the system event.
}
}
func (*World) SendTo ¶ added in v0.17.0
SendTo enqueues a targeted event that is delivered only to the named recipient (a user ID), provided they have an open event stream subscribed to this event. If the recipient has no open stream, the event is silently dropped. It panics if T was not registered with RegisterEvent.
Example:
w.SendTo(cmd.Persona, Result{OK: true})
func (*World) SendToShard ¶ added in v0.17.0
func (w *World) SendToShard(to OtherWorld, cmd command.Payload)
SendToShard sends cmd to another shard, addressed by to. This is the first-class shard-to-shard send: the world performs the send (it owns the event queue) and the address `to` is plain data with no behavior of its own. It mirrors the client-facing SendCommand RPC — a shard sending to a shard is the same operation, initiated in-engine.
Fire-and-forget: the actual network send happens when events flush at end-of-tick, so cmd must not be mutated after this call — a *Command whose fields change before the flush would send the mutated value. A send that fails is not returned (it must not block the tick) but is logged at error level, because a dropped shard-to-shard command is serious.
func (*World) StartGame ¶
func (w *World) StartGame()
StartGame runs the game until the process receives a stop signal.
func (*World) SystemEvents ¶ added in v0.17.0
func (w *World) SystemEvents[T ecs.SystemEvent]() iter.Seq[T]
SystemEvents yields the system events of type T emitted so far in the current tick. It panics if T was not registered with RegisterSystemEvent, in release builds too.
func (*World) Tick ¶ added in v0.10.0
Tick advances the world by one step.
Each tick is a root trace: ticks are driven by the clock, not by a request, so command spans from the ConnectRPC service are not their parents.
func (*World) TickHeight ¶ added in v0.17.0
TickHeight returns the height of the tick currently running.
type WorldOptions ¶
type WorldOptions struct {
Region string // Region that contains the shard
Organization string // Organization that owns the world
Project string // Project name within the organization
ShardID string // Unique ID of the world instance
TickRate float64 // Number of ticks each second
SnapshotStorageType snapshot.StorageType // Snapshot storage type
SnapshotRate uint32 // Number of ticks between snapshots
Debug *bool // Enables the debug server
Pprof *bool // Enables the pprof server
NATSConfig *micro.NATSConfig // Optional NATS configuration; nil uses environment values or defaults
AuthMode AuthMode // Authentication mode for the client ConnectRPC service
ArgusAuthURL string // Argus Auth service URL; required when AuthMode is ARGUS
}