hub (unreleased): the notice lock — no notice, no deletion; the hub sends the household's notice itself (decision 315, R-1374)

The hub agrees to remove a removed app's off-site copies only when its OWN record
(offsite_end_notices) says the household was told at least 30 days ago, by the hub's
clock — beside the 30 days of absence. The notice is sent from the box's report, at
every report until the mail service accepts it; the box's event mails nobody.
No address or a blocked household: the operator is mailed in its place and that mail
starts the 30 days. A notice that cannot go out: no agreement, the window's answer
names the reason, one line to the operator after 3 days.

This commit also supplies the files that handler.go (c3fa43a4) already calls
(store.NoteEndNotices, api.kickEndNotices) and the tests that replace
TestD84_Receipt_* (their files left the tree in b8cf6c24).

Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
This commit is contained in:
admin committed 2026-11-15 16:17:44 +01:00
1 parent b8cf6c2417
commit 42ef25c23b
25 files changed
+2077 -184

No files matched your search

+196
View File
@@ -0,0 +1,196 @@
package api
import (
"encoding/json"
"fmt"
"sort"
"sync"
"time"
"gitea.dooplex.hu/admin/felhom-hub/internal/notify"
"gitea.dooplex.hu/admin/felhom-hub/internal/offsitekeys"
"gitea.dooplex.hu/admin/felhom-hub/internal/store"
)
// THE NOTICE LOCK (`09` §3 decision 315; `07-backup-architecture.md` §8.2f „No notice, no deletion”) — the hub sends
// the household's notice ITSELF, from its own state, until it has gone.
//
// Every controller report feeds the hub's record (store.NoteEndNotices: which apps the box names in a pending end
// record). After that, endNotices walks the household's rows and, for each one whose household has not been told:
//
// - tries the household's mail (notify.SendEndNotice). Sent → the record says „told” at the hub's time, and the
// hub agrees to remove that app's copies no earlier than 30 days after it (offsitekeys.agreeEnded).
// - no address, or a blocked household → the OPERATOR is mailed in its place, once per app
// (`offsite_end_notice_operator`), and that mail starts the 30 days. When an address appears later, the household
// gets its own mail and the 30 days start again from it.
// - the daily limit, the mail hold, a send that fails → nothing is told; the reason is written on the row (the
// window's answer names it) and the next try is at a report at least endNoticeRetryGap later.
// - a row that has not been told for EndNoticeStuckAfter → one line to the operator (`offsite_end_notice_stuck`).
//
// Nothing here reads a date a box sent, and no event of a box starts or stops anything.
const (
// endNoticeRetryGap: after a try that told nobody, the next try waits this long (a report comes every 15 minutes;
// a mail service that is down is not asked 96 times a day per app).
endNoticeRetryGap = time.Hour
// EndNoticeStuckAfter: how long a notice may stay unsent before the operator gets one line. THREE DAYS: longer
// than any outage of the mail service the hub has had and than the hold on a restored copy is meant to last, and
// longer than the daily limit delays an honest household (5 notices a day: a household that removes up to 15
// apps at once is told about all of them inside it) — so the line means „this will not heal by itself”. Short
// enough that a deletion the household asked for has lost three days, not a month, when the operator hears.
EndNoticeStuckAfter = 3 * 24 * time.Hour
)
// endNoticeSpawn runs the sends off the report's request (a send can wait 10 s on the mail service). A seam: tests
// run it in line.
var endNoticeSpawn = func(f func()) { go f() }
// endNoticeBusy: one walk per household at a time — a second report that arrives while a walk is still sending does
// not send the same notice again; its rows are picked up by the next report.
var endNoticeBusy sync.Map // customerID → *sync.Mutex
// kickEndNotices starts a walk when the household has a row that still needs one.
func (h *Handler) kickEndNotices(customerID string) {
ns, err := h.store.EndNotices(customerID)
if err != nil {
h.logger.Printf("[WARN] [end-notice] %s: the hub's own notice record could not be read: %v", customerID, err)
return
}
work := false
for _, n := range ns {
if n.ToldTo != store.EndNoticeHousehold {
work = true
}
}
if work {
endNoticeSpawn(func() { h.endNotices(customerID, time.Now()) })
}
}
// endNotices is one walk over a household's rows (see the header). now is the HUB's clock.
func (h *Handler) endNotices(customerID string, now time.Time) {
mu, _ := endNoticeBusy.LoadOrStore(customerID, &sync.Mutex{})
if !mu.(*sync.Mutex).TryLock() {
return
}
defer mu.(*sync.Mutex).Unlock()
ns, err := h.store.EndNotices(customerID)
if err != nil {
h.logger.Printf("[WARN] [end-notice] %s: the hub's own notice record could not be read: %v", customerID, err)
return
}
apps := make([]string, 0, len(ns))
for app := range ns {
apps = append(apps, app)
}
sort.Strings(apps)
for _, app := range apps {
n := ns[app]
if n.ToldTo == store.EndNoticeHousehold {
continue
}
if n.LastReason != "" && !n.LastTry.IsZero() && now.Sub(n.LastTry) < endNoticeRetryGap {
h.endNoticeStuck(customerID, n, now)
continue
}
outcome, why := notify.EndNoticeFailed, "the hub has no mail service configured"
if h.dispatcher != nil {
// The day in the mail is the hub's own: its clock now + 30 days. Never the box's date.
outcome, why = h.dispatcher.SendEndNotice(customerID, app, now.Add(offsitekeys.EndedAppAfter))
}
switch outcome {
case notify.EndNoticeSent:
ok, merr := h.store.MarkEndNoticeTold(customerID, app, n.Press, store.EndNoticeHousehold, now)
if merr != nil || !ok {
// The mail went and the record does not say so: the household is mailed again at a later report and
// the 30 days start then. The safe direction (no deletion on a notice the hub cannot show).
h.logger.Printf("[WARN] [end-notice] %s/%s: the household's notice was sent, but the hub's record was NOT written (matched=%v, err=%v) — it will be sent again", customerID, app, ok, merr)
continue
}
n.ToldAt, n.ToldTo = now, store.EndNoticeHousehold
h.logger.Printf("[INFO] [end-notice] %s/%s: the household was told; the hub agrees to remove this app's off-site copies no earlier than %s",
customerID, app, now.Add(offsitekeys.EndedAppAfter).UTC().Format("2006-01-02"))
case notify.EndNoticeNoAddress:
if n.Told() {
continue // the operator was told in its place; the household still has no address
}
if terr := h.endNoticeToOperator(customerID, n, why, now); terr != nil {
why = why + "; and the operator could not be told in its place (" + terr.Error() + ")"
h.endNoticeTried(customerID, &n, why, now)
} else {
n.ToldAt, n.ToldTo = now, store.EndNoticeOperator
}
default: // the daily limit, the hold, a failed send
h.endNoticeTried(customerID, &n, why, now)
}
h.endNoticeStuck(customerID, n, now)
}
}
func (h *Handler) endNoticeTried(customerID string, n *store.EndNotice, why string, now time.Time) {
if err := h.store.MarkEndNoticeTried(customerID, n.App, n.Press, why, now); err != nil {
h.logger.Printf("[WARN] [end-notice] %s/%s: the try could not be recorded: %v", customerID, n.App, err)
}
n.LastReason, n.LastTry = why, now
h.logger.Printf("[WARN] [end-notice] %s/%s: nobody was told (%s) — nothing of this app is removed; tried again at a later report", customerID, n.App, why)
}
// endNoticeToOperator mails the operator in place of a household the hub cannot mail, and only when the mail service
// accepted that mail does the record say „told” (to the operator): that mail starts the app's 30 days.
// DECIDED BY CC UNATTENDED 2026-11-15 (the brief's A.3) — the operator may reverse it: `07` §8.2f.
func (h *Handler) endNoticeToOperator(customerID string, n store.EndNotice, why string, now time.Time) error {
if h.dispatcher == nil {
return fmt.Errorf("the hub has no mail service configured")
}
day := now.Add(offsitekeys.EndedAppAfter).UTC().Format("2006-01-02")
msg := fmt.Sprintf("Off-site: the household %s removed the app %q with „delete backup data”, and the hub could not tell the household: %s. "+
"This mail is the notice in its place. The hub counts the 30 days from now: from %s a clean-up window may remove that app's off-site copies. "+
"Tell the household. If the household did not ask for this, it can take it back on its Backups page (“Keep it after all”) and must change its password. "+
"When the household gets a notification address, the hub mails the household itself and the 30 days start again from that mail.",
customerID, n.App, why, day)
details, _ := json.Marshal(map[string]any{"subject": n.App, "app": n.App, "agrees_from": day})
if err := h.dispatcher.SendOperatorNow(customerID, offsitekeys.EventEndNoticeOperator, "warning", msg, string(details)); err != nil {
return err
}
if _, err := h.store.SaveEvent(customerID, offsitekeys.EventEndNoticeOperator, "warning", msg, string(details), "hub"); err != nil {
h.logger.Printf("[WARN] [end-notice] %s event save FAILED for %s (the mail went): %v", offsitekeys.EventEndNoticeOperator, customerID, err)
}
ok, err := h.store.MarkEndNoticeTold(customerID, n.App, n.Press, store.EndNoticeOperator, now)
if err != nil || !ok {
return fmt.Errorf("the operator's mail went, but the hub's record was not written (matched=%v, err=%v)", ok, err)
}
h.logger.Printf("[WARN] [end-notice] %s/%s: the household could not be told (%s) — the OPERATOR was told in its place; the hub agrees no earlier than %s", customerID, n.App, why, day)
return nil
}
// endNoticeStuck files the operator's one line for a notice that has told nobody for EndNoticeStuckAfter. Not while
// the mail hold is on (a held hub mails nobody; the line is filed at the first report after the release).
func (h *Handler) endNoticeStuck(customerID string, n store.EndNotice, now time.Time) {
if n.Told() || !n.StuckTold.IsZero() || n.FirstNamed.IsZero() || now.Sub(n.FirstNamed) < EndNoticeStuckAfter {
return
}
if h.dispatcher != nil && h.dispatcher.MailHeld() {
return
}
why := n.LastReason
if why == "" {
why = "no try has been recorded"
}
msg := fmt.Sprintf("Off-site: the household %s removed the app %q with „delete backup data” %d days ago, and the notice about it has not gone out: %s. "+
"NOTHING of that app's off-site copies is removed until the notice has gone and 30 days have passed after it. "+
"The household asked for this deletion and it is waiting: look at why the mail does not go. This line is sent once per app.",
customerID, n.App, int(now.Sub(n.FirstNamed).Hours()/24), why)
details, _ := json.Marshal(map[string]any{"subject": n.App, "app": n.App, "reason": why})
if _, err := h.store.SaveEvent(customerID, offsitekeys.EventEndNoticeStuck, "warning", msg, string(details), "hub"); err != nil {
h.logger.Printf("[WARN] [end-notice] %s event save FAILED for %s: %v", offsitekeys.EventEndNoticeStuck, customerID, err)
return // the audit row first: a mail without its event row lies
}
if err := h.store.MarkEndNoticeStuckTold(customerID, n.App, n.Press, now); err != nil {
h.logger.Printf("[WARN] [end-notice] %s/%s: the operator's line could not be marked as filed: %v", customerID, n.App, err)
}
h.logger.Printf("[WARN] [end-notice] %s/%s: the notice has told nobody for %d days (%s) — operator told once", customerID, n.App, int(now.Sub(n.FirstNamed).Hours()/24), why)
if h.dispatcher != nil {
h.dispatcher.ProcessEvent(customerID, offsitekeys.EventEndNoticeStuck, "warning", msg, string(details), "hub")
}
}
+509
View File
@@ -0,0 +1,509 @@
package api
import (
"errors"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"gitea.dooplex.hu/admin/felhom-hub/internal/mailhold"
"gitea.dooplex.hu/admin/felhom-hub/internal/notify"
"gitea.dooplex.hu/admin/felhom-hub/internal/offsitekeys"
"gitea.dooplex.hu/admin/felhom-hub/internal/store"
)
// THE NOTICE LOCK (`09` §3 decision 315; `07-backup-architecture.md` §8.2f „No notice, no deletion”): the hub sends
// the household's notice itself, from the box's REPORT, until it has gone — and its own record says „told” only when
// the mail service accepted the mail. Every test here drives the real report endpoint; no test posts the box's event.
// RED-PROOFS: documentation/audits/build-release-4b-2026-11-15/A/redproof-notice-hub.txt.
type noticeMail struct{ to, subject, body string }
type noticeRig struct {
t *testing.T
h *Handler
st *store.Store
d *notify.Dispatcher
mu sync.Mutex
mails []noticeMail
fail error // when set, every send fails with it
}
// newNoticeRig: a household c1 with a notification address (email "" = none), a dispatcher whose sends are recorded,
// and the sends run in line with the report.
func newNoticeRig(t *testing.T, email string) *noticeRig {
t.Helper()
h, st, _ := newTestHandler(t)
if err := st.SaveCustomerConfig(&store.CustomerConfig{CustomerID: "c1", APIKey: "ckey", RetrievalPassword: "pp"}); err != nil {
t.Fatal(err)
}
if email != "" {
if err := st.SaveNotificationPrefs("c1", email, []string{}, 6); err != nil { // every switch off
t.Fatal(err)
}
}
r := &noticeRig{t: t, h: h, st: st}
r.d = notify.NewDispatcher(st, "test-key-not-used", "from@felhom.eu", "operator@felhom.eu", true, log.New(io.Discard, "", 0))
r.d.SetSendFnForTest(func(to, subject, body string, _ map[string]string) error {
r.mu.Lock()
defer r.mu.Unlock()
if r.fail != nil {
return r.fail
}
r.mails = append(r.mails, noticeMail{to, subject, body})
return nil
})
h.SetDispatcher(r.d)
old := endNoticeSpawn
endNoticeSpawn = func(f func()) { f() }
t.Cleanup(func() { endNoticeSpawn = old })
// vikunja and kimai were seen installed: the never-seen warning (offsite_end_claim_unseen) is not this file's subject
r.report(`{"customer_id":"c1","stacks":{"deployed":["immich","vikunja","kimai"]},"offsite":{"enabled":true}}`)
return r
}
// all is a copy of every mail so far (the never-seen warning of another feature is sent off the request).
func (r *noticeRig) all() []noticeMail {
r.mu.Lock()
defer r.mu.Unlock()
return append([]noticeMail(nil), r.mails...)
}
// opNotice: the operator's mails of one event type.
func (r *noticeRig) opNotice(typ string) []noticeMail {
var out []noticeMail
for _, m := range r.to(operator) {
if strings.Contains(m.subject, typ) {
out = append(out, m)
}
}
return out
}
func (r *noticeRig) report(body string) {
r.t.Helper()
req := httptest.NewRequest(http.MethodPost, "/api/v1/report", strings.NewReader(body))
req.Header.Set("Authorization", "Bearer ckey")
rr := httptest.NewRecorder()
r.h.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
r.t.Fatalf("report → %d (%s)", rr.Code, rr.Body.String())
}
}
// to counts the mails that went to one address.
func (r *noticeRig) to(addr string) []noticeMail {
r.mu.Lock()
defer r.mu.Unlock()
var out []noticeMail
for _, m := range r.mails {
if m.to == addr {
out = append(out, m)
}
}
return out
}
func (r *noticeRig) notice(app string) (store.EndNotice, bool) {
r.t.Helper()
ns, err := r.st.EndNotices("c1")
if err != nil {
r.t.Fatal(err)
}
n, ok := ns[app]
return n, ok
}
func (r *noticeRig) events(typ string) []store.Event {
r.t.Helper()
evs, err := r.st.GetEventsByType("c1", typ, time.Now().Add(-time.Hour))
if err != nil {
r.t.Fatal(err)
}
return evs
}
const (
household = "customer@example.com"
operator = "operator@felhom.eu"
// installed: immich runs; nothing is pending
repInstalled = `{"customer_id":"c1","stacks":{"deployed":["immich","vikunja"]},"offsite":{"enabled":true}}`
// the household removed vikunja with „delete backup data”
repPressed = `{"customer_id":"c1","stacks":{"deployed":["immich"]},"offsite":{"enabled":true,"ended_apps":[{"app":"vikunja","removed_at":"2026-11-15T10:00:00Z","ends_at":"1999-01-31T10:00:00Z"}]}}`
// the tier is on and no record is pending: a take-back (or the window has run)
repKept = `{"customer_id":"c1","stacks":{"deployed":["immich"]},"offsite":{"enabled":true}}`
)
func pressed(app, removedAt string) string {
return fmt.Sprintf(`{"customer_id":"c1","stacks":{"deployed":["immich"]},"offsite":{"enabled":true,"ended_apps":[{"app":%q,"removed_at":%q,"ends_at":"2026-12-15T10:00:00Z"}]}}`, app, removedAt)
}
// 1. THE HUB SENDS THE NOTICE ITSELF — the box's event never arrives in this test. One press is one notice, however
// many reports name it; the record says „told” at the hub's time; the mail's day is the HUB's (its clock + 30 days),
// not the box's `ends_at` (a day in 1999 here).
func TestNotice_AReportNamesAnApp_TheHubMailsTheHouseholdOncePerPress(t *testing.T) {
r := newNoticeRig(t, household)
r.report(repInstalled)
if len(r.all()) != 0 {
t.Fatalf("an installed app caused %d mail(s)", len(r.all()))
}
before := time.Now().Add(-time.Second)
r.report(repPressed)
got := r.to(household)
if len(got) != 1 {
t.Fatalf("the household got %d notice(s) after the first report that names the app, want 1: %+v", len(got), r.all())
}
hubDay := time.Now().Add(offsitekeys.EndedAppAfter)
if !strings.Contains(got[0].subject, "vikunja: ") || strings.Contains(got[0].subject+got[0].body, "1999") {
t.Fatalf("the notice must name the app and the HUB's day, never the box's ends_at:\n%s\n%s", got[0].subject, got[0].body)
}
if y := fmt.Sprintf("Törlésük napja: %d.", hubDay.Year()); !strings.Contains(got[0].body, y) {
t.Fatalf("the mail's day is not the hub's clock + 30 days (%s): %s", y, got[0].body)
}
n, ok := r.notice("vikunja")
if !ok || n.ToldTo != store.EndNoticeHousehold || n.ToldAt.Before(before) || n.ToldAt.After(time.Now().Add(time.Second)) {
t.Fatalf("the hub's own record does not say the household was told now: %+v (found=%v)", n, ok)
}
if len(r.to(operator)) != 0 {
t.Fatalf("the operator was mailed for a household that has an address: %+v", r.to(operator))
}
for i := 0; i < 6; i++ {
r.report(repPressed)
}
if got := r.to(household); len(got) != 1 {
t.Fatalf("one press, seven reports: %d notices, want 1", len(got))
}
if n2, _ := r.notice("vikunja"); !n2.ToldAt.Equal(n.ToldAt) {
t.Fatalf("a later report moved the told time: %s → %s", n.ToldAt, n2.ToldAt)
}
}
// 2. Two apps pressed in one minute: two notices, two records.
func TestNotice_TwoAppsInOneMinute_TwoNotices(t *testing.T) {
r := newNoticeRig(t, household)
r.report(`{"customer_id":"c1","stacks":{"deployed":["immich"]},"offsite":{"enabled":true,"ended_apps":[
{"app":"vikunja","removed_at":"2026-11-15T10:00:00Z"},{"app":"kimai","removed_at":"2026-11-15T10:00:30Z"}]}}`)
got := r.to(household)
if len(got) != 2 || !strings.Contains(got[0].subject+got[1].subject, "kimai") || !strings.Contains(got[0].subject+got[1].subject, "vikunja") {
t.Fatalf("two apps: %+v", got)
}
for _, app := range []string{"vikunja", "kimai"} {
if n, ok := r.notice(app); !ok || !n.Told() {
t.Fatalf("%s is not recorded as told: %+v", app, n)
}
}
}
// 3. A TAKE-BACK OR AN INSTALL VOIDS THE NOTICE. Press, take-back and press again within one day: the second press
// gets its own notice and its own told time — the first one's is gone. The same after an install.
func TestNotice_ATakeBackOrAnInstallVoidsTheNotice(t *testing.T) {
r := newNoticeRig(t, household)
r.report(pressed("vikunja", "2026-11-15T10:00:00Z"))
// the first notice is 40 days old in the hub's record: it would be old enough
old := time.Now().UTC().Add(-40 * 24 * time.Hour)
if err := r.st.SetEndNoticeForTest("c1", "vikunja", "2026-11-15T10:00:00Z", old, old, store.EndNoticeHousehold); err != nil {
t.Fatal(err)
}
r.report(repKept) // „keep it after all”
if n, ok := r.notice("vikunja"); ok {
t.Fatalf("after the take-back the hub still holds a notice: %+v", n)
}
r.report(pressed("vikunja", "2026-11-15T16:00:00Z")) // pressed again, the same day
if got := r.to(household); len(got) != 2 {
t.Fatalf("press, take-back, press: %d notices, want 2 (a new press needs a new notice)", len(got))
}
n, _ := r.notice("vikunja")
if !n.Told() || time.Since(n.ToldAt) > time.Minute {
t.Fatalf("the second press must have its OWN told time (now), not the first one's (40 days ago): %+v", n)
}
// an install: the app is in the app list again
if err := r.st.SetEndNoticeForTest("c1", "vikunja", "2026-11-15T16:00:00Z", old, old, store.EndNoticeHousehold); err != nil {
t.Fatal(err)
}
r.report(repInstalled)
if n, ok := r.notice("vikunja"); ok {
t.Fatalf("after an install the hub still holds a notice: %+v", n)
}
// another press that the hub never saw taken back (the tier was off in between): the press's key differs
r.report(pressed("vikunja", "2026-11-16T09:00:00Z"))
if err := r.st.SetEndNoticeForTest("c1", "vikunja", "2026-11-16T09:00:00Z", old, old, store.EndNoticeHousehold); err != nil {
t.Fatal(err)
}
r.report(`{"customer_id":"c1","stacks":{"deployed":["immich"]}}`) // the tier is off: silence is NOT a take-back
if n, ok := r.notice("vikunja"); !ok || !n.Told() {
t.Fatalf("a report that does not show the tier voided the notice: %+v", n)
}
sent := len(r.to(household))
r.report(pressed("vikunja", "2026-11-20T09:00:00Z"))
n, _ = r.notice("vikunja")
if len(r.to(household)) != sent+1 || time.Since(n.ToldAt) > time.Minute {
t.Fatalf("another press (another removed_at) must be told again and wait again: mails %d→%d, %+v", sent, len(r.to(household)), n)
}
}
// 5a. A NOTICE THAT CANNOT GO OUT tells nobody: the record stays „not told” with the reason, the next try waits an
// hour, and the first try that the mail service accepts sets the told time — then, not earlier.
func TestNotice_AFailedSendIsTriedAgainUntilItHasGone(t *testing.T) {
r := newNoticeRig(t, household)
r.fail = errors.New("resend: 503")
r.report(repPressed)
n, ok := r.notice("vikunja")
if !ok || n.Told() || !strings.Contains(n.LastReason, "did not accept") || n.Tries != 1 {
t.Fatalf("after a failed send: %+v (found=%v) — want not told, with the reason", n, ok)
}
r.fail = nil
now := time.Now()
r.h.endNotices("c1", now.Add(10*time.Minute))
if len(r.all()) != 0 {
t.Fatalf("a second try ten minutes after a failed one: %d mail(s)", len(r.all()))
}
at := now.Add(61 * time.Minute)
r.h.endNotices("c1", at)
n, _ = r.notice("vikunja")
if len(r.to(household)) != 1 || !n.Told() || n.ToldAt.Unix() != at.Unix() {
t.Fatalf("the try an hour later must send and set the told time to THAT try (%s): mails=%d %+v", at.UTC().Format(time.RFC3339), len(r.all()), n)
}
}
// 5b. The mail hold: nobody is told, the reason names the hold, and after the release the notice goes.
func TestNotice_TheMailHoldTellsNobody(t *testing.T) {
r := newNoticeRig(t, household)
dir := t.TempDir()
marker := filepath.Join(dir, mailhold.FileName)
if err := os.WriteFile(marker, nil, 0o644); err != nil {
t.Fatal(err)
}
r.d.SetMailHold(mailhold.New(dir, nil))
r.report(repPressed)
n, _ := r.notice("vikunja")
if n.Told() || !strings.Contains(n.LastReason, "MAIL-HOLD") || len(r.all()) != 0 {
t.Fatalf("under the hold: %+v, %d mail(s)", n, len(r.all()))
}
if err := os.Remove(marker); err != nil {
t.Fatal(err)
}
r.h.endNotices("c1", time.Now().Add(2*time.Hour))
if n, _ := r.notice("vikunja"); !n.Told() || len(r.to(household)) != 1 {
t.Fatalf("after the release: %+v, %d mail(s)", n, len(r.all()))
}
}
// 1b. THE DAILY LIMIT DELAYS A NOTICE; IT NEVER DROPS ONE. Seven apps in one report: five are told today, two stay
// „not told” with the reason — and are told a day later.
func TestNotice_TheDailyLimitDelaysAndNeverDrops(t *testing.T) {
r := newNoticeRig(t, household)
var recs []string
for i := 0; i < 7; i++ {
recs = append(recs, fmt.Sprintf(`{"app":"app-%d","removed_at":"2026-11-15T10:00:00Z"}`, i))
}
r.report(`{"customer_id":"c1","stacks":{"deployed":["immich"]},"offsite":{"enabled":true,"ended_apps":[` + strings.Join(recs, ",") + `]}}`)
if got := r.to(household); len(got) != 5 {
t.Fatalf("seven presses: %d notices today, want the daily limit 5", len(got))
}
untold := 0
for i := 0; i < 7; i++ {
if n, ok := r.notice(fmt.Sprintf("app-%d", i)); !ok {
t.Fatalf("app-%d has no record — a notice was DROPPED", i)
} else if !n.Told() {
untold++
if !strings.Contains(n.LastReason, "daily limit") {
t.Fatalf("app-%d: not told, and the reason is %q", i, n.LastReason)
}
}
}
if untold != 2 {
t.Fatalf("%d of 7 are not told, want 2", untold)
}
if err := r.st.BackdateNotificationLogForTest("c1", 25*time.Hour); err != nil {
t.Fatal(err)
}
r.h.endNotices("c1", time.Now().Add(25*time.Hour))
if got := r.to(household); len(got) != 7 {
t.Fatalf("a day later: %d notices in all, want 7 — the limit must only delay", len(got))
}
for i := 0; i < 7; i++ {
if n, _ := r.notice(fmt.Sprintf("app-%d", i)); !n.Told() {
t.Fatalf("app-%d is still not told", i)
}
}
}
// 3 (A.3). A HOUSEHOLD WITH NO ADDRESS: the operator is told once per app, operator-only, and THAT mail starts the
// 30 days. The address is added after the press: the household gets its own notice and the 30 days start again.
func TestNotice_NoAddress_TheOperatorIsToldInItsPlace_AndAnAddressLaterRestarts(t *testing.T) {
r := newNoticeRig(t, "")
r.report(repPressed)
op := r.opNotice(offsitekeys.EventEndNoticeOperator)
if len(op) != 1 || !strings.Contains(op[0].body, `"vikunja"`) || !strings.Contains(op[0].body, "c1") || !strings.Contains(op[0].body, "no notification address") {
t.Fatalf("the operator must be told once, naming the household, the app and why: %+v", r.all())
}
n, _ := r.notice("vikunja")
if n.ToldTo != store.EndNoticeOperator || !n.Told() {
t.Fatalf("the record must say the OPERATOR was told: %+v", n)
}
if e := r.events(offsitekeys.EventEndNoticeOperator); len(e) != 1 || e[0].Severity != "warning" || !strings.Contains(e[0].DetailsJSON, `"subject":"vikunja"`) {
t.Fatalf("the operator's event row: %+v", e)
}
for i := 0; i < 5; i++ {
r.report(repPressed)
}
if got := r.opNotice(offsitekeys.EventEndNoticeOperator); len(got) != 1 {
t.Fatalf("told once per app: %d mails after six reports", len(got))
}
// the operator's notice is 40 days old; the household gets an address now
old := time.Now().UTC().Add(-40 * 24 * time.Hour)
if err := r.st.SetEndNoticeForTest("c1", "vikunja", "2026-11-15T10:00:00Z", old, old, store.EndNoticeOperator); err != nil {
t.Fatal(err)
}
if err := r.st.SaveNotificationPrefs("c1", household, []string{}, 6); err != nil {
t.Fatal(err)
}
r.report(repPressed)
n, _ = r.notice("vikunja")
if len(r.to(household)) != 1 || n.ToldTo != store.EndNoticeHousehold || time.Since(n.ToldAt) > time.Minute {
t.Fatalf("an address added after the press: the household must be told and the 30 days start again: mails=%+v record=%+v", r.mails, n)
}
// a blocked household is the same case
r2 := newNoticeRig(t, household)
if err := r2.st.SetCustomerConfigStatus("c1", "blocked"); err != nil {
t.Fatal(err)
}
r2.report(repPressed)
if n, _ := r2.notice("vikunja"); n.ToldTo != store.EndNoticeOperator || len(r2.to(household)) != 0 || len(r2.opNotice(offsitekeys.EventEndNoticeOperator)) != 1 {
t.Fatalf("a blocked household: record %+v, mails %+v", n, r2.all())
}
}
// 3b. The operator cannot be told either: NOBODY was told, so nothing starts.
func TestNotice_NoAddress_AndTheOperatorsMailFails_NobodyWasTold(t *testing.T) {
r := newNoticeRig(t, "")
r.fail = errors.New("resend: 503")
r.report(repPressed)
n, ok := r.notice("vikunja")
if !ok || n.Told() || !strings.Contains(n.LastReason, "operator could not be told") {
t.Fatalf("no address and the operator's mail failed: %+v", n)
}
if e := r.events(offsitekeys.EventEndNoticeOperator); len(e) != 0 {
t.Fatalf("an event row says the operator was told, and no mail went: %+v", e)
}
}
// 5c. A notice that has told nobody for three days: the operator gets ONE line. Not at two days; not twice; not
// while the hold is on.
func TestNotice_StuckForThreeDays_TheOperatorGetsOneLine(t *testing.T) {
r := newNoticeRig(t, household)
r.fail = errors.New("resend: 503")
r.report(repPressed)
now := time.Now()
stuck := func() []store.Event { return r.events(offsitekeys.EventEndNoticeStuck) }
r.h.endNotices("c1", now.Add(2*24*time.Hour))
if e := stuck(); len(e) != 0 {
t.Fatalf("told the operator after two days: %+v", e)
}
dir := t.TempDir()
marker := filepath.Join(dir, mailhold.FileName)
if err := os.WriteFile(marker, nil, 0o644); err != nil {
t.Fatal(err)
}
r.d.SetMailHold(mailhold.New(dir, nil))
r.h.endNotices("c1", now.Add(EndNoticeStuckAfter+time.Hour))
if e := stuck(); len(e) != 0 {
t.Fatalf("the line was filed while the hold is on: %+v", e)
}
_ = os.Remove(marker)
r.h.endNotices("c1", now.Add(EndNoticeStuckAfter+3*time.Hour))
e := stuck()
if len(e) != 1 || e[0].Severity != "warning" || !strings.Contains(e[0].Message, `"vikunja"`) || !strings.Contains(e[0].Message, "did not accept") || !strings.Contains(e[0].DetailsJSON, `"subject":"vikunja"`) {
t.Fatalf("want ONE warning naming the app and the reason: %+v", e)
}
for i := 5; i < 10; i++ {
r.h.endNotices("c1", now.Add(EndNoticeStuckAfter+time.Duration(i)*time.Hour))
}
if e := stuck(); len(e) != 1 {
t.Fatalf("the line was repeated: %d", len(e))
}
if n, _ := r.notice("vikunja"); n.Told() {
t.Fatalf("the operator's line must not count as the notice: %+v", n)
}
}
// 7. THE DATABASE IS PUT BACK FROM A COPY THAT LACKS THE NOTICE: the hub has no record, so it tells again and the
// told time is new — it waits again.
func TestNotice_ADatabaseWithoutTheNoticeTellsAgain(t *testing.T) {
r := newNoticeRig(t, household)
r.report(repPressed)
if len(r.to(household)) != 1 {
t.Fatal("fixture: no first notice")
}
restored := newNoticeRig(t, household) // the copy: the household and its address, no notice row
if _, ok := restored.notice("vikunja"); ok {
t.Fatal("fixture: the copy holds a notice")
}
restored.report(repPressed)
n, ok := restored.notice("vikunja")
if !ok || !n.Told() || time.Since(n.ToldAt) > time.Minute || len(restored.to(household)) != 1 {
t.Fatalf("on the copy the household must be told again, with a told time of now: %+v mails=%d", n, len(restored.all()))
}
}
// 7. A household deleted between the notice and the window: its notice rows go with it, and nothing is mailed after.
func TestNotice_ADeletedHouseholdHasNoNotice(t *testing.T) {
r := newNoticeRig(t, household)
r.fail = errors.New("resend: 503")
r.report(repPressed)
if err := r.st.PurgeCustomerResidue("c1"); err != nil {
t.Fatal(err)
}
if ns, _ := r.st.EndNotices("c1"); len(ns) != 0 {
t.Fatalf("the notice outlived the household: %+v", ns)
}
r.fail = nil
r.h.endNotices("c1", time.Now().Add(2*time.Hour))
if len(r.all()) != 0 {
t.Fatalf("a deleted household was mailed: %+v", r.all())
}
}
// A box's names are the box's word: a name that is not an app name, a reserved name and an installed app get no
// notice; and no box can POST the hub's own two warnings.
func TestNotice_OnlyRealRemovedAppsAreTold(t *testing.T) {
r := newNoticeRig(t, household)
r.report(`{"customer_id":"c1","stacks":{"deployed":["immich"]},"offsite":{"enabled":true,"ended_apps":[
{"app":"<b>x</b>"},{"app":"_shares"},{"app":"traefik"},{"app":"immich"},{"app":"pay now at evil.example"}]}}`)
if len(r.all()) != 0 {
t.Fatalf("mails: %+v", r.all())
}
if ns, _ := r.st.EndNotices("c1"); len(ns) != 0 {
t.Fatalf("rows: %+v", ns)
}
for _, typ := range []string{offsitekeys.EventEndNoticeOperator, offsitekeys.EventEndNoticeStuck} {
if allowedEventTypes[typ] {
t.Fatalf("a box must not be able to POST %s", typ)
}
}
}
// THE SEAM IS WIRED: with the real spawn (off the request) a report still causes the notice.
func TestNotice_TheReportStartsTheWalkOffTheRequest(t *testing.T) {
r := newNoticeRig(t, household)
endNoticeSpawn = func(f func()) { go f() } // newNoticeRig's cleanup restores the original
r.report(repPressed)
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) {
if len(r.to(household)) == 1 {
if n, _ := r.notice("vikunja"); n.Told() {
return
}
}
time.Sleep(10 * time.Millisecond)
}
t.Fatalf("no notice within 3 s of the report: %+v", r.all())
}