diff --git a/cache_key_review_bench_test.go b/cache_key_review_bench_test.go new file mode 100644 index 00000000..fabf7c2c --- /dev/null +++ b/cache_key_review_bench_test.go @@ -0,0 +1,80 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package casbin + +import ( + "strings" + "testing" + + "github.com/casbin/casbin/v3/model" +) + +var reviewCacheKeySink string + +func BenchmarkReviewCacheKey(b *testing.B) { + for _, tc := range []struct { + name string + args []interface{} + }{ + {"route", []interface{}{"alice", "/v1/users/42", "GET"}}, + {"domain", []interface{}{"alice", "tenant-123", "/v1/users/42", "GET"}}, + {"long", []interface{}{"alice", strings.Repeat("x", 160), "GET"}}, + } { + b.Run(tc.name, func(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + reviewCacheKeySink, _ = GetCacheKey(tc.args...) + } + }) + } +} + +const reviewCacheModel = ` +[request_definition] +r = sub, obj, act +[policy_definition] +p = sub, obj, act +[policy_effect] +e = some(where (p.eft == allow)) +[matchers] +m = r.sub == p.sub && r.obj == p.obj && r.act == p.act +` + +func BenchmarkReviewSyncedCacheHit(b *testing.B) { + m, err := model.NewModelFromString(reviewCacheModel) + if err != nil { + b.Fatal(err) + } + e, err := NewSyncedCachedEnforcer(m) + if err != nil { + b.Fatal(err) + } + if _, err := e.AddPolicy("alice", "/v1/users/42", "GET"); err != nil { + b.Fatal(err) + } + if ok, err := e.Enforce("alice", "/v1/users/42", "GET"); err != nil || !ok { + b.Fatal(ok, err) + } + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + if ok, err := e.Enforce("alice", "/v1/users/42", "GET"); err != nil || !ok { + b.Fatal(ok, err) + } + } +} diff --git a/cache_key_review_test.go b/cache_key_review_test.go new file mode 100644 index 00000000..feac4fc5 --- /dev/null +++ b/cache_key_review_test.go @@ -0,0 +1,67 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package casbin + +import ( + "strings" + "testing" +) + +type reviewCacheable struct { + calls int +} + +func (value *reviewCacheable) GetCacheKey() string { + value.calls++ + return "name" +} + +func TestReviewCacheKeyPreservesEncoding(t *testing.T) { + for _, tc := range []struct { + name string + args []interface{} + key string + ok bool + }{ + {"empty request", nil, "", true}, + {"three strings", []interface{}{"alice", "data", "read"}, "s5:alices4:datas4:read", true}, + {"UTF8 and delimiter", []interface{}{"", "é", "a:b"}, "s0:s2:és3:a:b", true}, + {"null byte", []interface{}{"a\x00b"}, "s3:a\x00b", true}, + {"three length digits", []interface{}{strings.Repeat("x", 100)}, "s100:" + strings.Repeat("x", 100), true}, + {"unsupported", []interface{}{"alice", 42}, "", false}, + } { + t.Run(tc.name, func(t *testing.T) { + key, ok := GetCacheKey(tc.args...) + if key != tc.key || ok != tc.ok { + t.Fatalf("GetCacheKey = %q, %v; want %q, %v", key, ok, tc.key, tc.ok) + } + }) + } +} + +func TestReviewCacheKeyCallsCustomKeyOnce(t *testing.T) { + value := &reviewCacheable{} + key, ok := GetCacheKey("alice", value, "read") + if !ok || key != "s5:alicec4:names4:read" || value.calls != 1 { + t.Fatalf("key = %q, cacheable = %v, calls = %d", key, ok, value.calls) + } + stringKey, _ := GetCacheKey("alice", "name", "read") + if key == stringKey { + t.Fatal("custom and string arguments must have distinct key namespaces") + } +} diff --git a/enforcer_cached.go b/enforcer_cached.go index 10f9e459..858560ed 100644 --- a/enforcer_cached.go +++ b/enforcer_cached.go @@ -164,6 +164,24 @@ func (e *CachedEnforcer) InvalidateCache() error { func GetCacheKey(params ...interface{}) (string, bool) { key := strings.Builder{} + // Most requests contain only strings. Reserve their exact encoded size + // without calling CacheableParam.GetCacheKey more than once. + size := 0 + allStrings := true + for _, param := range params { + part, ok := param.(string) + if !ok { + allStrings = false + break + } + size += len(part) + 3 // kind, first length digit, and colon + for n := len(part); n >= 10; n /= 10 { + size++ + } + } + if allStrings { + key.Grow(size) + } for _, param := range params { switch typedParam := param.(type) { case string: @@ -180,7 +198,8 @@ func GetCacheKey(params ...interface{}) (string, bool) { // writeCacheKeyPart length-prefixes each part so that different requests never share a key. func writeCacheKeyPart(key *strings.Builder, kind byte, part string) { key.WriteByte(kind) - key.WriteString(strconv.Itoa(len(part))) + var length [20]byte + key.Write(strconv.AppendInt(length[:0], int64(len(part)), 10)) key.WriteByte(':') key.WriteString(part) }