Phase 6 part 1: database backups
Backups with SQLite's VACUUM INTO into <data>/backups: on request (Settings → Backups, supermarket backup [note]), before every schema migration, and daily, keeping 7 dailies and 4 weeklies. Listed with size and schema; downloadable and deletable. The old app.db.pre-* copies are moved in, with their -wal files folded in first. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,118 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"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) {
|
||||
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.DB, 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) {
|
||||
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")
|
||||
}
|
||||
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,
|
||||
}})
|
||||
}
|
||||
|
||||
func (s *Server) backupsAction(w http.ResponseWriter, r *http.Request) {
|
||||
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.DB, 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 "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) {
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/backup"
|
||||
)
|
||||
|
||||
func TestBackupsPage(t *testing.T) {
|
||||
s, h := newTestServer(t, nil)
|
||||
if body := do(h, http.MethodGet, "/settings/backups", nil, nil).Body.String(); !strings.Contains(body, "No backups yet") {
|
||||
t.Errorf("empty: %s", body)
|
||||
}
|
||||
body := postForm(h, "/settings/backups/now", url.Values{"note": {"Before the import"}}).Body.String()
|
||||
if !strings.Contains(body, "Backed up to app-") || !strings.Contains(body, "-manual-before-the-import.db") ||
|
||||
!strings.Contains(body, "By you") || !strings.Contains(body, "before-the-import") {
|
||||
t.Errorf("after backing up: %s", body)
|
||||
}
|
||||
bs, _ := backup.List(s.backupDir())
|
||||
if len(bs) != 1 {
|
||||
t.Fatalf("backups: %v", bs)
|
||||
}
|
||||
rec := do(h, http.MethodGet, "/settings/backups/file/"+bs[0].Name, nil, nil)
|
||||
if rec.Code != http.StatusOK || !strings.HasPrefix(rec.Body.String(), "SQLite format 3") ||
|
||||
!strings.Contains(rec.Header().Get("Content-Disposition"), bs[0].Name) {
|
||||
t.Errorf("download: %d %v", rec.Code, rec.Header())
|
||||
}
|
||||
for _, bad := range []string{"..%2Fapp.db", "secrets.json", "app.db"} {
|
||||
if rec := do(h, http.MethodGet, "/settings/backups/file/"+bad, nil, nil); rec.Code != http.StatusNotFound {
|
||||
t.Errorf("%s: %d", bad, rec.Code)
|
||||
}
|
||||
}
|
||||
// The daily one, once a day.
|
||||
s.dailyBackup(time.Now())
|
||||
s.dailyBackup(time.Now())
|
||||
if bs, _ := backup.List(s.backupDir()); len(bs) != 2 {
|
||||
t.Errorf("after the daily: %d", len(bs))
|
||||
}
|
||||
body = postForm(h, "/settings/backups/delete", url.Values{"name": {bs[0].Name}}).Body.String()
|
||||
if !strings.Contains(body, "Deleted "+bs[0].Name) {
|
||||
t.Errorf("delete: %s", body)
|
||||
}
|
||||
if _, err := os.Stat(bs[0].Path); err == nil {
|
||||
t.Error("still there")
|
||||
}
|
||||
if body := postForm(h, "/settings/backups/delete", url.Values{"name": {"../app.db"}}).Body.String(); !strings.Contains(body, "There's no backup called") {
|
||||
t.Errorf("bad delete: %s", body)
|
||||
}
|
||||
}
|
||||
@@ -230,6 +230,9 @@ func (s *Server) Handler() (http.Handler, error) {
|
||||
mux.HandleFunc("POST /crm/{action}", s.crmAction)
|
||||
mux.HandleFunc("POST /crm/{id}/{action}", s.crmAction)
|
||||
|
||||
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("GET /settings/core", s.corePage)
|
||||
mux.HandleFunc("GET /settings/core/checks", s.coreChecks)
|
||||
|
||||
@@ -300,6 +303,19 @@ func sameOrigin(r *http.Request) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// humanBytes is a file size for people: "840 KB", "12.3 MB".
|
||||
func humanBytes(n int64) string {
|
||||
switch {
|
||||
case n >= 1<<30:
|
||||
return fmt.Sprintf("%.1f GB", float64(n)/(1<<30))
|
||||
case n >= 1<<20:
|
||||
return fmt.Sprintf("%.1f MB", float64(n)/(1<<20))
|
||||
case n >= 1<<10:
|
||||
return fmt.Sprintf("%d KB", n>>10)
|
||||
}
|
||||
return fmt.Sprintf("%d bytes", n)
|
||||
}
|
||||
|
||||
var backticks = regexp.MustCompile("`([^`]+)`")
|
||||
|
||||
// ticks shows Markdown's `code` spans as code, the rest as plain text.
|
||||
@@ -313,6 +329,7 @@ func (s *Server) loadTemplates() error {
|
||||
"join": strings.Join,
|
||||
"ago": ago,
|
||||
"ticks": ticks,
|
||||
"bytes": humanBytes,
|
||||
"kindLabel": sites.KindLabel,
|
||||
"add": func(a, b int) int { return a + b },
|
||||
"hasPrefix": strings.HasPrefix,
|
||||
|
||||
@@ -100,7 +100,7 @@ func TestEveryPageRenders(t *testing.T) {
|
||||
"/settings/ai", "/settings/accounts", "/settings/core", "/static/app.css", "/favicon.ico", "/static/favicon.png", "/static/logo.png", "/static/apple-touch-icon.png", "/search", "/crm", "/search?q=rival", "/search?q=nothing+here", "/static/htmx.min.js", "/healthz",
|
||||
"/content", "/content/1", "/content/1?dismissed=1", "/posts", "/posts?msg=drafted",
|
||||
"/content/scheduled", "/content/published",
|
||||
"/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines", "/metrics", "/metrics/customers", "/metrics/customers?show=all", "/metrics/spend", "/metrics/clv", "/metrics/clv?view=profit", "/metrics/publish", "/sites", "/sites?site=0", "/sites/previews", "/sites/pages", "/sites/publishing",
|
||||
"/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines", "/metrics", "/metrics/customers", "/metrics/customers?show=all", "/metrics/spend", "/metrics/clv", "/metrics/clv?view=profit", "/metrics/publish", "/sites", "/sites?site=0", "/sites/previews", "/sites/pages", "/sites/publishing", "/settings/backups",
|
||||
"/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} {
|
||||
rec := do(h, http.MethodGet, path, nil, nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
{{define "content"}}{{template "settings-start" .}}{{with .Data}}{{$d := .}}
|
||||
<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>
|
||||
|
||||
<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">
|
||||
<label>Note <span class="muted">(optional)</span> <input name="note" placeholder="before the big import" maxlength="60"></label>
|
||||
<button type="submit" data-busy="Backing up…">Back up now</button>
|
||||
</form>
|
||||
<p class="small muted">They're kept in <code>{{.Dir}}</code>, on this computer. From a terminal: <code>supermarket backup [note]</code> and <code>supermarket backups</code>.</p>
|
||||
</section>
|
||||
|
||||
{{if .Backups}}
|
||||
<p class="small">{{len .Backups}} backup{{if ne (len .Backups) 1}}s{{end}}, {{bytes .Total}} in all. This version of Supermarket is at schema {{.Schema}}.</p>
|
||||
<div class="table-wrap"><table>
|
||||
<thead><tr><th>Made</th><th>Why</th><th class="num">Size</th><th class="num">Schema</th><th></th></tr></thead>
|
||||
<tbody>{{range .Backups}}<tr>
|
||||
<td>{{.At.Format "2 Jan 2006, 15:04"}}<br><span class="small muted">{{ago .At}}</span></td>
|
||||
<td>{{if eq .Kind "manual"}}By you{{else if eq .Kind "migration"}}Before an update{{else if eq .Kind "daily"}}Daily{{if not (index $d.Keep .Name)}} <span class="muted">(next to go)</span>{{end}}{{else if eq .Kind "restore"}}Before a restore{{else}}An older copy{{end}}{{with .Note}}<br><span class="small muted">{{.}}</span>{{end}}</td>
|
||||
<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">
|
||||
<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>
|
||||
</div></td>
|
||||
</tr>{{end}}</tbody>
|
||||
</table></div>
|
||||
{{else}}
|
||||
<section class="card empty"><p>No backups yet. The first daily one is made when Supermarket starts.</p></section>
|
||||
{{end}}
|
||||
{{end}}{{template "settings-end"}}{{end}}
|
||||
@@ -127,6 +127,8 @@
|
||||
<a href="/settings/search" {{if eq .Nav "settings/search"}}aria-current="page"{{end}}>{{template "icon" "seo"}}Search engines</a>
|
||||
<div class="nav-label">AI</div>
|
||||
<a href="/settings/ai" {{if eq .Nav "settings/ai"}}aria-current="page"{{end}}>{{template "icon" "ai"}}AI</a>
|
||||
<div class="nav-label">Data</div>
|
||||
<a href="/settings/backups" {{if eq .Nav "settings/backups"}}aria-current="page"{{end}}>{{template "icon" "backups"}}Backups</a>
|
||||
</nav>
|
||||
<div class="settings-body">
|
||||
{{end}}
|
||||
@@ -174,6 +176,7 @@
|
||||
{{- else if eq . "accounts"}}<circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="m8.59 13.51 6.83 3.98"/><path d="m15.41 6.51-6.82 3.98"/>
|
||||
{{- else if eq . "ai"}}<path d="M12 8V4H8"/><rect width="16" height="12" x="4" y="8" rx="2"/><path d="M2 14h2"/><path d="M20 14h2"/><path d="M15 13v2"/><path d="M9 13v2"/>
|
||||
{{- else if eq . "core"}}<path d="M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z"/><path d="m2 22 3-3"/><path d="M7.5 13.5 10 11"/><path d="M10.5 16.5 13 14"/><path d="m18 3-4 4h6l-4 4"/>
|
||||
{{- else if eq . "backups"}}<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l4 2"/>
|
||||
{{- else if eq . "menu"}}<path d="M4 12h16"/><path d="M4 6h16"/><path d="M4 18h16"/>
|
||||
{{- end}}</svg>{{end}}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user