forked from grafana/k6
/
grpc.go
81 lines (70 loc) · 2.37 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
package grpc
import (
"github.com/dop251/goja"
"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{}
}
)
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 {
mi := &ModuleInstance{
vu: vu,
exports: make(map[string]interface{}),
}
mi.exports["Client"] = mi.NewClient
mi.defineConstants()
return mi
}
// NewClient is the JS constructor for the grpc Client.
func (mi *ModuleInstance) NewClient(call 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,
}
}