Files
felhom.eu/hub/internal/api/end_notice.go
T
admin 42ef25c23b 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
2026-11-15 16:17:44 +01:00

197 lines
10 KiB
Go

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")
}
}