From 29dec6488d86aa5ac08fc8381c3b83cb78b08914 Mon Sep 17 00:00:00 2001 From: mouldybread <38598858+mouldybread@users.noreply.github.com> Date: Sun, 29 Nov 2026 05:48:31 +0800 Subject: [PATCH 01/12] Add recording filesystem usage measurement and 5-minute monitor job (#14 CP2) Read-only: measures used % of the /recordings filesystem every 5 minutes (first check 5 minutes after startup) in its own background job joined on shutdown. Failures are logged and leave usage unknown. No deletion, setting or UI yet. --- cmd/simplenvr/main.go | 1 + cmd/simplenvr/storage_usage.go | 128 ++++++++++++++++++ cmd/simplenvr/storage_usage_test.go | 202 ++++++++++++++++++++++++++++ docs/FILESYSTEM_USAGE.md | 50 +++++++ 4 files changed, 381 insertions(+) create mode 100644 cmd/simplenvr/storage_usage.go create mode 100644 cmd/simplenvr/storage_usage_test.go create mode 100644 docs/FILESYSTEM_USAGE.md diff --git a/cmd/simplenvr/main.go b/cmd/simplenvr/main.go index ae1b76b..3cac925 100644 --- a/cmd/simplenvr/main.go +++ b/cmd/simplenvr/main.go @@ -145,6 +145,7 @@ func main() { server:=&http.Server{Addr:":443",Handler:gate,ReadHeaderTimeout:10*time.Second,ReadTimeout:30*time.Second,IdleTimeout:60*time.Second,MaxHeaderBytes:32768} autoStartRecordings() gate.startBackgroundJob(func(ctx context.Context){cleanupRoutine(ctx,nvr)}) + gate.startBackgroundJob(recordingFilesystemUsage.Run) log.Println("SimpleNVR starting authenticated HTTPS server on :443...") serveErr:=runAuthenticatedServer(appCtx,nvr,gate,server,certPath,keyPath) cleanupCtx,cancel:=context.WithTimeout(context.Background(),5*time.Second);defer cancel() diff --git a/cmd/simplenvr/storage_usage.go b/cmd/simplenvr/storage_usage.go new file mode 100644 index 0000000..ae1158c --- /dev/null +++ b/cmd/simplenvr/storage_usage.go @@ -0,0 +1,128 @@ +package main + +import ( + "context" + "errors" + "log" + "sync" + "time" + + "golang.org/x/sys/unix" +) + +// recordingsRoot is the one filesystem whose usage is measured. Every camera +// directory is /recordings/ (see validateCameraPath). +const recordingsRoot = "/recordings" + +// The first measurement is taken one interval after startup, not immediately. +const filesystemUsageInterval = 5 * time.Minute + +var errFilesystemUsage = errors.New("unable to measure recording filesystem usage") + +// filesystemUsage is a filesystem-wide observation. It includes data that does not +// belong to SimpleNVR and is not a count of camera media bytes. +type filesystemUsage struct { + UsedPercent float64 + AvailableBytes uint64 + ObservedAt time.Time +} + +// filesystemUsedPercent uses the df convention: used / (used + available), where +// used is total minus free blocks and available is the blocks a non-privileged +// process may use. Blocks reserved for privileged users therefore count as used. +// Block counts are converted to floating point so no integer arithmetic can +// overflow. Inconsistent counts are an error, never a guessed percentage. +func filesystemUsedPercent(blocks, free, available uint64) (float64, error) { + if blocks == 0 || free > blocks || available > free { + return 0, errFilesystemUsage + } + used := float64(blocks - free) + total := used + float64(available) + if total == 0 { + return 0, errFilesystemUsage + } + return used * 100 / total, nil +} + +// readFilesystemUsage opens the directory itself without following symlinks, so a +// replaced or missing directory is an error rather than a different filesystem. +func readFilesystemUsage(dir string) (filesystemUsage, error) { + fd, err := unix.Open(dir, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) + if err != nil { + return filesystemUsage{}, errFilesystemUsage + } + defer unix.Close(fd) + var stat unix.Statfs_t + if err := unix.Fstatfs(fd, &stat); err != nil { + return filesystemUsage{}, errFilesystemUsage + } + percent, err := filesystemUsedPercent(uint64(stat.Blocks), uint64(stat.Bfree), uint64(stat.Bavail)) + if err != nil { + return filesystemUsage{}, err + } + available, err := availableStorageBytes(uint64(stat.Bavail), int64(stat.Bsize)) + if err != nil { + return filesystemUsage{}, err + } + return filesystemUsage{UsedPercent: percent, AvailableBytes: available, ObservedAt: time.Now().UTC()}, nil +} + +// filesystemUsageMonitor keeps the latest observation. A failed measurement makes +// usage unknown (it never keeps an old value) and is logged. It deletes nothing. +type filesystemUsageMonitor struct { + dir string + interval time.Duration + read func(string) (filesystemUsage, error) + + mu sync.RWMutex + latest filesystemUsage + known bool +} + +func newFilesystemUsageMonitor(dir string, read func(string) (filesystemUsage, error)) *filesystemUsageMonitor { + return &filesystemUsageMonitor{dir: dir, interval: filesystemUsageInterval, read: read} +} + +var recordingFilesystemUsage = newFilesystemUsageMonitor(recordingsRoot, readFilesystemUsage) + +// Latest returns the last successful observation, or false while usage is unknown. +func (m *filesystemUsageMonitor) Latest() (filesystemUsage, bool) { + m.mu.RLock() + defer m.mu.RUnlock() + return m.latest, m.known +} + +func (m *filesystemUsageMonitor) sample() { + usage, err := m.read(m.dir) + m.mu.Lock() + defer m.mu.Unlock() + if err != nil { + m.latest, m.known = filesystemUsage{}, false + log.Printf("Recording filesystem usage unavailable: %v", err) + return + } + m.latest, m.known = usage, true +} + +func (m *filesystemUsageMonitor) run(ctx context.Context, ticks <-chan time.Time) { + for { + select { + case <-ctx.Done(): + return + case _, ok := <-ticks: + if !ok || ctx.Err() != nil { + return + } + m.sample() + } + } +} + +// Run blocks until ctx is canceled. Start it with shutdownGate.startBackgroundJob so +// shutdown cancels and joins it before final persistence. +func (m *filesystemUsageMonitor) Run(ctx context.Context) { + ticker := time.NewTicker(m.interval) + defer ticker.Stop() + log.Println("Filesystem usage monitor started") + m.run(ctx, ticker.C) +} diff --git a/cmd/simplenvr/storage_usage_test.go b/cmd/simplenvr/storage_usage_test.go new file mode 100644 index 0000000..5bc563f --- /dev/null +++ b/cmd/simplenvr/storage_usage_test.go @@ -0,0 +1,202 @@ +package main + +import ( + "bytes" + "context" + "errors" + "log" + "math" + "net/http" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" +) + +func TestFilesystemUsedPercent(t *testing.T) { + cases := []struct { + name string + blocks, free, avail uint64 + want float64 + fail bool + }{ + {"half used", 100, 50, 50, 50, false}, + {"reserved blocks count as used", 100, 20, 10, 8000.0 / 90.0, false}, + {"empty", 100, 100, 100, 0, false}, + {"full", 100, 0, 0, 100, false}, + {"huge counts do not overflow", math.MaxUint64, math.MaxUint64 / 2, math.MaxUint64 / 2, 50, false}, + {"zero blocks", 0, 0, 0, 0, true}, + {"free above total", 10, 11, 5, 0, true}, + {"available above free", 100, 10, 20, 0, true}, + {"nothing used and nothing available", 100, 100, 0, 0, true}, + } + for _, item := range cases { + got, err := filesystemUsedPercent(item.blocks, item.free, item.avail) + if item.fail { + if !errors.Is(err, errFilesystemUsage) || got != 0 { + t.Fatalf("%s: expected failure, got %v %v", item.name, got, err) + } + continue + } + if err != nil || math.Abs(got-item.want) > 1e-9 { + t.Fatalf("%s: got %v %v, want %v", item.name, got, err, item.want) + } + } +} + +func TestReadFilesystemUsageRefusesUnsafeDirectories(t *testing.T) { + dir := t.TempDir() + link := filepath.Join(dir, "link") + if err := os.Symlink(dir, link); err != nil { + t.Fatal(err) + } + file := filepath.Join(dir, "file") + if err := os.WriteFile(file, []byte("x"), 0600); err != nil { + t.Fatal(err) + } + for _, path := range []string{filepath.Join(dir, "missing"), link, file} { + if _, err := readFilesystemUsage(path); !errors.Is(err, errFilesystemUsage) { + t.Fatalf("%s: expected measurement failure, got %v", filepath.Base(path), err) + } + } +} + +func TestReadFilesystemUsageRealDirectory(t *testing.T) { + usage, err := readFilesystemUsage(t.TempDir()) + if err != nil { + t.Skipf("test filesystem does not report usable block counts: %v", err) + } + if usage.UsedPercent < 0 || usage.UsedPercent > 100 || usage.ObservedAt.IsZero() { + t.Fatalf("implausible observation: %+v", usage) + } +} + +func newTestUsageMonitor(read func(string) (filesystemUsage, error)) *filesystemUsageMonitor { + return newFilesystemUsageMonitor("/unused", read) +} + +func TestFilesystemUsageMonitorUsesFiveMinutesAndNoImmediateRead(t *testing.T) { + if filesystemUsageInterval != 5*time.Minute { + t.Fatalf("interval changed: %v", filesystemUsageInterval) + } + var reads atomic.Int32 + m := newTestUsageMonitor(func(string) (filesystemUsage, error) { + reads.Add(1) + return filesystemUsage{UsedPercent: 10}, nil + }) + if m.interval != filesystemUsageInterval || m.dir != "/unused" { + t.Fatalf("unexpected monitor configuration: %v %q", m.interval, m.dir) + } + if _, ok := m.Latest(); ok || reads.Load() != 0 { + t.Fatal("usage must be unknown and unread before the first tick") + } + if recordingFilesystemUsage.dir != recordingsRoot || recordingsRoot != "/recordings" { + t.Fatal("production monitor must measure /recordings") + } +} + +func TestFilesystemUsageMonitorSamplesPerTickAndLogsFailure(t *testing.T) { + var logs bytes.Buffer + old := log.Writer() + log.SetOutput(&logs) + t.Cleanup(func() { log.SetOutput(old) }) + var fail atomic.Bool + var reads atomic.Int32 + m := newTestUsageMonitor(func(string) (filesystemUsage, error) { + reads.Add(1) + if fail.Load() { + return filesystemUsage{}, errFilesystemUsage + } + return filesystemUsage{UsedPercent: 42, AvailableBytes: 7}, nil + }) + runTicks := func(n int) { + ticks := make(chan time.Time, n) + for i := 0; i < n; i++ { + ticks <- time.Now() + } + close(ticks) + done := make(chan struct{}) + go func() { + defer close(done) + m.run(context.Background(), ticks) + }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("monitor did not stop") + } + } + runTicks(2) + if reads.Load() != 2 { + t.Fatalf("expected one read per tick, got %d", reads.Load()) + } + if usage, ok := m.Latest(); !ok || usage.UsedPercent != 42 || usage.AvailableBytes != 7 { + t.Fatalf("unexpected observation: %+v %v", usage, ok) + } + fail.Store(true) + runTicks(1) + if _, ok := m.Latest(); ok { + t.Fatal("failed measurement must make usage unknown") + } + if !strings.Contains(logs.String(), "Recording filesystem usage unavailable") || strings.Contains(logs.String(), "/recordings") { + t.Fatalf("failure was not logged safely: %q", logs.String()) + } + fail.Store(false) + runTicks(1) + if _, ok := m.Latest(); !ok { + t.Fatal("usage did not recover after a successful measurement") + } +} + +func TestCanceledFilesystemUsageTickDoesNotRead(t *testing.T) { + var reads atomic.Int32 + m := newTestUsageMonitor(func(string) (filesystemUsage, error) { + reads.Add(1) + return filesystemUsage{}, nil + }) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + ticks := make(chan time.Time, 1) + ticks <- time.Now() + done := make(chan struct{}) + go func() { + defer close(done) + m.run(ctx, ticks) + }() + awaitShutdownStep(t, done, "canceled monitor did not exit") + if reads.Load() != 0 { + t.Fatal("canceled monitor still read the filesystem") + } +} + +func TestFilesystemUsageMonitorIsCanceledAndJoinedOnShutdown(t *testing.T) { + n := &NVR{cameras: map[string]*Camera{}} + gate := newShutdownGate(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + m := newTestUsageMonitor(func(string) (filesystemUsage, error) { + t.Error("monitor read before its first interval") + return filesystemUsage{}, nil + }) + started, exited := make(chan struct{}), make(chan struct{}) + if !gate.startBackgroundJob(func(ctx context.Context) { + close(started) + m.Run(ctx) + close(exited) + }) { + t.Fatal("monitor job rejected before shutdown") + } + awaitShutdownStep(t, started, "monitor job not started") + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := shutdownApplication(ctx, n, gate, nil, func() error { return nil }); err != nil { + t.Fatal(err) + } + awaitShutdownStep(t, exited, "shutdown did not cancel and join the monitor") + gate.mu.Lock() + remaining := len(gate.jobs) + gate.mu.Unlock() + if remaining != 0 { + t.Fatalf("background job registration leaked: %d", remaining) + } +} diff --git a/docs/FILESYSTEM_USAGE.md b/docs/FILESYSTEM_USAGE.md new file mode 100644 index 0000000..3a05497 --- /dev/null +++ b/docs/FILESYSTEM_USAGE.md @@ -0,0 +1,50 @@ +# Recording filesystem usage (issue #14, CP2) + +SimpleNVR measures how full the recordings filesystem is. This checkpoint only +measures; it adds no setting, no display and no deletion. + +## What is measured + +The used percentage of the filesystem that holds `/recordings`. Every camera +directory is `/recordings/`, so one filesystem is measured. The value is +filesystem-wide: it includes anything else stored on that filesystem and is not a +count of camera media bytes. The per-camera Disk Usage figure in the camera list +is a different number and is unchanged (see [DISK_USAGE.md](DISK_USAGE.md)). + +## Formula + +From `fstatfs` block counts, the same convention as `df`: + + used = total blocks - free blocks + percent = used / (used + available blocks) * 100 + +"Available" is the blocks a non-privileged process may use, so blocks reserved +for privileged users count as used. Counts are converted to floating point so +large filesystems cannot overflow. Zero total blocks, free blocks above total, +available blocks above free, or nothing used and nothing available are treated +as a failed measurement, not as a percentage. + +The directory is opened without following symlinks and must be a directory, so +a missing or replaced directory is an error rather than another filesystem. + +## When it runs + +A background job started through the shutdown gate measures every 5 minutes. The +first measurement is 5 minutes after startup, so usage is unknown until then. +Shutdown cancels and joins the job before final persistence. + +## When measurement fails + +Usage becomes unknown (an earlier value is not kept), and a log line says that +recording filesystem usage is unavailable. The log does not include the path. +Later checkpoints must not delete anything while usage is unknown. + +## Limits + +- Quotas, ZFS datasets and snapshots, and other volume features decide what the + filesystem reports. The percentage is whatever `fstatfs` reports for that + directory. +- It is not a quota, a reservation, or proof that recording can continue. +- `SIMPLENVR_MIN_FREE_BYTES` is unchanged and independent. +- Verified only by unit tests and CI. It has not been run on the deployment + filesystem. From 60df3d728157d50d1bf6231e468723594f7de7d7 Mon Sep 17 00:00:00 2001 From: mouldybread <38598858+mouldybread@users.noreply.github.com> Date: Sun, 29 Nov 2026 05:55:59 +0800 Subject: [PATCH 02/12] Share one statfs reader between storage status and filesystem usage (#14 CP2) Add readRecordingFilesystemStats (no-follow open + Fstatfs returning raw counts). readRecordingStorageCapacity keeps its result and errors; readFilesystemUsage now uses the same reader instead of duplicating it. --- cmd/simplenvr/storage_status.go | 26 +++++++++++++++++++++----- cmd/simplenvr/storage_usage.go | 19 ++++++------------- 2 files changed, 27 insertions(+), 18 deletions(-) diff --git a/cmd/simplenvr/storage_status.go b/cmd/simplenvr/storage_status.go index 2bc02a1..f0394d1 100644 --- a/cmd/simplenvr/storage_status.go +++ b/cmd/simplenvr/storage_status.go @@ -50,15 +50,31 @@ func availableStorageBytes(blocks uint64,size int64) (uint64,error) { return blocks*uint64(size),nil } -func readRecordingStorageCapacity(dir string) (*recordingStorageCapacity,error) { +// recordingFilesystemStats are the raw counts the kernel reports for the filesystem +// holding one directory. Every capacity or usage figure is derived from these. +type recordingFilesystemStats struct { + Blocks,Free,Available uint64 + BlockSize int64 + Files,FreeInodes uint64 +} + +// readRecordingFilesystemStats opens the directory itself without following symlinks +// and reads its filesystem with Fstatfs, so a missing, replaced or non-directory +// path is an error rather than another filesystem. +func readRecordingFilesystemStats(dir string) (recordingFilesystemStats,error) { fd,err:=unix.Open(dir,unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC,0) - if err!=nil {return nil,errStorageUnavailable} + if err!=nil {return recordingFilesystemStats{},errStorageUnavailable} defer unix.Close(fd) var stat unix.Statfs_t - if err:=unix.Fstatfs(fd,&stat);err!=nil {return nil,errStorageUnavailable} - available,err:=availableStorageBytes(uint64(stat.Bavail),int64(stat.Bsize));if err!=nil {return nil,err} + if err:=unix.Fstatfs(fd,&stat);err!=nil {return recordingFilesystemStats{},errStorageUnavailable} + return recordingFilesystemStats{Blocks:uint64(stat.Blocks),Free:uint64(stat.Bfree),Available:uint64(stat.Bavail),BlockSize:int64(stat.Bsize),Files:uint64(stat.Files),FreeInodes:uint64(stat.Ffree)},nil +} + +func readRecordingStorageCapacity(dir string) (*recordingStorageCapacity,error) { + stats,err:=readRecordingFilesystemStats(dir);if err!=nil {return nil,err} + available,err:=availableStorageBytes(stats.Available,stats.BlockSize);if err!=nil {return nil,err} capacity:=&recordingStorageCapacity{AvailableBytes:available} - if stat.Files>0 {free:=uint64(stat.Ffree);capacity.FreeInodes=&free} + if stats.Files>0 {free:=stats.FreeInodes;capacity.FreeInodes=&free} return capacity,nil } diff --git a/cmd/simplenvr/storage_usage.go b/cmd/simplenvr/storage_usage.go index ae1158c..f4a0d43 100644 --- a/cmd/simplenvr/storage_usage.go +++ b/cmd/simplenvr/storage_usage.go @@ -6,8 +6,6 @@ import ( "log" "sync" "time" - - "golang.org/x/sys/unix" ) // recordingsRoot is the one filesystem whose usage is measured. Every camera @@ -44,25 +42,20 @@ func filesystemUsedPercent(blocks, free, available uint64) (float64, error) { return used * 100 / total, nil } -// readFilesystemUsage opens the directory itself without following symlinks, so a -// replaced or missing directory is an error rather than a different filesystem. +// readFilesystemUsage derives usage from the shared raw reader, so a missing, +// replaced or non-directory path is an error rather than a different filesystem. func readFilesystemUsage(dir string) (filesystemUsage, error) { - fd, err := unix.Open(dir, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) + stats, err := readRecordingFilesystemStats(dir) if err != nil { return filesystemUsage{}, errFilesystemUsage } - defer unix.Close(fd) - var stat unix.Statfs_t - if err := unix.Fstatfs(fd, &stat); err != nil { - return filesystemUsage{}, errFilesystemUsage - } - percent, err := filesystemUsedPercent(uint64(stat.Blocks), uint64(stat.Bfree), uint64(stat.Bavail)) + percent, err := filesystemUsedPercent(stats.Blocks, stats.Free, stats.Available) if err != nil { return filesystemUsage{}, err } - available, err := availableStorageBytes(uint64(stat.Bavail), int64(stat.Bsize)) + available, err := availableStorageBytes(stats.Available, stats.BlockSize) if err != nil { - return filesystemUsage{}, err + return filesystemUsage{}, errFilesystemUsage } return filesystemUsage{UsedPercent: percent, AvailableBytes: available, ObservedAt: time.Now().UTC()}, nil } From cd216539f2a67ba31c26d06cd94d4699710d9b62 Mon Sep 17 00:00:00 2001 From: mouldybread <38598858+mouldybread@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:15:29 +0800 Subject: [PATCH 03/12] CP3 (#14): filesystem usage ceiling setting, API and settings display Add the persisted max_filesystem_used_percent setting (default 80, 10 to 95, written explicitly on every save), GET/POST /api/storage/ceiling, and a Filesystem Usage row in camera settings. No deletion yet. --- cmd/simplenvr/filesystem_ceiling.go | 145 ++++++++++++++++++ cmd/simplenvr/filesystem_ceiling_test.go | 179 +++++++++++++++++++++++ cmd/simplenvr/persistence.go | 5 +- web/static/js/filesystem-ceiling.js | 160 ++++++++++++++++++++ web/templates/index.html | 1 + 5 files changed, 489 insertions(+), 1 deletion(-) create mode 100644 cmd/simplenvr/filesystem_ceiling.go create mode 100644 cmd/simplenvr/filesystem_ceiling_test.go create mode 100644 web/static/js/filesystem-ceiling.js diff --git a/cmd/simplenvr/filesystem_ceiling.go b/cmd/simplenvr/filesystem_ceiling.go new file mode 100644 index 0000000..8d6b286 --- /dev/null +++ b/cmd/simplenvr/filesystem_ceiling.go @@ -0,0 +1,145 @@ +package main + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "log" + "math" + "net/http" + "strconv" + "sync" + "time" +) + +// The ceiling is the highest filesystem-used percentage the owner accepts. It is a +// setting only in this checkpoint; nothing reads it to delete anything yet. +const ( + defaultMaxFilesystemUsedPercent=80 + minMaxFilesystemUsedPercent=10 + maxMaxFilesystemUsedPercent=95 + filesystemPruneMarginPercent=2 + maxFilesystemCeilingRequestBytes=1024 +) + +var errFilesystemCeiling=errors.New("max_filesystem_used_percent must be a whole number from 10 to 95") + +type filesystemCeilingSetting struct { + mu sync.RWMutex + percent int +} + +func (s *filesystemCeilingSetting) get() int {s.mu.RLock();defer s.mu.RUnlock();return s.percent} +func (s *filesystemCeilingSetting) set(percent int) {s.mu.Lock();s.percent=percent;s.mu.Unlock()} + +var recordingFilesystemCeiling=&filesystemCeilingSetting{percent:defaultMaxFilesystemUsedPercent} + +// filesystemCeilingUpdateMu serializes updates so a failed save restores the value +// that was current before that update. +var filesystemCeilingUpdateMu sync.Mutex + +func validateFilesystemCeiling(percent int) error { + if percentmaxMaxFilesystemUsedPercent {return errFilesystemCeiling} + return nil +} + +// filesystemPruneTrigger is derived from the ceiling and never stored. +func filesystemPruneTrigger(ceiling int) int {return ceiling-filesystemPruneMarginPercent} + +// parseFilesystemCeilingValue accepts only a JSON integer literal in range. A +// string, fraction, exponent, null or boolean is refused. +func parseFilesystemCeilingValue(raw []byte) (int,error) { + percent,err:=strconv.Atoi(string(bytes.TrimSpace(raw))) + if err!=nil {return 0,errFilesystemCeiling} + if err=validateFilesystemCeiling(percent);err!=nil {return 0,err} + return percent,nil +} + +// storedFilesystemCeiling reads the top-level key from configuration. A missing key +// is the default; a present but invalid value is an error. +func storedFilesystemCeiling(raw []byte) (int,error) { + var doc struct {Value json.RawMessage `json:"max_filesystem_used_percent"`} + if err:=json.Unmarshal(raw,&doc);err!=nil {return 0,err} + if doc.Value==nil {return defaultMaxFilesystemUsedPercent,nil} + return parseFilesystemCeilingValue(doc.Value) +} + +// persistedDocument is what is written to cameras.json. persistedState stays a +// three-field struct so existing positional literals keep compiling; the embedded +// fields are written at the top level beside the ceiling. +type persistedDocument struct { + persistedState + MaxFilesystemUsedPercent int `json:"max_filesystem_used_percent"` +} + +type filesystemCeilingResponse struct { + Ceiling int `json:"max_filesystem_used_percent"` + Trigger int `json:"filesystem_prune_trigger_percent"` + Used *float64 `json:"filesystem_used_percent"` + ObservedAt *time.Time `json:"filesystem_observed_at"` +} + +type filesystemCeilingDeps struct { + setting *filesystemCeilingSetting + read func(string) (filesystemUsage,error) + save func() error +} + +func filesystemCeilingSnapshot(deps filesystemCeilingDeps) filesystemCeilingResponse { + ceiling:=deps.setting.get() + resp:=filesystemCeilingResponse{Ceiling:ceiling,Trigger:filesystemPruneTrigger(ceiling)} + usage,err:=deps.read(recordingsRoot) + if err==nil && !math.IsNaN(usage.UsedPercent) && !math.IsInf(usage.UsedPercent,0) { + used:=math.Round(usage.UsedPercent*10)/10 + observed:=usage.ObservedAt + resp.Used=&used;resp.ObservedAt=&observed + } + return resp +} + +func writeFilesystemCeiling(w http.ResponseWriter,deps filesystemCeilingDeps) { + w.Header().Set("Content-Type","application/json") + w.Header().Set("X-Content-Type-Options","nosniff") + json.NewEncoder(w).Encode(filesystemCeilingSnapshot(deps)) +} + +func updateFilesystemCeiling(w http.ResponseWriter,r *http.Request,deps filesystemCeilingDeps) { + r.Body=http.MaxBytesReader(w,r.Body,maxFilesystemCeilingRequestBytes) + dec:=json.NewDecoder(r.Body) + dec.DisallowUnknownFields() + var req struct {Value json.RawMessage `json:"max_filesystem_used_percent"`} + if err:=dec.Decode(&req);err!=nil || req.Value==nil {http.Error(w,errFilesystemCeiling.Error(),400);return} + var extra interface{} + if err:=dec.Decode(&extra);err!=io.EOF {http.Error(w,errFilesystemCeiling.Error(),400);return} + percent,err:=parseFilesystemCeilingValue(req.Value) + if err!=nil {http.Error(w,err.Error(),400);return} + filesystemCeilingUpdateMu.Lock() + defer filesystemCeilingUpdateMu.Unlock() + previous:=deps.setting.get() + deps.setting.set(percent) + if err=deps.save();err!=nil { + deps.setting.set(previous) + log.Printf("Saving filesystem usage ceiling failed: %v",err) + http.Error(w,"Failed to save filesystem usage ceiling",500) + return + } + writeFilesystemCeiling(w,deps) +} + +func serveFilesystemCeiling(w http.ResponseWriter,r *http.Request,deps filesystemCeilingDeps) { + w.Header().Set("Cache-Control","no-store") + switch r.Method { + case http.MethodGet: + writeFilesystemCeiling(w,deps) + case http.MethodPost: + updateFilesystemCeiling(w,r,deps) + default: + w.Header().Set("Allow","GET, POST") + http.Error(w,"Method not allowed",405) + } +} + +func filesystemCeilingHandler(w http.ResponseWriter,r *http.Request) { + serveFilesystemCeiling(w,r,filesystemCeilingDeps{setting:recordingFilesystemCeiling,read:readFilesystemUsage,save:nvr.save}) +} diff --git a/cmd/simplenvr/filesystem_ceiling_test.go b/cmd/simplenvr/filesystem_ceiling_test.go new file mode 100644 index 0000000..650869f --- /dev/null +++ b/cmd/simplenvr/filesystem_ceiling_test.go @@ -0,0 +1,179 @@ +package main + +import ( + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func resetFilesystemCeiling(t *testing.T,value int) { + t.Helper() + previous:=recordingFilesystemCeiling.get() + recordingFilesystemCeiling.set(value) + t.Cleanup(func(){recordingFilesystemCeiling.set(previous)}) +} + +func newCeilingNVR() *NVR { + return &NVR{cameras:map[string]*Camera{},cameraOrder:[]string{},events:[]Event{}} +} + +func TestValidateFilesystemCeilingRange(t *testing.T) { + for _,value:=range []int{10,11,80,94,95} { + if err:=validateFilesystemCeiling(value);err!=nil {t.Fatalf("%d refused: %v",value,err)} + } + for _,value:=range []int{-1,0,9,96,100,1000000} { + if err:=validateFilesystemCeiling(value);err==nil {t.Fatalf("%d accepted",value)} + } + if got:=filesystemPruneTrigger(80);got!=78 {t.Fatalf("trigger for 80 = %d",got)} + if got:=filesystemPruneTrigger(10);got!=8 {t.Fatalf("trigger for 10 = %d",got)} +} + +func TestStoredFilesystemCeiling(t *testing.T) { + valid:=map[string]int{`{}`:80,`{"max_filesystem_used_percent":10}`:10,`{"max_filesystem_used_percent":80}`:80,`{"max_filesystem_used_percent":95}`:95} + for raw,want:=range valid { + got,err:=storedFilesystemCeiling([]byte(raw)) + if err!=nil || got!=want {t.Fatalf("%s = %d, %v; want %d",raw,got,err,want)} + } + for _,value:=range []string{`9`,`96`,`-5`,`0`,`80.5`,`"80"`,`null`,`1e1`,`true`,`[]`,`{}`} { + raw:=`{"max_filesystem_used_percent":`+value+`}` + if got,err:=storedFilesystemCeiling([]byte(raw));err==nil {t.Fatalf("%s accepted as %d",raw,got)} + } +} + +func TestDecodeStateChecksFilesystemCeiling(t *testing.T) { + for _,raw:=range []string{`{"cameras":{}}`,`{"cameras":{},"max_filesystem_used_percent":55}`} { + if _,err:=decodeState([]byte(raw));err!=nil {t.Fatalf("%s refused: %v",raw,err)} + } + for _,raw:=range []string{`{"cameras":{},"max_filesystem_used_percent":96}`,`{"cameras":{},"max_filesystem_used_percent":"80"}`,`{"cameras":{},"max_filesystem_used_percent":null}`} { + if _,err:=decodeState([]byte(raw));err==nil {t.Fatalf("%s accepted",raw)} + } +} + +func TestSaveWritesFilesystemCeilingExplicitly(t *testing.T) { + for _,value:=range []int{80,55} { + resetFilesystemCeiling(t,value) + path:=filepath.Join(t.TempDir(),"cameras.json") + var written []byte + err:=newCeilingNVR().saveAtWithWriter(path,func(target string,raw []byte) error {if target==path {written=raw};return nil}) + if err!=nil {t.Fatal(err)} + var doc map[string]json.RawMessage + if err=json.Unmarshal(written,&doc);err!=nil {t.Fatal(err)} + if string(doc["max_filesystem_used_percent"])!=fmt.Sprint(value) {t.Fatalf("saved ceiling = %s; want %d",doc["max_filesystem_used_percent"],value)} + for _,key:=range []string{"cameras","camera_order","events"} { + if _,ok:=doc[key];!ok {t.Fatalf("top-level key %q missing",key)} + } + } +} + +func TestFilesystemCeilingSurvivesSaveAndLoad(t *testing.T) { + resetFilesystemCeiling(t,55) + path:=filepath.Join(t.TempDir(),"cameras.json") + var written []byte + if err:=newCeilingNVR().saveAtWithWriter(path,func(target string,raw []byte) error {if target==path {written=raw};return nil});err!=nil {t.Fatal(err)} + if err:=os.WriteFile(path,written,0600);err!=nil {t.Fatal(err)} + recordingFilesystemCeiling.set(80) + if err:=newCeilingNVR().loadAt(path);err!=nil {t.Fatal(err)} + if got:=recordingFilesystemCeiling.get();got!=55 {t.Fatalf("loaded ceiling = %d; want 55",got)} +} + +func TestLoadRefusesInvalidFilesystemCeiling(t *testing.T) { + resetFilesystemCeiling(t,70) + path:=filepath.Join(t.TempDir(),"cameras.json") + if err:=os.WriteFile(path,[]byte(`{"cameras":{},"max_filesystem_used_percent":96}`),0600);err!=nil {t.Fatal(err)} + if err:=newCeilingNVR().loadAt(path);err==nil {t.Fatal("invalid ceiling loaded")} + if got:=recordingFilesystemCeiling.get();got!=70 {t.Fatalf("ceiling changed to %d after refused load",got)} +} + +func ceilingTestDeps(saveErr error,saves *int) filesystemCeilingDeps { + return filesystemCeilingDeps{ + setting:recordingFilesystemCeiling, + read:func(string) (filesystemUsage,error) {return filesystemUsage{UsedPercent:61.26,ObservedAt:time.Date(2026,11,29,12,0,0,0,time.UTC)},nil}, + save:func() error {*saves++;return saveErr}, + } +} + +func doCeilingRequest(deps filesystemCeilingDeps,method,body string) *httptest.ResponseRecorder { + req:=httptest.NewRequest(method,"/api/storage/ceiling",strings.NewReader(body)) + w:=httptest.NewRecorder() + serveFilesystemCeiling(w,req,deps) + return w +} + +func TestFilesystemCeilingGet(t *testing.T) { + resetFilesystemCeiling(t,80) + saves:=0 + w:=doCeilingRequest(ceilingTestDeps(nil,&saves),http.MethodGet,"") + if w.Code!=200 || saves!=0 {t.Fatalf("status %d saves %d",w.Code,saves)} + if w.Header().Get("Cache-Control")!="no-store" {t.Fatal("response is cacheable")} + var got filesystemCeilingResponse + if err:=json.Unmarshal(w.Body.Bytes(),&got);err!=nil {t.Fatal(err)} + if got.Ceiling!=80 || got.Trigger!=78 || got.Used==nil || *got.Used!=61.3 || got.ObservedAt==nil {t.Fatalf("unexpected response %s",w.Body.String())} +} + +func TestFilesystemCeilingGetUnknownUsage(t *testing.T) { + resetFilesystemCeiling(t,80) + saves:=0 + deps:=ceilingTestDeps(nil,&saves) + deps.read=func(string) (filesystemUsage,error) {return filesystemUsage{},errFilesystemUsage} + w:=doCeilingRequest(deps,http.MethodGet,"") + if w.Code!=200 {t.Fatalf("status %d; unknown usage must not hide the ceiling",w.Code)} + var raw map[string]interface{} + if err:=json.Unmarshal(w.Body.Bytes(),&raw);err!=nil {t.Fatal(err)} + for _,key:=range []string{"filesystem_used_percent","filesystem_observed_at"} { + if value,ok:=raw[key];!ok || value!=nil {t.Fatalf("%s = %v; want null",key,value)} + } + if raw["max_filesystem_used_percent"]!=float64(80) {t.Fatalf("ceiling missing: %s",w.Body.String())} +} + +func TestFilesystemCeilingPostSavesAndReturnsStoredValue(t *testing.T) { + for _,value:=range []int{10,80,90,95} { + resetFilesystemCeiling(t,50) + saves:=0 + w:=doCeilingRequest(ceilingTestDeps(nil,&saves),http.MethodPost,fmt.Sprintf(`{"max_filesystem_used_percent":%d}`,value)) + if w.Code!=200 || saves!=1 {t.Fatalf("%d: status %d saves %d",value,w.Code,saves)} + if got:=recordingFilesystemCeiling.get();got!=value {t.Fatalf("stored %d; want %d",got,value)} + var got filesystemCeilingResponse + if err:=json.Unmarshal(w.Body.Bytes(),&got);err!=nil {t.Fatal(err)} + if got.Ceiling!=value || got.Trigger!=value-2 {t.Fatalf("response %s",w.Body.String())} + } +} + +func TestFilesystemCeilingPostRefusesInvalidRequests(t *testing.T) { + bodies:=[]string{ + `{"max_filesystem_used_percent":9}`,`{"max_filesystem_used_percent":96}`,`{"max_filesystem_used_percent":80.5}`, + `{"max_filesystem_used_percent":"80"}`,`{"max_filesystem_used_percent":null}`,`{"max_filesystem_used_percent":1e1}`, + `{}`,`{"max_filesystem_used_percent":80,"extra":1}`,`{"max_filesystem_used_percent":80} {}`,`not json`,``, + `{"max_filesystem_used_percent":80,"pad":"`+strings.Repeat("x",2000)+`"}`, + } + for _,body:=range bodies { + resetFilesystemCeiling(t,70) + saves:=0 + w:=doCeilingRequest(ceilingTestDeps(nil,&saves),http.MethodPost,body) + if w.Code!=400 {t.Fatalf("%.60q: status %d",body,w.Code)} + if saves!=0 || recordingFilesystemCeiling.get()!=70 {t.Fatalf("%.60q changed state: saves %d ceiling %d",body,saves,recordingFilesystemCeiling.get())} + } +} + +func TestFilesystemCeilingPostRestoresValueWhenSaveFails(t *testing.T) { + resetFilesystemCeiling(t,80) + saves:=0 + w:=doCeilingRequest(ceilingTestDeps(errors.New("disk failure"),&saves),http.MethodPost,`{"max_filesystem_used_percent":90}`) + if w.Code!=500 || saves!=1 {t.Fatalf("status %d saves %d",w.Code,saves)} + if got:=recordingFilesystemCeiling.get();got!=80 {t.Fatalf("ceiling = %d after failed save; want 80",got)} + if strings.Contains(w.Body.String(),"disk failure") {t.Fatal("internal error text returned to client")} +} + +func TestFilesystemCeilingRefusesOtherMethods(t *testing.T) { + for _,method:=range []string{http.MethodPut,http.MethodDelete,http.MethodPatch} { + saves:=0 + w:=doCeilingRequest(ceilingTestDeps(nil,&saves),method,`{"max_filesystem_used_percent":90}`) + if w.Code!=405 || w.Header().Get("Allow")!="GET, POST" || saves!=0 {t.Fatalf("%s: status %d allow %q saves %d",method,w.Code,w.Header().Get("Allow"),saves)} + } +} diff --git a/cmd/simplenvr/persistence.go b/cmd/simplenvr/persistence.go index 8c66ccf..091b07a 100644 --- a/cmd/simplenvr/persistence.go +++ b/cmd/simplenvr/persistence.go @@ -48,6 +48,7 @@ func decodeState(raw []byte) (persistedState, error) { } if cam.RecordingMode == ModeNoRecording { cam.IsRecording = false } } + if _, err := storedFilesystemCeiling(raw); err != nil { return s, fmt.Errorf("invalid filesystem usage ceiling: %w", err) } seen := make(map[string]bool) order := make([]string, 0, len(s.Cameras)) for _, id := range s.CameraOrder { @@ -73,7 +74,7 @@ func (n *NVR) saveAtWithWriter(path string,write func(string,[]byte)error) error persistenceMu.Lock() defer persistenceMu.Unlock() n.mu.RLock() - raw, err := json.MarshalIndent(persistedState{n.cameras, n.cameraOrder, n.events}, "", " ") + raw, err := json.MarshalIndent(persistedDocument{persistedState{n.cameras, n.cameraOrder, n.events}, recordingFilesystemCeiling.get()}, "", " ") n.mu.RUnlock() if err != nil { return err } raw = append(raw, '\n') @@ -106,8 +107,10 @@ func (n *NVR) loadAt(path string) error { if err != nil { return err } s, err := decodeState(raw) if err != nil { return fmt.Errorf("invalid configuration %s; backup if present: %s.bak: %w", path, path, err) } + ceiling, _ := storedFilesystemCeiling(raw) n.mu.Lock() n.cameras, n.cameraOrder, n.events = s.Cameras, s.CameraOrder, s.Events n.mu.Unlock() + recordingFilesystemCeiling.set(ceiling) return nil } diff --git a/web/static/js/filesystem-ceiling.js b/web/static/js/filesystem-ceiling.js new file mode 100644 index 0000000..d6e00dd --- /dev/null +++ b/web/static/js/filesystem-ceiling.js @@ -0,0 +1,160 @@ +// Filesystem usage ceiling row for camera settings (issue #14, CP3). +// Adds a section to the camera settings modal without changing modals.js. +(function () { + 'use strict'; + + const ENDPOINT = '/api/storage/ceiling'; + const SECTION_ID = 'filesystem-ceiling-section'; + const MIN_PERCENT = 10; + const MAX_PERCENT = 95; + const baseOpen = window.openCameraSettings; + if (typeof baseOpen !== 'function') return; + + let saving = false; + + function notify(kind, message) { + const fn = kind === 'error' ? window.showError : window.showSuccess; + if (typeof fn === 'function') fn(message); + } + + function isPercent(value) { + return typeof value === 'number' && Number.isFinite(value); + } + + function validResponse(data) { + return data !== null && typeof data === 'object' && + Number.isInteger(data.max_filesystem_used_percent) && + Number.isInteger(data.filesystem_prune_trigger_percent) && + (data.filesystem_used_percent === null || isPercent(data.filesystem_used_percent)); + } + + function render(data, syncInput) { + const text = document.getElementById('filesystem-usage-text'); + const input = document.getElementById('filesystem-ceiling-input'); + if (!text || !input) return; + const used = data.filesystem_used_percent === null + ? 'unknown' + : data.filesystem_used_percent.toFixed(1) + '%'; + text.textContent = 'Filesystem used: ' + used + '. Ceiling: ' + + data.max_filesystem_used_percent + '%. Trigger level: ' + + data.filesystem_prune_trigger_percent + '%.'; + if (syncInput) input.value = String(data.max_filesystem_used_percent); + } + + function showUnavailable() { + const text = document.getElementById('filesystem-usage-text'); + if (text) text.textContent = 'Filesystem usage could not be loaded.'; + } + + function readJson(response) { + const type = (response.headers.get('Content-Type') || '').split(';')[0].trim().toLowerCase(); + if (!response.ok || type !== 'application/json') throw new Error('Unexpected response (HTTP ' + response.status + ')'); + return response.json().then(function (data) { + if (!validResponse(data)) throw new Error('Unexpected response body'); + return data; + }); + } + + function refresh(syncInput) { + return fetch(ENDPOINT, { cache: 'no-store' }) + .then(readJson) + .then(function (data) { render(data, syncInput); }) + .catch(function (error) { + console.error('Failed to load filesystem usage:', error); + showUnavailable(); + }); + } + + function saveCeiling() { + if (saving) return; + const input = document.getElementById('filesystem-ceiling-input'); + const button = document.getElementById('filesystem-ceiling-button'); + if (!input || !button) return; + const raw = input.value.trim(); + const percent = /^[0-9]{1,3}$/.test(raw) ? parseInt(raw, 10) : NaN; + if (!(percent >= MIN_PERCENT && percent <= MAX_PERCENT)) { + notify('error', 'Enter a whole number from ' + MIN_PERCENT + ' to ' + MAX_PERCENT); + return; + } + saving = true; + button.disabled = true; + fetch(ENDPOINT, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ max_filesystem_used_percent: percent }) + }) + .then(readJson) + .then(function (data) { + render(data, true); + notify('success', 'Filesystem usage ceiling updated'); + }) + .catch(function (error) { + console.error('Failed to update filesystem ceiling:', error); + notify('error', 'Failed to update filesystem usage ceiling'); + }) + .then(function () { + saving = false; + button.disabled = false; + }); + } + + function buildSection() { + const section = document.createElement('div'); + section.className = 'config-subsection'; + section.id = SECTION_ID; + + const heading = document.createElement('h3'); + heading.textContent = 'Filesystem Usage'; + + const usage = document.createElement('p'); + usage.id = 'filesystem-usage-text'; + usage.textContent = 'Checking filesystem usage...'; + + const row = document.createElement('div'); + row.style.cssText = 'display: flex; align-items: center; gap: 10px;'; + + const label = document.createElement('label'); + label.htmlFor = 'filesystem-ceiling-input'; + label.style.cssText = 'margin: 0; white-space: nowrap;'; + label.textContent = 'Maximum filesystem used (%):'; + + const input = document.createElement('input'); + input.type = 'number'; + input.id = 'filesystem-ceiling-input'; + input.min = String(MIN_PERCENT); + input.max = String(MAX_PERCENT); + input.step = '1'; + input.value = '80'; + input.style.width = '80px'; + + const button = document.createElement('button'); + button.type = 'button'; + button.id = 'filesystem-ceiling-button'; + button.className = 'btn'; + button.textContent = 'Set Ceiling'; + button.addEventListener('click', saveCeiling); + + const note = document.createElement('p'); + note.style.cssText = 'margin: 8px 0 0 0; color: #ccc;'; + note.textContent = 'This percentage covers the whole recordings filesystem, including data that is not SimpleNVR media.'; + + row.append(label, input, button); + section.append(heading, usage, row, note); + return section; + } + + function ensureSection() { + if (document.getElementById(SECTION_ID)) return true; + const list = document.getElementById('modal-camera-list'); + const anchor = list && list.closest('.config-subsection'); + if (!anchor || !anchor.parentNode) return false; + anchor.parentNode.insertBefore(buildSection(), anchor); + return true; + } + + window.openCameraSettings = function () { + const result = baseOpen.apply(this, arguments); + if (ensureSection()) refresh(true); + return result; + }; +})(); diff --git a/web/templates/index.html b/web/templates/index.html index 70c08df..645d5b6 100644 --- a/web/templates/index.html +++ b/web/templates/index.html @@ -110,6 +110,7 @@

✓ Cleanup Complete

+ From 3409776a41a6e4184390ea35c3983da36a1bf37f Mon Sep 17 00:00:00 2001 From: mouldybread <38598858+mouldybread@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:17:22 +0800 Subject: [PATCH 04/12] CP3 (#14): register /api/storage/ceiling and document the ceiling Register the ceiling handler in main.go and describe the setting, the API and the settings row in docs/FILESYSTEM_USAGE.md. Nothing is deleted yet. --- cmd/simplenvr/main.go | 1 + docs/FILESYSTEM_USAGE.md | 54 ++++++++++++++++++++++++++++++++++++---- 2 files changed, 50 insertions(+), 5 deletions(-) diff --git a/cmd/simplenvr/main.go b/cmd/simplenvr/main.go index 3cac925..f127546 100644 --- a/cmd/simplenvr/main.go +++ b/cmd/simplenvr/main.go @@ -127,6 +127,7 @@ func main() { http.HandleFunc("/api/stream/",streamProxyHandler) http.HandleFunc("/api/recordings/list",listRecordingsHandler) http.HandleFunc("/api/storage/status",storageStatusHandler) + http.HandleFunc("/api/storage/ceiling",filesystemCeilingHandler) http.HandleFunc("/api/recovery/status",recoveryStatusHandler) http.HandleFunc("/api/timeline/recordings",timelineRecordingsHandler) http.HandleFunc("/api/recordings/delete-all",deleteAllRecordingsHandler) diff --git a/docs/FILESYSTEM_USAGE.md b/docs/FILESYSTEM_USAGE.md index 3a05497..040be1d 100644 --- a/docs/FILESYSTEM_USAGE.md +++ b/docs/FILESYSTEM_USAGE.md @@ -1,7 +1,8 @@ -# Recording filesystem usage (issue #14, CP2) +# Recording filesystem usage and ceiling (issue #14, CP2 and CP3) -SimpleNVR measures how full the recordings filesystem is. This checkpoint only -measures; it adds no setting, no display and no deletion. +SimpleNVR measures how full the recordings filesystem is and stores the highest +used percentage the owner accepts (the ceiling). These checkpoints only measure, +store and display; they add no deletion. ## What is measured @@ -30,8 +31,11 @@ a missing or replaced directory is an error rather than another filesystem. ## When it runs A background job started through the shutdown gate measures every 5 minutes. The -first measurement is 5 minutes after startup, so usage is unknown until then. -Shutdown cancels and joins the job before final persistence. +first measurement is 5 minutes after startup, so the job's own value is unknown +until then. Shutdown cancels and joins the job before final persistence. + +Opening camera settings does not use the job's value. It asks the server for a +fresh reading, so the settings row is accurate even in the first 5 minutes. ## When measurement fails @@ -39,6 +43,46 @@ Usage becomes unknown (an earlier value is not kept), and a log line says that recording filesystem usage is unavailable. The log does not include the path. Later checkpoints must not delete anything while usage is unknown. +## The ceiling setting (CP3) + +- **Stored as** the top-level key `max_filesystem_used_percent` in + `cameras.json`, beside `cameras`, `camera_order` and `events`. +- **Default** is 80. A file without the key reads as 80. Every save writes the + value out explicitly, including when it is still the default. +- **Valid values** are whole numbers from 10 to 95. A stored value outside that + range, or one that is not an integer (a string, fraction, exponent or null), + makes the configuration invalid: startup is refused, and saves are refused until + it is fixed, the same as invalid retention. +- **Trigger level** is the ceiling minus 2 percentage points (78 for the default). + It is derived and never stored. Nothing uses it yet. + +## API + +`GET /api/storage/ceiling` returns: + + { + "max_filesystem_used_percent": 80, + "filesystem_prune_trigger_percent": 78, + "filesystem_used_percent": 61.3, + "filesystem_observed_at": "2026-11-29T12:00:00Z" + } + +It takes a fresh reading on each request. If the reading fails, the last two +fields are `null` and the status is still 200, so the ceiling stays visible. + +`POST /api/storage/ceiling` takes `{"max_filesystem_used_percent": }`, +validates it, saves it, and returns the same body as GET. Anything invalid is +refused with 400 and changes nothing. If the save fails, the previous value is +restored and the response is a generic 500. Other methods get 405. + +The per-camera `/api/storage/status` endpoint is unchanged. + +## Settings display + +Camera settings has a "Filesystem Usage" row showing the used percentage (or +"unknown"), the ceiling and the trigger level, with a number input and a Set +Ceiling button. It refreshes each time settings open. + ## Limits - Quotas, ZFS datasets and snapshots, and other volume features decide what the From e58835a6563cb99eb5fc7a1689ea6b6e259fbe5b Mon Sep 17 00:00:00 2001 From: mouldybread <38598858+mouldybread@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:34:23 +0800 Subject: [PATCH 05/12] CP3 (#14): add frontend regression test for the filesystem ceiling row Load filesystem-ceiling.js into a fake DOM and check that opening settings adds one row and refreshes it, that unknown usage and failed loads are shown plainly, that only valid whole numbers from 10 to 95 are sent, that failures never announce success, that a pending save blocks a second request, and that the script loads once, after modals.js. --- .../filesystem_ceiling_frontend_test.go | 7 + tests/frontend/filesystem-ceiling.cjs | 277 ++++++++++++++++++ 2 files changed, 284 insertions(+) create mode 100644 cmd/simplenvr/filesystem_ceiling_frontend_test.go create mode 100644 tests/frontend/filesystem-ceiling.cjs diff --git a/cmd/simplenvr/filesystem_ceiling_frontend_test.go b/cmd/simplenvr/filesystem_ceiling_frontend_test.go new file mode 100644 index 0000000..f633e58 --- /dev/null +++ b/cmd/simplenvr/filesystem_ceiling_frontend_test.go @@ -0,0 +1,7 @@ +package main + +import "testing" + +func TestFrontendFilesystemCeiling(t *testing.T) { + runFrontendRegression(t, "tests/frontend/filesystem-ceiling.cjs", "UTC") +} diff --git a/tests/frontend/filesystem-ceiling.cjs b/tests/frontend/filesystem-ceiling.cjs new file mode 100644 index 0000000..26820a9 --- /dev/null +++ b/tests/frontend/filesystem-ceiling.cjs @@ -0,0 +1,277 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); + +const root = path.join(__dirname, '..', '..'); +const script = fs.readFileSync(path.join(root, 'web', 'static', 'js', 'filesystem-ceiling.js'), 'utf8'); +const indexHtml = fs.readFileSync(path.join(root, 'web', 'templates', 'index.html'), 'utf8'); +const ENDPOINT = '/api/storage/ceiling'; +const SECTION = 'filesystem-ceiling-section'; +const LOADED_TEXT = 'Filesystem used: 61.3%. Ceiling: 80%. Trigger level: 78%.'; +const body80 = { + max_filesystem_used_percent: 80, + filesystem_prune_trigger_percent: 78, + filesystem_used_percent: 61.3, + filesystem_observed_at: '2026-11-29T12:00:00Z' +}; +const body90 = Object.assign({}, body80, {max_filesystem_used_percent: 90, filesystem_prune_trigger_percent: 88}); + +class El { + constructor(tag) { + this.tagName = tag; + this.children = []; + this.parentNode = null; + this.style = {}; + this.listeners = {}; + this.id = ''; + this.className = ''; + this.textContent = ''; + this.value = ''; + this.disabled = false; + } + append(...nodes) { + for (const node of nodes) { node.parentNode = this; this.children.push(node); } + } + insertBefore(node, ref) { + const index = this.children.indexOf(ref); + assert.ok(index >= 0, 'reference node must be a child'); + node.parentNode = this; + this.children.splice(index, 0, node); + } + closest(selector) { + assert.equal(selector, '.config-subsection'); + for (let node = this; node; node = node.parentNode) if (node.className === 'config-subsection') return node; + return null; + } + addEventListener(type, fn) { this.listeners[type] = fn; } + find(id) { + if (this.id === id) return this; + for (const child of this.children) { const found = child.find(id); if (found) return found; } + return null; + } +} + +function jsonResponse(data, options) { + const status = (options && options.status) || 200; + const type = (options && options.type) || 'application/json; charset=utf-8'; + return Promise.resolve({ + ok: status >= 200 && status < 300, + status, + headers: {get: name => name.toLowerCase() === 'content-type' ? type : null}, + json: () => Promise.resolve(data) + }); +} + +const isPost = options => !!options && options.method === 'POST'; +const settle = async () => { for (let i = 0; i < 10; i++) await new Promise(resolve => setImmediate(resolve)); }; + +function makeEnv(respond) { + const body = new El('body'); + const modal = new El('div'); + modal.id = 'camera-settings-modal'; + const bulk = new El('div'); + bulk.className = 'config-subsection'; + const cameras = new El('div'); + cameras.className = 'config-subsection'; + const list = new El('div'); + list.id = 'modal-camera-list'; + cameras.append(list); + modal.append(bulk, cameras); + body.append(modal); + const requests = [], successes = [], errors = []; + let baseCalls = 0; + const window = { + openCameraSettings() { baseCalls++; }, + showSuccess(message) { successes.push(message); }, + showError(message) { errors.push(message); } + }; + const context = vm.createContext({ + console: {error() {}, warn() {}, log() {}}, + window, + document: {getElementById: id => body.find(id), createElement: tag => new El(tag)}, + fetch(url, options) { requests.push({url, options}); return respond(url, options); } + }); + vm.runInContext(script, context, {filename: 'filesystem-ceiling.js'}); + return {body, modal, cameras, window, requests, successes, errors, baseCalls: () => baseCalls}; +} + +const usageText = env => env.body.find('filesystem-usage-text').textContent; +const input = env => env.body.find('filesystem-ceiling-input'); +const button = env => env.body.find('filesystem-ceiling-button'); + +async function openAddsOneRowAndRefreshes() { + const env = makeEnv(() => jsonResponse(body80)); + env.window.openCameraSettings(); + await settle(); + assert.equal(env.baseCalls(), 1, 'the original openCameraSettings must still run'); + const section = env.body.find(SECTION); + assert.ok(section, 'row is added'); + assert.equal(env.modal.children.indexOf(section), env.modal.children.indexOf(env.cameras) - 1, 'row sits directly before the camera list'); + assert.equal(input(env).min, '10'); + assert.equal(input(env).max, '95'); + assert.equal(env.requests.length, 1); + assert.equal(env.requests[0].url, ENDPOINT); + assert.equal(env.requests[0].options.cache, 'no-store'); + assert.notEqual(env.requests[0].options.method, 'POST'); + assert.equal(usageText(env), LOADED_TEXT); + assert.equal(input(env).value, '80'); + env.window.openCameraSettings(); + await settle(); + assert.equal(env.baseCalls(), 2); + assert.equal(env.modal.children.filter(child => child.id === SECTION).length, 1, 'reopening must not duplicate the row'); + assert.equal(env.requests.length, 2, 'every open refreshes usage'); + assert.deepEqual(env.errors, []); + assert.deepEqual(env.successes, []); +} + +async function unknownUsageIsShownPlainly() { + const env = makeEnv(() => jsonResponse(Object.assign({}, body80, {filesystem_used_percent: null, filesystem_observed_at: null}))); + env.window.openCameraSettings(); + await settle(); + assert.equal(usageText(env), 'Filesystem used: unknown. Ceiling: 80%. Trigger level: 78%.'); +} + +async function failedLoadsAreShownPlainly() { + const variants = [ + () => jsonResponse(body80, {status: 500}), + () => jsonResponse(body80, {type: 'text/html'}), + () => jsonResponse({}), + () => jsonResponse(Object.assign({}, body80, {max_filesystem_used_percent: '80'})), + () => Promise.reject(new Error('network unavailable')) + ]; + for (const variant of variants) { + const env = makeEnv(variant); + env.window.openCameraSettings(); + await settle(); + assert.equal(usageText(env), 'Filesystem usage could not be loaded.'); + assert.equal(env.requests.length, 1, 'no retries'); + assert.deepEqual(env.successes, []); + } +} + +async function validSaveSendsOneRequestAndShowsStoredValue() { + const env = makeEnv((url, options) => jsonResponse(isPost(options) ? body90 : body80)); + env.window.openCameraSettings(); + await settle(); + input(env).value = ' 90 '; + button(env).listeners.click(); + await settle(); + assert.equal(env.requests.length, 2); + const post = env.requests[1]; + assert.equal(post.url, ENDPOINT); + assert.equal(post.options.method, 'POST'); + assert.equal(post.options.headers['Content-Type'], 'application/json'); + assert.deepEqual(JSON.parse(post.options.body), {max_filesystem_used_percent: 90}); + assert.equal(usageText(env), 'Filesystem used: 61.3%. Ceiling: 90%. Trigger level: 88%.'); + assert.equal(input(env).value, '90'); + assert.deepEqual(env.successes, ['Filesystem usage ceiling updated']); + assert.deepEqual(env.errors, []); + assert.equal(button(env).disabled, false); + for (const edge of ['10', '95']) { + input(env).value = edge; + button(env).listeners.click(); + await settle(); + assert.equal(JSON.parse(env.requests[env.requests.length - 1].options.body).max_filesystem_used_percent, Number(edge)); + } +} + +async function invalidInputIsNeverSent() { + for (const value of ['', ' ', '9', '96', '0', '100', '80.5', 'abc', '1e1', '-5', '+80', '0950']) { + const env = makeEnv(() => jsonResponse(body80)); + env.window.openCameraSettings(); + await settle(); + input(env).value = value; + button(env).listeners.click(); + await settle(); + assert.equal(env.requests.length, 1, 'no request for ' + JSON.stringify(value)); + assert.equal(env.errors.length, 1, 'one error for ' + JSON.stringify(value)); + assert.deepEqual(env.successes, []); + assert.equal(button(env).disabled, false); + } +} + +async function failedSaveNeverAnnouncesSuccess() { + const variants = [ + () => jsonResponse('bad request', {status: 400, type: 'text/plain'}), + () => jsonResponse('server error', {status: 500, type: 'text/plain'}), + () => jsonResponse(body90, {type: 'text/html'}), + () => jsonResponse({}), + () => Promise.reject(new Error('network unavailable')) + ]; + for (const variant of variants) { + const env = makeEnv((url, options) => isPost(options) ? variant() : jsonResponse(body80)); + env.window.openCameraSettings(); + await settle(); + input(env).value = '90'; + button(env).listeners.click(); + await settle(); + assert.equal(env.requests.length, 2, 'exactly one save request; no retries'); + assert.deepEqual(env.successes, [], 'failure must not announce success'); + assert.deepEqual(env.errors, ['Failed to update filesystem usage ceiling']); + assert.equal(usageText(env), LOADED_TEXT, 'failure must not change the displayed values'); + assert.equal(button(env).disabled, false, 'button must be usable again'); + } +} + +async function pendingSaveBlocksASecondRequest() { + let release; + const pending = new Promise(resolve => { release = resolve; }); + const env = makeEnv((url, options) => isPost(options) ? pending.then(() => jsonResponse(body90)) : jsonResponse(body80)); + env.window.openCameraSettings(); + await settle(); + input(env).value = '90'; + button(env).listeners.click(); + button(env).listeners.click(); + await settle(); + assert.equal(env.requests.filter(request => isPost(request.options)).length, 1, 'second click must not send another request'); + assert.equal(button(env).disabled, true); + release(); + await settle(); + assert.equal(button(env).disabled, false); + assert.equal(env.requests.filter(request => isPost(request.options)).length, 1); + assert.deepEqual(env.successes, ['Filesystem usage ceiling updated']); +} + +function scriptLoadsOnceAfterModals() { + const tags = Array.from(indexHtml.matchAll(/ + From 4d24b37c4ee8579cb776490643b4a1933f4bf8ed Mon Sep 17 00:00:00 2001 From: mouldybread <38598858+mouldybread@users.noreply.github.com> Date: Sun, 29 Nov 2026 09:32:57 +0800 Subject: [PATCH 08/12] CP5 (#14): use a stamped name in the age-versus-ceiling test Retention keeps names shorter than 15 characters, so s.mp4 was never expired by age. Use a full stamped name so the limited camera's old day is actually due. --- cmd/simplenvr/retention_age_off_test.go | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/cmd/simplenvr/retention_age_off_test.go b/cmd/simplenvr/retention_age_off_test.go index c59a60b..c01d8c1 100644 --- a/cmd/simplenvr/retention_age_off_test.go +++ b/cmd/simplenvr/retention_age_off_test.go @@ -132,23 +132,27 @@ func itoa(value int) string { func TestAgeOffAndCeilingEachActOnlyUnderTheirOwnRule(t *testing.T) { // Age cleanup acts on a camera with a limit and never on one without, whatever the // filesystem ceiling says; ceiling pruning acts on usage alone, whatever the age limit. + // Retention keeps names shorter than 15 characters, so the old recording needs a + // full stamped name to be due for age cleanup. + const oldFile="20000101_000000_old.mp4" f:=newPruneFixture(t,"limited","unlimited") f.n.cameras["limited"].RetentionDays=1 f.n.cameras["unlimited"].RetentionDays=0 f.fs.setUsed(10) oldDay:="20000101" for _,id:=range []string{"limited","unlimited"} { - f.file(id,oldDay+"/s.mp4") + f.file(id,oldDay+"/"+oldFile) f.file(id,"20300101/new.mp4") } // Below the trigger, ceiling pruning does nothing. f.p.runPass(context.Background()) - for _,id:=range []string{"limited","unlimited"} {f.mustExist(id,oldDay+"/s.mp4")} + for _,id:=range []string{"limited","unlimited"} {f.mustExist(id,oldDay+"/"+oldFile)} // Age cleanup removes only the limited camera's expired day. ticks:=make(chan time.Time,1);ticks<-time.Now();close(ticks) runCleanupTicks(context.Background(),f.n,ticks) f.mustBeGone("limited",oldDay) - f.mustExist("unlimited",oldDay+"/s.mp4") + f.mustExist("unlimited",oldDay+"/"+oldFile) + f.mustExist("limited","20300101/new.mp4") // At the trigger, ceiling pruning removes the unlimited camera's oldest day. f.fs.setUsed(85) f.p.runPass(context.Background()) From ed5e01cb98d810ce498f12fdf4597bdb76eb31c6 Mon Sep 17 00:00:00 2001 From: mouldybread <38598858+mouldybread@users.noreply.github.com> Date: Sun, 29 Nov 2026 09:56:03 +0800 Subject: [PATCH 09/12] CP6 (#14): real-container acceptance for ceiling pruning Run the real runtime image on a loopback ext4 volume and drive it with headless Chrome and the real HTTP API: settings rows, retention 0, ceiling pruning one day per camera per pass, the 1 MiB no-effect guard (hard links stand in for snapshots), a partial failure (chattr +i), ceiling-not-met, untouched evidence, running recorder, clean shutdown and restart. Add the job to the required gate and an owner runbook for a real ZFS volume. --- .github/workflows/safety-ci.yml | 51 ++- docs/FILESYSTEM_ACCEPTANCE.md | 63 ++++ .../acceptance/filesystem-prune-acceptance.sh | 138 ++++++++ .../acceptance/filesystem_prune_acceptance.py | 311 ++++++++++++++++++ 4 files changed, 560 insertions(+), 3 deletions(-) create mode 100644 docs/FILESYSTEM_ACCEPTANCE.md create mode 100644 tests/acceptance/filesystem-prune-acceptance.sh create mode 100644 tests/acceptance/filesystem_prune_acceptance.py diff --git a/.github/workflows/safety-ci.yml b/.github/workflows/safety-ci.yml index 3319765..99cacc5 100644 --- a/.github/workflows/safety-ci.yml +++ b/.github/workflows/safety-ci.yml @@ -183,6 +183,49 @@ jobs: if-no-files-found: warn retention-days: 14 + prune_acceptance: + name: Filesystem pruning — real container acceptance + runs-on: ubuntu-24.04 + timeout-minutes: 25 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ env.CHECKPOINT_SHA }} + persist-credentials: false + - name: Refresh Ubuntu package indexes + timeout-minutes: 5 + run: bash .github/scripts/ci-media-apt.sh update + - name: Install media test tools + timeout-minutes: 8 + run: bash .github/scripts/ci-media-apt.sh install ffmpeg python3-venv openssl + - name: Build the exact checkout runtime image + timeout-minutes: 8 + run: docker build -t simplenvr-safety-test . + - name: Install pinned browser acceptance tooling + timeout-minutes: 8 + shell: bash + run: | + set -euo pipefail + python3 -m venv "$RUNNER_TEMP/simplenvr-browser-venv" + . "$RUNNER_TEMP/simplenvr-browser-venv/bin/activate" + python -m pip install 'playwright==1.56.0' + python -m playwright install --with-deps chrome + - name: Real container ceiling pruning on a loopback ext4 volume, with Chrome + timeout-minutes: 12 + shell: bash + run: | + set -euo pipefail + . "$RUNNER_TEMP/simplenvr-browser-venv/bin/activate" + GITHUB_SHA="$CHECKPOINT_SHA" bash tests/acceptance/filesystem-prune-acceptance.sh simplenvr-safety-test "$RUNNER_TEMP/simplenvr-prune-evidence" + - name: Retain pruning acceptance evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: filesystem-prune-acceptance-${{ env.CHECKPOINT_SHA }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/simplenvr-prune-evidence + if-no-files-found: warn + retention-days: 14 + correspondence_resources: name: Ordered content — bounded synthetic resource measurements runs-on: ubuntu-24.04 @@ -263,18 +306,20 @@ jobs: verify: name: Required checks — all must pass if: always() - needs: [core, browser, correspondence_resources] + needs: [core, browser, prune_acceptance, correspondence_resources] runs-on: ubuntu-24.04 timeout-minutes: 2 steps: - - name: Require core, both browser attempts and resource measurements + - name: Require core, both browser attempts, pruning acceptance and resource measurements env: CORE_RESULT: ${{ needs.core.result }} BROWSER_RESULT: ${{ needs.browser.result }} + PRUNE_RESULT: ${{ needs.prune_acceptance.result }} RESOURCE_RESULT: ${{ needs.correspondence_resources.result }} run: | set -euo pipefail - printf 'core=%s browser=%s resources=%s\n' "$CORE_RESULT" "$BROWSER_RESULT" "$RESOURCE_RESULT" + printf 'core=%s browser=%s prune=%s resources=%s\n' "$CORE_RESULT" "$BROWSER_RESULT" "$PRUNE_RESULT" "$RESOURCE_RESULT" test "$CORE_RESULT" = success test "$BROWSER_RESULT" = success + test "$PRUNE_RESULT" = success test "$RESOURCE_RESULT" = success diff --git a/docs/FILESYSTEM_ACCEPTANCE.md b/docs/FILESYSTEM_ACCEPTANCE.md new file mode 100644 index 0000000..ce00230 --- /dev/null +++ b/docs/FILESYSTEM_ACCEPTANCE.md @@ -0,0 +1,63 @@ +# Filesystem ceiling acceptance (issue #14, CP6) + +This describes what the CI acceptance proves, what it cannot, and the steps the owner +runs on a real ZFS volume. + +## What CI runs + +`tests/acceptance/filesystem-prune-acceptance.sh` runs the real runtime image on a +real 64 MiB ext4 volume (a loopback mount), with headless Chrome and the real HTTP API. +Only the camera capture input is a file fixture. `filesystem_prune_acceptance.py` checks: + +- The Filesystem Usage row shows the server's used %, ceiling and trigger level; a valid + ceiling saves and survives a reload; an invalid one sends nothing. +- Retention `0` is saved through the real UI (per camera and for all cameras) and persists. +- A ceiling above usage deletes nothing. +- Lowering the ceiling prunes the oldest day with `.mp4` files from each camera, one day + per pass, removes that day's events, and stops when usage falls below the trigger. +- Evidence the pruner must not touch (`.tmp`, `temp/`, `buffer/`, a leftover-only day, the + newest day, files in the camera folder) is byte-identical at the end. The recorder keeps + running throughout. +- The 1 MiB guard: hard links on the same volume stand in for a snapshot, so deleting the + names frees no space. Pruning pauses, then resumes once the links are removed. +- A partial failure (one file made immutable with `chattr +i`): the rest of the day is + removed, the incomplete day is logged, and its events are kept. +- Ceiling-not-met is logged exactly once. +- A clean shutdown persists the ceiling (`cameras.json`, mode 0600) and a restart keeps it. + +Each `POST /api/storage/ceiling` asks for one pass, so CI does not wait for the 5-minute +timer. + +## What CI does not prove + +Live RTSP cameras; ZFS or any snapshotting filesystem; the 5-minute timer and age cleanup +on that timer (unit tests cover age cleanup); unknown-usage handling inside the container +(unit-tested); performance with very large trees. + +## Owner runbook: a real ZFS volume + +**Use a throwaway dataset and a throwaway test instance. Pruning deletes recordings and +deleted footage is not recoverable. Do not point this at your real recordings.** + +1. Create a small dataset with a quota, for example `zfs create -o quota=2G pool/simplenvr-test`, + and mount it as the instance's `/recordings`. +2. Seed a few cameras with several day folders of `.mp4` files plus a newest day. Real or + dummy files are fine. Note which files are evidence you expect to survive. +3. Take a snapshot: `zfs snapshot pool/simplenvr-test@before`. +4. Record `df -h` and `zfs list -o name,used,avail,refer` for the dataset. +5. Start the instance. Open camera settings and compare the Filesystem Usage row with `df`. +6. Set the ceiling a few points below the current usage. Read the instance log for each + pass (`docker logs `). Because a snapshot holds the deleted blocks, expect + `Filesystem pruning paused: deleting did not raise available space by at least 1 MiB` + after the first pass, and no further days removed. +7. Destroy the snapshot (`zfs destroy pool/simplenvr-test@before`) and set the ceiling + again. Expect `Filesystem pruning resumed` and further days removed, one per camera + per pass. +8. Leave the instance running through at least one 5-minute interval and confirm the + scheduled pass and (for a camera with a retention limit) age cleanup happen. +9. Confirm the newest day folder and the evidence files from step 2 are untouched, and + the recorders (if any are active) kept recording. + +Record what you saw: the log lines, `df` and `zfs list` before and after, and anything that +differed from the expectations above. CP6 is not complete without this, or without an +explicit owner waiver. diff --git a/tests/acceptance/filesystem-prune-acceptance.sh b/tests/acceptance/filesystem-prune-acceptance.sh new file mode 100644 index 0000000..565b73b --- /dev/null +++ b/tests/acceptance/filesystem-prune-acceptance.sh @@ -0,0 +1,138 @@ +#!/usr/bin/env bash +set -euo pipefail +image=${1:?usage: bash tests/acceptance/filesystem-prune-acceptance.sh IMAGE EVIDENCE_DIR} +evidence=${2:?evidence directory required} +work=$(mktemp -d "${RUNNER_TEMP:-/tmp}/simplenvr-prune.XXXXXX") +state=$work/state +bin=$work/bin +fixture=$work/fixture +disk=$work/volume.img +name=simplenvr-prune-$$ +mkdir -p "$evidence" "$state" "$bin" "$fixture" +chmod 755 "$work" "$bin" "$fixture" +cleanup() { + docker logs "$name" > "$evidence/runtime-container.log" 2>&1 || true + docker rm -f "$name" >/dev/null 2>&1 || true + sudo chattr -R -i "$state" >/dev/null 2>&1 || true + sudo umount "$state" >/dev/null 2>&1 || true + sudo rm -rf -- "$work" +} +trap cleanup EXIT + +# A real, small ext4 volume: fstatfs reports a real used percentage and available bytes. +truncate -s 64M "$disk" +sudo mkfs.ext4 -q -F -m 0 -O '^has_journal' "$disk" +sudo mount -o loop "$disk" "$state" +sudo chown "$(id -u):$(id -g)" "$state" +python3 - "$state" <<'PY' +import json,os,sys +root=sys.argv[1] +MIB=1024*1024 +def put(path,size=0,text=None): + os.makedirs(os.path.dirname(path),exist_ok=True) + with open(path,'wb') as f: + f.write(text.encode() if text is not None else b'\0'*size) +days=['20200101','20200102','20200103','20200104','20200105'] +for cam in ('id_a','id_b'): + base=os.path.join(root,cam) + for day in days: + for n in (1,2,3): + put(f'{base}/{day}/seg{n}.mp4',MIB) + put(f'{base}/20991231/floor.mp4',MIB) + put(f'{base}/20190101/leftover.tmp',text='leftover evidence\n') + put(f'{base}/loose.mp4',text='loose published-looking file\n') +put(root+'/id_a/temp/retained-evidence/event.mp4',text='synthetic retained event input\n') +put(root+'/id_a/temp/retained-evidence/recovery.json',text='synthetic checkpoint evidence, not a valid recovery authorization\n') +put(root+'/id_a/buffer/retained-unreported.mp4',text='synthetic unreported prebuffer evidence\n') +put(root+'/id_a/buffer/retained-big.mp4',8*MIB) +os.makedirs(root+'/id_live',exist_ok=True) +cameras={} +for ident,name,recording,mode in [('id_a','Alpha',False,'no_recording'),('id_b','Bravo',False,'no_recording'),('id_live','Live',True,'continuous')]: + cameras[ident]={'id':ident,'name':name,'rtsp_url':'rtsp://synthetic-fixture/'+ident,'record_dir':'/recordings/'+ident,'is_recording':recording,'retention_days':7,'recording_mode':mode} +events=[] +for name in ('Alpha','Bravo'): + for day in days: + stamp=f'{day[:4]}-{day[4:6]}-{day[6:]}T10:00:00Z' + events.append({'id':name+'-'+day,'camera_name':name,'label':'fixture','start_time':stamp,'duration_seconds':5,'created_at':stamp}) +events.append({'id':'Live-20200101','camera_name':'Live','label':'fixture','start_time':'2020-01-01T10:00:00Z','duration_seconds':5,'created_at':'2020-01-01T10:00:00Z'}) +with open(root+'/cameras.json','w') as f: + json.dump({'cameras':cameras,'camera_order':list(cameras),'events':events},f) +PY + +docker run --rm --network none --entrypoint /usr/bin/ffmpeg \ + --mount "type=bind,src=$fixture,dst=/fixture" "$image" \ + -nostdin -v error -f lavfi -i testsrc2=size=256x144:rate=10 \ + -t 2 -c:v mpeg4 -threads 1 -an -y /fixture/source.mp4 +# Substitute only the capture input. This is real FFmpeg in the runtime image, +# but it is deliberately NOT live RTSP acceptance. +cat > "$bin/ffmpeg" <<'SH' +#!/bin/sh +segment=0 +last= +for arg do + test "$arg" != '-segment_list' || segment=1 + last=$arg +done +if test "$segment" -eq 1; then + exec /usr/bin/ffmpeg -nostdin -v error -re -stream_loop -1 -i /fixture/source.mp4 -c copy -f segment -segment_time 5 -segment_format mp4 -reset_timestamps 1 -strftime 1 -segment_list pipe:1 -segment_list_type csv -segment_list_size 0 "$last" +fi +exec /usr/bin/ffmpeg -nostdin -v error -re -stream_loop -1 -i /fixture/source.mp4 -t 600 -c copy -f mp4 -movflags faststart -y "$last" +SH +chmod 755 "$bin/ffmpeg" +SIMPLENVR_E2E_PASSWORD=$(python3 -c 'import secrets; print(secrets.token_urlsafe(32))') +export SIMPLENVR_E2E_PASSWORD +printf '%s\n' "$SIMPLENVR_E2E_PASSWORD" | docker run --rm -i \ + --mount "type=bind,src=$state,dst=/recordings" "$image" auth set-password ci-prune +sudo chown -R 0:0 "$state" +sudo chmod 700 "$state" +docker run -d --name "$name" --read-only --cap-drop ALL --cap-add NET_BIND_SERVICE \ + --security-opt no-new-privileges --tmpfs /certs:rw,nosuid,nodev,noexec \ + --tmpfs /tmp:rw,nosuid,nodev,noexec,size=64m \ + -p 127.0.0.1::443 \ + --env PATH=/fixture-bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + --mount "type=bind,src=$state,dst=/recordings" \ + --mount "type=bind,src=$fixture,dst=/fixture,readonly" \ + --mount "type=bind,src=$bin,dst=/fixture-bin,readonly" "$image" >/dev/null +image_id=$(docker image inspect -f '{{.Id}}' "$image") + +wait_ready() { + for attempt in $(seq 1 60); do + if docker exec "$name" wget --no-check-certificate -q -O /dev/null https://127.0.0.1/auth/login; then return 0; fi + sleep 0.5 + done + docker logs "$name" + return 1 +} +drive() { + local phase=$1 port ifindex + port=$(docker inspect -f '{{(index (index .NetworkSettings.Ports "443/tcp") 0).HostPort}}' "$name") + ifindex=$(docker exec "$name" cat /sys/class/net/eth0/iflink) + [[ "$ifindex" =~ ^[1-9][0-9]*$ ]] + timeout --kill-after=10 400 python3 tests/acceptance/browser_network_ready.py \ + --ifindex "$ifindex" --evidence "$evidence" -- \ + python3 tests/acceptance/filesystem_prune_acceptance.py --phase "$phase" \ + --origin "https://127.0.0.1:$port" --container "$name" --state "$state" \ + --evidence "$evidence" --commit "${GITHUB_SHA:-$(git rev-parse HEAD)}" --image-id "$image_id" +} + +wait_ready +drive main +docker stop --timeout 75 "$name" >/dev/null +test "$(docker inspect -f '{{.State.ExitCode}}' "$name")" -eq 0 +docker logs "$name" 2>&1 | grep -F 'Shutdown complete; recording intent persisted' +sudo python3 - "$state/cameras.json" <<'PY' +import json,os,stat,sys +p=sys.argv[1] +mode=stat.S_IMODE(os.stat(p).st_mode) +assert mode==0o600, oct(mode) +with open(p) as f: d=json.load(f) +assert d['max_filesystem_used_percent']==10, d.get('max_filesystem_used_percent') +assert d['cameras']['id_live']['is_recording'] is True +assert all(c['retention_days']==0 for c in d['cameras'].values()), d['cameras'] +PY +docker start "$name" >/dev/null +wait_ready +drive restart +docker stop --timeout 75 "$name" >/dev/null +test "$(docker inspect -f '{{.State.ExitCode}}' "$name")" -eq 0 +printf 'FILESYSTEM_PRUNE_VERIFIED image_id=%s filesystem=ext4_loop restart=checked live_rtsp=not_tested zfs=not_tested age_cleanup_tick=not_tested\n' "$image_id" diff --git a/tests/acceptance/filesystem_prune_acceptance.py b/tests/acceptance/filesystem_prune_acceptance.py new file mode 100644 index 0000000..adb84e2 --- /dev/null +++ b/tests/acceptance/filesystem_prune_acceptance.py @@ -0,0 +1,311 @@ +"""Real runtime-container acceptance for the filesystem ceiling and pruning (issue #14, CP6). + +Real HTTPS server in the runtime image, a real ext4 loopback volume and headless Chrome. +Only the camera capture input is a file fixture. Not covered: live RTSP, ZFS or any +snapshotting filesystem, the 5-minute tick, age cleanup on that tick. +""" +import argparse +import asyncio +import json +import os +import re +import subprocess +import time +from pathlib import Path +from urllib.parse import urlsplit + +from playwright.async_api import async_playwright + +CAMERAS = ("id_a", "id_b") +NAMES = {"id_a": "Alpha", "id_b": "Bravo"} +DAYS = ("20200101", "20200102", "20200103", "20200104", "20200105") +FLOOR, LEFTOVER = "20991231", "20190101" +PROTECTED = { + "id_a": [FLOOR + "/floor.mp4", LEFTOVER + "/leftover.tmp", "temp/retained-evidence/event.mp4", "temp/retained-evidence/recovery.json", "buffer/retained-unreported.mp4", "buffer/retained-big.mp4", "loose.mp4"], + "id_b": [FLOOR + "/floor.mp4", LEFTOVER + "/leftover.tmp", "loose.mp4"], +} + + +def sudo(*command, check=True): + return subprocess.run(["sudo", "-n", *command], check=check, capture_output=True, timeout=120) + + +def exists(path): + return sudo("test", "-e", str(path), check=False).returncode == 0 + + +def digest(path): + return sudo("sha256sum", str(path)).stdout.split()[0].decode() + + +def read_json(path): + return json.loads(sudo("cat", str(path)).stdout) + + +def container_log(container): + result = subprocess.run(["docker", "logs", container], capture_output=True, text=True, timeout=60) + return result.stdout + result.stderr + + +def ffmpeg_pids(container): + result = subprocess.run(["docker", "exec", container, "pidof", "ffmpeg"], capture_output=True, text=True, timeout=10) + return result.stdout.split() if result.returncode == 0 else [] + + +def seeded_events(): + events = {(NAMES[camera], "2020-01-0" + day[-1]) for camera in CAMERAS for day in DAYS} + events.add(("Live", "2020-01-01")) + return events + + +class Volume: + def __init__(self, state): + self.state = Path(state) + + def day(self, camera, day): + return self.state / camera / day + + def days_present(self, days, cameras=CAMERAS): + return all(exists(self.day(camera, day)) for camera in cameras for day in days) + + def days_absent(self, days, cameras=CAMERAS): + return not any(exists(self.day(camera, day)) for camera in cameras for day in days) + + def digests(self): + return {camera + "/" + rel: digest(self.state / camera / rel) for camera, items in PROTECTED.items() for rel in items} + + def config(self): + return read_json(self.state / "cameras.json") + + def events(self): + return sorted(set((event["camera_name"], event["start_time"][:10]) for event in self.config()["events"])) + + def hold(self, day): + # Hard links on the same volume stand in for a snapshot: deleting the names frees no space. + holds = self.state / ".holds" + sudo("mkdir", "-p", str(holds)) + for camera in CAMERAS: + listing = sudo("find", str(self.day(camera, day)), "-type", "f").stdout.decode().split("\n") + for source in filter(None, listing): + sudo("ln", source, str(holds / (camera + "-" + Path(source).name))) + + def release(self): + sudo("rm", "-rf", str(self.state / ".holds")) + + +async def wait_for(condition, what, timeout=30): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if await asyncio.to_thread(condition): + return + await asyncio.sleep(0.25) + raise AssertionError("timed out waiting for " + what) + + +async def stays(condition, what, seconds=3): + end = time.monotonic() + seconds + while time.monotonic() < end: + assert await asyncio.to_thread(condition), what + " changed" + await asyncio.sleep(0.25) + + +async def get_ceiling(request, origin): + response = await request.get(origin + "/api/storage/ceiling") + assert response.status == 200, response.status + return await response.json() + + +async def post_ceiling(request, origin, value): + response = await request.post(origin + "/api/storage/ceiling", data={"max_filesystem_used_percent": value}) + assert response.status == 200, (response.status, (await response.text())[:300]) + return await response.json() + + +async def login(page, origin): + await page.goto(origin + "/auth/login") + await page.locator('[name="username"]').fill("ci-prune") + await page.locator('[name="password"]').fill(os.environ["SIMPLENVR_E2E_PASSWORD"]) + await page.get_by_role("button", name="Sign in", exact=True).click() + await page.wait_for_url(origin + "/", wait_until="load") + + +async def open_settings(page): + await page.evaluate("openCameraSettings()") + await page.wait_for_function("(() => { const t = document.getElementById('filesystem-usage-text'); return !!t && t.textContent.startsWith('Filesystem used:'); })()") + + +def log_count(container, pattern): + return len(re.findall(pattern, container_log(container))) + + +async def main_phase(args, page, context, report): + request, volume, checks = context.request, Volume(args.state), report["checks_passed"] + protected = await asyncio.to_thread(volume.digests) + (args.evidence / "protected-digests.json").write_text(json.dumps(protected, indent=2) + "\n") + await login(page, args.origin) + checks.append("real-login") + await wait_for(lambda: ffmpeg_pids(args.container), "the live recorder's FFmpeg", 90) + + posts = [] + page.on("request", lambda r: posts.append(r.url) if r.method == "POST" and urlsplit(r.url).path == "/api/storage/ceiling" else None) + await open_settings(page) + api = await get_ceiling(request, args.origin) + assert api["max_filesystem_used_percent"] == 80 and api["filesystem_prune_trigger_percent"] == 78, api + used = api["filesystem_used_percent"] + assert used is not None and 40 < used < 75, api + shown = re.fullmatch(r"Filesystem used: ([0-9.]+)%\. Ceiling: ([0-9]+)%\. Trigger level: ([0-9]+)%\.", await page.locator("#filesystem-usage-text").inner_text()) + assert shown and abs(float(shown.group(1)) - used) < 1.5 and shown.group(2) == "80" and shown.group(3) == "78", shown + checks.append("settings-row-shows-server-usage-ceiling-and-trigger") + + assert await page.locator("#filesystem-ceiling-input").input_value() == "80" + await page.locator("#filesystem-ceiling-input").fill("90") + async with page.expect_response(lambda r: urlsplit(r.url).path == "/api/storage/ceiling" and r.request.method == "POST") as pending: + await page.locator("#filesystem-ceiling-button").click() + assert (await pending.value).status == 200 + assert (await get_ceiling(request, args.origin))["max_filesystem_used_percent"] == 90 + await stays(lambda: volume.days_present(DAYS), "seeded days after a ceiling above usage") + await page.reload(wait_until="load") + await open_settings(page) + assert await page.locator("#filesystem-ceiling-input").input_value() == "90" + sent = len(posts) + await page.locator("#filesystem-ceiling-input").fill("9") + await page.locator("#filesystem-ceiling-button").click() + await asyncio.sleep(1) + assert len(posts) == sent and (await get_ceiling(request, args.origin))["max_filesystem_used_percent"] == 90 + checks.append("settings-row-saves-valid-ceiling-persists-and-refuses-invalid") + + box = page.locator('#modal-camera-list .camera-box[data-camera-id="id_a"]') + await box.locator("#retention-id_a").fill("0") + async with page.expect_response(lambda r: urlsplit(r.url).path == "/api/cameras/update-retention") as pending: + await box.locator(".btn-update").click() + response = await pending.value + assert response.status == 200, response.status + assert json.loads(response.request.post_data) == {"id": "id_a", "retention_days": 0} + await page.locator("#modal-retention-all").fill("0") + async with page.expect_response(lambda r: urlsplit(r.url).path == "/api/cameras/update-retention-all") as pending: + await page.locator('#camera-settings-modal button:has-text("Set Retention")').click() + response = await pending.value + assert response.status == 200, response.status + assert json.loads(response.request.post_data) == {"retention_days": 0} + cameras = (await asyncio.to_thread(volume.config))["cameras"] + assert {c: cameras[c]["retention_days"] for c in cameras} == {"id_a": 0, "id_b": 0, "id_live": 0}, cameras + assert await page.locator("#modal-camera-list #retention-id_b").input_value() == "0" + checks.append("retention-zero-saved-through-the-real-ui-and-persisted") + + await post_ceiling(request, args.origin, 80) + await stays(lambda: volume.days_present(DAYS), "seeded days below the trigger") + checks.append("below-trigger-deletes-nothing") + + used = (await get_ceiling(request, args.origin))["filesystem_used_percent"] + ceiling = int(used - 12) + 2 + assert 10 <= ceiling <= 95, (used, ceiling) + await post_ceiling(request, args.origin, ceiling) + await wait_for(lambda: volume.days_absent(DAYS[:1]), "the oldest day of both cameras to be pruned") + assert await asyncio.to_thread(volume.days_present, DAYS[1:]) + expected = seeded_events() - {("Alpha", "2020-01-01"), ("Bravo", "2020-01-01")} + await wait_for(lambda: set(volume.events()) == expected, "events of the pruned day to be removed") + assert await asyncio.to_thread(volume.digests) == protected + for camera in CAMERAS: + assert log_count(args.container, r"removed 3 recording\(s\), \d+ bytes, from camera " + camera + r" day 20200101") == 1 + assert ffmpeg_pids(args.container) and (await asyncio.to_thread(volume.config))["cameras"]["id_live"]["is_recording"] is True + checks.append("one-oldest-day-per-camera-events-removed-evidence-untouched-recorder-running") + + await post_ceiling(request, args.origin, ceiling) + await wait_for(lambda: volume.days_absent(DAYS[1:2]), "the second day to be pruned") + assert await asyncio.to_thread(volume.days_present, DAYS[2:]) + await post_ceiling(request, args.origin, ceiling) + await stays(lambda: volume.days_present(DAYS[2:]), "days after usage fell below the trigger") + checks.append("repeated-passes-prune-one-day-each-and-stop-below-the-trigger") + + before = (await get_ceiling(request, args.origin))["filesystem_used_percent"] + await asyncio.to_thread(volume.hold, DAYS[2]) + await post_ceiling(request, args.origin, 10) + await wait_for(lambda: volume.days_absent(DAYS[2:3]), "the held day's names to be removed") + await wait_for(lambda: "Filesystem pruning paused" in container_log(args.container), "the no-effect pause") + held = (await get_ceiling(request, args.origin))["filesystem_used_percent"] + assert abs(held - before) < 1.0, (before, held) + await post_ceiling(request, args.origin, 10) + await stays(lambda: volume.days_present(DAYS[3:]), "days while pruning is paused") + await asyncio.to_thread(volume.release) + await post_ceiling(request, args.origin, 10) + await wait_for(lambda: volume.days_absent(DAYS[3:4]), "pruning to resume after space was freed") + assert "Filesystem pruning resumed" in container_log(args.container) + checks.append("no-effect-guard-pauses-and-resumes-with-hard-link-stand-in-for-a-snapshot") + + immutable = Path(args.state) / "id_a" / DAYS[4] / "seg2.mp4" + await asyncio.to_thread(sudo, "chattr", "+i", str(immutable)) + await post_ceiling(request, args.origin, 10) + await wait_for(lambda: volume.days_absent(DAYS[4:], ["id_b"]), "the other camera's day to be pruned") + await wait_for(lambda: log_count(args.container, r"incomplete for camera id_a day 20200105: removed 2 recording\(s\), 1 could not be removed") >= 1, "the partial failure log") + assert await asyncio.to_thread(exists, immutable) + assert not await asyncio.to_thread(exists, Path(args.state) / "id_a" / DAYS[4] / "seg1.mp4") + kept = set(await asyncio.to_thread(volume.events)) + assert ("Alpha", "2020-01-05") in kept and ("Bravo", "2020-01-05") not in kept, kept + checks.append("partial-failure-continues-logs-and-keeps-events-of-that-day") + + await asyncio.to_thread(sudo, "chattr", "-i", str(immutable)) + await post_ceiling(request, args.origin, 10) + await wait_for(lambda: volume.days_absent(DAYS), "every prunable day to be gone") + await wait_for(lambda: volume.events() == [("Live", "2020-01-01")], "all pruned days' events to be gone") + assert await asyncio.to_thread(volume.digests) == protected + for camera in CAMERAS: + assert await asyncio.to_thread(exists, volume.day(camera, FLOOR)) + final = (await get_ceiling(request, args.origin))["filesystem_used_percent"] + assert final >= 10, "the volume is too empty to show the ceiling-not-met state: %s" % final + await post_ceiling(request, args.origin, 10) + await wait_for(lambda: log_count(args.container, "cannot meet the ceiling") == 1, "the ceiling-not-met log") + await post_ceiling(request, args.origin, 10) + await stays(lambda: log_count(args.container, "cannot meet the ceiling") == 1, "the ceiling-not-met log count") + checks.append("newest-day-and-evidence-kept-ceiling-not-met-logged-once") + assert ffmpeg_pids(args.container) + checks.append("recorder-ran-throughout") + + +async def restart_phase(args, page, context, report): + volume = Volume(args.state) + expected = json.loads((args.evidence / "protected-digests.json").read_text()) + await login(page, args.origin) + api = await get_ceiling(context.request, args.origin) + assert api["max_filesystem_used_percent"] == 10 and api["filesystem_prune_trigger_percent"] == 8, api + await stays(lambda: volume.digests() == expected, "protected files after restart") + report["checks_passed"].append("restart-keeps-the-saved-ceiling-and-protected-files") + + +async def run(args): + args.evidence.mkdir(parents=True, exist_ok=True) + report = {"phase": args.phase, "commit": args.commit, "image_id": args.image_id, "backend": "real HTTPS runtime container on a loopback ext4 volume", "checks_passed": [], "status": "failed", "limits": "File-fed FFmpeg capture input; no live RTSP; no ZFS or snapshots (hard links stand in); the 5-minute tick and age cleanup on it are not exercised."} + async with async_playwright() as p: + browser = await p.chromium.launch(channel="chrome", headless=True) + context = await browser.new_context(ignore_https_errors=True, timezone_id="UTC") + context.set_default_timeout(30000) + errors = [] + try: + page = await context.new_page() + page.on("pageerror", lambda e: errors.append(str(e)[:500])) + if args.phase == "main": + await main_phase(args, page, context, report) + else: + await restart_phase(args, page, context, report) + assert not errors, errors + report["status"] = "passed" + except BaseException as error: + report["failure"] = type(error).__name__ + ": " + str(error)[:2000] + report["container_log_tail"] = container_log(args.container)[-4000:] + raise + finally: + (args.evidence / ("filesystem-prune-" + args.phase + "-report.json")).write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps(report, indent=2), flush=True) + await context.close() + await browser.close() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--phase", choices=("main", "restart"), required=True) + parser.add_argument("--origin", required=True) + parser.add_argument("--container", required=True) + parser.add_argument("--state", required=True) + parser.add_argument("--evidence", type=Path, required=True) + parser.add_argument("--commit", required=True) + parser.add_argument("--image-id", required=True) + asyncio.run(run(parser.parse_args())) From fd8cbd65ee96ed54fe6ea951f445edd7fe1e3f4b Mon Sep 17 00:00:00 2001 From: mouldybread <38598858+mouldybread@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:08:45 +0800 Subject: [PATCH 10/12] Fix: let POST /api/storage/ceiling through the auth method policy The auth layer allowed only GET and HEAD on paths outside mutationPaths and only POST on paths inside it, so the ceiling route (GET and POST) was rejected with 405 on every POST in a running server. CP3 tests called the handler directly and bypassed auth. Add a small read-write mutation allowlist, register the ceiling route as a tracked mutation that also serves reads, test it through the real auth handler, and print the response status when the acceptance save assertion fails. --- cmd/simplenvr/auth.go | 25 +++++- cmd/simplenvr/filesystem_ceiling_routes.go | 11 +++ .../filesystem_ceiling_routes_test.go | 77 +++++++++++++++++++ .../acceptance/filesystem_prune_acceptance.py | 16 ++-- 4 files changed, 119 insertions(+), 10 deletions(-) create mode 100644 cmd/simplenvr/filesystem_ceiling_routes.go create mode 100644 cmd/simplenvr/filesystem_ceiling_routes_test.go diff --git a/cmd/simplenvr/auth.go b/cmd/simplenvr/auth.go index 793c736..dd55ed9 100644 --- a/cmd/simplenvr/auth.go +++ b/cmd/simplenvr/auth.go @@ -228,6 +228,25 @@ var mutationPaths = map[string]bool{ "/api/events/clear-all":true, "/api/events/clear-camera":true, } +// readWriteMutationPaths are mutation paths that also serve GET and HEAD reads. They +// stay in mutationPaths, so the shutdown gate still tracks their POST, and cross-origin +// protection and the session check still apply to every method. +var readWriteMutationPaths = map[string]bool{} + +// methodPolicy says which methods a path accepts once the caller is authenticated. +// Paths outside mutationPaths accept only GET and HEAD, mutation paths only POST, and +// read-write mutation paths all three. +func methodPolicy(path, method string) (allow string, ok bool) { + switch { + case readWriteMutationPaths[path]: + return "GET, HEAD, POST", method == http.MethodGet || method == http.MethodHead || method == http.MethodPost + case mutationPaths[path]: + return "POST", method == http.MethodPost + default: + return "GET, HEAD", method == http.MethodGet || method == http.MethodHead + } +} + func (a *authManager) Handler(next http.Handler) http.Handler { protected := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Content-Type-Options", "nosniff") @@ -247,10 +266,8 @@ func (a *authManager) Handler(next http.Handler) http.Handler { } if r.URL.Path == "/api/settings/session" { a.sessionSettingsHandler(w,r); return } if r.URL.Path == "/api/settings/restart" { a.restartHandler(w,r); return } - if mutationPaths[r.URL.Path] { - if r.Method != http.MethodPost { w.Header().Set("Allow","POST"); http.Error(w,"Method not allowed",http.StatusMethodNotAllowed); return } - } else if r.Method != http.MethodGet && r.Method != http.MethodHead { - w.Header().Set("Allow","GET, HEAD"); http.Error(w,"Method not allowed",http.StatusMethodNotAllowed); return + if allow, ok := methodPolicy(r.URL.Path, r.Method); !ok { + w.Header().Set("Allow",allow); http.Error(w,"Method not allowed",http.StatusMethodNotAllowed); return } if strings.HasPrefix(r.URL.Path,"/recordings/") { servePrivateRecording(w,r); return } clean := r.Clone(r.Context()) diff --git a/cmd/simplenvr/filesystem_ceiling_routes.go b/cmd/simplenvr/filesystem_ceiling_routes.go new file mode 100644 index 0000000..ad22c1e --- /dev/null +++ b/cmd/simplenvr/filesystem_ceiling_routes.go @@ -0,0 +1,11 @@ +package main + +const filesystemCeilingPath="/api/storage/ceiling" + +// The ceiling route serves GET (read) and POST (change). Registering it as a tracked +// mutation makes the shutdown gate wait for an in-flight save, and registering it as +// read-write lets the auth layer accept its GET as well as its POST. +func init() { + mutationPaths[filesystemCeilingPath]=true + readWriteMutationPaths[filesystemCeilingPath]=true +} diff --git a/cmd/simplenvr/filesystem_ceiling_routes_test.go b/cmd/simplenvr/filesystem_ceiling_routes_test.go new file mode 100644 index 0000000..2ec99e3 --- /dev/null +++ b/cmd/simplenvr/filesystem_ceiling_routes_test.go @@ -0,0 +1,77 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" +) + +func httpHandlerRecording(reached *[]string) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter,r *http.Request) { + *reached=append(*reached,r.Method+" "+r.URL.Path) + w.WriteHeader(204) + }) +} + +func TestMethodPolicy(t *testing.T) { + for _,c:=range []struct{path,method,allow string;ok bool}{ + {"/api/storage/ceiling","GET","GET, HEAD, POST",true}, + {"/api/storage/ceiling","HEAD","GET, HEAD, POST",true}, + {"/api/storage/ceiling","POST","GET, HEAD, POST",true}, + {"/api/storage/ceiling","PUT","GET, HEAD, POST",false}, + {"/api/storage/ceiling","DELETE","GET, HEAD, POST",false}, + {"/api/cameras/delete-all","POST","POST",true}, + {"/api/cameras/delete-all","GET","POST",false}, + {"/api/cameras/update-retention","GET","POST",false}, + {"/api/cameras","GET","GET, HEAD",true}, + {"/api/cameras","POST","GET, HEAD",false}, + {"/api/storage/status","POST","GET, HEAD",false}, + } { + allow,ok:=methodPolicy(c.path,c.method) + if allow!=c.allow || ok!=c.ok {t.Fatalf("%s %s = %q, %v; want %q, %v",c.method,c.path,allow,ok,c.allow,c.ok)} + } +} + +func TestFilesystemCeilingPathIsATrackedMutation(t *testing.T) { + if !mutationPaths[filesystemCeilingPath] {t.Fatal("the shutdown gate would not wait for an in-flight ceiling save")} + if !readWriteMutationPaths[filesystemCeilingPath] {t.Fatal("the auth layer would reject the ceiling read")} + for path:=range readWriteMutationPaths { + if !mutationPaths[path] {t.Fatalf("%s is read-write but not a tracked mutation",path)} + } +} + +// The CP3 handler tests called the handler directly and never saw the auth layer, which +// rejected every POST with 405. This sends the route through the real auth handler. +func TestFilesystemCeilingRouteThroughRealAuth(t *testing.T) { + a,_:=authFixture(t) + var reached []string + handler:=a.Handler(httpHandlerRecording(&reached)) + form:=url.Values{"username":{"admin"},"password":{"correct horse battery staple"}} + login:=httptest.NewRequest("POST","https://nvr.test/auth/login",strings.NewReader(form.Encode())) + login.Header.Set("Content-Type","application/x-www-form-urlencoded") + loginResponse:=httptest.NewRecorder();handler.ServeHTTP(loginResponse,login) + if loginResponse.Code!=303 {t.Fatalf("login: %d",loginResponse.Code)} + cookies:=loginResponse.Result().Cookies() + if len(cookies)==0 {t.Fatal("no session cookie")} + request:=func(method,origin string,withCookie bool) *httptest.ResponseRecorder { + r:=httptest.NewRequest(method,"https://nvr.test"+filesystemCeilingPath,strings.NewReader(`{"max_filesystem_used_percent":90}`)) + if withCookie {r.AddCookie(cookies[0])} + if origin!="" {r.Header.Set("Origin",origin)} + w:=httptest.NewRecorder();handler.ServeHTTP(w,r);return w + } + for _,method:=range []string{"GET","HEAD"} { + if w:=request(method,"",true);w.Code!=204 {t.Fatalf("%s with a session: %d",method,w.Code)} + } + if w:=request("POST","https://nvr.test",true);w.Code!=204 {t.Fatalf("POST with a session: %d",w.Code)} + for _,method:=range []string{"PUT","DELETE","PATCH"} { + w:=request(method,"https://nvr.test",true) + if w.Code!=405 || w.Header().Get("Allow")!="GET, HEAD, POST" {t.Fatalf("%s: %d allow %q",method,w.Code,w.Header().Get("Allow"))} + } + if w:=request("POST","https://evil.invalid",true);w.Code!=403 {t.Fatalf("cross-origin POST: %d",w.Code)} + if w:=request("GET","",false);w.Code!=401 {t.Fatalf("unauthenticated GET: %d",w.Code)} + if w:=request("POST","https://nvr.test",false);w.Code!=401 {t.Fatalf("unauthenticated POST: %d",w.Code)} + want:="GET /api/storage/ceiling,HEAD /api/storage/ceiling,POST /api/storage/ceiling" + if got:=strings.Join(reached,",");got!=want {t.Fatalf("requests that reached the handler = %q; want %q",got,want)} +} diff --git a/tests/acceptance/filesystem_prune_acceptance.py b/tests/acceptance/filesystem_prune_acceptance.py index adb84e2..d9d25f9 100644 --- a/tests/acceptance/filesystem_prune_acceptance.py +++ b/tests/acceptance/filesystem_prune_acceptance.py @@ -111,7 +111,7 @@ async def stays(condition, what, seconds=3): async def get_ceiling(request, origin): response = await request.get(origin + "/api/storage/ceiling") - assert response.status == 200, response.status + assert response.status == 200, (response.status, (await response.text())[:300]) return await response.json() @@ -138,6 +138,12 @@ def log_count(container, pattern): return len(re.findall(pattern, container_log(container))) +async def expect_ok(pending, what): + response = await pending.value + assert response.status == 200, (what, response.status, (await response.text())[:300]) + return response + + async def main_phase(args, page, context, report): request, volume, checks = context.request, Volume(args.state), report["checks_passed"] protected = await asyncio.to_thread(volume.digests) @@ -161,7 +167,7 @@ async def main_phase(args, page, context, report): await page.locator("#filesystem-ceiling-input").fill("90") async with page.expect_response(lambda r: urlsplit(r.url).path == "/api/storage/ceiling" and r.request.method == "POST") as pending: await page.locator("#filesystem-ceiling-button").click() - assert (await pending.value).status == 200 + await expect_ok(pending, "saving the ceiling from the settings row") assert (await get_ceiling(request, args.origin))["max_filesystem_used_percent"] == 90 await stays(lambda: volume.days_present(DAYS), "seeded days after a ceiling above usage") await page.reload(wait_until="load") @@ -178,14 +184,12 @@ async def main_phase(args, page, context, report): await box.locator("#retention-id_a").fill("0") async with page.expect_response(lambda r: urlsplit(r.url).path == "/api/cameras/update-retention") as pending: await box.locator(".btn-update").click() - response = await pending.value - assert response.status == 200, response.status + response = await expect_ok(pending, "saving retention 0 for one camera") assert json.loads(response.request.post_data) == {"id": "id_a", "retention_days": 0} await page.locator("#modal-retention-all").fill("0") async with page.expect_response(lambda r: urlsplit(r.url).path == "/api/cameras/update-retention-all") as pending: await page.locator('#camera-settings-modal button:has-text("Set Retention")').click() - response = await pending.value - assert response.status == 200, response.status + response = await expect_ok(pending, "saving retention 0 for all cameras") assert json.loads(response.request.post_data) == {"retention_days": 0} cameras = (await asyncio.to_thread(volume.config))["cameras"] assert {c: cameras[c]["retention_days"] for c in cameras} == {"id_a": 0, "id_b": 0, "id_live": 0}, cameras From f9b1dc2c1cfb50d36a099e22fe3e37fb8fbf135f Mon Sep 17 00:00:00 2001 From: mouldybread <38598858+mouldybread@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:13:26 +0800 Subject: [PATCH 11/12] Fix: per-camera retention Update read the hidden duplicate input The camera list is rendered twice with the same element ids (a hidden section and the settings dialog). getElementById returns the hidden copy, so Update sent its stale value instead of what was typed in the settings dialog. Look the input up in the settings dialog's list first, falling back to the old lookup, and test it. --- tests/frontend/retention-days.cjs | 27 +++++++++++++++++++++++++-- web/static/js/retention-days.js | 13 ++++++++++++- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/tests/frontend/retention-days.cjs b/tests/frontend/retention-days.cjs index 745d088..5efb45c 100644 --- a/tests/frontend/retention-days.cjs +++ b/tests/frontend/retention-days.cjs @@ -10,11 +10,18 @@ const cameraTemplate = fs.readFileSync(path.join(root, 'web', 'templates', 'came const HTML = '

Updated
'; const INVALID = 'Please enter a whole number of days from 0 to 365 (0 = no age limit)'; -function makeEnv(respond, inputs) { +function makeEnv(respond, inputs, modalInputs) { + const scoped = modalInputs || {}; const elements = {}; for (const id of Object.keys(inputs)) elements[id] = {id, value: inputs[id]}; elements['camera-list'] = {innerHTML: 'original-main'}; - elements['modal-camera-list'] = {innerHTML: 'original-modal'}; + elements['modal-camera-list'] = { + innerHTML: 'original-modal', + querySelector(selector) { + const match = /^\[id="(.*)"\]$/.exec(selector); + return match ? (scoped[match[1]] || null) : null; + } + }; const requests = [], successes = [], errors = [], heights = []; let baseCalls = 0; const window = { @@ -101,6 +108,21 @@ async function failuresNeverAnnounceSuccess() { } } +async function perCameraReadsTheSettingsListCopy() { + // The hidden section's input still shows 7; the settings dialog's copy was edited to 0. + const env = makeEnv(okResponse, {'retention-cam1': '7'}, {'retention-cam1': {id: 'retention-cam1', value: '0'}}); + env.window.updateRetention('cam1'); + await settle(); + assert.equal(env.requests.length, 1); + assert.deepEqual(JSON.parse(env.requests[0].options.body), {id: 'cam1', retention_days: 0}); + // An invalid value in the settings copy is refused even though the hidden copy is valid. + const refused = makeEnv(okResponse, {'retention-cam1': '7'}, {'retention-cam1': {id: 'retention-cam1', value: '999'}}); + refused.window.updateRetention('cam1'); + await settle(); + assert.equal(refused.requests.length, 0); + assert.deepEqual(refused.errors, [INVALID]); +} + function openingSettingsAllowsZero() { const env = makeEnv(okResponse, {'modal-retention-all': '7'}); env.elements['modal-retention-all'].min = '1'; @@ -130,6 +152,7 @@ const tests = [ ['invalid input is never sent', invalidInputIsNeverSent], ['a missing input is never sent', missingInputIsNeverSent], ['failures never announce success', failuresNeverAnnounceSuccess], + ['per-camera update reads the settings dialog input, not the hidden duplicate', perCameraReadsTheSettingsListCopy], ['opening settings allows 0 in the bulk input', openingSettingsAllowsZero], ['script loads once, after cameras.js and modals.js', scriptLoadsOnceAfterCamerasAndModals], ['camera list input allows 0 and explains it', cameraListInputAllowsZero] diff --git a/web/static/js/retention-days.js b/web/static/js/retention-days.js index 56129dd..8b987b8 100644 --- a/web/static/js/retention-days.js +++ b/web/static/js/retention-days.js @@ -20,6 +20,17 @@ return days <= MAX_DAYS ? days : NaN; } + // The camera list is rendered twice with the same element ids: in a hidden section + // and in the settings dialog. getElementById returns the hidden copy, whose value is + // stale, so prefer the settings dialog's own input and fall back to the old lookup. + function retentionInput(cameraId) { + const list = document.getElementById('modal-camera-list'); + const scoped = list && typeof list.querySelector === 'function' + ? list.querySelector('[id="retention-' + cameraId + '"]') + : null; + return scoped || document.getElementById('retention-' + cameraId); + } + function showLists(html, both) { if (both) { const main = document.getElementById('camera-list'); @@ -51,7 +62,7 @@ } window.updateRetention = function (cameraId) { - const input = document.getElementById('retention-' + cameraId); + const input = retentionInput(cameraId); const days = input ? parseDays(input.value) : NaN; if (Number.isNaN(days)) { notify('error', INVALID); return; } send('/api/cameras/update-retention', { id: cameraId, retention_days: days }, From d86f255fab03936b4a57b7174eb22e8e44743f8d Mon Sep 17 00:00:00 2001 From: mouldybread <38598858+mouldybread@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:30:35 +0800 Subject: [PATCH 12/12] Fix: log ceiling-not-met once per ceiling value, not once per save requestPass re-armed the message on every ceiling save, so saving the same value twice logged it twice, contradicting the documented behavior. Remember the ceiling the state was logged for: the same ceiling stays silent, a different one logs again, and falling below the trigger or pruning something still resets it. --- cmd/simplenvr/filesystem_prune.go | 10 ++++-- cmd/simplenvr/filesystem_prune_notmet_test.go | 31 +++++++++++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) create mode 100644 cmd/simplenvr/filesystem_prune_notmet_test.go diff --git a/cmd/simplenvr/filesystem_prune.go b/cmd/simplenvr/filesystem_prune.go index 2fd4292..a7f47f8 100644 --- a/cmd/simplenvr/filesystem_prune.go +++ b/cmd/simplenvr/filesystem_prune.go @@ -56,6 +56,7 @@ type filesystemPruner struct { guardActive bool guardBaseline uint64 notMet bool + notMetCeiling int } func newFilesystemPruner(n *NVR,ceiling *filesystemCeilingSetting,read func(string) (filesystemUsage,error),persist func() error) *filesystemPruner { @@ -65,9 +66,9 @@ func newFilesystemPruner(n *NVR,ceiling *filesystemCeilingSetting,read func(stri var recordingFilesystemPruner=newFilesystemPruner(nvr,recordingFilesystemCeiling,readFilesystemUsage,func() error {return nvr.save()}) // requestPass asks the running job for a pass soon, for example after the ceiling -// changed. It never blocks and never deletes by itself. +// changed. It never blocks and never deletes by itself. It does not re-arm the +// ceiling-not-met message: that message is logged once per ceiling value. func (p *filesystemPruner) requestPass() { - p.mu.Lock();p.notMet=false;p.mu.Unlock() select {case p.requests<-struct{}{}:default:} } @@ -121,8 +122,11 @@ func (p *filesystemPruner) guardFor(ctx context.Context,t pruneTarget) func() er func (p *filesystemPruner) setNotMet(state bool) {p.mu.Lock();p.notMet=state;p.mu.Unlock()} +// enterNotMet logs the ceiling-not-met state once for a given ceiling value. The same +// ceiling stays silent; a different ceiling logs again; falling below the trigger or +// pruning something clears the state through setNotMet. func (p *filesystemPruner) enterNotMet(used float64,ceiling int) { - p.mu.Lock();already:=p.notMet;p.notMet=true;p.mu.Unlock() + p.mu.Lock();already:=p.notMet && p.notMetCeiling==ceiling;p.notMet=true;p.notMetCeiling=ceiling;p.mu.Unlock() if !already {log.Printf("Filesystem pruning cannot meet the ceiling: no prunable day remains (used %.1f%%, ceiling %d%%)",used,ceiling)} } diff --git a/cmd/simplenvr/filesystem_prune_notmet_test.go b/cmd/simplenvr/filesystem_prune_notmet_test.go new file mode 100644 index 0000000..66031d1 --- /dev/null +++ b/cmd/simplenvr/filesystem_prune_notmet_test.go @@ -0,0 +1,31 @@ +package main + +import ( + "context" + "strings" + "testing" +) + +// The ceiling-not-met line is logged once per ceiling value. Saving the same ceiling +// again must not repeat it; a different ceiling logs it again once. +func TestPruneCeilingNotMetLogsOncePerCeilingValue(t *testing.T) { + f:=newPruneFixture(t,"a") + logs:=captureLog(t) + f.file("a","20991231/floor.mp4") + ctx:=context.Background() + count:=func() int {return strings.Count(logs(),"cannot meet the ceiling")} + f.p.runPass(ctx) + if got:=count();got!=1 {t.Fatalf("first pass logged %d times",got)} + for i:=0;i<3;i++ { + f.p.requestPass() + f.p.runPass(ctx) + } + if got:=count();got!=1 {t.Fatalf("same ceiling logged %d times after repeated requests",got)} + f.ceiling.set(70) + f.p.requestPass() + f.p.runPass(ctx) + if got:=count();got!=2 {t.Fatalf("a different ceiling logged %d times; want 2",got)} + f.p.requestPass() + f.p.runPass(ctx) + if got:=count();got!=2 {t.Fatalf("the new ceiling repeated: %d",got)} +}