-
Notifications
You must be signed in to change notification settings - Fork 4
/
kod.go
478 lines (406 loc) · 11.8 KB
/
kod.go
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
package kod
import (
"context"
"fmt"
"io/fs"
"log/slog"
"os"
"path/filepath"
"reflect"
"strings"
"sync"
"time"
"github.com/creasty/defaults"
"github.com/knadh/koanf/parsers/json"
"github.com/knadh/koanf/parsers/toml/v2"
"github.com/knadh/koanf/parsers/yaml"
"github.com/knadh/koanf/providers/env"
"github.com/knadh/koanf/providers/file"
"github.com/knadh/koanf/v2"
"github.com/samber/lo"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
"github.com/go-kod/kod/interceptor"
"github.com/go-kod/kod/internal/hooks"
"github.com/go-kod/kod/internal/registry"
"github.com/go-kod/kod/internal/signals"
)
const (
PkgPath = "github.com/go-kod/kod"
)
// Implements[T any] provides a common structure for components,
// with logging/tracing/metrics capabilities and a reference to the component's interface.
type Implements[T any] struct {
name string
//nolint
component_interface_type T
}
// L returns the associated logger.
func (i *Implements[T]) L(ctx context.Context) *slog.Logger {
s := trace.SpanContextFromContext(ctx)
if s.IsValid() {
return slog.Default().With(
slog.String("component", i.name),
slog.String("span_id", s.SpanID().String()),
slog.String("trace_id", s.TraceID().String()),
)
}
return slog.Default().With(slog.String("component", i.name))
}
// Tracer return the associated tracer.
func (i *Implements[T]) Tracer(opts ...trace.TracerOption) trace.Tracer {
return otel.Tracer(i.name, opts...)
}
// Meter return the associated meter.
func (i *Implements[T]) Meter(opts ...metric.MeterOption) metric.Meter {
return otel.Meter(i.name, opts...)
}
// setName sets the name for the component.
// nolint
func (i *Implements[T]) setName(name string) {
i.name = name
}
// implements is a marker method to assert implementation of an interface.
// nolint
func (Implements[T]) implements(T) {}
// Ref[T any] is a reference holder to a value of type T.
// The reference is expected to be a field of a component struct.
// The value is set by the framework, and is accessible via the Get() method.
//
// Example:
//
// type app struct {
// kod.Implements[kod.Main]
// component kod.Ref[example.Component]
// }
//
// func main() {
// kod.Run(context.Background(), func(ctx context.Context, main *app) error {
// component := main.component.Get()
// // ...
// })
// }
type Ref[T any] struct {
value T
once sync.Once
getter componentGetter
}
// Get returns the held reference value.
func (r *Ref[T]) Get() T {
r.init()
return r.value
}
// isRef is a marker method to identify a Ref type.
// nolint
func (r Ref[T]) isRef() {}
// setRef sets the reference value.
// nolint
func (r *Ref[T]) setRef(lazyInit bool, getter componentGetter) {
r.getter = getter
if !lazyInit {
r.init()
}
}
// init initializes the reference value.
func (r *Ref[T]) init() {
r.once.Do(func() { r.value = lo.Must(r.getter()).(T) })
}
// componentGetter is a function type for getting a reference value.
type componentGetter func() (any, error)
// LazyInit is a marker type for lazy initialization of components.
type LazyInit struct{}
// isLazyInit is a marker method to identify a LazyInit type.
// nolint
func (r LazyInit) isLazyInit() {}
// Main is the interface that should be implemented by an application's main component.
// The main component is the entry point of the application,
// and is expected to be a struct that embeds Implements[Main].
//
// Example:
//
// type app struct {
// kod.Implements[kod.Main]
// }
//
// func main() {
// kod.Run(context.Background(), func(ctx context.Context, main *app) error {
// fmt.Println("Hello, World!")
// return nil
// })
// }
type Main interface{}
// PointerToMain is a type constraint that asserts *T is an instance of Main
// (i.e. T is a struct that embeds kod.Implements[kod.Main]).
type PointerToMain[T any] interface {
*T
InstanceOf[Main]
}
// InstanceOf[T any] is an interface for asserting implementation of an interface T.
type InstanceOf[T any] interface {
implements(T)
}
// WithConfig[T any] is a struct to hold configuration of type T.
// The struct is expected to be a field of a component struct.
// The configuration is loaded from a file, and is accessible via the Config() method.
//
// Example:
//
// type app struct {
// kod.Implements[kod.Main]
// kod.WithConfig[appConfig]
// }
//
// type appConfig struct {
// Host string
// Port int
// }
//
// func main() {
// kod.Run(context.Background(), func(ctx context.Context, main *app) error {
// fmt.Println("config:", main.Config())
// })
// }
type WithConfig[T any] struct {
config T
}
// Config returns a pointer to the config.
func (wc *WithConfig[T]) Config() *T {
return &wc.config
}
// getConfig returns the config.
func (wc *WithConfig[T]) getConfig() any {
return &wc.config
}
// WithGlobalConfig[T any] is a struct to hold global configuration of type T.
// The struct is expected to be a field of a component struct.
// The configuration is loaded from a file, and is accessible via the Config() method.
type WithGlobalConfig[T any] struct {
config T
}
// Config returns a pointer to the config.
func (wc *WithGlobalConfig[T]) Config() *T {
return &wc.config
}
// getGlobalConfig returns the config.
func (wc *WithGlobalConfig[T]) getGlobalConfig() any {
return &wc.config
}
// WithConfigFile is an option setter for specifying a configuration file.
func WithConfigFile(filename string) func(*options) {
return func(opts *options) {
opts.configFilename = filename
}
}
// WithFakes is an option setter for specifying fake components for testing.
func WithFakes(fakes ...fakeComponent) func(*options) {
return func(opts *options) {
opts.fakes = lo.SliceToMap(fakes, func(f fakeComponent) (reflect.Type, any) { return f.intf, f.impl })
}
}
// WithRegistrations is an option setter for specifying component registrations.
func WithRegistrations(regs ...*Registration) func(*options) {
return func(opts *options) {
opts.registrations = regs
}
}
// WithInterceptors is an option setter for specifying interceptors.
func WithInterceptors(interceptors ...interceptor.Interceptor) func(*options) {
return func(opts *options) {
opts.interceptors = interceptors
}
}
// WithKoanf is an option setter for specifying a custom Koanf instance.
func WithKoanf(cfg *koanf.Koanf) func(*options) {
return func(opts *options) {
opts.koanf = cfg
}
}
// MustRun is a helper function to run the application with the provided main component and options.
// It panics if an error occurs during the execution.
func MustRun[T any, P PointerToMain[T]](ctx context.Context, run func(context.Context, *T) error, opts ...func(*options)) {
lo.Must0(Run[T, P](ctx, run, opts...))
}
// Run initializes and runs the application with the provided main component and options.
func Run[T any, _ PointerToMain[T]](ctx context.Context, run func(context.Context, *T) error, opts ...func(*options)) error {
// Create a new Kod instance.
kod, err := newKod(ctx, opts...)
if err != nil {
return err
}
// create a new context with kod
ctx = newContext(ctx, kod)
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// get the main component implementation
main, err := kod.getImpl(ctx, reflect.TypeFor[T]())
if err != nil {
return err
}
// wait for shutdown signal
stop := make(chan struct{}, 2)
sig := make(chan os.Signal, 2)
signals.Shutdown(ctx, sig, func(_ bool) {
cancel()
stop <- struct{}{}
})
// run the main component
go func() {
err = run(ctx, main.(*T))
stop <- struct{}{}
}()
// wait for stop signal
<-stop
ctx, timeoutCancel := context.WithTimeout(
context.WithoutCancel(ctx), kod.config.ShutdownTimeout)
defer timeoutCancel()
// run hook functions
kod.hooker.Do(ctx)
return err
}
// kodConfig defines the overall configuration for the Kod application.
type kodConfig struct {
Name string
Env string
Version string
ShutdownTimeout time.Duration
}
// Kod represents the core structure of the application, holding configuration and component registrations.
type Kod struct {
mu *sync.Mutex
cfg *koanf.Koanf
config kodConfig
hooker *hooks.Hooker
regs []*Registration
registryByName map[string]*Registration
registryByInterface map[reflect.Type]*Registration
registryByImpl map[reflect.Type]*Registration
components map[string]any
lazyInitComponents map[reflect.Type]bool
opts *options
}
// options defines the configuration options for Kod.
type options struct {
configFilename string
fakes map[reflect.Type]any
registrations []*Registration
interceptors []interceptor.Interceptor
koanf *koanf.Koanf
}
// newKod creates a new instance of Kod with the provided registrations and options.
func newKod(_ context.Context, opts ...func(*options)) (*Kod, error) {
opt := &options{}
for _, o := range opts {
o(opt)
}
kod := &Kod{
mu: &sync.Mutex{},
config: kodConfig{
Name: filepath.Base(lo.Must(os.Executable())),
Env: "local",
ShutdownTimeout: 5 * time.Second,
},
hooker: hooks.New(),
regs: registry.All(),
registryByName: make(map[string]*Registration),
registryByInterface: make(map[reflect.Type]*Registration),
registryByImpl: make(map[reflect.Type]*Registration),
components: make(map[string]any),
opts: opt,
}
kod.register(opt.registrations)
err := kod.parseConfig(opt.configFilename)
if err != nil {
return nil, err
}
kod.lazyInitComponents, err = processRegistrations(kod.regs)
if err != nil {
return nil, err
}
if err := checkCircularDependency(kod.regs); err != nil {
return nil, err
}
return kod, nil
}
// Config returns the current configuration of the Kod instance.
func (k *Kod) Config() kodConfig {
return k.config
}
// Defer adds a hook function to the Kod instance.
func (k *Kod) Defer(name string, fn func(context.Context) error) {
k.hooker.Add(hooks.HookFunc{Name: name, Fn: fn})
}
// unmarshalConfig sets the configuration for the Kod instance.
func (k *Kod) unmarshalConfig(key string, out interface{}) error {
err := defaults.Set(out)
if err != nil {
return fmt.Errorf("set defaults: %w", err)
}
return k.cfg.Unmarshal(key, out)
}
// register adds the given implementations to the Kod instance.
func (k *Kod) register(regs []*Registration) {
if len(regs) > 0 {
k.regs = regs
}
for _, v := range k.regs {
k.registryByName[v.Name] = v
k.registryByInterface[v.Interface] = v
k.registryByImpl[v.Impl] = v
}
}
// parseConfig parses the config file.
func (k *Kod) parseConfig(filename string) error {
k.cfg = k.opts.koanf
if k.cfg == nil {
err := k.loadConfig(filename)
if err != nil {
return err
}
}
return k.unmarshalConfig("kod", &k.config)
}
// loadConfig loads the configuration from the specified file.
func (k *Kod) loadConfig(filename string) error {
noConfigProvided := false
if filename == "" {
filename = os.Getenv("KOD_CONFIG")
if filename == "" {
noConfigProvided = true
filename = "kod.toml"
}
}
c := koanf.New(".")
err := c.Load(env.Provider("KOD_", ".", func(s string) string {
return strings.Replace(strings.ToLower(s), "_", ".", -1)
}), nil)
if err != nil {
return fmt.Errorf("load env config: %w", err)
}
// get ext
ext := filepath.Ext(filename)
switch ext {
case ".toml":
err = c.Load(file.Provider(filename), toml.Parser())
case ".yaml":
err = c.Load(file.Provider(filename), yaml.Parser())
case ".json":
err = c.Load(file.Provider(filename), json.Parser())
default:
return fmt.Errorf("read config file: Unsupported Config Type %q", ext)
}
if err != nil {
switch err.(type) {
case *fs.PathError:
if noConfigProvided {
fmt.Fprintln(os.Stderr, "failed to load config file, use default config")
} else {
return fmt.Errorf("read config file: %w", err)
}
default:
return fmt.Errorf("read config file: %w", err)
}
}
k.cfg = c
return nil
}