...

Source file src/go.etcd.io/etcd/pkg/v3/grpc_testing/recorder.go

Documentation: go.etcd.io/etcd/pkg/v3/grpc_testing

     1  // Copyright 2021 The etcd Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package grpc_testing
    16  
    17  import (
    18  	"context"
    19  	"sync"
    20  
    21  	"google.golang.org/grpc"
    22  	"google.golang.org/grpc/metadata"
    23  )
    24  
    25  type GrpcRecorder struct {
    26  	mux      sync.RWMutex
    27  	requests []RequestInfo
    28  }
    29  
    30  type RequestInfo struct {
    31  	FullMethod string
    32  	Authority  string
    33  }
    34  
    35  func (ri *GrpcRecorder) UnaryInterceptor() grpc.UnaryServerInterceptor {
    36  	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
    37  		ri.record(toRequestInfo(ctx, info))
    38  		resp, err := handler(ctx, req)
    39  		return resp, err
    40  	}
    41  }
    42  
    43  func (ri *GrpcRecorder) RecordedRequests() []RequestInfo {
    44  	ri.mux.RLock()
    45  	defer ri.mux.RUnlock()
    46  	reqs := make([]RequestInfo, len(ri.requests))
    47  	copy(reqs, ri.requests)
    48  	return reqs
    49  }
    50  
    51  func toRequestInfo(ctx context.Context, info *grpc.UnaryServerInfo) RequestInfo {
    52  	req := RequestInfo{
    53  		FullMethod: info.FullMethod,
    54  	}
    55  	md, ok := metadata.FromIncomingContext(ctx)
    56  	if ok {
    57  		as := md.Get(":authority")
    58  		if len(as) != 0 {
    59  			req.Authority = as[0]
    60  		}
    61  	}
    62  	return req
    63  }
    64  
    65  func (ri *GrpcRecorder) record(r RequestInfo) {
    66  	ri.mux.Lock()
    67  	defer ri.mux.Unlock()
    68  	ri.requests = append(ri.requests, r)
    69  }
    70  

View as plain text