cluster

package
v0.0.0-...-79b1474 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 33 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package cluster is the home side of multi-instance Maktaba (Epic 31, specs/epics/31-multi-instance/design.md): the join cryptography (§3.2), the instance identity and machine registry store (§4) and the database role provisioning for joined machines (§3.3).

Index

Constants

View Source
const (
	// AccessNotApproved: the machine is not an approved member (pending, revoked).
	AccessNotApproved = "not_approved"
	// AccessUnknown: the home does not know the machine (removed, or never joined).
	AccessUnknown = "unknown"
	// AccessCannotCreate: the home's database user may not create roles, and the home
	// could not mend it (not its own bundled Postgres, or the mending failed).
	AccessCannotCreate = "cannot_create_roles"
	// AccessNoGroup: the machines' group role is missing and could not be made again.
	AccessNoGroup = "no_worker_group"
	// AccessNoAdmin: the home's database user may not change the machine's role (Postgres
	// 16: a role it does not administer, as one the superuser made in a restore), and the
	// home could not mend it.
	AccessNoAdmin = "cannot_alter_role"
	// AccessTerm: the cluster's term could not be read.
	AccessTerm = "term"
	// AccessCA: the bundled database's CA could not be read.
	AccessCA = "database_ca"
	// AccessRateLimited: the machine asked again too soon.
	AccessRateLimited = "rate_limited"
	// AccessNotTaken: the machine refused the access it was given (its answer in the
	// reason: a home of an earlier term, a switch under way).
	AccessNotTaken = "not_taken"
	// AccessNotMendable: a re-made access would not mend the machine's login (TLS at the
	// right address: its certificate, the home's), so none is made: a new password would
	// only be one its roles no longer have.
	AccessNotMendable = "not_mendable"
	// AccessOther: anything else (the database's error in the reason).
	AccessOther = "other"
)

Why the home cannot give a machine a new login to its database (a re-made access: the home's push, or the machine's own request): the code the machine logs and the Machines page shows it by, with the reason in words.

View Source
const (
	ReasonSQLite       = "joining machines needs a Postgres home (this home runs on SQLite)"
	ReasonCannotCreate = "the database user cannot create roles"
	ReasonNoGroup      = "the maktaba_worker role is missing (run the migrations as a user that may create roles)"
	// ReasonCheckFailed starts the reason when the privileges could not be read (the
	// database's error follows it).
	ReasonCheckFailed = "cannot check the database user's privileges: "
)

Reasons the home cannot take machines.

View Source
const (
	StatePending  = "pending"
	StateApproved = "approved"
	StateRejected = "rejected"
	StateRevoked  = "revoked"
)

Node states as stored (cluster_nodes.state).

View Source
const (
	PathMapInferred = "inferred"
	PathMapAdmin    = "admin"
)

Path map sources (cluster_nodes.path_map_source).

View Source
const BeatEvery = 5 * time.Second

BeatEvery is how often the home writes its beat while a machine follows it.

View Source
const KeySize = 32

KeySize is the size of an X25519 key (private or public), in bytes.

View Source
const PayloadVersion = 1

PayloadVersion is the sealed payload's "v".

View Source
const ReplicaGroup = "maktaba_replicas"

ReplicaGroup is the group role every machine's replication role joins (slot 0147).

View Source
const WorkerGroup = "maktaba_worker"

WorkerGroup is the group role every machine role joins (slot 0103).

Variables

View Source
var CanonActions = map[string]bool{"run": true, "revert": true, "resume": true}

CanonActions are the requests an admin may make: check now, undo the last conversion (automatic conversion then holds), convert automatically again.

View Source
var ErrAlreadyMember = errors.New("cluster: node is already a member")

ErrAlreadyMember: the node id is approved or revoked.

View Source
var ErrBadAction = errors.New("cluster: action is run, revert or resume")

ErrBadAction is returned for an action not in CanonActions.

View Source
var ErrBadServer = errors.New("cluster: a server name is lower case, without '/'")

ErrBadServer is returned for an invalid server name.

View Source
var ErrNotFound = errors.New("cluster: not found")

ErrNotFound is returned for a missing node.

View Source
var ErrUnknownStage = errors.New("cluster: unknown stage")

ErrUnknownStage is returned by SetStages for a stage not in job_stages.

Functions

func AccessCode

func AccessCode(err error) string

AccessCode is err's access code (AccessOther for an error without one).

func ComputerName

func ComputerName() string

ComputerName is the machine's name for people: on macOS the computer name (`scutil --get ComputerName`, "Sara's Mac mini"), elsewhere the host name; in a container (whose host name is its id) or when neither is known, "Maktaba".

func CopyNames

func CopyNames(role string) (copyRole, slot string, ok bool)

CopyNames are a machine's replication role and slot, from its database role (false: not a machine role).

func DatabaseURL

func DatabaseURL(role, password, host string, port int, dbName string) string

DatabaseURL builds the machine's connection string: its own role and password, the host the machine used to reach the API, the given port and the home's database name, sslmode=prefer.

func DecodeKey

func DecodeKey(s string) ([]byte, error)

DecodeKey parses a standard-base64 32-byte key.

func EncodeKey

func EncodeKey(b []byte) string

EncodeKey is standard base64.

func EnsureWorkerGroup

func EnsureWorkerGroup(ctx context.Context, db *sql.DB) error

EnsureWorkerGroup makes the machines' group role again when the home's database lacks it, with every privilege the migrations gave it (db: the home's own user, which may create roles: a bundled Postgres's after its grants were mended). A group that exists is left as it is.

func GenerateKey

func GenerateKey() (priv, pub []byte, err error)

GenerateKey returns a fresh X25519 keypair (private, public).

func MarshalPayload

func MarshalPayload(p Payload) ([]byte, error)

MarshalPayload encodes p as compact JSON without HTML escaping (the Python side's json.dumps(sort_keys=True, separators=(",", ":")) form).

func NewPassword

func NewPassword() (string, error)

NewPassword is 32 random bytes, base64url without padding.

func Open

func Open(key []byte, nodeID string, env Envelope) ([]byte, error)

Open decrypts an envelope sealed by Seal.

func PublicKey

func PublicKey(priv []byte) ([]byte, error)

PublicKey derives the X25519 public key of priv.

func RoleName

func RoleName(nodeID string) string

RoleName is the machine's database role: maktaba_node_<the id's 32 hex digits>. The whole id, never a prefix: the machine chooses its id, and a shared prefix would hand a second machine the first one's role.

func SAS

func SAS(shared, nodePub, homePub []byte) (string, error)

SAS is the 6-digit pairing code both sides show / expect: HKDF-SHA256(shared, salt=node_pub||home_pub, info="maktaba-join-sas", L=4) as a big-endian integer modulo 1 000 000, zero-padded.

func ScramVerifier

func ScramVerifier(password string) (string, error)

ScramVerifier is Postgres's SCRAM-SHA-256 verifier of password (RFC 5802 / 7677: a random salt, 4096 iterations), as Postgres stores it for a role: a role made or changed with it checks the password at sign-in, and no statement, log or pg_stat_activity ever carries the password itself (nodecopy.scramVerifier makes the copies' the same way).

func SealKey

func SealKey(shared, nodePub, homePub []byte) ([]byte, error)

SealKey is the ChaCha20-Poly1305 key: HKDF-SHA256(shared, salt=node_pub||home_pub, info="maktaba-join-seal", L=32).

func SetStagesTx

func SetStagesTx(ctx context.Context, tx *sql.Tx, id string, stages map[string]*bool) error

SetStagesTx is SetStages inside the caller's transaction (Epic 51 story 51.12: a machine's component override writes its stage switches with it). The caller commits.

func SharedSecret

func SharedSecret(ownPriv, peerPub []byte) ([]byte, error)

SharedSecret is X25519(own private, peer public). It fails on a low-order peer key (an all-zero result).

func StableHostName

func StableHostName() string

StableHostName is the machine's stable host name: on macOS the Bonjour LocalHostName (`scutil --get LocalHostName`, which does not change with the network the way `hostname` can), elsewhere os.Hostname. The domain part and a trailing ".local" are dropped.

func ValidRole

func ValidRole(role string) bool

ValidRole reports whether role is a machine role name.

Types

type AccessError

type AccessError struct {
	Code   string
	Reason string
}

AccessError is a re-made access the home could not give, with its code.

func (*AccessError) Error

func (e *AccessError) Error() string

type Advertiser

type Advertiser struct {
	Publisher discovery.Publisher
	Port      int
	Version   string
	SchemaRev int
	// Path is the web base path ("" or "/": none is announced).
	Path string
	// TLS: the home's web address is https (TXT tls=1, else tls=0).
	TLS bool
}

Advertiser announces the home on the LAN (design §2). It carries no library or user name: only the instance name, its id, the API version, the schema revision and whether joins are open.

The apps' home picker (Epic 42 story 42.2) reads `home` (the home's instance id, the same as GET /api/discovery/home's `id`; `id` is the announcing machine's own, here the same), `name` (its display name), `path` (the web base path, only when it is not "/") and `tls` (1 or 0); they dedupe by `home`, then `id`, then host:port.

func (*Advertiser) Announce

func (a *Advertiser) Announce(ctx context.Context, id Identity) error

Announce (re-)publishes the home. A nil Advertiser is a no-op.

func (*Advertiser) Service

func (a *Advertiser) Service(id Identity) discovery.Service

Service builds the announcement for id.

type CanonStatus

type CanonStatus struct {
	State       json.RawMessage `json:"state"`
	Request     *string         `json:"request"`
	RequestedAt *time.Time      `json:"requested_at"`
	RequestedBy *string         `json:"requested_by"`
}

CanonStatus is the storage_canonicalize row (story 31.3, automatic).

type Copies

type Copies struct {
	DB *sql.DB
	// CAFile is the database's TLS CA (MAKTABA_CLUSTER_PG_CA; "": none).
	CAFile string
	// KeepGB returns the cap (0: none).
	KeepGB func() int
	// OperatorPG reads rules.cluster.copies_on_operator_postgres: on a database that is not
	// Maktaba's own Postgres the machines keep copies only while it is on (nil: off). An
	// error leaves things as they are for that beat: no copy is ended for a rule not read.
	OperatorPG func(ctx context.Context) (bool, error)
	// Bundled: the database is Maktaba's own Postgres (no physical slot there is anyone's).
	Bundled bool
	Logger  *slog.Logger
	// contains filtered or unexported fields
}

Copies is the home's side of its machines' copies of its database (specs/epics/37-node-replica): while a machine follows it, it writes its clock into cluster_replica_beat every BeatEvery (a copy then knows how far it has applied the home's changes); it publishes its database's TLS CA there (a machine pins it for its replication); it gives up on a machine so far behind that what the home keeps for it passes the cap (rules.cluster.replica_wal_keep_gb): that slot is dropped, and the machine copies the database anew when it is back; and every beat it drops the slots that are not Maktaba's (guardSlots). A database that is not Maktaba's own Postgres (an operator's) may have output plugins other than pgoutput, which the sweep alone guards against: the machines keep no copy of it unless the admin allows it (rules.cluster.copies_on_operator_postgres): until then they may not ask for one (holdDoor), and the copies they have end (endCopies).

func (*Copies) Run

func (c *Copies) Run(ctx context.Context)

Run writes the beat, publishes the CA and holds the cap until ctx ends.

type Envelope

type Envelope struct {
	Nonce      string `json:"nonce"`
	Ciphertext string `json:"ciphertext"`
}

Envelope is a sealed payload on the wire: standard base64 of the 12-byte nonce and of the ciphertext (which carries the 16-byte Poly1305 tag).

func Seal

func Seal(key []byte, nodeID string, plaintext []byte) (Envelope, error)

Seal encrypts plaintext with key, AAD = nodeID (its canonical lowercase uuid), under a random nonce.

func SealWithNonce

func SealWithNonce(key []byte, nodeID string, nonce, plaintext []byte) (Envelope, error)

SealWithNonce is Seal with a caller-chosen nonce (test vectors only).

type Identity

type Identity struct {
	InstanceID       string
	Name             string
	AcceptJoins      bool
	AcceptJoinsUntil *time.Time
	CreatedAt        time.Time
	UpdatedAt        time.Time
}

Identity is the instance_identity singleton.

func (Identity) Short

func (i Identity) Short() string

Short is the first 8 hex digits of the instance id (the mDNS "id").

type MemoryStorage

type MemoryStorage struct {
	Storage json.RawMessage
	PathMap json.RawMessage
	// Canon is the automatic conversion's row (nil: none yet).
	Canon *CanonStatus
	// Access is LibraryAccess's answer.
	Access []RootAccess
	// contains filtered or unexported fields
}

MemoryStorage is the in-memory StorageStore (SQLite homes, tests).

func (*MemoryStorage) Canonicalize

func (m *MemoryStorage) Canonicalize(context.Context) (*CanonStatus, error)

func (*MemoryStorage) DeleteServer

func (m *MemoryStorage) DeleteServer(_ context.Context, name string) error

func (*MemoryStorage) HomeStorage

func (*MemoryStorage) LibraryAccess

func (m *MemoryStorage) LibraryAccess(context.Context) ([]RootAccess, error)

func (*MemoryStorage) PutServer

func (*MemoryStorage) RequestCanonicalize

func (m *MemoryStorage) RequestCanonicalize(_ context.Context, action, by string) error

func (*MemoryStorage) Servers

func (m *MemoryStorage) Servers(context.Context) ([]StorageServer, error)

func (*MemoryStorage) SetHomePathMap

func (m *MemoryStorage) SetHomePathMap(_ context.Context, pm json.RawMessage) error

type MemoryStore

type MemoryStore struct {

	// KnownStages, when non-nil, is the job_stages registry SetStages
	// checks against.
	KnownStages map[string]bool
	// contains filtered or unexported fields
}

MemoryStore is an in-process Store: handler tests use it, and so does a home that cannot take machines (SQLite), which only needs an identity for the mDNS advertisement and an empty registry.

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore returns an empty store.

func (*MemoryStore) AddWorker

func (m *MemoryStore) AddWorker(w NodeWorker)

AddWorker registers a node worker (tests).

func (*MemoryStore) Approve

func (m *MemoryStore) Approve(_ context.Context, id, dbRole string, sealed json.RawMessage, by string, now time.Time) error

Approve implements Store.

func (*MemoryStore) ClearSealed

func (m *MemoryStore) ClearSealed(_ context.Context, cutoff time.Time) error

ClearSealed implements Store.

func (*MemoryStore) CloseExpiredJoins

func (m *MemoryStore) CloseExpiredJoins(_ context.Context, now time.Time) (bool, error)

CloseExpiredJoins implements Store.

func (*MemoryStore) DeleteNode

func (m *MemoryStore) DeleteNode(_ context.Context, id string) error

DeleteNode implements Store.

func (*MemoryStore) EnsureIdentity

func (m *MemoryStore) EnsureIdentity(_ context.Context, name string) (Identity, error)

EnsureIdentity implements Store.

func (*MemoryStore) Identity

func (m *MemoryStore) Identity(ctx context.Context) (Identity, error)

Identity implements Store.

func (*MemoryStore) Node

func (m *MemoryStore) Node(_ context.Context, id string) (Node, error)

Node implements Store.

func (*MemoryStore) Nodes

func (m *MemoryStore) Nodes(_ context.Context) ([]Node, error)

Nodes implements Store.

func (*MemoryStore) PruneComponentStatus

func (m *MemoryStore) PruneComponentStatus(context.Context) (int64, error)

PruneComponentStatus implements Store: the memory store keeps no component status.

func (*MemoryStore) PutPending

func (m *MemoryStore) PutPending(_ context.Context, n Node) error

PutPending implements Store.

func (*MemoryStore) Reject

func (m *MemoryStore) Reject(_ context.Context, id string, now time.Time) error

Reject implements Store.

func (*MemoryStore) Revoke

func (m *MemoryStore) Revoke(_ context.Context, id string, now time.Time) error

Revoke implements Store.

func (*MemoryStore) SetAcceptJoins

func (m *MemoryStore) SetAcceptJoins(ctx context.Context, on bool, until *time.Time) (Identity, error)

SetAcceptJoins implements Store.

func (*MemoryStore) SetFullCapable

func (m *MemoryStore) SetFullCapable(id string, capable bool)

SetFullCapable is a machine's report that it can be full (tests: on Postgres, cluster_node_report_full); full_node follows the admin's FullAllowed (slot 0151).

func (*MemoryStore) SetName

func (m *MemoryStore) SetName(ctx context.Context, name string) (Identity, error)

SetName implements Store.

func (*MemoryStore) SetStages

func (m *MemoryStore) SetStages(_ context.Context, id string, stages map[string]*bool) error

SetStages implements Store.

func (*MemoryStore) Stages

func (m *MemoryStore) Stages(_ context.Context) (map[string]map[string]bool, error)

Stages implements Store.

func (*MemoryStore) UpdateNode

func (m *MemoryStore) UpdateNode(_ context.Context, id string, p NodePatch, now time.Time) error

UpdateNode implements Store.

func (*MemoryStore) Workers

func (m *MemoryStore) Workers(_ context.Context) ([]NodeWorker, error)

Workers implements Store.

func (*MemoryStore) WrongCode

func (m *MemoryStore) WrongCode(_ context.Context, id string, maxAttempts int, now time.Time) (int, error)

WrongCode implements Store.

type Node

type Node struct {
	ID            string
	Name          string
	State         string
	OS            *string
	Arch          *string
	Versions      json.RawMessage
	Capabilities  json.RawMessage
	Storage       json.RawMessage
	PathMap       json.RawMessage // nil: not set
	PathMapSource *string
	Drain         bool
	NodePubkey    string
	HomePubkey    *string
	HomePrivkey   *string
	CodeAttempts  int
	ExpiresAt     *time.Time
	Sealed        json.RawMessage // nil: none
	DBRole        *string
	RemoteAddr    *string
	APIURL        *string
	CreatedAt     time.Time
	ApprovedAt    *time.Time
	ApprovedBy    *string
	RevokedAt     *time.Time
	LastSeenAt    *time.Time
	UpdatedAt     time.Time

	// What a full node reports about itself (Epic 35 slot 0135, story 35.8): its
	// release, platform, own web address, whether it runs maktaba-server in node mode,
	// the VOD fallback (design §11.5) and the rollout's view of it (story 35.12).
	Version  *string
	Platform *string
	WebURL   *string
	FullNode bool
	// FullCapable: the machine reports it can be a full machine; FullAllowed: a home
	// admin allowed it (slot 0151). FullNode is both: only then does it get a copy.
	FullCapable bool
	FullAllowed bool
	VOD         json.RawMessage
	UpdateState json.RawMessage
	// Copy is what a full node reports of its copy of this database (Epic 37, slot
	// 0147: state, lag, when it last applied), and when it did.
	Copy           json.RawMessage
	CopyReportedAt *time.Time
}

Node is one cluster_nodes row, secrets included: callers that render it must not copy HomePrivkey / Sealed out.

type NodePatch

type NodePatch struct {
	Name         *string
	Drain        *bool
	PathMap      json.RawMessage
	ClearPathMap bool
	// FullAllowed: a home admin allows (or takes back) a full machine's copy; full_node
	// becomes what the machine reports and this (slot 0151).
	FullAllowed *bool
}

NodePatch is an admin edit; nil fields are left alone. ClearPathMap drops the map (back to "inferred by the node").

type NodeWorker

type NodeWorker struct {
	ID         string
	NodeID     string
	Host       string
	Stages     []string
	StagesOff  json.RawMessage
	LastSeenAt time.Time
}

NodeWorker is a workers row that belongs to a node.

type PGRoles

type PGRoles struct {
	DB *sql.DB
}

PGRoles provisions roles on the home's Postgres.

func (*PGRoles) Create

func (p *PGRoles) Create(ctx context.Context, role, password string) error

Create implements Roles. A role left over from an earlier membership (the machine was removed, the role could not be dropped) is re-enabled with the new password.

func (*PGRoles) DatabaseName

func (p *PGRoles) DatabaseName(ctx context.Context) (string, error)

DatabaseName implements Roles.

func (*PGRoles) Disable

func (p *PGRoles) Disable(ctx context.Context, role string) (int, error)

Disable implements Roles.

func (*PGRoles) Drop

func (p *PGRoles) Drop(ctx context.Context, role string) error

Drop implements Roles.

func (*PGRoles) ServerPort

func (p *PGRoles) ServerPort(ctx context.Context) (int, error)

ServerPort is the port the database says it listens on (0 over a Unix socket).

func (*PGRoles) Supported

func (p *PGRoles) Supported(ctx context.Context) (bool, string)

Supported implements Roles: the current user is superuser or may create roles, and the maktaba_worker group exists.

func (*PGRoles) Term

func (p *PGRoles) Term(ctx context.Context) (int64, error)

Term is the cluster's current term (0 before its first, or on a database without the terms: a home from before Epic 37); an error when the database cannot say (a machine's access is then not re-made: one with no term would be refused by a machine that follows a later one, its password already changed).

func (*PGRoles) Usable

func (p *PGRoles) Usable(ctx context.Context, role string) (bool, error)

Usable reports whether role exists and may log in on this database's cluster now.

type PGStorage

type PGStorage struct{ DB *sql.DB }

PGStorage is the Postgres StorageStore.

func (*PGStorage) Canonicalize

func (p *PGStorage) Canonicalize(ctx context.Context) (*CanonStatus, error)

func (*PGStorage) DeleteServer

func (p *PGStorage) DeleteServer(ctx context.Context, name string) error

func (*PGStorage) HomeStorage

func (p *PGStorage) HomeStorage(ctx context.Context) (json.RawMessage, json.RawMessage, error)

func (*PGStorage) LibraryAccess

func (p *PGStorage) LibraryAccess(ctx context.Context) ([]RootAccess, error)

func (*PGStorage) PutServer

func (p *PGStorage) PutServer(ctx context.Context, s StorageServer) (StorageServer, error)

func (*PGStorage) RequestCanonicalize

func (p *PGStorage) RequestCanonicalize(ctx context.Context, action, by string) error

func (*PGStorage) Servers

func (p *PGStorage) Servers(ctx context.Context) ([]StorageServer, error)

func (*PGStorage) SetHomePathMap

func (p *PGStorage) SetHomePathMap(ctx context.Context, pm json.RawMessage) error

type PGStore

type PGStore struct {
	DB *sql.DB
}

PGStore is the Postgres Store. The home's own database user runs it (the maktaba_worker group has no access to these tables).

func (*PGStore) Approve

func (s *PGStore) Approve(ctx context.Context, id, dbRole string, sealed json.RawMessage, by string, now time.Time) error

Approve implements Store.

func (*PGStore) ClearSealed

func (s *PGStore) ClearSealed(ctx context.Context, cutoff time.Time) error

ClearSealed implements Store.

func (*PGStore) CloseExpiredJoins

func (s *PGStore) CloseExpiredJoins(ctx context.Context, now time.Time) (bool, error)

CloseExpiredJoins implements Store.

func (*PGStore) DeleteNode

func (s *PGStore) DeleteNode(ctx context.Context, id string) error

DeleteNode implements Store.

func (*PGStore) EnsureIdentity

func (s *PGStore) EnsureIdentity(ctx context.Context, name string) (Identity, error)

EnsureIdentity implements Store.

func (*PGStore) Identity

func (s *PGStore) Identity(ctx context.Context) (Identity, error)

Identity implements Store.

func (*PGStore) Node

func (s *PGStore) Node(ctx context.Context, id string) (Node, error)

Node implements Store.

func (*PGStore) Nodes

func (s *PGStore) Nodes(ctx context.Context) ([]Node, error)

Nodes implements Store.

func (*PGStore) PruneComponentStatus

func (s *PGStore) PruneComponentStatus(ctx context.Context) (int64, error)

PruneComponentStatus implements Store. A status row's machine is "home" or a node's id; a node deleted while its row could not be pruned, or one that reported after its delete, leaves rows no machine owns, which the component pages would show forever.

func (*PGStore) PutPending

func (s *PGStore) PutPending(ctx context.Context, n Node) error

PutPending implements Store. An approved or revoked row is left alone (the caller answers 409 first; the WHERE makes it race-safe).

func (*PGStore) Reject

func (s *PGStore) Reject(ctx context.Context, id string, now time.Time) error

Reject implements Store.

func (*PGStore) Revoke

func (s *PGStore) Revoke(ctx context.Context, id string, now time.Time) error

Revoke implements Store.

func (*PGStore) SetAcceptJoins

func (s *PGStore) SetAcceptJoins(ctx context.Context, on bool, until *time.Time) (Identity, error)

SetAcceptJoins implements Store.

func (*PGStore) SetName

func (s *PGStore) SetName(ctx context.Context, name string) (Identity, error)

SetName implements Store.

func (*PGStore) SetStages

func (s *PGStore) SetStages(ctx context.Context, id string, stages map[string]*bool) error

SetStages implements Store.

func (*PGStore) Stages

func (s *PGStore) Stages(ctx context.Context) (map[string]map[string]bool, error)

Stages implements Store.

func (*PGStore) UpdateNode

func (s *PGStore) UpdateNode(ctx context.Context, id string, p NodePatch, now time.Time) error

UpdateNode implements Store.

func (*PGStore) Workers

func (s *PGStore) Workers(ctx context.Context) ([]NodeWorker, error)

Workers implements Store.

func (*PGStore) WrongCode

func (s *PGStore) WrongCode(ctx context.Context, id string, maxAttempts int, now time.Time) (int, error)

WrongCode implements Store.

type Payload

type Payload struct {
	// DatabaseCA is the home's database CA (PEM), which the machine verifies it with;
	// DatabaseTLS is "off" when the home's database has no TLS. Neither for a database
	// that is not the bundled one (its own TLS, which the home cannot vouch for).
	DatabaseCA  string      `json:"database_ca,omitempty"`
	DatabaseTLS string      `json:"database_tls,omitempty"`
	DatabaseURL string      `json:"database_url"`
	Home        PayloadHome `json:"home"`
	NodeID      string      `json:"node_id"`
	// TLS is the machine's cluster-link certificate (story 35.16): its CSR was in the
	// join request; absent for a machine that sent none (it asks over its channel session).
	TLS *PayloadTLS `json:"tls,omitempty"`
	V   int         `json:"v"`
}

Payload is what the home seals to an approved machine (design §3.2). Fields are declared in key order so the encoding matches the sorted-keys JSON of shared/testdata/cluster/vectors.json byte for byte.

type PayloadHome

type PayloadHome struct {
	APIURL     string `json:"api_url"`
	ClusterPub string `json:"cluster_pub,omitempty"`
	InstanceID string `json:"instance_id"`
	Name       string `json:"name"`
}

PayloadHome identifies the home inside the sealed payload. ClusterPub (phase 2) is the home's long-term cluster key, which the machine's agent checks in the channel handshake (design-agent.md §4.2); empty only in the phase-1 vectors.

type PayloadTLS

type PayloadTLS struct {
	CACert   string `json:"ca_cert"`
	CASHA256 string `json:"ca_sha256"`
	Cert     string `json:"cert"`
}

PayloadTLS is the machine's certificate from the home's cluster CA, the CA and its fingerprint (pinned through the pairing code's protection: no trust on first use).

type Roles

type Roles interface {
	// Supported reports whether machines can be given roles, and why not.
	Supported(ctx context.Context) (bool, string)
	// DatabaseName is the home's own database.
	DatabaseName(ctx context.Context) (string, error)
	// Create makes (or re-enables) a LOGIN role in the worker group.
	Create(ctx context.Context, role, password string) error
	// Disable makes the role NOLOGIN, rotates its password and ends its
	// sessions where the home's user may (and the machine's copy of the
	// database stops following). It returns how many sessions were ended.
	Disable(ctx context.Context, role string) (int, error)
	// Drop removes the role and the machine's replication role (best
	// effort, when a machine is removed).
	Drop(ctx context.Context, role string) error
}

Roles provisions the machines' database roles (design §3.3).

type RootAccess

type RootAccess struct {
	Path   string  `json:"path"`
	Access *string `json:"access"`
}

RootAccess is one library root and its library's media access.

type StorageServer

type StorageServer struct {
	ID        string            `json:"id"`
	Name      string            `json:"name"`
	Addresses []string          `json:"addresses"`
	CharMap   string            `json:"char_map"`
	Exports   map[string]string `json:"exports"`
}

StorageServer is a storage_servers row (story 31.3): the identity a canonical path smb://<name>/<share>/... names, and its addresses.

func NormaliseServer

func NormaliseServer(s StorageServer) (StorageServer, error)

NormaliseServer lower-cases the name, trims and dedups the addresses.

type StorageStore

type StorageStore interface {
	// HomeStorage is instance_identity.storage and .path_map (nil: none).
	HomeStorage(ctx context.Context) (storage, pathMap json.RawMessage, err error)
	// SetHomePathMap sets the home's override; nil clears it.
	SetHomePathMap(ctx context.Context, pathMap json.RawMessage) error
	Servers(ctx context.Context) ([]StorageServer, error)
	PutServer(ctx context.Context, s StorageServer) (StorageServer, error)
	DeleteServer(ctx context.Context, name string) error
	// Canonicalize is the home's automatic path conversion as its pipeline
	// reports it (storage_canonicalize: state + the pending request); nil when
	// the home has none yet.
	Canonicalize(ctx context.Context) (*CanonStatus, error)
	// RequestCanonicalize asks the home's pipeline for one of CanonActions.
	RequestCanonicalize(ctx context.Context, action, by string) error
	// LibraryAccess is every live library root with its library's media access (Epic 59
	// story 59.03: rw, ro, none; nil never checked), for a NAS home's writable folder
	// (story 59.13).
	LibraryAccess(ctx context.Context) ([]RootAccess, error)
}

StorageStore holds the shares' side of the cluster: the storage servers, the home's per-share storage report and its "share -> local mount" override.

type Store

type Store interface {
	// EnsureIdentity creates the singleton (random instance id, the given
	// name) when absent and returns it.
	EnsureIdentity(ctx context.Context, name string) (Identity, error)
	Identity(ctx context.Context) (Identity, error)
	// SetAcceptJoins switches joins; until is when they turn off again.
	SetAcceptJoins(ctx context.Context, on bool, until *time.Time) (Identity, error)
	// CloseExpiredJoins turns accept_joins off when its time is up and
	// reports whether it did.
	CloseExpiredJoins(ctx context.Context, now time.Time) (bool, error)
	SetName(ctx context.Context, name string) (Identity, error)

	// Node returns ErrNotFound when absent.
	Node(ctx context.Context, id string) (Node, error)
	Nodes(ctx context.Context) ([]Node, error)
	// PutPending creates a pending request, or replaces a pending /
	// rejected one with the same id (new keys, attempts reset).
	PutPending(ctx context.Context, n Node) error
	// WrongCode counts a wrong code; at max attempts the request is
	// rejected. Returns the attempts made.
	WrongCode(ctx context.Context, id string, maxAttempts int, now time.Time) (int, error)
	// Approve stores the role and the sealed envelope and clears the home's
	// private key.
	Approve(ctx context.Context, id, dbRole string, sealed json.RawMessage, by string, now time.Time) error
	// Reject / Revoke set the state and drop the keys and the envelope.
	Reject(ctx context.Context, id string, now time.Time) error
	Revoke(ctx context.Context, id string, now time.Time) error
	UpdateNode(ctx context.Context, id string, p NodePatch, now time.Time) error
	DeleteNode(ctx context.Context, id string) error

	// Stage switches: nil removes the row (automatic).
	SetStages(ctx context.Context, id string, stages map[string]*bool) error
	Stages(ctx context.Context) (map[string]map[string]bool, error)
	Workers(ctx context.Context) ([]NodeWorker, error)

	// ClearSealed drops envelopes of approved machines whose worker has
	// registered, or that were approved before cutoff.
	ClearSealed(ctx context.Context, cutoff time.Time) error
	// PruneComponentStatus deletes the component status rows of machines whose node row
	// is gone (Epic 51 story 51.02: the home's housekeeping), and answers how many.
	PruneComponentStatus(ctx context.Context) (int64, error)
}

Store persists the identity and the machine registry.

type Unsupported

type Unsupported struct{ Reason string }

Unsupported is Roles for a home that cannot take machines.

func (Unsupported) Create

Create implements Roles.

func (Unsupported) DatabaseName

func (u Unsupported) DatabaseName(context.Context) (string, error)

DatabaseName implements Roles.

func (Unsupported) Disable

func (u Unsupported) Disable(context.Context, string) (int, error)

Disable implements Roles.

func (Unsupported) Drop

Drop implements Roles.

func (Unsupported) Supported

func (u Unsupported) Supported(context.Context) (bool, string)

Supported implements Roles.

Directories

Path Synopsis
Package agent is the home's side of the cluster channel (Epic 31 phase 2, specs/epics/31-multi-instance/design-agent.md): the authenticated, encrypted WebSocket every Maktaba process holds to the home (/api/cluster/agent), the hub that keeps the live state of every connected process, the browser WebSocket (/api/cluster/ws), the history endpoints that read the cluster files on the share, the per-process commands and the LLM router with its OpenAI-compatible door.
Package agent is the home's side of the cluster channel (Epic 31 phase 2, specs/epics/31-multi-instance/design-agent.md): the authenticated, encrypted WebSocket every Maktaba process holds to the home (/api/cluster/agent), the hub that keeps the live state of every connected process, the browser WebSocket (/api/cluster/ws), the history endpoints that read the cluster files on the share, the per-process commands and the LLM router with its OpenAI-compatible door.
relayfixture command
Command relayfixture is the home side of the extension relay's two-process test (pipeline/tests/cluster/test_relay_two_process.py): the real cluster hub with the real service door, on a scratch Postgres database, reading the node registry (cluster_nodes), rules.relay and the Plex extension's row and token (home_secrets) from it.
Command relayfixture is the home side of the extension relay's two-process test (pipeline/tests/cluster/test_relay_two_process.py): the real cluster hub with the real service door, on a scratch Postgres database, reading the node registry (cluster_nodes), rules.relay and the Plex extension's row and token (home_secrets) from it.
Package ca is the home's cluster CA (Epic 35 story 35.16, design §18.2): a small ECDSA P-256 root, valid ten years, created by the home's API at its first start after the story.
Package ca is the home's cluster CA (Epic 35 story 35.16, design §18.2): a small ECDSA P-256 root, valid ten years, created by the home's API at its first start after the story.
Package cache is the home database's cache of the cluster channel (specs/epics/31-multi-instance/design-agent.md §7.9).
Package cache is the home database's cache of the cluster channel (specs/epics/31-multi-instance/design-agent.md §7.9).
Package clustertest gives the Epic 31 tests a scratch, fully migrated Postgres database.
Package clustertest gives the Epic 31 tests a scratch, fully migrated Postgres database.
Package delegation is how a full node acts for a user without ever reading the sessions table (Epic 35 story 35.9, design §10): every node → home HTTP request is signed with the node's delegation key, a per-node HMAC key the home issues over the cluster channel (`keys` frame), keeps sealed in home_secrets, rotates daily and deletes when the machine is revoked.
Package delegation is how a full node acts for a user without ever reading the sessions table (Epic 35 story 35.9, design §10): every node → home HTTP request is signed with the node's delegation key, a per-node HMAC key the home issues over the cluster channel (`keys` frame), keeps sealed in home_secrets, rotates daily and deletes when the machine is revoked.
Package homelink is a full node's way to the home (Epic 35 stories 35.9, 35.10): the session checks, the cluster sign-in's exchange, the home's JWKS, the home-class requests the node proxies, and the events the home pushes (a new delegation key, a revocation).
Package homelink is a full node's way to the home (Epic 35 stories 35.9, 35.10): the session checks, the cluster sign-in's exchange, the home's JWKS, the home-class requests the node proxies, and the events the home pushes (a new delegation key, a revocation).
Package homeproxy is a full node's reverse proxy to its home (Epic 35 story 35.10, design §11.2): every `home` route a node gets goes to the home's API with the user's session as X-Maktaba-Delegated-Session, the node's signature (story 35.9) and X-Maktaba-Via: node.
Package homeproxy is a full node's reverse proxy to its home (Epic 35 story 35.10, design §11.2): every `home` route a node gets goes to the home's API with the user's session as X-Maktaba-Delegated-Session, the node's signature (story 35.9) and X-Maktaba-Via: node.
Package link is the cluster link (Epic 35 story 35.16, design §18): machine-to-home traffic over WebSockets on mutual TLS, on the home API's existing port.
Package link is the cluster link (Epic 35 story 35.16, design §18): machine-to-home traffic over WebSockets on mutual TLS, on the home API's existing port.
Package linkctx carries the cluster link's word on a request (Epic 35 story 35.16): which machine sent it over its mutual-TLS link, and the home's link mode.
Package linkctx carries the cluster link's word on a request (Epic 35 story 35.16): which machine sent it over its mutual-TLS link, and the home's link mode.
Package nodeauth resolves who is asking on a full node (Epic 35 story 35.9, design §10.3).
Package nodeauth resolves who is asking on a full node (Epic 35 story 35.9, design §10.3).
Package nodedb is a full node's database (specs/epics/37-node-replica): one *sql.DB over two Postgres servers, this machine's own read-only copy of the home's database and the home's database itself.
Package nodedb is a full node's database (specs/epics/37-node-replica): one *sql.DB over two Postgres servers, this machine's own read-only copy of the home's database and the home's database itself.
Package nodemetrics is a full node's Prometheus metrics (Epic 35 story 35.15 AC1), on the API's /metrics: the sessions it asks the home about (delegation, story 35.9), the requests it serves by placement class (story 35.10) and whether the schema guard paused it (story 35.8 AC4).
Package nodemetrics is a full node's Prometheus metrics (Epic 35 story 35.15 AC1), on the API's /metrics: the sessions it asks the home about (delegation, story 35.9), the requests it serves by placement class (story 35.10) and whether the schema guard paused it (story 35.8 AC4).
Package placement says where each API route is served when the API runs on a full node (Epic 35 story 35.10, design §11.1):
Package placement says where each API route is served when the API runs on a full node (Epic 35 story 35.10, design §11.1):
Package relay is the home's service door (story 31.R, design specs/epics/31-multi-instance/story-31-relay-service-door.md): a cluster node sends an extension's HTTP request over its sealed agent channel, and the home checks it against that extension's allow-list, adds the secret the node never sees (the Plex token, kept in home_secrets), forwards it to the configured server and streams the answer back with the secret scrubbed out of it.
Package relay is the home's service door (story 31.R, design specs/epics/31-multi-instance/story-31-relay-service-door.md): a cluster node sends an extension's HTTP request over its sealed agent channel, and the home checks it against that extension's allow-list, adds the secret the node never sees (the Plex token, kept in home_secrets), forwards it to the configured server and streams the answer back with the secret scrubbed out of it.
Package schemaguard is a full node's API schema guard (Epic 35 story 35.8, design §9.3): the same rule, table and reason texts as the pipeline's cluster/schema.py and the streaming node's streaming/internal/cluster/schema.go (Epic 31 design §5.1).
Package schemaguard is a full node's API schema guard (Epic 35 story 35.8, design §9.3): the same rule, table and reason texts as the pipeline's cluster/schema.py and the streaming node's streaming/internal/cluster/schema.go (Epic 31 design §5.1).
Package switchover runs a switch of the home from the home's API (specs/epics/ 37-node-replica, "Switching the home"): another machine of the cluster, whose copy follows this home, becomes the home, and this one one of its machines.
Package switchover runs a switch of the home from the home's API (specs/epics/ 37-node-replica, "Switching the home"): another machine of the cluster, whose copy follows this home, becomes the home, and this one one of its machines.
Package vodfallback serves video on demand on a full node (Epic 35 story 35.8 AC9, story 35.10 AC4a, design §11.5).
Package vodfallback serves video on demand on a full node (Epic 35 story 35.8 AC9, story 35.10 AC4a, design §11.5).

Jump to

Keyboard shortcuts

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