Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 29 additions & 18 deletions configuration.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package httpcache

import (
"fmt"
"math"
"regexp"
"strconv"
"strings"
Expand All @@ -9,6 +11,7 @@ import (
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/darkweak/souin/configurationtypes"
"github.com/darkweak/storages/core"
"github.com/dustin/go-humanize"
)

// DefaultCache the struct
Expand Down Expand Up @@ -364,33 +367,38 @@ func parseRedisConfiguration(c map[string]interface{}) map[string]interface{} {
return c
}

func parseSimpleFSConfiguration(c map[string]interface{}) map[string]interface{} {
func parseSimpleFSConfiguration(c map[string]interface{}) (map[string]interface{}, error) {
for k, v := range c {
switch k {
case "path":
c[k] = v
case "size":
switch v {
case false:
c[k] = 0
case true:
c[k] = 1
default:
c[k], _ = strconv.Atoi(v.(string))
val, ok := v.(string)
if !ok {
return nil, fmt.Errorf("simplefs size expects a single integer value, got %v", v)
}
size, err := strconv.Atoi(val)
if err != nil || size < 0 {
return nil, fmt.Errorf("simplefs size expects a positive integer, got %q", val)
}
c[k] = size
case "directory_size":
switch v {
case false:
c[k] = 0
case true:
c[k] = 1
default:
c[k], _ = strconv.Atoi(v.(string))
val, ok := v.(string)
if !ok {
return nil, fmt.Errorf("simplefs directory_size expects a single size value, got %v", v)
}
size, err := humanize.ParseBytes(val)
if err != nil {
return nil, fmt.Errorf("simplefs directory_size: invalid size %q: %w", val, err)
}
if size > math.MaxInt64 {
return nil, fmt.Errorf("simplefs directory_size: %q is too large", val)
}
c[k] = int64(size)
}
}

return c
return c, nil
}

func parseConfiguration(cfg *Configuration, h *caddyfile.Dispenser, isGlobal bool) error {
Expand Down Expand Up @@ -729,8 +737,11 @@ func parseConfiguration(cfg *Configuration, h *caddyfile.Dispenser, isGlobal boo
urlArgs := h.RemainingArgs()
provider.Path = urlArgs[0]
case "configuration":
provider.Configuration = parseCaddyfileRecursively(h)
provider.Configuration = parseSimpleFSConfiguration(provider.Configuration.(map[string]interface{}))
sfsConfiguration, err := parseSimpleFSConfiguration(parseCaddyfileRecursively(h).(map[string]interface{}))
if err != nil {
return h.Err(err.Error())
}
provider.Configuration = sfsConfiguration
default:
return h.Errf("unsupported simplefs directive: %s", directive)
}
Expand Down
123 changes: 123 additions & 0 deletions configuration_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package httpcache

import (
"encoding/json"
"reflect"
"testing"

"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/darkweak/souin/configurationtypes"
)

// roundTripCaddyfileDirective parses a `cache` directive and round trips it through JSON like Caddy does.
func roundTripCaddyfileDirective(t *testing.T, input string) (*SouinCaddyMiddleware, error) {
t.Helper()

var parsed SouinCaddyMiddleware
if err := parsed.UnmarshalCaddyfile(caddyfile.NewTestDispenser(input)); err != nil {
return nil, err
}

raw, err := json.Marshal(&parsed)
if err != nil {
t.Fatalf("unable to marshal the parsed configuration: %v", err)
}

var loaded SouinCaddyMiddleware
if err := json.Unmarshal(raw, &loaded); err != nil {
t.Fatalf("unable to unmarshal the configuration %s: %v", raw, err)
}

return &loaded, nil
}

// Regression test for https://github.com/darkweak/souin/issues/847.
func TestSimpleFSConfigurationSizes(t *testing.T) {
cases := map[string]float64{
"10485760": 10485760,
"10mb": 10_000_000,
"10MiB": 10485760,
"1GB": 1_000_000_000,
}

for value, expected := range cases {
loaded, err := roundTripCaddyfileDirective(t, `cache {
simplefs {
configuration {
size 1000
directory_size `+value+`
}
}
}`)
if err != nil {
t.Fatalf("unexpected error for directory_size %s: %v", value, err)
}

cfg, ok := loaded.Configuration.DefaultCache.SimpleFS.Configuration.(map[string]interface{})
if !ok {
t.Fatalf("unexpected simplefs configuration type %T", loaded.Configuration.DefaultCache.SimpleFS.Configuration)
}

if cfg["directory_size"] != expected {
t.Errorf("directory_size %s: expected %v, got %#v", value, expected, cfg["directory_size"])
}
if cfg["size"] != float64(1000) {
t.Errorf("size: expected 1000, got %#v", cfg["size"])
}
}
}

func TestSimpleFSConfigurationInvalidSizes(t *testing.T) {
for _, block := range []string{
"directory_size tenmegs",
"directory_size 10 mb extra",
"size 10mb",
"size -1",
} {
_, err := roundTripCaddyfileDirective(t, `cache {
simplefs {
configuration {
`+block+`
}
}
}`)
if err == nil {
t.Errorf("expected an error for %q, got nil", block)
}
}
}

// Regression test for https://github.com/darkweak/souin/issues/688.
func TestCacheKeysCaddyfileRoundTrip(t *testing.T) {
loaded, err := roundTripCaddyfileDirective(t, `cache {
cache_keys {
.+\/404$ {
disable_host
}
.+\.css {
disable_body
disable_query
headers Authorization Content-Type
}
}
}`)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}

expected := map[string]configurationtypes.Key{
`.+\/404$`: {DisableHost: true},
`.+\.css`: {DisableBody: true, DisableQuery: true, Headers: []string{"Authorization", "Content-Type"}},
}

got := map[string]configurationtypes.Key{}
for _, cacheKey := range loaded.Configuration.CacheKeys {
for rg, key := range cacheKey {
got[rg.String()] = key
}
}

if !reflect.DeepEqual(expected, got) {
t.Errorf("unexpected cache_keys after the JSON round trip, expected %#v, got %#v", expected, got)
}
}
120 changes: 120 additions & 0 deletions disable_coalescing_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
package httpcache

import (
"fmt"
"net/http"
"net/http/httptest"
"sync"
"sync/atomic"
"testing"
"time"

"github.com/caddyserver/caddy/v2/caddytest"
)

func TestFromAppInheritsDisableCoalescing(t *testing.T) {
s := &SouinCaddyMiddleware{}
app := &SouinApp{DefaultCache: DefaultCache{DisableCoalescing: true}}

if err := s.FromApp(app); err != nil {
t.Fatalf("FromApp: %v", err)
}
if !s.Configuration.DefaultCache.IsCoalescingDisable() {
t.Error("the global disable_coalescing was not inherited by the handler")
}
}

func TestFromAppKeepsCoalescingWhenNotDisabled(t *testing.T) {
s := &SouinCaddyMiddleware{}
app := &SouinApp{}

if err := s.FromApp(app); err != nil {
t.Fatalf("FromApp: %v", err)
}
if s.Configuration.DefaultCache.IsCoalescingDisable() {
t.Error("coalescing was disabled although neither the app nor the handler disabled it")
}
}

type slowCountingOrigin struct {
calls atomic.Int64
}

func (o *slowCountingOrigin) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
o.calls.Add(1)
time.Sleep(200 * time.Millisecond)
w.Header().Set("Cache-Control", "public, s-maxage=60")
_, _ = w.Write([]byte("ok"))
}

// concurrentOriginCalls returns how many of n identical concurrent requests reached the upstream.
func concurrentOriginCalls(t *testing.T, caddyfile string) int64 {
t.Helper()
origin := &slowCountingOrigin{}
srv := httptest.NewServer(origin)
t.Cleanup(srv.Close)

tester := caddytest.NewTester(t)
tester.InitServer(fmt.Sprintf(caddyfile, srv.Listener.Addr()), "caddyfile")

const n = 8
start := make(chan struct{})
var wg sync.WaitGroup
for i := 0; i < n; i++ {
wg.Add(1)
go func() {
defer wg.Done()
<-start
res, err := tester.Client.Get("http://localhost:9080/coalescing")
if err != nil {
t.Errorf("request: %v", err)
return
}
_ = res.Body.Close()
}()
}
close(start)
wg.Wait()

return origin.calls.Load()
}

func TestGlobalDisableCoalescingTakesEffect(t *testing.T) {
calls := concurrentOriginCalls(t, `
{
admin localhost:2999
http_port 9080
cache {
disable_coalescing
}
}
localhost:9080 {
route /coalescing {
cache
reverse_proxy %s
}
}`)

if calls != 8 {
t.Errorf("with disable_coalescing, want one upstream call per request (8), got %d", calls)
}
}

func TestCoalescingIsOnByDefault(t *testing.T) {
calls := concurrentOriginCalls(t, `
{
admin localhost:2999
http_port 9080
cache
}
localhost:9080 {
route /coalescing {
cache
reverse_proxy %s
}
}`)

if calls != 1 {
t.Errorf("without disable_coalescing, want the burst coalesced into 1 upstream call, got %d", calls)
}
}
10 changes: 6 additions & 4 deletions dispatch.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,11 +145,13 @@ func (s *SouinCaddyMiddleware) parseStorages(ctx caddy.Context) {
if d, ok := p["InitAddress"]; ok {
elements := make([]string, 0)

for _, elt := range d.([]interface{}) {
elements = append(elements, elt.(string))
}
if vals, ok := d.([]interface{}); ok {
for _, elt := range vals {
elements = append(elements, elt.(string))
}

address = strings.Join(elements, ",")
address = strings.Join(elements, ",")
}
}
if d, ok := p["SelectDB"]; ok {
dbname = fmt.Sprint(d)
Expand Down
Loading