From 655bcb309d4b0e99d9380e5f4ebe85a884ef8836 Mon Sep 17 00:00:00 2001 From: moein Date: Fri, 13 Nov 2026 21:12:09 +0330 Subject: [PATCH 1/2] feat: add startup catch-up runs for cron backups Add --at-startup to run an incremental backup after system startup while keeping the regular cron schedule. Startup runs wait for shared output folders so concurrent jobs each get a turn. Preserve safe updates and removal of managed cron blocks, show startup triggers in the job list, and document the behavior with regression tests. --- cmd/cron.go | 16 +++++-- cmd/cron_test.go | 7 ++- docs/backups.md | 9 +++- internal/cron/cron.go | 18 ++++++-- internal/cron/cron_test.go | 91 ++++++++++++++++++++++++++++++++++++++ 5 files changed, 131 insertions(+), 10 deletions(-) diff --git a/cmd/cron.go b/cmd/cron.go index 092df7a..c7404b2 100644 --- a/cmd/cron.go +++ b/cmd/cron.go @@ -25,7 +25,7 @@ func NewCron() *cobra.Command { func newCron(manager managedcron.Manager, execute managedcron.Runner) *cobra.Command { group := &cobra.Command{Use: "cron", Short: "Install and manage backups in your system crontab", Annotations: map[string]string{"offline": "true"}} - var runNow bool + var runNow, atStartup bool add := newSyncPlan(nil, func(cmd *cobra.Command, dir string, timing schedule.Options) error { name := cmd.Flags().Args()[0] if err := managedcron.ValidateName(name); err != nil { @@ -50,11 +50,14 @@ func newCron(manager managedcron.Manager, execute managedcron.Runner) *cobra.Com if err != nil { return err } - job := managedcron.Job{Name: name, Schedule: expression, Executable: executable, Directory: working, Arguments: args, Environment: environment, Log: filepath.Join(manager.Directory, name+".log")} + job := managedcron.Job{Name: name, Schedule: expression, AtStartup: atStartup, Executable: executable, Directory: working, Arguments: args, Environment: environment, Log: filepath.Join(manager.Directory, name+".log")} if err := manager.Install(cmd.Context(), job); err != nil { return err } fmt.Fprintf(cmd.OutOrStdout(), "Installed cron job %q: %s (cron's timezone)\nOutput: %s\nLog: %s\nTa can exit; cron will launch each backup.\n", name, expression, dir, job.Log) + if atStartup { + fmt.Fprintln(cmd.OutOrStdout(), "Also runs at system startup, waiting for a busy output folder.") + } if runNow { skipBusy, _ := cmd.Flags().GetBool("skip-busy") return managedcron.Run(cmd.Context(), manager.File(name), cmd.OutOrStdout(), cronRunWithSkipBusy(execute, cmd.Flags().Changed("skip-busy") && skipBusy)) @@ -71,6 +74,7 @@ func newCron(manager managedcron.Manager, execute managedcron.Runner) *cobra.Com add.Flags().Lookup("every").DefValue = "6h" add.Flags().Lookup("every").Usage = "cron interval: minutes dividing an hour, hours dividing a day, or 24h" add.Flags().BoolVar(&runNow, "run-now", false, "also run the first backup immediately after installing cron") + add.Flags().BoolVar(&atStartup, "at-startup", false, "also run a backup at system startup to catch up after downtime") add.Flags().MarkHidden("runs") add.Flags().MarkHidden("stop-on-error") @@ -90,7 +94,11 @@ func newCron(manager managedcron.Manager, execute managedcron.Runner) *cobra.Com if !job.Installed { status = "not in crontab" } - fmt.Fprintf(out, "%s\t%s\t%s\t%s\n", job.Name, job.Schedule, status, job.Log) + expression := job.Schedule + if job.AtStartup { + expression += " + startup" + } + fmt.Fprintf(out, "%s\t%s\t%s\t%s\n", job.Name, expression, status, job.Log) } return out.Flush() }} @@ -244,7 +252,7 @@ func cronArguments(cmd *cobra.Command) ([]string, map[string]string, error) { args = append(args, "sync") cmd.LocalNonPersistentFlags().VisitAll(func(flag *pflag.Flag) { switch flag.Name { - case "every", "runs", "stop-on-error", "run-now", "help": + case "every", "runs", "stop-on-error", "run-now", "at-startup", "help": return } // These flags enable account backup / override its takeout default by diff --git a/cmd/cron_test.go b/cmd/cron_test.go index e1503e3..11ada78 100644 --- a/cmd/cron_test.go +++ b/cmd/cron_test.go @@ -60,7 +60,7 @@ func TestCronInstallCapturesSettingsAndRunsSyncOnlyOnce(t *testing.T) { }) var output bytes.Buffer root.SetOut(&output) - args := []string{"--storage=type=bolt,path=sessions", "cron", "add", "channel", "--chat=Private group", "--every=6h", "--media=all", "--format=both", "--output=backup", "--run-now"} + args := []string{"--storage=type=bolt,path=sessions", "cron", "add", "channel", "--chat=Private group", "--every=6h", "--media=all", "--format=both", "--output=backup", "--run-now", "--at-startup"} if account { args = append(args, "--account") } @@ -71,6 +71,9 @@ func TestCronInstallCapturesSettingsAndRunsSyncOnlyOnce(t *testing.T) { if calls != 1 || table.writes != 1 { t.Fatalf("calls=%d writes=%d", calls, table.writes) } + if !strings.Contains(table.content, "@reboot ") || !strings.Contains(table.content, "0 */6 * * * ") { + t.Fatalf("startup option must keep both triggers: %s", table.content) + } if strings.Contains(table.content, "private") || strings.Contains(output.String(), "private") { t.Fatal("credentials were printed or put in crontab") } @@ -87,7 +90,7 @@ func TestCronInstallCapturesSettingsAndRunsSyncOnlyOnce(t *testing.T) { } } for _, value := range job.Arguments { - if strings.HasPrefix(value, "--every=") || strings.HasPrefix(value, "--account-include") || strings.HasPrefix(value, "--takeout") || strings.HasPrefix(value, "--run-now") { + if strings.HasPrefix(value, "--every=") || strings.HasPrefix(value, "--account-include") || strings.HasPrefix(value, "--takeout") || strings.HasPrefix(value, "--run-now") || strings.HasPrefix(value, "--at-startup") { t.Fatalf("changed one-shot argument: %q", value) } } diff --git a/docs/backups.md b/docs/backups.md index 2a8f3a4..65e54ab 100644 --- a/docs/backups.md +++ b/docs/backups.md @@ -48,7 +48,7 @@ Install a real cron job using ta commands: ```sh # Back up now, then sync every six hours. ta cron add my-channel --chat "channel_username" --every 6h \ - --media all --format both --output ./data --run-now + --media all --format both --output ./data --run-now --at-startup # All chats, media and separate account data, once a day. ta cron add everything --everything --every 24h --format both --run-now @@ -67,6 +67,13 @@ 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. +Cron only runs at scheduled times while the computer is on. It does not replay +backups missed while the computer was off or asleep. Add `--at-startup` to also +run one incremental backup when the system starts, keeping the regular schedule. +Startup runs wait for a shared output folder so each job gets a turn. They use +the saved login and settings, so no terminal needs to be open. Add or update the +same job without `--at-startup` to remove its startup trigger. + 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 diff --git a/internal/cron/cron.go b/internal/cron/cron.go index d44a049..10eb473 100644 --- a/internal/cron/cron.go +++ b/internal/cron/cron.go @@ -19,6 +19,7 @@ type Job struct { ResultFile string `json:"-"` // Private per-invocation child result; never saved. Name string `json:"name"` Schedule string `json:"schedule"` + AtStartup bool `json:"at_startup,omitempty"` Executable string `json:"executable"` Directory string `json:"directory"` Arguments []string `json:"arguments"` @@ -82,7 +83,14 @@ func (m Manager) Line(job Job) (string, error) { if len(strings.Fields(job.Schedule)) != 5 || strings.ContainsAny(job.Schedule, "\r\n") { return "", fmt.Errorf("invalid cron schedule") } - return job.Schedule + " " + quote(job.Executable) + " cron run --file " + quote(m.File(job.Name)) + " > /dev/null 2>&1", nil + command := quote(job.Executable) + " cron run --file " + quote(m.File(job.Name)) + line := job.Schedule + " " + command + " > /dev/null 2>&1" + if job.AtStartup { + // Startup jobs all launch together. Wait for shared output folders so + // each gets a catch-up run, rather than skipping until the next tick. + line += "\n@reboot " + command + " --skip-busy=false > /dev/null 2>&1" + } + return line, nil } func begin(name string) string { return "# ta cron begin " + name } @@ -96,10 +104,14 @@ func replace(table, name, line string) (string, error) { out.WriteString(lines[i]) continue } - if i+2 >= len(lines) || strings.TrimSpace(lines[i+2]) != end(name) { + last := i + 2 + if last < len(lines) && strings.HasPrefix(strings.TrimSpace(lines[last]), "@reboot ") { + last++ + } + if last >= len(lines) || strings.TrimSpace(lines[last]) != end(name) { return "", fmt.Errorf("cron block for %q is damaged; leaving your crontab unchanged", name) } - i += 2 + i = last } if line != "" { if out.Len() > 0 && !strings.HasSuffix(out.String(), "\n") { diff --git a/internal/cron/cron_test.go b/internal/cron/cron_test.go index 6c31bb6..cdd08e9 100644 --- a/internal/cron/cron_test.go +++ b/internal/cron/cron_test.go @@ -2,8 +2,10 @@ package cron import ( "context" + "encoding/json" "errors" "os" + "os/exec" "path/filepath" "strings" "testing" @@ -116,6 +118,95 @@ func TestInstallFailureRollsBackAndReadErrorsNeverOverwrite(t *testing.T) { } } +func TestStartupJobKeepsScheduleAndCanBeUpdatedAndRemoved(t *testing.T) { + dir := t.TempDir() + table := &memoryTable{content: "MAILTO=operator@example.test\n17 3 * * * /usr/bin/true\n"} + original := table.content + m := Manager{Directory: filepath.Join(dir, "jobs"), Table: table} + job := sampleJob(dir) + // Use the saved representation to also cover loading an enabled startup job. + if err := json.Unmarshal([]byte(`{"at_startup":true}`), &job); err != nil { + t.Fatal(err) + } + for range 2 { + if err := m.Install(context.Background(), job); err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(table.content, original) || strings.Count(table.content, begin(job.Name)) != 1 { + t.Fatalf("startup install changed other jobs or duplicated the block: %s", table.content) + } + if strings.Count(table.content, job.Schedule+" ") != 1 || strings.Count(table.content, "@reboot ") != 1 { + t.Fatalf("job must run on its schedule and once at startup: %s", table.content) + } + startup := strings.Split(strings.Split(table.content, "@reboot ")[1], "\n")[0] + if !strings.Contains(startup, "cron run --file "+quote(m.File(job.Name))) || !strings.Contains(startup, "--skip-busy=false") { + t.Fatalf("startup must run the saved job and wait for shared output folders: %s", startup) + } + var err error + job, err = ReadJob(m.File(job.Name)) + if err != nil { + t.Fatal(err) + } + } + if err := m.Remove(context.Background(), job.Name); err != nil || table.content != original { + t.Fatalf("removing startup job changed unrelated entries: %v, %s", err, table.content) + } + if err := m.Install(context.Background(), job); err != nil { + t.Fatal(err) + } + if err := json.Unmarshal([]byte(`{"at_startup":false}`), &job); err != nil { + t.Fatal(err) + } + if err := m.Install(context.Background(), job); err != nil { + t.Fatal(err) + } + if strings.Contains(table.content, "@reboot") || strings.Count(table.content, job.Schedule+" ") != 1 { + t.Fatalf("disabling startup lost the schedule or kept the startup entry: %s", table.content) + } +} + +func TestDamagedStartupBlockIsNeverOverwritten(t *testing.T) { + for _, block := range []string{ + "# ta cron begin channel\n0 * * * * ta\n@reboot ta\n", + "# ta cron begin channel\n0 * * * * ta\nunrelated job\n# ta cron end channel\n", + "# ta cron begin channel\n0 * * * * ta\n@reboot ta\n# ta cron end another\n", + } { + if _, err := replace(block, "channel", "replacement"); err == nil { + t.Fatalf("damaged startup block was overwritten: %s", block) + } + } +} + +func TestStartupEntryExecutesSavedJobWithQuotedPaths(t *testing.T) { + dir := t.TempDir() + job := sampleJob(dir) + job.AtStartup = true + job.Executable = filepath.Join(dir, "ta 'quoted'") + arguments := filepath.Join(dir, "arguments") + if err := os.WriteFile(job.Executable, []byte("#!/bin/sh\nprintf '%s\\n' \"$@\" > \"$TA_TEST_ARGUMENTS\"\n"), 0700); err != nil { + t.Fatal(err) + } + m := Manager{Directory: filepath.Join(dir, "jobs 'quoted'")} + entries, err := m.Line(job) + if err != nil { + t.Fatal(err) + } + lines := strings.Split(entries, "\n") + if len(lines) != 2 || !strings.HasPrefix(lines[1], "@reboot ") { + t.Fatalf("missing startup entry: %s", entries) + } + command := exec.Command("/bin/sh", "-c", strings.TrimPrefix(lines[1], "@reboot ")) + command.Env = append(os.Environ(), "TA_TEST_ARGUMENTS="+arguments) + if err := command.Run(); err != nil { + t.Fatal(err) + } + got, err := os.ReadFile(arguments) + want := "cron\nrun\n--file\n" + m.File(job.Name) + "\n--skip-busy=false\n" + if err != nil || string(got) != want { + t.Fatalf("startup ran the wrong arguments: %q, %v", got, err) + } +} + func TestDamagedBlocksAndUnsafePathsAreRejected(t *testing.T) { if _, err := replace("# ta cron begin channel\nuser job\n", "channel", "replacement"); err == nil { t.Fatal("damaged block was overwritten") From 0c6789274d1c1d89b7effc177f9fec1dc688c7f2 Mon Sep 17 00:00:00 2001 From: moein Date: Fri, 13 Nov 2026 21:12:13 +0330 Subject: [PATCH 2/2] perf: speed up archive planning and add transfer benchmarks Avoid per-page durable flushes for the disposable planning database while preserving durable archive checkpoints. Add repeatable planning and ta versus tdl-core download benchmarks with payload integrity checks. Record local measurements and their scope, plus coverage for colored progress output. Validation: 262 tests, race checks, go vet, build, and a live saved backup passed. --- Makefile | 9 +- cmd/progress_color_test.go | 43 +++++ docs/performance.md | 92 +++++++++ internal/archive/planning.go | 4 +- internal/archive/planning_benchmark_test.go | 51 +++++ internal/telegram/download_benchmark_test.go | 188 +++++++++++++++++++ 6 files changed, 385 insertions(+), 2 deletions(-) create mode 100644 cmd/progress_color_test.go create mode 100644 docs/performance.md create mode 100644 internal/archive/planning_benchmark_test.go create mode 100644 internal/telegram/download_benchmark_test.go diff --git a/Makefile b/Makefile index b1ad58e..5ddcb07 100644 --- a/Makefile +++ b/Makefile @@ -2,12 +2,13 @@ GO ?= go BIN ?= bin/ta$(shell $(GO) env GOEXE) ARGS ?= --help -.PHONY: help build build-manual install run test race vet bench +.PHONY: help build build-manual install run test race vet bench bench-plan bench-downloads help: @echo "make install Install ta into GOBIN (or GOPATH/bin)" @echo "make build Build $(BIN)" @echo "make run ARGS='archive --all --types channels --format both'" @echo "make test race vet bench" + @echo "make bench-plan bench-downloads Planning and controlled ta/tdl-core benchmarks" @echo "ta sync --everything --every 6h --format both Recurring incremental backups" build: @@ -32,3 +33,9 @@ vet: bench: $(GO) test ./internal/archive -run '^$$' -bench . -benchmem + +bench-plan: + $(GO) test ./internal/archive -run '^$$' -bench '^BenchmarkPlanBatch$$' -benchmem -benchtime=5x -count=5 + +bench-downloads: + $(GO) test ./internal/telegram -run '^$$' -bench '^BenchmarkDownloadEngines$$' -benchmem -benchtime=1x -count=5 diff --git a/cmd/progress_color_test.go b/cmd/progress_color_test.go new file mode 100644 index 0000000..7c59f74 --- /dev/null +++ b/cmd/progress_color_test.go @@ -0,0 +1,43 @@ +package cmd + +import ( + "strings" + "testing" + "time" + + "github.com/jedib0t/go-pretty/v6/text" + "github.com/mattn/go-runewidth" + "github.com/mo1ein/TelegramArchive/internal/archive" +) + +func TestBackupProgressColorPreservesContentAndTerminalWidth(t *testing.T) { + started := time.Now().Add(-time.Second) + p := &backupProgress{started: started, transferStarted: started, active: map[string]activeTransfer{}, colorful: true} + p.setPlan(archive.DownloadPlan{Ready: true, Bytes: 100, Files: 1}) + file := archive.File{Path: "files/video.mp4", Size: 100} + p.transfer(archive.TransferEvent{Kind: archive.TransferStarted, File: file}) + p.transfer(archive.TransferEvent{Kind: archive.TransferProgressed, File: file, Delta: 40}) + colored := p.lines(started.Add(time.Second), 80) + p.colorful = false + plain := p.lines(started.Add(time.Second), 80) + for i := range colored { + if text.StripEscape(colored[i]) != plain[i] { + t.Fatalf("color changed progress information: %q vs %q", colored[i], plain[i]) + } + if strings.Contains(plain[i], "\x1b") { + t.Fatalf("plain progress contains color escapes: %q", plain[i]) + } + if text.FgCyan.Sprint("probe") != "probe" && !strings.Contains(colored[i], "\x1b[") { + t.Fatalf("colored progress has no color: %q", colored[i]) + } + } + if !strings.Contains(strings.Join(plain, "\n"), "40.0%") { + t.Fatal("progress lost its percentage") + } + p.colorful = true + for _, line := range p.lines(started.Add(time.Second), 24) { + if runewidth.StringWidth(text.StripEscape(line)) >= 24 { + t.Fatalf("colored progress overflows a narrow terminal: %q", line) + } + } +} diff --git a/docs/performance.md b/docs/performance.md new file mode 100644 index 0000000..4be4535 --- /dev/null +++ b/docs/performance.md @@ -0,0 +1,92 @@ +# Performance measurements + +Measure planning, media transfer, and complete backups separately. The transfer +comparison below uses the actual download paths from `ta` and the pinned +`github.com/iyear/tdl/core v0.20.4` dependency. It does not benchmark the installed +`tdl` CLI, live Telegram bandwidth, authentication, chat discovery, or rendering. +The two engines share the same Go compiler and gotd dependency in this test. + +## Reproduce + +```sh +make bench-plan +make bench-downloads +``` + +Both commands run without Telegram credentials or network access. They report +allocations and repeat each case five times. Compare medians and ranges on the +same machine. Use the same compiler, filesystem, and test settings for a baseline +and a changed build; avoid running other benchmarks concurrently. + +`bench-plan` measures the real progress-planning pass over 1,000 or 10,000 +messages, in pages of 100. It checks the final message, file, and byte counts. +History is generated locally, so these timings exclude Telegram RPC latency. + +`bench-downloads` uses a simulated Telegram endpoint with a fixed 5 ms delay per +file request. Both engines use two concurrent files, up to four threads per file, +1 MiB chunks, the same file bytes, and the same destination filesystem. Output +file opening and closing are timed for both. Progress callbacks are empty; ta's +normal download watchdog remains enabled. Output length and SHA-256 are checked +after every iteration, outside the timer, and benchmark-created files are reset +before the next iteration. A failed or incomplete download fails the benchmark, +including individual errors that tdl-core normally logs instead of returning. + +The fixture models request latency, not a bandwidth cap or real DC connection +setup. Its MB/s output is synthetic throughput. Do not present it as Internet +download speed or an end-to-end backup comparison. + +## Local results: November 13, 2026 + +Machine: Intel Core i7-7700HQ, Linux amd64, Go 1.26.4, eight logical CPUs. Test +output used ext4 under `/tmp`. Values are median wall times over five samples. +Raw measurements are retained locally in `.cache/performance-20261113/`. + +### Planning improvement + +The temporary planning database previously flushed every page to durable storage. +It is rebuilt on every run and is not a recovery checkpoint. Opening this +temporary database with `NoSync` avoids those flushes. Persistent archive +databases keep their existing durability settings. Planning still finishes +before downloads begin and retains accurate progress totals. + +| Pending messages/files | Before | After | Before / after | +|---|---:|---:|---:| +| 1,000 | 140.62 ms | 42.40 ms | 3.32× | +| 10,000 | 1,024.37 ms | 110.81 ms | 9.24× | + +The before and after binaries were run directly with identical benchmark flags, +without CPU profiling. Each sample averaged five planning passes. For 10,000 +items, sample ranges were 1,013.51–1,245.93 ms before and 101.22–129.46 ms after. +This is a planning-stage improvement; it is not a 9.24× whole-backup speedup. + +### Controlled download comparison + +| Workload | ta median (range) | tdl-core median (range) | +|---|---:|---:| +| 16 × 64 KiB files | 46.65 ms (43.63–47.00) | 1,650.45 ms (1,650.28–1,650.92) | +| 8 × 64 KiB + 2 × (4 MiB + 1 byte) | 38.90 ms (38.72–39.67) | 1,043.06 ms (1,042.39–1,044.97) | +| 2 × 16 MiB, aligned chunks | 28.54 ms (28.43–28.72) | 28.41 ms (28.31–30.76) | +| 2 × (16 MiB + 1 byte) | 28.73 ms (28.25–28.86) | 333.06 ms (230.80–335.00) | + +ta already avoids tdl-core's fixed 200 ms sleep when writing a short final chunk. +That existing behavior explains the small-file advantage (35.4× here). The +aligned large-file case avoids that delay and is effectively at parity; ta's +median was about 0.5% slower. The larger spread in the final tdl-core case is +another reason to keep ranges and repeat measurements. The benchmark also reports +request counts: the parallel downloader can issue different numbers of empty +end-of-file probes depending on scheduling. Both engines must still produce +exactly the same complete payload, verified by length and SHA-256. + +The planning change does not cause these transfer ratios. Large transfers still +use the same gotd downloader and remain subject to Telegram's server limits and +the user's network. A live comparison must use the same account, file manifest, +concurrency, output disk, integrity checks, and alternating run order, and must +report transfer time separately from discovery and archive output generation. + +## Progress display + +Interactive terminals already use colored labels, a yellow progress bar, cyan +byte totals, magenta throughput, and green timing information. Rendering refreshes +at up to ten frames per second. `NO_COLOR`, `TERM=dumb`, and redirected output +produce plain text. Cron jobs save plain-output settings so logs remain readable. +Color rendering is tested for unchanged metrics and narrow-terminal clipping. diff --git a/internal/archive/planning.go b/internal/archive/planning.go index add0b26..b148639 100644 --- a/internal/archive/planning.go +++ b/internal/archive/planning.go @@ -40,7 +40,9 @@ func planBatch(ctx context.Context, source Source, root string, directories []st name := f.Name() f.Close() defer os.Remove(name) - db, err := bolt.Open(name, 0600, nil) + // This database is rebuilt for each scan and never used for recovery. + // Avoid a durable disk flush per page; archive checkpoints remain synced. + db, err := bolt.Open(name, 0600, &bolt.Options{NoSync: true}) if err != nil { return nil, err } diff --git a/internal/archive/planning_benchmark_test.go b/internal/archive/planning_benchmark_test.go new file mode 100644 index 0000000..b14ffa9 --- /dev/null +++ b/internal/archive/planning_benchmark_test.go @@ -0,0 +1,51 @@ +package archive + +import ( + "context" + "fmt" + "strconv" + "testing" +) + +// Use indexed pagination so the benchmark measures planning, not an O(n²) +// fixture search. There is no Telegram network or media transfer in this case. +type planningBenchmarkSource struct{ items []Item } + +func (s planningBenchmarkSource) History(ctx context.Context, _ Chat, cursor string) (Page, error) { + if err := ctx.Err(); err != nil { + return Page{}, err + } + start, _ := strconv.Atoi(cursor) + end := min(start+100, len(s.items)) + return Page{Items: s.items[start:end], Next: strconv.Itoa(end), Done: end == len(s.items)}, nil +} + +func (planningBenchmarkSource) Download(context.Context, File, string) error { + return fmt.Errorf("planning must not download media") +} + +func BenchmarkPlanBatch(b *testing.B) { + for _, count := range []int{1000, 10000} { + b.Run(strconv.Itoa(count), func(b *testing.B) { + ids := make([]int, count) + for i := range ids { + ids[i] = count - i + } + source := planningBenchmarkSource{items: fakeItems(ids...)} + root := b.TempDir() + chats := []Chat{{ID: 1, Key: "channel_1"}} + var plan DownloadPlan + opts := Options{Concurrency: 2, Media: []string{"photos"}, OnPlan: func(p DownloadPlan) { plan = p }} + b.ReportAllocs() + b.ResetTimer() + for range b.N { + if _, err := planBatch(context.Background(), source, root, nil, chats, opts); err != nil { + b.Fatal(err) + } + if !plan.Ready || plan.Files != int64(count) || plan.Bytes != int64(count*4) || plan.Messages != int64(count) { + b.Fatalf("incorrect planning totals: %+v", plan) + } + } + }) + } +} diff --git a/internal/telegram/download_benchmark_test.go b/internal/telegram/download_benchmark_test.go new file mode 100644 index 0000000..f7986ff --- /dev/null +++ b/internal/telegram/download_benchmark_test.go @@ -0,0 +1,188 @@ +package telegram + +import ( + "context" + "crypto/sha256" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/gotd/td/bin" + tgclient "github.com/gotd/td/telegram" + "github.com/gotd/td/tg" + transferdownload "github.com/iyear/tdl/core/downloader" + "github.com/iyear/tdl/core/tmedia" + "github.com/mo1ein/TelegramArchive/internal/archive" + "golang.org/x/sync/errgroup" +) + +// These cases compare the real ta and pinned tdl-core download paths against +// the same simulated Telegram endpoint. They do not measure Internet speed, +// authentication, chat discovery, archive rendering, or tdl's CLI progress UI. +// Both use two files in flight, four maximum threads, 1 MiB chunks and 5 ms RTT. +func BenchmarkDownloadEngines(b *testing.B) { + for _, workload := range []struct { + name string + sizes []int + }{ + {"small", repeatSize(16, 64<<10)}, + {"mixed", append(repeatSize(8, 64<<10), repeatSize(2, (4<<20)+1)...)}, + {"large-aligned", repeatSize(2, 16<<20)}, + {"large-tail", repeatSize(2, (16<<20)+1)}, + } { + for _, engine := range []string{"ta", "tdl-core"} { + b.Run(workload.name+"/"+engine, func(b *testing.B) { + fixtures := make([]*transferBenchmarkFile, len(workload.sizes)) + root := b.TempDir() + var total int64 + for i, size := range workload.sizes { + body := make([]byte, size) + for j := range body { + body[j] = byte((j/1024 + i) % 251) + } + path := filepath.Join(root, fmt.Sprintf("%d.bin", i)) + if err := os.WriteFile(path, nil, 0600); err != nil { + b.Fatal(err) + } + location := &tg.InputDocumentFileLocation{ID: int64(i + 1)} + file := archive.File{Path: filepath.Base(path), Size: int64(size), Remote: &tmedia.Media{DC: 4, Size: int64(size), InputFileLoc: location}} + fixtures[i] = &transferBenchmarkFile{body: body, path: path, file: file, location: location, hash: sha256.Sum256(body)} + total += int64(size) + } + var requests atomic.Int64 + api := tg.NewClient(DownloadActivityMiddleware().Handle(tgclient.InvokeFunc(func(ctx context.Context, input bin.Encoder, output bin.Decoder) error { + request, ok := input.(*tg.UploadGetFileRequest) + if !ok { + return fmt.Errorf("unexpected request %T", input) + } + requests.Add(1) + timer := time.NewTimer(5 * time.Millisecond) + defer timer.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-timer.C: + } + body := fixtures[request.Location.(*tg.InputDocumentFileLocation).ID-1].body + 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 + }))) + pool := watchdogTestPool{client: func(context.Context, int) *tg.Client { return api }} + source := &Source{pool: pool, threads: 4, DownloadTimeout: DefaultDownloadTimeout} + b.ReportAllocs() + b.SetBytes(total) + for b.Loop() { + if engine == "ta" { + group, ctx := errgroup.WithContext(b.Context()) + group.SetLimit(2) + for _, fixture := range fixtures { + group.Go(func() error { + return source.DownloadWithProgress(ctx, fixture.file, fixture.path, func(int64) {}) + }) + } + if err := group.Wait(); err != nil { + b.Fatal(err) + } + } else { + progress := &transferBenchmarkProgress{} + iterator := &transferBenchmarkIterator{files: fixtures} + downloader := transferdownload.New(transferdownload.Options{Pool: pool, Threads: 4, Iter: iterator, Progress: progress}) + if err := downloader.Download(b.Context(), 2); err != nil { + b.Fatal(err) + } + // tdl-core logs individual failures and returns nil; never let + // those failures masquerade as a fast benchmark result. + if progress.err != nil { + b.Fatal(progress.err) + } + } + b.StopTimer() + for _, fixture := range fixtures { + data, err := os.ReadFile(fixture.path) + if err != nil || len(data) != len(fixture.body) || sha256.Sum256(data) != fixture.hash { + b.Fatalf("downloaded bytes differ: %s: %v", fixture.path, err) + } + // Reset only benchmark-created output. A later iteration must + // not pass integrity checks by reusing earlier complete bytes. + if err := os.Truncate(fixture.path, 0); err != nil { + b.Fatal(err) + } + } + b.StartTimer() + } + b.ReportMetric(float64(requests.Load())/float64(b.N), "requests/op") + }) + } + } +} + +func repeatSize(count, size int) []int { + sizes := make([]int, count) + for i := range sizes { + sizes[i] = size + } + return sizes +} + +type transferBenchmarkFile struct { + body []byte + path string + file archive.File + output *os.File + location *tg.InputDocumentFileLocation + hash [sha256.Size]byte +} + +func (f *transferBenchmarkFile) File() transferdownload.File { return f } +func (f *transferBenchmarkFile) To() io.WriterAt { return f.output } +func (f *transferBenchmarkFile) AsTakeout() bool { return false } +func (f *transferBenchmarkFile) Location() tg.InputFileLocationClass { return f.location } +func (f *transferBenchmarkFile) Size() int64 { return int64(len(f.body)) } +func (f *transferBenchmarkFile) DC() int { return 4 } + +type transferBenchmarkIterator struct { + files []*transferBenchmarkFile + index int + err error +} + +func (i *transferBenchmarkIterator) Next(ctx context.Context) bool { + if i.err = ctx.Err(); i.err != nil || i.index == len(i.files) { + return false + } + // The real tdl iterator opens output files, and OnDone closes them. + // Include that file lifecycle in the measured time for both engines. + file := i.files[i.index] + file.output, i.err = os.OpenFile(file.path, os.O_WRONLY|os.O_TRUNC, 0600) + if i.err != nil { + return false + } + i.index++ + return true +} +func (i *transferBenchmarkIterator) Value() transferdownload.Elem { return i.files[i.index-1] } +func (i *transferBenchmarkIterator) Err() error { return i.err } + +type transferBenchmarkProgress struct { + mu sync.Mutex + err error +} + +func (*transferBenchmarkProgress) OnAdd(transferdownload.Elem) {} +func (*transferBenchmarkProgress) OnDownload(transferdownload.Elem, transferdownload.ProgressState) {} +func (p *transferBenchmarkProgress) OnDone(elem transferdownload.Elem, err error) { + err = errors.Join(err, elem.(*transferBenchmarkFile).output.Close()) + p.mu.Lock() + defer p.mu.Unlock() + if p.err == nil { + p.err = err + } +}