forked from rbaliyan/config
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.go
More file actions
261 lines (219 loc) · 7.69 KB
/
config.go
File metadata and controls
261 lines (219 loc) · 7.69 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
package config
import (
"context"
"fmt"
"github.com/rbaliyan/config/codec"
_ "github.com/rbaliyan/config/codec/json"
)
// Reader provides read-only access to configuration.
// Use this interface in application code to read config values.
//
// The Reader automatically uses an internal cache for resilience. If the backend
// store is temporarily unavailable, cached values will be returned. This ensures
// your application continues working even during database outages.
type Reader interface {
// Get retrieves a configuration value by key.
//
// Get uses an internal cache for resilience. If the store is unavailable,
// it will return a cached value if one exists. This is intentional - for
// use cases like feature flags and rate limits, having slightly stale
// configuration is better than failing completely.
Get(ctx context.Context, key string) (Value, error)
// Find returns a page of keys and values matching the filter.
// Use Page.NextCursor() to paginate through results.
Find(ctx context.Context, filter Filter) (Page, error)
}
// Writer provides write access to configuration.
// Use this interface for gRPC/HTTP servers to manage config.
type Writer interface {
// Set creates or updates a configuration value.
Set(ctx context.Context, key string, value any, opts ...SetOption) error
// Delete removes a configuration value by key.
Delete(ctx context.Context, key string) error
}
// Config combines Reader and Writer for a specific namespace.
type Config interface {
Reader
Writer
// Namespace returns the namespace name.
Namespace() string
}
// VersionedReader provides access to version history for a namespace.
// Obtained via type assertion on Config:
//
// if vr, ok := cfg.(config.VersionedReader); ok {
// // Get specific version
// page, _ := vr.GetVersions(ctx, "key", config.NewVersionFilter().WithVersion(3).Build())
// // List all versions
// page, _ := vr.GetVersions(ctx, "key", config.NewVersionFilter().WithLimit(10).Build())
// }
type VersionedReader interface {
// GetVersions retrieves version history for a configuration key.
// See VersionedStore.GetVersions for full semantics.
// Returns ErrVersioningNotSupported if the underlying store does not support versioning.
GetVersions(ctx context.Context, key string, filter VersionFilter) (VersionPage, error)
}
// nsConfig is the default Config implementation for a specific namespace.
type nsConfig struct {
namespace string
manager *manager
}
// Compile-time interface checks
var (
_ Config = (*nsConfig)(nil)
_ VersionedReader = (*nsConfig)(nil)
)
// Namespace returns the namespace name.
func (c *nsConfig) Namespace() string {
return c.namespace
}
// Get retrieves a configuration value by key.
// It first attempts to fetch from the store. If the store is unavailable,
// it falls back to cached values for resilience.
func (c *nsConfig) Get(ctx context.Context, key string) (Value, error) {
if !c.manager.isConnected() {
return nil, ErrManagerClosed
}
// Validate key
if err := ValidateKey(key); err != nil {
return nil, err
}
// Try to fetch from store first
value, err := c.manager.store.Get(ctx, c.namespace, key)
if err == nil {
// Update cache with fresh value
if cacheErr := c.manager.cache.Set(ctx, c.namespace, key, value); cacheErr != nil {
c.manager.logger.Warn("failed to cache value", "key", key, "error", cacheErr)
}
return value, nil
}
// If store error is NOT "not found", try cache as fallback for resilience
if !IsNotFound(err) {
if cachedValue, cacheErr := c.manager.cache.Get(ctx, c.namespace, key); cacheErr == nil {
c.manager.logger.Warn("serving stale cached value due to store error",
"namespace", c.namespace, "key", key, "store_error", err)
// Mark the value as stale so callers know it came from cache due to error
return MarkStale(cachedValue), nil
}
}
// Return original store error (either NotFound or connection error with no cache)
return nil, err
}
// Find returns a page of keys and values matching the filter.
func (c *nsConfig) Find(ctx context.Context, filter Filter) (Page, error) {
if !c.manager.isConnected() {
return nil, ErrManagerClosed
}
return c.manager.store.Find(ctx, c.namespace, filter)
}
// Set creates or updates a configuration value.
func (c *nsConfig) Set(ctx context.Context, key string, value any, opts ...SetOption) error {
if !c.manager.isConnected() {
return ErrManagerClosed
}
// Validate key
if err := ValidateKey(key); err != nil {
return err
}
// Apply options
setOpts := newSetOptions()
for _, opt := range opts {
opt(setOpts)
}
// Determine codec
codecToUse := c.manager.codec
if setOpts.codec != nil {
codecToUse = setOpts.codec
}
if codecToUse == nil {
codecToUse = codec.Default()
}
// Validate codec against store
if cv, ok := c.manager.store.(CodecValidator); ok {
if !cv.SupportsCodec(codecToUse.Name()) {
return &UnsupportedCodecError{Codec: codecToUse.Name(), Backend: fmt.Sprintf("%T", c.manager.store)}
}
}
// Determine type
typ := setOpts.typ
if typ == TypeUnknown {
typ = detectType(value)
}
// Create Value with write mode
val := NewValue(value,
WithValueCodec(codecToUse),
WithValueType(typ),
WithValueWriteMode(setOpts.writeMode),
)
// Enforce max keys per namespace on creates (skip for update-only mode)
if limit := c.manager.maxKeysPerNS; limit > 0 && setOpts.writeMode != WriteModeUpdate {
if err := c.checkNamespaceLimit(ctx, key, limit); err != nil {
return err
}
}
// Set in store - returns the stored value with updated metadata
newValue, err := c.manager.store.Set(ctx, c.namespace, key, val)
if err != nil {
return err
}
// Update cache with the returned value
if newValue != nil {
if cacheErr := c.manager.cache.Set(ctx, c.namespace, key, newValue); cacheErr != nil {
c.manager.logger.Warn("failed to cache value", "key", key, "error", cacheErr)
}
}
return nil
}
// Delete removes a configuration value by key.
func (c *nsConfig) Delete(ctx context.Context, key string) error {
if !c.manager.isConnected() {
return ErrManagerClosed
}
// Validate key
if err := ValidateKey(key); err != nil {
return err
}
if err := c.manager.store.Delete(ctx, c.namespace, key); err != nil {
return err
}
// Remove from cache
if cacheErr := c.manager.cache.Delete(ctx, c.namespace, key); cacheErr != nil {
c.manager.logger.Warn("failed to remove from cache", "key", key, "error", cacheErr)
}
return nil
}
// GetVersions retrieves version history for a configuration key.
// Returns ErrVersioningNotSupported if the underlying store does not support versioning.
func (c *nsConfig) GetVersions(ctx context.Context, key string, filter VersionFilter) (VersionPage, error) {
if !c.manager.isConnected() {
return nil, ErrManagerClosed
}
if err := ValidateKey(key); err != nil {
return nil, err
}
vs, ok := c.manager.store.(VersionedStore)
if !ok {
return nil, ErrVersioningNotSupported
}
if filter == nil {
filter = NewVersionFilter().Build()
}
return vs.GetVersions(ctx, c.namespace, key, filter)
}
// checkNamespaceLimit verifies the namespace has not exceeded its key limit.
// Only checks when the key does not already exist (updates are always allowed).
func (c *nsConfig) checkNamespaceLimit(ctx context.Context, key string, limit int) error {
// If the key already exists, this is an update -- no limit check needed
if _, err := c.manager.store.Get(ctx, c.namespace, key); err == nil {
return nil
}
// Count existing keys via Find with limit+1 to check if we're at capacity
page, err := c.manager.store.Find(ctx, c.namespace, NewFilter().WithPrefix("").WithLimit(limit+1).Build())
if err != nil {
return err
}
if len(page.Results()) >= limit {
return &NamespaceFullError{Namespace: c.namespace, Limit: limit}
}
return nil
}