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
|
package config
import (
"fmt"
"reflect"
"strings"
"time"
)
// ConfigWithDefaults defines an interface for configurations that can apply their own defaults
type ConfigWithDefaults interface {
// ApplySchemaDefaults applies default values using the provided schema
ApplySchemaDefaults(schema *Schema) error
// Validate validates the configuration
Validate() error
}
// FieldType defines the type of a configuration field
type FieldType string
const (
FieldTypeBool FieldType = "bool"
FieldTypeInt FieldType = "int"
FieldTypeDuration FieldType = "duration"
FieldTypeInterval FieldType = "interval"
FieldTypeString FieldType = "string"
FieldTypeFloat FieldType = "float"
)
// FieldUnit defines the unit for display purposes
type FieldUnit string
const (
UnitSeconds FieldUnit = "seconds"
UnitMinutes FieldUnit = "minutes"
UnitHours FieldUnit = "hours"
UnitDays FieldUnit = "days"
UnitCount FieldUnit = "count"
UnitNone FieldUnit = ""
)
// Field defines a configuration field with all its metadata
type Field struct {
// Field identification
Name string `json:"name"`
JSONName string `json:"json_name"`
Type FieldType `json:"type"`
// Default value and validation
DefaultValue interface{} `json:"default_value"`
MinValue interface{} `json:"min_value,omitempty"`
MaxValue interface{} `json:"max_value,omitempty"`
Required bool `json:"required"`
// UI display
DisplayName string `json:"display_name"`
Description string `json:"description"`
HelpText string `json:"help_text"`
Placeholder string `json:"placeholder"`
Unit FieldUnit `json:"unit"`
// Form rendering
InputType string `json:"input_type"` // "checkbox", "number", "text", "interval", etc.
CSSClasses string `json:"css_classes,omitempty"`
}
// GetDisplayValue returns the value formatted for display in the specified unit
func (f *Field) GetDisplayValue(value interface{}) interface{} {
if (f.Type == FieldTypeDuration || f.Type == FieldTypeInterval) && f.Unit != UnitSeconds {
if duration, ok := value.(time.Duration); ok {
switch f.Unit {
case UnitMinutes:
return int(duration.Minutes())
case UnitHours:
return int(duration.Hours())
case UnitDays:
return int(duration.Hours() / 24)
}
}
if seconds, ok := value.(int); ok {
switch f.Unit {
case UnitMinutes:
return seconds / 60
case UnitHours:
return seconds / 3600
case UnitDays:
return seconds / (24 * 3600)
}
}
}
return value
}
// GetIntervalDisplayValue returns the value and unit for interval fields
func (f *Field) GetIntervalDisplayValue(value interface{}) (int, string) {
if f.Type != FieldTypeInterval {
return 0, "minutes"
}
seconds := 0
if duration, ok := value.(time.Duration); ok {
seconds = int(duration.Seconds())
} else if s, ok := value.(int); ok {
seconds = s
}
return SecondsToIntervalValueUnit(seconds)
}
// SecondsToIntervalValueUnit converts seconds to the most appropriate interval unit
func SecondsToIntervalValueUnit(totalSeconds int) (int, string) {
if totalSeconds == 0 {
return 0, "minutes"
}
// Check if it's evenly divisible by days
if totalSeconds%(24*3600) == 0 {
return totalSeconds / (24 * 3600), "days"
}
// Check if it's evenly divisible by hours
if totalSeconds%3600 == 0 {
return totalSeconds / 3600, "hours"
}
// Default to minutes
return totalSeconds / 60, "minutes"
}
// IntervalValueUnitToSeconds converts interval value and unit to seconds
func IntervalValueUnitToSeconds(value int, unit string) int {
switch unit {
case "days":
return value * 24 * 3600
case "hours":
return value * 3600
case "minutes":
return value * 60
default:
return value * 60 // Default to minutes
}
}
// ParseDisplayValue converts a display value back to the storage format
func (f *Field) ParseDisplayValue(displayValue interface{}) interface{} {
if (f.Type == FieldTypeDuration || f.Type == FieldTypeInterval) && f.Unit != UnitSeconds {
if val, ok := displayValue.(int); ok {
switch f.Unit {
case UnitMinutes:
return val * 60
case UnitHours:
return val * 3600
case UnitDays:
return val * 24 * 3600
}
}
}
return displayValue
}
// ParseIntervalFormData parses form data for interval fields (value + unit)
func (f *Field) ParseIntervalFormData(valueStr, unitStr string) (int, error) {
if f.Type != FieldTypeInterval {
return 0, fmt.Errorf("field %s is not an interval field", f.Name)
}
value := 0
if valueStr != "" {
var err error
value, err = fmt.Sscanf(valueStr, "%d", &value)
if err != nil {
return 0, fmt.Errorf("invalid interval value: %s", valueStr)
}
}
return IntervalValueUnitToSeconds(value, unitStr), nil
}
// ValidateValue validates a value against the field constraints
func (f *Field) ValidateValue(value interface{}) error {
if f.Required && (value == nil || value == "" || value == 0) {
return fmt.Errorf("%s is required", f.DisplayName)
}
if f.MinValue != nil {
if !f.compareValues(value, f.MinValue, ">=") {
return fmt.Errorf("%s must be >= %v", f.DisplayName, f.MinValue)
}
}
if f.MaxValue != nil {
if !f.compareValues(value, f.MaxValue, "<=") {
return fmt.Errorf("%s must be <= %v", f.DisplayName, f.MaxValue)
}
}
return nil
}
// compareValues compares two values based on the operator
func (f *Field) compareValues(a, b interface{}, op string) bool {
switch f.Type {
case FieldTypeInt:
aVal, aOk := a.(int)
bVal, bOk := b.(int)
if !aOk || !bOk {
return false
}
switch op {
case ">=":
return aVal >= bVal
case "<=":
return aVal <= bVal
}
case FieldTypeFloat:
aVal, aOk := a.(float64)
bVal, bOk := b.(float64)
if !aOk || !bOk {
return false
}
switch op {
case ">=":
return aVal >= bVal
case "<=":
return aVal <= bVal
}
}
return true
}
// Schema provides common functionality for configuration schemas
type Schema struct {
Fields []*Field `json:"fields"`
}
// GetFieldByName returns a field by its JSON name
func (s *Schema) GetFieldByName(jsonName string) *Field {
for _, field := range s.Fields {
if field.JSONName == jsonName {
return field
}
}
return nil
}
// ApplyDefaultsToConfig applies defaults to a configuration that implements ConfigWithDefaults
func (s *Schema) ApplyDefaultsToConfig(config ConfigWithDefaults) error {
return config.ApplySchemaDefaults(s)
}
// ApplyDefaultsToProtobuf applies defaults to protobuf types using reflection
func (s *Schema) ApplyDefaultsToProtobuf(config interface{}) error {
return s.applyDefaultsReflection(config)
}
// applyDefaultsReflection applies default values using reflection (internal use only)
// Used for protobuf types and embedded struct handling
func (s *Schema) applyDefaultsReflection(config interface{}) error {
configValue := reflect.ValueOf(config)
if configValue.Kind() == reflect.Ptr {
configValue = configValue.Elem()
}
if configValue.Kind() != reflect.Struct {
return fmt.Errorf("config must be a struct or pointer to struct")
}
configType := configValue.Type()
for i := 0; i < configValue.NumField(); i++ {
field := configValue.Field(i)
fieldType := configType.Field(i)
// Handle embedded structs recursively (before JSON tag check)
if field.Kind() == reflect.Struct && fieldType.Anonymous {
if !field.CanAddr() {
return fmt.Errorf("embedded struct %s is not addressable - config must be a pointer", fieldType.Name)
}
err := s.applyDefaultsReflection(field.Addr().Interface())
if err != nil {
return fmt.Errorf("failed to apply defaults to embedded struct %s: %v", fieldType.Name, err)
}
continue
}
// Get JSON tag name
jsonTag := fieldType.Tag.Get("json")
if jsonTag == "" {
continue
}
// Remove options like ",omitempty"
if commaIdx := strings.Index(jsonTag, ","); commaIdx >= 0 {
jsonTag = jsonTag[:commaIdx]
}
// Find corresponding schema field
schemaField := s.GetFieldByName(jsonTag)
if schemaField == nil {
continue
}
// Apply default if field is zero value
if field.CanSet() && field.IsZero() {
defaultValue := reflect.ValueOf(schemaField.DefaultValue)
if defaultValue.Type().ConvertibleTo(field.Type()) {
field.Set(defaultValue.Convert(field.Type()))
}
}
}
return nil
}
// ValidateConfig validates a configuration against the schema
func (s *Schema) ValidateConfig(config interface{}) []error {
var errors []error
configValue := reflect.ValueOf(config)
if configValue.Kind() == reflect.Ptr {
configValue = configValue.Elem()
}
if configValue.Kind() != reflect.Struct {
errors = append(errors, fmt.Errorf("config must be a struct or pointer to struct"))
return errors
}
configType := configValue.Type()
for i := 0; i < configValue.NumField(); i++ {
field := configValue.Field(i)
fieldType := configType.Field(i)
// Get JSON tag name
jsonTag := fieldType.Tag.Get("json")
if jsonTag == "" {
continue
}
// Remove options like ",omitempty"
if commaIdx := strings.Index(jsonTag, ","); commaIdx > 0 {
jsonTag = jsonTag[:commaIdx]
}
// Find corresponding schema field
schemaField := s.GetFieldByName(jsonTag)
if schemaField == nil {
continue
}
// Validate field value
fieldValue := field.Interface()
if err := schemaField.ValidateValue(fieldValue); err != nil {
errors = append(errors, err)
}
}
return errors
}
|