-
Notifications
You must be signed in to change notification settings - Fork 8
/
interceptors.go
71 lines (58 loc) · 1.78 KB
/
interceptors.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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package servercore
import (
"fmt"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
"github.com/philopon/go-toposort"
"google.golang.org/grpc"
"namespacelabs.dev/foundation/std/go/core"
"namespacelabs.dev/foundation/std/go/grpc/interceptors"
"namespacelabs.dev/foundation/std/grpc/requestid"
)
func OrderedServerInterceptors() []grpc.ServerOption {
registrations := interceptors.ServerInterceptors()
var rid requestid.Interceptor
registrations = append(registrations, interceptors.Registered{
Name: "namespace-rid",
After: []string{"otel-tracing"},
Unary: rid.Unary,
Stream: rid.Streaming,
})
graph := toposort.NewGraph(len(registrations))
names := make([]string, len(registrations))
index := map[string]int{}
for k, reg := range registrations {
name := reg.Name
if name == "" {
name = fmt.Sprintf("$interceptor_%d", k)
}
names[k] = name
index[name] = k
graph.AddNode(name)
}
for k, reg := range registrations {
for _, after := range reg.After {
if _, ok := index[after]; ok {
graph.AddEdge(after, names[k])
}
}
}
sorted, ok := graph.Toposort()
if !ok {
panic("loop in interceptor order")
}
core.ZLog.Debug().Strs("interceptors", sorted).Send()
var coreU []grpc.UnaryServerInterceptor
var coreS []grpc.StreamServerInterceptor
for _, key := range sorted {
reg := registrations[index[key]]
coreU = append(coreU, reg.Unary)
coreS = append(coreS, reg.Stream)
}
return []grpc.ServerOption{
grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(coreS...)),
grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(coreU...)),
}
}