gspot/main.go

71 lines
1.4 KiB
Go
Raw Normal View History

2024-02-23 20:48:32 +00:00
package main
import (
2024-07-06 21:05:01 +00:00
"context"
"errors"
"fmt"
"log/slog"
2024-02-23 20:48:32 +00:00
"go.uber.org/fx"
2024-07-06 21:05:01 +00:00
"go.uber.org/fx/fxevent"
2024-02-23 20:48:32 +00:00
"git.asdf.cafe/abs3nt/gspot/src/components/cache"
"git.asdf.cafe/abs3nt/gspot/src/components/cli"
"git.asdf.cafe/abs3nt/gspot/src/components/commands"
"git.asdf.cafe/abs3nt/gspot/src/components/logger"
"git.asdf.cafe/abs3nt/gspot/src/services"
)
func main() {
var s fx.Shutdowner
app := fx.New(
2024-07-06 21:05:01 +00:00
fx.WithLogger(func(logger *slog.Logger) fxevent.Logger {
l := &fxevent.SlogLogger{Logger: logger}
l.UseLogLevel(slog.LevelDebug)
return l
}),
2024-02-23 20:48:32 +00:00
fx.Populate(&s),
services.Config,
fx.Provide(
2024-07-06 21:05:01 +00:00
Context,
2024-02-23 20:48:32 +00:00
cache.NewCache,
commands.NewCommander,
logger.NewLogger,
),
fx.Invoke(
cli.Run,
),
)
app.Run()
}
2024-07-06 21:05:01 +00:00
type AsyncInit func(func(ctx context.Context) error)
var ErrContextShutdown = errors.New("shutdown")
func Context(
lc fx.Lifecycle,
s fx.Shutdowner,
log *slog.Logger,
) (context.Context, AsyncInit) {
if log == nil {
log = slog.Default()
}
ctx, cn := context.WithCancelCause(context.Background())
lc.Append(fx.Hook{
OnStop: func(ctx context.Context) error {
cn(fmt.Errorf("%w: %w", context.Canceled, ErrContextShutdown))
return nil
},
})
return ctx, func(fn func(ctx context.Context) error) {
go func() {
err := fn(ctx)
if err != nil {
log.Error("Failed to run async hook", "err", err)
s.Shutdown()
}
}()
}
}