fix: prevent context cancellation from blocking file delivery on cancel race
All checks were successful
CI / build (push) Successful in 35s
All checks were successful
CI / build (push) Successful in 35s
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.
This commit is contained in:
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user