Documentation
¶
Overview ¶
Package kvs provides an in-memory key-value store implementation that supports sharding, batching, and transactions.
Index ¶
- type BatchDeleteResult
- type BatchGetResult
- type BatchSetResult
- type ErrCode
- type HashFunc
- type KeyValueStore
- func (kvs *KeyValueStore) BatchDelete(keys []string) (*BatchDeleteResult, error)
- func (kvs *KeyValueStore) BatchGet(keys []string) (*BatchGetResult, error)
- func (kvs *KeyValueStore) BatchSet(items map[string]Value) (*BatchSetResult, error)
- func (kvs *KeyValueStore) Close() error
- func (kvs *KeyValueStore) Delete(key string) error
- func (kvs *KeyValueStore) Exists(key string) bool
- func (kvs *KeyValueStore) Get(key string) (Value, error)
- func (kvs *KeyValueStore) Keys() ([]string, error)
- func (kvs *KeyValueStore) Len() int
- func (kvs *KeyValueStore) LoadSnapshot(filepath string) error
- func (kvs *KeyValueStore) SaveSnapshot(filepath string) error
- func (kvs *KeyValueStore) Set(key string, val Value) error
- func (kvs *KeyValueStore) SetWithTTL(key string, val Value, ttl time.Duration) error
- func (kvs *KeyValueStore) Size() string
- type Store
- type Value
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type BatchDeleteResult ¶ added in v0.0.2
type BatchDeleteResult struct {
Deleted int // Count of successfully deleted keys
Errors map[string]error // Failed deletions: key → error
}
BatchDeleteResult contains the results of a BatchDelete operation. Deleted count + len(Errors) == total input keys.
type BatchGetResult ¶ added in v0.0.2
type BatchGetResult struct {
Values map[string]Value // Successful retrievals: key → value
Errors map[string]error // Failed retrievals: key → error
}
BatchGetResult contains the results of a BatchGet operation. Keys appear in either Values (success) or Errors (failure), never both.
type BatchSetResult ¶ added in v0.0.2
type BatchSetResult struct {
Successful int // Count of successfully stored keys
Errors map[string]error // Failed operations: key → error
}
BatchSetResult contains the results of a BatchSet operation. Successful count + len(Errors) == total input items.
type HashFunc ¶ added in v0.0.2
HashFunc maps a key string to a shard index. Must be deterministic and return values in range [0, numShards).
type KeyValueStore ¶
type KeyValueStore struct {
// contains filtered or unexported fields
}
KeyValueStore is a type that implements the Store interface using an in-memory map.
func NewKeyValueStore ¶
func NewKeyValueStore(numShards int) (*KeyValueStore, error)
NewKeyValueStore creates a new KeyValueStore instance with a specified number of shards. Uses the default FNV-1a hash function for key distribution. Starts a background goroutine for TTL cleanup - call Close() to stop it.
func NewKeyValueStoreWithHash ¶ added in v0.0.2
func NewKeyValueStoreWithHash(numShards int, hashFunc HashFunc) (*KeyValueStore, error)
NewKeyValueStoreWithHash creates a new store with a custom hash function. The hash function maps keys to shard indices and must be deterministic.
Parameters:
- numShards: Number of shards (must be > 0)
- hashFunc: Custom hash function (must return [0, numShards))
Returns error if numShards <= 0 or hashFunc is nil. Default behavior: Use NewKeyValueStore() for FNV-1a hash.
IMPORTANT: The hash function MUST:
- Be deterministic (same key always returns same index)
- Return values in range [0, numShards)
- Be thread-safe (may be called concurrently)
func (*KeyValueStore) BatchDelete ¶ added in v0.0.2
func (kvs *KeyValueStore) BatchDelete(keys []string) (*BatchDeleteResult, error)
BatchDelete removes multiple keys with optimized locking. Returns count of successful deletions and per-key errors.
Thread-safe: Acquires Lock per shard (not per key) Complexity: O(N + M) where N=keys, M=shards touched Partial success: One key's error doesn't affect others Missing keys: Reported in Errors map with ErrNotFound
func (*KeyValueStore) BatchGet ¶ added in v0.0.2
func (kvs *KeyValueStore) BatchGet(keys []string) (*BatchGetResult, error)
BatchGet retrieves multiple keys in a single operation with optimized locking. Returns successful retrievals in Values map and per-key errors in Errors map.
Thread-safe: Acquires RLock per shard (not per key) Complexity: O(N + M) where N=keys, M=shards touched TTL-aware: Expired keys return ErrNotFound Partial success: One key's error doesn't affect others
func (*KeyValueStore) BatchSet ¶ added in v0.0.2
func (kvs *KeyValueStore) BatchSet(items map[string]Value) (*BatchSetResult, error)
BatchSet stores multiple key-value pairs with optimized locking. Returns count of successful operations and per-key errors.
Thread-safe: Acquires Lock per shard (not per key) Complexity: O(N + M) where N=items, M=shards touched Partial success: One key's error doesn't affect others Duplicate keys: Last value in input map wins
func (*KeyValueStore) Close ¶ added in v0.0.2
func (kvs *KeyValueStore) Close() error
Close gracefully shuts down the store, stopping background goroutines. Must be called to prevent goroutine leaks if TTL features were used.
Thread-safe: Can be called multiple times (idempotent) Blocks until: TTL cleanup goroutine terminates (timeout: 5 seconds) Post-close: All operations return ErrStoreClosed
func (*KeyValueStore) Delete ¶
func (kvs *KeyValueStore) Delete(key string) error
Delete removes the key-value pair associated with the given key from the store. If the key is not found in the store, it returns an error.
func (*KeyValueStore) Exists ¶ added in v0.0.2
func (kvs *KeyValueStore) Exists(key string) bool
Exists returns true if the key is present in the store, false otherwise. This method does NOT return an error for missing keys (unlike Get).
Thread-safe: Uses shard-level RLock Complexity: O(1) hash lookup + map access TTL-aware: Returns false for expired keys
func (*KeyValueStore) Get ¶
func (kvs *KeyValueStore) Get(key string) (Value, error)
Get retrieves the value associated with the given key from the store. If the key is not found in the store, it returns an error. TTL-aware: Returns ErrNotFound for expired keys (passive cleanup).
func (*KeyValueStore) Keys ¶
func (kvs *KeyValueStore) Keys() ([]string, error)
Keys returns a slice of all the keys in the store.
func (*KeyValueStore) Len ¶ added in v0.0.2
func (kvs *KeyValueStore) Len() int
Len returns the total number of key-value pairs across all shards. This operation is O(1) using an atomic counter maintained by Set/Delete.
Thread-safe: Uses atomic load Complexity: O(1) TTL-aware: Includes keys that haven't been cleaned up yet (eventual consistency)
func (*KeyValueStore) LoadSnapshot ¶ added in v0.0.2
func (kvs *KeyValueStore) LoadSnapshot(filepath string) error
LoadSnapshot replaces the current store contents with data from a snapshot file. All existing data is cleared before loading (replace semantics). Expired keys in the snapshot are skipped (not restored).
Thread-safe: Acquires Lock on all shards (exclusive access) Complexity: O(N * D) where N=keys, D=gob decode time Atomicity: All-or-nothing (corruption or error leaves store unchanged) Version check: Rejects unsupported snapshot formats
func (*KeyValueStore) SaveSnapshot ¶ added in v0.0.2
func (kvs *KeyValueStore) SaveSnapshot(filepath string) error
SaveSnapshot writes the current store contents to a file with a consistent point-in-time view. The snapshot includes all keys, values, and TTL metadata with CRC32 integrity checking.
Thread-safe: Acquires RLock per shard (concurrent with reads) Complexity: O(N * S) where N=keys per shard, S=gob encode time TTL persistence: Absolute expiration timestamps saved File format: Versioned binary with gob encoding
func (*KeyValueStore) Set ¶
func (kvs *KeyValueStore) Set(key string, val Value) error
Set adds or updates the given key-value pair in the store. If the key already exists, it overwrites the previous value.
func (*KeyValueStore) SetWithTTL ¶ added in v0.0.2
SetWithTTL stores a key-value pair with automatic expiration after the specified duration. The key will be automatically removed when TTL expires (active cleanup). Accessing an expired key returns ErrNotFound (passive cleanup).
Thread-safe: Acquires shard Lock Complexity: O(1) hash lookup + map insert TTL precision: ±50ms (background cleanup runs every 50ms) Zero TTL: Treated as no expiration Negative TTL: Returns ErrInvalidTTL
func (*KeyValueStore) Size ¶
func (kvs *KeyValueStore) Size() string
Size returns the size of the store in human-readable format.
type Store ¶
type Store interface {
// Get retrieves the value associated with the given key from the store.
// If the key is not found in the store, it returns an ErrNotFound error.
Get(key string) (Value, error)
// Set adds or updates the given key-value pair in the store.
// If the key already exists, it overwrites the previous value.
Set(key string, val Value) error
// Delete removes the key-value pair associated with the given key from the store.
// If the key is not found in the store, it returns an ErrNotFound error.
Delete(key string) error
// Keys returns a slice of all the keys in the store.
Keys() []string
}
Store is an interface that defines the methods that a key-value store must implement.
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
crawl-and-store
command
|
|
|
multi-thread
command
|
|
|
sharding-with-consistent-hashing
command
|