| 322 | } |
| 323 | |
| 324 | void InputMessenger::OnNewMessages(Socket* m) { |
| 325 | // Notes: |
| 326 | // - If the socket has only one message, the message will be parsed and |
| 327 | // processed in this bthread. nova-pbrpc and http works in this way. |
| 328 | // - If the socket has several messages, all messages will be parsed ( |
| 329 | // meaning cutting from butil::IOBuf. serializing from protobuf is part of |
| 330 | // "process") in this bthread. All messages except the last one will be |
| 331 | // processed in separate bthreads. To minimize the overhead, scheduling |
| 332 | // is batched(notice the BTHREAD_NOSIGNAL and bthread_flush). |
| 333 | // - Verify will always be called in this bthread at most once and before |
| 334 | // any process. |
| 335 | InputMessenger* messenger = static_cast<InputMessenger*>(m->user()); |
| 336 | int progress = Socket::PROGRESS_INIT; |
| 337 | |
| 338 | // Notice that all *return* no matter successful or not will run last |
| 339 | // message, even if the socket is about to be closed. This should be |
| 340 | // OK in most cases. |
| 341 | InputMessageClosure last_msg; |
| 342 | bool read_eof = false; |
| 343 | while (!read_eof) { |
| 344 | const int64_t received_us = butil::cpuwide_time_us(); |
| 345 | const int64_t base_realtime = butil::gettimeofday_us() - received_us; |
| 346 | |
| 347 | // Calculate bytes to be read. |
| 348 | size_t once_read = m->_avg_msg_size * 16; |
| 349 | if (once_read < MIN_ONCE_READ) { |
| 350 | once_read = MIN_ONCE_READ; |
| 351 | } else if (once_read > MAX_ONCE_READ) { |
| 352 | once_read = MAX_ONCE_READ; |
| 353 | } |
| 354 | |
| 355 | // Read. |
| 356 | const ssize_t nr = m->DoRead(once_read); |
| 357 | if (nr <= 0) { |
| 358 | if (0 == nr) { |
| 359 | // Set `read_eof' flag and proceed to feed EOF into `Protocol' |
| 360 | // (implied by m->_read_buf.empty), which may produce a new |
| 361 | // `InputMessageBase' under some protocols such as HTTP |
| 362 | LOG_IF(WARNING, FLAGS_log_connection_close) << *m << " was closed by remote side"; |
| 363 | read_eof = true; |
| 364 | } else if (errno != EAGAIN) { |
| 365 | if (errno == EINTR) { |
| 366 | continue; // just retry |
| 367 | } |
| 368 | const int saved_errno = errno; |
| 369 | PLOG(WARNING) << "Fail to read from " << *m; |
| 370 | m->SetFailed(saved_errno, "Fail to read from %s: %s", |
| 371 | m->description().c_str(), berror(saved_errno)); |
| 372 | return; |
| 373 | } else if (!m->MoreReadEvents(&progress)) { |
| 374 | return; |
| 375 | } else { // new events during processing |
| 376 | continue; |
| 377 | } |
| 378 | } |
| 379 | |
| 380 | if (messenger->ProcessNewMessage(m, nr, read_eof, received_us, |
| 381 | base_realtime, last_msg) < 0) { |
nothing calls this directly
no test coverage detected