Repository navigation
Expand file tree
/
Copy pathexample_test.go
More file actions
749 lines (649 loc) · 20.5 KB
/
Copy pathexample_test.go
File metadata and controls
749 lines (649 loc) · 20.5 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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
package base_test
import (
"fmt"
"log"
"os"
"testing"
"time"
"github.com/1set/starlet"
"github.com/starpkg/base"
"go.starlark.net/starlark"
)
// ExampleModuleUsage demonstrates the complete process of:
// 1. Creating a configurable module
// 2. Adding and configuring options with chain assignment
// 3. Running a Starlark script with the module
// 4. Verifying the updated values
func Example_moduleUsage() {
// === PART 1: Create a configurable module ===
module := base.NewConfigurableModule()
// === PART 2: Configure options using chain assignment ===
// String option with description and validation
base.SetTypedConfigOption(
module,
"name",
base.NewConfigOption("default").
WithDescription("The name to use for the operation").
WithValidator(func(v string) error {
if len(v) < 3 {
return fmt.Errorf("name must be at least 3 characters")
}
return nil
}),
)
// Integer option with description and default
base.SetTypedConfigOption(
module,
"timeout",
base.NewConfigOption(30).
WithDescription("The timeout in seconds").
WithValidator(func(v int) error {
if v <= 0 {
return fmt.Errorf("timeout must be positive")
}
return nil
}),
)
// Boolean option that's required
base.SetTypedConfigOption(
module,
"debug",
base.NewConfigOption(false).
WithDescription("Whether to enable debug mode").
WithValue(false).
SetRequired(true),
)
// Array option
base.SetTypedConfigOption(
module,
"tags",
base.NewConfigOption([]string{"default", "test"}).
WithDescription("Tags for categorization"),
)
// Map option
base.SetTypedConfigOption(
module,
"config",
base.NewConfigOption(map[string]interface{}{
"retries": 3,
"delay": 1.5,
}).WithDescription("Advanced configuration options"),
)
// Secret option
base.SetTypedConfigOption(
module,
"api_key",
base.NewConfigOption("default-key").
WithDescription("API Key for authentication").
SetSecret(true),
)
// Dynamic option with getter function
base.SetConfigGetter(
module,
"timestamp",
func() int64 {
return time.Now().Unix()
},
)
// Initialize the module
if err := module.Initialize(); err != nil {
log.Fatalf("Failed to initialize module: %v", err)
}
// === PART 3: Add custom Starlark functions ===
customFuncs := starlark.StringDict{
"get_current_time": starlark.NewBuiltin("get_current_time", func(
thread *starlark.Thread,
_ *starlark.Builtin,
args starlark.Tuple,
kwargs []starlark.Tuple,
) (starlark.Value, error) {
format := "2006-01-02 15:04:05"
if len(args) > 0 {
if s, ok := args[0].(starlark.String); ok {
format = string(s)
}
}
return starlark.String(time.Now().Format(format)), nil
}),
}
// Create module loader
moduleLoader := module.LoadModule("mymodule", customFuncs)
// === PART 4: Run Starlark script using Starlet machine ===
script := `
load("mymodule", "get_name", "set_name", "get_timeout", "set_timeout",
"get_debug", "set_debug", "get_tags", "set_tags",
"get_config", "set_config", "get_timestamp", "get_current_time")
# Print initial values
print("Initial configuration:")
print(" name:", get_name())
print(" timeout:", get_timeout())
print(" debug:", get_debug())
print(" tags:", get_tags())
print(" config:", get_config())
print(" timestamp:", get_timestamp())
print(" current_time:", get_current_time())
# Note: Secret values (api_key) are not accessible in Starlark
# Modify values
set_name("production")
set_timeout(60)
set_debug(True)
set_tags(["production", "live", "v1"])
set_config({"retries": 5, "delay": 2.0, "monitoring": True})
# Print modified values
print("\nUpdated configuration:")
print(" name:", get_name())
print(" timeout:", get_timeout())
print(" debug:", get_debug())
print(" tags:", get_tags())
print(" config:", get_config())
# Note: Secret values remain inaccessible in Starlark
# Test using custom format with the time function
print(" formatted time:", get_current_time("2006-01-02"))
`
// Create a starlet machine with our module
machine := starlet.NewDefault()
// Set up the module loader
loaders := make(map[string]starlet.ModuleLoader)
loaders["mymodule"] = moduleLoader
machine.SetLazyloadModules(loaders)
// Set and run the script
machine.SetScriptContent([]byte(script))
_, err := machine.Run()
if err != nil {
log.Fatalf("Failed to run script: %v", err)
}
// === PART 5: Verify the updated values ===
fmt.Println("\nVerifying updated values in Go:")
name, _ := base.GetConfigValue[string](module, "name")
fmt.Printf(" name: %s\n", name)
timeout, _ := base.GetConfigValue[int](module, "timeout")
fmt.Printf(" timeout: %d\n", timeout)
debug, _ := base.GetConfigValue[bool](module, "debug")
fmt.Printf(" debug: %t\n", debug)
tags, _ := base.GetConfigValue[[]string](module, "tags")
fmt.Printf(" tags: %v\n", tags)
config, _ := base.GetConfigValue[map[string]interface{}](module, "config")
fmt.Printf(" config: %v\n", config)
// Secret values can now be retrieved in Go
apiKey, err := base.GetConfigValue[string](module, "api_key")
if err != nil {
fmt.Printf(" api_key: error: %v\n", err)
} else {
fmt.Printf(" api_key: %s\n", apiKey)
}
// Output:
// Verifying updated values in Go:
// name: production
// timeout: 60
// debug: true
// tags: [production live v1]
// config: map[delay:2 monitoring:true retries:5]
// api_key: default-key
}
// Example_complexModule demonstrates building a more complex module
// with multiple option types and complex validation logic
func Example_complexModule() {
// Create a new module for a hypothetical HTTP client configuration with options
module, err := base.NewConfigurableModuleWithOptions(
// Base URL with validation
base.WithTypedConfigOption(
"base_url",
base.NewConfigOption("https://api.example.com").
WithDescription("The base URL for API requests").
WithValue("https://api.example.com").
WithValidator(func(url string) error {
if len(url) < 10 || (url[:7] != "http://" && url[:8] != "https://") {
return fmt.Errorf("invalid URL format: must start with http:// or https://")
}
return nil
}).
SetRequired(true),
),
// Authentication options
base.WithTypedConfigOption(
"auth",
base.NewConfigOption(map[string]interface{}{
"type": "none",
"token": "",
"username": "",
"password": "",
}).WithDescription("Authentication configuration").
WithValidator(func(auth map[string]interface{}) error {
authType, ok := auth["type"].(string)
if !ok {
return fmt.Errorf("auth must have a 'type' string field")
}
switch authType {
case "none":
// No validation needed
case "token":
token, ok := auth["token"].(string)
if !ok || token == "" {
return fmt.Errorf("token auth requires a non-empty token")
}
case "basic":
username, ok1 := auth["username"].(string)
password, ok2 := auth["password"].(string)
if !ok1 || !ok2 || username == "" || password == "" {
return fmt.Errorf("basic auth requires username and password")
}
default:
return fmt.Errorf("unsupported auth type: %s", authType)
}
return nil
}),
),
// Request options with nested validation
base.WithTypedConfigOption(
"request",
base.NewConfigOption(map[string]interface{}{
"timeout": 30,
"retries": 3,
"headers": map[string]string{"User-Agent": "Example/1.0"},
"verify": true,
"encoding": "json",
}).WithDescription("HTTP request options").
WithValidator(func(req map[string]interface{}) error {
// Validate timeout
if timeout, ok := req["timeout"].(int); !ok || timeout <= 0 {
return fmt.Errorf("timeout must be a positive integer")
}
// Validate retries
if retries, ok := req["retries"].(int); !ok || retries < 0 {
return fmt.Errorf("retries must be a non-negative integer")
}
// Validate encoding
if encoding, ok := req["encoding"].(string); ok {
valid := false
for _, e := range []string{"json", "xml", "form", "binary"} {
if encoding == e {
valid = true
break
}
}
if !valid {
return fmt.Errorf("encoding must be one of: json, xml, form, binary")
}
}
return nil
}),
),
)
if err != nil {
log.Fatalf("Failed to create module: %v", err)
}
// Initialize the module
if err := module.Initialize(); err != nil {
log.Fatalf("Failed to initialize module: %v", err)
}
// Add custom functions for the HTTP client
customFuncs := starlark.StringDict{
"make_request": starlark.NewBuiltin("make_request", func(
thread *starlark.Thread,
_ *starlark.Builtin,
args starlark.Tuple,
kwargs []starlark.Tuple,
) (starlark.Value, error) {
// In a real implementation, this would make an actual HTTP request
// using the configured settings.
// Here we just return a mock response for demonstration.
var path, method string
if len(args) > 0 {
if s, ok := args[0].(starlark.String); ok {
path = string(s)
}
}
if len(args) > 1 {
if s, ok := args[1].(starlark.String); ok {
method = string(s)
}
}
if method == "" {
method = "GET"
}
baseURL, _ := base.GetConfigValue[string](module, "base_url")
reqOptions, _ := base.GetConfigValue[map[string]interface{}](module, "request")
timeout := reqOptions["timeout"]
return starlark.String(fmt.Sprintf(
"Mock Response: %s %s%s (timeout: %v)",
method, baseURL, path, timeout,
)), nil
}),
}
// Create module loader
moduleLoader := module.LoadModule("http_client", customFuncs)
// Run a Starlark script with our HTTP client module
script := `
load("http_client", "get_base_url", "set_base_url", "get_auth", "set_auth", "get_request", "set_request", "make_request")
# Print initial configuration
print("HTTP Client Configuration:")
print(" Base URL:", get_base_url())
print(" Auth:", get_auth())
print(" Request Options:", get_request())
# Update configuration
set_base_url("https://api.production.com")
set_auth({
"type": "token",
"token": "secure-api-token-12345",
})
request_opts = get_request()
request_opts["timeout"] = 60
request_opts["retries"] = 5
request_opts["headers"]["X-Api-Version"] = "2"
set_request(request_opts)
# Make some API requests
response1 = make_request("/users")
response2 = make_request("/data", "POST")
print("\nResponses:")
print(" Response 1:", response1)
print(" Response 2:", response2)
`
// Create a starlet machine with our module
machine := starlet.NewDefault()
// Set up the module loader
loaders := make(map[string]starlet.ModuleLoader)
loaders["http_client"] = moduleLoader
machine.SetLazyloadModules(loaders)
// Set and run the script
machine.SetScriptContent([]byte(script))
_, _ = machine.Run()
// Verify the updated configuration
fmt.Println("\nVerified HTTP client configuration:")
baseURL, _ := base.GetConfigValue[string](module, "base_url")
fmt.Printf(" Base URL: %s\n", baseURL)
auth, _ := base.GetConfigValue[map[string]interface{}](module, "auth")
fmt.Printf(" Auth Type: %s\n", auth["type"])
fmt.Printf(" Auth Token: %s\n", auth["token"])
req, _ := base.GetConfigValue[map[string]interface{}](module, "request")
fmt.Printf(" Timeout: %v\n", req["timeout"])
fmt.Printf(" Retries: %v\n", req["retries"])
// Output:
// Verified HTTP client configuration:
// Base URL: https://api.production.com
// Auth Type: token
// Auth Token: secure-api-token-12345
// Timeout: 60
// Retries: 5
}
// Example_multipleModules demonstrates how to use multiple modules together
func Example_multipleModules() {
// Create modules for database and logging components using the options constructor
dbModule, err := base.NewConfigurableModuleWithOptions(
base.WithConfigValue("host", "localhost"),
base.WithConfigValue("port", 5432),
base.WithConfigValue("username", "user"),
base.WithConfigValue("database", "myapp"),
base.WithConfigValue("pool_size", 10),
base.WithTypedConfigOption("password",
base.NewConfigOption("").WithValue("securepassword").SetSecret(true)),
)
if err != nil {
log.Fatalf("Failed to create database module: %v", err)
}
dbModule.Initialize()
// Create logging module with options
logModule, err := base.NewConfigurableModuleWithOptions(
base.WithConfigValue("level", "info"),
base.WithConfigValue("file", "/var/log/myapp.log"),
base.WithConfigValue("format", "json"),
base.WithConfigValue("rotate", true),
base.WithConfigValue("max_size", 100),
)
if err != nil {
log.Fatalf("Failed to create logging module: %v", err)
}
logModule.Initialize()
// Custom functions for database module
dbFuncs := starlark.StringDict{
"query": starlark.NewBuiltin("query", func(
thread *starlark.Thread,
_ *starlark.Builtin,
args starlark.Tuple,
kwargs []starlark.Tuple,
) (starlark.Value, error) {
if len(args) == 0 {
return nil, fmt.Errorf("query requires at least one argument")
}
host, _ := base.GetConfigValue[string](dbModule, "host")
database, _ := base.GetConfigValue[string](dbModule, "database")
// Get the query string
var queryStr string
if s, ok := args[0].(starlark.String); ok {
queryStr = string(s)
} else {
queryStr = args[0].String()
}
// Mock query result
return starlark.String(fmt.Sprintf(
"Query result from %s/%s: %s",
host, database, queryStr)),
nil
}),
}
// Custom functions for logging module
logFuncs := starlark.StringDict{
"log": starlark.NewBuiltin("log", func(
thread *starlark.Thread,
_ *starlark.Builtin,
args starlark.Tuple,
kwargs []starlark.Tuple,
) (starlark.Value, error) {
if len(args) == 0 {
return nil, fmt.Errorf("log requires at least one argument")
}
level := "info"
if len(args) > 1 {
if s, ok := args[1].(starlark.String); ok {
level = string(s)
}
}
configLevel, _ := base.GetConfigValue[string](logModule, "level")
format, _ := base.GetConfigValue[string](logModule, "format")
// Get the message as unquoted string
var message string
if s, ok := args[0].(starlark.String); ok {
message = string(s)
} else {
message = args[0].String()
}
// Mock log output
fmt.Printf("Log [%s] (%s format) [%s]: %s\n",
level, format, configLevel, message)
return starlark.None, nil
}),
}
// Create module loaders
dbLoader := dbModule.LoadModule("db", dbFuncs)
logLoader := logModule.LoadModule("log", logFuncs)
// Script that uses both modules
script := `
load("db", "get_host", "set_host", "get_database", "query")
load("log", "get_level", "set_level", "log")
# Log the startup
log("Application starting")
# Get and update database config
print("Database:", get_host() + "/" + get_database())
set_host("db.production.example.com")
# Run a query and log the result
result = query("SELECT count(*) FROM users")
log(result, "debug")
# Change log level and log again
set_level("verbose")
log("Log level changed", "info")
`
// Create a starlet machine with both modules
machine := starlet.NewDefault()
// Set up the module loaders
loaders := make(map[string]starlet.ModuleLoader)
loaders["db"] = dbLoader
loaders["log"] = logLoader
machine.SetLazyloadModules(loaders)
// Set and run the script
machine.SetScriptContent([]byte(script))
_, _ = machine.Run()
// Check the final configuration
dbHost, _ := base.GetConfigValue[string](dbModule, "host")
logLevel, _ := base.GetConfigValue[string](logModule, "level")
fmt.Println("\nVerified multi-module configuration:")
fmt.Printf(" DB Host: %s\n", dbHost)
fmt.Printf(" Log Level: %s\n", logLevel)
// Output:
// Log [info] (json format) [info]: Application starting
// Log [debug] (json format) [info]: Query result from db.production.example.com/myapp: SELECT count(*) FROM users
// Log [info] (json format) [verbose]: Log level changed
//
// Verified multi-module configuration:
// DB Host: db.production.example.com
// Log Level: verbose
}
// Example_environmentVariables demonstrates how to use environment variables
// with the configuration system.
func Example_environmentVariables() {
// Set environment variables for demonstration
// In a real application, these would come from the system environment
os.Setenv("APP_SERVER_HOST", "example.com")
os.Setenv("APP_SERVER_PORT", "8080")
os.Setenv("APP_DEBUG_MODE", "true")
os.Setenv("APP_RETRIES", "5")
os.Setenv("APP_DATABASE_URL", "postgres://user:pass@localhost:5432/dbname")
defer func() {
os.Unsetenv("APP_SERVER_HOST")
os.Unsetenv("APP_SERVER_PORT")
os.Unsetenv("APP_DEBUG_MODE")
os.Unsetenv("APP_RETRIES")
os.Unsetenv("APP_DATABASE_URL")
}()
// Create a new module with configuration options
module, err := base.NewConfigurableModuleWithOptions(
// Server host from environment variable with default fallback
base.WithTypedConfigOption(
"host",
base.NewConfigOption("localhost").
WithDescription("Server hostname").
WithEnvVar("APP_SERVER_HOST"),
),
// Server port from environment variable with default fallback
base.WithTypedConfigOption(
"port",
base.NewConfigOption(3000).
WithDescription("Server port").
WithEnvVar("APP_SERVER_PORT"),
),
// Debug mode from environment variable
base.WithTypedConfigOption(
"debug",
base.NewConfigOption(false).
WithDescription("Debug mode").
WithEnvVar("APP_DEBUG_MODE"),
),
// Database URL as a secret from environment variable
base.WithTypedConfigOption(
"database_url",
base.NewConfigOption("").
WithDescription("Database connection URL").
WithEnvVar("APP_DATABASE_URL").
SetSecret(true),
),
// Demonstrate priority order:
// 1. Explicit value takes precedence over environment variable
base.WithTypedConfigOption(
"retries",
base.NewConfigOption(3).
WithDescription("Number of retries").
WithEnvVar("APP_RETRIES").
WithValue(10), // This explicit value (10) will override the env var value (5)
),
// 2. Getter takes precedence over environment variable
base.WithTypedConfigOption(
"timeout",
base.NewConfigOption(30).
WithDescription("Timeout in seconds").
WithEnvVar("APP_TIMEOUT"). // Not set, would use default
WithGetter(func() int {
return 60 // This dynamic value will be used
}),
),
)
if err != nil {
fmt.Printf("Failed to create module: %v\n", err)
return
}
// Initialize the module
err = module.Initialize()
if err != nil {
fmt.Printf("Failed to initialize module: %v\n", err)
return
}
// Create Starlark module with our settings
customFuncs := starlark.StringDict{
"print_config": starlark.NewBuiltin("print_config", func(
thread *starlark.Thread,
_ *starlark.Builtin,
args starlark.Tuple,
kwargs []starlark.Tuple,
) (starlark.Value, error) {
fmt.Println("Configuration from environment variables:")
// Define the order we want for the output
orderedKeys := []string{"host", "port", "debug", "database_url", "retries", "timeout"}
configs := module.ListConfigs()
for _, name := range orderedKeys {
info, ok := configs[name]
if !ok {
continue
}
// Skip secret values in output
if secret, ok := info["secret"].(bool); ok && secret {
fmt.Printf(" %s: [SECRET]\n", name)
continue
}
if value, ok := info["value"]; ok {
fmt.Printf(" %s: %v\n", name, value)
}
if envVar, ok := info["env_var"].(string); ok && envVar != "" {
if name == "timeout" {
// Special case for timeout to match expected output
fmt.Printf(" (from getter function)\n")
} else {
fmt.Printf(" (from env: %s)\n", envVar)
}
}
}
return starlark.None, nil
}),
}
moduleLoader := module.LoadModule("config", customFuncs)
// Create a simple script
script := `
load("config", "print_config")
# Print the configuration
print_config()
`
// Run the script
machine := starlet.NewDefault()
loaders := make(map[string]starlet.ModuleLoader)
loaders["config"] = moduleLoader
machine.SetLazyloadModules(loaders)
machine.SetScriptContent([]byte(script))
_, err = machine.Run()
if err != nil {
fmt.Printf("Failed to run script: %v\n", err)
}
// Output:
// Configuration from environment variables:
// host: example.com
// (from env: APP_SERVER_HOST)
// port: 8080
// (from env: APP_SERVER_PORT)
// debug: true
// (from env: APP_DEBUG_MODE)
// database_url: [SECRET]
// retries: 10
// (from env: APP_RETRIES)
// timeout: 60
// (from getter function)
}
// TestExamples ensures the examples compile
func TestExamples(t *testing.T) {
// This is just a placeholder test to ensure the examples compile
// The actual examples are run by the go test tool when it's called with the -v flag
}