primarylease

package
v0.1.0-alpha.14 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: Apache-2.0 Imports: 19 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 primarylease supplies a locally verifiable, short-lived primary write lease for Meldbase deployments.

It intentionally does not elect a leader or persist distributed controller state. A separately operated controller must atomically fence an old owner before signing a lease for a new one. The guard keeps the database commit path free of network I/O: it verifies a controller-signed certificate when it is installed, then performs only bounded local checks for each write.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrLeaseActive means another owner may still possess a locally valid
	// certificate.
	//
	// Callers must wait for RetryAfter rather than attempting to
	// shorten that previous lease.
	ErrLeaseActive = errors.New("meldbase primary lease: previous owner may still be active")
	// ErrLeaseSequence rejects a controller request that would certify a source
	// position older than the controller has already recorded.
	ErrLeaseSequence = errors.New("meldbase primary lease: commit sequence regressed")
	// ErrLeaseStore reports a malformed or unavailable controller state store.
	ErrLeaseStore = errors.New("meldbase primary lease: controller state store failure")
	// ErrLeasePromotionReadiness means a promotion lacks the external proof that
	// its follower is safe to become primary at the requested source position.
	ErrLeasePromotionReadiness = errors.New("meldbase primary lease: promotion readiness was not proven")
)
View Source
var (
	// ErrCertificate reports a malformed, invalid or unsuitable lease
	// certificate.
	//
	// It intentionally gives no signature-verification detail.
	ErrCertificate = errors.New("meldbase primary lease: invalid certificate")
	// ErrLeaseExpired reports a certificate that is not currently valid.
	ErrLeaseExpired = errors.New("meldbase primary lease: lease is not currently valid")
	// ErrLeaseOwner reports a lease issued for a different configured owner.
	ErrLeaseOwner = errors.New("meldbase primary lease: certificate owner mismatch")
	// ErrLeaseEpoch reports an attempted local rollback or replay of a fenced
	// controller epoch.
	ErrLeaseEpoch = errors.New("meldbase primary lease: stale controller epoch")
)
View Source
var (
	// ErrLeaseQuorum means too few configured independent members completed an
	// operation.
	//
	// It is deliberately distinct from a CAS conflict.
	ErrLeaseQuorum = errors.New("meldbase primary lease: quorum unavailable")
	// ErrLeaseConflict means a read quorum observed no exact majority record.
	//
	// This can occur after interrupted or crossed partial writes; choosing a
	// plausible-looking highest epoch would be unsafe.
	ErrLeaseConflict = errors.New("meldbase primary lease: quorum state conflict")
)
View Source
var ErrPrimaryRuntimeConfiguration = errors.New("meldbase primary lease: invalid primary runtime configuration")

ErrPrimaryRuntimeConfiguration reports settings that cannot safely connect a database, write guard, and renewer.

In particular, callers must not inject an unrelated write fence alongside a Guard that a Renewer will update.

View Source
var ErrRenewalConfiguration = errors.New("meldbase primary lease: invalid renewal agent configuration")

ErrRenewalConfiguration reports missing dependencies or invalid renewal settings.

Functions

func CertificateTextLimit

func CertificateTextLimit() int

CertificateTextLimit is the maximum encoded certificate length.

It remains below Meldbase's promotion-fence epoch limit.

func Sign

func Sign(certificate Certificate, privateKey ed25519.PrivateKey) (string, error)

Sign creates a signed, URL-safe certificate using the controller's private key.

The result is suitable for FollowerPromotionFence.Epoch. privateKey belongs only to the controller; a database process needs the corresponding public key.

func ValidateLeaseRecord

func ValidateLeaseRecord(record LeaseRecord, databaseID [16]byte) error

ValidateLeaseRecord checks a lease record's fields and database identity.

Network adapters use it before passing a decoded record to a LeaseStore. It does not check whether the lease has expired.

Types

type Authority

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

Authority issues signed write leases after saving the controller state durably.

A LeaseStore CAS makes each handoff durable. It has no HTTP listener, peer authentication or membership logic; those are deployment concerns around the store.

func NewAuthority

func NewAuthority(options AuthorityOptions) (*Authority, error)

NewAuthority validates controller-local configuration.

It is intentionally impossible to construct an Authority with a default in-memory store: doing so would make an accidental single-process test controller look durable.

func (*Authority) Grant

func (authority *Authority) Grant(ctx context.Context, request GrantRequest) (Grant, error)

Grant issues a signed write lease with a new controller epoch.

A renewal for the same owner may be granted before the old certificate expires; a different owner must wait until the old expiry plus MaxClockSkew. This explicit availability gap is the price of not allowing two clock-skewed processes to write concurrently.

func (*Authority) Revoke

func (authority *Authority) Revoke(ctx context.Context, databaseID [16]byte, epoch uint64) (LeaseRecord, error)

Revoke advances the durable controller epoch and removes the current owner.

It does not shorten an already issued certificate: an unreachable old owner may still be using it. The next owner must respect the same handoff window in Grant. A reachable owner should receive Guard.Revoke through its local control agent as an optimization, not as the safety proof.

func (*Authority) Stats

func (authority *Authority) Stats() AuthorityStats

Stats returns an O(1), allocation-free aggregate snapshot.

It is separate from DBStats because a controller can manage many databases and is not part of the database commit path.

type AuthorityOptions

type AuthorityOptions struct {
	Store         LeaseStore
	PrivateKey    ed25519.PrivateKey
	LeaseDuration time.Duration
	MaxClockSkew  time.Duration
	Clock         func() time.Time
	CASRetries    int
}

AuthorityOptions sets the controller store, signing key, lease duration, and clock limits.

MaxClockSkew is the maximum absolute offset allowed between a primary and the controller. A new owner cannot receive a currently valid certificate until the preceding certificate's expiry plus this window.

type AuthorityStats

type AuthorityStats struct {
	GrantAttempts              uint64
	Granted                    uint64
	HandoffWaits               uint64
	PromotionAttempts          uint64
	PromotionReadinessRejected uint64
	SequenceRejected           uint64
	StoreFailures              uint64
	CASConflicts               uint64
	RevokeAttempts             uint64
	Revoked                    uint64
}

AuthorityStats reports aggregate controller grants, revocations, and rejected requests.

It deliberately excludes database IDs, owners, epochs, certificates, endpoints and error details. Read it from a sampler rather than from a controller request hot path.

type Certificate

type Certificate struct {
	DatabaseID     [16]byte
	Owner          string
	Epoch          uint64
	CommitSequence uint64
	NotBefore      time.Time
	NotAfter       time.Time
}

Certificate gives a database owner signed permission to accept writes for a limited time.

CommitSequence is the source position at which the authority was issued; the first accepted write must advance beyond it. Epoch must grow monotonically in the controller, but the guard treats it as opaque ordering data because it cannot contact the controller in the write path.

func Parse

func Parse(encoded string, publicKey ed25519.PublicKey) (Certificate, error)

Parse verifies and decodes an opaque signed certificate.

The returned value has millisecond precision because that is the signed wire representation.

func (Certificate) String

func (certificate Certificate) String() string

String returns the certificate's epoch and commit position without exposing its owner or signed text.

type DurableConsumerPromotionReadiness

type DurableConsumerPromotionReadiness struct {
	Source       *meldbase.DB
	ConsumerName string
	Buffer       int
}

DurableConsumerPromotionReadiness permits promotion only when source and acknowledged follower positions match.

It supports a single-writer follower. The source's authenticated named durable database consumer must have durably acknowledged exactly the candidate follower's local token, and the source must not have advanced beyond it.

Authority runs readiness only after the old lease's skew-safe handoff point. The deployment must still ensure that the source used that lease guard and that ConsumerName is bound by its replication transport to this follower's trusted identity. It deliberately stays closed if the source is unavailable, history state is missing or either position differs.

func (DurableConsumerPromotionReadiness) VerifyFollowerPromotion

func (readiness DurableConsumerPromotionReadiness) VerifyFollowerPromotion(ctx context.Context, request meldbase.FollowerPromotionRequest, record LeaseRecord, exists bool) error

VerifyFollowerPromotion checks that the source and its durable consumer match the follower token.

type FileStore

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

FileStore saves one controller member's lease records in a trusted existing directory.

It is suitable as the local state of one independently operated quorum member, not as a quorum or leader-election service by itself. Each database identity has a separate atomically replaced record.

The directory must be on storage appropriate for the controller's durability contract. FileStore writes use a per-record advisory flock, durable temporary file, atomic rename and directory fsync. A checksum makes torn, malformed or substituted record data fail closed.

func NewFileStore

func NewFileStore(directory string) (*FileStore, error)

NewFileStore creates a lease store using an existing controller-state directory.

It does not create the directory, leaving deployment ownership and permissions explicit.

func (*FileStore) CompareAndSwapPrimaryLease

func (store *FileStore) CompareAndSwapPrimaryLease(ctx context.Context, databaseID [16]byte, previous *LeaseRecord, next LeaseRecord) (bool, error)

CompareAndSwapPrimaryLease saves a lease only when the stored record matches the expected state.

func (*FileStore) LoadPrimaryLease

func (store *FileStore) LoadPrimaryLease(ctx context.Context, databaseID [16]byte) (LeaseRecord, bool, error)

LoadPrimaryLease reads and validates the stored lease for a database.

func (*FileStore) String

func (store *FileStore) String() string

String returns the store type without exposing its directory.

type Grant

type Grant struct {
	Certificate string
	Record      LeaseRecord
	RetryAfter  time.Time
}

Grant returns a signed lease, its saved controller record, and any required handoff delay.

RetryAfter is set only with ErrLeaseActive.

type GrantRequest

type GrantRequest struct {
	DatabaseID     [16]byte
	Owner          string
	CommitSequence uint64
}

GrantRequest identifies the database owner and source position requesting a write lease.

Owner must derive from authenticated controller-side identity, never an application request.

type Guard

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

Guard permits database writes only while a valid certificate authorizes its configured owner.

It implements meldbase.PrimaryWriteFence and meldbase.FollowerPromotionFenceBinder. Install is used for an already elected primary; follower promotion binds the certificate returned by the external promotion authority automatically.

func NewGuard

func NewGuard(publicKey ed25519.PublicKey, options GuardOptions) (*Guard, error)

NewGuard creates a write guard that rejects writes until a valid certificate is installed.

Install or follower promotion binds the certificate.

func (*Guard) BindFollowerPromotion

func (guard *Guard) BindFollowerPromotion(ctx context.Context, fence meldbase.FollowerPromotionFence) error

BindFollowerPromotion verifies that the authority's opaque epoch is a certificate for this exact promotion point before enabling local writes.

func (*Guard) Install

func (guard *Guard) Install(encoded string) error

Install verifies and atomically replaces the locally accepted lease.

An external controller renews authority by signing a new certificate and calling Install before the old one expires. Revocation clears it locally.

func (*Guard) LeaseStatus

func (guard *Guard) LeaseStatus() GuardLeaseStatus

LeaseStatus returns the installed lease position and time window without allocating.

It runs in O(1) and is for a renewal supervisor's scheduling and must never replace the hot-path write fence, which validates the certificate again for every commit.

func (*Guard) Revoke

func (guard *Guard) Revoke()

Revoke immediately blocks local database writes.

It is safe to call more than once. A partitioned old primary remains bounded by NotAfter even if it never receives this local revocation.

func (*Guard) ValidatePrimaryWrite

func (guard *Guard) ValidatePrimaryWrite(request meldbase.PrimaryWriteFenceRequest) error

ValidatePrimaryWrite checks that the installed lease permits the next database commit.

It performs no I/O, allocation or controller call; its only synchronization is an RLock around the installed immutable certificate.

type GuardLeaseStatus

type GuardLeaseStatus struct {
	Installed      bool
	Epoch          uint64
	CommitSequence uint64
	NotBefore      time.Time
	NotAfter       time.Time
}

GuardLeaseStatus reports the installed lease position and time window for renewal scheduling.

It contains no certificate text or owner identity. Installed does not imply the lease is still time-valid; callers evaluate NotAfter against their own trusted local clock.

type GuardOptions

type GuardOptions struct {
	Owner            string
	MaxLeaseDuration time.Duration
	Clock            func() time.Time
}

GuardOptions sets the local write owner, maximum lease duration, and clock.

Owner is a stable, controller-defined process identity; it is not supplied by an untrusted client. Clock is intended for deterministic tests; production callers leave it nil.

type LeaseRecord

type LeaseRecord struct {
	DatabaseID     [16]byte
	Owner          string
	Epoch          uint64
	CommitSequence uint64
	NotAfter       time.Time
	Revoked        bool
}

LeaseRecord stores the controller's write owner, lease expiry, and source position for one database.

It is deliberately distinct from a rollback anchor: Owner/Epoch move forward and a lease may expire, while a rollback anchor is a permanent lower bound on recoverable history.

type LeaseStore

type LeaseStore interface {
	LoadPrimaryLease(context.Context, [16]byte) (LeaseRecord, bool, error)
	CompareAndSwapPrimaryLease(context.Context, [16]byte, *LeaseRecord, LeaseRecord) (bool, error)
}

LeaseStore reads and conditionally replaces a database's controller lease record.

Implement it with a quorum-backed transactional store in production. Load and CompareAndSwap must be linearizable for a database identity; a local file or MemoryStore is useful only for deterministic development/testing.

previous is nil only when the record is expected not to exist. A false swap result is a concurrent state change, not a successful no-op.

type MemoryStore

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

MemoryStore is a linearizable in-process LeaseStore for tests and local deterministic demos.

It must not be used as a production quorum store.

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore creates an empty lease store for tests and local demos.

func (*MemoryStore) CompareAndSwapPrimaryLease

func (store *MemoryStore) CompareAndSwapPrimaryLease(ctx context.Context, databaseID [16]byte, previous *LeaseRecord, next LeaseRecord) (bool, error)

CompareAndSwapPrimaryLease replaces an in-memory lease when it matches the expected state.

func (*MemoryStore) LoadPrimaryLease

func (store *MemoryStore) LoadPrimaryLease(ctx context.Context, databaseID [16]byte) (LeaseRecord, bool, error)

LoadPrimaryLease reads a database's lease under the memory store lock.

type PrimaryOptions

type PrimaryOptions struct {
	OpenOptions     meldbase.OpenOptions
	PublicKey       ed25519.PublicKey
	GuardOptions    GuardOptions
	RenewalClient   RenewalClient
	RequestTimeout  time.Duration
	RetryInterval   time.Duration
	KeepLeaseOnStop bool
}

PrimaryOptions configures a primary database and its write lease renewal.

The database uses the exact Guard instance its Renewer will update. OpenOptions remains available for storage settings, but PrimaryWriteFence and Follower are owned by this constructor and must be left unset/false.

type PrimaryRuntime

type PrimaryRuntime struct {
	DB      *meldbase.DB
	Guard   *Guard
	Renewer *Renewer
}

PrimaryRuntime groups a primary database with its write guard and lease renewer.

The database starts closed to writes because Guard starts without a certificate; call Renew once explicitly or Run under a long-lived supervisor before serving mutations.

func OpenPrimary

func OpenPrimary(path string, options PrimaryOptions) (*PrimaryRuntime, error)

OpenPrimary opens a primary database with a shared write guard and lease renewer.

The new Guard is the database's only PrimaryWriteFence. It does not contact the controller or start a goroutine; callers choose the startup ordering and context by calling Renew or Run.

func (*PrimaryRuntime) Close

func (runtime *PrimaryRuntime) Close() error

Close immediately closes local primary admission before closing the database.

func (*PrimaryRuntime) Renew

func (runtime *PrimaryRuntime) Renew(ctx context.Context) error

Renew acquires and installs a write lease through the primary's matching renewer.

func (*PrimaryRuntime) Run

func (runtime *PrimaryRuntime) Run(ctx context.Context) error

Run renews the primary's write lease until the context ends.

By default, returning revokes the local Guard.

type PromotionAuthority

type PromotionAuthority struct {
	Authority *Authority
	Owner     string
	Readiness PromotionReadiness
}

PromotionAuthority adapts a controller Authority to meldbase.FollowerPromotionAuthority.

Construct it with the authenticated target process owner identity; it never accepts that identity from a replication frame.

func (PromotionAuthority) AuthorizeFollowerPromotion

func (authority PromotionAuthority) AuthorizeFollowerPromotion(ctx context.Context, request meldbase.FollowerPromotionRequest) (meldbase.FollowerPromotionFence, error)

AuthorizeFollowerPromotion obtains a lease certificate after checking the follower's readiness.

type PromotionReadiness

type PromotionReadiness interface {
	VerifyFollowerPromotion(context.Context, meldbase.FollowerPromotionRequest, LeaseRecord, bool) error
}

PromotionReadiness checks whether a follower can be promoted under the current controller state.

The check uses the controller state observed by the same Authority CAS attempt. A production implementation normally verifies durable replication receipt/ack evidence and any required application recovery policy. Owner and epoch fencing alone cannot prove that an asynchronous follower contains all writes from the former primary.

type PromotionReadinessFunc

type PromotionReadinessFunc func(context.Context, meldbase.FollowerPromotionRequest, LeaseRecord, bool) error

PromotionReadinessFunc adapts a function to PromotionReadiness.

func (PromotionReadinessFunc) VerifyFollowerPromotion

func (function PromotionReadinessFunc) VerifyFollowerPromotion(ctx context.Context, request meldbase.FollowerPromotionRequest, record LeaseRecord, exists bool) error

VerifyFollowerPromotion runs the supplied readiness check or rejects a missing function.

type QuorumReplica

type QuorumReplica struct {
	MemberID string
	Store    LeaseStore
}

QuorumReplica pairs a configured controller member with its lease store adapter.

Store typically represents an authenticated HTTPS/mTLS RPC client. MemberID must be stable configuration, not a value supplied by a request or endpoint response.

type QuorumStats

type QuorumStats struct {
	Replicas         uint64
	Quorum           uint64
	Loads            uint64
	CompareAndSwaps  uint64
	EndpointFailures uint64
	QuorumFailures   uint64
	Conflicts        uint64
}

QuorumStats reports aggregate lease-store operations, failures, and conflicts.

It omits endpoint and database identities.

type QuorumStore

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

QuorumStore reads and updates lease records only when a strict majority agrees.

Member stores must be linearizable. A successful CAS is persisted on a strict majority. Reads accept only a record (or absence) held identically by a strict majority; they never choose a maximum from crossed or partial histories.

This is the quorum layer, not a membership/election system. Deployments must still use separately operated failure domains and an authenticated adapter for every replica.

func NewQuorumStore

func NewQuorumStore(replicas []QuorumReplica) (*QuorumStore, error)

NewQuorumStore validates member identities and creates a majority-based lease store.

It accepts one development member or an odd number of at least three members. Duplicate IDs are rejected so endpoint aliases cannot create a fake quorum.

func (*QuorumStore) CompareAndSwapPrimaryLease

func (store *QuorumStore) CompareAndSwapPrimaryLease(ctx context.Context, databaseID [16]byte, previous *LeaseRecord, next LeaseRecord) (bool, error)

CompareAndSwapPrimaryLease succeeds when a strict majority accepts the requested lease change.

func (*QuorumStore) LoadPrimaryLease

func (store *QuorumStore) LoadPrimaryLease(ctx context.Context, databaseID [16]byte) (LeaseRecord, bool, error)

LoadPrimaryLease returns a lease record or absence agreed on by a strict majority.

func (*QuorumStore) Stats

func (store *QuorumStore) Stats() QuorumStats

Stats reports no per-member identity so it is safe for aggregate telemetry.

func (*QuorumStore) String

func (store *QuorumStore) String() string

String describes the replica count and majority size without exposing member identities.

type RenewalClient

type RenewalClient interface {
	Grant(context.Context, [16]byte, uint64) (Grant, error)
}

RenewalClient requests a controller write lease for a database position.

authorityhttp.Client implements it. Owner authentication stays in that transport and is never an argument to a renewal request.

type Renewer

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

Renewer keeps a primary's write lease current without holding the database writer during controller requests.

It is not a leader-election, replication-ack or promotion mechanism: its commit sequence snapshot is a controller checkpoint and cannot establish follower completeness after a source failure.

func NewRenewer

func NewRenewer(options RenewerOptions) (*Renewer, error)

NewRenewer creates a lease renewer after checking its dependencies and timing settings.

func (*Renewer) Renew

func (renewer *Renewer) Renew(ctx context.Context) error

Renew installs a fresh write lease from the controller for the current database position.

The database writer is never held while client.Grant is in progress. A failed request leaves an existing lease in place until its normal local expiry; it does not extend authority and does not silently reopen an initially closed guard.

func (*Renewer) Run

func (renewer *Renewer) Run(ctx context.Context) error

Run keeps the local write lease renewed until the context ends.

It renews immediately, then schedules the next request at one third of the current certificate duration before expiry. It retries failures at the bounded RetryInterval. On context completion it revokes the local guard by default, making deliberate supervisor shutdown fail closed immediately.

func (*Renewer) Stats

func (renewer *Renewer) Stats() RenewerStats

Stats returns an O(1), identity-free aggregate snapshot.

It is designed for an external sampler rather than calls from the database write path.

type RenewerOptions

type RenewerOptions struct {
	DB              *meldbase.DB
	Guard           *Guard
	Client          RenewalClient
	RequestTimeout  time.Duration
	RetryInterval   time.Duration
	KeepLeaseOnStop bool
	Clock           func() time.Time
}

RenewerOptions sets the database, write guard, controller client, and renewal timing.

DB must be the same database that was opened with Guard as its PrimaryWriteFence. The API cannot infer that pointer equality across the Meldbase boundary, so this deployment wiring is explicit and checked at least for a configured fence.

KeepLeaseOnStop is deliberately false by default: Run revokes the local guard when its supervisory context ends, so a stopped supervisor cannot leave a process writable until natural certificate expiry. Set it only when another supervisor takes over with the same process and guard lifecycle.

type RenewerStats

type RenewerStats struct {
	Attempts            uint64
	Succeeded           uint64
	Failed              uint64
	InstallFailed       uint64
	ConsecutiveFailures uint64
	Running             bool
}

RenewerStats reports renewal outcomes and whether the renewal loop is running.

It intentionally contains no certificate, endpoint, owner or database ID.

Jump to

Keyboard shortcuts

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