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:
+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