Debian Codegraph @

cache_test.go

raw
1 package schema
2
3 import (
4 "fmt"
5 "reflect"
6 "runtime"
7 "strconv"
8 "strings"
9 "sync"
10 "testing"
11
12 utils "github.com/gofiber/utils/v2"
13 utilstrings "github.com/gofiber/utils/v2/strings"
14 )
15
16 func TestNextPathSegment(t *testing.T) {
17 cases := []struct {
18 path string
19 start int
20 end int
21 segment string
22 wantErr bool
23 }{
24 {"a.b", 0, 1, "a", false},
25 {"a.b", 2, 3, "b", false},
26 {"abc.defgh", 0, 3, "abc", false},
27 // dot exactly on the SWAR word boundary
28 {"abcdefgh.x", 0, 8, "abcdefgh", false},
29 // segments longer than one SWAR word
30 {"averylongsegmentname.next", 0, 20, "averylongsegmentname", false},
31 {"averylongsegmentname.next", 21, 25, "next", false},
32 {"noseparatorhere", 0, 15, "noseparatorhere", false},
33 // non-ASCII bytes must pass through the word scan untouched
34 {"héllo.wörld", 0, 6, "héllo", false},
35 {"", 0, 0, "", true},
36 {".abc", 0, 0, "", true},
37 {"a..b", 2, 0, "", true},
38 }
39 for _, c := range cases {
40 end, segment, err := nextPathSegment(c.path, c.start)
41 if c.wantErr {
42 if err == nil {
43 t.Errorf("nextPathSegment(%q, %d): expected error", c.path, c.start)
44 }
45 continue
46 }
47 if err != nil {
48 t.Errorf("nextPathSegment(%q, %d): unexpected error %v", c.path, c.start, err)
49 continue
50 }
51 if end != c.end || segment != c.segment {
52 t.Errorf("nextPathSegment(%q, %d) = (%d, %q), want (%d, %q)",
53 c.path, c.start, end, segment, c.end, c.segment)
54 }
55 }
56 }
57
58 func BenchmarkNextPathSegment(b *testing.B) {
59 const path = "averylongsegmentname.middle.tail"
60 for b.Loop() {
61 for start := 0; ; {
62 end, _, err := nextPathSegment(path, start)
63 if err != nil || end == len(path) {
64 break
65 }
66 start = end + 1
67 }
68 }
69 }
70
71 // The setDefaults fast path must not be defeated by anonymous pointers the
72 // walk can never allocate (unexported ones).
73 func TestNeedsDefaultsWalk(t *testing.T) {
74 type hidden struct {
75 X string `schema:"x"`
76 }
77 type onlyUnexported struct {
78 *hidden
79 A string `schema:"a"`
80 }
81
82 d := NewDecoder()
83 if d.cache.get(reflect.TypeOf(onlyUnexported{})).needsDefaultsWalk {
84 t.Error("unexported anonymous pointer must not force the defaults walk")
85 }
86
87 type Inner struct {
88 Y string `schema:"y"`
89 }
90 type withExported struct {
91 *Inner
92 A string `schema:"a"`
93 }
94 if !d.cache.get(reflect.TypeOf(withExported{})).needsDefaultsWalk {
95 t.Error("exported anonymous pointer must keep the defaults walk (it allocates)")
96 }
97
98 type withDefaults struct {
99 A string `schema:"a,default:z"`
100 }
101 if !d.cache.get(reflect.TypeOf(withDefaults{})).needsDefaultsWalk {
102 t.Error("default tags must keep the defaults walk")
103 }
104 }
105
106 func BenchmarkParsePathCacheMiss(b *testing.B) {
107 type Nested struct {
108 Value string `schema:"value"`
109 }
110 type Outer struct {
111 Items []Nested `schema:"items"`
112 }
113 d := NewDecoder()
114 typ := reflect.TypeOf(Outer{})
115 b.ReportAllocs()
116 info := d.cache.get(typ)
117 for b.Loop() {
118 info.paths.clear()
119 if _, err := d.cache.parsePath("items.0.value", typ); err != nil {
120 b.Fatal(err)
121 }
122 }
123 }
124
125 // foldASCIILower backs the allocation-free case-insensitive probes, so it has
126 // to agree with the utils folder it stands in for at every length, and leave
127 // non-ASCII bytes untouched.
128 func TestFoldASCIILower(t *testing.T) {
129 t.Parallel()
130
131 alphabet := make([]byte, 0, 256)
132 for c := 0; c < 256; c++ {
133 alphabet = append(alphabet, byte(c))
134 }
135
136 for n := 0; n <= maxDirectKeyLen; n++ {
137 for off := 0; off < 256; off++ {
138 in := make([]byte, n)
139 for i := range in {
140 in[i] = alphabet[(off+i*7)%256]
141 }
142 src := string(in)
143 var buf [maxDirectKeyLen]byte
144 changed := foldASCIILower(buf[:], src)
145 got := string(buf[:n])
146 want := utilstrings.ToLower(src)
147 if got != want {
148 t.Fatalf("foldASCIILower(%q) = %q, want %q", src, got, want)
149 }
150 if changed != (got != src) {
151 t.Fatalf("foldASCIILower(%q) reported changed=%v, want %v", src, changed, got != src)
152 }
153 }
154 }
155 }
156
157 // A mixed-case path the direct map cannot answer walks the generic parser,
158 // which folds every segment before its field lookup; that must not allocate.
159 func BenchmarkParsePathCacheMissMixedCase(b *testing.B) {
160 type Nested struct {
161 Value string `schema:"value"`
162 }
163 type Outer struct {
164 Items []Nested `schema:"items"`
165 }
166 d := NewDecoder()
167 typ := reflect.TypeOf(Outer{})
168 b.ReportAllocs()
169 info := d.cache.get(typ)
170 for b.Loop() {
171 info.paths.clear()
172 if _, err := d.cache.parsePath("Items.0.Value", typ); err != nil {
173 b.Fatal(err)
174 }
175 }
176 }
177
178 // parsePathInfo rejects a dotless key that misses the direct map without
179 // parsing it, which is only sound if every field a bare alias can reach is in
180 // that map: a single-segment path must parse exactly when the map holds its
181 // folded form.
182 func TestDirectMapCoversEveryBareAlias(t *testing.T) {
183 t.Parallel()
184
185 type Leaf struct {
186 Value string `schema:"value"`
187 }
188 type Embedded struct {
189 Promoted string `schema:"promoted"`
190 }
191 type Dup struct {
192 A string `schema:"same"`
193 B string `schema:"same"`
194 }
195 type Shapes struct {
196 Embedded
197 Dup
198 Plain string `schema:"plain"`
199 MixedCase string `schema:"MixedCase"`
200 Nested Leaf `schema:"nested"`
201 NestedPtr *Leaf `schema:"nestedptr"`
202 Items []Leaf `schema:"items"`
203 Scalars []int `schema:"scalars"`
204 Skipped string `schema:"-"`
205 Unexported string `schema:"unexported"`
206 Dotted string `schema:"dot.ted"`
207 Deep [][]string `schema:"deep"`
208 }
209
210 types := []reflect.Type{
211 reflect.TypeOf(Leaf{}), reflect.TypeOf(Dup{}),
212 reflect.TypeOf(Embedded{}), reflect.TypeOf(Shapes{}),
213 }
214 // Every alias above, some case variants, and keys that only resemble one.
215 keys := []string{
216 "value", "same", "promoted", "plain", "mixedcase", "MixedCase", "MIXEDCASE",
217 "nested", "nestedptr", "items", "scalars", "skipped", "-", "unexported",
218 "dot.ted", "dotted", "deep", "embedded", "dup", "missing", "", "plainx", "Plain",
219 }
220
221 d := NewDecoder()
222 for _, typ := range types {
223 info := d.cache.get(typ)
224 for _, key := range keys {
225 if strings.IndexByte(key, '.') >= 0 {
226 continue // the shortcut only claims anything about dotless keys
227 }
228 _, err := d.cache.parsePath(key, typ)
229 _, inDirect := info.direct[utilstrings.ToLower(key)]
230 if (err == nil) != inDirect {
231 t.Fatalf("%s: parsePath(%q) err=%v but direct map entry=%v", typ, key, err, inDirect)
232 }
233 }
234 }
235 }
236
237 // The path cache seals and spills under concurrent writers; every path must
238 // still resolve to its own index whichever side of the seal it landed on.
239 func TestPathCacheConcurrentSpill(t *testing.T) {
240 type Item struct {
241 Value string `schema:"value"`
242 }
243 type S struct {
244 Items []Item `schema:"items"`
245 }
246 const goroutines, per = 8, maxFastPaths/2 + 64 // together well past the seal
247
248 d := NewDecoder()
249 var wg sync.WaitGroup
250 errs := make(chan error, goroutines)
251 for g := 0; g < goroutines; g++ {
252 wg.Add(1)
253 go func(g int) {
254 defer wg.Done()
255 for i := 0; i < per; i++ {
256 idx := (g*per + i) % (maxFastPaths + 128) // overlap between goroutines
257 key := "items." + strconv.Itoa(idx) + ".value"
258 var s S
259 if err := d.Decode(&s, map[string][]string{key: {key}}); err != nil {
260 errs <- err
261 return
262 }
263 if len(s.Items) != idx+1 || s.Items[idx].Value != key {
264 errs <- fmt.Errorf("%s decoded into %d items, [%d]=%q", key, len(s.Items), idx, s.Items[idx].Value)
265 return
266 }
267 }
268 }(g)
269 }
270 wg.Wait()
271 close(errs)
272 for err := range errs {
273 t.Fatal(err)
274 }
275 info := d.cache.get(reflect.TypeOf(S{}))
276 if !info.paths.sealed.Load() {
277 t.Fatal("expected the cache to have sealed")
278 }
279 }
280
281 // Decode callers (e.g. Fiber binders) pass map keys aliasing reused request
282 // buffers; pathCache must clone the key so later buffer reuse cannot poison it.
283 func TestParsePathDetachesCacheKey(t *testing.T) {
284 // Use a slice-index path: statically-resolvable keys are served from the
285 // direct map and never stored in the sync.Map path cache.
286 type Item struct {
287 Value string `schema:"value"`
288 }
289 type S struct {
290 Items []Item `schema:"items"`
291 }
292 d := NewDecoder()
293 buf := []byte("items.0.value")
294 var s S
295 if err := d.Decode(&s, map[string][]string{utils.UnsafeString(buf): {"x"}}); err != nil {
296 t.Fatal(err)
297 }
298 copy(buf, "xtems.9.qalue") // simulate fasthttp buffer reuse mutating the key bytes
299
300 keys := cachedPathKeys(&d.cache.get(reflect.TypeOf(s)).paths)
301 if len(keys) != 1 {
302 t.Fatalf("expected 1 cached path, got %d (%v)", len(keys), keys)
303 }
304 if keys[0] != "items.0.value" {
305 t.Fatalf("path cache key mutated to %q; key must be cloned before caching", keys[0])
306 }
307 }
308
309 // cachedPathKeys lists everything the cache holds, published map and spill.
310 func cachedPathKeys(c *pathCache) []string {
311 var keys []string
312 if m := c.fast.Load(); m != nil {
313 for k := range *m {
314 keys = append(keys, k)
315 }
316 }
317 c.spill.Range(func(k, _ any) bool {
318 keys = append(keys, k.(string))
319 return true
320 })
321 return keys
322 }
323
324 // Past maxFastPaths the cache spills instead of growing the map it copies on
325 // every write, but every path must still be cached and served.
326 func TestPathCacheSpill(t *testing.T) {
327 t.Parallel()
328
329 type Item struct {
330 Value string `schema:"value"`
331 }
332 type S struct {
333 Items []Item `schema:"items"`
334 }
335 d := NewDecoder()
336 typ := reflect.TypeOf(S{})
337 info := d.cache.get(typ)
338
339 const n = maxFastPaths + 64
340 want := make([]string, 0, n)
341 for i := 0; i < n; i++ {
342 want = append(want, "items."+strconv.Itoa(i)+".value")
343 }
344 for _, p := range want {
345 if _, err := d.cache.parsePath(p, typ); err != nil {
346 t.Fatalf("parsePath(%q): %v", p, err)
347 }
348 }
349 if !info.paths.sealed.Load() {
350 t.Fatal("cache should be sealed past maxFastPaths")
351 }
352 if got := len(*info.paths.fast.Load()); got != maxFastPaths {
353 t.Fatalf("published map holds %d paths, want %d", got, maxFastPaths)
354 }
355 // Every path, spilled or not, still resolves to the right index.
356 for i, p := range want {
357 parts, ok := info.paths.load(p)
358 if !ok {
359 t.Fatalf("path %q not cached", p)
360 }
361 if parts[0].index != i {
362 t.Fatalf("path %q cached as index %d, want %d", p, parts[0].index, i)
363 }
364 }
365 if got := len(cachedPathKeys(&info.paths)); got != n {
366 t.Fatalf("cache holds %d paths, want %d", got, n)
367 }
368
369 info.paths.clear()
370 if info.paths.sealed.Load() || info.paths.fast.Load() != nil {
371 t.Fatal("clear must reset the cache")
372 }
373 if got := len(cachedPathKeys(&info.paths)); got != 0 {
374 t.Fatalf("cache holds %d paths after clear, want 0", got)
375 }
376 }
377
378 // The parser sizes its hop and part slices from a key's separator count, and
379 // that count arrives unvalidated: a key that is mostly separators is rejected
380 // at its first segment, so it must not reserve in proportion to its length
381 // first.
382 func TestParserReservationDoesNotScaleWithSeparators(t *testing.T) {
383 c := newCache()
384 typ := reflect.TypeOf(struct{ A string }{})
385
386 const iters = 100
387 allocated := func(dots int) uint64 {
388 key := "a" + strings.Repeat(".", dots)
389 if _, err := c.parsePath(key, typ); err == nil {
390 t.Fatalf("parsePath(%d separators) succeeded, want rejection", dots)
391 }
392 var before, after runtime.MemStats
393 runtime.GC()
394 runtime.ReadMemStats(&before)
395 for i := 0; i < iters; i++ {
396 _, _ = c.parsePath(key, typ)
397 }
398 runtime.ReadMemStats(&after)
399 return after.TotalAlloc - before.TotalAlloc
400 }
401
402 short := allocated(maxPathReserve)
403 long := allocated(maxPathReserve * 512)
404 if long > short*4 {
405 t.Fatalf("%d separators allocate %d bytes over %d rejections against %d for %d separators: the reservation follows the key length",
406 maxPathReserve*512, long, iters, short, maxPathReserve)
407 }
408 }