Welcome to mirror list, hosted at ThFree Co, Russian Federation.

server.go « streamrpc « internal - gitlab.com/gitlab-org/gitaly.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 365898caeb301fa93d8cd36207d2c67817976480 (plain)
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
package streamrpc

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"
	"google.golang.org/protobuf/proto"
)

var _ grpc.ServiceRegistrar = &Server{}

// Server handles network connections and routes them to StreamRPC handlers.
type Server struct {
	methods     map[string]*method
	interceptor grpc.UnaryServerInterceptor
}

type method struct {
	*grpc.MethodDesc
	implementation interface{}
}

// ServerOption is an abstraction that lets you pass 0 or more server
// options to NewServer.
type ServerOption func(*Server)

// WithServerInterceptor adds a unary gRPC server interceptor.
func WithServerInterceptor(interceptor grpc.UnaryServerInterceptor) ServerOption {
	return func(s *Server) { s.interceptor = interceptor }
}

// NewServer returns a new StreamRPC server. You can pass the result to
// grpc-go RegisterFooServer functions.
func NewServer(opts ...ServerOption) *Server {
	s := &Server{
		methods: make(map[string]*method),
	}
	for _, o := range opts {
		o(s)
	}
	return s
}

// RegisterService implements grpc.ServiceRegistrar. It makes it possible
// to pass a *Server to grpc-go foopb.RegisterFooServer functions as the
// first argument.
func (s *Server) RegisterService(sd *grpc.ServiceDesc, impl interface{}) {
	for i := range sd.Methods {
		m := &sd.Methods[i]
		s.methods["/"+sd.ServiceName+"/"+m.MethodName] = &method{
			MethodDesc:     m,
			implementation: impl,
		}
	}
}

// Handle handles an incoming network connection with the StreamRPC
// protocol. It is intended to be called from a net.Listener.Accept loop
// (or something equivalent).
func (s *Server) Handle(c net.Conn) error {
	defer c.Close()

	deadline := time.Now().Add(defaultHandshakeTimeout)
	req, err := recvFrame(c, deadline)
	if err != nil {
		return err
	}

	session := &serverSession{
		c:        c,
		deadline: deadline,
	}
	if err := s.handleSession(session, req); err != nil {
		return session.reject(err)
	}

	return nil
}

func (s *Server) handleSession(session *serverSession, reqBytes []byte) error {
	req := &request{}
	if err := json.Unmarshal(reqBytes, req); err != nil {
		return err
	}

	method, ok := s.methods[req.Method]
	if !ok {
		return fmt.Errorf("method not found: %s", req.Method)
	}

	ctx, cancel := serverContext(session, req)
	defer cancel()

	if _, err := method.Handler(
		method.implementation,
		ctx,
		func(msg interface{}) error { return proto.Unmarshal(req.Message, msg.(proto.Message)) },
		s.interceptor,
	); err != nil {
		return err
	}

	return nil
}

func serverContext(session *serverSession, req *request) (context.Context, func()) {
	ctx := context.Background()
	ctx = context.WithValue(ctx, sessionKey{}, session)
	ctx = metadata.NewIncomingContext(ctx, req.Metadata)
	return context.WithCancel(ctx)
}

type sessionKey struct{}

// AcceptConnection completes the StreamRPC handshake on the server side.
// It notifies the client that the server has accepted the stream, and
// returns the connection.
func AcceptConnection(ctx context.Context) (net.Conn, error) {
	session, ok := ctx.Value(sessionKey{}).(*serverSession)
	if !ok {
		return nil, errors.New("context has no serverSession")
	}
	return session.Accept()
}

// serverSession wraps an incoming connection whose handshake has not
// been completed yet.
type serverSession struct {
	c        net.Conn
	accepted bool
	deadline time.Time
}

// Accept completes the handshake on the connection wrapped by ss and
// unwraps the connection.
func (ss *serverSession) Accept() (net.Conn, error) {
	if ss.accepted {
		return nil, errors.New("connection already accepted")
	}

	ss.accepted = true
	if err := sendFrame(ss.c, nil, ss.deadline); err != nil {
		return nil, fmt.Errorf("accept session: %w", err)
	}

	return ss.c, nil
}

func (ss *serverSession) reject(err error) error {
	if ss.accepted {
		return nil
	}

	buf, err := json.Marshal(&response{Error: err.Error()})
	if err != nil {
		return fmt.Errorf("mashal response: %w", err)
	}

	return sendFrame(ss.c, buf, ss.deadline)
}