How to use withTags method of grpcext Package

Best K6 code snippet using grpcext.withTags

conn.go

Source:conn.go Github

copy

Full Screen

...94 reqdm := dynamicpb.NewMessage(req.MethodDescriptor.Input())95 if err := protojson.Unmarshal(req.Message, reqdm); err != nil {96 return nil, fmt.Errorf("unable to serialise request object to protocol buffer: %w", err)97 }98 ctx = withTags(ctx, req.Tags)99 resp := dynamicpb.NewMessage(req.MethodDescriptor.Output())100 header, trailer := metadata.New(nil), metadata.New(nil)101 copts := make([]grpc.CallOption, 0, len(opts)+2)102 copts = append(copts, opts...)103 copts = append(copts, grpc.Header(&header), grpc.Trailer(&trailer))104 err := c.raw.Invoke(ctx, url, reqdm, resp, copts...)105 response := Response{106 Headers: header,107 Trailers: trailer,108 }109 marshaler := protojson.MarshalOptions{EmitUnpopulated: true}110 if err != nil {111 sterr := status.Convert(err)112 response.Status = sterr.Code()113 // (rogchap) when you access a JSON property in goja, you are actually accessing the underling114 // Go type (struct, map, slice etc); because these are dynamic messages the Unmarshaled JSON does115 // not map back to a "real" field or value (as a normal Go type would). If we don't marshal and then116 // unmarshal back to a map, you will get "undefined" when accessing JSON properties, even when117 // JSON.Stringify() shows the object to be correctly present.118 raw, _ := marshaler.Marshal(sterr.Proto())119 errMsg := make(map[string]interface{})120 _ = json.Unmarshal(raw, &errMsg)121 response.Error = errMsg122 }123 if resp != nil {124 // (rogchap) there is a lot of marshaling/unmarshaling here, but if we just pass the dynamic message125 // the default Marshaller would be used, which would strip any zero/default values from the JSON.126 // eg. given this message:127 // message Point {128 // double x = 1;129 // double y = 2;130 // double z = 3;131 // }132 // and a value like this:133 // msg := Point{X: 6, Y: 4, Z: 0}134 // would result in JSON output:135 // {"x":6,"y":4}136 // rather than the desired:137 // {"x":6,"y":4,"z":0}138 raw, _ := marshaler.Marshal(resp)139 msg := make(map[string]interface{})140 _ = json.Unmarshal(raw, &msg)141 response.Message = msg142 }143 return &response, nil144}145// Close closes the underhood connection.146func (c *Conn) Close() error {147 return c.raw.Close()148}149type statsHandler struct {150 vu modules.VU151}152// TagConn implements the grpcstats.Handler interface153func (statsHandler) TagConn(ctx context.Context, _ *grpcstats.ConnTagInfo) context.Context { // noop154 return ctx155}156// HandleConn implements the grpcstats.Handler interface157func (statsHandler) HandleConn(context.Context, grpcstats.ConnStats) {158 // noop159}160// TagRPC implements the grpcstats.Handler interface161func (statsHandler) TagRPC(ctx context.Context, _ *grpcstats.RPCTagInfo) context.Context {162 // noop163 return ctx164}165// HandleRPC implements the grpcstats.Handler interface166func (h statsHandler) HandleRPC(ctx context.Context, stat grpcstats.RPCStats) {167 state := h.vu.State()168 tags := getTags(ctx)169 switch s := stat.(type) {170 case *grpcstats.OutHeader:171 if state.Options.SystemTags.Has(metrics.TagIP) && s.RemoteAddr != nil {172 if ip, _, err := net.SplitHostPort(s.RemoteAddr.String()); err == nil {173 tags["ip"] = ip174 }175 }176 case *grpcstats.End:177 if state.Options.SystemTags.Has(metrics.TagStatus) {178 tags["status"] = strconv.Itoa(int(status.Code(s.Error)))179 }180 mTags := map[string]string(tags)181 sampleTags := metrics.IntoSampleTags(&mTags)182 metrics.PushIfNotDone(ctx, state.Samples, metrics.ConnectedSamples{183 Samples: []metrics.Sample{184 {185 Metric: state.BuiltinMetrics.GRPCReqDuration,186 Tags: sampleTags,187 Value: metrics.D(s.EndTime.Sub(s.BeginTime)),188 Time: s.EndTime,189 },190 },191 })192 }193 // (rogchap) Re-using --http-debug flag as gRPC is technically still HTTP194 if state.Options.HTTPDebug.String != "" {195 logger := state.Logger.WithField("source", "http-debug")196 httpDebugOption := state.Options.HTTPDebug.String197 DebugStat(logger, stat, httpDebugOption)198 }199}200// DebugStat prints debugging information based on RPCStats.201func DebugStat(logger logrus.FieldLogger, stat grpcstats.RPCStats, httpDebugOption string) {202 switch s := stat.(type) {203 case *grpcstats.OutHeader:204 logger.Infof("Out Header:\nFull Method: %s\nRemote Address: %s\n%s\n",205 s.FullMethod, s.RemoteAddr, formatMetadata(s.Header))206 case *grpcstats.OutTrailer:207 if len(s.Trailer) > 0 {208 logger.Infof("Out Trailer:\n%s\n", formatMetadata(s.Trailer))209 }210 case *grpcstats.OutPayload:211 if httpDebugOption == "full" {212 logger.Infof("Out Payload:\nWire Length: %d\nSent Time: %s\n%s\n\n",213 s.WireLength, s.SentTime, formatPayload(s.Payload))214 }215 case *grpcstats.InHeader:216 if len(s.Header) > 0 {217 logger.Infof("In Header:\nWire Length: %d\n%s\n", s.WireLength, formatMetadata(s.Header))218 }219 case *grpcstats.InTrailer:220 if len(s.Trailer) > 0 {221 logger.Infof("In Trailer:\nWire Length: %d\n%s\n", s.WireLength, formatMetadata(s.Trailer))222 }223 case *grpcstats.InPayload:224 if httpDebugOption == "full" {225 logger.Infof("In Payload:\nWire Length: %d\nReceived Time: %s\n%s\n\n",226 s.WireLength, s.RecvTime, formatPayload(s.Payload))227 }228 }229}230func formatMetadata(md metadata.MD) string {231 var sb strings.Builder232 for k, v := range md {233 sb.WriteString(k)234 sb.WriteString(": ")235 sb.WriteString(strings.Join(v, ", "))236 sb.WriteRune('\n')237 }238 return sb.String()239}240func formatPayload(payload interface{}) string {241 msg, ok := payload.(proto.Message)242 if !ok {243 // check to see if we are dealing with a APIv1 message244 msgV1, ok := payload.(protov1.Message)245 if !ok {246 return ""247 }248 msg = protov1.MessageV2(msgV1)249 }250 marshaler := prototext.MarshalOptions{251 Multiline: true,252 Indent: " ",253 }254 b, err := marshaler.Marshal(msg)255 if err != nil {256 return ""257 }258 return string(b)259}260type ctxKeyTags struct{}261type reqtags map[string]string262func withTags(ctx context.Context, tags reqtags) context.Context {263 if tags == nil {264 tags = make(map[string]string)265 }266 return context.WithValue(ctx, ctxKeyTags{}, tags)267}268func getTags(ctx context.Context) reqtags {269 v := ctx.Value(ctxKeyTags{})270 if v == nil {271 return make(map[string]string)272 }273 return v.(reqtags)274}...

Full Screen

Full Screen

withTags

Using AI Code Generation

copy

Full Screen

1import (2func init() {3 lis = bufconn.Listen(bufSize)4 s := grpc.NewServer()5 grpc_testing.RegisterTestServiceServer(s, &testServer{})6 go func() {7 if err := s.Serve(lis); err != nil {8 log.Fatalf("Server exited with error: %v", err)9 }10 }()11}12func bufDialer(context.Context, string) (net.Conn, error) {13 return lis.Dial()14}15type testServer struct{}16func (s *testServer) EmptyCall(ctx context.Context, in *grpc_testing.Empty) (*grpc_testing.Empty, error) {17 return &grpc_testing.Empty{}, nil18}19func (s *testServer) UnaryCall(ctx context.Context, in *grpc_testing.SimpleRequest) (*grpc_testing.SimpleResponse, error) {20 return &grpc_testing.SimpleResponse{}, nil21}22func main() {23 ctx := context.Background()24 ctx, cancel := context.WithTimeout(ctx, time.Second)25 defer cancel()26 conn, err := grpc.DialContext(ctx, "bufnet", grpc.WithInsecure(), grpc.WithContextDialer(bufDialer))27 if err != nil {28 log.Fatalf("Failed to dial bufnet: %v", err)29 }30 defer conn.Close()31 client := grpc_testing.NewTestServiceClient(conn)32 _, err = client.EmptyCall(ctx, &grpc_testing.Empty{})33 if err != nil {34 log.Fatalf("EmptyCall failed: %v", err)35 }36 tags := make(map[string]string)

Full Screen

Full Screen

withTags

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 ctx, cancel := context.WithTimeout(ctx, time.Second)5 defer cancel()6 conn, err := grpc.DialContext(ctx, "localhost:50051", grpc.WithInsecure(), grpc.WithBlock())7 if err != nil {8 log.Fatal(err)9 }10 defer conn.Close()11 client := NewGreeterClient(conn)12 ctx = metadata.AppendToOutgoingContext(ctx, "x-user-id", "123")13 r, err := client.SayHello(ctx, &HelloRequest{Name: "world"})14 if err != nil {15 log.Fatal(err)16 }17 log.Println(r.Message)18}19import (20func main() {21 ctx := context.Background()22 ctx, cancel := context.WithTimeout(ctx, time.Second)23 defer cancel()24 conn, err := grpc.DialContext(ctx, "localhost:50051", grpc.WithInsecure(), grpc.WithBlock())25 if err != nil {26 log.Fatal(err)27 }28 defer conn.Close()29 client := NewGreeterClient(conn)30 ctx = metadata.AppendToOutgoingContext(ctx, "x-user-id", "123")31 r, err := client.SayHello(ctx, &HelloRequest{Name: "world"})32 if err != nil {33 log.Fatal(err)34 }35 log.Println(r.Message)36}37import (38func main() {39 ctx := context.Background()40 ctx, cancel := context.WithTimeout(ctx, time.Second)41 defer cancel()42 conn, err := grpc.DialContext(ctx, "localhost:50051", grpc.WithInsecure(), grpc.WithBlock())43 if err != nil {44 log.Fatal(err)45 }46 defer conn.Close()47 client := NewGreeterClient(conn)48 ctx = metadata.AppendToOutgoingContext(ctx, "x-user-id", "123")49 r, err := client.SayHello(ctx, &HelloRequest{Name: "world"})

Full Screen

Full Screen

withTags

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 lis, err := net.Listen("tcp", ":7777")4 if err != nil {5 log.Fatalf("failed to listen: %v", err)6 }7 s := grpc.NewServer()8 pb.RegisterPingServer(s, &server{})9 if err := s.Serve(lis); err != nil {10 log.Fatalf("failed to serve: %v", err)11 }12}13type server struct{}14func (s *server) Ping(ctx context.Context, in *pb.PingRequest) (*pb.PingResponse, error) {15 tag := grpcext.FromContext(ctx)16 fmt.Printf("Tag: %v17 return &pb.PingResponse{Message: "Pong"}, nil18}19import (20func main() {21 lis, err := net.Listen("tcp", ":7777")22 if err != nil {23 log.Fatalf("failed to listen: %v", err)24 }25 s := grpc.NewServer()26 pb.RegisterPingServer(s, &server{})27 if err := s.Serve(lis); err != nil {28 log.Fatalf("failed to serve: %v", err)29 }30}31type server struct{}

Full Screen

Full Screen

withTags

Using AI Code Generation

copy

Full Screen

1func main() {2 conn, err := grpc.Dial("localhost:5000", grpc.WithInsecure())3 if err != nil {4 log.Fatalf("Failed to connect to server: %v", err)5 }6 defer conn.Close()7 client := grpcext.NewClient(conn)8 ctx, cancel := context.WithTimeout(context.Background(), time.Second)9 defer cancel()10 res, err := client.WithTags(ctx, &pb.HelloRequest{Name: "John"})11 if err != nil {12 log.Fatalf("Error calling service: %v", err)13 }14 log.Printf("Response: %s", res.Message)15 for k, v := range client.GetTags() {16 log.Printf("Tag: %s = %s", k, v)17 }18}19func main() {20 conn, err := grpc.Dial("localhost:5000", grpc.WithInsecure())21 if err != nil {22 log.Fatalf("Failed to connect to server: %v", err)23 }24 defer conn.Close()25 client := grpcext.NewClient(conn)26 ctx, cancel := context.WithTimeout(context.Background(), time.Second)27 defer cancel()28 res, err := client.WithTags(ctx, &pb.HelloRequest{Name: "John"})29 if err != nil {30 log.Fatalf("Error calling service: %v", err)31 }32 log.Printf("Response: %s", res.Message)33 for k, v := range client.GetTags() {34 log.Printf("Tag: %s = %s", k, v)35 }36}37func main() {38 conn, err := grpc.Dial("localhost:5000", grpc.WithInsecure())39 if err != nil {40 log.Fatalf("Failed to connect to server: %v", err)41 }42 defer conn.Close()

Full Screen

Full Screen

withTags

Using AI Code Generation

copy

Full Screen

1import (2const (3type server struct{}4func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {5 grpcext.SetHeader(ctx, "custom-server-header-bin", []string{"server value"})6 grpcext.SetTrailer(ctx, "custom-server-trailer-bin", []string{"server value"})7 grpcext.SetTrailer(ctx, "custom-server-trailer-bin", []string{"server value2"})8 grpcext.SetTrailer(ctx, "custom-server-trailer-bin", []string{"server value3"})9 return &pb.HelloReply{Message: "Hello " + in.Name}, nil10}11func main() {12 lis, err := net.Listen("tcp", port)13 if err != nil {14 grpclog.Fatalf("failed to listen: %v", err)15 }16 s := grpc.NewServer()17 pb.RegisterGreeterServer(s, &server{})18 grpclog.Println("server listening at", lis.Addr())19 if err := s.Serve(lis); err != nil {20 grpclog.Fatalf("failed to serve: %v", err)21 }22}23import (24const (

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