gokv

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 14, 2025 License: MIT Imports: 34 Imported by: ? modules, 0 packages

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

README

Go-KV

GitHub Actions Workflow Status

Simple Distributed in-memory key/value store. GoKV provides high availability and fault tolerance which makes it suitable large-scale applications system without sacrificing performance and reliability. With GoKV, you can instantly create a fast, scalable, distributed system across a cluster of computers.

👋 Table Of Content

🖥️ Installation

go get github.com/tochemey/gokv

🏛️ Design

Go-KV is a distributed key/value store designed to synchronize data across a cluster of computers using the push-pull anti-entropy method. This ensures that updates made to a node are eventually propagated to all other nodes, maintaining eventual consistency within the system. Whenever a key/value entry is modified on any node, the entire state of that entry is replicated across the cluster. While Go-KV does not guarantee immediate consistency, it ensures that all nodes will converge to the same state over time. To control the frequency of synchronization, Go-KV provides a configurable parameter:syncInterval that defines how often nodes exchange data to reconcile differences.

  • Lower values lead to faster synchronization but increase network traffic.
  • Higher values reduce network overhead but may lead to longer delays in data propagation.

🎯 Features

  • Built-in client to interact with the cluster via the following apis:
    • Put: create key/value pair that is eventually distributed in the cluster of nodes. The key is a string and the value is a byte array. One can set an expiry to the key.
    • PutProto: to create a key/value pair where the value is a protocol buffer message
    • PutString: to create a key/value pair where the value is a string
    • PutAny: to create a key/value pair with a given Codec to encode the value type.
    • Get: retrieves the value of a given key from the cluster of nodes. This can return a false negative meaning that the key may exist but at the time of checking it is having yet to be replicated in the cluster.
    • GetProto: retrieves a protocol buffer message for a given key. This requires PutProto or Put to be used to set the value.
    • GetString: retrieves a string value for a given key. This requires PutString or Put to be used to set the value.
    • GetAny: retrieves any value type for a given key. This requires PutAny to be used to set the value.
    • List: retrieves the list of key/value pairs in the cluster at a point in time
    • Exists: check the existence of a given key in the cluster. This can return a false negative meaning that the key may exist but at the time of checking it is having yet to be replicated in the cluster.
    • Delete: delete a given key from the cluster. Node only deletes the key they own
  • Built-in janitor to remove expired entries. One can set the janitor execution interval. Bearing in mind of the eventual consistency of the Go-KV, one need to set that interval taking into consideration the syncInterval
  • Discovery API to implement custom nodes discovery provider. See: Discovery
  • Data encryption using the cookie and the set of secrets via the Config
  • Configuration can be customized. See Config
  • TLS Support. See Config
  • Comes bundled with some discovery providers that can help you hit the ground running:

💡 Use Cases

Go-KV is suitable for scenarios where high availability and fault tolerance are more critical than strict consistency, such as:

  • Service Discovery
  • Configuration Management
  • Decentralized Coordination
  • Distributed Caching

⚖️ Trade-offs

  • ✅ Highly Available – Nodes remain operational even in the presence of network partitions.
  • ✅ Fault Tolerant – Can recover from node failures without losing data permanently.
  • ❌ Eventual Consistency – No immediate guarantees that all nodes have the same data at any given moment.
  • ❌ Increased Network Traffic – Lower syncInterval values can lead to higher bandwidth usage.

📋 Example

There is an example on how to use it with NATs here

🌐 Builtin Discovery

nats

To use the nats discovery provider one needs to provide the following:

  • Server: the NATS Server address
  • Subject: the NATS subject to use
  • Timeout: the nodes discovery timeout
  • MaxJoinAttempts: the maximum number of attempts to connect an existing NATs server. Defaults to 5
  • ReconnectWait: the time to backoff after attempting a reconnect to a server that we were already connected to previously. Default to 2 seconds
  • DiscoveryPort: the discovery port of the running node
  • Host: the host address of the running node
dns

This provider performs nodes discovery based upon the domain name provided. This is very useful when doing local development using docker.

To use the DNS discovery provider one needs to provide the following:

  • DomainName: the domain name
  • IPv6: it states whether to lookup for IPv6 addresses.
static

This provider performs nodes discovery based upon the list of static hosts addresses. The address of each host is the form of host:port where port is the discovery port.

kubernetes

To get the kubernetes discovery working as expected, the following need to be set in the manifest files:

  • Namespace: the kubernetes namespace
  • DiscoveryPortName: the discovery port name
  • PortName: the client port name. This port is used by the built-in cluster client for the various operations on the key/value pair distributed store
  • PodLabels: the POD labels

Make sure to provide the right RBAC settings to be able to access the pods.

Documentation

Index

Constants

View Source
const (
	// NoExpiration is used to state there is no expiration
	NoExpiration time.Duration = -1
)

Variables

View Source
var (
	// ErrNodeNotStarted is returned when the cluster has not started
	ErrNodeNotStarted = errors.New("cluster node not started")
	// ErrKeyNotFound is return when the given key value is not found in the cluster
	ErrKeyNotFound        = errors.New("key not found")
	ErrClientNotConnected = errors.New("cluster client not connected")
)

Functions

This section is empty.

Types

type Client added in v0.1.1

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

Client defines the cluster client This client can connect to any Go-KV cluster node and retrieve data from other of the cluster.

func NewClient added in v0.1.1

func NewClient(host string, port int) *Client

NewClient creates an instance of the cluster Client host and port are a Go-KV cluster node host and port

func (*Client) Close added in v0.1.1

func (client *Client) Close() error

Close closes the client connection to the cluster

func (*Client) Delete added in v0.1.1

func (client *Client) Delete(ctx context.Context, key string) error

Delete deletes a given key from the cluster nolint

func (*Client) Exists added in v0.1.1

func (client *Client) Exists(ctx context.Context, key string) (bool, error)

Exists checks the existence of a given key in the cluster

func (*Client) Get added in v0.1.1

func (client *Client) Get(ctx context.Context, key string) (*Entry, error)

Get retrieves the value of the given key from the cluster

func (*Client) GetAny added in v0.1.1

func (client *Client) GetAny(ctx context.Context, key string, codec Codec) (any, error)

GetAny retrieves the value of the given from the cluster Prior to calling this method one must set a string as the value of the key

func (*Client) GetProto added in v0.1.1

func (client *Client) GetProto(ctx context.Context, key string, dst proto.Message) error

GetProto retrieves the value of the given from the cluster as protocol buffer message Prior to calling this method one must set a proto message as the value of the key

func (*Client) GetString added in v0.1.1

func (client *Client) GetString(ctx context.Context, key string) (string, error)

GetString retrieves the value of the given from the cluster as a string Prior to calling this method one must set a string as the value of the key

func (*Client) List added in v0.1.1

func (client *Client) List(ctx context.Context) ([]*Entry, error)

List returns the list of entries at a point in time

func (*Client) Put added in v0.1.1

func (client *Client) Put(ctx context.Context, entry *Entry, expiration time.Duration) error

Put distributes the key/value pair in the cluster

func (*Client) PutAny added in v0.1.1

func (client *Client) PutAny(ctx context.Context, key string, value any, expiration time.Duration, codec Codec) error

PutAny distributes the key/value pair in the cluster. A binary encoder is required to properly encode the value.

func (*Client) PutProto added in v0.1.1

func (client *Client) PutProto(ctx context.Context, key string, value proto.Message, expiration time.Duration) error

PutProto creates a key/value pair where the value is a proto message and distributes in the cluster

func (*Client) PutString added in v0.1.1

func (client *Client) PutString(ctx context.Context, key string, value string, expiration time.Duration) error

PutString creates a key/value pair where the value is a string and distributes in the cluster

type Codec added in v0.1.1

type Codec interface {
	// Encode encodes the receiver into a binary form and returns the result.
	Encode(any) ([]byte, error)
	// Decode decodes a binary message
	Decode([]byte) (any, error)
}

Codec will be implemented to encode and decode message

type Config added in v0.1.1

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

Config defines the cluster config

func NewConfig added in v0.1.1

func NewConfig() *Config

NewConfig creates an instance of Config with the required default values

func (*Config) Validate added in v0.1.1

func (config *Config) Validate() error

Validate implements validation.Validator.

func (*Config) WithCleanerJobInterval added in v0.1.1

func (config *Config) WithCleanerJobInterval(interval time.Duration) *Config

WithCleanerJobInterval sets the Node cleaning job interval This helps remove expired entries on the localState of the given node

func (*Config) WithDiscoveryPort added in v0.1.1

func (config *Config) WithDiscoveryPort(port uint16) *Config

WithDiscoveryPort sets the discovery port

func (*Config) WithDiscoveryProvider added in v0.1.1

func (config *Config) WithDiscoveryProvider(provider discovery.Provider) *Config

WithDiscoveryProvider sets the discovery provider

func (*Config) WithEncryption added in v0.1.1

func (config *Config) WithEncryption(cookie string, secretKeys []string) *Config

WithEncryption defines the cookie and the secret keys cookie is a set of bytes to use as authentication label This has to be the same within the cluster to ensure smooth GCM authenticated data reference: https://en.wikipedia.org/wiki/Galois/Counter_Mode

A list of base64 encoded keys. Each key should be either 16, 24, or 32 bytes when decoded to select AES-128, AES-192, or AES-256 respectively. The first key in the list will be used for encrypting outbound messages. All keys are attempted when decrypting gossip, which allows for rotations. These keys should be the same for all nodes in the cluster

func (*Config) WithHost added in v0.1.1

func (config *Config) WithHost(host string) *Config

WithHost specifies the config host

func (*Config) WithJoinRetryInterval added in v0.1.1

func (config *Config) WithJoinRetryInterval(interval time.Duration) *Config

WithJoinRetryInterval sets the join retry interval

func (*Config) WithLogger added in v0.1.1

func (config *Config) WithLogger(logger log.Logger) *Config

WithLogger sets the logger

func (*Config) WithMaxJoinAttempts added in v0.1.1

func (config *Config) WithMaxJoinAttempts(max int) *Config

WithMaxJoinAttempts sets the max join attempts

func (*Config) WithPort added in v0.1.1

func (config *Config) WithPort(port uint16) *Config

WithPort sets the client port

func (*Config) WithReadTimeout added in v0.1.1

func (config *Config) WithReadTimeout(timeout time.Duration) *Config

WithReadTimeout sets the Node read timeout. This timeout specifies the timeout of a data retrieval The read timeout should be either greater or equal to syncInterval

func (*Config) WithShutdownTimeout added in v0.1.1

func (config *Config) WithShutdownTimeout(timeout time.Duration) *Config

WithShutdownTimeout sets the timeout

func (*Config) WithSyncInterval added in v0.1.1

func (config *Config) WithSyncInterval(interval time.Duration) *Config

WithSyncInterval sets the cluster synchronization interval. This is the interval between complete states synchronization between nodes. Complete states synchronization are done with a single node over TCP and are quite expensive relative to standard gossiped messages. Setting this interval lower (more frequent) will increase convergence speeds across larger clusters at the expense of increased bandwidth usage.

func (*Config) WithTLS added in v0.2.0

func (config *Config) WithTLS(tlConfig *tls.Config) *Config

WithTLS configures 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.

In cluster mode, all nodes must share the same root CA to establish secure communication and complete handshakes successfully.

type Entry added in v0.1.1

type Entry struct {
	// Key represents the key
	Key string
	// Value represents the value
	Value []byte
}

Entry represents the key/value pair

type Event added in v0.1.1

type Event struct {
	Member *Member
	Time   time.Time
	Type   EventType
}

Event defines the cluster event

type EventType added in v0.1.1

type EventType int
const (
	NodeJoined EventType = iota
	NodeLeft
	NodeDead
)

func (EventType) String added in v0.1.1

func (et EventType) String() string

type Member added in v0.1.1

type Member struct {
	Name          string
	Host          string
	Port          uint16
	DiscoveryPort uint16
	CreatedAt     time.Time
}

Member specifies the cluster member

func (*Member) DiscoveryAddress added in v0.1.1

func (m *Member) DiscoveryAddress() string

DiscoveryAddress returns the member discoveryAddress

type Node added in v0.1.1

type Node struct {
	internalpbconnect.UnimplementedKVServiceHandler
	// contains filtered or unexported fields
}

Node defines the cluster node

func NewNode

func NewNode(config *Config) (*Node, error)

NewNode creates a distributed key/value store cluster node

func (*Node) Client added in v0.1.1

func (node *Node) Client() *Client

Client returns the cluster Client

func (*Node) Delete added in v0.1.1

Delete is used to remove a key/value pair from a cluster of nodes nolint

func (*Node) Events added in v0.1.1

func (node *Node) Events() <-chan *Event

Events returns a channel where cluster events are published

func (*Node) Get added in v0.1.1

Get is used to retrieve a key/value pair in a cluster of nodes

func (*Node) HostPort added in v0.1.1

func (node *Node) HostPort() string

HostPort returns the node host:port address

func (*Node) KeyExists added in v0.1.1

KeyExists is used to check the existence of a given key in the cluster nolint

func (*Node) Leader added in v0.1.1

func (node *Node) Leader() (*Member, error)

Leader returns the eldest member of the cluster Leadership here is based upon node time creation

func (*Node) List added in v0.1.1

List returns the list of all entries at a given point in time nolint

func (*Node) Peers added in v0.1.1

func (node *Node) Peers() ([]*Member, error)

Peers returns the list of peers

func (*Node) Put added in v0.1.1

Put is used to distribute a key/value pair across a cluster of nodes nolint

func (*Node) Start added in v0.1.1

func (node *Node) Start(ctx context.Context) error

Start starts the cluster node

func (*Node) Stop added in v0.1.1

func (node *Node) Stop(ctx context.Context) error

Stop stops gracefully the cluster node

func (*Node) Whoami added in v0.1.1

func (node *Node) Whoami() *Member

Whoami returns the node member data

Jump to

Keyboard shortcuts

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