Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
16 changes: 12 additions & 4 deletions cmd/cron.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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))
Expand All @@ -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")

Expand All @@ -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()
}}
Expand Down Expand Up @@ -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
Expand Down
7 changes: 5 additions & 2 deletions cmd/cron_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
Expand All @@ -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")
}
Expand All @@ -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)
}
}
Expand Down
43 changes: 43 additions & 0 deletions cmd/progress_color_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}
9 changes: 8 additions & 1 deletion docs/backups.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
92 changes: 92 additions & 0 deletions docs/performance.md
Original file line number Diff line number Diff line change
@@ -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.
4 changes: 3 additions & 1 deletion internal/archive/planning.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
51 changes: 51 additions & 0 deletions internal/archive/planning_benchmark_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
})
}
}
18 changes: 15 additions & 3 deletions internal/cron/cron.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand Down Expand Up @@ -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 }
Expand All @@ -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") {
Expand Down
Loading
Loading