Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
45 changes: 45 additions & 0 deletions gateway/gateway_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
os.Exit(InitTestMain(context.Background(), m))
}

func testKey(testName string, name string) string {

Check warning on line 39 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Group together these consecutive parameters of the same type.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNnN&open=AZq7oar8BlbkNXtvGNnN&pullRequest=7558
return fmt.Sprintf("%s-%s", testName, name)
}

Expand Down Expand Up @@ -97,7 +97,7 @@

})

_, _ = ts.Run(t, []test.TestCase{

Check failure on line 100 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNmW&open=AZq7oar8BlbkNXtvGNmW&pullRequest=7558
{Path: "/myapi/anything/a/myapi/b/c", BodyMatch: `"Url":"/something/a/myapi/b/c"`},
}...)
})
Expand Down Expand Up @@ -131,7 +131,7 @@
spec.Proxy.ListenPath = "/"
})

_, _ = ts.Run(t, []test.TestCase{

Check failure on line 134 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNmY&open=AZq7oar8BlbkNXtvGNmY&pullRequest=7558
{Path: "/(abc,xyz)?arg=val", BodyMatch: `"Url":"/\(abc,xyz\)\?arg=val"`},
{Path: "/%28abc,xyz%29?arg=val", BodyMatch: `"Url":"/%28abc,xyz%29\?arg=val"`},
}...)
Expand All @@ -148,7 +148,7 @@
spec.Proxy.TargetURL = TestHttpAny + "/sent_to_me"
})

_, _ = ts.Run(t, []test.TestCase{

Check failure on line 151 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNmZ&open=AZq7oar8BlbkNXtvGNmZ&pullRequest=7558
{Path: "/listen_me/(abc,xyz)?arg=val", BodyMatch: `"Url":"/sent_to_me/listen_me/%28abc,xyz%29\?arg=val"`},
{Path: "/listen_me/%28abc,xyz%29?arg=val", BodyMatch: `"Url":"/sent_to_me/listen_me/%28abc,xyz%29\?arg=val"`},
}...)
Expand All @@ -165,7 +165,7 @@
spec.Proxy.TargetURL = TestHttpAny + "/sent_to_me"
})

_, _ = ts.Run(t, []test.TestCase{

Check failure on line 168 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNma&open=AZq7oar8BlbkNXtvGNma&pullRequest=7558
{Path: "/listen_me/(abc,xyz)?arg=val", BodyMatch: `"Url":"/sent_to_me/listen_me/\(abc,xyz\)\?arg=val"`},
{Path: "/listen_me/%28abc,xyz%29?arg=val", BodyMatch: `"Url":"/sent_to_me/listen_me/%28abc,xyz%29\?arg=val"`},
}...)
Expand All @@ -182,7 +182,7 @@
spec.Proxy.TargetURL = TestHttpAny + "/sent_to_me"
})

_, _ = ts.Run(t, []test.TestCase{

Check failure on line 185 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNmb&open=AZq7oar8BlbkNXtvGNmb&pullRequest=7558
{Path: "/listen_me/(abc,xyz)?arg=val", BodyMatch: `"Url":"/sent_to_me/%28abc,xyz%29\?arg=val"`},
{Path: "/listen_me/%28abc,xyz%29?arg=val", BodyMatch: `"Url":"/sent_to_me/%28abc,xyz%29\?arg=val"`},
}...)
Expand Down Expand Up @@ -240,7 +240,7 @@
spec.Proxy.ListenPath = "/"
})

_, _ = ts.Run(t, []test.TestCase{

Check failure on line 243 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNme&open=AZq7oar8BlbkNXtvGNme&pullRequest=7558
{Path: "/abc/xyz/http%3A%2F%2Ftest.com?arg=val", BodyMatch: `"Url":"/abc/xyz/http%3A%2F%2Ftest.com\?arg=val`},
}...)
})
Expand All @@ -256,7 +256,7 @@
spec.Proxy.TargetURL = TestHttpAny + "/sent_to_me"
})

_, _ = ts.Run(t, []test.TestCase{

Check failure on line 259 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNmf&open=AZq7oar8BlbkNXtvGNmf&pullRequest=7558
{Path: "/listen_me/(abc,xyz)?arg=val", BodyMatch: `"Url":"/sent_to_me/listen_me/%28abc,xyz%29\?arg=val"`},
{Path: "/listen_me/%28abc,xyz%29?arg=val", BodyMatch: `"Url":"/sent_to_me/listen_me/%28abc,xyz%29\?arg=val"`},
{Path: "/listen_me/http%3A%2F%2Ftest.com?arg=val", BodyMatch: `"Url":"/sent_to_me/listen_me/http%3A%2F%2Ftest.com\?arg=val`},
Expand Down Expand Up @@ -294,7 +294,7 @@
spec.Name = t.Name()
})

_, _ = ts.Run(t, []test.TestCase{

Check failure on line 297 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNmh&open=AZq7oar8BlbkNXtvGNmh&pullRequest=7558
{Path: "/listen_me/(abc,xyz)?arg=val", BodyMatch: `"Url":"/sent_to_me/%28abc,xyz%29\?arg=val"`},
{Path: "/listen_me/%28abc,xyz%29?arg=val", BodyMatch: `"Url":"/sent_to_me/%28abc,xyz%29\?arg=val"`},
{Path: "/listen_me/http%3A%2F%2Ftest.com?arg=val", BodyMatch: `"Url":"/sent_to_me/http%3A%2F%2Ftest.com\?arg=val`},
Expand Down Expand Up @@ -340,7 +340,7 @@
}

var data map[string]string
body, _ := ioutil.ReadAll(r.Body)

Check failure on line 343 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNmj&open=AZq7oar8BlbkNXtvGNmj&pullRequest=7558
json.Unmarshal(body, &data)

if data["event"] != "QuotaExceeded" || data["message"] != "Key Quota Limit Exceeded" || data["key"] != keyID {
Expand Down Expand Up @@ -514,7 +514,7 @@
spec.UseKeylessAccess = true
})

_, _ = ts.Run(t, []test.TestCase{

Check failure on line 517 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNml&open=AZq7oar8BlbkNXtvGNml&pullRequest=7558
{Path: "/user-api", Code: http.StatusOK},
{Path: "/user-api", ControlRequest: true, Code: http.StatusNotFound},
}...)
Expand Down Expand Up @@ -546,7 +546,7 @@
})
t.Cleanup(ts.Close)

_, _ = ts.Run(t, []test.TestCase{

Check failure on line 549 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNmn&open=AZq7oar8BlbkNXtvGNmn&pullRequest=7558
{Path: "/debug/pprof/", Code: 404},
{Path: "/debug/pprof/", Code: 200, ControlRequest: true},
{Path: "/debug/pprof/heap", Code: 200, ControlRequest: true},
Expand Down Expand Up @@ -615,7 +615,7 @@
}

n.Signature = "wrong"
payload, _ = json.Marshal(n)

Check failure on line 618 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNmo&open=AZq7oar8BlbkNXtvGNmo&pullRequest=7558
msg.Msg = string(payload)

valid := false
Expand All @@ -629,6 +629,51 @@
})
}

func TestDistributedRateLimiterDisabledRedisEvents(t *testing.T) {
ts := StartTest(nil)
t.Cleanup(ts.Close)

drlNotificationCommand := &testMessageAdapter{
Msg: `{"Command": "NoticeGatewayDRLNotification"}`,
}

shouldNotHandleNotification := func(NotificationCommand) {
assert.Fail(t, "should skip redis event")
}

globalConf := ts.Gw.GetConfig()

t.Run("enabled Sentinel Rate Limiter - should skip DRL updates", func(*testing.T) {
globalConf.EnableSentinelRateLimiter = true
ts.Gw.SetConfig(globalConf)

ts.Gw.handleRedisEvent(drlNotificationCommand, shouldNotHandleNotification, nil)

globalConf.EnableSentinelRateLimiter = false
ts.Gw.SetConfig(globalConf)
})

t.Run("enabled Redis Rolling Limiter - should skip DRL updates", func(*testing.T) {
globalConf.EnableRedisRollingLimiter = true
ts.Gw.SetConfig(globalConf)

ts.Gw.handleRedisEvent(drlNotificationCommand, shouldNotHandleNotification, nil)

globalConf.EnableRedisRollingLimiter = false
ts.Gw.SetConfig(globalConf)
})

t.Run("enabled Fixed Window Rate Limiter - should skip DRL updates", func(*testing.T) {
globalConf.EnableFixedWindowRateLimiter = true
ts.Gw.SetConfig(globalConf)

Check warning on line 669 in gateway/gateway_test.go

View check run for this annotation

probelabs / Visor: quality

architecture Issue

The sub-tests in `TestDistributedRateLimiterDisabledRedisEvents` modify a shared `globalConf` variable across test cases. This pattern is fragile and prevents tests from being run in parallel safely. Each sub-test should manage its own state and ensure proper cleanup to maintain test isolation.
Raw output
Refactor the sub-tests to be self-contained. Either create a fresh configuration object within each `t.Run` block or use `t.Cleanup` to guarantee that the configuration is restored, making the test more robust and safe for parallel execution.
ts.Gw.handleRedisEvent(drlNotificationCommand, shouldNotHandleNotification, nil)

globalConf.EnableFixedWindowRateLimiter = false
ts.Gw.SetConfig(globalConf)
})
}

func TestListenPathTykPrefix(t *testing.T) {
ts := StartTest(nil)
t.Cleanup(ts.Close)
Expand All @@ -637,7 +682,7 @@
spec.Proxy.ListenPath = "/tyk-foo/"
})

_, _ = ts.Run(t, test.TestCase{

Check failure on line 685 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNmp&open=AZq7oar8BlbkNXtvGNmp&pullRequest=7558
Path: "/tyk-foo/",
Code: 200,
})
Expand Down Expand Up @@ -805,7 +850,7 @@
},
)

_, _ = ts.Run(t, []test.TestCase{

Check failure on line 853 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNmt&open=AZq7oar8BlbkNXtvGNmt&pullRequest=7558
{Client: localClient, Code: 200, Path: "/with_domain", Domain: "host1"},
{Client: localClient, Code: 404, Path: "/with_domain"},
{Client: localClient, Code: 200, Path: "/without_domain"},
Expand Down Expand Up @@ -844,7 +889,7 @@
t.Cleanup(ts.Close)

t.Run("Without APIs", func(t *testing.T) {
_, _ = ts.Run(t, []test.TestCase{

Check failure on line 892 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNmv&open=AZq7oar8BlbkNXtvGNmv&pullRequest=7558
{Path: "/hello", BodyMatch: `"status":"pass"`, Code: http.StatusOK},
}...)
})
Expand All @@ -867,7 +912,7 @@
t.Cleanup(ts.Close)

t.Run("Without APIs", func(t *testing.T) {
_, _ = ts.Run(t, []test.TestCase{

Check failure on line 915 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNmx&open=AZq7oar8BlbkNXtvGNmx&pullRequest=7558
{Path: "/hello", Code: http.StatusNotFound},
{ControlRequest: true, Path: "/hello", BodyMatch: `"status":"pass"`, Code: http.StatusOK},
}...)
Expand All @@ -878,7 +923,7 @@
spec.Proxy.ListenPath = "/sample"
})

_, _ = ts.Run(t, []test.TestCase{

Check failure on line 926 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNmy&open=AZq7oar8BlbkNXtvGNmy&pullRequest=7558
{Path: "/hello", Code: http.StatusNotFound},
{ControlRequest: true, Path: "/hello", BodyMatch: `"status":"pass"`, Code: http.StatusOK},
}...)
Expand Down Expand Up @@ -910,7 +955,7 @@

headerCache := map[string]string{"x-tyk-cached-response": "1"}

_, _ = ts.Run(t, []test.TestCase{

Check failure on line 958 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNmz&open=AZq7oar8BlbkNXtvGNmz&pullRequest=7558
{Method: "GET", Path: "/", HeadersNotMatch: headerCache, Delay: 10 * time.Millisecond},
{Method: "GET", Path: "/", HeadersMatch: headerCache},
{Method: "POST", Path: "/", HeadersNotMatch: headerCache},
Expand Down Expand Up @@ -956,7 +1001,7 @@
s.Per = 60
})

_, _ = ts.Run(t, []test.TestCase{

Check failure on line 1004 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNm0&open=AZq7oar8BlbkNXtvGNm0&pullRequest=7558
{Method: http.MethodGet, Path: "/", Headers: map[string]string{authorization: sess1token}, HeadersNotMatch: headerCache, Delay: 10 * time.Millisecond},
{Method: http.MethodGet, Path: "/", Headers: map[string]string{authorization: sess1token}, HeadersMatch: headerCache},
{Method: http.MethodGet, Path: "/", Headers: map[string]string{authorization: sess2token}, HeadersNotMatch: headerCache, Delay: 10 * time.Millisecond},
Expand Down Expand Up @@ -1019,7 +1064,7 @@
matchHeaders := map[string]string{"rewritePath": "newpath"}
randomheaders := map[string]string{"something": "abcd"}

_, _ = ts.Run(t, []test.TestCase{

Check failure on line 1067 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNm1&open=AZq7oar8BlbkNXtvGNm1&pullRequest=7558
{Method: http.MethodGet, Path: "/test", Headers: matchHeaders, HeadersNotMatch: headerCache, Delay: 10 * time.Millisecond},
{Method: http.MethodGet, Path: "/test", Headers: matchHeaders, HeadersMatch: headerCache},
//Even if trigger condition failed, as response is cached
Expand Down Expand Up @@ -1068,7 +1113,7 @@

headerCache := map[string]string{"x-tyk-cached-response": "1"}

_, _ = ts.Run(t, []test.TestCase{

Check failure on line 1116 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNm2&open=AZq7oar8BlbkNXtvGNm2&pullRequest=7558
{Method: http.MethodPost, Path: "/", Data: "{\"id\":\"1\",\"name\":\"test\"}", HeadersNotMatch: headerCache, Delay: 10 * time.Millisecond},
{Method: http.MethodPost, Path: "/", Data: "{\"id\":\"1\",\"name\":\"test\"}", HeadersMatch: headerCache, Delay: 10 * time.Millisecond},
{Method: http.MethodPost, Path: "/", Data: "{\"id\":\"2\",\"name\":\"test\"}", HeadersNotMatch: headerCache, Delay: 10 * time.Millisecond},
Expand Down Expand Up @@ -1134,7 +1179,7 @@

headerCache := map[string]string{"x-tyk-cached-response": "1"}

_, _ = ts.Run(t, []test.TestCase{

Check failure on line 1182 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNm3&open=AZq7oar8BlbkNXtvGNm3&pullRequest=7558
{Method: http.MethodPut, Path: "/put/", Data: "{\"id\":\"1\",\"name\":\"test\"}", HeadersNotMatch: headerCache, Delay: 10 * time.Millisecond}, // 0
{Method: http.MethodPut, Path: "/put/", Data: "{\"id\":\"1\",\"name\":\"test\"}", HeadersMatch: headerCache, Delay: 10 * time.Millisecond},
{Method: http.MethodPut, Path: "/put/", Data: "{\"id\":\"2\",\"name\":\"test\"}", HeadersNotMatch: headerCache, Delay: 10 * time.Millisecond},
Expand Down Expand Up @@ -1211,7 +1256,7 @@

headerCache := map[string]string{"x-tyk-cached-response": "1"}

_, _ = ts.Run(t, []test.TestCase{

Check failure on line 1259 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNm4&open=AZq7oar8BlbkNXtvGNm4&pullRequest=7558
// Make sure CacheAllSafeRequests is working
{Method: http.MethodGet, Path: "/", HeadersNotMatch: headerCache, Delay: 10 * time.Millisecond},
{Method: http.MethodGet, Path: "/", HeadersMatch: headerCache},
Expand Down Expand Up @@ -1354,7 +1399,7 @@
extendedPaths.AdvanceCacheConfig[0].Timeout = 120
ts.Gw.LoadAPI(api)

_, _ = ts.Run(t, []test.TestCase{

Check failure on line 1402 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNm8&open=AZq7oar8BlbkNXtvGNm8&pullRequest=7558
{Method: http.MethodGet, Path: "/my-cached-endpoint", HeadersNotMatch: headerCache, Delay: 10 * time.Millisecond},
{Method: http.MethodGet, Path: "/my-cached-endpoint", HeadersMatch: headerCache},
}...)
Expand Down Expand Up @@ -1528,7 +1573,7 @@
}

// make 2nd http request
_, _ = ts.Run(t, test.TestCase{

Check failure on line 1576 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNm-&open=AZq7oar8BlbkNXtvGNm-&pullRequest=7558
Method: "GET",
Path: "/abc",
Code: http.StatusOK,
Expand All @@ -1545,7 +1590,7 @@
}

func createTestUptream(t *testing.T, allowedConns int, readsPerConn int) net.Listener {
l, _ := net.Listen("tcp", "127.0.0.1:0")

Check failure on line 1593 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNnA&open=AZq7oar8BlbkNXtvGNnA&pullRequest=7558
go func() {
conns := 0

Expand Down Expand Up @@ -1609,7 +1654,7 @@
spec.Proxy.TargetURL = "http://" + upstream.Addr().String()
})

_, _ = ts.Run(t, []test.TestCase{

Check failure on line 1657 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNnB&open=AZq7oar8BlbkNXtvGNnB&pullRequest=7558
{Code: 200},
{Code: 200},
{Code: 200},
Expand Down Expand Up @@ -1652,7 +1697,7 @@
spec.Proxy.TargetURL = "http://" + upstream.Addr().String()
})[0]

_, _ = ts.Run(t, []test.TestCase{

Check failure on line 1700 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNnD&open=AZq7oar8BlbkNXtvGNnD&pullRequest=7558
{Code: 200},
{Code: 200},
}...)
Expand Down Expand Up @@ -1702,7 +1747,7 @@
})
defer ts.Gw.GlobalSessionManager.RemoveSession("default", sess2token, false)

_, _ = ts.Run(t, []test.TestCase{

Check failure on line 1750 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNnF&open=AZq7oar8BlbkNXtvGNnF&pullRequest=7558
{Headers: map[string]string{"Authorization": sess1token}, Code: http.StatusOK, Path: "/", Delay: 100 * time.Millisecond},
{Headers: map[string]string{"Authorization": sess1token}, Code: http.StatusTooManyRequests, Path: "/"},
{Headers: map[string]string{"Authorization": sess2token}, Code: http.StatusOK, Path: "/", Delay: 100 * time.Millisecond},
Expand Down Expand Up @@ -1786,7 +1831,7 @@
buf := make([]byte, 1024)

t.Run("Valid client", func(t *testing.T) {
conn, _ := net.DialTimeout("tcp", ts.mainProxy().listener.Addr().String(), 0)

Check failure on line 1834 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNnI&open=AZq7oar8BlbkNXtvGNnI&pullRequest=7558
conn.Write([]byte("GET / HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n"))
conn.Read(buf)

Expand All @@ -1799,7 +1844,7 @@
time.Sleep(recordsBufferFlushInterval + 50*time.Millisecond)
ts.Gw.Analytics.Store.GetAndDeleteSet(analyticsKeyName)

conn, _ := net.DialTimeout("tcp", ts.mainProxy().listener.Addr().String(), 0)

Check failure on line 1847 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNnJ&open=AZq7oar8BlbkNXtvGNnJ&pullRequest=7558
conn.Write([]byte("GET / HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n"))
conn.Close()
//conn.Read(buf)
Expand Down Expand Up @@ -1838,7 +1883,7 @@

srv.Close()

_, _ = ts.Run(t,

Check failure on line 1886 in gateway/gateway_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oar8BlbkNXtvGNnL&open=AZq7oar8BlbkNXtvGNnL&pullRequest=7558
test.TestCase{Method: http.MethodGet, Path: "/", Code: http.StatusOK},
)

Expand Down
6 changes: 2 additions & 4 deletions gateway/redis_signals.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,10 +140,8 @@
case NoticeDashboardConfigRequest:
gw.handleSendMiniConfig(notif.Payload)
case NoticeGatewayDRLNotification:
if gw.GetConfig().ManagementNode {
// DRL is not initialized, going through would
// be mostly harmless but would flood the log
// with warnings since DRLManager.Ready == false
if gw.isDRLDisabled() {
// DRL is disabled - other Rate Limiter is being used or this node is a Management Node.
return
}
gw.onServerStatusReceivedHandler(notif.Payload)
Expand Down Expand Up @@ -299,7 +297,7 @@
// Decode the configuration from the payload
dashPayload := dashboardConfigPayload{}

if err := json.Unmarshal([]byte(payload), &dashPayload); err != nil {

Check warning on line 300 in gateway/redis_signals.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove this unnecessary variable declaration and use the expression directly in the condition.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oasPBlbkNXtvGNnP&open=AZq7oasPBlbkNXtvGNnP&pullRequest=7558

pubSubLog.Error("Failed to decode dashboard zeroconf payload")
return
Expand Down
10 changes: 7 additions & 3 deletions gateway/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@
}

// GetNodeID reads NodeID safely.
func (gw *Gateway) GetNodeID() string {

Check warning on line 355 in gateway/server.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove the 'Get' prefix from this function name.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oapuBlbkNXtvGNl_&open=AZq7oapuBlbkNXtvGNl_&pullRequest=7558
gw.nodeIDMu.Lock()
defer gw.nodeIDMu.Unlock()
return gw.nodeID
Expand All @@ -371,14 +371,14 @@
gw.runningTestsMu.Unlock()
}

func (gw *Gateway) getApiSpec(apiID string) *APISpec {

Check warning on line 374 in gateway/server.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove the 'Get' prefix from this function name.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oapuBlbkNXtvGNmA&open=AZq7oapuBlbkNXtvGNmA&pullRequest=7558
gw.apisMu.RLock()
spec := gw.apisByID[apiID]
gw.apisMu.RUnlock()
return spec
}

func (gw *Gateway) getAPIDefinition(apiID string) (*apidef.APIDefinition, error) {

Check warning on line 381 in gateway/server.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove the 'Get' prefix from this function name.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oapuBlbkNXtvGNmB&open=AZq7oapuBlbkNXtvGNmB&pullRequest=7558
apiSpec := gw.getApiSpec(apiID)
if apiSpec == nil {
return nil, errors.New("API not found")
Expand Down Expand Up @@ -649,7 +649,7 @@
// this is the only case now where we need a policy record name
mainLog.Debug("No policy record name defined, skipping...")
return 0, nil
} else {

Check failure on line 652 in gateway/server.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove this 'else' clause; the code should continue after the error check.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oapuBlbkNXtvGNmM&open=AZq7oapuBlbkNXtvGNmM&pullRequest=7558
pols, err = LoadPoliciesFromFile(gw.GetConfig().Policies.PolicyRecordName)
}
}
Expand Down Expand Up @@ -684,7 +684,7 @@
return http.HandlerFunc(fn)
}

func (gw *Gateway) controlAPICheckClientCertificate(certLevel string, next http.Handler) http.Handler {

Check warning on line 687 in gateway/server.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Unused parameter 'certLevel' should be removed.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oapuBlbkNXtvGNmJ&open=AZq7oapuBlbkNXtvGNmJ&pullRequest=7558
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if gw.GetConfig().Security.ControlAPIUseMutualTLS {
gwCerts := gw.CertificateManager.List(gw.GetConfig().Security.Certificates.ControlAPI, certs.CertificatePublic)
Expand Down Expand Up @@ -930,7 +930,7 @@
{name: "post", slice: &mwPostFuncs},
} {
globPath := filepath.Join(gw.GetConfig().MiddlewarePath, spec.APIID, folder.name, "*.js")
paths, _ := filepath.Glob(globPath)

Check failure on line 933 in gateway/server.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this error explicitly or document why it can be safely ignored.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oapuBlbkNXtvGNmN&open=AZq7oapuBlbkNXtvGNmN&pullRequest=7558
for _, path := range paths {
mainLog.Debug("Loading file middleware from ", path)

Expand Down Expand Up @@ -1104,7 +1104,7 @@
if count, err := syncResourcesWithReload("apis", gw.GetConfig(), gw.syncAPISpecs); err != nil {
mainLog.Error("Error during syncing apis")
return
} else {

Check failure on line 1107 in gateway/server.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove this 'else' clause; the code should continue after the error check.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oapuBlbkNXtvGNmO&open=AZq7oapuBlbkNXtvGNmO&pullRequest=7558
// skip re-loading only if dashboard service reported 0 APIs
// and current registry had 0 APIs
if count == 0 && gw.apisByIDLen() == 0 {
Expand Down Expand Up @@ -1535,7 +1535,7 @@
return verifier, nil
}

func getPID() string {

Check warning on line 1538 in gateway/server.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove the 'Get' prefix from this function name.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oapuBlbkNXtvGNmC&open=AZq7oapuBlbkNXtvGNmC&pullRequest=7558
return strconv.Itoa(os.Getpid())
}

Expand Down Expand Up @@ -1735,7 +1735,7 @@

var getIpAddress = netutil.GetIpAddress

func (gw *Gateway) getHostDetails() {

Check warning on line 1738 in gateway/server.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove the 'Get' prefix from this function name.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oapuBlbkNXtvGNmD&open=AZq7oapuBlbkNXtvGNmD&pullRequest=7558
var err error
gw.hostDetails.PID = os.Getpid()
if gw.hostDetails.Hostname, err = os.Hostname(); err != nil {
Expand Down Expand Up @@ -1775,7 +1775,7 @@
return localStorage
}

func (gw *Gateway) getGlobalStorageHandler(keyPrefix string, hashKeys bool) storage.Handler {

Check warning on line 1778 in gateway/server.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove the 'Get' prefix from this function name.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oapuBlbkNXtvGNmF&open=AZq7oapuBlbkNXtvGNmF&pullRequest=7558
if gw.GetConfig().SlaveOptions.UseRPC {
return &RPCStorageHandler{
KeyPrefix: keyPrefix,
Expand Down Expand Up @@ -1914,7 +1914,7 @@
mainLog.Info("Cpu profiling active")
cpuProfFile, err := os.Create(cpuprofile)
if err != nil {
panic(err)

Check failure on line 1917 in gateway/server.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Return an error instead of using panic for normal error conditions.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oapuBlbkNXtvGNmQ&open=AZq7oapuBlbkNXtvGNmQ&pullRequest=7558
}
pprof.StartCPUProfile(cpuProfFile)
defer pprof.StopCPUProfile()
Expand Down Expand Up @@ -1953,10 +1953,10 @@
if cli.BlockProfile != nil && *cli.BlockProfile {
f, err := os.Create("tyk.blockprof")
if err != nil {
panic(err)

Check failure on line 1956 in gateway/server.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Return an error instead of using panic for normal error conditions.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oapuBlbkNXtvGNmR&open=AZq7oapuBlbkNXtvGNmR&pullRequest=7558
}
if err = pprof.Lookup("block").WriteTo(f, 0); err != nil {
panic(err)

Check failure on line 1959 in gateway/server.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Return an error instead of using panic for normal error conditions.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oapuBlbkNXtvGNmS&open=AZq7oapuBlbkNXtvGNmS&pullRequest=7558
}
f.Close()
}
Expand All @@ -1966,7 +1966,7 @@
panic(err)
}
if err = pprof.Lookup("mutex").WriteTo(f, 0); err != nil {
panic(err)

Check failure on line 1969 in gateway/server.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Return an error instead of using panic for normal error conditions.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oapuBlbkNXtvGNmU&open=AZq7oapuBlbkNXtvGNmU&pullRequest=7558
}
f.Close()
}
Expand Down Expand Up @@ -2052,15 +2052,13 @@
func (gw *Gateway) startDRL() {
gwConfig := gw.GetConfig()

disabled := gwConfig.ManagementNode || gwConfig.EnableSentinelRateLimiter || gwConfig.EnableRedisRollingLimiter || gwConfig.EnableFixedWindowRateLimiter

gw.drlOnce.Do(func() {
drlManager := &drl.DRL{}
gw.SessionLimiter = NewSessionLimiter(gw.ctx, &gwConfig, drlManager, &gwConfig.ExternalServices)

gw.DRLManager = drlManager

if disabled {
if gw.isDRLDisabled() {
return
}

Expand All @@ -2077,8 +2075,14 @@
})
}

func (gw *Gateway) isDRLDisabled() bool {
gwConfig := gw.GetConfig()

return gwConfig.ManagementNode || gwConfig.EnableSentinelRateLimiter || gwConfig.EnableRedisRollingLimiter || gwConfig.EnableFixedWindowRateLimiter
}

func (gw *Gateway) setupPortsWhitelist() {
// setup listen and control ports as whitelisted

Check notice on line 2085 in gateway/server.go

View check run for this annotation

probelabs / Visor: performance

performance Issue

The new function `isDRLDisabled` is called within `handleRedisEvent`, which can be a hot path for processing Redis notifications. Each call to this function acquires a read lock via `gw.GetConfig()`. Introducing lock contention on a frequent event-handling path can be a source of performance degradation under high load.
Raw output
To avoid locking on this hot path, cache the boolean result of the check in an `atomic.Value` field on the `Gateway` struct. This value should be computed at startup and updated only when the configuration changes (i.e., in `SetConfig`). The check in `handleRedisEvent` can then become a more performant, lock-free atomic read. As a related improvement, refactoring `isDRLDisabled` to be a pure function `isDRLDisabled(cfg config.Config)` would also allow you to eliminate a redundant `GetConfig()` call within the `startDRL` function.
gwConf := gw.GetConfig()
w := gwConf.PortWhiteList
if w == nil {
Expand Down Expand Up @@ -2133,7 +2137,7 @@
gw.DoReload()
}

func (gw *Gateway) GetConfig() config.Config {

Check warning on line 2140 in gateway/server.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove the 'Get' prefix from this function name.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oapuBlbkNXtvGNmG&open=AZq7oapuBlbkNXtvGNmG&pullRequest=7558
return gw.config.Load().(config.Config)
}

Expand All @@ -2141,7 +2145,7 @@
return gw.CertificateManager
}

func (gw *Gateway) SetConfig(conf config.Config, skipReload ...bool) {

Check warning on line 2148 in gateway/server.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Unused parameter 'skipReload' should be removed.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AZq7oapuBlbkNXtvGNmK&open=AZq7oapuBlbkNXtvGNmK&pullRequest=7558
gw.configMu.Lock()
gw.config.Store(conf)
gw.configMu.Unlock()
Expand Down
Loading