graph

package
v0.19.8 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 38 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

/pkg/history

cd /

[!NOTE] asyncmachine-go is a declarative execution model based on AOP, actor model, and state machines.

/pkg/graph handles a directional multigraph of connected state machines. It's used by the debugging tools (am-dbg and am-vis) and the NetworkGraph based discovery network. The graph is an essential tool to handle large swarms of state machines.

Graph

The in-memory graph is based on dominikbraun/graph and consumes /pkg/telemetry/dbg (large and explicit) or /pkg/rpc.MsgServerUpdate (checksumed diffs). It outputs as MD, DOT, SVG, D2, Mermaid, and encoding/gob. RPC connections are inferred from machine tags.

NetworkGraph

NetworkGraph is a UDP-based synchronization node for Graph instances. It can form any custom mesh network topology to create the desired redundancy of streams and sink nodes (cycles allowed). It features basic encryption, but running over Wireguard is advised. It also requires a locally injected SchemaStore for all the observed state machines.

Features
  • UDP diffs with checksums and on-demand full sync
  • emit to multiple downstreams
  • receive from multiple upstreams
  • deduplication via machine time (cycles allowed)
  • optional ChaCha20-Poly1305 PSK datagram encryption
cipher, _ := graph.NewCipher(1, psk) // 32-byte key
cipher.AddKey(0, oldPsk)             // optional rotation grace period
ng, _ := graph.NewNetworkGraph(ctx, addr, g,
    graph.NetworkGraphOpts{Cipher: cipher})

DbGraph

DbGraph is a swappable DB backend serving over HTTP and WebSocket and speaking Graph Query Language (not GraphQL) in read-only mode. It can be attached to a NetworkGraph, which usually happens on redundant sink nodes.

Dictionary:

(:Machine {id, parent, schema_hash, mtime_sum, queue_tick, mach_tick})
(:State   {mach, name, tick, active})
(:Tag     {mach, name, value})
(Machine)-[:HAS]->(State)
(Machine)-[:HAS_TAG]->(Tag)
(Machine)-[:CHILD_OF]->(Machine)
(Machine)-[:CONNECTED_TO]->(Machine)   // rpc conns (src-id tags)
(State)-[:REQUIRE|ADD|REMOVE|AFTER]->(State)

Examples:

A machine with an active state and a tag value:

MATCH (m:Machine)-[:HAS]->(s:State), (m)-[:HAS_TAG]->(t:Tag)
WHERE s.name = 'Available' AND s.active = true AND t.value = 'db'
RETURN m.id AS id

A child of a machine with a tag value:

MATCH (m:Machine)-[:CHILD_OF]->(p:Machine)-[:HAS_TAG]->(pt:Tag)
WHERE p.id = 'somemach' AND pt.value = 'sometag'
RETURN m.id AS id

RPC conns (from src-id tags):

MATCH (m:Machine)-[:CONNECTED_TO]->(src:Machine)
RETURN m.id AS id, src.id AS src
Backend
gochickpeas

The gochickpeas backend is the fastest backend as a native Go port of RustyChickpeas.

benchmark ns/op tps allocs/op
MachineListExec 38 k 26278 305
MachineListExecParallel 24 k 41476 305
MachineListHttp 246 k 4070 1108
MachineListHttpParallel 53 k 18978 1136
MachineSerializedHttp 110 k 9080 308
WsQueryJson 158 k 6319 1016
WsQueryMsgpack 118 k 8480 768
WsQueryMsgpackParallel 37 k 27062 768
FrogDB

The FrogDB backend uses the official WASM build translated to Golang via ncruces/wasm2go. A custom build step is required to download and translate the binary locally. Behind frogql tag, see task gen-graph-frogql.

benchmark ns/op tps allocs/op
MachineListExec 483 k 2071 723
MachineListExecParallel 496 k 2015 723
MachineListHttp 820 k 1219 1527
MachineListHttpParallel 564 k 1772 1527
MachineSerializedHttp 920 k 1087 247
WsQueryJson 645 k 1549 1434
WsQueryMsgpack 595 k 1680 1186
WsQueryMsgpackParallel 554 k 1804 1188
Native

The native backend simply traverses /pkg/graph.Graph using a GQL parser from gochickpeas. It's the most lightweight, but also the slowest.

benchmark ns/op tps allocs/op
MachineListExec 761 k 1314 6971
MachineListExecParallel 326 k 3066 6971
MachineListHttp 1.09 M 922 7788
MachineListHttpParallel 375 k 2669 7809
MachineSerializedHttp 913 k 1095 6619
WsQueryJson 947 k 1056 7687
WsQueryMsgpack 894 k 1119 7435
WsQueryMsgpackParallel 348 k 2874 7438

HistoryGraph

HistoryGraph wraps Graph and tracks history via /pkg/history/gorm (N-shards) for all machine present in the graph. NetworkGraph supports running MemoryApi queries over the /history endpoint.

Topology Examples

Example of clustered NetworkGraphs in tree structures with a single sink per cluster. The sink nodes have public endpoints, but also (as netgraphs) synchronize the graph between each other in a ring. Machine-time backed de-duplication prevents an infinite sync loop. This is both a suggested topology and a runnable test.

TODO

  • optimizations

Status

Testing, work in progress, not semantically versioned.

monorepo

Go back to the monorepo root to continue reading.

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

View Source
const (
	// CipherKeySize is the required PSK size in bytes.
	CipherKeySize = chacha20poly1305.KeySize
)

Variables

View Source
var (
	ErrGraph      = errors.New("graph error")
	StateErrGraph = am.PrefixErr + "Graph"
)
View Source
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")
)
View Source
var (
	ErrVertexNotFound = errors.New("vertex not found")
	ErrEdgeNotFound   = errors.New("edge not found")
	ErrPathNotFound   = errors.New("path not found")
)
View Source
var ErrCipher = errors.New("graph: cipher")

ErrCipher is returned for invalid cipher packets.

View Source
var ErrGraphDrop = errors.New("graph update dropped")

ErrGraphDrop indicates a test-injected dropped graph update.

Functions

func AddErrGraph added in v0.18.8

func AddErrGraph(
	event *am.Event, mach *am.Machine, err error, args ...am.A,
) am.Result

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

func NewCipher(sendID uint8, key []byte) (*Cipher, error)

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

func (c *Cipher) AddKey(id uint8, key []byte) error

AddKey registers a receive key, e.g. an old key during rotation.

func (*Cipher) Overhead added in v0.19.8

func (c *Cipher) Overhead() int

Overhead returns the number of bytes added to each datagram.

func (*Cipher) WrapConn added in v0.19.8

func (c *Cipher) WrapConn(conn net.Conn) net.Conn

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 Connection struct {
	Edge   *EdgeData
	Source *Vertex
	Target *Vertex
}

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

func New(parentMach *am.Machine) (*Graph, error)

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

func NewWithWorld(parentMach *am.Machine, world *ecs.World) (*Graph, error)

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 (g *Graph) AddMachine(gmach *Machine) error

func (*Graph) AdjacencyMap added in v0.19.8

func (g *Graph) AdjacencyMap() map[string]map[string]Edge

AdjacencyMap returns all vertices and their outgoing edges.

func (*Graph) Clear

func (g *Graph) Clear()

func (*Graph) Clone

func (g *Graph) Clone() (*Graph, error)

Clone returns a deep clone of the graph.

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

func (g *Graph) DumpGv(path string) error

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

func (g *Graph) Edge(source, target string) (Edge, error)

Edge returns a copy of an edge by its source and target hashes.

func (*Graph) Edges added in v0.19.8

func (g *Graph) Edges() []Edge

Edges returns all edges.

func (*Graph) EdgesFrom added in v0.19.8

func (g *Graph) EdgesFrom(source string, kind amtypes.RelKind) []Edge

EdgesFrom returns all edges of a GQL relationship kind starting at source.

func (*Graph) EdgesOfKind added in v0.19.8

func (g *Graph) EdgesOfKind(kind amtypes.RelKind) []Edge

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) Inspect added in v0.18.6

func (g *Graph) Inspect() (map[string]*MachInspect, error)

func (*Graph) LoadGob added in v0.19.6

func (g *Graph) LoadGob(r io.Reader) error

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

func (g *Graph) Machine(id string) (*Machine, bool)

Machine returns a copy of a client for safe concurrent reads.

func (*Graph) MachineCount added in v0.19.8

func (g *Graph) MachineCount() int

MachineCount returns the number of machines in the graph.

func (*Graph) ParseMsgDbg added in v0.19.6

func (g *Graph) ParseMsgDbg(id string, msgTx *dbg.DbgMsgTx)

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

func (g *Graph) PredecessorMap() map[string]map[string]Edge

PredecessorMap returns all vertices and their incoming edges.

func (*Graph) RemoveMachine added in v0.19.6

func (g *Graph) RemoveMachine(id string) error

func (*Graph) RemoveTags added in v0.19.6

func (g *Graph) RemoveTags(id string)

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

func (g *Graph) SaveGob(w io.Writer) error

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

func (g *Graph) ShortestPath(from, to string) ([]string, error)

ShortestPath returns the shortest undirected path between two vertices.

func (*Graph) Snapshot added in v0.19.8

func (g *Graph) Snapshot() ([]*Vertex, []Edge)

Snapshot returns all vertices and edges in one batch.

func (*Graph) Vertex added in v0.19.8

func (g *Graph) Vertex(hash string) (*Vertex, error)

Vertex returns a copy of a vertex by its hash.

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.

func (*HistoryGraph) Update added in v0.19.8

func (hg *HistoryGraph) Update(
	id string, mTime am.Time, qTick uint64, machTick uint32,
)

Update applies the current clocks of a machine to its history mirror. It's a no-op for machines which aren't tracked. Updates of machines being registered are buffered and applied after registration.

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 MachInspect struct {
	Child    string
	States   []string
	Conns    []string
	Pipes    map[string][]string
	Schema   am.Schema
	Tags     []string
	MTime    am.Time
	MTimeSum uint64
}

type MachPipeTo

type MachPipeTo struct {
	FromState string
	ToState   string
	MutType   am.MutationType
}

type Machine added in v0.19.6

type Machine = amtypes.Machine

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 MachineHas struct {
	Auto  bool
	Multi bool
}

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.

func (*NetTracer) SchemaChange added in v0.19.6

func (t *NetTracer) SchemaChange(mach am.Api, oldSchema am.Schema)

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.

func (*NetworkGraph) TraceMach added in v0.19.8

func (n *NetworkGraph) TraceMach(mach am.Api) (string, error)

TraceMach adds a machine to the mirrored graph and starts emitting its clock updates. It returns the tracer ID used by the source machine.

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

type SchemaInfo struct {
	Schema      am.Schema
	StatesIndex am.S
}

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

func (*Server) Close added in v0.19.6

func (s *Server) Close() error

Close stops the server and its WebSocket connections.

type StateRelation

type StateRelation struct {
	RelType am.Relation
}

type Vertex

type Vertex struct {
	StateName string
	TagName   string
	MachId    string
}

func (*Vertex) Hash added in v0.19.8

func (v *Vertex) Hash() string

Hash returns the graph hash of the vertex.

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.

Jump to

Keyboard shortcuts

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