Documentation
¶
Overview ¶
Package destiny records what a program did as a tree of execution paths, so that tests can check not only that something happened but along which path.
It is github.com/rm4n0s/errors for things that are not errors. A game has few errors, but it has many outcomes: an enemy fled, a chest dropped a rare item, a quest advanced. Each call to Tree.Grow adds a leaf that remembers the path that led to it. One run grows many leaves, and their paths together form a tree:
Game.Tick
├── EnemyAI.decide
│ └── EnemyAI.flee
│ └── [LowHealth] hp=12
└── Loot.roll
└── [RareDrop] item=sword
A route is one path of that tree, written from the root to the leaf:
Game.Tick->EnemyAI.decide->EnemyAI.flee.LowHealth
Tree.HasRoute reports whether the tree grew a given path.
A path is made of the functions on the call stack. Four methods change what the call stack alone would give:
- Tree.Here starts the routes at the calling function, whatever an engine or a test has on the stack above it.
- Tree.Branch gives a part of the tree a name where the call stack says nothing useful: a scene graph or a behaviour tree walked by one function that calls itself.
- Tree.Fork carries a path to another goroutine or to a later moment: an event queue, a timer.
- Tree.Inline leaves the calling function out of the routes: a function that only organizes code and decides nothing.
Index ¶
- Constants
- type Leaf
- type LeafJson
- type PathJson
- type StackFrame
- type Tree
- func (t *Tree) Branch(name string) *Tree
- func (t *Tree) Dump(w io.Writer) error
- func (t *Tree) During(first, last int) *Tree
- func (t *Tree) Find(route string) []*Leaf
- func (t *Tree) Fork() *Tree
- func (t *Tree) Grow(tag string, metadata ...any)
- func (t *Tree) HasRoute(route string) bool
- func (t *Tree) Here() *Tree
- func (t *Tree) Inline() *Tree
- func (t *Tree) Leaves() []*Leaf
- func (t *Tree) Len() int
- func (t *Tree) LogValue() slog.Value
- func (t *Tree) Only(route string) *Tree
- func (t *Tree) Routes() []string
- func (t *Tree) String() string
- func (t *Tree) Tick() int
- func (t *Tree) ToJson() *TreeJson
- type TreeJson
Constants ¶
const ( // TagDumpEncodeFailed is the tag of the error of Dump when the leaves // could not be turned into JSON. TagDumpEncodeFailed = "DumpEncodeFailed" // TagDumpWriteFailed is the tag of the error of Dump when the writer // failed. Its OriginalErr is the error of the writer. TagDumpWriteFailed = "DumpWriteFailed" // TagLoadDecodeFailed is the tag of the error of Load when the reader // failed or what it read is not a dump. Its metadata has the number of // the line under "line". TagLoadDecodeFailed = "LoadDecodeFailed" )
The tags of the errors of this package.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Leaf ¶
type Leaf struct {
Tag string
Metadata map[string]any
// Tick is how many times Tree.Tick had been called when the leaf grew.
Tick int
// contains filtered or unexported fields
}
Leaf is one outcome grown on a Tree: a tag, optional metadata, the tick it grew in and the path that led to it.
func (*Leaf) HasRoute ¶
HasRoute reports whether the route of the leaf contains the given route. The given route may leave out the start or the end of the path, but not part of a name: "EnemyAI.flee.LowHealth", "decide->EnemyAI.flee" and "LowHealth" all match "Game.Tick->EnemyAI.decide->EnemyAI.flee.LowHealth", while "flee.Low" and "Tick->Enemy" do not. An empty route matches nothing.
func (*Leaf) Route ¶
Route returns the path of the leaf from the root of its tree, followed by its tag: "Game.Tick->EnemyAI.decide->EnemyAI.flee.LowHealth".
func (*Leaf) StackFrames ¶
func (l *Leaf) StackFrames() []StackFrame
StackFrames returns the steps on the path of the leaf, from the root of the tree to the function that grew the leaf.
type LeafJson ¶
type LeafJson struct {
Tag string
Path int // an index into TreeJson.Paths
Tick int `json:",omitempty"`
Metadata map[string]any `json:",omitempty"`
}
LeafJson is a Leaf in a form that can be marshaled.
type PathJson ¶
type PathJson struct {
// Route is the steps as text, for whoever reads the log. FromJson and
// Load ignore it and use StackFrames.
Route string `json:",omitempty"`
StackFrames []StackFrame // from the root of the tree to the leaf
}
PathJson is one path of a tree: the steps that several leaves share.
type StackFrame ¶
type StackFrame struct {
FuncName string
StructName string `json:",omitempty"`
PackageName string `json:",omitempty"`
}
StackFrame is one step of a route: a function on the call stack, or a name given by Tree.Branch, which has only a FuncName.
type Tree ¶
type Tree struct {
// contains filtered or unexported fields
}
Tree collects the leaves that a program grows while it runs.
The root of the tree is the function that called NewTree: routes start with the functions that it calls. When that function is no longer running, routes start below the deepest function that is on both the stack of NewTree and the stack of Grow. With nothing in common, a route is the whole stack of the goroutine.
A nil *Tree is valid and does nothing, so a game can leave its tree nil when it does not record.
A tree keeps every leaf until Dump writes them out, so a tree that records a long session has to be dumped from time to time.
A Tree is safe for concurrent use. The handles that Here, Branch, Fork and Inline return grow leaves on the same tree, and the methods that read the tree (HasRoute, Routes, Leaves, String...) read all of it whichever handle they are called on.
func FromJson ¶
FromJson rebuilds a tree, for example one that was logged by a running game, so that a test can compare it with the tree of its own run. The root of the leaves grown on it afterwards is the function that called FromJson.
Numbers in the metadata of a tree that went through JSON are float64.
func Load ¶
Load reads what Dump wrote, any number of lines, into one tree. The root of the leaves grown on it afterwards is the function that called Load.
When the reader fails or a line is not a dump (the last line of a game that crashed while writing, for example), Load returns the tree of the lines before it together with an error with the tag TagLoadDecodeFailed.
Numbers in the metadata of a loaded tree are float64.
func NewTree ¶
func NewTree() *Tree
NewTree returns an empty tree whose root is the calling function.
func (*Tree) Branch ¶
Branch returns a handle for a named part of the tree. In the routes of what grows through the handle, the function that called Branch appears under the given name:
func (n *Node) update(t *destiny.Tree) {
t = t.Branch(n.Name)
for _, child := range n.Children {
child.update(t)
}
}
Without Branch every route of this scene graph would read Node.update->Node.update->Node.update. With it they read World->Level1->Door3.
Calling Branch again in the same function, on the handle it returned, adds a name below the first one.
A name is part of the route, so it has to come from a small, fixed set (the names of nodes, states or scripts) and must not contain "." or "->". What changes for each entity or frame belongs in the metadata of a leaf.
func (*Tree) Dump ¶
Dump writes the leaves that the tree holds to w and then forgets them, so that a tree that records a long session does not grow without end. Call it from time to time: every tick, every few seconds, or when Len passes a limit.
Each call writes one line of JSON, a TreeJson, that can be read on its own: the output can be cut into files between two calls. A tree without leaves writes nothing. Load reads the lines back.
When writing fails, Dump returns an error with the tag TagDumpWriteFailed and the tree keeps its leaves. A metadata value that JSON cannot hold (a channel, a function, a NaN) is written as its text.
Dump may be called from another goroutine than the one that grows the tree. Growing does not wait for the writer.
func (*Tree) During ¶
During returns a tree with the leaves that grew in the ticks from first to last, both included. It is a copy: leaves grown later on either tree do not appear on the other.
func (*Tree) Find ¶
Find returns the leaves whose route has the given route, in the order they grew. Use it to count how often a path was taken, to read the metadata of its leaves, or to compare the ticks of two outcomes.
func (*Tree) Fork ¶
Fork returns a handle that continues the current path somewhere else: in another goroutine, or at a later moment in the same one.
A goroutine's call stack does not contain the function that started it. Call Fork in the goroutine that hands the work off and use the handle in the new one:
go ai.think(tree.Fork()) // the arguments of a go statement run in the parent
An event that is queued and handled later has the same problem: when the handler runs, the function that sent the event has returned. Store a fork in the event and grow through it in the handler:
queue.push(event{kind: doorOpened, fate: tree.Fork()})
The routes of the leaves grown through the handle start with the path of the Fork call and continue with the functions of the stack of Grow that were not already running when Fork was called.
func (*Tree) Grow ¶
Grow adds a leaf with the given tag at the end of the current path.
The metadata is a list of key-value pairs, as in log/slog: Grow("LowHealth", "hp", 12). A value without a string key before it is stored as "arg<index>". Pass values, not pointers to things that change: the leaf keeps what it is given, and what a pointer points to may be different when the leaf is read.
Whatever is different for each entity or each frame (an ID, a position) belongs in the metadata. The tag is part of the route, and the tree keeps every different path it has seen.
func (*Tree) HasRoute ¶
HasRoute reports whether the tree grew a leaf along the given route. See Leaf.HasRoute for what a route may leave out.
func (*Tree) Here ¶
Here returns a handle whose routes continue with the calling function alone, and leave out everything else that is on the call stack above it.
A game engine calls the frame function of a game through many functions of its own, and a test calls it through others. Call Here at the top of the frame function and grow through the handle: the routes then start with that function wherever it was called from.
func (w *World) Step(in Input) {
fate := w.fate.Here()
w.player.act(fate, in) // World.Step->Player.act...
}
On a handle of Fork or Branch, Here keeps the path of the handle and adds the calling function to it.
func (*Tree) Inline ¶ added in v0.2.0
Inline returns a handle in whose routes the calling function does not appear: it counts as part of the function that called it.
Every function between the frame function and a Grow line is in the route. That is wanted for a function that decides something. A function that only organizes code (the body of a frame function that was moved into its own function, a loop over entities, a closure) calls Inline first and goes on with the handle, so that the routes are what they were without it:
func (w *World) play(fate *destiny.Tree, in Input) {
fate = fate.Inline()
w.player.act(fate, in) // World.Step->Player.act, not World.Step->World.play->Player.act
}
Only what grows through the handle leaves the function out. A leaf grown in the function itself, through the handle, has the path of the caller.
Inline is Branch without a name. It does nothing about a function that was renamed: give that one a name that stays, with Branch.
func (*Tree) Leaves ¶
Leaves returns the leaves that the tree holds, in the order they grew. A path that was taken twice has two leaves.
func (*Tree) LogValue ¶
LogValue implements slog.LogValuer. The keys match the fields of TreeJson, so a logged tree can be unmarshaled into TreeJson and rebuilt with FromJson.
func (*Tree) Only ¶
Only returns a tree with the leaves whose route has the given route (see Leaf.HasRoute). Use it to look at one part of a tree: the routes below one function, or the leaves with one tag. It is a copy, as with During.
func (*Tree) Routes ¶
Routes returns the different routes of the tree, in the order they first grew. A path that was taken many times appears once, so the result describes the shape of the tree: comparing it with a list of expected routes checks both what happened and that nothing else did.
func (*Tree) String ¶
String draws the tree, one step or leaf per line, in the order they first grew. A leaf is written as its tag in brackets followed by its metadata. Leaves with the same tag at the same place are drawn once, with how many there are instead of their metadata:
Game.Tick
├── EnemyAI.decide
│ └── EnemyAI.flee
│ └── [LowHealth] hp=12
└── Physics.step
└── [Grounded] x120