/
server_reflection.go
219 lines (184 loc) ยท 4.48 KB
/
server_reflection.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
package reflection
import (
"bytes"
"context"
"fmt"
"path/filepath"
"reflect"
"strings"
"text/template"
"unicode"
"unicode/utf8"
"github.com/ChimeraCoder/gojson"
jsoniter "github.com/json-iterator/go"
"github.com/smallnest/rpcx/log"
)
var (
typeOfError = reflect.TypeOf((*error)(nil)).Elem()
typeOfContext = reflect.TypeOf((*context.Context)(nil)).Elem()
)
var json = jsoniter.Config{
TagKey: "-",
}.Froze()
// ServiceInfo service info.
type ServiceInfo struct {
Name string
PkgPath string
Methods []*MethodInfo
}
// MethodInfo method info
type MethodInfo struct {
Name string
ReqName string
Req string
ReplyName string
Reply string
}
var siTemplate = `package {{.PkgPath}}
type {{.Name}} struct{}
{{$name := .Name}}
{{range .Methods}}
{{.Req}}
{{.Reply}}
type (s *{{$name}}) {{.Name}}(ctx context.Context, arg *{{.ReqName}}, reply *{{.ReplyName}}) error {
return nil
}
{{end}}
`
func (si ServiceInfo) String() string {
tpl := template.Must(template.New("service").Parse(siTemplate))
var buf bytes.Buffer
_ = tpl.Execute(&buf, si)
return buf.String()
}
type Reflection struct {
Services map[string]*ServiceInfo
}
func New() *Reflection {
return &Reflection{
Services: make(map[string]*ServiceInfo),
}
}
func (r *Reflection) Register(name string, rcvr interface{}, metadata string) error {
si := &ServiceInfo{}
val := reflect.ValueOf(rcvr)
typ := reflect.TypeOf(rcvr)
vTyp := reflect.Indirect(val).Type()
si.Name = vTyp.Name()
pkg := vTyp.PkgPath()
if strings.Index(pkg, ".") > 0 {
pkg = pkg[strings.LastIndex(pkg, ".")+1:]
}
pkg = filepath.Base(pkg)
pkg = strings.ReplaceAll(pkg, "-", "_")
si.PkgPath = pkg
for m := 0; m < val.NumMethod(); m++ {
method := typ.Method(m)
mtype := method.Type
if method.PkgPath != "" {
continue
}
if mtype.NumIn() != 4 {
continue
}
// First arg must be context.Context
ctxType := mtype.In(1)
if !ctxType.Implements(typeOfContext) {
continue
}
// Second arg need not be a pointer.
argType := mtype.In(2)
if !isExportedOrBuiltinType(argType) {
continue
}
// Third arg must be a pointer.
replyType := mtype.In(3)
if replyType.Kind() != reflect.Ptr {
continue
}
// Reply type must be exported.
if !isExportedOrBuiltinType(replyType) {
continue
}
// Method needs one out.
if mtype.NumOut() != 1 {
continue
}
// The return type of the method must be error.
if returnType := mtype.Out(0); returnType != typeOfError {
continue
}
mi := &MethodInfo{}
mi.Name = method.Name
if argType.Kind() == reflect.Ptr {
argType = argType.Elem()
}
replyType = replyType.Elem()
mi.ReqName = argType.Name()
mi.Req = generateTypeDefination(mi.ReqName, si.PkgPath, generateJSON(argType))
mi.ReplyName = replyType.Name()
mi.Reply = generateTypeDefination(mi.ReplyName, si.PkgPath, generateJSON(replyType))
si.Methods = append(si.Methods, mi)
}
if len(si.Methods) > 0 {
r.Services[name] = si
}
return nil
}
func (r *Reflection) Unregister(name string) error {
delete(r.Services, name)
return nil
}
func (r *Reflection) GetService(ctx context.Context, s string, reply *string) error {
si, ok := r.Services[s]
if !ok {
return fmt.Errorf("not found service %s", s)
}
*reply = si.String()
return nil
}
func (r *Reflection) GetServices(ctx context.Context, s string, reply *string) error {
var buf bytes.Buffer
pkg := `package `
for _, si := range r.Services {
if pkg == `package ` {
pkg = pkg + si.PkgPath + "\n\n"
}
buf.WriteString(strings.ReplaceAll(si.String(), pkg, ""))
}
if pkg != `package ` {
*reply = pkg + buf.String()
} else {
*reply = buf.String()
}
return nil
}
func generateTypeDefination(name, pkg string, jsonValue string) string {
jsonValue = strings.TrimSpace(jsonValue)
if jsonValue == "" || jsonValue == `""` {
return ""
}
r := strings.NewReader(jsonValue)
output, err := gojson.Generate(r, gojson.ParseJson, name, pkg, nil, false, true)
if err != nil {
log.Errorf("failed to generate json: %v", err)
return ""
}
rt := strings.ReplaceAll(string(output), "``", "")
return strings.ReplaceAll(rt, "package "+pkg+"\n\n", "")
}
func generateJSON(typ reflect.Type) string {
v := reflect.New(typ).Interface()
data, _ := json.Marshal(v)
return string(data)
}
func isExported(name string) bool {
rune, _ := utf8.DecodeRuneInString(name)
return unicode.IsUpper(rune)
}
func isExportedOrBuiltinType(t reflect.Type) bool {
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
return isExported(t.Name()) || t.PkgPath() == ""
}