go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/resultdb/internal/rpcutil/rpcutil.go (about)

     1  // Copyright 2022 The LUCI 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 rpcutil contains utility functions for RPC handlers.
    16  package rpcutil
    17  
    18  import (
    19  	"context"
    20  	"fmt"
    21  	"strings"
    22  
    23  	"google.golang.org/grpc"
    24  
    25  	"go.chromium.org/luci/common/tsmon/field"
    26  	"go.chromium.org/luci/common/tsmon/metric"
    27  	"go.chromium.org/luci/server/auth"
    28  )
    29  
    30  // IdentityKindCounter is exported for testing.
    31  //
    32  // Normally this counter is updated via IdentityKindCountingInterceptor().
    33  var IdentityKindCounter = metric.NewCounter(
    34  	"resultdb/rpc/identitykind",
    35  	"Number of identities",
    36  	nil,
    37  	field.String("service"), // RPC service
    38  	field.String("method"),  // RPC method
    39  	field.String("kind"),    // LUCI auth identity Kind
    40  )
    41  
    42  // IdentityKindCountingInterceptor returns a gRPC interceptor that updates a
    43  // tsmon counter with the type of authenticated principal.
    44  func IdentityKindCountingInterceptor() grpc.UnaryServerInterceptor {
    45  	return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) {
    46  		// FullMethod has form "/<service>/<method>".
    47  		parts := strings.Split(info.FullMethod, "/")
    48  		if len(parts) != 3 || parts[0] != "" {
    49  			panic(fmt.Sprintf("unexpected format of info.FullMethod: %q", info.FullMethod))
    50  		}
    51  		service, method := parts[1], parts[2]
    52  
    53  		IdentityKindCounter.Add(ctx, 1, service, method, string(auth.CurrentIdentity(ctx).Kind()))
    54  		return handler(ctx, req)
    55  	}
    56  }