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

cache.go « cache « middleware « internal - gitlab.com/gitlab-org/gitaly.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: cb5fbb219f6e978f1e109b67d3dfb497cb2b30a1 (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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
package cache

import (
	"context"
	"fmt"
	"strings"
	"sync"

	"github.com/sirupsen/logrus"
	diskcache "gitlab.com/gitlab-org/gitaly/v16/internal/cache"
	"gitlab.com/gitlab-org/gitaly/v16/internal/praefect/protoregistry"
	"google.golang.org/grpc"
	"google.golang.org/protobuf/proto"
)

func methodErrLogger(method string) func(error) {
	return func(err error) {
		countMethodErr(method)
		logrus.WithField("full_method_name", method).Error(err)
	}
}

func shouldIgnore(reg *protoregistry.Registry, fullMethod string) bool {
	return strings.HasPrefix(fullMethod, "/grpc.health") || reg.IsInterceptedMethod(fullMethod)
}

func shouldInvalidate(mi protoregistry.MethodInfo) bool {
	if mi.Scope != protoregistry.ScopeRepository {
		return false
	}

	if mi.Operation == protoregistry.OpAccessor {
		return false
	}

	if mi.Operation == protoregistry.OpMaintenance {
		return false
	}

	return true
}

// StreamInvalidator will invalidate any mutating RPC that targets a
// repository in a gRPC stream based RPC
func StreamInvalidator(ci diskcache.Invalidator, reg *protoregistry.Registry) grpc.StreamServerInterceptor {
	return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
		if shouldIgnore(reg, info.FullMethod) {
			return handler(srv, ss)
		}

		errLogger := methodErrLogger(info.FullMethod)

		mInfo, err := reg.LookupMethod(info.FullMethod)
		countRPCType(mInfo)
		if err != nil {
			errLogger(err)
			return handler(srv, ss)
		}

		if !shouldInvalidate(mInfo) {
			return handler(srv, ss)
		}

		handler, callback := invalidateCache(ci, mInfo, handler, errLogger)
		peeker := newStreamPeeker(ss, callback)
		return handler(srv, peeker)
	}
}

// UnaryInvalidator will invalidate any mutating RPC that targets a
// repository in a gRPC unary RPC
func UnaryInvalidator(ci diskcache.Invalidator, reg *protoregistry.Registry) grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
		if shouldIgnore(reg, info.FullMethod) {
			return handler(ctx, req)
		}

		errLogger := methodErrLogger(info.FullMethod)

		mInfo, err := reg.LookupMethod(info.FullMethod)
		countRPCType(mInfo)
		if err != nil {
			errLogger(err)
			return handler(ctx, req)
		}

		if !shouldInvalidate(mInfo) {
			return handler(ctx, req)
		}

		pbReq, ok := req.(proto.Message)
		if !ok {
			errLogger(fmt.Errorf("expected protobuf message but got %T", req))
			return handler(ctx, req)
		}

		target, err := mInfo.TargetRepo(pbReq)
		if err != nil {
			errLogger(err)
			return handler(ctx, req)
		}

		le, err := ci.StartLease(target)
		if err != nil {
			errLogger(err)
			return handler(ctx, req)
		}

		// wrap the handler to ensure the lease is always ended
		return func() (resp interface{}, err error) {
			defer func() {
				if err := le.EndLease(ctx); err != nil {
					errLogger(err)
				}
			}()
			return handler(ctx, req)
		}()
	}
}

type recvMsgCallback func(interface{}, error)

func invalidateCache(ci diskcache.Invalidator, mInfo protoregistry.MethodInfo, handler grpc.StreamHandler, errLogger func(error)) (grpc.StreamHandler, recvMsgCallback) {
	var le struct {
		sync.RWMutex
		diskcache.LeaseEnder
	}

	// ensures that the lease ender is invoked after the original handler
	wrappedHandler := func(srv interface{}, stream grpc.ServerStream) error {
		defer func() {
			le.RLock()
			defer le.RUnlock()

			if le.LeaseEnder == nil {
				return
			}
			if err := le.EndLease(stream.Context()); err != nil {
				errLogger(err)
			}
		}()
		return handler(srv, stream)
	}

	// starts the cache lease and sets the lease ender iff the request's target
	// repository can be determined from the first request message
	peekerCallback := func(firstReq interface{}, err error) {
		if err != nil {
			errLogger(err)
			return
		}

		pbFirstReq, ok := firstReq.(proto.Message)
		if !ok {
			errLogger(fmt.Errorf("cache invalidation expected protobuf request, but got %T", firstReq))
			return
		}

		target, err := mInfo.TargetRepo(pbFirstReq)
		if err != nil {
			errLogger(err)
			return
		}

		le.Lock()
		defer le.Unlock()

		l, err := ci.StartLease(target)
		if err != nil {
			errLogger(err)
			return
		}
		le.LeaseEnder = l
	}

	return wrappedHandler, peekerCallback
}

// streamPeeker allows a stream interceptor to insert peeking logic to perform
// an action when the first RecvMsg
type streamPeeker struct {
	grpc.ServerStream

	// onFirstRecvCallback is called the first time the server stream's RecvMsg
	// is invoked. It passes the results of the stream's RecvMsg as the
	// callback's parameters.
	onFirstRecvOnce     sync.Once
	onFirstRecvCallback recvMsgCallback
}

// newStreamPeeker returns a wrapped stream that allows a callback to be called
// on the first invocation of RecvMsg.
func newStreamPeeker(stream grpc.ServerStream, callback recvMsgCallback) grpc.ServerStream {
	return &streamPeeker{
		ServerStream:        stream,
		onFirstRecvCallback: callback,
	}
}

// RecvMsg overrides the embedded grpc.ServerStream's method of the same name so
// that the callback is called on the first call.
func (sp *streamPeeker) RecvMsg(m interface{}) error {
	err := sp.ServerStream.RecvMsg(m)
	sp.onFirstRecvOnce.Do(func() { sp.onFirstRecvCallback(m, err) })
	return err
}