Repository navigation
perf: cache compiled path regexes and cut request validation allocations #340
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -1430,3 +1430,107 @@ func TestExtractRawQueryValues(t *testing.T) { | |
| "novalue": {""}, | ||
| }, raw) | ||
| } | ||
|
|
||
| func TestExtractRawQueryValuesEmptyQuery(t *testing.T) { | ||
| require.Nil(t, ExtractRawQueryValues("")) | ||
| } | ||
|
|
||
| func TestExtractParamsForOperationOneSideEmpty(t *testing.T) { | ||
| operationOnly := &v3.Parameter{Name: "id", In: Path} | ||
|
|
||
| t.Run("no path level parameters returns the operation slice itself", func(t *testing.T) { | ||
| item := &v3.PathItem{Get: &v3.Operation{Parameters: []*v3.Parameter{operationOnly}}} | ||
| got := ExtractParamsForOperation(&http.Request{Method: http.MethodGet}, item) | ||
| require.Equal(t, []*v3.Parameter{operationOnly}, got) | ||
| // the operation's own slice is handed back, not a copy | ||
| require.Same(t, &got[0], &item.Get.Parameters[0]) | ||
| }) | ||
|
|
||
| t.Run("no operation parameters returns path slice untouched", func(t *testing.T) { | ||
| item := &v3.PathItem{Parameters: []*v3.Parameter{operationOnly}, Get: &v3.Operation{}} | ||
| got := ExtractParamsForOperation(&http.Request{Method: http.MethodGet}, item) | ||
| require.Equal(t, []*v3.Parameter{operationOnly}, got) | ||
| // the path level slice is returned as-is, not copied | ||
| require.Same(t, &got[0], &item.Parameters[0]) | ||
| }) | ||
|
|
||
| t.Run("both sides merge without writing into the model slice", func(t *testing.T) { | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Great catch on the backing array. Concurrent GET and POST requests on the same path item could stomp on each other's parameter lists, which is a properly sneaky bug. The test can't see it though. |
||
| pathLevel := &v3.Parameter{Name: "shared", In: Path} | ||
| operationLevel := &v3.Parameter{Name: "id", In: Path} | ||
| // spare capacity: with len == cap the old append into the model | ||
| // slice reallocated and this test could not see the bug | ||
| item := &v3.PathItem{ | ||
| Parameters: make([]*v3.Parameter, 1, 4), | ||
| Get: &v3.Operation{Parameters: []*v3.Parameter{operationLevel}}, | ||
| } | ||
| item.Parameters[0] = pathLevel | ||
|
|
||
| got := ExtractParamsForOperation(&http.Request{Method: http.MethodGet}, item) | ||
|
|
||
| require.Equal(t, []*v3.Parameter{pathLevel, operationLevel}, got) | ||
| // the model slice keeps its own length, and the capacity slot past | ||
| // its length stays empty: the old append wrote the merged result | ||
| // straight into the model backing array | ||
| require.Len(t, item.Parameters, 1) | ||
| require.Equal(t, pathLevel, item.Parameters[0]) | ||
| require.Nil(t, item.Parameters[1:cap(item.Parameters)][0]) | ||
| }) | ||
| } | ||
|
|
||
| // The tests below pin the pre-existing gaps flagged in the PR 340 review. | ||
| // They assert the CURRENT behavior; the fixes flip the assertions. | ||
|
|
||
| var yesVar = true | ||
|
|
||
| func TestExtractParamsForOperationHeadFallsBackToGet(t *testing.T) { | ||
| // ExtractOperation falls back to get for HEAD, so a HEAD request is | ||
| // validated as the GET operation. ExtractParamsForOperation makes the | ||
| // same fallback, so GET's required query and header parameters are | ||
| // checked for HEAD requests too. | ||
| item := &v3.PathItem{ | ||
| Get: &v3.Operation{Parameters: []*v3.Parameter{{Name: "limit", In: Query, Required: &yesVar}}}, | ||
| Head: nil, | ||
| } | ||
|
|
||
| request, _ := http.NewRequest(http.MethodHead, "/reports", nil) | ||
|
|
||
| // the router and ExtractOperation resolve HEAD to the get operation | ||
| require.Same(t, item.Get, ExtractOperation(request, item)) | ||
|
|
||
| // and the extracted parameters now carry the get operation's parameters | ||
| got := ExtractParamsForOperation(request, item) | ||
| require.Len(t, got, 1) | ||
| require.Equal(t, "limit", got[0].Name) | ||
| } | ||
|
|
||
| func TestExtractParamsForOperationQueryOperation(t *testing.T) { | ||
| // OpenAPI 3.2 query operations carry their own parameters, and QUERY | ||
| // requests resolve to them. | ||
| queryOperation := &v3.Operation{Parameters: []*v3.Parameter{{Name: "limit", In: Query, Required: &yesVar}}} | ||
| item := &v3.PathItem{Query: queryOperation} | ||
|
|
||
| request, _ := http.NewRequest("QUERY", "/search", nil) | ||
|
|
||
| require.Same(t, queryOperation, ExtractOperation(request, item)) | ||
|
|
||
| got := ExtractParamsForOperation(request, item) | ||
| require.Len(t, got, 1, "query operation parameters should be extracted for QUERY requests") | ||
| require.Equal(t, "limit", got[0].Name) | ||
| } | ||
|
|
||
| func TestExtractParamsForOperationAdditionalOperations(t *testing.T) { | ||
| // the router resolves AdditionalOperations, and method extraction now | ||
| // resolves custom methods as well. | ||
| custom := &v3.Operation{Parameters: []*v3.Parameter{{Name: "range", In: Query, Required: &yesVar}}} | ||
| item := &v3.PathItem{} | ||
| item.AdditionalOperations = orderedmap.New[string, *v3.Operation]() | ||
| item.AdditionalOperations.Set("CUSTOM", custom) | ||
|
|
||
| request, _ := http.NewRequest("CUSTOM", "/search", nil) | ||
|
|
||
| require.Same(t, custom, ExtractOperation(request, item)) | ||
|
|
||
| got := ExtractParamsForOperation(request, item) | ||
| require.Len(t, got, 1, "additional operation parameters should be extracted for custom methods") | ||
| require.Equal(t, "range", got[0].Name) | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,9 @@ | ||
| // Copyright 2023-2026 Princess Beef Heavy Industries, LLC / Dave Shanley | ||
| // SPDX-License-Identifier: MIT | ||
|
|
||
| package helpers | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Tiny one: this file is missing the standard copyright header. Worth adding while you're in here. |
||
|
|
||
| import ( | ||
| "bytes" | ||
| "fmt" | ||
| "regexp" | ||
| "strings" | ||
|
|
@@ -26,6 +28,10 @@ var ( | |
| // The function ensures that the template is well-formed, with balanced and properly | ||
| // nested braces. If the template is invalid, an error is returned. | ||
| // | ||
| // The function holds no state: every call compiles the template again. Validators | ||
| // cache compiled regexes per validator in config.ValidationOptions.RegexCache; | ||
| // set config.WithRegexCache to share or supply a cache. | ||
| // | ||
| // Parameters: | ||
| // - tpl: The path template string to convert into a regular expression. | ||
| // | ||
|
|
@@ -39,6 +45,12 @@ var ( | |
| // // regex: ^/orders/([0-9]+)/items/([^/]+)$ | ||
| // // err: nil | ||
| func GetRegexForPath(tpl string) (*regexp.Regexp, error) { | ||
| return compilePathRegex(tpl) | ||
| } | ||
|
|
||
| // compilePathRegex builds and compiles a regular expression for the given | ||
| // path template. | ||
| func compilePathRegex(tpl string) (*regexp.Regexp, error) { | ||
| // Check if it is well-formed. | ||
| idxs, errBraces := BraceIndices(tpl) | ||
| if errBraces != nil { | ||
|
|
@@ -48,7 +60,11 @@ func GetRegexForPath(tpl string) (*regexp.Regexp, error) { | |
| // Backup the original. | ||
| template := tpl | ||
|
|
||
| pattern := bytes.NewBufferString("^") | ||
| // strings.Builder writes cannot fail: the builder grows on demand and | ||
| // panics on overflow instead of returning an error, so the pattern is | ||
| // assembled with plain writes and no error checks. | ||
| var pattern strings.Builder | ||
| pattern.WriteString("^") | ||
| var end int | ||
|
|
||
| for i := 0; i < len(idxs); i += 2 { | ||
|
|
@@ -69,10 +85,10 @@ func GetRegexForPath(tpl string) (*regexp.Regexp, error) { | |
| } | ||
|
|
||
| // Build the regexp pattern. | ||
| _, err := fmt.Fprintf(pattern, "%s(%s)", regexp.QuoteMeta(raw), patt) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| pattern.WriteString(regexp.QuoteMeta(raw)) | ||
| pattern.WriteByte('(') | ||
| pattern.WriteString(patt) | ||
| pattern.WriteByte(')') | ||
|
|
||
| } | ||
|
|
||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This now hands back the operation's own
Parametersslice when there are no path level params. Everything in the repo only reads the result, so we're fine internally. It's exported though, so I'd add a line to the doc comment saying the result is read-only. Otherwise someone appends to it and writes straight into the shared model.