From 5313369328ceafb000c6ed87285cdeae46935b07 Mon Sep 17 00:00:00 2001 From: David Young Date: Sun, 22 Nov 2026 14:38:23 -0700 Subject: [PATCH] Phase 6 part 1: database backups MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Backups with SQLite's VACUUM INTO into /backups: on request (Settings → Backups, supermarket backup [note]), before every schema migration, and daily, keeping 7 dailies and 4 weeklies. Listed with size and schema; downloadable and deletable. The old app.db.pre-* copies are moved in, with their -wal files folded in first. Co-Authored-By: Claude Opus 5.5 --- PLAN.md | 63 ++++- TEST.md | 19 ++ bin/supermarket | 9 + cmd/supermarket/main.go | 65 +++++ internal/backup/backup.go | 386 ++++++++++++++++++++++++++++ internal/backup/backup_test.go | 192 ++++++++++++++ internal/db/db.go | 21 ++ internal/db/migrate_hook_test.go | 61 +++++ internal/web/backups.go | 118 +++++++++ internal/web/backups_test.go | 54 ++++ internal/web/server.go | 17 ++ internal/web/server_test.go | 2 +- internal/web/templates/backups.html | 33 +++ internal/web/templates/layout.html | 3 + 14 files changed, 1039 insertions(+), 4 deletions(-) create mode 100644 internal/backup/backup.go create mode 100644 internal/backup/backup_test.go create mode 100644 internal/db/migrate_hook_test.go create mode 100644 internal/web/backups.go create mode 100644 internal/web/backups_test.go create mode 100644 internal/web/templates/backups.html diff --git a/PLAN.md b/PLAN.md index ba08766..655a498 100644 --- a/PLAN.md +++ b/PLAN.md @@ -1348,11 +1348,66 @@ under Sections and pages. **Phase 5 is complete** (parts 1–5). Not yet tried for real: building a page (a paid AI call) and pushing it to the real repository. +### Phase 6: Backups, lead forms, the LinkedIn page, new sites + +**Started 2026-11-22** on branch `phase6`, after Phase 5 was merged into +`main`. Phases 0–5 had covered the plan; the user chose to make Phase 6 +of four further pieces: the first three future enhancements below, and a +shared theme for new sites (deferred in Phase 5). + +**Parts, in order, a commit after each:** +1. **Backups.** As designed under Future enhancements, item 2: SQLite's own + backup (`VACUUM INTO`), into `backups/`; made on request (Settings → + Backups, `supermarket backup [note]`), before every schema migration, + and daily; kept 7 daily and 4 weekly, the rest until deleted; listed + with size and schema, downloadable and deletable; the old + `app.db.pre-*` copies moved in. +2. **Restore.** From a backup in the list, an uploaded one, or `supermarket + restore `: checked (integrity, schema not newer), the current + database backed up first, then swapped in and the app restarted. + `supermarket backup --with-secrets` for moving machines. +3. **Inbound lead forms.** The sites' `form` sections post to EspoCRM's own + lead capture (Supermarket is local-only, so it can't take the posts + itself), with the buying signal from the page's campaign tag. Supermarket + sets the capture up, puts its address in the site's settings by pull + request, and counts the leads in the funnel. +4. **The LinkedIn company page.** As designed under Future enhancements, + item 1: the second app's keys, choosing the page, and posting as the + page or the profile per draft. Built against LinkedIn's documented API; + used for real once LinkedIn approves the app. +5. **New sites from a shared theme.** A Hugo theme of sections common to + federated-website and webcoredesktop, and creating a new site from it: + a new Gitea repository, a first set of pages built by Part 3 of Phase 5, + and a preview. Planned in detail when it starts. + +**Part 1 built (2026-11-22; no schema change).** `internal/backup` makes +backups with `VACUUM INTO` (to a `.part` file, then renamed; mode 0600) +into `/backups`, named `app---[-].db` +(kinds: manual, migration, daily, restore, legacy). `db.BeforeMigrate` +backs up an existing database before any pending migration +(`before-schema-`; a failed backup stops the migration); a new database +isn't backed up. The app makes the daily backup at start and then hourly +checks whether one is due, pruning dailies to the newest 7 plus the newest +of each of the 4 weeks before. Settings → Backups lists them (when, why, +size, schema; unreadable files are flagged), makes one with a note, +downloads and deletes; only names from the list are served. `supermarket +backup [note]` and `supermarket backups` run the binary in the container +with `docker exec`; it opens the database beside the app without +migrating it. On start, the old `app.db.pre-*` copies are moved in as +*legacy* backups dated by their file time, with any `-wal` folded in +first; one that fails the integrity check is left in place. Live: all 23 +moved. Some show an older schema than the database had when they were +taken (pre-phase5-part5 is at 22, not 23): plain `cp` missed writes still +in the WAL, as feared. The live database is 60 MB (mostly Stripe objects), +so the backups folder holds about 620 MB; old legacy copies can be deleted +from the page. + ### Future enhancements Not in any phase yet; picked up when the user asks. -1. **Post to the LinkedIn company page** (deferred 2026-11-21). Today posts +1. **Post to the LinkedIn company page** (deferred 2026-11-21; Phase 6, + part 4). Today posts go to the signed-in member's profile (`w_member_social`). Posting as the Federated Computer page needs LinkedIn's **Community Management API**, which LinkedIn approves by hand. @@ -1374,7 +1429,7 @@ Not in any phase yet; picked up when the user asks. and .../community-management/community-management-overview. 2. **Back up the database and restore from a backup** (asked for - 2026-11-21). Today backups are copies made by hand before risky changes + 2026-11-21; Phase 6, parts 1 and 2). Today backups are copies made by hand before risky changes (`app.db.pre-phase1`, `app.db.pre-dedupe`, …) in the data folder. A plain `cp` of a running database in WAL mode can miss recent writes, so backups must use SQLite's own backup (`VACUUM INTO` or the online backup @@ -1452,7 +1507,9 @@ Phase 0 (incl. Hermes bridge test) ──► Phase 1 (content) │ mail on the Core, Plausible, Stripe key ├──► Phase 3 (SEO) ──────── needs: Google OAuth (Search Console), Gitea token ├──► Phase 4 (metrics) ──── needs: Stripe key; CRM reads for pipeline - └──► Phase 5 (sites) ────── needs: Gitea token + ├──► Phase 5 (sites) ────── needs: Gitea token + └──► Phase 6 (backups; lead forms ─ needs: EspoCRM lead capture; + LinkedIn page ─ needs: LinkedIn's approval; new sites) ``` Phases 1, 3, 5 and the Stripe half of 4 depend only on Phase 0. diff --git a/TEST.md b/TEST.md index 33c0b85..28f5c86 100644 --- a/TEST.md +++ b/TEST.md @@ -97,6 +97,25 @@ Throughout, also notice: saves and is used. - [ ] With an OpenAI-compatible server, *List its models* lists them. +### Backups + +- [ ] Settings → Backups lists the backups, newest first, with when, why + (by you, daily, before an update, before a restore, an older copy), + size and schema. +- [ ] *Back up now* with a note adds one at the top, named with the note. +- [ ] *Download* saves a file that opens with `sqlite3` (`.tables` lists + Supermarket's tables); there's no `secrets.json` content in it. +- [ ] *Delete* asks first, then removes it from the list and the folder. +- [ ] A daily backup appears once a day while the app runs, never twice + on one day; after more than a week, older dailies thin out to one a + week. +- [ ] Updating Supermarket to a version with a database change makes a + "Before an update" backup first. +- [ ] `supermarket backup "a note"` and `supermarket backups` work from a + terminal; with the app stopped they say to start it. +- [ ] The old `app.db.pre-*` files are gone from the data folder and listed + as "An older copy". + ## 4. Inventory - [ ] Add a partner and a competitor by hand, with websites, feeds, X diff --git a/bin/supermarket b/bin/supermarket index c843f05..83b56e8 100755 --- a/bin/supermarket +++ b/bin/supermarket @@ -19,6 +19,8 @@ Usage: supermarket [command] hermes Set up, or repair, Hermes' connection to your Core's MCP hub token Print the token agents use to reach Supermarket's MCP endpoint data Print where its data is kept + backup [note] Back up the database now (it also backs up daily) + backups List the backups Updates come with CoreDesktop's \`update\`. EOF @@ -57,6 +59,13 @@ case "${1:-open}" in logs) compose logs -f --tail 200 ;; hermes) shift; bash "$REPO/hermes/setup.sh" "$@" ;; token) cat "$DATA/mcp-token" ;; + backup|backups) + if ! docker exec supermarket true 2> /dev/null; then + echo "Supermarket isn't running: start it first (supermarket start)." + exit 1 + fi + docker exec supermarket supermarket "$@" + ;; data) echo "$DATA" ;; -h|--help|help) usage ;; *) usage; exit 1 ;; diff --git a/cmd/supermarket/main.go b/cmd/supermarket/main.go index ac71c2f..7bed21e 100644 --- a/cmd/supermarket/main.go +++ b/cmd/supermarket/main.go @@ -15,6 +15,7 @@ package main import ( "context" "crypto/rand" + "database/sql" "encoding/hex" "errors" "fmt" @@ -28,6 +29,7 @@ import ( "time" "supermarket/internal/ai" + "supermarket/internal/backup" "supermarket/internal/content" "supermarket/internal/core" "supermarket/internal/crm" @@ -47,6 +49,13 @@ func main() { fmt.Println(version) return } + if len(os.Args) > 1 && (os.Args[1] == "backup" || os.Args[1] == "backups") { + if err := backupCommand(os.Args[1], os.Args[2:]); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + return + } log := slog.New(slog.NewTextHandler(os.Stdout, nil)) if err := run(log); err != nil { log.Error("stopped", "err", err) @@ -76,6 +85,19 @@ func run(log *slog.Logger) error { if err := os.MkdirAll(dataDir, 0700); err != nil { return err } + // Old hand-made copies (app.db.pre-*) join the backups. + if n := backup.AdoptLegacy(dataDir, func(name string, err error) { + log.Warn("backups: an old copy was left where it is", "file", name, "err", err) + }); n > 0 { + log.Info("backups: moved old copies into the backups folder", "count", n) + } + db.BeforeMigrate = func(d *sql.DB, from, to int) error { + b, err := backup.Make(d, backup.Dir(dataDir), backup.Migration, fmt.Sprintf("before-schema-%d", to), time.Now()) + if err == nil { + log.Info("backups: backed up before migrating", "from", from, "to", to, "file", b.Name) + } + return err + } database, err := db.Open(filepath.Join(dataDir, "app.db")) if err != nil { return err @@ -162,6 +184,7 @@ func run(log *slog.Logger) error { go srv.RunTracking(ctx) go srv.RunSEO(ctx) go srv.RunMetrics(ctx) + go srv.RunBackups(ctx) // A sync falls due, and a claim times out, without anything being // written: refresh the state file each minute. go func() { @@ -220,3 +243,45 @@ func mcpToken(path string) (string, error) { } return t, nil } + +// backupCommand runs `supermarket backup [note]` and `supermarket backups` +// (inside the container: the host's command runs them with docker exec). +// It reads the database beside the running app, which WAL allows; it +// never migrates it. +func backupCommand(cmd string, args []string) error { + dataDir := env("SUPERMARKET_DATA", "/data") + dir := backup.Dir(dataDir) + if cmd == "backups" { + bs, err := backup.List(dir) + if err != nil { + return err + } + if len(bs) == 0 { + fmt.Println("No backups yet.") + return nil + } + for _, b := range bs { + schema := fmt.Sprintf("schema %d", b.Schema) + if b.Schema < 0 { + schema = "unreadable" + } + fmt.Printf("%-60s %8.1f MB %s\n", b.Name, float64(b.Size)/(1<<20), schema) + } + return nil + } + path := filepath.Join(dataDir, "app.db") + if _, err := os.Stat(path); err != nil { + return fmt.Errorf("no database at %s", path) + } + d, err := sql.Open("sqlite", "file:"+path+"?_pragma=busy_timeout(10000)") + if err != nil { + return err + } + defer d.Close() + b, err := backup.Make(d, dir, backup.Manual, strings.Join(args, " "), time.Now()) + if err != nil { + return err + } + fmt.Printf("Backed up to %s (%.1f MB)\n", b.Name, float64(b.Size)/(1<<20)) + return nil +} diff --git a/internal/backup/backup.go b/internal/backup/backup.go new file mode 100644 index 0000000..b4c6f37 --- /dev/null +++ b/internal/backup/backup.go @@ -0,0 +1,386 @@ +// Package backup makes and keeps copies of Supermarket's database. Each +// backup is one consistent SQLite file made with SQLite's own VACUUM INTO, +// so it's safe while the app is writing (a plain copy of a database in WAL +// mode can miss recent writes). Secrets aren't in the database, so they're +// never in a backup. +// +// Backups live in /backups, named +// app---[-].db, so the folder alone says what +// each one is. +package backup + +import ( + "database/sql" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "time" + + _ "modernc.org/sqlite" +) + +// Kinds of backup. +const ( + Manual = "manual" // made by the user + Migration = "migration" // made before a schema migration + Daily = "daily" // made once a day + Restore = "restore" // made before a restore + Legacy = "legacy" // an old hand-made app.db.pre-* copy +) + +// Kept says whether a kind is kept until the user deletes it. +func Kept(kind string) bool { return kind != Daily } + +// Backup is one backup file. +type Backup struct { + Name string + Path string + At time.Time + Kind string + Note string + Size int64 + Schema int // the database's schema version; -1 if it can't be read + Err string // why it can't be read, if it can't +} + +// Dir is where a data folder's backups go. +func Dir(dataDir string) string { return filepath.Join(dataDir, "backups") } + +var ( + nameRe = regexp.MustCompile(`^app-(\d{8})-(\d{6})-(manual|migration|daily|restore|legacy)(?:-([a-z0-9-]+))?\.db$`) + nonSlug = regexp.MustCompile(`[^a-z0-9]+`) + stampFmt = "20060102-150405" +) + +// Slug makes a note fit a file name: "Before the big import!" becomes +// "before-the-big-import". +func Slug(note string) string { + s := strings.Trim(nonSlug.ReplaceAllString(strings.ToLower(note), "-"), "-") + if len(s) > 60 { + s = strings.TrimRight(s[:60], "-") + } + return s +} + +// Parse reads a backup's name; ok is false for files that aren't backups. +func Parse(name string) (b Backup, ok bool) { + m := nameRe.FindStringSubmatch(name) + if m == nil { + return b, false + } + at, err := time.ParseInLocation(stampFmt, m[1]+"-"+m[2], time.Local) + if err != nil { + return b, false + } + return Backup{Name: name, At: at, Kind: m[3], Note: m[4]}, true +} + +func fileName(at time.Time, kind, note string) string { + n := "app-" + at.Format(stampFmt) + "-" + kind + if s := Slug(note); s != "" { + n += "-" + s + } + return n + ".db" +} + +// Make backs up the open database into dir. +func Make(d *sql.DB, dir, kind, note string, now time.Time) (*Backup, error) { + if err := os.MkdirAll(dir, 0o700); err != nil { + return nil, err + } + name := fileName(now, kind, note) + for n := 2; ; n++ { + if _, err := os.Stat(filepath.Join(dir, name)); errors.Is(err, os.ErrNotExist) { + break + } + name = fileName(now.Add(time.Duration(n-1)*time.Second), kind, note) + } + path := filepath.Join(dir, name) + tmp := filepath.Join(dir, "."+name+".part") + os.Remove(tmp) + if _, err := d.Exec(`VACUUM INTO ?`, tmp); err != nil { + os.Remove(tmp) + return nil, fmt.Errorf("backing up: %w", err) + } + if err := os.Chmod(tmp, 0o600); err != nil { + os.Remove(tmp) + return nil, err + } + if err := os.Rename(tmp, path); err != nil { + os.Remove(tmp) + return nil, err + } + b, _ := Parse(name) + b.Path = path + b.read() + return &b, nil +} + +// read fills in the size and schema. +func (b *Backup) read() { + if st, err := os.Stat(b.Path); err == nil { + b.Size = st.Size() + } + b.Schema = -1 + v, err := SchemaOf(b.Path) + if err != nil { + b.Err = err.Error() + return + } + b.Schema = v +} + +// open opens a database file read-only, without touching it. +func open(path string) (*sql.DB, error) { + d, err := sql.Open("sqlite", "file:"+path+"?mode=ro&_pragma=busy_timeout(5000)") + if err != nil { + return nil, err + } + d.SetMaxOpenConns(1) + return d, nil +} + +// SchemaOf reads a database file's schema version. +func SchemaOf(path string) (int, error) { + d, err := open(path) + if err != nil { + return 0, err + } + defer d.Close() + var v int + if err := d.QueryRow(`PRAGMA user_version`).Scan(&v); err != nil { + return 0, fmt.Errorf("not a database Supermarket can read: %w", err) + } + return v, nil +} + +// Check checks a database file: SQLite's integrity check, and that it's a +// Supermarket database (it has the settings table). +func Check(path string) error { + d, err := open(path) + if err != nil { + return err + } + defer d.Close() + var res string + if err := d.QueryRow(`PRAGMA integrity_check`).Scan(&res); err != nil { + return fmt.Errorf("not a database Supermarket can read: %w", err) + } + if res != "ok" { + return fmt.Errorf("the database is damaged: %s", res) + } + var n int + if err := d.QueryRow(`SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = 'settings'`).Scan(&n); err != nil || n == 0 { + return errors.New("that isn't a Supermarket database") + } + return nil +} + +// List lists the backups in dir, newest first. +func List(dir string) ([]Backup, error) { + entries, err := os.ReadDir(dir) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + var out []Backup + for _, e := range entries { + b, ok := Parse(e.Name()) + if !ok || e.IsDir() { + continue + } + b.Path = filepath.Join(dir, e.Name()) + b.read() + out = append(out, b) + } + sort.Slice(out, func(i, j int) bool { + if !out[i].At.Equal(out[j].At) { + return out[i].At.After(out[j].At) + } + return out[i].Name > out[j].Name + }) + return out, nil +} + +// Find finds a backup by name; only names from the list are accepted. +func Find(dir, name string) (*Backup, error) { + bs, err := List(dir) + if err != nil { + return nil, err + } + for i := range bs { + if bs[i].Name == name { + return &bs[i], nil + } + } + return nil, os.ErrNotExist +} + +// Delete deletes a backup. +func Delete(dir, name string) error { + b, err := Find(dir, name) + if err != nil { + return err + } + return os.Remove(b.Path) +} + +// Keep says which daily backups to keep: the newest 7, then the newest of +// each of the 4 weeks before them. Other kinds are always kept. +func Keep(bs []Backup) map[string]bool { + keep := map[string]bool{} + var daily []Backup + for _, b := range bs { + if Kept(b.Kind) { + keep[b.Name] = true + } else { + daily = append(daily, b) + } + } + sort.Slice(daily, func(i, j int) bool { return daily[i].At.After(daily[j].At) }) + weeks := map[string]bool{} + for i, b := range daily { + if i < 7 { + keep[b.Name] = true + continue + } + y, w := b.At.ISOWeek() + wk := fmt.Sprintf("%d-%02d", y, w) + if len(weeks) < 4 && !weeks[wk] { + weeks[wk] = true + keep[b.Name] = true + } + } + return keep +} + +// Prune deletes the daily backups Keep doesn't keep. +func Prune(dir string) (int, error) { + bs, err := List(dir) + if err != nil { + return 0, err + } + keep := Keep(bs) + n := 0 + for _, b := range bs { + if !keep[b.Name] { + if err := os.Remove(b.Path); err != nil { + return n, err + } + n++ + } + } + return n, nil +} + +// DueDaily says whether today's daily backup hasn't been made yet. +func DueDaily(dir string, now time.Time) (bool, error) { + bs, err := List(dir) + if err != nil { + return false, err + } + today := now.Format("20060102") + for _, b := range bs { + if b.Kind == Daily && b.At.Format("20060102") == today { + return false, nil + } + } + return true, nil +} + +// AdoptLegacy moves the old hand-made copies (app.db.pre-) from the +// data folder into the backups, as legacy backups dated by when they were +// made. A copy taken with its -wal file has it folded in first; each copy +// is checked before its leftovers are removed, and one that fails the +// check is left where it is. It returns how many it moved. +func AdoptLegacy(dataDir string, log func(string, error)) int { + matches, _ := filepath.Glob(filepath.Join(dataDir, "app.db.pre-*")) + dir := Dir(dataDir) + moved := 0 + for _, path := range matches { + base := filepath.Base(path) + if strings.HasSuffix(base, "-wal") || strings.HasSuffix(base, "-shm") { + continue + } + st, err := os.Stat(path) // when it was made, before folding in changes it + if err != nil { + log(base, err) + continue + } + if _, err := os.Stat(path + "-wal"); err == nil { + if err := checkpoint(path); err != nil { + log(base, err) + continue + } + } + if err := Check(path); err != nil { + log(base, err) + continue + } + if err := os.MkdirAll(dir, 0o700); err != nil { + log(base, err) + return moved + } + name := fileName(st.ModTime(), Legacy, strings.TrimPrefix(base, "app.db.pre-")) + if _, err := os.Stat(filepath.Join(dir, name)); err == nil { + log(base, errors.New("a backup with its name is already there")) + continue + } + if err := moveFile(path, filepath.Join(dir, name)); err != nil { + log(base, err) + continue + } + os.Remove(path + "-wal") + os.Remove(path + "-shm") + moved++ + } + return moved +} + +// checkpoint folds a copy's -wal file into it. +func checkpoint(path string) error { + d, err := sql.Open("sqlite", "file:"+path+"?_pragma=busy_timeout(5000)") + if err != nil { + return err + } + defer d.Close() + d.SetMaxOpenConns(1) + if _, err := d.Exec(`PRAGMA wal_checkpoint(TRUNCATE)`); err != nil { + return fmt.Errorf("folding in its -wal file: %w", err) + } + _, err = d.Exec(`PRAGMA journal_mode = DELETE`) + return err +} + +// moveFile renames, or copies and removes across file systems. +func moveFile(from, to string) error { + if err := os.Rename(from, to); err == nil { + return nil + } + in, err := os.Open(from) + if err != nil { + return err + } + defer in.Close() + out, err := os.OpenFile(to, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) + if err != nil { + return err + } + if _, err := io.Copy(out, in); err != nil { + out.Close() + os.Remove(to) + return err + } + if err := out.Close(); err != nil { + os.Remove(to) + return err + } + return os.Remove(from) +} diff --git a/internal/backup/backup_test.go b/internal/backup/backup_test.go new file mode 100644 index 0000000..15c7749 --- /dev/null +++ b/internal/backup/backup_test.go @@ -0,0 +1,192 @@ +package backup + +import ( + "database/sql" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func newDB(t *testing.T, path string) *sql.DB { + t.Helper() + d, err := sql.Open("sqlite", "file:"+path+"?_pragma=journal_mode(WAL)") + if err != nil { + t.Fatal(err) + } + d.SetMaxOpenConns(1) + for _, q := range []string{`CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT)`, `INSERT INTO settings VALUES ('a', '1')`, `PRAGMA user_version = 7`} { + if _, err := d.Exec(q); err != nil { + t.Fatal(err) + } + } + return d +} + +func TestMakeListFind(t *testing.T) { + dir := t.TempDir() + d := newDB(t, filepath.Join(dir, "app.db")) + defer d.Close() + bdir := Dir(dir) + now := time.Date(2026, 11, 22, 18, 30, 5, 0, time.Local) + b, err := Make(d, bdir, Manual, "Before the big import!", now) + if err != nil { + t.Fatal(err) + } + if b.Name != "app-20261122-183005-manual-before-the-big-import.db" || b.Schema != 7 || b.Size == 0 || b.Note != "before-the-big-import" { + t.Errorf("made: %+v", b) + } + if st, _ := os.Stat(b.Path); st.Mode().Perm() != 0o600 { + t.Errorf("mode: %v", st.Mode()) + } + // Written after the backup: not in it. + d.Exec(`INSERT INTO settings VALUES ('b', '2')`) + cp, _ := sql.Open("sqlite", "file:"+b.Path+"?mode=ro") + var n int + cp.QueryRow(`SELECT count(*) FROM settings`).Scan(&n) + cp.Close() + if n != 1 { + t.Errorf("rows in the backup: %d", n) + } + if err := Check(b.Path); err != nil { + t.Errorf("check: %v", err) + } + // Same second: a different name. + b2, err := Make(d, bdir, Manual, "Before the big import!", now) + if err != nil || b2.Name == b.Name { + t.Errorf("second: %v %v", b2, err) + } + daily, _ := Make(d, bdir, Daily, "", now.Add(time.Hour)) + os.WriteFile(filepath.Join(bdir, "notes.txt"), []byte("x"), 0o600) + os.WriteFile(filepath.Join(bdir, "app-20261101-000000-manual.db"), []byte("not a database"), 0o600) + bs, err := List(bdir) + if err != nil || len(bs) != 4 || bs[0].Name != daily.Name || bs[3].Schema != -1 || bs[3].Err == "" { + t.Fatalf("list: %+v %v", bs, err) + } + if err := Check(bs[3].Path); err == nil { + t.Error("a bad file passed the check") + } + if _, err := Find(bdir, "../app.db"); err == nil { + t.Error("found a file outside the list") + } + if err := Delete(bdir, daily.Name); err != nil { + t.Fatal(err) + } + if due, _ := DueDaily(bdir, now.Add(2*time.Hour)); !due { + t.Error("not due after deleting today's") + } + Make(d, bdir, Daily, "", now.Add(3*time.Hour)) + if due, _ := DueDaily(bdir, now.Add(4*time.Hour)); due { + t.Error("due twice in a day") + } + if due, _ := DueDaily(bdir, now.Add(24*time.Hour)); !due { + t.Error("not due the next day") + } +} + +func TestCheckNotSupermarket(t *testing.T) { + path := filepath.Join(t.TempDir(), "other.db") + d, _ := sql.Open("sqlite", "file:"+path) + d.Exec(`CREATE TABLE x (y)`) + d.Close() + if err := Check(path); err == nil || !strings.Contains(err.Error(), "isn't a Supermarket database") { + t.Errorf("check: %v", err) + } +} + +func TestKeep(t *testing.T) { + var bs []Backup + start := time.Date(2026, 9, 1, 3, 0, 0, 0, time.Local) + for i := 0; i < 60; i++ { // 60 days of dailies + at := start.AddDate(0, 0, i) + bs = append(bs, Backup{Name: fileName(at, Daily, ""), At: at, Kind: Daily}) + } + bs = append(bs, Backup{Name: "m", At: start, Kind: Manual}, Backup{Name: "g", At: start, Kind: Migration}) + keep := Keep(bs) + var kept []string + for _, b := range bs { + if keep[b.Name] && b.Kind == Daily { + kept = append(kept, b.At.Format("01-02")) + } + } + // The newest 7 days, then the newest of each of 4 earlier weeks. + if len(kept) != 11 || !keep["m"] || !keep["g"] { + t.Errorf("kept %d dailies: %v", len(kept), kept) + } + last := start.AddDate(0, 0, 59) + for i := 0; i < 7; i++ { + if !keep[fileName(last.AddDate(0, 0, -i), Daily, "")] { + t.Errorf("day %d not kept", i) + } + } +} + +func TestPrune(t *testing.T) { + dir := t.TempDir() + d := newDB(t, filepath.Join(dir, "app.db")) + defer d.Close() + bdir := Dir(dir) + start := time.Date(2026, 10, 1, 3, 0, 0, 0, time.Local) + for i := 0; i < 20; i++ { + if _, err := Make(d, bdir, Daily, "", start.AddDate(0, 0, i)); err != nil { + t.Fatal(err) + } + } + Make(d, bdir, Manual, "keep me", start) + n, err := Prune(bdir) + bs, _ := List(bdir) + if err != nil || n+len(bs) != 21 || len(bs) > 12 || !strings.Contains(bs[len(bs)-1].Name, "keep-me") { + t.Errorf("pruned %d, left %d: %v", n, len(bs), err) + } +} + +func TestAdoptLegacy(t *testing.T) { + dir := t.TempDir() + // A copy taken with its -wal: its last rows are only in the -wal. + src := filepath.Join(t.TempDir(), "src.db") + d := newDB(t, src) + d.Exec(`PRAGMA wal_autocheckpoint = 0`) + d.Exec(`INSERT INTO settings VALUES ('only-in-wal', 'x')`) + for _, suffix := range []string{"", "-wal", "-shm"} { + raw, err := os.ReadFile(src + suffix) + if err != nil { + t.Fatal(err) + } + os.WriteFile(filepath.Join(dir, "app.db.pre-phase2-part3"+suffix), raw, 0o600) + } + d.Close() + // A broken one. + os.WriteFile(filepath.Join(dir, "app.db.pre-broken"), []byte("junk"), 0o600) + when := time.Date(2026, 11, 20, 9, 15, 0, 0, time.Local) + os.Chtimes(filepath.Join(dir, "app.db.pre-phase2-part3"), when, when) + + var problems []string + n := AdoptLegacy(dir, func(name string, err error) { problems = append(problems, name+": "+err.Error()) }) + if n != 1 || len(problems) != 1 || !strings.HasPrefix(problems[0], "app.db.pre-broken") { + t.Fatalf("moved %d; problems %v", n, problems) + } + bs, _ := List(Dir(dir)) + if len(bs) != 1 || bs[0].Kind != Legacy || bs[0].Note != "phase2-part3" || !bs[0].At.Equal(when) { + t.Fatalf("adopted: %+v", bs) + } + cp, _ := sql.Open("sqlite", "file:"+bs[0].Path+"?mode=ro") + var v string + err := cp.QueryRow(`SELECT value FROM settings WHERE key = 'only-in-wal'`).Scan(&v) + cp.Close() + if err != nil { + t.Errorf("the -wal's rows were lost: %v", err) + } + for _, f := range []string{"app.db.pre-phase2-part3", "app.db.pre-phase2-part3-wal", "app.db.pre-phase2-part3-shm"} { + if _, err := os.Stat(filepath.Join(dir, f)); err == nil { + t.Errorf("%s is still there", f) + } + } + if _, err := os.Stat(filepath.Join(dir, "app.db.pre-broken")); err != nil { + t.Error("the broken copy was moved") + } + // Running again does nothing more. + if n := AdoptLegacy(dir, func(string, error) {}); n != 0 { + t.Errorf("second run moved %d", n) + } +} diff --git a/internal/db/db.go b/internal/db/db.go index fa735e1..e98ecdd 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -618,6 +618,14 @@ type DB struct { } // Open opens (creating if needed) the database at path and migrates it. +// BeforeMigrate, if set, runs before an existing database is migrated to +// a newer schema (from and to are the schema versions): the app backs it +// up. A new, empty database isn't backed up. +var BeforeMigrate func(d *sql.DB, from, to int) error + +// Schema is the schema version this build migrates databases to. +func Schema() int { return len(migrations) } + func Open(path string) (*DB, error) { // WAL lets the web UI read while a background job writes; busy_timeout // waits out short write locks instead of failing. @@ -634,6 +642,19 @@ func Open(path string) (*DB, error) { return nil, fmt.Errorf("opening %s: %w", path, err) } d := &DB{sqldb} + if BeforeMigrate != nil { + var version int + if err := d.QueryRow(`PRAGMA user_version`).Scan(&version); err != nil { + sqldb.Close() + return nil, err + } + if version > 0 && version < len(migrations) { + if err := BeforeMigrate(sqldb, version, len(migrations)); err != nil { + sqldb.Close() + return nil, fmt.Errorf("backing up before migrating to schema %d: %w", len(migrations), err) + } + } + } if err := d.migrate(); err != nil { sqldb.Close() return nil, err diff --git a/internal/db/migrate_hook_test.go b/internal/db/migrate_hook_test.go new file mode 100644 index 0000000..b8f09b3 --- /dev/null +++ b/internal/db/migrate_hook_test.go @@ -0,0 +1,61 @@ +package db + +import ( + "database/sql" + "errors" + "fmt" + "path/filepath" + "strings" + "testing" +) + +func TestBeforeMigrate(t *testing.T) { + defer func() { BeforeMigrate = nil }() + var calls []string + BeforeMigrate = func(d *sql.DB, from, to int) error { + var n int + d.QueryRow(`PRAGMA user_version`).Scan(&n) + calls = append(calls, fmt.Sprintf("%d→%d at %d", from, to, n)) + return nil + } + dir := t.TempDir() + // A new database: nothing to back up. + d, err := Open(filepath.Join(dir, "new.db")) + if err != nil { + t.Fatal(err) + } + d.Close() + // Already current: nothing either. + d, _ = Open(filepath.Join(dir, "new.db")) + d.Close() + if len(calls) != 0 { + t.Fatalf("called for a new or current database: %v", calls) + } + // One migration behind: backed up first, before the migration runs. + old := filepath.Join(dir, "old.db") + raw, _ := sql.Open("sqlite", "file:"+old) + for _, m := range migrations[:len(migrations)-1] { + if _, err := raw.Exec(m); err != nil { + t.Fatal(err) + } + } + raw.Exec(fmt.Sprintf(`PRAGMA user_version = %d`, len(migrations)-1)) + raw.Close() + d, err = Open(old) + if err != nil { + t.Fatal(err) + } + d.Close() + want := fmt.Sprintf("%d→%d at %d", len(migrations)-1, len(migrations), len(migrations)-1) + if len(calls) != 1 || calls[0] != want || Schema() != len(migrations) { + t.Errorf("calls: %v, want %s", calls, want) + } + // A failed backup stops the migration. + raw, _ = sql.Open("sqlite", "file:"+old) + raw.Exec(fmt.Sprintf(`PRAGMA user_version = %d`, len(migrations)-1)) + raw.Close() + BeforeMigrate = func(*sql.DB, int, int) error { return errors.New("disk full") } + if _, err := Open(old); err == nil || !strings.Contains(err.Error(), "disk full") { + t.Errorf("open: %v", err) + } +} diff --git a/internal/web/backups.go b/internal/web/backups.go new file mode 100644 index 0000000..23c7b62 --- /dev/null +++ b/internal/web/backups.go @@ -0,0 +1,118 @@ +package web + +import ( + "context" + "errors" + "net/http" + "os" + "path/filepath" + "time" + + "supermarket/internal/backup" + "supermarket/internal/db" +) + +func (s *Server) backupDir() string { return backup.Dir(s.DataDir) } + +// RunBackups makes the daily backup, and prunes old dailies, while the app +// runs. +func (s *Server) RunBackups(ctx context.Context) { + tick := time.NewTicker(time.Hour) + defer tick.Stop() + for { + s.dailyBackup(time.Now()) + select { + case <-ctx.Done(): + return + case <-tick.C: + } + } +} + +func (s *Server) dailyBackup(now time.Time) { + due, err := backup.DueDaily(s.backupDir(), now) + if err != nil { + s.Log.Warn("backups: listing", "err", err) + return + } + if !due { + return + } + if _, err := backup.Make(s.DB.DB, s.backupDir(), backup.Daily, "", now); err != nil { + s.Log.Error("backups: the daily backup failed", "err", err) + return + } + if n, err := backup.Prune(s.backupDir()); err != nil { + s.Log.Warn("backups: pruning", "err", err) + } else if n > 0 { + s.Log.Info("backups: removed old daily backups", "count", n) + } +} + +func (s *Server) backupsPage(w http.ResponseWriter, r *http.Request) { + s.renderBackups(w, r, "", "") +} + +func (s *Server) renderBackups(w http.ResponseWriter, r *http.Request, errMsg, flash string) { + bs, err := backup.List(s.backupDir()) + if err != nil { + s.serverError(w, err) + return + } + var total int64 + for _, b := range bs { + total += b.Size + } + keep := backup.Keep(bs) + hostDir := s.backupDir() + if s.MCPSocket != "" { // the data folder's path on the host + hostDir = filepath.Join(filepath.Dir(s.MCPSocket), "backups") + } + s.render(w, r, "backups", page{Title: "Backups", Nav: "settings/backups", Error: errMsg, Flash: flash, Data: map[string]any{ + "Backups": bs, "Total": total, "Keep": keep, "Schema": db.Schema(), "Dir": hostDir, + }}) +} + +func (s *Server) backupsAction(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + switch r.PathValue("action") { + case "now": + b, err := backup.Make(s.DB.DB, s.backupDir(), backup.Manual, r.PostFormValue("note"), time.Now()) + if err != nil { + s.renderBackups(w, r, err.Error(), "") + return + } + s.renderBackups(w, r, "", "Backed up to "+b.Name+".") + case "delete": + name := r.PostFormValue("name") + if err := backup.Delete(s.backupDir(), name); err != nil { + if errors.Is(err, os.ErrNotExist) { + s.renderBackups(w, r, "There's no backup called "+name+".", "") + return + } + s.serverError(w, err) + return + } + s.renderBackups(w, r, "", "Deleted "+name+".") + default: + http.NotFound(w, r) + } +} + +// backupDownload sends a backup file. It holds contacts and the app's +// data (not its secrets), so it's served to this machine only, like +// everything else here. +func (s *Server) backupDownload(w http.ResponseWriter, r *http.Request) { + b, err := backup.Find(s.backupDir(), r.PathValue("name")) + if err != nil { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "application/vnd.sqlite3") + w.Header().Set("Content-Disposition", `attachment; filename="`+b.Name+`"`) + w.Header().Set("Cache-Control", "no-store") + http.ServeFile(w, r, b.Path) +} diff --git a/internal/web/backups_test.go b/internal/web/backups_test.go new file mode 100644 index 0000000..e05deb8 --- /dev/null +++ b/internal/web/backups_test.go @@ -0,0 +1,54 @@ +package web + +import ( + "net/http" + "net/url" + "os" + "strings" + "testing" + "time" + + "supermarket/internal/backup" +) + +func TestBackupsPage(t *testing.T) { + s, h := newTestServer(t, nil) + if body := do(h, http.MethodGet, "/settings/backups", nil, nil).Body.String(); !strings.Contains(body, "No backups yet") { + t.Errorf("empty: %s", body) + } + body := postForm(h, "/settings/backups/now", url.Values{"note": {"Before the import"}}).Body.String() + if !strings.Contains(body, "Backed up to app-") || !strings.Contains(body, "-manual-before-the-import.db") || + !strings.Contains(body, "By you") || !strings.Contains(body, "before-the-import") { + t.Errorf("after backing up: %s", body) + } + bs, _ := backup.List(s.backupDir()) + if len(bs) != 1 { + t.Fatalf("backups: %v", bs) + } + rec := do(h, http.MethodGet, "/settings/backups/file/"+bs[0].Name, nil, nil) + if rec.Code != http.StatusOK || !strings.HasPrefix(rec.Body.String(), "SQLite format 3") || + !strings.Contains(rec.Header().Get("Content-Disposition"), bs[0].Name) { + t.Errorf("download: %d %v", rec.Code, rec.Header()) + } + for _, bad := range []string{"..%2Fapp.db", "secrets.json", "app.db"} { + if rec := do(h, http.MethodGet, "/settings/backups/file/"+bad, nil, nil); rec.Code != http.StatusNotFound { + t.Errorf("%s: %d", bad, rec.Code) + } + } + // The daily one, once a day. + s.dailyBackup(time.Now()) + s.dailyBackup(time.Now()) + if bs, _ := backup.List(s.backupDir()); len(bs) != 2 { + t.Errorf("after the daily: %d", len(bs)) + } + body = postForm(h, "/settings/backups/delete", url.Values{"name": {bs[0].Name}}).Body.String() + if !strings.Contains(body, "Deleted "+bs[0].Name) { + t.Errorf("delete: %s", body) + } + if _, err := os.Stat(bs[0].Path); err == nil { + t.Error("still there") + } + if body := postForm(h, "/settings/backups/delete", url.Values{"name": {"../app.db"}}).Body.String(); !strings.Contains(body, "There's no backup called") { + t.Errorf("bad delete: %s", body) + } +} diff --git a/internal/web/server.go b/internal/web/server.go index 53b7435..b7f2081 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -230,6 +230,9 @@ func (s *Server) Handler() (http.Handler, error) { mux.HandleFunc("POST /crm/{action}", s.crmAction) mux.HandleFunc("POST /crm/{id}/{action}", s.crmAction) + mux.HandleFunc("GET /settings/backups", s.backupsPage) + mux.HandleFunc("POST /settings/backups/{action}", s.backupsAction) + mux.HandleFunc("GET /settings/backups/file/{name}", s.backupDownload) mux.HandleFunc("GET /settings/core", s.corePage) mux.HandleFunc("GET /settings/core/checks", s.coreChecks) @@ -300,6 +303,19 @@ func sameOrigin(r *http.Request) bool { return false } +// humanBytes is a file size for people: "840 KB", "12.3 MB". +func humanBytes(n int64) string { + switch { + case n >= 1<<30: + return fmt.Sprintf("%.1f GB", float64(n)/(1<<30)) + case n >= 1<<20: + return fmt.Sprintf("%.1f MB", float64(n)/(1<<20)) + case n >= 1<<10: + return fmt.Sprintf("%d KB", n>>10) + } + return fmt.Sprintf("%d bytes", n) +} + var backticks = regexp.MustCompile("`([^`]+)`") // ticks shows Markdown's `code` spans as code, the rest as plain text. @@ -313,6 +329,7 @@ func (s *Server) loadTemplates() error { "join": strings.Join, "ago": ago, "ticks": ticks, + "bytes": humanBytes, "kindLabel": sites.KindLabel, "add": func(a, b int) int { return a + b }, "hasPrefix": strings.HasPrefix, diff --git a/internal/web/server_test.go b/internal/web/server_test.go index b6181ab..8284728 100644 --- a/internal/web/server_test.go +++ b/internal/web/server_test.go @@ -100,7 +100,7 @@ func TestEveryPageRenders(t *testing.T) { "/settings/ai", "/settings/accounts", "/settings/core", "/static/app.css", "/favicon.ico", "/static/favicon.png", "/static/logo.png", "/static/apple-touch-icon.png", "/search", "/crm", "/search?q=rival", "/search?q=nothing+here", "/static/htmx.min.js", "/healthz", "/content", "/content/1", "/content/1?dismissed=1", "/posts", "/posts?msg=drafted", "/content/scheduled", "/content/published", - "/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines", "/metrics", "/metrics/customers", "/metrics/customers?show=all", "/metrics/spend", "/metrics/clv", "/metrics/clv?view=profit", "/metrics/publish", "/sites", "/sites?site=0", "/sites/previews", "/sites/pages", "/sites/publishing", + "/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines", "/metrics", "/metrics/customers", "/metrics/customers?show=all", "/metrics/spend", "/metrics/clv", "/metrics/clv?view=profit", "/metrics/publish", "/sites", "/sites?site=0", "/sites/previews", "/sites/pages", "/sites/publishing", "/settings/backups", "/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} { rec := do(h, http.MethodGet, path, nil, nil) if rec.Code != http.StatusOK { diff --git a/internal/web/templates/backups.html b/internal/web/templates/backups.html new file mode 100644 index 0000000..2e6274e --- /dev/null +++ b/internal/web/templates/backups.html @@ -0,0 +1,33 @@ +{{define "content"}}{{template "settings-start" .}}{{with .Data}}{{$d := .}} +

Backups

+

Copies of Supermarket's database: your profile, inventory, signals, prospects, drafts, SEO and metrics. Each one is a single SQLite file. Your keys and tokens aren't in them; they stay in secrets.json.

+ +
+

Supermarket backs up by itself once a day, and before every update that changes the database. The last 7 daily backups are kept, plus one a week for 4 weeks. The ones made before an update, before a restore, and the ones you make are kept until you delete them.

+
+ + +
+

They're kept in {{.Dir}}, on this computer. From a terminal: supermarket backup [note] and supermarket backups.

+
+ +{{if .Backups}} +

{{len .Backups}} backup{{if ne (len .Backups) 1}}s{{end}}, {{bytes .Total}} in all. This version of Supermarket is at schema {{.Schema}}.

+
+ + {{range .Backups}} + + + + + + {{end}} +
MadeWhySizeSchema
{{.At.Format "2 Jan 2006, 15:04"}}
{{ago .At}}
{{if eq .Kind "manual"}}By you{{else if eq .Kind "migration"}}Before an update{{else if eq .Kind "daily"}}Daily{{if not (index $d.Keep .Name)}} (next to go){{end}}{{else if eq .Kind "restore"}}Before a restore{{else}}An older copy{{end}}{{with .Note}}
{{.}}{{end}}
{{bytes .Size}}{{if ge .Schema 0}}{{.Schema}}{{else}}unreadable{{end}}
+ Download +
+
+
+{{else}} +

No backups yet. The first daily one is made when Supermarket starts.

+{{end}} +{{end}}{{template "settings-end"}}{{end}} diff --git a/internal/web/templates/layout.html b/internal/web/templates/layout.html index 4595641..f5d82c8 100644 --- a/internal/web/templates/layout.html +++ b/internal/web/templates/layout.html @@ -127,6 +127,8 @@ {{template "icon" "seo"}}Search engines {{template "icon" "ai"}}AI + + {{template "icon" "backups"}}Backups
{{end}} @@ -174,6 +176,7 @@ {{- else if eq . "accounts"}} {{- else if eq . "ai"}} {{- else if eq . "core"}} +{{- else if eq . "backups"}} {{- else if eq . "menu"}} {{- end}}{{end}}