Repository navigation
Expand file tree
/
Copy pathmodule.go
More file actions
426 lines (388 loc) · 14 KB
/
Copy pathmodule.go
File metadata and controls
426 lines (388 loc) · 14 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
package base
import (
"fmt"
"sync"
"github.com/1set/starlet"
"github.com/1set/starlet/dataconv"
"go.starlark.net/starlark"
)
// ConfigOptionInterface defines the common interface for configuration options.
// It is used by ConfigurableModule to manage configuration settings.
type ConfigOptionInterface interface {
// Core methods
GetName() string
SetName(name string)
IsRequired() bool
IsSecret() bool
IsHostOnly() bool
FreezeHostOnlyEnv()
HasValue() bool
HasGetter() bool
HasDefault() bool
HasEnvVar() bool
Validate() error
// Starlark integration
SetValueFromStarlark(v starlark.Value) error
GetStarlarkValue() (starlark.Value, error)
// Go inspection
GetInfo() map[string]interface{}
}
// ConfigurableModule provides a generic module that can be extended with different configurations.
// Once initialized, the module becomes immutable.
//
// Configuration values are resolved in the following priority order (from highest to lowest):
// 1. Immediate value (set via WithValue/SetValue)
// 2. Returned value from the getter function (set via WithGetter)
// 3. Environment variable value (set via WithEnvVar)
// 4. Default value (set via WithDefault or NewConfigOption)
type ConfigurableModule struct {
mu sync.RWMutex
initialized bool
configs map[string]ConfigOptionInterface
}
// ModuleOption applies a configuration to the module.
type ModuleOption func(*ConfigurableModule) error
// WithConfigOption registers a configuration option for the module.
func WithConfigOption(name string, option ConfigOptionInterface) ModuleOption {
return func(m *ConfigurableModule) error {
return m.SetConfigOption(name, option)
}
}
// WithTypedConfigOption registers a strongly-typed configuration option for the module.
func WithTypedConfigOption[T any](name string, option *ConfigOption[T]) ModuleOption {
return func(m *ConfigurableModule) error {
return SetTypedConfigOption(m, name, option)
}
}
// WithConfigValue sets a configuration value directly.
// This has the highest priority in the resolution order.
func WithConfigValue[T any](name string, value T) ModuleOption {
return func(m *ConfigurableModule) error {
return SetConfigValue(m, name, value)
}
}
// WithConfigGetter registers a dynamic getter for the configuration.
// This has the second highest priority in the resolution order.
func WithConfigGetter[T any](name string, getter ConfigGetter[T]) ModuleOption {
return func(m *ConfigurableModule) error {
return SetConfigGetter(m, name, getter)
}
}
// WithConfigEnvVar associates an environment variable with the configuration.
// This has the third highest priority in the resolution order.
func WithConfigEnvVar[T any](name string, envVar string) ModuleOption {
return func(m *ConfigurableModule) error {
return SetConfigEnvVar[T](m, name, envVar)
}
}
// WithConfigDefault sets a default value for the configuration.
// This has the lowest priority in the resolution order.
func WithConfigDefault[T any](name string, defaultValue T) ModuleOption {
return func(m *ConfigurableModule) error {
return SetConfigDefault(m, name, defaultValue)
}
}
// NewConfigurableModule returns a new instance of ConfigurableModule.
func NewConfigurableModule() *ConfigurableModule {
return &ConfigurableModule{
configs: make(map[string]ConfigOptionInterface),
}
}
// NewConfigurableModuleWithOptions returns a new instance of ConfigurableModule with the provided options applied.
func NewConfigurableModuleWithOptions(options ...ModuleOption) (*ConfigurableModule, error) {
m := NewConfigurableModule()
for _, opt := range options {
if err := opt(m); err != nil {
return nil, fmt.Errorf("failed to apply module option: %w", err)
}
}
return m, nil
}
// NewConfigurableModuleWithConfigOptions returns a new instance of ConfigurableModule with the provided ConfigOptions added.
// Unlike NewConfigurableModuleWithOptions which takes functional ModuleOptions, this function directly accepts
// the actual ConfigOption instances. This is a more convenient way to create a module when you have ConfigOption
// instances directly.
//
// The name of each option is inferred from its Name field if set, otherwise a generated name will be used
// following the pattern "option_1", "option_2", etc.
//
// Example:
//
// // Create config options
// strOpt := base.NewConfigOption("default_str").WithName("string_option")
// intOpt := base.NewConfigOption(42).WithName("int_option")
//
// // Create module with options
// module, err := base.NewConfigurableModuleWithConfigOptions(strOpt, intOpt)
func NewConfigurableModuleWithConfigOptions(options ...ConfigOptionInterface) (*ConfigurableModule, error) {
m := NewConfigurableModule()
for i, opt := range options {
name := opt.GetName()
if name == "" {
name = fmt.Sprintf("option_%d", i+1)
opt.SetName(name)
}
if err := m.SetConfigOption(name, opt); err != nil {
return nil, fmt.Errorf("failed to add config option %q: %w", name, err)
}
}
return m, nil
}
// SetConfigOption registers a configuration option for the module.
func (m *ConfigurableModule) SetConfigOption(name string, option ConfigOptionInterface) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.initialized {
return ErrModuleAlreadyInitialized
}
if option.GetName() == "" {
option.SetName(name)
}
// Snapshot a host-only option's env value now, at construction time (before
// any script can mutate the process environment), so the host limit it
// enforces cannot be re-widened at runtime via a runtime.setenv-style builtin.
option.FreezeHostOnlyEnv()
m.configs[name] = option
return nil
}
// Initialize finalizes the module configuration and prevents further modifications.
func (m *ConfigurableModule) Initialize() error {
m.mu.Lock()
defer m.mu.Unlock()
for name, option := range m.configs {
if option.GetName() == "" {
option.SetName(name)
}
// Backstop the construction-time snapshot: freeze any host-only option not
// already frozen at registration — e.g. one made host-only, or given its
// env var, AFTER it was added. Initialize is the last point before the
// module is sealed (no further config changes are accepted), so this
// captures everything configured before load. Idempotent: a no-op for the
// standard case where the option was frozen at registration.
option.FreezeHostOnlyEnv()
if isMissingRequired(option) {
return fmt.Errorf("%w: %s", ErrConfigRequired, option.GetName())
}
if err := option.Validate(); err != nil {
return fmt.Errorf("validation failed for option '%s': %w", name, err)
}
}
m.initialized = true
return nil
}
// isMissingRequired reports whether a required option has no value from any
// source (immediate value, getter, env var, or default) and so cannot be
// satisfied at initialization.
func isMissingRequired(option ConfigOptionInterface) bool {
return option.IsRequired() &&
!option.HasValue() && !option.HasGetter() &&
!option.HasEnvVar() && !option.HasDefault()
}
// LoadModule returns a Starlark module loader with registered built-in
// functions. Initialization (and its validation) is deferred into the
// returned loader, so a configuration error surfaces as the loader's error
// return rather than a panic that would crash the host (PKG-03).
func (m *ConfigurableModule) LoadModule(moduleName string, additionalFuncs starlark.StringDict) starlet.ModuleLoader {
return func() (starlark.StringDict, error) {
if err := m.Initialize(); err != nil {
return nil, fmt.Errorf("failed to initialize module %q: %w", moduleName, err)
}
m.mu.RLock()
defer m.mu.RUnlock()
// Add config setters and getters
sd := make(starlark.StringDict, len(m.configs)*2+len(additionalFuncs))
for name, option := range m.configs {
// Host-only options get no set_<name>: a script must not be able to
// change a safety/resource limit the module enforces against it.
if !option.IsHostOnly() {
sd["set_"+name] = m.generateSetBuiltin(name, option)
}
// Don't expose getters for secret values in Starlark
if !option.IsSecret() {
sd["get_"+name] = m.generateGetBuiltin(name, option)
}
}
// Add additional functions
for k, v := range additionalFuncs {
sd[k] = v
}
// Wrap as module data
return dataconv.WrapModuleData(moduleName, sd)()
}
}
// generateSetBuiltin creates a Starlark builtin for setting a configuration option.
func (m *ConfigurableModule) generateSetBuiltin(name string, option ConfigOptionInterface) starlark.Callable {
return starlark.NewBuiltin("set_"+name, func(thread *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var v starlark.Value
if err := starlark.UnpackArgs(b.Name(), args, kwargs, "value", &v); err != nil {
return nil, err
}
if err := option.SetValueFromStarlark(v); err != nil {
return nil, err
}
return starlark.None, nil
})
}
// generateGetBuiltin creates a Starlark builtin for retrieving a configuration option.
func (m *ConfigurableModule) generateGetBuiltin(name string, option ConfigOptionInterface) starlark.Callable {
return starlark.NewBuiltin("get_"+name, func(thread *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
return option.GetStarlarkValue()
})
}
// ListConfigs returns a map with configuration details for each option.
func (m *ConfigurableModule) ListConfigs() map[string]map[string]interface{} {
m.mu.RLock()
defer m.mu.RUnlock()
result := make(map[string]map[string]interface{})
for name, option := range m.configs {
result[name] = option.GetInfo()
}
return result
}
// GetConfigOption retrieves a configuration option by name.
func (m *ConfigurableModule) GetConfigOption(name string) (ConfigOptionInterface, error) {
m.mu.RLock()
defer m.mu.RUnlock()
option, exists := m.configs[name]
if !exists {
return nil, fmt.Errorf("%w: %s", ErrConfigNotSet, name)
}
return option, nil
}
// Helper functions
// SetTypedConfigOption registers a strongly-typed configuration option.
func SetTypedConfigOption[T any](m *ConfigurableModule, name string, option *ConfigOption[T]) error {
return m.SetConfigOption(name, option)
}
// GetConfigValue returns the value of a configuration option.
func GetConfigValue[T any](m *ConfigurableModule, name string) (T, error) {
var zero T
m.mu.RLock()
option, exists := m.configs[name]
m.mu.RUnlock()
if !exists {
return zero, fmt.Errorf("%w: %s", ErrConfigNotSet, name)
}
typedOption, ok := option.(*ConfigOption[T])
if !ok {
return zero, fmt.Errorf("config '%s' is not of expected type", name)
}
return typedOption.GetValue()
}
// GetConfigValueWithFallback retrieves a configuration value with a fallback.
// If the configuration doesn't exist or there's an error retrieving it, the fallback value is returned.
//
// Example:
//
// // Instead of:
// val, err := GetConfigValue(m, key)
// if err != nil {
// val = fallbackVal
// }
//
// // You can use:
// val := base.GetConfigValueWithFallback(m.cfgMod, key, fallbackVal)
//
// For even more convenience, use the ConfigurableModuleExt methods via the Extend() function.
func GetConfigValueWithFallback[T any](m *ConfigurableModule, name string, fallbackVal T) T {
// Get the config option
option, err := m.GetConfigOption(name)
if err != nil {
return fallbackVal
}
// For typed options, retrieve the value directly
if typedOption, ok := option.(*ConfigOption[T]); ok {
val, err := typedOption.GetValue()
if err != nil {
return fallbackVal
}
return val
}
// As a fallback, try the generic approach
val, err := GetConfigValue[T](m, name)
if err != nil {
return fallbackVal
}
return val
}
// SetConfigValue sets the configuration value.
// This has the highest priority in the resolution order.
func SetConfigValue[T any](m *ConfigurableModule, name string, value T) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.initialized {
return ErrModuleAlreadyInitialized
}
if option, exists := m.configs[name]; exists {
typedOption, ok := option.(*ConfigOption[T])
if !ok {
return fmt.Errorf("cannot set value of different type for config '%s'", name)
}
return typedOption.SetValue(value)
}
newOption := NewConfigOption(value).WithName(name)
m.configs[name] = newOption
return nil
}
// SetConfigGetter registers a dynamic getter for the configuration.
// This has the second highest priority in the resolution order.
func SetConfigGetter[T any](m *ConfigurableModule, name string, getter ConfigGetter[T]) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.initialized {
return ErrModuleAlreadyInitialized
}
if option, exists := m.configs[name]; exists {
typedOption, ok := option.(*ConfigOption[T])
if !ok {
return fmt.Errorf("cannot set getter of different type for config '%s'", name)
}
typedOption.WithGetter(getter)
return nil
}
var zero T
newOption := NewConfigOption(zero).WithName(name).WithGetter(getter)
m.configs[name] = newOption
return nil
}
// SetConfigEnvVar associates an environment variable with the configuration.
// This has the third highest priority in the resolution order.
func SetConfigEnvVar[T any](m *ConfigurableModule, name string, envVar string) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.initialized {
return ErrModuleAlreadyInitialized
}
if option, exists := m.configs[name]; exists {
typedOption, ok := option.(*ConfigOption[T])
if !ok {
return fmt.Errorf("cannot set environment variable for config of different type '%s'", name)
}
typedOption.WithEnvVar(envVar)
return nil
}
var zero T
newOption := NewConfigOption(zero).WithName(name).WithEnvVar(envVar)
m.configs[name] = newOption
return nil
}
// SetConfigDefault sets a default value for the configuration.
// This has the lowest priority in the resolution order.
func SetConfigDefault[T any](m *ConfigurableModule, name string, defaultValue T) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.initialized {
return ErrModuleAlreadyInitialized
}
if option, exists := m.configs[name]; exists {
typedOption, ok := option.(*ConfigOption[T])
if !ok {
return fmt.Errorf("cannot set default value of different type for config '%s'", name)
}
typedOption.WithDefault(defaultValue)
return nil
}
newOption := NewConfigOption(defaultValue).WithName(name)
m.configs[name] = newOption
return nil
}