-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.go
More file actions
60 lines (54 loc) · 1.61 KB
/
Copy pathbackground.go
File metadata and controls
60 lines (54 loc) · 1.61 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
package api
import (
"context"
"log/slog"
"sync"
)
// Background registers fn to run after the current response has been sent.
// The context passed to fn is detached from the request — it is not cancelled
// when the client disconnects or the request times out. Use this for
// fire-and-forget work like sending notifications, writing audit logs, or
// invalidating caches.
//
// Calling Background outside a handler (or after the handler returns) is a
// no-op. Each task runs in its own goroutine; a panic is logged and does not
// affect other tasks or the server.
func Background(ctx context.Context, fn func(ctx context.Context)) {
q, ok := ctx.Value(bgQueueKey{}).(*bgQueue)
if !ok {
return
}
q.mu.Lock()
q.funcs = append(q.funcs, fn)
q.mu.Unlock()
}
type bgQueueKey struct{}
type bgQueue struct {
mu sync.Mutex
funcs []func(context.Context)
}
// withBackgroundQueue returns a context that carries an empty background
// queue. Handlers append tasks via Background; the framework drains the queue
// after the response is sent.
func withBackgroundQueue(ctx context.Context) (context.Context, *bgQueue) {
q := &bgQueue{}
return context.WithValue(ctx, bgQueueKey{}, q), q
}
// runBackgroundTasks launches each queued task in its own goroutine with a
// fresh background context. Panics are recovered and logged.
func runBackgroundTasks(q *bgQueue) {
q.mu.Lock()
funcs := q.funcs
q.funcs = nil
q.mu.Unlock()
for _, fn := range funcs {
go func() {
defer func() {
if rec := recover(); rec != nil {
slog.Error("background task panicked", "panic", rec)
}
}()
fn(context.Background())
}()
}
}