-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
verifier.go
392 lines (336 loc) · 10.9 KB
/
verifier.go
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
package test
import (
"container/list"
"fmt"
"sync"
"testing"
"time"
"cloud.google.com/go/internal/testutil"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
// blockWaitTimeout is the timeout for any wait operations to ensure no
// deadlocks.
blockWaitTimeout = 30 * time.Second
)
// Barrier is used to perform two-way synchronization betwen the server and
// client (test) to ensure tests are deterministic.
type Barrier struct {
// Used to block until the server is ready to send the response.
serverBlock chan struct{}
// Used to block until the client wants the server to send the response.
clientBlock chan struct{}
err error
}
func newBarrier() *Barrier {
return &Barrier{
serverBlock: make(chan struct{}),
clientBlock: make(chan struct{}),
}
}
// ReleaseAfter releases the barrier, after invoking f provided by the test.
func (b *Barrier) ReleaseAfter(f func()) {
// Wait for the server to reach the barrier.
select {
case <-time.After(blockWaitTimeout):
// Note: avoid returning a retryable code to quickly terminate the test.
b.err = status.Errorf(codes.FailedPrecondition, "mockserver: server did not reach barrier within %v", blockWaitTimeout)
case <-b.serverBlock:
}
// Run any test-specific code.
if f != nil {
f()
}
// Then close the client block.
close(b.clientBlock)
}
// Release should be called by the test.
func (b *Barrier) Release() {
b.ReleaseAfter(nil)
}
func (b *Barrier) serverWait() error {
if b.err != nil {
return b.err
}
// Close the server block to signal the server reaching the point where it is
// ready to send the response.
close(b.serverBlock)
// Wait for the test to release the client block.
select {
case <-time.After(blockWaitTimeout):
// Note: avoid returning a retryable code to quickly terminate the test.
return status.Errorf(codes.FailedPrecondition, "mockserver: test did not unblock response within %v", blockWaitTimeout)
case <-b.clientBlock:
return nil
}
}
type rpcMetadata struct {
wantRequest interface{}
retResponse interface{}
retErr error
barrier *Barrier
}
// wait until the barrier is released by the test, or a timeout occurs.
// Returns immediately if there was no block.
func (r *rpcMetadata) wait() error {
if r.barrier == nil {
return nil
}
return r.barrier.serverWait()
}
// RPCVerifier stores an queue of requests expected from the client, and the
// corresponding response or error to return.
type RPCVerifier struct {
t *testing.T
mu sync.Mutex
rpcs *list.List // Value = *rpcMetadata
numCalls int
}
// NewRPCVerifier creates a new verifier for requests received by the server.
func NewRPCVerifier(t *testing.T) *RPCVerifier {
return &RPCVerifier{
t: t,
rpcs: list.New(),
numCalls: -1,
}
}
// Push appends a new {request, response, error} tuple.
//
// Valid combinations for unary and streaming RPCs:
// - {request, response, nil}
// - {request, nil, error}
//
// Additional combinations for streams only:
// - {nil, response, nil}: send a response without a request (e.g. messages).
// - {nil, nil, error}: break the stream without a request.
// - {request, nil, nil}: expect a request, but don't send any response.
func (v *RPCVerifier) Push(wantRequest interface{}, retResponse interface{}, retErr error) {
v.mu.Lock()
defer v.mu.Unlock()
v.rpcs.PushBack(&rpcMetadata{
wantRequest: wantRequest,
retResponse: retResponse,
retErr: retErr,
})
}
// PushWithBarrier is like Push, but returns a barrier that the test should call
// Release when it would like the response to be sent to the client. This is
// useful for synchronizing with work that needs to be done on the client.
func (v *RPCVerifier) PushWithBarrier(wantRequest interface{}, retResponse interface{}, retErr error) *Barrier {
v.mu.Lock()
defer v.mu.Unlock()
barrier := newBarrier()
v.rpcs.PushBack(&rpcMetadata{
wantRequest: wantRequest,
retResponse: retResponse,
retErr: retErr,
barrier: barrier,
})
return barrier
}
// Pop validates the received request with the next {request, response, error}
// tuple.
func (v *RPCVerifier) Pop(gotRequest interface{}) (interface{}, error) {
v.mu.Lock()
defer v.mu.Unlock()
v.numCalls++
elem := v.rpcs.Front()
if elem == nil {
v.t.Errorf("call(%d): unexpected request:\n[%T] %v", v.numCalls, gotRequest, gotRequest)
return nil, status.Error(codes.FailedPrecondition, "mockserver: got unexpected request")
}
rpc, _ := elem.Value.(*rpcMetadata)
v.rpcs.Remove(elem)
if !testutil.Equal(gotRequest, rpc.wantRequest) {
v.t.Errorf("call(%d): got request: [%T] %v\nwant request: [%T] %v", v.numCalls, gotRequest, gotRequest, rpc.wantRequest, rpc.wantRequest)
}
if err := rpc.wait(); err != nil {
return nil, err
}
return rpc.retResponse, rpc.retErr
}
// TryPop should be used only for streams. It checks whether the request in the
// next tuple is nil, in which case the response or error should be returned to
// the client without waiting for a request. Useful for streams where the server
// continuously sends data (e.g. subscribe stream).
func (v *RPCVerifier) TryPop() (bool, interface{}, error) {
v.mu.Lock()
defer v.mu.Unlock()
elem := v.rpcs.Front()
if elem == nil {
return false, nil, nil
}
rpc, _ := elem.Value.(*rpcMetadata)
if rpc.wantRequest != nil {
return false, nil, nil
}
v.rpcs.Remove(elem)
if err := rpc.wait(); err != nil {
return true, nil, err
}
return true, rpc.retResponse, rpc.retErr
}
// Flush logs an error for any remaining {request, response, error} tuples, in
// case the client terminated early.
func (v *RPCVerifier) Flush() {
v.mu.Lock()
defer v.mu.Unlock()
for elem := v.rpcs.Front(); elem != nil; elem = elem.Next() {
v.numCalls++
rpc, _ := elem.Value.(*rpcMetadata)
if rpc.wantRequest != nil {
v.t.Errorf("call(%d): did not receive expected request:\n[%T] %v", v.numCalls, rpc.wantRequest, rpc.wantRequest)
} else {
v.t.Errorf("call(%d): unsent response:\n[%T] %v, err = (%v)", v.numCalls, rpc.retResponse, rpc.retResponse, rpc.retErr)
}
}
v.rpcs.Init()
}
// streamVerifiers stores a queue of verifiers for unique stream connections.
type streamVerifiers struct {
t *testing.T
verifiers *list.List // Value = *RPCVerifier
numStreams int
}
func newStreamVerifiers(t *testing.T) *streamVerifiers {
return &streamVerifiers{
t: t,
verifiers: list.New(),
numStreams: -1,
}
}
func (sv *streamVerifiers) Push(v *RPCVerifier) {
sv.verifiers.PushBack(v)
}
func (sv *streamVerifiers) Pop(key string) (*RPCVerifier, error) {
sv.numStreams++
elem := sv.verifiers.Front()
if elem == nil {
sv.t.Errorf("unexpected stream index %d for key %s", sv.numStreams, key)
return nil, status.Error(codes.FailedPrecondition, "mockserver: got unexpected stream connection")
}
v, _ := elem.Value.(*RPCVerifier)
sv.verifiers.Remove(elem)
return v, nil
}
func (sv *streamVerifiers) Flush() {
for elem := sv.verifiers.Front(); elem != nil; elem = elem.Next() {
v, _ := elem.Value.(*RPCVerifier)
v.Flush()
}
}
// keyedStreamVerifiers stores indexed streamVerifiers. Examples of keys:
// "streamType:topic_path:partition".
type keyedStreamVerifiers struct {
verifiers map[string]*streamVerifiers
}
func newKeyedStreamVerifiers() *keyedStreamVerifiers {
return &keyedStreamVerifiers{verifiers: make(map[string]*streamVerifiers)}
}
func (kv *keyedStreamVerifiers) Push(key string, v *RPCVerifier) {
sv, ok := kv.verifiers[key]
if !ok {
sv = newStreamVerifiers(v.t)
kv.verifiers[key] = sv
}
sv.Push(v)
}
func (kv *keyedStreamVerifiers) Pop(key string) (*RPCVerifier, error) {
sv, ok := kv.verifiers[key]
if !ok {
return nil, status.Error(codes.FailedPrecondition, "mockserver: unexpected connection with no configured responses")
}
return sv.Pop(key)
}
func (kv *keyedStreamVerifiers) Flush() {
for _, sv := range kv.verifiers {
sv.Flush()
}
}
// Verifiers contains RPCVerifiers for unary RPCs and streaming RPCs.
type Verifiers struct {
t *testing.T
mu sync.Mutex
// Global list of verifiers for all unary RPCs.
GlobalVerifier *RPCVerifier
// Stream verifiers by key.
streamVerifiers *keyedStreamVerifiers
activeStreamVerifiers []*RPCVerifier
}
// NewVerifiers creates a new instance of Verifiers for a test.
func NewVerifiers(t *testing.T) *Verifiers {
return &Verifiers{
t: t,
GlobalVerifier: NewRPCVerifier(t),
streamVerifiers: newKeyedStreamVerifiers(),
}
}
// streamType is used as a key prefix for keyedStreamVerifiers.
type streamType string
const (
publishStreamType streamType = "publish"
subscribeStreamType streamType = "subscribe"
commitStreamType streamType = "commit"
assignmentStreamType streamType = "assignment"
)
func keyPartition(st streamType, path string, partition int) string {
return fmt.Sprintf("%s:%s:%d", st, path, partition)
}
func key(st streamType, path string) string {
return fmt.Sprintf("%s:%s", st, path)
}
// AddPublishStream adds verifiers for a publish stream.
func (tv *Verifiers) AddPublishStream(topic string, partition int, streamVerifier *RPCVerifier) {
tv.mu.Lock()
defer tv.mu.Unlock()
tv.streamVerifiers.Push(keyPartition(publishStreamType, topic, partition), streamVerifier)
}
// AddSubscribeStream adds verifiers for a subscribe stream.
func (tv *Verifiers) AddSubscribeStream(subscription string, partition int, streamVerifier *RPCVerifier) {
tv.mu.Lock()
defer tv.mu.Unlock()
tv.streamVerifiers.Push(keyPartition(subscribeStreamType, subscription, partition), streamVerifier)
}
// AddCommitStream adds verifiers for a commit stream.
func (tv *Verifiers) AddCommitStream(subscription string, partition int, streamVerifier *RPCVerifier) {
tv.mu.Lock()
defer tv.mu.Unlock()
tv.streamVerifiers.Push(keyPartition(commitStreamType, subscription, partition), streamVerifier)
}
// AddAssignmentStream adds verifiers for an assignment stream.
func (tv *Verifiers) AddAssignmentStream(subscription string, streamVerifier *RPCVerifier) {
tv.mu.Lock()
defer tv.mu.Unlock()
tv.streamVerifiers.Push(key(assignmentStreamType, subscription), streamVerifier)
}
func (tv *Verifiers) popStreamVerifier(key string) (*RPCVerifier, error) {
tv.mu.Lock()
defer tv.mu.Unlock()
v, err := tv.streamVerifiers.Pop(key)
if v != nil {
tv.activeStreamVerifiers = append(tv.activeStreamVerifiers, v)
}
return v, err
}
func (tv *Verifiers) flush() {
tv.mu.Lock()
defer tv.mu.Unlock()
tv.GlobalVerifier.Flush()
tv.streamVerifiers.Flush()
for _, v := range tv.activeStreamVerifiers {
v.Flush()
}
}