forked from rbaliyan/config
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalue.go
More file actions
537 lines (470 loc) · 14.1 KB
/
value.go
File metadata and controls
537 lines (470 loc) · 14.1 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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
package config
import (
"encoding/json"
"fmt"
"math"
"strconv"
"time"
"github.com/rbaliyan/config/codec"
)
// Value provides type-safe access to configuration values.
// This interface is focused on read operations. Write-related concerns
// like WriteMode are accessed via the WriteModer interface.
type Value interface {
// Marshal serializes the value to bytes using the configured codec.
Marshal() ([]byte, error)
// Unmarshal deserializes the value into the target.
Unmarshal(v any) error
// Type returns the detected type of the value.
Type() Type
// Codec returns the codec name used for this value.
Codec() string
// Int64 returns the value as int64.
Int64() (int64, error)
// Float64 returns the value as float64.
Float64() (float64, error)
// String returns the value as string.
String() (string, error)
// Bool returns the value as bool.
Bool() (bool, error)
// Metadata returns associated metadata, if any.
Metadata() Metadata
}
// WriteModer is an optional interface for values that carry write mode hints.
// Store implementations check for this interface in Set operations to determine
// conditional write behavior (create-only, update-only, or upsert).
type WriteModer interface {
WriteMode() WriteMode
}
// Metadata provides version and timestamp information for stored values.
type Metadata interface {
// Version returns the version number of the value.
Version() int64
// CreatedAt returns when the value was first created.
CreatedAt() time.Time
// UpdatedAt returns when the value was last modified.
UpdatedAt() time.Time
// IsStale returns true if this value was served from cache due to a store error.
// When true, the value may be outdated. Applications can use this to:
// - Log warnings about stale data
// - Show degraded UI indicators
// - Trigger background refresh
IsStale() bool
}
// storeMetadata extends Metadata with internal fields used by store implementations.
type storeMetadata interface {
Metadata
// EntryID returns the unique storage identifier for this entry.
// This is the database ID (e.g., PostgreSQL BIGSERIAL, MongoDB ObjectID).
// Used internally for pagination and store operations.
EntryID() string
}
// val is the concrete Value implementation.
type val struct {
raw any
data []byte
dataType Type
codec codec.Codec
metadata *valueMetadata
writeMode WriteMode
}
// valueMetadata implements Metadata and StoreMetadata interfaces.
type valueMetadata struct {
version int64
createdAt time.Time
updatedAt time.Time
entryID string // Internal: database-level entry ID for store operations
stale bool // True if served from cache due to store error
}
func (m *valueMetadata) Version() int64 { return m.version }
func (m *valueMetadata) CreatedAt() time.Time { return m.createdAt }
func (m *valueMetadata) UpdatedAt() time.Time { return m.updatedAt }
func (m *valueMetadata) EntryID() string { return m.entryID }
func (m *valueMetadata) IsStale() bool { return m.stale }
// Compile-time interface checks for valueMetadata
var (
_ Metadata = (*valueMetadata)(nil)
_ storeMetadata = (*valueMetadata)(nil)
)
// ValueOption configures a value during construction.
type ValueOption func(*val)
// WithCodec sets the codec for the value.
func WithValueCodec(c codec.Codec) ValueOption {
return func(v *val) {
v.codec = c
}
}
// WithValueType sets the type for the value.
func WithValueType(t Type) ValueOption {
return func(v *val) {
v.dataType = t
}
}
// WithValueMetadata sets metadata for the value.
func WithValueMetadata(version int64, createdAt, updatedAt time.Time) ValueOption {
return func(v *val) {
if v.metadata == nil {
v.metadata = &valueMetadata{}
}
v.metadata.version = version
v.metadata.createdAt = createdAt
v.metadata.updatedAt = updatedAt
}
}
// WithValueEntryID sets the internal entry ID for the value.
// This is used by store implementations to track the database-level ID.
// Not intended for end-user code.
func WithValueEntryID(id string) ValueOption {
return func(v *val) {
if v.metadata == nil {
v.metadata = &valueMetadata{}
}
v.metadata.entryID = id
}
}
// WithValueStale marks the value as stale (served from cache due to store error).
// This is used internally by the Manager when falling back to cached values.
func WithValueStale(stale bool) ValueOption {
return func(v *val) {
if v.metadata == nil {
v.metadata = &valueMetadata{}
}
v.metadata.stale = stale
}
}
// WithValueWriteMode sets the write mode for the value.
func WithValueWriteMode(mode WriteMode) ValueOption {
return func(v *val) {
v.writeMode = mode
}
}
// rawCodec is a codec placeholder for values whose encoding is managed
// externally (e.g., client-side encryption). It preserves the codec name
// but refuses to encode or decode — the server treats the bytes as opaque.
type rawCodec struct {
name string
}
func (r *rawCodec) Name() string { return r.name }
func (r *rawCodec) Encode(any) ([]byte, error) {
return nil, fmt.Errorf("rawCodec %q: encode not supported", r.name)
}
func (r *rawCodec) Decode([]byte, any) error {
return fmt.Errorf("rawCodec %q: decode not supported", r.name)
}
// Compile-time interface check for rawCodec.
var _ codec.Codec = (*rawCodec)(nil)
// NewRawValue creates a Value holding pre-marshaled bytes without decoding.
// The bytes are stored as-is and returned verbatim by Marshal().
// This is used when the server does not have the codec registered (e.g.,
// client-side encrypted data) and should pass the bytes through opaquely.
func NewRawValue(data []byte, codecName string, opts ...ValueOption) Value {
v := &val{
raw: data, // non-nil so Marshal returns v.data
data: data,
dataType: TypeCustom,
codec: &rawCodec{name: codecName},
}
for _, opt := range opts {
opt(v)
}
return v
}
// NewValue creates a Value from any data with optional configuration.
func NewValue(data any, opts ...ValueOption) Value {
v := &val{
raw: data,
dataType: detectType(data),
codec: codec.Default(),
}
for _, opt := range opts {
opt(v)
}
return v
}
// NewValueFromBytes creates a Value from encoded bytes.
// If the named codec is not registered and differs from the default codec,
// the bytes are stored as a raw pass-through value (see NewRawValue).
func NewValueFromBytes(data []byte, codecName string, opts ...ValueOption) (Value, error) {
c := codec.Get(codecName)
if c == nil {
if codecName != "" && codecName != codec.Default().Name() {
return NewRawValue(data, codecName, opts...), nil
}
c = codec.Default()
}
var raw any
if err := c.Decode(data, &raw); err != nil {
return nil, fmt.Errorf("decode value: %w", err)
}
v := &val{
raw: raw,
data: data,
dataType: detectType(raw),
codec: c,
}
for _, opt := range opts {
opt(v)
}
return v, nil
}
// MarkStale returns a copy of the value with the stale flag set.
// This is used when serving cached values due to store errors.
// The returned value's Metadata().IsStale() will return true.
func MarkStale(v Value) Value {
if v == nil {
return nil
}
// If it's our val type, we can copy it efficiently
if src, ok := v.(*val); ok {
cp := &val{
raw: src.raw,
data: src.data,
dataType: src.dataType,
codec: src.codec,
writeMode: src.writeMode,
}
// Copy metadata and set stale flag
if src.metadata != nil {
cp.metadata = &valueMetadata{
version: src.metadata.version,
createdAt: src.metadata.createdAt,
updatedAt: src.metadata.updatedAt,
entryID: src.metadata.entryID,
stale: true,
}
} else {
cp.metadata = &valueMetadata{stale: true}
}
return cp
}
// For other Value implementations, wrap with stale metadata
// This shouldn't happen in practice since we control all Value creation
return &staleValueWrapper{Value: v}
}
// staleValueWrapper wraps a Value to indicate it's stale.
type staleValueWrapper struct {
Value
}
func (w *staleValueWrapper) Metadata() Metadata {
return &staleMetadataWrapper{Metadata: w.Value.Metadata()}
}
// staleMetadataWrapper wraps Metadata to return stale=true.
type staleMetadataWrapper struct {
Metadata
}
func (w *staleMetadataWrapper) IsStale() bool {
return true
}
// Compile-time interface check
var _ Value = (*val)(nil)
// Marshal serializes the value to bytes using the configured codec.
func (v *val) Marshal() ([]byte, error) {
if v.raw == nil {
return nil, ErrInvalidValue
}
// If we already have encoded data and it matches the raw value, return it
if v.data != nil {
return v.data, nil
}
return v.codec.Encode(v.raw)
}
// Unmarshal deserializes the value into the target.
func (v *val) Unmarshal(target any) error {
if v.raw == nil {
return ErrInvalidValue
}
// If we have raw bytes, use the codec
if v.data != nil && v.codec != nil {
return v.codec.Decode(v.data, target)
}
// Otherwise use JSON round-trip
data, err := json.Marshal(v.raw)
if err != nil {
return fmt.Errorf("%w: marshal failed: %w", ErrTypeMismatch, err)
}
if err := json.Unmarshal(data, target); err != nil {
return fmt.Errorf("%w: unmarshal failed: %w", ErrTypeMismatch, err)
}
return nil
}
// Type returns the detected type of the value.
func (v *val) Type() Type {
return v.dataType
}
// Codec returns the codec name.
func (v *val) Codec() string {
if v.codec != nil {
return v.codec.Name()
}
return "json"
}
// Metadata returns associated metadata.
func (v *val) Metadata() Metadata {
if v.metadata == nil {
return &valueMetadata{}
}
return v.metadata
}
// WriteMode returns the write mode for this value.
func (v *val) WriteMode() WriteMode {
return v.writeMode
}
// Compile-time interface check
var _ WriteModer = (*val)(nil)
// GetWriteMode extracts the write mode from a Value.
// Returns WriteModeUpsert (default) if the value does not implement WriteModer.
// Store implementations should use this instead of calling WriteMode() directly.
func GetWriteMode(v Value) WriteMode {
if wm, ok := v.(WriteModer); ok {
return wm.WriteMode()
}
return WriteModeUpsert
}
// Int64 returns the value as int64.
// Returns an error if the value cannot be converted to int64.
func (v *val) Int64() (int64, error) {
if v.raw == nil {
return 0, ErrNotFound
}
switch val := v.raw.(type) {
case int:
return int64(val), nil
case int8:
return int64(val), nil
case int16:
return int64(val), nil
case int32:
return int64(val), nil
case int64:
return val, nil
case float32:
if float32(int64(val)) != val {
return 0, fmt.Errorf("%w: cannot convert float32 %v to int64 without truncation", ErrTypeMismatch, val)
}
return int64(val), nil
case float64:
if val != math.Trunc(val) || math.IsInf(val, 0) || math.IsNaN(val) {
return 0, fmt.Errorf("%w: cannot convert float64 %v to int64 without truncation", ErrTypeMismatch, val)
}
return int64(val), nil
case string:
if i, err := strconv.ParseInt(val, 10, 64); err == nil {
return i, nil
}
return 0, fmt.Errorf("%w: cannot convert string %q to int64", ErrTypeMismatch, val)
case json.Number:
if i, err := val.Int64(); err == nil {
return i, nil
}
return 0, fmt.Errorf("%w: cannot convert json.Number to int64", ErrTypeMismatch)
}
return 0, fmt.Errorf("%w: cannot convert %T to int64", ErrTypeMismatch, v.raw)
}
// Float64 returns the value as float64.
// Returns an error if the value cannot be converted to float64.
func (v *val) Float64() (float64, error) {
if v.raw == nil {
return 0, ErrNotFound
}
switch val := v.raw.(type) {
case float64:
return val, nil
case float32:
return float64(val), nil
case int:
return float64(val), nil
case int8:
return float64(val), nil
case int16:
return float64(val), nil
case int32:
return float64(val), nil
case int64:
return float64(val), nil
case string:
if f, err := strconv.ParseFloat(val, 64); err == nil {
return f, nil
}
return 0, fmt.Errorf("%w: cannot convert string %q to float64", ErrTypeMismatch, val)
case json.Number:
if f, err := val.Float64(); err == nil {
return f, nil
}
return 0, fmt.Errorf("%w: cannot convert json.Number to float64", ErrTypeMismatch)
}
return 0, fmt.Errorf("%w: cannot convert %T to float64", ErrTypeMismatch, v.raw)
}
// String returns the value as string.
// Returns an error if the value is nil.
func (v *val) String() (string, error) {
if v.raw == nil {
return "", ErrNotFound
}
switch val := v.raw.(type) {
case string:
return val, nil
case []byte:
return string(val), nil
default:
return fmt.Sprintf("%v", val), nil
}
}
// Bool returns the value as bool.
// Returns an error if the value cannot be converted to bool.
func (v *val) Bool() (bool, error) {
if v.raw == nil {
return false, ErrNotFound
}
switch val := v.raw.(type) {
case bool:
return val, nil
case int:
return val != 0, nil
case int64:
return val != 0, nil
case float64:
return val != 0, nil
case string:
if b, err := strconv.ParseBool(val); err == nil {
return b, nil
}
return false, fmt.Errorf("%w: cannot convert string %q to bool", ErrTypeMismatch, val)
}
return false, fmt.Errorf("%w: cannot convert %T to bool", ErrTypeMismatch, v.raw)
}
// Helper functions
// detectType maps a Go value to its config Type.
// It handles JSON-decoded numbers (float64 that are actually integers,
// json.Number) and unsigned integer types.
//
// Note: whole float64 values (e.g. 42.0) are classified as TypeInt because
// JSON decodes all numbers as float64. As a result, a float64 that is a whole
// number will have TypeInt, which can cause the detected type to change across
// a JSON round-trip (a TypeFloat 42.0 stored and retrieved via a JSON codec
// may come back as TypeInt). Callers that need TypeFloat should set the type
// explicitly with WithValueType(TypeFloat).
func detectType(data any) Type {
switch val := data.(type) {
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
return TypeInt
case float64:
// JSON decodes all numbers as float64; detect integers.
if val == math.Trunc(val) && !math.IsInf(val, 0) && !math.IsNaN(val) {
return TypeInt
}
return TypeFloat
case float32:
return TypeFloat
case json.Number:
if _, err := val.Int64(); err == nil {
return TypeInt
}
return TypeFloat
case string:
return TypeString
case bool:
return TypeBool
default:
return TypeCustom
}
}