From 6bbc87a7c8a432a34393a3686a4252e500e95cb6 Mon Sep 17 00:00:00 2001 From: db123 Date: Fri, 26 Jun 2026 13:01:25 +0330 Subject: [PATCH] fix: prevent context cancellation from blocking file delivery on cancel race When a download completes but the user clicks Cancel at the same time, handleDownloadCompletion's Telegram calls used the cancelled download context and failed. Use context.Background() for all notification calls so the file is always delivered regardless of download state. --- internal/handler/download.go | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/internal/handler/download.go b/internal/handler/download.go index 32d266d..afa1970 100644 --- a/internal/handler/download.go +++ b/internal/handler/download.go @@ -511,23 +511,25 @@ func (h *Handler) trackDownloadProgress(ctx context.Context, job *domain.Downloa } // handleDownloadCompletion sends the downloaded file and records history. +// Uses context.Background() for Telegram notifications so that cancellation +// of the download context does not prevent the file from being delivered. func (h *Handler) handleDownloadCompletion(ctx context.Context, job *domain.DownloadJob) { pattern := filepath.Join(h.downloadDir, job.ID+"_*") files, err := filepath.Glob(pattern) if err != nil || len(files) == 0 { - h.editText(ctx, job.ChatID, job.MessageID, "Download completed but file not found.", nil) + h.editText(context.Background(), job.ChatID, job.MessageID, "Download completed but file not found.", nil) return } f := files[0] fileInfo, err := os.Stat(f) if err != nil { - h.editText(ctx, job.ChatID, job.MessageID, "Download completed but file not found.", nil) + h.editText(context.Background(), job.ChatID, job.MessageID, "Download completed but file not found.", nil) return } if fileInfo.Size() > h.maxFileSize { - h.editText(ctx, job.ChatID, job.MessageID, + h.editText(context.Background(), job.ChatID, job.MessageID, fmt.Sprintf("File too large (%s). Max: %s", formatBytes(fileInfo.Size()), formatBytes(h.maxFileSize)), nil) os.Remove(f) return @@ -538,7 +540,7 @@ func (h *Handler) handleDownloadCompletion(ctx context.Context, job *domain.Down h.applyQuota(job.UserID, job.FileSize) } - h.sendDocument(ctx, job.ChatID, f, job.Title) + h.sendDocument(context.Background(), job.ChatID, f, job.Title) os.Remove(f) if err := h.Repo.AddHistory(job.UserID, &domain.DownloadRecord{ @@ -552,7 +554,7 @@ func (h *Handler) handleDownloadCompletion(ctx context.Context, job *domain.Down slog.Error("add history failed", "user_id", job.UserID, "error", err) } - h.editText(ctx, job.ChatID, job.MessageID, "Download completed!", nil) + h.editText(context.Background(), job.ChatID, job.MessageID, "Download completed!", nil) } func (h *Handler) sendDocument(ctx context.Context, chatID int64, filePath, title string) {