distcache

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2025 License: MIT Imports: 31 Imported by: 0

README

DistCache

GitHub Actions Workflow Status codecov GitHub go.mod Go version Go Reference

DistCache is a distributed read‑through cache engine built in Go.

In a read‑through cache, the cache sits between your application and the data source. When the application requests data:

  • If the data is in the cache (cache hit), it is returned immediately.
  • If the data is not in the cache (cache miss), DistCache fetches it from the primary data source (database, API, etc.), stores it in the cache, and returns it to the caller.

This reduces direct load on your backend, lowers latency, and improves scalability.

DistCache is designed to be scalable and highly available. It allows you to quickly build fast, distributed systems across a cluster of machines.

The caching engine is powered by the battle‑tested groupcache-go.

👋 Table of Contents

⭐️ Features

  • Automatic fetch on miss – Data is loaded into the cache only when requested.
  • Distributed architecture – Data is sharded across nodes for scalability and availability.
  • Reduced backend load – Frequent reads are served from the cache instead of the database.
  • Configurable expiry & eviction – Support for TTL, LRU, and custom policies.
  • Automatic node discovery – Nodes automatically react to cluster topology changes.
  • Discovery provider – Implement custom discovery backends or use the built‑in ones:
    • Kubernetes – discover peers via the Kubernetes API.
    • NATS – discover peers via NATS.
    • Static – fixed list of peers, ideal for tests and demos.
    • DNS – discover peers via Go’s DNS resolver.
  • TLS support – End‑to‑end encrypted communication between nodes. All nodes must share the same root Certificate Authority (CA) for a successful handshake. TLS is enabled via the WithTLS option in the configuration and applies to both client and server sides.
  • Instrumentation - Support for metrics and tracing via OpenTelemetry. That can be enabled using the WithMetrics and WithTracing options in the configuration.

💻 Installation

go get github.com/tochemey/distcache

⚙️ Engine

All core capabilities are exposed through the DistCache Engine, which provides a simple API for interacting with the cache.

Core Methods
  • Put – Store a single key/value pair in a given keyspace.
  • PutMany – Store multiple key/value pairs in a given keyspace.
  • Get – Retrieve a specific key/value pair from a given keyspace.
  • Delete – Remove a specific key/value pair from a given keyspace.
  • DeleteMany – Remove multiple key/value pairs from a given keyspace.
KeySpace Management
  • DeleteKeySpace – Delete a single keyspace and all of its entries.
  • DeleteKeyspaces – Delete multiple keyspaces at once.
  • KeySpaces – List all available keyspaces.

The Engine is designed to provide high‑performance operations across a distributed cluster while keeping the API simple and predictable.

📝 How It Works

  1. Cache lookup – The application requests data from DistCache.
  2. Cache hit – If the data is present, it is returned immediately.
  3. Cache miss:
    • DistCache fetches data from the configured primary data source.
    • The data is stored in the cache according to the keyspace configuration.
    • The data is returned to the caller.
  4. Subsequent requests – Future reads for the same key are served from the cache until the entry expires or is evicted by the eviction policy.

💡 Use Cases

  • High‑traffic applications – Reduce database load (e‑commerce, social networks, analytics dashboards).
  • API response caching – Cache expensive or frequently called external APIs.
  • Session and profile caching – Keep user session or profile data close to your application across nodes.

🚀 Get Started

To integrate DistCache, configure a Config and implement two interfaces before starting the Engine:

  • DataSource: Defines how to fetch data on a cache miss. This can be a database, REST API, gRPC service, filesystem, or any other backend.
  • KeySpace: Defines a logical namespace for grouping key/value pairs. It controls metadata such as:
    • Keyspace name
    • Storage constraints
    • Expiration and eviction behavior

KeySpaces are loaded during DistCache bootstrap and dictate how data is partitioned and managed in the cluster.

Example

A complete example can be found in the example directory.

🤲 Contribution

Contributions are welcome.

This project follows:

To contribute:

  1. Fork the repository.
  2. Create a feature branch.
  3. Commit your changes using Conventional Commits.
  4. Submit a pull request.

Documentation

Index

Constants

View Source
const (
	// DefaultPort is for distcache
	DefaultPort = 3320

	// DefaultDiscoveryPort is for memberlist
	DefaultDiscoveryPort = 3322

	// MinimumReplicaCount denotes default and minimum replica count in a distcache
	// cluster.
	MinimumReplicaCount = 1

	// DefaultBootstrapTimeout denotes default timeout value to check bootstrapping
	// status.
	DefaultBootstrapTimeout = 30 * time.Second

	// DefaultJoinRetryInterval denotes a time gap between sequential join attempts.
	DefaultJoinRetryInterval = time.Second

	// DefaultMaxJoinAttempts denotes a maximum number of failed join attempts
	// before forming a standalone cluster.
	DefaultMaxJoinAttempts = 10

	// DefaultKeepAlivePeriod is the default value of TCP keepalive. It's 300 seconds.
	// This option is useful in order to detect dead peers (clients that cannot
	// be reached even if they look connected). Moreover, if there is network
	// equipment between clients and servers that need to see some traffic in
	// order to take the connection open, the option will prevent unexpected
	// connection closed events.
	DefaultKeepAlivePeriod = 300 * time.Second

	// DefaultShutdownTimeout is the default value of maximum amount of time before
	// shutting down
	DefaultShutdownTimeout = 30 * time.Second

	// DefaultReadTimeout is the default timeout for reading data from the distributed cache
	DefaultReadTimeout = 5 * time.Second

	// DefaultWriteTimeout is default write timeout to write data into the distributed cache
	DefaultWriteTimeout = 5 * time.Second

	// MinimumMemberCountQuorum denotes minimum required count of members to form
	// a cluster.
	MinimumMemberCountQuorum = 1
)

Variables

View Source
var ErrClusterQuorum = errors.New("cannot be reached cluster quorum to operate")

ErrClusterQuorum means that the cluster could not reach a healthy numbers of members to operate.

View Source
var ErrKeySpaceNotFound = errors.New("key space not found")

ErrKeySpaceNotFound means that distributed cache does not have the given keyspace requested

Functions

This section is empty.

Types

type Config

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

Config defines distcache configuration

func NewConfig

func NewConfig(provider discovery.Provider, keySpaces []KeySpace, opts ...Option) *Config

NewConfig creates a new configuration instance for the distributed cache engine.

It initializes the cache engine with the given discovery provider, keyspaces, and optional settings.

Parameters:

  • provider: The discovery.Provider responsible for node discovery and cluster formation.
  • keySpaces: A slice of KeySpace instances defining different storage namespaces within the cache.
  • opts: Optional configuration settings that can be applied to customize the engine behavior.

Returns:

  • *Config: A pointer to the newly created Config instance.

func (Config) BindAddr

func (c Config) BindAddr() string

BindAddr denotes the address that distcache will bind to for communication with other distcache nodes.

func (Config) BindPort

func (c Config) BindPort() int

BindPort denotes the address that distcache will bind to for communication with other distcache nodes.

func (Config) BootstrapTimeout

func (c Config) BootstrapTimeout() time.Duration

BootstrapTimeout for bootstrap control

An distcache node checks operation status before taking any action for the cluster events, responding incoming requests and running API functions. Bootstrapping status is one of the most important checkpoints for an "operable" distcache node. BootstrapTimeout sets a deadline to check bootstrapping status without blocking indefinitely.

func (Config) DiscoveryPort

func (c Config) DiscoveryPort() int

DiscoveryPort denotes the port distcache will use to discover other distcache nodes in the cluster

func (Config) DiscoveryProvider

func (c Config) DiscoveryProvider() discovery.Provider

DiscoveryProvider denotes the discovery provider to use to locate other distcache nodes in the cluster

func (Config) Hasher

func (c Config) Hasher() hash.Hasher

Hasher returns the hasher

func (Config) Interface

func (c Config) Interface() string

Interface denotes a binding interface. It can be used instead of BindAddr if the interface is known but not the address. If both are provided, then distcache verifies that the interface has the bind address that is provided.

func (Config) JoinRetryInterval

func (c Config) JoinRetryInterval() time.Duration

JoinRetryInterval is the time gap between attempts to join an existing cluster.

func (Config) KeepAlivePeriod

func (c Config) KeepAlivePeriod() time.Duration

KeepAlivePeriod denotes whether the operating system should send keep-alive messages on the connection.

func (Config) KeySpaces

func (c Config) KeySpaces() []KeySpace

KeySpaces defines the various keySpaces used by distcache

func (Config) Label added in v0.3.0

func (c Config) Label() string

Label returns the distcache node label This label is used to identify the distcache node. This label should be the same for all nodes in the cluster.

func (Config) Logger

func (c Config) Logger() log.Logger

Logger is a custom logger which you provide. If Logger is set, it will use this for the internal logger.

func (Config) MaxJoinAttempts

func (c Config) MaxJoinAttempts() int

MaxJoinAttempts denotes the maximum number of attempts to join an existing cluster before forming a new one.

func (Config) MetricConfig added in v0.3.0

func (c Config) MetricConfig() *otel.MetricConfig

MetricConfig returns the metric configuration

func (Config) MinimumPeersQuorum

func (c Config) MinimumPeersQuorum() int

MinimumPeersQuorum denotes the minimum number of peers required to form a cluster

func (Config) ReadTimeout

func (c Config) ReadTimeout() time.Duration

ReadTimeout defines the read timeout. This timeout is used to read data from the distributed cache

func (Config) ReplicaCount

func (c Config) ReplicaCount() int

ReplicaCount is 1, by default.

func (Config) ShutdownTimeout

func (c Config) ShutdownTimeout() time.Duration

ShutdownTimeout returns the shutdown timeout

distcache will broadcast a leave message but will not shut down the background listeners, meaning the node will continue participating in gossip and state updates.

Sending a leave message will block until the leave message is successfully broadcast to a member of the cluster, if any exist or until a specified timeout is reached.

func (Config) TLSInfo

func (c Config) TLSInfo() *TLSInfo

TLSInfo returns the TLS Info. This option allows secure communication by setting a custom TLS configuration for encrypting data in transit.

func (Config) TraceConfig added in v0.3.0

func (c Config) TraceConfig() *otel.TracerConfig

TraceConfig returns the trace configuration

func (Config) Validate

func (c Config) Validate() error

Validate validates the distcache configuration

func (Config) WriteTimeout

func (c Config) WriteTimeout() time.Duration

WriteTimeout defines the write timeout used to set a key/value pair in the distributed cache engine

type DataSource

type DataSource interface {
	// Fetch retrieves the value associated with the given key from the data source.
	// It is called when a cache miss occurs.
	//
	// Parameters:
	//   - ctx: A context for managing timeouts, cancellations, or deadlines.
	//   - key: The cache key whose value needs to be fetched.
	//
	// Returns:
	//   - A byte slice containing the fetched data.
	//   - An error if the data retrieval fails.
	Fetch(ctx context.Context, key string) ([]byte, error)
}

DataSource defines the interface used by `distcache` to retrieve data when a requested entry is not found in the cache. Implementations of this interface provide a mechanism to fetch data from an external source, such as a database, API, or file system.

type Engine

type Engine interface {
	// Put stores a single key/value pair in the cache.
	//
	// Parameters:
	//   - ctx: The context for cancellation and deadlines.
	//   - keyspace: The keyspace in which to store the key/value pair.
	//   - entry: The key/value pair to store with an optional expiration time.
	//     If Expiry is set to the zero value (time.Time{}), the entry does not expire.
	//
	// Returns an error if the operation fails.
	Put(ctx context.Context, keyspace string, entry *Entry) error

	// PutMany stores multiple key/value pairs in the cache.
	//
	// Parameters:
	//   - ctx: The context for cancellation and deadlines.
	//   - keyspace: The keyspace in which to store the key/value pairs.
	//   - kvs: A slice of key/value pairs to store.
	//
	// Returns an error if the operation fails.
	PutMany(ctx context.Context, keyspace string, entries []*Entry) error

	// Get retrieves a specific key/value pair from the cache.
	//
	// Parameters:
	//   - ctx: The context for cancellation and deadlines.
	//   - keyspace: The keyspace from which to retrieve the key/value pair.
	//   - key: The key identifying the desired key/value pair.
	//
	// Returns the key/value pair if found, or an error if the operation fails or the key does not exist.
	Get(ctx context.Context, keyspace string, key string) (*KV, error)

	// Delete removes a specific key/value pair from the cache.
	//
	// Parameters:
	//   - ctx: The context for cancellation and deadlines.
	//   - keyspace: The keyspace from which to delete the key/value pair.
	//   - key: The key identifying the key/value pair to be deleted.
	//
	// Returns an error if the operation fails.
	Delete(ctx context.Context, keyspace string, key string) error

	// DeleteMany removes multiple key/value pairs from the cache.
	//
	// Parameters:
	//   - ctx: The context for cancellation and deadlines.
	//   - keyspace: The keyspace from which to delete the key/value pairs.
	//   - keys: A slice of keys identifying the key/value pairs to be deleted.
	//
	// Returns an error if the operation fails.
	DeleteMany(ctx context.Context, keyspace string, keys []string) error

	// Start initializes and runs the distributed cache engine.
	// It performs the following operations:
	//   - Discovers existing nodes in the system.
	//   - Joins an existing cluster or forms a new one if none exists.
	//   - Starts the cache engine to handle key-value storage and retrieval.
	//   - Builds the configured keyspaces, preparing them for use.
	//
	// Parameters:
	//   - ctx: A context used to manage initialization timeouts or cancellations.
	//
	// Returns:
	//   - err: An error if the startup process fails, otherwise nil.
	Start(ctx context.Context) (err error)

	// Stop gracefully shuts down the distributed cache engine.
	// It ensures that any ongoing operations complete and that the cluster
	// state is properly maintained before termination.
	//
	// Parameters:
	//   - ctx: A context used to manage shutdown timeouts or cancellations.
	//
	// Returns:
	//   - error: An error if the shutdown process encounters issues, otherwise nil.
	Stop(ctx context.Context) error

	// DeleteKeySpace delete a given keySpace from the cache.
	//
	// Parameters:
	//   - ctx: The context for cancellation and deadlines.
	//   - keyspace: The keyspace from which to delete the key/value pairs.
	//
	// Returns an error if the operation fails.
	DeleteKeySpace(ctx context.Context, keyspace string) error

	// DeleteKeyspaces removes multiple keyspaces from the cache.
	//
	// Parameters:
	//   - ctx: The context for cancellation and deadlines.
	//   - keyspaces: A slice of keyspaces to be deleted.
	//
	// Returns an error if the operation fails.
	DeleteKeyspaces(ctx context.Context, keyspaces []string) error

	// KeySpaces returns the list of available KeySpaces from the cache.
	//
	// Returns an empty list if there are no keyspaces
	KeySpaces() []string
}

Engine defines a set of operations for managing key/value pairs in a cache or store, organized by keyspace. It supports inserting, retrieving, listing, and deleting individual or multiple key/value entries. Each method accepts a context.Context to allow for cancellation, timeouts, and passing request-scoped values.

The methods include:

  • Put: Stores a single key/value pair in the specified .
  • PutMany: Stores multiple key/value pairs in one operation.
  • Get: Retrieves a specific key/value pair from the cache using its key.
  • Delete: Removes a specific key/value pair from the cache using its key.
  • DeleteMany: Removes multiple key/value pairs from the cache given their keys.
  • DeleteKeySpace: Remove a given keySpace from the cache
  • DeleteKeyspaces: Remove a set of keySpaces from the cache

func NewEngine

func NewEngine(config *Config) (Engine, error)

NewEngine creates and initializes a new distributed cache engine based on the provided configuration.

It sets up the necessary components required for caching, including:

  • Cluster discovery and membership management.
  • Keyspace initialization.
  • Cache storage backend configuration.
  • Any additional settings defined in the provided configuration.

Parameters:

  • config: A pointer to a Config struct containing the necessary settings for initializing the cache engine.

Returns:

  • Engine: An instance of the initialized cache engine.
  • error: An error if the engine fails to initialize due to misconfiguration or other issues.

type Entry

type Entry struct {
	KV
	// Expiry is the expiration time of the key-value pair, represented as a Unix timestamp.
	// If Expiry is set to the zero value (time.Time{}), the entry does not expire.
	Expiry time.Time
}

Entry represents a key-value pair with an optional expiration time.

The Key field holds the identifier for the value, while Value stores the data associated with that key. Expiry is a Unix timestamp (in seconds) indicating when the key-value pair should expire. An Expiry value of 0 typically means that the pair does not expire.

type KV

type KV struct {
	// Key is the identifier for the value.
	Key string

	// Value contains the data associated with the key.
	Value []byte
}

KV represents a key-value pair.

The Key field holds the identifier for the value, while Value stores the data associated with that key.

type KeySpace

type KeySpace interface {
	// Name returns the name of the namespace.
	// The namespace is used to logically group key-value pairs.
	Name() string

	// MaxBytes returns the maximum number of bytes allocated for this namespace.
	// Once the limit is reached, the cache may evict entries based on its eviction policy.
	MaxBytes() int64

	// DataSource returns the underlying data source for this namespace.
	// This source is used to fetch data in case of a cache miss.
	DataSource() DataSource

	// ExpiresAt returns the expiration time for a given key within the namespace.
	// If the key does not have a predefined expiration time, it may return a zero time.
	//
	// ctx: Context for managing timeouts or cancellations.
	// key: The cache key whose expiration time is being queried.
	ExpiresAt(ctx context.Context, key string) time.Time
}

KeySpace defines a logical namespace for storing key-value pairs in a distributed cache. It provides metadata about the namespace, including its name, storage limits, and data source. Additionally, it allows checking when a specific key is set to expire.

type Option

type Option interface {
	// Apply applies the configuration option to the given Config instance.
	Apply(config *Config)
}

Option defines a configuration option that can be applied to a Config.

Implementations of this interface modify the configuration when applied.

func WithBindAddr

func WithBindAddr(addr string) Option

WithBindAddr configures the config to use a custom bind address.

BindAddr denotes the address that distcache will bind to for communication with other distcache nodes.

Parameters:

  • addr: The bind address to use.

Returns:

  • An Option that applies the custom bind addr to the Config.

Usage:

config := NewConfig(WithBindAddr(addr))

func WithBindPort

func WithBindPort(port int) Option

WithBindPort configures the config to use a custom bind port.

BindPort denotes the address that distcache will bind to for communication with other distcache nodes.

Parameters:

  • port: The bind port to use.

Returns:

  • An Option that applies the custom bind port to the Config.

Usage:

config := NewConfig(WithBindPort(port))

func WithBootstrapTimeout

func WithBootstrapTimeout(timeout time.Duration) Option

WithBootstrapTimeout configures the config to use a custom bootstrap timeout.

A distcache node checks operation status before taking any action for the cluster events, responding incoming requests and running API functions. Bootstrapping status is one of the most important checkpoints for an "operable" distcache node. BootstrapTimeout sets a deadline to check bootstrapping status without blocking indefinitely.

Parameters:

  • timeout: The custom bootstrap timeout.

Returns:

  • An Option that applies the custom bootstrap timeout to the Config.

Usage:

config := NewConfig(WithBootstrapTimeout(timeout))

func WithDiscoveryPort

func WithDiscoveryPort(port int) Option

WithDiscoveryPort configures the config to use a custom discovery port.

Parameters:

  • port: The discovery port to use.

Returns:

  • An Option that applies the custom discovery port to the Config.

Usage:

config := NewConfig(WithDiscoveryPort(port))

func WithHasher

func WithHasher(hashFn hash.Hasher) Option

WithHasher configures the cache engine to use a custom hashing function.

This option allows you to specify a custom hash function for key hashing, which can be useful for controlling hash collisions, performance, or cryptographic security.

Parameters:

  • hashFn: A hash.Hasher that defines the hashing function to be used for key hashing.

Returns:

  • Option: A functional option that applies the specified hashing function to the cache engine.

func WithInterface

func WithInterface(ifname string) Option

WithInterface configures the config to use a custom bind interface.

Interface denotes a binding interface. It can be used instead of BindAddr if the interface is known but not the address. If both are provided, then distcache verifies that the interface has the bind address that is provided.

Parameters:

  • ifname: The bind interface to use.

Returns:

  • An Option that applies the custom bind addr to the Config.

Usage:

config := NewConfig(WithInterface(ifname))

func WithJoinRetryInterval

func WithJoinRetryInterval(interval time.Duration) Option

WithJoinRetryInterval configures the config to use a custom join retry interval.

JoinRetryInterval is the time gap between attempts to join an existing cluster.

Parameters:

  • interval: The custom join retry interval.

Returns:

  • An Option that applies the custom retry interval to the Config.

Usage:

config := NewConfig(WithJoinRetryInterval(interval))

func WithKeepAlivePeriod

func WithKeepAlivePeriod(period time.Duration) Option

WithKeepAlivePeriod configures the config to use a custom keepAlive period.

KeepAlivePeriod denotes whether the operating system should send keep-alive messages on the connection.

Parameters:

  • period: The keep alive period.

Returns:

  • An Option that applies the custom keep alive period to the Config.

Usage:

config := NewConfig(WithKeepAlivePeriod(period))

func WithLabel added in v0.3.0

func WithLabel(label string) Option

WithLabel configures the distcache node with a specific label.

This label is used to identify the distcache node. It is required that all nodes in the cluster use the same label to ensure proper identification and grouping.

Parameters:

  • label: A string representing the label for the distcache node.

Returns:

  • Option: A functional option that applies the specified label to the distcache node.

func WithLogger

func WithLogger(logger log.Logger) Option

WithLogger configures the config to use a custom logger.

Parameters:

  • logger: An instance of log.Logger used for logging.

Returns:

  • An Option that applies the custom logger to the Config.

Usage:

config := NewConfig(WithLogger(myLogger))

func WithMaxJoinAttempts

func WithMaxJoinAttempts(maxAttempts int) Option

WithMaxJoinAttempts configures the config to use a custom max join attempts.

MaxJoinAttempts denotes the maximum number of attempts to join an existing cluster before forming a new one.

Parameters:

  • maxAttempts: The custom maximum join attempts.

Returns:

  • An Option that applies the custom maximum join attempts to the Config.

Usage:

config := NewConfig(WithMaxJoinAttempts(maxAttempts))

func WithMetrics added in v0.3.0

func WithMetrics(metricsConfig *otel.MetricConfig) Option

WithMetrics configures distcache to use the provided OpenTelemetry metric settings.

Use this option to supply a pre-built otel.MetricConfig (e.g., a custom MeterProvider or instrumentation name) for creating meters and instruments.

Parameters:

  • metricsConfig: A pointer to otel.MetricConfig that defines the MeterProvider and instrumentation name to be used.

Returns:

  • Option: A functional option that applies the metric configuration to distcache.

Usage:

cfg := NewConfig(WithMetrics(otel.NewMetricConfig()))

func WithMinimumPeersQuorum

func WithMinimumPeersQuorum(minQuorum int) Option

WithMinimumPeersQuorum configures the config to use a custom minimum peers quorum.

MinimumPeersQuorum denotes the minimum number of peers required to form a cluster.

Parameters:

  • minQuorum: The custom minimum peers quorum.

Returns:

  • An Option that applies the custom minimum peers quorum to the Config.

Usage:

config := NewConfig(WithMinimumPeersQuorum(minQuorum)

func WithReplicaCount

func WithReplicaCount(count int) Option

WithReplicaCount configures the config to use a custom replica count.

Parameters:

  • count: The custom replica count.

Returns:

  • An Option that applies the custom replica count to the Config.

Usage:

config := NewConfig(WithReplicaCount(count))

func WithShutdownTimeout

func WithShutdownTimeout(timeout time.Duration) Option

WithShutdownTimeout configures the config to use a custom shutdown timeout.

distcache will broadcast a leave message but will not shut down the background listeners, meaning the node will continue participating in gossip and state updates.

Sending a leave message will block until the leave message is successfully broadcast to a member of the cluster, if any exist or until a specified timeout is reached.

Parameters:

  • timeout: The custom shutdown timeout.

Returns:

  • An Option that applies the custom shutdown timeout to the Config.

Usage:

config := NewConfig(WithShutdownTimeout(timeout))

func WithTLS

func WithTLS(info *TLSInfo) Option

WithTLS configures the cache engine to use the specified TLS settings for both the Server and Client.

Ensure that both the Server and Client are configured with the same root Certificate Authority (CA) to enable successful handshake and mutual authentication.

This option allows secure communication by setting a custom TLS configuration for encrypting data in transit.

Parameters:

  • info: A pointer to TLSInfo struct that defines TLS settings, such as certificates, cipher suites, and authentication options.

Returns:

  • Option: A functional option that applies the TLS configuration to the cache engine.

func WithTracing added in v0.3.0

func WithTracing(traceConfig *otel.TracerConfig) Option

WithTracing configures distcache to use the provided OpenTelemetry tracing settings.

Use this option to supply a pre-built otel.TracerConfig (e.g., a custom TracerProvider or instrumentation name) for creating tracers and spans.

Parameters:

  • traceConfig: A pointer to otel.TracerConfig that defines the TracerProvider and instrumentation name to be used.

Returns:

  • Option: A functional option that applies the tracing configuration to distcache.

Usage:

cfg := NewConfig(WithTracing(otel.NewTracerConfig()))

type OptionFunc

type OptionFunc func(config *Config)

OptionFunc is a function type that implements the Option interface.

It allows functions to be used as configuration options for Config.

func (OptionFunc) Apply

func (f OptionFunc) Apply(config *Config)

Apply applies the OptionFunc to the given Config.

This enables the use of functions as dynamic configuration options.

type Peer

type Peer struct {
	// BindAddr denotes the address that Engine will bind to for communication
	// with other Engine nodes.
	BindAddr string `json:"bind_addr"`

	// BindPort denotes the address that Engine will bind to for communication
	// with other Engine nodes.
	BindPort int `json:"bind_port"`

	// DiscoveryPort denotes the port engine will use to discover other engine nodes
	// in the cluster
	DiscoveryPort int `json:"discovery_port"`

	// IsSelf denotes whether the given peer is the running node
	IsSelf bool `json:"is_self"`
}

Peer defines the discovery peer

func (Peer) Address

func (p Peer) Address() string

type TLSInfo

type TLSInfo struct {
	// ClientTLS defines the client TLS config
	ClientTLS *tls.Config
	// ServerTLS defines the server TLS config
	ServerTLS *tls.Config
}

Directories

Path Synopsis
internal
tcp
mocks

Jump to

Keyboard shortcuts

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