Go app framework

This commit is contained in:
2025-01-04 12:24:42 -05:00
parent 41036b3c3a
commit d0a430505c
16 changed files with 1199 additions and 1 deletions

93
pkg/app/app.go Normal file
View File

@ -0,0 +1,93 @@
package app
import (
"context"
"errors"
"github.com/rs/zerolog"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/otel"
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv"
)
type App struct {
AppContext context.Context
HTTP *AppHTTP
cfg *config.AppConfig
l *zerolog.Logger
tracer trace.Tracer
shutdownFuncs []shutdownFunc
appDone chan interface{}
}
type AppHTTP struct {
Funcs []srv.HTTPFunc
HealthChecks []srv.HealthCheckFunc
httpDone <-chan interface{}
}
type (
healthCheckFunc func(context.Context) error
shutdownFunc func(context.Context) error
)
func (a *App) Done() <-chan interface{} {
return a.appDone
}
func (a *App) MustRun() {
if a.cfg != nil {
panic(errors.New("already ran app trying to run"))
}
// Set up app
a.cfg = config.MustFromCtx(a.AppContext)
a.l = zerolog.Ctx(a.AppContext)
a.shutdownFuncs = make([]shutdownFunc, 0)
a.appDone = make(chan interface{})
a.HTTP.httpDone = make(chan interface{})
if len(a.HTTP.Funcs) < 1 {
a.l.Warn().Msg("no http funcs provided, only serving health and metrics")
}
// Start OTEL
a.initOTEL()
var initSpan trace.Span
_, initSpan = a.tracer.Start(a.AppContext, "init")
// Start HTTP
a.initHTTP()
// Monitor app lifecycle
go a.run()
// Startup Complete
a.l.Info().
Str("name", a.cfg.Name).
Str("version", a.cfg.Version).
Str("logLevel", a.cfg.Logging.Level).
Msg("app initialized")
initSpan.SetStatus(codes.Ok, "")
initSpan.End()
}
func (a *App) initHTTP() {
var httpShutdown shutdownFunc
httpShutdown, a.HTTP.httpDone = srv.MustInitHTTPServer(
a.AppContext,
a.HTTP.Funcs,
a.HTTP.HealthChecks...,
)
a.shutdownFuncs = append(a.shutdownFuncs, httpShutdown)
}
func (a *App) initOTEL() {
var otelShutdown shutdownFunc
a.AppContext, otelShutdown = otel.Init(a.AppContext)
a.shutdownFuncs = append(a.shutdownFuncs, otelShutdown)
a.tracer = otel.MustTracerFromCtx(a.AppContext)
}

67
pkg/app/run.go Normal file
View File

@ -0,0 +1,67 @@
package app
import (
"context"
"sync"
"time"
"go.opentelemetry.io/otel/codes"
)
// Watches contexts and channels for the
// app to be finished and calls shutdown once
// the app is done
func (a *App) run() {
select {
case <-a.AppContext.Done():
a.l.Warn().Str("reason", a.AppContext.Err().Error()).
Msg("shutting down on context done")
case <-a.HTTP.httpDone:
a.l.Warn().Msg("shutting down early on http server done")
}
a.Shutdown()
a.appDone <- nil
}
// Typically invoked when AppContext is done
// or Server has exited. Not intended to be called
// manually
func (a *App) Shutdown() {
now := time.Now()
doneCtx, cncl := context.WithTimeout(context.Background(), 15*time.Second)
defer func() {
if doneCtx.Err() == context.DeadlineExceeded {
a.l.Err(doneCtx.Err()).
Dur("shutdownTime", time.Since(now)).
Msg("app shutdown aborted")
} else {
a.l.Info().
Int("shutdownFuncsCalled", len(a.shutdownFuncs)).
Dur("shutdownTime", time.Since(now)).
Msg("app shutdown normally")
}
cncl()
}()
doneCtx, span := a.tracer.Start(doneCtx, "shutdown")
defer span.End()
var wg sync.WaitGroup
wg.Add(len(a.shutdownFuncs))
for _, f := range a.shutdownFuncs {
go func() {
defer wg.Done()
err := f(doneCtx)
if err != nil {
span.SetStatus(codes.Error, "shutdown failed")
span.RecordError(err)
a.l.Err(err).Send()
}
}()
}
wg.Wait()
}

25
pkg/app/setup.go Normal file
View File

@ -0,0 +1,25 @@
package app
import (
"context"
"github.com/rs/zerolog"
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/logging"
)
// Helper function to return a context loaded up with
// config.AppConfig and a logger
func MustSetupConfigAndLogging(ctx context.Context) context.Context {
ctx, err := config.LoadConfig(ctx)
if err != nil {
panic(err)
}
cfg := config.MustFromCtx(ctx)
ctx = logging.MustInitLogging(ctx)
zerolog.Ctx(ctx).Trace().Any("config", *cfg).Send()
return ctx
}