fogsync

package
v0.47.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 18 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.

Documentation

Overview

Package fogsync synchronises the engine in the cloud with the engines on gateways: the cloud side (cloud.go), the gateway side (gateway.go) and the protocol between them (protocol.go).

The protocol connects the engine in the cloud and the engines on gateways (section 17). Both run the same engine, so the synchronisation replicates between equal data models with the same ids.

Transport: MQTT through mgw-device-cloud-connector, which bridges processes/{network}/cmd/# of the cloud broker to processes/cmd/# of the gateway broker and processes/state/# of the gateway broker to processes/{network}/state/# of the cloud broker. It delivers at most once, so reliability is part of the protocol:

  • Down, the cloud sends the desired state of resources: namespaces, deployments with their event descriptions, instances to run, stop or delete. Every resource has a version that grows with each change of its desired state, also after both sides forgot the resource: it starts at the time in milliseconds. The gateway applies a newer version idempotently and acknowledges every resource; the cloud sends again what stays unacknowledged (SYNC-01, SYNC-08). The order of messages does not matter. Applied deletions and the start of an instance the gateway reported as ended are forgotten, in the cloud at once, on the gateway once the instance is gone there.
  • Up, the gateway sends its change stream: batches of instance states after a position of the stream up to a position. The cloud takes a batch only if it continues the position it acknowledged last, and acknowledges after its commit; the gateway sends again from there (SYNC-02, SYNC-10). Changes of an instance within a batch are folded to its latest state (LONG-09, LONG-10); a gateway that cannot continue sends a snapshot. Retention and storage budget of the gateway keep an instance until the cloud took its end; an ended instance missing from a snapshot stays in the cloud.
  • The gateway reports its status when it starts and periodically: versions, positions, applied resources and storage (SYNC-11, SYNC-12, SYNC-13, LONG-14).

Every message carries the protocol version; the cloud writes to each gateway in the version of that gateway, see Version (SYNC-11).

Index

Constants

View Source
const (

	// down
	KindDesired = "desired"
	KindUpAck   = "ack"
	KindRequest = "request"
	// up
	KindStatus     = "status"
	KindChanges    = "changes"
	KindDesiredAck = "applied"
	// up, followed by the replica that asked: response/{replica}
	KindResponse = "response"
)
View Source
const (
	ResourceNamespace  = "namespace"
	ResourceDeployment = "deployment"
	ResourceInstance   = "instance"
)

Kinds of desired resources.

View Source
const (
	MethodDebugState       = "debug_state"
	MethodHistoryState     = "history_state"
	MethodListRuns         = "list_runs"
	MethodListActivities   = "list_activities"
	MethodListElementStats = "list_element_stats"
	MethodGetVariables     = "get_variables"
	MethodGetVariable      = "get_variable"
	MethodHistoryVariable  = "history_variable"
	// a stream of debug messages; the gateway ends it without renewal within WatchLease
	MethodWatch   = "watch"
	MethodUnwatch = "unwatch"
	// allows automatic restarts of a deployment again after a restart loop (INC-04); the
	// deployment is Args.Deployment, the request names no instance
	MethodResetRestarts = "reset_restarts"
)

Requests read the history and the state of an instance on its gateway, where it stays (DBG-15), or watch it live while the cloud renews the request (DBG-12); one resets the restart loop of a deployment there.

View Source
const GatewayCommandFilter = root + "cmd/" + path + "#"

GatewayCommandFilter subscribes the messages of the cloud on the broker of a gateway.

View Source
const Version = 1

Version of this protocol; a change of a message is a new version (SYNC-11).

A gateway takes only messages of its own version. The cloud serves gateways of its version and of the CloudSettings.ProtocolWindow versions before it, so that the cloud is updated first and the gateways after it: it stamps every message to a gateway with the version that gateway reported, and reads what gateways of the window send. A new version therefore has to

  • write the messages of each older version of the window in that version's format (encode) and read the messages of those versions (Cloud.Handle),
  • keep the topics and the envelope, which the version is read from before anything else,
  • keep a gateway of the new version from taking messages of an older cloud; it waits for the update of the cloud.
View Source
const WatchLease = time.Minute

WatchLease is how long a gateway streams after the last watch request.

Variables

This section is empty.

Functions

func CloudCommandTopic

func CloudCommandTopic(networkId string, kind string) string

CloudCommandTopic is where the cloud sends a message of a kind to a network.

func CloudResponseFilter

func CloudResponseFilter(replica string) string

CloudResponseFilter subscribes the answers to the requests of one replica, of every gateway; not shared, the replica waits for them itself.

func CloudStateFilter

func CloudStateFilter(group string) string

CloudStateFilter subscribes the messages of all gateways in the cloud; with a group, replicas share them (SYNC-10).

func Compatible

func Compatible(gatewayProtocol int, window int) bool

Compatible tells whether the cloud serves a gateway of a protocol version; the cloud supports its own version and window versions before it (SYNC-11).

func CompatibleWith

func CompatibleWith(own int, gatewayProtocol int, window int) bool

CompatibleWith tells whether a cloud of protocol version own serves a gateway.

func GatewayResponseTopic

func GatewayResponseTopic(replica string) string

GatewayResponseTopic is where a gateway answers a request of a replica.

func GatewayStateTopic

func GatewayStateTopic(kind string) string

GatewayStateTopic is where a gateway sends a message of a kind.

func KindOf

func KindOf(topic string) (network string, kind string, ok bool)

KindOf reads the kind of a message from its topic, on either side; network is empty on a gateway.

Types

type Applied

type Applied struct {
	Envelope
	Results []Result `json:"results"`
}

Applied acknowledges desired resources; Error says why one could not be applied (SYNC-13).

type Changes

type Changes struct {
	Envelope
	After            int64           `json:"after"`
	Upto             int64           `json:"upto"`
	Snapshot         bool            `json:"snapshot,omitempty"`
	Instances        []InstanceState `json:"instances,omitempty"`
	DeletedInstances []string        `json:"deleted_instances,omitempty"`
}

Changes is a batch of the change stream of a gateway. The cloud takes it only if After is the position it acknowledged last; a snapshot replaces everything the cloud holds of the network.

type Cloud

type Cloud struct {
	// contains filtered or unexported fields
}

Cloud is the side of the synchronisation that runs in the engine replicas of the cloud (SYNC-09, SYNC-10): it takes status and change stream of the gateways and sends them their desired state, see protocol.go. It replaces process-sync.

func NewCloud

func NewCloud(settings CloudSettings, s *store.Store, broker mqtt.Broker, logger *slog.Logger) *Cloud

func (*Cloud) Call

func (this *Cloud) Call(ctx context.Context, networkId string, method string, namespace string, instance string, args RequestArgs, result any) error

Call reads from a gateway: the state or history of an instance, which stay there (DBG-15). An offline gateway or one that does not answer in time is unavailable.

func (*Cloud) Cleanup

func (this *Cloud) Cleanup(ctx context.Context) error

Cleanup removes networks without contact for longer than the maximum age with their deployments and instances (SYNC-07).

func (*Cloud) Desire

func (this *Cloud) Desire(tx *store.Tx, networkId string, resource Resource) error

Desire sets the desired state of a resource of a gateway within the transaction of the change that causes it; the reconciler sends it (SYNC-01).

func (*Cloud) Handle

func (this *Cloud) Handle(ctx context.Context, topic string, payload []byte) error

Handle processes a message of a gateway; it returns an error only when the message should be delivered again, which a gateway does by itself anyway.

func (*Cloud) Overview

func (this *Cloud) Overview(ctx context.Context, ids []string, detailed bool) (result []model.Network, err error)

Overview reads the networks with the given ids, all if ids is nil; detailed adds the desired state per resource (SYNC-12, SYNC-13).

func (*Cloud) Reconcile

func (this *Cloud) Reconcile(ctx context.Context) error

Reconcile sends every desired version a gateway has not applied, once and then after the resend time, to networks in contact (SYNC-08).

func (*Cloud) RequestChanges added in v0.21.0

func (this *Cloud) RequestChanges(ctx context.Context, networkId string) error

RequestChanges tells a gateway the position of its change stream the cloud took, as the answer to a status does; a gateway behind it sends from there at once instead of after its next status, e.g. after an import set the position back (SNRGY-5066). A gateway the cloud has not heard from yet learns it with its first message.

func (*Cloud) SetClock

func (this *Cloud) SetClock(now func() time.Time)

SetClock replaces the clock, for tests.

func (*Cloud) SetProtocol

func (this *Cloud) SetProtocol(version int)

SetProtocol replaces the own protocol version, for tests of a change of the protocol.

func (*Cloud) Start

func (this *Cloud) Start(ctx context.Context) error

Start subscribes to the messages of all gateways and runs reconciler and cleanup.

func (*Cloud) Wake

func (this *Cloud) Wake()

Wake lets the reconciler send new desired state now, e.g. after a deployment.

func (*Cloud) Watch

func (this *Cloud) Watch(ctx context.Context, networkId string, namespace string, instance string, options model.WatchOptions) (<-chan model.DebugMessage, error)

Watch streams the debug messages of an instance of a gateway; the gateway streams only while the request is renewed, so the stream ends with ctx or a lost gateway (DBG-12).

type CloudSettings

type CloudSettings struct {
	EngineVersion string
	// the shared subscription of the replicas; empty subscribes without sharing
	Group string
	// a desired version without acknowledgement is sent again after this time (SYNC-08)
	ResendAfter time.Duration
	// a network without status since this time counts as offline and is not sent to
	OfflineAfter time.Duration
	// a network without contact since this time is removed with its resources (SYNC-07)
	CleanupMaxAge time.Duration
	// protocol versions before the own one the cloud still serves (SYNC-11)
	ProtocolWindow int
	// answers of gateways to the requests of this replica come to it alone
	ReplicaId string
	// how long a request waits for the gateway (DBG-15)
	CallTimeout time.Duration
}

func DefaultCloudSettings

func DefaultCloudSettings() CloudSettings

type DeploymentSpec

type DeploymentSpec struct {
	Deployment   model.Deployment         `json:"deployment"`
	Version      model.DeploymentVersion  `json:"version"`
	Descriptions []model.EventDescription `json:"descriptions,omitempty"`
	Groups       []string                 `json:"groups,omitempty"`
}

DeploymentSpec is a deployment with its current version, as in the cloud; the event descriptions are derived in the cloud and read the topics of the gateway (SYNC-06).

type Desired

type Desired struct {
	Envelope
	Resources []Resource `json:"resources"`
}

Desired carries desired resources from the cloud to a gateway.

type Envelope

type Envelope struct {
	Protocol int `json:"protocol"`
	// version of the sending engine
	Engine string    `json:"engine,omitempty"`
	SentAt time.Time `json:"sent_at"`
}

Envelope is part of every message.

type FaultyDeployment added in v0.25.0

type FaultyDeployment struct {
	Id    string    `json:"id"`
	Since time.Time `json:"since"`
}

FaultyDeployment is a deployment of a gateway marked faulty after a restart loop (INC-04).

type Gateway

type Gateway struct {
	// contains filtered or unexported fields
}

Gateway is the side of the synchronisation that runs in the engine on a gateway (SYNC-09): it applies the desired state of the cloud and sends the change stream of the gateway, see protocol.go. It replaces mgw-process-sync-client.

func NewGateway

func NewGateway(settings GatewaySettings, s *store.Store, e *engine.Engine, namespaces Namespaces, broker mqtt.Broker, logger *slog.Logger) *Gateway

func (*Gateway) Apply

func (this *Gateway) Apply(ctx context.Context, r Resource) Result

Apply applies a desired resource unless the same or a newer version was applied already; a failure is recorded with the version, so that the cloud shows it (SYNC-13).

func (*Gateway) ApplyAll

func (this *Gateway) ApplyAll(ctx context.Context, resources []Resource) []Result

ApplyAll applies desired resources in their order and returns a result for each; calls run one after the other, so a message applies only after the one before it is done.

func (*Gateway) Handle

func (this *Gateway) Handle(ctx context.Context, topic string, payload []byte) error

Handle processes a message of the cloud.

func (*Gateway) SendChanges

func (this *Gateway) SendChanges(ctx context.Context) error

SendChanges sends the next batch of the change stream after the acknowledged position, or sends the batch in flight again after the resend time.

func (*Gateway) SendStatus

func (this *Gateway) SendStatus(ctx context.Context) error

SendStatus reports versions, positions, applied resources, storage and the deployments in a restart loop (SYNC-12, LONG-14, SYNC-02).

func (*Gateway) SetClock

func (this *Gateway) SetClock(now func() time.Time)

SetClock replaces the clock, for tests.

func (*Gateway) SetLocal

func (this *Gateway) SetLocal(local Local)

SetLocal lets the cloud read instances of the gateway.

func (*Gateway) SetNetworkOwner added in v0.16.0

func (this *Gateway) SetNetworkOwner(source NetworkOwner)

SetNetworkOwner names where the owner of the network is read; nil keeps the owners the cloud sends (FOG-11).

func (*Gateway) SetProtocol

func (this *Gateway) SetProtocol(version int)

SetProtocol replaces the own protocol version, for tests of a change of the protocol.

func (*Gateway) Start

func (this *Gateway) Start(ctx context.Context) error

Start subscribes to the messages of the cloud and sends status and change stream until ctx is done.

func (*Gateway) TakeOverOwner added in v0.16.0

func (this *Gateway) TakeOverOwner(ctx context.Context) error

TakeOverOwner reads the owner of the network and gives it the deployments and instances on the gateway, also those it received before (FOG-11). Tick calls it every OwnerInterval.

func (*Gateway) Tick

func (this *Gateway) Tick(ctx context.Context) error

Tick sends the status when it is due and the next batch of the change stream.

type GatewaySettings

type GatewaySettings struct {
	EngineVersion string
	// a batch without acknowledgement is sent again after this time, then with backoff up to MaxResendAfter
	ResendAfter    time.Duration
	MaxResendAfter time.Duration
	StatusInterval time.Duration
	// instances per batch of the change stream
	BatchSize     int
	StorageBudget int64
	// how often the owner of the network is read (FOG-11)
	OwnerInterval time.Duration
}

func DefaultGatewaySettings

func DefaultGatewaySettings() GatewaySettings

type InstanceSpec

type InstanceSpec struct {
	DeploymentId string         `json:"deployment_id"`
	Owner        string         `json:"owner"`
	Variables    map[string]any `json:"variables,omitempty"`
	Stopped      bool           `json:"stopped,omitempty"`
}

InstanceSpec is an instance the gateway runs; a start is idempotent by the id (RUN-01). Stopped stops it, restarts after incidents are the gateway's own (FOG-07).

type InstanceState

type InstanceState struct {
	Instance  model.Instance   `json:"instance"`
	Incidents []model.Incident `json:"incidents,omitempty"`
}

InstanceState is the latest state of an instance with the incidents of its current run.

type Local

type Local interface {
	DebugState(ctx context.Context, token string, namespace string, id string, options model.DebugOptions) (model.DebugState, error)
	HistoryState(ctx context.Context, token string, namespace string, id string, options model.HistoryOptions) (model.DebugState, error)
	ListRuns(ctx context.Context, token string, namespace string, id string) ([]model.Run, error)
	ListActivities(ctx context.Context, token string, namespace string, id string, options model.ActivityListOptions) (model.ActivityPage, error)
	ListElementStats(ctx context.Context, token string, namespace string, id string, run int) ([]model.ElementStats, error)
	GetVariables(ctx context.Context, token string, namespace string, id string) ([]model.Variable, error)
	GetVariable(ctx context.Context, token string, namespace string, id string, name string, elementId string) (model.Variable, error)
	HistoryVariable(ctx context.Context, token string, namespace string, id string, name string, elementId string, options model.HistoryOptions) (model.HistoryVariable, error)
	Watch(ctx context.Context, token string, namespace string, id string, options model.WatchOptions) (<-chan model.DebugMessage, error)
	ResetRestarts(ctx context.Context, token string, namespace string, id string) (model.Deployment, error)
}

Local is the API of the gateway the cloud reads through requests: the history stays on the gateway (DBG-15), the live stream runs while the cloud renews it (DBG-12).

type Namespaces

type Namespaces interface {
	Get(name string) (model.Namespace, bool)
	Put(ctx context.Context, ns model.Namespace) (model.Namespace, bool, error)
}

Namespaces stores namespaces replicated from the cloud (NS-10).

type NetworkOwner added in v0.16.0

type NetworkOwner func(ctx context.Context) (string, error)

NetworkOwner reads the owner of the network of the gateway; empty while the gateway is not paired with a network (FOG-11).

func NetworkInfo added in v0.16.0

func NetworkInfo(url string) NetworkOwner

NetworkInfo reads user_id of the network from the cert-manager of the cloud proxy. It is the user its certificate names, whose token the cloud proxy sends with every request of the gateway, e.g. to the notifier (FOG-08).

type Request

type Request struct {
	Envelope
	Id        string `json:"id"`
	ReplyTo   string `json:"reply_to"`
	Method    string `json:"method"`
	Namespace string `json:"namespace"`
	Instance  string `json:"instance"`
	// method parameters: options of the method, a deployment, a variable name, element id or run
	Args RequestArgs `json:"args"`
}

Request asks a gateway; the answer goes to GatewayResponseTopic(ReplyTo).

type RequestArgs

type RequestArgs struct {
	Deployment string          `json:"deployment,omitempty"`
	Name       string          `json:"name,omitempty"`
	ElementId  string          `json:"element_id,omitempty"`
	Run        int             `json:"run,omitempty"`
	Options    json.RawMessage `json:"options,omitempty"`
}

type Resource

type Resource struct {
	Kind    string `json:"kind"`
	Id      string `json:"id"`
	Version int64  `json:"version"`
	Deleted bool   `json:"deleted,omitempty"`

	Namespace  *model.Namespace `json:"namespace,omitempty"`
	Deployment *DeploymentSpec  `json:"deployment,omitempty"`
	Instance   *InstanceSpec    `json:"instance,omitempty"`
}

Resource is the complete desired state of one resource; Deleted removes it.

type Response

type Response struct {
	Envelope
	RequestId string          `json:"request_id"`
	Result    json.RawMessage `json:"result,omitempty"`
	Error     *model.Error    `json:"error,omitempty"`
	Final     bool            `json:"final,omitempty"`
}

Response answers a request; a watch answers with one response per debug message and a final one when it ends.

type Result

type Result struct {
	Kind    string    `json:"kind"`
	Id      string    `json:"id"`
	Version int64     `json:"version"`
	Error   string    `json:"error,omitempty"`
	At      time.Time `json:"at"`
}

type Status

type Status struct {
	Envelope
	StartedAt time.Time `json:"started_at"`
	// the latest position of the change stream and the one the cloud acknowledged
	Latest int64 `json:"latest"`
	Acked  int64 `json:"acked"`
	// every resource the gateway applied, so that the cloud resends what is missing
	Applied []Result `json:"applied,omitempty"`
	Storage Storage  `json:"storage"`
	// the deployments the gateway stopped restarting after a restart loop (INC-04, SYNC-02);
	// a gateway that reports them sends an empty list when there are none, so that nil tells
	// an older gateway, whose marks the cloud then leaves as they are
	Faulty []FaultyDeployment `json:"faulty"`
}

Status of a gateway, at its start and periodically; it serves as sign of life (SYNC-12).

type Storage

type Storage struct {
	UsedBytes   int64            `json:"used_bytes"`
	BudgetBytes int64            `json:"budget_bytes"`
	Rows        map[string]int64 `json:"rows,omitempty"`
	// size per part: runtime, history, outbox and io, indexes included
	Bytes map[string]int64 `json:"bytes,omitempty"`
	// the instances with the most history entries
	Top []TopInstance `json:"top,omitempty"`
}

Storage of a gateway (LONG-14).

type TopInstance added in v0.29.0

type TopInstance struct {
	Id        string `json:"id"`
	Namespace string `json:"namespace"`
	Entries   int64  `json:"entries"`
}

TopInstance is an instance with many history entries (LONG-14).

type UpAck

type UpAck struct {
	Envelope
	Acked int64 `json:"acked"`
}

UpAck tells a gateway the position of its change stream the cloud has taken.

Jump to

Keyboard shortcuts

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