Files
felhom.eu/hub/internal/store/offsite_end_notice.go
T

443 lines
19 KiB
Go

package store
import (
"crypto/sha256"
"database/sql"
"encoding/hex"
"fmt"
"sort"
"strings"
"sync"
"testing"
"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)
}
// told_addr: a key of the household's notification address the notice was accepted for (NoticeAddressKey) —
// never the address itself. „Told to the household” counts only while it is the address the household has NOW.
s.db.Exec("ALTER TABLE offsite_end_notices ADD COLUMN told_addr TEXT NOT NULL DEFAULT ''")
return nil
}
// „TOLD” IS TOLD AT AN ADDRESS (review of 2026-11-15, finding 1). Somebody who holds the household's login could
// set the notification address to his own, press „delete backup data”, get the notice and put the real address
// back: the row said told, the real address had got nothing, and 30 days later the hub agreed. So a row that is
// told to the household carries a key of the address the mail was accepted for, and it counts as told only while
// that is the household's CURRENT address. Two mechanisms, on purpose:
//
// 1. THE READER (EndNotices) compares the row's key with the address on record at every read: a row told at another
// address reads as NOT told. This is the rule; it holds whoever changed the address and however.
// 2. THE WRITER of the address (SaveNotificationPrefsAs) un-tells the household's rows in the same transaction when
// the address changes, is removed or is added — so the row is clean, its „first named” starts again (the
// operator's 3-day line counts from the change) and the log says what happened.
//
// The same address in other capitals or with spaces around it is the same address. An operator-told row is not
// touched: the operator was told, and a household that gets an address is mailed by the walk anyway.
// reasonAddressChanged is the hub's own reason on a row whose household must be told again.
const reasonAddressChanged = "the household's notification address changed after it was told — it is told again at the address it has now, and the 30 days start again"
// NoticeAddressKey is the key of a notification address for the notice record: a hash of the address in lower case
// without the spaces around it; "" for no address. The address itself is not stored a second time.
func NoticeAddressKey(email string) string {
norm := strings.ToLower(strings.TrimSpace(email))
if norm == "" {
return ""
}
sum := sha256.Sum256([]byte("felhom notice address\n" + norm))
return hex.EncodeToString(sum[:])
}
// untellHouseholdNotices clears „told to the household” on every row of a household, inside the caller's
// transaction. Returns how many rows it changed.
func untellHouseholdNotices(tx *sql.Tx, customerID string, now time.Time) (int64, error) {
res, err := tx.Exec(`UPDATE offsite_end_notices SET told_at = NULL, told_to = '', told_addr = '', tries = 0, last_try = NULL,
last_reason = ?, first_named = ?, stuck_told = NULL WHERE customer_id = ? AND told_to = ?`,
reasonAddressChanged, now.UTC().Format(time.RFC3339), customerID, EndNoticeHousehold)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// 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 !ValidNoticeApp(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) {
// The address the household has NOW (no row, or an empty one: no address).
var email sql.NullString
if err := s.db.QueryRow(`SELECT email FROM customer_notifications WHERE customer_id = ?`, customerID).Scan(&email); err != nil && err != sql.ErrNoRows {
return nil, err
}
current := NoticeAddressKey(email.String)
rows, err := s.db.Query(`SELECT app, press, first_named, told_at, told_to, tries, last_try, last_reason, stuck_told, told_addr
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, toldAddr 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, &toldAddr); err != nil {
return nil, err
}
if n.ToldTo == EndNoticeHousehold && (toldAddr == "" || toldAddr != current) {
// told at an address the household does not have now (or at none the hub can show): not told
n.ToldTo, told = "", sql.NullString{}
n.LastReason = reasonAddressChanged
}
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.
//
// addrKey is NoticeAddressKey of the address the household's mail was accepted for (the address at the SEND, which
// the sender returns) — required for EndNoticeHousehold, ignored for EndNoticeOperator. If the household's address
// has changed since the send, the row is written and reads as not told (EndNotices).
func (s *Store) MarkEndNoticeTold(customerID, app, press, to, addrKey string, now time.Time) (ok bool, err error) {
if to != EndNoticeHousehold && to != EndNoticeOperator {
return false, fmt.Errorf("MarkEndNoticeTold: unknown recipient %q", to)
}
if to == EndNoticeHousehold && addrKey == "" {
return false, fmt.Errorf("MarkEndNoticeTold: a household notice needs the key of the address it went to")
}
if to == EndNoticeOperator {
addrKey = ""
}
stamp := now.UTC().Format(time.RFC3339)
res, err := s.db.Exec(`UPDATE offsite_end_notices SET told_at = ?, told_to = ?, told_addr = ?, tries = tries + 1, last_try = ?, last_reason = ''
WHERE customer_id = ? AND app = ? AND press = ?`, stamp, to, addrKey, 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.
//
// It lives in a production file because other packages' tests need it (a _test.go file is not visible to them). It
// REFUSES TO RUN outside a test binary (errTestOnly), and no production file may call it
// (api.TestReview6_NoProductionFileCallsATestOnlyHelper).
func (s *Store) SetEndNoticeForTest(customerID, app, press string, firstNamed, toldAt time.Time, to string) error {
if !inTestBinary() {
return errTestOnly
}
var told sql.NullString
if !toldAt.IsZero() {
told = sql.NullString{String: toldAt.UTC().Format(time.RFC3339), Valid: true}
}
// A household-told row is told at the address the household has now; a fixture household with none gets one.
addr := ""
if to == EndNoticeHousehold {
var email sql.NullString
_ = s.db.QueryRow(`SELECT email FROM customer_notifications WHERE customer_id = ?`, customerID).Scan(&email)
if strings.TrimSpace(email.String) == "" {
email.String = "fixture@example.com"
if _, err := s.db.Exec(`INSERT INTO customer_notifications (customer_id, email, enabled_events, cooldown_hours) VALUES (?, ?, '[]', 6)
ON CONFLICT(customer_id) DO UPDATE SET email = excluded.email`, customerID, email.String); err != nil {
return err
}
}
addr = NoticeAddressKey(email.String)
}
_, err := s.db.Exec(`INSERT INTO offsite_end_notices (customer_id, app, press, first_named, told_at, told_to, told_addr) 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, told_addr = excluded.told_addr`,
customerID, app, press, firstNamed.UTC().Format(time.RFC3339), told, to, addr)
return err
}
// BackdateNotificationLogForTest moves a household's sent-log rows into the past. TEST-ONLY.
// Refuses to run outside a test binary, like SetEndNoticeForTest.
func (s *Store) BackdateNotificationLogForTest(customerID string, by time.Duration) error {
if !inTestBinary() {
return errTestOnly
}
_, 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
}
// CountOperatorTriesSince counts the operator mails of one type about a household that REACHED the mail service
// since `since` — `sent` and `failed`, for the reason CountCustomerTriesSince gives (the daily limit of the
// operator's in-place notice).
func (s *Store) CountOperatorTriesSince(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 IN ('sent', 'failed') 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
}
// ValidNoticeApp: the shape of a name that may reach a household's mail — a plain app slug: 1..64 of lower-case
// letters, digits, `-` and `_`, starting with a letter or a digit. NO DOT and no capital: the app record's rule
// (ValidPresenceApp) allows both, and a box could then put `www.some-bank.example.com` into the subject of a mail the
// hub sends to its household (review of 2026-11-15). Every catalog app name passes it
// (api.TestReview3_EveryCatalogAppNameIsANoticeName). A name that fails gets no notice row: nobody is told about it
// and the hub never agrees to it.
func ValidNoticeApp(app string) bool {
if app == "" || len(app) > maxPresenceName || ReservedPresenceApp(app) {
return false
}
for i, r := range app {
switch {
case r >= 'a' && r <= 'z', r >= '0' && r <= '9':
case i > 0 && (r == '_' || r == '-'):
default:
return false
}
}
return true
}
// inTestBinary says whether this process is a test binary. A variable so that a test can show what the test-only
// helpers do in the production binary.
var inTestBinary = testing.Testing
// errTestOnly: a test-only helper was called in a binary that is not a test.
var errTestOnly = fmt.Errorf("store: a test-only helper was called outside a test binary — refused")