backup

package
v0.0.0-...-95891f2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: AGPL-3.0 Imports: 28 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package backup provides the admin-facing UI for triggering whole-database backups and inspecting prior runs. The actual backup mechanics live in scripts/backup.sh — this package shells out to that script under a timeout and a single-flight lock so a flood of admin clicks (or a runaway browser refresh) cannot spawn parallel mysqldumps.

Restore is intentionally a separate package (internal/plugins/restore) because its blast radius is much larger. See ADR-035 (and the planned ADR-036 reversal) in .ai/decisions.md for the policy reasoning.

Index

Constants

View Source
const (
	DefaultScheduleHour = 3
	DefaultKeepDays     = 7
	MinKeepDays         = 1
	MaxKeepDays         = 90
)

Defaults and bounds for the daily backup. Keep is in days because the script prunes by the date in each file name; with one run a day that is the same as "the last N backups".

View Source
const CheckFreshFor = 24 * time.Hour

CheckFreshFor is how new a finished backup must be for the site check-up to read it back instead of making its own. With daily backups on, last night's backup is always this new, so the check-up adds no extra run.

Variables

View Source
var ErrAlreadyRunning = fmt.Errorf("backup already running")

ErrAlreadyRunning is returned by RunBackup when another invocation is in flight. Callers translate this into HTTP 409 (Conflict).

Functions

func RegisterRoutes

func RegisterRoutes(admin *echo.Group, h *Handler, reauth echo.MiddlewareFunc)

RegisterRoutes mounts the admin backup routes on the given group. The caller is responsible for the auth gate; this package assumes the group already requires site-admin.

Rate limits are deliberately tight: backup is heavy, downloads are large, and the only legitimate caller is a human admin clicking occasionally. Lower bounds prevent click-flooding from spawning parallel mysqldumps even with the in-process single-flight lock as a backstop.

reauth guards the link route: the download itself is a plain GET a browser follows, so the password re-confirmation happens when the short-lived link is requested, and the GET only honours a link minted for that admin and file.

func ResolveArtifactPath

func ResolveArtifactPath(backupDir, name string) (string, error)

ResolveArtifactPath validates a basename against BACKUP_DIR and returns the absolute path if and only if the file exists inside that directory. Rejects path-traversal attempts and any name that escapes the configured backup root after Clean. Used by the download handler.

func SaveSchedule

func SaveSchedule(ctx context.Context, st SettingsStore, s Schedule) error

SaveSchedule validates and stores the schedule.

func VerifyBackup

func VerifyBackup(backupDir, manifestName string) error

VerifyBackup reads a finished backup's database dump back from end to end without loading it anywhere: the checksum the manifest recorded must still match, the file must decompress completely, the dump must have finished, and the core tables must be inside. It catches the backups that would fail a restore (cut short, empty, damaged) using only read access, since the app's database account cannot create a scratch database to restore into.

manifestName is a basename inside backupDir. The error says, in plain words, which check failed.

Types

type ActivityRecorder

type ActivityRecorder interface {
	RecordAdminChange(c *echo.Context, action, targetType, targetID, label string)
}

ActivityRecorder is the slice of the admin change log this plugin writes to. It is declared here, not imported from the admin plugin, so the plugins stay independent; app wiring supplies an adapter that stamps the signed-in admin. Recording is best-effort: implementations must not fail the request.

type Artifact

type Artifact struct {
	// Name is the basename. Validated against BACKUP_DIR for traversal
	// safety before any download.
	Name string

	// SizeBytes is the on-disk size at scan time.
	SizeBytes int64

	// ModTime is the filesystem mtime, used as the "created at" label.
	ModTime time.Time

	// Kind classifies the artifact. Known kinds: "db", "media", "redis",
	// "manifest", "pre-migrate", "other". Used for grouping in the UI.
	Kind string
}

Artifact describes one file in BACKUP_DIR. The admin UI lists these so operators can confirm the latest backup landed and download an artifact from outside the host shell when convenient.

type BackupCheck

type BackupCheck struct {
	At       time.Time `json:"at"`
	BackupAt time.Time `json:"backupAt,omitempty"` // when the checked backup was made
	MadeNow  bool      `json:"madeNow,omitempty"`  // the check made this backup itself
	OK       bool      `json:"ok"`
	Problem  string    `json:"problem,omitempty"` // a plain sentence when !OK
}

BackupCheck is the outcome of the site check-up's backup check.

func CheckBackup

func CheckBackup(ctx context.Context, svc Service, store SettingsStore, now time.Time) (BackupCheck, error)

CheckBackup proves the site has a backup a restore could use: it reads the newest finished backup back from end to end, first making one when none is newer than CheckFreshFor. A backup it makes keeps the daily schedule's retention when that is on, and otherwise the same retention as the Run backup button, so the check-up never deletes more than the owner chose. ErrAlreadyRunning is returned untouched so the caller can try again later.

type Config

type Config struct {
	// ScriptPath is the absolute path to backup.sh. Required.
	ScriptPath string

	// BackupDir is where backup.sh writes artifacts. Defaults to the
	// script's own default if empty (i.e. /app/data/backups in the
	// container). Must match the BACKUP_DIR env var the script reads.
	BackupDir string

	// Timeout caps a single RunBackup invocation. Default 20 minutes.
	Timeout time.Duration
}

Config holds tunables for the service. Defaults are sensible for a production deployment; tests inject smaller values to exercise the timeout path without sleeping for minutes.

type FailureNotifier

type FailureNotifier interface {
	BackupFailed(ctx context.Context, run ScheduledRun) error
}

FailureNotifier tells site admins a scheduled backup failed. Optional.

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

Handler renders the admin backup page and accepts the "run backup" and "download artifact" actions. All routes are mounted under /admin/backup and inherit RequireSiteAdmin from the parent group.

func NewHandler

func NewHandler(svc Service) *Handler

NewHandler constructs a Handler against the given Service. Downloads fail closed until SetDownloadAuth supplies the identity lookup.

func (*Handler) Download

func (h *Handler) Download(c *echo.Context) error

Download serves a single artifact file (GET /admin/backup/files/:name). It requires a valid token from DownloadLink for this user and file name, so the file cannot be fetched without a recent re-confirmation. The :name parameter is validated against BACKUP_DIR; any attempt at path traversal is rejected with 400.

Uses middleware.ServeAttachment, which Go-quotes the filename in the Content-Disposition header. ResolveArtifactPath rejects path separators and ".." but does not reject quotes or newlines in basenames — Linux filesystems allow both. Without proper encoding, an admin who renamed a backup artifact on disk to include `"` or `\n` could inject HTTP headers via this response.

func (h *Handler) DownloadLink(c *echo.Context) error

DownloadLink mints a short-lived download URL (POST /admin/backup/files/:name/link). The route sits behind the reauth middleware, so a token only exists after a recent password confirmation. The name is validated exactly as Download does.

func (*Handler) Page

func (h *Handler) Page(c *echo.Context) error

Page renders the backup dashboard (GET /admin/backup).

func (*Handler) Run

func (h *Handler) Run(c *echo.Context) error

Run triggers a backup (POST /admin/backup/run). The actual shell-out happens synchronously here — backups are infrequent and a 20-minute browser hang on the admin who clicked the button is acceptable. The rate limiter on the route prevents click-flooding.

If a backup is already in flight (e.g. the admin double-clicked, or another admin is running one), we return 409 rather than coalescing — operators benefit from knowing their click didn't start a fresh run.

func (*Handler) SaveSchedule

func (h *Handler) SaveSchedule(c *echo.Context) error

SaveSchedule stores the daily backup choice (POST /admin/backup/schedule).

func (*Handler) SetActivityRecorder

func (h *Handler) SetActivityRecorder(r ActivityRecorder)

SetActivityRecorder wires the admin change log. Optional: nil disables it.

func (*Handler) SetDownloadAuth

func (h *Handler) SetDownloadAuth(secret string, userID func(*echo.Context) string)

SetDownloadAuth wires the signing secret and the current-user lookup used to bind download tokens to the admin who re-confirmed. The lookup is injected so this plugin does not import the auth plugin. An empty secret keeps the per-process random key.

func (*Handler) SetScheduleStore

func (h *Handler) SetScheduleStore(st SettingsStore)

SetScheduleStore wires the site settings that hold the daily backup schedule. Without it the page leaves the schedule card out.

type RunResult

type RunResult struct {
	StartedAt   time.Time
	FinishedAt  time.Time
	ExitCode    int
	Stdout      string
	Stderr      string
	TimedOut    bool
	ErrorString string // populated when the run could not start at all
}

RunResult captures the outcome of one backup invocation. ExitCode follows the script's own convention: 0 success, 1 operator error, 2 precondition failure, 3 tool failure.

func (*RunResult) Duration

func (r *RunResult) Duration() time.Duration

Duration returns how long the run took. Zero if FinishedAt is unset.

func (*RunResult) Succeeded

func (r *RunResult) Succeeded() bool

Succeeded reports whether the run finished with exit code 0 and did not time out.

type Schedule

type Schedule struct {
	Enabled  bool
	Hour     int // 0-23, server time
	KeepDays int
}

Schedule is the owner's daily backup choice.

func LoadSchedule

func LoadSchedule(ctx context.Context, st SettingsStore) (Schedule, error)

LoadSchedule reads the schedule, falling back to defaults (off) for keys never saved or holding values out of range.

func (Schedule) Validate

func (s Schedule) Validate() error

Validate rejects values the form can't produce, so a crafted POST can't store an hour that never comes round or a retention that prunes everything.

type ScheduledRun

type ScheduledRun struct {
	At     time.Time `json:"at"`
	Day    string    `json:"day"` // server-local YYYY-MM-DD the run counted for
	OK     bool      `json:"ok"`
	Detail string    `json:"detail,omitempty"`
}

ScheduledRun is the outcome of the last scheduled backup. It is stored so the Backup page can show it after a restart, and so a restart inside the chosen hour doesn't run the same day's backup twice.

func LoadLastScheduledRun

func LoadLastScheduledRun(ctx context.Context, st SettingsStore) (*ScheduledRun, error)

LoadLastScheduledRun returns the stored last scheduled run, or nil.

type Scheduler

type Scheduler struct {
	// contains filtered or unexported fields
}

Scheduler runs the daily backup from inside the server process.

func NewScheduler

func NewScheduler(svc Service, store SettingsStore, notifier FailureNotifier) *Scheduler

NewScheduler builds a Scheduler. notifier may be nil.

func (*Scheduler) Run

func (s *Scheduler) Run(ctx context.Context)

Run checks once a minute until ctx ends. Call it in its own goroutine.

type Service

type Service interface {
	// RunBackup invokes scripts/backup.sh under the configured timeout.
	// Returns ErrAlreadyRunning if a backup is in progress; the caller
	// should surface that as 429-style "try again later" rather than
	// silently coalescing — operators want to know their click did not
	// start a fresh run.
	RunBackup(ctx context.Context) (*RunResult, error)

	// RunBackupKeeping is RunBackup with the script's retention set to
	// keepDays, so the scheduled run prunes to the owner's chosen window.
	// keepDays <= 0 leaves the script's own default.
	RunBackupKeeping(ctx context.Context, keepDays int) (*RunResult, error)

	// ListBackups returns the artifacts currently in the backup directory
	// as Lister sees them. Read-only; never mutates disk.
	ListBackups() ([]Artifact, error)

	// LastRun returns the most recent RunResult observed by this service
	// instance, or nil if no backup has run since boot.
	LastRun() *RunResult

	// IsRunning reports whether a backup is currently in flight.
	IsRunning() bool

	// BackupDir returns the configured backup directory path. Used by the
	// download handler to validate filename parameters against a known
	// root.
	BackupDir() string
}

Service is the admin-facing backup operations interface. Hidden behind an interface so tests can stub the script execution without spawning real mysqldump processes.

func NewService

func NewService(cfg Config) Service

NewService constructs a Service. Panics on missing ScriptPath because the caller has no recovery path for that — it is a wiring bug, not a runtime condition.

type SettingsStore

type SettingsStore interface {
	Get(ctx context.Context, key string) (string, error)
	Set(ctx context.Context, key, value string) error
}

SettingsStore is the slice of the site settings repository this package uses. Get returns an apperror NotFound for a key never set.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL