-
Notifications
You must be signed in to change notification settings - Fork 4.1k
Expand file tree
/
Copy pathbrpc_streaming_rpc_unittest.cpp
More file actions
864 lines (788 loc) · 30.2 KB
/
brpc_streaming_rpc_unittest.cpp
File metadata and controls
864 lines (788 loc) · 30.2 KB
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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
//
// http://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 limitations
// under the License.
// brpc - A framework to host and access services throughout Baidu.
// Date: 2015/10/22 16:28:44
#include <gtest/gtest.h>
#include <atomic>
#include "brpc/server.h"
#include "brpc/controller.h"
#include "brpc/channel.h"
#include "brpc/callback.h"
#include "brpc/socket.h"
#include "brpc/stream_impl.h"
#include "brpc/policy/streaming_rpc_protocol.h"
#include "echo.pb.h"
class AfterAcceptStream {
public:
virtual void action(brpc::StreamId) = 0;
};
class MyServiceWithStream : public test::EchoService {
public:
MyServiceWithStream(const brpc::StreamOptions& options)
: _options(options)
, _after_accept_stream(NULL)
{}
MyServiceWithStream(const brpc::StreamOptions& options,
AfterAcceptStream* after_accept_stream)
: _options(options)
, _after_accept_stream(after_accept_stream)
{}
MyServiceWithStream()
: _options()
, _after_accept_stream(NULL)
{}
void Echo(::google::protobuf::RpcController* controller,
const ::test::EchoRequest* request,
::test::EchoResponse* response,
::google::protobuf::Closure* done) {
brpc::ClosureGuard done_guard(done);
response->set_message(request->message());
brpc::Controller* cntl = (brpc::Controller*)controller;
brpc::StreamId response_stream;
ASSERT_EQ(0, StreamAccept(&response_stream, *cntl, &_options));
LOG(INFO) << "Created response_stream=" << response_stream;
if (_after_accept_stream) {
_after_accept_stream->action(response_stream);
}
}
private:
brpc::StreamOptions _options;
AfterAcceptStream* _after_accept_stream;
};
class StreamingRpcTest : public testing::Test {
protected:
void SetUp() { request.set_message("hello world"); }
void TearDown() {}
test::EchoRequest request;
test::EchoResponse response;
};
struct BatchStreamFeedbackRaceState {
brpc::StreamId server_first_stream_id{brpc::INVALID_STREAM_ID};
brpc::StreamId server_extra_stream_id{brpc::INVALID_STREAM_ID};
brpc::StreamId client_extra_stream_id{brpc::INVALID_STREAM_ID};
std::atomic<int> server_first_write_rc{-1};
std::atomic<int> server_second_write_rc{-1};
std::atomic<bool> client_got_first_msg{false};
std::atomic<bool> client_got_second_msg{false};
std::atomic<bool> server_write_done{false};
std::atomic<bool> rpc_done{false};
bthread_t server_send_tid{0};
std::atomic<bool> server_send_started{false};
};
class BatchStreamClientHandler : public brpc::StreamInputHandler {
public:
explicit BatchStreamClientHandler(BatchStreamFeedbackRaceState* state)
: _state(state) {}
int on_received_messages(brpc::StreamId id,
butil::IOBuf* const messages[],
size_t size) override {
if (id != _state->client_extra_stream_id) {
// This test only cares about extra stream in batch creation.
return 0;
}
for (size_t i = 0; i < size; ++i) {
const size_t len = messages[i]->length();
messages[i]->clear();
// First payload: 64 bytes. Second payload: 1 byte.
if (len == 64) {
_state->client_got_first_msg.store(true, std::memory_order_release);
} else if (len == 1) {
_state->client_got_second_msg.store(true, std::memory_order_release);
}
}
return 0;
}
void on_idle_timeout(brpc::StreamId /*id*/) override {}
void on_closed(brpc::StreamId /*id*/) override {}
void on_failed(brpc::StreamId /*id*/, int /*error_code*/, const std::string& /*error_text*/) override {}
private:
BatchStreamFeedbackRaceState* _state;
};
static void* SendTwoMessagesOnServerExtraStream(void* arg) {
auto* state = static_cast<BatchStreamFeedbackRaceState*>(arg);
const brpc::StreamId sid = state->server_extra_stream_id;
// Wait until server-side stream is connected.
const int64_t connect_deadline_us = butil::gettimeofday_us() + 2 * 1000 * 1000L;
bool connected = false;
while (butil::gettimeofday_us() < connect_deadline_us) {
brpc::SocketUniquePtr ptr;
if (brpc::Socket::Address(sid, &ptr) == 0) {
brpc::Stream* s = static_cast<brpc::Stream*>(ptr->conn());
if (s->_host_socket != NULL && s->_connected) {
connected = true;
break;
}
}
usleep(1000);
}
if (!connected) {
state->server_first_write_rc.store(ETIMEDOUT, std::memory_order_relaxed);
state->server_second_write_rc.store(ETIMEDOUT, std::memory_order_relaxed);
state->server_write_done.store(true, std::memory_order_release);
return NULL;
}
// 1) Send a payload exactly equal to max_buf_size(64).
{
std::string payload(64, 'a');
butil::IOBuf out;
out.append(payload);
state->server_first_write_rc.store(brpc::StreamWrite(sid, out), std::memory_order_relaxed);
}
// 2) Then send another byte. This write should become writable only after
// client sends FEEDBACK with consumed_size >= 64.
const int64_t write_deadline_us = butil::gettimeofday_us() + 2 * 1000 * 1000L;
int rc = -1;
while (butil::gettimeofday_us() < write_deadline_us) {
butil::IOBuf out;
out.append("b", 1);
rc = brpc::StreamWrite(sid, out);
if (rc == 0) {
break;
}
if (rc != EAGAIN) {
break;
}
const timespec duetime = butil::milliseconds_from_now(100);
(void)brpc::StreamWait(sid, &duetime);
}
state->server_second_write_rc.store(rc, std::memory_order_relaxed);
state->server_write_done.store(true, std::memory_order_release);
return NULL;
}
class MyServiceWithBatchStream : public test::EchoService {
public:
MyServiceWithBatchStream(const brpc::StreamOptions& options,
BatchStreamFeedbackRaceState* state)
: _options(options), _state(state) {}
void Echo(::google::protobuf::RpcController* controller,
const ::test::EchoRequest* request,
::test::EchoResponse* response,
::google::protobuf::Closure* done) override {
brpc::ClosureGuard done_guard(done);
response->set_message(request->message());
brpc::Controller* cntl = static_cast<brpc::Controller*>(controller);
brpc::StreamIds response_streams;
ASSERT_EQ(0, brpc::StreamAccept(response_streams, *cntl, &_options));
ASSERT_EQ(2u, response_streams.size());
_state->server_first_stream_id = response_streams[0];
_state->server_extra_stream_id = response_streams[1];
bthread_t tid;
ASSERT_EQ(0, bthread_start_background(
&tid, &BTHREAD_ATTR_NORMAL,
SendTwoMessagesOnServerExtraStream, _state));
_state->server_send_tid = tid;
_state->server_send_started.store(true, std::memory_order_release);
}
private:
brpc::StreamOptions _options;
BatchStreamFeedbackRaceState* _state;
};
static void SetAtomicTrue(std::atomic<bool>* f) {
f->store(true, std::memory_order_release);
}
static bool WaitForTrue(const std::atomic<bool>& f, int timeout_ms) {
const int64_t deadline_us = butil::gettimeofday_us() + (int64_t)timeout_ms * 1000L;
while (!f.load(std::memory_order_acquire) && butil::gettimeofday_us() < deadline_us) {
usleep(1000);
}
return f.load(std::memory_order_acquire);
}
TEST_F(StreamingRpcTest, sanity) {
brpc::Server server;
MyServiceWithStream service;
ASSERT_EQ(0, server.AddService(&service, brpc::SERVER_DOESNT_OWN_SERVICE));
ASSERT_EQ(0, server.Start(9007, NULL));
brpc::Channel channel;
ASSERT_EQ(0, channel.Init("127.0.0.1:9007", NULL));
brpc::Controller cntl;
brpc::StreamId request_stream;
ASSERT_EQ(0, StreamCreate(&request_stream, cntl, NULL));
brpc::ScopedStream stream_guard(request_stream);
test::EchoService_Stub stub(&channel);
stub.Echo(&cntl, &request, &response, NULL);
ASSERT_FALSE(cntl.Failed()) << cntl.ErrorText() << " request_stream=" << request_stream;
usleep(10);
brpc::StreamClose(request_stream);
server.Stop(0);
server.Join();
}
TEST_F(StreamingRpcTest, batch_create_stream_feedback_race) {
BatchStreamFeedbackRaceState state;
BatchStreamClientHandler client_handler(&state);
brpc::StreamOptions server_stream_opt;
// Make server-side sender sensitive to FEEDBACK quickly.
server_stream_opt.max_buf_size = 16;
brpc::Server server;
MyServiceWithBatchStream service(server_stream_opt, &state);
ASSERT_EQ(0, server.AddService(&service, brpc::SERVER_DOESNT_OWN_SERVICE));
ASSERT_EQ(0, server.Start(9007, NULL));
brpc::Channel channel;
ASSERT_EQ(0, channel.Init("127.0.0.1:9007", NULL));
brpc::Controller cntl;
brpc::StreamIds request_streams;
brpc::StreamOptions client_stream_opt;
client_stream_opt.handler = &client_handler;
client_stream_opt.max_buf_size = 0;
ASSERT_EQ(0, brpc::StreamCreate(request_streams, 2, cntl, &client_stream_opt));
ASSERT_EQ(2u, request_streams.size());
state.client_extra_stream_id = request_streams[1];
// Block SetConnected() on the extra stream to enlarge the race window.
brpc::SocketUniquePtr client_extra_ptr;
ASSERT_EQ(0, brpc::Socket::Address(state.client_extra_stream_id, &client_extra_ptr));
brpc::Stream* client_extra_stream = static_cast<brpc::Stream*>(client_extra_ptr->conn());
bthread_mutex_lock(&client_extra_stream->_connect_mutex);
struct UnlockGuard {
bthread_mutex_t* m;
~UnlockGuard() {
if (m) {
bthread_mutex_unlock(m);
}
}
} unlock_guard{&client_extra_stream->_connect_mutex};
BRPC_SCOPE_EXIT {
if (state.server_extra_stream_id != brpc::INVALID_STREAM_ID) {
brpc::StreamClose(state.server_extra_stream_id);
}
if (state.server_first_stream_id != brpc::INVALID_STREAM_ID) {
brpc::StreamClose(state.server_first_stream_id);
}
for (auto sid : request_streams) {
brpc::StreamClose(sid);
}
if (state.server_send_tid) {
bthread_join(state.server_send_tid, NULL);
}
server.Stop(0);
server.Join();
};
test::EchoService_Stub stub(&channel);
stub.Echo(&cntl, &request, &response, brpc::NewCallback(SetAtomicTrue, &state.rpc_done));
// Wait until client consumes the first 64B payload on extra stream.
ASSERT_TRUE(WaitForTrue(state.client_got_first_msg, 2000));
// Unblock SetConnected(); the fix in PR 3215 should send the first FEEDBACK
// with consumed_size=64 here, making server-side stream writable again.
bthread_mutex_unlock(&client_extra_stream->_connect_mutex);
unlock_guard.m = NULL;
ASSERT_TRUE(WaitForTrue(state.rpc_done, 2000));
ASSERT_FALSE(cntl.Failed()) << cntl.ErrorText();
// Wait for server-side send thread to be started.
ASSERT_TRUE(WaitForTrue(state.server_send_started, 2000));
ASSERT_TRUE(WaitForTrue(state.server_write_done, 2000));
ASSERT_EQ(0, state.server_first_write_rc.load(std::memory_order_relaxed));
ASSERT_EQ(0, state.server_second_write_rc.load(std::memory_order_relaxed));
ASSERT_TRUE(WaitForTrue(state.client_got_second_msg, 2000));
}
struct HandlerControl {
HandlerControl()
: block(false)
{}
bool block;
};
class OrderedInputHandler : public brpc::StreamInputHandler {
public:
explicit OrderedInputHandler(HandlerControl *cntl = NULL)
: _expected_next_value(0)
, _failed(false)
, _stopped(false)
, _idle_times(0)
, _cntl(cntl)
{}
int on_received_messages(brpc::StreamId /*id*/,
butil::IOBuf *const messages[],
size_t size) override {
if (_cntl && _cntl->block) {
while (_cntl->block) {
usleep(100);
}
}
for (size_t i = 0; i < size; ++i) {
CHECK(messages[i]->length() == sizeof(int));
int network = 0;
messages[i]->cutn(&network, sizeof(int));
EXPECT_EQ((int)ntohl(network), _expected_next_value++);
}
return 0;
}
void on_idle_timeout(brpc::StreamId /*id*/) override {
++_idle_times;
}
void on_closed(brpc::StreamId /*id*/) override {
ASSERT_FALSE(_stopped);
_stopped = true;
}
void on_failed(brpc::StreamId id, int error_code,
const std::string& /*error_text*/) override {
ASSERT_FALSE(_failed);
ASSERT_NE(0, error_code);
_failed = true;
}
bool failed() const { return _failed; }
bool stopped() const { return _stopped; }
int idle_times() const { return _idle_times; }
private:
int _expected_next_value;
bool _failed;
bool _stopped;
int _idle_times;
HandlerControl* _cntl;
};
TEST_F(StreamingRpcTest, received_in_order) {
OrderedInputHandler handler;
brpc::StreamOptions opt;
opt.handler = &handler;
opt.messages_in_batch = 100;
brpc::Server server;
MyServiceWithStream service(opt);
ASSERT_EQ(0, server.AddService(&service, brpc::SERVER_DOESNT_OWN_SERVICE));
ASSERT_EQ(0, server.Start(9007, NULL));
brpc::Channel channel;
ASSERT_EQ(0, channel.Init("127.0.0.1:9007", NULL));
brpc::Controller cntl;
brpc::StreamId request_stream;
brpc::StreamOptions request_stream_options;
request_stream_options.max_buf_size = 0;
ASSERT_EQ(0, StreamCreate(&request_stream, cntl, &request_stream_options));
brpc::ScopedStream stream_guard(request_stream);
test::EchoService_Stub stub(&channel);
stub.Echo(&cntl, &request, &response, NULL);
ASSERT_FALSE(cntl.Failed()) << cntl.ErrorText() << " request_stream=" << request_stream;
const int N = 10000;
for (int i = 0; i < N; ++i) {
int network = htonl(i);
butil::IOBuf out;
out.append(&network, sizeof(network));
ASSERT_EQ(0, brpc::StreamWrite(request_stream, out)) << "i=" << i;
}
ASSERT_EQ(0, brpc::StreamClose(request_stream));
server.Stop(0);
server.Join();
while (!handler.stopped()) {
usleep(100);
}
ASSERT_FALSE(handler.failed());
ASSERT_EQ(0, handler.idle_times());
ASSERT_EQ(N, handler._expected_next_value);
}
void on_writable(brpc::StreamId, void* arg, int error_code) {
std::pair<bool, int>* p = (std::pair<bool, int>*)arg;
p->first = true;
p->second = error_code;
LOG(INFO) << "error_code=" << error_code;
}
TEST_F(StreamingRpcTest, block) {
HandlerControl hc;
hc.block = true;
OrderedInputHandler handler(&hc);
brpc::StreamOptions opt;
opt.handler = &handler;
const int N = 10000;
opt.max_buf_size = sizeof(uint32_t) * N;
brpc::Server server;
MyServiceWithStream service(opt);
ASSERT_EQ(0, server.AddService(&service, brpc::SERVER_DOESNT_OWN_SERVICE));
ASSERT_EQ(0, server.Start(9007, NULL));
brpc::Channel channel;
ASSERT_EQ(0, channel.Init("127.0.0.1:9007", NULL));
brpc::Controller cntl;
brpc::StreamId request_stream;
brpc::ScopedStream stream_guard(request_stream);
brpc::StreamOptions request_stream_options;
request_stream_options.max_buf_size = sizeof(uint32_t) * N;
ASSERT_EQ(0, StreamCreate(&request_stream, cntl, &request_stream_options));
test::EchoService_Stub stub(&channel);
stub.Echo(&cntl, &request, &response, NULL);
ASSERT_FALSE(cntl.Failed()) << cntl.ErrorText() << " request_stream="
<< request_stream;
for (int i = 0; i < N; ++i) {
int network = htonl(i);
butil::IOBuf out;
out.append(&network, sizeof(network));
ASSERT_EQ(0, brpc::StreamWrite(request_stream, out)) << "i=" << i;
}
// sync wait
int dummy = 102030123;
butil::IOBuf out;
out.append(&dummy, sizeof(dummy));
ASSERT_EQ(EAGAIN, brpc::StreamWrite(request_stream, out));
hc.block = false;
// wait flushing all the pending messages
while (handler._expected_next_value != N) {
usleep(100);
}
// block hanlder again to test async wait
hc.block = true;
// async wait
for (int i = N; i < N + N; ++i) {
ASSERT_EQ(0, brpc::StreamWait(request_stream, NULL));
int network = htonl(i);
butil::IOBuf out;
out.append(&network, sizeof(network));
ASSERT_EQ(0, brpc::StreamWrite(request_stream, out)) << "i=" << i;
}
out.clear();
out.append(&dummy, sizeof(dummy));
ASSERT_EQ(EAGAIN, brpc::StreamWrite(request_stream, out));
hc.block = false;
std::pair<bool, int> p = std::make_pair(false, 0);
usleep(10);
brpc::StreamWait(request_stream, NULL, on_writable, &p);
while (!p.first) {
usleep(100);
}
ASSERT_EQ(0, p.second);
// wait flushing all the pending messages
while (handler._expected_next_value != N + N) {
usleep(100);
}
usleep(1000);
LOG(INFO) << "Starting block";
hc.block = true;
for (int i = N + N; i < N + N + N; ++i) {
int network = htonl(i);
butil::IOBuf out;
out.append(&network, sizeof(network));
ASSERT_EQ(0, brpc::StreamWrite(request_stream, out)) << "i=" << i - N - N;
}
out.clear();
out.append(&dummy, sizeof(dummy));
ASSERT_EQ(EAGAIN, brpc::StreamWrite(request_stream, out));
timespec duetime = butil::microseconds_from_now(1);
p.first = false;
LOG(INFO) << "Start wait";
brpc::StreamWait(request_stream, &duetime, on_writable, &p);
while (!p.first) {
usleep(100);
}
ASSERT_TRUE(p.first);
EXPECT_EQ(ETIMEDOUT, p.second);
hc.block = false;
ASSERT_EQ(0, brpc::StreamClose(request_stream));
while (!handler.stopped()) {
usleep(100);
}
ASSERT_FALSE(handler.failed());
ASSERT_EQ(0, handler.idle_times());
ASSERT_EQ(N + N + N, handler._expected_next_value);
}
TEST_F(StreamingRpcTest, auto_close_if_host_socket_closed) {
HandlerControl hc;
hc.block = true;
OrderedInputHandler handler(&hc);
brpc::StreamOptions opt;
opt.handler = &handler;
const int N = 10000;
opt.max_buf_size = sizeof(uint32_t) * N;
brpc::Server server;
MyServiceWithStream service(opt);
ASSERT_EQ(0, server.AddService(&service, brpc::SERVER_DOESNT_OWN_SERVICE));
ASSERT_EQ(0, server.Start(9007, NULL));
brpc::Channel channel;
ASSERT_EQ(0, channel.Init("127.0.0.1:9007", NULL));
brpc::Controller cntl;
brpc::StreamId request_stream;
brpc::StreamOptions request_stream_options;
request_stream_options.max_buf_size = sizeof(uint32_t) * N;
ASSERT_EQ(0, StreamCreate(&request_stream, cntl, &request_stream_options));
brpc::ScopedStream stream_guard(request_stream);
test::EchoService_Stub stub(&channel);
stub.Echo(&cntl, &request, &response, NULL);
ASSERT_FALSE(cntl.Failed()) << cntl.ErrorText() << " request_stream=" << request_stream;
{
brpc::SocketUniquePtr ptr;
ASSERT_EQ(0, brpc::Socket::Address(request_stream, &ptr));
brpc::Stream* s = (brpc::Stream*)ptr->conn();
ASSERT_TRUE(s->_host_socket != NULL);
s->_host_socket->SetFailed();
}
usleep(100);
butil::IOBuf out;
out.append("test");
ASSERT_EQ(EINVAL, brpc::StreamWrite(request_stream, out));
while (!handler.stopped()) {
usleep(100);
}
ASSERT_TRUE(handler.failed());
ASSERT_EQ(0, handler.idle_times());
ASSERT_EQ(0, handler._expected_next_value);
}
TEST_F(StreamingRpcTest, failed_when_rst) {
OrderedInputHandler handler;
brpc::StreamOptions opt;
opt.handler = &handler;
opt.messages_in_batch = 100;
brpc::Server server;
MyServiceWithStream service(opt);
ASSERT_EQ(0, server.AddService(&service, brpc::SERVER_DOESNT_OWN_SERVICE));
ASSERT_EQ(0, server.Start(9007, NULL));
brpc::Channel channel;
ASSERT_EQ(0, channel.Init("127.0.0.1:9007", NULL));
brpc::Controller cntl;
brpc::StreamId request_stream;
brpc::StreamOptions request_stream_options;
request_stream_options.max_buf_size = 0;
ASSERT_EQ(0, StreamCreate(&request_stream, cntl, &request_stream_options));
brpc::ScopedStream stream_guard(request_stream);
test::EchoService_Stub stub(&channel);
stub.Echo(&cntl, &request, &response, NULL);
ASSERT_FALSE(cntl.Failed()) << cntl.ErrorText() << " request_stream=" << request_stream;
const int N = 10000;
for (int i = 0; i < N; ++i) {
int network = htonl(i);
butil::IOBuf out;
out.append(&network, sizeof(network));
ASSERT_EQ(0, brpc::StreamWrite(request_stream, out)) << "i=" << i;
}
usleep(1000 * 10);
{
brpc::SocketUniquePtr ptr;
ASSERT_EQ(0, brpc::Socket::Address(request_stream, &ptr));
brpc::Stream* s = (brpc::Stream*)ptr->conn();
ASSERT_TRUE(s->_host_socket != NULL);
brpc::policy::SendStreamRst(s->_host_socket,
s->_remote_settings.stream_id());
}
// ASSERT_EQ(0, brpc::StreamClose(request_stream));
server.Stop(0);
server.Join();
while (!handler.stopped() && !handler.failed()) {
usleep(100);
}
ASSERT_TRUE(handler.failed());
ASSERT_EQ(0, handler.idle_times());
ASSERT_EQ(N, handler._expected_next_value);
}
TEST_F(StreamingRpcTest, idle_timeout) {
HandlerControl hc;
hc.block = true;
OrderedInputHandler handler(&hc);
brpc::StreamOptions opt;
opt.handler = &handler;
opt.idle_timeout_ms = 2;
const int N = 10000;
opt.max_buf_size = sizeof(uint32_t) * N;
brpc::Server server;
MyServiceWithStream service(opt);
ASSERT_EQ(0, server.AddService(&service, brpc::SERVER_DOESNT_OWN_SERVICE));
ASSERT_EQ(0, server.Start(9007, NULL));
brpc::Channel channel;
ASSERT_EQ(0, channel.Init("127.0.0.1:9007", NULL));
brpc::Controller cntl;
brpc::StreamId request_stream;
brpc::StreamOptions request_stream_options;
request_stream_options.max_buf_size = sizeof(uint32_t) * N;
ASSERT_EQ(0, StreamCreate(&request_stream, cntl, &request_stream_options));
brpc::ScopedStream stream_guard(request_stream);
test::EchoService_Stub stub(&channel);
stub.Echo(&cntl, &request, &response, NULL);
ASSERT_FALSE(cntl.Failed()) << cntl.ErrorText() << " request_stream=" << request_stream;
usleep(10 * 1000 + 800);
ASSERT_EQ(0, brpc::StreamClose(request_stream));
while (!handler.stopped()) {
usleep(100);
}
ASSERT_FALSE(handler.failed());
// ASSERT_TRUE(handler.idle_times() >= 4 && handler.idle_times() <= 6)
// << handler.idle_times();
ASSERT_EQ(0, handler._expected_next_value);
}
class PingPongHandler : public brpc::StreamInputHandler {
public:
int on_received_messages(brpc::StreamId id,
butil::IOBuf *const messages[],
size_t size) override {
if (size != 1) {
LOG(INFO) << "size=" << size;
_error = true;
return 0;
}
for (size_t i = 0; i < size; ++i) {
CHECK(messages[i]->length() == sizeof(int));
int network = 0;
messages[i]->cutn(&network, sizeof(int));
if ((int)ntohl(network) != _expected_next_value) {
_error = true;
}
int send_back = ntohl(network) + 1;
_expected_next_value = send_back + 1;
butil::IOBuf out;
network = htonl(send_back);
out.append(&network, sizeof(network));
// don't care the return value
brpc::StreamWrite(id, out);
}
return 0;
}
void on_idle_timeout(brpc::StreamId /*id*/) override {
++_idle_times;
}
void on_closed(brpc::StreamId /*id*/) override {
ASSERT_FALSE(_stopped);
_stopped = true;
}
void on_failed(brpc::StreamId id, int error_code,
const std::string& /*error_text*/) override {
ASSERT_FALSE(_failed);
ASSERT_NE(0, error_code);
_failed = true;
}
bool error() const { return _error; }
bool failed() const { return _failed; }
bool stopped() const { return _stopped; }
int idle_times() const { return _idle_times; }
private:
int _expected_next_value{0};
bool _error{false};
bool _failed{false};
bool _stopped{false};
int _idle_times{0};
};
TEST_F(StreamingRpcTest, ping_pong) {
PingPongHandler resh;
brpc::StreamOptions opt;
opt.handler = &resh;
const int N = 10000;
opt.max_buf_size = sizeof(uint32_t) * N;
brpc::Server server;
MyServiceWithStream service(opt);
ASSERT_EQ(0, server.AddService(&service, brpc::SERVER_DOESNT_OWN_SERVICE));
ASSERT_EQ(0, server.Start(9007, NULL));
brpc::Channel channel;
ASSERT_EQ(0, channel.Init("127.0.0.1:9007", NULL));
brpc::Controller cntl;
brpc::StreamId request_stream;
brpc::StreamOptions request_stream_options;
PingPongHandler reqh;
reqh._expected_next_value = 1;
request_stream_options.handler = &reqh;
request_stream_options.max_buf_size = sizeof(uint32_t) * N;
ASSERT_EQ(0, StreamCreate(&request_stream, cntl, &request_stream_options));
brpc::ScopedStream stream_guard(request_stream);
test::EchoService_Stub stub(&channel);
stub.Echo(&cntl, &request, &response, NULL);
ASSERT_FALSE(cntl.Failed()) << cntl.ErrorText() << " request_stream=" << request_stream;
int send = 0;
butil::IOBuf out;
out.append(&send, sizeof(send));
ASSERT_EQ(0, brpc::StreamWrite(request_stream, out));
usleep(10 * 1000);
ASSERT_EQ(0, brpc::StreamClose(request_stream));
while (!resh.stopped() || !reqh.stopped()) {
usleep(100);
}
ASSERT_FALSE(resh.error());
ASSERT_FALSE(reqh.error());
ASSERT_EQ(0, resh.idle_times());
ASSERT_EQ(0, reqh.idle_times());
}
class SendNAfterAcceptStream : public AfterAcceptStream {
public:
explicit SendNAfterAcceptStream(int n)
: _n(n) {}
void action(brpc::StreamId s) {
for (int i = 0; i < _n; ++i) {
int network = htonl(i);
butil::IOBuf out;
out.append(&network, sizeof(network));
ASSERT_EQ(0, brpc::StreamWrite(s, out)) << "i=" << i;
}
}
private:
int _n;
};
TEST_F(StreamingRpcTest, server_send_data_before_run_done) {
const int N = 10000;
SendNAfterAcceptStream after_accept(N);
brpc::StreamOptions opt;
opt.max_buf_size = -1;
brpc::Server server;
MyServiceWithStream service(opt, &after_accept);
ASSERT_EQ(0, server.AddService(&service, brpc::SERVER_DOESNT_OWN_SERVICE));
ASSERT_EQ(0, server.Start(9007, NULL));
brpc::Channel channel;
ASSERT_EQ(0, channel.Init("127.0.0.1:9007", NULL));
OrderedInputHandler handler;
brpc::StreamOptions request_stream_options;
request_stream_options.handler = &handler;
brpc::StreamId request_stream;
brpc::Controller cntl;
ASSERT_EQ(0, StreamCreate(&request_stream, cntl, &request_stream_options));
brpc::ScopedStream stream_guard(request_stream);
test::EchoService_Stub stub(&channel);
stub.Echo(&cntl, &request, &response, NULL);
ASSERT_FALSE(cntl.Failed()) << cntl.ErrorText() << " request_stream=" << request_stream;
// wait flushing all the pending messages
while (handler._expected_next_value != N) {
usleep(100);
}
ASSERT_EQ(0, brpc::StreamClose(request_stream));
while (!handler.stopped()) {
usleep(100);
}
ASSERT_FALSE(handler.failed());
ASSERT_EQ(0, handler.idle_times());
}
TEST_F(StreamingRpcTest, segment_stream_data_automatically) {
GFLAGS_NAMESPACE::SetCommandLineOption("stream_write_max_segment_size", "1");
OrderedInputHandler handler;
brpc::StreamOptions opt;
opt.handler = &handler;
opt.messages_in_batch = 100;
brpc::Server server;
MyServiceWithStream service(opt);
ASSERT_EQ(0, server.AddService(&service, brpc::SERVER_DOESNT_OWN_SERVICE));
ASSERT_EQ(0, server.Start(9007, NULL));
brpc::Channel channel;
ASSERT_EQ(0, channel.Init("127.0.0.1:9007", NULL));
brpc::Controller cntl;
brpc::StreamId request_stream;
brpc::StreamOptions request_stream_options;
ASSERT_EQ(0, StreamCreate(&request_stream, cntl, &request_stream_options));
brpc::ScopedStream stream_guard(request_stream);
test::EchoService_Stub stub(&channel);
stub.Echo(&cntl, &request, &response, NULL);
ASSERT_FALSE(cntl.Failed()) << cntl.ErrorText() << " request_stream=" << request_stream;
const int N = 1000;
for (int i = 0; i < N; ++i) {
int network = htonl(i);
butil::IOBuf out;
out.append(&network, sizeof(network));
ASSERT_EQ(0, brpc::StreamWrite(request_stream, out)) << "i=" << i;
}
brpc::SocketUniquePtr host_socket_ptr;
{
brpc::SocketUniquePtr ptr;
ASSERT_EQ(0, brpc::Socket::Address(request_stream, &ptr));
brpc::Stream *s = (brpc::Stream *)ptr->conn();
ASSERT_TRUE(s->_host_socket != NULL);
s->_host_socket->ReAddress(&host_socket_ptr);
}
ASSERT_EQ(0, brpc::StreamClose(request_stream));
server.Stop(0);
server.Join();
while (!handler.stopped()) {
usleep(100);
}
const int64_t now_ms = butil::cpuwide_time_ms();
host_socket_ptr->UpdateStatsEverySecond(now_ms);
brpc::SocketStat stat;
host_socket_ptr->GetStat(&stat);
ASSERT_LT(N * sizeof(N), stat.out_num_messages_m);
ASSERT_FALSE(handler.failed());
ASSERT_EQ(0, handler.idle_times());
ASSERT_EQ(N, handler._expected_next_value);
GFLAGS_NAMESPACE::SetCommandLineOption("stream_write_max_segment_size", "536870912");
}