| 1 |
// Copyright 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 gsl |
| 15 |
|
| 16 |
import ( |
| 17 |
"errors" |
| 18 |
"strings" |
| 19 |
"sync" |
| 20 |
) |
| 21 |
|
| 22 |
// Sublist is a routing mechanism to handle subject distribution and |
| 23 |
// provides a facility to match subjects from published messages to |
| 24 |
// interested subscribers. Subscribers can have wildcard subjects to |
| 25 |
// match multiple published subjects. |
| 26 |
|
| 27 |
// Common byte variables for wildcards and token separator. |
| 28 |
const ( |
| 29 |
pwc = '*' |
| 30 |
pwcs = "*" |
| 31 |
fwc = '>' |
| 32 |
fwcs = ">" |
| 33 |
tsep = "." |
| 34 |
btsep = '.' |
| 35 |
_EMPTY_ = "" |
| 36 |
) |
| 37 |
|
| 38 |
// Sublist related errors |
| 39 |
var ( |
| 40 |
ErrInvalidSubject = errors.New("gsl: invalid subject") |
| 41 |
ErrNotFound = errors.New("gsl: no matches found") |
| 42 |
ErrNilChan = errors.New("gsl: nil channel") |
| 43 |
ErrAlreadyRegistered = errors.New("gsl: notification already registered") |
| 44 |
) |
| 45 |
|
| 46 |
// SimpleSublist is an alias type for GenericSublist that takes |
| 47 |
// empty values, useful for tracking interest only without any |
| 48 |
// unnecessary allocations. |
| 49 |
type SimpleSublist = GenericSublist[struct{}] |
| 50 |
|
| 51 |
// NewSimpleSublist will create a simple sublist. |
| 52 |
func NewSimpleSublist() *SimpleSublist { |
| 53 |
return &GenericSublist[struct{}]{root: newLevel[struct{}]()} |
| 54 |
} |
| 55 |
|
| 56 |
// A GenericSublist stores and efficiently retrieves subscriptions. |
| 57 |
type GenericSublist[T comparable] struct { |
| 58 |
sync.RWMutex |
| 59 |
root *level[T] |
| 60 |
count uint32 |
| 61 |
} |
| 62 |
|
| 63 |
// A node contains subscriptions and a pointer to the next level. |
| 64 |
type node[T comparable] struct { |
| 65 |
next *level[T] |
| 66 |
subs map[T]string // value -> subject |
| 67 |
} |
| 68 |
|
| 69 |
// A level represents a group of nodes and special pointers to |
| 70 |
// wildcard nodes. |
| 71 |
type level[T comparable] struct { |
| 72 |
nodes map[string]*node[T] |
| 73 |
pwc, fwc *node[T] |
| 74 |
} |
| 75 |
|
| 76 |
// Create a new default node. |
| 77 |
func newNode[T comparable]() *node[T] { |
| 78 |
return &node[T]{subs: make(map[T]string)} |
| 79 |
} |
| 80 |
|
| 81 |
// Create a new default level. |
| 82 |
func newLevel[T comparable]() *level[T] { |
| 83 |
return &level[T]{nodes: make(map[string]*node[T])} |
| 84 |
} |
| 85 |
|
| 86 |
// NewSublist will create a default sublist with caching enabled per the flag. |
| 87 |
func NewSublist[T comparable]() *GenericSublist[T] { |
| 88 |
return &GenericSublist[T]{root: newLevel[T]()} |
| 89 |
} |
| 90 |
|
| 91 |
// Insert adds a subscription into the sublist |
| 92 |
func (s *GenericSublist[T]) Insert(subject string, value T) error { |
| 93 |
s.Lock() |
| 94 |
|
| 95 |
var sfwc bool |
| 96 |
var n *node[T] |
| 97 |
l := s.root |
| 98 |
|
| 99 |
for t := range strings.SplitSeq(subject, tsep) { |
| 100 |
lt := len(t) |
| 101 |
if lt == 0 || sfwc { |
| 102 |
s.Unlock() |
| 103 |
return ErrInvalidSubject |
| 104 |
} |
| 105 |
|
| 106 |
if lt > 1 { |
| 107 |
n = l.nodes[t] |
| 108 |
} else { |
| 109 |
switch t[0] { |
| 110 |
case pwc: |
| 111 |
n = l.pwc |
| 112 |
case fwc: |
| 113 |
n = l.fwc |
| 114 |
sfwc = true |
| 115 |
default: |
| 116 |
n = l.nodes[t] |
| 117 |
} |
| 118 |
} |
| 119 |
if n == nil { |
| 120 |
n = newNode[T]() |
| 121 |
if lt > 1 { |
| 122 |
l.nodes[t] = n |
| 123 |
} else { |
| 124 |
switch t[0] { |
| 125 |
case pwc: |
| 126 |
l.pwc = n |
| 127 |
case fwc: |
| 128 |
l.fwc = n |
| 129 |
default: |
| 130 |
l.nodes[t] = n |
| 131 |
} |
| 132 |
} |
| 133 |
} |
| 134 |
if n.next == nil { |
| 135 |
n.next = newLevel[T]() |
| 136 |
} |
| 137 |
l = n.next |
| 138 |
} |
| 139 |
|
| 140 |
n.subs[value] = subject |
| 141 |
|
| 142 |
s.count++ |
| 143 |
s.Unlock() |
| 144 |
|
| 145 |
return nil |
| 146 |
} |
| 147 |
|
| 148 |
// Match will match all entries to the literal subject. |
| 149 |
// It will return a set of results for both normal and queue subscribers. |
| 150 |
func (s *GenericSublist[T]) Match(subject string, cb func(T)) { |
| 151 |
s.match(subject, cb, true) |
| 152 |
} |
| 153 |
|
| 154 |
// MatchBytes will match all entries to the literal subject. |
| 155 |
// It will return a set of results for both normal and queue subscribers. |
| 156 |
func (s *GenericSublist[T]) MatchBytes(subject []byte, cb func(T)) { |
| 157 |
s.match(string(subject), cb, true) |
| 158 |
} |
| 159 |
|
| 160 |
// HasInterest will return whether or not there is any interest in the subject. |
| 161 |
// In cases where more detail is not required, this may be faster than Match. |
| 162 |
func (s *GenericSublist[T]) HasInterest(subject string) bool { |
| 163 |
return s.hasInterest(subject, true, nil) |
| 164 |
} |
| 165 |
|
| 166 |
// NumInterest will return the number of subs interested in the subject. |
| 167 |
// In cases where more detail is not required, this may be faster than Match. |
| 168 |
func (s *GenericSublist[T]) NumInterest(subject string) (np int) { |
| 169 |
s.hasInterest(subject, true, &np) |
| 170 |
return |
| 171 |
} |
| 172 |
|
| 173 |
// MatchesFullWildcard returns true if there is top-level ">" interest. |
| 174 |
func (s *GenericSublist[T]) MatchesFullWildcard() bool { |
| 175 |
if s == nil { |
| 176 |
return false |
| 177 |
} |
| 178 |
s.RLock() |
| 179 |
defer s.RUnlock() |
| 180 |
return s.root.fwc != nil |
| 181 |
} |
| 182 |
|
| 183 |
// MatchesSingleFilter returns the filter when the sublist contains exactly one unique subject. |
| 184 |
func (s *GenericSublist[T]) MatchesSingleFilter() (string, bool) { |
| 185 |
if s == nil { |
| 186 |
return _EMPTY_, false |
| 187 |
} |
| 188 |
s.RLock() |
| 189 |
defer s.RUnlock() |
| 190 |
return singleFilter(s.root, _EMPTY_) |
| 191 |
} |
| 192 |
|
| 193 |
func singleFilter[T comparable](l *level[T], filter string) (string, bool) { |
| 194 |
if l == nil { |
| 195 |
return filter, filter != _EMPTY_ |
| 196 |
} |
| 197 |
if len(l.nodes) > 1 { |
| 198 |
return _EMPTY_, false |
| 199 |
} |
| 200 |
var next *node[T] |
| 201 |
branches := 0 |
| 202 |
if l.pwc != nil { |
| 203 |
next = l.pwc |
| 204 |
branches++ |
| 205 |
} |
| 206 |
if l.fwc != nil { |
| 207 |
next = l.fwc |
| 208 |
branches++ |
| 209 |
} |
| 210 |
for _, n := range l.nodes { |
| 211 |
next = n |
| 212 |
branches++ |
| 213 |
} |
| 214 |
if branches != 1 { |
| 215 |
return _EMPTY_, false |
| 216 |
} |
| 217 |
for _, subj := range next.subs { |
| 218 |
filter = subj |
| 219 |
break |
| 220 |
} |
| 221 |
if next.next == nil { |
| 222 |
return filter, filter != _EMPTY_ |
| 223 |
} |
| 224 |
if filter != _EMPTY_ { |
| 225 |
if next.next.numNodes() > 0 { |
| 226 |
return _EMPTY_, false |
| 227 |
} |
| 228 |
return filter, true |
| 229 |
} |
| 230 |
return singleFilter(next.next, filter) |
| 231 |
} |
| 232 |
|
| 233 |
func (s *GenericSublist[T]) match(subject string, cb func(T), doLock bool) { |
| 234 |
tsa := [32]string{} |
| 235 |
tokens := tsa[:0] |
| 236 |
start := 0 |
| 237 |
for i := 0; i < len(subject); i++ { |
| 238 |
if subject[i] == btsep { |
| 239 |
if i-start == 0 { |
| 240 |
return |
| 241 |
} |
| 242 |
tokens = append(tokens, subject[start:i]) |
| 243 |
start = i + 1 |
| 244 |
} |
| 245 |
} |
| 246 |
if start >= len(subject) { |
| 247 |
return |
| 248 |
} |
| 249 |
tokens = append(tokens, subject[start:]) |
| 250 |
|
| 251 |
if doLock { |
| 252 |
s.RLock() |
| 253 |
defer s.RUnlock() |
| 254 |
} |
| 255 |
matchLevel(s.root, tokens, cb) |
| 256 |
} |
| 257 |
|
| 258 |
func (s *GenericSublist[T]) hasInterest(subject string, doLock bool, np *int) bool { |
| 259 |
tsa := [32]string{} |
| 260 |
tokens := tsa[:0] |
| 261 |
start := 0 |
| 262 |
for i := 0; i < len(subject); i++ { |
| 263 |
if subject[i] == btsep { |
| 264 |
if i-start == 0 { |
| 265 |
return false |
| 266 |
} |
| 267 |
tokens = append(tokens, subject[start:i]) |
| 268 |
start = i + 1 |
| 269 |
} |
| 270 |
} |
| 271 |
if start >= len(subject) { |
| 272 |
return false |
| 273 |
} |
| 274 |
tokens = append(tokens, subject[start:]) |
| 275 |
|
| 276 |
if doLock { |
| 277 |
s.RLock() |
| 278 |
defer s.RUnlock() |
| 279 |
} |
| 280 |
return matchLevelForAny(s.root, tokens, np) |
| 281 |
} |
| 282 |
|
| 283 |
func matchLevelForAny[T comparable](l *level[T], toks []string, np *int) bool { |
| 284 |
var pwc, n *node[T] |
| 285 |
for i, t := range toks { |
| 286 |
if l == nil { |
| 287 |
return false |
| 288 |
} |
| 289 |
if l.fwc != nil { |
| 290 |
if np != nil { |
| 291 |
*np += len(l.fwc.subs) |
| 292 |
} |
| 293 |
return true |
| 294 |
} |
| 295 |
if pwc = l.pwc; pwc != nil { |
| 296 |
if match := matchLevelForAny(pwc.next, toks[i+1:], np); match { |
| 297 |
return true |
| 298 |
} |
| 299 |
} |
| 300 |
n = l.nodes[t] |
| 301 |
if n != nil { |
| 302 |
l = n.next |
| 303 |
} else { |
| 304 |
l = nil |
| 305 |
} |
| 306 |
} |
| 307 |
if n != nil { |
| 308 |
if np != nil { |
| 309 |
*np += len(n.subs) |
| 310 |
} |
| 311 |
if len(n.subs) > 0 { |
| 312 |
return true |
| 313 |
} |
| 314 |
} |
| 315 |
if pwc != nil { |
| 316 |
if np != nil { |
| 317 |
*np += len(pwc.subs) |
| 318 |
} |
| 319 |
return len(pwc.subs) > 0 |
| 320 |
} |
| 321 |
return false |
| 322 |
} |
| 323 |
|
| 324 |
// callbacksForResults will make the necessary callbacks for each |
| 325 |
// result in this node. |
| 326 |
func callbacksForResults[T comparable](n *node[T], cb func(T)) { |
| 327 |
for sub := range n.subs { |
| 328 |
cb(sub) |
| 329 |
} |
| 330 |
} |
| 331 |
|
| 332 |
// matchLevel is used to recursively descend into the trie. |
| 333 |
func matchLevel[T comparable](l *level[T], toks []string, cb func(T)) { |
| 334 |
var pwc, n *node[T] |
| 335 |
for i, t := range toks { |
| 336 |
if l == nil { |
| 337 |
return |
| 338 |
} |
| 339 |
if l.fwc != nil { |
| 340 |
callbacksForResults(l.fwc, cb) |
| 341 |
} |
| 342 |
if pwc = l.pwc; pwc != nil { |
| 343 |
matchLevel(pwc.next, toks[i+1:], cb) |
| 344 |
} |
| 345 |
n = l.nodes[t] |
| 346 |
if n != nil { |
| 347 |
l = n.next |
| 348 |
} else { |
| 349 |
l = nil |
| 350 |
} |
| 351 |
} |
| 352 |
if n != nil { |
| 353 |
callbacksForResults(n, cb) |
| 354 |
} |
| 355 |
if pwc != nil { |
| 356 |
callbacksForResults(pwc, cb) |
| 357 |
} |
| 358 |
} |
| 359 |
|
| 360 |
// lnt is used to track descent into levels for a removal for pruning. |
| 361 |
type lnt[T comparable] struct { |
| 362 |
l *level[T] |
| 363 |
n *node[T] |
| 364 |
t string |
| 365 |
} |
| 366 |
|
| 367 |
// Raw low level remove, can do batches with lock held outside. |
| 368 |
func (s *GenericSublist[T]) remove(subject string, value T, shouldLock bool) error { |
| 369 |
if shouldLock { |
| 370 |
s.Lock() |
| 371 |
defer s.Unlock() |
| 372 |
} |
| 373 |
|
| 374 |
var sfwc bool |
| 375 |
var n *node[T] |
| 376 |
l := s.root |
| 377 |
|
| 378 |
// Track levels for pruning |
| 379 |
var lnts [32]lnt[T] |
| 380 |
levels := lnts[:0] |
| 381 |
|
| 382 |
for t := range strings.SplitSeq(subject, tsep) { |
| 383 |
lt := len(t) |
| 384 |
if lt == 0 || sfwc { |
| 385 |
return ErrInvalidSubject |
| 386 |
} |
| 387 |
if l == nil { |
| 388 |
return ErrNotFound |
| 389 |
} |
| 390 |
if lt > 1 { |
| 391 |
n = l.nodes[t] |
| 392 |
} else { |
| 393 |
switch t[0] { |
| 394 |
case pwc: |
| 395 |
n = l.pwc |
| 396 |
case fwc: |
| 397 |
n = l.fwc |
| 398 |
sfwc = true |
| 399 |
default: |
| 400 |
n = l.nodes[t] |
| 401 |
} |
| 402 |
} |
| 403 |
if n != nil { |
| 404 |
levels = append(levels, lnt[T]{l, n, t}) |
| 405 |
l = n.next |
| 406 |
} else { |
| 407 |
l = nil |
| 408 |
} |
| 409 |
} |
| 410 |
|
| 411 |
if !s.removeFromNode(n, value) { |
| 412 |
return ErrNotFound |
| 413 |
} |
| 414 |
|
| 415 |
s.count-- |
| 416 |
|
| 417 |
for i := len(levels) - 1; i >= 0; i-- { |
| 418 |
l, n, t := levels[i].l, levels[i].n, levels[i].t |
| 419 |
if n.isEmpty() { |
| 420 |
l.pruneNode(n, t) |
| 421 |
} |
| 422 |
} |
| 423 |
|
| 424 |
return nil |
| 425 |
} |
| 426 |
|
| 427 |
// Remove will remove a subscription. |
| 428 |
func (s *GenericSublist[T]) Remove(subject string, value T) error { |
| 429 |
return s.remove(subject, value, true) |
| 430 |
} |
| 431 |
|
| 432 |
// HasInterestStartingIn is a helper for subject tree intersection. |
| 433 |
func (s *GenericSublist[T]) HasInterestStartingIn(subj string) bool { |
| 434 |
s.RLock() |
| 435 |
defer s.RUnlock() |
| 436 |
var _tokens [64]string |
| 437 |
tokens := tokenizeSubjectIntoSlice(_tokens[:0], subj) |
| 438 |
return hasInterestStartingIn(s.root, tokens) |
| 439 |
} |
| 440 |
|
| 441 |
func hasInterestStartingIn[T comparable](l *level[T], tokens []string) bool { |
| 442 |
if l == nil { |
| 443 |
return false |
| 444 |
} |
| 445 |
if len(tokens) == 0 { |
| 446 |
return true |
| 447 |
} |
| 448 |
token := tokens[0] |
| 449 |
if l.fwc != nil { |
| 450 |
return true |
| 451 |
} |
| 452 |
found := false |
| 453 |
if pwc := l.pwc; pwc != nil { |
| 454 |
found = found || hasInterestStartingIn(pwc.next, tokens[1:]) |
| 455 |
} |
| 456 |
if n := l.nodes[token]; n != nil { |
| 457 |
found = found || hasInterestStartingIn(n.next, tokens[1:]) |
| 458 |
} |
| 459 |
return found |
| 460 |
} |
| 461 |
|
| 462 |
// pruneNode is used to prune an empty node from the tree. |
| 463 |
func (l *level[T]) pruneNode(n *node[T], t string) { |
| 464 |
if n == nil { |
| 465 |
return |
| 466 |
} |
| 467 |
if n == l.fwc { |
| 468 |
l.fwc = nil |
| 469 |
} else if n == l.pwc { |
| 470 |
l.pwc = nil |
| 471 |
} else { |
| 472 |
delete(l.nodes, t) |
| 473 |
} |
| 474 |
} |
| 475 |
|
| 476 |
// isEmpty will test if the node has any entries. Used |
| 477 |
// in pruning. |
| 478 |
func (n *node[T]) isEmpty() bool { |
| 479 |
return len(n.subs) == 0 && (n.next == nil || n.next.numNodes() == 0) |
| 480 |
} |
| 481 |
|
| 482 |
// Return the number of nodes for the given level. |
| 483 |
func (l *level[T]) numNodes() int { |
| 484 |
if l == nil { |
| 485 |
return 0 |
| 486 |
} |
| 487 |
num := len(l.nodes) |
| 488 |
if l.pwc != nil { |
| 489 |
num++ |
| 490 |
} |
| 491 |
if l.fwc != nil { |
| 492 |
num++ |
| 493 |
} |
| 494 |
return num |
| 495 |
} |
| 496 |
|
| 497 |
// Remove the sub for the given node. |
| 498 |
func (s *GenericSublist[T]) removeFromNode(n *node[T], value T) (found bool) { |
| 499 |
if n == nil { |
| 500 |
return false |
| 501 |
} |
| 502 |
if _, found = n.subs[value]; found { |
| 503 |
delete(n.subs, value) |
| 504 |
} |
| 505 |
return found |
| 506 |
} |
| 507 |
|
| 508 |
// Count returns the number of subscriptions. |
| 509 |
func (s *GenericSublist[T]) Count() uint32 { |
| 510 |
s.RLock() |
| 511 |
defer s.RUnlock() |
| 512 |
return s.count |
| 513 |
} |
| 514 |
|
| 515 |
// numLevels will return the maximum number of levels |
| 516 |
// contained in the Sublist tree. |
| 517 |
func (s *GenericSublist[T]) numLevels() int { |
| 518 |
return visitLevel(s.root, 0) |
| 519 |
} |
| 520 |
|
| 521 |
// visitLevel is used to descend the Sublist tree structure |
| 522 |
// recursively. |
| 523 |
func visitLevel[T comparable](l *level[T], depth int) int { |
| 524 |
if l == nil || l.numNodes() == 0 { |
| 525 |
return depth |
| 526 |
} |
| 527 |
|
| 528 |
depth++ |
| 529 |
maxDepth := depth |
| 530 |
|
| 531 |
for _, n := range l.nodes { |
| 532 |
if n == nil { |
| 533 |
continue |
| 534 |
} |
| 535 |
newDepth := visitLevel(n.next, depth) |
| 536 |
if newDepth > maxDepth { |
| 537 |
maxDepth = newDepth |
| 538 |
} |
| 539 |
} |
| 540 |
if l.pwc != nil { |
| 541 |
pwcDepth := visitLevel(l.pwc.next, depth) |
| 542 |
if pwcDepth > maxDepth { |
| 543 |
maxDepth = pwcDepth |
| 544 |
} |
| 545 |
} |
| 546 |
if l.fwc != nil { |
| 547 |
fwcDepth := visitLevel(l.fwc.next, depth) |
| 548 |
if fwcDepth > maxDepth { |
| 549 |
maxDepth = fwcDepth |
| 550 |
} |
| 551 |
} |
| 552 |
return maxDepth |
| 553 |
} |
| 554 |
|
| 555 |
// use similar to append. meaning, the updated slice will be returned |
| 556 |
func tokenizeSubjectIntoSlice(tts []string, subject string) []string { |
| 557 |
start := 0 |
| 558 |
for i := 0; i < len(subject); i++ { |
| 559 |
if subject[i] == btsep { |
| 560 |
tts = append(tts, subject[start:i]) |
| 561 |
start = i + 1 |
| 562 |
} |
| 563 |
} |
| 564 |
tts = append(tts, subject[start:]) |
| 565 |
return tts |
| 566 |
} |