How to use Reflect method of grpcext Package

Best K6 code snippet using grpcext.Reflect

client.go

Source:client.go Github

copy

Full Screen

...91 c.conn, err = grpcext.Dial(ctx, addr, opts...)92 if err != nil {93 return false, err94 }95 if !p.UseReflectionProtocol {96 return true, nil97 }98 fdset, err := c.conn.Reflect(ctx)99 if err != nil {100 return false, err101 }102 _, err = c.convertToMethodInfo(fdset)103 if err != nil {104 return false, fmt.Errorf("can't convert method info: %w", err)105 }106 return true, err107}108// Invoke creates and calls a unary RPC by fully qualified method name109func (c *Client) Invoke(110 method string,111 req goja.Value,112 params map[string]interface{},113) (*grpcext.Response, error) {114 state := c.vu.State()115 if state == nil {116 return nil, common.NewInitContextError("invoking RPC methods in the init context is not supported")117 }118 if c.conn == nil {119 return nil, errors.New("no gRPC connection, you must call connect first")120 }121 if method == "" {122 return nil, errors.New("method to invoke cannot be empty")123 }124 if method[0] != '/' {125 method = "/" + method126 }127 methodDesc := c.mds[method]128 if methodDesc == nil {129 return nil, fmt.Errorf("method %q not found in file descriptors", method)130 }131 p, err := c.parseParams(params)132 if err != nil {133 return nil, err134 }135 b, err := req.ToObject(c.vu.Runtime()).MarshalJSON()136 if err != nil {137 return nil, fmt.Errorf("unable to serialise request object: %w", err)138 }139 md := metadata.New(nil)140 for param, strval := range p.Metadata {141 md.Append(param, strval)142 }143 ctx, cancel := context.WithTimeout(c.vu.Context(), p.Timeout)144 defer cancel()145 tags := state.CloneTags()146 for k, v := range p.Tags {147 tags[k] = v148 }149 if state.Options.SystemTags.Has(metrics.TagURL) {150 tags["url"] = fmt.Sprintf("%s%s", c.addr, method)151 }152 parts := strings.Split(method[1:], "/")153 if state.Options.SystemTags.Has(metrics.TagService) {154 tags["service"] = parts[0]155 }156 if state.Options.SystemTags.Has(metrics.TagMethod) {157 tags["method"] = parts[1]158 }159 // Only set the name system tag if the user didn't explicitly set it beforehand160 if _, ok := tags["name"]; !ok && state.Options.SystemTags.Has(metrics.TagName) {161 tags["name"] = method162 }163 reqmsg := grpcext.Request{164 MethodDescriptor: methodDesc,165 Message: b,166 Tags: tags,167 }168 return c.conn.Invoke(ctx, method, md, reqmsg)169}170// Close will close the client gRPC connection171func (c *Client) Close() error {172 if c.conn == nil {173 return nil174 }175 err := c.conn.Close()176 c.conn = nil177 return err178}179// MethodInfo holds information on any parsed method descriptors that can be used by the goja VM180type MethodInfo struct {181 Package string182 Service string183 FullMethod string184 grpc.MethodInfo `json:"-" js:"-"`185}186func (c *Client) convertToMethodInfo(fdset *descriptorpb.FileDescriptorSet) ([]MethodInfo, error) {187 files, err := protodesc.NewFiles(fdset)188 if err != nil {189 return nil, err190 }191 var rtn []MethodInfo192 if c.mds == nil {193 // This allows us to call load() multiple times, without overwriting the194 // previously loaded definitions.195 c.mds = make(map[string]protoreflect.MethodDescriptor)196 }197 appendMethodInfo := func(198 fd protoreflect.FileDescriptor,199 sd protoreflect.ServiceDescriptor,200 md protoreflect.MethodDescriptor,201 ) {202 name := fmt.Sprintf("/%s/%s", sd.FullName(), md.Name())203 c.mds[name] = md204 rtn = append(rtn, MethodInfo{205 MethodInfo: grpc.MethodInfo{206 Name: string(md.Name()),207 IsClientStream: md.IsStreamingClient(),208 IsServerStream: md.IsStreamingServer(),209 },210 Package: string(fd.Package()),211 Service: string(sd.Name()),212 FullMethod: name,213 })214 }215 files.RangeFiles(func(fd protoreflect.FileDescriptor) bool {216 sds := fd.Services()217 for i := 0; i < sds.Len(); i++ {218 sd := sds.Get(i)219 mds := sd.Methods()220 for j := 0; j < mds.Len(); j++ {221 md := mds.Get(j)222 appendMethodInfo(fd, sd, md)223 }224 }225 return true226 })227 return rtn, nil228}229type params struct {230 Metadata map[string]string231 Tags map[string]string232 Timeout time.Duration233}234func (c *Client) parseParams(raw map[string]interface{}) (params, error) {235 p := params{236 Timeout: 1 * time.Minute,237 }238 for k, v := range raw {239 switch k {240 case "headers":241 c.vu.State().Logger.Warn("The headers property is deprecated, replace it with the metadata property, please.")242 fallthrough243 case "metadata":244 p.Metadata = make(map[string]string)245 rawHeaders, ok := v.(map[string]interface{})246 if !ok {247 return p, errors.New("metadata must be an object with key-value pairs")248 }249 for hk, kv := range rawHeaders {250 // TODO(rogchap): Should we manage a string slice?251 strval, ok := kv.(string)252 if !ok {253 return p, fmt.Errorf("metadata %q value must be a string", hk)254 }255 p.Metadata[hk] = strval256 }257 case "tags":258 p.Tags = make(map[string]string)259 rawTags, ok := v.(map[string]interface{})260 if !ok {261 return p, errors.New("tags must be an object with key-value pairs")262 }263 for tk, tv := range rawTags {264 strVal, ok := tv.(string)265 if !ok {266 return p, fmt.Errorf("tag %q value must be a string", tk)267 }268 p.Tags[tk] = strVal269 }270 case "timeout":271 var err error272 p.Timeout, err = types.GetDurationValue(v)273 if err != nil {274 return p, fmt.Errorf("invalid timeout value: %w", err)275 }276 default:277 return p, fmt.Errorf("unknown param: %q", k)278 }279 }280 return p, nil281}282type connectParams struct {283 IsPlaintext bool284 UseReflectionProtocol bool285 Timeout time.Duration286}287func (c *Client) parseConnectParams(raw map[string]interface{}) (connectParams, error) {288 params := connectParams{289 IsPlaintext: false,290 UseReflectionProtocol: false,291 Timeout: time.Minute,292 }293 for k, v := range raw {294 switch k {295 case "plaintext":296 var ok bool297 params.IsPlaintext, ok = v.(bool)298 if !ok {299 return params, fmt.Errorf("invalid plaintext value: '%#v', it needs to be boolean", v)300 }301 case "timeout":302 var err error303 params.Timeout, err = types.GetDurationValue(v)304 if err != nil {305 return params, fmt.Errorf("invalid timeout value: %w", err)306 }307 case "reflect":308 var ok bool309 params.UseReflectionProtocol, ok = v.(bool)310 if !ok {311 return params, fmt.Errorf("invalid reflect value: '%#v', it needs to be boolean", v)312 }313 default:314 return params, fmt.Errorf("unknown connect param: %q", k)315 }316 }317 return params, nil318}319func walkFileDescriptors(seen map[string]struct{}, fd *desc.FileDescriptor) []*descriptorpb.FileDescriptorProto {320 fds := []*descriptorpb.FileDescriptorProto{}321 if _, ok := seen[fd.GetName()]; ok {322 return fds323 }...

Full Screen

Full Screen

chat.go

Source:chat.go Github

copy

Full Screen

...70 }71 return conn.Invoke(ctx, method, nil, req)72}73func (mi *ModuleInstance) methodDescriptor(ctx context.Context, c *grpcext.Conn, method string) (protoreflect.MethodDescriptor, error) {74 rc, err := c.ReflectionClient()75 if err != nil {76 return nil, err77 }78 fdset, err := rc.Reflect(ctx)79 if err != nil {80 return nil, err81 }82 files, err := protodesc.NewFiles(fdset)83 if err != nil {84 return nil, err85 }86 var md protoreflect.MethodDescriptor87 files.RangeFiles(func(fd protoreflect.FileDescriptor) bool {88 sds := fd.Services()89 for i := 0; i < sds.Len(); i++ {90 sd := sds.Get(i)91 sdname := sd.FullName()92 mds := sd.Methods()...

Full Screen

Full Screen

Reflect

Using AI Code Generation

copy

Full Screen

1import (2type reflectionServer struct {3}4func (s *reflectionServer) ServerReflectionInfo(stream reflection_grpc.ServerReflection_ServerReflectionInfoServer) error {5 grpclog.Info("ServerReflectionInfo")6 return grpc_reflection_v1alpha.ServerReflectionInfo(&reflectionServer{}, stream)7}8func main() {9 lis, err := net.Listen("tcp", "localhost:50051")10 if err != nil {11 log.Fatalf("failed to listen: %v", err)12 }13 s := grpc.NewServer()14 reflection_grpc.RegisterServerReflectionServer(s, &reflectionServer{})15 if err := s.Serve(lis); err != nil {16 log.Fatalf("failed to serve: %v", err)17 }18}19import (20func main() {21 conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())22 if err != nil {23 log.Fatal(err)24 }25 defer conn.Close()26 client := reflection_grpc.NewServerReflectionClient(conn)27 stream, err := client.ServerReflectionInfo(context.Background())28 if err != nil {29 log.Fatal(err)30 }31 req := &reflection.ServerReflectionRequest{32 MessageRequest: &reflection.ServerReflectionRequest_ListServices{},33 }34 if err := stream.Send(req); err != nil {35 log.Fatal(err)36 }37 resp, err := stream.Recv()38 if err != nil {39 log.Fatal(err)40 }41 fmt.Println(resp)42}43&{&{[service:<name:"grpc.reflection.v1alpha.ServerReflection" > ]} []}

Full Screen

Full Screen

Reflect

Using AI Code Generation

copy

Full Screen

1import (2type server struct {3}4func (s *server) SayHello(in *HelloRequest) (*HelloReply, error) {5 return &HelloReply{Message: "Hello " + in.Name}, nil6}7type config struct {8}9func (c *config) TagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context {10}11func (c *config) HandleRPC(ctx context.Context, stat stats.RPCStats) {12}13func (c *config) TagConn(ctx context.Context, info *stats.ConnTagInfo) context.Context {14}15func (c *config) HandleConn(ctx context.Context, stat stats.ConnStats) {16}17func main() {18 lis, err := net.Listen("tcp", "localhost:50051")19 if err != nil {20 grpclog.Fatalf("failed to listen: %v", err)21 }22 s := grpc.NewServer(23 grpc.StatsHandler(&config{}),24 RegisterGreeterServer(s, &server{})25 reflection.Register(s)26 if err := s.Serve(lis); err != nil {27 grpclog.Fatalf("failed to serve: %v", err)28 }29}30import (31type server struct {32}33func (s *server) SayHello(in *HelloRequest) (*HelloReply, error) {34 return &HelloReply{Message: "Hello " + in.Name}, nil35}36type config struct {37}38func (c *config) TagRPC(ctx context.Context, info *stats.RP

Full Screen

Full Screen

Reflect

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 conn, err := grpc.Dial("localhost:8080", grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")))4 if err != nil {5 log.Fatal(err)6 }7 defer conn.Close()8 stub := grpc_testing.NewTestServiceClient(conn)9 req := &grpc_testing.SimpleRequest{10 ResponseSize: proto.Int32(100),11 FillUsername: proto.Bool(true),12 FillOauthScope: proto.Bool(true),13 }14 resp, err := stub.UnaryCall(grpcext.WithUserAgent(context.Background(), "grpc-go/1.0"), req)15 if err != nil {16 log.Fatal(err)17 }18 fmt.Println("Response: ", resp)19}20import (21func main() {22 conn, err := grpc.Dial("localhost:8080", grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")))23 if err != nil {24 log.Fatal(err)25 }26 defer conn.Close()27 stub := grpc_testing.NewTestServiceClient(conn)28 req := &grpc_testing.SimpleRequest{29 ResponseSize: proto.Int32(100),30 FillUsername: proto.Bool(true),31 FillOauthScope: proto.Bool(true),32 }33 resp, err := stub.UnaryCall(grpcext.WithUser

Full Screen

Full Screen

Reflect

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())4 if err != nil {5 grpclog.Fatalf("did not connect: %v", err)6 }7 defer conn.Close()8 c := pb.NewGreeterClient(conn)9 r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name})10 if err != nil {11 grpclog.Fatalf("could not greet: %v", err)12 }13 grpclog.Printf("Greeting: %s", r.Message)14 method, ok := grpcext.MethodName(c.SayHello)15 if ok {16 grpclog.Printf("Method name: %s", method)17 } else {18 grpclog.Fatalf("Method name not available")19 }20}

Full Screen

Full Screen

Reflect

Using AI Code Generation

copy

Full Screen

1func main() {2 var req interface{}3 var resp interface{}4 handler(ctx, req)5 method := grpcext.MethodName(info.FullMethod)6 log.Println(method)7}8func main() {9 var req interface{}10 var resp interface{}11 handler(ctx, req)12 method := grpcext.MethodName(info.FullMethod)13 log.Println(method)14}15func main() {16 var req interface{}17 var resp interface{}18 handler(ctx, req)19 method := grpcext.MethodName(info.FullMethod)20 log.Println(method)21}22func main() {23 var req interface{}24 var resp interface{}25 handler(ctx, req)26 method := grpcext.MethodName(info.FullMethod)27 log.Println(method)28}29func main() {30 var req interface{}31 var resp interface{}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful