Files
summercms/modules/cooler/example_test.go
Jakub Zych d04454c57b docs(cooler,diary,festival,fetchguard): compile README Go examples via src= (quick-261118-qsd)
- cooler: ExampleFromApp and the articlesController purge declarations;
  AllowExport run by TestDocsAllowExport on miniredis
- diary: blogLog and ExampleFor; the generated main's run function, run by
  TestDocsRun in a temp directory with diary.Reset on cleanup
- festival: PostPublished/ExampleBus_Fire and PostFormExtended/Collected/
  ExampleBus_Collect, with a TestDocsDeclarations for Collected
- fetchguard: fetch region run by TestDocsFetchImage (loopback refused as
  private_ip), client region run by TestDocsSyncItems on a stub transport
2026-11-18 19:48:01 +01:00

202 lines
5.8 KiB
Go

package cooler_test
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"testing"
"time"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/compass"
"git.golem15.com/golem15/summercms/modules/cooler"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/golem15/summercms/modules/surf"
"github.com/alicebob/miniredis/v2"
)
func ExampleFromApp() {
// serve publishes the Cache at start-up; a job or console command asks
// FromApp, which builds the configured driver (memory here) once.
app := backpack.New(nil)
cache, err := cooler.FromApp(app)
if err != nil {
fmt.Println(err)
return
}
ctx := context.Background()
loads := 0
popular := func(context.Context) ([]byte, error) {
loads++
return json.Marshal([]string{"Hello", "Summer"})
}
var titles []string
for range 2 {
raw, err := cache.Remember(ctx, "blog:popular", 10*time.Minute, popular)
if err != nil {
fmt.Println(err)
return
}
if err := json.Unmarshal(raw, &titles); err != nil {
fmt.Println(err)
return
}
}
fmt.Println(titles, loads)
// Output: [Hello Summer] 1
}
func ExampleCache_Pull() {
// A one-time code: one request stores it with a short TTL, the request
// that redeems it pulls it, and a second redemption finds nothing.
cache, err := cooler.NewMemoryCache("acme:", cooler.DefaultMaxEntries)
if err != nil {
fmt.Println(err)
return
}
ctx := context.Background()
if err := cache.Set(ctx, "signin:4f9c", []byte(`{"user_id":7}`), 5*time.Minute); err != nil {
fmt.Println(err)
return
}
for range 2 {
payload, ok, err := cache.Pull(ctx, "signin:4f9c")
if err != nil {
fmt.Println(err)
return
}
if !ok {
fmt.Println("unknown, expired or already used")
continue
}
fmt.Println(string(payload))
}
// Output:
// {"user_id":7}
// unknown, expired or already used
}
// Article is a blog's article model.
type Article struct {
Slug string
}
// articlesController is a blog's admin controller (its pact.AdminController
// methods are left out here).
type articlesController struct {
app func() *backpack.App
}
// purge queues one site-cache purge for the saved article once the save
// transaction commits (at once outside one); the save never waits for the
// site. Without a purge configured the purger is nil and nothing is sent.
func (c articlesController) purge(ctx context.Context, model any) error {
article, ok := model.(*Article)
if !ok {
return nil
}
tx, _ := cabana.TxFromContext(ctx)
cooler.PurgeSiteCacheAfterCommit(ctx, tx, cooler.SiteCacheFromApp(c.app()), "article", article.Slug)
return nil
}
// FormAfterCreate runs inside the create's transaction.
func (c articlesController) FormAfterCreate(ctx context.Context, model any) error {
return c.purge(ctx, model)
}
// FormAfterUpdate runs inside the update's transaction.
func (c articlesController) FormAfterUpdate(ctx context.Context, model any) error {
return c.purge(ctx, model)
}
// FormAfterDelete runs inside the delete's transaction.
func (c articlesController) FormAfterDelete(ctx context.Context, model any) error {
return c.purge(ctx, model)
}
var (
_ pact.FormAfterCreate = articlesController{}
_ pact.FormAfterUpdate = articlesController{}
_ pact.FormAfterDelete = articlesController{}
)
func ExampleSiteCacheFromApp() {
// The host site's purge route, standing in on loopback.
site := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
fmt.Println(r.Method, r.URL.Path, string(body))
_, _ = w.Write([]byte(`{"purged":3}`))
}))
defer site.Close()
dir, err := os.MkdirTemp("", "cooler-example")
if err != nil {
fmt.Println(err)
return
}
defer os.RemoveAll(dir)
cfg, err := compass.Open(compass.Options{Dir: dir, Environ: []string{
"SUMMER_SITE_CACHE__PURGE_URL=" + site.URL + "/api/__site__/cache/purge",
"SUMMER_SITE_CACHE__PURGE_TOKEN=example-purge-token-0123456789abcdef",
}})
if err != nil {
fmt.Println(err)
return
}
app := backpack.New(cfg)
c := articlesController{app: func() *backpack.App { return app }}
if err := c.FormAfterUpdate(context.Background(), &Article{Slug: "hello-summer"}); err != nil {
fmt.Println(err)
}
// The purge is queued; Wait drains the queue (serve does it at shutdown).
if err := cooler.SiteCacheFromApp(app).Wait(context.Background()); err != nil {
fmt.Println(err)
}
// Output: POST /api/__site__/cache/purge {"kind":"article","slug":"hello-summer"}
}
// AllowExport admits five exports a minute per user across all instances.
func AllowExport(ctx context.Context, app *backpack.App, fallback cooler.Attempter, userKey string) (bool, error) {
client, err := cooler.OpenRedis(ctx, app.Config.String(cooler.RedisURLKey))
if err != nil {
return false, err
}
defer client.Close()
store := cooler.NewRateLimitStore(client, "acme:", fallback)
allowed, _, _ := store.Attempt("export|"+userKey, 5, time.Minute)
return allowed, nil
}
// TestDocsAllowExport runs AllowExport on miniredis: a user's sixth export
// in a minute is refused, and another user's first one passes.
func TestDocsAllowExport(t *testing.T) {
mr := miniredis.RunT(t)
cfg, err := compass.Open(compass.Options{Dir: t.TempDir(), Environ: []string{"SUMMER_REDIS__URL=redis://" + mr.Addr() + "/0"}})
if err != nil {
t.Fatal(err)
}
app := backpack.New(cfg)
fallback := surf.NewMemoryStore(0)
for i := 1; i <= 6; i++ {
allowed, err := AllowExport(t.Context(), app, fallback, "user:7")
if err != nil {
t.Fatal(err)
}
if allowed != (i <= 5) {
t.Fatalf("export %d allowed = %v", i, allowed)
}
}
if allowed, err := AllowExport(t.Context(), app, fallback, "user:8"); err != nil || !allowed {
t.Fatalf("another user's export = %v, %v", allowed, err)
}
if len(mr.Keys()) == 0 {
t.Fatal("the store wrote no key to Redis")
}
}