Files
felhom-controller/controller/internal/api/geo.go
T
admin 7c05b59708
gates / gates (push) Successful in 24s
v0.253.0 — errors carry the key of the sentence they are (R-557 slice 2 release B)
179 Hungarian sentences were built deep inside a package with fmt.Errorf and printed by
whoever caught them: too late to translate where they are shown, too early where they are
made. Every one now carries its key across that gap. ZERO Hungarian error literals remain.

util.MsgError does three things at once, each earned:
  - Error() is the Hungarian, byte for byte, so every un-converted printer is unchanged;
  - errors.Is answers for the kind AND for a wrapped cause (KindErrorf dropped the cause);
  - an error ARGUMENT renders recursively, so "formázás sikertelen: %w" translates whole.
A foreign error — restic, docker, ssh, the stdlib — prints verbatim. It is not ours.

76 display sites go through errText, and TestNoErrErrorInPageOutput convicts any that do
not. memoryVerdict returns an error rather than a sentence, so the deploy's 409 and the
household's language come from one value; UpdateRefusal gained a Cause to carry it.

Plurals, one rule, stated once: a key with .one/.other takes its COUNT first. Not a
per-call-site flag — the producer somebody forgot would read "3 app is not running". The
guard caught a real key collision (alert.deadapp.one) the day the rule landed.

TWO DEFECTS FOUND IN MY OWN TOOLING, recorded rather than quietly fixed. The bulk converter
silently dropped multi-line concatenations, damaging 7 producers — and the parity gate could
not see it, because every surviving fragment WAS a real base literal while the CALL had lost
text; two behaviour tests caught it. And the counting script was case-sensitive, so it said
"0 left" while five remained.

MinAgent: 0.131.0 (unchanged). No hub release needed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
2026-09-18 11:44:30 +02:00

203 lines
6.6 KiB
Go

package api
import (
"context"
"encoding/json"
"net/http"
"sort"
cf "gitea.dooplex.hu/admin/felhom-controller/internal/cloudflare"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
)
func (r *Router) geoStatus(w http.ResponseWriter, _ *http.Request) {
geo := r.sett.GetGeoRestriction()
data := map[string]interface{}{
"cf_configured": r.cfg.Infrastructure.CFAPIToken != "",
"geo_available": r.geoSync != nil,
}
if geo != nil {
data["enabled"] = geo.Enabled
data["allowed_countries"] = geo.AllowedCountries
data["app_overrides"] = geo.AppOverrides
data["last_sync"] = geo.LastSync
data["last_sync_error"] = geo.LastSyncError
data["syncing"] = r.geoSync != nil && r.geoSync.IsRunning()
} else {
data["enabled"] = false
data["allowed_countries"] = []string{"HU"}
}
writeJSON(w, http.StatusOK, apiResponse{OK: true, Data: data})
}
func (r *Router) geoUpdateSettings(w http.ResponseWriter, req *http.Request) {
limitBody(w, req)
r.dbg("geoUpdateSettings: contentLength=%d", req.ContentLength)
var body struct {
Enabled bool `json:"enabled"`
AllowedCountries []string `json:"allowed_countries"`
}
if err := json.NewDecoder(req.Body).Decode(&body); err != nil {
writeJSON(w, http.StatusBadRequest, apiResponse{OK: false, Error: "invalid request body"})
return
}
// Validate country codes
for _, code := range body.AllowedCountries {
if !cf.ValidCountryCode(code) {
writeJSON(w, http.StatusBadRequest, apiResponse{OK: false, Error: "invalid country code: " + code})
return
}
}
// Get existing settings to preserve app overrides and sync state
existing := r.sett.GetGeoRestriction()
geo := &settings.GeoRestriction{
Enabled: body.Enabled,
AllowedCountries: body.AllowedCountries,
}
if existing != nil {
geo.AppOverrides = existing.AppOverrides
geo.ZoneID = existing.ZoneID
geo.RulesetID = existing.RulesetID
}
if err := r.sett.SetGeoRestriction(geo); err != nil {
r.logger.Printf("[ERROR] [api] Failed to save geo settings: %v", err)
writeJSON(w, http.StatusInternalServerError, apiResponse{OK: false, Error: r.errText(req, err)})
return
}
r.logger.Printf("[INFO] [api] Geo settings updated: enabled=%v, countries=%v", body.Enabled, body.AllowedCountries)
// Trigger async CF sync
if r.geoSync != nil {
go func() {
if err := r.geoSync.Sync(context.Background()); err != nil {
r.logger.Printf("[ERROR] [api] Geo sync after settings update failed: %v", err)
}
}()
}
// Push a fresh hub report out-of-band so the hub reflects the new geo state right
// away instead of after the next ~15-min cycle.
r.reportPushNow()
writeJSON(w, http.StatusOK, apiResponse{OK: true, Message: r.msg(req, "api.geo.set")})
}
func (r *Router) geoTriggerSync(w http.ResponseWriter, req *http.Request) {
if r.geoSync == nil {
writeJSON(w, http.StatusBadRequest, apiResponse{OK: false, Error: r.msg(req, "api.geo.no_cloudflare")})
return
}
go func() {
if err := r.geoSync.Sync(context.Background()); err != nil {
r.logger.Printf("[ERROR] [api] Manual geo sync failed: %v", err)
return
}
// On success the sync clears any stale last_sync_error — push a report so the hub
// reflects the cleared state immediately rather than after the next cycle.
r.reportPushNow()
}()
writeJSON(w, http.StatusOK, apiResponse{OK: true, Message: r.msg(req, "api.geo.sync_started")})
}
// geoCountries serves the picker's country list in the request's language.
//
// The TABLE in internal/cloudflare is untouched and stays Hungarian: it is also the validator, and
// internal/report puts country CODES on the wire. Only the NAME shown to the customer is translated,
// and the list is re-sorted afterwards -- alphabetical order is per language, and a list sorted by
// the Hungarian names would read as shuffled in English.
func (r *Router) geoCountries(w http.ResponseWriter, req *http.Request) {
lang := r.langFor(req)
list := cf.AllCountries()
for i := range list {
list[i].Name = r.countryName(lang, list[i].Code, list[i].Name)
}
sort.Slice(list, func(i, j int) bool { return list[i].Name < list[j].Name })
writeJSON(w, http.StatusOK, apiResponse{OK: true, Data: list})
}
func (r *Router) geoSetAppOverride(w http.ResponseWriter, req *http.Request, appName string) {
if appName == "" {
writeJSON(w, http.StatusBadRequest, apiResponse{OK: false, Error: "invalid app name"})
return
}
limitBody(w, req)
var body struct {
AllowedCountries []string `json:"allowed_countries"`
}
if err := json.NewDecoder(req.Body).Decode(&body); err != nil {
writeJSON(w, http.StatusBadRequest, apiResponse{OK: false, Error: "invalid request body"})
return
}
// Validate country codes
for _, code := range body.AllowedCountries {
if !cf.ValidCountryCode(code) {
writeJSON(w, http.StatusBadRequest, apiResponse{OK: false, Error: "invalid country code: " + code})
return
}
}
// Verify app exists
if _, ok := r.stackMgr.GetStack(appName); !ok {
writeJSON(w, http.StatusNotFound, apiResponse{OK: false, Error: "app not found: " + appName})
return
}
override := &settings.AppGeoOverride{AllowedCountries: body.AllowedCountries}
if err := r.sett.SetGeoAppOverride(appName, override); err != nil {
r.logger.Printf("[ERROR] [api] Failed to save geo override for %s: %v", appName, err)
writeJSON(w, http.StatusInternalServerError, apiResponse{OK: false, Error: r.errText(req, err)})
return
}
r.logger.Printf("[INFO] [api] Geo override set for %s: countries=%v", appName, body.AllowedCountries)
// Trigger async CF sync
if r.geoSync != nil {
go func() {
if err := r.geoSync.Sync(context.Background()); err != nil {
r.logger.Printf("[ERROR] [api] Geo sync after app override failed: %v", err)
}
}()
}
writeJSON(w, http.StatusOK, apiResponse{OK: true, Message: r.msg(req, "api.geo.app_set")})
}
func (r *Router) geoRemoveAppOverride(w http.ResponseWriter, req *http.Request, appName string) {
if appName == "" {
writeJSON(w, http.StatusBadRequest, apiResponse{OK: false, Error: "invalid app name"})
return
}
if err := r.sett.RemoveGeoAppOverride(appName); err != nil {
r.logger.Printf("[ERROR] [api] Failed to remove geo override for %s: %v", appName, err)
writeJSON(w, http.StatusInternalServerError, apiResponse{OK: false, Error: r.errText(req, err)})
return
}
r.logger.Printf("[INFO] [api] Geo override removed for %s", appName)
// Trigger async CF sync
if r.geoSync != nil {
go func() {
if err := r.geoSync.Sync(context.Background()); err != nil {
r.logger.Printf("[ERROR] [api] Geo sync after override removal failed: %v", err)
}
}()
}
writeJSON(w, http.StatusOK, apiResponse{OK: true, Message: r.msg(req, "api.geo.app_removed")})
}