-
Notifications
You must be signed in to change notification settings - Fork 42
/
valkeyrie.go
86 lines (65 loc) · 2.04 KB
/
valkeyrie.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Package valkeyrie Distributed Key/Value Store Abstraction Library written in Go.
package valkeyrie
import (
"context"
"sort"
"sync"
"github.com/kvtools/valkeyrie/store"
)
var (
constructorsMu sync.RWMutex
constructors = make(map[string]Constructor)
)
// Config the raw type of the store configurations.
type Config any
// Constructor The signature of a store constructor.
type Constructor func(ctx context.Context, endpoints []string, options Config) (store.Store, error)
// Register makes a store constructor available by the provided name.
// If Register is called twice with the same name or if constructor is nil, it panics.
func Register(name string, cttr Constructor) {
constructorsMu.Lock()
defer constructorsMu.Unlock()
if cttr == nil {
panic("valkeyrie: Register constructor is nil")
}
if _, dup := constructors[name]; dup {
panic("valkeyrie: Register called twice for constructor " + name)
}
constructors[name] = cttr
}
// Unregister Unregisters a store.
func Unregister(storeName string) {
constructorsMu.Lock()
defer constructorsMu.Unlock()
delete(constructors, storeName)
}
// UnregisterAllConstructors Unregisters all stores.
func UnregisterAllConstructors() {
constructorsMu.Lock()
defer constructorsMu.Unlock()
constructors = make(map[string]Constructor)
}
// Constructors returns a sorted list of the names of the registered constructors.
func Constructors() []string {
constructorsMu.RLock()
defer constructorsMu.RUnlock()
list := make([]string, 0, len(constructors))
for name := range constructors {
list = append(list, name)
}
sort.Strings(list)
return list
}
// NewStore creates a new store instance.
func NewStore(ctx context.Context, storeName string, endpoints []string, options Config) (store.Store, error) {
constructorsMu.RLock()
construct, ok := constructors[storeName]
constructorsMu.RUnlock()
if !ok {
return nil, &store.UnknownConstructorError{Store: storeName}
}
if construct == nil {
return nil, &store.UnknownConstructorError{Store: storeName}
}
return construct(ctx, endpoints, options)
}