Files
felhom.eu/hub/internal/store/offsite_end_notice.go
T
admin c9d67309e2 hub (unreleased): the operator's in-place notice is bounded — 5 per household a day, the same app once in 7 days (the security review of the notice lock)
A box of a household with no address could mail the operator at every new press.
A notice that waits is not told: it starts no 30 days and nothing is agreed for it.
The stuck line is bounded the same way.

Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
2026-11-15 16:28:49 +01:00

320 lines
13 KiB
Go

package store
import (
"database/sql"
"fmt"
"sort"
"sync"
"time"
)
// THE NOTICE LOCK (`09` §3 decision 315; `07-backup-architecture.md` §8.2f „No notice, no deletion”) — THE HUB'S OWN
// RECORD that a household was told its app's off-site copies will be deleted.
//
// One row per (household, app) that a box's REPORT names in a pending off-site end record. The hub mails the notice
// itself (api.endNotices → notify.SendEndNotice) and writes `told_at` — by ITS clock — only when the mail service
// accepted the mail. offsitekeys.agreeEnded agrees to an app only when this table says it was told EndedAppAfter ago.
//
// Why a table and not the sent log (`notification_log`): the 30 days are a condition of a deletion, so they must not
// rest on a log that is pruned (deleted households today; anything tomorrow), nor on anything a box says. Nothing
// here is written from a box's date: `press` is the box's `removed_at`, kept ONLY to tell one press from the next —
// a different value VOIDS the notice (the safe direction), and no value can make one.
//
// A row is deleted — and with it the notice, so a new press needs a new notice and a new 30 days — when:
// - a report lists the app as installed (an install);
// - a report that shows the off-site tier ON no longer names the app (a take-back, or the window has run);
// - the household goes (residueQueries, orphanTables).
//
// A row is RESET (told_at cleared, first_named = now) when a report names the app with another `press`.
// A report that does not show the tier (it is off, or waits for a key) changes nothing: its silence is not a
// take-back. A database put back from a copy that lacks a row has no notice: the hub tells again and waits again.
// maxEndNoticeRows bounds one household's rows (a box's list is the box's word). A claim above it is not stored, so
// it is never told and never agreed.
const maxEndNoticeRows = 50
// EndNoticeHousehold / EndNoticeOperator: who the notice that counts went to.
const (
EndNoticeHousehold = "household"
EndNoticeOperator = "operator"
)
func (s *Store) migrateOffsiteEndNotices() error {
if _, err := s.db.Exec(`
CREATE TABLE IF NOT EXISTS offsite_end_notices (
customer_id TEXT NOT NULL,
app TEXT NOT NULL,
press TEXT NOT NULL DEFAULT '',
first_named TEXT NOT NULL,
told_at TEXT,
told_to TEXT NOT NULL DEFAULT '',
tries INTEGER NOT NULL DEFAULT 0,
last_try TEXT,
last_reason TEXT NOT NULL DEFAULT '',
stuck_told TEXT,
PRIMARY KEY (customer_id, app)
);`); err != nil {
return fmt.Errorf("offsite_end_notices: %w", err)
}
return nil
}
// EndClaim is one pending end record of a report, as far as the notice needs it.
type EndClaim struct {
App string
// Press is the box's `removed_at`. NormalizeEndPress decides what is stored of it.
Press string
}
// EndNotice is the hub's record for one app of one household.
type EndNotice struct {
App string
Press string
// FirstNamed: the hub's time of the first report that named this press.
FirstNamed time.Time
// ToldAt: the hub's time at which the notice that counts was accepted by the mail service. Zero = not told.
ToldAt time.Time
// ToldTo: EndNoticeHousehold, or EndNoticeOperator for a household that had no usable address.
ToldTo string
Tries int
LastTry time.Time
LastReason string // the hub's own words for why the last try did not tell anybody
// StuckTold: the hub's time of the operator's one line about a notice that could not go out for days.
StuckTold time.Time
}
// Told: the hub's record says somebody was told.
func (n EndNotice) Told() bool { return !n.ToldAt.IsZero() && n.ToldTo != "" }
// NormalizeEndPress turns a box's `removed_at` into the key of a press: the same instant in UTC when it is a time,
// else the empty key. It is never read as a date.
func NormalizeEndPress(removedAt string) string {
if len(removedAt) > 40 {
return ""
}
t, err := time.Parse(time.RFC3339, removedAt)
if err != nil {
return ""
}
return t.UTC().Format(time.RFC3339)
}
// NoteEndNotices updates the record from ONE report (see the header). deployed is the report's app list; claims are
// its pending end records; tierOn says the report shows the off-site tier switched on (only then is a missing claim
// a take-back). now is the HUB's clock.
func (s *Store) NoteEndNotices(customerID string, deployed []string, claims []EndClaim, tierOn bool, now time.Time) error {
if customerID == "" {
return fmt.Errorf("NoteEndNotices: empty customer_id")
}
if len(deployed) > maxPresenceApps {
deployed = deployed[:maxPresenceApps]
}
if len(claims) > maxPresenceApps {
claims = claims[:maxPresenceApps]
}
cur, err := s.EndNotices(customerID)
if err != nil {
return err
}
if len(cur) == 0 && len(claims) == 0 {
return nil // the steady box: one read
}
in := make(map[string]bool, len(deployed))
for _, app := range deployed {
in[app] = true
}
claimed := map[string]string{} // app → press (the first claim of a name wins)
var order []string
for _, c := range claims {
if !ValidPresenceApp(c.App) || ReservedPresenceApp(c.App) || in[c.App] {
continue
}
if _, dup := claimed[c.App]; dup {
continue
}
claimed[c.App] = NormalizeEndPress(c.Press)
order = append(order, c.App)
}
var drop, fresh []string
for app, n := range cur {
press, named := claimed[app]
switch {
case in[app]: // an install voids the notice
drop = append(drop, app)
case named && press != n.Press: // another press: a new notice, a new 30 days
drop = append(drop, app)
fresh = append(fresh, app)
case !named && tierOn: // a take-back, or the window has run
drop = append(drop, app)
}
}
rows := len(cur) - len(drop)
notStored := 0
for _, app := range order {
if _, ok := cur[app]; ok {
continue
}
fresh = append(fresh, app)
}
sort.Strings(fresh)
if over := rows + len(fresh) - maxEndNoticeRows; over > 0 {
notStored = over
fresh = fresh[:len(fresh)-over]
}
s.noteEndNoticesFull(customerID, notStored)
if len(drop) == 0 && len(fresh) == 0 {
return nil
}
stamp := now.UTC().Format(time.RFC3339)
tx, err := s.db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
for _, app := range drop {
if _, err := tx.Exec(`DELETE FROM offsite_end_notices WHERE customer_id = ? AND app = ?`, customerID, app); err != nil {
return fmt.Errorf("NoteEndNotices %s/%s: %w", customerID, app, err)
}
}
for _, app := range fresh {
if _, err := tx.Exec(`INSERT INTO offsite_end_notices (customer_id, app, press, first_named) VALUES (?, ?, ?, ?)`,
customerID, app, claimed[app], stamp); err != nil {
return fmt.Errorf("NoteEndNotices %s/%s: %w", customerID, app, err)
}
}
return tx.Commit()
}
// endNoticesFull: the row limit is said in the log once per household, not once per report (in memory).
var (
endNoticesFullMu sync.Mutex
endNoticesFull = map[string]bool{}
)
func (s *Store) noteEndNoticesFull(customerID string, notStored int) {
endNoticesFullMu.Lock()
defer endNoticesFullMu.Unlock()
if notStored == 0 {
delete(endNoticesFull, customerID)
return
}
if endNoticesFull[customerID] {
return
}
endNoticesFull[customerID] = true
if s.logger != nil {
s.logger.Printf("[WARN] off-site end notices for %s are at their limit of %d apps: %d pending end record(s) of this report were NOT stored — nobody is told about them and the hub agrees to none of them. A household does not remove that many apps at once — look at what the box reports. (Said once; not repeated per report.)",
customerID, maxEndNoticeRows, notStored)
}
}
// EndNotices returns the hub's record for one household, by app. A date that cannot be read is the zero time — and
// a zero ToldAt is „not told”.
func (s *Store) EndNotices(customerID string) (map[string]EndNotice, error) {
rows, err := s.db.Query(`SELECT app, press, first_named, told_at, told_to, tries, last_try, last_reason, stuck_told
FROM offsite_end_notices WHERE customer_id = ?`, customerID)
if err != nil {
return nil, err
}
defer rows.Close()
out := map[string]EndNotice{}
for rows.Next() {
var n EndNotice
var first string
var told, lastTry, stuck sql.NullString
if err := rows.Scan(&n.App, &n.Press, &first, &told, &n.ToldTo, &n.Tries, &lastTry, &n.LastReason, &stuck); err != nil {
return nil, err
}
n.FirstNamed = parseNoticeTime(first)
n.ToldAt = parseNoticeTime(told.String)
n.LastTry = parseNoticeTime(lastTry.String)
n.StuckTold = parseNoticeTime(stuck.String)
if n.ToldTo != EndNoticeHousehold && n.ToldTo != EndNoticeOperator {
n.ToldTo, n.ToldAt = "", time.Time{} // a value the hub never writes is „not told”
}
out[n.App] = n
}
return out, rows.Err()
}
func parseNoticeTime(v string) time.Time {
if v == "" {
return time.Time{}
}
t, err := time.Parse(time.RFC3339, v)
if err != nil {
return time.Time{}
}
return t
}
// MarkEndNoticeTold writes that the notice of THIS press was accepted by the mail service, at the hub's time `now`,
// to `to` (EndNoticeHousehold or EndNoticeOperator). It matches the press: a row that was voided or reset while the
// mail was being sent is not marked (ok=false) — that press was never told.
func (s *Store) MarkEndNoticeTold(customerID, app, press, to string, now time.Time) (ok bool, err error) {
if to != EndNoticeHousehold && to != EndNoticeOperator {
return false, fmt.Errorf("MarkEndNoticeTold: unknown recipient %q", to)
}
stamp := now.UTC().Format(time.RFC3339)
res, err := s.db.Exec(`UPDATE offsite_end_notices SET told_at = ?, told_to = ?, tries = tries + 1, last_try = ?, last_reason = ''
WHERE customer_id = ? AND app = ? AND press = ?`, stamp, to, stamp, customerID, app, press)
if err != nil {
return false, err
}
n, _ := res.RowsAffected()
return n == 1, nil
}
// MarkEndNoticeTried writes a try that told nobody, with the hub's own words for why. It never touches told_at.
func (s *Store) MarkEndNoticeTried(customerID, app, press, reason string, now time.Time) error {
_, err := s.db.Exec(`UPDATE offsite_end_notices SET tries = tries + 1, last_try = ?, last_reason = ?
WHERE customer_id = ? AND app = ? AND press = ?`, now.UTC().Format(time.RFC3339), reason, customerID, app, press)
return err
}
// MarkEndNoticeStuckTold writes that the operator's one line about a notice that cannot go out was filed.
func (s *Store) MarkEndNoticeStuckTold(customerID, app, press string, now time.Time) error {
_, err := s.db.Exec(`UPDATE offsite_end_notices SET stuck_told = ? WHERE customer_id = ? AND app = ? AND press = ?`,
now.UTC().Format(time.RFC3339), customerID, app, press)
return err
}
// SetEndNoticeForTest writes a row as if the hub had named the app at firstNamed and (toldAt non-zero) told `to`
// at toldAt. TEST-ONLY.
func (s *Store) SetEndNoticeForTest(customerID, app, press string, firstNamed, toldAt time.Time, to string) error {
var told sql.NullString
if !toldAt.IsZero() {
told = sql.NullString{String: toldAt.UTC().Format(time.RFC3339), Valid: true}
}
_, err := s.db.Exec(`INSERT INTO offsite_end_notices (customer_id, app, press, first_named, told_at, told_to) VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(customer_id, app) DO UPDATE SET press = excluded.press, first_named = excluded.first_named, told_at = excluded.told_at, told_to = excluded.told_to`,
customerID, app, press, firstNamed.UTC().Format(time.RFC3339), told, to)
return err
}
// BackdateNotificationLogForTest moves a household's sent-log rows into the past. TEST-ONLY.
func (s *Store) BackdateNotificationLogForTest(customerID string, by time.Duration) error {
_, err := s.db.Exec(`UPDATE notification_log SET created_at = datetime(created_at, ?) WHERE customer_id = ?`,
fmt.Sprintf("-%d seconds", int(by.Seconds())), customerID)
return err
}
// CountOperatorSentSince counts the operator mails of one type that the hub's own log says were SENT about a
// household since `since` (the daily limit of the operator's in-place notice).
func (s *Store) CountOperatorSentSince(customerID, eventType string, since time.Time) (int, error) {
var n int
err := s.db.QueryRow(`SELECT COUNT(*) FROM notification_log WHERE customer_id = ? AND event_type = ? AND channel = 'operator' AND status = 'sent' AND created_at >= ?`,
customerID, eventType, since.UTC().Format("2006-01-02 15:04:05")).Scan(&n)
return n, err
}
// OperatorSentAboutSince reports whether the hub's own log holds a SENT operator mail of one type about a household
// whose text contains `marker`, since `since`. marker is the hub's own words around a checked app name; it is
// matched as plain text (instr), never as a pattern.
func (s *Store) OperatorSentAboutSince(customerID, eventType, marker string, since time.Time) (bool, error) {
var n int
err := s.db.QueryRow(`SELECT COUNT(*) FROM notification_log WHERE customer_id = ? AND event_type = ? AND channel = 'operator' AND status = 'sent' AND created_at >= ? AND instr(message, ?) > 0`,
customerID, eventType, since.UTC().Format("2006-01-02 15:04:05"), marker).Scan(&n)
return n > 0, err
}