-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.go
336 lines (279 loc) · 7.68 KB
/
router.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
package natsrouter
import (
"errors"
"fmt"
"github.com/nats-io/nats.go"
"regexp"
"sort"
"strconv"
"strings"
"sync"
)
// Handle is a function that can be registered to a route to handle NATS
// requests. It has a third parameter for the values of wildcards (path variables).
type Handle func(*nats.Msg, Params, interface{})
// Param is a single parameter, consisting of a key and a value.
type Param struct {
Key string
Value string
}
// Params is a Param-slice, as returned by the router.
// The slice is ordered, the first TOPIC parameter is also the first slice value.
// It is therefore safe to read values by the index.
type Params []Param
// ByName returns the value of the first Param which key matches the given name.
// If no matching Param is found, an empty string is returned.
func (ps Params) ByName(name string) string {
for _, p := range ps {
if p.Key == name {
return p.Value
}
}
return ""
}
var (
reNATSPathCatchAll = regexp.MustCompile(`(.*)\.>$`)
reNATSPathToken = regexp.MustCompile(`(\.\*)`)
)
const subsNATSPath = "$1.*>"
func fromNatsPath(path string) string {
i := 0
path = reNATSPathToken.ReplaceAllStringFunc(path, func(string) string {
i++
return fmt.Sprintf(".:p%d", i)
})
result := reNATSPathCatchAll.ReplaceAllString(path, subsNATSPath)
return result
}
// MatchedRoutePathParam is the Param name under which the path of the matched
// route is stored, if Router.SaveMatchedRoutePath is set.
var MatchedRoutePathParam = "$matchedRoutePath" //nolint
// MatchedRoutePath retrieves the path of the matched route.
// Router.SaveMatchedRoutePath must have been enabled when the respective
// handler was added, otherwise this function always returns an empty string.
func (ps Params) MatchedRoutePath() string {
return ps.ByName(MatchedRoutePathParam)
}
// Router is a handler which can be used to dispatch requests to different
// handler functions via configurable routes
type Router struct {
trees map[int]*node
// rank map start from priority 1 to max 255
paramsPool sync.Pool
maxParams uint16
// If enabled, adds the matched route path onto the request context
// before invoking the handler.
// The matched route path is only added to handlers of routes that were
// registered when this option was enabled.
SaveMatchedRoutePath bool
// Cached value of global (*) allowed ranks
globalAllowed string
// sorted rank list
rankIndexList []int
initialized bool
// Function to handle panics recovered from NATS handlers.
// The handler can be used to keep your server from crashing because of
// unrecovered panics.
PanicHandler func(*nats.Msg, interface{})
}
// New returns a new initialized Router.
// Path auto-correction, including trailing slashes, is enabled by default.
func New() *Router {
return &Router{
initialized: false,
rankIndexList: make([]int, 0, 5),
}
}
func (r *Router) getParams() *Params {
if ps, ok := r.paramsPool.Get().(*Params); ok {
*ps = (*ps)[0:0] // reset slice
return ps
}
return nil
}
func (r *Router) putParams(ps *Params) {
if ps != nil {
r.paramsPool.Put(ps)
}
}
func (r *Router) saveMatchedRoutePath(path string, handle Handle) Handle {
return func(msg *nats.Msg, ps Params, payload interface{}) {
if ps == nil {
psp := r.getParams()
ps := (*psp)[0:1]
ps[0] = Param{Key: MatchedRoutePathParam, Value: path}
handle(msg, ps, payload)
r.putParams(psp)
} else {
ps = append(ps, Param{Key: MatchedRoutePathParam, Value: path})
handle(msg, ps, payload)
}
}
}
// Handle registers a new request handle with the given path.
func (r *Router) Handle(path string, rank int, handle Handle) {
varsCount := uint16(0)
if rank <= 0 || rank > 255 {
panic("rank must be > 0")
}
if handle == nil {
panic("handle must not be nil")
}
path = fromNatsPath(path)
if r.SaveMatchedRoutePath {
varsCount++
handle = r.saveMatchedRoutePath(path, handle)
}
if r.trees == nil {
r.trees = make(map[int]*node)
}
root := r.trees[rank]
if root == nil {
root = new(node)
r.trees[rank] = root
r.globalAllowed = r.allowed("*", 0)
}
root.addRoute(path, handle)
// Update maxParams
if paramsCount := countParams(path); paramsCount+varsCount > r.maxParams {
r.maxParams = paramsCount + varsCount
}
// Lazy-init paramsPool alloc func
if r.paramsPool.New == nil && r.maxParams > 0 {
r.paramsPool.New = func() interface{} {
ps := make(Params, 0, r.maxParams)
return &ps
}
}
}
// Lookup allows the manual lookup of a rank + path combo.
// This is e.g. useful to build a framework around this router.
// If the path was found, it returns the handle function and the path parameter
// values.
func (r *Router) Lookup(path string, rank int) (Handle, Params, bool) {
if root := r.trees[rank]; root != nil {
handle, ps, tsr := root.getValue(path, r.getParams)
if handle == nil {
r.putParams(ps)
return nil, nil, tsr
}
if ps == nil {
return handle, nil, tsr
}
return handle, *ps, tsr
}
return nil, nil, false
}
func (r *Router) allowed(path string, reqRank int) (allow string) {
allowed := make([]int, 0, 9)
if path == "*" { // server-wide
// 0 rank is used for internal calls to refresh the cache
if reqRank == 0 {
for rank := range r.trees {
// Add request rank to list of allowed ranks
allowed = append(allowed, rank)
}
} else {
return r.globalAllowed
}
} else { // specific path
for rank := range r.trees {
// Skip the requested rank - we already tried this one
if rank == reqRank {
continue
}
handle, _, _ := r.trees[rank].getValue(path, nil)
if handle != nil {
// Add request rank to list of allowed ranks
allowed = append(allowed, rank)
}
}
}
if len(allowed) > 0 {
// Sort allowed ranks.
// sort.Strings(allowed) unfortunately causes unnecessary allocations
// due to allowed being moved to the heap and interface conversion
for i, l := 1, len(allowed); i < l; i++ {
for j := i; j > 0 && allowed[j] < allowed[j-1]; j-- {
allowed[j], allowed[j-1] = allowed[j-1], allowed[j]
}
}
// return as comma separated list
allowedStr := []string{}
for i := range allowed {
prio := allowed[i]
ptxt := strconv.Itoa(prio)
allowedStr = append(allowedStr, ptxt)
}
return strings.Join(allowedStr, ", ")
}
return ""
}
func (r *Router) recv(msg *nats.Msg) {
if rcv := recover(); rcv != nil {
r.PanicHandler(msg, rcv)
}
}
func (r *Router) getRankList() []int {
if !r.initialized {
for rank := range r.trees {
r.rankIndexList = append(r.rankIndexList, rank)
}
sort.Ints(r.rankIndexList)
r.initialized = true
}
return r.rankIndexList
}
// ServeNATS makes the router implement interface.
func (r *Router) ServeNATS(msg *nats.Msg) error {
if r.PanicHandler != nil {
defer r.recv(msg)
}
path := msg.Subject
rankList := r.getRankList()
for _, rank := range rankList {
if root := r.trees[rank]; root != nil {
if handle, ps, _ := root.getValue(path, r.getParams); handle != nil {
if ps != nil {
go func() {
handle(msg, *ps, nil)
r.putParams(ps)
}()
} else {
go func() {
handle(msg, nil, nil)
}()
}
return nil
}
}
}
// Handle 404
return errors.New("404 NotFound")
}
func (r *Router) ServeNATSWithPayload(msg *nats.Msg, payload interface{}) error {
if r.PanicHandler != nil {
defer r.recv(msg)
}
path := msg.Subject
rankList := r.getRankList()
for _, rank := range rankList {
if root := r.trees[rank]; root != nil {
if handle, ps, _ := root.getValue(path, r.getParams); handle != nil {
if ps != nil {
go func() {
handle(msg, *ps, payload)
r.putParams(ps)
}()
} else {
go func() {
handle(msg, nil, payload)
}()
}
return nil
}
}
}
// Handle 404
return errors.New("404 NotFound")
}