R-1199 reopened: a box with no list of its own reads the household's from the hub and adopts it, pushes its default once only when no household saved one; every push names its source; an empty saved list stays empty; R-1216 (D28 = A): the install page's swap sentence only when host swap is really short (shared case table); unreleased
gates / gates (push) Successful in 1m55s

This commit is contained in:
2026-10-22 12:13:26 +02:00
parent 08fa440d04
commit add310c80a
13 changed files with 512 additions and 61 deletions
+74 -12
View File
@@ -8,6 +8,7 @@ import (
"io"
"log"
"net/http"
"net/url"
"strings"
"sync"
"time"
@@ -1070,14 +1071,31 @@ type preferencesRequest struct {
// holds. OMITTED unless true: an empty address without it keeps the hub's no-clobber guard (an
// unconfigured box must never wipe a seeded address). Decoded by the hub's savePreferences.
EmailCleared bool `json:"email_cleared,omitempty"`
// Source (R-1199 reopened): PrefsSourceHousehold or PrefsSourceDefault. An older hub ignores it.
Source string `json:"source,omitempty"`
}
// SyncPreferences pushes the current notification preferences to the hub.
// SyncPreferences pushes the household's saved notification preferences to the hub (source "household").
// Synchronous — returns error for the handler to display to the user.
// emailCleared (R-922) is settings.NotificationPrefs.EmailCleared — true only after a household's clear.
func (n *Notifier) SyncPreferences(email string, enabledEvents []string, cooldownHours int, emailCleared bool) error {
_, err := n.SyncPreferencesAs(PrefsSourceHousehold, email, enabledEvents, cooldownHours, emailCleared)
return err
}
// PrefsSourceHousehold / PrefsSourceDefault (R-1199 reopened) tell the hub who chose the pushed list: the household
// (the settings page, or the re-push of a list saved on this box) or the box's own default (nothing saved here and
// the hub holds no household list). The hub never lets a default overwrite a household's list.
const (
PrefsSourceHousehold = "household"
PrefsSourceDefault = "default"
)
// SyncPreferencesAs is SyncPreferences with the source named. It returns the hub's status word: "ok", or "kept" when
// the hub refused a default push because the household saved its own list (hub ≥ 0.165.0).
func (n *Notifier) SyncPreferencesAs(source, email string, enabledEvents []string, cooldownHours int, emailCleared bool) (string, error) {
if !n.enabled {
return util.MsgError("err.notify.hub_nem_konfiguralt")
return "", util.MsgError("err.notify.hub_nem_konfiguralt")
}
payload := preferencesRequest{
@@ -1086,41 +1104,85 @@ func (n *Notifier) SyncPreferences(email string, enabledEvents []string, cooldow
EnabledEvents: enabledEvents,
CooldownHours: cooldownHours,
EmailCleared: emailCleared,
Source: source,
}
jsonData, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("marshal: %w", err)
return "", fmt.Errorf("marshal: %w", err)
}
url := n.hubURL + "/api/v1/preferences"
prefsURL := n.hubURL + "/api/v1/preferences"
if n.debug {
n.logger.Printf("[DEBUG] SyncPreferences: url=%s email=%s events=%v cooldown=%dh",
url, email, enabledEvents, cooldownHours)
n.logger.Printf("[DEBUG] SyncPreferences: url=%s source=%s email=%s events=%v cooldown=%dh",
prefsURL, source, email, enabledEvents, cooldownHours)
}
req, err := http.NewRequest("POST", url, bytes.NewReader(jsonData))
req, err := http.NewRequest("POST", prefsURL, bytes.NewReader(jsonData))
if err != nil {
return fmt.Errorf("request: %w", err)
return "", fmt.Errorf("request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+n.apiKey)
req.Header.Set("Content-Type", "application/json")
resp, err := n.httpClient.Do(req)
if err != nil {
return util.MsgError("err.notify.hub_elerhetetlen", err)
return "", util.MsgError("err.notify.hub_elerhetetlen", err)
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
return util.MsgError("err.notify.hub_error", resp.StatusCode, string(body))
return "", util.MsgError("err.notify.hub_error", resp.StatusCode, string(body))
}
var ack struct {
Status string `json:"status"`
}
_ = json.NewDecoder(io.LimitReader(resp.Body, 4096)).Decode(&ack) // an older hub answers {"status":"ok"} too
if ack.Status == "" {
ack.Status = "ok"
}
if n.debug {
n.logger.Printf("[DEBUG] SyncPreferences: response HTTP %d", resp.StatusCode)
}
n.logger.Printf("[INFO] Notification preferences synced to hub: email=%s, events=%v, cooldown=%dh, email_cleared=%t", email, enabledEvents, cooldownHours, emailCleared)
return nil
n.logger.Printf("[INFO] Notification preferences synced to hub: source=%s status=%s email=%s, events=%v, cooldown=%dh, email_cleared=%t", source, ack.Status, email, enabledEvents, cooldownHours, emailCleared)
return ack.Status, nil
}
// HubPrefs is the hub's stored notification list for this box's customer (GET /api/v1/preferences, hub ≥ 0.165.0).
type HubPrefs struct {
Exists bool `json:"exists"`
HouseholdSaved bool `json:"household_saved"`
Email string `json:"email"`
EnabledEvents []string `json:"enabled_events"`
CooldownHours int `json:"cooldown_hours"`
}
// FetchPreferences reads the hub's stored list for this customer (R-1199 reopened): a box with no list of its own
// adopts the household's instead of pushing its default over it. Any failure — an older hub (404), no network — is
// an error, and the caller then pushes nothing.
func (n *Notifier) FetchPreferences() (*HubPrefs, error) {
if !n.enabled {
return nil, util.MsgError("err.notify.hub_nem_konfiguralt")
}
req, err := http.NewRequest("GET", n.hubURL+"/api/v1/preferences?customer_id="+url.QueryEscape(n.customerID), nil)
if err != nil {
return nil, fmt.Errorf("request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+n.apiKey)
resp, err := n.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("hub unreachable: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("hub answered HTTP %d", resp.StatusCode)
}
var hp HubPrefs
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<16)).Decode(&hp); err != nil {
return nil, fmt.Errorf("decode: %w", err)
}
return &hp, nil
}
// ── Test notification ────────────────────────────────────────────────
@@ -0,0 +1,46 @@
package notify
import (
"encoding/json"
"io"
"log"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
)
// R-1199 reopened: the push names its source on the wire and returns the hub's "kept"; the read sends the box's own
// customer id with its key and decodes the hub's answer. The hub side: felhom.eu hub household_prefs.go.
func TestR1199Reopened_TheWire(t *testing.T) {
var gotSource, gotQuery, gotAuth string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotAuth = r.Header.Get("Authorization")
if r.Method == http.MethodGet {
gotQuery = r.URL.RawQuery
w.Write([]byte(`{"exists":true,"household_saved":true,"email":"f@example.hu","enabled_events":["node_down"],"cooldown_hours":6}`))
return
}
var body map[string]any
json.NewDecoder(r.Body).Decode(&body)
gotSource, _ = body["source"].(string)
w.Write([]byte(`{"status":"kept","household_saved":true}`))
}))
defer srv.Close()
sett, _ := settings.Load(filepath.Join(t.TempDir(), "settings.json"), log.New(io.Discard, "", 0))
n := New(srv.URL, "box-key", "demo-felhom", sett, log.New(io.Discard, "", 0), false)
status, err := n.SyncPreferencesAs(PrefsSourceDefault, "", []string{"node_down"}, 6, false)
if err != nil || status != "kept" || gotSource != "default" {
t.Fatalf("push: status=%q err=%v source=%q", status, err, gotSource)
}
hp, err := n.FetchPreferences()
if err != nil || !hp.HouseholdSaved || len(hp.EnabledEvents) != 1 || gotQuery != "customer_id=demo-felhom" || gotAuth != "Bearer box-key" {
t.Fatalf("read: %+v err=%v query=%q", hp, err, gotQuery)
}
if err := n.SyncPreferences("f@example.hu", nil, 6, false); err != nil || gotSource != "household" {
t.Fatalf("the page save must be the household's: err=%v source=%q", err, gotSource)
}
}