Debian Codegraph @

server/stree/stree.go

raw
1 // Copyright 2023-2025 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package stree
15
16 import (
17 "bytes"
18 "slices"
19 "strings"
20 "unsafe"
21
22 "github.com/nats-io/nats-server/v2/server/gsl"
23 )
24
25 // SubjectTree is an adaptive radix trie (ART) for storing subject information on literal subjects.
26 // Will use dynamic nodes, path compression and lazy expansion.
27 // The reason this exists is to not only save some memory in our filestore but to greatly optimize matching
28 // a wildcard subject to certain members, e.g. consumer NumPending calculations.
29 type SubjectTree[T any] struct {
30 root node
31 size int
32 }
33
34 // NewSubjectTree creates a new SubjectTree with values T.
35 func NewSubjectTree[T any]() *SubjectTree[T] {
36 return &SubjectTree[T]{}
37 }
38
39 // Size returns the number of elements stored.
40 func (t *SubjectTree[T]) Size() int {
41 if t == nil {
42 return 0
43 }
44 return t.size
45 }
46
47 // Will empty out the tree, or if tree is nil create a new one.
48 func (t *SubjectTree[T]) Empty() *SubjectTree[T] {
49 if t == nil {
50 return NewSubjectTree[T]()
51 }
52 t.root, t.size = nil, 0
53 return t
54 }
55
56 // Insert a value into the tree. Will return if the value was updated and if so the old value.
57 func (t *SubjectTree[T]) Insert(subject []byte, value T) (*T, bool) {
58 if t == nil {
59 return nil, false
60 }
61
62 // Make sure we never insert anything with a noPivot byte.
63 if bytes.IndexByte(subject, noPivot) >= 0 {
64 return nil, false
65 }
66
67 old, updated := t.insert(&t.root, subject, value, 0)
68 if !updated {
69 t.size++
70 }
71 return old, updated
72 }
73
74 // Find will find the value and return it or false if it was not found.
75 func (t *SubjectTree[T]) Find(subject []byte) (*T, bool) {
76 if t == nil {
77 return nil, false
78 }
79
80 var si int
81 for n := t.root; n != nil; {
82 if n.isLeaf() {
83 if ln := n.(*leaf[T]); ln.match(subject[si:]) {
84 return &ln.value, true
85 }
86 return nil, false
87 }
88 // We are a node type here, grab meta portion.
89 if bn := n.base(); len(bn.prefix) > 0 {
90 end := min(si+len(bn.prefix), len(subject))
91 if string(subject[si:end]) != bn.prefix {
92 return nil, false
93 }
94 // Increment our subject index.
95 si += len(bn.prefix)
96 }
97 if an := n.findChild(pivot(subject, si)); an != nil {
98 n = *an
99 } else {
100 return nil, false
101 }
102 }
103 return nil, false
104 }
105
106 // Delete will delete the item and return its value, or not found if it did not exist.
107 func (t *SubjectTree[T]) Delete(subject []byte) (*T, bool) {
108 if t == nil {
109 return nil, false
110 }
111
112 val, deleted := t.delete(&t.root, subject, 0)
113 if deleted {
114 t.size--
115 }
116 return val, deleted
117 }
118
119 // Match will match against a subject that can have wildcards and invoke the callback func for each matched value.
120 func (t *SubjectTree[T]) Match(filter []byte, cb func(subject []byte, val *T)) {
121 if t == nil || t.root == nil || len(filter) == 0 || cb == nil {
122 return
123 }
124 // We need to break this up into chunks based on wildcards, either pwc '*' or fwc '>'.
125 var raw [32][]byte
126 parts := genParts(filter, raw[:0])
127 var _pre [256]byte
128 t.match(t.root, parts, _pre[:0], func(subject []byte, val *T) bool {
129 cb(subject, val)
130 return true
131 })
132 }
133
134 // MatchUntil will match against a subject that can have wildcards and invoke
135 // the callback func for each matched value.
136 // Returning false from the callback will stop matching immediately.
137 // Returns true if matching ran to completion, false if callback stopped it early.
138 func (t *SubjectTree[T]) MatchUntil(filter []byte, cb func(subject []byte, val *T) bool) bool {
139 if t == nil || t.root == nil || len(filter) == 0 || cb == nil {
140 return true
141 }
142 // We need to break this up into chunks based on wildcards, either pwc '*' or fwc '>'.
143 var raw [32][]byte
144 parts := genParts(filter, raw[:0])
145 var _pre [256]byte
146 return t.match(t.root, parts, _pre[:0], cb)
147 }
148
149 // IterOrdered will walk all entries in the SubjectTree lexicographically. The callback can return false to terminate the walk.
150 func (t *SubjectTree[T]) IterOrdered(cb func(subject []byte, val *T) bool) {
151 if t == nil || t.root == nil {
152 return
153 }
154 var _pre [256]byte
155 t.iter(t.root, _pre[:0], true, cb)
156 }
157
158 // IterFast will walk all entries in the SubjectTree with no guarantees of ordering. The callback can return false to terminate the walk.
159 func (t *SubjectTree[T]) IterFast(cb func(subject []byte, val *T) bool) {
160 if t == nil || t.root == nil {
161 return
162 }
163 var _pre [256]byte
164 t.iter(t.root, _pre[:0], false, cb)
165 }
166
167 // Internal methods
168
169 // Internal call to insert that can be recursive.
170 func (t *SubjectTree[T]) insert(np *node, subject []byte, value T, si int) (*T, bool) {
171 n := *np
172 if n == nil {
173 *np = newLeaf(subject, value)
174 return nil, false
175 }
176 if n.isLeaf() {
177 ln := n.(*leaf[T])
178 if ln.match(subject[si:]) {
179 // Replace with new value.
180 old := ln.value
181 ln.value = value
182 return &old, true
183 }
184 // Here we need to split this leaf.
185 cpi := commonPrefixLen(stringToBytes(ln.suffix), subject[si:])
186 nn := newNode4(subject[si : si+cpi])
187 ln.setSuffix(stringToBytes(ln.suffix[cpi:]))
188 si += cpi
189 // Make sure we have different pivot, normally this will be the case unless we have overflowing prefixes.
190 if p := pivot(stringToBytes(ln.suffix), 0); cpi > 0 && si < len(subject) && p == subject[si] {
191 // We need to split the original leaf. Recursively call into insert.
192 t.insert(np, subject, value, si)
193 // Now add the update version of *np as a child to the new node4.
194 nn.addChild(p, *np)
195 } else {
196 // Can just add this new leaf as a sibling.
197 nl := newLeaf(subject[si:], value)
198 nn.addChild(pivot(stringToBytes(nl.suffix), 0), nl)
199 // Add back original.
200 nn.addChild(pivot(stringToBytes(ln.suffix), 0), ln)
201 }
202 *np = nn
203 return nil, false
204 }
205
206 // Non-leaf nodes.
207 bn := n.base()
208 if len(bn.prefix) > 0 {
209 cpi := commonPrefixLen(stringToBytes(bn.prefix), subject[si:])
210 if pli := len(bn.prefix); cpi >= pli {
211 // Move past this node. We look for an existing child node to recurse into.
212 // If one does not exist we can create a new leaf node.
213 si += pli
214 if nn := n.findChild(pivot(subject, si)); nn != nil {
215 return t.insert(nn, subject, value, si)
216 }
217 if n.isFull() {
218 n = n.grow()
219 *np = n
220 }
221 n.addChild(pivot(subject, si), newLeaf(subject[si:], value))
222 return nil, false
223 } else {
224 // We did not match the prefix completely here.
225 // Calculate new prefix for this node.
226 prefix := subject[si : si+cpi]
227 si += len(prefix)
228 // We will insert a new node4 and attach our current node below after adjusting prefix.
229 nn := newNode4(prefix)
230 // Shift the prefix for our original node.
231 n.setPrefix(stringToBytes(bn.prefix[cpi:]))
232 nn.addChild(pivot(stringToBytes(bn.prefix), 0), n)
233 // Add in our new leaf.
234 nn.addChild(pivot(subject[si:], 0), newLeaf(subject[si:], value))
235 // Update our node reference.
236 *np = nn
237 }
238 } else {
239 if nn := n.findChild(pivot(subject, si)); nn != nil {
240 return t.insert(nn, subject, value, si)
241 }
242 // No prefix and no matched child, so add in new leafnode as needed.
243 if n.isFull() {
244 n = n.grow()
245 *np = n
246 }
247 n.addChild(pivot(subject, si), newLeaf(subject[si:], value))
248 }
249
250 return nil, false
251 }
252
253 // internal function to recursively find the leaf to delete. Will do compaction if the item is found and removed.
254 func (t *SubjectTree[T]) delete(np *node, subject []byte, si int) (*T, bool) {
255 if t == nil || np == nil || *np == nil || len(subject) == 0 {
256 return nil, false
257 }
258 n := *np
259 if n.isLeaf() {
260 ln := n.(*leaf[T])
261 if ln.match(subject[si:]) {
262 *np = nil
263 return &ln.value, true
264 }
265 return nil, false
266 }
267 // Not a leaf node.
268 if bn := n.base(); len(bn.prefix) > 0 {
269 // subject could be shorter and would panic on bad index into subject slice.
270 if len(subject) < si+len(bn.prefix) {
271 return nil, false
272 }
273 if string(subject[si:si+len(bn.prefix)]) != bn.prefix {
274 return nil, false
275 }
276 // Increment our subject index.
277 si += len(bn.prefix)
278 }
279 p := pivot(subject, si)
280 nna := n.findChild(p)
281 if nna == nil {
282 return nil, false
283 }
284 nn := *nna
285 if nn.isLeaf() {
286 ln := nn.(*leaf[T])
287 if ln.match(subject[si:]) {
288 n.deleteChild(p)
289
290 if sn := n.shrink(); sn != nil {
291 bn := n.base()
292 pre := bn.prefix
293 // Need to fix up prefixes/suffixes.
294 if sn.isLeaf() {
295 ln := sn.(*leaf[T])
296 ln.suffix = pre + ln.suffix
297 } else {
298 // We are a node here, we need to add in the old prefix.
299 if len(pre) > 0 {
300 bsn := sn.base()
301 bsn.prefix = pre + bsn.prefix
302 }
303 }
304 *np = sn
305 }
306
307 return &ln.value, true
308 }
309 return nil, false
310 }
311 return t.delete(nna, subject, si)
312 }
313
314 // Internal function which can be called recursively to match all leaf nodes to a given filter subject which
315 // once here has been decomposed to parts. These parts only care about wildcards, both pwc and fwc.
316 // Returns false if the callback requested to stop matching.
317 func (t *SubjectTree[T]) match(n node, parts [][]byte, pre []byte, cb func(subject []byte, val *T) bool) bool {
318 // Capture if we are sitting on a terminal fwc.
319 var hasFWC bool
320 if lp := len(parts); lp > 0 && len(parts[lp-1]) > 0 && parts[lp-1][0] == fwc {
321 hasFWC = true
322 }
323
324 for n != nil {
325 nparts, matched := matchParts(parts, n.path())
326 // Check if we did not match.
327 if !matched {
328 return true
329 }
330 // We have matched here. If we are a leaf and have exhausted all parts or he have a FWC fire callback.
331 if n.isLeaf() {
332 if len(nparts) == 0 || (hasFWC && len(nparts) == 1) {
333 ln := n.(*leaf[T])
334 if !cb(append(pre, ln.suffix...), &ln.value) {
335 return false
336 }
337 }
338 return true
339 }
340 // We have normal nodes here.
341 // We need to append our prefix
342 bn := n.base()
343 if len(bn.prefix) > 0 {
344 // Note that this append may reallocate, but it doesn't modify "pre" at the "match" callsite.
345 pre = append(pre, bn.prefix...)
346 }
347
348 // Check our remaining parts.
349 if len(nparts) == 0 && !hasFWC {
350 // We are a node with no parts left and we are not looking at a fwc.
351 // We could have a leafnode with no suffix which would be a match.
352 // We could also have a terminal pwc. Check for those here.
353 var hasTermPWC bool
354 if lp := len(parts); lp > 0 && len(parts[lp-1]) == 1 && parts[lp-1][0] == pwc {
355 // If we are sitting on a terminal pwc, put the pwc back and continue.
356 nparts = parts[len(parts)-1:]
357 hasTermPWC = true
358 }
359 for _, cn := range n.children() {
360 if cn == nil {
361 continue
362 }
363 if cn.isLeaf() {
364 ln := cn.(*leaf[T])
365 if len(ln.suffix) == 0 {
366 if !cb(append(pre, ln.suffix...), &ln.value) {
367 return false
368 }
369 } else if hasTermPWC && strings.IndexByte(ln.suffix, tsep) < 0 {
370 if !cb(append(pre, ln.suffix...), &ln.value) {
371 return false
372 }
373 }
374 } else if hasTermPWC {
375 // We have terminal pwc so call into match again with the child node.
376 if !t.match(cn, nparts, pre, cb) {
377 return false
378 }
379 }
380 }
381 // Return regardless.
382 return true
383 }
384 // If we are sitting on a terminal fwc, put back and continue.
385 if hasFWC && len(nparts) == 0 {
386 nparts = parts[len(parts)-1:]
387 }
388
389 // Here we are a node type with a partial match.
390 // Check if the first part is a wildcard.
391 fp := nparts[0]
392 p := pivot(fp, 0)
393 // Check if we have a pwc/fwc part here. This will cause us to iterate.
394 if len(fp) == 1 && (p == pwc || p == fwc) {
395 // We need to iterate over all children here for the current node
396 // to see if we match further down.
397 for _, cn := range n.children() {
398 if cn != nil {
399 if !t.match(cn, nparts, pre, cb) {
400 return false
401 }
402 }
403 }
404 return true
405 }
406 // Here we have normal traversal, so find the next child.
407 nn := n.findChild(p)
408 if nn == nil {
409 return true
410 }
411 n, parts = *nn, nparts
412 }
413 return true
414 }
415
416 // Internal iter function to walk nodes in lexicographical order.
417 func (t *SubjectTree[T]) iter(n node, pre []byte, ordered bool, cb func(subject []byte, val *T) bool) bool {
418 if n.isLeaf() {
419 ln := n.(*leaf[T])
420 return cb(append(pre, ln.suffix...), &ln.value)
421 }
422 // We are normal node here.
423 bn := n.base()
424 // Note that this append may reallocate, but it doesn't modify "pre" at the "iter" callsite.
425 pre = append(pre, bn.prefix...)
426 // Not everything requires lexicographical sorting, so support a fast path for iterating in
427 // whatever order the stree has things stored instead.
428 if !ordered {
429 for _, cn := range n.children() {
430 if cn == nil {
431 continue
432 }
433 if !t.iter(cn, pre, false, cb) {
434 return false
435 }
436 }
437 return true
438 }
439 // Collect nodes since unsorted.
440 var _nodes [256]node
441 nodes := _nodes[:0]
442 for _, cn := range n.children() {
443 if cn != nil {
444 nodes = append(nodes, cn)
445 }
446 }
447 // Now sort.
448 slices.SortStableFunc(nodes, func(a, b node) int { return strings.Compare(a.path(), b.path()) })
449 // Now walk the nodes in order and call into next iter.
450 for i := range nodes {
451 if !t.iter(nodes[i], pre, true, cb) {
452 return false
453 }
454 }
455 return true
456 }
457
458 // LazyIntersect iterates the smaller of the two provided subject trees and
459 // looks for matching entries in the other. It is lazy in that it does not
460 // aggressively optimize against repeated walks, but is considerably faster
461 // in most cases than intersecting against a potentially large sublist.
462 func LazyIntersect[TL, TR any](tl *SubjectTree[TL], tr *SubjectTree[TR], cb func([]byte, *TL, *TR)) {
463 if tl == nil || tr == nil || tl.root == nil || tr.root == nil {
464 return
465 }
466 // Iterate over the smaller tree to reduce the number of rounds.
467 if tl.Size() <= tr.Size() {
468 tl.IterFast(func(key []byte, v1 *TL) bool {
469 if v2, ok := tr.Find(key); ok {
470 cb(key, v1, v2)
471 }
472 return true
473 })
474 } else {
475 tr.IterFast(func(key []byte, v2 *TR) bool {
476 if v1, ok := tl.Find(key); ok {
477 cb(key, v1, v2)
478 }
479 return true
480 })
481 }
482 }
483
484 // IntersectGSL will match all items in the given subject tree that
485 // have interest expressed in the given sublist. The callback will only be called
486 // once for each subject, regardless of overlapping subscriptions in the sublist.
487 func IntersectGSL[T any, SL comparable](t *SubjectTree[T], sl *gsl.GenericSublist[SL], cb func(subject []byte, val *T) bool) {
488 if t == nil || t.root == nil || sl == nil {
489 return
490 }
491 var _pre [256]byte
492 _intersectGSL(t.root, _pre[:0], sl, cb)
493 }
494
495 func _intersectGSL[T any, SL comparable](n node, pre []byte, sl *gsl.GenericSublist[SL], cb func(subject []byte, val *T) bool) bool {
496 if n.isLeaf() {
497 ln := n.(*leaf[T])
498 subj := append(pre, ln.suffix...)
499 if sl.HasInterest(bytesToString(subj)) {
500 return cb(subj, &ln.value)
501 }
502 return true
503 }
504 bn := n.base()
505 pre = append(pre, bn.prefix...)
506 for _, cn := range n.children() {
507 if cn == nil {
508 continue
509 }
510 subj := append(pre, cn.path()...)
511 if !hasInterestForTokens(sl, subj, len(pre)) {
512 continue
513 }
514 if !_intersectGSL(cn, pre, sl, cb) {
515 return false
516 }
517 }
518 return true
519 }
520
521 // The subject tree can return partial tokens so we need to check starting interest
522 // only from whole tokens when we encounter a tsep.
523 func hasInterestForTokens[SL comparable](sl *gsl.GenericSublist[SL], subj []byte, since int) bool {
524 for i := since; i < len(subj); i++ {
525 if subj[i] == tsep {
526 if !sl.HasInterestStartingIn(bytesToString(subj[:i])) {
527 return false
528 }
529 }
530 }
531 return true
532 }
533
534 // Note this will avoid a copy of the data used for the string, but it will also reference the existing slice's data pointer.
535 // So this should be used sparingly when we know the encompassing byte slice's lifetime is the same.
536 func bytesToString(b []byte) string {
537 if len(b) == 0 {
538 return ""
539 }
540 p := unsafe.SliceData(b)
541 return unsafe.String(p, len(b))
542 }
543
544 // Note this will avoid a copy of the string data, but the returned slice must
545 // only be used for reading since strings are immutable.
546 func stringToBytes(s string) []byte {
547 if len(s) == 0 {
548 return nil
549 }
550 p := unsafe.StringData(s)
551 return unsafe.Slice(p, len(s))
552 }