Documentation
¶
Overview ¶
Package graph provides a graph or interconnected state-machines and their states, based on the dbg telemetry protocol. The graph is stored in an ark ECS.
Index ¶
- Constants
- Variables
- func AddErrGraph(event *am.Event, mach *am.Machine, err error, args ...am.A) am.Result
- func Markdown(inspect map[string]*MachInspect) string
- func Markup(inspect map[string]*MachInspect) string
- type Cipher
- type Connection
- type DbServerOpts
- type Edge
- type EdgeData
- type EdgeProperties
- type Graph
- func (g *Graph) AddMachine(gmach *Machine) error
- func (g *Graph) AdjacencyMap() map[string]map[string]Edge
- func (g *Graph) Clear()
- func (g *Graph) Clone() (*Graph, error)
- func (g *Graph) Connection(source, target string) (*Connection, error)
- func (g *Graph) DumpGv(path string) error
- func (g *Graph) Edge(source, target string) (Edge, error)
- func (g *Graph) Edges() []Edge
- func (g *Graph) EdgesFrom(source string, kind amtypes.RelKind) []Edge
- func (g *Graph) EdgesOfKind(kind amtypes.RelKind) []Edge
- func (g *Graph) Hist() *HistoryGraph
- func (g *Graph) Inspect() (map[string]*MachInspect, error)
- func (g *Graph) LoadGob(r io.Reader) error
- func (g *Graph) Machine(id string) (*Machine, bool)
- func (g *Graph) MachineCount() int
- func (g *Graph) ParseMsgDbg(id string, msgTx *dbg.DbgMsgTx)
- func (g *Graph) ParseMsgRpc(update *MsgGraphUpdate) bool
- func (g *Graph) PredecessorMap() map[string]map[string]Edge
- func (g *Graph) RemoveMachine(id string) error
- func (g *Graph) RemoveTags(id string)
- func (g *Graph) SaveGob(w io.Writer) error
- func (g *Graph) ShortestPath(from, to string) ([]string, error)
- func (g *Graph) Snapshot() ([]*Vertex, []Edge)
- func (g *Graph) Vertex(hash string) (*Vertex, error)
- type HistParams
- type HistoryGraph
- func (hg *HistoryGraph) Close() error
- func (hg *HistoryGraph) History(ctx context.Context, id string, action amtypes.HistoryAction, p HistParams) (*HistoryResp, error)
- func (hg *HistoryGraph) Remove(id string)
- func (hg *HistoryGraph) ShardCounts() []int
- func (hg *HistoryGraph) ShardOf(id string) (uint8, bool)
- func (hg *HistoryGraph) Track(c *Machine)
- func (hg *HistoryGraph) TrackedCount() int
- func (hg *HistoryGraph) Update(id string, mTime am.Time, qTick uint64, machTick uint32)
- type HistoryGraphOpts
- type HistoryResp
- type MachInspect
- type MachPipeTo
- type Machine
- type MachineHas
- type MsgGraphReqSerialized
- type MsgGraphUpdate
- type NetTracer
- type NetTracerData
- type NetworkGraph
- func (n *NetworkGraph) Broadcast(update *MsgGraphUpdate) error
- func (n *NetworkGraph) Close() error
- func (n *NetworkGraph) EmitToAddr(addr string) (context.Context, context.CancelFunc)
- func (n *NetworkGraph) Sinks() []string
- func (n *NetworkGraph) StartDbHttpServer(addr string, opts ...DbServerOpts) (string, error)
- func (n *NetworkGraph) TraceMach(mach am.Api) (string, error)
- type NetworkGraphOpts
- type SchemaInfo
- type Server
- type StateRelation
- type Vertex
Constants ¶
const ( // CipherKeySize is the required PSK size in bytes. CipherKeySize = chacha20poly1305.KeySize )
Variables ¶
var ( ErrGraph = errors.New("graph error") StateErrGraph = am.PrefixErr + "Graph" )
var ( // ErrHistory is when a history graph operation fails. ErrHistory = errors.New("history graph error") // ErrHistoryParams is when a history action gets invalid params. ErrHistoryParams = errors.New("history params error") // ErrHistoryAction is when a history action is unknown. ErrHistoryAction = errors.New("history action error") // ErrMachineNotTracked is when a machine has no history (yet). ErrMachineNotTracked = errors.New("machine not tracked") )
var ( ErrVertexNotFound = errors.New("vertex not found") ErrEdgeNotFound = errors.New("edge not found") ErrPathNotFound = errors.New("path not found") )
var ErrCipher = errors.New("graph: cipher")
ErrCipher is returned for invalid cipher packets.
var ErrGraphDrop = errors.New("graph update dropped")
ErrGraphDrop indicates a test-injected dropped graph update.
Functions ¶
func AddErrGraph ¶ added in v0.18.8
AddErrGraph adds ErrGraph.
func Markdown ¶ added in v0.18.6
func Markdown(inspect map[string]*MachInspect) string
Markdown returns a Markdown format of the network graph, with state lists, with a flat hierarchy. It's useful for debugging.
func Markup ¶ added in v0.18.9
func Markup(inspect map[string]*MachInspect) string
Markup returns an XML format of the network graph, including full schemas, with a nested hierarchy. It's useful for CSS/XPath queries.
Types ¶
type Cipher ¶ added in v0.19.8
type Cipher struct {
// MetricDropped counts datagrams dropped due to decryption, unknown key,
// or replay errors.
MetricDropped atomic.Int64
// contains filtered or unexported fields
}
Cipher encrypts NetworkGraph datagrams with pre-shared ChaCha20-Poly1305 keys. The same keys must be configured on all peers.
The wire format is version|keyID|nonce|ciphertext|tag, where nonce is a random session prefix followed by a monotonic counter. Datagrams with an unknown key, a bad tag, or a replayed counter are dropped.
A Cipher is safe for concurrent use, but keys should be added before the cipher is passed to NetworkGraphOpts.
func NewCipher ¶ added in v0.19.8
NewCipher returns a cipher sending with sendID and the given key, which has to be CipherKeySize bytes long.
func (*Cipher) AddKey ¶ added in v0.19.8
AddKey registers a receive key, e.g. an old key during rotation.
func (*Cipher) Overhead ¶ added in v0.19.8
Overhead returns the number of bytes added to each datagram.
func (*Cipher) WrapConn ¶ added in v0.19.8
WrapConn returns an encrypted view of conn, with one replay window for the peer.
func (*Cipher) WrapPacketConn ¶ added in v0.19.8
func (c *Cipher) WrapPacketConn(pc net.PacketConn) net.PacketConn
WrapPacketConn returns an encrypted view of pc.
type Connection ¶
type DbServerOpts ¶ added in v0.19.6
type DbServerOpts struct {
// ApiKeys authorizes every request when non-empty. Clients pass a key in
// the X-API-Key header, or as a Sec-WebSocket-Protocol token for
// browser/WASM WebSocket clients (like tools/relay).
ApiKeys []string
}
DbServerOpts configures the Db HTTP server.
type Edge ¶
type Edge struct {
Source string
Target string
Properties EdgeProperties
}
Edge is a directed graph edge between two vertex hashes.
type EdgeData ¶
type EdgeData struct {
// machine has a state
MachHas *MachineHas
// machine has an RPC connection to another machine
MachConnectedTo bool
// machine is a child of another machine
MachChildOf bool
// machine has pipes going to another machine
MachPipesTo []*MachPipeTo
// machine has a tag
MachHasTag bool
// state has relations with other states
StateRelation []*StateRelation
}
type EdgeProperties ¶ added in v0.19.8
type EdgeProperties struct {
Data any
}
EdgeProperties contains edge metadata.
type Graph ¶
type Graph struct {
ParentMach *am.Machine
Machines map[string]*Machine
// contains filtered or unexported fields
}
Graph represents a network graph of state machines, states, and tags.
func New ¶
New creates a graph backed by a new ark world. See NewWithWorld to share the world with other ark users.
func NewWithWorld ¶ added in v0.19.8
NewWithWorld creates a graph backed by the given ark world. A nil world creates a new one.
func (*Graph) AddMachine ¶ added in v0.19.6
func (*Graph) AdjacencyMap ¶ added in v0.19.8
AdjacencyMap returns all vertices and their outgoing edges.
func (*Graph) Connection ¶
func (g *Graph) Connection(source, target string) (*Connection, error)
Connection returns a Connection for the given source-target.
func (*Graph) DumpGv ¶ added in v0.18.1
DumpGv will create a dot-format *.gv file of the graph. To create an SVG:
dot -Tsvg -O path
func (*Graph) Edge ¶ added in v0.19.8
Edge returns a copy of an edge by its source and target hashes.
func (*Graph) EdgesFrom ¶ added in v0.19.8
EdgesFrom returns all edges of a GQL relationship kind starting at source.
func (*Graph) EdgesOfKind ¶ added in v0.19.8
EdgesOfKind returns all edges of a GQL relationship kind, e.g. amtypes.RelHas or amtypes.RelRequire. Pipes are returned one edge per pipe.
func (*Graph) Hist ¶ added in v0.19.8
func (g *Graph) Hist() *HistoryGraph
Hist returns the attached history mirror, or nil.
func (*Graph) LoadGob ¶ added in v0.19.6
LoadGob replaces the graph's contents with the data read from r, as written by Graph.SaveGob. ParentMach is preserved, everything else is rebuilt.
func (*Graph) Machine ¶ added in v0.19.6
Machine returns a copy of a client for safe concurrent reads.
func (*Graph) MachineCount ¶ added in v0.19.8
MachineCount returns the number of machines in the graph.
func (*Graph) ParseMsgDbg ¶ added in v0.19.6
func (*Graph) ParseMsgRpc ¶ added in v0.19.6
func (g *Graph) ParseMsgRpc(update *MsgGraphUpdate) bool
ParseMsgRpc applies a network graph update to the local clock data.
func (*Graph) PredecessorMap ¶ added in v0.19.8
PredecessorMap returns all vertices and their incoming edges.
func (*Graph) RemoveMachine ¶ added in v0.19.6
func (*Graph) RemoveTags ¶ added in v0.19.6
RemoveTags removes all tag vertices and their edges of a machine, e.g. forx render snapshots which don't need tags.
func (*Graph) SaveGob ¶ added in v0.19.6
SaveGob writes the graph to w using encoding/gob.
Only the exported graph data is saved: clients (Machine), vertices, and edges with their EdgeData. Runtime-only state (ParentMach, locks, the ark ECS internals) is not serialized; Graph.LoadGob rebuilds them.
func (*Graph) ShortestPath ¶ added in v0.19.8
ShortestPath returns the shortest undirected path between two vertices.
type HistParams ¶ added in v0.19.8
type HistParams struct {
// State is the state of the bool actions.
State string
// States is the state list of latest-activated / latest-deactivated.
States am.S
// Start is the start of the human time range of the bool actions and
// find-latest.
Start time.Time
// End is the end of the human time range of the bool actions and
// find-latest.
End time.Time
// Limit is the maximum number of find-latest records. Default: 100.
Limit int
// Query are the filters of find-latest.
Query amhist.Query
}
HistParams are the optional params of a history action.
type HistoryGraph ¶ added in v0.19.8
type HistoryGraph struct {
*Graph
// Cfg is the history config shared by all machines.
Cfg amhistgorm.Config
// Dbs are the history database shards.
Dbs []*gorm.DB
// contains filtered or unexported fields
}
HistoryGraph wraps a Graph with a sharded GORM history mirror. Each tracked machine gets a rpc.NetworkMachine and a GORM history tracer, all sharing HistoryGraph.Cfg. Clock updates from the graph are applied to the network machines, which emit transitions to their history tracers.
Machines are distributed across HistoryGraph.Dbs shards using the least loaded shard at registration time. The databases and their connections are owned by the caller. A shard can be shared by many HistoryGraph instances.
func NewHistoryGraph ¶ added in v0.19.8
func NewHistoryGraph( g *Graph, dbs []*gorm.DB, cfg amhistgorm.Config, opts ...HistoryGraphOpts, ) (*HistoryGraph, error)
NewHistoryGraph wraps g with a sharded GORM history mirror and tracks all of its machines. Each db is migrated once and used as a history shard.
func (*HistoryGraph) Close ¶ added in v0.19.8
func (hg *HistoryGraph) Close() error
Close stops mirroring all machines. The databases are left open.
func (*HistoryGraph) History ¶ added in v0.19.8
func (hg *HistoryGraph) History( ctx context.Context, id string, action amtypes.HistoryAction, p HistParams, ) (*HistoryResp, error)
History runs a history API method of a tracked machine.
func (*HistoryGraph) Remove ¶ added in v0.19.8
func (hg *HistoryGraph) Remove(id string)
Remove stops mirroring a machine and disposes its history.
func (*HistoryGraph) ShardCounts ¶ added in v0.19.8
func (hg *HistoryGraph) ShardCounts() []int
ShardCounts returns the number of machines assigned to each history shard.
func (*HistoryGraph) ShardOf ¶ added in v0.19.8
func (hg *HistoryGraph) ShardOf(id string) (uint8, bool)
ShardOf returns the history shard of a machine.
func (*HistoryGraph) Track ¶ added in v0.19.8
func (hg *HistoryGraph) Track(c *Machine)
Track starts mirroring a graph machine into the history. It's called by Graph.AddMachine. Re-tracking with the same schema hash is a no-op. Registration is asynchronous; HistoryGraph.Update calls made meanwhile are buffered and applied once the machine is registered.
func (*HistoryGraph) TrackedCount ¶ added in v0.19.8
func (hg *HistoryGraph) TrackedCount() int
TrackedCount returns the number of machines with a registered history.
type HistoryGraphOpts ¶ added in v0.19.8
type HistoryGraphOpts struct {
// OnErr handles history errors. Defaults to [Graph.ParentMach.AddErr], or
// [log/slog].
OnErr func(err error)
// Parent parents all history network machines. Defaults to
// [Graph.ParentMach], or a private machine.
Parent am.Api
}
HistoryGraphOpts configures a new HistoryGraph.
type HistoryResp ¶ added in v0.19.8
type HistoryResp struct {
// Action is the executed history action.
Action amtypes.HistoryAction `json:"action"`
// Machine is the machine ID.
Machine string `json:"machine"`
// Bool is the result of the bool actions.
Bool bool `json:"bool,omitempty"`
// State is the result of latest-activated / latest-deactivated.
State string `json:"state,omitempty"`
// Records is the result of find-latest.
Records []*amhist.MemoryRecord `json:"records,omitempty"`
// Record is the machine record of find-latest.
Record *amhist.MachineRecord `json:"record,omitempty"`
}
HistoryResp is the history payload of a machine.
type MachInspect ¶ added in v0.18.6
type MachPipeTo ¶
type MachPipeTo struct {
FromState string
ToState string
MutType am.MutationType
}
type Machine ¶ added in v0.19.6
Machine represents a single state machine withing the network graph.
func MsgDbgToMach ¶ added in v0.19.6
func MsgDbgToMach(msg *dbg.DbgMsgStruct) *Machine
type MachineHas ¶
type MsgGraphReqSerialized ¶ added in v0.19.6
type MsgGraphReqSerialized struct {
// MachId is the ID of the machine to resend in full serialized form.
MachId string `json:"m" msgpack:"m"`
}
MsgGraphReqSerialized is when the sender requests a resend of full data for mach ID
type MsgGraphUpdate ¶ added in v0.19.6
type MsgGraphUpdate struct {
*rpc.MsgSrvUpdate `json:"u,omitempty" msgpack:"u"`
// MachId is the machine's ID.
MachId string `json:"i" msgpack:"i"`
// MTimeSum is the machine's time, used as a history ID.
MTimeSum uint64 `json:"m"`
// SchemaHash identifies the machine's schema.
SchemaHash string `json:"s" msgpack:"s"`
// TagsTime is the machine time of the latest change in tags.
TagsTime uint64 `json:"tt" msgpack:"tt"`
// Parent is the machine's parent ID. TODO cache
Parent string `json:"p,omitempty" msgpack:"p"`
// Tags are the source machine tags. nil means unchanged.
Tags []string `json:"t" msgpack:"t"`
}
MsgGraphUpdate is a diff update pushed to sinks.
type NetTracer ¶ added in v0.19.6
type NetTracer struct {
*rpc.SourceTracer
// Mach is the source machine.
Mach am.Api
// MachId is the source machine ID.
MachId string
// SchemaHash identifies the source machine schema.
SchemaHash string
// DataLatestSent is the latest graph data sent for this source.
DataLatestSent *NetTracerData
// Tags is the last successfully sent tag list.
Tags []string
// TagsTime is the machine time of the latest change in tags.
TagsTime uint64
}
NetTracer is a graph source backed by a rpc.SourceTracer.
type NetTracerData ¶ added in v0.19.6
type NetTracerData struct {
*rpc.TracerData
// MachId is the source machine ID.
MachId string
// SchemaHash identifies the source machine schema.
SchemaHash string
}
NetTracerData is a tracer snapshot decorated with source metadata.
type NetworkGraph ¶ added in v0.19.8
type NetworkGraph struct {
// Addr is the local UDP listen address.
Addr string
// Graph is the graph being mirrored.
Graph *Graph
// Db optionally mirrors all graph changes into a graph database.
// See [DbGraph] and pkg/graph/frogql ("frogql" build tag).
// TODO expose via HTTP+JSON, open way for more transports later
Db gtypes.DbGraph
// PushInterval is the interval for emitting clock updates. 0 disables
// periodic updates.
PushInterval time.Duration
// Json uses Json instead of msgpack for the wire format.
Json bool
// Logger is used for diagnostics. Defaults to [slog.Default].
Logger *slog.Logger
// SchemaStore maps schema hashes to source schemas.
// TODO migrate to am.Serialized
SchemaStore map[string]SchemaInfo
// MissingSchemas contains schema hashes seen in updates but not yet
// registered in SchemaStore.
MissingSchemas map[string]struct{}
// Enable random drops of broadcast messages.
TestBroadcastRandomDrops atomic.Bool
// TODO MetricsEnabled atomic.Bool
// MetricResendRequests counts sent MsgGraphReqSerialized messages.
MetricResendRequests atomic.Int32
MetricUpdateTooOld atomic.Int32
// MetricResendsHandled counts handled MsgGraphReqSerialized messages.
MetricResendsHandled atomic.Int32
// MetricReconnects counts successful sink dials, incl. reconnects.
MetricReconnects atomic.Int32
// contains filtered or unexported fields
}
NetworkGraph transports directional graph updates over UDP using the standard library and [GraphUpdate] as the wire message.
func NewNetworkGraph ¶ added in v0.19.8
func NewNetworkGraph( ctx context.Context, addr string, g *Graph, opts ...NetworkGraphOpts, ) (*NetworkGraph, error)
NewNetworkGraph creates a NetworkGraph listening on addr and mirroring g.
func (*NetworkGraph) Broadcast ¶ added in v0.19.8
func (n *NetworkGraph) Broadcast(update *MsgGraphUpdate) error
Broadcast sends an update to every registered UDP destination.
func (*NetworkGraph) Close ¶ added in v0.19.8
func (n *NetworkGraph) Close() error
Close stops the receiver and all emitters.
func (*NetworkGraph) EmitToAddr ¶ added in v0.19.8
func (n *NetworkGraph) EmitToAddr( addr string, ) (context.Context, context.CancelFunc)
EmitToAddr registers a directional UDP destination for graph updates. Cancel the returned context to stop emitting to the address.
The first dial happens synchronously (so an immediate broadcast lands), then the sink is maintained in the background: failed dials are retried with exponential backoff, and broken sinks (write errors) are dropped and re-dialed. Use NetworkGraph.Sinks to check the live set and NetworkGraph.MetricReconnects for dial counts. Only one sink per address is supported; a duplicate call returns an already-cancelled context.
func (*NetworkGraph) Sinks ¶ added in v0.19.8
func (n *NetworkGraph) Sinks() []string
Sinks returns the addresses of the currently connected sinks.
func (*NetworkGraph) StartDbHttpServer ¶ added in v0.19.8
func (n *NetworkGraph) StartDbHttpServer( addr string, opts ...DbServerOpts, ) (string, error)
StartDbHttpServer starts a Server on addr exposing NetworkGraph.Db and the optional HistoryGraph. It returns the actual listen address. NetworkGraph.Close shuts it down.
type NetworkGraphOpts ¶ added in v0.19.8
type NetworkGraphOpts struct {
// Db optionally mirrors all graph changes into a graph database.
Db gtypes.DbGraph
// PushInterval overrides the default clock emit interval.
PushInterval time.Duration
// ReadBufSize overrides the UDP read buffer size. Defaults to 64KB.
ReadBufSize int
// SinkLocalAddr optionally binds sinks to a specific local address, eg
// "127.1.2.3:0". Useful when many sinks share the default local address.
SinkLocalAddr string
// Listener optionally creates the datagram listener. Tests only, nil uses
// UDP.
Listener func(addr string) (net.PacketConn, error)
// Dial optionally creates a datagram sink conn. Tests only, nil uses UDP.
Dial func(addr string) (net.Conn, error)
// Cipher optionally encrypts all graph datagrams with a PSK. The same keys
// must be configured on peers. See [NewCipher].
Cipher *Cipher
}
NetworkGraphOpts configures a new NetworkGraph.
type SchemaInfo ¶ added in v0.19.6
SchemaInfo describes a source schema for remote graph mirroring.
type Server ¶ added in v0.19.6
type Server struct {
// Addr is the actual listen address.
Addr string
// contains filtered or unexported fields
}
Server exposes a types.DbGraph and an optional HistoryGraph over HTTP+JSON and WebSocket on a single listener. Raw GQL is executed against NetworkGraph.Db.
POST /query raw GQL body, JSON reply (msgpack via Accept)
GET /machine?id=X one machine as [am.Serialized], lowercase JSON
GET /history?id=X history API of one machine as [HistResp], with
&action=<HistAction>&state=&states=&start=&end=&limit=
GET /ws WebSocket, one frame per request:
GQL / {"machine": "X"} / {"history": "X", ...}
-> JSON or msgpack reply, matching the frame type
type StateRelation ¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package gochickpeas implements the amtypes.DbGraph backend over the in-memory gochickpeas graph database.
|
Package gochickpeas implements the amtypes.DbGraph backend over the in-memory gochickpeas graph database. |
|
Package shared contains graph types and helpers shared by the DbGraph backends: the DbGraph interface, the mirror model types, and GQL model helpers.
|
Package shared contains graph types and helpers shared by the DbGraph backends: the DbGraph interface, the mirror model types, and GQL model helpers. |
/pkg/history