Skip to content

Commit

Permalink
feat: introduce BaseContext, pass shutdown context to f()
Browse files Browse the repository at this point in the history
  • Loading branch information
ernado committed Feb 3, 2025
1 parent 8577d1e commit da9c726
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
6 changes: 5 additions & 1 deletion app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,10 @@ func Run(f func(ctx context.Context, lg *zap.Logger, m *Telemetry) error, op ...
if ctx, err = autologs.Setup(ctx, m.LoggerProvider(), opts.zapTee); err != nil {
panic(fmt.Sprintf("failed to setup logs: %v", err))
}

shutdownCtx = zctx.Base(shutdownCtx, zctx.From(ctx))
m.shutdownContext = shutdownCtx
m.baseContext = ctx

{
// Automatically setting GOMAXPROCS.
Expand Down Expand Up @@ -155,7 +158,8 @@ func Run(f func(ctx context.Context, lg *zap.Logger, m *Telemetry) error, op ...
rerr = fmt.Errorf("shutting down (panic): %v", ec)
}
}()
if err := f(ctx, zctx.From(ctx), m); err != nil {
m.baseContext = ctx
if err := f(m.shutdownContext, zctx.From(ctx), m); err != nil {
if errors.Is(err, ctx.Err()) {
// Parent context got cancelled, error is expected.
// TODO(ernado): check for shutdownCtx instead.
Expand Down
15 changes: 11 additions & 4 deletions app/telemetry.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,22 +53,28 @@ type Telemetry struct {
meterProvider metric.MeterProvider
loggerProvider log.LoggerProvider
shutdownContext context.Context
baseContext context.Context

resource *resource.Resource
propagator propagation.TextMapPropagator
resource *resource.Resource

shutdowns []shutdown
propagator propagation.TextMapPropagator
shutdowns []shutdown
}

// ShutdownContext is context for triggering graceful shutdown.
// It is cancelled on SIGINT.
//
// Base context can be used during shutdown to finish pending operations, it will be cancelled later
// Base context [Telemetry.BaseContext] can be used during shutdown to finish pending operations, it will be cancelled later
// on timeout.
func (m *Telemetry) ShutdownContext() context.Context {
return m.shutdownContext
}

// BaseContext is base context for the application.
func (m *Telemetry) BaseContext() context.Context {
return m.baseContext
}

func (m *Telemetry) registerShutdown(name string, fn func(ctx context.Context) error) {
m.shutdowns = append(m.shutdowns, shutdown{name: name, fn: fn})
}
Expand Down Expand Up @@ -214,6 +220,7 @@ func newTelemetry(
resource: res,

shutdownContext: shutdownCtx,
baseContext: baseCtx,
}
ctx := baseCtx
{
Expand Down

0 comments on commit da9c726

Please sign in to comment.