Skip to content

Commit 9129ebb

Browse files
committed
db: roll back the request transaction on handler panic
The middleware only committed or rolled back after the handler returned. If the handler panicked, control jumped to the recoverer and the open transaction was leaked. Add a deferred rollback that runs unless one of the normal commit/rollback paths already handled it. Signed-off-by: Robin Jarry <robin@jarry.cc>
1 parent b452b8b commit 9129ebb

1 file changed

Lines changed: 12 additions & 0 deletions

File tree

‎pkg/db/middleware.go‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,19 @@ func Middleware(database *bun.DB, bus EventBus) func(http.Handler) http.Handler
5252
}
5353
ctx = context.WithValue(ctx, queriesKey{}, q)
5454
rw := &statusWriter{ResponseWriter: w}
55+
// Ensure the transaction is rolled back if the handler
56+
// panics (the panic then propagates to the recoverer);
57+
// the normal paths below set handled and take over.
58+
handled := false
59+
defer func() {
60+
if !handled {
61+
if err := q.Rollback(); err != nil {
62+
log.Printf("rollback: %v", err)
63+
}
64+
}
65+
}()
5566
next.ServeHTTP(rw, r.WithContext(ctx))
67+
handled = true
5668
if rw.status >= 400 {
5769
if err := q.Rollback(); err != nil {
5870
log.Printf("rollback: %v", err)

0 commit comments

Comments
 (0)