From 0636d17f55dcfc8d2fb9504d136645a2b14a71fa Mon Sep 17 00:00:00 2001 From: moein Date: Mon, 9 Nov 2026 15:32:39 +0330 Subject: [PATCH] feat: report backup outcomes and recover unavailable thumbnails Make archive and cron completion easy to verify with explicit Finished markers, message totals, active filters, finish times, and elapsed time. Report downloaded, reused, filtered, failed, canceled, and unavailable files by media type without double counting retries or reusing stale job results. Bound repeated Telegram timeouts for optional thumbnails while retaining primary media. Keep unavailable thumbnail warnings visible across later incremental runs until a successful refresh replaces them. Persist structured completion reports, preserve colorful progress, and document the result statuses and per-run counters. Validation: 258 tests pass, including race checks; go vet and build pass. --- CHANGELOG.md | 6 + README.md | 1 + cmd/account.go | 21 +- cmd/archive.go | 64 ++++++- cmd/completion.go | 44 +++++ cmd/completion_test.go | 70 +++++++ cmd/cron.go | 2 +- cmd/progress.go | 39 +++- cmd/progress_test.go | 31 +++ cmd/root.go | 2 + cmd/sync.go | 69 ++++++- docs/archiving.md | 36 ++++ docs/backups.md | 14 ++ internal/archive/account.go | 3 + internal/archive/batch.go | 49 ++++- internal/archive/engine.go | 165 ++++++++++++---- internal/archive/summary.go | 95 +++++++++ internal/archive/summary_output.go | 148 +++++++++++++++ internal/archive/summary_recorder.go | 243 ++++++++++++++++++++++++ internal/archive/summary_test.go | 120 ++++++++++++ internal/archive/thumbnail_inventory.go | 60 ++++++ internal/archive/thumbnail_test.go | 154 +++++++++++++++ internal/cron/cron.go | 1 + internal/cron/run.go | 49 ++++- internal/cron/run_summary_test.go | 220 +++++++++++++++++++++ internal/cron/run_test.go | 2 +- internal/telegram/account.go | 23 +++ internal/telegram/account_media.go | 16 +- internal/telegram/account_test.go | 26 +++ internal/telegram/source.go | 3 + internal/telegram/thumbnail.go | 39 ++++ internal/telegram/thumbnail_test.go | 139 ++++++++++++++ 32 files changed, 1891 insertions(+), 63 deletions(-) create mode 100644 cmd/completion.go create mode 100644 cmd/completion_test.go create mode 100644 internal/archive/summary.go create mode 100644 internal/archive/summary_output.go create mode 100644 internal/archive/summary_recorder.go create mode 100644 internal/archive/summary_test.go create mode 100644 internal/archive/thumbnail_inventory.go create mode 100644 internal/archive/thumbnail_test.go create mode 100644 internal/cron/run_summary_test.go create mode 100644 internal/telegram/thumbnail.go create mode 100644 internal/telegram/thumbnail_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index fcb6ded..4c8b45e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,9 @@ - Separate account backups, including Saved Messages and selectable account data. - Recurring foreground sync and managed system cron jobs with per-job logs and protection against overlapping runs of the same job. +- Archive and cron job completion summaries with message totals, media outcomes + by type, active filters, finish times and elapsed time. Counts are also saved + in structured reports and stay accurate across retries and skipped runs. - Telegram Desktop export assets and formats; supported coverage and remaining differences are documented in `docs/desktop-compatibility.md`. @@ -24,6 +27,9 @@ - Convert poll answer variants from gotd v0.145.1 so the CLI builds with the updated Telegram dependency. +- Continue backups after repeated Telegram timeouts for an optional thumbnail, + retaining the original media and reporting the unavailable preview. Existing + thumbnail warnings remain visible until a successful refresh replaces them. ### Removed diff --git a/README.md b/README.md index c588890..08a6d9a 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ Inspired by [tdl](https://github.com/iyear/tdl), ta uses its transfer and sessio - Desktop-style JSON and offline HTML with local media. - File-type, date and size filters. - Parallel downloads with progress, resume and recovery. +- Archive and cron job results with message totals and media counts by type. - Account data and Saved Messages backups. - Incremental sync, refresh and cron schedules. - Multiple saved Telegram accounts with separate cron backups. diff --git a/cmd/account.go b/cmd/account.go index 1e5de5c..0500af6 100644 --- a/cmd/account.go +++ b/cmd/account.go @@ -8,6 +8,7 @@ import ( "slices" "strconv" "strings" + "time" "github.com/gotd/td/telegram" "github.com/iyear/tdl/core/storage" @@ -74,7 +75,15 @@ func NewAccount() *cobra.Command { if threads < 1 || threads > 64 || pool < 1 || pool > 64 { return fmt.Errorf("threads and pool must be between 1 and 64") } - return tRun(cmd.Context(), func(ctx context.Context, c *telegram.Client, kv storage.Storage) (rerr error) { + recorder, err := archive.NewSummaryRecorder(f.output) + if err != nil { + return err + } + defer recorder.Close() + opts.SummaryRecorder = recorder + started := time.Now().UTC() + var finalReport archive.AccountReport + runErr := tRun(cmd.Context(), func(ctx context.Context, c *telegram.Client, kv storage.Storage) (rerr error) { source := transport.New(ctx, c, kv, pool, threads, viper.GetDuration(consts.FlagReconnectTimeout), since, until) source.DownloadTimeout = viper.GetDuration(flagDownloadTimeout) defer func() { rerr = errors.Join(rerr, source.Close(rerr == nil)) }() @@ -89,6 +98,7 @@ func NewAccount() *cobra.Command { } dir := filepath.Join(f.output, "AccountExport_"+strconv.FormatInt(source.AccountID(), 10)) report, err := source.ExportAccount(ctx, dir, include, opts) + finalReport = report for _, section := range report.Sections { if section.Error != "" { fmt.Fprintf(cmd.ErrOrStderr(), "%s: failed: %s\n", section.Name, section.Error) @@ -99,6 +109,15 @@ func NewAccount() *cobra.Command { fmt.Fprintln(cmd.OutOrStdout(), dir) return err }) + status := archive.SummaryStatus(runErr, finalReport.Summary, finalReport.Warnings) + if errors.Is(cmd.Context().Err(), context.Canceled) { + status = "canceled" + } + fmt.Fprint(cmd.ErrOrStderr(), archive.SummaryText("Finished account backup", status, finalReport.Summary, time.Now(), time.Since(started))) + for _, warning := range finalReport.Warnings { + fmt.Fprintln(cmd.ErrOrStderr(), "Export:", warning) + } + return errors.Join(runErr, writeCompletion(completionPath(cmd), "account", started, finalReport.Summary, finalReport.Warnings, runErr, cmd.Context().Err())) } return cmd } diff --git a/cmd/archive.go b/cmd/archive.go index f726d06..9279dde 100644 --- a/cmd/archive.go +++ b/cmd/archive.go @@ -86,7 +86,15 @@ func newArchive(f *archiveFlags) *cobra.Command { if len(f.chats) == 0 && !f.all { f.chats = []string{"me"} } - return tRunArchive(cmd.Context(), f.resume, cmd.ErrOrStderr(), func(ctx context.Context, c *telegram.Client, kv storage.Storage) (rerr error) { + recorder, err := archive.NewSummaryRecorder(f.output) + if err != nil { + return err + } + defer recorder.Close() + opts.SummaryRecorder = recorder + started := time.Now().UTC() + var finalReport archive.RunReport + runErr := tRunArchive(cmd.Context(), f.resume, cmd.ErrOrStderr(), func(ctx context.Context, c *telegram.Client, kv storage.Storage) (rerr error) { var err error source := transport.New(ctx, c, kv, pool, threads, viper.GetDuration(consts.FlagReconnectTimeout), since, until) source.DownloadTimeout = viper.GetDuration(flagDownloadTimeout) @@ -165,16 +173,38 @@ func newArchive(f *archiveFlags) *cobra.Command { progress := newBackupProgress(cmd.ErrOrStderr()) opts.OnPlan = progress.setPlan opts.OnTransfer = progress.transfer - report, batchErr := archive.RunBatch(ctx, source, f.output, chats, opts, source.Warnings) - newWarnings := len(report.Warnings) != len(source.Warnings) + opts.OnChatFinished = func(entry archive.ChatExport) { + var failure error + if entry.Error != "" { + failure = errors.New(entry.Error) + } + status := archive.SummaryStatus(failure, entry.Summary, nil) + if errors.Is(ctx.Err(), context.Canceled) { + status = "canceled" + } + name := entry.Chat.Name + if name == "" { + name = entry.Chat.Key + } + progress.print(archive.SummaryText(fmt.Sprintf("Finished archive %q", name), status, entry.Summary, entry.Finished, entry.Finished.Sub(entry.Started))) + } + discoveryWarnings := slices.Clone(source.Warnings) + report, batchErr := archive.RunBatch(ctx, source, f.output, chats, opts, discoveryWarnings) + newWarnings := false + for _, warning := range source.Warnings { + if !slices.Contains(report.Warnings, warning) { + report.Warnings = append(report.Warnings, warning) + newWarnings = true + } + } if newWarnings { - report.Warnings = source.Warnings batchErr = errors.Join(batchErr, archive.WriteData(filepath.Join(f.output, "run-report.json"), report)) } + finalReport = report resultErr := errors.Join(batchErr, err, ctx.Err()) progress.finish(resultErr) - if newWarnings { - for _, warning := range source.Warnings { + for _, warning := range report.Warnings { + if !slices.Contains(discoveryWarnings, warning) { fmt.Fprintln(cmd.ErrOrStderr(), "Export:", warning) } } @@ -185,6 +215,28 @@ func newArchive(f *archiveFlags) *cobra.Command { } return resultErr }) + status := archive.SummaryStatus(runErr, finalReport.Summary, finalReport.Warnings) + if errors.Is(cmd.Context().Err(), context.Canceled) { + status = "canceled" + } + if len(finalReport.Chats) == 0 { + finalReport.Summary = recorder.Total(f.output) + finalReport.Summary.HasMessages = true + finalReport.Summary.MessagesKnown = runErr == nil + finalReport.Summary.Filters = archive.SummaryFilters(opts) + status = archive.SummaryStatus(runErr, finalReport.Summary, finalReport.Warnings) + if errors.Is(cmd.Context().Err(), context.Canceled) { + status = "canceled" + } + fmt.Fprint(cmd.ErrOrStderr(), archive.SummaryText("Finished archive run", status, finalReport.Summary, time.Now(), time.Since(started))) + } else { + unit := "chat" + if len(finalReport.Chats) != 1 { + unit = "chats" + } + fmt.Fprintf(cmd.ErrOrStderr(), "Finished archive run | %s | %d %s | Elapsed %s\n", archive.CompletionLabel(status), len(finalReport.Chats), unit, time.Since(started).Round(time.Second)) + } + return errors.Join(runErr, writeCompletion(completionPath(cmd), "archive", started, finalReport.Summary, finalReport.Warnings, runErr, cmd.Context().Err())) } flags := cmd.Flags() flags.BoolVar(&f.refresh, "refresh", false, "refresh existing messages and reactions while retaining archived deletions") diff --git a/cmd/completion.go b/cmd/completion.go new file mode 100644 index 0000000..cdf5816 --- /dev/null +++ b/cmd/completion.go @@ -0,0 +1,44 @@ +package cmd + +import ( + "context" + "encoding/json" + "errors" + "os" + "time" + + "github.com/mo1ein/TelegramArchive/internal/archive" + "github.com/spf13/cobra" +) + +const flagResultFile = "result-file" + +func completionPath(cmd *cobra.Command) string { + flag := cmd.Root().PersistentFlags().Lookup(flagResultFile) + if flag == nil { + return "" + } + return flag.Value.String() +} +func writeCompletion(path, kind string, started time.Time, summary archive.Summary, warnings []string, err, contextErr error) error { + if path == "" { + return nil + } + report := archive.CompletionReport{Kind: kind, Status: archive.SummaryStatus(err, summary, warnings), Started: started, Finished: time.Now().UTC(), Summary: summary, Warnings: warnings} + if errors.Is(contextErr, context.Canceled) { + report.Status = "canceled" + } + if err != nil { + report.Error = err.Error() + } + return archive.WriteData(path, report) +} +func readCompletion(path string) (archive.CompletionReport, error) { + var report archive.CompletionReport + raw, err := os.ReadFile(path) + if err != nil { + return report, err + } + err = json.Unmarshal(raw, &report) + return report, err +} diff --git a/cmd/completion_test.go b/cmd/completion_test.go new file mode 100644 index 0000000..5fc7d99 --- /dev/null +++ b/cmd/completion_test.go @@ -0,0 +1,70 @@ +package cmd + +import ( + "bytes" + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/mo1ein/TelegramArchive/internal/archive" + "github.com/spf13/cobra" + bolt "go.etcd.io/bbolt" +) + +func TestBackupCompletionCarriesChildSummaryToParent(t *testing.T) { + dir := t.TempDir() + result := filepath.Join(dir, "parent-result") + root := &cobra.Command{Use: "ta"} + root.PersistentFlags().String(flagResultFile, "", "") + child := newSync(func(_ context.Context, _ *cobra.Command, args []string) error { + var path string + for _, arg := range args { + if value, ok := strings.CutPrefix(arg, "--"+flagResultFile+"="); ok { + path = value + } + } + info, err := os.Stat(path) + if err != nil || info.Size() != 0 { + t.Fatalf("child did not receive a fresh result file: %v", err) + } + return archive.WriteData(path, archive.CompletionReport{Kind: "archive", Status: "complete_with_warnings", Started: time.Now(), Finished: time.Now(), Warnings: []string{"preview unavailable"}, Summary: archive.Summary{HasMessages: true, MessagesKnown: true, Messages: 3, MediaKnown: true, Media: map[string]archive.MediaCounts{"photos": {Downloaded: 2}, "thumbnails": {Unavailable: 1}}}}) + }) + root.AddCommand(child) + root.SetArgs([]string{"sync", "--chat=demo", "--output=" + dir, "--" + flagResultFile + "=" + result}) + if err := root.ExecuteContext(context.Background()); err != nil { + t.Fatal(err) + } + report, err := readCompletion(result) + if err != nil || report.Kind != "backup" || report.Status != "complete_with_warnings" || report.Summary.Messages != 3 || report.Summary.Totals().Downloaded != 2 || report.Summary.Totals().Unavailable != 1 { + t.Fatalf("job lost child outcomes: %+v err=%v", report, err) + } +} + +func TestSkippedBackupReportsSkipWithoutReusingOldSummary(t *testing.T) { + dir := t.TempDir() + result := filepath.Join(dir, "parent-result") + lock, err := bolt.Open(filepath.Join(dir, ".backup.lock"), 0600, nil) + if err != nil { + t.Fatal(err) + } + defer lock.Close() + old := []byte("previous active backup report") + if err = os.WriteFile(filepath.Join(dir, "backup-report.json"), old, 0600); err != nil { + t.Fatal(err) + } + root := &cobra.Command{Use: "ta"} + root.PersistentFlags().String(flagResultFile, "", "") + root.AddCommand(newSync(func(context.Context, *cobra.Command, []string) error { t.Fatal("busy backup executed"); return nil })) + root.SetArgs([]string{"sync", "--chat=demo", "--output=" + dir, "--skip-busy", "--" + flagResultFile + "=" + result}) + if err = root.ExecuteContext(context.Background()); err != nil { + t.Fatal(err) + } + report, err := readCompletion(result) + current, _ := os.ReadFile(filepath.Join(dir, "backup-report.json")) + if err != nil || report.Status != "skipped" || report.Summary.Totals().Downloaded != 0 || !bytes.Equal(old, current) { + t.Fatalf("skip reused or overwrote active results: %+v err=%v", report, err) + } +} diff --git a/cmd/cron.go b/cmd/cron.go index 75d3294..092df7a 100644 --- a/cmd/cron.go +++ b/cmd/cron.go @@ -199,7 +199,7 @@ func cronArguments(cmd *cobra.Command) ([]string, map[string]string, error) { var args []string var optionErr error cmd.Root().PersistentFlags().VisitAll(func(flag *pflag.Flag) { - if flag.Deprecated != "" || flag.Name == "proxy" { + if flag.Deprecated != "" || flag.Name == "proxy" || flag.Name == flagResultFile { return } value := "" diff --git a/cmd/progress.go b/cmd/progress.go index f06ff87..a5b01aa 100644 --- a/cmd/progress.go +++ b/cmd/progress.go @@ -1,6 +1,7 @@ package cmd import ( + "errors" "fmt" "io" "math" @@ -22,6 +23,11 @@ type activeTransfer struct { order uint64 } +type progressMessage struct { + text string + done chan struct{} +} + type backupProgress struct { mu sync.Mutex started, transferStarted time.Time @@ -30,15 +36,17 @@ type backupProgress struct { order uint64 bytes, completeBytes int64 completeFiles int64 + unavailableThumbnails int64 finished bool colorful bool failure error stop chan error stopped, refresh chan struct{} + messages chan progressMessage } func newBackupProgress(output io.Writer) *backupProgress { - p := &backupProgress{started: time.Now(), active: map[string]activeTransfer{}, stop: make(chan error), stopped: make(chan struct{}), refresh: make(chan struct{}, 1)} + p := &backupProgress{started: time.Now(), active: map[string]activeTransfer{}, stop: make(chan error), stopped: make(chan struct{}), refresh: make(chan struct{}, 1), messages: make(chan progressMessage)} fd, terminal := 0, false if file, ok := output.(interface{ Fd() uintptr }); ok { fd = int(file.Fd()) @@ -77,6 +85,14 @@ func newBackupProgress(output io.Writer) *backupProgress { render() for { select { + case message := <-p.messages: + if terminal && drawn { + fmt.Fprint(output, "\x1b[3A\x1b[J") + } + fmt.Fprint(output, message.text) + drawn = false + render() + close(message.done) case err := <-p.stop: p.mu.Lock() p.finished, p.failure = true, err @@ -93,6 +109,12 @@ func newBackupProgress(output io.Writer) *backupProgress { return p } +func (p *backupProgress) print(message string) { + request := progressMessage{text: message, done: make(chan struct{})} + p.messages <- request + <-request.done +} + func (p *backupProgress) setPlan(plan archive.DownloadPlan) { p.mu.Lock() p.plan = plan @@ -129,6 +151,14 @@ func (p *backupProgress) transfer(event archive.TransferEvent) { if event.Err == nil { p.completeFiles++ p.completeBytes += t.received + } else if event.File.Field == "thumbnail" && errors.Is(event.Err, archive.ErrThumbnailUnavailable) { + p.unavailableThumbnails++ + p.bytes = max(0, p.bytes-t.received) + p.plan.Bytes = max(0, p.plan.Bytes-t.size) + p.plan.Files = max(0, p.plan.Files-1) + if t.size <= 0 { + p.plan.UnknownFiles = max(0, p.plan.UnknownFiles-1) + } } delete(p.active, key) } @@ -181,6 +211,13 @@ func (p *backupProgress) lines(now time.Time, width int) []string { label = "Backup failed" } else { percent = 100 + if p.unavailableThumbnails > 0 { + label += fmt.Sprintf(" ยท %d thumbnail", p.unavailableThumbnails) + if p.unavailableThumbnails != 1 { + label += "s" + } + label += " unavailable" + } } } elapsed := max(0, now.Sub(p.started)) diff --git a/cmd/progress_test.go b/cmd/progress_test.go index 4477695..b2b9803 100644 --- a/cmd/progress_test.go +++ b/cmd/progress_test.go @@ -60,6 +60,27 @@ func TestBackupProgressShowsHistoryScanWork(t *testing.T) { } } +func TestBackupProgressExcludesUnavailableThumbnails(t *testing.T) { + start := time.Now() + p := &backupProgress{started: start, active: map[string]activeTransfer{}} + p.setPlan(archive.DownloadPlan{Ready: true, Files: 2, Bytes: 100}) + thumb := archive.File{Field: "thumbnail", Path: "video_files/thumb.jpg", Size: 20} + p.transfer(archive.TransferEvent{Kind: archive.TransferStarted, File: thumb}) + p.transfer(archive.TransferEvent{Kind: archive.TransferProgressed, File: thumb, Delta: 4}) + p.transfer(archive.TransferEvent{Kind: archive.TransferFinished, File: thumb, Err: archive.ErrThumbnailUnavailable}) + video := archive.File{Field: "file", Path: "video_files/movie.mp4", Size: 80} + p.transfer(archive.TransferEvent{Kind: archive.TransferStarted, File: video}) + p.transfer(archive.TransferEvent{Kind: archive.TransferProgressed, File: video, Delta: 40}) + output := strings.Join(p.lines(start.Add(time.Second), 100), "\n") + if !strings.Contains(output, "50.0%") || !strings.Contains(output, "40 B / 80 B") { + t.Fatalf("unavailable thumbnail distorted remaining progress:\n%s", output) + } + p.finished = true + if output = strings.Join(p.lines(start.Add(time.Second), 100), "\n"); !strings.Contains(output, "1 thumbnail unavailable") { + t.Fatalf("completion hid missing thumbnail:\n%s", output) + } +} + func TestBackupProgressFinishesOnlyAfterArchiveSucceeds(t *testing.T) { start := time.Now() p := &backupProgress{started: start, active: map[string]activeTransfer{}} @@ -111,3 +132,13 @@ func TestBackupProgressRunsWithArchiveAndWritesPlainLogs(t *testing.T) { t.Fatalf("invalid progress log:\n%s", text) } } + +func TestBackupProgressKeepsArchiveSummaryVisible(t *testing.T) { + var output bytes.Buffer + progress := newBackupProgress(&output) + progress.print("Finished archive test | completed\nMessages archived: 4 total\n") + progress.finish(nil) + if text := output.String(); strings.Count(text, "Finished archive test") != 1 || !strings.Contains(text, "Messages archived: 4 total") || strings.Contains(text, "\x1b") { + t.Fatalf("summary was lost or corrupted in progress output: %q", text) + } +} diff --git a/cmd/root.go b/cmd/root.go index 4fcc36b..004c5f1 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -17,6 +17,8 @@ func New() *cobra.Command { root.Use = "ta" root.Short = "Back up Telegram chats and account data as JSON or offline HTML" root.Version = version() + root.PersistentFlags().String(flagResultFile, "", "private completion report for a parent backup process") + root.PersistentFlags().MarkHidden(flagResultFile) root.PersistentFlags().Duration(flagDownloadTimeout, transport.DefaultDownloadTimeout, "inactivity limit for archive history reads and media transfers; 0 disables") _ = viper.BindPFlag(flagDownloadTimeout, root.PersistentFlags().Lookup(flagDownloadTimeout)) for _, command := range root.Commands() { diff --git a/cmd/sync.go b/cmd/sync.go index 2b1a6d5..8676480 100644 --- a/cmd/sync.go +++ b/cmd/sync.go @@ -6,6 +6,7 @@ import ( "fmt" "os" "path/filepath" + "slices" "strings" "time" @@ -17,9 +18,10 @@ import ( ) type backupComponent struct { - Command string `json:"command"` - Status string `json:"status"` - Error string `json:"error,omitempty"` + Command string `json:"command"` + Status string `json:"status"` + Error string `json:"error,omitempty"` + Summary archive.Summary `json:"summary"` } type backupReport struct { @@ -27,6 +29,8 @@ type backupReport struct { Finished time.Time `json:"finished_at,omitempty"` Status string `json:"status"` Components []backupComponent `json:"components"` + Summary archive.Summary `json:"summary"` + Warnings []string `json:"warnings,omitempty"` } type childRunner func(context.Context, *cobra.Command, []string) error @@ -144,7 +148,25 @@ func newSyncPlan(run childRunner, planned func(*cobra.Command, string, schedule. return cmd } -func runBackupCycle(ctx context.Context, cmd *cobra.Command, dir string, commands [][]string, run childRunner, skipBusy bool) error { +func runBackupCycle(ctx context.Context, cmd *cobra.Command, dir string, commands [][]string, run childRunner, skipBusy bool) (rerr error) { + started := time.Now().UTC() + provided := completionPath(cmd) + completion := archive.CompletionReport{Kind: "backup", Started: started, Status: "failed"} + defer func() { + completion.Finished = time.Now().UTC() + if rerr != nil { + completion.Status = "failed" + completion.Error = rerr.Error() + } + if errors.Is(ctx.Err(), context.Canceled) { + completion.Status = "canceled" + } + if provided != "" { + rerr = errors.Join(rerr, archive.WriteData(provided, completion)) + } else { + fmt.Fprint(cmd.ErrOrStderr(), archive.SummaryText("Finished backup", completion.Status, completion.Summary, completion.Finished, completion.Finished.Sub(started))) + } + }() if err := os.MkdirAll(dir, 0700); err != nil { return err } @@ -153,9 +175,21 @@ func runBackupCycle(ctx context.Context, cmd *cobra.Command, dir string, command return err } if lock == nil { + completion.Status = "skipped" + completion.Error = "Output folder was busy; this backup was skipped." return nil } defer lock.Close() + resultPath := provided + if resultPath == "" { + f, err := os.CreateTemp(dir, ".component-result-*") + if err != nil { + return err + } + resultPath = f.Name() + f.Close() + defer os.Remove(resultPath) + } report := backupReport{Started: time.Now().UTC(), Status: "running"} path := filepath.Join(dir, "backup-report.json") if err := archive.WriteData(path, report); err != nil { @@ -177,12 +211,29 @@ func runBackupCycle(ctx context.Context, cmd *cobra.Command, dir string, command if err := archive.WriteData(path, report); err != nil { return err } - err := run(ctx, cmd, args) + if err := os.WriteFile(resultPath, nil, 0600); err != nil { + return err + } + childArgs := slices.DeleteFunc(slices.Clone(args), func(arg string) bool { return strings.HasPrefix(arg, "--"+flagResultFile+"=") }) + childArgs = append(childArgs, "--"+flagResultFile+"="+resultPath) + err := run(ctx, cmd, childArgs) if ctx.Err() != nil { err = errors.Join(err, ctx.Err()) } component := &report.Components[len(report.Components)-1] component.Status = "complete" + child, summaryErr := readCompletion(resultPath) + if summaryErr == nil && child.Kind == name { + component.Summary = child.Summary + report.Summary.Add(child.Summary) + report.Warnings = append(report.Warnings, child.Warnings...) + component.Status = child.Status + } else { + component.Summary.Error = "Child did not report media counts." + report.Summary.Add(component.Summary) + } + completion.Summary = report.Summary + completion.Warnings = report.Warnings if err != nil { component.Status, component.Error = "failed", err.Error() failures = append(failures, fmt.Errorf("%s: %w", name, err)) @@ -191,11 +242,11 @@ func runBackupCycle(ctx context.Context, cmd *cobra.Command, dir string, command return err } } - report.Status = "complete" - if len(failures) > 0 { - report.Status = "failed" - } + report.Status = archive.SummaryStatus(errors.Join(failures...), report.Summary, report.Warnings) report.Finished = time.Now().UTC() + completion.Status = report.Status + completion.Summary = report.Summary + completion.Warnings = report.Warnings return errors.Join(errors.Join(failures...), archive.WriteData(path, report)) } diff --git a/docs/archiving.md b/docs/archiving.md index d7d6947..4130fb8 100644 --- a/docs/archiving.md +++ b/docs/archiving.md @@ -157,6 +157,17 @@ restart a stalled run after upgrading to enable this behavior. Ctrl+C, authorization errors and local file errors stop the run. `--resume=false` disables these session retries. +Telegram can return repeated timeouts for a document thumbnail while its video +or document remains downloadable. After three consecutive server timeout replies, +ta marks that thumbnail as unavailable and continues the backup. Original videos, +documents and photos still require successful downloads. Cancellation and local +file errors still stop the run. + +Unavailable thumbnails appear as placeholders in JSON/HTML, with details in +`archive-metadata.json` and a warning in `run-report.json`. Progress excludes them +from the remaining download total and reports their count at completion. +Use `--refresh` to retry these thumbnails later. + ta reads history in pages of 100 messages. Downloads run in parallel: | Setting | Default | Controls | @@ -201,6 +212,31 @@ Messages arriving after preparation are left for the next sync. If Telegram does not report a file size, progress uses completed files and omits the total byte size. Cron and redirected output receive periodic plain text updates. +Each chat ends with a `Finished archive` summary. It includes the finish time, +elapsed time, active filters, total archived messages and new messages added. +Media results are grouped by type, with thumbnails listed separately: + +```text +Type Downloaded Reused Filtered Failed Unavailable Canceled +Photos 12 30 2 0 0 0 +Videos 3 8 0 0 0 0 +Thumbnails 8 20 0 0 1 0 +``` + +These are counts for the current invocation. Downloaded means a complete, +verified file was saved. Reused means a matching local file was checked and kept. +Filtered means a visited file was excluded by the selected media, date, size, +extension or MIME filters. Excluded history is not scanned just to count it. +Failed and canceled transfers are listed separately. Retries and repeated file +references do not inflate counts, and files downloaded before a reconnect remain +counted as downloaded. + +Unchanged history is retained without recounting every old media file. An +incremental run can therefore report the full archived message total alongside +zero new downloads. Stored unavailable thumbnails keep the result marked +`completed with warnings` until a refresh successfully replaces them. +The structured counts are also saved in `run-report.json` and account reports. + History stays on disk; output streams in date order. Memory holds a history page, transfer buffers and statistics maps. Account photo, story and contact lists keep their metadata in memory. diff --git a/docs/backups.md b/docs/backups.md index aca37ad..2a8f3a4 100644 --- a/docs/backups.md +++ b/docs/backups.md @@ -67,6 +67,20 @@ wait for it to finish. Ctrl+C cancels waiting and keeps the installed cron job. Automatic cron runs skip a busy output folder, and triggers are also skipped while the same job is running. Failed jobs retry at the next scheduled time. +The last line of a completed job starts with `Finished job "NAME"`. It reports +the result, downloaded/reused/filtered/failed/unavailable file totals, finish time +and elapsed time. A table above it breaks down media types, and the archive +summary gives the total messages stored and the new messages added this run. +`completed with warnings` keeps unavailable thumbnails visible even on later +incremental runs. A skipped job says `skipped` and does not claim a completed +backup or reuse counts from a previous run. A failed job retains the work and +reports the partial results available. +If a child cannot provide a valid report, the result or counts are marked +unavailable rather than claiming success or inventing zero counts. + +Inspect `backup-report.json` for the structured totals and component outcomes. +For live results, use `ta cron logs NAME` or `tail -f ~/.ta/cron/NAME.log`. + `--every 6h` means 00:00, 06:00, 12:00 and 18:00 in cron's timezone. Use whole minutes that divide an hour, or whole hours that divide a day. Examples are `15m`, `1h`, `6h` and `24h`. Use foreground sync for intervals such as `90m`. diff --git a/internal/archive/account.go b/internal/archive/account.go index 44e1a6d..1a65f7f 100644 --- a/internal/archive/account.go +++ b/internal/archive/account.go @@ -15,6 +15,8 @@ type AccountSection struct { Error string `json:"error,omitempty"` } type AccountReport struct { + Summary Summary `json:"summary"` + Warnings []string `json:"warnings,omitempty"` AccountID int64 `json:"account_id"` ExportedAt time.Time `json:"exported_at"` Sections []AccountSection `json:"sections"` @@ -58,6 +60,7 @@ func plainValue(v any) string { // DownloadItems applies the same media filters, cache and integrity checks used // by chats to a bounded page of account photos or stories. func DownloadItems(ctx context.Context, source Source, dir string, items []Item, opts Options) error { + opts = summaryOptions(opts, dir) return downloadPage(ctx, source, dir, items, opts) } diff --git a/internal/archive/batch.go b/internal/archive/batch.go index f6e81b3..ccbe7ee 100644 --- a/internal/archive/batch.go +++ b/internal/archive/batch.go @@ -9,20 +9,25 @@ import ( "path/filepath" "slices" "strings" + "sync" "time" "unicode" "unicode/utf8" ) type ChatExport struct { - Chat Chat `json:"chat"` - Paths []string `json:"files,omitempty"` - Stats Stats `json:"statistics"` - Error string `json:"error,omitempty"` - Link string `json:"-"` + Started time.Time `json:"started_at"` + Finished time.Time `json:"finished_at"` + Summary Summary `json:"summary"` + Chat Chat `json:"chat"` + Paths []string `json:"files,omitempty"` + Stats Stats `json:"statistics"` + Error string `json:"error,omitempty"` + Link string `json:"-"` } type RunReport struct { + Summary Summary `json:"summary"` Started time.Time `json:"started_at"` Finished time.Time `json:"finished_at"` Chats []ChatExport `json:"chats"` @@ -31,7 +36,8 @@ type RunReport struct { // RunBatch finishes independent chats after a failure, then returns all errors. func RunBatch(ctx context.Context, source Source, root string, chats []Chat, opts Options, warnings []string) (RunReport, error) { - report := RunReport{Started: time.Now().UTC(), Warnings: warnings} + report := RunReport{Started: time.Now().UTC(), Warnings: slices.Clone(warnings)} + opts.unavailableThumbnails = &sync.Map{} var failures []error if err := opts.Validate(); err != nil { return report, err @@ -39,6 +45,14 @@ func RunBatch(ctx context.Context, source Source, root string, chats []Chat, opt if err := os.MkdirAll(root, 0700); err != nil { return report, err } + if opts.SummaryRecorder == nil { + var err error + opts.SummaryRecorder, err = NewSummaryRecorder(root) + if err != nil { + return report, err + } + defer opts.SummaryRecorder.Close() + } entries, err := os.ReadDir(root) if err != nil { return report, err @@ -74,11 +88,16 @@ func RunBatch(ctx context.Context, source Source, root string, chats []Chat, opt failures = append(failures, fmt.Errorf("unsafe chat key")) continue } - record := ChatExport{Chat: chat} + record := ChatExport{Chat: chat, Started: time.Now().UTC(), Summary: Summary{HasMessages: true, MediaKnown: true, Media: map[string]MediaCounts{}, Filters: SummaryFilters(opts)}} name, err := exportDirectory(chat, opts.ExportName, directories) if err != nil { record.Error = err.Error() + record.Finished = time.Now().UTC() + report.Summary.Add(record.Summary) report.Chats = append(report.Chats, record) + if opts.OnChatFinished != nil { + opts.OnChatFinished(record) + } failures = append(failures, fmt.Errorf("%s: %w", chat.Name, err)) continue } @@ -92,6 +111,12 @@ func RunBatch(ctx context.Context, source Source, root string, chats []Chat, opt if err == nil { result, err = Run(ctx, source, dir, chat, chatOpts) } + record.Summary = result.Summary + if !record.Summary.HasMessages { + record.Summary = opts.SummaryRecorder.Snapshot(dir) + record.Summary.HasMessages = true + record.Summary.Filters = SummaryFilters(opts) + } if err != nil { record.Error = err.Error() failures = append(failures, fmt.Errorf("%s: %w", chat.Name, err)) @@ -108,7 +133,12 @@ func RunBatch(ctx context.Context, source Source, root string, chats []Chat, opt } } } + record.Finished = time.Now().UTC() + report.Summary.Add(record.Summary) report.Chats = append(report.Chats, record) + if opts.OnChatFinished != nil { + opts.OnChatFinished(record) + } // Recreate a stalled connection before trying the remaining chats. // Permanent per-chat failures still leave other chats independent. var timeout net.Error @@ -117,6 +147,11 @@ func RunBatch(ctx context.Context, source Source, root string, chats []Chat, opt } } report.Finished = time.Now().UTC() + if count := report.Summary.Totals().Unavailable; count > 0 { + report.Warnings = append(report.Warnings, fmt.Sprintf("%d thumbnail(s) unavailable after Telegram timeouts; primary media retained. Use --refresh to retry the thumbnails later.", count)) + } else if count := report.Summary.StoredUnavailableThumbnails; count > 0 { + report.Warnings = append(report.Warnings, fmt.Sprintf("Archive retains %d unavailable thumbnail(s); use --refresh to retry later.", count)) + } if err := writeJSON(filepath.Join(root, "run-report.json"), report); err != nil { failures = append(failures, err) } diff --git a/internal/archive/engine.go b/internal/archive/engine.go index bf0acd5..0f5f930 100644 --- a/internal/archive/engine.go +++ b/internal/archive/engine.go @@ -12,6 +12,7 @@ import ( "path/filepath" "slices" "strconv" + "sync" "sync/atomic" "time" @@ -53,12 +54,24 @@ type ProgressSource interface { DownloadWithProgress(context.Context, File, string, func(int64)) error } +// ErrThumbnailUnavailable marks a server-side thumbnail failure after bounded +// retries. It never excuses a failed primary attachment or a local file error. +var ErrThumbnailUnavailable = errors.New("thumbnail unavailable") + +func unavailableThumbnail(file File, err error) bool { + var local *os.PathError + return file.Field == "thumbnail" && errors.Is(err, ErrThumbnailUnavailable) && + !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded) && !errors.As(err, &local) +} + type TransferEventKind uint8 const ( TransferStarted TransferEventKind = iota TransferProgressed TransferFinished + TransferReused + TransferFiltered ) type TransferEvent struct { @@ -66,29 +79,33 @@ type TransferEvent struct { File File Delta int64 Err error + Bytes int64 // Size of the verified completed file, independent of metadata. } type Options struct { - Media []string - Concurrency int - MaxFileSize int64 - MinFileSize int64 - Extensions []string - MIMETypes []string - OnlyMedia bool - Format string - ExportName string - HTMLPageSize int - PartSize int64 - Since time.Time - Until time.Time - Resume bool - Refresh bool - Takeout bool - Progress func(int) - OnTransfer func(TransferEvent) - OnPlan func(DownloadPlan) - snapshotNewest *int + Media []string + Concurrency int + MaxFileSize int64 + MinFileSize int64 + Extensions []string + MIMETypes []string + OnlyMedia bool + Format string + ExportName string + HTMLPageSize int + PartSize int64 + Since time.Time + Until time.Time + Resume bool + Refresh bool + Takeout bool + Progress func(int) + OnTransfer func(TransferEvent) + OnPlan func(DownloadPlan) + SummaryRecorder *SummaryRecorder + OnChatFinished func(ChatExport) + snapshotNewest *int + unavailableThumbnails *sync.Map } func (o Options) Validate() error { @@ -124,8 +141,9 @@ func (o Options) Validate() error { var MediaKinds = []string{"photos", "videos", "audios", "stickers", "animations", "documents", "voice_messages", "video_messages", "contacts"} type Result struct { - Paths []string - Stats Stats + Paths []string + Stats Stats + Summary Summary } type checkpoint struct { Settings string @@ -140,10 +158,14 @@ var messageBucket = []byte("messages") var metaBucket = []byte("meta") var stateKey = []byte("checkpoint") -// Run checkpoints a page only after every selected media file succeeds. An +// Run checkpoints a page after required media succeeds; unavailable optional +// thumbnails are recorded explicitly. An // interrupted page is retried, and already completed files are reused by size. // bbolt provides ordered disk-backed iteration without collecting chat history. -func Run(ctx context.Context, source Source, dir string, chat Chat, opts Options) (Result, error) { +func Run(ctx context.Context, source Source, dir string, chat Chat, opts Options) (result Result, rerr error) { + if opts.unavailableThumbnails == nil { + opts.unavailableThumbnails = &sync.Map{} + } if err := opts.Validate(); err != nil { return Result{}, err } @@ -153,6 +175,25 @@ func Run(ctx context.Context, source Source, dir string, chat Chat, opts Options if err := os.MkdirAll(dir, 0700); err != nil { return Result{}, err } + if opts.SummaryRecorder == nil { + var err error + opts.SummaryRecorder, err = NewSummaryRecorder(dir) + if err != nil { + return Result{}, err + } + defer opts.SummaryRecorder.Close() + } + opts = summaryOptions(opts, dir) + var inventory int64 + var inventoryKnown bool + defer func() { + opts.SummaryRecorder.SetMessages(dir, result.Stats.Messages+result.Stats.ServiceMessages, rerr == nil) + if inventoryKnown { + opts.SummaryRecorder.SetStoredUnavailable(dir, inventory) + } + result.Summary = opts.SummaryRecorder.Snapshot(dir) + result.Summary.Filters = SummaryFilters(opts) + }() db, err := bolt.Open(filepath.Join(dir, "archive.db"), 0600, &bolt.Options{Timeout: time.Second}) if err != nil { return Result{}, fmt.Errorf("open archive checkpoint: %w", err) @@ -207,6 +248,9 @@ func Run(ctx context.Context, source Source, dir string, chat Chat, opts Options if err := prepareRenderIndexes(ctx, tx); err != nil { return err } + if err := prepareThumbnailInventory(tx); err != nil { + return err + } b, err := json.Marshal(state) if err != nil { return err @@ -216,8 +260,17 @@ func Run(ctx context.Context, source Source, dir string, chat Chat, opts Options if err != nil { return Result{}, err } + if err = db.View(func(tx *bolt.Tx) error { + inventory = int64(binary.BigEndian.Uint64(tx.Bucket(metaBucket).Get(thumbnailInventoryKey))) + return nil + }); err != nil { + return Result{}, err + } + inventoryKnown = true save := func(items []Item) error { - return db.Update(func(tx *bolt.Tx) error { + var added int64 + nextInventory := inventory + err := db.Update(func(tx *bolt.Tx) error { for _, item := range items { b, err := json.Marshal(item.Message) if err != nil { @@ -228,6 +281,9 @@ func Run(ctx context.Context, source Source, dir string, chat Chat, opts Options if bytes.Equal(bucket.Get(key), b) { continue } + if bucket.Get(key) == nil { + added++ + } if err := bucket.Put(key, b); err != nil { return err } @@ -235,6 +291,9 @@ func Run(ctx context.Context, source Source, dir string, chat Chat, opts Options if err != nil { return err } + if err = updateThumbnailInventory(tx, key, item.Message); err != nil { + return err + } if len(row) == 0 { err = tx.Bucket(metadataRowsBucket).Delete(key) } else { @@ -252,11 +311,28 @@ func Run(ctx context.Context, source Source, dir string, chat Chat, opts Options if err != nil { return err } + nextInventory = int64(binary.BigEndian.Uint64(tx.Bucket(metaBucket).Get(thumbnailInventoryKey))) return tx.Bucket(metaBucket).Put(stateKey, b) }) + if err == nil { + inventory = nextInventory + opts.SummaryRecorder.AddMessages(dir, added) + } + return err } err = walkHistory(ctx, source, chat, &state, opts, func(items []Item) error { selected := FilterItems(items, opts) + selectedIDs := map[int]bool{} + for _, item := range selected { + selectedIDs[item.Message.ID] = true + } + for _, item := range items { + if !selectedIDs[item.Message.ID] { + for _, file := range item.Files { + opts.OnTransfer(TransferEvent{Kind: TransferFiltered, File: file}) + } + } + } if err := downloadPage(ctx, source, dir, selected, opts); err != nil { return err } @@ -396,6 +472,9 @@ func downloadPage(ctx context.Context, source Source, dir string, items []Item, } value := Excluded reason := fileSkipReason(file, item.Message, opts) + if reason != "" && opts.OnTransfer != nil { + opts.OnTransfer(TransferEvent{Kind: TransferFiltered, File: file}) + } if reason == "file_size" { value = TooLarge } @@ -408,9 +487,13 @@ func downloadPage(ctx context.Context, source Source, dir string, items []Item, } _, err, _ := transfers.Do(file.Path, func() (any, error) { return nil, downloadFile(ctx, source, dir, file, opts) }) if err != nil { - return fmt.Errorf("message %d, %s: %w", item.Message.ID, file.Path, err) + if ctx.Err() != nil || !unavailableThumbnail(file, err) { + return fmt.Errorf("message %d, %s: %w", item.Message.ID, file.Path, err) + } + reason = "unavailable" + } else { + value = file.Path } - value = file.Path } switch file.Field { case "custom_emoji": @@ -440,8 +523,26 @@ func downloadPage(ctx context.Context, source Source, dir string, items []Item, func downloadFile(ctx context.Context, source Source, dir string, file File, opts Options) (rerr error) { dest := filepath.Join(dir, filepath.FromSlash(file.Path)) if completedFile(dir, file) { + if opts.OnTransfer != nil { + opts.OnTransfer(TransferEvent{Kind: TransferReused, File: file, Bytes: downloadSize(file)}) + } return nil } + if opts.unavailableThumbnails != nil { + if failure, ok := opts.unavailableThumbnails.Load(dest); ok { + return failure.(error) + } + defer func() { + if unavailableThumbnail(file, rerr) { + opts.unavailableThumbnails.Store(dest, rerr) + } + }() + } + var written int64 + if opts.OnTransfer != nil { + opts.OnTransfer(TransferEvent{Kind: TransferStarted, File: file}) + defer func() { opts.OnTransfer(TransferEvent{Kind: TransferFinished, File: file, Err: rerr, Bytes: written}) }() + } if err := os.MkdirAll(filepath.Dir(dest), 0700); err != nil { return err } @@ -453,10 +554,6 @@ func downloadFile(ctx context.Context, source Source, dir string, file File, opt f.Close() defer os.Remove(tmp) var reported atomic.Int64 - if opts.OnTransfer != nil { - opts.OnTransfer(TransferEvent{Kind: TransferStarted, File: file}) - defer func() { opts.OnTransfer(TransferEvent{Kind: TransferFinished, File: file, Err: rerr}) }() - } if file.Data != nil { err = os.WriteFile(tmp, file.Data, 0600) } else { @@ -485,7 +582,11 @@ func downloadFile(ctx context.Context, source Source, dir string, file File, opt if opts.OnTransfer != nil && st.Size() > reported.Load() { opts.OnTransfer(TransferEvent{Kind: TransferProgressed, File: file, Delta: st.Size() - reported.Load()}) } - return os.Rename(tmp, dest) + err = os.Rename(tmp, dest) + if err == nil { + written = st.Size() + } + return err } func writeJSON(path string, value any) error { diff --git a/internal/archive/summary.go b/internal/archive/summary.go new file mode 100644 index 0000000..b831e1c --- /dev/null +++ b/internal/archive/summary.go @@ -0,0 +1,95 @@ +package archive + +import ( + "slices" + "time" +) + +// MediaCounts describes the final outcome of each distinct file in this run. +// A file downloaded before a reconnect remains downloaded when later reused. +type MediaCounts struct { + Downloaded int64 `json:"downloaded"` + Reused int64 `json:"reused"` + Filtered int64 `json:"filtered"` + Failed int64 `json:"failed"` + Unavailable int64 `json:"unavailable"` + Canceled int64 `json:"canceled"` +} + +// Summary separates archive inventory from work performed by this invocation. +type Summary struct { + HasMessages bool `json:"has_messages,omitempty"` + MessagesKnown bool `json:"messages_known"` + Messages int64 `json:"messages"` + MessagesAdded int64 `json:"messages_added"` + StoredUnavailableThumbnails int64 `json:"stored_unavailable_thumbnails,omitempty"` + MediaKnown bool `json:"media_known"` + Media map[string]MediaCounts `json:"media"` + DownloadedBytes int64 `json:"downloaded_bytes"` + Filters []string `json:"filters,omitempty"` + Error string `json:"error,omitempty"` +} + +// CompletionReport is passed privately from each backup child to its parent. +// A fresh file per invocation prevents a skipped job from reporting old results. +type CompletionReport struct { + Kind string `json:"kind"` + Status string `json:"status"` + Started time.Time `json:"started_at"` + Finished time.Time `json:"finished_at"` + Summary Summary `json:"summary"` + Warnings []string `json:"warnings,omitempty"` + Error string `json:"error,omitempty"` +} + +func (s *Summary) Add(other Summary) { + if s.Media == nil { + s.Media = map[string]MediaCounts{} + s.MediaKnown = other.MediaKnown + } else { + s.MediaKnown = s.MediaKnown && other.MediaKnown + } + for kind, c := range other.Media { + v := s.Media[kind] + v.add(c) + s.Media[kind] = v + } + s.DownloadedBytes += other.DownloadedBytes + s.MessagesAdded += other.MessagesAdded + s.StoredUnavailableThumbnails += other.StoredUnavailableThumbnails + if other.HasMessages { + if !s.HasMessages { + s.MessagesKnown = other.MessagesKnown + } else { + s.MessagesKnown = s.MessagesKnown && other.MessagesKnown + } + s.HasMessages = true + s.Messages += other.Messages + } + for _, filter := range other.Filters { + if !slices.Contains(s.Filters, filter) { + s.Filters = append(s.Filters, filter) + } + } + if other.Error != "" { + if s.Error != "" { + s.Error += "; " + } + s.Error += other.Error + } +} +func (c *MediaCounts) add(v MediaCounts) { + c.Downloaded += v.Downloaded + c.Reused += v.Reused + c.Filtered += v.Filtered + c.Failed += v.Failed + c.Unavailable += v.Unavailable + c.Canceled += v.Canceled +} +func (s Summary) Totals() MediaCounts { + var total MediaCounts + for _, c := range s.Media { + total.add(c) + } + return total +} diff --git a/internal/archive/summary_output.go b/internal/archive/summary_output.go new file mode 100644 index 0000000..0b0aa05 --- /dev/null +++ b/internal/archive/summary_output.go @@ -0,0 +1,148 @@ +package archive + +import ( + "bytes" + "fmt" + "slices" + "sort" + "strings" + "text/tabwriter" + "time" + "unicode" +) + +func SummaryFilters(opts Options) []string { + media := strings.Join(opts.Media, ",") + all := true + for _, kind := range MediaKinds { + all = all && slices.Contains(opts.Media, kind) + } + if all { + media = "all" + } + if media == "" { + media = "none" + } + filters := []string{"media=" + media} + if len(opts.Extensions) > 0 { + filters = append(filters, "extensions="+strings.Join(opts.Extensions, ",")) + } + if len(opts.MIMETypes) > 0 { + filters = append(filters, "mime="+strings.Join(opts.MIMETypes, ",")) + } + if opts.MinFileSize > 0 { + filters = append(filters, fmt.Sprintf("min-size=%d B", opts.MinFileSize)) + } + if opts.MaxFileSize > 0 { + filters = append(filters, fmt.Sprintf("max-size=%d B", opts.MaxFileSize)) + } + if !opts.Since.IsZero() { + filters = append(filters, "since="+opts.Since.Format(time.RFC3339)) + } + if !opts.Until.IsZero() { + filters = append(filters, "until="+opts.Until.Format(time.RFC3339)) + } + if opts.OnlyMedia { + filters = append(filters, "matching-media messages only") + } + return filters +} + +func CompletionLabel(status string) string { + label := map[string]string{"complete": "completed", "complete_with_warnings": "completed with warnings", "failed": "failed", "canceled": "canceled", "skipped": "skipped", "unknown": "result unavailable"}[status] + if label == "" { + return status + } + return label +} + +func SummaryStatus(err error, s Summary, warnings []string) string { + if err != nil { + return "failed" + } + if len(warnings) > 0 || s.StoredUnavailableThumbnails > 0 || s.Totals().Unavailable > 0 || s.Totals().Failed > 0 || s.Totals().Canceled > 0 || s.Error != "" { + return "complete_with_warnings" + } + return "complete" +} + +func SummaryText(title, status string, s Summary, finished time.Time, elapsed time.Duration) string { + var out bytes.Buffer + clean := func(value string) string { + return strings.Map(func(r rune) rune { + if unicode.IsControl(r) { + return -1 + } + return r + }, value) + } + label := CompletionLabel(status) + fmt.Fprintf(&out, "\nResults: %s\n", clean(strings.TrimPrefix(title, "Finished "))) + finish := func() string { + fmt.Fprintf(&out, "%s | %s", clean(title), clean(label)) + if status != "skipped" && s.MediaKnown { + total := s.Totals() + fmt.Fprintf(&out, " | %d downloaded, %d reused, %d filtered, %d failed, %d unavailable", total.Downloaded, total.Reused, total.Filtered, total.Failed, total.Unavailable) + if total.Canceled > 0 { + fmt.Fprintf(&out, ", %d canceled", total.Canceled) + } + if s.StoredUnavailableThumbnails > 0 { + fmt.Fprintf(&out, " | %d thumbnail(s) unavailable in archive", s.StoredUnavailableThumbnails) + } + } + fmt.Fprintf(&out, " | %s | Elapsed %s\n", finished.Local().Format(time.RFC3339), max(time.Duration(0), elapsed).Round(time.Second)) + return out.String() + } + if status == "skipped" { + out.WriteString("No backup work was performed.\n") + return finish() + } + if len(s.Filters) > 0 { + fmt.Fprintln(&out, "Filters:", clean(strings.Join(s.Filters, "; "))) + } + if s.StoredUnavailableThumbnails > 0 { + fmt.Fprintf(&out, "Archive warning: %d unavailable thumbnail(s) retained; use --refresh to retry.\n", s.StoredUnavailableThumbnails) + } + if s.HasMessages { + if s.MessagesKnown { + fmt.Fprintf(&out, "Messages archived: %d total | %d added this run\n", s.Messages, s.MessagesAdded) + } else { + fmt.Fprintln(&out, "Messages archived: unavailable (archive did not finish)") + } + } + if !s.MediaKnown { + if s.Error != "" { + fmt.Fprintln(&out, "Media summary unavailable:", clean(s.Error)) + } else { + fmt.Fprintln(&out, "Media summary unavailable.") + } + return finish() + } + if len(s.Media) == 0 { + fmt.Fprintln(&out, "Media this run: no files processed (0 downloaded)") + return finish() + } + fmt.Fprintln(&out, "Media this run (unique files):") + table := tabwriter.NewWriter(&out, 0, 4, 2, ' ', 0) + fmt.Fprintln(table, "Type\tDownloaded\tReused\tFiltered\tFailed\tUnavailable\tCanceled") + labels := map[string]string{"photos": "Photos", "videos": "Videos", "audios": "Audio files", "documents": "Documents", "voice_messages": "Voice messages", "video_messages": "Round videos", "stickers": "Stickers", "animations": "Animations", "contacts": "Contacts", "thumbnails": "Thumbnails", "custom_emoji": "Custom emoji", "files": "Files", "account_data": "Account data"} + keys := make([]string, 0, len(s.Media)) + for kind := range s.Media { + keys = append(keys, kind) + } + sort.Strings(keys) + row := func(label string, c MediaCounts) { + fmt.Fprintf(table, "%s\t%d\t%d\t%d\t%d\t%d\t%d\n", label, c.Downloaded, c.Reused, c.Filtered, c.Failed, c.Unavailable, c.Canceled) + } + for _, kind := range keys { + label := labels[kind] + if label == "" { + label = kind + } + row(clean(label), s.Media[kind]) + } + row("Total", s.Totals()) + table.Flush() + fmt.Fprintf(&out, "Downloaded this run: %s\n", fileSize(s.DownloadedBytes)) + return finish() +} diff --git a/internal/archive/summary_recorder.go b/internal/archive/summary_recorder.go new file mode 100644 index 0000000..ac15ff6 --- /dev/null +++ b/internal/archive/summary_recorder.go @@ -0,0 +1,243 @@ +package archive + +import ( + "context" + "encoding/json" + "errors" + "net" + "os" + "path/filepath" + "strings" + "sync" + + bolt "go.etcd.io/bbolt" +) + +// SummaryRecorder retains file outcomes on temporary disk rather than keeping +// one in-memory record per attachment in large archives. +type SummaryRecorder struct { + db *bolt.DB + path string + mu sync.Mutex + err error +} +type fileOutcome struct { + Kind, State string + Bytes int64 +} + +var summaryKey = []byte{0} + +func NewSummaryRecorder(root string) (*SummaryRecorder, error) { + if err := os.MkdirAll(root, 0700); err != nil { + return nil, err + } + f, err := os.CreateTemp(root, ".run-summary-*") + if err != nil { + return nil, err + } + name := f.Name() + f.Close() + db, err := bolt.Open(name, 0600, &bolt.Options{NoSync: true}) + if err != nil { + os.Remove(name) + return nil, err + } + return &SummaryRecorder{db: db, path: name}, nil +} +func (r *SummaryRecorder) Close() error { return errors.Join(r.db.Close(), os.Remove(r.path)) } +func (r *SummaryRecorder) failed(err error) { + if err != nil { + r.mu.Lock() + if r.err == nil { + r.err = err + } + r.mu.Unlock() + } +} +func readSummary(bucket *bolt.Bucket) (Summary, error) { + s := Summary{MediaKnown: true, Media: map[string]MediaCounts{}} + if bucket != nil { + if b := bucket.Get(summaryKey); b != nil { + if err := json.Unmarshal(b, &s); err != nil { + return s, err + } + } + } + return s, nil +} +func (r *SummaryRecorder) update(scope string, change func(*bolt.Bucket, *Summary) error) { + if scope == "" { + scope = "archive" + } + r.failed(r.db.Update(func(tx *bolt.Tx) error { + b, err := tx.CreateBucketIfNotExists([]byte(scope)) + if err != nil { + return err + } + s, err := readSummary(b) + if err != nil { + return err + } + if err = change(b, &s); err != nil { + return err + } + data, err := json.Marshal(s) + if err != nil { + return err + } + return b.Put(summaryKey, data) + })) +} +func (r *SummaryRecorder) Observe(scope string, event TransferEvent) { + state := "" + switch event.Kind { + case TransferReused: + state = "reused" + case TransferFiltered: + state = "filtered" + case TransferFinished: + var timeout net.Error + switch { + case event.Err == nil: + state = "downloaded" + case unavailableThumbnail(event.File, event.Err): + state = "unavailable" + case errors.As(event.Err, &timeout) && timeout.Timeout(): + state = "failed" + case errors.Is(event.Err, context.Canceled): + state = "canceled" + default: + state = "failed" + } + default: + return + } + kind := event.File.Kind + if event.File.Field == "thumbnail" { + kind = "thumbnails" + } else if event.File.Field == "custom_emoji" { + kind = "custom_emoji" + } + if kind == "" { + kind = "files" + } + next := fileOutcome{Kind: kind, State: state, Bytes: event.Bytes} + r.update(scope, func(b *bolt.Bucket, s *Summary) error { + key := append([]byte{1}, []byte(event.File.Path)...) + if raw := b.Get(key); raw != nil { + var old fileOutcome + if err := json.Unmarshal(raw, &old); err != nil { + return err + } + if state == "filtered" || (state == "reused" && old.State == "downloaded") { + return nil + } + s.adjust(old, -1) + } + s.adjust(next, 1) + raw, err := json.Marshal(next) + if err != nil { + return err + } + return b.Put(key, raw) + }) +} +func (r *SummaryRecorder) AddMessages(scope string, count int64) { + if count > 0 { + r.update(scope, func(_ *bolt.Bucket, s *Summary) error { s.MessagesAdded += count; return nil }) + } +} + +func (r *SummaryRecorder) SetMessages(scope string, count int64, known bool) { + r.update(scope, func(_ *bolt.Bucket, s *Summary) error { + s.HasMessages = true + s.Messages = count + s.MessagesKnown = known + return nil + }) +} + +func (r *SummaryRecorder) SetStoredUnavailable(scope string, count int64) { + r.update(scope, func(_ *bolt.Bucket, s *Summary) error { s.StoredUnavailableThumbnails = count; return nil }) +} + +func summaryOptions(opts Options, scope string) Options { + if opts.SummaryRecorder == nil { + return opts + } + previous := opts.OnTransfer + opts.OnTransfer = func(event TransferEvent) { + opts.SummaryRecorder.Observe(scope, event) + if previous != nil { + previous(event) + } + } + return opts +} +func (r *SummaryRecorder) Snapshot(scope string) Summary { + var s Summary + if scope == "" { + scope = "archive" + } + err := r.db.View(func(tx *bolt.Tx) error { var err error; s, err = readSummary(tx.Bucket([]byte(scope))); return err }) + r.failed(err) + r.mu.Lock() + defer r.mu.Unlock() + if r.err != nil { + s.MediaKnown = false + s.Error = r.err.Error() + } + return s +} + +// Total combines the account root and its independently exported subsections. +func (r *SummaryRecorder) Total(prefix string) Summary { + prefix = filepath.Clean(prefix) + var total Summary + err := r.db.View(func(tx *bolt.Tx) error { + return tx.ForEach(func(name []byte, b *bolt.Bucket) error { + scope := string(name) + if scope != prefix && !strings.HasPrefix(scope, prefix+string(os.PathSeparator)) { + return nil + } + s, err := readSummary(b) + if err != nil { + return err + } + total.Add(s) + return nil + }) + }) + r.failed(err) + r.mu.Lock() + defer r.mu.Unlock() + if total.Media == nil { + total.MediaKnown = true + total.Media = map[string]MediaCounts{} + } + if r.err != nil { + total.MediaKnown = false + total.Error = r.err.Error() + } + return total +} +func (s *Summary) adjust(out fileOutcome, n int64) { + counts := s.Media[out.Kind] + switch out.State { + case "downloaded": + counts.Downloaded += n + s.DownloadedBytes += n * out.Bytes + case "reused": + counts.Reused += n + case "filtered": + counts.Filtered += n + case "failed": + counts.Failed += n + case "unavailable": + counts.Unavailable += n + case "canceled": + counts.Canceled += n + } + s.Media[out.Kind] = counts +} diff --git a/internal/archive/summary_test.go b/internal/archive/summary_test.go new file mode 100644 index 0000000..a18504e --- /dev/null +++ b/internal/archive/summary_test.go @@ -0,0 +1,120 @@ +package archive + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +func TestSummaryRecorderDeduplicatesAndResolvesRetries(t *testing.T) { + r, err := NewSummaryRecorder(t.TempDir()) + if err != nil { + t.Fatal(err) + } + defer r.Close() + photo := File{Kind: "photos", Field: "photo", Path: "photos/1.jpg", Size: 4} + r.Observe("chat", TransferEvent{Kind: TransferFinished, File: photo, Bytes: 4}) + r.Observe("chat", TransferEvent{Kind: TransferReused, File: photo}) + document := File{Kind: "documents", Field: "file", Path: "files/2.pdf", Size: 8} + r.Observe("chat", TransferEvent{Kind: TransferFinished, File: document, Err: errors.New("connection dropped")}) + r.Observe("chat", TransferEvent{Kind: TransferFinished, File: document, Bytes: 8}) + thumb := File{Kind: "videos", Field: "thumbnail", Path: "video_files/2_thumb.jpg"} + for range 2 { + r.Observe("chat", TransferEvent{Kind: TransferFinished, File: thumb, Err: ErrThumbnailUnavailable}) + } + filtered := File{Kind: "audios", Path: "audio_files/excluded.mp3"} + for range 2 { + r.Observe("chat", TransferEvent{Kind: TransferFiltered, File: filtered}) + } + r.Observe("chat", TransferEvent{Kind: TransferReused, File: File{Kind: "videos", Path: "video_files/old.mp4"}}) + r.Observe("chat", TransferEvent{Kind: TransferFinished, File: File{Kind: "photos", Path: "photos/canceled.jpg"}, Err: context.Canceled}) + r.AddMessages("chat", 2) + s := r.Snapshot("chat") + totals := s.Totals() + if !s.MediaKnown || totals.Downloaded != 2 || totals.Reused != 1 || totals.Filtered != 1 || totals.Unavailable != 1 || totals.Canceled != 1 || totals.Failed != 0 || s.DownloadedBytes != 12 || s.MessagesAdded != 2 { + t.Fatalf("incorrect final outcomes after replay/retry: %+v totals=%+v", s, totals) + } + if s.Media["thumbnails"].Unavailable != 1 || s.Media["videos"].Reused != 1 { + t.Fatalf("thumbnail mixed into video totals: %+v", s.Media) + } + r.Observe("other", TransferEvent{Kind: TransferFinished, File: photo, Bytes: 4}) + if got := r.Snapshot("other").Totals().Downloaded; got != 1 { + t.Fatalf("chat scopes collided: %d", got) + } +} +func TestSummaryRecorderHandlesConcurrentFiles(t *testing.T) { + r, err := NewSummaryRecorder(t.TempDir()) + if err != nil { + t.Fatal(err) + } + defer r.Close() + var workers sync.WaitGroup + for i := range 40 { + workers.Go(func() { + file := File{Kind: "photos", Path: fmt.Sprintf("photos/%d.jpg", i)} + r.Observe("chat", TransferEvent{Kind: TransferFinished, File: file, Bytes: 4}) + }) + } + workers.Wait() + s := r.Snapshot("chat") + if !s.MediaKnown || s.Totals().Downloaded != 40 || s.DownloadedBytes != 160 { + t.Fatalf("lost concurrent outcomes: %+v", s) + } +} +func TestSummaryTextMakesCompletionAndUnavailableCountsVisible(t *testing.T) { + s := Summary{HasMessages: true, MessagesKnown: true, Messages: 120, MediaKnown: true, Media: map[string]MediaCounts{"audios": {Downloaded: 12, Reused: 8, Filtered: 2}, "thumbnails": {Unavailable: 1}}, Filters: []string{"media=all"}} + text := SummaryText("Finished archive \"Example Channel\"", "complete_with_warnings", s, time.Now(), time.Minute) + for _, want := range []string{"Finished archive", "completed with warnings", "120", "Downloaded", "Reused", "Filtered", "Failed", "Unavailable", "Audio", "Thumbnail", "media=all"} { + if !strings.Contains(text, want) { + t.Fatalf("missing %q in summary:\n%s", want, text) + } + } + text = SummaryText("Finished archive test\n\x1b[31m", "failed", Summary{Error: "summary storage unavailable"}, time.Now(), time.Second) + if strings.Contains(text, "\x1b") || strings.Contains(text, "Downloaded") || !strings.Contains(text, "unavailable") || strings.Contains(text, "completed") { + t.Fatalf("unknown summary reported success or invented counters: %q", text) + } +} + +func TestArchiveSummaryCountsFilteredReusedAndDownloadedFiles(t *testing.T) { + root := t.TempDir() + source := &fakeSource{items: fakeItems(3, 2, 1), pageSize: 2} + source.items[1].Files[0].Kind = "documents" + folder := filepath.Join(root, "ChatExport_user_1", "photos") + if err := os.MkdirAll(folder, 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(folder, "3.jpg"), []byte("file"), 0600); err != nil { + t.Fatal(err) + } + var finished []ChatExport + report, err := RunBatch(context.Background(), source, root, []Chat{{ID: 1, Key: "user_1"}}, Options{Concurrency: 1, Media: []string{"photos"}, Resume: true, OnChatFinished: func(c ChatExport) { finished = append(finished, c) }}, nil) + if err != nil { + t.Fatal(err) + } + total := report.Summary.Totals() + if len(finished) != 1 || finished[0].Finished.IsZero() || !report.Summary.MessagesKnown || report.Summary.Messages != 3 || report.Summary.MessagesAdded != 3 || total.Downloaded != 1 || total.Reused != 1 || total.Filtered != 1 || report.Summary.DownloadedBytes != 4 { + t.Fatalf("incorrect archive summary: %+v totals=%+v callbacks=%+v", report.Summary, total, finished) + } +} + +func TestArchiveSummaryIncludesFailuresBeforeNetworkStarts(t *testing.T) { + root := t.TempDir() + source := &fakeSource{items: fakeItems(1), pageSize: 2} + if err := os.MkdirAll(filepath.Join(root, "ChatExport_user_1"), 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, "ChatExport_user_1", "photos"), []byte("not a directory"), 0600); err != nil { + t.Fatal(err) + } + var ended ChatExport + report, err := RunBatch(context.Background(), source, root, []Chat{{ID: 1, Key: "user_1"}}, Options{Concurrency: 1, Media: []string{"photos"}, OnChatFinished: func(c ChatExport) { ended = c }}, nil) + if err == nil || ended.Error == "" || report.Summary.Totals().Failed != 1 || report.Summary.MessagesKnown { + t.Fatalf("failure summary invented completion: summary=%+v ended=%+v err=%v", report.Summary, ended, err) + } +} diff --git a/internal/archive/thumbnail_inventory.go b/internal/archive/thumbnail_inventory.go new file mode 100644 index 0000000..2a081ea --- /dev/null +++ b/internal/archive/thumbnail_inventory.go @@ -0,0 +1,60 @@ +package archive + +import ( + "encoding/binary" + "encoding/json" + + bolt "go.etcd.io/bbolt" +) + +var thumbnailInventoryKey = []byte("unavailable_thumbnails") + +func thumbnailMissing(row []byte) (bool, error) { + if len(row) == 0 { + return false, nil + } + var value struct { + Reason string `json:"thumbnail_skip_reason"` + } + err := json.Unmarshal(row, &value) + return value.Reason == "unavailable", err +} + +// Bootstrap once for older archives, then maintain the count with each changed +// message. Unchanged incremental runs never rescan the archive for warnings. +func prepareThumbnailInventory(tx *bolt.Tx) error { + meta := tx.Bucket(metaBucket) + if len(meta.Get(thumbnailInventoryKey)) == 8 { + return nil + } + var count uint64 + if err := tx.Bucket(metadataRowsBucket).ForEach(func(_, row []byte) error { + missing, err := thumbnailMissing(row) + if missing { + count++ + } + return err + }); err != nil { + return err + } + return meta.Put(thumbnailInventoryKey, binary.BigEndian.AppendUint64(nil, count)) +} + +func updateThumbnailInventory(tx *bolt.Tx, key []byte, message Message) error { + old, err := thumbnailMissing(tx.Bucket(metadataRowsBucket).Get(key)) + if err != nil { + return err + } + missing := message.ThumbnailSkipReason == "unavailable" + if old == missing { + return nil + } + meta := tx.Bucket(metaBucket) + count := binary.BigEndian.Uint64(meta.Get(thumbnailInventoryKey)) + if missing { + count++ + } else if count > 0 { + count-- + } + return meta.Put(thumbnailInventoryKey, binary.BigEndian.AppendUint64(nil, count)) +} diff --git a/internal/archive/thumbnail_test.go b/internal/archive/thumbnail_test.go new file mode 100644 index 0000000..77cddc2 --- /dev/null +++ b/internal/archive/thumbnail_test.go @@ -0,0 +1,154 @@ +package archive + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "testing" +) + +type thumbnailFailureSource struct { + fakeSource + failure error + field string + cancel context.CancelFunc + failures int +} + +func (s *thumbnailFailureSource) Download(ctx context.Context, file File, path string) error { + if file.Field == s.field && s.failure != nil { + s.failures++ + if s.cancel != nil { + s.cancel() + } + return s.failure + } + return s.fakeSource.Download(ctx, file, path) +} +func thumbnailSource() *thumbnailFailureSource { + s := &thumbnailFailureSource{fakeSource: fakeSource{items: fakeItems(2, 1), pageSize: 2}, field: "thumbnail"} + s.items[0].Files = append(s.items[0].Files, File{Kind: "photos", Field: "thumbnail", Path: "photos/2_thumb.jpg", Size: 4}) + return s +} +func TestUnavailableThumbnailKeepsMediaAndCanBeRefreshed(t *testing.T) { + source := thumbnailSource() + source.failure = ErrThumbnailUnavailable + root := t.TempDir() + chats := []Chat{{ID: 1, Key: "user_1"}} + opts := Options{Concurrency: 1, Resume: true, Media: []string{"photos"}, Format: "both"} + report, err := RunBatch(context.Background(), source, root, chats, opts, nil) + if err != nil { + t.Fatalf("optional thumbnail stopped backup: %v", err) + } + if len(report.Warnings) != 1 || !strings.Contains(report.Warnings[0], "thumbnail") { + t.Fatalf("missing unavailable thumbnail warning: %+v", report) + } + check := func(wantUnavailable bool) { + t.Helper() + b, err := os.ReadFile(filepath.Join(root, "ChatExport_user_1/result.json")) + if err != nil { + t.Fatal(err) + } + var out struct{ Messages []Message } + if err = json.Unmarshal(b, &out); err != nil { + t.Fatal(err) + } + if len(out.Messages) != 2 { + t.Fatalf("lost messages: %+v", out) + } + for _, m := range out.Messages { + if _, err := os.Stat(filepath.Join(root, "ChatExport_user_1", m.Photo)); err != nil { + t.Fatalf("primary media missing: %v", err) + } + if m.ID == 2 { + if wantUnavailable && m.Thumbnail != "(File unavailable, please try again later)" { + t.Fatalf("missing thumbnail was hidden: thumbnail=%q reason=%q", m.Thumbnail, m.ThumbnailSkipReason) + } + if !wantUnavailable && (m.Thumbnail != "photos/2_thumb.jpg" || m.ThumbnailSkipReason != "") { + t.Fatalf("refresh did not restore thumbnail: %+v", m) + } + } + } + metadata, err := os.ReadFile(filepath.Join(root, "ChatExport_user_1/archive-metadata.json")) + if err != nil { + t.Fatal(err) + } + var details struct{ Messages []Message } + if err = json.Unmarshal(metadata, &details); err != nil { + t.Fatal(err) + } + found := false + for _, m := range details.Messages { + if m.ID == 2 && m.ThumbnailSkipReason == "unavailable" { + found = true + } + } + if found != wantUnavailable { + t.Fatalf("unavailable thumbnail metadata: %s", metadata) + } + } + check(true) + source.failure = nil + report, err = RunBatch(context.Background(), source, root, chats, opts, nil) + if err != nil || report.Summary.StoredUnavailableThumbnails != 1 || len(report.Warnings) == 0 || report.Summary.Totals().Unavailable != 0 { + t.Fatalf("incremental run hid an existing unavailable thumbnail: %+v err=%v", report, err) + } + opts.Refresh = true + if report, err = RunBatch(context.Background(), source, root, chats, opts, nil); err != nil { + t.Fatal(err) + } + if report.Summary.StoredUnavailableThumbnails != 0 { + t.Fatalf("refreshed thumbnail still reported unavailable: %+v", report.Summary) + } + check(false) +} +func TestThumbnailFailureHandlingPreservesFatalErrors(t *testing.T) { + for _, tc := range []struct { + name, field string + failure error + cancel bool + }{ + {"primary attachment", "photo", ErrThumbnailUnavailable, false}, + {"local filesystem", "thumbnail", &os.PathError{Op: "write", Path: "thumb.jpg", Err: os.ErrPermission}, false}, + {"local close after server failure", "thumbnail", errors.Join(ErrThumbnailUnavailable, &os.PathError{Op: "close", Path: "thumb.jpg", Err: os.ErrPermission}), false}, + {"canceled thumbnail transfer", "thumbnail", errors.Join(ErrThumbnailUnavailable, context.Canceled), false}, + {"parent cancellation", "thumbnail", ErrThumbnailUnavailable, true}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + source := thumbnailSource() + source.failure = tc.failure + source.field = tc.field + if tc.cancel { + source.cancel = cancel + } + _, err := RunBatch(ctx, source, t.TempDir(), []Chat{{ID: 1}}, Options{Concurrency: 1, Media: []string{"photos"}}, nil) + if err == nil || (!errors.Is(err, tc.failure) && !errors.Is(err, context.Canceled)) { + t.Fatalf("fatal error was hidden: %v", err) + } + }) + } +} + +func TestUnavailableThumbnailIsCountedOnceDuringRefresh(t *testing.T) { + source := thumbnailSource() + root := t.TempDir() + chats := []Chat{{ID: 1}} + opts := Options{Concurrency: 1, Resume: true, Media: []string{"photos"}} + if _, err := RunBatch(context.Background(), source, root, chats, opts, nil); err != nil { + t.Fatal(err) + } + newest := fakeItems(3)[0] + newest.Files = append(newest.Files, File{Kind: "photos", Field: "thumbnail", Path: "photos/3_thumb.jpg", Size: 4}) + source.items = append([]Item{newest}, source.items...) + source.failure = ErrThumbnailUnavailable + opts.Refresh = true + report, err := RunBatch(context.Background(), source, root, chats, opts, nil) + if err != nil || source.failures != 1 || len(report.Warnings) != 1 || !strings.Contains(report.Warnings[0], "1 thumbnail") { + t.Fatalf("refresh retried or double-counted a known unavailable thumbnail: failures=%d warnings=%v err=%v", source.failures, report.Warnings, err) + } +} diff --git a/internal/cron/cron.go b/internal/cron/cron.go index 967848c..d44a049 100644 --- a/internal/cron/cron.go +++ b/internal/cron/cron.go @@ -16,6 +16,7 @@ import ( ) type Job struct { + ResultFile string `json:"-"` // Private per-invocation child result; never saved. Name string `json:"name"` Schedule string `json:"schedule"` Executable string `json:"executable"` diff --git a/internal/cron/run.go b/internal/cron/run.go index 3cc8e7b..8047cd5 100644 --- a/internal/cron/run.go +++ b/internal/cron/run.go @@ -2,11 +2,15 @@ package cron import ( "context" + "encoding/json" "errors" "fmt" + "github.com/mo1ein/TelegramArchive/internal/archive" "io" "os" "os/exec" + "path/filepath" + "slices" "syscall" "time" @@ -16,7 +20,11 @@ import ( type Runner func(context.Context, Job, io.Writer) error func Execute(ctx context.Context, job Job, output io.Writer) error { - child := exec.CommandContext(ctx, job.Executable, job.Arguments...) + args := slices.Clone(job.Arguments) + if job.ResultFile != "" { + args = append(args, "--result-file="+job.ResultFile) + } + child := exec.CommandContext(ctx, job.Executable, args...) child.Dir = job.Directory child.Env = os.Environ() for key, value := range job.Environment { @@ -57,22 +65,55 @@ func Run(ctx context.Context, file string, output io.Writer, execute Runner) err out := io.MultiWriter(log, output) lock, err := bolt.Open(file+".run.lock", 0600, &bolt.Options{Timeout: 50 * time.Millisecond}) if errors.Is(err, bolt.ErrTimeout) { - fmt.Fprintf(out, "[%s] %s is already running; skipping this tick.\n", time.Now().Format(time.RFC3339), job.Name) + fmt.Fprintf(out, "[%s] Skipped job %q | already running; no new backup started.\n", time.Now().Format(time.RFC3339), job.Name) return nil } if err != nil { return err } defer lock.Close() + result, err := os.CreateTemp(filepath.Dir(file), ".job-result-*") + if err != nil { + return err + } + job.ResultFile = result.Name() + result.Close() + defer os.Remove(job.ResultFile) + job.ResultFile, err = filepath.Abs(job.ResultFile) + if err != nil { + return err + } + started := time.Now().UTC() fmt.Fprintf(out, "[%s] Starting cron backup %s\n", time.Now().Format(time.RFC3339), job.Name) err = execute(ctx, job, out) if ctx.Err() != nil { err = ctx.Err() } + var report archive.CompletionReport + raw, readErr := os.ReadFile(job.ResultFile) + if readErr == nil { + readErr = json.Unmarshal(raw, &report) + } + validStatus := slices.Contains([]string{"complete", "complete_with_warnings", "failed", "canceled", "skipped"}, report.Status) + if readErr != nil || report.Kind != "backup" || !validStatus { + report = archive.CompletionReport{Status: "unknown", Summary: archive.Summary{Error: "child did not provide a valid completion report"}} + } + if err == nil && (report.Status == "failed" || report.Status == "canceled") { + err = fmt.Errorf("backup reported %s: %s", report.Status, report.Error) + } + if err != nil { + report.Status = "failed" + } + if errors.Is(ctx.Err(), context.Canceled) { + report.Status = "canceled" + } + finished := time.Now().UTC() + fmt.Fprint(out, archive.SummaryText(fmt.Sprintf("Finished job %q", job.Name), report.Status, report.Summary, finished, finished.Sub(started))) + if report.Status == "skipped" && report.Error != "" { + fmt.Fprintln(out, report.Error) + } if err != nil { - fmt.Fprintf(out, "[%s] Backup failed: %v\n", time.Now().Format(time.RFC3339), err) return fmt.Errorf("cron backup %s failed: %w; see %s", job.Name, err, job.Log) } - fmt.Fprintf(out, "[%s] Backup complete; future runs reuse these checkpoints.\n", time.Now().Format(time.RFC3339)) return nil } diff --git a/internal/cron/run_summary_test.go b/internal/cron/run_summary_test.go new file mode 100644 index 0000000..677ae56 --- /dev/null +++ b/internal/cron/run_summary_test.go @@ -0,0 +1,220 @@ +package cron + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "regexp" + "strings" + "testing" + "time" + + "github.com/mo1ein/TelegramArchive/internal/archive" +) + +func requireSummaryCount(t *testing.T, text, label string, count int64) { + t.Helper() + // Permit either "2 downloaded" or "Downloaded: 2" without fixing layout, + // spacing, row order or surrounding explanatory text. + pattern := fmt.Sprintf(`(?i)(?:\b%d\s+%s\b|\b%s\b[^\d\n]{0,24}\b%d\b)`, count, regexp.QuoteMeta(label), regexp.QuoteMeta(label), count) + if regexp.MustCompile(pattern).MatchString(text) { + return + } + // Match numeric cells under their header, allowing multiword media labels + // and any amount of padding from the table writer. + column, columns := -1, 0 + number := regexp.MustCompile(`^\d+$`) + for _, line := range strings.Split(text, "\n") { + fields := strings.Fields(line) + if len(fields) > 1 && strings.EqualFold(fields[0], "Type") { + columns = len(fields) - 1 + for i, header := range fields[1:] { + if strings.EqualFold(header, label) { + column = i + } + } + continue + } + if column < 0 || len(fields) <= columns { + continue + } + cells := fields[len(fields)-columns:] + valid := true + for _, cell := range cells { + valid = valid && number.MatchString(cell) + } + if valid && cells[column] == fmt.Sprint(count) { + return + } + } + t.Errorf("missing %s count %d in:\n%s", label, count, text) +} + +func TestRunSummaryReflectsChildOutcome(t *testing.T) { + runnerFailure := errors.New("media connection failed") + for _, test := range []struct { + name, status, phrase string + summary archive.Summary + runnerError error + }{ + { + name: "complete", status: "complete", phrase: "completed", + summary: archive.Summary{HasMessages: true, MessagesKnown: true, Messages: 120, MessagesAdded: 4, MediaKnown: true, DownloadedBytes: 2048, + Media: map[string]archive.MediaCounts{"videos": {Downloaded: 2, Reused: 5, Filtered: 1}}}, + }, + { + name: "warnings", status: "complete_with_warnings", phrase: "completed with warnings", + summary: archive.Summary{HasMessages: true, MessagesKnown: true, Messages: 120, MediaKnown: true, DownloadedBytes: 2048, + Media: map[string]archive.MediaCounts{"videos": {Downloaded: 2, Reused: 5}, "thumbnails": {Unavailable: 1}}}, + }, + { + name: "skipped", status: "skipped", phrase: "skipped", + summary: archive.Summary{HasMessages: true}, + }, + { + name: "failed", status: "failed", phrase: "failed", runnerError: runnerFailure, + summary: archive.Summary{HasMessages: true, MessagesKnown: true, Messages: 90, MessagesAdded: 2, MediaKnown: true, DownloadedBytes: 1024, + Media: map[string]archive.MediaCounts{"videos": {Downloaded: 1, Reused: 4, Failed: 2, Canceled: 3}}}, + }, + } { + t.Run(test.name, func(t *testing.T) { + dir := t.TempDir() + manager := Manager{Directory: filepath.Join(dir, "jobs"), Table: &memoryTable{}} + job := sampleJob(dir) + if err := manager.Install(context.Background(), job); err != nil { + t.Fatal(err) + } + original, err := os.ReadFile(manager.File(job.Name)) + if err != nil { + t.Fatal(err) + } + var output bytes.Buffer + var resultFile string + err = Run(context.Background(), manager.File(job.Name), &output, func(ctx context.Context, run Job, log io.Writer) error { + resultFile = run.ResultFile + if resultFile == "" { + t.Error("runner was not given a private completion result file") + return test.runnerError + } + info, err := os.Stat(resultFile) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0600 || info.Size() != 0 { + t.Errorf("completion file must be private and fresh: mode=%o size=%d", info.Mode().Perm(), info.Size()) + } + report := archive.CompletionReport{Kind: "backup", Status: test.status, Started: time.Now(), Summary: test.summary} + report.Finished = time.Now() + if test.status == "complete_with_warnings" { + report.Warnings = []string{"one thumbnail is unavailable"} + } + if test.runnerError != nil { + report.Error = test.runnerError.Error() + } + data, err := json.Marshal(report) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(resultFile, data, 0600); err != nil { + t.Fatal(err) + } + return test.runnerError + }) + if test.runnerError == nil && err != nil { + t.Fatal(err) + } + if test.runnerError != nil && !errors.Is(err, test.runnerError) { + t.Errorf("cron discarded the actual runner failure: %v", err) + } + text := output.String() + if !strings.Contains(text, fmt.Sprintf("Finished job %q", job.Name)) || !strings.Contains(strings.ToLower(text), test.phrase) { + t.Errorf("missing finished job identity or true status %q:\n%s", test.phrase, text) + } + if test.status == "skipped" { + if strings.Contains(strings.ToLower(text), "backup complete") || strings.Contains(strings.ToLower(text), " completed") { + t.Errorf("skipped cron job falsely claimed completion:\n%s", text) + } + } else { + if !strings.Contains(strings.ToLower(text), "videos") || !strings.Contains(strings.ToLower(text), "messages") || !strings.Contains(text, fmt.Sprint(test.summary.Messages)) { + t.Errorf("completion summary omitted the media type or archived message inventory:\n%s", text) + } + for _, counts := range test.summary.Media { + for label, count := range map[string]int64{ + "downloaded": counts.Downloaded, "reused": counts.Reused, "filtered": counts.Filtered, + "failed": counts.Failed, "unavailable": counts.Unavailable, "canceled": counts.Canceled, + } { + if count > 0 { + requireSummaryCount(t, text, label, count) + } + } + } + } + if resultFile != "" { + if _, err := os.Stat(resultFile); !os.IsNotExist(err) { + t.Errorf("private completion report was not removed: %s, %v", resultFile, err) + } + } + saved, err := os.ReadFile(manager.File(job.Name)) + if err != nil || !bytes.Equal(saved, original) { + t.Errorf("transient completion path changed saved job configuration: %v", err) + } + log, err := os.ReadFile(job.Log) + if err != nil || !bytes.Equal(log, output.Bytes()) { + t.Errorf("private job log and user-visible completion summary differ: %v", err) + } + }) + } +} + +func TestRunSummaryUsesFreshReportsAndCannotReusePreviousCompletion(t *testing.T) { + dir := t.TempDir() + manager := Manager{Directory: filepath.Join(dir, "jobs"), Table: &memoryTable{}} + job := sampleJob(dir) + if err := manager.Install(context.Background(), job); err != nil { + t.Fatal(err) + } + var previousPath string + for _, status := range []string{"complete", "skipped"} { + var output bytes.Buffer + err := Run(context.Background(), manager.File(job.Name), &output, func(ctx context.Context, run Job, log io.Writer) error { + if run.ResultFile == "" { + t.Error("runner did not receive a completion report path") + return nil + } + if previousPath == run.ResultFile { + t.Error("cron reused a completion report path across invocations") + } + previousPath = run.ResultFile + info, err := os.Stat(run.ResultFile) + if err != nil || info.Size() != 0 { + t.Errorf("new invocation inherited an old result: %v", err) + } + report := archive.CompletionReport{Kind: "backup", Status: status, Started: time.Now(), Finished: time.Now()} + if status == "complete" { + report.Summary = archive.Summary{HasMessages: true, MessagesKnown: true, Messages: 987654321, MediaKnown: true, + Media: map[string]archive.MediaCounts{"videos": {Downloaded: 12345}}} + } + data, err := json.Marshal(report) + if err != nil { + t.Fatal(err) + } + return os.WriteFile(run.ResultFile, data, 0600) + }) + if err != nil { + t.Fatal(err) + } + if status == "skipped" && (strings.Contains(output.String(), "987654321") || strings.Contains(output.String(), "12345") || strings.Contains(strings.ToLower(output.String()), "completed")) { + t.Errorf("skipped invocation reported the previous completed backup's results:\n%s", output.String()) + } + if previousPath != "" { + if _, err := os.Stat(previousPath); !os.IsNotExist(err) { + t.Errorf("completion report survived invocation: %v", err) + } + } + } +} diff --git a/internal/cron/run_test.go b/internal/cron/run_test.go index 28e5f1f..d3912dd 100644 --- a/internal/cron/run_test.go +++ b/internal/cron/run_test.go @@ -40,7 +40,7 @@ func TestRunSkipsOverlapAndRetainsPrivateLog(t *testing.T) { t.Fatal("overlap not skipped", err, skipped.String()) } data, _ := os.ReadFile(job.Log) - if !strings.Contains(string(data), "downloaded new messages") || !strings.Contains(string(data), "Backup complete") { + if !strings.Contains(string(data), "downloaded new messages") || !strings.Contains(string(data), "Finished job") { t.Fatal("missing job log") } info, _ := os.Stat(job.Log) diff --git a/internal/telegram/account.go b/internal/telegram/account.go index e6a6fa2..db1e3aa 100644 --- a/internal/telegram/account.go +++ b/internal/telegram/account.go @@ -58,6 +58,14 @@ func (s *Source) ExportAccount(ctx context.Context, dir string, kinds []string, if err := os.MkdirAll(dir, 0700); err != nil { return report, err } + if opts.SummaryRecorder == nil { + var err error + opts.SummaryRecorder, err = archive.NewSummaryRecorder(dir) + if err != nil { + return report, err + } + defer opts.SummaryRecorder.Close() + } var failures []error seen := map[string]bool{} for _, kind := range kinds { @@ -99,7 +107,15 @@ func (s *Source) ExportAccount(ctx context.Context, dir string, kinds []string, } } case "other_data": + file := archive.File{Kind: "account_data", Field: "file", Path: "other_data.json"} err = s.otherData(ctx, filepath.Join(dir, "other_data.json")) + var size int64 + if err == nil { + if st, e := os.Stat(filepath.Join(dir, file.Path)); e == nil { + size = st.Size() + } + } + opts.SummaryRecorder.Observe(dir, archive.TransferEvent{Kind: archive.TransferFinished, File: file, Bytes: size, Err: err}) if err == nil { section.Files = []string{"other_data.json"} } @@ -112,6 +128,13 @@ func (s *Source) ExportAccount(ctx context.Context, dir string, kinds []string, report.Sections = append(report.Sections, section) } format := opts.Format + report.Summary = opts.SummaryRecorder.Total(dir) + report.Summary.Filters = archive.SummaryFilters(opts) + if count := report.Summary.Totals().Unavailable; count > 0 { + report.Warnings = append(report.Warnings, fmt.Sprintf("%d thumbnail(s) unavailable; original media retained. Use --refresh to retry later.", count)) + } else if count := report.Summary.StoredUnavailableThumbnails; count > 0 { + report.Warnings = append(report.Warnings, fmt.Sprintf("Archive retains %d unavailable thumbnail(s); use --refresh to retry later.", count)) + } if format == "" { format = "json" } diff --git a/internal/telegram/account_media.go b/internal/telegram/account_media.go index 9108d13..9d22ad0 100644 --- a/internal/telegram/account_media.go +++ b/internal/telegram/account_media.go @@ -105,7 +105,21 @@ func (s *Source) accountMedia(ctx context.Context, root, kind string, opts archi items = append(items, item) } } - items = archive.FilterItems(items, opts) + selected := archive.FilterItems(items, opts) + if opts.SummaryRecorder != nil { + ids := map[int]bool{} + for _, item := range selected { + ids[item.Message.ID] = true + } + for _, item := range items { + if !ids[item.Message.ID] { + for _, file := range item.Files { + opts.SummaryRecorder.Observe(dir, archive.TransferEvent{Kind: archive.TransferFiltered, File: file}) + } + } + } + } + items = selected if err := s.attachCustomEmojis(ctx, items); err != nil { return nil, nil, err } diff --git a/internal/telegram/account_test.go b/internal/telegram/account_test.go index c96bb23..fc0816a 100644 --- a/internal/telegram/account_test.go +++ b/internal/telegram/account_test.go @@ -7,6 +7,7 @@ import ( "os" "path/filepath" "testing" + "time" "github.com/gotd/td/bin" tgclient "github.com/gotd/td/telegram" @@ -48,6 +49,31 @@ func TestAccountMetadataExcludesAuthorizationHashes(t *testing.T) { } } +func TestAccountSummaryCountsMediaAndFilters(t *testing.T) { + api := tg.NewClient(tgclient.InvokeFunc(func(ctx context.Context, input bin.Encoder, output bin.Decoder) error { + switch input.(type) { + case *tg.PhotosGetUserPhotosRequest: + output.(*tg.PhotosPhotosBox).Photos = &tg.PhotosPhotos{Photos: []tg.PhotoClass{ + &tg.Photo{ID: 1, Date: 100, DCID: 4, Sizes: []tg.PhotoSizeClass{&tg.PhotoSize{Type: "x", Size: 4, W: 10, H: 10}}}, + &tg.Photo{ID: 2, Date: 100, DCID: 4, Sizes: []tg.PhotoSizeClass{&tg.PhotoSize{Type: "x", Size: 8, W: 10, H: 10}}}, + }} + case *tg.UploadGetFileRequest: + output.(*tg.UploadFileBox).File = &tg.UploadFile{Type: &tg.StorageFileJpeg{}, Bytes: []byte("file")} + default: + t.Fatalf("unexpected account request %T", input) + } + return nil + })) + source := &Source{api: api, accountID: 42, self: &tg.User{ID: 42}, threads: 1, pool: watchdogTestPool{client: func(context.Context, int) *tg.Client { return api }}} + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + report, err := source.ExportAccount(ctx, t.TempDir(), []string{"profile_photos"}, archive.Options{Concurrency: 1, Format: "both", Media: []string{"photos"}, MaxFileSize: 4}) + counts := report.Summary.Totals() + if err != nil || !report.Summary.MediaKnown || counts.Downloaded != 1 || counts.Filtered != 1 || report.Summary.DownloadedBytes != 4 { + t.Fatalf("account outcomes missing: summary=%+v err=%v", report.Summary, err) + } +} + func TestSavedMessagesAreNotPartOfAllPersonalChats(t *testing.T) { api := tg.NewClient(tgclient.InvokeFunc(func(context.Context, bin.Encoder, bin.Decoder) error { return nil })) s := &Source{manager: peers.Options{}.Build(api), chats: map[string]tg.InputPeerClass{}, accountID: 42} diff --git a/internal/telegram/source.go b/internal/telegram/source.go index f545822..9c8ad08 100644 --- a/internal/telegram/source.go +++ b/internal/telegram/source.go @@ -465,6 +465,9 @@ func (s *Source) DownloadWithProgress(ctx context.Context, file archive.File, de if s.takeoutID != 0 { api = tg.NewClient(takeout.Middleware(s.takeoutID).Handle(api.Invoker())) } + if file.Field == "thumbnail" { + api = thumbnailClient(api) + } f, err := os.OpenFile(dest, os.O_WRONLY|os.O_TRUNC, 0600) if err != nil { return err diff --git a/internal/telegram/thumbnail.go b/internal/telegram/thumbnail.go new file mode 100644 index 0000000..32734c6 --- /dev/null +++ b/internal/telegram/thumbnail.go @@ -0,0 +1,39 @@ +package telegram + +import ( + "context" + "fmt" + "sync/atomic" + + "github.com/gotd/td/bin" + "github.com/gotd/td/telegram" + "github.com/gotd/td/tg" + "github.com/gotd/td/tgerr" + "github.com/mo1ein/TelegramArchive/internal/archive" +) + +// A missing document preview can return Telegram Timeout indefinitely while +// the original attachment remains downloadable. Stop the downloader's internal +// timeout loop after three consecutive responses for this optional resource. +func thumbnailClient(api *tg.Client) *tg.Client { + var timeouts atomic.Int32 + return tg.NewClient(telegram.InvokeFunc(func(ctx context.Context, input bin.Encoder, output bin.Decoder) error { + err := api.Invoker().Invoke(ctx, input, output) + if ctx.Err() != nil { + return ctx.Err() + } + if _, ok := input.(*tg.UploadGetFileRequest); !ok { + return err + } + if err == nil { + timeouts.Store(0) + return nil + } + if tgerr.Is(err, tg.ErrTimeout) && timeouts.Add(1) >= 3 { + // Keep the original RPC error as text: wrapping it would cause gotd to + // recognize Timeout again and resume its unlimited retry loop. + return fmt.Errorf("%w: Telegram timed out after 3 attempts: %v", archive.ErrThumbnailUnavailable, err) + } + return err + })) +} diff --git a/internal/telegram/thumbnail_test.go b/internal/telegram/thumbnail_test.go new file mode 100644 index 0000000..8268dfd --- /dev/null +++ b/internal/telegram/thumbnail_test.go @@ -0,0 +1,139 @@ +package telegram + +import ( + "bytes" + "context" + "errors" + "os" + "sync/atomic" + "testing" + "time" + + "github.com/gotd/td/bin" + tgclient "github.com/gotd/td/telegram" + "github.com/gotd/td/tg" + "github.com/gotd/td/tgerr" + transferdownload "github.com/iyear/tdl/core/downloader" + "github.com/mo1ein/TelegramArchive/internal/archive" +) + +func thumbnailTestSource(invoke tgclient.InvokeFunc) *Source { + // Real Telegram timeouts are not an instantaneous busy loop. Pace the fake + // so the old downloader's unlimited retry path reaches a bounded watchdog. + paced := tgclient.InvokeFunc(func(ctx context.Context, input bin.Encoder, output bin.Decoder) error { + timer := time.NewTimer(10 * time.Millisecond) + defer timer.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-timer.C: + return invoke(ctx, input, output) + } + }) + api := tg.NewClient(DownloadActivityMiddleware().Handle(paced)) + return &Source{threads: 1, DownloadTimeout: 150 * time.Millisecond, pool: watchdogTestPool{client: func(context.Context, int) *tg.Client { return api }}} +} + +func TestThumbnailRepeatedServerTimeoutBecomesUnavailable(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + var calls atomic.Int32 + source := thumbnailTestSource(tgclient.InvokeFunc(func(context.Context, bin.Encoder, bin.Decoder) error { + calls.Add(1) + return tgerr.New(-503, "Timeout") + })) + file, dest := watchdogTestFile(t, 4) + file.Field, file.Kind, file.Path = "thumbnail", "videos", "video_files/700_thumb.jpg" + err := source.DownloadWithProgress(ctx, file, dest, nil) + if !errors.Is(err, archive.ErrThumbnailUnavailable) { + t.Fatalf("thumbnail still stalled the transfer instead of being unavailable: calls=%d err=%v", calls.Load(), err) + } + if calls.Load() > 3 || calls.Load() == 0 || ctx.Err() != nil { + t.Fatalf("thumbnail retries were not bounded: calls=%d parent=%v", calls.Load(), ctx.Err()) + } + if tgerr.Is(err, tg.ErrTimeout) { + t.Fatal("unavailable thumbnail still wraps the raw server Timeout, causing the downloader to retry forever") + } +} + +func TestThumbnailTransientTimeoutsRecoverAndSuccessResetsRetryBudget(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + body := bytes.Repeat([]byte{'x'}, transferdownload.MaxPartSize+4) + attempts := map[int64]int{} + source := thumbnailTestSource(tgclient.InvokeFunc(func(ctx context.Context, input bin.Encoder, output bin.Decoder) error { + request := input.(*tg.UploadGetFileRequest) + attempts[request.Offset]++ + if attempts[request.Offset] <= 2 { + return tgerr.New(-503, "Timeout") + } + start := min(int(request.Offset), len(body)) + end := min(start+request.Limit, len(body)) + output.(*tg.UploadFileBox).File = &tg.UploadFile{Type: &tg.StorageFileUnknown{}, Bytes: body[start:end]} + return nil + })) + file, dest := watchdogTestFile(t, int64(len(body))) + file.Field, file.Kind, file.Path = "thumbnail", "videos", "video_files/recovered_thumb.jpg" + if err := source.DownloadWithProgress(ctx, file, dest, nil); err != nil { + t.Fatalf("a recoverable thumbnail was skipped: %v", err) + } + data, err := os.ReadFile(dest) + if err != nil || !bytes.Equal(data, body) { + t.Fatalf("recovered thumbnail was truncated: size=%d err=%v", len(data), err) + } + if attempts[0] != 3 || attempts[transferdownload.MaxPartSize] != 3 { + t.Fatalf("expected transient timeouts on both chunks: %v", attempts) + } +} + +func TestPrimaryMediaTimeoutDoesNotBecomeUnavailableThumbnail(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + var calls atomic.Int32 + source := thumbnailTestSource(tgclient.InvokeFunc(func(context.Context, bin.Encoder, bin.Decoder) error { + calls.Add(1) + return tgerr.New(-503, "Timeout") + })) + file, dest := watchdogTestFile(t, 4) + file.Field, file.Kind, file.Path = "file", "videos", "video_files/700.mp4" + err := source.DownloadWithProgress(ctx, file, dest, nil) + var stalled *DownloadStalledError + if !errors.As(err, &stalled) || errors.Is(err, archive.ErrThumbnailUnavailable) || calls.Load() <= 3 { + t.Fatalf("primary media was skipped: calls=%d err=%v", calls.Load(), err) + } +} + +func TestThumbnailCancellationIsNotUnavailable(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + var calls atomic.Int32 + source := thumbnailTestSource(tgclient.InvokeFunc(func(ctx context.Context, input bin.Encoder, output bin.Decoder) error { + if calls.Add(1) == 2 { + cancel() + return ctx.Err() + } + return tgerr.New(-503, "Timeout") + })) + file, dest := watchdogTestFile(t, 4) + file.Field, file.Kind = "thumbnail", "videos" + err := source.DownloadWithProgress(ctx, file, dest, nil) + if !errors.Is(err, context.Canceled) || errors.Is(err, archive.ErrThumbnailUnavailable) || calls.Load() != 2 { + t.Fatalf("cancellation was treated as a missing thumbnail: calls=%d err=%v", calls.Load(), err) + } +} + +func TestThumbnailLocalWriteFailureIsNotUnavailable(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + source := thumbnailTestSource(tgclient.InvokeFunc(func(context.Context, bin.Encoder, bin.Decoder) error { + t.Error("network request started despite an unusable destination") + return tgerr.New(-503, "Timeout") + })) + file, _ := watchdogTestFile(t, 4) + file.Field, file.Kind = "thumbnail", "videos" + err := source.DownloadWithProgress(ctx, file, t.TempDir(), nil) + var local *os.PathError + if !errors.As(err, &local) || errors.Is(err, archive.ErrThumbnailUnavailable) { + t.Fatalf("local write failure was treated as a missing thumbnail: %v", err) + } +}