Files
sm-journal-plugin/classes/site_cache.go
Jakub Zych f3b223f131 feat(16.2-07): purge the host site cache after a category admin update
- classes.SiteCachePurger posts {kind, slug} with a bearer token to
  golem15.journal.site_cache.purge_url, 2 s timeout, logged, never fails a save
- PurgeSiteCacheAfterCommit runs it through lagoon.AfterCommit
- Boot builds and publishes the purger from the two config keys
- categories FormAfterUpdate registers the purge; Postgres test proves
  one authorized request after the commit
2026-10-10 18:19:58 +02:00

140 lines
4.4 KiB
Go

package classes
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"time"
"git.golem15.com/golem15/summercms/modules/lagoon"
"gorm.io/gorm"
)
const (
// SiteCachePurgeURLKey is the config key of the host site's cache purge
// URL (env SUMMER_GOLEM15__JOURNAL__SITE_CACHE__PURGE_URL).
SiteCachePurgeURLKey = "golem15.journal.site_cache.purge_url"
// SiteCachePurgeTokenKey is the config key of the bearer token the purge
// request carries (env SUMMER_GOLEM15__JOURNAL__SITE_CACHE__PURGE_TOKEN).
SiteCachePurgeTokenKey = "golem15.journal.site_cache.purge_token"
// SiteCachePurgeTimeout bounds one purge request.
SiteCachePurgeTimeout = 2 * time.Second
// siteCacheAnswerLimit is how much of the purge answer is read.
siteCacheAnswerLimit = 4 << 10
)
// SiteCachePurger asks the host site to drop its page caches after an admin
// save of a Journal post or category. A nil *SiteCachePurger is disabled
// and does nothing.
type SiteCachePurger struct {
url string
token string
client *http.Client
}
// NewSiteCachePurger returns the purger for purgeURL and token. With both
// empty the purge is disabled and it returns nil, nil.
func NewSiteCachePurger(purgeURL, token string) (*SiteCachePurger, error) {
if purgeURL == "" && token == "" {
return nil, nil
}
u, err := url.Parse(purgeURL)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
return nil, fmt.Errorf("%s must be an http or https URL with a host", SiteCachePurgeURLKey)
}
if token == "" {
return nil, errors.New(SiteCachePurgeTokenKey + " must be set")
}
return &SiteCachePurger{url: purgeURL, token: token, client: &http.Client{}}, nil
}
type siteCachePurgeBody struct {
Kind string `json:"kind"`
Slug string `json:"slug"`
}
// Purge sends the purge request for one saved entity: a POST of
// {"kind":kind,"slug":slug} with the bearer token, bounded by
// SiteCachePurgeTimeout and detached from ctx's cancellation. It logs the
// outcome and returns nothing: a purge never fails a save. The token is
// never logged.
func (p *SiteCachePurger) Purge(ctx context.Context, kind, slug string) {
if p == nil {
return
}
if ctx == nil {
ctx = context.Background()
}
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), SiteCachePurgeTimeout)
defer cancel()
log := slog.Default()
raw, err := json.Marshal(siteCachePurgeBody{Kind: kind, Slug: slug})
if err != nil {
log.Warn("journal: site cache purge failed", "kind", kind, "slug", slug, "error", err.Error())
return
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.url, bytes.NewReader(raw))
if err != nil {
log.Warn("journal: site cache purge failed", "kind", kind, "slug", slug, "error", "invalid request")
return
}
req.Header.Set("Authorization", "Bearer "+p.token)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
res, err := p.client.Do(req)
if err != nil {
log.Warn("journal: site cache purge failed", "kind", kind, "slug", slug, "error", purgeTransportError(err))
return
}
defer res.Body.Close()
body, _ := io.ReadAll(io.LimitReader(res.Body, siteCacheAnswerLimit))
if res.StatusCode < 200 || res.StatusCode > 299 {
log.Warn("journal: site cache purge failed", "kind", kind, "slug", slug, "status", res.StatusCode)
return
}
attrs := []any{"kind", kind, "slug", slug, "status", res.StatusCode}
var answer struct {
Purged *int `json:"purged"`
}
if json.Unmarshal(body, &answer) == nil && answer.Purged != nil {
attrs = append(attrs, "purged", *answer.Purged)
}
log.Info("journal: site cache purged", attrs...)
}
// purgeTransportError describes a failed request without the request URL
// or headers.
func purgeTransportError(err error) string {
var uerr *url.Error
if errors.As(err, &uerr) {
err = uerr.Err
}
if errors.Is(err, context.DeadlineExceeded) {
return "timeout"
}
return err.Error()
}
// PurgeSiteCacheAfterCommit registers p.Purge(kind, slug) to run after the
// transaction db belongs to commits, through lagoon.AfterCommit: a failed
// save never purges, and a concurrent page view cannot re-cache the old
// content between the purge and the commit. A nil p does nothing.
func PurgeSiteCacheAfterCommit(ctx context.Context, db *gorm.DB, p *SiteCachePurger, kind, slug string) {
if p == nil {
return
}
lagoon.AfterCommit(ctx, db, func(ctx context.Context, _ *gorm.DB) {
p.Purge(ctx, kind, slug)
})
}