/
kod.go
388 lines (328 loc) · 9.18 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
package kod
import (
"context"
"fmt"
"io/fs"
"log/slog"
"os"
"path/filepath"
"reflect"
"sync"
"time"
"github.com/go-kod/kod/interceptor"
"github.com/go-kod/kod/internal/hooks"
"github.com/go-kod/kod/internal/kslog"
"github.com/go-kod/kod/internal/reflects"
"github.com/go-kod/kod/internal/registry"
"github.com/go-kod/kod/internal/signals"
"github.com/samber/lo"
"github.com/spf13/viper"
"go.opentelemetry.io/contrib/bridges/otelslog"
)
const (
PkgPath = "github.com/go-kod/kod"
)
// Implements[T any] provides a common structure for components,
// with logging capabilities and a reference to the component's interface.
type Implements[T any] struct {
log *slog.Logger
//nolint
component_interface_type T
}
// L returns the associated logger.
func (i *Implements[T]) L(ctx context.Context) *slog.Logger {
return kslog.LogWithContext(ctx, i.log)
}
// setLogger sets the logger for the component.
// nolint
func (i *Implements[T]) setLogger(log *slog.Logger) {
i.log = log
}
// 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
}
// Get returns the held reference value.
func (r Ref[T]) Get() T { 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(val any) { r.value = val.(T) }
// 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 weaver.Implements[weaver.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
}
// 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 })
}
}
// WithLogWrapper is an option setter for specifying a logger.
func WithLogWrapper(h func(slog.Handler) slog.Handler) func(*options) {
return func(opts *options) {
opts.logWrapper = h
}
}
// 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
}
}
// 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 {
opt := &options{}
for _, o := range opts {
o(opt)
}
// Create a new Kod instance.
kod, err := newKod(*opt)
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, reflects.TypeFor[T]())
if err != nil {
return err
}
// wait for shutdown signal
stop := make(chan struct{}, 2)
signals.Shutdown(ctx, func(grace bool) {
kod.log.Info("shutdown ...")
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
}
// logConfig defines the configuration for logging.
type logConfig struct {
Level string
File string
}
// kodConfig defines the overall configuration for the Kod application.
type kodConfig struct {
Name string
Env string
Version string
Log logConfig
ShutdownTimeout time.Duration
}
// Kod represents the core structure of the application, holding configuration and component registrations.
type Kod struct {
mu *sync.Mutex
config kodConfig
viper *viper.Viper
log *slog.Logger
hooker *hooks.Hooker
regs []*Registration
registryByName map[string]*Registration
registryByInterface map[reflect.Type]*Registration
registryByImpl map[reflect.Type]*Registration
components map[string]any
opts options
}
// options defines the configuration options for Kod.
type options struct {
configFilename string
fakes map[reflect.Type]any
logWrapper func(slog.Handler) slog.Handler
registrations []*Registration
interceptors []interceptor.Interceptor
}
// newKod creates a new instance of Kod with the provided registrations and options.
func newKod(opts options) (*Kod, error) {
kod := &Kod{
mu: &sync.Mutex{},
config: kodConfig{
Name: filepath.Base(lo.Must(os.Executable())),
Env: "local",
Log: logConfig{Level: "info"},
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: opts,
}
kod.register(opts.registrations)
if err := kod.parseConfig(opts.configFilename); err != nil {
return nil, err
}
if err := validateRegistrations(kod.regs); err != nil {
return nil, err
}
if err := checkCircularDependency(kod.regs); err != nil {
return nil, err
}
kod.initLog()
return kod, nil
}
// Config returns the current configuration of the Kod instance.
func (k *Kod) Config() kodConfig {
return k.config
}
// L() returns the logger of the Kod instance.
func (k *Kod) L(ctx context.Context) *slog.Logger {
return kslog.LogWithContext(ctx, k.log)
}
// 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 {
noConfigProvided := false
if filename == "" {
filename = os.Getenv("KOD_CONFIG")
if filename == "" {
noConfigProvided = true
filename = "kod.toml"
}
}
vip := viper.New()
vip.SetConfigFile(filename)
vip.AddConfigPath(".")
err := vip.ReadInConfig()
if err != nil {
switch err.(type) {
case viper.ConfigFileNotFoundError, *fs.PathError:
if !noConfigProvided {
fmt.Fprintln(os.Stderr, "failed to load config file, use default config")
}
default:
return fmt.Errorf("read config file: %w", err)
}
}
k.viper = vip
return vip.UnmarshalKey("kod", &k.config)
}
func (k *Kod) initLog() {
var handler slog.Handler
if k.opts.logWrapper != nil {
handler = k.opts.logWrapper(otelslog.NewHandler(k.config.Name,
otelslog.WithSchemaURL(PkgPath),
otelslog.WithVersion(k.config.Version),
))
} else {
handler = otelslog.NewHandler(k.config.Name,
otelslog.WithSchemaURL(PkgPath),
otelslog.WithVersion(k.config.Version),
)
}
k.log = slog.New(handler)
}