Repository navigation
Expand file tree
/
Copy pathbackground.go
More file actions
216 lines (189 loc) · 6.81 KB
/
Copy pathbackground.go
File metadata and controls
216 lines (189 loc) · 6.81 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
package laravel
import (
"context"
"errors"
"sync"
"time"
"go.opentelemetry.io/otel/trace"
"go.laravel.com/db"
"go.laravel.com/internal/callsite"
"go.laravel.com/internal/scope"
"go.laravel.com/internal/telemetry"
"go.laravel.com/web"
)
// Background runs work in a separate goroutine and returns immediately, for
// non-critical tasks that do not need to finish before the caller returns,
// such as notifying a webhook after a command completes. Pass the scoped
// context from a command, job, or listener; HTTP handlers should call
// [web.Request.Background] instead:
//
// laravel.Background(ctx, func(ctx context.Context) error {
// return webhooks.PostPublished(ctx, post.ID)
// })
//
// When called inside a database transaction, Background waits until the
// outermost transaction commits so work can read committed rows, and discards
// work if the transaction rolls back. The goroutine's context preserves
// values from ctx while dropping its cancellation and transaction. Laravel
// logs any error returned by work and recovers and logs panics.
//
// The serve command and every CLI command wait for in-flight background work
// up to SERVER_SHUTDOWN_TIMEOUT before exiting, canceling any remaining work
// with [web.ErrShutdown]. Background work is not durable: Laravel does not
// retry failures, and a process crash loses in-flight tasks. Background panics
// when ctx does not carry an application scope, such as [context.Background].
func Background(ctx context.Context, work func(ctx context.Context) error) {
scope.Get[interface {
Background(ctx context.Context, work func(ctx context.Context) error)
}](ctx, "laravel.Background").Background(ctx, work)
}
// WaitBackground blocks until all background work completes or ctx is
// canceled, returning ctx.Err() if ctx ends first. The serve command, CLI
// commands, and laraveltest already wait automatically, so call WaitBackground
// only from a custom main function that starts background work directly.
func (a *App) WaitBackground(ctx context.Context) error {
return a.background.wait(ctx)
}
// runBackground runs work in a tracked goroutine once ctx's transaction
// commits, passing any error or recovered panic to report unless the shutdown
// deadline ended the work.
func (a *App) runBackground(ctx context.Context, work func(ctx context.Context) error, report func(ctx context.Context, err error)) {
run := func(ctx context.Context) {
// Work that the shutdown deadline cut off isn't the work's failure.
runSpan(ctx, telemetry.Child(ctx), "background", work, report, func(ctx context.Context, _ error) bool {
return ctx.Err() != nil && errors.Is(context.Cause(ctx), web.ErrShutdown)
})
}
err := db.AfterCommit(ctx, func(ctx context.Context) error {
a.background.start(ctx, run)
return nil
})
if err != nil {
report(ctx, err)
}
}
// runSpan runs work, in a span named name when tracer isn't nil, and
// passes its error or recovered panic to report unless ignore reports true
// for it.
func runSpan(ctx context.Context, tracer trace.Tracer, name string, work func(ctx context.Context) error, report func(ctx context.Context, err error), ignore func(ctx context.Context, err error) bool) {
var span trace.Span
if tracer != nil {
ctx, span = tracer.Start(ctx, name)
}
err := runRecovered(ctx, work)
if err != nil && ignore(ctx, err) {
err = nil
}
if err != nil {
report(ctx, err)
}
if span != nil {
telemetry.End(span, err)
}
}
// runRecovered runs work, and returns a panic in it as a [web.PanicError].
func runRecovered(ctx context.Context, work func(ctx context.Context) error) (err error) {
defer func() {
if recovered := recover(); recovered != nil {
err = &web.PanicError{Value: recovered, Stack: callsite.Stack()}
}
}()
return work(ctx)
}
// endedByShutdown reports whether err is the shutdown deadline ending ctx, which
// isn't the work's fault.
func endedByShutdown(ctx context.Context, err error) bool {
return ctx.Err() != nil && errors.Is(context.Cause(ctx), web.ErrShutdown) && (errors.Is(err, ctx.Err()) || errors.Is(err, web.ErrShutdown))
}
// A group tracks the application's background work, so shutdown can wait
// for it and cut it off at the deadline. The zero group is ready to use.
type group struct {
mu sync.Mutex
running int
// idle is closed when the last running work returns.
idle chan struct{}
// ended ends when the group is cut off, which ends the context of the
// work still running, and of work started afterward.
ended context.Context
cutOff context.CancelCauseFunc
}
// start runs work in a goroutine with a context that keeps parent's values,
// except its transaction, but ends only when the group is cut off.
func (g *group) start(parent context.Context, work func(ctx context.Context)) {
g.mu.Lock()
if g.running == 0 {
g.idle = make(chan struct{})
}
g.running++
ended := g.endedLocked()
g.mu.Unlock()
// The work outlives the caller, so it runs outside the caller's
// transaction.
ctx, cancel := context.WithCancelCause(context.WithoutCancel(db.Outside(parent)))
stop := context.AfterFunc(ended, func() { cancel(context.Cause(ended)) })
go func() {
defer g.done()
defer cancel(nil)
defer stop()
work(ctx)
}()
}
func (g *group) done() {
g.mu.Lock()
defer g.mu.Unlock()
g.running--
if g.running == 0 {
close(g.idle)
}
}
func (g *group) endedLocked() context.Context {
if g.ended == nil {
g.ended, g.cutOff = context.WithCancelCause(context.Background())
}
return g.ended
}
// wait waits until no work is running, or until ctx ends.
func (g *group) wait(ctx context.Context) error {
for {
g.mu.Lock()
idle, running := g.idle, g.running
g.mu.Unlock()
if running == 0 {
return nil
}
select {
case <-idle:
// Work that just finished may have started more.
case <-ctx.Done():
return ctx.Err()
}
}
}
// finish waits for the running work until ctx ends. Then it cuts the work
// off with [web.ErrShutdown] and gives it a second to return. It reports
// whether work was still running when ctx ended.
func (g *group) finish(ctx context.Context) bool {
if g.wait(ctx) == nil {
return false
}
g.mu.Lock()
g.endedLocked()
g.cutOff(web.ErrShutdown)
g.mu.Unlock()
moment, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
g.wait(moment)
return true
}
// waitForBackground waits for the background work of a command that has
// returned, up to the shutdown timeout, and warns about work it cut off.
func (a *App) waitForBackground(ctx context.Context, warn func(format string, args ...any)) {
timeout := a.Config().Server.ShutdownTimeout
// A signal doesn't cut the wait short: the first one already ended the
// command, and a second ends the process.
deadline, cancel := context.WithTimeout(context.WithoutCancel(ctx), timeout)
defer cancel()
if a.background.finish(deadline) {
warn("Stopped background work still in progress after %s.", timeout)
}
}