From 8259243a96b1f65598026c66201e8938c63c2969 Mon Sep 17 00:00:00 2001 From: WeidiDeng Date: Wed, 7 Aug 2024 10:06:22 +0800 Subject: [PATCH] read data only when matchers need some to determine match status --- layer4/routes.go | 4 ++-- layer4/routes_test.go | 27 ++++++++++++++++++++++++++- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/layer4/routes.go b/layer4/routes.go index 3325753..9d3ff75 100644 --- a/layer4/routes.go +++ b/layer4/routes.go @@ -125,9 +125,9 @@ func (routes RouteList) Compile(logger *zap.Logger, matchingTimeout time.Duratio return err } for { - // only read more because there is no buffered data or matchers require more. + // only read more because matchers require more (no matcher in the simplest case). // can happen if this routes list is embedded in another - if len(cx.buf) == 0 || matcherNeedMore { + if matcherNeedMore { err = cx.prefetch() if err != nil { logFunc := logger.Error diff --git a/layer4/routes_test.go b/layer4/routes_test.go index 2b425e7..a66558c 100644 --- a/layer4/routes_test.go +++ b/layer4/routes_test.go @@ -2,7 +2,10 @@ package layer4 import ( "context" + "encoding/json" "errors" + "github.com/caddyserver/caddy/v2/modules/caddyhttp" + "io" "net" "testing" "time" @@ -13,11 +16,33 @@ import ( "go.uber.org/zap/zaptest/observer" ) +type testIoMatcher struct { +} + +func (testIoMatcher) CaddyModule() caddy.ModuleInfo { + return caddy.ModuleInfo{ + ID: "layer4.matchers.testIoMatcher", + New: func() caddy.Module { return new(testIoMatcher) }, + } +} + +func (m *testIoMatcher) Match(cx *Connection) (bool, error) { + buf := make([]byte, 1) + n, err := io.ReadFull(cx, buf) + return n > 0, err +} + func TestMatchingTimeoutWorks(t *testing.T) { ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) defer cancel() - routes := RouteList{&Route{}} + caddy.RegisterModule(testIoMatcher{}) + + routes := RouteList{&Route{ + MatcherSetsRaw: caddyhttp.RawMatcherSets{ + caddy.ModuleMap{"testIoMatcher": json.RawMessage("{}")}, // any io using matcher + }, + }} err := routes.Provision(ctx) if err != nil {