Documentation
¶
Overview ¶
Package lockd exposes the Go APIs behind the single-binary coordination plane that combines exclusive leases, atomic JSON state (with search/index), binary attachments, and an at-least-once queue. The server runs cleanly as PID 1 or can be embedded as a library; the same storage abstraction powers disk, S3/MinIO, Azure Blob, and in-memory backends with optional envelope encryption.
Copyright (C) 2025 Michel Blomgren <https://pkt.systems>
Running a server ¶
The server listens on the network specified by Config.ListenProto (default tcp) and address Config.Listen. Mutual TLS is enabled by default.
cfg := lockd.Config{
Store: "s3://locks/prod",
Listen: ":9341",
ListenProto: "tcp",
BundlePath: "/etc/lockd/server.pem",
DefaultNamespace: "analytics",
}
srv, err := lockd.NewServer(cfg)
if err != nil { log.Fatal(err) }
go func() {
if err := srv.Start(); err != nil {
log.Fatalf("lockd: %v", err)
}
}()
defer func() {
if err := srv.Shutdown(context.Background()); err != nil {
log.Printf("lockd shutdown: %v", err)
}
}()
Disk/NFS backends use a log-structured store with durable group commit. Batching is driven by natural backpressure: fsync occurs for each batch and the queue builds only while prior fsyncs are in-flight. LogstoreCommitMaxOps caps batch size. LogstoreSegmentSize controls when segment files roll. Background snapshot compaction is enabled by default on disk/NFS. It compacts sealed history only, installs snapshots atomically, and deletes obsolete files after a grace period. Tune it with LogstoreCompactionEnabled, LogstoreCompactionInterval, LogstoreCompactionMinSegments, LogstoreCompactionMinReclaimBytes, LogstoreCompactionDeleteGrace, LogstoreCompactionMaxIOBytesPerSec, and DisableLogstoreCompactionThrottling. DiskLockFileCacheSize caps cached lockfile descriptors for disk/NFS (default 2048; set negative to disable caching). Hot state reads can be cached in-process via StateCacheBytes (default 64 MiB; set 0 to disable). QueryDocPrefetch controls parallel fetch depth for query return=documents (default 8; set 1 to disable). In HA concurrent mode, single-writer optimizations are disabled.
cfg := lockd.Config{
Store: "disk:///var/lib/lockd-data",
LogstoreCommitMaxOps: 128, // disk/NFS only
LogstoreSegmentSize: 64 << 20, // disk/NFS only (bytes)
LogstoreCompactionInterval: 30 * time.Minute, // disk/NFS only
LogstoreCompactionDeleteGrace: 15 * time.Minute, // disk/NFS only
LogstoreCompactionMaxIOBytesPerSec: 8 << 20, // disk/NFS only
DiskLockFileCacheSize: 2048, // disk/NFS only
StateCacheBytes: 64 << 20, // cache hot state payloads
QueryDocPrefetch: 8, // return=documents prefetch depth
}
The CLI mirrors this with --logstore-commit-max-ops, --logstore-segment-size, --logstore-compaction, --logstore-compaction-interval, --logstore-compaction-min-segments, --logstore-compaction-min-reclaim-size, --logstore-compaction-delete-grace, --logstore-compaction-max-io-bytes-per-sec, --disable-logstore-compaction-throttling, --disk-lock-file-cache-size, --state-cache-bytes, and --query-doc-prefetch.
HA modes ¶
When multiple lockd servers share the same backend, HAMode controls concurrent vs coordinated behaviour. HAMode="failover" (default) uses a lease stored under the internal .ha/activelease key to elect a single active writer; passive nodes return HTTP 503 so clients can retry another endpoint. HAMode="concurrent" enables multi-writer semantics. HAMode="single" disables HA coordination entirely and assumes the backend is owned by one server process. HAMode="auto" starts in single-writer mode and promotes to failover when it observes another live node. HALeaseTTL controls the lease duration in failover mode and heartbeat cadence in auto mode. On backends without native single-writer detection, HASinglePresenceTTL controls how long a single-mode presence record fences peers.
cfg := lockd.Config{
Store: "disk:///var/lib/lockd-data",
HAMode: "failover",
HALeaseTTL: 10 * time.Second,
HASinglePresenceTTL: 5 * time.Minute, // object-store style backends only
}
The CLI mirrors this with --ha, --ha-lease-ttl, and --ha-single-presence-ttl.
Namespaces partition keys and metadata. When callers omit the namespace, the server falls back to Config.DefaultNamespace (default "default"). Setting the field on Config, providing Namespace in api.AcquireRequest, or configuring clients via client.WithDefaultNamespace keeps each workload’s state isolated under its own prefix. Namespaces that start with a dot are reserved for lockd internals (e.g. .txns stores transaction records) and are rejected by both the HTTP layer and the core service. Always use user-defined namespaces that do not begin with '.'.
Unix domain sockets ¶
For same-host sidecars you can serve over a Unix socket by setting ListenProto to "unix". Clean-up is automatic and mTLS can be disabled when the connection never leaves the machine.
cfg := lockd.Config{
Store: "mem://",
ListenProto: "unix",
Listen: "/var/run/lockd.sock",
DisableMTLS: true,
}
handle, err := lockd.StartServer(ctx, cfg)
if err != nil { log.Fatal(err) }
defer handle.Stop(context.Background())
Client SDK ¶
The Go client (pkt.systems/lockd/client) wraps the HTTP API. The base URL decides the transport:
- https://host:9341 – production mTLS connection (default)
- http://host:9341 – plain HTTP for trusted networks or local testing
- unix:///path/to/lockd.sock – Unix-domain sockets (requires DisableMTLS or supplying a client bundle)
Example:
cli, err := client.New("https://lockd.example.com")
if err != nil { log.Fatal(err) }
sess, err := cli.Acquire(ctx, api.AcquireRequest{
Namespace: "orders-v2",
Key: "orders",
Owner: "worker-1",
TTLSeconds: 30,
BlockSecs: client.BlockWaitForever,
// Optional: join an existing transaction across keys.
TxnID: existingTxnID,
})
if err != nil { log.Fatal(err) }
defer sess.Close()
var state struct {
Hello string
World string
Counter int
}
if err := sess.Load(ctx, &state); err != nil { log.Fatal(err) }
state.Counter++
if err := sess.Save(ctx, state); err != nil { log.Fatal(err) }
For create-only initialization, set AcquireRequest.IfNotExists=true. When state already exists for the key, acquire fails with error code "already_exists". The SDK exposes both helper styles: client.IsAlreadyExists(err) and errors.Is(err, client.ErrAlreadyExists). You only need one check style; for SDK-returned acquire errors they are equivalent.
_, err = cli.Acquire(ctx, api.AcquireRequest{
Namespace: "orders-v2",
Key: "orders",
Owner: "initializer",
TTLSeconds: 30,
BlockSecs: client.BlockNoWait,
IfNotExists: true,
})
if err != nil && client.IsAlreadyExists(err) {
// Another worker initialized the key first.
}
The lease session carries the TxnID minted by Acquire. All lease-bound mutations (Update/Remove/UpdateMetadata/Release/attachments) require that transaction id. The SDK wires X-Txn-ID automatically when you use LeaseSession; custom HTTP clients must supply it (and include txn_id in the release request body).
The client tracks fencing tokens automatically; reusing the same Client instance ensures follow-up KeepAlive/Get/Update/Release calls include the freshest X-Fencing-Token. For multi-process flows the CLI exports the token via LOCKD_CLIENT_FENCING_TOKEN, and your program can register it manually with Client.RegisterLeaseToken.
Shutdown sequencing is controlled via Config.DrainGrace and Config.ShutdownTimeout. Draining gives existing lease holders time to wrap up (default 10 s) before the HTTP server begins closing connections; the timeout caps the combined drain + HTTP shutdown interval (default 10 s). The defaults mirror the CLI flags (--drain-grace, --shutdown-timeout) and can be disabled by setting them to 0. Each server splits the budget 80/20 so a 10 s timeout reserves ~8 s for draining and ~2 s for http.Server.Shutdown.
Sweeping is split into two paths: (1) transparent cleanup on relevant ops (e.g., if an acquire encounters an expired lease) and (2) an idle maintenance sweeper that runs only after a period of inactivity. The idle sweeper is rate-limited (max ops and max runtime) and can be configured to pause between operations to reduce backend pressure. Transaction replay has its own throttle so active traffic can kick replay without inheriting the idle sweeper cadence. Configure these in the server SDK with:
cfg := lockd.Config{
Store: "aws://lockd-prod",
SweeperInterval: 5 * time.Minute, // idle sweep tick
IdleSweepGrace: 5 * time.Minute, // idle time before a sweep can start
IdleSweepOpDelay: 100 * time.Millisecond,
IdleSweepMaxOps: 1000,
IdleSweepMaxRuntime: 30 * time.Second,
TxnReplayInterval: 5 * time.Second, // throttle for replay on active ops
}
To disable the idle sweeper entirely, set SweeperInterval <= 0 (replay throttling is independent and controlled by TxnReplayInterval).
Queue transactions use a dedicated worklist to avoid list scans when a queue message is enlisted in a transaction decision. When a commit/rollback includes a queue message participant, the TC records a small per-queue decision list under .txn-queue-decisions. Dequeue checks that worklist at most once per cache window (no background sweeps) and applies up to a capped number of items, making rollback-visible messages reappear after restarts without scanning the queue. Non-transactional queues do not write these markers, so they incur no extra IO beyond the cached check.
Configure the worklist behavior with:
cfg := lockd.Config{
QueueDecisionCacheTTL: 60 * time.Second, // cache empty worklist checks
QueueDecisionMaxApply: 50, // max items applied per dequeue
QueueDecisionApplyTimeout: 2 * time.Second, // time budget per dequeue apply
}
The CLI mirrors these as --queue-decision-cache-ttl, --queue-decision-max-apply, and --queue-decision-apply-timeout.
The Go client and CLI are drain-aware by default: when the server emits the Shutdown-Imminent header, the SDK auto-releases leases once in-flight work is done. Opt out by using client.WithDrainAwareShutdown(false) or passing --drain-aware-shutdown=false / LOCKD_CLIENT_DRAIN_AWARE=false to the CLI.
Multi-host deployments can construct the client with multiple base URLs via client.NewWithEndpoints([]string{...}). The SDK rotates through the provided endpoints on failure, carrying the same bounded retry budget so that reacquire attempts remain deterministic even when the primary server drops mid-request.
Acquire-for-update workflow ¶
AcquireForUpdate wraps the usual acquire → get → update → release cycle in a single helper. Callers supply a function that receives an AcquireForUpdateContext; the context exposes the current StateSnapshot (so the handler can stream or decode the JSON) and forwards convenience methods like Update/UpdateBytes/Save/Remove. The helper keeps the lease alive in the background while the handler executes and always releases the lease when the handler returns. Both LeaseSession and AcquireForUpdateContext expose Remove helpers that delete the JSON blob while holding the lease. They honour the same conditional headers (X-If-Version, X-If-State-ETag) as updates and clear the server-side metadata when the delete succeeds.
Handshake failures (for example lease_required during the initial Get) consume the same bounded retry budget controlled by client.WithAcquireFailureRetries and client.WithAcquireBackoff. Once the handler starts running, further errors are surfaced immediately—the typical pattern is to return the error (acquire-for-update propagates it) and decide whether to retry at a higher level.
AcquireForUpdate forwards the acquire request unchanged. If IfNotExists=true and the key already exists, it returns already_exists and does not invoke the handler.
Explicit Release calls elsewhere still treat lease_required as success so teardown never hangs even if the lease has already been reclaimed.
State attachments ¶
Keys can carry multiple named binary attachments. Attachments are staged under the lease transaction just like JSON state updates: attach files while holding the lease, and they become visible to public reads once the lease is released (commit). Attachments are stored under state/<key>/attachments/<id> and flow through the same encryption-at-rest pipeline as state/queue payloads. Lease-bound attachment operations require X-Txn-ID; public reads do not.
Use ListAttachments/RetrieveAttachment on the lease to inspect staged files, and DeleteAttachment/DeleteAllAttachments to stage removals that apply on release (rollbacks discard staged changes).
lease, err := cli.Acquire(ctx, api.AcquireRequest{Key: "orders", Owner: "worker-1", TTLSeconds: 30})
if err != nil { log.Fatal(err) }
defer lease.Close()
if _, err := lease.Attach(ctx, client.AttachRequest{
Name: "invoice.pdf",
ContentType: "application/pdf",
Body: fileReader,
}); err != nil {
log.Fatal(err)
}
if err := lease.Release(ctx); err != nil { log.Fatal(err) }
// Public reads can list/retrieve attachments after release.
resp, err := cli.Get(ctx, "orders")
if err != nil { log.Fatal(err) }
defer resp.Close()
attachments, err := resp.ListAttachments(ctx)
if err != nil { log.Fatal(err) }
_ = attachments
Queue service ¶
lockd includes an at-least-once queue built on the same storage backends, encryption pipeline, and namespace layout as the lease/state surface. The HTTP API exposes /v1/queue/enqueue, /v1/queue/dequeue, /v1/queue/dequeue/state, /v1/queue/subscribe, /v1/queue/ack, /v1/queue/nack, and /v1/queue/extend. Namespaces are required for every queue call; omitting the field falls back to Config.DefaultNamespace, and the Go client/CLI mirror the same default/override behaviour (LOCKD_QUEUE_NAMESPACE for CLI flows).
Producers stream payloads (optionally zero-length) alongside JSON metadata describing queue, delay_seconds, visibility_timeout_seconds, ttl_seconds, max_attempts, and arbitrary attributes. Consumers issue dequeue requests with an owner identity; responses stream message metadata and payload via multipart/related parts so large blobs never buffer in RAM. State-aware dequeues acquire a workflow lease in the same request and expose helpers that keep message + state fencing tokens aligned when acking, nacking, or extending visibility.
The queue dispatcher multiplexes watchers/pollers across namespaces and storage backends. Disk/mem stores use native notifications (inotify / in-process) when available and fall back to polling when disabled or running on NFS. Object stores rely on the same observed-key tracking used by the lock surface so stale reads never reset metadata.
Perimeter defence (LSF + QRF) ¶
Each server embeds a **Local Security Force (LSF)** observer that samples host metrics (memory, swap, load averages, CPU) plus per-endpoint inflight counters, and a **Quick Reaction Force (QRF)** controller that applies adaptive back-pressure. When the QRF soft-arms or engages, lockd paces requests server-side by waiting for a computed delay before continuing. Only if the delay exceeds the configured max wait does lockd respond with HTTP 429, surface a Retry-After hint, and tag the response with X-Lockd-QRF-State. The Go client honours these signals automatically; other clients should do the same to keep queues draining while the perimeter defence recovers. Configuration knobs and workflow details live in docs/QRF.md. By default the controller leans on host-wide memory budgets (80 % soft / 90 % hard) and load-average multipliers derived from the LSF baseline (4×/8×) while queue/lock/query inflight guards remain disabled unless configured explicitly.
Telemetry ¶
Traces are exported over OTLP when Config.OTLPEndpoint is set (gRPC by default; use grpc://, grpcs://, http://, or https:// to force a transport). Metrics are exposed via a Prometheus scrape endpoint when Config.MetricsListen is non-empty (for example :9464). Runtime profiling metrics (goroutines, heap, scheduler latency) are opt-in via Config.EnableProfilingMetrics. A pprof debug listener can be exposed with Config.PprofListen. All three can be enabled together or independently:
cfg := lockd.Config{
Store: "disk:///var/lib/lockd",
OTLPEndpoint: "localhost:4317",
MetricsListen: ":9464",
EnableProfilingMetrics: true,
PprofListen: ":6060",
}
srv, err := lockd.NewServer(cfg)
if err != nil { log.Fatal(err) }
defer srv.Close(context.Background())
Embedded servers can override metrics via lockd.WithMetricsListen when using helpers such as StartServer or client/inprocess.
Embedding and helpers ¶
StartServer launches a server in a goroutine, waits for readiness, and returns a handle with a Stop method. It’s useful when wiring lockd into existing processes or sidecars. The client/inprocess package builds on top of it, starting an embedded server (MTLS disabled) and returning a ready-to-use client facade:
cfg := lockd.Config{Store: "mem://", DisableMTLS: true}
inproc, err := inprocess.New(ctx, cfg)
if err != nil { log.Fatal(err) }
defer inproc.Close(ctx)
sess, err := inproc.Acquire(ctx, api.AcquireRequest{Key: "demo", Owner: "inproc", TTLSeconds: 20})
if err != nil { log.Fatal(err) }
defer sess.Close()
Storage backends ¶
Configure the storage layer via Config.Store:
- mem:// – in-memory (tests and local experimentation)
- disk:///var/lib/lockd-data – SSD/NVMe-oriented disk backend with optional retention
- azure://account/container – Azure Blob Storage (Shared Key or SAS auth)
- aws://bucket/prefix – AWS S3 (uses standard AWS credential sources, requires region)
- s3://host:port/bucket – MinIO or other S3-compatible stores (TLS on unless ?insecure=1)
JSON uploads are compacted using the selected compactor (see Config.JSONUtil), and large payloads spill to disk after Config.SpoolMemoryThreshold.
LQL query & mutation language ¶
Both the CLI and HTTP APIs share a common selector/mutation DSL implemented by pkt.systems/lql. Selectors accept JSON Pointer field paths (and.eq{field=/status,value=open}, or.1.range{field=/progress/percent,gte=50}), while mutations cover assignments, arithmetic (++, --, =+5), removals (rm:/delete:), time: aliases for RFC3339 timestamps, and brace shorthand that fans out to nested keys. Examples:
lockd client set --key ledger \
'/data{/hello key="mars traveler",/count++}' \
/meta/previous=world \
time:/meta/processed=NOW
Keys follow RFC 6901 JSON Pointer semantics (leading /; escape / as ~1 and ~ as ~0). Commas/newlines can be mixed freely—making it practical to paste production-style JSON paths into CLI tests, Go unit tests, or query strings (/v1/query?and.eq{...}).
Consult README.md for detailed guidance, additional examples, and operational considerations (TLS, auth bundles, environment variables).
Index ¶
- Constants
- func BuildAzureConfig(cfg Config) (azurestore.Config, error)
- func CreateCABundle(req CreateCABundleRequest) ([]byte, error)
- func CreateCABundleFile(req CreateCABundleFileRequest) error
- func CreateClientBundle(req CreateClientBundleRequest) ([]byte, error)
- func CreateClientBundleFile(req CreateClientBundleFileRequest) error
- func CreateServerBundle(req CreateServerBundleRequest) ([]byte, error)
- func CreateServerBundleFile(req CreateServerBundleFileRequest) error
- func CreateTCClientBundle(req CreateTCClientBundleRequest) ([]byte, error)
- func CreateTCClientBundleFile(req CreateTCClientBundleFileRequest) error
- func DefaultBundlePath() (string, error)
- func DefaultCAPath() (string, error)
- func DefaultConfigDir() (string, error)
- func DefaultQueueMaxConsumers() int
- func DefaultTCTrustDir() (string, error)
- func NewTestingLogger(t testing.TB, level pslog.Level) pslog.Logger
- func NormalizeNamespace(ns, fallback string) (string, error)
- func OpenBackend(cfg Config, crypto *storage.Crypto) (storage.Backend, error)
- func ResolveClientBundlePath(role ClientBundleRole, explicitPath string) (string, error)
- func ResolveClientBundlePathWithHint(role ClientBundleRole, explicitPath, hint string) (string, error)
- func SPIFFEURIForRole(role ClientBundleRole, name string) (*url.URL, error)
- func SPIFFEURIForServer(nodeID string) (*url.URL, error)
- func ValidJSONUtils() []string
- type AWSConfigResult
- type ChaosConfig
- type ClientBundleRole
- type CloseOption
- type Config
- type CreateCABundleFileRequest
- type CreateCABundleRequest
- type CreateClientBundleFileRequest
- type CreateClientBundleRequest
- type CreateServerBundleFileRequest
- type CreateServerBundleRequest
- type CreateTCClientBundleFileRequest
- type CreateTCClientBundleRequest
- type CredentialSummary
- type DiskConfigResult
- type DrainLeasesPolicy
- type Option
- func WithBackend(b storage.Backend) Option
- func WithClock(c clock.Clock) Option
- func WithDefaultCloseOptions(opts ...CloseOption) Option
- func WithLSFLogInterval(interval time.Duration) Option
- func WithLogger(l pslog.Logger) Option
- func WithMetricsListen(addr string) Option
- func WithOTLPEndpoint(endpoint string) Option
- func WithPprofListen(addr string) Option
- func WithProfilingMetrics(enabled bool) Option
- func WithTCFanoutGate(gate txncoord.FanoutGate) Option
- func WithTCLeaderLeaseTTL(ttl time.Duration) Option
- type S3ConfigResult
- type Server
- func (s *Server) Abort(ctx context.Context) error
- func (s *Server) Close(opts ...CloseOption) error
- func (s *Server) ForceQRFObserve(snapshot qrf.Snapshot)
- func (s *Server) Handler() http.Handler
- func (s *Server) LastServeError() error
- func (s *Server) ListenerAddr() net.Addr
- func (s *Server) QRFState() qrf.State
- func (s *Server) QRFStatus() qrf.Status
- func (s *Server) Shutdown(ctx context.Context) error
- func (s *Server) ShutdownWithOptions(ctx context.Context, opts ...CloseOption) error
- func (s *Server) Start() error
- func (s *Server) WaitUntilReady(ctx context.Context) error
- type ServerHandle
- type TestMTLSCredentials
- type TestServer
- func (ts *TestServer) Abort(ctx context.Context) error
- func (ts *TestServer) Addr() net.Addr
- func (ts *TestServer) Backend() storage.Backend
- func (ts *TestServer) NewClient(opts ...client.Option) (*client.Client, error)
- func (ts *TestServer) NewEndpointsClient(endpoints []string, opts ...client.Option) (*client.Client, error)
- func (ts *TestServer) NewHTTPClient() (*http.Client, error)
- func (ts *TestServer) Stop(ctx context.Context, opts ...CloseOption) error
- func (ts *TestServer) TestMTLSCredentials() TestMTLSCredentials
- func (ts *TestServer) URL() string
- type TestServerOption
- func WithTestBackend(backend storage.Backend) TestServerOption
- func WithTestChaos(cfg *ChaosConfig) TestServerOption
- func WithTestClientOptions(opts ...client.Option) TestServerOption
- func WithTestClock(c clock.Clock) TestServerOption
- func WithTestCloseDefaults(opts ...CloseOption) TestServerOption
- func WithTestConfig(cfg Config) TestServerOption
- func WithTestConfigFunc(fn func(*Config)) TestServerOption
- func WithTestListener(proto, address string) TestServerOption
- func WithTestLogger(logger pslog.Logger) TestServerOption
- func WithTestLoggerFromTB(t testing.TB, level pslog.Level) TestServerOption
- func WithTestLoggerTB(t testing.TB) TestServerOption
- func WithTestMTLS() TestServerOption
- func WithTestMTLSCredentials(creds TestMTLSCredentials) TestServerOption
- func WithTestStartTimeout(d time.Duration) TestServerOption
- func WithTestStore(store string) TestServerOption
- func WithTestTCFanoutGate(gate txncoord.FanoutGate) TestServerOption
- func WithTestTCLeaderLeaseTTL(ttl time.Duration) TestServerOption
- func WithTestUnixSocket(path string) TestServerOption
- func WithoutTestClient() TestServerOption
- func WithoutTestMTLS() TestServerOption
Constants ¶
const ( // SPIFFESDKPrefix is the SPIFFE URI prefix for SDK client identities. SPIFFESDKPrefix = "spiffe://lockd/sdk/" // SPIFFETCPrefix is the SPIFFE URI prefix for transaction coordinator client identities. SPIFFETCPrefix = "spiffe://lockd/tc/" // SPIFFEServerPrefix is the SPIFFE URI prefix for server identities. SPIFFEServerPrefix = "spiffe://lockd/server/" )
const ( // JSONUtilLockd selects the native lockd streaming JSON compactor. JSONUtilLockd = "lockd" // JSONUtilJSONV2 enables the Go 1.25 json/v2 tokenizer pipeline. JSONUtilJSONV2 = "jsonv2" // JSONUtilStdlib opts into the encoding/json standard library implementation. JSONUtilStdlib = "stdlib" )
const ( // DefaultQueuePollInterval controls how often the dispatcher polls storage when no event hint exists. DefaultQueuePollInterval = 3 * time.Second // DefaultQueuePollJitter adds randomised delay to poll intervals to stagger load. DefaultQueuePollJitter = 500 * time.Millisecond // DefaultQueueResilientPollInterval bounds how often watchers fall back to polling to recover missed events. DefaultQueueResilientPollInterval = 5 * time.Minute // DefaultQueueListPageSize caps how many queue metadata entries are fetched per poll. DefaultQueueListPageSize = 128 )
const ( // DefaultPayloadSpoolMemoryThreshold defines how much JSON payload is buffered in memory before spilling to disk. DefaultPayloadSpoolMemoryThreshold = defaultSpoolMemoryThreshold // DefaultListen is the default TCP endpoint the server binds to. DefaultListen = ":9341" // DefaultListenProto controls the scheme used when no protocol is configured. DefaultListenProto = "tcp" // DefaultMetricsListen is the default metrics endpoint (Prometheus scrape). // Empty disables metrics unless explicitly configured. DefaultMetricsListen = "" // DefaultPprofListen is the default pprof debug listener (empty disables). DefaultPprofListen = "" // DefaultStore points the server at the in-memory backend when no store is provided. DefaultStore = "mem://" // DefaultHAMode controls coordination behaviour when multiple servers share a backend. DefaultHAMode = "failover" // DefaultHALeaseTTL controls how long HA failover leases are held in failover mode. DefaultHALeaseTTL = 10 * time.Second // DefaultHASinglePresenceTTL controls how long single-mode presence records // remain live on backends that require .ha advertisement. DefaultHASinglePresenceTTL = 5 * time.Minute // DefaultJSONMaxBytes bounds incoming JSON payloads. DefaultJSONMaxBytes = 100 * 1024 * 1024 // DefaultAttachmentMaxBytes bounds attachment payloads when not specified by the caller. DefaultAttachmentMaxBytes = int64(1 << 40) // DefaultDefaultTTL is the baseline lease duration handed to new acquirers. DefaultDefaultTTL = 30 * time.Second // DefaultMaxTTL is the hard ceiling enforced on user-supplied TTLs. DefaultMaxTTL = 30 * time.Minute // DefaultAcquireBlock controls how long acquire requests block before timing out. DefaultAcquireBlock = 60 * time.Second // DefaultSweeperInterval sets the tick frequency for idle maintenance sweeps. DefaultSweeperInterval = 5 * time.Minute // DefaultTxnReplayInterval throttles transaction replay sweeps on active operations. DefaultTxnReplayInterval = 5 * time.Second // DefaultQueueDecisionCacheTTL bounds how long empty queue decision checks are cached. DefaultQueueDecisionCacheTTL = 60 * time.Second // DefaultQueueDecisionMaxApply caps how many queue decision items are applied per dequeue attempt. DefaultQueueDecisionMaxApply = 50 // DefaultQueueDecisionApplyTimeout bounds how long a dequeue spends applying queued decisions. DefaultQueueDecisionApplyTimeout = 2 * time.Second // DefaultIdleSweepGrace controls how long the server must be idle before running maintenance sweeps. DefaultIdleSweepGrace = 5 * time.Minute // DefaultIdleSweepOpDelay pauses between maintenance sweep operations to reduce backend pressure. DefaultIdleSweepOpDelay = 100 * time.Millisecond // DefaultIdleSweepMaxOps caps how many sweep operations execute per run. DefaultIdleSweepMaxOps = 1000 // DefaultIdleSweepMaxRuntime caps how long a maintenance sweep run may execute. DefaultIdleSweepMaxRuntime = 30 * time.Second // DefaultDrainGrace is the grace period granted before HTTP shutdown begins. DefaultDrainGrace = 10 * time.Second // DefaultShutdownTimeout caps the total shutdown time (drain + HTTP server). DefaultShutdownTimeout = 10 * time.Second // DefaultMaxConcurrentStreams sets the default HTTP/2 MaxConcurrentStreams when not explicitly configured. DefaultMaxConcurrentStreams = 1024 // DefaultLogstoreCommitMaxOps caps how many logstore entries are committed per fsync batch. DefaultLogstoreCommitMaxOps = 4096 // DefaultLogstoreSegmentSize caps the size of a single logstore segment before rolling. DefaultLogstoreSegmentSize = int64(64 << 20) // DefaultLogstoreCompactionEnabled enables background logstore compaction on disk/NFS. DefaultLogstoreCompactionEnabled = true // DefaultLogstoreCompactionInterval controls how often the background compactor checks for eligible work. DefaultLogstoreCompactionInterval = 30 * time.Minute // DefaultLogstoreCompactionMinSegments requires at least this many sealed snapshot/segment files before compacting. DefaultLogstoreCompactionMinSegments = 2 // DefaultLogstoreCompactionMinReclaimBytes requires at least this many bytes of reclaimable sealed data before compacting. DefaultLogstoreCompactionMinReclaimBytes = int64(64 << 20) // DefaultLogstoreCompactionDeleteGrace delays deletion of obsolete compacted files so in-flight readers can finish. DefaultLogstoreCompactionDeleteGrace = 15 * time.Minute // DefaultLogstoreCompactionMaxIOBytesPerSec throttles background compaction IO on constrained systems. DefaultLogstoreCompactionMaxIOBytesPerSec = int64(8 << 20) // DefaultQueryDocPrefetch caps the number of in-flight document fetches for query return=documents. // A conservative default avoids over-saturating local disk backends; callers can raise this explicitly. DefaultQueryDocPrefetch = 1 // DefaultDiskLockFileCacheSize caps cached lockfile descriptors (disk/NFS). DefaultDiskLockFileCacheSize = 2048 // DefaultS3MaxPartSize tunes multipart uploads when writing state to S3-compatible stores. DefaultS3MaxPartSize = 16 * 1024 * 1024 // DefaultS3SmallEncryptBufferBudget caps concurrent small-object encryption buffers for S3 backends. DefaultS3SmallEncryptBufferBudget = 64 * 1024 * 1024 // DefaultStorageRetryMaxAttempts describes how many transient storage errors are retried. DefaultStorageRetryMaxAttempts = 6 // DefaultStorageRetryBaseDelay configures the base delay between storage retries. DefaultStorageRetryBaseDelay = 100 * time.Millisecond // DefaultStorageRetryMaxDelay caps the exponential backoff between storage retries. DefaultStorageRetryMaxDelay = 5 * time.Second // DefaultStorageRetryMultiplier defines the exponential backoff ratio. DefaultStorageRetryMultiplier = 2.0 // DefaultClientBlock drives the CLI client's default acquire block duration. DefaultClientBlock = 10 * time.Second // DefaultAzureEndpoint is empty so we can derive endpoints automatically for public regions. DefaultAzureEndpoint = "" // DefaultAzureEndpointPattern expands Azure account names into their HTTPS endpoint. DefaultAzureEndpointPattern = "https://%s.blob.core.windows.net" // DefaultAzureEndpointHelp documents the Azure endpoint format in CLI help output. DefaultAzureEndpointHelp = "https://<account>.blob.core.windows.net" // DefaultConfigFileName is the config file searched for when --config is omitted. DefaultConfigFileName = "config.yaml" // DefaultServerBundleName is the PEM bundle name emitted by lockd auth helpers. DefaultServerBundleName = "server.pem" )
const ( // DefaultQRFSoftDelay sets the base delay while the QRF is soft-armed. DefaultQRFSoftDelay = 50 * time.Millisecond // DefaultQRFEngagedDelay sets the base delay when the QRF is fully engaged. DefaultQRFEngagedDelay = 250 * time.Millisecond // DefaultQRFRecoveryDelay sets the base delay while recovering. DefaultQRFRecoveryDelay = 200 * time.Millisecond // DefaultQRFMaxWait caps how long a request will wait under QRF pacing before failing. DefaultQRFMaxWait = 5 * time.Second // DefaultStateCacheBytes caps in-memory cached state payloads for hot reads. DefaultStateCacheBytes = 64 << 20 // DefaultTCFanoutTimeout bounds how long the TC waits per RM apply request. DefaultTCFanoutTimeout = 5 * time.Second // DefaultTCFanoutMaxAttempts describes how many times to retry RM apply calls. DefaultTCFanoutMaxAttempts = 4 // DefaultTCFanoutBaseDelay configures the base backoff between RM apply retries. DefaultTCFanoutBaseDelay = 100 * time.Millisecond // DefaultTCFanoutMaxDelay caps RM apply retry backoff. DefaultTCFanoutMaxDelay = 2 * time.Second // DefaultTCFanoutMultiplier defines the exponential retry multiplier. DefaultTCFanoutMultiplier = 2.0 // DefaultTCDecisionRetention retains decided txn records for recovery/fan-out. DefaultTCDecisionRetention = 24 * time.Hour // DefaultQRFRecoverySamples controls how many consecutive healthy samples are required before disengaging. DefaultQRFRecoverySamples = 5 // DefaultQRFMemorySoftLimitPercent applies a soft guardrail when overall memory usage crosses this percentage. DefaultQRFMemorySoftLimitPercent = 75.0 // DefaultQRFMemoryHardLimitPercent applies a hard guardrail when overall memory usage crosses this percentage. DefaultQRFMemoryHardLimitPercent = 85.0 // DefaultQRFMemoryStrictHeadroomPercent discounts this much usage when reclaimable cache is unknown. DefaultQRFMemoryStrictHeadroomPercent = 15.0 // DefaultQRFMemorySoftLimitBytes is disabled by default; set explicitly to enforce a process RSS cap. DefaultQRFMemorySoftLimitBytes = 0 // DefaultQRFMemoryHardLimitBytes is disabled by default; set explicitly to enforce a hard process RSS cap. DefaultQRFMemoryHardLimitBytes = 0 // DefaultQRFSwapSoftLimitPercent disables swap-based QRF by default. DefaultQRFSwapSoftLimitPercent = 0.0 // DefaultQRFSwapHardLimitPercent disables swap-based QRF by default. DefaultQRFSwapHardLimitPercent = 0.0 // DefaultQRFCPUPercentSoftLimit applies a soft guardrail when CPU utilisation crosses this percentage. DefaultQRFCPUPercentSoftLimit = 70.0 // DefaultQRFCPUPercentHardLimit applies a hard guardrail when CPU utilisation crosses this percentage. DefaultQRFCPUPercentHardLimit = 85.0 // DefaultQRFLoadSoftLimitMultiplier is the baseline load-average multiplier that soft-arms the QRF. DefaultQRFLoadSoftLimitMultiplier = 4.0 // DefaultQRFLoadHardLimitMultiplier is the load-average multiplier that fully engages the QRF. DefaultQRFLoadHardLimitMultiplier = 8.0 // DefaultQRFQueueConsumerSoftLimitRatio controls the default soft ceiling for concurrent queue consumers. DefaultQRFQueueConsumerSoftLimitRatio = 0.75 // DefaultConnguardFailureThreshold is the number of suspicious connection events required before hard-blocking an IP. DefaultConnguardFailureThreshold = 5 // DefaultConnguardFailureWindow is the rolling window for suspicious connect attempts. DefaultConnguardFailureWindow = 30 * time.Second // DefaultConnguardBlockDuration controls how long an IP remains blocked. DefaultConnguardBlockDuration = 5 * time.Minute // DefaultConnguardProbeTimeout bounds the wait for early classification on plain TCP connections. DefaultConnguardProbeTimeout = 250 * time.Millisecond // DefaultLSFSampleInterval configures how frequently the LSF observer samples system metrics. DefaultLSFSampleInterval = 200 * time.Millisecond // DefaultLSFLogInterval controls how often the LSF emits lockd.lsf.sample telemetry logs. DefaultLSFLogInterval = 15 * time.Second // DefaultIndexerFlushDocs determines how many documents trigger a flush. DefaultIndexerFlushDocs = 2000 // DefaultIndexerFlushInterval bounds how long a memtable buffers before flushing. DefaultIndexerFlushInterval = 30 * time.Second )
const ( // DefaultNamespace applies when callers omit a namespace. DefaultNamespace = namespaces.Default )
Variables ¶
This section is empty.
Functions ¶
func BuildAzureConfig ¶
func BuildAzureConfig(cfg Config) (azurestore.Config, error)
BuildAzureConfig derives the Azure backend configuration.
func CreateCABundle ¶ added in v0.7.0
func CreateCABundle(req CreateCABundleRequest) ([]byte, error)
CreateCABundle generates a CA PEM bundle containing CA cert+key and kryptograf metadata material.
func CreateCABundleFile ¶ added in v0.7.0
func CreateCABundleFile(req CreateCABundleFileRequest) error
CreateCABundleFile writes a generated CA bundle to path. Parent directories are created with mode 0700 and the output file uses mode 0600.
func CreateClientBundle ¶ added in v0.7.0
func CreateClientBundle(req CreateClientBundleRequest) ([]byte, error)
CreateClientBundle generates an SDK client PEM bundle signed by the supplied CA bundle.
func CreateClientBundleFile ¶ added in v0.7.0
func CreateClientBundleFile(req CreateClientBundleFileRequest) error
CreateClientBundleFile writes a generated SDK client bundle to path. Parent directories are created with mode 0700 and the output file uses mode 0600.
func CreateServerBundle ¶ added in v0.7.0
func CreateServerBundle(req CreateServerBundleRequest) ([]byte, error)
CreateServerBundle generates a server PEM bundle signed by the supplied CA bundle.
func CreateServerBundleFile ¶ added in v0.7.0
func CreateServerBundleFile(req CreateServerBundleFileRequest) error
CreateServerBundleFile writes a generated server bundle to path. Parent directories are created with mode 0700 and the output file uses mode 0600.
func CreateTCClientBundle ¶ added in v0.7.0
func CreateTCClientBundle(req CreateTCClientBundleRequest) ([]byte, error)
CreateTCClientBundle generates a TC client PEM bundle signed by the supplied CA bundle.
func CreateTCClientBundleFile ¶ added in v0.7.0
func CreateTCClientBundleFile(req CreateTCClientBundleFileRequest) error
CreateTCClientBundleFile writes a generated TC client bundle to path. Parent directories are created with mode 0700 and the output file uses mode 0600.
func DefaultBundlePath ¶
DefaultBundlePath returns the default server bundle location.
func DefaultCAPath ¶
DefaultCAPath returns the default CA bundle location.
func DefaultConfigDir ¶
DefaultConfigDir returns the default configuration directory ($HOME/.lockd).
func DefaultQueueMaxConsumers ¶
func DefaultQueueMaxConsumers() int
DefaultQueueMaxConsumers returns an adaptive per-server consumer ceiling derived from CPU count.
func DefaultTCTrustDir ¶ added in v0.1.0
DefaultTCTrustDir returns the default directory holding trusted TC CA certificates.
func NewTestingLogger ¶
NewTestingLogger creates a pslog logger that writes through testing.TB.
func NormalizeNamespace ¶ added in v0.1.0
NormalizeNamespace delegates to namespaces.Normalize for config-level usage.
func OpenBackend ¶ added in v0.3.0
OpenBackend constructs a storage backend from the supplied config and crypto. Intended for server-side tooling; callers must Close() the returned backend.
func ResolveClientBundlePath ¶ added in v0.1.0
func ResolveClientBundlePath(role ClientBundleRole, explicitPath string) (string, error)
ResolveClientBundlePath resolves or validates the client bundle path for a role. When explicitPath is empty, it auto-discovers bundle files under the default config dir.
func ResolveClientBundlePathWithHint ¶ added in v0.7.0
func ResolveClientBundlePathWithHint(role ClientBundleRole, explicitPath, hint string) (string, error)
ResolveClientBundlePathWithHint resolves or validates the client bundle path for a role. This variant allows callers to override the CLI hint shown in error messages.
func SPIFFEURIForRole ¶ added in v0.1.0
func SPIFFEURIForRole(role ClientBundleRole, name string) (*url.URL, error)
SPIFFEURIForRole builds the default SPIFFE URI for a role and common name.
func SPIFFEURIForServer ¶ added in v0.1.0
SPIFFEURIForServer builds the SPIFFE URI for a server node identity.
func ValidJSONUtils ¶
func ValidJSONUtils() []string
ValidJSONUtils returns the supported jsonutil implementations.
Types ¶
type AWSConfigResult ¶ added in v0.3.0
type AWSConfigResult struct {
Config awsstore.Config
Credentials CredentialSummary
}
AWSConfigResult captures AWS configuration and selected credentials.
func BuildAWSConfig ¶
func BuildAWSConfig(cfg Config) (AWSConfigResult, error)
BuildAWSConfig parses aws:// URLs that target AWS S3 with regional configuration.
type ChaosConfig ¶
type ChaosConfig struct {
// Seed controls the pseudo-random source. When zero, time.Now is used.
Seed int64
// MinDelay and MaxDelay bound per-chunk latency. When both zero no delay is added.
MinDelay time.Duration
MaxDelay time.Duration
// DropProbability skips forwarding a chunk (0.0-1.0).
DropProbability float64
// ResetProbability closes both connections abruptly (0.0-1.0) evaluated per chunk.
ResetProbability float64
// DisconnectAfter closes the downstream connection after the specified duration (0 disables).
DisconnectAfter time.Duration
// BandwidthBytesPerSecond throttles throughput when >0.
BandwidthBytesPerSecond int64
// ChunkSize controls read/write batch size. Defaults to 32k if <=0.
ChunkSize int
// MaxDisconnects limits how many times DisconnectAfter is applied across connections (0 = unlimited).
MaxDisconnects int
}
ChaosConfig describes network perturbations applied by the chaos proxy.
type ClientBundleRole ¶ added in v0.1.0
type ClientBundleRole int
ClientBundleRole identifies which client bundle role to resolve.
const ( // ClientBundleRoleSDK resolves SDK client bundles. ClientBundleRoleSDK ClientBundleRole = iota // ClientBundleRoleTC resolves transaction coordinator client bundles. ClientBundleRoleTC )
func (ClientBundleRole) String ¶ added in v0.1.0
func (r ClientBundleRole) String() string
type CloseOption ¶ added in v0.1.0
type CloseOption func(*closeOptions)
CloseOption customises server shutdown semantics.
func WithDrainLeases ¶ added in v0.1.0
func WithDrainLeases(grace time.Duration) CloseOption
WithDrainLeases configures the shutdown grace period used to let existing lease holders flush state. Passing a negative duration disables draining.
func WithDrainLeasesPolicy ¶ added in v0.1.0
func WithDrainLeasesPolicy(policy DrainLeasesPolicy) CloseOption
WithDrainLeasesPolicy applies a full drain policy to shutdown calls.
func WithShutdownTimeout ¶ added in v0.1.0
func WithShutdownTimeout(d time.Duration) CloseOption
WithShutdownTimeout caps the total time allowed for drain plus HTTP shutdown. Zero disables the explicit cap and relies solely on the provided context.
type Config ¶
type Config struct {
// Listen is the server bind address (for example ":9341").
Listen string
// ListenProto selects listener type (for example "tcp").
ListenProto string
// MetricsListen is the metrics endpoint bind address; empty disables metrics.
MetricsListen string
// MetricsListenSet reports whether MetricsListen was explicitly set by caller/flags/env.
MetricsListenSet bool
// PprofListen is the pprof endpoint bind address; empty disables pprof.
PprofListen string
// PprofListenSet reports whether PprofListen was explicitly set by caller/flags/env.
PprofListenSet bool
// EnableProfilingMetrics enables runtime profiling metrics on the metrics endpoint.
EnableProfilingMetrics bool
// EnableProfilingMetricsSet reports whether profiling metrics toggle was explicitly set.
EnableProfilingMetricsSet bool
// Store is the backend DSN (for example mem://, disk://..., s3://..., azure://...).
Store string
// HAMode controls cluster coordination strategy ("concurrent", "failover", "single", or "auto").
HAMode string
// HALeaseTTL controls leader-lease lifetime in failover mode and heartbeat cadence in auto mode.
HALeaseTTL time.Duration
// HASinglePresenceTTL controls how long single-mode presence records remain
// live on backends that require .ha advertisement.
HASinglePresenceTTL time.Duration
// DefaultNamespace is used when requests omit namespace.
DefaultNamespace string
// JSONMaxBytes caps incoming JSON payload size.
JSONMaxBytes int64
// AttachmentMaxBytes caps attachment payload size.
AttachmentMaxBytes int64
// JSONUtil selects JSON implementation (lockd/jsonv2/stdlib).
JSONUtil string
// SpoolMemoryThreshold controls memory buffering before payload spill-to-disk.
SpoolMemoryThreshold int64
// DiskRetention controls retention for disk-backed transient files/log fragments.
DiskRetention time.Duration
// DiskJanitorInterval controls how often disk retention janitor runs.
DiskJanitorInterval time.Duration
// DiskQueueWatch enables native filesystem queue-watch acceleration on disk backends.
DiskQueueWatch bool
// DiskLockFileCacheSize caps cached lock-file descriptors for disk/NFS locking.
DiskLockFileCacheSize int
// LogstoreCommitMaxOps caps logstore entries committed per fsync batch.
LogstoreCommitMaxOps int
// LogstoreSegmentSize caps logstore segment size before rolling.
LogstoreSegmentSize int64
// LogstoreCompactionEnabled enables background logstore compaction on disk/NFS.
LogstoreCompactionEnabled bool
// LogstoreCompactionEnabledSet reports whether LogstoreCompactionEnabled was explicitly set.
LogstoreCompactionEnabledSet bool
// LogstoreCompactionInterval controls how often the background compactor checks for eligible work.
LogstoreCompactionInterval time.Duration
// LogstoreCompactionMinSegments requires at least this many sealed snapshot/segment files before compacting.
LogstoreCompactionMinSegments int
// LogstoreCompactionMinReclaimBytes requires at least this many bytes of reclaimable sealed data before compacting.
LogstoreCompactionMinReclaimBytes int64
// LogstoreCompactionDeleteGrace delays deletion of obsolete compacted files after cutover.
LogstoreCompactionDeleteGrace time.Duration
// LogstoreCompactionMaxIOBytesPerSec throttles background compaction IO (0 uses the default throttle).
LogstoreCompactionMaxIOBytesPerSec int64
// DisableLogstoreCompactionThrottling disables background compaction IO throttling entirely.
DisableLogstoreCompactionThrottling bool
// DisableMemQueueWatch disables in-memory queue watch hints (poll-only fallback).
DisableMemQueueWatch bool
// DefaultTTL is the default lease TTL for acquire/dequeue operations.
DefaultTTL time.Duration
// MaxTTL is the maximum allowed lease TTL.
MaxTTL time.Duration
// AcquireBlock is the default acquire/dequeue blocking window.
AcquireBlock time.Duration
// SweeperInterval controls maintenance sweep cadence.
SweeperInterval time.Duration
// TxnReplayInterval controls how often transaction replay scans run.
TxnReplayInterval time.Duration
// QueueDecisionCacheTTL controls empty decision-cache TTL for queue decision checks.
QueueDecisionCacheTTL time.Duration
// QueueDecisionMaxApply caps decision records applied per dequeue attempt.
QueueDecisionMaxApply int
// QueueDecisionApplyTimeout caps dequeue time spent applying queued decisions.
QueueDecisionApplyTimeout time.Duration
// StateCacheBytes caps in-memory state cache size (0 uses default, negative disables).
StateCacheBytes int64
// StateCacheBytesSet reports whether StateCacheBytes was explicitly set.
StateCacheBytesSet bool
// IdleSweepGrace is required idle time before maintenance sweeps begin.
IdleSweepGrace time.Duration
// IdleSweepOpDelay inserts pacing delay between maintenance operations.
IdleSweepOpDelay time.Duration
// IdleSweepMaxOps caps maintenance operations per sweep pass.
IdleSweepMaxOps int
// IdleSweepMaxRuntime caps wall-clock duration of a sweep pass.
IdleSweepMaxRuntime time.Duration
// DrainGrace is pre-shutdown lease-drain grace period.
DrainGrace time.Duration
// DrainGraceSet reports whether DrainGrace was explicitly set.
DrainGraceSet bool
// ShutdownTimeout caps total graceful shutdown duration (drain + HTTP shutdown).
ShutdownTimeout time.Duration
// ShutdownTimeoutSet reports whether ShutdownTimeout was explicitly set.
ShutdownTimeoutSet bool
// OTLPEndpoint enables OTLP export to the given collector endpoint.
OTLPEndpoint string
// DisableHTTPTracing disables OpenTelemetry spans for HTTP handlers.
DisableHTTPTracing bool
// DisableStorageTracing disables OpenTelemetry spans in storage backends.
DisableStorageTracing bool
// DisableMTLS disables mutual TLS on the public HTTP server.
DisableMTLS bool
// BundlePath points to server PEM bundle (CA + server cert + key + metadata material).
BundlePath string
// BundlePathDisableExpansion disables env/tilde expansion for BundlePath.
BundlePathDisableExpansion bool
// BundlePEM provides server bundle bytes directly (takes precedence when non-empty).
BundlePEM []byte
// DenylistPath points to serial denylist file merged with bundle denylist entries.
DenylistPath string
// HTTP2MaxConcurrentStreams sets HTTP/2 MaxConcurrentStreams; 0 uses default.
HTTP2MaxConcurrentStreams int
// HTTP2MaxConcurrentStreamsSet reports whether HTTP2MaxConcurrentStreams was explicitly set.
HTTP2MaxConcurrentStreamsSet bool
// TCTrustDir is directory of trusted CA certs for TC federation calls.
TCTrustDir string
// TCDisableAuth disables TC peer/client auth checks (testing/isolated setups only).
TCDisableAuth bool
// TCAllowDefaultCA allows trust fallback to local default CA material when explicit trust is absent.
TCAllowDefaultCA bool
// SelfEndpoint is this node's externally reachable endpoint for TC federation.
SelfEndpoint string
// TCJoinEndpoints is optional seed endpoint list used for initial TC peer discovery.
TCJoinEndpoints []string
// TCFanoutTimeout caps each remote apply attempt during TC fan-out.
TCFanoutTimeout time.Duration
// TCFanoutMaxAttempts caps retry attempts for TC fan-out calls.
TCFanoutMaxAttempts int
// TCFanoutBaseDelay is exponential backoff base for TC fan-out retries.
TCFanoutBaseDelay time.Duration
// TCFanoutMaxDelay caps TC fan-out backoff.
TCFanoutMaxDelay time.Duration
// TCFanoutMultiplier is exponential growth factor for TC fan-out retries.
TCFanoutMultiplier float64
// TCDecisionRetention keeps decided transaction records for replay/fan-out recovery.
TCDecisionRetention time.Duration
// TCClientBundlePath points to TC client bundle used for mTLS fan-out calls.
TCClientBundlePath string
// DisableStorageEncryption disables kryptograf envelope encryption at rest.
DisableStorageEncryption bool
// StorageEncryptionSnappy enables Snappy compression before encryption.
StorageEncryptionSnappy bool
// MetadataRootKey is kryptograf root key used to derive metadata/object keys.
MetadataRootKey keymgmt.RootKey
// MetadataDescriptor is kryptograf descriptor used for metadata encryption context.
MetadataDescriptor keymgmt.Descriptor
// MetadataContext is CA-derived context identifier used for encryption material lookup.
MetadataContext string
// DisableKryptoPool disables pooled crypto buffers (diagnostic mode).
DisableKryptoPool bool
// S3SSE controls server-side encryption mode for S3 writes (for example AES256/KMS).
S3SSE string
// S3KMSKeyID is KMS key identifier for S3 SSE-KMS mode.
S3KMSKeyID string
// AWSKMSKeyID is AWS KMS key identifier used by lockd's envelope crypto integrations.
AWSKMSKeyID string
// S3MaxPartSize controls multipart upload part size.
S3MaxPartSize int64
// S3SmallEncryptBufferBudget caps concurrent small-object encryption buffers.
S3SmallEncryptBufferBudget int64
// AWSRegion sets AWS region for aws:// and related integrations.
AWSRegion string
// S3AccessKeyID sets static S3 access key credential.
S3AccessKeyID string
// S3SecretAccessKey sets static S3 secret credential.
S3SecretAccessKey string
// S3SessionToken sets optional session token for temporary S3 credentials.
S3SessionToken string
// AzureAccount is the Azure storage account name.
AzureAccount string
// AzureAccountKey is the shared-key credential for Azure Blob.
AzureAccountKey string
// AzureEndpoint overrides Azure Blob endpoint URL.
AzureEndpoint string
// AzureSASToken configures SAS-token auth for Azure Blob.
AzureSASToken string
// StorageRetryMaxAttempts caps transient backend retry attempts.
StorageRetryMaxAttempts int
// StorageRetryBaseDelay is exponential retry base delay for backend operations.
StorageRetryBaseDelay time.Duration
// StorageRetryMaxDelay caps backend retry backoff.
StorageRetryMaxDelay time.Duration
// StorageRetryMultiplier is exponential growth factor for backend retries.
StorageRetryMultiplier float64
// QueueMaxConsumers caps concurrent queue consumer workers per server.
QueueMaxConsumers int
// QueuePollInterval controls queue poll cadence when no watch hint exists.
QueuePollInterval time.Duration
// QueuePollJitter adds random delay to queue polling intervals.
QueuePollJitter time.Duration
// QueueResilientPollInterval is fallback full-poll cadence to recover missed events.
QueueResilientPollInterval time.Duration
// QueueListPageSize caps queue list page size per poll request.
QueueListPageSize int
// IndexerFlushDocs flushes in-memory index docs after this many buffered docs.
IndexerFlushDocs int
// IndexerFlushInterval flushes in-memory index docs after this wall-clock interval.
IndexerFlushInterval time.Duration
// IndexerFlushDocsSet reports whether IndexerFlushDocs was explicitly set.
IndexerFlushDocsSet bool
// IndexerFlushIntervalSet reports whether IndexerFlushInterval was explicitly set.
IndexerFlushIntervalSet bool
// QueryDocPrefetch caps concurrent state fetches for query return=documents.
QueryDocPrefetch int
// QRFDisabled disables Quick Reaction Force request shaping.
QRFDisabled bool
// QRFQueueSoftLimit soft-arms QRF when in-flight queue leases exceed this count.
QRFQueueSoftLimit int64
// QRFQueueHardLimit fully engages QRF when in-flight queue leases exceed this count.
QRFQueueHardLimit int64
// QRFQueueConsumerSoftLimit soft-arms QRF when active queue consumers exceed this count.
QRFQueueConsumerSoftLimit int64
// QRFQueueConsumerHardLimit fully engages QRF when active queue consumers exceed this count.
QRFQueueConsumerHardLimit int64
// QRFLockSoftLimit soft-arms QRF when in-flight lock leases exceed this count.
QRFLockSoftLimit int64
// QRFLockHardLimit fully engages QRF when in-flight lock leases exceed this count.
QRFLockHardLimit int64
// QRFQuerySoftLimit soft-arms QRF when concurrent query load exceeds this count.
QRFQuerySoftLimit int64
// QRFQueryHardLimit fully engages QRF when concurrent query load exceeds this count.
QRFQueryHardLimit int64
// QRFMemorySoftLimitBytes soft-arms QRF when process memory exceeds this absolute byte threshold.
QRFMemorySoftLimitBytes uint64
// QRFMemoryHardLimitBytes fully engages QRF when process memory exceeds this absolute byte threshold.
QRFMemoryHardLimitBytes uint64
// QRFMemorySoftLimitPercent soft-arms QRF when process memory exceeds this percentage.
QRFMemorySoftLimitPercent float64
// QRFMemoryHardLimitPercent fully engages QRF when process memory exceeds this percentage.
QRFMemoryHardLimitPercent float64
// QRFMemoryStrictHeadroomPercent reserves this headroom when reclaimable cache is uncertain.
QRFMemoryStrictHeadroomPercent float64
// QRFSwapSoftLimitBytes soft-arms QRF when swap usage exceeds this absolute byte threshold.
QRFSwapSoftLimitBytes uint64
// QRFSwapHardLimitBytes fully engages QRF when swap usage exceeds this absolute byte threshold.
QRFSwapHardLimitBytes uint64
// QRFSwapSoftLimitPercent soft-arms QRF when swap usage exceeds this percentage.
QRFSwapSoftLimitPercent float64
// QRFSwapHardLimitPercent fully engages QRF when swap usage exceeds this percentage.
QRFSwapHardLimitPercent float64
// QRFCPUPercentSoftLimit soft-arms QRF when CPU utilization exceeds this percentage.
QRFCPUPercentSoftLimit float64
// QRFCPUPercentHardLimit fully engages QRF when CPU utilization exceeds this percentage.
QRFCPUPercentHardLimit float64
// QRFCPUPercentSoftLimitSet reports whether QRFCPUPercentSoftLimit was explicitly set.
QRFCPUPercentSoftLimitSet bool
// QRFCPUPercentHardLimitSet reports whether QRFCPUPercentHardLimit was explicitly set.
QRFCPUPercentHardLimitSet bool
// QRFLoadSoftLimitMultiplier soft-arms QRF when load average exceeds this CPU-multiplier.
QRFLoadSoftLimitMultiplier float64
// QRFLoadHardLimitMultiplier fully engages QRF when load average exceeds this CPU-multiplier.
QRFLoadHardLimitMultiplier float64
// QRFRecoverySamples is number of healthy samples required to disengage/recover.
QRFRecoverySamples int
// QRFSoftDelay is per-request pacing delay while soft-armed.
QRFSoftDelay time.Duration
// QRFEngagedDelay is per-request pacing delay while engaged.
QRFEngagedDelay time.Duration
// QRFRecoveryDelay is per-request pacing delay while recovering.
QRFRecoveryDelay time.Duration
// QRFMaxWait caps total time a request may wait under QRF pacing.
QRFMaxWait time.Duration
// LSFSampleInterval controls Local Security Force sample cadence.
LSFSampleInterval time.Duration
// LSFLogInterval controls cadence of lockd.lsf.sample telemetry logs.
LSFLogInterval time.Duration
// LSFLogIntervalSet reports whether LSFLogInterval was explicitly set.
LSFLogIntervalSet bool
// ConnguardEnabled enables suspicious-connection protection in the TCP listener path.
// This setting is unsupported for listen-proto=unix.
ConnguardEnabled bool
// ConnguardEnabledSet reports whether ConnguardEnabled was explicitly set.
ConnguardEnabledSet bool
// ConnguardFailureThreshold controls how many suspicious connection events trigger a hard block.
ConnguardFailureThreshold int
// ConnguardFailureWindow is the rolling window used to count suspicious connection events.
ConnguardFailureWindow time.Duration
// ConnguardBlockDuration controls how long a suspicious source IP is blocked.
ConnguardBlockDuration time.Duration
// ConnguardProbeTimeout controls how long plain TCP connections are probed before classification.
ConnguardProbeTimeout time.Duration
}
Config captures the tunables for a lockd.Server instance.
func (Config) MTLSEnabled ¶ added in v0.1.0
MTLSEnabled reports whether mutual TLS is active.
func (Config) StorageEncryptionEnabled ¶
StorageEncryptionEnabled reports whether kryptograf envelope encryption is active.
type CreateCABundleFileRequest ¶ added in v0.7.0
type CreateCABundleFileRequest struct {
// Path is the destination PEM file path. This field is required.
Path string
// Force controls overwrite behavior.
// When false, writing fails if Path already exists.
Force bool
// CreateCABundleRequest configures CA generation.
CreateCABundleRequest
}
CreateCABundleFileRequest controls CA bundle generation + file write.
type CreateCABundleRequest ¶ added in v0.7.0
type CreateCABundleRequest struct {
// CommonName sets the CA certificate subject CN.
// When empty, the default is "lockd-ca".
CommonName string
// ValidFor sets CA certificate validity duration.
// When <= 0, the default is 10 years (10 * 365 * 24h).
ValidFor time.Duration
}
CreateCABundleRequest controls CA bundle generation.
type CreateClientBundleFileRequest ¶ added in v0.7.0
type CreateClientBundleFileRequest struct {
// Path is the destination PEM file path. This field is required.
Path string
// Force controls overwrite behavior.
// When false, writing fails if Path already exists.
Force bool
// CreateClientBundleRequest configures client bundle generation.
CreateClientBundleRequest
}
CreateClientBundleFileRequest controls SDK client bundle generation + file write.
type CreateClientBundleRequest ¶ added in v0.7.0
type CreateClientBundleRequest struct {
// CABundlePEM is the CA bundle content (CA cert + CA key + kryptograf metadata).
// This field is required.
CABundlePEM []byte
// CommonName sets the client certificate subject CN.
// When empty, the default is "lockd-client".
CommonName string
// ValidFor sets client certificate validity duration.
// When <= 0, the default is 1 year (365 * 24h).
ValidFor time.Duration
// NamespaceClaims defines namespace ACL claims in CLI-compatible format.
// Accepted formats are "namespace" (defaults to rw) or "namespace=perm",
// and each entry may contain comma-separated values.
// Perm values are r, w, rw.
// If no explicit claims/flags are provided, default namespace rw is added.
NamespaceClaims []string
// ReadAll adds the ALL=r claim (alias of CLI --read-all).
ReadAll bool
// WriteAll adds the ALL=w claim (alias of CLI --write-all).
WriteAll bool
// ReadWriteAll adds the ALL=rw claim (alias of CLI --rw-all).
ReadWriteAll bool
}
CreateClientBundleRequest controls SDK client bundle generation from an existing CA bundle.
type CreateServerBundleFileRequest ¶ added in v0.7.0
type CreateServerBundleFileRequest struct {
// Path is the destination PEM file path. This field is required.
Path string
// Force controls overwrite behavior.
// When false, writing fails if Path already exists.
Force bool
// CreateServerBundleRequest configures server bundle generation.
CreateServerBundleRequest
}
CreateServerBundleFileRequest controls server bundle generation + file write.
type CreateServerBundleRequest ¶ added in v0.7.0
type CreateServerBundleRequest struct {
// CABundlePEM is the CA bundle content (CA cert + CA key + kryptograf metadata).
// This field is required.
CABundlePEM []byte
// CommonName sets the server certificate subject CN.
// When empty, the default is "lockd-server".
CommonName string
// ValidFor sets server certificate validity duration.
// When <= 0, the default is 1 year (365 * 24h).
ValidFor time.Duration
// Hosts lists DNS names/IPs for SANs. Values are trimmed.
// When empty, a wildcard DNS SAN "*" is used.
Hosts []string
// NodeID controls the server SPIFFE URI identity (spiffe://lockd/server/<NodeID>).
// When empty, a new UUIDv7 is generated.
NodeID string
// Denylist optionally seeds revoked client serials embedded in the server bundle.
// Nil/empty means no revoked serials.
Denylist []string
}
CreateServerBundleRequest controls server bundle generation from an existing CA bundle.
type CreateTCClientBundleFileRequest ¶ added in v0.7.0
type CreateTCClientBundleFileRequest struct {
// Path is the destination PEM file path. This field is required.
Path string
// Force controls overwrite behavior.
// When false, writing fails if Path already exists.
Force bool
// CreateTCClientBundleRequest configures TC client bundle generation.
CreateTCClientBundleRequest
}
CreateTCClientBundleFileRequest controls TC client bundle generation + file write.
type CreateTCClientBundleRequest ¶ added in v0.7.0
type CreateTCClientBundleRequest struct {
// CABundlePEM is the CA bundle content (CA cert + CA key + kryptograf metadata).
// This field is required.
CABundlePEM []byte
// CommonName sets the TC client certificate subject CN.
// When empty, the default is "lockd-tc-client".
CommonName string
// ValidFor sets client certificate validity duration.
// When <= 0, the default is 1 year (365 * 24h).
ValidFor time.Duration
}
CreateTCClientBundleRequest controls TC client bundle generation from an existing CA bundle.
type CredentialSummary ¶
CredentialSummary describes which credentials were selected for object storage.
type DiskConfigResult ¶ added in v0.1.0
DiskConfigResult captures disk configuration and its root path.
func BuildDiskConfig ¶
func BuildDiskConfig(cfg Config) (DiskConfigResult, error)
BuildDiskConfig parses disk:// URLs into a disk.Config.
type DrainLeasesPolicy ¶ added in v0.1.0
type DrainLeasesPolicy struct {
// GracePeriod defines how long the server should keep serving requests
// (while denying new leases) before beginning the HTTP shutdown. Zero skips
// the grace window.
GracePeriod time.Duration
// ForceRelease toggles metadata rewrites that explicitly clear outstanding
// leases when the grace period elapses. This is experimental and disabled by
// default.
ForceRelease bool
// NotifyClients controls whether the server surfaces Shutdown-Imminent
// headers while draining so clients can release proactively.
NotifyClients bool
}
DrainLeasesPolicy describes how the server should attempt to let existing lease holders finish work before the HTTP server stops accepting new connections.
type Option ¶
type Option func(*options)
Option configures server instances.
func WithBackend ¶
WithBackend injects a pre-built backend (useful for tests).
func WithDefaultCloseOptions ¶ added in v0.1.0
func WithDefaultCloseOptions(opts ...CloseOption) Option
WithDefaultCloseOptions sets the server-wide defaults applied to Close/Shutdown calls.
func WithLSFLogInterval ¶
WithLSFLogInterval overrides the cadence for lockd.lsf.sample telemetry logs; use 0 to disable logging.
func WithLogger ¶
WithLogger supplies a custom logger. Passing nil falls back to pslog.NoopLogger().
func WithMetricsListen ¶ added in v0.2.0
WithMetricsListen overrides the metrics listener address (empty disables metrics).
func WithOTLPEndpoint ¶
WithOTLPEndpoint overrides the OTLP collector endpoint used for telemetry.
func WithPprofListen ¶ added in v0.3.0
WithPprofListen overrides the pprof listener address (empty disables).
func WithProfilingMetrics ¶ added in v0.3.0
WithProfilingMetrics toggles Go runtime profiling metrics on the metrics endpoint.
func WithTCFanoutGate ¶ added in v0.1.0
func WithTCFanoutGate(gate txncoord.FanoutGate) Option
WithTCFanoutGate injects a hook between local apply and remote fan-out (test-only).
func WithTCLeaderLeaseTTL ¶ added in v0.1.0
WithTCLeaderLeaseTTL overrides the lease TTL used for TC leader election.
type S3ConfigResult ¶ added in v0.1.0
type S3ConfigResult struct {
Config s3.Config
Credentials CredentialSummary
}
S3ConfigResult captures S3 configuration and selected credentials.
func BuildGenericS3Config ¶
func BuildGenericS3Config(cfg Config) (S3ConfigResult, error)
BuildGenericS3Config parses s3:// URLs that target generic S3-compatible services (MinIO, etc.).
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server wraps the HTTP server, storage backend, and supporting components.
func NewServer ¶
NewServer constructs a lockd server according to cfg. Example:
cfg := lockd.Config{Store: "mem://", Listen: ":9341", ListenProto: "tcp"}
srv, err := lockd.NewServer(cfg)
if err != nil {
log.Fatal(err)
}
go srv.Start()
func (*Server) Abort ¶ added in v0.1.0
Abort stops serving and background loops without leaving the TC cluster. Intended for tests that need to simulate abrupt server loss.
func (*Server) Close ¶
func (s *Server) Close(opts ...CloseOption) error
Close gracefully shuts the server down using a background context.
func (*Server) ForceQRFObserve ¶
ForceQRFObserve injects a metrics snapshot into the QRF controller. It is intended for tests that need to drive the perimeter-defence state machine deterministically.
func (*Server) Handler ¶
Handler returns the underlying HTTP handler so lockd can be mounted inside an existing mux when embedding the server into another program.
func (*Server) LastServeError ¶
LastServeError returns the most recent error reported by the underlying HTTP server. It is primarily useful for diagnostics; Shutdown already reports any fatal serve/shutdown errors to callers.
func (*Server) ListenerAddr ¶
ListenerAddr returns the bound listener address once available.
func (*Server) QRFStatus ¶
QRFStatus returns the current controller state, reason, and last snapshot.
func (*Server) Shutdown ¶
Shutdown gracefully stops the server and returns any fatal serve/shutdown error. The returned error will be nil for clean shutdowns.
func (*Server) ShutdownWithOptions ¶ added in v0.1.0
func (s *Server) ShutdownWithOptions(ctx context.Context, opts ...CloseOption) error
ShutdownWithOptions gracefully stops the server while applying custom close behaviour.
type ServerHandle ¶ added in v0.1.0
type ServerHandle struct {
Server *Server
Stop func(context.Context, ...CloseOption) error
}
ServerHandle wraps a running server and its shutdown hook.
func StartServer ¶
StartServer starts a lockd server in a background goroutine and waits until it is ready to accept connections. It returns the running server alongside a stop function that gracefully shuts it down. Example:
cfg := lockd.Config{Store: "mem://", ListenProto: "unix", Listen: "/tmp/lockd.sock", DisableMTLS: true}
handle, err := lockd.StartServer(ctx, cfg)
if err != nil {
log.Fatal(err)
}
defer handle.Stop(context.Background())
type TestMTLSCredentials ¶ added in v0.1.0
type TestMTLSCredentials struct {
// contains filtered or unexported fields
}
TestMTLSCredentials captures ephemeral test-only MTLS material (server bundle + client credentials).
func NewTestMTLSCredentialsFromBundles ¶ added in v0.1.0
func NewTestMTLSCredentialsFromBundles(serverBundle, clientBundle []byte) (TestMTLSCredentials, error)
NewTestMTLSCredentialsFromBundles constructs test MTLS credentials using the provided server and client bundles.
func (TestMTLSCredentials) ClientBundle ¶ added in v0.1.0
func (c TestMTLSCredentials) ClientBundle() []byte
ClientBundle returns a copy of the PEM-encoded client bundle associated with the credentials.
func (TestMTLSCredentials) NewHTTPClient ¶ added in v0.1.0
func (c TestMTLSCredentials) NewHTTPClient() (*http.Client, error)
NewHTTPClient constructs an HTTP client configured for MTLS using the embedded client bundle.
func (TestMTLSCredentials) ServerBundle ¶ added in v0.1.0
func (c TestMTLSCredentials) ServerBundle() []byte
ServerBundle returns a copy of the PEM-encoded server bundle associated with the credentials.
func (TestMTLSCredentials) Valid ¶ added in v0.1.0
func (c TestMTLSCredentials) Valid() bool
Valid reports whether the credentials contain MTLS material.
type TestServer ¶
type TestServer struct {
Server *Server
BaseURL string
Listener net.Addr
Client *client.Client
Config Config
// contains filtered or unexported fields
}
TestServer wraps a running lockd.Server with convenient handles for tests.
func NewTestServer ¶
func NewTestServer(ctx context.Context, opts ...TestServerOption) (*TestServer, error)
NewTestServer starts a lockd server suitable for tests. Call Stop to clean up resources.
func StartTestServer ¶
func StartTestServer(t testing.TB, opts ...TestServerOption) *TestServer
StartTestServer is a convenience wrapper that fails the test on error and registers cleanup.
func (*TestServer) Abort ¶ added in v0.1.0
func (ts *TestServer) Abort(ctx context.Context) error
Abort stops the server abruptly without leaving TC cluster membership. Intended for tests that need crash-like behaviour.
func (*TestServer) Addr ¶
func (ts *TestServer) Addr() net.Addr
Addr returns the listener address the server is bound to.
func (*TestServer) Backend ¶
func (ts *TestServer) Backend() storage.Backend
Backend exposes the storage backend used by the server.
func (*TestServer) NewEndpointsClient ¶ added in v0.1.0
func (ts *TestServer) NewEndpointsClient(endpoints []string, opts ...client.Option) (*client.Client, error)
NewEndpointsClient returns a client configured with explicit endpoints while inheriting the test server defaults (mTLS, timeouts, logging, etc.).
func (*TestServer) NewHTTPClient ¶ added in v0.1.0
func (ts *TestServer) NewHTTPClient() (*http.Client, error)
NewHTTPClient returns a raw HTTP client configured for the test server's MTLS settings.
func (*TestServer) Stop ¶
func (ts *TestServer) Stop(ctx context.Context, opts ...CloseOption) error
Stop shuts down the server using the provided context.
func (*TestServer) TestMTLSCredentials ¶ added in v0.1.0
func (ts *TestServer) TestMTLSCredentials() TestMTLSCredentials
TestMTLSCredentials returns a clone of the MTLS material backing the test server (when enabled).
func (*TestServer) URL ¶
func (ts *TestServer) URL() string
URL returns the base URL clients should use to reach the server.
type TestServerOption ¶
type TestServerOption func(*testServerOptions)
TestServerOption customises NewTestServer/StartTestServer behaviour.
func WithTestBackend ¶
func WithTestBackend(backend storage.Backend) TestServerOption
WithTestBackend injects a pre-built backend (shared between servers if desired).
func WithTestChaos ¶
func WithTestChaos(cfg *ChaosConfig) TestServerOption
WithTestChaos enables an in-process chaos proxy in front of the listener. Passing nil disables chaos behaviour.
func WithTestClientOptions ¶
func WithTestClientOptions(opts ...client.Option) TestServerOption
WithTestClientOptions appends client options used when auto-constructing the helper client.
func WithTestClock ¶ added in v0.1.0
func WithTestClock(c clock.Clock) TestServerOption
WithTestClock injects a custom clock implementation for the server.
func WithTestCloseDefaults ¶ added in v0.1.0
func WithTestCloseDefaults(opts ...CloseOption) TestServerOption
WithTestCloseDefaults overrides the shutdown CloseOptions applied to StartTestServer instances. Passing no options restores the production defaults (currently 8s drain / 10s overall).
func WithTestConfig ¶
func WithTestConfig(cfg Config) TestServerOption
WithTestConfig provides an explicit Config to use. Missing fields will be defaulted during validation.
func WithTestConfigFunc ¶
func WithTestConfigFunc(fn func(*Config)) TestServerOption
WithTestConfigFunc applies a mutation to the server configuration before start.
func WithTestListener ¶
func WithTestListener(proto, address string) TestServerOption
WithTestListener overrides the listen protocol and address.
func WithTestLogger ¶
func WithTestLogger(logger pslog.Logger) TestServerOption
WithTestLogger supplies a custom logger.
func WithTestLoggerFromTB ¶
func WithTestLoggerFromTB(t testing.TB, level pslog.Level) TestServerOption
WithTestLoggerFromTB routes server logs to the provided testing logger at the supplied level.
func WithTestLoggerTB ¶
func WithTestLoggerTB(t testing.TB) TestServerOption
WithTestLoggerTB uses the testing logger with Debug level.
func WithTestMTLS ¶ added in v0.1.0
func WithTestMTLS() TestServerOption
WithTestMTLS forces StartTestServer to configure mutual TLS, regardless of the environment toggle.
func WithTestMTLSCredentials ¶ added in v0.1.0
func WithTestMTLSCredentials(creds TestMTLSCredentials) TestServerOption
WithTestMTLSCredentials reuses the provided MTLS material for the test server.
func WithTestStartTimeout ¶
func WithTestStartTimeout(d time.Duration) TestServerOption
WithTestStartTimeout overrides the wait timeout when starting the server.
func WithTestStore ¶
func WithTestStore(store string) TestServerOption
WithTestStore sets the storage URL while still defaulting other values.
func WithTestTCFanoutGate ¶ added in v0.1.0
func WithTestTCFanoutGate(gate txncoord.FanoutGate) TestServerOption
WithTestTCFanoutGate injects a hook between local apply and remote fan-out.
func WithTestTCLeaderLeaseTTL ¶ added in v0.1.0
func WithTestTCLeaderLeaseTTL(ttl time.Duration) TestServerOption
WithTestTCLeaderLeaseTTL overrides the lease TTL used for TC leader election.
func WithTestUnixSocket ¶
func WithTestUnixSocket(path string) TestServerOption
WithTestUnixSocket configures the server to listen on the provided unix socket path.
func WithoutTestClient ¶
func WithoutTestClient() TestServerOption
WithoutTestClient disables automatic client creation.
func WithoutTestMTLS ¶ added in v0.1.0
func WithoutTestMTLS() TestServerOption
WithoutTestMTLS disables automatic mTLS configuration for this test server.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
benchmark
|
|
|
Package client provides the Go SDK for talking to a lockd cluster over HTTP.
|
Package client provides the Go SDK for talking to a lockd cluster over HTTP. |
|
cmd
|
|
|
licensegen
command
|
|
|
lockd
command
|
|
|
lockd-bench
command
|
|
|
integration
|
|
|
internal/locktest
Package locktest provides reusable lock/lease integration test scenarios.
|
Package locktest provides reusable lock/lease integration test scenarios. |
|
internal/storepath
Package storepath provides helpers for scoping integration test store URLs.
|
Package storepath provides helpers for scoping integration test store URLs. |
|
internal
|
|
|
connguard
Package connguard provides listener-level protection for suspicious TCP/TLS connections before requests reach HTTP handlers.
|
Package connguard provides listener-level protection for suspicious TCP/TLS connections before requests reach HTTP handlers. |
|
nsauth
Package nsauth parses and evaluates certificate-based namespace authorization claims encoded in URI SAN entries.
|
Package nsauth parses and evaluates certificate-based namespace authorization claims encoded in URI SAN entries. |
|
storage/aws
Package aws provides the AWS S3 storage backend built on the AWS SDK v2.
|
Package aws provides the AWS S3 storage backend built on the AWS SDK v2. |
|
Package mcp provides the lockd MCP facade server.
|
Package mcp provides the lockd MCP facade server. |
|
admin
Package admin provides an SDK-friendly administrative surface for lockd MCP OAuth/bootstrap lifecycle operations.
|
Package admin provides an SDK-friendly administrative surface for lockd MCP OAuth/bootstrap lifecycle operations. |
|
cmd/getfullmcpspec
command
|
|
|
oauth
Package oauth implements local OAuth 2.1 primitives for the lockd MCP facade, including confidential client management, authorization/token handlers, and bearer-token verification.
|
Package oauth implements local OAuth 2.1 primitives for the lockd MCP facade, including confidential client management, authorization/token handlers, and bearer-token verification. |
|
state
Package state provides encrypted on-disk persistence for lockd MCP OAuth configuration and client credentials.
|
Package state provides encrypted on-disk persistence for lockd MCP OAuth configuration and client credentials. |
|
internal/swaggerhtml
command
|
|