| 421 | } |
| 422 | |
| 423 | func (a *API) databaseCleanup(cleanup models.Cleaner) func(http.Handler) http.Handler { |
| 424 | return func(next http.Handler) http.Handler { |
| 425 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 426 | wrappedResp := chimiddleware.NewWrapResponseWriter(w, r.ProtoMajor) |
| 427 | next.ServeHTTP(wrappedResp, r) |
| 428 | switch r.Method { |
| 429 | case http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete: |
| 430 | if (wrappedResp.Status() / 100) != 2 { |
| 431 | // don't do any cleanups for non-2xx responses |
| 432 | return |
| 433 | } |
| 434 | // continue |
| 435 | default: |
| 436 | return |
| 437 | } |
| 438 | |
| 439 | db := a.db.WithContext(r.Context()) |
| 440 | log := observability.GetLogEntry(r).Entry |
| 441 | |
| 442 | affectedRows, err := cleanup.Clean(db) |
| 443 | if err != nil { |
| 444 | log.WithError(err).WithField("affected_rows", affectedRows).Warn("database cleanup failed") |
| 445 | } else if affectedRows > 0 { |
| 446 | log.WithField("affected_rows", affectedRows).Debug("cleaned up expired or stale rows") |
| 447 | } |
| 448 | }) |
| 449 | } |
| 450 | } |
| 451 | |
| 452 | // timeoutResponseWriter is a http.ResponseWriter that queues up a response |
| 453 | // body to be sent if the serving completes before the context has exceeded its |