diff --git a/internal/api/legal.go b/internal/api/legal.go index b637f79..c3d64b3 100644 --- a/internal/api/legal.go +++ b/internal/api/legal.go @@ -6,8 +6,6 @@ import ( "net/url" "slices" "strings" - "sync" - "time" "github.com/a-h/templ" "github.com/gin-gonic/gin" @@ -34,40 +32,22 @@ func mergeLegal(rows []store.LegalDocument) []agentapi.LegalDoc { return out } -// platformLegal caches the platform's documents, which every console page -// links in its footer. -type platformLegal struct { - mu sync.Mutex - docs []agentapi.LegalDoc - fetched time.Time -} - -const legalCacheTTL = 30 * time.Second - +// platformLegalDocs returns the platform's documents, which every console +// page links in its footer. func (s *Server) platformLegalDocs(ctx context.Context) []agentapi.LegalDoc { - s.legal.mu.Lock() - defer s.legal.mu.Unlock() - if time.Since(s.legal.fetched) < legalCacheTTL { - return s.legal.docs - } - var rows []store.LegalDocument - err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { - var err error - rows, err = q.LegalDocuments(ctx, nil) - return err + docs, err := s.legal.get(ctx, s.rdb, func(ctx context.Context) ([]agentapi.LegalDoc, error) { + var rows []store.LegalDocument + err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + var err error + rows, err = q.LegalDocuments(ctx, nil) + return err + }) + return mergeLegal(rows), err }) if err != nil { s.log.WarnContext(ctx, "loading legal documents failed", "error", err) - return s.legal.docs } - s.legal.docs, s.legal.fetched = mergeLegal(rows), time.Now() - return s.legal.docs -} - -func (s *Server) forgetPlatformLegal() { - s.legal.mu.Lock() - s.legal.fetched = time.Time{} - s.legal.mu.Unlock() + return docs } func validLegalKind(kind string) bool { return slices.Contains(web.LegalKinds, kind) } @@ -119,7 +99,9 @@ func (s *Server) saveLegal(c *gin.Context, scope tenant.Scope, org *uuid.UUID) b func (s *Server) adminSaveLegal(c *gin.Context) { if s.saveLegal(c, tenant.System(), nil) { - s.forgetPlatformLegal() + if err := s.legal.bump(c.Request.Context(), s.rdb); err != nil { + s.log.ErrorContext(c.Request.Context(), "announcing legal document change failed", "error", err) + } } } diff --git a/internal/api/legal_test.go b/internal/api/legal_test.go index 10c24c8..1a37075 100644 --- a/internal/api/legal_test.go +++ b/internal/api/legal_test.go @@ -101,3 +101,28 @@ func TestLegalDocuments(t *testing.T) { } } } + +// A change on one replica shows on another with the next request. +func TestLegalChangeReachesOtherReplicas(t *testing.T) { + a := newEnv(t) + b := newEnv(t) + admin := a.browser(t) + admin.signup("a@"+uniq("lr")+".test", uniq("lr-")) + err := tenant.New(a.dbPool).Tx(context.Background(), tenant.Global(), func(q *store.Queries) error { + return q.MakeAdmin(context.Background(), admin.userIDSelf()) + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { admin.do("PUT", "/api/v1/admin/legal/imprint", map[string]any{}) }) + admin.do("PUT", "/api/v1/admin/legal/imprint", map[string]any{}) + + visitor := b.browser(t) + if _, _, html := visitor.page("/login"); strings.Contains(html, `href="/legal/imprint"`) { + t.Fatal("imprint linked before it exists") + } + admin.do("PUT", "/api/v1/admin/legal/imprint", map[string]any{"markdown": "# Impressum"}) + if _, _, html := visitor.page("/login"); !strings.Contains(html, `href="/legal/imprint"`) { + t.Error("the other replica still serves the old footer") + } +} diff --git a/internal/api/server.go b/internal/api/server.go index 5bc29d7..2890511 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -11,6 +11,7 @@ import ( "github.com/go-playground/validator/v10" "github.com/redis/go-redis/v9" + "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" "git.zb-server.de/ZB-Server/uptimesebi/internal/authz" "git.zb-server.de/ZB-Server/uptimesebi/internal/config" @@ -42,7 +43,7 @@ type Server struct { sched *schedule.Scheduler eval *evaluate.Evaluator smtp *notify.SMTP - legal platformLegal + legal *versioned[[]agentapi.LegalDoc] } // Deps are the external resources a Server needs. @@ -73,6 +74,7 @@ func New(cfg config.API, d Deps) *Server { totp: auth.NewTOTPVerifier(d.Redis), sso: sso.New(sso.SafeHTTPClient(allowPrivate), cfg.PublicURL+"/sso/callback", allowPrivate), sched: schedule.New(d.Redis), + legal: newVersioned[[]agentapi.LegalDoc]("legal"), } } diff --git a/internal/api/versioned.go b/internal/api/versioned.go new file mode 100644 index 0000000..e8fefda --- /dev/null +++ b/internal/api/versioned.go @@ -0,0 +1,54 @@ +package api + +import ( + "context" + "errors" + "sync" + + "github.com/redis/go-redis/v9" +) + +// versioned caches a value derived from the database on every replica. A +// counter in Redis names the current version; writers bump it after their +// change committed, and readers reload when it moved. A change is thus +// visible on every replica with the next request, at the cost of one Redis +// GET per read. +type versioned[T any] struct { + key string + + mu sync.Mutex + loaded bool + version int64 + value T +} + +func newVersioned[T any](name string) *versioned[T] { + return &versioned[T]{key: "version:" + name} +} + +// get returns the cached value, loading it when the version changed. If +// Redis is unreachable it keeps serving what it has. +func (v *versioned[T]) get(ctx context.Context, rdb redis.UniversalClient, load func(context.Context) (T, error)) (T, error) { + current, err := rdb.Get(ctx, v.key).Int64() + if errors.Is(err, redis.Nil) { + current, err = 0, nil + } + v.mu.Lock() + defer v.mu.Unlock() + if v.loaded && (err != nil || current == v.version) { + return v.value, nil + } + value, lerr := load(ctx) + if lerr != nil { + return v.value, lerr + } + // Remembering the version read before loading errs on the side of one + // extra reload, never of missing a change. + v.value, v.version, v.loaded = value, current, err == nil + return value, nil +} + +// bump announces a committed change to every replica. +func (v *versioned[T]) bump(ctx context.Context, rdb redis.UniversalClient) error { + return rdb.Incr(ctx, v.key).Err() +}