brpc_http_rpc_protocol_unittest.cpp 55.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// 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.

18
// brpc - A framework to host and access services throughout Baidu.
gejun's avatar
gejun committed
19 20 21 22 23 24 25 26 27

// Date: Sun Jul 13 15:04:18 CST 2014

#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <gtest/gtest.h>
#include <gflags/gflags.h>
#include <google/protobuf/descriptor.h>
28 29 30
#include "butil/time.h"
#include "butil/macros.h"
#include "butil/files/scoped_file.h"
31
#include "butil/fd_guard.h"
gejun's avatar
gejun committed
32 33 34 35 36 37
#include "brpc/socket.h"
#include "brpc/acceptor.h"
#include "brpc/server.h"
#include "brpc/channel.h"
#include "brpc/policy/most_common_message.h"
#include "brpc/controller.h"
38
#include "echo.pb.h"
gejun's avatar
gejun committed
39
#include "brpc/policy/http_rpc_protocol.h"
zhujiashun's avatar
zhujiashun committed
40
#include "brpc/policy/http2_rpc_protocol.h"
gejun's avatar
gejun committed
41 42 43 44 45 46
#include "json2pb/pb_to_json.h"
#include "json2pb/json_to_pb.h"
#include "brpc/details/method_status.h"

int main(int argc, char* argv[]) {
    testing::InitGoogleTest(&argc, argv);
47 48
    GFLAGS_NS::ParseCommandLineFlags(&argc, &argv, true);
    if (GFLAGS_NS::SetCommandLineOption("socket_max_unwritten_bytes", "2000000").empty()) {
gejun's avatar
gejun committed
49 50 51
        std::cerr << "Fail to set -socket_max_unwritten_bytes" << std::endl;
        return -1;
    }
52
    if (GFLAGS_NS::SetCommandLineOption("crash_on_fatal_log", "true").empty()) {
gejun's avatar
gejun committed
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
        std::cerr << "Fail to set -crash_on_fatal_log" << std::endl;
        return -1;
    }
    return RUN_ALL_TESTS();
}

namespace {

static const std::string EXP_REQUEST = "hello";
static const std::string EXP_RESPONSE = "world";

static const std::string MOCK_CREDENTIAL = "mock credential";
static const std::string MOCK_USER = "mock user";

class MyAuthenticator : public brpc::Authenticator {
public:
    MyAuthenticator() {}

    int GenerateCredential(std::string* auth_str) const {
        *auth_str = MOCK_CREDENTIAL;
        return 0;
    }

    int VerifyCredential(const std::string& auth_str,
77
                         const butil::EndPoint&,
gejun's avatar
gejun committed
78 79 80 81 82 83 84 85 86
                         brpc::AuthContext* ctx) const {
        EXPECT_EQ(MOCK_CREDENTIAL, auth_str);
        ctx->set_user(MOCK_USER);
        return 0;
    }
};

class MyEchoService : public ::test::EchoService {
public:
87
    void Echo(::google::protobuf::RpcController* cntl_base,
gejun's avatar
gejun committed
88 89 90 91
              const ::test::EchoRequest* req,
              ::test::EchoResponse* res,
              ::google::protobuf::Closure* done) {
        brpc::ClosureGuard done_guard(done);
92 93 94 95 96 97 98
        brpc::Controller* cntl =
            static_cast<brpc::Controller*>(cntl_base);
        const std::string* sleep_ms_str =
            cntl->http_request().uri().GetQuery("sleep_ms");
        if (sleep_ms_str) {
            bthread_usleep(strtol(sleep_ms_str->data(), NULL, 10) * 1000);
        }
gejun's avatar
gejun committed
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
        res->set_message(EXP_RESPONSE);
    }
};

class HttpTest : public ::testing::Test{
protected:
    HttpTest() {
        EXPECT_EQ(0, _server.AddBuiltinServices());
        EXPECT_EQ(0, _server.AddService(
            &_svc, brpc::SERVER_DOESNT_OWN_SERVICE));
        // Hack: Regard `_server' as running 
        _server._status = brpc::Server::RUNNING;
        _server._options.auth = &_auth;
        
        EXPECT_EQ(0, pipe(_pipe_fds));

        brpc::SocketId id;
        brpc::SocketOptions options;
        options.fd = _pipe_fds[1];
        EXPECT_EQ(0, brpc::Socket::Create(options, &id));
        EXPECT_EQ(0, brpc::Socket::Address(id, &_socket));
120 121 122

        brpc::SocketOptions h2_client_options;
        h2_client_options.user = brpc::get_client_side_messenger();
zyearn's avatar
zyearn committed
123
        h2_client_options.fd = _pipe_fds[1];
124 125
        EXPECT_EQ(0, brpc::Socket::Create(h2_client_options, &id));
        EXPECT_EQ(0, brpc::Socket::Address(id, &_h2_client_sock));
gejun's avatar
gejun committed
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
    };

    virtual ~HttpTest() {};
    virtual void SetUp() {};
    virtual void TearDown() {};

    void VerifyMessage(brpc::InputMessageBase* msg, bool expect) {
        if (msg->_socket == NULL) {
            _socket->ReAddress(&msg->_socket);
        }
        msg->_arg = &_server;
        EXPECT_EQ(expect, brpc::policy::VerifyHttpRequest(msg));
    }

    void ProcessMessage(void (*process)(brpc::InputMessageBase*),
                        brpc::InputMessageBase* msg, bool set_eof) {
        if (msg->_socket == NULL) {
            _socket->ReAddress(&msg->_socket);
        }
        msg->_arg = &_server;
        _socket->PostponeEOF();
        if (set_eof) {
            _socket->SetEOF();
        }
        (*process)(msg);
    }

gejun's avatar
gejun committed
153
    brpc::policy::HttpContext* MakePostRequestMessage(const std::string& path) {
154
        brpc::policy::HttpContext* msg = new brpc::policy::HttpContext(false);
gejun's avatar
gejun committed
155 156 157 158 159 160
        msg->header().uri().set_path(path);
        msg->header().set_content_type("application/json");
        msg->header().set_method(brpc::HTTP_METHOD_POST);

        test::EchoRequest req;
        req.set_message(EXP_REQUEST);
161
        butil::IOBufAsZeroCopyOutputStream req_stream(&msg->body());
gejun's avatar
gejun committed
162 163 164 165
        EXPECT_TRUE(json2pb::ProtoMessageToJson(req, &req_stream, NULL));
        return msg;
    }

gejun's avatar
gejun committed
166
    brpc::policy::HttpContext* MakeGetRequestMessage(const std::string& path) {
167
        brpc::policy::HttpContext* msg = new brpc::policy::HttpContext(false);
gejun's avatar
gejun committed
168 169 170 171 172 173
        msg->header().uri().set_path(path);
        msg->header().set_method(brpc::HTTP_METHOD_GET);
        return msg;
    }


gejun's avatar
gejun committed
174
    brpc::policy::HttpContext* MakeResponseMessage(int code) {
175
        brpc::policy::HttpContext* msg = new brpc::policy::HttpContext(false);
gejun's avatar
gejun committed
176 177 178 179 180
        msg->header().set_status_code(code);
        msg->header().set_content_type("application/json");
        
        test::EchoResponse res;
        res.set_message(EXP_RESPONSE);
181
        butil::IOBufAsZeroCopyOutputStream res_stream(&msg->body());
gejun's avatar
gejun committed
182 183 184 185 186 187 188 189 190 191 192 193 194
        EXPECT_TRUE(json2pb::ProtoMessageToJson(res, &res_stream, NULL));
        return msg;
    }

    void CheckResponseCode(bool expect_empty, int expect_code) {
        int bytes_in_pipe = 0;
        ioctl(_pipe_fds[0], FIONREAD, &bytes_in_pipe);
        if (expect_empty) {
            EXPECT_EQ(0, bytes_in_pipe);
            return;
        }

        EXPECT_GT(bytes_in_pipe, 0);
195
        butil::IOPortal buf;
gejun's avatar
gejun committed
196 197 198 199 200
        EXPECT_EQ((ssize_t)bytes_in_pipe,
                  buf.append_from_file_descriptor(_pipe_fds[0], 1024));
        brpc::ParseResult pr =
                brpc::policy::ParseHttpMessage(&buf, _socket.get(), false, NULL);
        EXPECT_EQ(brpc::PARSE_OK, pr.error());
gejun's avatar
gejun committed
201 202
        brpc::policy::HttpContext* msg =
            static_cast<brpc::policy::HttpContext*>(pr.message());
gejun's avatar
gejun committed
203 204 205 206 207

        EXPECT_EQ(expect_code, msg->header().status_code());
        msg->Destroy();
    }

208
    void MakeH2EchoRequestBuf(butil::IOBuf* out, brpc::Controller* cntl, int* h2_stream_id) {
zhujiashun's avatar
zhujiashun committed
209 210 211
        butil::IOBuf request_buf;
        test::EchoRequest req;
        req.set_message(EXP_REQUEST);
212
        cntl->http_request().set_method(brpc::HTTP_METHOD_POST);
zhujiashun's avatar
zhujiashun committed
213 214 215 216 217 218 219
        brpc::policy::SerializeHttpRequest(&request_buf, cntl, &req);
        ASSERT_FALSE(cntl->Failed());
        brpc::policy::H2UnsentRequest* h2_req = brpc::policy::H2UnsentRequest::New(cntl);
        cntl->_current_call.stream_user_data = h2_req;
        brpc::SocketMessage* socket_message = NULL;
        brpc::policy::PackH2Request(NULL, &socket_message, cntl->call_id().value,
                                    NULL, cntl, request_buf, NULL);
220
        butil::Status st = socket_message->AppendAndDestroySelf(out, _h2_client_sock.get());
zhujiashun's avatar
zhujiashun committed
221 222 223 224
        ASSERT_TRUE(st.ok());
        *h2_stream_id = h2_req->_stream_id;
    }

225
    void MakeH2EchoResponseBuf(butil::IOBuf* out, int h2_stream_id) {
zhujiashun's avatar
zhujiashun committed
226 227
        brpc::Controller cntl;
        test::EchoResponse res;
228
        res.set_message(EXP_RESPONSE);
zhujiashun's avatar
zhujiashun committed
229 230 231 232 233
        cntl.http_request().set_content_type("application/proto");
        {
            butil::IOBufAsZeroCopyOutputStream wrapper(&cntl.response_attachment());
            EXPECT_TRUE(res.SerializeToZeroCopyStream(&wrapper));
        }
234
        brpc::policy::H2UnsentResponse* h2_res = brpc::policy::H2UnsentResponse::New(&cntl, h2_stream_id, false /*is grpc*/);
235
        butil::Status st = h2_res->AppendAndDestroySelf(out, _h2_client_sock.get());
zhujiashun's avatar
zhujiashun committed
236 237 238
        ASSERT_TRUE(st.ok());
    }

gejun's avatar
gejun committed
239 240
    int _pipe_fds[2];
    brpc::SocketUniquePtr _socket;
241
    brpc::SocketUniquePtr _h2_client_sock;
gejun's avatar
gejun committed
242 243 244 245 246 247
    brpc::Server _server;

    MyEchoService _svc;
    MyAuthenticator _auth;
};

gejun's avatar
gejun committed
248 249 250 251 252 253 254 255 256 257 258 259 260
TEST_F(HttpTest, indenting_ostream) {
    std::ostringstream os1;
    brpc::IndentingOStream is1(os1, 2);
    brpc::IndentingOStream is2(is1, 2);
    os1 << "begin1\nhello" << std::endl << "world\nend1" << std::endl;
    is1 << "begin2\nhello" << std::endl << "world\nend2" << std::endl;
    is2 << "begin3\nhello" << std::endl << "world\nend3" << std::endl;
    ASSERT_EQ(
    "begin1\nhello\nworld\nend1\nbegin2\n  hello\n  world\n  end2\n"
    "  begin3\n    hello\n    world\n    end3\n",
    os1.str());
}

gejun's avatar
gejun committed
261
TEST_F(HttpTest, parse_http_address) {
262
    const std::string EXP_HOSTNAME = "www.baidu.com:9876";
263
    butil::EndPoint EXP_ENDPOINT;
gejun's avatar
gejun committed
264 265
    {
        std::string url = "https://" + EXP_HOSTNAME;
266
        EXPECT_TRUE(brpc::policy::ParseHttpServerAddress(&EXP_ENDPOINT, url.c_str()));
gejun's avatar
gejun committed
267 268
    }
    {
269
        butil::EndPoint ep;
gejun's avatar
gejun committed
270 271 272 273 274 275
        std::string url = "http://" +
                          std::string(endpoint2str(EXP_ENDPOINT).c_str());
        EXPECT_TRUE(brpc::policy::ParseHttpServerAddress(&ep, url.c_str()));
        EXPECT_EQ(EXP_ENDPOINT, ep);
    }
    {
276
        butil::EndPoint ep;
gejun's avatar
gejun committed
277
        std::string url = "https://" +
278
            std::string(butil::ip2str(EXP_ENDPOINT.ip).c_str());
gejun's avatar
gejun committed
279 280
        EXPECT_TRUE(brpc::policy::ParseHttpServerAddress(&ep, url.c_str()));
        EXPECT_EQ(EXP_ENDPOINT.ip, ep.ip);
gejun's avatar
gejun committed
281
        EXPECT_EQ(443, ep.port);
gejun's avatar
gejun committed
282 283
    }
    {
284
        butil::EndPoint ep;
gejun's avatar
gejun committed
285 286 287
        EXPECT_FALSE(brpc::policy::ParseHttpServerAddress(&ep, "invalid_url"));
    }
    {
288
        butil::EndPoint ep;
gejun's avatar
gejun committed
289 290 291 292 293 294 295
        EXPECT_FALSE(brpc::policy::ParseHttpServerAddress(
            &ep, "https://no.such.machine:9090"));
    }
}

TEST_F(HttpTest, verify_request) {
    {
gejun's avatar
gejun committed
296
        brpc::policy::HttpContext* msg =
gejun's avatar
gejun committed
297 298 299 300 301
                MakePostRequestMessage("/EchoService/Echo");
        VerifyMessage(msg, false);
        msg->Destroy();
    }
    {
gejun's avatar
gejun committed
302
        brpc::policy::HttpContext* msg = MakeGetRequestMessage("/status");
gejun's avatar
gejun committed
303 304 305 306
        VerifyMessage(msg, true);
        msg->Destroy();
    }
    {
gejun's avatar
gejun committed
307
        brpc::policy::HttpContext* msg =
gejun's avatar
gejun committed
308 309 310 311 312 313 314 315
                MakePostRequestMessage("/EchoService/Echo");
        _socket->SetFailed();
        VerifyMessage(msg, false);
        msg->Destroy();
    }
}

TEST_F(HttpTest, process_request_failed_socket) {
gejun's avatar
gejun committed
316
    brpc::policy::HttpContext* msg = MakePostRequestMessage("/EchoService/Echo");
gejun's avatar
gejun committed
317 318
    _socket->SetFailed();
    ProcessMessage(brpc::policy::ProcessHttpRequest, msg, false);
319
    ASSERT_EQ(0ll, _server._nerror_bvar.get_value());
gejun's avatar
gejun committed
320 321 322 323
    CheckResponseCode(true, 0);
}

TEST_F(HttpTest, reject_get_to_pb_services_with_required_fields) {
gejun's avatar
gejun committed
324
    brpc::policy::HttpContext* msg = MakeGetRequestMessage("/EchoService/Echo");
gejun's avatar
gejun committed
325 326
    _server._status = brpc::Server::RUNNING;
    ProcessMessage(brpc::policy::ProcessHttpRequest, msg, false);
327
    ASSERT_EQ(0ll, _server._nerror_bvar.get_value());
gejun's avatar
gejun committed
328 329 330 331
    const brpc::Server::MethodProperty* mp =
        _server.FindMethodPropertyByFullName("test.EchoService.Echo");
    ASSERT_TRUE(mp);
    ASSERT_TRUE(mp->status);
332
    ASSERT_EQ(1ll, mp->status->_nerror_bvar.get_value());
gejun's avatar
gejun committed
333 334 335 336
    CheckResponseCode(false, brpc::HTTP_STATUS_BAD_REQUEST);
}

TEST_F(HttpTest, process_request_logoff) {
gejun's avatar
gejun committed
337
    brpc::policy::HttpContext* msg = MakePostRequestMessage("/EchoService/Echo");
gejun's avatar
gejun committed
338 339
    _server._status = brpc::Server::READY;
    ProcessMessage(brpc::policy::ProcessHttpRequest, msg, false);
340
    ASSERT_EQ(1ll, _server._nerror_bvar.get_value());
341
    CheckResponseCode(false, brpc::HTTP_STATUS_SERVICE_UNAVAILABLE);
gejun's avatar
gejun committed
342 343 344
}

TEST_F(HttpTest, process_request_wrong_method) {
gejun's avatar
gejun committed
345
    brpc::policy::HttpContext* msg = MakePostRequestMessage("/NO_SUCH_METHOD");
gejun's avatar
gejun committed
346
    ProcessMessage(brpc::policy::ProcessHttpRequest, msg, false);
347
    ASSERT_EQ(1ll, _server._nerror_bvar.get_value());
gejun's avatar
gejun committed
348 349 350 351 352 353 354
    CheckResponseCode(false, brpc::HTTP_STATUS_NOT_FOUND);
}

TEST_F(HttpTest, process_response_after_eof) {
    test::EchoResponse res;
    brpc::Controller cntl;
    cntl._response = &res;
gejun's avatar
gejun committed
355
    brpc::policy::HttpContext* msg =
gejun's avatar
gejun committed
356 357 358 359 360 361 362 363 364 365 366
            MakeResponseMessage(brpc::HTTP_STATUS_OK);
    _socket->set_correlation_id(cntl.call_id().value);
    ProcessMessage(brpc::policy::ProcessHttpResponse, msg, true);
    ASSERT_EQ(EXP_RESPONSE, res.message());
    ASSERT_TRUE(_socket->Failed());
}

TEST_F(HttpTest, process_response_error_code) {
    {
        brpc::Controller cntl;
        _socket->set_correlation_id(cntl.call_id().value);
gejun's avatar
gejun committed
367
        brpc::policy::HttpContext* msg =
gejun's avatar
gejun committed
368 369 370 371 372 373 374 375
                MakeResponseMessage(brpc::HTTP_STATUS_CONTINUE);
        ProcessMessage(brpc::policy::ProcessHttpResponse, msg, false);
        ASSERT_EQ(brpc::EHTTP, cntl.ErrorCode());
        ASSERT_EQ(brpc::HTTP_STATUS_CONTINUE, cntl.http_response().status_code());
    }
    {
        brpc::Controller cntl;
        _socket->set_correlation_id(cntl.call_id().value);
gejun's avatar
gejun committed
376
        brpc::policy::HttpContext* msg =
gejun's avatar
gejun committed
377 378 379 380 381 382 383 384 385
                MakeResponseMessage(brpc::HTTP_STATUS_TEMPORARY_REDIRECT);
        ProcessMessage(brpc::policy::ProcessHttpResponse, msg, false);
        ASSERT_EQ(brpc::EHTTP, cntl.ErrorCode());
        ASSERT_EQ(brpc::HTTP_STATUS_TEMPORARY_REDIRECT,
                  cntl.http_response().status_code());
    }
    {
        brpc::Controller cntl;
        _socket->set_correlation_id(cntl.call_id().value);
gejun's avatar
gejun committed
386
        brpc::policy::HttpContext* msg =
gejun's avatar
gejun committed
387 388 389 390 391 392 393 394 395
                MakeResponseMessage(brpc::HTTP_STATUS_BAD_REQUEST);
        ProcessMessage(brpc::policy::ProcessHttpResponse, msg, false);
        ASSERT_EQ(brpc::EHTTP, cntl.ErrorCode());
        ASSERT_EQ(brpc::HTTP_STATUS_BAD_REQUEST,
                  cntl.http_response().status_code());
    }
    {
        brpc::Controller cntl;
        _socket->set_correlation_id(cntl.call_id().value);
gejun's avatar
gejun committed
396
        brpc::policy::HttpContext* msg = MakeResponseMessage(12345);
gejun's avatar
gejun committed
397 398 399 400 401 402 403
        ProcessMessage(brpc::policy::ProcessHttpResponse, msg, false);
        ASSERT_EQ(brpc::EHTTP, cntl.ErrorCode());
        ASSERT_EQ(12345, cntl.http_response().status_code());
    }
}

TEST_F(HttpTest, complete_flow) {
404 405
    butil::IOBuf request_buf;
    butil::IOBuf total_buf;
gejun's avatar
gejun committed
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
    brpc::Controller cntl;
    test::EchoRequest req;
    test::EchoResponse res;
    cntl._response = &res;
    cntl._connection_type = brpc::CONNECTION_TYPE_SHORT;
    cntl._method = test::EchoService::descriptor()->method(0);
    ASSERT_EQ(0, brpc::Socket::Address(_socket->id(), &cntl._current_call.sending_sock));

    // Send request
    req.set_message(EXP_REQUEST);
    brpc::policy::SerializeHttpRequest(&request_buf, &cntl, &req);
    ASSERT_FALSE(cntl.Failed());
    brpc::policy::PackHttpRequest(
        &total_buf, NULL, cntl.call_id().value,
        cntl._method, &cntl, request_buf, &_auth);
    ASSERT_FALSE(cntl.Failed());

    // Verify and handle request
    brpc::ParseResult req_pr =
            brpc::policy::ParseHttpMessage(&total_buf, _socket.get(), false, NULL);
    ASSERT_EQ(brpc::PARSE_OK, req_pr.error());
    brpc::InputMessageBase* req_msg = req_pr.message();
    VerifyMessage(req_msg, true);
    ProcessMessage(brpc::policy::ProcessHttpRequest, req_msg, false);

    // Read response from pipe
432
    butil::IOPortal response_buf;
gejun's avatar
gejun committed
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
    response_buf.append_from_file_descriptor(_pipe_fds[0], 1024);
    brpc::ParseResult res_pr =
            brpc::policy::ParseHttpMessage(&response_buf, _socket.get(), false, NULL);
    ASSERT_EQ(brpc::PARSE_OK, res_pr.error());
    brpc::InputMessageBase* res_msg = res_pr.message();
    ProcessMessage(brpc::policy::ProcessHttpResponse, res_msg, false);

    ASSERT_FALSE(cntl.Failed()) << cntl.ErrorText();
    ASSERT_EQ(EXP_RESPONSE, res.message());
}

TEST_F(HttpTest, chunked_uploading) {
    const int port = 8923;
    brpc::Server server;
    EXPECT_EQ(0, server.AddService(&_svc, brpc::SERVER_DOESNT_OWN_SERVICE));
    EXPECT_EQ(0, server.Start(port, NULL));

    // Send request via curl using chunked encoding
    const std::string req = "{\"message\":\"hello\"}";
    const std::string res_fname = "curl.out";
    std::string cmd;
454
    butil::string_printf(&cmd, "curl -X POST -d '%s' -H 'Transfer-Encoding:chunked' "
gejun's avatar
gejun committed
455 456 457 458 459 460 461
                        "-H 'Content-Type:application/json' -o %s "
                        "http://localhost:%d/EchoService/Echo",
                        req.c_str(), res_fname.c_str(), port);
    ASSERT_EQ(0, system(cmd.c_str()));

    // Check response
    const std::string exp_res = "{\"message\":\"world\"}";
462
    butil::ScopedFILE fp(res_fname.c_str(), "r");
gejun's avatar
gejun committed
463
    char buf[128];
gejun's avatar
gejun committed
464
    ASSERT_TRUE(fgets(buf, sizeof(buf), fp));
gejun's avatar
gejun committed
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
    EXPECT_EQ(exp_res, std::string(buf));
}

enum DonePlace {
    DONE_BEFORE_CREATE_PA = 0,
    DONE_AFTER_CREATE_PA_BEFORE_DESTROY_PA,
    DONE_AFTER_DESTROY_PA,
};
// For writing into PA.
const char PA_DATA[] = "abcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()_=-+";
const size_t PA_DATA_LEN = sizeof(PA_DATA) - 1/*not count the ending zero*/;

static void CopyPAPrefixedWithSeqNo(char* buf, uint64_t seq_no) {
    memcpy(buf, PA_DATA, PA_DATA_LEN);
    *(uint64_t*)buf = seq_no;
}

class DownloadServiceImpl : public ::test::DownloadService {
public:
    DownloadServiceImpl(DonePlace done_place = DONE_BEFORE_CREATE_PA,
                        size_t num_repeat = 1)
        : _done_place(done_place)
        , _nrep(num_repeat)
        , _nwritten(0)
        , _ever_full(false)
        , _last_errno(0) {}
    
    void Download(::google::protobuf::RpcController* cntl_base,
                  const ::test::HttpRequest*,
                  ::test::HttpResponse*,
                  ::google::protobuf::Closure* done) {
        brpc::ClosureGuard done_guard(done);
        brpc::Controller* cntl =
            static_cast<brpc::Controller*>(cntl_base);
        cntl->http_response().set_content_type("text/plain");
        brpc::StopStyle stop_style = (_nrep == std::numeric_limits<size_t>::max() 
                ? brpc::FORCE_STOP : brpc::WAIT_FOR_STOP);
502
        butil::intrusive_ptr<brpc::ProgressiveAttachment> pa(
gejun's avatar
gejun committed
503 504 505 506 507 508 509 510
                cntl->CreateProgressiveAttachment(stop_style));
        if (pa == NULL) {
            cntl->SetFailed("The socket was just failed");
            return;
        }
        if (_done_place == DONE_BEFORE_CREATE_PA) {
            done_guard.reset(NULL);
        }
gejun's avatar
gejun committed
511
        ASSERT_GT(PA_DATA_LEN, 8u);  // long enough to hold a 64-bit decimal.
gejun's avatar
gejun committed
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
        char buf[PA_DATA_LEN];
        for (size_t c = 0; c < _nrep;) {
            CopyPAPrefixedWithSeqNo(buf, c);
            if (pa->Write(buf, sizeof(buf)) != 0) {
                if (errno == brpc::EOVERCROWDED) {
                    LOG_EVERY_SECOND(INFO) << "full pa=" << pa.get();
                    _ever_full = true;
                    bthread_usleep(10000);
                    continue;
                } else {
                    _last_errno = errno;
                    break;
                }
            } else {
                _nwritten += PA_DATA_LEN;
            }
            ++c;
        }
        if (_done_place == DONE_AFTER_CREATE_PA_BEFORE_DESTROY_PA) {
            done_guard.reset(NULL);
        }
        LOG(INFO) << "Destroy pa="  << pa.get();
        pa.reset(NULL);
        if (_done_place == DONE_AFTER_DESTROY_PA) {
            done_guard.reset(NULL);
        }
    }

    void DownloadFailed(::google::protobuf::RpcController* cntl_base,
                        const ::test::HttpRequest*,
                        ::test::HttpResponse*,
                        ::google::protobuf::Closure* done) {
        brpc::ClosureGuard done_guard(done);
        brpc::Controller* cntl =
            static_cast<brpc::Controller*>(cntl_base);
        cntl->http_response().set_content_type("text/plain");
        brpc::StopStyle stop_style = (_nrep == std::numeric_limits<size_t>::max() 
                ? brpc::FORCE_STOP : brpc::WAIT_FOR_STOP);
550
        butil::intrusive_ptr<brpc::ProgressiveAttachment> pa(
gejun's avatar
gejun committed
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
                cntl->CreateProgressiveAttachment(stop_style));
        if (pa == NULL) {
            cntl->SetFailed("The socket was just failed");
            return;
        }
        char buf[PA_DATA_LEN];
        while (true) {
            if (pa->Write(buf, sizeof(buf)) != 0) {
                if (errno == brpc::EOVERCROWDED) {
                    LOG_EVERY_SECOND(INFO) << "full pa=" << pa.get();
                    bthread_usleep(10000);
                    continue;
                } else {
                    _last_errno = errno;
                    break;
                }
            }
            break;
        }
        // The remote client will not receive the data written to the
        // progressive attachment when the controller failed.
        cntl->SetFailed("Intentionally set controller failed");
        done_guard.reset(NULL);
        
        // Return value of Write after controller has failed should
        // be less than zero.
        CHECK_LT(pa->Write(buf, sizeof(buf)), 0);
        CHECK_EQ(errno, ECANCELED);
    }
    
    void set_done_place(DonePlace done_place) { _done_place = done_place; }
    size_t written_bytes() const { return _nwritten; }
    bool ever_full() const { return _ever_full; }
    int last_errno() const { return _last_errno; }
    
private:
    DonePlace _done_place;
    size_t _nrep;
    size_t _nwritten;
    bool _ever_full;
    int _last_errno;
};
    
TEST_F(HttpTest, read_chunked_response_normally) {
    const int port = 8923;
    brpc::Server server;
    DownloadServiceImpl svc;
    EXPECT_EQ(0, server.AddService(&svc, brpc::SERVER_DOESNT_OWN_SERVICE));
    EXPECT_EQ(0, server.Start(port, NULL));

    for (int i = 0; i < 3; ++i) {
        svc.set_done_place((DonePlace)i);
        brpc::Channel channel;
        brpc::ChannelOptions options;
        options.protocol = brpc::PROTOCOL_HTTP;
606
        ASSERT_EQ(0, channel.Init(butil::EndPoint(butil::my_ip(), port), &options));
gejun's avatar
gejun committed
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
        brpc::Controller cntl;
        cntl.http_request().uri() = "/DownloadService/Download";
        channel.CallMethod(NULL, &cntl, NULL, NULL, NULL);
        ASSERT_FALSE(cntl.Failed()) << cntl.ErrorText();

        std::string expected(PA_DATA_LEN, 0);
        CopyPAPrefixedWithSeqNo(&expected[0], 0);
        ASSERT_EQ(expected, cntl.response_attachment());
    }
}

TEST_F(HttpTest, read_failed_chunked_response) {
    const int port = 8923;
    brpc::Server server;
    DownloadServiceImpl svc;
    EXPECT_EQ(0, server.AddService(&svc, brpc::SERVER_DOESNT_OWN_SERVICE));
    EXPECT_EQ(0, server.Start(port, NULL));

    brpc::Channel channel;
    brpc::ChannelOptions options;
    options.protocol = brpc::PROTOCOL_HTTP;
628
    ASSERT_EQ(0, channel.Init(butil::EndPoint(butil::my_ip(), port), &options));
gejun's avatar
gejun committed
629 630 631 632 633

    brpc::Controller cntl;
    cntl.http_request().uri() = "/DownloadService/DownloadFailed";
    cntl.response_will_be_read_progressively();
    channel.CallMethod(NULL, &cntl, NULL, NULL, NULL);
634 635 636 637 638 639
    EXPECT_TRUE(cntl.response_attachment().empty());
    ASSERT_TRUE(cntl.Failed());
    ASSERT_NE(cntl.ErrorText().find("HTTP/1.1 500 Internal Server Error"),
              std::string::npos) << cntl.ErrorText();
    ASSERT_NE(cntl.ErrorText().find("Intentionally set controller failed"),
              std::string::npos) << cntl.ErrorText();
gejun's avatar
gejun committed
640 641 642 643 644 645 646 647 648 649
    ASSERT_EQ(0, svc.last_errno());
}

class ReadBody : public brpc::ProgressiveReader,
                 public brpc::SharedObject {
public:
    ReadBody()
        : _nread(0)
        , _ncount(0)
        , _destroyed(false) {
650
        butil::intrusive_ptr<ReadBody>(this).detach(); // ref
gejun's avatar
gejun committed
651 652
    }
                
653
    butil::Status OnReadOnePart(const void* data, size_t length) {
gejun's avatar
gejun committed
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
        _nread += length;
        while (length > 0) {
            size_t nappend = std::min(_buf.size() + length, PA_DATA_LEN) - _buf.size();
            _buf.append((const char*)data, nappend);
            data = (const char*)data + nappend;
            length -= nappend;
            if (_buf.size() >= PA_DATA_LEN) {
                EXPECT_EQ(PA_DATA_LEN, _buf.size());
                char expected[PA_DATA_LEN];
                CopyPAPrefixedWithSeqNo(expected, _ncount++);
                EXPECT_EQ(0, memcmp(expected, _buf.data(), PA_DATA_LEN))
                    << "ncount=" << _ncount;
                _buf.clear();
            }
        }
669
        return butil::Status::OK();
gejun's avatar
gejun committed
670
    }
671 672
    void OnEndOfMessage(const butil::Status& st) {
        butil::intrusive_ptr<ReadBody>(this, false); // deref
gejun's avatar
gejun committed
673 674 675 676 677 678 679
        ASSERT_LT(_buf.size(), PA_DATA_LEN);
        ASSERT_EQ(0, memcmp(_buf.data(), PA_DATA, _buf.size()));
        _destroyed = true;
        _destroying_st = st;
        LOG(INFO) << "Destroy ReadBody=" << this << ", " << st;
    }
    bool destroyed() const { return _destroyed; }
680
    const butil::Status& destroying_status() const { return _destroying_st; }
gejun's avatar
gejun committed
681 682 683 684 685 686
    size_t read_bytes() const { return _nread; }
private:
    std::string _buf;
    size_t _nread;
    size_t _ncount;
    bool _destroyed;
687
    butil::Status _destroying_st;
gejun's avatar
gejun committed
688 689 690 691 692
};

static const int GENERAL_DELAY_US = 300000; // 0.3s

TEST_F(HttpTest, read_long_body_progressively) {
693
    butil::intrusive_ptr<ReadBody> reader;
gejun's avatar
gejun committed
694 695 696 697 698 699 700 701 702 703
    {
        const int port = 8923;
        brpc::Server server;
        DownloadServiceImpl svc(DONE_BEFORE_CREATE_PA,
                                std::numeric_limits<size_t>::max());
        EXPECT_EQ(0, server.AddService(&svc, brpc::SERVER_DOESNT_OWN_SERVICE));
        EXPECT_EQ(0, server.Start(port, NULL));
        {
            brpc::Channel channel;
            brpc::ChannelOptions options;
704
            options.protocol = brpc::PROTOCOL_HTTP;
705
            ASSERT_EQ(0, channel.Init(butil::EndPoint(butil::my_ip(), port), &options));
gejun's avatar
gejun committed
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
            {
                brpc::Controller cntl;
                cntl.response_will_be_read_progressively();
                cntl.http_request().uri() = "/DownloadService/Download";
                channel.CallMethod(NULL, &cntl, NULL, NULL, NULL);
                ASSERT_FALSE(cntl.Failed()) << cntl.ErrorText();
                ASSERT_TRUE(cntl.response_attachment().empty());
                reader.reset(new ReadBody);
                cntl.ReadProgressiveAttachmentBy(reader.get());
                size_t last_read = 0;
                for (size_t i = 0; i < 3; ++i) {
                    sleep(1);
                    size_t current_read = reader->read_bytes();
                    LOG(INFO) << "read=" << current_read - last_read
                              << " total=" << current_read;
                    last_read = current_read;
                }
                // Read something in past N seconds.
724
                ASSERT_GT(last_read, (size_t)100000);
gejun's avatar
gejun committed
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
            }
            // the socket still holds a ref.
            ASSERT_FALSE(reader->destroyed());
        }
        // Wait for recycling of the main socket.
        usleep(GENERAL_DELAY_US);
        // even if the main socket is recycled, the pooled socket for
        // receiving data is not affected.
        ASSERT_FALSE(reader->destroyed());
    }
    // Wait for close of the connection due to server's stopping.
    usleep(GENERAL_DELAY_US);
    ASSERT_TRUE(reader->destroyed());
    ASSERT_EQ(ECONNRESET, reader->destroying_status().error_code());
}

TEST_F(HttpTest, read_short_body_progressively) {
742
    butil::intrusive_ptr<ReadBody> reader;
gejun's avatar
gejun committed
743 744 745 746 747 748 749 750 751 752
    const int port = 8923;
    brpc::Server server;
    const int NREP = 10000;
    DownloadServiceImpl svc(DONE_BEFORE_CREATE_PA, NREP);
    EXPECT_EQ(0, server.AddService(&svc, brpc::SERVER_DOESNT_OWN_SERVICE));
    EXPECT_EQ(0, server.Start(port, NULL));
    {
        brpc::Channel channel;
        brpc::ChannelOptions options;
        options.protocol = brpc::PROTOCOL_HTTP;
753
        ASSERT_EQ(0, channel.Init(butil::EndPoint(butil::my_ip(), port), &options));
gejun's avatar
gejun committed
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
        {
            brpc::Controller cntl;
            cntl.response_will_be_read_progressively();
            cntl.http_request().uri() = "/DownloadService/Download";
            channel.CallMethod(NULL, &cntl, NULL, NULL, NULL);
            ASSERT_FALSE(cntl.Failed()) << cntl.ErrorText();
            ASSERT_TRUE(cntl.response_attachment().empty());
            reader.reset(new ReadBody);
            cntl.ReadProgressiveAttachmentBy(reader.get());
            size_t last_read = 0;
            for (size_t i = 0; i < 3; ++i) {
                sleep(1);
                size_t current_read = reader->read_bytes();
                LOG(INFO) << "read=" << current_read - last_read
                          << " total=" << current_read;
                last_read = current_read;
            }
            ASSERT_EQ(NREP * PA_DATA_LEN, svc.written_bytes());
            ASSERT_EQ(NREP * PA_DATA_LEN, last_read);
        }
        ASSERT_TRUE(reader->destroyed());
        ASSERT_EQ(0, reader->destroying_status().error_code());
    }
}

TEST_F(HttpTest, read_progressively_after_cntl_destroys) {
780
    butil::intrusive_ptr<ReadBody> reader;
gejun's avatar
gejun committed
781 782 783 784 785 786 787 788 789 790 791
    {
        const int port = 8923;
        brpc::Server server;
        DownloadServiceImpl svc(DONE_BEFORE_CREATE_PA,
                                std::numeric_limits<size_t>::max());
        EXPECT_EQ(0, server.AddService(&svc, brpc::SERVER_DOESNT_OWN_SERVICE));
        EXPECT_EQ(0, server.Start(port, NULL));
        {
            brpc::Channel channel;
            brpc::ChannelOptions options;
            options.protocol = brpc::PROTOCOL_HTTP;
792
            ASSERT_EQ(0, channel.Init(butil::EndPoint(butil::my_ip(), port), &options));
gejun's avatar
gejun committed
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
            {
                brpc::Controller cntl;
                cntl.response_will_be_read_progressively();
                cntl.http_request().uri() = "/DownloadService/Download";
                channel.CallMethod(NULL, &cntl, NULL, NULL, NULL);
                ASSERT_FALSE(cntl.Failed()) << cntl.ErrorText();
                ASSERT_TRUE(cntl.response_attachment().empty());
                reader.reset(new ReadBody);
                cntl.ReadProgressiveAttachmentBy(reader.get());
            }
            size_t last_read = 0;
            for (size_t i = 0; i < 3; ++i) {
                sleep(1);
                size_t current_read = reader->read_bytes();
                LOG(INFO) << "read=" << current_read - last_read
                          << " total=" << current_read;
                last_read = current_read;
            }
            // Read something in past N seconds.
812
            ASSERT_GT(last_read, (size_t)100000);
gejun's avatar
gejun committed
813 814 815 816 817 818 819 820 821 822 823 824 825
            ASSERT_FALSE(reader->destroyed());
        }
        // Wait for recycling of the main socket.
        usleep(GENERAL_DELAY_US);
        ASSERT_FALSE(reader->destroyed());
    }
    // Wait for close of the connection due to server's stopping.
    usleep(GENERAL_DELAY_US);
    ASSERT_TRUE(reader->destroyed());
    ASSERT_EQ(ECONNRESET, reader->destroying_status().error_code());
}

TEST_F(HttpTest, read_progressively_after_long_delay) {
826
    butil::intrusive_ptr<ReadBody> reader;
gejun's avatar
gejun committed
827 828 829 830 831 832 833 834 835 836 837
    {
        const int port = 8923;
        brpc::Server server;
        DownloadServiceImpl svc(DONE_BEFORE_CREATE_PA,
                                std::numeric_limits<size_t>::max());
        EXPECT_EQ(0, server.AddService(&svc, brpc::SERVER_DOESNT_OWN_SERVICE));
        EXPECT_EQ(0, server.Start(port, NULL));
        {
            brpc::Channel channel;
            brpc::ChannelOptions options;
            options.protocol = brpc::PROTOCOL_HTTP;
838
            ASSERT_EQ(0, channel.Init(butil::EndPoint(butil::my_ip(), port), &options));
gejun's avatar
gejun committed
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
            {
                brpc::Controller cntl;
                cntl.response_will_be_read_progressively();
                cntl.http_request().uri() = "/DownloadService/Download";
                channel.CallMethod(NULL, &cntl, NULL, NULL, NULL);
                ASSERT_FALSE(cntl.Failed()) << cntl.ErrorText();
                ASSERT_TRUE(cntl.response_attachment().empty());
                LOG(INFO) << "Sleep 3 seconds to make PA at server-side full";
                sleep(3);
                EXPECT_TRUE(svc.ever_full());
                ASSERT_EQ(0, svc.last_errno());
                reader.reset(new ReadBody);
                cntl.ReadProgressiveAttachmentBy(reader.get());
                size_t last_read = 0;
                for (size_t i = 0; i < 3; ++i) {
                    sleep(1);
                    size_t current_read = reader->read_bytes();
                    LOG(INFO) << "read=" << current_read - last_read
                              << " total=" << current_read;
                    last_read = current_read;
                }
                // Read something in past N seconds.
861
                ASSERT_GT(last_read, (size_t)100000);
gejun's avatar
gejun committed
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
            }
            ASSERT_FALSE(reader->destroyed());
        }
        // Wait for recycling of the main socket.
        usleep(GENERAL_DELAY_US);
        ASSERT_FALSE(reader->destroyed());
    }
    // Wait for close of the connection due to server's stopping.
    usleep(GENERAL_DELAY_US);
    ASSERT_TRUE(reader->destroyed());
    ASSERT_EQ(ECONNRESET, reader->destroying_status().error_code());
}

TEST_F(HttpTest, skip_progressive_reading) {
    const int port = 8923;
    brpc::Server server;
    DownloadServiceImpl svc(DONE_BEFORE_CREATE_PA,
                            std::numeric_limits<size_t>::max());
    EXPECT_EQ(0, server.AddService(&svc, brpc::SERVER_DOESNT_OWN_SERVICE));
    EXPECT_EQ(0, server.Start(port, NULL));
    brpc::Channel channel;
    brpc::ChannelOptions options;
    options.protocol = brpc::PROTOCOL_HTTP;
885
    ASSERT_EQ(0, channel.Init(butil::EndPoint(butil::my_ip(), port), &options));
gejun's avatar
gejun committed
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
    {
        brpc::Controller cntl;
        cntl.response_will_be_read_progressively();
        cntl.http_request().uri() = "/DownloadService/Download";
        channel.CallMethod(NULL, &cntl, NULL, NULL, NULL);
        ASSERT_FALSE(cntl.Failed()) << cntl.ErrorText();
        ASSERT_TRUE(cntl.response_attachment().empty());
    }
    const size_t old_written_bytes = svc.written_bytes();
    LOG(INFO) << "Sleep 3 seconds after destroy of Controller";
    sleep(3);
    const size_t new_written_bytes = svc.written_bytes();
    ASSERT_EQ(0, svc.last_errno());
    LOG(INFO) << "Server still wrote " << new_written_bytes - old_written_bytes;
    // The server side still wrote things.
901
    ASSERT_GT(new_written_bytes - old_written_bytes, (size_t)100000);
gejun's avatar
gejun committed
902 903 904 905 906
}

class AlwaysFailRead : public brpc::ProgressiveReader {
public:
    // @ProgressiveReader
907 908
    butil::Status OnReadOnePart(const void* /*data*/, size_t /*length*/) {
        return butil::Status(-1, "intended fail at %s:%d", __FILE__, __LINE__);
gejun's avatar
gejun committed
909
    }
910
    void OnEndOfMessage(const butil::Status& st) {
gejun's avatar
gejun committed
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
        LOG(INFO) << "Destroy " << this << ": " << st;
        delete this;
    }
};

TEST_F(HttpTest, failed_on_read_one_part) {
    const int port = 8923;
    brpc::Server server;
    DownloadServiceImpl svc(DONE_BEFORE_CREATE_PA,
                            std::numeric_limits<size_t>::max());
    EXPECT_EQ(0, server.AddService(&svc, brpc::SERVER_DOESNT_OWN_SERVICE));
    EXPECT_EQ(0, server.Start(port, NULL));
    brpc::Channel channel;
    brpc::ChannelOptions options;
    options.protocol = brpc::PROTOCOL_HTTP;
926
    ASSERT_EQ(0, channel.Init(butil::EndPoint(butil::my_ip(), port), &options));
gejun's avatar
gejun committed
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
    {
        brpc::Controller cntl;
        cntl.response_will_be_read_progressively();
        cntl.http_request().uri() = "/DownloadService/Download";
        channel.CallMethod(NULL, &cntl, NULL, NULL, NULL);
        ASSERT_FALSE(cntl.Failed()) << cntl.ErrorText();
        ASSERT_TRUE(cntl.response_attachment().empty());
        cntl.ReadProgressiveAttachmentBy(new AlwaysFailRead);
    }
    LOG(INFO) << "Sleep 1 second";
    sleep(1);
    ASSERT_NE(0, svc.last_errno());
}

TEST_F(HttpTest, broken_socket_stops_progressive_reading) {
942
    butil::intrusive_ptr<ReadBody> reader;
gejun's avatar
gejun committed
943 944 945 946 947 948 949 950 951 952
    const int port = 8923;
    brpc::Server server;
    DownloadServiceImpl svc(DONE_BEFORE_CREATE_PA,
                            std::numeric_limits<size_t>::max());
    EXPECT_EQ(0, server.AddService(&svc, brpc::SERVER_DOESNT_OWN_SERVICE));
    EXPECT_EQ(0, server.Start(port, NULL));
        
    brpc::Channel channel;
    brpc::ChannelOptions options;
    options.protocol = brpc::PROTOCOL_HTTP;
953
    ASSERT_EQ(0, channel.Init(butil::EndPoint(butil::my_ip(), port), &options));
gejun's avatar
gejun committed
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
    {
        brpc::Controller cntl;
        cntl.response_will_be_read_progressively();
        cntl.http_request().uri() = "/DownloadService/Download";
        channel.CallMethod(NULL, &cntl, NULL, NULL, NULL);
        ASSERT_FALSE(cntl.Failed()) << cntl.ErrorText();
        ASSERT_TRUE(cntl.response_attachment().empty());
        reader.reset(new ReadBody);
        cntl.ReadProgressiveAttachmentBy(reader.get());
        size_t last_read = 0;
        for (size_t i = 0; i < 3; ++i) {
            sleep(1);
            size_t current_read = reader->read_bytes();
            LOG(INFO) << "read=" << current_read - last_read
                      << " total=" << current_read;
            last_read = current_read;
        }
        // Read something in past N seconds.
972
        ASSERT_GT(last_read, (size_t)100000);
gejun's avatar
gejun committed
973 974 975 976 977 978 979 980 981 982 983 984
    }
    // the socket still holds a ref.
    ASSERT_FALSE(reader->destroyed());
    LOG(INFO) << "Stopping the server";
    server.Stop(0);
    server.Join();
        
    // Wait for error reporting from the socket.
    usleep(GENERAL_DELAY_US);
    ASSERT_TRUE(reader->destroyed());
    ASSERT_EQ(ECONNRESET, reader->destroying_status().error_code());
}
zhujiashun's avatar
zhujiashun committed
985 986 987 988 989 990 991 992 993

TEST_F(HttpTest, http2_sanity) {
    const int port = 8923;
    brpc::Server server;
    EXPECT_EQ(0, server.AddService(&_svc, brpc::SERVER_DOESNT_OWN_SERVICE));
    EXPECT_EQ(0, server.Start(port, NULL));

    brpc::Channel channel;
    brpc::ChannelOptions options;
994
    options.protocol = "h2";
zhujiashun's avatar
zhujiashun committed
995 996
    ASSERT_EQ(0, channel.Init(butil::EndPoint(butil::my_ip(), port), &options));

997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
    // Check that the first request with size larger than the default window can
    // be sent out, when remote settings are not received.
    brpc::Controller cntl;
    test::EchoRequest big_req;
    test::EchoResponse res;
    std::string message(2 * 1024 * 1024 /* 2M */, 'x');
    big_req.set_message(message);
    cntl.http_request().set_method(brpc::HTTP_METHOD_POST);
    cntl.http_request().uri() = "/EchoService/Echo";
    channel.CallMethod(NULL, &cntl, &big_req, &res, NULL);
    ASSERT_FALSE(cntl.Failed());
    ASSERT_EQ(EXP_RESPONSE, res.message());

    // socket replacement when streamId runs out, the initial streamId is a special
    // value set in ctor of H2Context so that the number 15000 is enough to run out
    // of stream.
zhujiashun's avatar
zhujiashun committed
1013 1014
    test::EchoRequest req;
    req.set_message(EXP_REQUEST);
1015
    for (int i = 0; i < 15000; ++i) {
zhujiashun's avatar
zhujiashun committed
1016 1017 1018 1019 1020 1021 1022 1023
        brpc::Controller cntl;
        cntl.http_request().set_content_type("application/json");
        cntl.http_request().set_method(brpc::HTTP_METHOD_POST);
        cntl.http_request().uri() = "/EchoService/Echo";
        channel.CallMethod(NULL, &cntl, &req, &res, NULL);
        ASSERT_FALSE(cntl.Failed());
        ASSERT_EQ(EXP_RESPONSE, res.message());
    }
1024 1025 1026 1027 1028 1029 1030 1031 1032

    // check connection window size
    brpc::SocketUniquePtr main_ptr;
    brpc::SocketUniquePtr agent_ptr;
    EXPECT_EQ(brpc::Socket::Address(channel._server_id, &main_ptr), 0);
    EXPECT_EQ(main_ptr->GetAgentSocket(&agent_ptr, NULL), 0);
    brpc::policy::H2Context* ctx = static_cast<brpc::policy::H2Context*>(agent_ptr->parsing_context());
    ASSERT_GT(ctx->_remote_window_left.load(butil::memory_order_relaxed),
             brpc::H2Settings::DEFAULT_INITIAL_WINDOW_SIZE / 2);
zhujiashun's avatar
zhujiashun committed
1033
}
zhujiashun's avatar
zhujiashun committed
1034 1035 1036 1037 1038 1039 1040 1041

TEST_F(HttpTest, http2_ping) {
    // This test injects PING frames before and after header and data.
    brpc::Controller cntl;

    // Prepare request
    butil::IOBuf req_out;
    int h2_stream_id = 0;
1042
    MakeH2EchoRequestBuf(&req_out, &cntl, &h2_stream_id);
zhujiashun's avatar
zhujiashun committed
1043 1044 1045 1046 1047
    // Prepare response
    butil::IOBuf res_out;
    char pingbuf[9 /*FRAME_HEAD_SIZE*/ + 8 /*Opaque Data*/];
    brpc::policy::SerializeFrameHead(pingbuf, 8, brpc::policy::H2_FRAME_PING, 0, 0);
    // insert ping before header and data
1048 1049
    res_out.append(pingbuf, sizeof(pingbuf));
    MakeH2EchoResponseBuf(&res_out, h2_stream_id);
zhujiashun's avatar
zhujiashun committed
1050
    // insert ping after header and data
1051
    res_out.append(pingbuf, sizeof(pingbuf));
zhujiashun's avatar
zhujiashun committed
1052 1053
    // parse response
    brpc::ParseResult res_pr =
1054
            brpc::policy::ParseH2Message(&res_out, _h2_client_sock.get(), false, NULL);
zhujiashun's avatar
zhujiashun committed
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
    ASSERT_TRUE(res_pr.is_ok());
    // process response
    ProcessMessage(brpc::policy::ProcessHttpResponse, res_pr.message(), false);
    ASSERT_FALSE(cntl.Failed());
}

inline void SaveUint32(void* out, uint32_t v) {
    uint8_t* p = (uint8_t*)out;
    p[0] = (v >> 24) & 0xFF;
    p[1] = (v >> 16) & 0xFF;
    p[2] = (v >> 8) & 0xFF;
    p[3] = v & 0xFF;
}

TEST_F(HttpTest, http2_rst_before_header) {
    brpc::Controller cntl;
    // Prepare request
    butil::IOBuf req_out;
    int h2_stream_id = 0;
1074
    MakeH2EchoRequestBuf(&req_out, &cntl, &h2_stream_id);
zhujiashun's avatar
zhujiashun committed
1075 1076 1077 1078 1079
    // Prepare response
    butil::IOBuf res_out;
    char rstbuf[9 /*FRAME_HEAD_SIZE*/ + 4];
    brpc::policy::SerializeFrameHead(rstbuf, 4, brpc::policy::H2_FRAME_RST_STREAM, 0, h2_stream_id);
    SaveUint32(rstbuf + 9, brpc::H2_INTERNAL_ERROR);
1080 1081
    res_out.append(rstbuf, sizeof(rstbuf));
    MakeH2EchoResponseBuf(&res_out, h2_stream_id);
zhujiashun's avatar
zhujiashun committed
1082 1083
    // parse response
    brpc::ParseResult res_pr =
1084
            brpc::policy::ParseH2Message(&res_out, _h2_client_sock.get(), false, NULL);
zhujiashun's avatar
zhujiashun committed
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
    ASSERT_TRUE(res_pr.is_ok());
    // process response
    ProcessMessage(brpc::policy::ProcessHttpResponse, res_pr.message(), false);
    ASSERT_TRUE(cntl.Failed());
    ASSERT_TRUE(cntl.ErrorCode() == brpc::EHTTP);
    ASSERT_TRUE(cntl.http_response().status_code() == brpc::HTTP_STATUS_INTERNAL_SERVER_ERROR);
}

TEST_F(HttpTest, http2_rst_after_header_and_data) {
    brpc::Controller cntl;
    // Prepare request
    butil::IOBuf req_out;
    int h2_stream_id = 0;
1098
    MakeH2EchoRequestBuf(&req_out, &cntl, &h2_stream_id);
zhujiashun's avatar
zhujiashun committed
1099 1100
    // Prepare response
    butil::IOBuf res_out;
1101
    MakeH2EchoResponseBuf(&res_out, h2_stream_id);
zhujiashun's avatar
zhujiashun committed
1102 1103 1104
    char rstbuf[9 /*FRAME_HEAD_SIZE*/ + 4];
    brpc::policy::SerializeFrameHead(rstbuf, 4, brpc::policy::H2_FRAME_RST_STREAM, 0, h2_stream_id);
    SaveUint32(rstbuf + 9, brpc::H2_INTERNAL_ERROR);
1105
    res_out.append(rstbuf, sizeof(rstbuf));
zhujiashun's avatar
zhujiashun committed
1106 1107
    // parse response
    brpc::ParseResult res_pr =
1108
            brpc::policy::ParseH2Message(&res_out, _h2_client_sock.get(), false, NULL);
zhujiashun's avatar
zhujiashun committed
1109 1110 1111 1112 1113 1114 1115
    ASSERT_TRUE(res_pr.is_ok());
    // process response
    ProcessMessage(brpc::policy::ProcessHttpResponse, res_pr.message(), false);
    ASSERT_FALSE(cntl.Failed());
    ASSERT_TRUE(cntl.http_response().status_code() == brpc::HTTP_STATUS_OK);
}

1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
TEST_F(HttpTest, http2_window_used_up) {
    brpc::Controller cntl;
    butil::IOBuf request_buf;
    test::EchoRequest req;
    // longer message to trigger using up window size sooner
    req.set_message("FLOW_CONTROL_FLOW_CONTROL");
    cntl.http_request().set_method(brpc::HTTP_METHOD_POST);
    cntl.http_request().set_content_type("application/proto");
    brpc::policy::SerializeHttpRequest(&request_buf, &cntl, &req);

1126 1127 1128 1129 1130 1131 1132 1133
    char settingsbuf[brpc::policy::FRAME_HEAD_SIZE + 36];
    brpc::H2Settings h2_settings;
    const size_t nb = brpc::policy::SerializeH2Settings(h2_settings, settingsbuf + brpc::policy::FRAME_HEAD_SIZE);
    brpc::policy::SerializeFrameHead(settingsbuf, nb, brpc::policy::H2_FRAME_SETTINGS, 0, 0);
    butil::IOBuf buf;
    buf.append(settingsbuf, brpc::policy::FRAME_HEAD_SIZE + nb);
    brpc::policy::ParseH2Message(&buf, _h2_client_sock.get(), false, NULL);

1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
    int nsuc = brpc::H2Settings::DEFAULT_INITIAL_WINDOW_SIZE / cntl.request_attachment().size();
    for (int i = 0; i <= nsuc; i++) {
        brpc::policy::H2UnsentRequest* h2_req = brpc::policy::H2UnsentRequest::New(&cntl);
        cntl._current_call.stream_user_data = h2_req;
        brpc::SocketMessage* socket_message = NULL;
        brpc::policy::PackH2Request(NULL, &socket_message, cntl.call_id().value,
                                    NULL, &cntl, request_buf, NULL);
        butil::IOBuf dummy;
        butil::Status st = socket_message->AppendAndDestroySelf(&dummy, _h2_client_sock.get());
        if (i == nsuc) {
            // the last message should fail according to flow control policy.
            ASSERT_FALSE(st.ok());
1146
            ASSERT_TRUE(st.error_code() == brpc::ELIMIT);
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
            ASSERT_TRUE(butil::StringPiece(st.error_str()).starts_with("remote_window_left is not enough"));
        } else {
            ASSERT_TRUE(st.ok());
        }
        h2_req->DestroyStreamUserData(_h2_client_sock, &cntl, 0, false);
    }
}

TEST_F(HttpTest, http2_settings) {
    char settingsbuf[brpc::policy::FRAME_HEAD_SIZE + 36];
    brpc::H2Settings h2_settings;
    h2_settings.header_table_size = 8192;
    h2_settings.max_concurrent_streams = 1024;
    h2_settings.stream_window_size= (1u << 29) - 1;
    const size_t nb = brpc::policy::SerializeH2Settings(h2_settings, settingsbuf + brpc::policy::FRAME_HEAD_SIZE);
    brpc::policy::SerializeFrameHead(settingsbuf, nb, brpc::policy::H2_FRAME_SETTINGS, 0, 0);
    butil::IOBuf buf;
    buf.append(settingsbuf, brpc::policy::FRAME_HEAD_SIZE + nb);

    brpc::policy::H2Context* ctx = new brpc::policy::H2Context(_socket.get(), NULL);
    CHECK_EQ(ctx->Init(), 0);
    _socket->initialize_parsing_context(&ctx);
    ctx->_conn_state = brpc::policy::H2_CONNECTION_READY;
    // parse settings
    brpc::policy::ParseH2Message(&buf, _socket.get(), false, NULL);

    butil::IOPortal response_buf;
1174 1175
    CHECK_EQ(response_buf.append_from_file_descriptor(_pipe_fds[0], 1024),
             (ssize_t)brpc::policy::FRAME_HEAD_SIZE);
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
    brpc::policy::H2FrameHead frame_head;
    butil::IOBufBytesIterator it(response_buf);
    ctx->ConsumeFrameHead(it, &frame_head);
    CHECK_EQ(frame_head.type, brpc::policy::H2_FRAME_SETTINGS);
    CHECK_EQ(frame_head.flags, 0x01 /* H2_FLAGS_ACK */);
    CHECK_EQ(frame_head.stream_id, 0);
    ASSERT_TRUE(ctx->_remote_settings.header_table_size == 8192);
    ASSERT_TRUE(ctx->_remote_settings.max_concurrent_streams == 1024);
    ASSERT_TRUE(ctx->_remote_settings.stream_window_size == (1u << 29) - 1);
}

TEST_F(HttpTest, http2_invalid_settings) {
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
    {
        brpc::Server server;
        brpc::ServerOptions options;
        options.h2_settings.stream_window_size = brpc::H2Settings::MAX_WINDOW_SIZE + 1;
        ASSERT_EQ(-1, server.Start("127.0.0.1:8924", &options));
    }
    {
        brpc::Server server;
        brpc::ServerOptions options;
        options.h2_settings.max_frame_size =
            brpc::H2Settings::DEFAULT_MAX_FRAME_SIZE - 1;
        ASSERT_EQ(-1, server.Start("127.0.0.1:8924", &options));
    }
    {
        brpc::Server server;
        brpc::ServerOptions options;
        options.h2_settings.max_frame_size =
            brpc::H2Settings::MAX_OF_MAX_FRAME_SIZE + 1;
        ASSERT_EQ(-1, server.Start("127.0.0.1:8924", &options));
    }
1208 1209
}

1210 1211 1212 1213 1214 1215 1216
TEST_F(HttpTest, http2_not_closing_socket_when_rpc_timeout) {
    const int port = 8923;
    brpc::Server server;
    EXPECT_EQ(0, server.AddService(&_svc, brpc::SERVER_DOESNT_OWN_SERVICE));
    EXPECT_EQ(0, server.Start(port, NULL));
    brpc::Channel channel;
    brpc::ChannelOptions options;
1217
    options.protocol = "h2";
1218
    ASSERT_EQ(0, channel.Init(butil::EndPoint(butil::my_ip(), port), &options));
1219

1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
    test::EchoRequest req;
    test::EchoResponse res;
    req.set_message(EXP_REQUEST);
    {
        // make a successful call to create the connection first
        brpc::Controller cntl;
        cntl.http_request().set_method(brpc::HTTP_METHOD_POST);
        cntl.http_request().uri() = "/EchoService/Echo";
        channel.CallMethod(NULL, &cntl, &req, &res, NULL);
        ASSERT_FALSE(cntl.Failed());
        ASSERT_EQ(EXP_RESPONSE, res.message());
    }

    brpc::SocketUniquePtr main_ptr;
    EXPECT_EQ(brpc::Socket::Address(channel._server_id, &main_ptr), 0);
    brpc::SocketId agent_id = main_ptr->_agent_socket_id.load(butil::memory_order_relaxed);

    for (int i = 0; i < 4; i++) {
        brpc::Controller cntl;
        cntl.set_timeout_ms(50);
        cntl.http_request().set_method(brpc::HTTP_METHOD_POST);
        cntl.http_request().uri() = "/EchoService/Echo?sleep_ms=300";
        channel.CallMethod(NULL, &cntl, &req, &res, NULL);
        ASSERT_TRUE(cntl.Failed());

        brpc::SocketUniquePtr ptr;
        brpc::SocketId id = main_ptr->_agent_socket_id.load(butil::memory_order_relaxed);
        EXPECT_EQ(id, agent_id);
    }

    {
        // make a successful call again to make sure agent_socket not changing
        brpc::Controller cntl;
        cntl.http_request().set_method(brpc::HTTP_METHOD_POST);
        cntl.http_request().uri() = "/EchoService/Echo";
        channel.CallMethod(NULL, &cntl, &req, &res, NULL);
        ASSERT_FALSE(cntl.Failed());
        ASSERT_EQ(EXP_RESPONSE, res.message());
        brpc::SocketUniquePtr ptr;
        brpc::SocketId id = main_ptr->_agent_socket_id.load(butil::memory_order_relaxed);
        EXPECT_EQ(id, agent_id);
    }
1262 1263
}

1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
TEST_F(HttpTest, http2_header_after_data) {
    brpc::Controller cntl;

    // Prepare request
    butil::IOBuf req_out;
    int h2_stream_id = 0;
    MakeH2EchoRequestBuf(&req_out, &cntl, &h2_stream_id);

    // Prepare response to res_out
    butil::IOBuf res_out;
    {
        butil::IOBuf data_buf;
        test::EchoResponse res;
        res.set_message(EXP_RESPONSE);
        {
            butil::IOBufAsZeroCopyOutputStream wrapper(&data_buf);
            EXPECT_TRUE(res.SerializeToZeroCopyStream(&wrapper));
        }
        brpc::policy::H2Context* ctx =
            static_cast<brpc::policy::H2Context*>(_h2_client_sock->parsing_context());
        brpc::HPacker& hpacker = ctx->hpacker();
        butil::IOBufAppender header1_appender;
        brpc::HPackOptions options;
        options.encode_name = false;    /* disable huffman encoding */
        options.encode_value = false;
        {
            brpc::HPacker::Header header(":status", "200");
            hpacker.Encode(&header1_appender, header, options);
        }
        {
            brpc::HPacker::Header header("content-length",
                    butil::string_printf("%" PRIu64, data_buf.size()));
            hpacker.Encode(&header1_appender, header, options);
        }
        {
            brpc::HPacker::Header header(":status", "200");
            hpacker.Encode(&header1_appender, header, options);
        }
        {
            brpc::HPacker::Header header("content-type", "application/proto");
            hpacker.Encode(&header1_appender, header, options);
        }
        {
            brpc::HPacker::Header header("user-defined1", "a");
            hpacker.Encode(&header1_appender, header, options);
        }
        butil::IOBuf header1;
        header1_appender.move_to(header1);

        char headbuf[brpc::policy::FRAME_HEAD_SIZE];
        brpc::policy::SerializeFrameHead(headbuf, header1.size(),
                brpc::policy::H2_FRAME_HEADERS, 0, h2_stream_id);
        // append header1
        res_out.append(headbuf, sizeof(headbuf));
        res_out.append(butil::IOBuf::Movable(header1));

        brpc::policy::SerializeFrameHead(headbuf, data_buf.size(),
            brpc::policy::H2_FRAME_DATA, 0, h2_stream_id);
        // append data
        res_out.append(headbuf, sizeof(headbuf));
        res_out.append(butil::IOBuf::Movable(data_buf));

        butil::IOBufAppender header2_appender;
        {
            brpc::HPacker::Header header("user-defined1", "overwrite-a");
            hpacker.Encode(&header2_appender, header, options);
        }
        {
            brpc::HPacker::Header header("user-defined2", "b");
            hpacker.Encode(&header2_appender, header, options);
        }
        butil::IOBuf header2;
        header2_appender.move_to(header2);

        brpc::policy::SerializeFrameHead(headbuf, header2.size(),
                brpc::policy::H2_FRAME_HEADERS, 0x05/* end header and stream */,
                h2_stream_id);
        // append header2
        res_out.append(headbuf, sizeof(headbuf));
        res_out.append(butil::IOBuf::Movable(header2));
    }
    // parse response
    brpc::ParseResult res_pr =
            brpc::policy::ParseH2Message(&res_out, _h2_client_sock.get(), false, NULL);
    ASSERT_TRUE(res_pr.is_ok());
    // process response
    ProcessMessage(brpc::policy::ProcessHttpResponse, res_pr.message(), false);
    ASSERT_FALSE(cntl.Failed());

    brpc::HttpHeader& res_header = cntl.http_response();
    ASSERT_EQ(res_header.content_type(), "application/proto");
    // Check overlapped header is overwritten by the latter.
    const std::string* user_defined1 = res_header.GetHeader("user-defined1");
    ASSERT_EQ(*user_defined1, "overwrite-a");
    const std::string* user_defined2 = res_header.GetHeader("user-defined2");
    ASSERT_EQ(*user_defined2, "b");
}

1362
TEST_F(HttpTest, http2_goaway_sanity) {
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
    brpc::Controller cntl;
    // Prepare request
    butil::IOBuf req_out;
    int h2_stream_id = 0;
    MakeH2EchoRequestBuf(&req_out, &cntl, &h2_stream_id);
    // Prepare response
    butil::IOBuf res_out;
    MakeH2EchoResponseBuf(&res_out, h2_stream_id);
    // append goaway
    char goawaybuf[9 /*FRAME_HEAD_SIZE*/ + 8];
    brpc::policy::SerializeFrameHead(goawaybuf, 8, brpc::policy::H2_FRAME_GOAWAY, 0, 0);
    SaveUint32(goawaybuf + 9, 0x7fffd8ef /*last stream id*/);
    SaveUint32(goawaybuf + 13, brpc::H2_NO_ERROR);
    res_out.append(goawaybuf, sizeof(goawaybuf));
    // parse response
    brpc::ParseResult res_pr =
            brpc::policy::ParseH2Message(&res_out, _h2_client_sock.get(), false, NULL);
    ASSERT_TRUE(res_pr.is_ok());
    // process response
    ProcessMessage(brpc::policy::ProcessHttpResponse, res_pr.message(), false);
    ASSERT_TRUE(!cntl.Failed());

    // parse GOAWAY
    res_pr = brpc::policy::ParseH2Message(&res_out, _h2_client_sock.get(), false, NULL);
    ASSERT_EQ(res_pr.error(), brpc::PARSE_ERROR_NOT_ENOUGH_DATA);

    // Since GOAWAY has been received, the next request should fail
    brpc::policy::H2UnsentRequest* h2_req = brpc::policy::H2UnsentRequest::New(&cntl);
    cntl._current_call.stream_user_data = h2_req;
    brpc::SocketMessage* socket_message = NULL;
    brpc::policy::PackH2Request(NULL, &socket_message, cntl.call_id().value,
                                NULL, &cntl, butil::IOBuf(), NULL);
    butil::IOBuf dummy;
    butil::Status st = socket_message->AppendAndDestroySelf(&dummy, _h2_client_sock.get());
    ASSERT_EQ(st.error_code(), brpc::ELOGOFF);
    ASSERT_TRUE(st.error_data().ends_with("the connection just issued GOAWAY"));
}

1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
class AfterRecevingGoAway : public ::google::protobuf::Closure {
public:
    void Run() {
        ASSERT_EQ(brpc::EHTTP, cntl.ErrorCode());
        delete this;
    }
    brpc::Controller cntl;
};

TEST_F(HttpTest, http2_handle_goaway_streams) {
    const butil::EndPoint ep(butil::IP_ANY, 5961);
    butil::fd_guard listenfd(butil::tcp_listen(ep));
    ASSERT_GT(listenfd, 0);

    brpc::Channel channel;
    brpc::ChannelOptions options;
    options.protocol = brpc::PROTOCOL_H2;
    ASSERT_EQ(0, channel.Init(ep, &options));

    int req_size = 10;
    std::vector<brpc::CallId> ids(req_size);
    for (int i = 0; i < req_size; i++) {
        AfterRecevingGoAway* done = new AfterRecevingGoAway;
        brpc::Controller& cntl = done->cntl;
        ids.push_back(cntl.call_id());
        cntl.set_timeout_ms(-1);
        cntl.http_request().uri() = "/it-doesnt-matter";
        channel.CallMethod(NULL, &cntl, NULL, NULL, done);
    }

    int servfd = accept(listenfd, NULL, NULL);
    ASSERT_GT(servfd, 0);
    // Sleep for a while to make sure that server has received all data.
    bthread_usleep(2000);
    char goawaybuf[brpc::policy::FRAME_HEAD_SIZE + 8];
    SerializeFrameHead(goawaybuf, 8, brpc::policy::H2_FRAME_GOAWAY, 0, 0);
    SaveUint32(goawaybuf + brpc::policy::FRAME_HEAD_SIZE, 0);
    SaveUint32(goawaybuf + brpc::policy::FRAME_HEAD_SIZE + 4, 0);
    ASSERT_EQ(brpc::policy::FRAME_HEAD_SIZE + 8, ::write(servfd, goawaybuf, brpc::policy::FRAME_HEAD_SIZE + 8));

    // After receving GOAWAY, the callbacks in client should be run correctly.
    for (int i = 0; i < req_size; i++) {
        brpc::Join(ids[i]);
    }
}
gejun's avatar
gejun committed
1446
} //namespace