config

package
v0.18.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 32 Imported by: 0

README

config

The configuration the node's owner edits: node settings, the access policy, presets, adapter instances with their endpoint settings, where the node listens and the addresses of other nodes, the stable endpoint ids, the revocation records the node keeps, and the installed adapter packages. Read ../../../docs/references/configuration/README.md for the file formats, the reasons and what the tests prove.

This is a runtime package, layer 3 of internal/node/README.md: it imports txn and the contract packages, and of fsx only types, so it cannot obtain a writable file system. Every write is a step of a transaction declared here or in the package that composes it. It reads no clock.

Entry points

Name Purpose
Load(w) Reads and checks all of config/, then repairs the adapter directory. Returns a *Config, or a *FileError that names the file that is wrong.
Adapter.Fault Why an installed package could not be loaded (a *FileError); nil for a package that loaded.
Config accessors: Node, Policy, Presets, Instances, Network, EndpointIDs, EndpointSettings, Backup, Revocations, RevocationSet, Adapters, LastOperations Copies of the loaded state, manifests of Adapters included: nothing a caller changes reaches the configuration or another caller.
NodeSettings.ArchiveRetention() The retention of the archive as a duration: the one conversion of archive_retention_days.
NodeSettings.WireJSON(), EndpointOverride.WireJSON(), Preset.WireJSON() The settings and presets as the owner's commands show them: the compact object the file holds (under "settings", or the preset's own document), with the names node set, endpoint set and preset add take, so the names are written once.
ValidateListen, ValidatePeerAddress, ValidatePort, DefaultListen The one definition of what a listen address and an address entered for a peer may be, and of the port init is given. The file's decoder and every change of it use them; the management layer reuses them.
MaxPresets The most presets a node has; AddPreset refuses the one over it, and stored presets are not checked again (the reference says why the number is 20).
SetNodeSettings, AddPreset, RemovePreset, EnableAdapter, DisableAdapter, SetEndpointSettings, SetListen, SetPeerAddresses, RemovePeer The versioned changes. A Request names the operation by admin.RequestKey, which only admin.KeyFor should make, so the person and the id cannot be put together wrongly. Each checks the version the request names, validates, records the operation and its result in the file it changes, in the same replacement, and returns the new state. Refusals are *ChangeError with a typed ChangeReason.
RemoveInstance, Trash, DropTrash The removal of an instance moves the state directory the caller names aside in the same transaction (adapter-remove) and returns it as a Trash; DropTrash deletes it later, outside the loop (adapter-state-drop). A directory that cannot be moved refuses the removal with ChangeInstanceStateBusy.
RuntimeID, DirectID, PrepareBackup, PrepareRevocation, PlanInstall, PutEndpointIDs, PutBackup, PutRevocation, Install.Point Write functions for transactions of other packages. The prepare steps (RuntimeID and DirectID encode the ids they mint, PrepareBackup, PrepareRevocation and PlanInstall check and encode) run before Begin; the put steps take a *txn.Tx and the prepared value, write under an exported role, can fail only as a write of the transaction does, and return an AfterCommit that the caller calls once Commit returned nil.
StageAdapter, Unstage, PlanInstall, Install The installation of an adapter package: copy it next to the versions, drop it, plan the writes that make it current.
AdapterGCWork(r) The garbage of the adapter directory as a pure function of the disk: what the repair removes, and what a clean run must leave empty.
PlanInit(r, InitOptions), InitPlan The configuration side of init: what is missing, refusing an invalid file that exists. InitOptions.Port is the port network.json listens on (zero is DefaultListenPort).
Decode…/Encode of every file, DecodePreset, DecodeNodePatch, DecodeEndpointPatch The strict decoders and the canonical encoders; the management layer decodes what it receives with these and with nothing else.
InitWrites(), EndpointIDsWrite(), BackupWrite(), RevocationWrite(), InstallWrites(), InstallOldWrite() The writes this package contributes to the transactions its composers declare, in the order they are made; a composer builds its Decl from them, as from keys.InitWrites(), and adds its own writes around them.
Transactions(), the Role… constants, LayoutDirs(), the path helpers The static declarations, the roles other packages compose, and where things live.
Default… constants, DefaultNodeSettings() The values init writes.

Rules

  • Strict decoding, one rule for every file. Decoding goes through strictjson: a key matches exactly, a field without omitempty is required, null is no value, an explicit zero in an optional field is an error, unknown and repeated keys are errors. A file that fails refuses startup (an adapter package that fails faults only its adapter) and the error names the file and the JSON path of the value. Nothing is written when a file is refused, the repair of the adapter directory included.
  • Every file has format (1); versioned files also have version (from 1). node.json, policy.json, presets.json and instances.json have one version each, for the whole collection: a change of any member raises it by one. The files for which a request names no version (endpoint ids, the backup confirmation, the current pointer) carry only format.
  • A versioned change checks the version itself. The version a request names is compared with the current one by admin.CheckVersion, inside the change, before the content is looked at: a stale and invalid request is a conflict. The management layer does not check it separately, because the check and the write have to be one step. Whether the request was already answered is not decided here: the management layer runs admin.CheckReplay first, and calls a change only when it says to execute. The lookup runs against all stored results: each versioned file's last_operation (what LastOperations() returns) and the results kept under state/admin/, whose key spaces do not overlap, by admin.KeyFor(actor, id), in the same loop command as the change.
  • No file is written that its own decoder refuses. A versioned encoder refuses version 0 and an operation with a zero id, by the decoder's own check. A change whose request has a zero operation id, or that would raise the largest version past it, is refused with ChangeInvalid before anything is written: a file the next start refuses to read would leave the node unable to start.
  • The operation is recorded in the file it changed. last_operation holds the operation id, the person, the fingerprint and the result, written in the same replacement as the new version. The management layer builds the result through a ResultFunc, which sees the state the change produces; the shape of a result is its own.
  • Values are checked against the manifest when they are written. AddPreset, EnableAdapter (a new instance) and SetInstanceConfig check the values they carry with manifest.CheckValues against the manifest of the adapter, which must be installed and loadable; a failure is a ChangeInvalid at config.<key> (config.<adapter id>.<key> in a preset) or, for an adapter that cannot be checked against, ChangeAdapterNotInstalled. The loaders check only the shape, because a manifest may be unavailable at load and a bad package faults its adapter, never the node; values already stored are not checked again.
  • A value is stored compact, and an object in sorted key order. A map value written in two orders is the same bytes, so the file's version comparison and what the owner is shown do not depend on how it was typed.
  • A preset must state whether local sources may start a session with it. local_sources is "allow" or "deny", required, with no default. It decodes to authz.PresetLocalAccess, whose zero value is not a statement; no decoder returns a preset with the zero value.
  • Settings are judged by their owners. The queue time and backlog limit of an endpoint are checked with delivery, the node's concurrent prompt turns with handoff; the error a setting gets is the owner's, wrapped. The numbers of the defaults come from the same packages. Only what no other package decides is a number here (below).
  • A patch is merged, then validated whole, and applies whole. A setting is judged against the others it depends on, and one bad value changes nothing.
  • A name that begins with a dot is never configuration. Reading endpoint-ids/, revocations/ and adapters/ ignores every such name: the leftovers of interrupted operations (.tmp-, .trash-, which the cleanup at start removes) and the files an operating system or an editor puts into a directory (.DS_Store). Any other name in these three directories that is not what belongs there refuses startup and is named. Revocations and stable ids fail closed: a record that was not read would revive a retired identity, and an id file that was not read would give an endpoint a new address. The root of config/ and the package directories under adapters/ are not checked for extra files.
  • The disk reserve covers the queue and the logs. disk_reserve_bytes must be at least log_total_bytes plus OpenDeliveryDiskGrowth (4 KiB) times node_queue_limit, computed without overflow: below that, new work would be refused only after the disk was already full.
  • Memory follows the disk, after the commit. A change updates the in-memory configuration only after its transaction returned nil. A write function for another package's transaction returns an AfterCommit instead; an abandoned or failed transaction leaves memory as it was.
  • The settings of closed session endpoints go with the owner's next write of instances.json. An endpoint whose id is not a stable id of the instance and that is not open now is a closed session endpoint; its id is random and never used again. Stable ids (runtime and direct) are kept. A write that is given no knowledge of the open endpoints (nil) drops nothing.
  • A setting that is not given takes the node default. An endpoint's own settings name only what the owner set; EndpointSettings returns what applies.
  • Stable endpoint ids are minted once. DirectID returns the same id for the same key for ever; the id is written before the endpoint record exists, and an id without a record is not an endpoint.
  • Adapter packages are installed by a pointer. adapters/<id>/versions/<v>/ is immutable; adapters/<id>/current names the installed version, and replacing it is the commit point of an installation. A package is copied to versions/.stage-<hex> next to the versions (a rename needs one parent), the copy is what is parsed, and the manifest read from the source and from the copy must be of the same adapter and version. A name in a package that begins with .tmp-, .trash- or .stage- is refused: the cleanup would remove it.
  • A bad package faults its adapter, never the node. A pointer or manifest that cannot be loaded leaves the adapter in Adapters() with Fault set and no manifest; PlanInstall replaces it even with the digest its pointer holds, and the repair leaves it alone. Only an entry of adapters/ that is no adapter directory refuses startup.
  • No pointer means not installed, and never a reason to refuse startup. An adapter directory without current is an installation that did not finish; the repair removes it. So does it remove staging directories and version directories the pointer does not name. AdapterGCWork is that list and is the only definition of it.
  • An address is judged in one place. network.json holds multiaddrs, and what a listen address or a peer address may be is ValidateListen and ValidatePeerAddress: direct TCP or QUIC addresses with an ip or dns host, a fixed port, and for a peer an optional /p2p/<peer id>; no relay circuit. The decoder, the encoder and the changes call them, so a file and a request are refused for the same reasons. The package imports go-multiaddr and go-libp2p/core/peer for this and for nothing else.
  • init never overwrites. For each of the five files it writes, a missing one is written with the defaults, a valid one stays byte for byte, an invalid one makes the plan fail naming the file.
  • A directory missing from config/ refuses startup, naming it: it is the owner removing what init made.

Decided numbers

Setting Value Reason
node_queue_limit 10,000 unfinished deliveries Above what ordinary traffic queues in the default queue time, small enough that the disk reserve below covers it.
disk_reserve_bytes 256 MiB Covers the log total and 4 KiB for each of 10,000 deliveries (about 190 MiB) with room.
log_total_bytes 150 MiB Shared by the daemon and every adapter instance; the size at which each log rotates follows from it and from the number of instances.
archive_retention_days 30, at most 106,751 How long summaries stay; the archive is not counted in the reserve. The upper bound is the number of days a time.Duration holds: above it the conversion would wrap around to a negative or short retention and the archive would discard its summaries at once. Consumers read the retention only through ArchiveRetention().
OpenDeliveryDiskGrowth 4 KiB An unfinished delivery adds its archive summary and the feedback notification it may cause before it is archived.

The prompt turns and the endpoint defaults are not here: they are handoff.DefaultMaxConcurrentTurns, delivery.DefaultEndpointBacklogLimit and delivery.DefaultEndpointMaxQueue.

What the caller must guarantee

  • Build the transaction table once, from txn.Internal(), Transactions() and the composed declarations, and call Writer.Recover before Load.
  • Serialise the writes of one declaration (the single writer loop does). Config also serialises its versioned changes and PlanInstall, but a second writer would only wait.
  • Call a versioned change only after admin.CheckReplay has said to execute, run against all stored results (the operations LastOperations() returns and the results under state/admin/, by admin.KeyFor(actor, id)), in the same loop command as the change: the version check is inside config, the replay check is not, and a retry that came between the lookup and the change would run twice.
  • A transaction that spans owners is declared by the composing package, with the roles exported here, and writes config's files only through the functions here: direct-register and runtime-admit (RoleEndpointIDs), backup-confirm (RoleBackup), identity-retire (RoleRevocation), adapter-install (RoleVersion, RoleCurrent, RoleOld in this order, the current pointer being the commit point), init (RoleDir, RoleNode, RolePolicy, RolePresets, RoleInstances, RoleNetworkConfig).
  • Do every check and encoding a cross-owner transaction needs before Begin: RuntimeID or DirectID, PrepareBackup, PrepareRevocation and PlanInstall return the error of a value that cannot be written, while the put functions inside the transaction fail only as its writes do. An error found after the commit point would be fatal, and Tx.Close panics for a transaction closed there with no result.
  • Call the AfterCommit of a write function only after Commit returned nil.
  • Pass OpenEndpoints to every write of instances.json, with the set of endpoints that are open now.
  • For StageAdapter, pass a fsx.Reader rooted at the package directory, a reader of at least StageSuffixBytes bytes of randomness for the name of the staging directory, and check the platform in Staged.Manifest (adapterreg.RunsOn). A directory or file of the package that cannot be read is a *SourceError naming its path inside the package, and is not a failure of the node's own storage. The manifest and each copied file are read through ReadFileLimit, using the package's remaining MaxPackageBytes budget; overflow is refused as invalid without reading an oversized file whole. Reads follow symbolic links only when their targets are regular files: target bytes count against the budget, while directories, FIFOs and devices are unreadable sources. The manifest of the copy must be the bytes that were judged. StageAdapter and Unstage are called only by the single install worker, one at a time, and may run concurrently with the writer loop: they take no lock of Config and touch only staging directories that no change reads. Unstage therefore drops only the staging directory it is given, and the adapter directory when that held nothing else and the adapter is not installed; a version directory that was renamed in and never became current is left to the repair, since Unstage cannot tell it from one an installation committed meanwhile.
  • Run PlanInstall and the transaction it plans in the same loop command, so that nothing changes between the plan and its writes. Pass it the StillEnding that asks the adapter host whether a process of an instance is still ending (nil when nothing runs adapters), so that the files a disabled instance's process may still hold are not discarded; nothing is refused for it. The plan's Replaced tells the caller to restart the instances that run: another version, or the same version with other contents, is installed without refusing them. The package goes to a directory that does not exist yet (the first free revision of its version), so no installation discards a directory but the one of the package it replaces, and that one only when no process may hold it. A package is found at Adapter.Dir(), never at a path built from the version alone. Call Unstage when the result is AlreadyCurrent, when the installation is refused and when it failed with an error that is not fatal; after a fatal error the next start removes what is left.
  • Read the archive retention only through ArchiveRetention().
  • A Fatal error from a write means exit and rescan: memory was not changed, and the next start reads what is on disk.
  • Do not edit endpoint-ids/ by hand; edit the other files only while the node is stopped.

Where the tests are

The named tests are in load_test.go (an invalid file refuses startup, one row per kind of file and failure), preset_test.go (the statement about local sources), version_test.go (expected versions), writable_test.go (nothing is written that its decoder refuses), settings_test.go (settings delegate to their owners), crash_test.go (every transaction from every crash state, a crash during the repair, init crashing), clean_test.go (a clean run leaves no recovery work), network_test.go (the address rules, the file's bounds, its changes), init_test.go and golden_test.go. fuzz_test.go has one fuzz target for each decoder.

Documentation

Overview

Package config owns the configuration the node's owner edits: node settings, the access policy, presets, adapter instances with their endpoint settings, the stable endpoint identifiers, the revocation records the node keeps, and the installed adapter packages. See README.md for the rules and docs/references/configuration for the reasons.

Index

Constants

View Source
const (
	// RoleDir creates the directories of config/ (init).
	RoleDir = "dir"
	// RoleNode, RolePolicy, RolePresets and RoleInstances replace the file of
	// that name; RoleNetworkConfig replaces network.json (the role "network" is
	// the network key of keys, in the same transaction).
	RoleNode          = "node"
	RolePolicy        = "policy"
	RolePresets       = "presets"
	RoleInstances     = "instances"
	RoleNetworkConfig = "network-config"
	// RoleEndpointIDs replaces the endpoint-id file of one instance.
	RoleEndpointIDs = "ids"
	// RoleBackup replaces revocation-backup.json.
	RoleBackup = "backup"
	// RoleRevocation writes one revocation record.
	RoleRevocation = "revocation"
	// RoleVersion, RoleCurrent and RoleOld are the writes of an adapter
	// installation: rename the staging directory to the version, replace the
	// current pointer, discard the previous version.
	RoleVersion = "version"
	RoleCurrent = "current"
	RoleOld     = "old"
)

The roles of the writes this package offers to transactions of other packages. A transaction that spans owners is declared by the package that composes it, with these names, and every write function below writes only under the role it is documented with.

View Source
const (
	// DefaultListenPort is the port `init` makes the node listen on unless the
	// owner names another.
	DefaultListenPort = 7744
	// MaxAddressesPerNode is the most addresses one list holds: the listen
	// list, and the list of one peer. It is the limit of an address list in a
	// pairing record, so an address the book holds can be offered in one.
	MaxAddressesPerNode = pairing.MaxAddresses
	// MaxAddressLen is the longest address, in bytes, by the same reasoning.
	MaxAddressLen = pairing.MaxAddressLen
)
View Source
const (
	// DefaultNodeQueueLimit is how many unfinished deliveries the node holds.
	DefaultNodeQueueLimit = 10000
	// DefaultDiskReserveBytes is the free space below which new work is refused.
	DefaultDiskReserveBytes = 256 << 20
	// DefaultLogTotalBytes is the space all logs together may take.
	DefaultLogTotalBytes = 150 << 20
	// DefaultArchiveRetentionDays is how long the archive keeps its summaries.
	DefaultArchiveRetentionDays = 30
	// OpenDeliveryDiskGrowth is what an unfinished delivery adds to the disk
	// before it is finished and archived: its summary and the
	// feedback it may give rise to. The disk reserve must cover this for as many
	// deliveries as the queue holds, plus the logs.
	OpenDeliveryDiskGrowth = 4 << 10
	// MaxArchiveRetentionDays is the most days of retention a time.Duration can
	// hold. A larger number would wrap around to a negative or short retention
	// in ArchiveRetention, and the archive would then discard its summaries at
	// once. The limit is almost three centuries, which no owner needs.
	MaxArchiveRetentionDays = math.MaxInt64 / int64(24*time.Hour)
)

The settings that no other package decides. Each has its reason in the README: the numbers that another package owns are read from it, not repeated.

View Source
const (
	Dir            = "config"
	NodePath       = Dir + "/node.json"
	PolicyPath     = Dir + "/policy.json"
	PresetsPath    = Dir + "/presets.json"
	InstancesPath  = Dir + "/instances.json"
	NetworkPath    = Dir + "/network.json"
	EndpointIDsDir = Dir + "/endpoint-ids"
	BackupPath     = Dir + "/revocation-backup.json"
	RevocationsDir = Dir + "/revocations"
	AdaptersDir    = Dir + "/adapters"
)

The files of config/, relative to the data directory root.

View Source
const (
	DefaultPresetName = "default"
)

DefaultPresetName is the one preset `init` writes, and the description it carries.

View Source
const FormatVersion = 1

FormatVersion is the format of every file of config/. It is not the version a management request names: it is what a future change of the format reads to know what it migrates.

View Source
const MaxPackageBytes = 256 << 20

MaxPackageBytes is the most a package may hold in all, the sizes of its files added up. The whole package is read through a file system the owner points at, one file at a time into memory, so a package without a limit could take the node down by being large; no adapter is anywhere near it, so the limit is a refusal of a mistake (the wrong directory) and never of a package.

View Source
const MaxPresets = 20

MaxPresets is the most presets a node has. Every preset is told to a requester in the node's answer to endpoint.status, the answer is one signed record, and a record is read only up to record.DefaultMaxInput (64 KiB) bytes, so the presets together must fit in it whatever they say. The largest a preset can be in the answer, from the bounds of the adapter protocol (adapterproto.MaxPresetNameLen, MaxModelNameLen, MaxAllowedModels and the five efforts of the scale):

name 64 + default model 128 + default effort 6 ("medium")
+ 16 allowed models x (128 + the five efforts, 26)
+ the framing of the encoding                      = about 2.8 KB

so 23 presets nearly fill the record (64 KiB). Twenty makes the largest reply about 55 KB and leaves about 9.5 KB: room for the rest of the reply (the id of the signal, the conditions, the envelope of the record) and for a bound of the adapter protocol raised a little. TestTheLargestStatusReplyTheLimitOnPresetsAllowsFitsInOneSignedRecord builds that largest reply and fails when a raise of any of the bounds, or of this number, makes it too large to read. AddPreset refuses the preset that would be over the limit; the presets already stored are not checked again, so a node that holds more keeps working, and its status reply is refused when it cannot be read (see the control reply in the engine).

View Source
const StageSuffixBytes = 8

StageSuffixBytes is how much randomness StageAdapter reads from its reader to name a staging directory. A caller that may not let the staging read its own source of randomness (the engine draws only in its loop, and staging runs outside it) draws this many bytes first and hands them over.

Variables

View Source
var ErrDiskReserveTooLow = errors.New("disk reserve below what the node queue and the logs can fill")

ErrDiskReserveTooLow is wrapped by the error of a disk reserve that the unfinished deliveries and the logs could fill: new work would be refused only after the disk was already full.

View Source
var ErrOutOfRange = errors.New("value out of range")

ErrOutOfRange is wrapped by the error of a setting whose own rule is violated: the settings whose limits another package owns return that package's error instead.

Functions

func AdapterCurrentPath

func AdapterCurrentPath(id string) string

AdapterCurrentPath is the pointer file that names the installed version.

func AdapterDir

func AdapterDir(id string) string

AdapterDir is the directory of an adapter: its versions and its pointer.

func AdapterManifestPath

func AdapterManifestPath(id, version string) string

AdapterManifestPath is the manifest of the first package of one version.

func AdapterRevisionDir

func AdapterRevisionDir(id, version string, revision uint32) string

AdapterRevisionDir is the immutable package directory of one version at one revision. Revision 0 is the directory of the version itself; a package that is installed when that name is taken (the same version again with other contents, or a version that was replaced earlier and may still be run from) needs a directory of another name, so that the pointer's replacement is what switches packages and no directory is ever replaced in place. The "~" cannot be part of a version.

func AdapterStageDir

func AdapterStageDir(id, suffix string) string

AdapterStageDir is the staging directory of an installation, next to the versions so that it can be renamed into one.

func AdapterVersionDir

func AdapterVersionDir(id, version string) string

AdapterVersionDir is the immutable package directory of one version.

func AdapterVersionsDir

func AdapterVersionsDir(id string) string

AdapterVersionsDir holds the version directories and the staging directories.

func BackupWrite

func BackupWrite() txn.Write

BackupWrite is the write of PutBackup, in backup-confirm.

func DecodeRevocation

func DecodeRevocation(name string, data []byte) (revocation.Revocation, record.Record, error)

DecodeRevocation decodes the file of a revocation record, verifies it with the rules of the revocation package, and checks that the file is named after the record's digest. name is the name of the file in config/revocations. The error is a *FileError that names the file.

func DefaultListen

func DefaultListen(port int) ([]string, error)

DefaultListen is the listen list `init` writes for a port: TCP and QUIC on every IPv4 interface.

func EncodeAdapterCurrent

func EncodeAdapterCurrent(c AdapterCurrent) ([]byte, error)

EncodeAdapterCurrent returns the bytes of a current pointer.

func EndpointIDsPath

func EndpointIDsPath(instance string) string

EndpointIDsPath is the file of the stable endpoint ids of an instance.

func EndpointIDsWrite

func EndpointIDsWrite() txn.Write

EndpointIDsWrite is the write of PutEndpointIDs, in direct-register and runtime-admit. It is optional: an id that already exists is not written.

func InitWrites

func InitWrites() []txn.Write

InitWrites are the writes of init that belong to this package, in the order they are made: the directories, then the files that are not already valid. The writes of the other owners and the marker come after.

func InstallOldWrite

func InstallOldWrite() txn.Write

InstallOldWrite is the write of Install.DiscardOld, the last of adapter-install. It is optional: a first installation has no previous version.

func InstallWrites

func InstallWrites() []txn.Write

InstallWrites are the writes of adapter-install up to and including the current pointer, in the order of Install's methods: Promote is preparation (a crash before the pointer changes leaves a directory adapter-gc discards), and Point is the commit point. The composer's own write follows, then InstallOldWrite.

func LayoutDirs

func LayoutDirs() []string

LayoutDirs is the directories config/ consists of, each after its parent. `init` creates them and loading refuses a tree that lacks one.

func RevocationPath

func RevocationPath(d record.Digest) string

RevocationPath is the file of a revocation record.

func RevocationWrite

func RevocationWrite() txn.Write

RevocationWrite is the write of PutRevocation, in identity-retire.

func Transactions

func Transactions() []*txn.Decl

Transactions lists the transactions this package runs itself. The composition root puts them in the table of the program.

func ValidateListen

func ValidateListen(addr string) error

ValidateListen checks an address the node listens on: /<host>/tcp/<port> or /<host>/udp/<port>/quic-v1, with an ip4, ip6, dns, dns4 or dns6 host. It is the one definition of what a listen address may be.

func ValidatePeerAddress

func ValidatePeerAddress(addr string) error

ValidatePeerAddress checks an address entered for another node: the shapes of ValidateListen, and after them an optional /p2p/<peer id> that must be a libp2p peer identifier. A relay circuit is refused: relaying is not a way the owner can state, and a circuit address would name a third node.

func ValidatePort

func ValidatePort(port int) error

ValidatePort checks a port the node is told to listen on: a fixed one, so 0, which would ask the system for any, is refused.

Types

type Adapter

type Adapter struct {
	ID string
	// Version is the version the current pointer names; empty when the pointer
	// could not be read.
	Version string
	// Digest and Revision are those of the current pointer.
	Digest   string
	Revision uint32
	// Manifest is the manifest of the package; the zero value when Fault is set.
	Manifest manifest.Manifest
	// Fault says why the package on the disk could not be loaded: the pointer or the
	// manifest it names is missing, unreadable or invalid, or is of another adapter
	// or version. The adapter is still installed, so that an installation replaces
	// it, but nothing of it can run. A fault is the package's, never the node's: the
	// node loads and the other adapters run.
	Fault *FileError
}

Adapter is an installed adapter package.

func (Adapter) Dir

func (a Adapter) Dir() string

Dir is the directory of the package, relative to the data directory root.

type AdapterCurrent

type AdapterCurrent struct {
	Version string
	// Digest is the digest of the contents of the installed package in lower case
	// hex; empty for a package installed before the contents were told apart,
	// whose contents are then unknown.
	Digest string
	// Revision numbers the directories of one version: 0 is the directory named by
	// the version itself, and an installation takes the first revision whose
	// directory does not exist (see AdapterRevisionDir).
	Revision uint32
}

AdapterCurrent is what the current pointer of an adapter says: the installed version, the digest of the package's contents and the revision of the version whose directory holds it.

func DecodeAdapterCurrent

func DecodeAdapterCurrent(id string, data []byte) (AdapterCurrent, error)

DecodeAdapterCurrent decodes the current pointer of an adapter. The error is a *FileError that names the file.

type AfterCommit

type AfterCommit func()

AfterCommit is returned by a write function that runs inside a transaction of another package. The caller calls it after Commit returned nil, and not otherwise: only then does the in-memory configuration take the change over.

type Backup

type Backup struct {
	ConfirmedAt time.Time
	// Digest is the digest of the self-revocation that was confirmed.
	Digest record.Digest
}

Backup is the owner's confirmation that the self-revocation was kept offline.

func DecodeBackup

func DecodeBackup(data []byte) (Backup, error)

DecodeBackup decodes revocation-backup.json. The error is a *FileError that names the file.

func (Backup) Confirms

func (b Backup) Confirms(selfRevocation record.Digest) bool

Confirms reports whether the confirmation is for the given self-revocation: the confirmation of an earlier identity says nothing about this one.

func (Backup) Encode

func (b Backup) Encode() ([]byte, error)

Encode returns the bytes of revocation-backup.json.

type ChangeError

type ChangeError struct {
	Reason ChangeReason
	// Field names what the refusal is about. For ChangeInvalid it is the JSON
	// path of the offending value, or for a package being installed the path of
	// the offending file in it. For the reasons about a name it is that name: the
	// preset (ChangePresetExists, ChangePresetUnknown), the instance
	// (ChangeInstanceUnknown, ChangeInstanceExists, ChangeInstanceAdapterMismatch,
	// ChangeInstanceEnabled, ChangeInstanceInUse, ChangeInstanceStateBusy),
	// the adapter (ChangeAdapterNotInstalled), "instances.<name>" for
	// ChangeAdapterInUse and the endpoint id for ChangeEndpointUnknown and the node id for
	// ChangePeerUnknown. It is
	// empty for ChangeVersionConflict and ChangeNothingToChange.
	Field string
	// Current is the current version of the collection, for
	// ChangeVersionConflict.
	Current admin.Version
	Err     error
}

ChangeError is a refused change.

func (*ChangeError) Error

func (e *ChangeError) Error() string

func (*ChangeError) Unwrap

func (e *ChangeError) Unwrap() error

type ChangeReason

type ChangeReason uint8

ChangeReason says why a change of the configuration was refused.

const (
	// ChangeInvalid: a value is malformed or breaks a rule; Field names it.
	ChangeInvalid ChangeReason = iota + 1
	// ChangeVersionConflict: the version the request was based on is not the
	// current one; Current has the current one.
	ChangeVersionConflict
	// ChangePresetExists: a preset of this name exists.
	ChangePresetExists
	// ChangePresetUnknown: no preset of this name.
	ChangePresetUnknown
	// ChangeInstanceUnknown: no adapter instance of this name.
	ChangeInstanceUnknown
	// ChangeInstanceExists: enabling an existing instance with a configuration
	// would silently replace or ignore it.
	ChangeInstanceExists
	// ChangeInstanceAdapterMismatch: the existing instance belongs to another
	// adapter.
	ChangeInstanceAdapterMismatch
	// ChangeEndpointUnknown: the endpoint is neither a stable endpoint of the
	// instance nor open, so a setting for it could not be kept.
	ChangeEndpointUnknown
	// ChangeAdapterNotInstalled: the adapter has no installed package.
	ChangeAdapterNotInstalled
	// ChangeAdapterInUse: an adapter that an instance is using. No change returns
	// it now (a package is installed over an adapter whatever its instances do);
	// the reason stays because its wire code is part of the stable vocabulary.
	ChangeAdapterInUse
	// ChangeNothingToChange: a patch that names no setting.
	ChangeNothingToChange
	// ChangePeerUnknown: removing a node that has no address in the book.
	ChangePeerUnknown
	// ChangeInstanceEnabled: removing an instance that is still enabled.
	ChangeInstanceEnabled
	// ChangeInstanceInUse: removing an instance that session endpoints made through
	// it are still open on.
	ChangeInstanceInUse
	// ChangeInstanceStateBusy: removing an instance whose state directory could not
	// be moved aside, because something still holds a file in it (on Windows a
	// process that was not ended); Field names the instance and Err the path.
	ChangeInstanceStateBusy
)

The reasons a change is refused. Nothing is written for any of them.

func (ChangeReason) String

func (r ChangeReason) String() string

String names the reason.

type Config

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

Config is the configuration of the node as loaded, and the one writer of config/. Its values are read through the methods, which return copies; its writes go through the transactions of this package, and the in-memory configuration takes a change over only after the transaction that wrote it has committed.

func Load

func Load(w *txn.Writer) (*Config, error)

Load reads and checks all of config/ and then repairs the adapter directory.

A file that is missing where it must exist, cannot be read, is not a valid document of its kind or breaks a rule makes Load return a *FileError that names it, and nothing is written. The files are read in a fixed order, so with several wrong ones the owner is shown the first: the directories, then node.json, policy.json, presets.json, instances.json, network.json, the endpoint-id files by name, revocation-backup.json, the revocation records by name, and the adapters by id. Only when everything is valid does the repair run, which removes what an interrupted installation left among the adapters.

func (*Config) Adapters

func (c *Config) Adapters() []Adapter

Adapters returns the installed adapters, in the order of their ids. The manifests are copies: changing one changes nothing a later call returns.

func (*Config) AddPreset

func (c *Config) AddPreset(req Request, name string, preset []byte, result ResultFunc[Presets]) (Presets, error)

AddPreset adds a preset named name from its document. The document must make the statement about local sources; a name that is taken is refused. Each adapter's section is checked against the manifest of that adapter, which must be installed (see checkPresetConfig).

func (*Config) Backup

func (c *Config) Backup() (Backup, bool)

Backup returns the owner's confirmation of the offline backup, if there is one. Whether it holds for the node's current self-revocation is Backup.Confirms.

func (*Config) DirectID

func (c *Config) DirectID(instance, key string, rnd io.Reader) (IDChange, error)

DirectID returns the id of the direct endpoint an adapter registers under key. A key that is new gets an id minted from rnd. The same key always gives the same id, which is the promise the adapter protocol makes.

func (*Config) DisableAdapter

func (c *Config) DisableAdapter(req Request, instance string, open OpenEndpoints, result ResultFunc[Instances]) (Instances, error)

DisableAdapter disables the instance named instance. The instance stays, with its settings and its stable endpoint ids, so that enabling it again finds the same endpoints.

func (*Config) DropTrash added in v0.13.0

func (c *Config) DropTrash(t Trash) error

DropTrash deletes what a removal moved aside, and syncs the directory it was in. It is meant to run outside the loop that made the removal, after the removal has been answered, because the directory can be large. A failure is the caller's to log: the directory has a garbage name, and the next start removes it. The zero Trash is nothing to delete.

func (*Config) EnableAdapter

func (c *Config) EnableAdapter(req Request, instance, adapter string, instanceConfig []byte, open OpenEndpoints, result ResultFunc[Instances]) (Instances, error)

EnableAdapter enables the instance named instance of an installed adapter. A new instance is created, with instanceConfig as its configuration when that is given (a JSON object); an existing one is turned on, and keeps what the owner set. An existing instance of another adapter, and an existing instance together with a configuration, which would be silently ignored or replace the owner's, are refused. The configuration of a new instance is checked against the manifest of the adapter, so a new instance without one is refused when the adapter has a required field.

func (*Config) EndpointIDs

func (c *Config) EndpointIDs(instance string) EndpointIDs

EndpointIDs returns the stable endpoint ids of an instance: none for an instance that has none.

func (*Config) EndpointSettings

func (c *Config) EndpointSettings(instance string, id ident.EndpointID) EndpointSettings

EndpointSettings returns the settings that apply to an endpoint of an instance: what the owner gave it, and for what they did not, the node default.

func (*Config) Instances

func (c *Config) Instances() Instances

Instances returns instances.json.

func (*Config) LastOperations

func (c *Config) LastOperations() []Operation

LastOperations returns the operation recorded in each versioned file that has one: the results the management layer can still answer a repeated request from.

func (*Config) Network

func (c *Config) Network() Network

Network returns network.json.

func (*Config) Node

func (c *Config) Node() Node

Node returns node.json.

func (*Config) PlanInstall

func (c *Config) PlanInstall(s Staged, ending StillEnding) (Install, error)

PlanInstall plans the installation of a staged package.

The same version with the same contents (the digest the staging computed) is already installed and writes nothing. Any other package of the adapter, another version or the same version with other contents, replaces the installed one under a directory of its own, one that does not exist yet, the pointer's replacement being what switches to it; the processes of the adapter keep running the files they were started from, so no instance is refused, and the caller restarts the enabled ones. The directory they run from is not discarded while one may still hold it (an enabled instance, or a disabled one whose process is still ending; ending says so, and nil says none is): a running executable does not allow that on every platform, and the repair of the adapter directory removes it at the next start. No other directory of the adapter is discarded either, for the same reason.

func (*Config) Policy

func (c *Config) Policy() PolicyFile

Policy returns policy.json.

func (*Config) Presets

func (c *Config) Presets() Presets

Presets returns presets.json.

func (*Config) PutBackup

func (c *Config) PutBackup(tx *txn.Tx, p PreparedBackup) (AfterCommit, error)

PutBackup writes a prepared confirmation under RoleBackup, in a transaction of the composing package. The returned function is called after the transaction committed. It panics for a PreparedBackup that PrepareBackup did not return.

func (*Config) PutEndpointIDs

func (c *Config) PutEndpointIDs(tx *txn.Tx, ch IDChange) (AfterCommit, error)

PutEndpointIDs writes the ids of an instance with the id of ch in them, under RoleEndpointIDs, in a transaction of the composing package. The ids were encoded when RuntimeID or DirectID minted the id, before the transaction, so the write can only fail the way a write of the transaction does. For an id that already existed it writes nothing. The returned function makes the configuration in memory take the ids over; it is called after the transaction committed.

func (*Config) PutRevocation

func (c *Config) PutRevocation(tx *txn.Tx, p PreparedRevocation) (AfterCommit, error)

PutRevocation writes a prepared revocation under the name its digest gives, under RoleRevocation, in a transaction of the composing package. The returned function is called after the transaction committed. It panics for a PreparedRevocation that PrepareRevocation did not return.

func (*Config) RemoveInstance

func (c *Config) RemoveInstance(req Request, instance, stateDir string, sessions OpenSessions, open OpenEndpoints, result ResultFunc[Instances]) (Instances, Trash, error)

RemoveInstance removes the instance named instance from the configuration, with the settings it holds for endpoints. The instance has to be disabled, so that no process of it is meant to run, and no session endpoint made through it may be open: both are the owner's to undo first, and the refusal of the second says how many there are. The stable endpoint ids of the instance stay in endpoint-ids/, as they do when it is disabled: an instance later made under the same name finds the same endpoints. sessions may be nil, which says there are none.

stateDir, a path in the data directory, is the state directory of the instance: the adapter's own files, which belong to the instance and go with it. It is moved aside, to a garbage name in its own directory, in the transaction that removes the instance and before the file is replaced, which is O(1) whatever it holds, and the Trash returned names it for DropTrash to delete once the removal has been answered. A directory that is not there is nothing to move. When it cannot be moved (on Windows a file in it is still open) nothing is removed and the refusal is ChangeInstanceStateBusy, naming the path. An empty stateDir moves nothing.

func (*Config) RemovePeer

func (c *Config) RemovePeer(req Request, node ident.NodeID, result ResultFunc[Network]) (Network, error)

RemovePeer removes a node and its addresses from the book. A node that is not listed is refused with ChangePeerUnknown.

func (*Config) RemovePreset

func (c *Config) RemovePreset(req Request, name string, result ResultFunc[Presets]) (Presets, error)

RemovePreset removes the preset named name.

func (*Config) RevocationSet

func (c *Config) RevocationSet() *revocation.Set

RevocationSet returns the revocations as the set that the packages which judge read. The set is new on each call.

func (*Config) Revocations

func (c *Config) Revocations() []revocation.Revocation

Revocations returns the verified revocations the node keeps, in the order of their file names.

func (*Config) RuntimeID

func (c *Config) RuntimeID(instance string, rnd io.Reader) (IDChange, error)

RuntimeID returns the runtime endpoint id of an instance. An instance that has none gets one minted from rnd; the id is then written by PutEndpointIDs in the transaction that registers the endpoint.

func (*Config) SetEndpointSettings

func (c *Config) SetEndpointSettings(req Request, instance string, endpoint ident.EndpointID, patch []byte, open OpenEndpoints, result ResultFunc[Instances]) (Instances, error)

SetEndpointSettings changes the settings of one endpoint of an instance: the settings the patch names change and the others stay. The endpoint is a stable endpoint of the instance or one that is open now; a setting for any other would be dropped with the next write, so it is refused. Without knowledge of the open endpoints that is not judged.

func (*Config) SetInstanceConfig

func (c *Config) SetInstanceConfig(req Request, instance string, instanceConfig []byte, open OpenEndpoints, result ResultFunc[Instances]) (Instances, error)

SetInstanceConfig replaces the configuration of the instance named instance with instanceConfig, a JSON object read as `enable` reads one, so an empty object clears it. The instance stays as it is otherwise, enabled or not, with its endpoint settings and its stable endpoint ids. The values are checked against the manifest of the instance's adapter, whose package must load. The adapter reads the values when it starts, so a running instance takes them only when the caller restarts it.

func (*Config) SetListen

func (c *Config) SetListen(req Request, listen []string, result ResultFunc[Network]) (Network, error)

SetListen replaces the listen list. An empty list is valid: the node then does not listen.

func (*Config) SetNodeSettings

func (c *Config) SetNodeSettings(req Request, patch []byte, result ResultFunc[Node]) (Node, error)

SetNodeSettings changes the settings of the node named by patch, a JSON object of settings, atomically: with one value refused nothing changes. The patch is merged into the current settings and the result is validated whole, so a setting is judged against the others it depends on. The change is recorded in node.json with the operation and the result, in the same replacement.

func (*Config) SetPeerAddresses

func (c *Config) SetPeerAddresses(req Request, node ident.NodeID, addrs []string, result ResultFunc[Network]) (Network, error)

SetPeerAddresses replaces the addresses of a node, adding the node when it is not listed. At least one address is given: removing a node is RemovePeer.

func (*Config) StageAdapter

func (c *Config) StageAdapter(src fsx.Reader, rnd io.Reader) (Staged, error)

StageAdapter copies the package that src is rooted at into a staging directory next to the versions of its adapter, and checks that the manifest of the copy is, byte for byte, the one that was read and judged first. Nothing is installed: everything it writes is preparation that the repair of the adapter directory removes after a crash, and that Unstage removes when the installation is refused. A package that changes between the check and the copy is refused, so what the install runs is what was checked.

After preflight, the package is copied one entry at a time. Link targets are judged during the copy, and a failed copy cleans up what was written to the staging directory. A package over MaxPackageBytes is refused. rnd names the staging directory. The platform the manifest lists is the caller's to check on Staged.Manifest.

func (*Config) Unstage

func (c *Config) Unstage(s Staged) error

Unstage drops the staging directory of an installation that did not complete, and, when the adapter was never installed and nothing else is staged beside it, the directory of the adapter that the staging made. It touches nothing else: a version directory that was renamed in and did not become current, like one a crash left, is the repair's, because Unstage runs outside the writer loop and cannot tell such a directory from one that an installation committed meanwhile. What is not there is not an error, and with nothing to drop it writes nothing.

type EndpointIDs

type EndpointIDs struct {
	Runtime ident.EndpointID
	Direct  map[string]ident.EndpointID
}

EndpointIDs are the endpoint ids of one instance that must outlive the run-time state: the runtime endpoint and the direct endpoints by key.

func DecodeEndpointIDs

func DecodeEndpointIDs(instance string, data []byte) (EndpointIDs, error)

DecodeEndpointIDs decodes the endpoint-id file of an instance. The error is a *FileError that names the file.

func (EndpointIDs) Encode

func (e EndpointIDs) Encode() ([]byte, error)

Encode returns the bytes of an endpoint-id file.

type EndpointOverride

type EndpointOverride struct {
	MaxQueue     time.Duration
	BacklogLimit int
}

EndpointOverride is the settings an owner gave one endpoint. A zero field is not set: the node default applies.

func (EndpointOverride) Validate

func (o EndpointOverride) Validate() error

Validate checks the settings an owner gave one endpoint. A field that is not set is not checked: the node default applies.

func (EndpointOverride) WireJSON

func (o EndpointOverride) WireJSON() ([]byte, error)

WireJSON is what the owner gave one endpoint, as the owner's commands show it: the compact JSON object that names only the settings that are set, as `endpoint set` takes them, so that a setting left to the node default is not shown as if the owner had chosen its value.

type EndpointPatch

type EndpointPatch struct {
	MaxQueue     *time.Duration
	BacklogLimit *int
}

EndpointPatch names the endpoint settings a request changes; a nil field is not named.

func DecodeEndpointPatch

func DecodeEndpointPatch(data []byte) (EndpointPatch, error)

DecodeEndpointPatch decodes the settings object of an endpoints.set request.

type EndpointSettings

type EndpointSettings struct {
	// MaxQueue is the longest the endpoint keeps a message queued.
	MaxQueue time.Duration
	// BacklogLimit is how many messages the endpoint holds queued.
	BacklogLimit int
}

EndpointSettings are the settings of one endpoint that an owner can change.

func (EndpointSettings) Validate

func (s EndpointSettings) Validate() error

Validate checks the settings of an endpoint with the rules of the package that owns them: delivery decides what a queue time and a backlog limit may be.

type FieldError

type FieldError struct {
	// Field is the JSON path of the value.
	Field string
	// Malformed is true when the input is not a document of the expected shape
	// (see FileMalformed); false when a well formed value breaks a rule.
	Malformed bool
	Err       error
}

FieldError is a value of a document, or a setting, that is refused.

func (*FieldError) Error

func (e *FieldError) Error() string

func (*FieldError) Unwrap

func (e *FieldError) Unwrap() error

type FileError

type FileError struct {
	// Path is relative to the data directory root.
	Path   string
	Kind   FileKind
	Reason FileReason
	// Field is the JSON path of the offending value inside the file; empty when
	// the file as a whole is meant.
	Field string
	Err   error
}

FileError is what a refused file gives: the node does not start, and the message names the file, so the owner knows what to fix.

func (*FileError) Error

func (e *FileError) Error() string

func (*FileError) Unwrap

func (e *FileError) Unwrap() error

type FileKind

type FileKind uint8

FileKind says which kind of file or directory of config/ an error is about.

const (
	KindDir FileKind = iota + 1
	KindNode
	KindPolicy
	KindPresets
	KindInstances
	KindNetwork
	KindEndpointIDs
	KindBackup
	KindRevocation
	KindAdapterCurrent
	KindAdapterManifest
)

The kinds of file and directory the loader reads.

func (FileKind) String

func (k FileKind) String() string

String names the kind in words.

type FileReason

type FileReason uint8

FileReason says why a file was refused.

const (
	// FileMissing: a file or directory that must exist does not.
	FileMissing FileReason = iota + 1
	// FileUnreadable: the file exists and could not be read.
	FileUnreadable
	// FileMalformed: the content is not a document of the file's shape: not
	// JSON, an unknown, repeated, missing or null field, or a value of the
	// wrong type.
	FileMalformed
	// FileInvalid: the document is well formed and a value breaks a rule.
	FileInvalid
	// FileMisnamed: the name of the file does not match what it holds.
	FileMisnamed
)

The ways loading a file fails.

func (FileReason) String

func (r FileReason) String() string

String names the reason.

type GCItem

type GCItem struct {
	Path   string
	Reason GCReason
}

GCItem is one directory adapter-gc removes.

func AdapterGCWork

func AdapterGCWork(r fsx.Reader) ([]GCItem, error)

AdapterGCWork lists what the repair of the adapter directory removes: an adapter directory without a current pointer, and in an installed adapter a staging directory or a version directory the pointer does not name. It only reads, and it is the one definition of that garbage: the repair removes exactly this list (an adapter whose pointer cannot be read is left alone, for what to keep is not known), and a test evaluates it on a copy of the disk, where a run without a crash must leave it empty at every quiet point. The order is by adapter id and, within an adapter, by name.

type GCReason

type GCReason uint8

GCReason says why an adapter directory entry is garbage.

const (
	// GCNotInstalled: an adapter directory without a current pointer: an
	// installation that did not finish.
	GCNotInstalled GCReason = iota + 1
	// GCStaging: a staging directory.
	GCStaging
	// GCSuperseded: a version directory that the current pointer does not name.
	GCSuperseded
)

What adapter-gc removes.

func (GCReason) String

func (r GCReason) String() string

String names the reason.

type IDChange

type IDChange struct {
	Instance string
	ID       ident.EndpointID
	// New is true when the id was minted and has to be written.
	New bool
	// contains filtered or unexported fields
}

IDChange is an endpoint id that was looked up or minted for an instance, and the whole set of ids that holds it.

type InitOptions

type InitOptions struct {
	// Port is the port network.json makes the node listen on; zero is
	// DefaultListenPort.
	Port int
}

InitOptions are the choices of the owner that `init` writes into the files it makes.

type InitPlan

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

InitPlan is what `init` has to do on the side of config/. `init` never overwrites: for each of the five files it writes, a file that is missing is written with the defaults, one that exists and is valid stays as the owner left it, and one that exists and is not valid makes the plan fail, naming the file, so that the owner decides what becomes of it.

func PlanInit

func PlanInit(r fsx.Reader, opts InitOptions) (*InitPlan, error)

PlanInit checks what is on disk and decides what is missing. It only reads, so when it fails nothing has been written. A port that cannot be listened on is refused even when network.json exists and will be kept: the owner asked for something that cannot be done.

func (*InitPlan) MakeDirs

func (p *InitPlan) MakeDirs(tx *txn.Tx) error

MakeDirs creates the directories of config/ that are missing, each after its parent, under RoleDir. It is a part of the transaction of `init`, which the initialisation entry declares, with the other owners' directories made under the same role before the files.

func (*InitPlan) WriteFiles

func (p *InitPlan) WriteFiles(tx *txn.Tx) error

WriteFiles writes the files that are missing, in the order node, policy, presets, instances, network, each under its role.

type Install

type Install struct {
	// AlreadyCurrent is true when the staged package is the one that is current,
	// the same version with the same contents: there is nothing to write, and the
	// installation is already done.
	AlreadyCurrent bool
	// Replaced is true when the package replaces one that was installed: another
	// version, or the same version with other contents. A running process of the
	// adapter runs the package that was replaced until it is started again.
	Replaced bool
	// contains filtered or unexported fields
}

Install is the plan of the writes that make a staged package the current version of its adapter. The composing package runs them in its own transaction, in this order, with its own write between Point and DiscardOld: Promote, Point, DiscardOld. The commit point is the replacement of the current pointer. PlanInstall, before the transaction begins, does every check and encoding the writes need, so none of them can fail for a reason of its own.

func (Install) DiscardOld

func (i Install) DiscardOld(tx *txn.Tx) error

DiscardOld discards the package that was replaced, under RoleOld. It writes nothing for a first installation, and nothing when a process may still hold the package's files (see PlanInstall), which the repair removes at the next start.

func (Install) Point

func (i Install) Point(tx *txn.Tx) (AfterCommit, error)

Point replaces the current pointer, under RoleCurrent. This is the commit point of the installation. The returned function makes the configuration in memory take the version over; it is called after the transaction committed.

func (Install) Promote

func (i Install) Promote(tx *txn.Tx) error

Promote renames the staging directory to the version, under RoleVersion.

type Instance

type Instance struct {
	Adapter string
	Enabled bool
	// Config holds the values of the manifest's instance fields.
	Config map[string]json.RawMessage
	// Endpoints are the settings owners gave single endpoints.
	Endpoints map[ident.EndpointID]EndpointOverride
}

Instance is one adapter instance.

type Instances

type Instances struct {
	Version       admin.Version
	Items         map[string]Instance
	LastOperation *Operation
}

Instances is the content of instances.json.

func DecodeInstances

func DecodeInstances(data []byte) (Instances, error)

DecodeInstances decodes instances.json. The error is a *FileError that names the file.

func (Instances) Encode

func (i Instances) Encode() ([]byte, error)

Encode returns the bytes of instances.json.

type Network

type Network struct {
	Version admin.Version
	// Listen holds multiaddrs without a peer identifier. An empty list means the
	// node does not listen: it can still dial.
	Listen []string
	// Peers holds, per node, the multiaddrs it can be reached on, each with an
	// optional trailing /p2p/<peer id>. A node with no address is not listed.
	Peers         map[ident.NodeID][]string
	LastOperation *Operation
}

Network is the content of network.json: where the node listens, and the addresses the owner entered for other nodes. A node that is learned about later is not here: only what the owner decided is configuration.

func DecodeNetwork

func DecodeNetwork(data []byte) (Network, error)

DecodeNetwork decodes network.json. The error is a *FileError that names the file.

func (Network) Encode

func (n Network) Encode() ([]byte, error)

Encode returns the bytes of network.json, in canonical form: addresses as the multiaddr library writes them, repeats dropped, nodes sorted by id.

type Node

type Node struct {
	Version       admin.Version
	Settings      NodeSettings
	LastOperation *Operation
}

Node is the content of node.json.

func DecodeNode

func DecodeNode(data []byte) (Node, error)

DecodeNode decodes node.json. The error is a *FileError that names the file.

func (Node) Encode

func (n Node) Encode() ([]byte, error)

Encode returns the bytes of node.json.

type NodePatch

type NodePatch struct {
	// Name is the new name; a pointer to the empty string takes the name away.
	Name                 *string
	ReplyPermission      *bool
	NodeQueueLimit       *int
	DiskReserveBytes     *int64
	NodePromptTurns      *int
	ArchiveRetentionDays *int
	LogTotalBytes        *int64
	EndpointDefaults     *EndpointPatch
}

NodePatch names the node settings a request changes; a nil field is not named.

func DecodeNodePatch

func DecodeNodePatch(data []byte) (NodePatch, error)

DecodeNodePatch decodes the settings object of a node.set request.

type NodeSettings

type NodeSettings struct {
	// Name is what the owner calls the node, shown to people and agents beside
	// the node's identifier; empty means the node has no name of its own and is
	// called by its host name. It is a label: nothing is addressed, trusted or
	// allowed by it.
	Name string
	// ReplyPermission is whether a reply with evidence may reach an endpoint
	// that did not ask for it.
	ReplyPermission bool
	// NodeQueueLimit is how many unfinished deliveries the node holds.
	NodeQueueLimit int
	// DiskReserveBytes is the free space below which new work is refused.
	DiskReserveBytes int64
	// NodePromptTurns is how many turns started by prompts may run at once.
	NodePromptTurns int
	// ArchiveRetentionDays is how long the archive keeps what it summarises.
	ArchiveRetentionDays int
	// LogTotalBytes is the space all logs together may take.
	LogTotalBytes int64
	// EndpointDefaults apply to an endpoint without settings of its own.
	EndpointDefaults EndpointSettings
}

NodeSettings are the settings of the node.

func DefaultNodeSettings

func DefaultNodeSettings() NodeSettings

DefaultNodeSettings are the settings `init` writes. The limits another package decided come from that package.

func (NodeSettings) ArchiveRetention

func (s NodeSettings) ArchiveRetention() time.Duration

ArchiveRetention is how long the archive keeps its summaries, the one conversion of archive_retention_days to a duration. Validate refuses a number of days that the conversion would wrap around.

func (NodeSettings) Validate

func (s NodeSettings) Validate() error

Validate checks every setting: the ones that another package owns by asking it, the others by the ranges the README gives, and the disk reserve against what the queue and the logs can fill.

func (NodeSettings) WireJSON

func (s NodeSettings) WireJSON() ([]byte, error)

WireJSON is the settings as the owner's commands show them: the compact JSON object that node.json holds under "settings", whose names `node set` takes patches by. It is the one place the names of the settings are written for anything but the file, so that what a command shows is what the file says.

type OpenEndpoints

type OpenEndpoints func(ident.EndpointID) bool

OpenEndpoints says whether an endpoint is open now. The session endpoints that are closed are the ones whose settings a write of instances.json drops. A nil value drops nothing.

type OpenSessions

type OpenSessions func(instance string) int

OpenSessions says how many session endpoints made through the instance are still open. Config does not hold endpoints, so the caller that does tells it.

type Operation

type Operation struct {
	ID admin.OperationID
	// Person is who sent the request; the zero value is the local owner.
	Person      ident.PersonID
	Fingerprint admin.Fingerprint
	// Result is one compact JSON object.
	Result json.RawMessage
}

Operation is the management operation that produced the current version of a file, with its result. It is stored in the file it changed, in the same replacement as the change, so the effect and its result cannot be told apart by a crash. A file the owner edited by hand has none.

func (Operation) Key

func (o Operation) Key() admin.RequestKey

Key is the key under which the management layer files the operation's result.

type PolicyFile

type PolicyFile struct {
	Version       admin.Version
	Policy        authz.Policy
	LastOperation *Operation
}

PolicyFile is the content of policy.json.

func DecodePolicy

func DecodePolicy(data []byte) (PolicyFile, error)

DecodePolicy decodes policy.json: the rules, each as authz reads it. The error is a *FileError that names the file.

func (PolicyFile) Encode

func (p PolicyFile) Encode() ([]byte, error)

Encode returns the bytes of policy.json.

type PreparedBackup

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

PreparedBackup is the owner's confirmation of the offline backup, checked and encoded for a transaction of the composing package. PrepareBackup runs before that transaction begins, so a confirmation that cannot be written is an error that touches nothing, and PutBackup can only fail the way a write of the transaction does.

func PrepareBackup

func PrepareBackup(b Backup) (PreparedBackup, error)

PrepareBackup checks and encodes a confirmation. It does no I/O.

type PreparedRevocation

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

PreparedRevocation is a verified revocation record, with its file, for a transaction of the composing package. PrepareRevocation runs before that transaction begins, so a record that does not verify is an error that touches nothing, and PutRevocation can only fail the way a write of the transaction does.

func PrepareRevocation

func PrepareRevocation(rec record.Record) (PreparedRevocation, error)

PrepareRevocation verifies a revocation record and encodes its file, the record's own wire bytes. It does no I/O.

type Preset

type Preset struct {
	// LocalSources is the preset's statement about local sources. It has no
	// default: a preset without one is not valid.
	LocalSources authz.PresetLocalAccess
	Description  string
	// Config holds, per adapter id, the values of the manifest's preset fields.
	// Only the shape is checked here; the manifest decides what is valid.
	Config map[string]map[string]json.RawMessage
}

Preset is one preset: what local sources may do with it, and the values it gives the adapters.

func DecodePreset

func DecodePreset(data []byte) (Preset, error)

DecodePreset decodes one preset document, as presets.add carries it. The statement about local sources is required and has no default: a document without it, or with a value that is not exactly "allow" or "deny", is refused, and the result never holds the zero statement. The error is a *FieldError.

func (Preset) WireJSON

func (p Preset) WireJSON() ([]byte, error)

WireJSON is the preset as the owner's commands show it and as presets.add takes it: the compact JSON object that presets.json holds under the preset's name. It is the one place the names of a preset's members are written for anything but the file, so that what a command shows is what the file says.

type Presets

type Presets struct {
	Version       admin.Version
	Items         map[string]Preset
	LastOperation *Operation
}

Presets is the content of presets.json.

func DecodePresets

func DecodePresets(data []byte) (Presets, error)

DecodePresets decodes presets.json. The error is a *FileError that names the file.

func (Presets) Encode

func (p Presets) Encode() ([]byte, error)

Encode returns the bytes of presets.json.

type Request

type Request struct {
	// Key is the key the request's results are filed under, as admin.KeyFor
	// makes it from the actor and the operation id. The change records its
	// person and id in last_operation, so the replay lookup finds them under the
	// same key.
	Key         admin.RequestKey
	Fingerprint admin.Fingerprint
	// Expected is the version of the collection the sender last saw.
	Expected admin.Version
}

Request is what a versioned change takes from the management layer: which request it is, and the version it was based on.

type ResultFunc

type ResultFunc[T any] func(after T) (json.RawMessage, error)

ResultFunc builds the result that is stored with a change, from the state the change produced. The management layer owns the shape of a result; the version is known only once the change is made, so it is built here.

type SourceError

type SourceError struct {
	Path string
	Err  error
}

SourceError is a package that cannot be read: Path is the directory or file inside the package whose reading failed, relative to the package, "." for the package itself. The package is not what it should be, and the owner who named it can fix it; that is no failure of this node's own storage.

func (*SourceError) Error

func (e *SourceError) Error() string

func (*SourceError) Unwrap

func (e *SourceError) Unwrap() error

type Staged

type Staged struct {
	ID      string
	Version string
	// Digest is the digest of the contents of the copy in lower case hex: every
	// directory and file by relative path, and every file's bytes.
	Digest   string
	Dir      string
	Manifest manifest.Manifest
}

Staged is a package copied into a staging directory next to the versions, parsed there, and not installed yet.

type StillEnding

type StillEnding func(instance string) bool

StillEnding says whether a process of the instance is still being ended. Config does not run adapters, so the caller that does tells it.

type Trash added in v0.13.0

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

Trash is a directory that a removal moved aside and that DropTrash deletes. The zero value is nothing to delete. Only RemoveInstance makes one, so DropTrash can delete nothing else.

Jump to

Keyboard shortcuts

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