Files
davidandClaude Opus 5.5 fa4792e0fe Phase 6 part 2: restore from a backup
A restore is staged (checked, the current database backed up) and swapped
in when the app next starts. Settings → Backups restores with a
self-restart, cancels a waiting restore, and takes uploads; supermarket
restore takes a backup name or a file; supermarket backup --with-secrets
makes an archive with the keys, for moving machines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 14:46:36 -07:00

411 lines
10 KiB
Go

// 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)
}
// Adopt moves a checked database file into the backups as one the user
// made (an upload, say).
func Adopt(path, dir, note string, now time.Time) (*Backup, error) {
if err := os.MkdirAll(dir, 0o700); err != nil {
return nil, err
}
name := fileName(now, Manual, note)
for n := 1; ; n++ {
if _, err := os.Stat(filepath.Join(dir, name)); errors.Is(err, os.ErrNotExist) {
break
}
name = fileName(now.Add(time.Duration(n)*time.Second), Manual, note)
}
to := filepath.Join(dir, name)
if err := moveFile(path, to); err != nil {
return nil, err
}
os.Chmod(to, 0o600)
b, _ := Parse(name)
b.Path = to
b.read()
return &b, nil
}