File: callmeta.go

package info (click to toggle)
golang-github-grpc-ecosystem-go-grpc-middleware 2.1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,464 kB
  • sloc: makefile: 107; sh: 9
file content (66 lines) | stat: -rw-r--r-- 1,694 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Copyright (c) The go-grpc-middleware Authors.
// Licensed under the Apache License 2.0.

package interceptors

import (
	"fmt"
	"strings"

	"google.golang.org/grpc"
)

func splitFullMethodName(fullMethod string) (string, string) {
	fullMethod = strings.TrimPrefix(fullMethod, "/") // remove leading slash
	if i := strings.Index(fullMethod, "/"); i >= 0 {
		return fullMethod[:i], fullMethod[i+1:]
	}
	return "unknown", "unknown"
}

type CallMeta struct {
	ReqOrNil any
	Typ      GRPCType
	Service  string
	Method   string
	IsClient bool
}

func NewClientCallMeta(fullMethod string, streamDesc *grpc.StreamDesc, reqOrNil any) CallMeta {
	c := CallMeta{IsClient: true, ReqOrNil: reqOrNil, Typ: Unary}
	if streamDesc != nil {
		c.Typ = clientStreamType(streamDesc)
	}
	c.Service, c.Method = splitFullMethodName(fullMethod)
	return c
}

func NewServerCallMeta(fullMethod string, streamInfo *grpc.StreamServerInfo, reqOrNil any) CallMeta {
	c := CallMeta{IsClient: false, ReqOrNil: reqOrNil, Typ: Unary}
	if streamInfo != nil {
		c.Typ = serverStreamType(streamInfo)
	}
	c.Service, c.Method = splitFullMethodName(fullMethod)
	return c
}
func (c CallMeta) FullMethod() string {
	return fmt.Sprintf("/%s/%s", c.Service, c.Method)
}

func clientStreamType(desc *grpc.StreamDesc) GRPCType {
	if desc.ClientStreams && !desc.ServerStreams {
		return ClientStream
	} else if !desc.ClientStreams && desc.ServerStreams {
		return ServerStream
	}
	return BidiStream
}

func serverStreamType(info *grpc.StreamServerInfo) GRPCType {
	if info.IsClientStream && !info.IsServerStream {
		return ClientStream
	} else if !info.IsClientStream && info.IsServerStream {
		return ServerStream
	}
	return BidiStream
}