server

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: BSD-3-Clause Imports: 24 Imported by: ? modules, 0 packages

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

Documentation

Overview

Package server provides coordination storage, enrollment and peer discovery.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound means the requested entry is absent or expired.
	ErrNotFound = errors.New("coordination entry not found")
	// ErrDeviceLimit means the account has reached its live enrollment cap.
	ErrDeviceLimit = errors.New("device limit reached")
	// ErrNodeKeyConflict means another live enrollment holds the node key.
	ErrNodeKeyConflict = errors.New("node key already enrolled")
	// ErrUnauthorized means the principal does not hold a live enrollment.
	ErrUnauthorized = errors.New("unauthorized principal")
	// ErrUnavailable means storage cannot currently evaluate the operation.
	ErrUnavailable = errors.New("coordination store unavailable")
)

Functions

This section is empty.

Types

type AccountID

type AccountID string

AccountID identifies the caller's account namespace.

type Device

type Device struct {
	Ref             DeviceRef
	NodeKey         protocol.NodeKey
	Policy          []byte
	LeaseExpires    time.Time
	Registration    *protocol.Registration
	PresenceExpires time.Time
}

Device holds an enrollment lease and its independently expiring presence.

type DeviceID

type DeviceID string

DeviceID identifies one enrollment within an account.

type DeviceRef

type DeviceRef struct {
	Account AccountID
	Device  DeviceID
}

DeviceRef identifies an enrollment across accounts.

type Directory

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

Directory keeps a bounded LRU and coalesces asynchronous misses per node key. Call Run to refresh held entries; Lookup and Devices also reject local expiry. Changed has one reader and coalesces unread notifications.

func NewDirectory

func NewDirectory(st Store, o DirectoryOptions) *Directory

NewDirectory constructs an empty cache. Lookup performs no synchronous store I/O.

func (*Directory) Changed

func (d *Directory) Changed() <-chan struct{}

Changed returns the capacity-1 channel for add, removal, disco key, endpoint, policy and expiry changes. Notifications never block and unread events coalesce.

func (*Directory) Devices

func (d *Directory) Devices() []PeerEntry

Devices returns copies of held live device entries, sorted by node key. Expired entries are removed and fire Changed, including during a store outage.

func (*Directory) Invalidate

func (d *Directory) Invalidate(k protocol.NodeKey)

Invalidate removes a cached key and rejects completion of its old in-flight read. The next Lookup starts a new read. Removing a peer fires Changed.

func (*Directory) Lookup

func (d *Directory) Lookup(ctx context.Context, k protocol.NodeKey) (PeerEntry, bool)

Lookup returns a caller-owned cache hit. A miss returns false immediately and starts at most one store read for k. Absent keys stay negative for MissTTL; unavailable storage never creates a positive or negative cache entry. A shared read retains the caller's context values but has its own 2-second timeout; canceling one caller does not cancel the read for other waiters.

func (*Directory) Reload

func (d *Directory) Reload(ctx context.Context, k protocol.NodeKey)

Reload reads k from the store and replaces its cached entry in place. The old entry stays visible until the read lands, and Changed fires only when the new entry differs. A failed read keeps the old entry. The call rejects completion of any earlier in-flight read for k. Use Invalidate to drop a key.

func (*Directory) Run

func (d *Directory) Run(ctx context.Context) error

Run refreshes held devices in one batch per account and held hosts in one scan every Refresh. Failed reads retain entries only until their own expiry. Cancellation returns nil; it does not clear the cache or close Changed.

type DirectoryOptions

type DirectoryOptions struct {
	MaxEntries int
	MissTTL    time.Duration
	Refresh    time.Duration
	Clock      func() time.Time
}

DirectoryOptions sets the cache bound, negative-cache lifetime and refresh period. Zero selects 4096 entries, 2 s misses and 10 s refresh; nil Clock uses time.Now. Nonpositive explicit limits use those defaults as well.

type Forwarder

type Forwarder interface {
	ForwardPacket(src, dst protocol.NodeKey, payload []byte) error
}

Forwarder sends a packet to another region endpoint. Payload is lent only for the call. Implementations must be comparable for registration/removal.

type HostEntry

type HostEntry struct {
	Label           string
	NodeKey         protocol.NodeKey
	DiscoKey        protocol.DiscoKey
	Endpoints       []netip.AddrPort
	Origin          string
	PresenceExpires time.Time
}

HostEntry describes one host until PresenceExpires.

type Options

type Options struct {
	Store                Store
	Regions              []protocol.Region
	Clock                func() time.Time
	Logger               *slog.Logger
	MaxDevicesPerAccount int
	Presence             time.Duration
	Refresh              time.Duration
	Lease                time.Duration
	Hold                 time.Duration
	Reconcile            time.Duration
}

Options configures storage, regions and independent lease/presence deadlines. Zero durations select the documented defaults; Clock nil uses time.Now. Logger nil discards logs. MaxDevicesPerAccount zero selects 32. Hold must stay below protocol.NetmapRequestTimeout.

type PeerEntry

type PeerEntry struct {
	NodeKey   protocol.NodeKey
	Ref       DeviceRef
	IsHost    bool
	DiscoKey  protocol.DiscoKey
	Endpoints []netip.AddrPort
	Policy    []byte
	Expires   time.Time
}

PeerEntry is a live device or host view. Device Policy is opaque; hosts have nil Policy and a zero Ref. Expires is the earliest lease/presence deadline.

type Principal

type Principal struct {
	Ref     DeviceRef
	NodeKey protocol.NodeKey
	Expires time.Time
}

Principal is a credential verified by the caller, valid until Expires.

type Region

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

Region serves discovery-only DERP streams with enrollment, host admission, identity binding and a shared envelope on local and forwarded traffic.

func NewRegion

func NewRegion(o RegionOptions) (*Region, error)

NewRegion validates dependencies and constructs one private, authenticated in-memory delivery client. Entropy, mesh setup and handshake errors fail the construction. No socket or external credential is used by this constructor.

func (*Region) AddForwarder

func (r *Region) AddForwarder(dst protocol.NodeKey, f Forwarder)

AddForwarder registers a comparable forwarder for dst. Repeated registration is idempotent; a local connection takes priority over a remote forwarder.

func (*Region) Close

func (r *Region) Close() error

Close idempotently refuses new streams and delivery, closes all pending and admitted streams, then waits for DERP shutdown. Transport errors are returned.

func (*Region) Deliver

func (r *Region) Deliver(src, dst protocol.NodeKey, payload []byte) error

Deliver validates a forwarded discovery payload against the receiver's live directory and normalized pair budget. Refusals return an error and count a drop without closing the shared delivery client or affecting other pairs. Acceptance injects a ForwardPacket; DERP never forwards it to another region.

func (*Region) DialLocal

func (r *Region) DialLocal(ctx context.Context) (net.Conn, error)

DialLocal returns a buffered in-memory connection for this host's engine. The caller closes its end. Its first ClientInfo must identify a live host in Directory; devices cannot enter through this path. Its admission read waits at most 2 seconds; timeout closes the returned connection during the handshake. A closed region or canceled context refuses the dial.

func (*Region) Disconnect

func (r *Region) Disconnect(k protocol.NodeKey)

Disconnect closes admitted and pending device connections for k outside internal locks. Withdraw enrollment separately to refuse future Serve.

func (*Region) RemoveForwarder

func (r *Region) RemoveForwarder(dst protocol.NodeKey, f Forwarder)

RemoveForwarder removes the exact comparable registration. An absent registration is a no-op and other forwarders for the same key remain.

func (*Region) Serve

func (r *Region) Serve(ctx context.Context, conn net.Conn, p Principal) error

Serve authenticates a device and blocks until transport closure, cancellation or credential expiry. ClientInfo must prove p.NodeKey. It owns and closes conn; authorization and envelope failures are returned to the caller. The directory read for admission waits at most 2 seconds, independently of cache lifetimes.

func (*Region) Stats

func (r *Region) Stats() RegionStats

Stats copies counters and maps; callers can mutate the snapshot safely.

type RegionOptions

type RegionOptions struct {
	Server                      *Server
	Directory                   *Directory
	PrivateKey                  [32]byte
	Budget                      protocol.Budget
	LocalConnectionBytes        int
	LocalConnectionBytesPerPair int
	Logger                      *slog.Logger
	Clock                       func() time.Time
}

RegionOptions supplies the shared coordinator and peer directory. A zero PrivateKey generates a new identity. Budget.Limits sets the envelope numbers for every stream and pair; a zero Limits, or a zero field in it, uses the protocol default, and Budget's other fields are ignored. The stream DialLocal returns carries every pair of its host, so its connection byte total grows with the number of devices. LocalConnectionBytes replaces Budget.Limits.ConnectionBytes for that stream, and LocalConnectionBytesPerPair raises its limit to that many bytes for each pair that carried a frame in the current 90 s window when the product is larger. A pair that expires in the window still counts until the window ends, so the limit never falls within a window. Zero keeps the shared limit. Clock nil uses time.Now and Logger nil discards logs. Keys stay in process.

type RegionStats

type RegionStats struct {
	Connections int
	Drops       map[string]uint64
	Closes      map[string]uint64
	Replaced    uint64
}

RegionStats is an independent snapshot. Connections counts admitted clients, excluding the private delivery client. Refusal reasons have bounded names.

type Server

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

Server coordinates enrolled devices and live hosts over a shared Store. Run observes external host writes; Wake and WakeAll support external notices.

func New

func New(o Options) (*Server, error)

New validates options without reading the store. Missing storage, invalid durations, invalid regions and holds reaching the client timeout are refused.

func (*Server) Authorize

func (s *Server) Authorize(ctx context.Context, p Principal) (Device, error)

Authorize requires a live credential and matching live enrollment. Missing enrollment returns ErrUnauthorized; storage outages remain storage errors.

func (*Server) ClearConfirmation

func (s *Server) ClearConfirmation(ctx context.Context, hostLabel string, device protocol.NodeKey) error

ClearConfirmation removes this host's confirmation and wakes the device. A missing device returns ErrNotFound; no enrollment is recreated.

func (*Server) DeleteHost

func (s *Server) DeleteHost(ctx context.Context, label string) error

DeleteHost removes a host and wakes all held netmaps after storage succeeds.

func (*Server) Enroll

func (s *Server) Enroll(ctx context.Context, ref DeviceRef, k protocol.NodeKey, policy []byte, leaseExpires time.Time) (bool, error)

Enroll atomically reserves a live device lease and opaque policy. It returns whether a live enrollment's node key was replaced, or a store admission error.

func (*Server) Netmap

func (s *Server) Netmap(ctx context.Context, p Principal, sinceVersion string) (protocol.Netmap, error)

Netmap returns only live hosts, regions and timing hints. An empty or different version returns immediately. An equal version holds until a wake, Hold, or cancellation, then reauthorizes and reads the current view.

func (*Server) PutHost

func (s *Server) PutHost(ctx context.Context, h HostEntry) error

PutHost validates and renews a host's presence for Presence. It wakes all held netmaps only when the stored host is new or its node key, disco key, endpoints or origin differ; an unchanged entry renews presence without a wake. The caller publishes the host again on change and refresh.

func (*Server) Register

func (s *Server) Register(ctx context.Context, p Principal, reg protocol.Registration) error

Register validates the body and principal identity, then stores independent presence for Presence. It never creates an enrollment and wakes this device.

func (*Server) Run

func (s *Server) Run(ctx context.Context) error

Run rereads the host view every Reconcile and wakes held netmaps on changes. Store outages retain the last version for comparison. Cancellation returns nil.

func (*Server) SetConfirmation

func (s *Server) SetConfirmation(ctx context.Context, hostLabel string, c protocol.Confirmation) error

SetConfirmation stores a host's confirmation of c.Peer until now + Presence. Equal live identity renews its deadline without a wake or version change. Invalid c returns an error wrapping protocol.ErrInvalid before store access or wake.

func (*Server) Wake

func (s *Server) Wake(ref DeviceRef)

Wake releases all currently held netmaps for ref; it records no future event.

func (*Server) WakeAll

func (s *Server) WakeAll()

WakeAll releases every currently held netmap, including external-store writes.

func (*Server) Withdraw

func (s *Server) Withdraw(ctx context.Context, ref DeviceRef) error

Withdraw deletes the enrollment and wakes its held netmaps. Callers separately disconnect region connections and remove the device from their engine.

type Store

type Store interface {
	// PutDevice enforces the live account cap and global node-key uniqueness.
	// A replacement changes the key index and clears registration atomically.
	PutDevice(ctx context.Context, d Device, maxPerAccount int, now time.Time) (replaced bool, err error)
	// Device returns ErrNotFound for a missing or expired lease.
	Device(ctx context.Context, ref DeviceRef, now time.Time) (Device, error)
	// DeviceByNodeKey resolves an unexpired lease or returns ErrNotFound.
	DeviceByNodeKey(ctx context.Context, k protocol.NodeKey, now time.Time) (Device, error)
	// ListDevices returns live leases sorted by Ref.Device, empty when none.
	ListDevices(ctx context.Context, account AccountID, now time.Time) ([]Device, error)
	// DeleteDevice removes only this member, its indices and confirmations.
	DeleteDevice(ctx context.Context, ref DeviceRef) error
	// PutRegistration requires a live lease with the same node key.
	PutRegistration(ctx context.Context, ref DeviceRef, reg protocol.Registration, presenceExpires, now time.Time) error
	// PutHost stores a host until its presence deadline.
	PutHost(ctx context.Context, h HostEntry, now time.Time) error
	// DeleteHost removes the host and its confirmations.
	DeleteHost(ctx context.Context, label string) error
	// Hosts returns live hosts sorted by label.
	Hosts(ctx context.Context, now time.Time) ([]HostEntry, error)
	// PutConfirmation stores a host's confirmation until expires; nil deletes it.
	PutConfirmation(ctx context.Context, hostLabel string, ref DeviceRef, c *protocol.Confirmation, expires, now time.Time) error
	// Confirmations returns live confirmations indexed by host label.
	Confirmations(ctx context.Context, ref DeviceRef, now time.Time) (map[string]protocol.Confirmation, error)
}

Store operations are atomic and return caller-owned values. Expiry at now is absent. Device leases and registration presence have independent deadlines.

func NewMemoryStore

func NewMemoryStore() Store

NewMemoryStore returns an empty concurrency-safe store with atomic indices. Stored slices and registrations never alias values supplied or returned.

Directories

Path Synopsis
Package storetest supplies a clock-independent Store conformance suite.
Package storetest supplies a clock-independent Store conformance suite.

Jump to

Keyboard shortcuts

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