Documentation
¶
Overview ¶
Package server provides coordination storage, enrollment and peer discovery.
Index ¶
- Variables
- type AccountID
- type Device
- type DeviceID
- type DeviceRef
- type Directory
- func (d *Directory) Changed() <-chan struct{}
- func (d *Directory) Devices() []PeerEntry
- func (d *Directory) Invalidate(k protocol.NodeKey)
- func (d *Directory) Lookup(ctx context.Context, k protocol.NodeKey) (PeerEntry, bool)
- func (d *Directory) Reload(ctx context.Context, k protocol.NodeKey)
- func (d *Directory) Run(ctx context.Context) error
- type DirectoryOptions
- type Forwarder
- type HostEntry
- type Options
- type PeerEntry
- type Principal
- type Region
- func (r *Region) AddForwarder(dst protocol.NodeKey, f Forwarder)
- func (r *Region) Close() error
- func (r *Region) Deliver(src, dst protocol.NodeKey, payload []byte) error
- func (r *Region) DialLocal(ctx context.Context) (net.Conn, error)
- func (r *Region) Disconnect(k protocol.NodeKey)
- func (r *Region) RemoveForwarder(dst protocol.NodeKey, f Forwarder)
- func (r *Region) Serve(ctx context.Context, conn net.Conn, p Principal) error
- func (r *Region) Stats() RegionStats
- type RegionOptions
- type RegionStats
- type Server
- func (s *Server) Authorize(ctx context.Context, p Principal) (Device, error)
- func (s *Server) ClearConfirmation(ctx context.Context, hostLabel string, device protocol.NodeKey) error
- func (s *Server) DeleteHost(ctx context.Context, label string) error
- func (s *Server) Enroll(ctx context.Context, ref DeviceRef, k protocol.NodeKey, policy []byte, ...) (bool, error)
- func (s *Server) Netmap(ctx context.Context, p Principal, sinceVersion string) (protocol.Netmap, error)
- func (s *Server) PutHost(ctx context.Context, h HostEntry) error
- func (s *Server) Register(ctx context.Context, p Principal, reg protocol.Registration) error
- func (s *Server) Run(ctx context.Context) error
- func (s *Server) SetConfirmation(ctx context.Context, hostLabel string, c protocol.Confirmation) error
- func (s *Server) Wake(ref DeviceRef)
- func (s *Server) WakeAll()
- func (s *Server) Withdraw(ctx context.Context, ref DeviceRef) error
- type Store
Constants ¶
This section is empty.
Variables ¶
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 = errors.New("unauthorized principal") ErrUnavailable = errors.New("coordination store unavailable") )
Functions ¶
This section is empty.
Types ¶
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 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 ¶
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 ¶
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 ¶
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 ¶
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.
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 ¶
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 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 ¶
AddForwarder registers a comparable forwarder for dst. Repeated registration is idempotent; a local connection takes priority over a remote forwarder.
func (*Region) Close ¶
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 ¶
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 ¶
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 ¶
Disconnect closes admitted and pending device connections for k outside internal locks. Withdraw enrollment separately to refuse future Serve.
func (*Region) RemoveForwarder ¶
RemoveForwarder removes the exact comparable registration. An absent registration is a no-op and other forwarders for the same key remain.
func (*Region) Serve ¶
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 ¶
New validates options without reading the store. Missing storage, invalid durations, invalid regions and holds reaching the client timeout are refused.
func (*Server) Authorize ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
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.