forked from grafana/xk6-grpc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
grpc.go
171 lines (138 loc) · 4.57 KB
/
grpc.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
// Package grpc is the root module of the k6-grpc extension.
package grpc
import (
"errors"
"fmt"
"github.com/dop251/goja"
"github.com/mstoykov/k6-taskqueue-lib/taskqueue"
"go.k6.io/k6/js/common"
"go.k6.io/k6/js/modules"
"google.golang.org/grpc/codes"
)
type (
// RootModule is the global module instance that will create module
// instances for each VU.
RootModule struct{}
// ModuleInstance represents an instance of the GRPC module for every VU.
ModuleInstance struct {
vu modules.VU
exports map[string]interface{}
metrics *instanceMetrics
}
)
var (
_ modules.Module = &RootModule{}
_ modules.Instance = &ModuleInstance{}
)
// New returns a pointer to a new RootModule instance.
func New() *RootModule {
return &RootModule{}
}
// NewModuleInstance implements the modules.Module interface to return
// a new instance for each VU.
func (*RootModule) NewModuleInstance(vu modules.VU) modules.Instance {
metrics, err := registerMetrics(vu.InitEnv().Registry)
if err != nil {
common.Throw(vu.Runtime(), fmt.Errorf("failed to register GRPC module metrics: %w", err))
}
mi := &ModuleInstance{
vu: vu,
exports: make(map[string]interface{}),
metrics: metrics,
}
mi.exports["Client"] = mi.NewClient
mi.defineConstants()
mi.exports["Stream"] = mi.stream
return mi
}
// NewClient is the JS constructor for the grpc Client.
func (mi *ModuleInstance) NewClient(_ goja.ConstructorCall) *goja.Object {
rt := mi.vu.Runtime()
return rt.ToValue(&Client{vu: mi.vu}).ToObject(rt)
}
// defineConstants defines the constant variables of the module.
func (mi *ModuleInstance) defineConstants() {
rt := mi.vu.Runtime()
mustAddCode := func(name string, code codes.Code) {
mi.exports[name] = rt.ToValue(code)
}
mustAddCode("StatusOK", codes.OK)
mustAddCode("StatusCanceled", codes.Canceled)
mustAddCode("StatusUnknown", codes.Unknown)
mustAddCode("StatusInvalidArgument", codes.InvalidArgument)
mustAddCode("StatusDeadlineExceeded", codes.DeadlineExceeded)
mustAddCode("StatusNotFound", codes.NotFound)
mustAddCode("StatusAlreadyExists", codes.AlreadyExists)
mustAddCode("StatusPermissionDenied", codes.PermissionDenied)
mustAddCode("StatusResourceExhausted", codes.ResourceExhausted)
mustAddCode("StatusFailedPrecondition", codes.FailedPrecondition)
mustAddCode("StatusAborted", codes.Aborted)
mustAddCode("StatusOutOfRange", codes.OutOfRange)
mustAddCode("StatusUnimplemented", codes.Unimplemented)
mustAddCode("StatusInternal", codes.Internal)
mustAddCode("StatusUnavailable", codes.Unavailable)
mustAddCode("StatusDataLoss", codes.DataLoss)
mustAddCode("StatusUnauthenticated", codes.Unauthenticated)
}
// Exports returns the exports of the grpc module.
func (mi *ModuleInstance) Exports() modules.Exports {
return modules.Exports{
Named: mi.exports,
}
}
// stream returns a new stream object
func (mi *ModuleInstance) stream(c goja.ConstructorCall) *goja.Object {
rt := mi.vu.Runtime()
client, err := extractClient(c.Argument(0), rt)
if err != nil {
common.Throw(rt, fmt.Errorf("invalid GRPC Stream's client: %w", err))
}
methodName := sanitizeMethodName(c.Argument(1).String())
methodDescriptor, err := client.getMethodDescriptor(methodName)
if err != nil {
common.Throw(rt, fmt.Errorf("invalid GRPC Stream's method: %w", err))
}
p, err := newCallParams(mi.vu, c.Argument(2))
if err != nil {
common.Throw(rt, fmt.Errorf("invalid GRPC Stream's parameters: %w", err))
}
p.SetSystemTags(mi.vu.State(), client.addr, methodName)
logger := mi.vu.State().Logger.WithField("streamMethod", methodName)
s := &stream{
vu: mi.vu,
client: client,
methodDescriptor: methodDescriptor,
method: methodName,
logger: logger,
tq: taskqueue.New(mi.vu.RegisterCallback),
instanceMetrics: mi.metrics,
builtinMetrics: mi.vu.State().BuiltinMetrics,
done: make(chan struct{}),
writingState: opened,
writeQueueCh: make(chan message),
eventListeners: newEventListeners(),
obj: rt.NewObject(),
tagsAndMeta: &p.TagsAndMeta,
}
defineStream(rt, s)
err = s.beginStream(p)
if err != nil {
s.tq.Close()
common.Throw(rt, err)
}
return s.obj
}
// extractClient extracts & validates a grpc.Client from a goja.Value.
func extractClient(v goja.Value, rt *goja.Runtime) (*Client, error) {
if common.IsNullish(v) {
return nil, errors.New("empty gRPC client")
}
client, ok := v.ToObject(rt).Export().(*Client)
if !ok {
return nil, errors.New("not a gRPC client")
}
if client.conn == nil {
return nil, errors.New("no gRPC connection, you must call connect first")
}
return client, nil
}