github.com/cloudwego/kitex@v0.9.0/pkg/generic/jsonpb_test/generic_init.go (about)

     1  /*
     2   * Copyright 2023 CloudWeGo Authors
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package test
    18  
    19  import (
    20  	"context"
    21  	"encoding/json"
    22  	"errors"
    23  	"fmt"
    24  	"math"
    25  	"net"
    26  	"reflect"
    27  	"strconv"
    28  	"time"
    29  
    30  	"github.com/cloudwego/kitex/client"
    31  	"github.com/cloudwego/kitex/client/genericclient"
    32  	"github.com/cloudwego/kitex/internal/test"
    33  	"github.com/cloudwego/kitex/pkg/generic"
    34  	"github.com/cloudwego/kitex/pkg/kerrors"
    35  	"github.com/cloudwego/kitex/pkg/rpcinfo"
    36  	"github.com/cloudwego/kitex/pkg/transmeta"
    37  	"github.com/cloudwego/kitex/server"
    38  	"github.com/cloudwego/kitex/server/genericserver"
    39  	"github.com/cloudwego/kitex/transport"
    40  )
    41  
    42  func newGenericClient(destService string, g generic.Generic, targetIPPort string) genericclient.Client {
    43  	var opts []client.Option
    44  	opts = append(opts, client.WithHostPorts(targetIPPort), client.WithMetaHandler(transmeta.ClientTTHeaderHandler), client.WithTransportProtocol(transport.TTHeader))
    45  	genericCli, _ := genericclient.NewClient(destService, g, opts...)
    46  	return genericCli
    47  }
    48  
    49  func newGenericServer(g generic.Generic, addr net.Addr, handler generic.Service) server.Server {
    50  	var opts []server.Option
    51  	opts = append(opts, server.WithServiceAddr(addr), server.WithExitWaitTime(time.Microsecond*10), server.WithMetaHandler(transmeta.ServerTTHeaderHandler))
    52  	svr := genericserver.NewServer(handler, g, opts...)
    53  	go func() {
    54  		err := svr.Run()
    55  		if err != nil {
    56  			panic(err)
    57  		}
    58  	}()
    59  	test.WaitServerStart(addr.String())
    60  	return svr
    61  }
    62  
    63  // GenericServiceImpl ...
    64  type TestEchoService struct{}
    65  
    66  // GenericCall ...
    67  func (g *TestEchoService) GenericCall(ctx context.Context, method string, request interface{}) (response interface{}, err error) {
    68  	buf := request.(string)
    69  	if buf == getBizErrReq() {
    70  		return nil, kerrors.NewBizStatusError(404, "not found")
    71  	}
    72  	rpcinfo := rpcinfo.GetRPCInfo(ctx)
    73  	fmt.Printf("Method from Ctx: %s\n", rpcinfo.Invocation().MethodName())
    74  	fmt.Printf("Recv: %v\n", buf)
    75  	fmt.Printf("Method: %s\n", method)
    76  	// Check that request received is correct
    77  	if buf != getEchoReq() {
    78  		return nil, errors.New("incorrect request received")
    79  	}
    80  	return getEchoRes(), nil
    81  }
    82  
    83  // GenericService for example.proto
    84  type TestExampleMethodService struct{}
    85  
    86  // GenericCall ...
    87  func (g *TestExampleMethodService) GenericCall(ctx context.Context, method string, request interface{}) (response interface{}, err error) {
    88  	buf := request.(string)
    89  	rpcinfo := rpcinfo.GetRPCInfo(ctx)
    90  	fmt.Printf("Method from Ctx: %s\n", rpcinfo.Invocation().MethodName())
    91  	fmt.Printf("Recv: %v\n", buf)
    92  	fmt.Printf("Method: %s\n", method)
    93  	// Check that request received is correct
    94  	if buf != getExampleMethodReq() {
    95  		return nil, errors.New("incorrect request received")
    96  	}
    97  	return getExampleMethodRes(), nil
    98  }
    99  
   100  // GenericService for example.proto
   101  type TestVoidService struct{}
   102  
   103  // GenericCall ...
   104  func (g *TestVoidService) GenericCall(ctx context.Context, method string, request interface{}) (response interface{}, err error) {
   105  	buf := request.(string)
   106  	rpcinfo := rpcinfo.GetRPCInfo(ctx)
   107  	fmt.Printf("Method from Ctx: %s\n", rpcinfo.Invocation().MethodName())
   108  	fmt.Printf("Recv: %v\n", buf)
   109  	fmt.Printf("Method: %s\n", method)
   110  	// Check that request received is correct
   111  	if buf != getVoidReq() {
   112  		return nil, errors.New("incorrect request received")
   113  	}
   114  	return getVoidRes(), nil
   115  }
   116  
   117  // GenericService for example2.proto
   118  type TestExampleMethod2Service struct{}
   119  
   120  // GenericCall ...
   121  func (g *TestExampleMethod2Service) GenericCall(ctx context.Context, method string, request interface{}) (response interface{}, err error) {
   122  	buf := request.(string)
   123  	rpcinfo := rpcinfo.GetRPCInfo(ctx)
   124  	fmt.Printf("Method from Ctx: %s\n", rpcinfo.Invocation().MethodName())
   125  	fmt.Printf("Recv: %v\n", buf)
   126  	fmt.Printf("Method: %s\n", method)
   127  	// Check that request received is correct
   128  	var jsonMapResp map[string]interface{}
   129  	var jsonMapOriginal map[string]interface{}
   130  	err = json.Unmarshal([]byte(buf), &jsonMapResp)
   131  	if err != nil {
   132  		return nil, errors.New("json str to map conversion error")
   133  	}
   134  	err = json.Unmarshal([]byte(getExampleMethod2Req()), &jsonMapOriginal)
   135  	if err != nil {
   136  		return nil, errors.New("json str to map conversion error")
   137  	}
   138  	if !reflect.DeepEqual(jsonMapResp, jsonMapOriginal) {
   139  		return nil, errors.New("incorrect request received")
   140  	}
   141  	return getExampleMethod2Res(), nil
   142  }
   143  
   144  // GenericService for TestInt2FloatMethod
   145  type TestInt2FloatMethodService struct{}
   146  
   147  type ExampleInt2Float struct {
   148  	Int32   int32
   149  	Float64 float64
   150  	String_ string
   151  	Int64   int64
   152  	Subfix  float64
   153  }
   154  
   155  // GenericCall ...
   156  func (g *TestInt2FloatMethodService) GenericCall(ctx context.Context, method string, request interface{}) (response interface{}, err error) {
   157  	buf := request.(string)
   158  
   159  	rpcinfo := rpcinfo.GetRPCInfo(ctx)
   160  	fmt.Printf("Method from Ctx: %s\n", rpcinfo.Invocation().MethodName())
   161  	fmt.Printf("Recv: %v\n", buf)
   162  	fmt.Printf("Method: %s\n", method)
   163  	// Check that request received is correct
   164  	if buf != getInt2FloatMethodRes() {
   165  		return nil, errors.New("call failed")
   166  	}
   167  	return getInt2FloatMethodRes(), nil
   168  }
   169  
   170  // GenericService for TestInt2FloatMethod2
   171  type TestInt2FloatMethod2Service struct{}
   172  
   173  // GenericCall ...
   174  func (g *TestInt2FloatMethod2Service) GenericCall(ctx context.Context, method string, request interface{}) (response interface{}, err error) {
   175  	buf := request.(string)
   176  
   177  	rpcinfo := rpcinfo.GetRPCInfo(ctx)
   178  	fmt.Printf("Method from Ctx: %s\n", rpcinfo.Invocation().MethodName())
   179  	fmt.Printf("Recv: %v\n", buf)
   180  	fmt.Printf("Method: %s\n", method)
   181  	// Check that request received is correct
   182  	if buf != getInt2FloatMethod2Req() {
   183  		return nil, errors.New("call failed")
   184  	}
   185  	return getInt2FloatMethod2Res(), nil
   186  }
   187  
   188  func getEchoReq() string {
   189  	return `{"message":"this is the request"}`
   190  }
   191  
   192  func getBizErrReq() string {
   193  	return `{"message":"return biz error"}`
   194  }
   195  
   196  func getEchoRes() string {
   197  	return `{"message":"this is the response"}`
   198  }
   199  
   200  func getExampleMethodReq() string {
   201  	return `{"reqs":["req_one","req_two","req_three"]}`
   202  }
   203  
   204  func getExampleMethodRes() string {
   205  	return `{"resps":["res_one","res_two","res_three"]}`
   206  }
   207  
   208  func getVoidReq() string {
   209  	return `{}`
   210  }
   211  
   212  func getVoidRes() string {
   213  	return `{}`
   214  }
   215  
   216  func getExampleMethod2Req() string {
   217  	return `{
   218      "Msg":"hello",
   219      "A":25,
   220      "InnerBase2":{
   221          "Bool":true,
   222          "Uint32":123,
   223          "Uint64":123,
   224          "Double":22.3,
   225          "String":"hello_inner",
   226          "ListInt32":[12,13,14,15,16,17],
   227          "MapStringString":{"m1":"aaa","m2":"bbb"},
   228          "SetInt32":[200,201,202,203,204,205],
   229          "MapInt32String":{"1":"aaa","2":"bbb","3":"ccc","4":"ddd"},
   230          "Binary":"AQIDBA==",
   231          "MapUint32String":{"1":"u32aa","2":"u32bb","3":"u32cc","4":"u32dd"},
   232          "MapUint64String":{"1":"u64aa","2":"u64bb","3":"u64cc","4":"u64dd"},
   233          "MapInt64String":{"1":"64aaa","2":"64bbb","3":"64ccc","4":"64ddd"},
   234          "MapInt64Base":{
   235              "1":{
   236                  "LogID":"logId","Caller":"caller","Addr":"addr","Client":"client","TrafficEnv":{"Env":"env"},"Extra":{"1a":"aaa","2a":"bbb","3a":"ccc","4a":"ddd"}
   237              },
   238              "2":{
   239                  "LogID":"logId2","Caller":"caller2","Addr":"addr2","Client":"client2","TrafficEnv":{"Open":true,"Env":"env2"},"Extra":{"1a":"aaa2","2a":"bbb2","3a":"ccc2","4a":"ddd2"}
   240              }
   241          },
   242          "MapStringBase":{
   243              "1":{
   244                  "LogID":"logId","Caller":"caller","Addr":"addr","Client":"client","TrafficEnv":{"Env":"env"},"Extra":{"1a":"aaa","2a":"bbb","3a":"ccc","4a":"ddd"}
   245              },
   246              "2":{
   247                  "LogID":"logId2","Caller":"caller2","Addr":"addr2","Client":"client2","TrafficEnv":{"Open":true,"Env":"env2"},"Extra":{"1a":"aaa2","2a":"bbb2","3a":"ccc2","4a":"ddd2"}
   248              }
   249          },
   250          "ListBase":[
   251              {"LogID":"logId","Caller":"caller","Addr":"addr","Client":"client","TrafficEnv":{"Env":"env"},"Extra":{"1a":"aaa","2a":"bbb","3a":"ccc","4a":"ddd"}},
   252              {"LogID":"logId2","Caller":"caller2","Addr":"addr2","Client":"client2","TrafficEnv":{"Open":true,"Env":"env2"},"Extra":{"1a":"aaa2","2a":"bbb2","3a":"ccc2","4a":"ddd2"}}
   253          ],
   254          "ListString":["111","222","333","44","51","6"],
   255          "Base":{"LogID":"logId","Caller":"caller","Addr":"addr","Client":"client","TrafficEnv":{"Env":"env"},"Extra":{"1b":"aaa","2b":"bbb","3b":"ccc","4b":"ddd"}}
   256      }
   257  }`
   258  }
   259  
   260  func getExampleMethod2Res() string {
   261  	return `{
   262      "Msg":"hello",
   263      "A":25,
   264      "InnerBase2":{
   265          "Bool":true,
   266          "Uint32":123,
   267          "Uint64":123,
   268          "Double":22.3,
   269          "String":"hello_inner",
   270          "ListInt32":[12,13,14,15,16,17],
   271          "MapStringString":{"m1":"aaa","m2":"bbb"},
   272          "SetInt32":[200,201,202,203,204,205],
   273          "MapInt32String":{"1":"aaa","2":"bbb","3":"ccc","4":"ddd"},
   274          "Binary":"AQIDBA==",
   275          "MapUint32String":{"1":"u32aa","2":"u32bb","3":"u32cc","4":"u32dd"},
   276          "MapUint64String":{"1":"u64aa","2":"u64bb","3":"u64cc","4":"u64dd"},
   277          "MapInt64String":{"1":"64aaa","2":"64bbb","3":"64ccc","4":"64ddd"},
   278          "MapInt64Base":{
   279              "1":{
   280                  "LogID":"logId","Caller":"caller","Addr":"addr","Client":"client","TrafficEnv":{"Env":"env"},"Extra":{"1a":"aaa","2a":"bbb","3a":"ccc","4a":"ddd"}
   281              },
   282              "2":{
   283                  "LogID":"logId2","Caller":"caller2","Addr":"addr2","Client":"client2","TrafficEnv":{"Open":true,"Env":"env2"},"Extra":{"1a":"aaa2","2a":"bbb2","3a":"ccc2","4a":"ddd2"}
   284              }
   285          },
   286          "MapStringBase":{
   287              "1":{
   288                  "LogID":"logId","Caller":"caller","Addr":"addr","Client":"client","TrafficEnv":{"Env":"env"},"Extra":{"1a":"aaa","2a":"bbb","3a":"ccc","4a":"ddd"}
   289              },
   290              "2":{
   291                  "LogID":"logId2","Caller":"caller2","Addr":"addr2","Client":"client2","TrafficEnv":{"Open":true,"Env":"env2"},"Extra":{"1a":"aaa2","2a":"bbb2","3a":"ccc2","4a":"ddd2"}
   292              }
   293          },
   294          "ListBase":[
   295              {"LogID":"logId","Caller":"caller","Addr":"addr","Client":"client","TrafficEnv":{"Env":"env"},"Extra":{"1a":"aaa","2a":"bbb","3a":"ccc","4a":"ddd"}},
   296              {"LogID":"logId2","Caller":"caller2","Addr":"addr2","Client":"client2","TrafficEnv":{"Open":true,"Env":"env2"},"Extra":{"1a":"aaa2","2a":"bbb2","3a":"ccc2","4a":"ddd2"}}
   297          ],
   298          "ListString":["111","222","333","44","51","6"],
   299          "Base":{"LogID":"logId","Caller":"caller","Addr":"addr","Client":"client","TrafficEnv":{"Env":"env"},"Extra":{"1b":"aaa","2b":"bbb","3b":"ccc","4b":"ddd"}}
   300      }
   301  }`
   302  }
   303  
   304  func getInt2FloatMethodReq() string {
   305  	return `{"Int32":1,"Float64":3.14,"String":"hello","Int64":2,"Subfix":0.92653}`
   306  }
   307  
   308  func getInt2FloatMethodRes() string {
   309  	return `{"Int32":1,"Float64":3.14,"String":"hello","Int64":2,"Subfix":0.92653}`
   310  }
   311  
   312  func getInt2FloatMethod2Res() string {
   313  	return `{"Int64":` + strconv.Itoa(math.MaxInt64) + `}`
   314  }
   315  
   316  func getInt2FloatMethod2Req() string {
   317  	return `{"Int64":` + strconv.Itoa(math.MaxInt64) + `}`
   318  }