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

164 lines
6.9 KiB
Go

package store
import (
"encoding/json"
"fmt"
"regexp"
"time"
)
// R-901 (operator ruling 2026-10-08 09:04, `09` §3 decision 181): after a customer is DELETED, the hub's audit rows for
// it — `events` and `notification_log` — are kept 1 year, then deleted.
//
// The delete cascade (web/customer_delete.go) deliberately leaves both tables („the audit trail outlives every
// lifecycle tier"), and nothing ever pruned `notification_log`; `events` are pruned for EVERY customer at
// retention.max_days (90 on the live hub), so in practice the year bites `notification_log`. Both are covered here so the
// rule holds if max_days is ever raised.
//
// WHICH customers: the ones whose delete cascade COMPLETED — a `customer_resets` journal row with leg
// `customer_delete` = `ok` and a `completed_at` stamp (a RESET has no such leg and is not a deletion). WHICH rows: only
// those created AT OR BEFORE that completion — a customer id re-used after the deletion keeps everything it made since.
// The journal row itself stays (F-14 provenance) — and since D86 it loses its id in the same step (below).
//
// Pinned by TestR901_* (deleted_customer_audit_test.go).
const DeletedCustomerAuditKeep = 365 * 24 * time.Hour
// D86 (operator ruling 2026-11-15, `09` §3 decision 314; `05-hub-architecture.md` §14.3, option A): an id of a household
// or a box is typed by a person and can be a name, so the delete journal must not keep it for ever. Every reader of the
// journal needs the id only while the household exists or during the year after its deletion; so, in the SAME
// transaction that removes a deleted household's audit rows at the year's end, the journal rows of that deleted life
// lose their ids: `customer_resets.customer_id`, `host_deletions.customer_id` and `host_deletions.host_id` become the
// empty string. The rows stay, with their times and their step states — „a deletion happened, at this time”.
//
// - The empty string, never a word: a word could be typed as a new household's id, and the daily run would then
// treat that household's rows as a deleted one's. An id is never empty, so no reader can match these rows.
// - Only the rows of the DELETED LIFE: those started (or, for a box, deleted) at or before that deletion's
// completion. An id used again for a new household keeps every journal row it made since — the new household's
// box deletes and RESETs are read by live code (the escrow carry, the purge of a later delete).
// - `legs_json` keeps its step names and state words; anything in it that is not a plain lower-case word is replaced
// by „other”, so a later writer cannot leave a name there.
//
// Pinned by TestD86_* (deleted_customer_audit_test.go).
const journalIDRemoved = ""
var journalWordRe = regexp.MustCompile(`^[a-z][a-z0-9_]{0,39}$`)
// scrubLegs returns legs_json with every key and value that is not a plain word replaced by "other".
func scrubLegs(raw string) string {
m := map[string]string{}
if json.Unmarshal([]byte(raw), &m) != nil {
return "{}"
}
out := map[string]string{}
for k, v := range m {
if !journalWordRe.MatchString(k) {
k = "other"
}
if !journalWordRe.MatchString(v) {
v = "other"
}
out[k] = v
}
b, _ := json.Marshal(out)
return string(b)
}
// PruneDeletedCustomerAudit deletes the events, notification_log and operator_actions rows of customers whose deletion
// completed before now-keep, and in the same transaction removes the ids from that deleted life's journal rows (D86).
// Returns the audit rows deleted per table. A household whose delete never completed is not touched: its year has
// not started.
func (s *Store) PruneDeletedCustomerAudit(now time.Time, keep time.Duration) (events, notifications int64, err error) {
rows, err := s.db.Query(`SELECT customer_id, completed_at, legs_json FROM customer_resets WHERE completed_at IS NOT NULL AND customer_id != ''`)
if err != nil {
return 0, 0, err
}
type del struct {
id string
at time.Time
}
var dels []del
for rows.Next() {
var id, at, legs string
if err := rows.Scan(&id, &at, &legs); err != nil {
rows.Close()
return 0, 0, err
}
m := map[string]string{}
if json.Unmarshal([]byte(legs), &m) != nil || m["customer_delete"] != "ok" {
continue
}
t := parseSQLiteTime(at)
if t.IsZero() || now.Sub(t) <= keep {
continue
}
dels = append(dels, del{id, t.UTC()})
}
rows.Close()
for _, d := range dels {
ev, nl, err := s.pruneOneDeletedCustomer(d.id, d.at.Format("2006-01-02 15:04:05"))
if err != nil {
return events, notifications, err
}
events += ev
notifications += nl
}
return events, notifications, nil
}
// pruneOneDeletedCustomer is one deleted household's year-end, all or nothing: there is no day on which the log is
// gone and the id is not.
func (s *Store) pruneOneDeletedCustomer(id, cutoff string) (events, notifications int64, err error) {
tx, err := s.db.Begin()
if err != nil {
return 0, 0, err
}
defer tx.Rollback()
r, err := tx.Exec(`DELETE FROM events WHERE customer_id = ? AND created_at <= ?`, id, cutoff)
if err != nil {
return 0, 0, fmt.Errorf("PruneDeletedCustomerAudit %s: events: %w", id, err)
}
events, _ = r.RowsAffected()
r, err = tx.Exec(`DELETE FROM notification_log WHERE customer_id = ? AND created_at <= ?`, id, cutoff)
if err != nil {
return 0, 0, fmt.Errorf("PruneDeletedCustomerAudit %s: notification_log: %w", id, err)
}
notifications, _ = r.RowsAffected()
// D73 (R-1376): the operator's action log of the deleted household is an audit record of the same kind — it had
// no delete at all; it goes with the other two.
if _, err = tx.Exec(`DELETE FROM operator_actions WHERE customer_id = ? AND requested_at <= ?`, id, cutoff); err != nil {
return 0, 0, fmt.Errorf("PruneDeletedCustomerAudit %s: operator_actions: %w", id, err)
}
// D86: the journal rows of the deleted life lose their ids. legs_json first (row by row), then the id columns.
jr, err := tx.Query(`SELECT id, legs_json FROM customer_resets WHERE customer_id = ? AND started_at <= ?`, id, cutoff)
if err != nil {
return 0, 0, fmt.Errorf("PruneDeletedCustomerAudit %s: journal read: %w", id, err)
}
type leg struct {
id int64
raw string
}
var legs []leg
for jr.Next() {
var l leg
if err := jr.Scan(&l.id, &l.raw); err != nil {
jr.Close()
return 0, 0, err
}
legs = append(legs, l)
}
jr.Close()
for _, l := range legs {
if _, err = tx.Exec(`UPDATE customer_resets SET customer_id = ?, legs_json = ? WHERE id = ?`, journalIDRemoved, scrubLegs(l.raw), l.id); err != nil {
return 0, 0, fmt.Errorf("PruneDeletedCustomerAudit %s: customer_resets: %w", id, err)
}
}
if _, err = tx.Exec(`UPDATE host_deletions SET host_id = ?, customer_id = ? WHERE customer_id = ? AND deleted_at <= ?`,
journalIDRemoved, journalIDRemoved, id, cutoff); err != nil {
return 0, 0, fmt.Errorf("PruneDeletedCustomerAudit %s: host_deletions: %w", id, err)
}
if err = tx.Commit(); err != nil {
return 0, 0, err
}
return events, notifications, nil
}