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>
This commit is contained in:
2026-11-25 09:37:34 -07:00
co-authored by Claude Opus 5.5
parent c8964cec12
commit da16736fb4
15 changed files with 532 additions and 17 deletions
+5 -1
View File
@@ -93,7 +93,8 @@ type Config struct {
SecretKey []byte // 32 bytes that encrypt secrets in the database; nil if not set
OldKey []byte // the key being replaced: secrets under it are encrypted again with SecretKey
Storage Storage
Mail *Mail // nil if not set
Mail *Mail // nil if not set
PGBackups string // where the server's nightly dumps are, to list them; "" if not known
}
// Environment variables.
@@ -115,6 +116,7 @@ const (
EnvS3SecretKey = "SUPERMARKET_S3_SECRET_KEY"
EnvMailURL = "SUPERMARKET_MAIL_URL"
EnvMailFrom = "SUPERMARKET_MAIL_FROM"
EnvPGBackups = "SUPERMARKET_PG_BACKUPS"
)
// Load reads the settings through getenv (os.Getenv) and checks them. All
@@ -208,6 +210,8 @@ func Load(getenv func(string) string) (*Config, error) {
bad("%s is needed on the %s edition, to send invitations and password resets: smtp://user:password@mail.example.com:587", EnvMailURL, c.Edition.Name())
}
c.PGBackups = get(EnvPGBackups, "")
if len(problems) > 0 {
return c, errors.New(strings.Join(problems, "\n"))
}
+50
View File
@@ -7,6 +7,7 @@ import (
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"time"
@@ -59,6 +60,10 @@ func (s *Server) backupsPage(w http.ResponseWriter, r *http.Request) {
}
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)
@@ -82,6 +87,10 @@ func (s *Server) renderBackups(w http.ResponseWriter, r *http.Request, errMsg, f
}
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
@@ -124,6 +133,10 @@ func (s *Server) backupsAction(w http.ResponseWriter, r *http.Request) {
// 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)
@@ -208,3 +221,40 @@ func (s *Server) backupUpload(w http.ResponseWriter, r *http.Request) {
}
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})
}
+21
View File
@@ -14,6 +14,7 @@ import (
"time"
"supermarket/internal/backup"
"supermarket/internal/users"
)
func TestBackupsPage(t *testing.T) {
@@ -125,3 +126,23 @@ func TestBackupUpload(t *testing.T) {
t.Errorf("temporary files left: %v", left)
}
}
func TestServerBackupsPage(t *testing.T) {
if !db.OnPostgres() {
t.Skip("the server's backups page is Postgres's")
}
s, h := newServerEdition(t)
dir := t.TempDir()
s.Config.PGBackups = dir
os.WriteFile(filepath.Join(dir, "supermarket-2026-11-24.dump"), []byte("x"), 0o600)
os.WriteFile(filepath.Join(dir, "notes.txt"), []byte("x"), 0o600)
owner := addUser(t, s, "owner@example.com", users.Owner, nil)
c := sessionFor(t, s, owner)
body := as(h, c, http.MethodGet, "/settings/backups", nil).Body.String()
if !strings.Contains(body, "supermarket-2026-11-24.dump") || strings.Contains(body, "notes.txt") || !strings.Contains(body, "pg_restore") {
t.Errorf("page: %s", body)
}
if rec := as(h, c, http.MethodPost, "/settings/backups/now", url.Values{}); rec.Code != http.StatusNotFound {
t.Errorf("back up now on Postgres: %d", rec.Code)
}
}
@@ -0,0 +1,29 @@
{{define "content"}}{{template "settings-start" .}}{{with .Data}}
<h2>Backups</h2>
<p class="lede">Supermarket's database is Postgres, on the server. It's dumped every night at 03:00, and two weeks of dumps are kept. Keys and tokens are in it too, encrypted with the server's secret key: a dump restored elsewhere needs that key as well.</p>
{{if not .Dir}}
<section class="card warn"><p>Supermarket doesn't know where the dumps are (<code>SUPERMARKET_PG_BACKUPS</code>). With <code>compose.server.yaml</code>, they're in the <code>pgbackups</code> volume; whoever runs Postgres otherwise backs it up their own way.</p></section>
{{else}}
{{with .Err}}<p class="error">The dumps can't be read: {{.}}</p>{{end}}
{{with .Stale}}<p class="error">The last dump is from {{.Local.Format "2 Jan 2006"}}: the nightly backup isn't working. Check the backup service's log on the server.</p>{{end}}
{{if .Dumps}}
<p class="small">{{len .Dumps}} dump{{if ne (len .Dumps) 1}}s{{end}}, {{bytes .Total}} in all.</p>
<div class="table-wrap"><table>
<thead><tr><th>Made</th><th>File</th><th class="num">Size</th></tr></thead>
<tbody>{{range .Dumps}}<tr><td>{{.At.Local.Format "2 Jan 2006, 15:04"}}<br><span class="small muted">{{ago .At}}</span></td><td><code>{{.Name}}</code></td><td class="num">{{bytes .Size}}</td></tr>{{end}}</tbody>
</table></div>
{{else if not .Err}}<section class="card empty"><p>No dumps yet: the first is made when the backup service starts.</p></section>{{end}}
{{end}}
<section class="card">
<h2>Restoring</h2>
<p>Restoring is done on the server, by whoever runs it, so that no one can undo the team's work from a browser. Stop Supermarket, restore the dump over the database, and start it again:</p>
<pre id="restore">docker compose -f compose.server.yaml --env-file server.env stop supermarket
docker compose -f compose.server.yaml --env-file server.env exec backup \
pg_restore --clean --if-exists --no-owner -d supermarket /backups/supermarket-YYYY-MM-DD.dump
docker compose -f compose.server.yaml --env-file server.env start supermarket</pre>
<button type="button" class="secondary small" data-copy="restore">Copy</button>
<p class="help">To move to another server, <code>supermarket export</code> and <code>supermarket import</code> work too, from either database to either.</p>
</section>
{{end}}{{template "settings-end"}}{{end}}