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>
This commit is contained in:
2026-11-22 14:46:36 -07:00
co-authored by Claude Opus 5.5
parent 5313369328
commit fa4792e0fe
11 changed files with 744 additions and 4 deletions
+24
View File
@@ -384,3 +384,27 @@ func moveFile(from, to string) error {
}
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
}
+298
View File
@@ -0,0 +1,298 @@
package backup
import (
"archive/tar"
"compress/gzip"
"database/sql"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
)
// Files a restore leaves in the data folder between staging it and the
// app's next start, when it's applied.
const (
pendingDB = "restore-pending.db"
pendingSecrets = "restore-pending-secrets.json"
pendingInfo = "restore-pending.json"
doneInfo = "restore-done.json"
)
// Restored says what the last restore put back.
type Restored struct {
From string `json:"from"` // the backup's name, or the file restored
Backup string `json:"backup"` // the backup of what was replaced
Secrets bool `json:"secrets,omitempty"` // secrets.json was replaced too
At time.Time `json:"at"`
}
// Stage prepares a restore from a backup file (a .db, or a .tar.gz made
// with secrets): it checks the file (SQLite's integrity check, a
// Supermarket database, a schema no newer than maxSchema), backs up the
// current database, and leaves the copy to be swapped in when the app
// next starts (ApplyPending). Secrets in an archive are swapped in too.
func Stage(current *sql.DB, dataDir, src string, maxSchema int, now time.Time) (*Restored, error) {
from := filepath.Base(src)
tmpDB := filepath.Join(dataDir, "."+pendingDB+".part")
tmpSecrets := ""
os.Remove(tmpDB)
defer os.Remove(tmpDB)
if strings.HasSuffix(src, ".tar.gz") || strings.HasSuffix(src, ".tgz") {
tmpSecrets = filepath.Join(dataDir, "."+pendingSecrets+".part")
defer os.Remove(tmpSecrets)
has, err := unpack(src, tmpDB, tmpSecrets)
if err != nil {
return nil, err
}
if !has {
tmpSecrets = ""
}
} else if err := copyFile(src, tmpDB); err != nil {
return nil, err
}
if err := Check(tmpDB); err != nil {
return nil, err
}
v, err := SchemaOf(tmpDB)
if err != nil {
return nil, err
}
if v > maxSchema {
return nil, fmt.Errorf("that backup is from a newer Supermarket (schema %d; this one knows %d): update Supermarket first", v, maxSchema)
}
if tmpSecrets != "" {
raw, err := os.ReadFile(tmpSecrets)
if err != nil {
return nil, err
}
var m map[string]any
if json.Unmarshal(raw, &m) != nil {
return nil, errors.New("the archive's secrets.json isn't readable")
}
}
b, err := Make(current, Dir(dataDir), Restore, "", now)
if err != nil {
return nil, fmt.Errorf("backing up the current database first: %w", err)
}
r := &Restored{From: from, Backup: b.Name, Secrets: tmpSecrets != "", At: now}
if err := os.Rename(tmpDB, filepath.Join(dataDir, pendingDB)); err != nil {
return nil, err
}
if tmpSecrets != "" {
if err := os.Rename(tmpSecrets, filepath.Join(dataDir, pendingSecrets)); err != nil {
os.Remove(filepath.Join(dataDir, pendingDB))
return nil, err
}
} else {
os.Remove(filepath.Join(dataDir, pendingSecrets))
}
raw, _ := json.Marshal(r)
if err := os.WriteFile(filepath.Join(dataDir, pendingInfo), raw, 0o600); err != nil {
os.Remove(filepath.Join(dataDir, pendingDB))
return nil, err
}
return r, nil
}
// Pending says whether a restore is waiting for the app to restart.
func Pending(dataDir string) bool {
_, err := os.Stat(filepath.Join(dataDir, pendingDB))
return err == nil
}
// Cancel drops a staged restore.
func Cancel(dataDir string) {
for _, f := range []string{pendingDB, pendingSecrets, pendingInfo} {
os.Remove(filepath.Join(dataDir, f))
}
}
// ApplyPending swaps a staged restore in, before the app opens its
// database: the database file replaced (its -wal and -shm removed) and,
// from an archive, secrets.json (the old one kept in the backups folder).
// It returns what was restored, or nil when nothing was staged.
func ApplyPending(dataDir string, now time.Time) (*Restored, error) {
pending := filepath.Join(dataDir, pendingDB)
if _, err := os.Stat(pending); errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err := Check(pending); err != nil {
Cancel(dataDir)
return nil, fmt.Errorf("the staged restore failed its check, so it was dropped: %w", err)
}
var r Restored
if raw, err := os.ReadFile(filepath.Join(dataDir, pendingInfo)); err == nil {
_ = json.Unmarshal(raw, &r)
}
db := filepath.Join(dataDir, "app.db")
for _, f := range []string{db + "-wal", db + "-shm"} {
if err := os.Remove(f); err != nil && !errors.Is(err, os.ErrNotExist) {
return nil, err
}
}
if err := os.Rename(pending, db); err != nil {
return nil, err
}
if secrets := filepath.Join(dataDir, pendingSecrets); r.Secrets {
cur := filepath.Join(dataDir, "secrets.json")
if _, err := os.Stat(cur); err == nil {
keep := filepath.Join(Dir(dataDir), "secrets-before-restore-"+now.Format(stampFmt)+".json")
if err := os.MkdirAll(Dir(dataDir), 0o700); err == nil {
_ = moveFile(cur, keep)
}
}
if err := os.Rename(secrets, cur); err != nil {
return nil, fmt.Errorf("the database was restored, but not the secrets: %w", err)
}
os.Chmod(cur, 0o600)
}
os.Remove(filepath.Join(dataDir, pendingInfo))
r.At = now
raw, _ := json.Marshal(r)
_ = os.WriteFile(filepath.Join(dataDir, doneInfo), raw, 0o600)
return &r, nil
}
// LastRestore is the last restore applied, if any.
func LastRestore(dataDir string) *Restored {
raw, err := os.ReadFile(filepath.Join(dataDir, doneInfo))
if err != nil {
return nil
}
var r Restored
if json.Unmarshal(raw, &r) != nil {
return nil
}
return &r
}
// Archive makes a backup with the app's secrets beside the database, for
// moving Supermarket to another machine: a mode-0600 .tar.gz in the
// backups folder holding app.db, secrets.json and mcp-token. It holds
// credentials: it must be kept as carefully as they are.
func Archive(d *sql.DB, dataDir string, now time.Time) (string, error) {
dir := Dir(dataDir)
if err := os.MkdirAll(dir, 0o700); err != nil {
return "", err
}
tmp := filepath.Join(dir, ".archive-"+now.Format(stampFmt)+".db")
os.Remove(tmp)
defer os.Remove(tmp)
if _, err := d.Exec(`VACUUM INTO ?`, tmp); err != nil {
return "", fmt.Errorf("backing up: %w", err)
}
path := filepath.Join(dir, "app-"+now.Format(stampFmt)+"-with-secrets.tar.gz")
f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
if err != nil {
return "", err
}
gz := gzip.NewWriter(f)
tw := tar.NewWriter(gz)
add := func(name, from string) error {
in, err := os.Open(from)
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return err
}
defer in.Close()
st, err := in.Stat()
if err != nil {
return err
}
if err := tw.WriteHeader(&tar.Header{Name: name, Mode: 0o600, Size: st.Size(), ModTime: now}); err != nil {
return err
}
_, err = io.Copy(tw, in)
return err
}
err = add("app.db", tmp)
if err == nil {
err = add("secrets.json", filepath.Join(dataDir, "secrets.json"))
}
if err == nil {
err = add("mcp-token", filepath.Join(dataDir, "mcp-token"))
}
for _, c := range []io.Closer{tw, gz, f} {
if cerr := c.Close(); err == nil {
err = cerr
}
}
if err != nil {
os.Remove(path)
return "", err
}
return path, nil
}
// unpack reads an archive made by Archive: its app.db to db, and its
// secrets.json, if there is one, to secrets.
func unpack(src, db, secrets string) (hasSecrets bool, err error) {
f, err := os.Open(src)
if err != nil {
return false, err
}
defer f.Close()
gz, err := gzip.NewReader(f)
if err != nil {
return false, fmt.Errorf("not an archive Supermarket made: %w", err)
}
tr := tar.NewReader(gz)
hasDB := false
for {
h, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return false, fmt.Errorf("reading the archive: %w", err)
}
var to string
switch h.Name {
case "app.db":
to, hasDB = db, true
case "secrets.json":
to, hasSecrets = secrets, true
default:
continue // mcp-token and anything else stay as they are here
}
out, err := os.OpenFile(to, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600)
if err != nil {
return false, err
}
_, err = io.Copy(out, io.LimitReader(tr, 16<<30))
if cerr := out.Close(); err == nil {
err = cerr
}
if err != nil {
return false, err
}
}
if !hasDB {
return false, errors.New("the archive has no app.db")
}
return hasSecrets, nil
}
func copyFile(from, to string) error {
in, err := os.Open(from)
if err != nil {
return err
}
defer in.Close()
out, err := os.OpenFile(to, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600)
if err != nil {
return err
}
if _, err := io.Copy(out, in); err != nil {
out.Close()
return err
}
return out.Close()
}
+145
View File
@@ -0,0 +1,145 @@
package backup
import (
"database/sql"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func value(t *testing.T, path, key string) string {
t.Helper()
d, err := sql.Open("sqlite", "file:"+path)
if err != nil {
t.Fatal(err)
}
defer d.Close()
var v string
d.QueryRow(`SELECT value FROM settings WHERE key = ?`, key).Scan(&v)
return v
}
func TestStageAndApply(t *testing.T) {
data := t.TempDir()
cur := newDB(t, filepath.Join(data, "app.db"))
now := time.Date(2026, 11, 22, 15, 0, 0, 0, time.Local)
old, err := Make(cur, Dir(data), Manual, "good", now.Add(-time.Hour))
if err != nil {
t.Fatal(err)
}
cur.Exec(`UPDATE settings SET value = 'changed' WHERE key = 'a'`)
// Too new, damaged and foreign files are refused, and nothing is staged.
newer := filepath.Join(t.TempDir(), "newer.db")
nd := newDB(t, newer)
nd.Exec(`PRAGMA user_version = 99`)
nd.Close()
junk := filepath.Join(t.TempDir(), "junk.db")
os.WriteFile(junk, []byte("junk"), 0o600)
for src, want := range map[string]string{newer: "newer Supermarket", junk: "not a database", "/nope.db": "no such file"} {
if _, err := Stage(cur, data, src, 24, now); err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("%s: %v", src, err)
}
if Pending(data) {
t.Errorf("%s was staged", src)
}
}
r, err := Stage(cur, data, old.Path, 24, now)
if err != nil {
t.Fatal(err)
}
if r.From != old.Name || !strings.HasSuffix(r.Backup, "-restore.db") || r.Secrets || !Pending(data) {
t.Errorf("staged: %+v", r)
}
// What was there is backed up, with the change.
if v := value(t, filepath.Join(Dir(data), r.Backup), "a"); v != "changed" {
t.Errorf("safety backup: %q", v)
}
cur.Close()
os.WriteFile(filepath.Join(data, "app.db-wal"), []byte("stale"), 0o600)
got, err := ApplyPending(data, now.Add(time.Minute))
if err != nil || got == nil || got.From != old.Name {
t.Fatalf("applied: %+v %v", got, err)
}
if v := value(t, filepath.Join(data, "app.db"), "a"); v != "1" {
t.Errorf("restored value: %q", v)
}
if _, err := os.Stat(filepath.Join(data, "app.db-wal")); err == nil {
t.Error("the old -wal is still there")
}
if Pending(data) || LastRestore(data) == nil || LastRestore(data).From != old.Name {
t.Errorf("after: pending=%v last=%+v", Pending(data), LastRestore(data))
}
if r, err := ApplyPending(data, now); r != nil || err != nil {
t.Errorf("applied twice: %v %v", r, err)
}
}
func TestCancel(t *testing.T) {
data := t.TempDir()
cur := newDB(t, filepath.Join(data, "app.db"))
defer cur.Close()
b, _ := Make(cur, Dir(data), Manual, "", time.Now())
if _, err := Stage(cur, data, b.Path, 24, time.Now()); err != nil {
t.Fatal(err)
}
Cancel(data)
if Pending(data) {
t.Error("still pending")
}
if r, _ := ApplyPending(data, time.Now()); r != nil {
t.Error("applied a cancelled restore")
}
}
func TestArchiveWithSecrets(t *testing.T) {
// Machine one: a database, secrets and a token, archived.
one := t.TempDir()
d1 := newDB(t, filepath.Join(one, "app.db"))
d1.Exec(`UPDATE settings SET value = 'from-one' WHERE key = 'a'`)
os.WriteFile(filepath.Join(one, "secrets.json"), []byte(`{"stripe":"sk_one"}`), 0o600)
os.WriteFile(filepath.Join(one, "mcp-token"), []byte("token-one"), 0o600)
now := time.Date(2026, 11, 22, 16, 0, 0, 0, time.Local)
path, err := Archive(d1, one, now)
d1.Close()
if err != nil {
t.Fatal(err)
}
if st, _ := os.Stat(path); st.Mode().Perm() != 0o600 || !strings.HasSuffix(path, "-with-secrets.tar.gz") {
t.Errorf("archive: %s %v", path, st.Mode())
}
if bs, _ := List(Dir(one)); len(bs) != 0 {
t.Errorf("the archive is listed with the backups: %v", bs)
}
// Machine two: restored from it, secrets included; its own token stays.
two := t.TempDir()
d2 := newDB(t, filepath.Join(two, "app.db"))
os.WriteFile(filepath.Join(two, "secrets.json"), []byte(`{"stripe":"sk_two"}`), 0o600)
os.WriteFile(filepath.Join(two, "mcp-token"), []byte("token-two"), 0o600)
r, err := Stage(d2, two, path, 24, now)
d2.Close()
if err != nil || !r.Secrets {
t.Fatalf("staged: %+v %v", r, err)
}
if _, err := ApplyPending(two, now); err != nil {
t.Fatal(err)
}
if v := value(t, filepath.Join(two, "app.db"), "a"); v != "from-one" {
t.Errorf("database: %q", v)
}
raw, _ := os.ReadFile(filepath.Join(two, "secrets.json"))
tok, _ := os.ReadFile(filepath.Join(two, "mcp-token"))
if string(raw) != `{"stripe":"sk_one"}` || string(tok) != "token-two" {
t.Errorf("secrets %s, token %s", raw, tok)
}
kept, _ := filepath.Glob(filepath.Join(Dir(two), "secrets-before-restore-*.json"))
if len(kept) != 1 {
t.Fatalf("the old secrets weren't kept: %v", kept)
}
if old, _ := os.ReadFile(kept[0]); string(old) != `{"stripe":"sk_two"}` {
t.Errorf("kept: %s", old)
}
}