grid

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2026 License: MIT Imports: 13 Imported by: ? modules, 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

Grid Application

Doc: https://docs.ergo.services/extra-library/applications/grid

In a cluster you often need processes on different nodes to find each other by name, react when one appears or disappears, and broadcast to a changing set of subscribers. Doing this by hand means wiring point-to-point monitors, tracking who lives where, and inventing a naming scheme, all while nodes join and leave.

Grid provides this as an application: a distributed in-memory registry, key-scoped lifecycle monitors, and per-key process groups. It is AP and eventually consistent - every node keeps a full local copy of the registry, so lookups are local and instant, and writes replicate to peers in the background. Actors interact with it through helper functions in the grid package; there is no wiring between nodes to maintain.

Installation

go get ergo.services/application/grid

Starting

Load and start the Grid application on your node:

import (
    "ergo.services/application/grid"
    "ergo.services/ergo"
    "ergo.services/ergo/gen"
)

func main() {
    node, _ := ergo.StartNode("mynode@localhost", gen.NodeOptions{
        Applications: []gen.ApplicationBehavior{
            grid.CreateApp(grid.Options{Domain: "grid", Shards: 8}),
        },
    })

    node.Wait()
}

Every node that starts Grid with the same Domain discovers the others automatically - through the registrar, connected nodes, or static Peers - and forms a mesh. No further configuration is required.

Using from Actors

Every helper takes the calling actor (a gen.Process) as its first argument. An empty domain resolves to "default".

Registry

Register a key under the calling process, look it up from any node, and unregister it:

func (w *worker) Init(args ...any) error {
    if err := grid.Register(w, "grid", "order/42", "meta-v1"); err != nil {
        return err // gen.ErrTaken if a live owner already holds the key
    }
    return nil
}

func (w *worker) HandleMessage(from gen.PID, message any) error {
    switch message.(type) {
    case messageDone:
        grid.Unregister(w, "grid", "order/42")
    }
    return nil
}

Register and Unregister are synchronous (they route to the owning shard and return an error). Lookup and the counts read the node's local view directly, with no actor call:

// Registry (sync Call, returns error)
grid.Register(process, domain, key, meta)   // gen.ErrTaken if held by another live owner
grid.Unregister(process, domain, key)       // gen.ErrUnknown / gen.ErrIncorrect

// Reads (local, lock-free)
grid.Lookup(process, domain, key)           // (gen.PID, any, bool)
grid.RegistryCount(process, domain)         // int, converges to the cluster total
grid.LocalRegistryCount(process, domain)    // int, keys owned by this node
grid.LocalEntries(process, domain)          // []grid.Entry owned by this node
grid.Peers(process, domain)                 // ([]gen.Atom, error)

Re-registering the same key by its current owner with unchanged metadata is a no-op; with changed metadata it updates the entry and notifies monitors.

Monitoring

Subscribe to lifecycle changes of a key, a prefix, or the whole domain. Notifications arrive in HandleMessage:

func (o *observer) Init(args ...any) error {
    // matches "order/42" and "order/42/..." but not "order/420"
    return grid.MonitorPrefix(o, "grid", "order")
}

func (o *observer) HandleMessage(from gen.PID, message any) error {
    switch m := message.(type) {
    case grid.MessageRegistered:
        o.Log().Info("%s registered at %s", m.Key, m.Owner)
    case grid.MessageUpdated:
        o.Log().Info("%s meta changed: %v", m.Key, m.Meta)
    case grid.MessageUnregistered:
        o.Log().Info("%s gone: %s", m.Key, m.Reason)
    }
    return nil
}

On subscribe you first receive a MessageRegistered for every already-present matching key, then live changes. MessageUnregistered carries a Reason: ReasonUnregister, ReasonDown (owner terminated), ReasonConflict (owner lost a conflict), or ReasonNodeDown (owner's node was lost). Subscriptions survive a shard restart.

// Subscribe (notifications in HandleMessage)
grid.MonitorKey(process, domain, key)
grid.MonitorPrefix(process, domain, prefix)
grid.MonitorAll(process, domain)

// Cancel
grid.DemonitorKey(process, domain, key)
grid.DemonitorPrefix(process, domain, prefix)
grid.DemonitorAll(process, domain)
Groups

A group is per-key pub/sub. The key owner opens a group; other processes join to receive broadcasts. Dispatched payloads arrive in HandleEvent:

// owner side
func (w *worker) Init(args ...any) error {
    grid.Register(w, "grid", "room/42", nil)
    return grid.OpenGroup(w, "grid", "room/42")
}

func (w *worker) HandleMessage(from gen.PID, message any) error {
    return grid.Dispatch(w, "grid", "room/42", message) // to all members
}

// member side
func (m *member) HandleMessage(from gen.PID, message any) error {
    switch msg := message.(type) {
    case grid.MessageRegistered:
        grid.Join(m, msg.Domain, msg.Key) // returns the event; keep it for Leave
    }
    return nil
}

func (m *member) HandleEvent(message gen.MessageEvent) error {
    // dispatched payloads land here; gen.MessageDownEvent means the owner is gone
    return nil
}

Dispatch and MemberCount must run on the owner node. A group lives as long as its owner; when the owner terminates, members receive a gen.MessageDownEvent and re-Join once the key reappears.

grid.OpenGroup(process, domain, key)
grid.CloseGroup(process, domain, key)
grid.Join(process, domain, key)            // (gen.Event, error)
grid.Leave(process, event)                 // pass the event returned by Join
grid.Dispatch(process, domain, key, msg)   // owner node
grid.MemberCount(process, domain, key)     // (int, error), owner node

Options

Option Default Description
Domain "default" Peering scope. A node peers only with grids of the same domain; the application name is grid_<Domain>.
Shards 8 Keyspace shard count. All nodes in a domain must use the same value; a mismatch is rejected.
Separator "/" Key hierarchy separator for MonitorPrefix. A prefix matches at separator boundaries.
Peers none Static seed nodes for discovery when no registrar is available.

Conflict Resolution

Grid is AP: two nodes can register the same key at the same time. Grid resolves this last-writer-wins, ordered by registration time, then by owner PID (ID, then Creation), then by node name. The losing owner is stopped with ErrRegistryConflict so the cluster converges on a single owner. If your application requires at-most-one ownership with no window of divergence, grid's registry is a fast observation layer, not a lock - pair it with a linearizable authority.

Any non-primitive meta value, and any custom group payload, crosses the wire and must be EDF-registered by the consumer.

License

See LICENSE file in the repository root.

Documentation

Index

Constants

View Source
const (
	DefaultDomain    gen.Atom = "default"
	DefaultShards    int      = 8
	DefaultSeparator string   = "/"
)

Variables

View Source
var ErrRegistryConflict = errors.New("grid: registry conflict")

ErrRegistryConflict is the exit reason sent to a local owner that lost a registry conflict.

View Source
var Version = gen.Version{
	Name:    "Grid Application",
	Release: strings.TrimPrefix(strings.TrimSpace(version), "v"),
	License: gen.LicenseMIT,
}

Functions

func CloseGroup

func CloseGroup(process gen.Process, domain gen.Atom, key string) error

CloseGroup removes the group opened by OpenGroup.

func CreateApp

func CreateApp(options Options) gen.ApplicationBehavior

CreateApp creates the grid application: an AP eventually-consistent distributed in-memory store and registry.

func DemonitorAll

func DemonitorAll(process gen.Process, domain gen.Atom) error

DemonitorAll cancels a MonitorAll subscription.

func DemonitorKey

func DemonitorKey(process gen.Process, domain gen.Atom, key string) error

DemonitorKey cancels a MonitorKey subscription for key.

func DemonitorPrefix

func DemonitorPrefix(process gen.Process, domain gen.Atom, prefix string) error

DemonitorPrefix cancels a MonitorPrefix subscription for prefix.

func Dispatch

func Dispatch(process gen.Process, domain gen.Atom, key string, message any) error

Dispatch broadcasts message to all members of key's group. It must be called on the owner node, where the group is open.

func Join

func Join(process gen.Process, domain gen.Atom, key string) (gen.Event, error)

Join subscribes the calling process to key's group, which must already be open on the owner. Dispatched messages arrive in HandleEvent as gen.MessageEvent. It returns the joined event; pass it to Leave to unsubscribe. When the owner terminates, the subscription ends with a MessageDownEvent.

func Leave

func Leave(process gen.Process, event gen.Event) error

Leave unsubscribes the calling process from the group event returned by Join.

func LocalRegistryCount

func LocalRegistryCount(process gen.Process, domain gen.Atom) int

LocalRegistryCount returns the number of keys owned by the caller's node.

func Lookup

func Lookup(process gen.Process, domain gen.Atom, key string) (gen.PID, any, bool)

Lookup returns the owner and meta of key, or false if it is not registered.

func MemberCount

func MemberCount(process gen.Process, domain gen.Atom, key string) (int, error)

MemberCount returns the number of members of key's group. It must be called on the owner node.

func MonitorAll

func MonitorAll(process gen.Process, domain gen.Atom) error

MonitorAll subscribes to every key in the domain.

func MonitorKey

func MonitorKey(process gen.Process, domain gen.Atom, key string) error

MonitorKey subscribes the calling process to lifecycle events for the exact key. Events arrive as MessageRegistered/MessageUnregistered/MessageUpdated in HandleMessage. On subscribe it first receives MessageRegistered for the key if it is already present. A subscription is identified by its scope: cancel with DemonitorKey. Re-monitoring the same scope is a no-op.

func MonitorPrefix

func MonitorPrefix(process gen.Process, domain gen.Atom, prefix string) error

MonitorPrefix subscribes to every key at or below prefix, split on the domain Separator (default "/"): "a/b" matches "a/b" and "a/b/c" but not "a/bc".

func OpenGroup

func OpenGroup(process gen.Process, domain gen.Atom, key string) error

OpenGroup opens a group for key on the calling process, which should own key in the registry. Members can then Join and receive Dispatch. The group is removed by CloseGroup or automatically when the owner terminates.

func Peers

func Peers(process gen.Process, domain gen.Atom) ([]gen.Atom, error)

Peers returns the peer node names known to the local grid instance of the given domain. Empty domain resolves to DefaultDomain.

func Register

func Register(process gen.Process, domain gen.Atom, key string, meta any) error

Register registers key under the calling process, owned by its PID. The meta value crosses the wire on replication, so a non-primitive meta type must be EDF-registered by the consumer. Returns gen.ErrTaken if a live owner holds it.

func RegistryCount

func RegistryCount(process gen.Process, domain gen.Atom) int

RegistryCount returns the number of keys in the caller's local registry view, which converges to the cluster-wide count.

func Unregister

func Unregister(process gen.Process, domain gen.Atom, key string) error

Unregister removes key if the calling process owns it locally.

Types

type Entry

type Entry struct {
	Key   string
	Owner gen.PID
	Meta  any
}

Entry is a registry entry returned by LocalEntries.

func LocalEntries

func LocalEntries(process gen.Process, domain gen.Atom) []Entry

LocalEntries returns the registry entries owned by the caller's node.

type MessageRegistered

type MessageRegistered struct {
	Domain gen.Atom
	Key    string
	Owner  gen.PID
	Meta   any
}

MessageRegistered is delivered to a subscriber when a monitored key is registered.

type MessageUnregistered

type MessageUnregistered struct {
	Domain gen.Atom
	Key    string
	Owner  gen.PID
	Reason UnregisterReason
}

MessageUnregistered is delivered when a monitored key is unregistered. Reason says why (manual unregister, owner down, lost conflict, or peer loss).

type MessageUpdated

type MessageUpdated struct {
	Domain gen.Atom
	Key    string
	Owner  gen.PID
	Meta   any
}

MessageUpdated is delivered when a monitored key's meta changes under the same owner.

type Options

type Options struct {
	// Domain is the peering domain; a node peers only with grids of the same
	// Domain. The Ergo application name is "grid_<Domain>". Default: "default".
	Domain gen.Atom
	// Shards is the keyspace shard count; all nodes in a domain must agree.
	// Default: 8.
	Shards int
	// Separator is the key hierarchy separator used by MonitorPrefix: a prefix
	// matches the key itself and everything below it at a separator boundary, so
	// MonitorPrefix("a/b") matches "a/b" and "a/b/c" but not "a/bc". Default: "/".
	Separator string
	// Peers are optional static seed nodes for discovery without a registrar.
	Peers []gen.Atom
}

Options configures a grid application instance.

type UnregisterReason

type UnregisterReason uint8

UnregisterReason says why a key left the registry.

const (
	ReasonUnregister UnregisterReason = iota // the owner called Unregister
	ReasonDown                               // the owner process terminated
	ReasonConflict                           // the owner lost a registry conflict
	ReasonNodeDown                           // the owner's node/peer was lost
)

func (UnregisterReason) String

func (r UnregisterReason) String() string

Jump to

Keyboard shortcuts

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