Documentation
¶
Overview ¶
Package hive provides an embeddable, leaderless distributed cache for Go applications. Any Go application can include a Hive node to participate in a self-organizing cluster that shares in-memory state across instances without external infrastructure.
Basic usage:
node, err := hive.NewNode(hive.Config{
Mode: hive.ModeCluster,
Seeds: []string{"node1:7946", "node2:7946"},
})
if err != nil {
log.Fatal(err)
}
defer node.Shutdown()
cache := node.Cache()
sessions := hive.NewValueStore[Session](cache, "sessions")
users := hive.NewValueStore[User](cache, "users")
sessions.Set("abc", mySession)
val, err := sessions.Get("abc")
Index ¶
- Variables
- type Cache
- type ClusterStatus
- type Config
- type HashStore
- func (h *HashStore[T]) Del(key string) error
- func (h *HashStore[T]) Expire(key string, ttl time.Duration) error
- func (h *HashStore[T]) HDel(key, field string) error
- func (h *HashStore[T]) HExpireField(key, field string, ttl time.Duration) error
- func (h *HashStore[T]) HGet(key, field string) (T, error)
- func (h *HashStore[T]) HGetAll(key string) (map[string]T, error)
- func (h *HashStore[T]) HKeys(key string) ([]string, error)
- func (h *HashStore[T]) HSet(key, field string, value T) error
- func (h *HashStore[T]) HSetWithTTL(key, field string, value T, ttl time.Duration) error
- type ListStore
- func (l *ListStore[T]) Del(key string) error
- func (l *ListStore[T]) Expire(key string, ttl time.Duration) error
- func (l *ListStore[T]) LIndex(key string, index int) (T, error)
- func (l *ListStore[T]) LLen(key string) (int, error)
- func (l *ListStore[T]) LPop(key string) (T, error)
- func (l *ListStore[T]) LPush(key string, value T) error
- func (l *ListStore[T]) LRange(key string, start, stop int) ([]T, error)
- func (l *ListStore[T]) LSet(key string, index int, value T) error
- func (l *ListStore[T]) RPop(key string) (T, error)
- func (l *ListStore[T]) RPush(key string, value T) error
- type Mode
- type Node
- type SetStore
- func (s *SetStore) Del(key string) error
- func (s *SetStore) Expire(key string, ttl time.Duration) error
- func (s *SetStore) SAdd(key, member string) error
- func (s *SetStore) SCard(key string) (int, error)
- func (s *SetStore) SExpireMember(key, member string, ttl time.Duration) error
- func (s *SetStore) SIsMember(key, member string) (bool, error)
- func (s *SetStore) SMembers(key string) ([]string, error)
- func (s *SetStore) SRem(key, member string) error
- type ValueStore
- type ZSetEntry
- type ZSetStore
- func (z *ZSetStore) Del(key string) error
- func (z *ZSetStore) Expire(key string, ttl time.Duration) error
- func (z *ZSetStore) ZAdd(key string, score float64, member string) error
- func (z *ZSetStore) ZCard(key string) (int, error)
- func (z *ZSetStore) ZRange(key string, start, stop int) ([]ZSetEntry, error)
- func (z *ZSetStore) ZRangeByScore(key string, min, max float64) ([]ZSetEntry, error)
- func (z *ZSetStore) ZRank(key, member string) (int, error)
- func (z *ZSetStore) ZRem(key, member string) error
- func (z *ZSetStore) ZRevRank(key, member string) (int, error)
- func (z *ZSetStore) ZScore(key, member string) (float64, error)
Constants ¶
This section is empty.
Variables ¶
var ErrCapacityExceeded = store.ErrCapacityExceeded
ErrCapacityExceeded is returned by write operations when the node has reached its configured MemLimit. Scale the cluster horizontally to add capacity.
var ErrNotFound = cluster.ErrNotFound
ErrNotFound is returned by Get operations when the key or field does not exist or has expired.
Functions ¶
This section is empty.
Types ¶
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache is a handle to the cluster's data layer obtained from a Node. It is the entry point for store constructors and cluster-wide operations.
type ClusterStatus ¶
ClusterStatus is a point-in-time snapshot of cluster membership.
type Config ¶
type Config struct {
// NodeID is a unique identifier for this node.
// Defaults to a generated UUID if empty.
NodeID string
// Mode controls standalone vs cluster operation.
// Defaults to ModeStandalone.
Mode Mode
// BindAddr is the address this node listens on for peer communication.
// Defaults to "0.0.0.0".
BindAddr string
// BindPort is the port this node listens on for peer communication.
// Defaults to 7946.
BindPort int
// Seeds is a list of peer addresses (host:port) used to bootstrap
// cluster membership. At least one reachable seed is required when
// Mode is ModeCluster.
Seeds []string
// ReplicationFactor is the number of nodes that should hold a copy
// of each key. Must be <= cluster size. Defaults to 1.
ReplicationFactor int
// MemLimit is the maximum memory this node intends to use, in bytes.
// It is used to compute the node's virtual node count on the hash ring:
// nodes with more memory receive proportionally more keyspace.
// A value of 0 uses the default of 100 virtual nodes.
MemLimit uint64
// GossipInterval is how often this node sends heartbeats to peers.
// Defaults to 1s.
GossipInterval time.Duration
// GossipFanout is how many peers receive each heartbeat round.
// Defaults to 3.
GossipFanout int
// RebalanceDebounce is the delay after a topology change before
// rebalancing starts, to let the cluster stabilize.
// Defaults to 500ms.
RebalanceDebounce time.Duration
// CleanupInterval is how often the cluster janitor runs to evict dead peer
// tombstones and expired store entries.
// Default: 30s
CleanupInterval time.Duration
// LogLevel controls the verbosity of internal log output.
// nil defaults to slog.LevelError (quiet). Set explicitly to enable
// more verbose output, e.g. &slog.LevelInfo or &slog.LevelDebug.
LogLevel *slog.Level
}
Config holds all configuration for a Hive node.
type HashStore ¶
type HashStore[T any] struct { // contains filtered or unexported fields }
HashStore is a typed key/field/value store backed by a Cache. Keys are namespaced as {name}:h:{key} to prevent collisions with other stores on the same node.
streams := hive.NewHashStore[Stream](cache, "streams")
streams.HSet("user:123", "stream:abc", Stream{StartedAt: time.Now()})
streams.HExpireField("user:123", "stream:abc", 30*time.Minute)
func NewHashStore ¶
NewHashStore creates a typed hash store backed by cache. name is used as the namespace — use a distinct name per hash type.
func (*HashStore[T]) Expire ¶
Expire sets a key-level TTL. The entire hash is deleted after ttl elapses.
func (*HashStore[T]) HExpireField ¶
HExpireField sets a TTL on a single field. The field is evicted after ttl elapses without affecting other fields or the key itself.
func (*HashStore[T]) HGet ¶
HGet retrieves and decodes the value stored under key/field. Returns an error if the key or field does not exist or has expired.
func (*HashStore[T]) HGetAll ¶
HGetAll retrieves and decodes all live fields under key. Results are returned as alternating field/value pairs, same as Redis HGETALL.
type ListStore ¶
type ListStore[T any] struct { // contains filtered or unexported fields }
ListStore[T] is a distributed ordered list backed by a Cache. Each element is msgpack-encoded. Keys are namespaced as {name}:l:{key}.
queue := hive.NewListStore[Task](cache, "work_queue")
queue.RPush("jobs", task)
job, err := queue.LPop("jobs")
func NewListStore ¶
NewListStore creates a list store backed by cache. name is used as the namespace — use a distinct name per list.
func (*ListStore[T]) Expire ¶
Expire sets a key-level TTL. The entire list is deleted after ttl elapses.
func (*ListStore[T]) LIndex ¶
LIndex returns the element at index. Negative indices count from the tail. Returns ErrNotFound if the index is out of bounds.
func (*ListStore[T]) LPop ¶
LPop removes and returns the head element. Returns ErrNotFound if the list is empty.
func (*ListStore[T]) LRange ¶
LRange returns elements from start to stop inclusive. Negative indices are supported. Out-of-range bounds are clipped silently.
func (*ListStore[T]) LSet ¶
LSet overwrites the element at index. Returns ErrNotFound if out of bounds.
type Node ¶
type Node struct {
// contains filtered or unexported fields
}
Node is a single member of the Hive cluster. Create one per application instance via NewNode. Multiple stores can share a single Node.
func NewNode ¶
NewNode creates and starts a Hive node with the given configuration. In ModeCluster the node will attempt to contact Seeds and join the cluster. In ModeStandalone the node operates as a local in-memory cache only.
func (*Node) Cache ¶
Cache returns a handle to the cluster's data layer. Pass it to store constructors (NewValueStore, NewSetStore, NewHashStore). Multiple stores can share the same Cache.
func (*Node) Shutdown ¶
Shutdown gracefully stops the node, announcing departure to peers before closing all connections and stopping background workers.
func (*Node) Status ¶
func (n *Node) Status() ClusterStatus
Status returns a snapshot of the current cluster state.
type SetStore ¶
type SetStore struct {
// contains filtered or unexported fields
}
SetStore is a distributed string set backed by a Cache. Keys are namespaced as {name}:s:{key} to prevent collisions with other stores on the same node.
online := hive.NewSetStore(cache, "online_users")
online.SAdd("room:1", "user:123")
online.SExpireMember("room:1", "user:123", 30*time.Second)
func NewSetStore ¶
NewSetStore creates a set store backed by cache. name is used as the namespace — use a distinct name per set.
func (*SetStore) SExpireMember ¶
SExpireMember sets a TTL on a single member. The member is evicted after ttl elapses without affecting other members or the key itself.
func (*SetStore) SIsMember ¶
SIsMember reports whether member exists in the set at key and has not expired.
type ValueStore ¶
type ValueStore[T any] struct { // contains filtered or unexported fields }
ValueStore is a typed key/value store backed by a Cache. Keys are namespaced as {name}:v:{key} to prevent collisions with other stores on the same node.
sessions := hive.NewValueStore[Session](cache, "sessions") users := hive.NewValueStore[User](cache, "users")
func NewValueStore ¶
func NewValueStore[T any](cache *Cache, name string) *ValueStore[T]
NewValueStore creates a typed value store backed by cache. name is used as the namespace — use a distinct name per value type.
func (*ValueStore[T]) Del ¶
func (s *ValueStore[T]) Del(key string) error
Del removes key from the store.
func (*ValueStore[T]) Expire ¶
func (s *ValueStore[T]) Expire(key string, ttl time.Duration) error
Expire sets a TTL on key. The entry is deleted automatically after ttl elapses.
func (*ValueStore[T]) Get ¶
func (s *ValueStore[T]) Get(key string) (T, error)
Get retrieves and decodes the value stored under key. Returns an error if the key does not exist or has expired.
func (*ValueStore[T]) Set ¶
func (s *ValueStore[T]) Set(key string, value T) error
Set encodes value using msgpack and stores it under key.
type ZSetStore ¶
type ZSetStore struct {
// contains filtered or unexported fields
}
ZSetStore is a distributed sorted set backed by a Cache. Members are unique strings each associated with a float64 score. The set is always kept in ascending score order (ties broken lexicographically). Keys are namespaced as {name}:z:{key}.
scores := hive.NewZSetStore(cache, "leaderboard")
scores.ZAdd("game:1", 9500.0, "alice")
top, _ := scores.ZRange("game:1", -3, -1)
func NewZSetStore ¶
NewZSetStore creates a sorted-set store backed by cache.
func (*ZSetStore) Expire ¶
Expire sets a key-level TTL. The entire sorted set is deleted after ttl elapses.
func (*ZSetStore) ZRange ¶
ZRange returns members from rank start to rank stop inclusive. Negative indices count from the end (highest rank). Out-of-range bounds are clipped silently.
func (*ZSetStore) ZRangeByScore ¶
ZRangeByScore returns all members with min <= score <= max in ascending order.
func (*ZSetStore) ZRank ¶
ZRank returns the 0-based rank of member in ascending score order (lowest = 0). Returns ErrNotFound if member does not exist.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
cluster
Package cluster manages the node's membership in the Hive cluster, including peer tracking, consistent hashing, data routing, and rebalancing.
|
Package cluster manages the node's membership in the Hive cluster, including peer tracking, consistent hashing, data routing, and rebalancing. |
|
ring
Package ring implements a consistent hash ring with virtual nodes.
|
Package ring implements a consistent hash ring with virtual nodes. |
|
store
Package store provides a thread-safe, sharded in-memory store with TTL support.
|
Package store provides a thread-safe, sharded in-memory store with TTL support. |
|
transport
Package transport handles peer-to-peer communication between Hive nodes.
|
Package transport handles peer-to-peer communication between Hive nodes. |