Debian Codegraph @

radix/path_tree.go

raw
1 // Copyright 2026 Princess B33f Heavy Industries / Dave Shanley
2 // SPDX-License-Identifier: MIT
3
4 package radix
5
6 import (
7 v3 "github.com/pb33f/libopenapi/datamodel/high/v3"
8 )
9
10 // PathLookup defines the interface for radix tree path matching implementations.
11 // The default implementation provides O(k) lookup where k is the path segment count.
12 //
13 // Note: This interface handles URL path matching only. HTTP method validation
14 // is performed separately after the PathItem is retrieved, since a single path
15 // (e.g., "/users/{id}") can support multiple HTTP methods (GET, POST, PUT, DELETE).
16 type PathLookup interface {
17 // Lookup finds the PathItem for a given URL path.
18 // Returns the matched PathItem, the path template (e.g., "/users/{id}"), and whether found.
19 Lookup(urlPath string) (pathItem *v3.PathItem, matchedPath string, found bool)
20 }
21
22 // PathTree is a radix tree optimized for OpenAPI path matching.
23 // It provides O(k) lookup where k is the number of path segments (typically 3-5),
24 // with minimal allocations during lookup.
25 //
26 // This is a thin wrapper around the generic Tree, specialized for
27 // OpenAPI PathItem values. It implements the PathLookup interface.
28 type PathTree struct {
29 tree *Tree[*v3.PathItem]
30 }
31
32 // Ensure PathTree implements PathLookup at compile time.
33 var _ PathLookup = (*PathTree)(nil)
34
35 // NewPathTree creates a new empty radix tree for path matching.
36 func NewPathTree() *PathTree {
37 return &PathTree{
38 tree: New[*v3.PathItem](),
39 }
40 }
41
42 // Insert adds a path and its PathItem to the tree.
43 // Path should be in OpenAPI format, e.g., "/users/{id}/posts"
44 func (t *PathTree) Insert(path string, pathItem *v3.PathItem) {
45 t.tree.Insert(path, pathItem)
46 }
47
48 // Lookup finds the PathItem for a given request path.
49 // Returns the PathItem, the matched path template, and whether a match was found.
50 func (t *PathTree) Lookup(urlPath string) (*v3.PathItem, string, bool) {
51 return t.tree.Lookup(urlPath)
52 }
53
54 // Size returns the number of paths stored in the tree.
55 func (t *PathTree) Size() int {
56 return t.tree.Size()
57 }
58
59 // Walk calls the given function for each path in the tree.
60 func (t *PathTree) Walk(fn func(path string, pathItem *v3.PathItem) bool) {
61 t.tree.Walk(fn)
62 }
63
64 // BuildPathTree creates a PathTree from an OpenAPI document.
65 // This should be called once during validator initialization.
66 func BuildPathTree(doc *v3.Document) *PathTree {
67 tree := NewPathTree()
68
69 if doc == nil || doc.Paths == nil || doc.Paths.PathItems == nil {
70 return tree
71 }
72
73 for pair := doc.Paths.PathItems.First(); pair != nil; pair = pair.Next() {
74 path := pair.Key()
75 pathItem := pair.Value()
76 tree.Insert(path, pathItem)
77 }
78
79 return tree
80 }