Phase 6 part 1: database backups

Backups with SQLite's VACUUM INTO into <data>/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 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 14:38:23 -07:00
co-authored by Claude Opus 5.5
parent c425f49c93
commit 5313369328
14 changed files with 1039 additions and 4 deletions
+386
View File
@@ -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 <data>/backups, named
// app-<yyyymmdd>-<hhmmss>-<kind>[-<note>].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-<note>) 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)
}
+192
View File
@@ -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)
}
}
+21
View File
@@ -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
+61
View File
@@ -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)
}
}
+118
View File
@@ -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)
}
+54
View File
@@ -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&#39;s no backup called") {
t.Errorf("bad delete: %s", body)
}
}
+17
View File
@@ -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,
+1 -1
View File
@@ -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 {
+33
View File
@@ -0,0 +1,33 @@
{{define "content"}}{{template "settings-start" .}}{{with .Data}}{{$d := .}}
<h2>Backups</h2>
<p class="lede">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 <code>secrets.json</code>.</p>
<section class="card">
<p>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.</p>
<form method="post" action="/settings/backups/now" class="inline-form">
<label>Note <span class="muted">(optional)</span> <input name="note" placeholder="before the big import" maxlength="60"></label>
<button type="submit" data-busy="Backing up…">Back up now</button>
</form>
<p class="small muted">They're kept in <code>{{.Dir}}</code>, on this computer. From a terminal: <code>supermarket backup [note]</code> and <code>supermarket backups</code>.</p>
</section>
{{if .Backups}}
<p class="small">{{len .Backups}} backup{{if ne (len .Backups) 1}}s{{end}}, {{bytes .Total}} in all. This version of Supermarket is at schema {{.Schema}}.</p>
<div class="table-wrap"><table>
<thead><tr><th>Made</th><th>Why</th><th class="num">Size</th><th class="num">Schema</th><th></th></tr></thead>
<tbody>{{range .Backups}}<tr>
<td>{{.At.Format "2 Jan 2006, 15:04"}}<br><span class="small muted">{{ago .At}}</span></td>
<td>{{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)}} <span class="muted">(next to go)</span>{{end}}{{else if eq .Kind "restore"}}Before a restore{{else}}An older copy{{end}}{{with .Note}}<br><span class="small muted">{{.}}</span>{{end}}</td>
<td class="num">{{bytes .Size}}</td>
<td class="num">{{if ge .Schema 0}}{{.Schema}}{{else}}<span class="error-text" title="{{.Err}}">unreadable</span>{{end}}</td>
<td><div class="row-actions">
<a class="button secondary small" href="/settings/backups/file/{{.Name}}" download>Download</a>
<form method="post" action="/settings/backups/delete" data-confirm="Delete the backup from {{.At.Format "2 Jan 2006, 15:04"}}?">
<input type="hidden" name="name" value="{{.Name}}"><button type="submit" class="secondary small">Delete</button></form>
</div></td>
</tr>{{end}}</tbody>
</table></div>
{{else}}
<section class="card empty"><p>No backups yet. The first daily one is made when Supermarket starts.</p></section>
{{end}}
{{end}}{{template "settings-end"}}{{end}}
+3
View File
@@ -127,6 +127,8 @@
<a href="/settings/search" {{if eq .Nav "settings/search"}}aria-current="page"{{end}}>{{template "icon" "seo"}}Search engines</a>
<div class="nav-label">AI</div>
<a href="/settings/ai" {{if eq .Nav "settings/ai"}}aria-current="page"{{end}}>{{template "icon" "ai"}}AI</a>
<div class="nav-label">Data</div>
<a href="/settings/backups" {{if eq .Nav "settings/backups"}}aria-current="page"{{end}}>{{template "icon" "backups"}}Backups</a>
</nav>
<div class="settings-body">
{{end}}
@@ -174,6 +176,7 @@
{{- else if eq . "accounts"}}<circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="m8.59 13.51 6.83 3.98"/><path d="m15.41 6.51-6.82 3.98"/>
{{- else if eq . "ai"}}<path d="M12 8V4H8"/><rect width="16" height="12" x="4" y="8" rx="2"/><path d="M2 14h2"/><path d="M20 14h2"/><path d="M15 13v2"/><path d="M9 13v2"/>
{{- else if eq . "core"}}<path d="M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z"/><path d="m2 22 3-3"/><path d="M7.5 13.5 10 11"/><path d="M10.5 16.5 13 14"/><path d="m18 3-4 4h6l-4 4"/>
{{- else if eq . "backups"}}<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l4 2"/>
{{- else if eq . "menu"}}<path d="M4 12h16"/><path d="M4 6h16"/><path d="M4 18h16"/>
{{- end}}</svg>{{end}}