Debian Codegraph @

cache_test.go

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