brpc_http_rpc_protocol_unittest.cpp 52.4 KB
Newer Older
1
// brpc - A framework to host and access services throughout Baidu.
gejun's avatar
gejun committed
2
// Copyright (c) 2014 Baidu, Inc.
gejun's avatar
gejun committed
3 4 5 6 7 8 9 10 11

// 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>
12 13 14
#include "butil/time.h"
#include "butil/macros.h"
#include "butil/files/scoped_file.h"
gejun's avatar
gejun committed
15 16 17 18 19 20
#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"
21
#include "echo.pb.h"
gejun's avatar
gejun committed
22
#include "brpc/policy/http_rpc_protocol.h"
zhujiashun's avatar
zhujiashun committed
23
#include "brpc/policy/http2_rpc_protocol.h"
gejun's avatar
gejun committed
24 25 26 27 28 29
#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);
30 31
    GFLAGS_NS::ParseCommandLineFlags(&argc, &argv, true);
    if (GFLAGS_NS::SetCommandLineOption("socket_max_unwritten_bytes", "2000000").empty()) {
gejun's avatar
gejun committed
32 33 34
        std::cerr << "Fail to set -socket_max_unwritten_bytes" << std::endl;
        return -1;
    }
35
    if (GFLAGS_NS::SetCommandLineOption("crash_on_fatal_log", "true").empty()) {
gejun's avatar
gejun committed
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
        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,
60
                         const butil::EndPoint&,
gejun's avatar
gejun committed
61 62 63 64 65 66 67 68 69
                         brpc::AuthContext* ctx) const {
        EXPECT_EQ(MOCK_CREDENTIAL, auth_str);
        ctx->set_user(MOCK_USER);
        return 0;
    }
};

class MyEchoService : public ::test::EchoService {
public:
70
    void Echo(::google::protobuf::RpcController* cntl_base,
gejun's avatar
gejun committed
71 72 73 74
              const ::test::EchoRequest* req,
              ::test::EchoResponse* res,
              ::google::protobuf::Closure* done) {
        brpc::ClosureGuard done_guard(done);
75 76 77 78 79 80 81
        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
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104

        EXPECT_EQ(EXP_REQUEST, req->message());
        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));
105 106 107

        brpc::SocketOptions h2_client_options;
        h2_client_options.user = brpc::get_client_side_messenger();
zyearn's avatar
zyearn committed
108
        h2_client_options.fd = _pipe_fds[1];
109 110
        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
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
    };

    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
138
    brpc::policy::HttpContext* MakePostRequestMessage(const std::string& path) {
139
        brpc::policy::HttpContext* msg = new brpc::policy::HttpContext(false);
gejun's avatar
gejun committed
140 141 142 143 144 145
        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);
146
        butil::IOBufAsZeroCopyOutputStream req_stream(&msg->body());
gejun's avatar
gejun committed
147 148 149 150
        EXPECT_TRUE(json2pb::ProtoMessageToJson(req, &req_stream, NULL));
        return msg;
    }

gejun's avatar
gejun committed
151
    brpc::policy::HttpContext* MakeGetRequestMessage(const std::string& path) {
152
        brpc::policy::HttpContext* msg = new brpc::policy::HttpContext(false);
gejun's avatar
gejun committed
153 154 155 156 157 158
        msg->header().uri().set_path(path);
        msg->header().set_method(brpc::HTTP_METHOD_GET);
        return msg;
    }


gejun's avatar
gejun committed
159
    brpc::policy::HttpContext* MakeResponseMessage(int code) {
160
        brpc::policy::HttpContext* msg = new brpc::policy::HttpContext(false);
gejun's avatar
gejun committed
161 162 163 164 165
        msg->header().set_status_code(code);
        msg->header().set_content_type("application/json");
        
        test::EchoResponse res;
        res.set_message(EXP_RESPONSE);
166
        butil::IOBufAsZeroCopyOutputStream res_stream(&msg->body());
gejun's avatar
gejun committed
167 168 169 170 171 172 173 174 175 176 177 178 179
        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);
180
        butil::IOPortal buf;
gejun's avatar
gejun committed
181 182 183 184 185
        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
186 187
        brpc::policy::HttpContext* msg =
            static_cast<brpc::policy::HttpContext*>(pr.message());
gejun's avatar
gejun committed
188 189 190 191 192

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

193
    void MakeH2EchoRequestBuf(butil::IOBuf* out, brpc::Controller* cntl, int* h2_stream_id) {
zhujiashun's avatar
zhujiashun committed
194 195 196
        butil::IOBuf request_buf;
        test::EchoRequest req;
        req.set_message(EXP_REQUEST);
197
        cntl->http_request().set_method(brpc::HTTP_METHOD_POST);
zhujiashun's avatar
zhujiashun committed
198 199 200 201 202 203 204
        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);
205
        butil::Status st = socket_message->AppendAndDestroySelf(out, _h2_client_sock.get());
zhujiashun's avatar
zhujiashun committed
206 207 208 209
        ASSERT_TRUE(st.ok());
        *h2_stream_id = h2_req->_stream_id;
    }

210
    void MakeH2EchoResponseBuf(butil::IOBuf* out, int h2_stream_id) {
zhujiashun's avatar
zhujiashun committed
211 212
        brpc::Controller cntl;
        test::EchoResponse res;
213
        res.set_message(EXP_RESPONSE);
zhujiashun's avatar
zhujiashun committed
214 215 216 217 218
        cntl.http_request().set_content_type("application/proto");
        {
            butil::IOBufAsZeroCopyOutputStream wrapper(&cntl.response_attachment());
            EXPECT_TRUE(res.SerializeToZeroCopyStream(&wrapper));
        }
219
        brpc::policy::H2UnsentResponse* h2_res = brpc::policy::H2UnsentResponse::New(&cntl, h2_stream_id, false /*is grpc*/);
220
        butil::Status st = h2_res->AppendAndDestroySelf(out, _h2_client_sock.get());
zhujiashun's avatar
zhujiashun committed
221 222 223
        ASSERT_TRUE(st.ok());
    }

gejun's avatar
gejun committed
224 225
    int _pipe_fds[2];
    brpc::SocketUniquePtr _socket;
226
    brpc::SocketUniquePtr _h2_client_sock;
gejun's avatar
gejun committed
227 228 229 230 231 232
    brpc::Server _server;

    MyEchoService _svc;
    MyAuthenticator _auth;
};

gejun's avatar
gejun committed
233 234 235 236 237 238 239 240 241 242 243 244 245
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
246
TEST_F(HttpTest, parse_http_address) {
247
    const std::string EXP_HOSTNAME = "www.baidu.com:9876";
248
    butil::EndPoint EXP_ENDPOINT;
gejun's avatar
gejun committed
249 250
    {
        std::string url = "https://" + EXP_HOSTNAME;
251
        EXPECT_TRUE(brpc::policy::ParseHttpServerAddress(&EXP_ENDPOINT, url.c_str()));
gejun's avatar
gejun committed
252 253
    }
    {
254
        butil::EndPoint ep;
gejun's avatar
gejun committed
255 256 257 258 259 260
        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);
    }
    {
261
        butil::EndPoint ep;
gejun's avatar
gejun committed
262
        std::string url = "https://" +
263
            std::string(butil::ip2str(EXP_ENDPOINT.ip).c_str());
gejun's avatar
gejun committed
264 265
        EXPECT_TRUE(brpc::policy::ParseHttpServerAddress(&ep, url.c_str()));
        EXPECT_EQ(EXP_ENDPOINT.ip, ep.ip);
gejun's avatar
gejun committed
266
        EXPECT_EQ(443, ep.port);
gejun's avatar
gejun committed
267 268
    }
    {
269
        butil::EndPoint ep;
gejun's avatar
gejun committed
270 271 272
        EXPECT_FALSE(brpc::policy::ParseHttpServerAddress(&ep, "invalid_url"));
    }
    {
273
        butil::EndPoint ep;
gejun's avatar
gejun committed
274 275 276 277 278 279 280
        EXPECT_FALSE(brpc::policy::ParseHttpServerAddress(
            &ep, "https://no.such.machine:9090"));
    }
}

TEST_F(HttpTest, verify_request) {
    {
gejun's avatar
gejun committed
281
        brpc::policy::HttpContext* msg =
gejun's avatar
gejun committed
282 283 284 285 286
                MakePostRequestMessage("/EchoService/Echo");
        VerifyMessage(msg, false);
        msg->Destroy();
    }
    {
gejun's avatar
gejun committed
287
        brpc::policy::HttpContext* msg = MakeGetRequestMessage("/status");
gejun's avatar
gejun committed
288 289 290 291
        VerifyMessage(msg, true);
        msg->Destroy();
    }
    {
gejun's avatar
gejun committed
292
        brpc::policy::HttpContext* msg =
gejun's avatar
gejun committed
293 294 295 296 297 298 299 300
                MakePostRequestMessage("/EchoService/Echo");
        _socket->SetFailed();
        VerifyMessage(msg, false);
        msg->Destroy();
    }
}

TEST_F(HttpTest, process_request_failed_socket) {
gejun's avatar
gejun committed
301
    brpc::policy::HttpContext* msg = MakePostRequestMessage("/EchoService/Echo");
gejun's avatar
gejun committed
302 303
    _socket->SetFailed();
    ProcessMessage(brpc::policy::ProcessHttpRequest, msg, false);
304
    ASSERT_EQ(0ll, _server._nerror_bvar.get_value());
gejun's avatar
gejun committed
305 306 307 308
    CheckResponseCode(true, 0);
}

TEST_F(HttpTest, reject_get_to_pb_services_with_required_fields) {
gejun's avatar
gejun committed
309
    brpc::policy::HttpContext* msg = MakeGetRequestMessage("/EchoService/Echo");
gejun's avatar
gejun committed
310 311
    _server._status = brpc::Server::RUNNING;
    ProcessMessage(brpc::policy::ProcessHttpRequest, msg, false);
312
    ASSERT_EQ(0ll, _server._nerror_bvar.get_value());
gejun's avatar
gejun committed
313 314 315 316
    const brpc::Server::MethodProperty* mp =
        _server.FindMethodPropertyByFullName("test.EchoService.Echo");
    ASSERT_TRUE(mp);
    ASSERT_TRUE(mp->status);
317
    ASSERT_EQ(1ll, mp->status->_nerror_bvar.get_value());
gejun's avatar
gejun committed
318 319 320 321
    CheckResponseCode(false, brpc::HTTP_STATUS_BAD_REQUEST);
}

TEST_F(HttpTest, process_request_logoff) {
gejun's avatar
gejun committed
322
    brpc::policy::HttpContext* msg = MakePostRequestMessage("/EchoService/Echo");
gejun's avatar
gejun committed
323 324
    _server._status = brpc::Server::READY;
    ProcessMessage(brpc::policy::ProcessHttpRequest, msg, false);
325
    ASSERT_EQ(1ll, _server._nerror_bvar.get_value());
326
    CheckResponseCode(false, brpc::HTTP_STATUS_SERVICE_UNAVAILABLE);
gejun's avatar
gejun committed
327 328 329
}

TEST_F(HttpTest, process_request_wrong_method) {
gejun's avatar
gejun committed
330
    brpc::policy::HttpContext* msg = MakePostRequestMessage("/NO_SUCH_METHOD");
gejun's avatar
gejun committed
331
    ProcessMessage(brpc::policy::ProcessHttpRequest, msg, false);
332
    ASSERT_EQ(1ll, _server._nerror_bvar.get_value());
gejun's avatar
gejun committed
333 334 335 336 337 338 339
    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
340
    brpc::policy::HttpContext* msg =
gejun's avatar
gejun committed
341 342 343 344 345 346 347 348 349 350 351
            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
352
        brpc::policy::HttpContext* msg =
gejun's avatar
gejun committed
353 354 355 356 357 358 359 360
                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
361
        brpc::policy::HttpContext* msg =
gejun's avatar
gejun committed
362 363 364 365 366 367 368 369 370
                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
371
        brpc::policy::HttpContext* msg =
gejun's avatar
gejun committed
372 373 374 375 376 377 378 379 380
                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
381
        brpc::policy::HttpContext* msg = MakeResponseMessage(12345);
gejun's avatar
gejun committed
382 383 384 385 386 387 388
        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) {
389 390
    butil::IOBuf request_buf;
    butil::IOBuf total_buf;
gejun's avatar
gejun committed
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
    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
417
    butil::IOPortal response_buf;
gejun's avatar
gejun committed
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
    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;
439
    butil::string_printf(&cmd, "curl -X POST -d '%s' -H 'Transfer-Encoding:chunked' "
gejun's avatar
gejun committed
440 441 442 443 444 445 446
                        "-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\"}";
447
    butil::ScopedFILE fp(res_fname.c_str(), "r");
gejun's avatar
gejun committed
448
    char buf[128];
gejun's avatar
gejun committed
449
    ASSERT_TRUE(fgets(buf, sizeof(buf), fp));
gejun's avatar
gejun committed
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
    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);
487
        butil::intrusive_ptr<brpc::ProgressiveAttachment> pa(
gejun's avatar
gejun committed
488 489 490 491 492 493 494 495
                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
496
        ASSERT_GT(PA_DATA_LEN, 8u);  // long enough to hold a 64-bit decimal.
gejun's avatar
gejun committed
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
        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);
535
        butil::intrusive_ptr<brpc::ProgressiveAttachment> pa(
gejun's avatar
gejun committed
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
                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;
591
        ASSERT_EQ(0, channel.Init(butil::EndPoint(butil::my_ip(), port), &options));
gejun's avatar
gejun committed
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
        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;
613
    ASSERT_EQ(0, channel.Init(butil::EndPoint(butil::my_ip(), port), &options));
gejun's avatar
gejun committed
614 615 616 617 618

    brpc::Controller cntl;
    cntl.http_request().uri() = "/DownloadService/DownloadFailed";
    cntl.response_will_be_read_progressively();
    channel.CallMethod(NULL, &cntl, NULL, NULL, NULL);
619 620 621 622 623 624
    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
625 626 627 628 629 630 631 632 633 634
    ASSERT_EQ(0, svc.last_errno());
}

class ReadBody : public brpc::ProgressiveReader,
                 public brpc::SharedObject {
public:
    ReadBody()
        : _nread(0)
        , _ncount(0)
        , _destroyed(false) {
635
        butil::intrusive_ptr<ReadBody>(this).detach(); // ref
gejun's avatar
gejun committed
636 637
    }
                
638
    butil::Status OnReadOnePart(const void* data, size_t length) {
gejun's avatar
gejun committed
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
        _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();
            }
        }
654
        return butil::Status::OK();
gejun's avatar
gejun committed
655
    }
656 657
    void OnEndOfMessage(const butil::Status& st) {
        butil::intrusive_ptr<ReadBody>(this, false); // deref
gejun's avatar
gejun committed
658 659 660 661 662 663 664
        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; }
665
    const butil::Status& destroying_status() const { return _destroying_st; }
gejun's avatar
gejun committed
666 667 668 669 670 671
    size_t read_bytes() const { return _nread; }
private:
    std::string _buf;
    size_t _nread;
    size_t _ncount;
    bool _destroyed;
672
    butil::Status _destroying_st;
gejun's avatar
gejun committed
673 674 675 676 677
};

static const int GENERAL_DELAY_US = 300000; // 0.3s

TEST_F(HttpTest, read_long_body_progressively) {
678
    butil::intrusive_ptr<ReadBody> reader;
gejun's avatar
gejun committed
679 680 681 682 683 684 685 686 687 688
    {
        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;
689
            options.protocol = brpc::PROTOCOL_HTTP;
690
            ASSERT_EQ(0, channel.Init(butil::EndPoint(butil::my_ip(), port), &options));
gejun's avatar
gejun committed
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
            {
                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.
                ASSERT_GT(last_read, 100000);
            }
            // 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) {
727
    butil::intrusive_ptr<ReadBody> reader;
gejun's avatar
gejun committed
728 729 730 731 732 733 734 735 736 737
    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;
738
        ASSERT_EQ(0, channel.Init(butil::EndPoint(butil::my_ip(), port), &options));
gejun's avatar
gejun committed
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
        {
            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) {
765
    butil::intrusive_ptr<ReadBody> reader;
gejun's avatar
gejun committed
766 767 768 769 770 771 772 773 774 775 776
    {
        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;
777
            ASSERT_EQ(0, channel.Init(butil::EndPoint(butil::my_ip(), port), &options));
gejun's avatar
gejun committed
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
            {
                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.
            ASSERT_GT(last_read, 100000);
            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) {
811
    butil::intrusive_ptr<ReadBody> reader;
gejun's avatar
gejun committed
812 813 814 815 816 817 818 819 820 821 822
    {
        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;
823
            ASSERT_EQ(0, channel.Init(butil::EndPoint(butil::my_ip(), port), &options));
gejun's avatar
gejun committed
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 865 866 867 868 869
            {
                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.
                ASSERT_GT(last_read, 100000);
            }
            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;
870
    ASSERT_EQ(0, channel.Init(butil::EndPoint(butil::my_ip(), port), &options));
gejun's avatar
gejun committed
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
    {
        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.
    ASSERT_GT(new_written_bytes - old_written_bytes, 100000);
}

class AlwaysFailRead : public brpc::ProgressiveReader {
public:
    // @ProgressiveReader
892 893
    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
894
    }
895
    void OnEndOfMessage(const butil::Status& st) {
gejun's avatar
gejun committed
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
        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;
911
    ASSERT_EQ(0, channel.Init(butil::EndPoint(butil::my_ip(), port), &options));
gejun's avatar
gejun committed
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
    {
        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) {
927
    butil::intrusive_ptr<ReadBody> reader;
gejun's avatar
gejun committed
928 929 930 931 932 933 934 935 936 937
    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;
938
    ASSERT_EQ(0, channel.Init(butil::EndPoint(butil::my_ip(), port), &options));
gejun's avatar
gejun committed
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
    {
        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.
        ASSERT_GT(last_read, 100000);
    }
    // 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
970 971 972 973 974 975 976 977 978

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;
979
    options.protocol = "h2";
zhujiashun's avatar
zhujiashun committed
980 981
    ASSERT_EQ(0, channel.Init(butil::EndPoint(butil::my_ip(), port), &options));

982 983 984
    // 1) complete flow and
    // 2) socket replacement when streamId runs out, the initial streamId is a special
    // value set in ctor of H2Context
zhujiashun's avatar
zhujiashun committed
985 986 987
    test::EchoRequest req;
    req.set_message(EXP_REQUEST);
    test::EchoResponse res;
988
    for (int i = 0; i < 15000; ++i) {
zhujiashun's avatar
zhujiashun committed
989 990 991 992 993 994 995 996
        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());
    }
997 998 999 1000 1001 1002 1003 1004 1005

    // 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
1006
}
zhujiashun's avatar
zhujiashun committed
1007 1008 1009 1010 1011 1012 1013 1014

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;
1015
    MakeH2EchoRequestBuf(&req_out, &cntl, &h2_stream_id);
zhujiashun's avatar
zhujiashun committed
1016 1017 1018 1019 1020
    // 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
1021 1022
    res_out.append(pingbuf, sizeof(pingbuf));
    MakeH2EchoResponseBuf(&res_out, h2_stream_id);
zhujiashun's avatar
zhujiashun committed
1023
    // insert ping after header and data
1024
    res_out.append(pingbuf, sizeof(pingbuf));
zhujiashun's avatar
zhujiashun committed
1025 1026
    // parse response
    brpc::ParseResult res_pr =
1027
            brpc::policy::ParseH2Message(&res_out, _h2_client_sock.get(), false, NULL);
zhujiashun's avatar
zhujiashun committed
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
    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;
1047
    MakeH2EchoRequestBuf(&req_out, &cntl, &h2_stream_id);
zhujiashun's avatar
zhujiashun committed
1048 1049 1050 1051 1052
    // 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);
1053 1054
    res_out.append(rstbuf, sizeof(rstbuf));
    MakeH2EchoResponseBuf(&res_out, h2_stream_id);
zhujiashun's avatar
zhujiashun committed
1055 1056
    // parse response
    brpc::ParseResult res_pr =
1057
            brpc::policy::ParseH2Message(&res_out, _h2_client_sock.get(), false, NULL);
zhujiashun's avatar
zhujiashun committed
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
    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;
1071
    MakeH2EchoRequestBuf(&req_out, &cntl, &h2_stream_id);
zhujiashun's avatar
zhujiashun committed
1072 1073
    // Prepare response
    butil::IOBuf res_out;
1074
    MakeH2EchoResponseBuf(&res_out, h2_stream_id);
zhujiashun's avatar
zhujiashun committed
1075 1076 1077
    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);
1078
    res_out.append(rstbuf, sizeof(rstbuf));
zhujiashun's avatar
zhujiashun committed
1079 1080
    // parse response
    brpc::ParseResult res_pr =
1081
            brpc::policy::ParseH2Message(&res_out, _h2_client_sock.get(), false, NULL);
zhujiashun's avatar
zhujiashun committed
1082 1083 1084 1085 1086 1087 1088
    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);
}

1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
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);

    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());
1111
            ASSERT_TRUE(st.error_code() == brpc::ELIMIT);
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
            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;
1139 1140
    CHECK_EQ(response_buf.append_from_file_descriptor(_pipe_fds[0], 1024),
             (ssize_t)brpc::policy::FRAME_HEAD_SIZE);
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
    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) {
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
    {
        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));
    }
1173 1174
}

1175 1176 1177 1178 1179 1180 1181
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;
1182
    options.protocol = "h2";
1183
    ASSERT_EQ(0, channel.Init(butil::EndPoint(butil::my_ip(), port), &options));
1184

1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
    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);
    }
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 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
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");
}

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 1362 1363 1364 1365
TEST_F(HttpTest, http2_goaway) {
    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"));
}

gejun's avatar
gejun committed
1366
} //namespace