Files
davidandClaude Opus 5.5 da16736fb4 Phase 10, part 9: the server package
compose.server.yaml runs Supermarket behind Caddy (HTTPS from Let's
Encrypt, Caddy's own CA or the team's), with Postgres on an internal
network and a nightly pg_dump kept two weeks. install-server.sh asks for
the domain, certificate and mail server, makes the secret key and database
password, starts it all and prints the setup link. Settings → Backups lists
the dumps on a server, and how the operator restores one. Checked end to
end in Docker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 09:37:34 -07:00

261 lines
7.7 KiB
Go

package web
import (
"context"
"errors"
"io"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"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) {
if s.DB.Dialect != db.SQLite {
return // Postgres is backed up by whoever runs it
}
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.SQL, 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) {
if s.DB.Dialect != db.SQLite {
s.renderServerBackups(w, r)
return
}
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")
}
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) {
if s.DB.Dialect != db.SQLite {
http.NotFound(w, r) // the operator backs Postgres up, and restores it
return
}
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.SQL, 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 "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 {
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) {
if s.DB.Dialect != db.SQLite {
http.NotFound(w, r)
return
}
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)
}
// 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.SQL, 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 Supermarket backup: "+err.Error()+".", "")
return
}
// A backup downloaded from here keeps its note, not its whole name.
note := "uploaded " + strings.TrimSuffix(filepath.Base(hdr.Filename), ".db")
if b, ok := backup.Parse(filepath.Base(hdr.Filename)); ok {
note = "uploaded " + b.Kind
if b.Note != "" {
note = "uploaded " + b.Note
}
}
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.")
}
// dump is one of the server's nightly database dumps.
type dump struct {
Name string
Size int64
At time.Time
}
// renderServerBackups lists the nightly dumps of Postgres (compose.server.yaml's
// backup service), newest first, and how the operator restores one.
func (s *Server) renderServerBackups(w http.ResponseWriter, r *http.Request) {
data := map[string]any{"Dir": ""}
if s.Config != nil && s.Config.PGBackups != "" {
data["Dir"] = s.Config.PGBackups
entries, err := os.ReadDir(s.Config.PGBackups)
if err != nil {
data["Err"] = err.Error()
}
var dumps []dump
var total int64
for _, e := range entries {
if e.IsDir() || !strings.HasSuffix(e.Name(), ".dump") {
continue
}
if fi, err := e.Info(); err == nil {
dumps = append(dumps, dump{Name: e.Name(), Size: fi.Size(), At: fi.ModTime()})
total += fi.Size()
}
}
sort.Slice(dumps, func(i, j int) bool { return dumps[i].At.After(dumps[j].At) })
data["Dumps"], data["Total"] = dumps, total
if len(dumps) > 0 && time.Since(dumps[0].At) > 36*time.Hour {
data["Stale"] = dumps[0].At
}
}
s.render(w, r, "backups-server", page{Title: "Backups", Nav: "settings/backups", Data: data})
}