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:
@@ -1402,6 +1402,28 @@ 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.
|
||||
|
||||
**Part 2 built (2026-11-22; no schema change).** A restore is staged,
|
||||
then applied on the next start, since a running app can't swap its own
|
||||
database: `backup.Stage` checks the file (integrity, a Supermarket
|
||||
database, schema no newer than the app's), backs up the current database
|
||||
(kind *restore*), and leaves `restore-pending.db` (plus
|
||||
`restore-pending.json`); `ApplyPending` runs in `main` before anything
|
||||
opens the database, re-checks it, removes the old `-wal`/`-shm`, renames
|
||||
it over `app.db`, and records `restore-done.json`; migrations then run as
|
||||
usual. From Settings → Backups, *Restore* (asks first) stages it and
|
||||
stops the app (`Server.Restart`, the signal context's cancel); Docker's
|
||||
`restart: unless-stopped` starts it again within a second, and the page
|
||||
reloads (a `Refresh` header). A staged restore can be cancelled until
|
||||
then. *Upload* takes a `.db` file, checks it and adds it to the list as
|
||||
one of the user's backups. `supermarket restore <name or file>` copies a
|
||||
host file into the data folder, stages it in the container, and restarts
|
||||
the app. `supermarket backup --with-secrets` writes a mode-0600
|
||||
`app-<time>-with-secrets.tar.gz` (app.db, secrets.json, mcp-token) to the
|
||||
backups folder, not listed on the page; restoring one replaces
|
||||
secrets.json too (the old one kept in the backups folder), while this
|
||||
machine's mcp-token stays. Tried live both ways (the command line and the
|
||||
page) by restoring a backup taken seconds before.
|
||||
|
||||
### Future enhancements
|
||||
|
||||
Not in any phase yet; picked up when the user asks.
|
||||
|
||||
@@ -115,6 +115,21 @@ Throughout, also notice:
|
||||
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".
|
||||
- [ ] *Restore* on a backup asks first; then the page says it's restarting
|
||||
and reloads by itself within about ten seconds, showing "Restored
|
||||
from …" and the backup of what was there before. Data made after the
|
||||
backup is gone; data from before it is back.
|
||||
- [ ] A backup from a newer Supermarket (a higher schema) has no *Restore*
|
||||
button; `supermarket restore` refuses it with a reason.
|
||||
- [ ] *Upload* a downloaded `.db`: it's checked and listed ("uploaded …");
|
||||
a file that isn't a Supermarket database is refused.
|
||||
- [ ] `supermarket restore <name>` (a name from `supermarket backups`) and
|
||||
`supermarket restore ~/Downloads/<file>.db` both work and restart the
|
||||
app.
|
||||
- [ ] `supermarket backup --with-secrets` makes a `.tar.gz` in the backups
|
||||
folder (only you can read it) and warns about it; on another computer
|
||||
`supermarket restore <file>.tar.gz` brings back the data and the keys
|
||||
(Settings show them as saved).
|
||||
|
||||
## 4. Inventory
|
||||
|
||||
|
||||
@@ -20,7 +20,11 @@ Usage: supermarket [command]
|
||||
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)
|
||||
backup --with-secrets The same, with your keys and tokens, for moving
|
||||
to another computer (keep the file safe)
|
||||
backups List the backups
|
||||
restore <backup or file> Put a backup back (a name from \`backups\`, or
|
||||
a file), after backing up what's there now; then restarts
|
||||
|
||||
Updates come with CoreDesktop's \`update\`.
|
||||
EOF
|
||||
@@ -66,6 +70,35 @@ case "${1:-open}" in
|
||||
fi
|
||||
docker exec supermarket supermarket "$@"
|
||||
;;
|
||||
restore)
|
||||
if [ -z "$2" ]; then
|
||||
echo "Usage: supermarket restore <backup name or file>"
|
||||
exit 1
|
||||
fi
|
||||
if ! docker exec supermarket true 2> /dev/null; then
|
||||
echo "Supermarket isn't running: start it first (supermarket start)."
|
||||
exit 1
|
||||
fi
|
||||
target="$2"
|
||||
staged=""
|
||||
if [ -f "$target" ]; then
|
||||
# A file on this computer: the container only sees the data folder.
|
||||
case "$target" in
|
||||
*.tar.gz|*.tgz) staged="$DATA/restore-upload.tar.gz" ;;
|
||||
*) staged="$DATA/restore-upload.db" ;;
|
||||
esac
|
||||
install -m 600 "$target" "$staged" || exit 1
|
||||
target="/data/$(basename "$staged")"
|
||||
fi
|
||||
if docker exec supermarket supermarket restore "$target"; then
|
||||
[ -n "$staged" ] && rm -f "$staged"
|
||||
echo "Restarting Supermarket to apply it..."
|
||||
compose restart
|
||||
else
|
||||
[ -n "$staged" ] && rm -f "$staged"
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
data) echo "$DATA" ;;
|
||||
-h|--help|help) usage ;;
|
||||
*) usage; exit 1 ;;
|
||||
|
||||
+39
-1
@@ -49,7 +49,7 @@ func main() {
|
||||
fmt.Println(version)
|
||||
return
|
||||
}
|
||||
if len(os.Args) > 1 && (os.Args[1] == "backup" || os.Args[1] == "backups") {
|
||||
if len(os.Args) > 1 && (os.Args[1] == "backup" || os.Args[1] == "backups" || os.Args[1] == "restore") {
|
||||
if err := backupCommand(os.Args[1], os.Args[2:]); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
@@ -85,6 +85,13 @@ func run(log *slog.Logger) error {
|
||||
if err := os.MkdirAll(dataDir, 0700); err != nil {
|
||||
return err
|
||||
}
|
||||
// A restore staged before the restart is swapped in before the
|
||||
// database opens.
|
||||
if r, err := backup.ApplyPending(dataDir, time.Now()); err != nil {
|
||||
log.Error("backups: the restore wasn't applied", "err", err)
|
||||
} else if r != nil {
|
||||
log.Info("backups: restored", "from", r.From, "secrets", r.Secrets, "previous database", r.Backup)
|
||||
}
|
||||
// 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)
|
||||
@@ -170,6 +177,9 @@ func run(log *slog.Logger) error {
|
||||
}
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
// A restore from the browser stops the app; Docker starts it again
|
||||
// (restart: unless-stopped), and the restore is applied on the way up.
|
||||
srv.Restart = stop
|
||||
|
||||
errCh := make(chan error, 2)
|
||||
go func() {
|
||||
@@ -278,6 +288,34 @@ func backupCommand(cmd string, args []string) error {
|
||||
return err
|
||||
}
|
||||
defer d.Close()
|
||||
if cmd == "restore" {
|
||||
if len(args) != 1 {
|
||||
return errors.New("usage: supermarket restore <backup name or file>")
|
||||
}
|
||||
src := args[0]
|
||||
if !filepath.IsAbs(src) {
|
||||
src = filepath.Join(dir, src)
|
||||
}
|
||||
r, err := backup.Stage(d, dataDir, src, db.Schema(), time.Now())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("Ready to restore %s; the current database is backed up as %s.\n", r.From, r.Backup)
|
||||
if r.Secrets {
|
||||
fmt.Println("Its secrets.json (keys and tokens) will replace this one; the current one is kept in the backups folder.")
|
||||
}
|
||||
fmt.Println("It's applied when Supermarket restarts.")
|
||||
return nil
|
||||
}
|
||||
if len(args) > 0 && args[0] == "--with-secrets" {
|
||||
p, err := backup.Archive(d, dataDir, time.Now())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("Backed up, with secrets, to backups/%s\n", filepath.Base(p))
|
||||
fmt.Println("It holds your keys and tokens: keep it as safe as they are, and delete it once you've moved.")
|
||||
return nil
|
||||
}
|
||||
b, err := backup.Make(d, dir, backup.Manual, strings.Join(args, " "), time.Now())
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
+85
-3
@@ -3,9 +3,11 @@ package web
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/backup"
|
||||
@@ -68,9 +70,12 @@ func (s *Server) renderBackups(w http.ResponseWriter, r *http.Request, errMsg, f
|
||||
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,
|
||||
}})
|
||||
data := map[string]any{"Backups": bs, "Total": total, "Keep": keep, "Schema": db.Schema(), "Dir": hostDir,
|
||||
"Pending": backup.Pending(s.DataDir), "CanRestart": s.Restart != nil}
|
||||
if last := backup.LastRestore(s.DataDir); last != nil && time.Since(last.At) < 24*time.Hour {
|
||||
data["Restored"] = last
|
||||
}
|
||||
s.render(w, r, "backups", page{Title: "Backups", Nav: "settings/backups", Error: errMsg, Flash: flash, Data: data})
|
||||
}
|
||||
|
||||
func (s *Server) backupsAction(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -86,6 +91,16 @@ func (s *Server) backupsAction(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
s.renderBackups(w, r, "", "Backed up to "+b.Name+".")
|
||||
case "restore":
|
||||
b, err := backup.Find(s.backupDir(), r.PostFormValue("name"))
|
||||
if err != nil {
|
||||
s.renderBackups(w, r, "There's no backup called "+r.PostFormValue("name")+".", "")
|
||||
return
|
||||
}
|
||||
s.restore(w, r, b.Path)
|
||||
case "cancel":
|
||||
backup.Cancel(s.DataDir)
|
||||
s.renderBackups(w, r, "", "The restore is cancelled.")
|
||||
case "delete":
|
||||
name := r.PostFormValue("name")
|
||||
if err := backup.Delete(s.backupDir(), name); err != nil {
|
||||
@@ -116,3 +131,70 @@ func (s *Server) backupDownload(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
http.ServeFile(w, r, b.Path)
|
||||
}
|
||||
|
||||
// restore stages a restore from a backup file, then restarts the app to
|
||||
// apply it. Without a way to restart (tests, or not under Docker) it's
|
||||
// left staged for the next start.
|
||||
func (s *Server) restore(w http.ResponseWriter, r *http.Request, path string) {
|
||||
res, err := backup.Stage(s.DB.DB, s.DataDir, path, db.Schema(), time.Now())
|
||||
if err != nil {
|
||||
s.renderBackups(w, r, "Not restored: "+err.Error(), "")
|
||||
return
|
||||
}
|
||||
msg := "Restoring " + res.From + ". The current database is backed up as " + res.Backup + "."
|
||||
if s.Restart == nil {
|
||||
s.renderBackups(w, r, "", msg+" It's applied when Supermarket next starts.")
|
||||
return
|
||||
}
|
||||
s.Log.Info("backups: restoring; restarting", "from", res.From)
|
||||
// Reload once the app is back: Docker starts it again in a few seconds.
|
||||
w.Header().Set("Refresh", "8; url=/settings/backups")
|
||||
s.renderBackups(w, r, "", msg+" Supermarket is restarting to apply it; this page reloads by itself.")
|
||||
go func() {
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
s.Restart()
|
||||
}()
|
||||
}
|
||||
|
||||
// maxUpload is the biggest backup that can be uploaded.
|
||||
const maxUpload = 4 << 30
|
||||
|
||||
// backupUpload takes a backup file from the browser (one downloaded from
|
||||
// here, perhaps on another machine) and adds it to the list, checked;
|
||||
// restoring it is a second step.
|
||||
func (s *Server) backupUpload(w http.ResponseWriter, r *http.Request) {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxUpload)
|
||||
f, hdr, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
s.renderBackups(w, r, "Choose a backup file to upload.", "")
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
if err := os.MkdirAll(s.backupDir(), 0o700); err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
tmp, err := os.CreateTemp(s.backupDir(), ".upload-*.db")
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
defer os.Remove(tmp.Name())
|
||||
if _, err := io.Copy(tmp, f); err != nil {
|
||||
tmp.Close()
|
||||
s.renderBackups(w, r, "The upload didn't finish: "+err.Error(), "")
|
||||
return
|
||||
}
|
||||
tmp.Close()
|
||||
if err := backup.Check(tmp.Name()); err != nil {
|
||||
s.renderBackups(w, r, hdr.Filename+" isn't a backup Supermarket can use: "+err.Error(), "")
|
||||
return
|
||||
}
|
||||
note := "uploaded " + strings.TrimSuffix(filepath.Base(hdr.Filename), ".db")
|
||||
b, err := backup.Adopt(tmp.Name(), s.backupDir(), note, time.Now())
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
s.renderBackups(w, r, "", "Uploaded as "+b.Name+". Restore it from the list when you're ready.")
|
||||
}
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -52,3 +56,62 @@ func TestBackupsPage(t *testing.T) {
|
||||
t.Errorf("bad delete: %s", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreFromThePage(t *testing.T) {
|
||||
s, h := newTestServer(t, nil)
|
||||
s.DB.PutJSON("test:value", "before")
|
||||
b, err := backup.Make(s.DB.DB, s.backupDir(), backup.Manual, "good", time.Now().Add(-time.Hour))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.DB.PutJSON("test:value", "after")
|
||||
var restarts atomic.Int32
|
||||
s.Restart = func() { restarts.Add(1) }
|
||||
|
||||
rec := postForm(h, "/settings/backups/restore", url.Values{"name": {b.Name}})
|
||||
body := rec.Body.String()
|
||||
if !strings.Contains(body, "Restoring "+b.Name) || !strings.Contains(body, "this page reloads by itself") ||
|
||||
!strings.Contains(body, "A restore is waiting") || rec.Header().Get("Refresh") == "" {
|
||||
t.Errorf("restore: %v %s", rec.Header(), body)
|
||||
}
|
||||
time.Sleep(700 * time.Millisecond)
|
||||
if restarts.Load() != 1 || !backup.Pending(s.DataDir) {
|
||||
t.Errorf("restarts %d, pending %v", restarts.Load(), backup.Pending(s.DataDir))
|
||||
}
|
||||
// Cancelled before the restart: nothing happens.
|
||||
body = postForm(h, "/settings/backups/cancel", nil).Body.String()
|
||||
if !strings.Contains(body, "The restore is cancelled") || backup.Pending(s.DataDir) {
|
||||
t.Errorf("cancel: %s", body)
|
||||
}
|
||||
if body := postForm(h, "/settings/backups/restore", url.Values{"name": {"../app.db"}}).Body.String(); !strings.Contains(body, "There's no backup called") {
|
||||
t.Errorf("bad name: %s", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBackupUpload(t *testing.T) {
|
||||
s, h := newTestServer(t, nil)
|
||||
b, _ := backup.Make(s.DB.DB, t.TempDir(), backup.Manual, "elsewhere", time.Now())
|
||||
raw, _ := os.ReadFile(b.Path)
|
||||
upload := func(name string, content []byte) string {
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
fw, _ := mw.CreateFormFile("file", name)
|
||||
fw.Write(content)
|
||||
mw.Close()
|
||||
return do(h, http.MethodPost, "/settings/backups/upload", &buf, map[string]string{"Content-Type": mw.FormDataContentType()}).Body.String()
|
||||
}
|
||||
body := upload("app-from-laptop.db", raw)
|
||||
if !strings.Contains(body, "Uploaded as app-") || !strings.Contains(body, "-manual-uploaded-app-from-laptop.db") {
|
||||
t.Errorf("upload: %s", body)
|
||||
}
|
||||
if body := upload("notes.txt", []byte("hello")); !strings.Contains(body, "isn't a backup Supermarket can use") {
|
||||
t.Errorf("bad upload: %s", body)
|
||||
}
|
||||
if bs, _ := backup.List(s.backupDir()); len(bs) != 1 {
|
||||
t.Errorf("backups: %v", bs)
|
||||
}
|
||||
left, _ := filepath.Glob(filepath.Join(s.backupDir(), ".upload-*"))
|
||||
if len(left) != 0 {
|
||||
t.Errorf("temporary files left: %v", left)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,6 +48,7 @@ type Server struct {
|
||||
MCPToken string
|
||||
MCPSocket string // the MCP socket's path on the host, for Hermes' config
|
||||
MCP http.Handler
|
||||
Restart func() // stops the app so Docker starts it again; nil in tests
|
||||
Log *slog.Logger
|
||||
|
||||
// What the legacy import did at startup, or why it failed.
|
||||
@@ -233,6 +234,7 @@ func (s *Server) Handler() (http.Handler, error) {
|
||||
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("POST /settings/backups/upload", s.backupUpload)
|
||||
mux.HandleFunc("GET /settings/core", s.corePage)
|
||||
mux.HandleFunc("GET /settings/core/checks", s.coreChecks)
|
||||
|
||||
|
||||
@@ -2,6 +2,13 @@
|
||||
<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>
|
||||
|
||||
{{with .Restored}}<p class="ok">Restored from {{.From}} {{ago .At}}{{if .Secrets}}, keys and tokens included{{end}}. What was there before is backed up as {{.Backup}}.</p>{{end}}
|
||||
{{if .Pending}}
|
||||
<section class="card warn">
|
||||
<p><strong>A restore is waiting</strong> for Supermarket to restart. {{if not .CanRestart}}It's applied the next time Supermarket starts (<code>supermarket restart</code>).{{end}}</p>
|
||||
<form method="post" action="/settings/backups/cancel"><button type="submit" class="secondary small">Cancel the restore</button></form>
|
||||
</section>
|
||||
{{end}}
|
||||
<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">
|
||||
@@ -21,6 +28,8 @@
|
||||
<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">
|
||||
{{if ge .Schema 0}}{{if le .Schema $d.Schema}}<form method="post" action="/settings/backups/restore" data-confirm="Restore the backup from {{.At.Format "2 Jan 2006, 15:04"}}? Everything since then is replaced (it's backed up first), and Supermarket restarts.">
|
||||
<input type="hidden" name="name" value="{{.Name}}"><button type="submit" class="secondary small" data-busy="Restoring…">Restore</button></form>{{end}}{{end}}
|
||||
<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>
|
||||
@@ -30,4 +39,13 @@
|
||||
{{else}}
|
||||
<section class="card empty"><p>No backups yet. The first daily one is made when Supermarket starts.</p></section>
|
||||
{{end}}
|
||||
|
||||
<section class="card">
|
||||
<h3>Restore from a file</h3>
|
||||
<p class="help">A backup downloaded from here, on this computer or another. It's checked and added to the list; then restore it from there. For a backup made with <code>supermarket backup --with-secrets</code> (keys and tokens included), use <code>supermarket restore <file></code> in a terminal.</p>
|
||||
<form method="post" action="/settings/backups/upload" enctype="multipart/form-data" class="inline-form">
|
||||
<input type="file" name="file" accept=".db,application/vnd.sqlite3" required>
|
||||
<button type="submit" class="secondary" data-busy="Uploading…">Upload</button>
|
||||
</form>
|
||||
</section>
|
||||
{{end}}{{template "settings-end"}}{{end}}
|
||||
|
||||
Reference in New Issue
Block a user