-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_lifecycle.go
More file actions
305 lines (260 loc) · 9.37 KB
/
Copy pathserver_lifecycle.go
File metadata and controls
305 lines (260 loc) · 9.37 KB
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
// Package zerohttp provides server lifecycle hooks. See [Server.RegisterPreStartupHook], [Server.RegisterStartupHook], and [Server.RegisterShutdownHook].
package zerohttp
import (
"context"
"fmt"
"sync"
"github.com/alexferl/zerohttp/log"
)
// RegisterPreStartupHook registers a hook to run before servers start and before startup hooks.
// Pre-startup hooks execute sequentially in registration order.
// If any pre-startup hook returns an error, the server will not start.
//
// Hooks must respect context cancellation by checking ctx.Done().
// If a hook blocks without respecting the context, startup will hang.
//
// Example:
//
// app.RegisterPreStartupHook("validate-config", func(ctx context.Context) error {
// return validateConfig()
// })
func (s *Server) RegisterPreStartupHook(name string, hook StartupHook) {
s.mu.Lock()
defer s.mu.Unlock()
s.preStartupHooks = append(s.preStartupHooks, StartupHookConfig{Name: name, Hook: hook})
}
// RegisterStartupHook registers a hook to run concurrently with servers starting up.
// Startup hooks execute sequentially in registration order, after PreStartupHooks.
// If any startup hook returns an error, the server will not start.
//
// Hooks must respect context cancellation by checking ctx.Done().
// If a hook blocks without respecting the context, startup will hang.
//
// Example:
//
// app.RegisterStartupHook("migrations", func(ctx context.Context) error {
// return goose.Up(db.DB, "migrations")
// })
func (s *Server) RegisterStartupHook(name string, hook StartupHook) {
s.mu.Lock()
defer s.mu.Unlock()
s.startupHooks = append(s.startupHooks, StartupHookConfig{Name: name, Hook: hook})
}
// RegisterPostStartupHook registers a hook to run after servers have started accepting connections.
// Post-startup hooks execute sequentially in registration order.
// Errors from post-startup hooks are logged but do not stop the server.
//
// Hooks must respect context cancellation by checking ctx.Done().
// If a hook blocks without respecting the context, startup will hang.
//
// Example:
//
// app.RegisterPostStartupHook("announce-ready", func(ctx context.Context) error {
// return notifyServiceDiscovery()
// })
func (s *Server) RegisterPostStartupHook(name string, hook StartupHook) {
s.mu.Lock()
defer s.mu.Unlock()
s.postStartupHooks = append(s.postStartupHooks, StartupHookConfig{Name: name, Hook: hook})
}
// runPreStartupHooks executes pre-startup hooks sequentially in registration order.
func (s *Server) runPreStartupHooks(ctx context.Context) error {
s.mu.RLock()
hooks := s.preStartupHooks
s.mu.RUnlock()
if len(hooks) == 0 {
return nil
}
s.logger.Info("Running pre-startup hooks", log.F("count", len(hooks)))
for _, hook := range hooks {
select {
case <-ctx.Done():
s.logger.Warn("Pre-startup hook aborted due to context cancellation", log.F("hook", hook.Name))
return ctx.Err()
default:
}
s.logger.Info("Running pre-startup hook", log.F("hook", hook.Name))
if err := hook.Hook(ctx); err != nil {
s.logger.Error("Pre-startup hook failed", log.F("hook", hook.Name), log.E(err))
return fmt.Errorf("pre-startup hook %q failed: %w", hook.Name, err)
}
}
s.logger.Info("All pre-startup hooks completed successfully")
return nil
}
// runStartupHooks executes startup hooks sequentially in registration order.
// If any hook returns an error, execution stops and the error is returned.
func (s *Server) runStartupHooks(ctx context.Context) error {
s.mu.RLock()
hooks := s.startupHooks
s.mu.RUnlock()
if len(hooks) == 0 {
return nil
}
s.logger.Info("Running startup hooks", log.F("count", len(hooks)))
for _, hook := range hooks {
select {
case <-ctx.Done():
s.logger.Warn("Startup hook aborted due to context cancellation", log.F("hook", hook.Name))
return ctx.Err()
default:
}
s.logger.Info("Running startup hook", log.F("hook", hook.Name))
if err := hook.Hook(ctx); err != nil {
s.logger.Error("Startup hook failed", log.F("hook", hook.Name), log.E(err))
return fmt.Errorf("startup hook %q failed: %w", hook.Name, err)
}
}
s.logger.Info("All startup hooks completed successfully")
return nil
}
// runPostStartupHooks executes post-startup hooks sequentially in registration order.
func (s *Server) runPostStartupHooks(ctx context.Context) error {
s.mu.RLock()
hooks := s.postStartupHooks
s.mu.RUnlock()
if len(hooks) == 0 {
return nil
}
s.logger.Info("Running post-startup hooks", log.F("count", len(hooks)))
for _, hook := range hooks {
select {
case <-ctx.Done():
s.logger.Warn("Post-startup hook aborted due to context cancellation", log.F("hook", hook.Name))
return ctx.Err()
default:
}
s.logger.Info("Running post-startup hook", log.F("hook", hook.Name))
if err := hook.Hook(ctx); err != nil {
s.logger.Error("Post-startup hook failed", log.F("hook", hook.Name), log.E(err))
// Continue with other hooks despite error
}
}
s.logger.Info("All post-startup hooks completed successfully")
return nil
}
// RegisterPreShutdownHook registers a hook to run before server shutdown begins.
// Pre-shutdown hooks execute sequentially in registration order, before servers stop.
// Errors from pre-shutdown hooks are logged but do not stop shutdown.
//
// Hooks must respect context cancellation by checking ctx.Done().
// If a hook blocks without respecting the context, shutdown will hang.
//
// Example:
//
// app.RegisterPreShutdownHook("health", func(ctx context.Context) error {
// health.SetUnhealthy()
// return nil
// })
func (s *Server) RegisterPreShutdownHook(name string, hook ShutdownHook) {
s.mu.Lock()
defer s.mu.Unlock()
s.preShutdownHooks = append(s.preShutdownHooks, ShutdownHookConfig{Name: name, Hook: hook})
}
// RegisterShutdownHook registers a hook to run concurrently with server shutdown.
// Shutdown hooks execute concurrently alongside server shutdown.
// Errors from shutdown hooks are logged but do not stop shutdown.
//
// Hooks must respect context cancellation by checking ctx.Done().
// If a hook blocks without respecting the context, shutdown will hang.
//
// Example:
//
// app.RegisterShutdownHook("close-db", func(ctx context.Context) error {
// return db.Close()
// })
func (s *Server) RegisterShutdownHook(name string, hook ShutdownHook) {
s.mu.Lock()
defer s.mu.Unlock()
s.shutdownHooks = append(s.shutdownHooks, ShutdownHookConfig{Name: name, Hook: hook})
}
// RegisterPostShutdownHook registers a hook to run after servers have shut down.
// Post-shutdown hooks execute sequentially in registration order.
// Errors from post-shutdown hooks are logged but do not affect shutdown.
//
// Hooks must respect context cancellation by checking ctx.Done().
// If a hook blocks without respecting the context, shutdown will hang.
//
// Example:
//
// app.RegisterPostShutdownHook("cleanup", func(ctx context.Context) error {
// return os.RemoveAll("/tmp/app-*")
// })
func (s *Server) RegisterPostShutdownHook(name string, hook ShutdownHook) {
s.mu.Lock()
defer s.mu.Unlock()
s.postShutdownHooks = append(s.postShutdownHooks, ShutdownHookConfig{Name: name, Hook: hook})
}
// runPreShutdownHooks executes pre-shutdown hooks sequentially in registration order.
func (s *Server) runPreShutdownHooks(ctx context.Context) error {
s.mu.RLock()
hooks := s.preShutdownHooks
s.mu.RUnlock()
if len(hooks) == 0 {
return nil
}
s.logger.Info("Running pre-shutdown hooks", log.F("count", len(hooks)))
for _, hook := range hooks {
select {
case <-ctx.Done():
s.logger.Warn("Pre-shutdown hook aborted due to context cancellation", log.F("hook", hook.Name))
return ctx.Err()
default:
}
s.logger.Info("Running pre-shutdown hook", log.F("hook", hook.Name))
if err := hook.Hook(ctx); err != nil {
s.logger.Error("Pre-shutdown hook failed", log.F("hook", hook.Name), log.E(err))
// Continue with other hooks despite error
}
}
return nil
}
// startShutdownHooks starts shutdown hooks concurrently and returns a WaitGroup and error channel.
// The caller must wait on the returned WaitGroup and then close the error channel.
func (s *Server) startShutdownHooks(ctx context.Context) (*sync.WaitGroup, chan error) {
s.mu.RLock()
hooks := s.shutdownHooks
s.mu.RUnlock()
var wg sync.WaitGroup
errCh := make(chan error, len(hooks))
if len(hooks) == 0 {
return &wg, errCh
}
s.logger.Info("Starting shutdown hooks", log.F("count", len(hooks)))
for _, hook := range hooks {
wg.Add(1)
go func(h ShutdownHookConfig) {
defer wg.Done()
s.logger.Info("Running shutdown hook", log.F("hook", h.Name))
if err := h.Hook(ctx); err != nil {
s.logger.Error("Shutdown hook failed", log.F("hook", h.Name), log.E(err))
errCh <- err
}
}(hook)
}
return &wg, errCh
}
// runPostShutdownHooks executes post-shutdown hooks sequentially in registration order.
func (s *Server) runPostShutdownHooks(ctx context.Context) error {
s.mu.RLock()
hooks := s.postShutdownHooks
s.mu.RUnlock()
if len(hooks) == 0 {
return nil
}
s.logger.Info("Running post-shutdown hooks", log.F("count", len(hooks)))
for _, hook := range hooks {
select {
case <-ctx.Done():
s.logger.Warn("Post-shutdown hook aborted due to context cancellation", log.F("hook", hook.Name))
return ctx.Err()
default:
}
s.logger.Info("Running post-shutdown hook", log.F("hook", hook.Name))
if err := hook.Hook(ctx); err != nil {
s.logger.Error("Post-shutdown hook failed", log.F("hook", hook.Name), log.E(err))
// Continue with other hooks despite error
}
}
return nil
}