Debian Codegraph @

internal/daemon/runtime.go

raw
1 package daemon
2
3 import (
4 "context"
5 "fmt"
6 "log/slog"
7 "sync"
8 )
9
10 // Reloader refreshes runtime state that can be updated without a full restart.
11 type Reloader interface {
12 Reload(ctx context.Context) error
13 }
14
15 type service struct {
16 run func(context.Context) error
17 errPrefix string
18 }
19
20 // Runtime owns the process services for one loaded configuration.
21 type Runtime struct {
22 cause error
23 reloader Reloader
24 cancel context.CancelCauseFunc
25 done <-chan struct{}
26 logger *slog.Logger
27 services []service
28 stopped bool
29 wg sync.WaitGroup
30 causeMu sync.Mutex
31 }
32
33 func newRuntime(logger *slog.Logger, reloader Reloader, services []service) *Runtime {
34 return &Runtime{
35 logger: logger,
36 reloader: reloader,
37 services: services,
38 }
39 }
40
41 // Start starts all services and records the first service error as the runtime
42 // cancellation cause.
43 func (r *Runtime) Start(ctx context.Context) {
44 ctx, cancel := context.WithCancelCause(ctx)
45 r.cancel = cancel
46 r.done = ctx.Done()
47
48 for _, svc := range r.services {
49 r.wg.Go(func() {
50 if err := svc.run(ctx); err != nil {
51 r.Stop(fmt.Errorf("%s: %w", svc.errPrefix, err))
52
53 return
54 }
55
56 r.Stop(nil)
57 })
58 }
59 }
60
61 // Done is closed when the runtime is stopping.
62 func (r *Runtime) Done() <-chan struct{} {
63 return r.done
64 }
65
66 // Err returns the cause that stopped the runtime.
67 func (r *Runtime) Err() error {
68 r.causeMu.Lock()
69 defer r.causeMu.Unlock()
70
71 return r.cause
72 }
73
74 // Stop requests shutdown with the supplied cause.
75 func (r *Runtime) Stop(cause error) {
76 r.causeMu.Lock()
77 if !r.stopped {
78 r.stopped = true
79 r.cause = cause
80 }
81 r.causeMu.Unlock()
82
83 if r.cancel != nil {
84 r.cancel(cause)
85 }
86 }
87
88 // Wait blocks until all runtime services have exited.
89 func (r *Runtime) Wait() {
90 r.wg.Wait()
91 }
92
93 // Reload refreshes reloadable runtime state.
94 func (r *Runtime) Reload(ctx context.Context) error {
95 if r.reloader == nil {
96 return nil
97 }
98
99 if err := r.reloader.Reload(ctx); err != nil {
100 return fmt.Errorf("error reloading http server: %w", err)
101 }
102
103 return nil
104 }
105
106 // LogSignal records a signal received by the command package.
107 func (r *Runtime) LogSignal(ctx context.Context, sig string) {
108 r.logger.LogAttrs(ctx, slog.LevelInfo, "receiving signal: "+sig)
109 }