-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathapp.go
443 lines (374 loc) · 12 KB
/
app.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
package flamingo
import (
"context"
"errors"
"flag"
"fmt"
"log"
"net"
"net/http"
"os"
"reflect"
"strings"
"time"
"flamingo.me/dingo"
"github.com/spf13/cobra"
"flamingo.me/flamingo/v3/core/runtime"
"flamingo.me/flamingo/v3/core/zap"
"flamingo.me/flamingo/v3/framework"
"flamingo.me/flamingo/v3/framework/cmd"
"flamingo.me/flamingo/v3/framework/config"
"flamingo.me/flamingo/v3/framework/flamingo"
flamingoHttp "flamingo.me/flamingo/v3/framework/http"
"flamingo.me/flamingo/v3/framework/web"
)
//go:generate go run github.com/vektra/mockery/v2@v2.50.4
type (
// Application contains a main flamingo application
Application struct {
configDir string
childAreas []*config.Area
area *config.Area
args []string
routesModules []web.RoutesModule
loggerModule dingo.Module
defaultContext string
eagerSingletons bool
flagset *flag.FlagSet
}
// ApplicationOption configures an Application
ApplicationOption func(config *Application)
)
// ConfigDir configuration ApplicationOption
func ConfigDir(configdir string) ApplicationOption {
return func(config *Application) {
config.configDir = configdir
}
}
// ChildAreas allows to define additional config areas for roots
func ChildAreas(areas ...*config.Area) ApplicationOption {
return func(config *Application) {
config.childAreas = areas
}
}
// DefaultContext for flamingo to start with
func DefaultContext(name string) ApplicationOption {
return func(config *Application) {
config.defaultContext = name
}
}
// SetEagerSingletons controls if eager singletons will be created
func SetEagerSingletons(enabled bool) ApplicationOption {
return func(config *Application) {
config.eagerSingletons = enabled
}
}
// WithArgs sets the initial arguments different than os.Args[1:]
func WithArgs(args ...string) ApplicationOption {
return func(config *Application) {
config.args = args
}
}
// WithRoutes configures a given RoutesModule for usage in the flamingo app
func WithRoutes(routesModule web.RoutesModule) ApplicationOption {
return func(config *Application) {
config.routesModules = append(config.routesModules, routesModule)
}
}
// WithCustomLogger allows to use custom logger modules for flamingo app, if nothing available default will be used
func WithCustomLogger(logger dingo.Module) ApplicationOption {
return func(config *Application) {
config.loggerModule = logger
}
}
type eventRouterProvider func() flamingo.EventRouter
type arrayFlags []string
func (i *arrayFlags) String() string {
return strings.Join(*i, ", ")
}
func (i *arrayFlags) Set(value string) error {
*i = append(*i, value)
return nil
}
// NewApplication loads a new application for running the Flamingo application with the given modules, loaded configs etc
func NewApplication(modules []dingo.Module, options ...ApplicationOption) (*Application, error) {
app := &Application{
configDir: "config",
args: os.Args[1:],
defaultContext: "root",
loggerModule: new(zap.Module),
}
for _, option := range options {
option(app)
}
app.flagset = flag.NewFlagSet("flamingo", flag.ContinueOnError)
dingoTraceCircular := app.flagset.Bool("dingo-trace-circular", false, "enable dingo circular tracing")
dingoTraceInjections := app.flagset.Bool("dingo-trace-injections", false, "enable dingo injection tracing")
flamingoConfigLog := app.flagset.Bool("flamingo-config-log", false, "enable flamingo config logging")
flamingoConfigCueDebug := app.flagset.String("flamingo-config-cue-debug", "", "query the flamingo cue config loader (use . for root)")
flamingoContext := app.flagset.String("flamingo-context", app.defaultContext, "set flamingo execution context")
var flamingoConfig arrayFlags
app.flagset.Var(&flamingoConfig, "flamingo-config", "add additional flamingo yaml config")
dingoInspect := app.flagset.Bool("dingo-inspect", false, "inspect dingo")
if err := app.flagset.Parse(app.args); err != nil && err != flag.ErrHelp {
return nil, fmt.Errorf("app: parsing arguments: %w", err)
}
if dingoTraceCircular != nil && *dingoTraceCircular {
dingo.EnableCircularTracing()
}
if dingoTraceInjections != nil && *dingoTraceInjections {
dingo.EnableInjectionTracing()
}
modules = append([]dingo.Module{
new(framework.InitModule),
app.loggerModule,
new(runtime.Module),
new(cmd.Module),
}, modules...)
modules = append(modules, new(servemodule))
for _, routesModule := range app.routesModules {
modules = append(modules, dingo.ModuleFunc(func(injector *dingo.Injector) {
web.BindRoutes(injector, routesModule)
}))
}
root := config.NewArea("root", modules, app.childAreas...)
configLoadOptions := []config.LoadOption{
config.AdditionalConfig(flamingoConfig),
config.DebugLog(*flamingoConfigLog),
config.LegacyMapping(true, false),
}
if *flamingoConfigCueDebug != "" {
printCue := func(b []byte, err error) {
if err != nil {
fmt.Println(err)
}
fmt.Println(string(b))
os.Exit(-1)
}
if *flamingoConfigCueDebug == "." {
configLoadOptions = append(configLoadOptions, config.CueDebug(nil, printCue))
} else {
configLoadOptions = append(configLoadOptions, config.CueDebug(strings.Split(*flamingoConfigCueDebug, "."), printCue))
}
}
if err := config.Load(root, app.configDir, configLoadOptions...); err != nil {
return nil, fmt.Errorf("app: config load: %w", err)
}
areas, err := root.Flat()
if err != nil {
return nil, fmt.Errorf("app: flat areas: %w", err)
}
var ok bool
app.area, ok = areas[*flamingoContext]
if !ok {
return nil, fmt.Errorf("app: context %q not found", *flamingoContext)
}
injector, err := app.area.GetInitializedInjector()
if err != nil {
return nil, fmt.Errorf("app: get initialized injector: %w", err)
}
if *dingoInspect {
inspect(injector)
}
if app.eagerSingletons {
if err := injector.BuildEagerSingletons(false); err != nil {
return nil, fmt.Errorf("app: build eager singletons: %w", err)
}
}
return app, nil
}
// ConfigArea returns the initialized configuration area
func (app *Application) ConfigArea() *config.Area {
return app.area
}
// App is the default app-runner for flamingo
func App(modules []dingo.Module, options ...ApplicationOption) {
app, err := NewApplication(modules, options...)
if err != nil {
log.Fatal(err)
}
if err := app.Run(); err != nil {
log.Fatal(err)
}
}
// Run runs the Root Cmd and triggers the standard event
func (app *Application) Run() error {
injector, err := app.area.GetInitializedInjector()
if err != nil {
return fmt.Errorf("get initialized injector: %w", err)
}
i, err := injector.GetAnnotatedInstance(new(cobra.Command), "flamingo")
if err != nil {
return fmt.Errorf("app: get flamingo cobra.Command: %w", err)
}
rootCmd := i.(*cobra.Command)
rootCmd.SetArgs(app.flagset.Args())
i, err = injector.GetInstance(new(eventRouterProvider))
if err != nil {
return fmt.Errorf("app: get eventRouterProvider: %w", err)
}
i.(eventRouterProvider)().Dispatch(context.Background(), new(flamingo.StartupEvent))
return rootCmd.Execute()
}
func typeName(of reflect.Type) string {
var name string
for of.Kind() == reflect.Ptr {
of = of.Elem()
}
if of.Kind() == reflect.Slice {
name += "[]"
of = of.Elem()
}
if of.Kind() == reflect.Ptr {
name += "*"
of = of.Elem()
}
if of.PkgPath() != "" {
name += of.PkgPath() + "."
}
name += of.Name()
return name
}
func trunc(s string) string {
if len(s) > 25 {
return s[:25] + "..."
}
return s
}
func printBinding(of reflect.Type, annotation string, to reflect.Type, provider, instance *reflect.Value, in dingo.Scope) {
name := typeName(of)
if annotation != "" {
annotation = fmt.Sprintf("(%q)", annotation)
}
val := "<unset>"
if instance != nil {
val = trunc(fmt.Sprintf("%v", instance.Interface()))
} else if provider != nil {
val = "provider=" + provider.String()
} else if to != nil {
val = "type=" + typeName(to)
}
scopename := ""
if in != nil {
scopename = " (" + reflect.ValueOf(in).String() + ")"
}
fmt.Printf("%s%s: %s%s\n", name, annotation, val, scopename)
}
func inspect(injector *dingo.Injector) {
fmt.Println("Bindings:")
injector.Inspect(dingo.Inspector{
InspectBinding: printBinding,
})
fmt.Println("\nMultiBindings:")
injector.Inspect(dingo.Inspector{
InspectMultiBinding: func(of reflect.Type, index int, annotation string, to reflect.Type, provider, instance *reflect.Value, in dingo.Scope) {
//fmt.Printf("%d: ", index)
printBinding(of, annotation, to, provider, instance, in)
},
})
fmt.Println("\nMapBindings:")
injector.Inspect(dingo.Inspector{
InspectMapBinding: func(of reflect.Type, key string, annotation string, to reflect.Type, provider, instance *reflect.Value, in dingo.Scope) {
//fmt.Printf("%s: ", key)
printBinding(of, annotation, to, provider, instance, in)
},
})
fmt.Println("---")
injector.Inspect(dingo.Inspector{
InspectParent: inspect,
})
}
type servemodule struct {
router *web.Router
server *http.Server
eventRouter flamingo.EventRouter
logger flamingo.Logger
certFile, keyFile string
publicEndpoint bool
}
// Inject basic application dependencies
func (a *servemodule) Inject(
router *web.Router,
eventRouter flamingo.EventRouter,
logger flamingo.Logger,
cfg *struct {
Port int `inject:"config:core.serve.port"`
PublicEndpoint bool `inject:"config:flamingo.opencensus.publicEndpoint,optional"`
},
) {
a.router = router
a.eventRouter = eventRouter
a.logger = logger
a.server = &http.Server{
Addr: fmt.Sprintf(":%d", cfg.Port),
}
a.publicEndpoint = cfg.PublicEndpoint
}
// Configure dependency injection
func (a *servemodule) Configure(injector *dingo.Injector) {
flamingo.BindEventSubscriber(injector).ToInstance(a)
injector.BindMulti(new(cobra.Command)).ToProvider(func(opts *struct {
Handler flamingoHttp.HandlerWrapper `inject:",optional"`
}) *cobra.Command {
return serveProvider(a, a.logger, opts.Handler)
})
}
// CueConfig for the module
func (a *servemodule) CueConfig() string {
return `core: serve: port: >= 0 & <= 65535 | *3322`
}
func serveProvider(module *servemodule, logger flamingo.Logger, handlerWrapper flamingoHttp.HandlerWrapper) *cobra.Command {
serveCmd := &cobra.Command{
Use: "serve",
Short: "Default serve command - starts on Port 3322",
Run: func(cmd *cobra.Command, args []string) {
module.server.Handler = module.router.Handler()
if handlerWrapper != nil {
module.server.Handler = handlerWrapper(module.server.Handler)
}
err := module.listenAndServe()
if err != nil {
if errors.Is(err, http.ErrServerClosed) {
logger.Info(err)
} else {
logger.Fatal("unexpected error in serving:", err)
}
}
},
}
serveCmd.Flags().StringVarP(&module.server.Addr, "addr", "a", module.server.Addr, "addr on which flamingo runs")
serveCmd.Flags().StringVarP(&module.certFile, "certFile", "c", "", "certFile to enable HTTPS")
serveCmd.Flags().StringVarP(&module.keyFile, "keyFile", "k", "", "keyFile to enable HTTPS")
return serveCmd
}
func (a *servemodule) listenAndServe() error {
listener, err := net.Listen("tcp", a.server.Addr)
if err != nil {
return err
}
addr := listener.Addr().String()
a.logger.Info(fmt.Sprintf("Starting HTTP Server at %s .....", addr))
port := addr[strings.LastIndex(addr, ":")+1:]
a.eventRouter.Dispatch(context.Background(), &flamingo.ServerStartEvent{Port: port})
defer a.eventRouter.Dispatch(context.Background(), &flamingo.ServerShutdownEvent{})
if a.certFile != "" && a.keyFile != "" {
return a.server.ServeTLS(listener, a.certFile, a.keyFile)
}
return a.server.Serve(listener)
}
// Notify upon flamingo Shutdown event
func (a *servemodule) Notify(ctx context.Context, event flamingo.Event) {
if _, ok := event.(*flamingo.ShutdownEvent); ok {
if a.server.Handler == nil {
// server not running, nothing to shut down
return
}
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
a.logger.Info("Shutdown server on ", a.server.Addr)
err := a.server.Shutdown(ctx)
if err != nil {
a.logger.Error("unexpected error on server shutdown: ", err)
}
}
}