proxygen
proxygen::HTTPSession Class Referenceabstract

#include <HTTPSession.h>

Inheritance diagram for proxygen::HTTPSession:
folly::AsyncTransport::ReplaySafetyCallback folly::AsyncReader::ReadCallback folly::EventBase::LoopCallback proxygen::HTTPCodec::Callback proxygen::FlowControlFilter::Callback proxygen::HTTPPriorityMapFactoryProvider folly::AsyncTransport::BufferCallback proxygen::ByteEventTracker::Callback proxygen::HTTPTransaction::Transport proxygen::HTTPSessionBase proxygen::HTTPDownstreamSession proxygen::HTTPUpstreamSession

Classes

class  DrainTimeout
 
class  FlowControlTimeout
 
class  ShutdownTransportCallback
 
class  WriteSegment
 
class  WriteTimeout
 

Public Types

using UniquePtr = std::unique_ptr< HTTPSession, Destructor >
 
- Public Types inherited from proxygen::HTTPSessionBase
enum  SessionType { SessionType::HTTP, SessionType::HQ }
 
using FilterIteratorFn = std::function< void(HTTPCodecFilter *)>
 

Public Member Functions

HTTPSessionBase::SessionType getType () const noexceptoverride
 
folly::AsyncTransportWrappergetTransport () override
 
folly::EventBasegetEventBase () const override
 
const folly::AsyncTransportWrappergetTransport () const override
 
bool hasActiveTransactions () const override
 
uint32_t getNumOutgoingStreams () const override
 
uint32_t getNumIncomingStreams () const override
 
ByteEventTrackergetByteEventTracker ()
 
void setByteEventTracker (std::shared_ptr< ByteEventTracker > byteEventTracker)
 
void setSessionStats (HTTPSessionStats *stats) override
 
void setFlowControl (size_t initialReceiveWindow, size_t receiveStreamWindowSize, size_t receiveSessionWindowSize) override
 
void setEgressSettings (const SettingsList &inSettings) override
 
bool getHTTP2PrioritiesEnabled () const override
 
void setHTTP2PrioritiesEnabled (bool enabled) override
 
const folly::SocketAddressgetLocalAddress () const noexceptoverride
 
const folly::SocketAddressgetPeerAddress () const noexceptoverride
 
const wangle::TransportInfogetSetupTransportInfo () const noexceptoverride
 
bool getCurrentTransportInfo (wangle::TransportInfo *tinfo) override
 
void setMaxConcurrentIncomingStreams (uint32_t num) override
 
void setEgressBytesLimit (uint64_t bytesLimit)
 
void startNow () override
 
size_t sendSettings () override
 
size_t sendPing () override
 
HTTPCodec::StreamID sendPriority (http2::PriorityUpdate pri) override
 
size_t sendPriority (HTTPCodec::StreamID id, http2::PriorityUpdate pri) override
 
size_t sendCertificateRequest (std::unique_ptr< folly::IOBuf > certificateRequestContext, std::vector< fizz::Extension > extensions) override
 
void timeoutExpired () noexceptoverride
 
void describe (std::ostream &os) const override
 
bool isBusy () const override
 
void notifyPendingShutdown () override
 
void closeWhenIdle () override
 
void dropConnection () override
 
void dumpConnectionState (uint8_t loglevel) override
 
bool getCurrentTransportInfoWithoutUpdate (wangle::TransportInfo *tinfo) const override
 
void setHeaderCodecStats (HeaderCodec::Stats *stats) override
 
void enableDoubleGoawayDrain () override
 
bool connCloseByRemote () override
 
void setSecondAuthManager (std::unique_ptr< SecondaryAuthManager > secondAuthManager)
 
SecondaryAuthManagergetSecondAuthManager () const
 
- Public Member Functions inherited from proxygen::HTTPSessionBase
 HTTPSessionBase (const folly::SocketAddress &localAddr, const folly::SocketAddress &peerAddr, HTTPSessionController *controller, const wangle::TransportInfo &tinfo, InfoCallback *infoCallback, std::unique_ptr< HTTPCodec > codec)
 
virtual ~HTTPSessionBase ()
 
void setInfoCallback (InfoCallback *callback)
 
InfoCallbackgetInfoCallback () const
 
HTTPTransaction::HandlergetParseErrorHandler (HTTPTransaction *txn, const HTTPException &error)
 
bool supportsMoreTransactions () const
 
uint32_t getHistoricalMaxOutgoingStreams () const
 
uint32_t getMaxConcurrentOutgoingStreams () const
 
HTTPSessionControllergetController ()
 
void setController (HTTPSessionController *controller)
 
ConnectionCloseReason getConnectionCloseReason () const
 
template<typename Filter , typename... Args>
void addCodecFilter (Args &&...args)
 
virtual CodecProtocol getCodecProtocol () const
 
void setHTTP2PrioritiesEnabled (bool enabled)
 
void setMaxConcurrentOutgoingStreams (uint32_t num)
 
uint32_t getWriteBufferLimit () const
 
void setWriteBufferLimit (uint32_t limit)
 
void setReadBufferLimit (uint32_t limit)
 
uint64_t getNumTxnServed () const
 
std::chrono::seconds getLatestIdleTime () const
 
void setPrioritySampled (bool sampled)
 
const folly::SocketAddressgetLocalAddress () const noexcept
 
const folly::SocketAddressgetPeerAddress () const noexcept
 
const wangle::TransportInfogetSetupTransportInfo () const noexcept
 
wangle::TransportInfogetSetupTransportInfo () noexcept
 
virtual bool isDetachable (bool checkSocket) const =0
 
virtual void attachThreadLocals (folly::EventBase *eventBase, folly::SSLContextPtr sslContext, const WheelTimerInstance &timeout, HTTPSessionStats *stats, FilterIteratorFn fn, HeaderCodec::Stats *headerCodecStats, HTTPSessionController *controller)=0
 
virtual void detachThreadLocals (bool detachSSLContext=false)=0
 
virtual HTTPTransactionnewTransaction (HTTPTransaction::Handler *handler)=0
 
virtual bool isReplaySafe () const =0
 
virtual bool isReusable () const =0
 
virtual bool isClosing () const =0
 
void enableExHeadersSettings () noexcept
 
bool isExHeadersEnabled () noexcept
 
- Public Member Functions inherited from wangle::ManagedConnection
 ManagedConnection ()
 
void fireNotifyPendingShutdown ()
 
void fireCloseWhenIdle (bool force_to_close=false)
 
virtual void resetTimeout ()
 
void resetTimeoutTo (std::chrono::milliseconds)
 
virtual void scheduleTimeout (folly::HHWheelTimer::Callback *callback, std::chrono::milliseconds timeout)
 
ConnectionManagergetConnectionManager ()
 
- Public Member Functions inherited from folly::HHWheelTimer::Callback
 Callback ()=default
 
virtual ~Callback ()
 
virtual void callbackCanceled () noexcept
 
void cancelTimeout ()
 
bool isScheduled () const
 
std::chrono::milliseconds getTimeRemaining ()
 
- Public Member Functions inherited from folly::DelayedDestruction
virtual void destroy ()
 
bool getDestroyPending () const
 
- Public Member Functions inherited from folly::DelayedDestructionBase
virtual ~DelayedDestructionBase ()=default
 
- Public Member Functions inherited from proxygen::HTTPTransaction::Transport
virtual ~Transport ()
 
virtual void addWaitingForReplaySafety (folly::AsyncTransport::ReplaySafetyCallback *callback) noexcept=0
 
virtual void removeWaitingForReplaySafety (folly::AsyncTransport::ReplaySafetyCallback *callback) noexcept=0
 
virtual bool isReplaySafe () const =0
 
- Public Member Functions inherited from proxygen::ByteEventTracker::Callback
virtual ~Callback ()
 

Protected Member Functions

 HTTPSession (const WheelTimerInstance &timeout, folly::AsyncTransportWrapper::UniquePtr sock, const folly::SocketAddress &localAddr, const folly::SocketAddress &peerAddr, HTTPSessionController *controller, std::unique_ptr< HTTPCodec > codec, const wangle::TransportInfo &tinfo, InfoCallback *infoCallback)
 
 HTTPSession (folly::HHWheelTimer *transactionTimeouts, folly::AsyncTransportWrapper::UniquePtr sock, const folly::SocketAddress &localAddr, const folly::SocketAddress &peerAddr, HTTPSessionController *controller, std::unique_ptr< HTTPCodec > codec, const wangle::TransportInfo &tinfo, InfoCallback *infoCallback)
 
 ~HTTPSession () override
 
virtual void setupOnHeadersComplete (HTTPTransaction *txn, HTTPMessage *msg)=0
 
virtual HTTPTransaction::HandlergetTransactionTimeoutHandler (HTTPTransaction *txn)=0
 
virtual void onHeadersSent (const HTTPMessage &, bool)
 
virtual bool allTransactionsStarted () const =0
 
void setNewTransactionPauseState (HTTPCodec::StreamID streamID)
 
void onEgressMessageFinished (HTTPTransaction *txn, bool withRST=false)
 
std::unique_ptr< folly::IOBufgetNextToSend (bool *cork, bool *eom)
 
void decrementTransactionCount (HTTPTransaction *txn, bool ingressEOM, bool egressEOM)
 
size_t getCodecSendWindowSize () const
 
size_t sendPriorityImpl (HTTPCodec::StreamID streamID, http2::PriorityUpdate pri)
 
bool onNativeProtocolUpgradeImpl (HTTPCodec::StreamID txn, std::unique_ptr< HTTPCodec > codec, const std::string &protocolString)
 
virtual folly::Optional< const HTTPMessage::HTTPPrioritygetHTTPPriority (uint8_t) override
 
void readTimeoutExpired () noexcept
 
void writeTimeoutExpired () noexcept
 
void flowControlTimeoutExpired () noexcept
 
void getReadBuffer (void **buf, size_t *bufSize) override
 
void readDataAvailable (size_t readSize) noexceptoverride
 
bool isBufferMovable () noexceptoverride
 
void readBufferAvailable (std::unique_ptr< folly::IOBuf >) noexceptoverride
 
void processReadData ()
 
void readEOF () noexceptoverride
 
void readErr (const folly::AsyncSocketException &) noexceptoverride
 
std::string getSecurityProtocol () const override
 
void onMessageBegin (HTTPCodec::StreamID streamID, HTTPMessage *msg) override
 
void onPushMessageBegin (HTTPCodec::StreamID streamID, HTTPCodec::StreamID assocStreamID, HTTPMessage *msg) override
 
void onExMessageBegin (HTTPCodec::StreamID streamID, HTTPCodec::StreamID controlStream, bool unidirectional, HTTPMessage *msg) override
 
void onHeadersComplete (HTTPCodec::StreamID streamID, std::unique_ptr< HTTPMessage > msg) override
 
void onBody (HTTPCodec::StreamID streamID, std::unique_ptr< folly::IOBuf > chain, uint16_t padding) override
 
void onChunkHeader (HTTPCodec::StreamID stream, size_t length) override
 
void onChunkComplete (HTTPCodec::StreamID stream) override
 
void onTrailersComplete (HTTPCodec::StreamID streamID, std::unique_ptr< HTTPHeaders > trailers) override
 
void onMessageComplete (HTTPCodec::StreamID streamID, bool upgrade) override
 
void onError (HTTPCodec::StreamID streamID, const HTTPException &error, bool newTxn) override
 
void onAbort (HTTPCodec::StreamID streamID, ErrorCode code) override
 
void onGoaway (uint64_t lastGoodStreamID, ErrorCode code, std::unique_ptr< folly::IOBuf > debugData=nullptr) override
 
void onPingRequest (uint64_t uniqueID) override
 
void onPingReply (uint64_t uniqueID) override
 
void onWindowUpdate (HTTPCodec::StreamID stream, uint32_t amount) override
 
void onSettings (const SettingsList &settings) override
 
void onSettingsAck () override
 
void onPriority (HTTPCodec::StreamID stream, const HTTPMessage::HTTPPriority &) override
 
void onCertificateRequest (uint16_t requestId, std::unique_ptr< folly::IOBuf > authRequest) override
 
void onCertificate (uint16_t certId, std::unique_ptr< folly::IOBuf > authenticator) override
 
uint32_t numOutgoingStreams () const override
 
uint32_t numIncomingStreams () const override
 
void pauseIngress (HTTPTransaction *txn) noexceptoverride
 
void resumeIngress (HTTPTransaction *txn) noexceptoverride
 
void transactionTimeout (HTTPTransaction *txn) noexceptoverride
 
void sendHeaders (HTTPTransaction *txn, const HTTPMessage &headers, HTTPHeaderSize *size, bool includeEOM) noexceptoverride
 
size_t sendBody (HTTPTransaction *txn, std::unique_ptr< folly::IOBuf >, bool includeEOM, bool trackLastByteFlushed) noexceptoverride
 
size_t sendChunkHeader (HTTPTransaction *txn, size_t length) noexceptoverride
 
size_t sendChunkTerminator (HTTPTransaction *txn) noexceptoverride
 
size_t sendEOM (HTTPTransaction *txn, const HTTPHeaders *trailers) noexceptoverride
 
size_t sendAbort (HTTPTransaction *txn, ErrorCode statusCode) noexceptoverride
 
size_t sendPriority (HTTPTransaction *txn, const http2::PriorityUpdate &pri) noexceptoverride
 
void detach (HTTPTransaction *txn) noexceptoverride
 
size_t sendWindowUpdate (HTTPTransaction *txn, uint32_t bytes) noexceptoverride
 
void notifyPendingEgress () noexceptoverride
 
void notifyIngressBodyProcessed (uint32_t bytes) noexceptoverride
 
void notifyEgressBodyBuffered (int64_t bytes) noexceptoverride
 
HTTPTransactionnewPushedTransaction (HTTPCodec::StreamID assocStreamId, HTTPTransaction::PushHandler *handler) noexceptoverride
 
HTTPTransactionnewExTransaction (HTTPTransaction::Handler *handler, HTTPCodec::StreamID controlStream, bool unidirectional=false) noexceptoverride
 
const HTTPCodecgetCodec () const noexceptoverride
 
const folly::AsyncTransportWrappergetUnderlyingTransport () const noexceptoverride
 
bool isDraining () const override
 
void drain () override
 
void shutdownTransport (bool shutdownReads=true, bool shutdownWrites=true, const std::string &errorMsg="")
 
void shutdownTransportWithReset (ProxygenError errorCode, const std::string &errorMsg="")
 
void runLoopCallback () noexceptoverride
 
void scheduleWrite ()
 
void updateWriteCount ()
 
void updateWriteBufSize (int64_t delta)
 
uint64_t sessionByteOffset ()
 
void immediateShutdown ()
 
void checkForShutdown ()
 
HTTPTransactionfindTransaction (HTTPCodec::StreamID streamID)
 
HTTPTransactioncreateTransaction (HTTPCodec::StreamID streamID, const folly::Optional< HTTPCodec::StreamID > &assocStreamID, const folly::Optional< HTTPCodec::ExAttributes > &exAttributes, const http2::PriorityUpdate &priority=http2::DefaultPriority)
 
void onWriteSuccess (uint64_t bytesWritten)
 
void onWriteError (size_t bytesWritten, const folly::AsyncSocketException &ex)
 
void onWriteCompleted ()
 
void pauseReads ()
 
void onSessionParseError (const HTTPException &error)
 
void onNewTransactionParseError (HTTPCodec::StreamID streamID, const HTTPException &error)
 
void resumeReads ()
 
bool hasMoreWrites () const
 
template<typename... Args1, typename... Args2>
void invokeOnAllTransactions (void(HTTPTransaction::*fn)(Args1...), Args2 &&...args)
 
void resumeTransactions ()
 
void errorOnAllTransactions (ProxygenError err, const std::string &errorMsg)
 
void errorOnTransactionIds (const std::vector< HTTPCodec::StreamID > &ids, ProxygenError err, const std::string &extraErrorMsg="")
 
void errorOnTransactionId (HTTPCodec::StreamID id, HTTPException ex)
 
bool shouldShutdown () const
 
void drainImpl ()
 
void pauseReadsImpl ()
 
void resumeReadsImpl ()
 
bool readsUnpaused () const
 
bool readsPaused () const
 
bool readsShutdown () const
 
bool writesUnpaused () const
 
bool writesPaused () const
 
bool writesShutdown () const
 
void rescheduleLoopCallbacks ()
 
void cancelLoopCallbacks ()
 
- Protected Member Functions inherited from proxygen::HTTPSessionBase
void handleErrorDirectly (HTTPTransaction *txn, const HTTPException &error)
 
bool onBodyImpl (std::unique_ptr< folly::IOBuf > chain, size_t length, uint16_t padding, HTTPTransaction *txn)
 
bool notifyBodyProcessed (uint32_t bytes)
 
void setLatestActive ()
 
bool ingressLimitExceeded () const
 
bool egressLimitExceeded () const
 
void updatePendingWriteSize (int64_t delta)
 
void onCreateTransaction ()
 
void incrementSeqNo ()
 
bool isPrioritySampled () const
 
void onNewOutgoingStream (uint32_t outgoingStreams)
 
void setCloseReason (ConnectionCloseReason reason)
 
void runDestroyCallbacks ()
 
void onCodecChanged ()
 
void initCodecHeaderIndexingStrategy ()
 
void attachToSessionController ()
 
- Protected Member Functions inherited from wangle::ManagedConnection
 ~ManagedConnection () override
 
- Protected Member Functions inherited from folly::HHWheelTimer::Callback
virtual std::chrono::steady_clock::time_point getCurTime ()
 
- Protected Member Functions inherited from folly::DelayedDestruction
 ~DelayedDestruction () override=default
 
 DelayedDestruction ()
 
- Protected Member Functions inherited from folly::DelayedDestructionBase
 DelayedDestructionBase ()
 
uint32_t getDestructorGuardCount () const
 
- Protected Member Functions inherited from folly::AsyncTransport::BufferCallback
virtual ~BufferCallback ()
 
- Protected Member Functions inherited from proxygen::HTTPPriorityMapFactoryProvider
virtual ~HTTPPriorityMapFactoryProvider ()=default
 

Protected Attributes

WriteTimeout writeTimeout_
 
folly::IOBufQueue writeBuf_ {folly::IOBufQueue::cacheChainLength()}
 
folly::IOBufQueue readBuf_ {folly::IOBufQueue::cacheChainLength()}
 
HTTP2PriorityQueue txnEgressQueue_
 
std::map< HTTPCodec::StreamID, HTTPTransactiontransactions_
 
uint32_t liveTransactions_ {0}
 
folly::AsyncTransportWrapper::UniquePtr sock_
 
WheelTimerInstance timeout_
 
unsigned numActiveWrites_ {0}
 
bool draining_:1
 
bool started_:1
 
bool writesDraining_:1
 
bool resetAfterDrainingWrites_:1
 
bool ingressError_:1
 
- Protected Attributes inherited from proxygen::HTTPSessionBase
HTTPSessionStatssessionStats_ {nullptr}
 
InfoCallbackinfoCallback_ {nullptr}
 
wangle::TransportInfo transportInfo_
 
HTTPCodecFilterChain codec_
 
folly::SocketAddress localAddr_
 
folly::SocketAddress peerAddr_
 

Private Types

enum  SocketState { UNPAUSED = 0, PAUSED = 1, SHUTDOWN = 2 }
 
using WriteSegmentList = folly::IntrusiveList< WriteSegment,&WriteSegment::listHook >
 

Private Member Functions

uint32_t getMaxConcurrentOutgoingStreamsRemote () const override
 
bool isUpstream () const
 
bool isDownstream () const
 
void onEgressBuffered () override
 
void onEgressBufferCleared () override
 
void setupCodec ()
 
void onSetSendWindow (uint32_t windowSize)
 
void onSetMaxInitiatedStreams (uint32_t maxTxns)
 
uint32_t getCertAuthSettingVal ()
 
bool verifyCertAuthSetting (uint32_t value)
 
void addLastByteEvent (HTTPTransaction *txn, uint64_t byteNo) noexcept
 
void addAckToLastByteEvent (HTTPTransaction *txn, const ByteEvent &lastByteEvent)
 
void onConnectionSendWindowOpen () override
 
void onConnectionSendWindowClosed () override
 
HTTPCodec::StreamID getGracefulGoawayAck () const
 
void invalidStream (HTTPCodec::StreamID stream, ErrorCode code=ErrorCode::_SPDY_INVALID_STREAM)
 
http2::PriorityUpdate getMessagePriority (const HTTPMessage *msg)
 
bool isConnWindowFull () const
 
void onPingReplyLatency (int64_t latency) noexceptoverride
 
void onLastByteEvent (HTTPTransaction *txn, uint64_t offset, bool eomTracked) noexceptoverride
 
void onDeleteAckEvent () noexceptoverride
 
void commonEom (HTTPTransaction *txn, size_t encodedSize, bool piggybacked) noexcept
 
void addWaitingForReplaySafety (ReplaySafetyCallback *callback) noexceptoverride
 
void removeWaitingForReplaySafety (ReplaySafetyCallback *callback) noexceptoverride
 
bool needToBlockForReplaySafety () const override
 
void onReplaySafe () noexceptoverride
 
size_t getPipelineStreamCount () const
 
bool maybeResumePausedPipelinedTransaction (size_t oldStreamCount, uint32_t txnSeqn)
 
void incrementOutgoingStreams ()
 
- Private Member Functions inherited from proxygen::FlowControlFilter::Callback
virtual ~Callback ()
 
- Private Member Functions inherited from proxygen::HTTPCodec::Callback
virtual void onFrameHeader (StreamID, uint8_t, uint64_t, uint8_t, uint16_t=0)
 
virtual bool onNativeProtocolUpgrade (StreamID, CodecProtocol, const std::string &, HTTPMessage &)
 
virtual void onGenerateFrameHeader (StreamID, uint8_t, uint64_t, uint16_t=0)
 
virtual ~Callback ()
 
- Private Member Functions inherited from folly::EventBase::LoopCallback
virtual ~LoopCallback ()=default
 
void cancelLoopCallback ()
 
bool isLoopCallbackScheduled () const
 
- Private Member Functions inherited from folly::AsyncReader::ReadCallback
virtual ~ReadCallback ()=default
 
virtual size_t maxBufferSize () const
 
- Private Member Functions inherited from folly::AsyncTransport::ReplaySafetyCallback
virtual ~ReplaySafetyCallback ()=default
 

Private Attributes

std::list< ReplaySafetyCallback * > waitingForReplaySafety_
 
WriteSegmentList pendingWrites_
 
FlowControlFilterconnFlowControl_ {nullptr}
 
uint32_t maxConcurrentOutgoingStreamsRemote_ {100000}
 
uint32_t maxConcurrentIncomingStreams_ {100}
 
uint32_t outgoingStreams_ {0}
 
uint32_t incomingStreams_ {0}
 
uint64_t bytesWritten_ {0}
 
uint64_t bytesScheduled_ {0}
 
int64_t pendingWriteSizeDelta_ {0}
 
uint64_t bodyBytesPerWriteBuf_ {0}
 
HTTP2PriorityQueue::NextEgressResult nextEgressResults_
 
std::shared_ptr< ByteEventTrackerbyteEventTracker_ {nullptr}
 
uint64_t egressBytesLimit_ {0}
 
size_t initialReceiveWindow_ {0}
 
size_t receiveStreamWindowSize_ {0}
 
size_t receiveSessionWindowSize_ {0}
 
std::unique_ptr< ShutdownTransportCallbackshutdownTransportCb_
 
FlowControlTimeout flowControlTimeout_
 
DrainTimeout drainTimeout_
 
SocketState reads_:2
 
SocketState writes_:2
 
bool ingressUpgraded_:1
 
bool resetSocketOnShutdown_:1
 
bool inLoopCallback_:1
 
bool inResume_:1
 
bool pendingPause_:1
 
std::unique_ptr< SecondaryAuthManagersecondAuthManager_
 

Additional Inherited Members

- Static Public Member Functions inherited from proxygen::HTTPSessionBase
static void setDefaultReadBufferLimit (uint32_t limit)
 
static void setMaxReadBufferSize (uint32_t bytes)
 
static void setFlowControlledBodySizeLimit (uint32_t limit)
 
static void setDefaultWriteBufferLimit (uint32_t max)
 
- Static Protected Member Functions inherited from proxygen::HTTPSessionBase
static void handleLastByteEvents (ByteEventTracker *byteEventTracker, HTTPTransaction *txn, size_t encodedSize, size_t byteOffset, bool piggybacked)
 
- Static Protected Attributes inherited from proxygen::HTTPSessionBase
static uint32_t kDefaultReadBufLimit = 65536
 
static uint32_t maxReadBufferSize_ = 4000
 
static uint32_t kDefaultWriteBufLimit = 65536
 
static uint32_t egressBodySizeLimit_ = 4096
 

Detailed Description

Definition at line 43 of file HTTPSession.h.

Member Typedef Documentation

Definition at line 55 of file HTTPSession.h.

Member Enumeration Documentation

Enumerator
UNPAUSED 
PAUSED 
SHUTDOWN 

Definition at line 1035 of file HTTPSession.h.

Constructor & Destructor Documentation

proxygen::HTTPSession::HTTPSession ( const WheelTimerInstance timeout,
folly::AsyncTransportWrapper::UniquePtr  sock,
const folly::SocketAddress localAddr,
const folly::SocketAddress peerAddr,
HTTPSessionController controller,
std::unique_ptr< HTTPCodec codec,
const wangle::TransportInfo tinfo,
InfoCallback infoCallback 
)
protected

HTTPSession is an abstract base class and cannot be instantiated directly. If you want to handle requests and send responses (act as a server), construct a HTTPDownstreamSession. If you want to make requests and handle responses (act as a client), construct a HTTPUpstreamSession.

Parameters
transactionTimeoutsTimeout for each transaction in the session.
sockAn open socket on which any applicable TLS handshaking has been completed already.
localAddrAddress and port of the local end of the socket.
peerAddrAddress and port of the remote end of the socket.
controllerController which can create the handler for a new transaction.
codecA codec with which to parse/generate messages in whatever HTTP-like wire format this session needs.
tinfoStruct containing the transport's TCP/SSL level info.
InfoCallbackOptional callback to be informed of session lifecycle events.

Referenced by connCloseByRemote(), and proxygen::HTTPSession::WriteSegment::writeErr().

proxygen::HTTPSession::HTTPSession ( folly::HHWheelTimer transactionTimeouts,
folly::AsyncTransportWrapper::UniquePtr  sock,
const folly::SocketAddress localAddr,
const folly::SocketAddress peerAddr,
HTTPSessionController controller,
std::unique_ptr< HTTPCodec codec,
const wangle::TransportInfo tinfo,
InfoCallback infoCallback 
)
protected
proxygen::HTTPSession::~HTTPSession ( )
overrideprotected

Definition at line 278 of file HTTPSession.cpp.

References folly::HHWheelTimer::Callback::cancelTimeout(), proxygen::HTTP2PriorityQueue::dropPriorityNodes(), proxygen::HTTP2PriorityQueue::empty(), flowControlTimeout_, folly::HHWheelTimer::Callback::isScheduled(), proxygen::HTTPSessionBase::runDestroyCallbacks(), sock_, transactions_, txnEgressQueue_, and writeTimeout_.

Referenced by connCloseByRemote().

278  {
279  VLOG(4) << *this << " closing";
280 
281  CHECK(transactions_.empty());
283  CHECK(txnEgressQueue_.empty());
284  DCHECK(!sock_->getReadCallback());
285 
286  if (writeTimeout_.isScheduled()) {
288  }
289 
292  }
293 
295 }
WriteTimeout writeTimeout_
Definition: HTTPSession.h:681
folly::AsyncTransportWrapper::UniquePtr sock_
Definition: HTTPSession.h:697
HTTP2PriorityQueue txnEgressQueue_
Definition: HTTPSession.h:690
std::map< HTTPCodec::StreamID, HTTPTransaction > transactions_
Definition: HTTPSession.h:692
FlowControlTimeout flowControlTimeout_
Definition: HTTPSession.h:1020

Member Function Documentation

void proxygen::HTTPSession::addAckToLastByteEvent ( HTTPTransaction txn,
const ByteEvent lastByteEvent 
)
private
void proxygen::HTTPSession::addLastByteEvent ( HTTPTransaction txn,
uint64_t  byteNo 
)
privatenoexcept
void proxygen::HTTPSession::addWaitingForReplaySafety ( ReplaySafetyCallback *  callback)
inlineoverrideprivatenoexcept

Add a ReplaySafetyCallback requesting notification when the transport has replay protection.

Most transport-layer security protocols (like TLS) provide protection against an eavesdropper capturing data, and later replaying it to the server. However, 0-RTT security protocols allow initial data to be sent without replay protection before the security handshake completes. This function can be used when a HTTP session is in that initial non-replay safe stage, but a request requires a replay safe transport. Will trigger callback synchronously if the transport is already replay safe.

Definition at line 800 of file HTTPSession.h.

References waitingForReplaySafety_.

801  {
802  if (sock_->isReplaySafe()) {
803  callback->onReplaySafe();
804  } else {
805  waitingForReplaySafety_.push_back(callback);
806  }
807  }
folly::AsyncTransportWrapper::UniquePtr sock_
Definition: HTTPSession.h:697
std::list< ReplaySafetyCallback * > waitingForReplaySafety_
Definition: HTTPSession.h:846
virtual bool proxygen::HTTPSession::allTransactionsStarted ( ) const
protectedpure virtual
void proxygen::HTTPSession::cancelLoopCallbacks ( )
inlineprotected

Definition at line 661 of file HTTPSession.h.

References folly::EventBase::LoopCallback::cancelLoopCallback(), folly::EventBase::LoopCallback::isLoopCallbackScheduled(), and shutdownTransportCb_.

Referenced by proxygen::HTTPUpstreamSession::detachThreadLocals().

661  {
662  if (isLoopCallbackScheduled()) {
664  }
665  if (shutdownTransportCb_) {
666  shutdownTransportCb_->cancelLoopCallback();
667  }
668  }
std::unique_ptr< ShutdownTransportCallback > shutdownTransportCb_
Definition: HTTPSession.h:998
bool isLoopCallbackScheduled() const
Definition: EventBase.h:160
void proxygen::HTTPSession::checkForShutdown ( )
protected

Check whether the socket is shut down in both directions; if it is, initiate the destruction of this HTTPSession.

Definition at line 2435 of file HTTPSession.cpp.

References folly::DelayedDestruction::destroy(), folly::EventBase::LoopCallback::isLoopCallbackScheduled(), reads_, readsShutdown(), resetSocketOnShutdown_, folly::AsyncSocket::setBufferCallback(), proxygen::SHUTDOWN, sock_, transactions_, and writesShutdown().

Referenced by detach(), immediateShutdown(), runLoopCallback(), sessionByteOffset(), shutdownTransport(), and shutdownTransportWithReset().

2435  {
2436  VLOG(10) << *this << " checking for shutdown, readShutdown="
2437  << readsShutdown() << ", writesShutdown=" << writesShutdown()
2438  << ", transaction set empty=" << transactions_.empty();
2439 
2440  // Two conditions are required to destroy the HTTPSession:
2441  // * All writes have been finished.
2442  // * There are no transactions remaining on the session.
2443  if (writesShutdown() && transactions_.empty() &&
2445  VLOG(4) << "destroying " << *this;
2446  sock_->setReadCB(nullptr);
2447  auto asyncSocket = sock_->getUnderlyingTransport<folly::AsyncSocket>();
2448  if (asyncSocket) {
2449  asyncSocket->setBufferCallback(nullptr);
2450  }
2452  if (resetSocketOnShutdown_) {
2453  sock_->closeWithReset();
2454  } else {
2455  sock_->closeNow();
2456  }
2457  destroy();
2458  }
2459 }
folly::AsyncTransportWrapper::UniquePtr sock_
Definition: HTTPSession.h:697
bool isLoopCallbackScheduled() const
Definition: EventBase.h:160
bool readsShutdown() const
Definition: HTTPSession.h:634
bool writesShutdown() const
Definition: HTTPSession.h:646
std::map< HTTPCodec::StreamID, HTTPTransaction > transactions_
Definition: HTTPSession.h:692
void setBufferCallback(BufferCallback *cb)
void proxygen::HTTPSession::closeWhenIdle ( )
overridevirtual

Instruct the connection that it should shutdown as soon as it is safe. This is called after notifyPendingShutdown().

Implements wangle::ManagedConnection.

Definition at line 464 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, drain(), dropConnection(), proxygen::HTTPCodec::generateGoaway(), proxygen::HTTPCodec::getLastIncomingStreamID(), hasMoreWrites(), isBusy(), proxygen::NO_ERROR, scheduleWrite(), and writeBuf_.

Referenced by CurlService::CurlClient::connectSuccess(), timeoutExpired(), and proxygen::HTTPSession::DrainTimeout::timeoutExpired().

464  {
465  // If drain() already called, this is a noop
466  drain();
467  // Generate the second GOAWAY now. No-op if second GOAWAY already sent.
471  scheduleWrite();
472  }
473  if (!isBusy() && !hasMoreWrites()) {
474  // if we're already idle, close now
475  dropConnection();
476  }
477 }
HTTPCodecFilterChain codec_
bool isBusy() const override
void dropConnection() override
void drain() override
virtual StreamID getLastIncomingStreamID() const
Definition: HTTPCodec.h:675
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
virtual size_t generateGoaway(folly::IOBufQueue &writeBuf, StreamID lastStream, ErrorCode code, std::unique_ptr< folly::IOBuf > debugData=nullptr)=0
bool hasMoreWrites() const
void proxygen::HTTPSession::commonEom ( HTTPTransaction txn,
size_t  encodedSize,
bool  piggybacked 
)
privatenoexcept

Common EOM process shared by sendHeaders, sendBody and sendEOM

Parameters
txnthe transaction that's sending request
encodedSizesize of data frame generated by codec
piggybackedwhether this eom is a separate sendEOM or piggybacked in sendHeaders and sendBody

Definition at line 1656 of file HTTPSession.cpp.

References byteEventTracker_, proxygen::HTTPSessionBase::handleLastByteEvents(), onEgressMessageFinished(), and sessionByteOffset().

Referenced by isConnWindowFull(), sendBody(), sendEOM(), and sendHeaders().

1659  {
1661  byteEventTracker_.get(), txn, encodedSize, sessionByteOffset(),
1662  piggybacked);
1664 }
void onEgressMessageFinished(HTTPTransaction *txn, bool withRST=false)
static void handleLastByteEvents(ByteEventTracker *byteEventTracker, HTTPTransaction *txn, size_t encodedSize, size_t byteOffset, bool piggybacked)
std::shared_ptr< ByteEventTracker > byteEventTracker_
Definition: HTTPSession.h:966
uint64_t sessionByteOffset()
Definition: HTTPSession.h:511
bool proxygen::HTTPSession::connCloseByRemote ( )
inlineoverridevirtual

If the connection is closed by remote end

Implements proxygen::HTTPSessionBase.

Definition at line 215 of file HTTPSession.h.

References codec, getSecondAuthManager(), getTransactionTimeoutHandler(), getTransport(), folly::AsyncTransportWrapper::getUnderlyingTransport(), HTTPSession(), folly::AsyncSocket::isClosedByPeer(), proxygen::localAddr, proxygen::peerAddr, setSecondAuthManager(), setupOnHeadersComplete(), and ~HTTPSession().

215  {
217  if (sock) {
218  return sock->isClosedByPeer();
219  }
220  return false;
221  }
folly::AsyncTransportWrapper * getTransport() override
Definition: HTTPSession.h:61
virtual bool isClosedByPeer() const
Definition: AsyncSocket.h:571
const T * getUnderlyingTransport() const
HTTPTransaction * proxygen::HTTPSession::createTransaction ( HTTPCodec::StreamID  streamID,
const folly::Optional< HTTPCodec::StreamID > &  assocStreamID,
const folly::Optional< HTTPCodec::ExAttributes > &  exAttributes,
const http2::PriorityUpdate priority = http2::DefaultPriority 
)
protected

Create a new transaction.

Returns
pointer to the transaction on success, or else nullptr if it already exists

Definition at line 2555 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, getCodecSendWindowSize(), wangle::ManagedConnection::getConnectionManager(), proxygen::WheelTimerInstance::getDefaultTimeout(), proxygen::HTTPTransaction::getID(), proxygen::HTTPSessionBase::getNumTxnServed(), proxygen::HTTPTransaction::getSessionStats(), proxygen::HTTPCodec::getTransportDirection(), proxygen::WheelTimerInstance::getWheelTimer(), incomingStreams_, incrementOutgoingStreams(), proxygen::HTTPSessionBase::incrementSeqNo(), proxygen::HTTPSessionBase::infoCallback_, initialReceiveWindow_, isDownstream(), proxygen::HTTPSessionBase::isPrioritySampled(), proxygen::HTTPTransaction::isPushed(), isUpstream(), liveTransactions_, proxygen::HTTPSessionBase::InfoCallback::onActivateConnection(), wangle::ConnectionManager::onActivated(), proxygen::HTTPSessionBase::onCreateTransaction(), receiveStreamWindowSize_, proxygen::HTTPSessionStats::recordSessionReused(), proxygen::HTTPSessionBase::sessionStats_, proxygen::HTTPTransaction::setPrioritySampled(), proxygen::HTTPTransaction::setReceiveWindow(), sock_, streamID, proxygen::HTTPCodec::supportsStreamFlowControl(), timeout_, transactions_, and txnEgressQueue_.

Referenced by newExTransaction(), newPushedTransaction(), proxygen::HTTPUpstreamSession::newTransaction(), onError(), onExMessageBegin(), onMessageBegin(), onPushMessageBegin(), and sessionByteOffset().

2559  {
2560  if (!sock_->good() || transactions_.count(streamID)) {
2561  // Refuse to add a transaction on a closing session or if a
2562  // transaction of that ID already exists.
2563  return nullptr;
2564  }
2565 
2566  if (transactions_.empty()) {
2567  if (infoCallback_) {
2569  }
2570  if (getConnectionManager()) {
2572  }
2574  }
2575 
2576  auto matchPair = transactions_.emplace(
2577  std::piecewise_construct,
2578  std::forward_as_tuple(streamID),
2579  std::forward_as_tuple(
2582  sessionStats_,
2586  priority,
2587  assocStreamID,
2588  exAttributes
2589  ));
2590 
2591  CHECK(matchPair.second) << "Emplacement failed, despite earlier "
2592  "existence check.";
2593 
2594  HTTPTransaction* txn = &matchPair.first->second;
2595 
2596  if (isPrioritySampled()) {
2597  txn->setPrioritySampled(true /* sampled */);
2598  }
2599 
2600  if (getNumTxnServed() > 0) {
2601  auto stats = txn->getSessionStats();
2602  if (stats != nullptr) {
2603  stats->recordSessionReused();
2604  }
2605  }
2606 
2607  VLOG(5) << *this << " adding streamID=" << txn->getID()
2608  << ", liveTransactions_ was " << liveTransactions_;
2609 
2611  incrementSeqNo();
2612  txn->setReceiveWindow(receiveStreamWindowSize_);
2613 
2614  if (isUpstream() && !txn->isPushed()) {
2616  // do not count towards MAX_CONCURRENT_STREAMS for PUSH_PROMISE
2617  } else if (!(isDownstream() && txn->isPushed())) {
2618  incomingStreams_++;
2619  }
2620 
2621  return txn;
2622 }
virtual void onActivateConnection(const HTTPSessionBase &)
HTTPCodecFilterChain codec_
size_t getCodecSendWindowSize() const
size_t receiveStreamWindowSize_
Definition: HTTPSession.h:975
std::chrono::milliseconds getDefaultTimeout() const
folly::AsyncTransportWrapper::UniquePtr sock_
Definition: HTTPSession.h:697
HTTP2PriorityQueue txnEgressQueue_
Definition: HTTPSession.h:690
void onActivated(ManagedConnection &conn) override
bool isUpstream() const
WheelTimerInstance timeout_
Definition: HTTPSession.h:699
virtual bool supportsStreamFlowControl() const
Definition: HTTPCodec.h:367
uint64_t getNumTxnServed() const
ConnectionManager * getConnectionManager()
uint32_t liveTransactions_
Definition: HTTPSession.h:695
std::map< HTTPCodec::StreamID, HTTPTransaction > transactions_
Definition: HTTPSession.h:692
HTTPSessionStats * sessionStats_
uint32_t streamID
Definition: SPDYCodec.cpp:131
bool isDownstream() const
virtual TransportDirection getTransportDirection() const =0
folly::HHWheelTimer * getWheelTimer() const
void proxygen::HTTPSession::decrementTransactionCount ( HTTPTransaction txn,
bool  ingressEOM,
bool  egressEOM 
)
protected

Definition at line 1858 of file HTTPSession.cpp.

References incomingStreams_, isDownstream(), proxygen::HTTPTransaction::isPushed(), isUpstream(), outgoingStreams_, and proxygen::HTTPTransaction::testAndClearActive().

Referenced by detach(), onEgressMessageFinished(), onHeadersSent(), and onMessageComplete().

1860  {
1861  if ((isUpstream() && !txn->isPushed()) ||
1862  (isDownstream() && txn->isPushed())) {
1863  if (ingressEOM && txn->testAndClearActive()) {
1864  outgoingStreams_--;
1865  }
1866  } else {
1867  if (egressEOM && txn->testAndClearActive()) {
1868  incomingStreams_--;
1869  }
1870  }
1871 }
bool isUpstream() const
bool isDownstream() const
void proxygen::HTTPSession::describe ( std::ostream &  os) const
overridevirtual

Implements proxygen::HTTPTransaction::Transport.

Definition at line 435 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, proxygen::getCodecProtocolString(), getLocalAddress(), getPeerAddress(), proxygen::HTTPCodec::getProtocol(), proxygen::HTTPCodec::getUserAgent(), and isDownstream().

Referenced by timeoutExpired().

435  {
436  os << "proto=" << getCodecProtocolString(codec_->getProtocol());
437  if (isDownstream()) {
438  os << ", UA=" << codec_->getUserAgent()
439  << ", downstream=" << getPeerAddress() << ", " << getLocalAddress()
440  << "=local";
441  } else {
442  os << ", local=" << getLocalAddress() << ", " << getPeerAddress()
443  << "=upstream";
444  }
445 }
HTTPCodecFilterChain codec_
virtual CodecProtocol getProtocol() const =0
const folly::SocketAddress & getLocalAddress() const noexceptoverride
Definition: HTTPSession.h:122
const folly::SocketAddress & getPeerAddress() const noexceptoverride
Definition: HTTPSession.h:126
virtual const std::string & getUserAgent() const =0
const std::string & getCodecProtocolString(CodecProtocol proto)
bool isDownstream() const
void proxygen::HTTPSession::detach ( HTTPTransaction txn)
overrideprotectedvirtualnoexcept

Implements proxygen::HTTPTransaction::Transport.

Definition at line 1896 of file HTTPSession.cpp.

References checkForShutdown(), decrementTransactionCount(), findTransaction(), wangle::ManagedConnection::getConnectionManager(), getPipelineStreamCount(), folly::gen::guard(), hasMoreWrites(), proxygen::HTTPSessionBase::infoCallback_, folly::HHWheelTimer::Callback::isScheduled(), liveTransactions_, maybeResumePausedPipelinedTransaction(), proxygen::HTTPSessionBase::InfoCallback::onDeactivateConnection(), wangle::ConnectionManager::onDeactivated(), proxygen::HTTPSessionBase::InfoCallback::onTransactionDetached(), readsShutdown(), proxygen::HTTPTransaction::removeExTransaction(), proxygen::HTTPTransaction::removePushedTransaction(), wangle::ManagedConnection::resetTimeout(), resumeIngress(), resumeReads(), proxygen::HTTPSessionBase::setLatestActive(), shouldShutdown(), shutdownTransport(), streamID, transactions_, writesDraining_, and writesShutdown().

Referenced by proxygen::HTTPUpstreamSession::detachTransactions(), numIncomingStreams(), and proxygen::HTTPSession::WriteSegment::setEOR().

1896  {
1897  DestructorGuard guard(this);
1898  HTTPCodec::StreamID streamID = txn->getID();
1899  auto txnSeqn = txn->getSequenceNumber();
1900  auto it = transactions_.find(txn->getID());
1901  DCHECK(it != transactions_.end());
1902 
1903  if (txn->isIngressPaused()) {
1904  // Someone detached a transaction that was paused. Make the resumeIngress
1905  // call to keep liveTransactions_ in order
1906  VLOG(4) << *this << " detached paused transaction=" << streamID;
1907  resumeIngress(txn);
1908  }
1909 
1910  VLOG(4) << *this << " removing streamID=" << streamID <<
1911  ", liveTransactions was " << liveTransactions_;
1912  CHECK_GT(liveTransactions_, 0);
1913  liveTransactions_--;
1914 
1915  if (txn->isPushed()) {
1916  auto assocTxn = findTransaction(*txn->getAssocTxnId());
1917  if (assocTxn) {
1918  assocTxn->removePushedTransaction(streamID);
1919  }
1920  }
1921  if (txn->getControlStream()) {
1922  auto controlTxn = findTransaction(*txn->getControlStream());
1923  if (controlTxn) {
1924  controlTxn->removeExTransaction(streamID);
1925  }
1926  }
1927 
1928  auto oldStreamCount = getPipelineStreamCount();
1929  decrementTransactionCount(txn, true, true);
1930  transactions_.erase(it);
1931 
1932  if (transactions_.empty()) {
1934  if (infoCallback_) {
1936  }
1937  if (getConnectionManager()) {
1939  }
1940  } else {
1941  if (infoCallback_) {
1943  }
1944  }
1945 
1946  if (!readsShutdown()) {
1947  if (maybeResumePausedPipelinedTransaction(oldStreamCount, txnSeqn)) {
1948  return;
1949  } else {
1950  // this will resume reads if they were paused (eg: 0 HTTP transactions)
1951  resumeReads();
1952  }
1953  }
1954 
1955  if (liveTransactions_ == 0 && transactions_.empty() && !isScheduled()) {
1956  resetTimeout();
1957  }
1958 
1959  // It's possible that this is the last transaction in the session,
1960  // so check whether the conditions for shutdown are satisfied.
1961  if (transactions_.empty()) {
1962  if (shouldShutdown()) {
1963  writesDraining_ = true;
1964  }
1965  // Handle the case where we are draining writes but all remaining
1966  // transactions terminated with no egress.
1967  if (writesDraining_ && !writesShutdown() && !hasMoreWrites()) {
1968  shutdownTransport(false, true);
1969  return;
1970  }
1971  }
1972  checkForShutdown();
1973 }
size_t getPipelineStreamCount() const
Definition: HTTPSession.h:835
void shutdownTransport(bool shutdownReads=true, bool shutdownWrites=true, const std::string &errorMsg="")
HTTPTransaction * findTransaction(HTTPCodec::StreamID streamID)
void resumeIngress(HTTPTransaction *txn) noexceptoverride
void decrementTransactionCount(HTTPTransaction *txn, bool ingressEOM, bool egressEOM)
bool maybeResumePausedPipelinedTransaction(size_t oldStreamCount, uint32_t txnSeqn)
void onDeactivated(ManagedConnection &conn) override
virtual void onTransactionDetached(const HTTPSessionBase &)
GuardImpl guard(ErrorHandler &&handler)
Definition: Base.h:840
bool shouldShutdown() const
void removePushedTransaction(HTTPCodec::StreamID pushStreamId)
bool readsShutdown() const
Definition: HTTPSession.h:634
ConnectionManager * getConnectionManager()
bool writesShutdown() const
Definition: HTTPSession.h:646
uint32_t liveTransactions_
Definition: HTTPSession.h:695
std::map< HTTPCodec::StreamID, HTTPTransaction > transactions_
Definition: HTTPSession.h:692
uint64_t StreamID
Definition: HTTPCodec.h:49
virtual void onDeactivateConnection(const HTTPSessionBase &)
uint32_t streamID
Definition: SPDYCodec.cpp:131
void removeExTransaction(HTTPCodec::StreamID exStreamId)
bool hasMoreWrites() const
void proxygen::HTTPSession::drain ( )
overrideprotectedvirtual

Drains the current transactions and prevents new transactions from being created on this session. If this is an upstream session and the number of transactions reaches zero, this session will shutdown the transport and delete itself. For downstream sessions, an explicit call to dropConnection() or shutdownTransport() is required.

Implements proxygen::HTTPSessionBase.

Reimplemented in proxygen::HTTPUpstreamSession.

Definition at line 2462 of file HTTPSession.cpp.

References allTransactionsStarted(), drainImpl(), draining_, isUpstream(), proxygen::HTTPSessionBase::setCloseReason(), proxygen::SHUTDOWN, shutdownTransport(), and transactions_.

Referenced by closeWhenIdle(), proxygen::HTTPUpstreamSession::drain(), isDraining(), notifyPendingShutdown(), and onGoaway().

2462  {
2463  if (!draining_) {
2464  VLOG(4) << *this << " draining";
2465  draining_ = true;
2467 
2468  if (allTransactionsStarted()) {
2469  drainImpl();
2470  }
2471  if (transactions_.empty() && isUpstream()) {
2472  // We don't do this for downstream since we need to wait for
2473  // inflight requests to arrive
2474  VLOG(4) << *this << " shutdown from drain";
2475  shutdownTransport(true, true);
2476  }
2477  } else {
2478  VLOG(4) << *this << " already draining";
2479  }
2480 }
void shutdownTransport(bool shutdownReads=true, bool shutdownWrites=true, const std::string &errorMsg="")
bool isUpstream() const
void setCloseReason(ConnectionCloseReason reason)
std::map< HTTPCodec::StreamID, HTTPTransaction > transactions_
Definition: HTTPSession.h:692
virtual bool allTransactionsStarted() const =0
void proxygen::HTTPSession::drainImpl ( )
protected

Definition at line 2482 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, proxygen::HTTPCodec::generateGoaway(), getGracefulGoawayAck(), proxygen::HTTPCodec::isReusable(), proxygen::HTTPCodec::isWaitingToDrain(), proxygen::NO_ERROR, scheduleWrite(), proxygen::HTTPSessionBase::setCloseReason(), proxygen::SHUTDOWN, started_, and writeBuf_.

Referenced by drain(), invokeOnAllTransactions(), and sendHeaders().

2482  {
2483  if (codec_->isReusable() || codec_->isWaitingToDrain()) {
2485  // For HTTP/2, if we haven't started yet then we cannot send a GOAWAY frame
2486  // since we haven't sent the initial SETTINGS frame. Defer sending that
2487  // GOAWAY until the initial SETTINGS is sent.
2488  if (started_) {
2492  scheduleWrite();
2493  }
2494  }
2495 }
HTTPCodecFilterChain codec_
virtual bool isWaitingToDrain() const =0
HTTPCodec::StreamID getGracefulGoawayAck() const
void setCloseReason(ConnectionCloseReason reason)
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
virtual bool isReusable() const =0
virtual size_t generateGoaway(folly::IOBufQueue &writeBuf, StreamID lastStream, ErrorCode code, std::unique_ptr< folly::IOBuf > debugData=nullptr)=0
void proxygen::HTTPSession::dropConnection ( )
overridevirtual

Forcibly drop a connection.

If a request is in progress, this should cause the connection to be closed with a reset.

Implements wangle::ManagedConnection.

Definition at line 493 of file HTTPSession.cpp.

References hasMoreWrites(), immediateShutdown(), proxygen::kErrorDropped, readsShutdown(), proxygen::HTTPSessionBase::setCloseReason(), proxygen::SHUTDOWN, shutdownTransport(), shutdownTransportWithReset(), sock_, transactions_, and writesShutdown().

Referenced by closeWhenIdle(), and timeoutExpired().

493  {
494  VLOG(4) << "dropping " << *this;
495  if (!sock_ || (readsShutdown() && writesShutdown())) {
496  VLOG(4) << *this << " already shutdown";
497  return;
498  }
499 
501  if (transactions_.empty() && !hasMoreWrites()) {
502  DestructorGuard dg(this);
503  shutdownTransport(true, true);
504  // shutdownTransport might have generated a write (goaway)
505  // If so, writes will not be shutdown, so fall through to
506  // shutdownTransportWithReset.
507  if (readsShutdown() && writesShutdown()) {
509  return;
510  }
511  }
513 }
void shutdownTransport(bool shutdownReads=true, bool shutdownWrites=true, const std::string &errorMsg="")
folly::AsyncTransportWrapper::UniquePtr sock_
Definition: HTTPSession.h:697
void setCloseReason(ConnectionCloseReason reason)
bool readsShutdown() const
Definition: HTTPSession.h:634
bool writesShutdown() const
Definition: HTTPSession.h:646
std::map< HTTPCodec::StreamID, HTTPTransaction > transactions_
Definition: HTTPSession.h:692
void shutdownTransportWithReset(ProxygenError errorCode, const std::string &errorMsg="")
bool hasMoreWrites() const
void proxygen::HTTPSession::dumpConnectionState ( uint8_t  loglevel)
overridevirtual

Dump the state of the connection to the log

Implements wangle::ManagedConnection.

Definition at line 515 of file HTTPSession.cpp.

Referenced by timeoutExpired().

515 {}
void proxygen::HTTPSession::enableDoubleGoawayDrain ( )
inlineoverridevirtual

Implements proxygen::HTTPSessionBase.

Definition at line 208 of file HTTPSession.h.

References proxygen::HTTPSessionBase::codec_, and proxygen::HTTPCodec::enableDoubleGoawayDrain().

208  {
210  }
HTTPCodecFilterChain codec_
virtual void enableDoubleGoawayDrain()
Definition: HTTPCodec.h:665
void proxygen::HTTPSession::errorOnAllTransactions ( ProxygenError  err,
const std::string errorMsg 
)
protected

This function invokes a callback on all transactions. It is safe, but runs in O(n*log n) and if the callback adds transactions, they will not get the callback.

Definition at line 2812 of file HTTPSession.cpp.

References errorOnTransactionIds(), and transactions_.

Referenced by invokeOnAllTransactions(), and shutdownTransportWithReset().

2814  {
2815  std::vector<HTTPCodec::StreamID> ids;
2816  for (const auto& txn: transactions_) {
2817  ids.push_back(txn.first);
2818  }
2819  errorOnTransactionIds(ids, err, errorMsg);
2820 }
void errorOnTransactionIds(const std::vector< HTTPCodec::StreamID > &ids, ProxygenError err, const std::string &extraErrorMsg="")
std::map< HTTPCodec::StreamID, HTTPTransaction > transactions_
Definition: HTTPSession.h:692
void proxygen::HTTPSession::errorOnTransactionId ( HTTPCodec::StreamID  id,
HTTPException  ex 
)
protected

Definition at line 2841 of file HTTPSession.cpp.

References findTransaction(), and folly::gen::move.

Referenced by errorOnTransactionIds(), invokeOnAllTransactions(), and onGoaway().

2843  {
2844  auto txn = findTransaction(id);
2845  if (txn != nullptr) {
2846  txn->onError(std::move(ex));
2847  }
2848 }
HTTPTransaction * findTransaction(HTTPCodec::StreamID streamID)
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
void proxygen::HTTPSession::errorOnTransactionIds ( const std::vector< HTTPCodec::StreamID > &  ids,
ProxygenError  err,
const std::string extraErrorMsg = "" 
)
protected

Definition at line 2822 of file HTTPSession.cpp.

References errorOnTransactionId(), proxygen::getErrorString(), proxygen::HTTPException::INGRESS_AND_EGRESS, folly::gen::move, proxygen::Exception::setProxygenError(), and string.

Referenced by errorOnAllTransactions(), invokeOnAllTransactions(), and onGoaway().

2825  {
2826  std::string extraErrorMsg;
2827  if (!errorMsg.empty()) {
2828  extraErrorMsg = folly::to<std::string>(". ", errorMsg);
2829  }
2830 
2831  for (auto id: ids) {
2833  folly::to<std::string>(getErrorString(err),
2834  " on transaction id: ", id,
2835  extraErrorMsg));
2836  ex.setProxygenError(err);
2838  }
2839 }
void errorOnTransactionId(HTTPCodec::StreamID id, HTTPException ex)
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
const char * string
Definition: Conv.cpp:212
const char * getErrorString(ProxygenError error)
HTTPTransaction * proxygen::HTTPSession::findTransaction ( HTTPCodec::StreamID  streamID)
protected

Get the HTTPTransaction for the given transaction ID, or nullptr if that transaction ID does not exist within this HTTPSession.

Definition at line 2545 of file HTTPSession.cpp.

References transactions_.

Referenced by detach(), errorOnTransactionId(), invokeOnAllTransactions(), onAbort(), onBody(), onChunkComplete(), onChunkHeader(), onError(), onExMessageBegin(), onHeadersComplete(), onMessageBegin(), onMessageComplete(), proxygen::HTTPDownstreamSession::onNativeProtocolUpgrade(), onNativeProtocolUpgradeImpl(), onPriority(), onPushMessageBegin(), onTrailersComplete(), onWindowUpdate(), pauseIngress(), resumeIngress(), sessionByteOffset(), and setNewTransactionPauseState().

2545  {
2546  auto it = transactions_.find(streamID);
2547  if (it == transactions_.end()) {
2548  return nullptr;
2549  } else {
2550  return &it->second;
2551  }
2552 }
std::map< HTTPCodec::StreamID, HTTPTransaction > transactions_
Definition: HTTPSession.h:692
uint32_t streamID
Definition: SPDYCodec.cpp:131
void proxygen::HTTPSession::flowControlTimeoutExpired ( )
protectednoexcept

Definition at line 425 of file HTTPSession.cpp.

References g(), proxygen::HTTPSessionBase::setCloseReason(), shutdownTransport(), and proxygen::TIMEOUT.

Referenced by getHTTPPriority(), and proxygen::HTTPSession::FlowControlTimeout::timeoutExpired().

425  {
426  VLOG(4) << "Flow control timeout for " << *this;
427 
428  DestructorGuard g(this);
429 
431  shutdownTransport(true, true);
432 }
void shutdownTransport(bool shutdownReads=true, bool shutdownWrites=true, const std::string &errorMsg="")
void setCloseReason(ConnectionCloseReason reason)
g_t g(f_t)
ByteEventTracker* proxygen::HTTPSession::getByteEventTracker ( )
inline

Definition at line 88 of file HTTPSession.h.

References byteEventTracker_, setByteEventTracker(), setEgressSettings(), setFlowControl(), and setSessionStats().

88 { return byteEventTracker_.get(); }
std::shared_ptr< ByteEventTracker > byteEventTracker_
Definition: HTTPSession.h:966
uint32_t proxygen::HTTPSession::getCertAuthSettingVal ( )
private

Definition at line 185 of file HTTPSession.cpp.

References folly::IOBuf::computeChainDataLength(), fizz::extensions::test::ekm, getTransport(), folly::AsyncTransportWrapper::getUnderlyingTransport(), isUpstream(), fizz::test::label, uint16_t, and uint32_t.

Referenced by getMaxConcurrentOutgoingStreamsRemote(), and setupCodec().

185  {
186  uint32_t certAuthSettingVal = 0;
187  constexpr uint16_t settingLen = 4;
188  std::unique_ptr<folly::IOBuf> ekm;
190  if (isUpstream()) {
191  label = kClientLabel;
192  } else {
193  label = kServerLabel;
194  }
195  auto fizzBase = getTransport()->getUnderlyingTransport<AsyncFizzBase>();
196  if (fizzBase) {
197  ekm = fizzBase->getEkm(label, nullptr, settingLen);
198  } else {
199  VLOG(4) << "Underlying transport does not support secondary "
200  "authentication.";
201  return certAuthSettingVal;
202  }
203  if (ekm && ekm->computeChainDataLength() == settingLen) {
204  folly::io::Cursor cursor(ekm.get());
205  uint32_t ekmVal = cursor.readBE<uint32_t>();
206  certAuthSettingVal = (ekmVal & 0x3fffffff) | 0x80000000;
207  }
208  return certAuthSettingVal;
209 }
folly::AsyncTransportWrapper * getTransport() override
Definition: HTTPSession.h:61
bool isUpstream() const
const T * getUnderlyingTransport() const
std::size_t computeChainDataLength() const
Definition: IOBuf.cpp:501
StringPiece label
const HTTPCodec& proxygen::HTTPSession::getCodec ( ) const
inlineoverrideprotectedvirtualnoexcept
size_t proxygen::HTTPSession::getCodecSendWindowSize ( ) const
protected

Definition at line 712 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, proxygen::HTTPCodec::getDefaultWindowSize(), proxygen::HTTPCodec::getIngressSettings(), proxygen::HTTPSettings::getSetting(), proxygen::INITIAL_WINDOW_SIZE, and settings.

Referenced by createTransaction(), onHeadersSent(), and onNativeProtocolUpgradeImpl().

712  {
713  const HTTPSettings* settings = codec_->getIngressSettings();
714  if (settings) {
717  }
718  return codec_->getDefaultWindowSize();
719 }
virtual const HTTPSettings * getIngressSettings() const
Definition: HTTPCodec.h:657
HTTPCodecFilterChain codec_
static http_parser_settings settings
Definition: test.c:1529
virtual uint32_t getDefaultWindowSize() const
Definition: HTTPCodec.h:680
const HTTPSetting * getSetting(SettingsId id) const
bool proxygen::HTTPSession::getCurrentTransportInfo ( wangle::TransportInfo tinfo)
overridevirtual

Implements proxygen::HTTPSessionBase.

Definition at line 2019 of file HTTPSession.cpp.

References wangle::TransportInfo::appProtocol, getCurrentTransportInfoWithoutUpdate(), wangle::TransportInfo::rtt, wangle::TransportInfo::rtx, wangle::TransportInfo::secure, wangle::TransportInfo::setupTime, wangle::TransportInfo::sslCipher, wangle::TransportInfo::sslError, wangle::TransportInfo::sslResume, wangle::TransportInfo::sslSetupTime, wangle::TransportInfo::sslVersion, and proxygen::HTTPSessionBase::transportInfo_.

Referenced by getSetupTransportInfo().

2019  {
2021  // some fields are the same with the setup transport info
2023  tinfo->secure = transportInfo_.secure;
2029  tinfo->sslError = transportInfo_.sslError;
2030 #if defined(__linux__) || defined(__FreeBSD__)
2031  // update connection transport info with the latest RTT
2032  if (tinfo->tcpinfo.tcpi_rtt > 0) {
2033  transportInfo_.tcpinfo.tcpi_rtt = tinfo->tcpinfo.tcpi_rtt;
2034  transportInfo_.rtt = std::chrono::microseconds(tinfo->tcpinfo.tcpi_rtt);
2035  }
2036  transportInfo_.rtx = tinfo->rtx;
2037 #endif
2038  return true;
2039  }
2040  return false;
2041 }
bool getCurrentTransportInfoWithoutUpdate(wangle::TransportInfo *tinfo) const override
SSLResumeEnum sslResume
std::chrono::milliseconds setupTime
std::chrono::microseconds rtt
Definition: TransportInfo.h:70
std::shared_ptr< std::string > sslCipher
std::shared_ptr< std::string > appProtocol
std::chrono::milliseconds sslSetupTime
wangle::TransportInfo transportInfo_
bool proxygen::HTTPSession::getCurrentTransportInfoWithoutUpdate ( wangle::TransportInfo tinfo) const
overridevirtual

Implements proxygen::HTTPSessionBase.

Definition at line 2009 of file HTTPSession.cpp.

References wangle::TransportInfo::initWithSocket(), and sock_.

Referenced by getCurrentTransportInfo(), and timeoutExpired().

2010  {
2011  auto sock = sock_->getUnderlyingTransport<AsyncSocket>();
2012  if (sock) {
2013  tinfo->initWithSocket(sock);
2014  return true;
2015  }
2016  return false;
2017 }
folly::AsyncTransportWrapper::UniquePtr sock_
Definition: HTTPSession.h:697
bool initWithSocket(const folly::AsyncSocket *sock)
folly::EventBase* proxygen::HTTPSession::getEventBase ( ) const
inlineoverridevirtual

Implements proxygen::HTTPSessionBase.

Definition at line 65 of file HTTPSession.h.

References sock_.

65  {
66  if (sock_) {
67  return sock_->getEventBase();
68  }
69  return nullptr;
70  }
folly::AsyncTransportWrapper::UniquePtr sock_
Definition: HTTPSession.h:697
HTTPCodec::StreamID proxygen::HTTPSession::getGracefulGoawayAck ( ) const
private

Get the id of the stream we should ack in a graceful GOAWAY

Definition at line 2899 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, proxygen::HTTPCodec::getLastIncomingStreamID(), proxygen::HTTPCodec::isReusable(), proxygen::HTTPCodec::isWaitingToDrain(), and max.

Referenced by drainImpl(), getMaxConcurrentOutgoingStreamsRemote(), and startNow().

2899  {
2900  if (!codec_->isReusable() || codec_->isWaitingToDrain()) {
2901  // TODO: just track last stream ID inside HTTPSession since this logic
2902  // is shared between HTTP/2 and SPDY
2903  return codec_->getLastIncomingStreamID();
2904  }
2905  VLOG(4) << *this << " getGracefulGoawayAck is reusable and not draining";
2906  // return the maximum possible stream id
2908 }
HTTPCodecFilterChain codec_
LogLevel max
Definition: LogLevel.cpp:31
virtual bool isWaitingToDrain() const =0
virtual StreamID getLastIncomingStreamID() const
Definition: HTTPCodec.h:675
virtual bool isReusable() const =0
bool proxygen::HTTPSession::getHTTP2PrioritiesEnabled ( ) const
inlineoverridevirtual

Reimplemented from proxygen::HTTPSessionBase.

Definition at line 114 of file HTTPSession.h.

References proxygen::HTTPSessionBase::getHTTP2PrioritiesEnabled().

Referenced by getMessagePriority(), onPriority(), and sendHeaders().

114  {
116  }
virtual bool getHTTP2PrioritiesEnabled() const
const folly::SocketAddress& proxygen::HTTPSession::getLocalAddress ( ) const
inlineoverridevirtualnoexcept

Implements proxygen::HTTPTransaction::Transport.

Definition at line 122 of file HTTPSession.h.

References proxygen::HTTPSessionBase::getLocalAddress().

Referenced by describe(), and proxygen::HTTPDownstreamSession::getTransactionTimeoutHandler().

122  {
124  }
const folly::SocketAddress & getLocalAddress() const noexcept
http2::PriorityUpdate proxygen::HTTPSession::getMessagePriority ( const HTTPMessage msg)
private

Definition at line 737 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, proxygen::http2::DefaultPriority, proxygen::http2::PriorityUpdate::exclusive, getHTTP2PrioritiesEnabled(), proxygen::HTTPMessage::getHTTP2Priority(), proxygen::HTTPMessage::getPriority(), proxygen::HTTPCodec::mapPriorityToDependency(), proxygen::http2::PriorityUpdate::streamDependency, and proxygen::http2::PriorityUpdate::weight.

Referenced by getMaxConcurrentOutgoingStreamsRemote(), onExMessageBegin(), onMessageBegin(), onPushMessageBegin(), and sendHeaders().

737  {
738  http2::PriorityUpdate h2Pri = http2::DefaultPriority;
739 
740  // if HTTP2 priorities are enabled, get them from the message
741  // and ignore otherwise
742  if (getHTTP2PrioritiesEnabled() && msg) {
743  auto res = msg->getHTTP2Priority();
744  if (res) {
745  h2Pri.streamDependency = std::get<0>(*res);
746  h2Pri.exclusive = std::get<1>(*res);
747  h2Pri.weight = std::get<2>(*res);
748  } else {
749  // HTTPMessage with setPriority called explicitly
750  h2Pri.streamDependency =
751  codec_->mapPriorityToDependency(msg->getPriority());
752  }
753  }
754  return h2Pri;
755 }
HTTPCodecFilterChain codec_
bool getHTTP2PrioritiesEnabled() const override
Definition: HTTPSession.h:114
virtual StreamID mapPriorityToDependency(uint8_t) const
Definition: HTTPCodec.h:706
const PriorityUpdate DefaultPriority
Definition: HTTP2Framer.cpp:21
unique_ptr< IOBuf > proxygen::HTTPSession::getNextToSend ( bool *  cork,
bool *  eom 
)
protected

Gets the next IOBuf to send (either writeBuf_ or new egress from the priority queue), and sets cork appropriately

Definition at line 2043 of file HTTPSession.cpp.

References byteEventTracker_, bytesWritten_, folly::IOBufQueue::chainLength(), proxygen::HTTPSessionBase::codec_, connFlowControl_, proxygen::HTTPSessionBase::egressBodySizeLimit_, proxygen::HTTP2PriorityQueue::empty(), folly::IOBufQueue::empty(), proxygen::FlowControlFilter::getAvailableSend(), proxygen::HTTPCodec::getProtocol(), isConnWindowFull(), proxygen::isSpdyCodecProtocol(), min, folly::IOBufQueue::move(), proxygen::HTTP2PriorityQueue::nextEgress(), nextEgressResults_, numActiveWrites_, proxygen::TTLBAStats::recordTTLBAIOBSplitByEom(), proxygen::HTTPSessionBase::sessionStats_, folly::IOBufQueue::split(), txnEgressQueue_, uint32_t, uint64_t, writeBuf_, and writesShutdown().

Referenced by onHeadersSent(), and runLoopCallback().

2043  {
2044  // limit ourselves to one outstanding write at a time (onWriteSuccess calls
2045  // scheduleWrite)
2046  if (numActiveWrites_ > 0 || writesShutdown()) {
2047  VLOG(4) << "skipping write during this loop, numActiveWrites_=" <<
2048  numActiveWrites_ << " writesShutdown()=" << writesShutdown();
2049  return nullptr;
2050  }
2051 
2052  // We always tack on at least one body packet to the current write buf
2053  // This ensures that a short HTTPS response will go out in a single SSL record
2054  while (!txnEgressQueue_.empty()) {
2055  uint32_t toSend = kWriteReadyMax;
2056  if (connFlowControl_) {
2057  if (connFlowControl_->getAvailableSend() == 0) {
2058  VLOG(4) << "Session-level send window is full, skipping remaining "
2059  << "body writes this loop";
2060  break;
2061  }
2062  toSend = std::min(toSend, connFlowControl_->getAvailableSend());
2063  }
2066  CHECK(!nextEgressResults_.empty()); // Queue was non empty, so this must be
2067  // The maximum we will send for any transaction in this loop
2068  uint32_t txnMaxToSend = toSend * nextEgressResults_.front().second;
2069  if (txnMaxToSend == 0) {
2070  // toSend is smaller than the number of transactions. Give all egress
2071  // to the first transaction
2072  nextEgressResults_.erase(++nextEgressResults_.begin(),
2073  nextEgressResults_.end());
2074  txnMaxToSend = std::min(toSend, egressBodySizeLimit_);
2075  nextEgressResults_.front().second = 1;
2076  }
2077  if (nextEgressResults_.size() > 1 && txnMaxToSend > egressBodySizeLimit_) {
2078  // Cap the max to egressBodySizeLimit_, and recompute toSend accordingly
2079  txnMaxToSend = egressBodySizeLimit_;
2080  toSend = txnMaxToSend / nextEgressResults_.front().second;
2081  }
2082  // split allowed by relative weight, with some minimum
2083  for (auto txnPair: nextEgressResults_) {
2084  uint32_t txnAllowed = txnPair.second * toSend;
2085  if (nextEgressResults_.size() > 1) {
2086  CHECK_LE(txnAllowed, egressBodySizeLimit_);
2087  }
2088  if (connFlowControl_) {
2089  CHECK_LE(txnAllowed, connFlowControl_->getAvailableSend());
2090  }
2091  if (txnAllowed == 0) {
2092  // The ratio * toSend was so small this txn gets nothing.
2093  VLOG(4) << *this << " breaking egress loop on 0 txnAllowed";
2094  break;
2095  }
2096 
2097  VLOG(4) << *this << " egressing txnID=" << txnPair.first->getID() <<
2098  " allowed=" << txnAllowed;
2099  txnPair.first->onWriteReady(txnAllowed, txnPair.second);
2100  }
2101  nextEgressResults_.clear();
2102  // it can be empty because of HTTPTransaction rate limiting. We should
2103  // change rate limiting to clearPendingEgress while waiting.
2104  if (!writeBuf_.empty()) {
2105  break;
2106  }
2107  }
2108  *eom = false;
2109  if (byteEventTracker_) {
2110  uint64_t needed = byteEventTracker_->preSend(cork, eom, bytesWritten_);
2111  if (needed > 0) {
2112  VLOG(5) << *this << " writeBuf_.chainLength(): "
2113  << writeBuf_.chainLength() << " txnEgressQueue_.empty(): "
2114  << txnEgressQueue_.empty();
2115 
2116  if (needed < writeBuf_.chainLength()) {
2117  // split the next EOM chunk
2118  VLOG(5) << *this << " splitting " << needed << " bytes out of a "
2119  << writeBuf_.chainLength() << " bytes IOBuf";
2120  *cork = true;
2121  if (sessionStats_) {
2123  }
2124  return writeBuf_.split(needed);
2125  } else {
2126  CHECK_EQ(needed, writeBuf_.chainLength());
2127  }
2128  }
2129  }
2130 
2131  // cork if there are txns with pending egress and room to send them
2132  *cork = !txnEgressQueue_.empty() && !isConnWindowFull();
2133  return writeBuf_.move();
2134 }
std::unique_ptr< folly::IOBuf > split(size_t n)
Definition: IOBufQueue.h:420
size_t chainLength() const
Definition: IOBufQueue.h:492
HTTPCodecFilterChain codec_
FlowControlFilter * connFlowControl_
Definition: HTTPSession.h:913
HTTP2PriorityQueue::NextEgressResult nextEgressResults_
Definition: HTTPSession.h:964
bool empty() const
Definition: IOBufQueue.h:503
virtual CodecProtocol getProtocol() const =0
std::unique_ptr< folly::IOBuf > move()
Definition: IOBufQueue.h:459
HTTP2PriorityQueue txnEgressQueue_
Definition: HTTPSession.h:690
LogLevel min
Definition: LogLevel.cpp:30
bool isConnWindowFull() const
Definition: HTTPSession.h:765
virtual void recordTTLBAIOBSplitByEom() noexcept=0
bool writesShutdown() const
Definition: HTTPSession.h:646
HTTPSessionStats * sessionStats_
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
bool isSpdyCodecProtocol(CodecProtocol protocol)
std::shared_ptr< ByteEventTracker > byteEventTracker_
Definition: HTTPSession.h:966
void nextEgress(NextEgressResult &result, bool spdyMode=false)
uint32_t getAvailableSend() const
static uint32_t egressBodySizeLimit_
uint32_t proxygen::HTTPSession::getNumIncomingStreams ( ) const
inlineoverridevirtual

Implements proxygen::HTTPSessionBase.

Definition at line 84 of file HTTPSession.h.

References incomingStreams_.

Referenced by proxygen::HTTPUpstreamSession::isDetachable().

84  {
85  return incomingStreams_;
86  }
uint32_t proxygen::HTTPSession::getNumOutgoingStreams ( ) const
inlineoverridevirtual

Implements proxygen::HTTPSessionBase.

Definition at line 80 of file HTTPSession.h.

References outgoingStreams_.

80  {
81  return outgoingStreams_;
82  }
const folly::SocketAddress& proxygen::HTTPSession::getPeerAddress ( ) const
inlineoverridevirtualnoexcept

Implements proxygen::HTTPTransaction::Transport.

Definition at line 126 of file HTTPSession.h.

References proxygen::HTTPSessionBase::getPeerAddress().

Referenced by describe(), and shutdownTransport().

126  {
128  }
const folly::SocketAddress & getPeerAddress() const noexcept
size_t proxygen::HTTPSession::getPipelineStreamCount ( ) const
inlineprivate

Definition at line 835 of file HTTPSession.h.

References incomingStreams_, incrementOutgoingStreams(), isDownstream(), maybeResumePausedPipelinedTransaction(), and uint32_t.

Referenced by detach(), maybeResumePausedPipelinedTransaction(), onEgressMessageFinished(), and onMessageBegin().

835  {
836  return isDownstream() ? incomingStreams_ : transactions_.size();
837  }
std::map< HTTPCodec::StreamID, HTTPTransaction > transactions_
Definition: HTTPSession.h:692
bool isDownstream() const
void proxygen::HTTPSession::getReadBuffer ( void **  bufReturn,
size_t *  lenReturn 
)
overrideprotectedvirtual

When data becomes available, getReadBuffer() will be invoked to get the buffer into which data should be read.

This method allows the ReadCallback to delay buffer allocation until data becomes available. This allows applications to manage large numbers of idle connections, without having to maintain a separate read buffer for each idle connection.

It is possible that in some cases, getReadBuffer() may be called multiple times before readDataAvailable() is invoked. In this case, the data will be written to the buffer returned from the most recent call to readDataAvailable(). If the previous calls to readDataAvailable() returned different buffers, the ReadCallback is responsible for ensuring that they are not leaked.

If getReadBuffer() throws an exception, returns a nullptr buffer, or returns a 0 length, the ReadCallback will be uninstalled and its readError() method will be invoked.

getReadBuffer() is not allowed to change the transport state before it returns. (For example, it should never uninstall the read callback, or set a different read callback.)

Parameters
bufReturngetReadBuffer() should update *bufReturn to contain the address of the read buffer. This parameter will never be nullptr.
lenReturngetReadBuffer() should update *lenReturn to contain the maximum number of bytes that may be written to the read buffer. This parameter will never be nullptr.

Implements folly::AsyncReader::ReadCallback.

Definition at line 526 of file HTTPSession.cpp.

References FOLLY_SCOPED_TRACE_SECTION, fizz::kMinReadSize, proxygen::HTTPSessionBase::maxReadBufferSize_, folly::IOBufQueue::preallocate(), and readBuf_.

Referenced by getHTTPPriority().

526  {
527  FOLLY_SCOPED_TRACE_SECTION("HTTPSession - getReadBuffer");
528  pair<void*,uint32_t> readSpace =
530  *buf = readSpace.first;
531  *bufSize = readSpace.second;
532 }
#define FOLLY_SCOPED_TRACE_SECTION(arg,...)
static uint32_t maxReadBufferSize_
folly::IOBufQueue readBuf_
Definition: HTTPSession.h:687
static const uint32_t kMinReadSize
std::pair< void *, std::size_t > preallocate(std::size_t min, std::size_t newAllocationSize, std::size_t max=std::numeric_limits< std::size_t >::max())
Definition: IOBufQueue.h:356
SecondaryAuthManager * proxygen::HTTPSession::getSecondAuthManager ( ) const

Get the SecondaryAuthManager attached to this session.

Definition at line 1821 of file HTTPSession.cpp.

References secondAuthManager_.

Referenced by connCloseByRemote().

1821  {
1822  return secondAuthManager_.get();
1823 }
std::unique_ptr< SecondaryAuthManager > secondAuthManager_
Definition: HTTPSession.h:1055
const wangle::TransportInfo& proxygen::HTTPSession::getSetupTransportInfo ( ) const
inlineoverridevirtualnoexcept
virtual HTTPTransaction::Handler* proxygen::HTTPSession::getTransactionTimeoutHandler ( HTTPTransaction txn)
protectedpure virtual

Called by transactionTimeout if the transaction has no handler.

Implemented in proxygen::HTTPUpstreamSession, and proxygen::HTTPDownstreamSession.

Referenced by connCloseByRemote(), and transactionTimeout().

folly::AsyncTransportWrapper* proxygen::HTTPSession::getTransport ( )
inlineoverridevirtual

Implements proxygen::HTTPSessionBase.

Definition at line 61 of file HTTPSession.h.

References sock_.

Referenced by connCloseByRemote(), getCertAuthSettingVal(), onCertificate(), onCertificateRequest(), and verifyCertAuthSetting().

61  {
62  return sock_.get();
63  }
folly::AsyncTransportWrapper::UniquePtr sock_
Definition: HTTPSession.h:697
const folly::AsyncTransportWrapper* proxygen::HTTPSession::getTransport ( ) const
inlineoverridevirtual

Implements proxygen::HTTPSessionBase.

Definition at line 72 of file HTTPSession.h.

References sock_.

72  {
73  return sock_.get();
74  }
folly::AsyncTransportWrapper::UniquePtr sock_
Definition: HTTPSession.h:697
HTTPSessionBase::SessionType proxygen::HTTPSession::getType ( ) const
inlineoverridevirtualnoexcept
const folly::AsyncTransportWrapper* proxygen::HTTPSession::getUnderlyingTransport ( ) const
inlineoverrideprotectedvirtualnoexcept

Returns the underlying AsyncTransportWrapper. Overrides HTTPTransaction::Transport::getUnderlyingTransport().

Implements proxygen::HTTPTransaction::Transport.

Definition at line 446 of file HTTPSession.h.

References sock_.

447  {
448  return sock_.get();
449  }
folly::AsyncTransportWrapper::UniquePtr sock_
Definition: HTTPSession.h:697
bool proxygen::HTTPSession::hasActiveTransactions ( ) const
inlineoverridevirtual

Implements proxygen::HTTPSessionBase.

Definition at line 76 of file HTTPSession.h.

References transactions_.

76  {
77  return !transactions_.empty();
78  }
std::map< HTTPCodec::StreamID, HTTPTransaction > transactions_
Definition: HTTPSession.h:692
bool proxygen::HTTPSession::hasMoreWrites ( ) const
protected

Check whether the session has any writes in progress or upcoming

Definition at line 2800 of file HTTPSession.cpp.

References proxygen::HTTP2PriorityQueue::empty(), folly::IOBufQueue::front(), numActiveWrites_, pendingWrites_, txnEgressQueue_, and writeBuf_.

Referenced by closeWhenIdle(), detach(), dropConnection(), proxygen::HTTPUpstreamSession::isReusable(), onWriteSuccess(), runLoopCallback(), sessionByteOffset(), and shutdownTransport().

2800  {
2801  VLOG(10) << __PRETTY_FUNCTION__
2802  << " numActiveWrites_: " << numActiveWrites_
2803  << " pendingWrites_.empty(): " << pendingWrites_.empty()
2804  << " pendingWrites_.size(): " << pendingWrites_.size()
2805  << " txnEgressQueue_.empty(): " << txnEgressQueue_.empty();
2806 
2807  return (numActiveWrites_ != 0) ||
2808  !pendingWrites_.empty() || writeBuf_.front() ||
2810 }
const folly::IOBuf * front() const
Definition: IOBufQueue.h:476
HTTP2PriorityQueue txnEgressQueue_
Definition: HTTPSession.h:690
WriteSegmentList pendingWrites_
Definition: HTTPSession.h:908
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
void proxygen::HTTPSession::immediateShutdown ( )
protected

Immediately shut down the session, by deleting the loop callbacks first

Definition at line 479 of file HTTPSession.cpp.

References folly::EventBase::LoopCallback::cancelLoopCallback(), checkForShutdown(), folly::EventBase::LoopCallback::isLoopCallbackScheduled(), shutdownTransportCb_, transactions_, and writesShutdown().

Referenced by dropConnection(), and sessionByteOffset().

479  {
480  if (isLoopCallbackScheduled()) {
482  }
483  if (shutdownTransportCb_) {
484  shutdownTransportCb_.reset();
485  }
486  // checkForShutdown only closes the connection if these conditions are true
487  DCHECK(writesShutdown());
488  DCHECK(transactions_.empty());
490 }
std::unique_ptr< ShutdownTransportCallback > shutdownTransportCb_
Definition: HTTPSession.h:998
bool isLoopCallbackScheduled() const
Definition: EventBase.h:160
bool writesShutdown() const
Definition: HTTPSession.h:646
std::map< HTTPCodec::StreamID, HTTPTransaction > transactions_
Definition: HTTPSession.h:692
void proxygen::HTTPSession::incrementOutgoingStreams ( )
private
void proxygen::HTTPSession::invalidStream ( HTTPCodec::StreamID  stream,
ErrorCode  code = ErrorCode::_SPDY_INVALID_STREAM 
)
private

Invoked when the codec processes callbacks for a stream we are no longer tracking.

Definition at line 2910 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, proxygen::ERROR, proxygen::HTTPException::INGRESS_AND_EGRESS, onError(), proxygen::HTTPException::setCodecStatusCode(), and proxygen::HTTPCodec::supportsParallelRequests().

Referenced by getMaxConcurrentOutgoingStreamsRemote(), onBody(), onChunkComplete(), onChunkHeader(), onError(), onExMessageBegin(), onHeadersComplete(), onMessageComplete(), onPushMessageBegin(), and onTrailersComplete().

2910  {
2911  if (!codec_->supportsParallelRequests()) {
2912  LOG(ERROR) << "Invalid stream on non-parallel codec.";
2913  return;
2914  }
2915 
2917  folly::to<std::string>("invalid stream=", stream));
2918  // TODO: Below line will change for HTTP/2 -- just call a const getter
2919  // function for the status code.
2920  err.setCodecStatusCode(code);
2921  onError(stream, err, true);
2922 }
HTTPCodecFilterChain codec_
virtual bool supportsParallelRequests() const =0
void onError(HTTPCodec::StreamID streamID, const HTTPException &error, bool newTxn) override
template<typename... Args1, typename... Args2>
void proxygen::HTTPSession::invokeOnAllTransactions ( void(HTTPTransaction::*)(Args1...)  fn,
Args2 &&...  args 
)
inlineprotected

This function invokes a callback on all transactions. It is safe, but runs in O(n*log n) and if the callback adds transactions, they will not get the callback.

Definition at line 584 of file HTTPSession.h.

References drainImpl(), errorOnAllTransactions(), errorOnTransactionId(), errorOnTransactionIds(), findTransaction(), g(), pauseReadsImpl(), resumeReadsImpl(), resumeTransactions(), shouldShutdown(), string, and transactions_.

Referenced by onGoaway(), onSetSendWindow(), resumeTransactions(), runLoopCallback(), shutdownTransport(), and updateWriteBufSize().

585  {
586  DestructorGuard g(this);
587  std::vector<HTTPCodec::StreamID> ids;
588  for (const auto& txn: transactions_) {
589  ids.push_back(txn.first);
590  }
591  for (auto idit = ids.begin(); idit != ids.end() && !transactions_.empty();
592  ++idit) {
593  auto txn = findTransaction(*idit);
594  if (txn != nullptr) {
595  (txn->*fn)(std::forward<Args2>(args)...);
596  }
597  }
598  }
HTTPTransaction * findTransaction(HTTPCodec::StreamID streamID)
std::map< HTTPCodec::StreamID, HTTPTransaction > transactions_
Definition: HTTPSession.h:692
g_t g(f_t)
bool proxygen::HTTPSession::isBufferMovable ( )
overrideprotectedvirtualnoexcept

When data becomes available, isBufferMovable() will be invoked to figure out which API will be used, readBufferAvailable() or readDataAvailable(). If isBufferMovable() returns true, that means ReadCallback supports the IOBuf ownership transfer and readBufferAvailable() will be used. Otherwise, not.

By default, isBufferMovable() always return false. If readBufferAvailable() is implemented and to be invoked, You should overwrite isBufferMovable() and return true in the inherited class.

This method allows the AsyncSocket/AsyncSSLSocket do buffer allocation by itself until data becomes available. Compared with the pre/post buffer allocation in getReadBuffer()/readDataAvailabe(), readBufferAvailable() has two advantages. First, this can avoid memcpy. E.g., in AsyncSSLSocket, the decrypted data was copied from the openssl internal buffer to the readbuf buffer. With the buffer ownership transfer, the internal buffer can be directly "moved" to ReadCallback. Second, the memory allocation can be more precise. The reason is AsyncSocket/AsyncSSLSocket can allocate the memory of precise size because they have more context about the available data than ReadCallback. Think about the getReadBuffer() pre-allocate 4072 bytes buffer, but the available data is always 16KB (max OpenSSL record size).

Reimplemented from folly::AsyncReader::ReadCallback.

Definition at line 552 of file HTTPSession.cpp.

Referenced by getHTTPPriority().

552  {
553  return true;
554 }
bool proxygen::HTTPSession::isBusy ( ) const
overridevirtual

Check whether the connection has any requests outstanding.

Implements wangle::ManagedConnection.

Definition at line 448 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, proxygen::HTTPCodec::isBusy(), and transactions_.

Referenced by closeWhenIdle(), and timeoutExpired().

448  {
449  return !transactions_.empty() || codec_->isBusy();
450 }
HTTPCodecFilterChain codec_
std::map< HTTPCodec::StreamID, HTTPTransaction > transactions_
Definition: HTTPSession.h:692
virtual bool isBusy() const =0
bool proxygen::HTTPSession::isConnWindowFull ( ) const
inlineprivate
bool proxygen::HTTPSession::isDraining ( ) const
inlineoverrideprotectedvirtual

Returns true if this session is draining. This can happen if drain() is called explicitly, if a GOAWAY frame is received, or during shutdown.

Implements proxygen::HTTPTransaction::Transport.

Definition at line 455 of file HTTPSession.h.

References drain(), draining_, int64_t, runLoopCallback(), scheduleWrite(), shutdownTransport(), shutdownTransportWithReset(), string, updateWriteBufSize(), and updateWriteCount().

455 { return draining_; }
bool proxygen::HTTPSession::maybeResumePausedPipelinedTransaction ( size_t  oldStreamCount,
uint32_t  txnSeqn 
)
private

Definition at line 1879 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, getPipelineStreamCount(), proxygen::HTTPCodec::supportsParallelRequests(), and transactions_.

Referenced by detach(), getPipelineStreamCount(), and onEgressMessageFinished().

1880  {
1881  if (!codec_->supportsParallelRequests() && !transactions_.empty() &&
1882  getPipelineStreamCount() < oldStreamCount &&
1883  getPipelineStreamCount() == 1) {
1884  auto& nextTxn = transactions_.rbegin()->second;
1885  DCHECK_EQ(nextTxn.getSequenceNumber(), txnSeqn + 1);
1886  DCHECK(!nextTxn.isIngressComplete());
1887  DCHECK(nextTxn.isIngressPaused());
1888  VLOG(4) << "Resuming paused pipelined txn " << nextTxn;
1889  nextTxn.resumeIngress();
1890  return true;
1891  }
1892  return false;
1893 }
size_t getPipelineStreamCount() const
Definition: HTTPSession.h:835
HTTPCodecFilterChain codec_
std::map< HTTPCodec::StreamID, HTTPTransaction > transactions_
Definition: HTTPSession.h:692
virtual bool supportsParallelRequests() const =0
bool proxygen::HTTPSession::needToBlockForReplaySafety ( ) const
inlineoverrideprivatevirtual

This is a temporary workaround until we have a better way to allocate stream IDs to waiting transactions.

Implements proxygen::HTTPTransaction::Transport.

Definition at line 822 of file HTTPSession.h.

References onReplaySafe(), and waitingForReplaySafety_.

822  {
823  return !waitingForReplaySafety_.empty();
824  }
std::list< ReplaySafetyCallback * > waitingForReplaySafety_
Definition: HTTPSession.h:846
HTTPTransaction *FOLLY_NULLABLE proxygen::HTTPSession::newExTransaction ( HTTPTransaction::Handler handler,
HTTPCodec::StreamID  controlStream,
bool  unidirectional = false 
)
overrideprotectedvirtualnoexcept

Implements proxygen::HTTPTransaction::Transport.

Definition at line 681 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, proxygen::HTTPCodec::createStream(), createTransaction(), draining_, proxygen::ENABLE_EX_HEADERS, proxygen::ERROR, proxygen::getCodecProtocolString(), proxygen::HTTPCodec::getEgressSettings(), proxygen::HTTPTransaction::getID(), proxygen::HTTPCodec::getProtocol(), handler(), maxConcurrentOutgoingStreamsRemote_, proxygen::HTTPCodec::NoStream, outgoingStreams_, proxygen::HTTPTransaction::setHandler(), setNewTransactionPauseState(), and started_.

Referenced by numIncomingStreams().

684  {
685  CHECK(handler && controlStream > 0);
686  auto eSettings = codec_->getEgressSettings();
687  if (!eSettings || !eSettings->getSetting(SettingsId::ENABLE_EX_HEADERS, 0)) {
689  << " does not support ExTransaction";
690  return nullptr;
691  }
693  LOG(ERROR) << "cannot support any more transactions in " << *this;
694  return nullptr;
695  }
696 
697  DCHECK(started_);
698  HTTPTransaction* txn =
701  HTTPCodec::ExAttributes(controlStream, unidirectional));
702  if (!txn) {
703  return nullptr;
704  }
705 
706  DestructorGuard dg(this);
707  txn->setHandler(handler);
708  setNewTransactionPauseState(txn->getID());
709  return txn;
710 }
HTTPTransaction * createTransaction(HTTPCodec::StreamID streamID, const folly::Optional< HTTPCodec::StreamID > &assocStreamID, const folly::Optional< HTTPCodec::ExAttributes > &exAttributes, const http2::PriorityUpdate &priority=http2::DefaultPriority)
virtual StreamID createStream()=0
virtual HTTPSettings * getEgressSettings()
Definition: HTTPCodec.h:653
HTTPCodecFilterChain codec_
void setNewTransactionPauseState(HTTPCodec::StreamID streamID)
virtual CodecProtocol getProtocol() const =0
uint32_t maxConcurrentOutgoingStreamsRemote_
Definition: HTTPSession.h:922
void handler(int, siginfo_t *, void *)
const std::string & getCodecProtocolString(CodecProtocol proto)
static const folly::Optional< StreamID > NoStream
Definition: HTTPCodec.h:51
HTTPTransaction * proxygen::HTTPSession::newPushedTransaction ( HTTPCodec::StreamID  assocStreamId,
HTTPTransaction::PushHandler handler 
)
overrideprotectedvirtualnoexcept

Implements proxygen::HTTPTransaction::Transport.

Definition at line 649 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, proxygen::HTTPCodec::createStream(), createTransaction(), draining_, FOLLY_NULLABLE, proxygen::HTTPTransaction::getID(), handler(), isDownstream(), maxConcurrentOutgoingStreamsRemote_, proxygen::HTTPCodec::NoExAttributes, outgoingStreams_, proxygen::HTTPTransaction::setHandler(), setNewTransactionPauseState(), and proxygen::HTTPCodec::supportsPushTransactions().

Referenced by numIncomingStreams().

651  {
653  return nullptr;
654  }
655  CHECK(isDownstream());
656  CHECK_NOTNULL(handler);
658  // This session doesn't support any more push transactions
659  // This could be an actual problem - since a single downstream SPDY session
660  // might be connected to N upstream hosts, each of which send M pushes,
661  // which exceeds the limit.
662  // should we queue?
663  return nullptr;
664  }
665 
666  HTTPTransaction* txn = createTransaction(codec_->createStream(),
667  assocStreamId,
669  if (!txn) {
670  return nullptr;
671  }
672 
673  DestructorGuard dg(this);
674  auto txnID = txn->getID();
675  txn->setHandler(handler);
677  return txn;
678 }
HTTPTransaction * createTransaction(HTTPCodec::StreamID streamID, const folly::Optional< HTTPCodec::StreamID > &assocStreamID, const folly::Optional< HTTPCodec::ExAttributes > &exAttributes, const http2::PriorityUpdate &priority=http2::DefaultPriority)
virtual StreamID createStream()=0
HTTPCodecFilterChain codec_
virtual bool supportsPushTransactions() const =0
void setNewTransactionPauseState(HTTPCodec::StreamID streamID)
uint32_t maxConcurrentOutgoingStreamsRemote_
Definition: HTTPSession.h:922
void handler(int, siginfo_t *, void *)
bool isDownstream() const
static const folly::Optional< ExAttributes > NoExAttributes
Definition: HTTPCodec.h:66
void proxygen::HTTPSession::notifyEgressBodyBuffered ( int64_t  bytes)
overrideprotectedvirtualnoexcept

Implements proxygen::HTTPTransaction::Transport.

Definition at line 1997 of file HTTPSession.cpp.

References folly::EventBase::LoopCallback::isLoopCallbackScheduled(), pendingWriteSizeDelta_, sock_, and updateWriteBufSize().

Referenced by numIncomingStreams().

1997  {
1998  pendingWriteSizeDelta_ += bytes;
1999  // any net change requires us to update pause/resume state in the
2000  // loop callback
2001  if (pendingWriteSizeDelta_ > 0) {
2002  // pause inline, resume in loop
2003  updateWriteBufSize(0);
2004  } else if (!isLoopCallbackScheduled()) {
2005  sock_->getEventBase()->runInLoop(this);
2006  }
2007 }
folly::AsyncTransportWrapper::UniquePtr sock_
Definition: HTTPSession.h:697
bool isLoopCallbackScheduled() const
Definition: EventBase.h:160
int64_t pendingWriteSizeDelta_
Definition: HTTPSession.h:954
void updateWriteBufSize(int64_t delta)
void proxygen::HTTPSession::notifyIngressBodyProcessed ( uint32_t  bytes)
overrideprotectedvirtualnoexcept

Implements proxygen::HTTPTransaction::Transport.

Definition at line 1986 of file HTTPSession.cpp.

References connFlowControl_, proxygen::FlowControlFilter::ingressBytesProcessed(), proxygen::HTTPSessionBase::notifyBodyProcessed(), resumeReads(), scheduleWrite(), and writeBuf_.

Referenced by numIncomingStreams().

1986  {
1988  resumeReads();
1989  }
1990  if (connFlowControl_ &&
1992  scheduleWrite();
1993  }
1994 }
FlowControlFilter * connFlowControl_
Definition: HTTPSession.h:913
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
bool notifyBodyProcessed(uint32_t bytes)
bool ingressBytesProcessed(folly::IOBufQueue &writeBuf, uint32_t delta)
void proxygen::HTTPSession::notifyPendingEgress ( )
overrideprotectedvirtualnoexcept

Implements proxygen::HTTPTransaction::Transport.

Definition at line 453 of file HTTPSession.cpp.

References scheduleWrite().

Referenced by numIncomingStreams().

453  {
454  scheduleWrite();
455 }
void proxygen::HTTPSession::notifyPendingShutdown ( )
overridevirtual

Notify the connection that a shutdown is pending. This method will be called at the beginning of graceful shutdown.

Implements wangle::ManagedConnection.

Definition at line 458 of file HTTPSession.cpp.

References drain().

Referenced by readTimeoutExpired(), and timeoutExpired().

458  {
459  VLOG(4) << *this << " notified pending shutdown";
460  drain();
461 }
void drain() override
uint32_t proxygen::HTTPSession::numIncomingStreams ( ) const
inlineoverrideprotectedvirtual

Return the number of open streams started by the remote side. Parallel codecs with a maximum number of streams will invoke this to determine if a new stream exceeds the limit.

Reimplemented from proxygen::HTTPCodec::Callback.

Definition at line 401 of file HTTPSession.h.

References detach(), handler(), incomingStreams_, int64_t, newExTransaction(), newPushedTransaction(), notifyEgressBodyBuffered(), notifyIngressBodyProcessed(), notifyPendingEgress(), pauseIngress(), resumeIngress(), sendAbort(), sendBody(), sendChunkHeader(), sendChunkTerminator(), sendEOM(), sendHeaders(), sendPriority(), sendWindowUpdate(), folly::size(), statusCode, transactionTimeout(), and uint32_t.

401  {
402  return incomingStreams_;
403  }
uint32_t proxygen::HTTPSession::numOutgoingStreams ( ) const
inlineoverrideprotectedvirtual

Return the number of open streams started by this codec callback. Parallel codecs with a maximum number of streams will invoke this to determine if a new stream exceeds the limit.

Reimplemented from proxygen::HTTPCodec::Callback.

Definition at line 398 of file HTTPSession.h.

References outgoingStreams_.

398  {
399  return outgoingStreams_;
400  }
void proxygen::HTTPSession::onAbort ( HTTPCodec::StreamID  ,
ErrorCode   
)
overrideprotectedvirtual

Called when the peer has asked to shut down a stream immediately.

Parameters
streamThe stream ID
codeThe code the stream was aborted with
Note
Not applicable to all protocols.

Reimplemented from proxygen::HTTPCodec::Callback.

Definition at line 1163 of file HTTPSession.cpp.

References proxygen::CANCEL, findTransaction(), proxygen::HTTPTransaction::getAssocTxnId(), proxygen::getErrorCodeString(), proxygen::HTTPTransaction::getExTransactions(), proxygen::HTTPTransaction::getPushedTransactions(), proxygen::HTTPException::INGRESS_AND_EGRESS, isDownstream(), proxygen::kErrorStreamAbort, proxygen::HTTPTransaction::onError(), proxygen::HTTPException::setCodecStatusCode(), proxygen::Exception::setProxygenError(), and streamID.

Referenced by getSecurityProtocol().

1164  {
1165  VLOG(4) << "stream abort on " << *this << ", streamID=" << streamID
1166  << ", code=" << getErrorCodeString(code);
1167  HTTPTransaction* txn = findTransaction(streamID);
1168  if (!txn) {
1169  VLOG(4) << *this << " abort for unrecognized transaction, streamID= "
1170  << streamID;
1171  return;
1172  }
1174  folly::to<std::string>("Stream aborted, streamID=",
1175  streamID, ", code=", getErrorCodeString(code)));
1176  ex.setProxygenError(kErrorStreamAbort);
1177  ex.setCodecStatusCode(code);
1178  DestructorGuard dg(this);
1179  if (isDownstream() && !txn->getAssocTxnId() && code == ErrorCode::CANCEL) {
1180  // Cancelling the assoc txn cancels all push txns
1181  for (auto it = txn->getPushedTransactions().begin();
1182  it != txn->getPushedTransactions().end(); ) {
1183  auto pushTxn = findTransaction(*it);
1184  ++it;
1185  DCHECK(pushTxn != nullptr);
1186  pushTxn->onError(ex);
1187  }
1188  }
1189  auto exTxns = txn->getExTransactions();
1190  for (auto it = exTxns.begin(); it != exTxns.end(); ++it) {
1191  auto exTxn = findTransaction(*it);
1192  if (exTxn) {
1193  exTxn->onError(ex);
1194  }
1195  }
1196  txn->onError(ex);
1197 }
HTTPTransaction * findTransaction(HTTPCodec::StreamID streamID)
const char * getErrorCodeString(ErrorCode error)
Definition: ErrorCode.cpp:18
uint32_t streamID
Definition: SPDYCodec.cpp:131
bool isDownstream() const
void proxygen::HTTPSession::onBody ( HTTPCodec::StreamID  stream,
std::unique_ptr< folly::IOBuf chain,
uint16_t  padding 
)
overrideprotectedvirtual

Called for each block of message body data

Parameters
streamThe stream ID
chainOne or more buffers of body data. The codec will remove any protocol framing, such as HTTP/1.1 chunk headers, from the buffers before calling this function.
paddingNumber of pad bytes that came with the data segment

Implements proxygen::HTTPCodec::Callback.

Definition at line 970 of file HTTPSession.cpp.

References folly::IOBuf::computeChainDataLength(), connFlowControl_, findTransaction(), FOLLY_SCOPED_TRACE_SECTION, proxygen::FlowControlFilter::ingressBytesProcessed(), invalidStream(), folly::gen::move, proxygen::HTTPSessionBase::onBodyImpl(), pauseReads(), scheduleWrite(), uint64_t, and writeBuf_.

Referenced by getSecurityProtocol().

971  {
972  FOLLY_SCOPED_TRACE_SECTION("HTTPSession - onBody");
973  DestructorGuard dg(this);
974  // The codec's parser detected part of the ingress message's
975  // entity-body.
976  uint64_t length = chain->computeChainDataLength();
977  HTTPTransaction* txn = findTransaction(streamID);
978  if (!txn) {
979  if (connFlowControl_ &&
981  scheduleWrite();
982  }
984  return;
985  }
986 
987  if (HTTPSessionBase::onBodyImpl(std::move(chain), length, padding, txn)) {
988  VLOG(4) << *this << " pausing due to read limit exceeded.";
989  pauseReads();
990  }
991 }
#define FOLLY_SCOPED_TRACE_SECTION(arg,...)
HTTPTransaction * findTransaction(HTTPCodec::StreamID streamID)
FlowControlFilter * connFlowControl_
Definition: HTTPSession.h:913
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
bool onBodyImpl(std::unique_ptr< folly::IOBuf > chain, size_t length, uint16_t padding, HTTPTransaction *txn)
void invalidStream(HTTPCodec::StreamID stream, ErrorCode code=ErrorCode::_SPDY_INVALID_STREAM)
std::size_t computeChainDataLength() const
Definition: IOBuf.cpp:501
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
bool ingressBytesProcessed(folly::IOBufQueue &writeBuf, uint32_t delta)
uint32_t streamID
Definition: SPDYCodec.cpp:131
void proxygen::HTTPSession::onCertificate ( uint16_t  ,
std::unique_ptr< folly::IOBuf  
)
overrideprotectedvirtual

Called upon receipt of an authenticator, for protocols that support secondary certificate authentication.

Parameters
certIdThe Cert-ID identifying this authenticator
authenticatorThe authenticator request
Note
Not all protocols support secondary certificate authentication. HTTP/2 does, but HTTP/1.1 doesn't.

Reimplemented from proxygen::HTTPCodec::Callback.

Definition at line 1380 of file HTTPSession.cpp.

References proxygen::DOWNSTREAM, getTransport(), folly::AsyncTransportWrapper::getUnderlyingTransport(), isUpstream(), folly::gen::move, secondAuthManager_, and proxygen::UPSTREAM.

Referenced by getSecurityProtocol().

1381  {
1382  DestructorGuard dg(this);
1383  VLOG(4) << "CERTIFICATE on" << *this << ", certId=" << certId;
1384 
1385  bool isValid = false;
1386  auto fizzBase = getTransport()->getUnderlyingTransport<AsyncFizzBase>();
1387  if (fizzBase) {
1388  if (isUpstream()) {
1389  isValid = secondAuthManager_->validateAuthenticator(
1390  *fizzBase,
1392  certId,
1393  std::move(authenticator));
1394  } else {
1395  isValid = secondAuthManager_->validateAuthenticator(
1396  *fizzBase,
1398  certId,
1399  std::move(authenticator));
1400  }
1401  } else {
1402  VLOG(4) << "Underlying transport does not support secondary "
1403  "authentication.";
1404  return;
1405  }
1406  if (isValid) {
1407  VLOG(4) << "Successfully validated the authenticator provided by the peer.";
1408  } else {
1409  VLOG(4) << "Failed to validate the authenticator provided by the peer";
1410  }
1411 }
folly::AsyncTransportWrapper * getTransport() override
Definition: HTTPSession.h:61
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
bool isUpstream() const
const T * getUnderlyingTransport() const
std::unique_ptr< SecondaryAuthManager > secondAuthManager_
Definition: HTTPSession.h:1055
void proxygen::HTTPSession::onCertificateRequest ( uint16_t  ,
std::unique_ptr< folly::IOBuf  
)
overrideprotectedvirtual

Called upon receipt of a certificate request frame, for protocols that support secondary certificate authentication.

Parameters
requestIdThe Request-ID identifying the certificate request
authRequestThe authenticator request
Note
Not all protocols support secondary certificate authentication. HTTP/2 does, but HTTP/1.1 doesn't.

Reimplemented from proxygen::HTTPCodec::Callback.

Definition at line 1347 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, proxygen::DOWNSTREAM, proxygen::HTTPCodec::generateCertificate(), getTransport(), folly::AsyncTransportWrapper::getUnderlyingTransport(), isUpstream(), folly::gen::move, scheduleWrite(), secondAuthManager_, proxygen::UPSTREAM, and writeBuf_.

Referenced by getSecurityProtocol().

1348  {
1349  DestructorGuard dg(this);
1350  VLOG(4) << "CERTIFICATE_REQUEST on" << *this << ", requestId=" << requestId;
1351 
1352  std::pair<uint16_t, std::unique_ptr<folly::IOBuf>> authenticator;
1353  auto fizzBase = getTransport()->getUnderlyingTransport<AsyncFizzBase>();
1354  if (fizzBase) {
1355  if (isUpstream()) {
1356  authenticator =
1357  secondAuthManager_->getAuthenticator(*fizzBase,
1359  requestId,
1360  std::move(authRequest));
1361  } else {
1362  authenticator =
1363  secondAuthManager_->getAuthenticator(*fizzBase,
1365  requestId,
1366  std::move(authRequest));
1367  }
1368  } else {
1369  VLOG(4) << "Underlying transport does not support secondary "
1370  "authentication.";
1371  return;
1372  }
1374  authenticator.first,
1375  std::move(authenticator.second)) > 0) {
1376  scheduleWrite();
1377  }
1378 }
folly::AsyncTransportWrapper * getTransport() override
Definition: HTTPSession.h:61
HTTPCodecFilterChain codec_
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
bool isUpstream() const
virtual size_t generateCertificate(folly::IOBufQueue &, uint16_t, std::unique_ptr< folly::IOBuf >)
Definition: HTTPCodec.h:642
const T * getUnderlyingTransport() const
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
std::unique_ptr< SecondaryAuthManager > secondAuthManager_
Definition: HTTPSession.h:1055
void proxygen::HTTPSession::onChunkComplete ( HTTPCodec::StreamID  )
overrideprotectedvirtual

Called when the terminating CRLF is received to end a chunk of HTTP body data.

Parameters
streamThe stream ID

Reimplemented from proxygen::HTTPCodec::Callback.

Definition at line 1018 of file HTTPSession.cpp.

References findTransaction(), invalidStream(), and proxygen::HTTPTransaction::onIngressChunkComplete().

Referenced by getSecurityProtocol().

1018  {
1019  // The codec's parser detected the end of the message body chunk
1020  // associated with the most recent call to onChunkHeader().
1021  HTTPTransaction* txn = findTransaction(streamID);
1022  if (!txn) {
1024  return;
1025  }
1026  txn->onIngressChunkComplete();
1027 }
HTTPTransaction * findTransaction(HTTPCodec::StreamID streamID)
void invalidStream(HTTPCodec::StreamID stream, ErrorCode code=ErrorCode::_SPDY_INVALID_STREAM)
uint32_t streamID
Definition: SPDYCodec.cpp:131
void proxygen::HTTPSession::onChunkHeader ( HTTPCodec::StreamID  ,
size_t   
)
overrideprotectedvirtual

Called for each HTTP chunk header.

onChunkHeader() will be called when the chunk header is received. As the chunk data arrives, it will be passed to the callback normally with onBody() calls. Note that the chunk data may arrive in multiple onBody() calls: it is not guaranteed to arrive in a single onBody() call.

After the chunk data has been received and the terminating CRLF has been received, onChunkComplete() will be called.

Parameters
streamThe stream ID
lengthThe chunk length.

Reimplemented from proxygen::HTTPCodec::Callback.

Definition at line 993 of file HTTPSession.cpp.

References findTransaction(), invalidStream(), and proxygen::HTTPTransaction::onIngressChunkHeader().

Referenced by getSecurityProtocol().

994  {
995  // The codec's parser detected a chunk header (meaning that this
996  // connection probably is HTTP/1.1).
997  //
998  // After calling onChunkHeader(), the codec will call onBody() zero
999  // or more times and then call onChunkComplete().
1000  //
1001  // The reason for this callback on the chunk header is to support
1002  // an optimization. In general, the job of the codec is to present
1003  // the HTTPSession with an abstract view of a message,
1004  // with all the details of wire formatting hidden. However, there's
1005  // one important case where we want to know about chunking: reverse
1006  // proxying where both the client and server streams are HTTP/1.1.
1007  // In that scenario, we preserve the server's chunk boundaries when
1008  // sending the response to the client, in order to avoid possibly
1009  // making the egress packetization worse by rechunking.
1010  HTTPTransaction* txn = findTransaction(streamID);
1011  if (!txn) {
1013  return;
1014  }
1015  txn->onIngressChunkHeader(length);
1016 }
HTTPTransaction * findTransaction(HTTPCodec::StreamID streamID)
void invalidStream(HTTPCodec::StreamID stream, ErrorCode code=ErrorCode::_SPDY_INVALID_STREAM)
uint32_t streamID
Definition: SPDYCodec.cpp:131
void proxygen::HTTPSession::onConnectionSendWindowClosed ( )
overrideprivatevirtual

Implements proxygen::FlowControlFilter::Callback.

Definition at line 2880 of file HTTPSession.cpp.

References proxygen::HTTP2PriorityQueue::empty(), flowControlTimeout_, proxygen::HTTPSession::FlowControlTimeout::getTimeoutDuration(), proxygen::HTTPSessionBase::infoCallback_, folly::HHWheelTimer::Callback::isScheduled(), proxygen::HTTPSessionBase::InfoCallback::onFlowControlWindowClosed(), proxygen::HTTPSessionStats::recordSessionStalled(), proxygen::WheelTimerInstance::scheduleTimeout(), proxygen::HTTPSessionBase::sessionStats_, timeout_, and txnEgressQueue_.

Referenced by getMaxConcurrentOutgoingStreamsRemote().

2880  {
2881  if(!txnEgressQueue_.empty()) {
2882  VLOG(4) << *this << " session stalled by flow control";
2883  if (sessionStats_) {
2885  }
2886  }
2887  DCHECK(!flowControlTimeout_.isScheduled());
2888  if (infoCallback_) {
2890  }
2892  if (timeout != std::chrono::milliseconds(0)) {
2894  } else {
2896  }
2897 }
virtual void recordSessionStalled() noexcept=0
std::chrono::milliseconds getTimeoutDuration() const
Definition: HTTPSession.h:1009
HTTP2PriorityQueue txnEgressQueue_
Definition: HTTPSession.h:690
void scheduleTimeout(folly::HHWheelTimer::Callback *callback, std::chrono::milliseconds timeout)
WheelTimerInstance timeout_
Definition: HTTPSession.h:699
HTTPSessionStats * sessionStats_
FlowControlTimeout flowControlTimeout_
Definition: HTTPSession.h:1020
virtual void onFlowControlWindowClosed(const HTTPSessionBase &)
void proxygen::HTTPSession::onConnectionSendWindowOpen ( )
overrideprivatevirtual

Callback function from the flow control filter if the full window becomes not full.

Implements proxygen::FlowControlFilter::Callback.

Definition at line 2874 of file HTTPSession.cpp.

References folly::HHWheelTimer::Callback::cancelTimeout(), flowControlTimeout_, and scheduleWrite().

Referenced by getMaxConcurrentOutgoingStreamsRemote().

2874  {
2876  // We can write more now. Schedule a write.
2877  scheduleWrite();
2878 }
FlowControlTimeout flowControlTimeout_
Definition: HTTPSession.h:1020
void proxygen::HTTPSession::onDeleteAckEvent ( )
overrideprivatevirtualnoexcept

Implements proxygen::ByteEventTracker::Callback.

Definition at line 2930 of file HTTPSession.cpp.

References readsShutdown(), shutdownTransport(), and transactions_.

Referenced by isConnWindowFull().

2930  {
2931  if (readsShutdown()) {
2932  shutdownTransport(true, transactions_.empty());
2933  }
2934 }
void shutdownTransport(bool shutdownReads=true, bool shutdownWrites=true, const std::string &errorMsg="")
bool readsShutdown() const
Definition: HTTPSession.h:634
std::map< HTTPCodec::StreamID, HTTPTransaction > transactions_
Definition: HTTPSession.h:692
void proxygen::HTTPSession::onEgressBufferCleared ( )
overrideprivatevirtual
void proxygen::HTTPSession::onEgressBuffered ( )
overrideprivatevirtual
void proxygen::HTTPSession::onEgressMessageFinished ( HTTPTransaction txn,
bool  withRST = false 
)
protected

Invoked when the transaction finishes sending a message and appropriately shuts down reads and/or writes with respect to downstream or upstream semantics.

Definition at line 1714 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, decrementTransactionCount(), proxygen::HTTPTransaction::getMaxDeferredSize(), getPipelineStreamCount(), proxygen::HTTPTransaction::getSequenceNumber(), proxygen::HTTPSessionBase::infoCallback_, proxygen::HTTPCodec::isReusable(), maybeResumePausedPipelinedTransaction(), proxygen::HTTPSessionBase::InfoCallback::onRequestEnd(), readsShutdown(), resetAfterDrainingWrites_, proxygen::HTTPSessionBase::setCloseReason(), shutdownTransport(), shutdownTransportCb_, sock_, proxygen::TRANSACTION_ABORT, and transactions_.

Referenced by commonEom(), onHeadersSent(), and sendAbort().

1714  {
1715  // If the semantics of the protocol don't permit more messages
1716  // to be read or sent on this connection, close the socket in one or
1717  // more directions.
1718  CHECK(!transactions_.empty());
1719 
1720  if (infoCallback_) {
1721  infoCallback_->onRequestEnd(*this, txn->getMaxDeferredSize());
1722  }
1723  auto oldStreamCount = getPipelineStreamCount();
1724  decrementTransactionCount(txn, false, true);
1725  if (withRST || ((!codec_->isReusable() || readsShutdown()) &&
1726  transactions_.size() == 1)) {
1727  // We should shutdown reads if we are closing with RST or we aren't
1728  // interested in any further messages (ie if we are a downstream session).
1729  // Upgraded sessions have independent ingress and egress, and the reads
1730  // need not be shutdown on egress finish.
1731  if (withRST) {
1732  // Let any queued writes complete, but send a RST when done.
1733  VLOG(4) << *this << " resetting egress after this message";
1736  shutdownTransport(true, true);
1737  } else {
1738  // the reason is already set (either not reusable or readshutdown).
1739 
1740  // Defer normal shutdowns until the end of the loop. This
1741  // handles an edge case with direct responses with Connection:
1742  // close served before ingress EOM. The remainder of the ingress
1743  // message may be in the parse loop, so give it a chance to
1744  // finish out and avoid a kErrorEOF
1745 
1746  // we can get here during shutdown, in that case do not schedule a
1747  // shutdown callback again
1748  if (!shutdownTransportCb_) {
1749  // Just for safety, the following bumps the refcount on this session
1750  // to keep it live until the loopCb runs
1751  shutdownTransportCb_.reset(new ShutdownTransportCallback(this));
1752  sock_->getEventBase()->runInLoop(shutdownTransportCb_.get(), true);
1753  }
1754  }
1755  } else {
1757  txn->getSequenceNumber());
1758  }
1759 }
size_t getPipelineStreamCount() const
Definition: HTTPSession.h:835
void shutdownTransport(bool shutdownReads=true, bool shutdownWrites=true, const std::string &errorMsg="")
HTTPCodecFilterChain codec_
folly::AsyncTransportWrapper::UniquePtr sock_
Definition: HTTPSession.h:697
void decrementTransactionCount(HTTPTransaction *txn, bool ingressEOM, bool egressEOM)
bool maybeResumePausedPipelinedTransaction(size_t oldStreamCount, uint32_t txnSeqn)
std::unique_ptr< ShutdownTransportCallback > shutdownTransportCb_
Definition: HTTPSession.h:998
void setCloseReason(ConnectionCloseReason reason)
bool readsShutdown() const
Definition: HTTPSession.h:634
std::map< HTTPCodec::StreamID, HTTPTransaction > transactions_
Definition: HTTPSession.h:692
virtual void onRequestEnd(const HTTPSessionBase &, uint32_t)
virtual bool isReusable() const =0
void proxygen::HTTPSession::onError ( HTTPCodec::StreamID  stream,
const HTTPException error,
bool  newTxn 
)
overrideprotectedvirtual

Called when a parsing or protocol error has occurred

Parameters
streamThe stream ID
errorDescription of the error
newTxntrue if onMessageBegin has not been called for txn

Implements proxygen::HTTPCodec::Callback.

Definition at line 1099 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, createTransaction(), folly::pushmi::operators::error(), findTransaction(), proxygen::HTTPTransaction::getEgressState(), proxygen::HTTPTransaction::getHandler(), proxygen::HTTPSessionBase::handleErrorDirectly(), proxygen::HTTPSessionBase::infoCallback_, ingressError_, invalidStream(), proxygen::HTTPCodec::isReusable(), proxygen::kErrorMessage, proxygen::HTTPCodec::NoExAttributes, proxygen::HTTPCodec::NoStream, proxygen::HTTPTransaction::onError(), proxygen::HTTPSessionBase::InfoCallback::onIngressError(), onNewTransactionParseError(), proxygen::HTTPSessionBase::InfoCallback::onRequestBegin(), onSessionParseError(), proxygen::SESSION_PARSE_ERROR, proxygen::HTTPSessionBase::setCloseReason(), shutdownTransport(), proxygen::HTTPCodec::supportsParallelRequests(), and transactions_.

Referenced by getSecurityProtocol(), invalidStream(), onHeadersComplete(), and onPushMessageBegin().

1100  {
1101  DestructorGuard dg(this);
1102  // The codec detected an error in the ingress stream, possibly bad
1103  // syntax, a truncated message, or bad semantics in the frame. If reads
1104  // are paused, queue up the event; otherwise, process it now.
1105  VLOG(4) << "Error on " << *this << ", streamID=" << streamID
1106  << ", " << error;
1107 
1108  if (ingressError_) {
1109  return;
1110  }
1111  if (!codec_->supportsParallelRequests()) {
1112  // this error should only prevent us from reading/handling more errors
1113  // on serial streams
1114  ingressError_ = true;
1116  }
1117  if ((streamID == 0) && infoCallback_) {
1119  }
1120 
1121  if (!streamID) {
1122  ingressError_ = true;
1123  onSessionParseError(error);
1124  return;
1125  }
1126 
1127  HTTPTransaction* txn = findTransaction(streamID);
1128  if (!txn) {
1129  if (error.hasHttpStatusCode() && streamID != 0) {
1130  // If the error has an HTTP code, then parsing was fine, it just was
1131  // illegal in a higher level way
1134  if (infoCallback_) {
1135  infoCallback_->onRequestBegin(*this);
1136  }
1137  if (txn) {
1138  handleErrorDirectly(txn, error);
1139  }
1140  } else if (newTxn) {
1142  } else {
1143  VLOG(4) << *this << " parse error with invalid transaction";
1145  }
1146  return;
1147  }
1148 
1149  if (!txn->getHandler() &&
1150  txn->getEgressState() == HTTPTransactionEgressSM::State::Start) {
1151  handleErrorDirectly(txn, error);
1152  return;
1153  }
1154 
1155  txn->onError(error);
1156  if (!codec_->isReusable() && transactions_.empty()) {
1157  VLOG(4) << *this << "shutdown from onError";
1159  shutdownTransport(true, true);
1160  }
1161 }
HTTPTransaction * createTransaction(HTTPCodec::StreamID streamID, const folly::Optional< HTTPCodec::StreamID > &assocStreamID, const folly::Optional< HTTPCodec::ExAttributes > &exAttributes, const http2::PriorityUpdate &priority=http2::DefaultPriority)
void shutdownTransport(bool shutdownReads=true, bool shutdownWrites=true, const std::string &errorMsg="")
HTTPCodecFilterChain codec_
HTTPTransaction * findTransaction(HTTPCodec::StreamID streamID)
void onNewTransactionParseError(HTTPCodec::StreamID streamID, const HTTPException &error)
virtual void onIngressError(const HTTPSessionBase &, ProxygenError)
requires And< SemiMovable< VN >... > &&SemiMovable< E > auto error(E e)
Definition: error.h:48
void setCloseReason(ConnectionCloseReason reason)
void handleErrorDirectly(HTTPTransaction *txn, const HTTPException &error)
void invalidStream(HTTPCodec::StreamID stream, ErrorCode code=ErrorCode::_SPDY_INVALID_STREAM)
std::map< HTTPCodec::StreamID, HTTPTransaction > transactions_
Definition: HTTPSession.h:692
void onSessionParseError(const HTTPException &error)
virtual bool isReusable() const =0
static const folly::Optional< StreamID > NoStream
Definition: HTTPCodec.h:51
uint32_t streamID
Definition: SPDYCodec.cpp:131
virtual bool supportsParallelRequests() const =0
virtual void onRequestBegin(const HTTPSessionBase &)
static const folly::Optional< ExAttributes > NoExAttributes
Definition: HTTPCodec.h:66
void proxygen::HTTPSession::onExMessageBegin ( HTTPCodec::StreamID  ,
HTTPCodec::StreamID  ,
bool  ,
HTTPMessage  
)
overrideprotectedvirtual

Called when a new extended message is seen while parsing the ingress.

Parameters
streamThe stream ID
controlStreamThe stream ID of the associated stream, which can never be 0
msgA newly allocated HTTPMessage

Reimplemented from proxygen::HTTPCodec::Callback.

Definition at line 860 of file HTTPSession.cpp.

References createTransaction(), proxygen::ERROR, findTransaction(), getMessagePriority(), proxygen::HTTPSessionBase::infoCallback_, invalidStream(), proxygen::HTTPTransaction::isIngressPaused(), proxygen::HTTPCodec::NoStream, proxygen::HTTPSessionBase::InfoCallback::onRequestBegin(), and proxygen::PROTOCOL_ERROR.

Referenced by getSecurityProtocol().

863  {
864  VLOG(4) << "processing new ExMessage=" << streamID
865  << " on controlStream=" << controlStream << ", " << *this;
866  if (infoCallback_) {
868  }
869  if (controlStream == 0) {
870  LOG(ERROR) << "ExMessage=" << streamID << " should have an active control "
871  << "stream=" << controlStream << ", " << *this;
873  return;
874  }
875 
876  HTTPTransaction* controlTxn = findTransaction(controlStream);
877  if (!controlTxn) {
878  // control stream is broken, or remote sends a bogus stream id
879  LOG(ERROR) << "no control stream=" << controlStream << ", " << *this;
880  return;
881  }
882 
883  http2::PriorityUpdate messagePriority = getMessagePriority(msg);
884  auto txn = createTransaction(streamID,
886  HTTPCodec::ExAttributes(controlStream,
887  unidirectional),
888  messagePriority);
889  if (!txn) {
890  return; // This could happen if the socket is bad.
891  }
892  // control stream may be paused if the upstream is not ready yet
893  if (controlTxn->isIngressPaused()) {
894  txn->pauseIngress();
895  }
896 }
HTTPTransaction * createTransaction(HTTPCodec::StreamID streamID, const folly::Optional< HTTPCodec::StreamID > &assocStreamID, const folly::Optional< HTTPCodec::ExAttributes > &exAttributes, const http2::PriorityUpdate &priority=http2::DefaultPriority)
HTTPTransaction * findTransaction(HTTPCodec::StreamID streamID)
http2::PriorityUpdate getMessagePriority(const HTTPMessage *msg)
void invalidStream(HTTPCodec::StreamID stream, ErrorCode code=ErrorCode::_SPDY_INVALID_STREAM)
static const folly::Optional< StreamID > NoStream
Definition: HTTPCodec.h:51
uint32_t streamID
Definition: SPDYCodec.cpp:131
virtual void onRequestBegin(const HTTPSessionBase &)
void proxygen::HTTPSession::onGoaway ( uint64_t  ,
ErrorCode  ,
std::unique_ptr< folly::IOBuf = nullptr 
)
overrideprotectedvirtual

Called upon receipt of a goaway.

Parameters
lastGoodStreamIDLast successful stream created by the receiver
codeThe code the connection was aborted with
debugDataThe additional debug data for diagnostic purpose
Note
Not all protocols have goaways. SPDY does, but HTTP/1.1 doesn't.

Reimplemented from proxygen::HTTPCodec::Callback.

Definition at line 1199 of file HTTPSession.cpp.

References folly::IOBuf::data(), drain(), errorOnTransactionId(), errorOnTransactionIds(), g(), proxygen::getErrorCodeString(), proxygen::getErrorString(), proxygen::GOAWAY, proxygen::HTTPException::INGRESS_AND_EGRESS, invokeOnAllTransactions(), isUpstream(), proxygen::kErrorStreamUnacknowledged, folly::gen::move, proxygen::NO_ERROR, proxygen::HTTPCodec::NoStream, proxygen::HTTPTransaction::onGoaway(), proxygen::HTTPSessionBase::setCloseReason(), proxygen::Exception::setProxygenError(), streamID, and transactions_.

Referenced by getSecurityProtocol().

1201  {
1202  DestructorGuard g(this);
1203  VLOG(4) << "GOAWAY on " << *this << ", code=" << getErrorCodeString(code);
1204 
1206 
1207  // Drain active transactions and prevent new transactions
1208  drain();
1209 
1210  // We give the less-forceful onGoaway() first so that transactions have
1211  // a chance to do stat tracking before potentially getting a forceful
1212  // onError().
1214 
1215  // Abort transactions which have been initiated but not created
1216  // successfully at the remote end. Upstream transactions are created
1217  // with odd transaction IDs and downstream transactions with even IDs.
1218  vector<HTTPCodec::StreamID> ids;
1219  auto firstStream = HTTPCodec::NoStream;
1220 
1221  for (const auto& txn: transactions_) {
1222  auto streamID = txn.first;
1223  if (((bool)(streamID & 0x01) == isUpstream()) &&
1224  (streamID > lastGoodStreamID)) {
1225  if (firstStream == HTTPCodec::NoStream) {
1226  // transactions_ is a set so it should be sorted by stream id.
1227  // We will defer adding the firstStream to the id list until
1228  // we can determine whether we have a codec error code.
1229  firstStream = streamID;
1230  continue;
1231  }
1232 
1233  ids.push_back(streamID);
1234  }
1235  }
1236 
1237 
1238  if (firstStream != HTTPCodec::NoStream && code != ErrorCode::NO_ERROR) {
1239  // If we get a codec error, we will attempt to blame the first stream
1240  // by delivering a specific error to it and let the rest of the streams
1241  // get a normal unacknowledged stream error.
1243  string debugInfo = (debugData) ?
1244  folly::to<string>(" with debug info: ", (char*)debugData->data()) : "";
1246  folly::to<std::string>(getErrorString(err),
1247  " on transaction id: ", *firstStream,
1248  " with codec error: ", getErrorCodeString(code),
1249  debugInfo));
1250  ex.setProxygenError(err);
1251  errorOnTransactionId(*firstStream, std::move(ex));
1252  } else if (firstStream != HTTPCodec::NoStream) {
1253  ids.push_back(*firstStream);
1254  }
1255 
1257 }
void invokeOnAllTransactions(void(HTTPTransaction::*fn)(Args1...), Args2 &&...args)
Definition: HTTPSession.h:584
void errorOnTransactionId(HTTPCodec::StreamID id, HTTPException ex)
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
bool isUpstream() const
void onGoaway(ErrorCode code)
void setCloseReason(ConnectionCloseReason reason)
void drain() override
const char * getErrorCodeString(ErrorCode error)
Definition: ErrorCode.cpp:18
void errorOnTransactionIds(const std::vector< HTTPCodec::StreamID > &ids, ProxygenError err, const std::string &extraErrorMsg="")
std::map< HTTPCodec::StreamID, HTTPTransaction > transactions_
Definition: HTTPSession.h:692
g_t g(f_t)
static const folly::Optional< StreamID > NoStream
Definition: HTTPCodec.h:51
uint32_t streamID
Definition: SPDYCodec.cpp:131
const char * getErrorString(ProxygenError error)
void proxygen::HTTPSession::onHeadersComplete ( HTTPCodec::StreamID  stream,
std::unique_ptr< HTTPMessage msg 
)
overrideprotectedvirtual

Called when all the headers of an ingress message have been parsed

Parameters
streamThe stream ID
msgThe message
sizeSize of the ingress header

Implements proxygen::HTTPCodec::Callback.

Definition at line 899 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, findTransaction(), proxygen::HTTPTransaction::getControlStream(), proxygen::HTTPSessionBase::infoCallback_, proxygen::HTTPException::INGRESS_AND_EGRESS, invalidStream(), proxygen::HTTPTransaction::isRemoteInitiated(), proxygen::HTTPCodec::isReusable(), folly::gen::move, onError(), proxygen::HTTPSessionBase::InfoCallback::onIngressMessage(), proxygen::REFUSED_STREAM, proxygen::REQ_NOTREUSABLE, wangle::TransportInfo::secure, proxygen::HTTPSessionBase::setCloseReason(), proxygen::HTTPException::setCodecStatusCode(), setupOnHeadersComplete(), wangle::TransportInfo::sslCipher, wangle::TransportInfo::sslVersion, streamID, and proxygen::HTTPSessionBase::transportInfo_.

Referenced by getSecurityProtocol().

900  {
901  // The codec's parser detected the end of an ingress message's
902  // headers.
903  VLOG(4) << "processing ingress headers complete for " << *this <<
904  ", streamID=" << streamID;
905 
906  if (!codec_->isReusable()) {
908  }
909 
910  if (infoCallback_) {
911  infoCallback_->onIngressMessage(*this, *msg.get());
912  }
913  HTTPTransaction* txn = findTransaction(streamID);
914  if (!txn) {
916  return;
917  }
918 
919  const char* sslCipher =
920  transportInfo_.sslCipher ? transportInfo_.sslCipher->c_str() : nullptr;
921  msg->setSecureInfo(transportInfo_.sslVersion, sslCipher);
922  msg->setSecure(transportInfo_.secure);
923 
924  auto controlStreamID = txn->getControlStream();
925  if (controlStreamID) {
926  auto controlTxn = findTransaction(*controlStreamID);
927  if (!controlTxn) {
928  VLOG(2) << "txn=" << streamID << " with a broken controlTxn="
929  << *controlStreamID << " " << *this;
930  HTTPException ex(
932  folly::to<std::string>("broken controlTxn ", *controlStreamID));
933  onError(streamID, ex, true);
934  return;
935  }
936 
937  // Call onExTransaction() only for requests.
938  if (txn->isRemoteInitiated() && !controlTxn->onExTransaction(txn)) {
939  VLOG(2) << "Failed to add exTxn=" << streamID
940  << " to controlTxn=" << *controlStreamID << ", " << *this;
941  HTTPException ex(
943  folly::to<std::string>("Fail to add exTxn ", streamID));
944  ex.setCodecStatusCode(ErrorCode::REFUSED_STREAM);
945  onError(streamID, ex, true);
946  return;
947  }
948  } else {
949  setupOnHeadersComplete(txn, msg.get());
950  }
951 
952  // The txn may have already been aborted by the handler.
953  // Verify that the txn still exists before ingress callbacks.
954  txn = findTransaction(streamID);
955  if (!txn) {
956  return;
957  }
958 
959  if (!txn->getHandler()) {
960  txn->sendAbort();
961  return;
962  }
963 
964  // Tell the Transaction to start processing the message now
965  // that the full ingress headers have arrived.
966  txn->onIngressHeadersComplete(std::move(msg));
967 }
HTTPCodecFilterChain codec_
HTTPTransaction * findTransaction(HTTPCodec::StreamID streamID)
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
virtual void setupOnHeadersComplete(HTTPTransaction *txn, HTTPMessage *msg)=0
virtual void onIngressMessage(const HTTPSessionBase &, const HTTPMessage &)
void setCloseReason(ConnectionCloseReason reason)
void invalidStream(HTTPCodec::StreamID stream, ErrorCode code=ErrorCode::_SPDY_INVALID_STREAM)
std::shared_ptr< std::string > sslCipher
virtual bool isReusable() const =0
uint32_t streamID
Definition: SPDYCodec.cpp:131
void onError(HTTPCodec::StreamID streamID, const HTTPException &error, bool newTxn) override
wangle::TransportInfo transportInfo_
virtual void proxygen::HTTPSession::onHeadersSent ( const HTTPMessage ,
bool   
)
inlineprotectedvirtual
void proxygen::HTTPSession::onLastByteEvent ( HTTPTransaction txn,
uint64_t  offset,
bool  eomTracked 
)
overrideprivatevirtualnoexcept

Implements proxygen::ByteEventTracker::Callback.

Definition at line 2962 of file HTTPSession.cpp.

References byteEventTracker_, and sock_.

Referenced by isConnWindowFull().

2963  {
2964  if (!sock_->isEorTrackingEnabled() || !eomTracked) {
2965  return;
2966  }
2967 
2968  if (eomOffset != sock_->getAppBytesWritten()) {
2969  VLOG(2) << "tracking ack to last app byte " << eomOffset
2970  << " while " << sock_->getAppBytesWritten()
2971  << " app bytes have already been written";
2972  return;
2973  }
2974 
2975  VLOG(5) << "tracking raw last byte " << sock_->getRawBytesWritten()
2976  << " while the app last byte is " << eomOffset;
2977 
2978  byteEventTracker_->addAckByteEvent(sock_->getRawBytesWritten(), txn);
2979 }
folly::AsyncTransportWrapper::UniquePtr sock_
Definition: HTTPSession.h:697
std::shared_ptr< ByteEventTracker > byteEventTracker_
Definition: HTTPSession.h:966
void proxygen::HTTPSession::onMessageBegin ( HTTPCodec::StreamID  stream,
HTTPMessage msg 
)
overrideprotectedvirtual

Called when a new message is seen while parsing the ingress

Parameters
streamThe stream ID
msgA newly allocated HTTPMessage

Implements proxygen::HTTPCodec::Callback.

Definition at line 758 of file HTTPSession.cpp.

References byteEventTracker_, proxygen::HTTPSessionBase::codec_, createTransaction(), findTransaction(), getMessagePriority(), getPipelineStreamCount(), proxygen::HTTPSessionBase::infoCallback_, proxygen::HTTPException::INGRESS_AND_EGRESS, isDownstream(), proxygen::HTTPTransaction::isPushed(), liveTransactions_, proxygen::HTTPCodec::NoExAttributes, proxygen::HTTPCodec::NoStream, proxygen::HTTPTransaction::onError(), proxygen::HTTPSessionBase::InfoCallback::onRequestBegin(), readsPaused(), readsUnpaused(), proxygen::HTTPException::setCodecStatusCode(), proxygen::STREAM_CLOSED, proxygen::HTTPCodec::supportsParallelRequests(), and transactions_.

Referenced by getSecurityProtocol().

758  {
759  VLOG(4) << "processing new msg streamID=" << streamID << " " << *this;
760  if (infoCallback_) {
762  }
763 
764  HTTPTransaction* txn = findTransaction(streamID);
765  if (txn) {
766  if (isDownstream() && txn->isPushed()) {
767  // Push streams are unidirectional (half-closed). If the downstream
768  // attempts to send ingress, abort with STREAM_CLOSED error.
770  "Downstream attempts to send ingress, abort.");
771  ex.setCodecStatusCode(ErrorCode::STREAM_CLOSED);
772  txn->onError(ex);
773  }
774  return; // If this transaction is already registered, no need to add it now
775  }
776 
777  http2::PriorityUpdate messagePriority = getMessagePriority(msg);
779  HTTPCodec::NoExAttributes, messagePriority);
780  if (!txn) {
781  return; // This could happen if the socket is bad.
782  }
783 
785  // The previous transaction hasn't completed yet. Pause reads until
786  // it completes; this requires pausing both transactions.
787 
788  // HTTP/1.1 pipeline is detected, and which is incompactible with
789  // ByteEventTracker. Drain all the ByteEvents
790  CHECK(byteEventTracker_);
791  byteEventTracker_->drainByteEvents();
792 
793  // drainByteEvents() may detach txn(s). Don't pause read if one txn left
794  if (getPipelineStreamCount() < 2) {
795  DCHECK(readsUnpaused());
796  return;
797  }
798 
799  // There must be at least two transactions (we just checked). The previous
800  // txns haven't completed yet. Pause reads until they complete
801  DCHECK_GE(transactions_.size(), 2);
802  for (auto it = ++transactions_.rbegin(); it != transactions_.rend(); ++it) {
803  DCHECK(it->second.isIngressEOMSeen());
804  it->second.pauseIngress();
805  }
806  transactions_.rbegin()->second.pauseIngress();
807  DCHECK_EQ(liveTransactions_, 0);
808  DCHECK(readsPaused());
809  }
810 }
size_t getPipelineStreamCount() const
Definition: HTTPSession.h:835
bool readsUnpaused() const
Definition: HTTPSession.h:626
HTTPTransaction * createTransaction(HTTPCodec::StreamID streamID, const folly::Optional< HTTPCodec::StreamID > &assocStreamID, const folly::Optional< HTTPCodec::ExAttributes > &exAttributes, const http2::PriorityUpdate &priority=http2::DefaultPriority)
HTTPCodecFilterChain codec_
HTTPTransaction * findTransaction(HTTPCodec::StreamID streamID)
bool readsPaused() const
Definition: HTTPSession.h:630
http2::PriorityUpdate getMessagePriority(const HTTPMessage *msg)
uint32_t liveTransactions_
Definition: HTTPSession.h:695
std::map< HTTPCodec::StreamID, HTTPTransaction > transactions_
Definition: HTTPSession.h:692
std::shared_ptr< ByteEventTracker > byteEventTracker_
Definition: HTTPSession.h:966
static const folly::Optional< StreamID > NoStream
Definition: HTTPCodec.h:51
uint32_t streamID
Definition: SPDYCodec.cpp:131
bool isDownstream() const
virtual bool supportsParallelRequests() const =0
static const folly::Optional< ExAttributes > NoExAttributes
Definition: HTTPCodec.h:66
virtual void onRequestBegin(const HTTPSessionBase &)
void proxygen::HTTPSession::onMessageComplete ( HTTPCodec::StreamID  stream,
bool  upgrade 
)
overrideprotectedvirtual

Called at end of a message (including body and trailers, if applicable)

Parameters
streamThe stream ID
upgradeWhether the connection has been upgraded to another protocol.

Implements proxygen::HTTPCodec::Callback.

Definition at line 1041 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, decrementTransactionCount(), proxygen::HTTPTransaction::extraResponseExpected(), findTransaction(), ingressUpgraded_, invalidStream(), proxygen::HTTPTransaction::isDownstream(), proxygen::HTTPCodec::isReusable(), proxygen::HTTPTransaction::onIngressEOM(), proxygen::HTTPTransaction::onIngressUpgrade(), shutdownTransport(), streamID, proxygen::HTTPCodec::supportsParallelRequests(), and proxygen::TCP.

Referenced by getSecurityProtocol().

1042  {
1043  DestructorGuard dg(this);
1044  // The codec's parser detected the end of the ingress message for
1045  // this transaction.
1046  VLOG(4) << "processing ingress message complete for " << *this <<
1047  ", streamID=" << streamID;
1048  HTTPTransaction* txn = findTransaction(streamID);
1049  if (!txn) {
1051  return;
1052  }
1053 
1054  if (upgrade) {
1055  /* Send the upgrade callback to the transaction and the handler.
1056  * Currently we support upgrades for only HTTP sessions and not SPDY
1057  * sessions.
1058  */
1059  ingressUpgraded_ = true;
1060  txn->onIngressUpgrade(UpgradeProtocol::TCP);
1061  return;
1062  }
1063 
1064  // txnIngressFinished = !1xx response
1065  const bool txnIngressFinished =
1066  txn->isDownstream() || !txn->extraResponseExpected();
1067  if (txnIngressFinished) {
1068  decrementTransactionCount(txn, true, false);
1069  }
1070  txn->onIngressEOM();
1071 
1072  // The codec knows, based on the semantics of whatever protocol it
1073  // supports, whether it's valid for any more ingress messages to arrive
1074  // after this one. For example, an HTTP/1.1 request containing
1075  // "Connection: close" indicates the end of the ingress, whereas a
1076  // SPDY session generally can handle more messages at any time.
1077  //
1078  // If the connection is not reusable, we close the read side of it
1079  // but not the write side. There are two reasons why more writes
1080  // may occur after this point:
1081  // * If there are previous writes buffered up in the pendingWrites_
1082  // queue, we need to attempt to complete them.
1083  // * The Handler associated with the transaction may want to
1084  // produce more egress data when the ingress message is fully
1085  // complete. (As a common example, an application that handles
1086  // form POSTs may not be able to even start generating a response
1087  // until it has received the full request body.)
1088  //
1089  // There may be additional checks that need to be performed that are
1090  // specific to requests or responses, so we call the subclass too.
1091  if (!codec_->isReusable() &&
1092  txnIngressFinished &&
1094  VLOG(4) << *this << " cannot reuse ingress";
1095  shutdownTransport(true, false);
1096  }
1097 }
void shutdownTransport(bool shutdownReads=true, bool shutdownWrites=true, const std::string &errorMsg="")
HTTPCodecFilterChain codec_
HTTPTransaction * findTransaction(HTTPCodec::StreamID streamID)
void decrementTransactionCount(HTTPTransaction *txn, bool ingressEOM, bool egressEOM)
void invalidStream(HTTPCodec::StreamID stream, ErrorCode code=ErrorCode::_SPDY_INVALID_STREAM)
virtual bool isReusable() const =0
uint32_t streamID
Definition: SPDYCodec.cpp:131
virtual bool supportsParallelRequests() const =0
bool proxygen::HTTPSession::onNativeProtocolUpgradeImpl ( HTTPCodec::StreamID  txn,
std::unique_ptr< HTTPCodec codec,
const std::string protocolString 
)
protected

Definition at line 1413 of file HTTPSession.cpp.

References wangle::TransportInfo::appProtocol, proxygen::HTTPSessionBase::codec_, connFlowControl_, proxygen::HTTPCodec::createStream(), findTransaction(), getCodecSendWindowSize(), proxygen::HTTPCodec::getDefaultWindowSize(), proxygen::HTTPCodec::getEgressSettings(), proxygen::INITIAL_WINDOW_SIZE, initialReceiveWindow_, maxConcurrentIncomingStreams_, maxConcurrentOutgoingStreamsRemote_, folly::gen::move, proxygen::HTTPSessionBase::onCodecChanged(), receiveSessionWindowSize_, receiveStreamWindowSize_, proxygen::HTTPTransaction::reset(), scheduleWrite(), wangle::TransportInfo::secure, sendSettings(), proxygen::FilterChain< T1, T2, FilterType, set_callback, TakeOwnership >::setDestination(), proxygen::FlowControlFilter::setReceiveWindowSize(), proxygen::HTTPSettings::setSetting(), settings, setupCodec(), sock_, proxygen::HTTPCodec::supportsParallelRequests(), proxygen::HTTPCodec::supportsStreamFlowControl(), proxygen::HTTPSessionBase::transportInfo_, and writeBuf_.

Referenced by onHeadersSent(), proxygen::HTTPDownstreamSession::onNativeProtocolUpgrade(), and proxygen::HTTPUpstreamSession::onNativeProtocolUpgrade().

1415  {
1416  CHECK_EQ(streamID, 1);
1417  HTTPTransaction* txn = findTransaction(streamID);
1418  CHECK(txn);
1419  // only HTTP1xCodec calls onNativeProtocolUpgrade
1420  CHECK(!codec_->supportsParallelRequests());
1421 
1422  // Reset to defaults
1425 
1426  // overwrite destination, delay current codec deletion until the end
1427  // of the event loop
1428  auto oldCodec = codec_.setDestination(std::move(codec));
1429  sock_->getEventBase()->runInLoop([oldCodec = std::move(oldCodec)] () {});
1430 
1431  onCodecChanged();
1432 
1433  setupCodec();
1434 
1435  // txn will be streamID=1, have to make a placeholder
1436  (void)codec_->createStream();
1437 
1438  // This can happen if flow control was not explicitly set, and it got the
1439  // HTTP1xCodec defaults. Reset to the new codec default
1444  }
1445 
1446  // trigger settings frame that would have gone out in startNow()
1447  HTTPSettings* settings = codec_->getEgressSettings();
1448  if (settings) {
1451  }
1452  sendSettings();
1453  if (connFlowControl_) {
1456  scheduleWrite();
1457  }
1458 
1459  // Convert the transaction that contained the Upgrade header
1460  txn->reset(codec_->supportsStreamFlowControl(),
1464 
1465  if (!transportInfo_.secure &&
1467  transportInfo_.appProtocol->empty())) {
1468  transportInfo_.appProtocol = std::make_shared<string>(
1469  protocolString);
1470  }
1471 
1472  return true;
1473 }
size_t sendSettings() override
virtual StreamID createStream()=0
virtual HTTPSettings * getEgressSettings()
Definition: HTTPCodec.h:653
HTTPCodecFilterChain codec_
HTTPTransaction * findTransaction(HTTPCodec::StreamID streamID)
size_t receiveSessionWindowSize_
Definition: HTTPSession.h:976
FlowControlFilter * connFlowControl_
Definition: HTTPSession.h:913
void setReceiveWindowSize(folly::IOBufQueue &writeBuf, uint32_t capacity)
size_t getCodecSendWindowSize() const
size_t receiveStreamWindowSize_
Definition: HTTPSession.h:975
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
folly::AsyncTransportWrapper::UniquePtr sock_
Definition: HTTPSession.h:697
static http_parser_settings settings
Definition: test.c:1529
uint32_t maxConcurrentIncomingStreams_
Definition: HTTPSession.h:928
uint32_t maxConcurrentOutgoingStreamsRemote_
Definition: HTTPSession.h:922
virtual bool supportsStreamFlowControl() const
Definition: HTTPCodec.h:367
virtual uint32_t getDefaultWindowSize() const
Definition: HTTPCodec.h:680
std::unique_ptr< T1 > setDestination(std::unique_ptr< T1 > destination)
Definition: FilterChain.h:260
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
std::shared_ptr< std::string > appProtocol
uint32_t streamID
Definition: SPDYCodec.cpp:131
virtual bool supportsParallelRequests() const =0
wangle::TransportInfo transportInfo_
void setSetting(SettingsId id, SettingsValue val)
void proxygen::HTTPSession::onNewTransactionParseError ( HTTPCodec::StreamID  streamID,
const HTTPException error 
)
protected

Send a transaction abort and leave the session and transport intact.

Definition at line 2742 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, proxygen::HTTPCodec::generateRstStream(), proxygen::HTTPException::getCodecStatusCode(), proxygen::HTTPException::hasCodecStatusCode(), proxygen::HTTPCodec::isReusable(), scheduleWrite(), proxygen::SESSION_PARSE_ERROR, proxygen::HTTPSessionBase::setCloseReason(), and writeBuf_.

Referenced by onError(), and sessionByteOffset().

2743  {
2744  VLOG(4) << *this << " parse error with new transaction";
2745  if (error.hasCodecStatusCode()) {
2746  codec_->generateRstStream(writeBuf_, streamID, error.getCodecStatusCode());
2747  scheduleWrite();
2748  }
2749  if (!codec_->isReusable()) {
2750  // HTTP 1x codec does not support per stream abort so this will
2751  // render the codec not reusable
2753  }
2754 }
HTTPCodecFilterChain codec_
requires And< SemiMovable< VN >... > &&SemiMovable< E > auto error(E e)
Definition: error.h:48
virtual size_t generateRstStream(folly::IOBufQueue &writeBuf, StreamID stream, ErrorCode code)=0
void setCloseReason(ConnectionCloseReason reason)
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
virtual bool isReusable() const =0
uint32_t streamID
Definition: SPDYCodec.cpp:131
void proxygen::HTTPSession::onPingReply ( uint64_t  )
overrideprotectedvirtual

Called upon receipt of a ping reply

Parameters
uniqueIDUnique identifier for the ping
Note
Not all protocols have pings. SPDY does, but HTTP/1.1 doesn't.

Reimplemented from proxygen::HTTPCodec::Callback.

Definition at line 1278 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::infoCallback_, and proxygen::HTTPSessionBase::InfoCallback::onPingReplyReceived().

Referenced by getSecurityProtocol().

1278  {
1279  VLOG(4) << *this << " got ping reply with id=" << uniqueID;
1280  if (infoCallback_) {
1282  }
1283 }
void proxygen::HTTPSession::onPingReplyLatency ( int64_t  latency)
overrideprivatevirtualnoexcept

Implements proxygen::ByteEventTracker::Callback.

Definition at line 2924 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::infoCallback_, and proxygen::HTTPSessionBase::InfoCallback::onPingReplySent().

Referenced by isConnWindowFull().

2924  {
2925  if (infoCallback_ && latency >= 0) {
2926  infoCallback_->onPingReplySent(latency);
2927  }
2928 }
void proxygen::HTTPSession::onPingRequest ( uint64_t  )
overrideprotectedvirtual

Called upon receipt of a ping request

Parameters
uniqueIDUnique identifier for the ping
Note
Not all protocols have pings. SPDY does, but HTTP/1.1 doesn't.

Reimplemented from proxygen::HTTPCodec::Callback.

Definition at line 1259 of file HTTPSession.cpp.

References folly::IOBufQueue::append(), byteEventTracker_, bytesScheduled_, folly::IOBufQueue::cacheChainLength(), folly::IOBufQueue::chainLength(), proxygen::HTTPSessionBase::codec_, proxygen::HTTPCodec::generatePingReply(), proxygen::getCurrentTime(), folly::IOBufQueue::move(), scheduleWrite(), and writeBuf_.

Referenced by getSecurityProtocol().

1259  {
1260  VLOG(4) << *this << " got ping request with id=" << uniqueID;
1261 
1262  TimePoint timestamp = getCurrentTime();
1263 
1264  // Insert the ping reply to the head of writeBuf_
1266  codec_->generatePingReply(pingBuf, uniqueID);
1267  size_t pingSize = pingBuf.chainLength();
1268  pingBuf.append(writeBuf_.move());
1269  writeBuf_.append(pingBuf.move());
1270 
1271  if (byteEventTracker_) {
1272  byteEventTracker_->addPingByteEvent(pingSize, timestamp, bytesScheduled_);
1273  }
1274 
1275  scheduleWrite();
1276 }
virtual size_t generatePingReply(folly::IOBufQueue &, uint64_t)
Definition: HTTPCodec.h:584
void append(std::unique_ptr< folly::IOBuf > &&buf, bool pack=false)
Definition: IOBufQueue.cpp:143
HTTPCodecFilterChain codec_
std::unique_ptr< folly::IOBuf > move()
Definition: IOBufQueue.h:459
static Options cacheChainLength()
Definition: IOBufQueue.h:83
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
std::shared_ptr< ByteEventTracker > byteEventTracker_
Definition: HTTPSession.h:966
std::chrono::time_point< ClockType > getCurrentTime()
Definition: Time.h:41
StatsClock::time_point TimePoint
void proxygen::HTTPSession::onPriority ( HTTPCodec::StreamID  ,
const HTTPMessage::HTTPPriority  
)
overrideprotectedvirtual

Called upon receipt of a priority frame, for protocols that support dynamic priority

Reimplemented from proxygen::HTTPCodec::Callback.

Definition at line 1330 of file HTTPSession.cpp.

References proxygen::HTTP2PriorityQueue::addOrUpdatePriorityNode(), findTransaction(), getHTTP2PrioritiesEnabled(), and txnEgressQueue_.

Referenced by getSecurityProtocol().

1331  {
1332  if (!getHTTP2PrioritiesEnabled()) {
1333  return;
1334  }
1335  http2::PriorityUpdate h2Pri{std::get<0>(pri), std::get<1>(pri),
1336  std::get<2>(pri)};
1337  HTTPTransaction* txn = findTransaction(streamID);
1338  if (txn) {
1339  // existing txn, change pri
1340  txn->onPriorityUpdate(h2Pri);
1341  } else {
1342  // virtual node
1344  }
1345 }
HTTPTransaction * findTransaction(HTTPCodec::StreamID streamID)
HTTP2PriorityQueue txnEgressQueue_
Definition: HTTPSession.h:690
bool getHTTP2PrioritiesEnabled() const override
Definition: HTTPSession.h:114
void addOrUpdatePriorityNode(HTTPCodec::StreamID id, http2::PriorityUpdate pri)
uint32_t streamID
Definition: SPDYCodec.cpp:131
void proxygen::HTTPSession::onPushMessageBegin ( HTTPCodec::StreamID  ,
HTTPCodec::StreamID  ,
HTTPMessage  
)
overrideprotectedvirtual

Called when a new push message is seen while parsing the ingress.

Parameters
streamThe stream ID
assocStreamThe stream ID of the associated stream, which can never be 0
msgA newly allocated HTTPMessage

Reimplemented from proxygen::HTTPCodec::Callback.

Definition at line 813 of file HTTPSession.cpp.

References createTransaction(), findTransaction(), getMessagePriority(), proxygen::HTTPSessionBase::infoCallback_, proxygen::HTTPException::INGRESS_AND_EGRESS, invalidStream(), isDownstream(), proxygen::HTTPTransaction::isIngressEOMSeen(), proxygen::HTTPCodec::NoExAttributes, onError(), proxygen::HTTPTransaction::onPushedTransaction(), proxygen::HTTPSessionBase::InfoCallback::onRequestBegin(), proxygen::PROTOCOL_ERROR, proxygen::REFUSED_STREAM, and proxygen::HTTPException::setCodecStatusCode().

Referenced by getSecurityProtocol().

815  {
816  VLOG(4) << "processing new push promise streamID=" << streamID
817  << " on assocStreamID=" << assocStreamID << " " << *this;
818  if (infoCallback_) {
820  }
821  if (assocStreamID == 0) {
822  VLOG(2) << "push promise " << streamID << " should be associated with "
823  << "an active stream=" << assocStreamID << " " << *this;
825  return;
826  }
827 
828  if (isDownstream()) {
829  VLOG(2) << "push promise cannot be sent to upstream " << *this;
831  return;
832  }
833 
834  HTTPTransaction* assocTxn = findTransaction(assocStreamID);
835  if (!assocTxn || assocTxn->isIngressEOMSeen()) {
836  VLOG(2) << "cannot find the assocTxn=" << assocTxn
837  << ", or assoc stream is already closed by upstream" << *this;
839  return;
840  }
841 
842  http2::PriorityUpdate messagePriority = getMessagePriority(msg);
843  auto txn = createTransaction(streamID, assocStreamID,
844  HTTPCodec::NoExAttributes, messagePriority);
845  if (!txn) {
846  return; // This could happen if the socket is bad.
847  }
848 
849  if (!assocTxn->onPushedTransaction(txn)) {
850  VLOG(1) << "Failed to add pushed txn " << streamID
851  << " to assoc txn " << assocStreamID << " on " << *this;
853  folly::to<std::string>("Failed to add pushed transaction ", streamID));
854  ex.setCodecStatusCode(ErrorCode::REFUSED_STREAM);
855  onError(streamID, ex, true);
856  }
857 }
HTTPTransaction * createTransaction(HTTPCodec::StreamID streamID, const folly::Optional< HTTPCodec::StreamID > &assocStreamID, const folly::Optional< HTTPCodec::ExAttributes > &exAttributes, const http2::PriorityUpdate &priority=http2::DefaultPriority)
HTTPTransaction * findTransaction(HTTPCodec::StreamID streamID)
http2::PriorityUpdate getMessagePriority(const HTTPMessage *msg)
void invalidStream(HTTPCodec::StreamID stream, ErrorCode code=ErrorCode::_SPDY_INVALID_STREAM)
uint32_t streamID
Definition: SPDYCodec.cpp:131
bool isDownstream() const
void onError(HTTPCodec::StreamID streamID, const HTTPException &error, bool newTxn) override
static const folly::Optional< ExAttributes > NoExAttributes
Definition: HTTPCodec.h:66
virtual void onRequestBegin(const HTTPSessionBase &)
void proxygen::HTTPSession::onReplaySafe ( )
overrideprivatevirtualnoexcept

Callback from the transport to this HTTPSession to signal when the transport has become replay safe.

Implements folly::AsyncTransport::ReplaySafetyCallback.

Definition at line 2948 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::infoCallback_, proxygen::HTTPSessionBase::InfoCallback::onFullHandshakeCompletion(), sock_, and waitingForReplaySafety_.

Referenced by needToBlockForReplaySafety().

2948  {
2949  CHECK(sock_);
2950  sock_->setReplaySafetyCallback(nullptr);
2951 
2952  if (infoCallback_) {
2954  }
2955 
2956  for (auto callback : waitingForReplaySafety_) {
2957  callback->onReplaySafe();
2958  }
2959  waitingForReplaySafety_.clear();
2960 }
folly::AsyncTransportWrapper::UniquePtr sock_
Definition: HTTPSession.h:697
virtual void onFullHandshakeCompletion(const HTTPSessionBase &)
std::list< ReplaySafetyCallback * > waitingForReplaySafety_
Definition: HTTPSession.h:846
void proxygen::HTTPSession::onSessionParseError ( const HTTPException error)
protected

Send a session layer abort and shutdown the transport for reads and writes.

Definition at line 2726 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, folly::IOBuf::copyBuffer(), proxygen::HTTPCodec::generateGoaway(), proxygen::HTTPException::getCodecStatusCode(), proxygen::HTTPCodec::getLastIncomingStreamID(), proxygen::HTTPCodec::getProtocol(), proxygen::HTTPException::hasCodecStatusCode(), proxygen::isHTTP2CodecProtocol(), folly::gen::move, scheduleWrite(), proxygen::SESSION_PARSE_ERROR, proxygen::HTTPSessionBase::setCloseReason(), shutdownTransport(), proxygen::Exception::what(), and writeBuf_.

Referenced by onError(), and sessionByteOffset().

2726  {
2727  VLOG(4) << *this << " session layer parse error. Terminate the session.";
2728  if (error.hasCodecStatusCode()) {
2729  std::unique_ptr<folly::IOBuf> errorMsg =
2733  error.getCodecStatusCode(),
2735  std::move(errorMsg) : nullptr);
2736  scheduleWrite();
2737  }
2739  shutdownTransport(true, true);
2740 }
void shutdownTransport(bool shutdownReads=true, bool shutdownWrites=true, const std::string &errorMsg="")
HTTPCodecFilterChain codec_
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
virtual CodecProtocol getProtocol() const =0
requires And< SemiMovable< VN >... > &&SemiMovable< E > auto error(E e)
Definition: error.h:48
#define nullptr
Definition: http_parser.c:41
void setCloseReason(ConnectionCloseReason reason)
virtual StreamID getLastIncomingStreamID() const
Definition: HTTPCodec.h:675
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
bool isHTTP2CodecProtocol(CodecProtocol protocol)
virtual size_t generateGoaway(folly::IOBufQueue &writeBuf, StreamID lastStream, ErrorCode code, std::unique_ptr< folly::IOBuf > debugData=nullptr)=0
static std::unique_ptr< IOBuf > copyBuffer(const void *buf, std::size_t size, std::size_t headroom=0, std::size_t minTailroom=0)
Definition: IOBuf.h:1587
void proxygen::HTTPSession::onSetMaxInitiatedStreams ( uint32_t  maxTxns)
private

Definition at line 1481 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::infoCallback_, maxConcurrentOutgoingStreamsRemote_, proxygen::HTTPSessionBase::InfoCallback::onSettingsOutgoingStreamsFull(), proxygen::HTTPSessionBase::InfoCallback::onSettingsOutgoingStreamsNotFull(), and proxygen::HTTPSessionBase::supportsMoreTransactions().

Referenced by getMaxConcurrentOutgoingStreamsRemote(), and onSettings().

1481  {
1482  VLOG(4) << *this << " got new maximum number of concurrent txns "
1483  << "we can initiate: " << maxTxns;
1484  const bool didSupport = supportsMoreTransactions();
1486  if (infoCallback_ && didSupport != supportsMoreTransactions()) {
1487  if (didSupport) {
1489  } else {
1491  }
1492  }
1493 }
virtual void onSettingsOutgoingStreamsNotFull(const HTTPSessionBase &)
uint32_t maxConcurrentOutgoingStreamsRemote_
Definition: HTTPSession.h:922
virtual void onSettingsOutgoingStreamsFull(const HTTPSessionBase &)
bool supportsMoreTransactions() const
void proxygen::HTTPSession::onSetSendWindow ( uint32_t  windowSize)
private

Definition at line 1475 of file HTTPSession.cpp.

References invokeOnAllTransactions(), and proxygen::HTTPTransaction::onIngressSetSendWindow().

Referenced by getMaxConcurrentOutgoingStreamsRemote(), and onSettings().

1475  {
1476  VLOG(4) << *this << " got send window size adjustment. new=" << windowSize;
1478  windowSize);
1479 }
void invokeOnAllTransactions(void(HTTPTransaction::*fn)(Args1...), Args2 &&...args)
Definition: HTTPSession.h:584
void onIngressSetSendWindow(uint32_t newWindowSize)
void proxygen::HTTPSession::onSettings ( const SettingsList )
overrideprotectedvirtual

Called upon receipt of a settings frame, for protocols that support settings.

Parameters
settingsa list of settings that were sent in the settings frame

Reimplemented from proxygen::HTTPCodec::Callback.

Definition at line 1302 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, g(), proxygen::HTTPCodec::generateSettingsAck(), proxygen::HTTPSessionBase::infoCallback_, proxygen::INITIAL_WINDOW_SIZE, proxygen::MAX_CONCURRENT_STREAMS, onSetMaxInitiatedStreams(), onSetSendWindow(), proxygen::HTTPSessionBase::InfoCallback::onSettings(), scheduleWrite(), proxygen::SETTINGS_HTTP_CERT_AUTH, verifyCertAuthSetting(), and writeBuf_.

Referenced by getSecurityProtocol().

1302  {
1303  DestructorGuard g(this);
1304  for (auto& setting : settings) {
1305  if (setting.id == SettingsId::INITIAL_WINDOW_SIZE) {
1306  onSetSendWindow(setting.value);
1307  } else if (setting.id == SettingsId::MAX_CONCURRENT_STREAMS) {
1308  onSetMaxInitiatedStreams(setting.value);
1309  } else if (setting.id == SettingsId::SETTINGS_HTTP_CERT_AUTH) {
1310  if (!(verifyCertAuthSetting(setting.value))) {
1311  return;
1312  }
1313  }
1314  }
1315  if (codec_->generateSettingsAck(writeBuf_) > 0) {
1316  scheduleWrite();
1317  }
1318  if (infoCallback_) {
1319  infoCallback_->onSettings(*this, settings);
1320  }
1321 }
HTTPCodecFilterChain codec_
static http_parser_settings settings
Definition: test.c:1529
void onSetSendWindow(uint32_t windowSize)
void onSetMaxInitiatedStreams(uint32_t maxTxns)
virtual size_t generateSettingsAck(folly::IOBufQueue &)
Definition: HTTPCodec.h:600
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
bool verifyCertAuthSetting(uint32_t value)
g_t g(f_t)
virtual void onSettings(const HTTPSessionBase &, const SettingsList &)
void proxygen::HTTPSession::onSettingsAck ( )
overrideprotectedvirtual

Called upon receipt of a settings frame with ACK set, for protocols that support settings ack.

Reimplemented from proxygen::HTTPCodec::Callback.

Definition at line 1323 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::infoCallback_, and proxygen::HTTPSessionBase::InfoCallback::onSettingsAck().

Referenced by getSecurityProtocol().

1323  {
1324  VLOG(4) << *this << " received settings ack";
1325  if (infoCallback_) {
1326  infoCallback_->onSettingsAck(*this);
1327  }
1328 }
virtual void onSettingsAck(const HTTPSessionBase &)
void proxygen::HTTPSession::onTrailersComplete ( HTTPCodec::StreamID  stream,
std::unique_ptr< HTTPHeaders trailers 
)
overrideprotectedvirtual

Called when all the trailers of an ingress message have been parsed, but only if the number of trailers is nonzero.

Parameters
streamThe stream ID
trailersThe message trailers

Implements proxygen::HTTPCodec::Callback.

Definition at line 1030 of file HTTPSession.cpp.

References findTransaction(), invalidStream(), folly::gen::move, and proxygen::HTTPTransaction::onIngressTrailers().

Referenced by getSecurityProtocol().

1031  {
1032  HTTPTransaction* txn = findTransaction(streamID);
1033  if (!txn) {
1035  return;
1036  }
1037  txn->onIngressTrailers(std::move(trailers));
1038 }
HTTPTransaction * findTransaction(HTTPCodec::StreamID streamID)
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
void invalidStream(HTTPCodec::StreamID stream, ErrorCode code=ErrorCode::_SPDY_INVALID_STREAM)
uint32_t streamID
Definition: SPDYCodec.cpp:131
void proxygen::HTTPSession::onWindowUpdate ( HTTPCodec::StreamID  ,
uint32_t   
)
overrideprotectedvirtual

Called upon receipt of a window update, for protocols that support flow control. For instance spdy/3 and higher.

Reimplemented from proxygen::HTTPCodec::Callback.

Definition at line 1285 of file HTTPSession.cpp.

References findTransaction(), and proxygen::HTTPTransaction::onIngressWindowUpdate().

Referenced by getSecurityProtocol().

1286  {
1287  VLOG(4) << *this << " got window update on streamID=" << streamID << " for "
1288  << amount << " bytes.";
1289  HTTPTransaction* txn = findTransaction(streamID);
1290  if (!txn) {
1291  // We MUST be using SPDY/3+ if we got WINDOW_UPDATE. The spec says that -
1292  //
1293  // A sender should ignore all the WINDOW_UPDATE frames associated with the
1294  // stream after it send the last frame for the stream.
1295  //
1296  // TODO: Only ignore if this is from some past transaction
1297  return;
1298  }
1299  txn->onIngressWindowUpdate(amount);
1300 }
HTTPTransaction * findTransaction(HTTPCodec::StreamID streamID)
uint32_t streamID
Definition: SPDYCodec.cpp:131
void proxygen::HTTPSession::onWriteCompleted ( )
protected

Check whether to shut down the transport after a write completes.

Definition at line 2708 of file HTTPSession.cpp.

References numActiveWrites_, pendingWrites_, shutdownTransport(), and writesDraining_.

Referenced by onWriteSuccess(), and sessionByteOffset().

2708  {
2709  if (!writesDraining_) {
2710  return;
2711  }
2712 
2713  if (numActiveWrites_) {
2714  return;
2715  }
2716 
2717  // Don't shutdown if there might be more writes
2718  if (!pendingWrites_.empty()) {
2719  return;
2720  }
2721 
2722  // All finished draining writes, so shut down the egress
2723  shutdownTransport(false, true);
2724 }
void shutdownTransport(bool shutdownReads=true, bool shutdownWrites=true, const std::string &errorMsg="")
WriteSegmentList pendingWrites_
Definition: HTTPSession.h:908
void proxygen::HTTPSession::onWriteError ( size_t  bytesWritten,
const folly::AsyncSocketException ex 
)
protected

Invoked by WriteSegment on write failure.

Definition at line 2690 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::infoCallback_, proxygen::IO_WRITE_ERROR, proxygen::kErrorWrite, proxygen::HTTPSessionBase::InfoCallback::onWrite(), proxygen::HTTPSessionBase::setCloseReason(), shutdownTransportWithReset(), folly::SSL_ERROR, wangle::TransportInfo::sslError, and proxygen::HTTPSessionBase::transportInfo_.

Referenced by sessionByteOffset(), and proxygen::HTTPSession::WriteSegment::writeErr().

2691  {
2692  VLOG(4) << *this << " write error: " << ex.what();
2693  if (infoCallback_) {
2694  infoCallback_->onWrite(*this, bytesWritten);
2695  }
2696 
2697  auto sslEx = dynamic_cast<const folly::SSLException*>(&ex);
2698  // Save the SSL error, if there was one. It will be recorded later
2699  if (sslEx && sslEx->getSSLError() == folly::SSLError::SSL_ERROR) {
2700  transportInfo_.sslError = ex.what();
2701  }
2702 
2705 }
virtual void onWrite(const HTTPSessionBase &, size_t)
void setCloseReason(ConnectionCloseReason reason)
void shutdownTransportWithReset(ProxygenError errorCode, const std::string &errorMsg="")
wangle::TransportInfo transportInfo_
void proxygen::HTTPSession::onWriteSuccess ( uint64_t  bytesWritten)
protected

Invoked by WriteSegment on completion of a write.

Definition at line 2631 of file HTTPSession.cpp.

References byteEventTracker_, bytesWritten_, folly::HHWheelTimer::Callback::cancelTimeout(), proxygen::HTTPSessionBase::codec_, egressBytesLimit_, hasMoreWrites(), proxygen::HTTPSessionBase::infoCallback_, inLoopCallback_, proxygen::HTTPCodec::isReusable(), folly::HHWheelTimer::Callback::isScheduled(), numActiveWrites_, proxygen::HTTPSessionBase::InfoCallback::onWrite(), onWriteCompleted(), pendingWrites_, readsShutdown(), runLoopCallback(), proxygen::WheelTimerInstance::scheduleTimeout(), proxygen::HTTPSessionBase::setCloseReason(), shutdownTransport(), timeout_, wangle::TransportInfo::totalBytes, transactions_, proxygen::HTTPSessionBase::transportInfo_, proxygen::UNKNOWN, updateWriteBufSize(), updateWriteCount(), and writeTimeout_.

Referenced by sessionByteOffset(), and proxygen::HTTPSession::WriteSegment::writeSuccess().

2631  {
2632  DestructorGuard dg(this);
2633  bytesWritten_ += bytesWritten;
2634  transportInfo_.totalBytes += bytesWritten;
2635  CHECK(writeTimeout_.isScheduled());
2636  if (pendingWrites_.empty()) {
2637  VLOG(10) << "Cancel write timer on last successful write";
2639  } else {
2640  VLOG(10) << "Refresh write timer on writeSuccess";
2642  }
2643 
2644  if (infoCallback_) {
2645  infoCallback_->onWrite(*this, bytesWritten);
2646  }
2647 
2648  VLOG(5) << "total bytesWritten_: " << bytesWritten_;
2649 
2650  // processByteEvents will return true if it has been replaced with another
2651  // tracker in the middle and needs to be re-run. Should happen at most
2652  // once. while with no body is intentional
2653  while (byteEventTracker_ &&
2654  byteEventTracker_->processByteEvents(
2655  byteEventTracker_, bytesWritten_)) {} // pass
2656 
2657  if ((!codec_->isReusable() || readsShutdown()) && (transactions_.empty())) {
2658  if (!codec_->isReusable()) {
2659  // Shouldn't happen unless there is a bug. This can only happen when
2660  // someone calls shutdownTransport, but did not specify a reason before.
2662  }
2663  VLOG(4) << *this << " shutdown from onWriteSuccess";
2664  shutdownTransport(true, true);
2665  }
2666  numActiveWrites_--;
2667  if (!inLoopCallback_) {
2668  updateWriteCount();
2669  // safe to resume here:
2670  updateWriteBufSize(-folly::to<int64_t>(bytesWritten));
2671  // PRIO_FIXME: this is done because of the corking business...
2672  // in the future we may want to have a pull model
2673  // whereby the socket asks us for a given amount of
2674  // data to send...
2675  if (numActiveWrites_ == 0 && hasMoreWrites()) {
2676  runLoopCallback();
2677  }
2678  }
2679  onWriteCompleted();
2680 
2682  VLOG(4) << "Egress limit reached, shutting down "
2683  "session (egressed " << bytesWritten_ << ", limit set to "
2684  << egressBytesLimit_ << ")";
2685  shutdownTransport(true, true);
2686  }
2687 }
void shutdownTransport(bool shutdownReads=true, bool shutdownWrites=true, const std::string &errorMsg="")
HTTPCodecFilterChain codec_
virtual void onWrite(const HTTPSessionBase &, size_t)
WriteTimeout writeTimeout_
Definition: HTTPSession.h:681
void scheduleTimeout(folly::HHWheelTimer::Callback *callback, std::chrono::milliseconds timeout)
WheelTimerInstance timeout_
Definition: HTTPSession.h:699
WriteSegmentList pendingWrites_
Definition: HTTPSession.h:908
void setCloseReason(ConnectionCloseReason reason)
bool readsShutdown() const
Definition: HTTPSession.h:634
void runLoopCallback() noexceptoverride
std::map< HTTPCodec::StreamID, HTTPTransaction > transactions_
Definition: HTTPSession.h:692
std::shared_ptr< ByteEventTracker > byteEventTracker_
Definition: HTTPSession.h:966
uint64_t egressBytesLimit_
Definition: HTTPSession.h:971
virtual bool isReusable() const =0
void updateWriteBufSize(int64_t delta)
bool hasMoreWrites() const
wangle::TransportInfo transportInfo_
void proxygen::HTTPSession::pauseIngress ( HTTPTransaction txn)
overrideprotectedvirtualnoexcept

Implements proxygen::HTTPTransaction::Transport.

Definition at line 1501 of file HTTPSession.cpp.

References findTransaction(), liveTransactions_, and pauseReads().

Referenced by numIncomingStreams().

1501  {
1502  VLOG(4) << *this << " pausing streamID=" << txn->getID() <<
1503  ", liveTransactions_ was " << liveTransactions_;
1504  CHECK_GT(liveTransactions_, 0);
1506  auto exTxns = txn->getExTransactions();
1507  for (auto it = exTxns.begin(); it != exTxns.end(); ++it) {
1508  auto exTxn = findTransaction(*it);
1509  if (exTxn) {
1510  exTxn->pauseIngress();
1511  }
1512  }
1513 
1514  if (liveTransactions_ == 0) {
1515  pauseReads();
1516  }
1517 }
HTTPTransaction * findTransaction(HTTPCodec::StreamID streamID)
uint32_t liveTransactions_
Definition: HTTPSession.h:695
void proxygen::HTTPSession::pauseReads ( )
protected

Stop reading from the transport until resumeReads() is called

Definition at line 2757 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, proxygen::HTTPSessionBase::ingressLimitExceeded(), pauseReadsImpl(), readsUnpaused(), proxygen::HTTPCodec::setParserPaused(), and proxygen::HTTPCodec::supportsParallelRequests().

Referenced by onBody(), pauseIngress(), and sessionByteOffset().

2757  {
2758  // Make sure the parser is paused. Note that if reads are shutdown
2759  // before they are paused, we never make it past the if.
2760  codec_->setParserPaused(true);
2761  if (!readsUnpaused() ||
2763  !ingressLimitExceeded())) {
2764  return;
2765  }
2766  pauseReadsImpl();
2767 }
bool readsUnpaused() const
Definition: HTTPSession.h:626
HTTPCodecFilterChain codec_
bool ingressLimitExceeded() const
virtual void setParserPaused(bool paused)=0
virtual bool supportsParallelRequests() const =0
void proxygen::HTTPSession::pauseReadsImpl ( )
protected

Definition at line 2769 of file HTTPSession.cpp.

References folly::HHWheelTimer::Callback::cancelTimeout(), proxygen::HTTPSessionBase::infoCallback_, proxygen::HTTPSessionBase::InfoCallback::onIngressPaused(), reads_, and sock_.

Referenced by proxygen::HTTPUpstreamSession::detachThreadLocals(), invokeOnAllTransactions(), and pauseReads().

2769  {
2770  VLOG(4) << *this << ": pausing reads";
2771  if (infoCallback_) {
2773  }
2774  cancelTimeout();
2775  sock_->setReadCB(nullptr);
2776  reads_ = SocketState::PAUSED;
2777 }
folly::AsyncTransportWrapper::UniquePtr sock_
Definition: HTTPSession.h:697
virtual void onIngressPaused(const HTTPSessionBase &)
void proxygen::HTTPSession::processReadData ( )
protected

Definition at line 575 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, FOLLY_SCOPED_TRACE_SECTION, folly::IOBufQueue::front(), ingressError_, folly::IOBuf::length(), proxygen::HTTPCodec::onIngress(), folly::IOBufQueue::pop_front(), readBuf_, readsUnpaused(), proxygen::HTTPCodec::setParserPaused(), and folly::IOBufQueue::trimStart().

Referenced by getHTTPPriority(), readBufferAvailable(), readDataAvailable(), and runLoopCallback().

575  {
576  FOLLY_SCOPED_TRACE_SECTION("HTTPSession - processReadData");
577  // skip any empty IOBufs before feeding CODEC.
578  while (readBuf_.front() != nullptr && readBuf_.front()->length() == 0) {
580  }
581 
582  // Pass the ingress data through the codec to parse it. The codec
583  // will invoke various methods of the HTTPSession as callbacks.
584  const IOBuf* currentReadBuf;
585  // It's possible for the last buffer in a chain to be empty here.
586  // AsyncTransport saw fd activity so asked for a read buffer, but it was
587  // SSL traffic and not enough to decrypt a whole record. Later we invoke
588  // this function from the loop callback.
589  while (!ingressError_ &&
590  readsUnpaused() &&
591  ((currentReadBuf = readBuf_.front()) != nullptr &&
592  currentReadBuf->length() != 0)) {
593  // We're about to parse, make sure the parser is not paused
594  codec_->setParserPaused(false);
595  size_t bytesParsed = codec_->onIngress(*currentReadBuf);
596  if (bytesParsed == 0) {
597  // If the codec didn't make any progress with current input, we
598  // better get more.
599  break;
600  }
601  readBuf_.trimStart(bytesParsed);
602  }
603 }
#define FOLLY_SCOPED_TRACE_SECTION(arg,...)
bool readsUnpaused() const
Definition: HTTPSession.h:626
virtual size_t onIngress(const folly::IOBuf &buf)=0
const folly::IOBuf * front() const
Definition: IOBufQueue.h:476
HTTPCodecFilterChain codec_
folly::IOBufQueue readBuf_
Definition: HTTPSession.h:687
std::size_t length() const
Definition: IOBuf.h:533
void trimStart(size_t amount)
Definition: IOBufQueue.cpp:255
virtual void setParserPaused(bool paused)=0
std::unique_ptr< folly::IOBuf > pop_front()
Definition: IOBufQueue.cpp:316
void proxygen::HTTPSession::readBufferAvailable ( std::unique_ptr< folly::IOBuf )
overrideprotectedvirtualnoexcept

readBufferAvailable() will be invoked when data has been successfully read.

Note that only either readBufferAvailable() or readDataAvailable() will be invoked according to the return value of isBufferMovable(). The timing and aftereffect of readBufferAvailable() are the same as readDataAvailable()

Parameters
readBufThe unique pointer of read buffer.

Reimplemented from folly::AsyncReader::ReadCallback.

Definition at line 557 of file HTTPSession.cpp.

References folly::IOBufQueue::append(), FOLLY_SCOPED_TRACE_SECTION, proxygen::HTTPSessionBase::infoCallback_, folly::gen::move, proxygen::HTTPSessionBase::InfoCallback::onRead(), processReadData(), fizz::detail::readBuf(), readBuf_, and wangle::ManagedConnection::resetTimeout().

Referenced by getHTTPPriority().

557  {
558  size_t readSize = readBuf->computeChainDataLength();
560  "HTTPSession - readBufferAvailable", "readSize", readSize);
561  VLOG(5) << "read completed on " << *this << ", bytes=" << readSize;
562 
563  DestructorGuard dg(this);
564  resetTimeout();
566 
567  if (infoCallback_) {
568  infoCallback_->onRead(*this, readSize);
569  }
570 
571  processReadData();
572 }
#define FOLLY_SCOPED_TRACE_SECTION(arg,...)
void append(std::unique_ptr< folly::IOBuf > &&buf, bool pack=false)
Definition: IOBufQueue.cpp:143
size_t readBuf(Buf &buf, folly::io::Cursor &cursor)
Definition: Types-inl.h:220
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
folly::IOBufQueue readBuf_
Definition: HTTPSession.h:687
virtual void onRead(const HTTPSessionBase &, size_t)
void proxygen::HTTPSession::readDataAvailable ( size_t  len)
overrideprotectedvirtualnoexcept

readDataAvailable() will be invoked when data has been successfully read into the buffer returned by the last call to getReadBuffer().

The read callback remains installed after readDataAvailable() returns. It must be explicitly uninstalled to stop receiving read events. getReadBuffer() will be called at least once before each call to readDataAvailable(). getReadBuffer() will also be called before any call to readEOF().

Parameters
lenThe number of bytes placed in the buffer.

Implements folly::AsyncReader::ReadCallback.

Definition at line 535 of file HTTPSession.cpp.

References FOLLY_SCOPED_TRACE_SECTION, proxygen::HTTPSessionBase::infoCallback_, proxygen::HTTPSessionBase::InfoCallback::onRead(), folly::IOBufQueue::postallocate(), processReadData(), readBuf_, and wangle::ManagedConnection::resetTimeout().

Referenced by getHTTPPriority().

535  {
537  "HTTPSession - readDataAvailable", "readSize", readSize);
538  VLOG(10) << "read completed on " << *this << ", bytes=" << readSize;
539 
540  DestructorGuard dg(this);
541  resetTimeout();
542  readBuf_.postallocate(readSize);
543 
544  if (infoCallback_) {
545  infoCallback_->onRead(*this, readSize);
546  }
547 
548  processReadData();
549 }
#define FOLLY_SCOPED_TRACE_SECTION(arg,...)
folly::IOBufQueue readBuf_
Definition: HTTPSession.h:687
virtual void onRead(const HTTPSessionBase &, size_t)
void postallocate(std::size_t n)
Definition: IOBufQueue.h:380
void proxygen::HTTPSession::readEOF ( )
overrideprotectedvirtualnoexcept

readEOF() will be invoked when the transport is closed.

The read callback will be automatically uninstalled immediately before readEOF() is invoked.

Implements folly::AsyncReader::ReadCallback.

Definition at line 606 of file HTTPSession.cpp.

References folly::IOBufQueue::empty(), proxygen::HTTPSessionBase::getNumTxnServed(), folly::gen::guard(), proxygen::HTTPSessionBase::infoCallback_, proxygen::kErrorClientSilent, proxygen::HTTPSessionBase::InfoCallback::onIngressError(), proxygen::READ_EOF, readBuf_, wangle::TransportInfo::secure, proxygen::HTTPSessionBase::setCloseReason(), shutdownTransport(), transactions_, and proxygen::HTTPSessionBase::transportInfo_.

Referenced by getHTTPPriority().

606  {
607  DestructorGuard guard(this);
608  VLOG(4) << "EOF on " << *this;
609  // for SSL only: error without any bytes from the client might happen
610  // due to client-side issues with the SSL cert. Note that it can also
611  // happen if the client sends a SPDY frame header but no body.
612  if (infoCallback_
613  && transportInfo_.secure && getNumTxnServed() == 0 && readBuf_.empty()) {
615  }
616 
617  // Shut down reads, and also shut down writes if there are no
618  // transactions. (If there are active transactions, leave the
619  // write side of the socket open so those transactions can
620  // finish generating responses.)
622  shutdownTransport(true, transactions_.empty());
623 }
void shutdownTransport(bool shutdownReads=true, bool shutdownWrites=true, const std::string &errorMsg="")
bool empty() const
Definition: IOBufQueue.h:503
virtual void onIngressError(const HTTPSessionBase &, ProxygenError)
folly::IOBufQueue readBuf_
Definition: HTTPSession.h:687
uint64_t getNumTxnServed() const
void setCloseReason(ConnectionCloseReason reason)
GuardImpl guard(ErrorHandler &&handler)
Definition: Base.h:840
std::map< HTTPCodec::StreamID, HTTPTransaction > transactions_
Definition: HTTPSession.h:692
wangle::TransportInfo transportInfo_
void proxygen::HTTPSession::readErr ( const folly::AsyncSocketException ex)
overrideprotectedvirtualnoexcept

readError() will be invoked if an error occurs reading from the transport.

The read callback will be automatically uninstalled immediately before readError() is invoked.

Parameters
exAn exception describing the error that occurred.

Implements folly::AsyncReader::ReadCallback.

Definition at line 626 of file HTTPSession.cpp.

References folly::CLIENT_RENEGOTIATION, folly::gen::guard(), proxygen::HTTPSessionBase::infoCallback_, proxygen::IO_READ_ERROR, proxygen::kErrorClientRenegotiation, proxygen::HTTPSessionBase::InfoCallback::onIngressError(), proxygen::HTTPSessionBase::setCloseReason(), shutdownTransport(), folly::SSL_ERROR, wangle::TransportInfo::sslError, transactions_, and proxygen::HTTPSessionBase::transportInfo_.

Referenced by getHTTPPriority().

626  {
627  DestructorGuard guard(this);
628  VLOG(4) << "read error on " << *this << ": " << ex.what();
629 
630  auto sslEx = dynamic_cast<const folly::SSLException*>(&ex);
631  if (infoCallback_ && sslEx) {
632  if (sslEx->getSSLError() == folly::SSLError::CLIENT_RENEGOTIATION) {
634  }
635  }
636 
637  // We're definitely finished reading. Don't close the write side
638  // of the socket if there are outstanding transactions, though.
639  // Instead, give the transactions a chance to produce any remaining
640  // output.
641  if (sslEx && sslEx->getSSLError() == folly::SSLError::SSL_ERROR) {
642  transportInfo_.sslError = ex.what();
643  }
645  shutdownTransport(true, transactions_.empty(), ex.what());
646 }
void shutdownTransport(bool shutdownReads=true, bool shutdownWrites=true, const std::string &errorMsg="")
virtual void onIngressError(const HTTPSessionBase &, ProxygenError)
void setCloseReason(ConnectionCloseReason reason)
GuardImpl guard(ErrorHandler &&handler)
Definition: Base.h:840
std::map< HTTPCodec::StreamID, HTTPTransaction > transactions_
Definition: HTTPSession.h:692
wangle::TransportInfo transportInfo_
bool proxygen::HTTPSession::readsPaused ( ) const
inlineprotected

Definition at line 630 of file HTTPSession.h.

References reads_.

Referenced by onMessageBegin(), and resumeReads().

630  {
631  return reads_ == SocketState::PAUSED;
632  }
bool proxygen::HTTPSession::readsUnpaused ( ) const
inlineprotected

Definition at line 626 of file HTTPSession.h.

References reads_.

Referenced by onMessageBegin(), pauseReads(), processReadData(), and runLoopCallback().

626  {
627  return reads_ == SocketState::UNPAUSED;
628  }
void proxygen::HTTPSession::readTimeoutExpired ( )
protectednoexcept

Definition at line 379 of file HTTPSession.cpp.

References drainTimeout_, proxygen::HTTPSessionBase::getController(), proxygen::HTTPSessionController::getGracefulShutdownTimeout(), liveTransactions_, notifyPendingShutdown(), wangle::ManagedConnection::resetTimeout(), proxygen::WheelTimerInstance::scheduleTimeout(), proxygen::HTTPSessionBase::setCloseReason(), proxygen::TIMEOUT, timeout_, and transactions_.

Referenced by getHTTPPriority(), and timeoutExpired().

379  {
380  VLOG(3) << "session-level timeout on " << *this;
381 
382  if (liveTransactions_ != 0) {
383  // There's at least one open transaction with a read timeout scheduled.
384  // We got here because the session timeout == the transaction timeout.
385  // Ignore, since the transaction is going to timeout very soon.
386  VLOG(4) << *this <<
387  "ignoring session timeout, transaction timeout imminent";
388  resetTimeout();
389  return;
390  }
391 
392  if (!transactions_.empty()) {
393  // There are one or more transactions, but none of them are live.
394  // That's valid if they've all received their full ingress messages
395  // and are waiting for their Handlers to process those messages.
396  VLOG(4) << *this <<
397  "ignoring session timeout, no transactions awaiting reads";
398  resetTimeout();
399  return;
400  }
401 
402  VLOG(4) << *this << " Timeout with nothing pending";
403 
405  auto controller = getController();
406  if (controller) {
408  controller->getGracefulShutdownTimeout());
409  }
411 }
void scheduleTimeout(folly::HHWheelTimer::Callback *callback, std::chrono::milliseconds timeout)
WheelTimerInstance timeout_
Definition: HTTPSession.h:699
HTTPSessionController * getController()
void setCloseReason(ConnectionCloseReason reason)
uint32_t liveTransactions_
Definition: HTTPSession.h:695
std::map< HTTPCodec::StreamID, HTTPTransaction > transactions_
Definition: HTTPSession.h:692
void notifyPendingShutdown() override
DrainTimeout drainTimeout_
Definition: HTTPSession.h:1033
void proxygen::HTTPSession::removeWaitingForReplaySafety ( ReplaySafetyCallback *  callback)
inlineoverrideprivatenoexcept

Remove a ReplaySafetyCallback that had been waiting for replay safety (eg if a transaction waiting for replay safety is canceled).

Definition at line 813 of file HTTPSession.h.

References waitingForReplaySafety_.

814  {
815  waitingForReplaySafety_.remove(callback);
816  }
std::list< ReplaySafetyCallback * > waitingForReplaySafety_
Definition: HTTPSession.h:846
void proxygen::HTTPSession::rescheduleLoopCallbacks ( )
inlineprotected

Definition at line 650 of file HTTPSession.h.

References folly::EventBase::LoopCallback::isLoopCallbackScheduled(), shutdownTransportCb_, and sock_.

Referenced by proxygen::HTTPUpstreamSession::attachThreadLocals().

650  {
651  if (!isLoopCallbackScheduled()) {
652  sock_->getEventBase()->runInLoop(this);
653  }
654 
655  if (shutdownTransportCb_ &&
656  !shutdownTransportCb_->isLoopCallbackScheduled()) {
657  sock_->getEventBase()->runInLoop(shutdownTransportCb_.get(), true);
658  }
659  }
folly::AsyncTransportWrapper::UniquePtr sock_
Definition: HTTPSession.h:697
std::unique_ptr< ShutdownTransportCallback > shutdownTransportCb_
Definition: HTTPSession.h:998
bool isLoopCallbackScheduled() const
Definition: EventBase.h:160
void proxygen::HTTPSession::resumeIngress ( HTTPTransaction txn)
overrideprotectedvirtualnoexcept

Implements proxygen::HTTPTransaction::Transport.

Definition at line 1519 of file HTTPSession.cpp.

References findTransaction(), liveTransactions_, and resumeReads().

Referenced by detach(), and numIncomingStreams().

1519  {
1520  VLOG(4) << *this << " resuming streamID=" << txn->getID() <<
1521  ", liveTransactions_ was " << liveTransactions_;
1523  auto exTxns = txn->getExTransactions();
1524  for (auto it = exTxns.begin(); it != exTxns.end(); ++it) {
1525  auto exTxn = findTransaction(*it);
1526  if (exTxn) {
1527  exTxn->resumeIngress();
1528  }
1529  }
1530 
1531  if (liveTransactions_ == 1) {
1532  resumeReads();
1533  }
1534 }
HTTPTransaction * findTransaction(HTTPCodec::StreamID streamID)
uint32_t liveTransactions_
Definition: HTTPSession.h:695
void proxygen::HTTPSession::resumeReads ( )
protected

Unpause reading from the transport.

Note
If any codec callbacks arrived while reads were paused, they will be processed before network reads resume.

Definition at line 2780 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, proxygen::HTTPSessionBase::ingressLimitExceeded(), readsPaused(), resumeReadsImpl(), and proxygen::HTTPCodec::supportsParallelRequests().

Referenced by detach(), notifyIngressBodyProcessed(), resumeIngress(), sessionByteOffset(), and startNow().

2780  {
2781  if (!readsPaused() ||
2783  ingressLimitExceeded())) {
2784  return;
2785  }
2786  resumeReadsImpl();
2787 }
HTTPCodecFilterChain codec_
bool readsPaused() const
Definition: HTTPSession.h:630
bool ingressLimitExceeded() const
virtual bool supportsParallelRequests() const =0
void proxygen::HTTPSession::resumeReadsImpl ( )
protected

Definition at line 2789 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, folly::EventBase::LoopCallback::isLoopCallbackScheduled(), reads_, wangle::ManagedConnection::resetTimeout(), proxygen::HTTPCodec::setParserPaused(), and sock_.

Referenced by proxygen::HTTPUpstreamSession::attachThreadLocals(), invokeOnAllTransactions(), and resumeReads().

2789  {
2790  VLOG(4) << *this << ": resuming reads";
2791  resetTimeout();
2792  reads_ = SocketState::UNPAUSED;
2793  codec_->setParserPaused(false);
2794  if (!isLoopCallbackScheduled()) {
2795  sock_->getEventBase()->runInLoop(this);
2796  }
2797 }
HTTPCodecFilterChain codec_
folly::AsyncTransportWrapper::UniquePtr sock_
Definition: HTTPSession.h:697
bool isLoopCallbackScheduled() const
Definition: EventBase.h:160
virtual void setParserPaused(bool paused)=0
void proxygen::HTTPSession::resumeTransactions ( )
protected

Definition at line 2850 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::egressLimitExceeded(), g(), inResume_, invokeOnAllTransactions(), proxygen::HTTP2PriorityQueue::iterateBFS(), proxygen::HTTPTransaction::pauseEgress(), pendingPause_, transactions_, and txnEgressQueue_.

Referenced by invokeOnAllTransactions(), and updateWriteBufSize().

2850  {
2851  CHECK(!inResume_);
2852  inResume_ = true;
2853  DestructorGuard g(this);
2854  auto resumeFn = [] (HTTP2PriorityQueue&, HTTPCodec::StreamID,
2855  HTTPTransaction *txn, double) {
2856  if (txn) {
2857  txn->resumeEgress();
2858  }
2859  return false;
2860  };
2861  auto stopFn = [this] {
2862  return (transactions_.empty() || egressLimitExceeded());
2863  };
2864 
2865  txnEgressQueue_.iterateBFS(resumeFn, stopFn, true /* all */);
2866  inResume_ = false;
2867  if (pendingPause_) {
2868  VLOG(3) << "Pausing txn egress for " << *this;
2869  pendingPause_ = false;
2871  }
2872 }
bool egressLimitExceeded() const
void invokeOnAllTransactions(void(HTTPTransaction::*fn)(Args1...), Args2 &&...args)
Definition: HTTPSession.h:584
HTTP2PriorityQueue txnEgressQueue_
Definition: HTTPSession.h:690
std::map< HTTPCodec::StreamID, HTTPTransaction > transactions_
Definition: HTTPSession.h:692
g_t g(f_t)
void iterateBFS(const std::function< bool(HTTP2PriorityQueue &, HTTPCodec::StreamID, HTTPTransaction *, double)> &fn, const std::function< bool()> &stopFn, bool all)
uint64_t StreamID
Definition: HTTPCodec.h:49
void proxygen::HTTPSession::runLoopCallback ( )
overrideprotectedvirtualnoexcept

Implements folly::EventBase::LoopCallback.

Definition at line 2137 of file HTTPSession.cpp.

References bodyBytesPerWriteBuf_, bytesScheduled_, checkForShutdown(), folly::IOBuf::computeChainDataLength(), connFlowControl_, proxygen::FlowControlFilter::getAvailableSend(), proxygen::HTTPSession::WriteSegment::getFlags(), getNextToSend(), hasMoreWrites(), i, inLoopCallback_, invokeOnAllTransactions(), proxygen::HTTPSessionBase::isPrioritySampled(), folly::HHWheelTimer::Callback::isScheduled(), folly::makeGuard(), folly::gen::move, numActiveWrites_, proxygen::HTTP2PriorityQueue::numPendingEgress(), pendingWrites_, pendingWriteSizeDelta_, processReadData(), readsUnpaused(), proxygen::WheelTimerInstance::scheduleTimeout(), scheduleWrite(), proxygen::HTTPSession::WriteSegment::setCork(), proxygen::HTTPSession::WriteSegment::setEOR(), sock_, timeout_, txnEgressQueue_, uint32_t, uint64_t, proxygen::HTTPTransaction::updateContentionsCount(), proxygen::HTTPTransaction::updateSessionBytesSheduled(), updateWriteBufSize(), updateWriteCount(), fizz::detail::writeBuf(), proxygen::HTTPSession::WriteSegment::WriteSegment(), writesShutdown(), and writeTimeout_.

Referenced by isDraining(), and onWriteSuccess().

2137  {
2138  // We schedule this callback to run at the end of an event
2139  // loop iteration if either of two conditions has happened:
2140  // * The session has generated some egress data (see scheduleWrite())
2141  // * Reads have become unpaused (see resumeReads())
2142  DestructorGuard dg(this);
2143  inLoopCallback_ = true;
2144  auto scopeg = folly::makeGuard([this] {
2145  inLoopCallback_ = false;
2146  // This ScopeGuard needs to be under the above DestructorGuard
2147  if (pendingWriteSizeDelta_) {
2148  updateWriteBufSize(0);
2149  }
2150  checkForShutdown();
2151  });
2152  VLOG(5) << *this << " in loop callback";
2153 
2154  for (uint32_t i = 0; i < kMaxWritesPerLoop; ++i) {
2156  if (isPrioritySampled()) {
2160  }
2161 
2162  bool cork = true;
2163  bool eom = false;
2164  unique_ptr<IOBuf> writeBuf = getNextToSend(&cork, &eom);
2165 
2166  if (!writeBuf) {
2167  break;
2168  }
2169  uint64_t len = writeBuf->computeChainDataLength();
2170  VLOG(11) << *this
2171  << " bytes of egress to be written: " << len
2172  << " cork:" << cork << " eom:" << eom;
2173  if (len == 0) {
2174  checkForShutdown();
2175  return;
2176  }
2177 
2178  if (isPrioritySampled()) {
2182  }
2183 
2184  WriteSegment* segment = new WriteSegment(this, len);
2185  segment->setCork(cork);
2186  segment->setEOR(eom);
2187 
2188  pendingWrites_.push_back(*segment);
2189  if (!writeTimeout_.isScheduled()) {
2190  // Any performance concern here?
2192  }
2193  numActiveWrites_++;
2194  VLOG(4) << *this << " writing " << len << ", activeWrites="
2195  << numActiveWrites_ << " cork=" << cork << " eom=" << eom;
2196  bytesScheduled_ += len;
2197  sock_->writeChain(segment, std::move(writeBuf), segment->getFlags());
2198  if (numActiveWrites_ > 0) {
2199  updateWriteCount();
2200  pendingWriteSizeDelta_ += len;
2201  // updateWriteBufSize called in scope guard
2202  break;
2203  }
2204  // writeChain can result in a writeError and trigger the shutdown code path
2205  }
2206  if (numActiveWrites_ == 0 && !writesShutdown() && hasMoreWrites() &&
2208  scheduleWrite();
2209  }
2210 
2211  if (readsUnpaused()) {
2212  processReadData();
2213 
2214  // Install the read callback if necessary
2215  if (readsUnpaused() && !sock_->getReadCallback()) {
2216  sock_->setReadCB(this);
2217  }
2218  }
2219  // checkForShutdown is now in ScopeGuard
2220 }
bool readsUnpaused() const
Definition: HTTPSession.h:626
void invokeOnAllTransactions(void(HTTPTransaction::*fn)(Args1...), Args2 &&...args)
Definition: HTTPSession.h:584
FlowControlFilter * connFlowControl_
Definition: HTTPSession.h:913
std::unique_ptr< folly::IOBuf > getNextToSend(bool *cork, bool *eom)
WriteTimeout writeTimeout_
Definition: HTTPSession.h:681
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
folly::AsyncTransportWrapper::UniquePtr sock_
Definition: HTTPSession.h:697
HTTP2PriorityQueue txnEgressQueue_
Definition: HTTPSession.h:690
void updateSessionBytesSheduled(uint64_t bytes)
void scheduleTimeout(folly::HHWheelTimer::Callback *callback, std::chrono::milliseconds timeout)
WheelTimerInstance timeout_
Definition: HTTPSession.h:699
WriteSegmentList pendingWrites_
Definition: HTTPSession.h:908
uint64_t bodyBytesPerWriteBuf_
Definition: HTTPSession.h:959
void writeBuf(const Buf &buf, folly::io::Appender &out)
int64_t pendingWriteSizeDelta_
Definition: HTTPSession.h:954
bool writesShutdown() const
Definition: HTTPSession.h:646
std::size_t computeChainDataLength() const
Definition: IOBuf.cpp:501
FOLLY_NODISCARD detail::ScopeGuardImplDecay< F, true > makeGuard(F &&f) noexcept(noexcept(detail::ScopeGuardImplDecay< F, true >(static_cast< F && >(f))))
Definition: ScopeGuard.h:184
uint32_t getAvailableSend() const
void updateWriteBufSize(int64_t delta)
void updateContentionsCount(uint64_t contentions)
bool hasMoreWrites() const
void proxygen::HTTPSession::scheduleWrite ( )
protected

Schedule a write to occur at the end of this event loop.

Definition at line 2223 of file HTTPSession.cpp.

References proxygen::HTTP2PriorityQueue::empty(), folly::IOBufQueue::front(), folly::EventBase::LoopCallback::isLoopCallbackScheduled(), sock_, txnEgressQueue_, and writeBuf_.

Referenced by closeWhenIdle(), drainImpl(), isDraining(), notifyIngressBodyProcessed(), notifyPendingEgress(), onBody(), onCertificateRequest(), onConnectionSendWindowOpen(), proxygen::HTTPUpstreamSession::onNativeProtocolUpgrade(), onNativeProtocolUpgradeImpl(), onNewTransactionParseError(), onPingRequest(), onSessionParseError(), onSettings(), runLoopCallback(), sendAbort(), sendCertificateRequest(), sendChunkHeader(), sendChunkTerminator(), sendHeaders(), sendPing(), sendPriorityImpl(), sendSettings(), sendWindowUpdate(), shutdownTransport(), proxygen::HTTPUpstreamSession::startNow(), and startNow().

2223  {
2224  // Do all the network writes for this connection in one batch at
2225  // the end of the current event loop iteration. Writing in a
2226  // batch helps us packetize the network traffic more efficiently,
2227  // as well as saving a few system calls.
2228  if (!isLoopCallbackScheduled() &&
2229  (writeBuf_.front() || !txnEgressQueue_.empty())) {
2230  VLOG(5) << *this << " scheduling write callback";
2231  sock_->getEventBase()->runInLoop(this);
2232  }
2233 }
const folly::IOBuf * front() const
Definition: IOBufQueue.h:476
folly::AsyncTransportWrapper::UniquePtr sock_
Definition: HTTPSession.h:697
HTTP2PriorityQueue txnEgressQueue_
Definition: HTTPSession.h:690
bool isLoopCallbackScheduled() const
Definition: EventBase.h:160
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
size_t proxygen::HTTPSession::sendAbort ( HTTPTransaction txn,
ErrorCode  statusCode 
)
overrideprotectedvirtualnoexcept

Implements proxygen::HTTPTransaction::Transport.

Definition at line 1783 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, proxygen::HTTPCodec::generateRstStream(), proxygen::HTTPCodec::isReusable(), onEgressMessageFinished(), scheduleWrite(), proxygen::HTTPSessionBase::setCloseReason(), statusCode, proxygen::TRANSACTION_ABORT, and writeBuf_.

Referenced by numIncomingStreams().

1784  {
1785  // Ask the codec to generate an abort indicator for the transaction.
1786  // Depending on the protocol, this may be a no-op.
1787  // Schedule a network write to send out whatever egress we might
1788  // have queued up.
1789  VLOG(4) << *this << " sending abort for streamID=" << txn->getID();
1790  // drain this transaction's writeBuf instead of flushing it
1791  // then enqueue the abort directly into the Session buffer,
1792  // hence with max priority.
1793  size_t encodedSize = codec_->generateRstStream(writeBuf_,
1794  txn->getID(),
1795  statusCode);
1796 
1797  if (!codec_->isReusable()) {
1798  // HTTP 1x codec does not support per stream abort so this will
1799  // render the codec not reusable
1801  }
1802 
1803  scheduleWrite();
1804 
1805  // If the codec wasn't able to write a L7 message for the abort, then
1806  // fall back to closing the transport with a TCP level RST
1807  onEgressMessageFinished(txn, !encodedSize);
1808  return encodedSize;
1809 }
spdy::GoawayStatusCode statusCode
Definition: SPDYCodec.cpp:110
HTTPCodecFilterChain codec_
void onEgressMessageFinished(HTTPTransaction *txn, bool withRST=false)
virtual size_t generateRstStream(folly::IOBufQueue &writeBuf, StreamID stream, ErrorCode code)=0
void setCloseReason(ConnectionCloseReason reason)
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
virtual bool isReusable() const =0
size_t proxygen::HTTPSession::sendBody ( HTTPTransaction txn,
std::unique_ptr< folly::IOBuf body,
bool  includeEOM,
bool  trackLastByteFlushed 
)
overrideprotectedvirtualnoexcept

Implements proxygen::HTTPTransaction::Transport.

Definition at line 1667 of file HTTPSession.cpp.

References bodyBytesPerWriteBuf_, byteEventTracker_, proxygen::HTTPSessionBase::codec_, commonEom(), proxygen::HTTPCodec::generateBody(), inLoopCallback_, folly::gen::move, proxygen::HTTPCodec::NoPadding, pendingWriteSizeDelta_, sessionByteOffset(), uint64_t, and writeBuf_.

Referenced by numIncomingStreams().

1670  {
1671  uint64_t offset = sessionByteOffset();
1672  size_t bodyLen = body ? body->computeChainDataLength(): 0;
1673  size_t encodedSize = codec_->generateBody(writeBuf_,
1674  txn->getID(),
1675  std::move(body),
1677  includeEOM);
1678  CHECK(inLoopCallback_);
1679  pendingWriteSizeDelta_ -= bodyLen;
1680  bodyBytesPerWriteBuf_ += bodyLen;
1681  if (encodedSize > 0 && !txn->testAndSetFirstByteSent() && byteEventTracker_) {
1682  byteEventTracker_->addFirstBodyByteEvent(offset, txn);
1683  }
1684 
1685  if (trackLastByteFlushed && encodedSize > 0 && byteEventTracker_) {
1686  byteEventTracker_->addTrackedByteEvent(txn, offset + encodedSize);
1687  }
1688 
1689  if (includeEOM) {
1690  VLOG(5) << *this << " sending EOM in body for streamID=" << txn->getID();
1691  commonEom(txn, encodedSize, true);
1692  }
1693  return encodedSize;
1694 }
static const folly::Optional< uint8_t > NoPadding
Definition: HTTPCodec.h:53
HTTPCodecFilterChain codec_
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
virtual size_t generateBody(folly::IOBufQueue &writeBuf, StreamID stream, std::unique_ptr< folly::IOBuf > chain, folly::Optional< uint8_t > padding, bool eom)=0
void commonEom(HTTPTransaction *txn, size_t encodedSize, bool piggybacked) noexcept
uint64_t bodyBytesPerWriteBuf_
Definition: HTTPSession.h:959
int64_t pendingWriteSizeDelta_
Definition: HTTPSession.h:954
std::size_t computeChainDataLength() const
Definition: IOBuf.cpp:501
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
std::shared_ptr< ByteEventTracker > byteEventTracker_
Definition: HTTPSession.h:966
uint64_t sessionByteOffset()
Definition: HTTPSession.h:511
size_t proxygen::HTTPSession::sendCertificateRequest ( std::unique_ptr< folly::IOBuf certificateRequestContext,
std::vector< fizz::Extension extensions 
)
overridevirtual

Send a CERTIFICATE_REQUEST frame. If the underlying protocol doesn't support secondary authentication, this is a no-op and 0 is returned.

Reimplemented from proxygen::HTTPSessionBase.

Definition at line 1829 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, proxygen::HTTPCodec::generateCertificateRequest(), proxygen::HTTPCodec::getEgressSettings(), proxygen::HTTPCodec::getIngressSettings(), folly::gen::move, scheduleWrite(), secondAuthManager_, proxygen::SETTINGS_HTTP_CERT_AUTH, and writeBuf_.

Referenced by getSetupTransportInfo().

1831  {
1832  // Check if both sending and receiving peer have advertised valid
1833  // SETTINGS_HTTP_CERT_AUTH setting. Otherwise, the frames for secondary
1834  // authentication should not be sent.
1835  auto ingressSettings = codec_->getIngressSettings();
1836  auto egressSettings = codec_->getEgressSettings();
1837  if (ingressSettings && egressSettings) {
1838  if (ingressSettings->getSetting(SettingsId::SETTINGS_HTTP_CERT_AUTH, 0) ==
1839  0 ||
1840  egressSettings->getSetting(SettingsId::SETTINGS_HTTP_CERT_AUTH, 0) ==
1841  0) {
1842  VLOG(4) << "Secondary certificate authentication is not supported.";
1843  return 0;
1844  }
1845  }
1846  auto authRequest = secondAuthManager_->createAuthRequest(
1847  std::move(certificateRequestContext), std::move(extensions));
1848  auto encodedSize = codec_->generateCertificateRequest(
1849  writeBuf_, authRequest.first, std::move(authRequest.second));
1850  if (encodedSize > 0) {
1851  scheduleWrite();
1852  } else {
1853  VLOG(4) << "Failed to generate CERTIFICATE_REQUEST frame.";
1854  }
1855  return encodedSize;
1856 }
virtual const HTTPSettings * getIngressSettings() const
Definition: HTTPCodec.h:657
virtual HTTPSettings * getEgressSettings()
Definition: HTTPCodec.h:653
HTTPCodecFilterChain codec_
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
std::unique_ptr< SecondaryAuthManager > secondAuthManager_
Definition: HTTPSession.h:1055
virtual size_t generateCertificateRequest(folly::IOBufQueue &, uint16_t, std::unique_ptr< folly::IOBuf >)
Definition: HTTPCodec.h:631
size_t proxygen::HTTPSession::sendChunkHeader ( HTTPTransaction txn,
size_t  length 
)
overrideprotectedvirtualnoexcept

Implements proxygen::HTTPTransaction::Transport.

Definition at line 1696 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, proxygen::HTTPCodec::generateChunkHeader(), scheduleWrite(), and writeBuf_.

Referenced by numIncomingStreams().

1697  {
1698  size_t encodedSize = codec_->generateChunkHeader(writeBuf_,
1699  txn->getID(),
1700  length);
1701  scheduleWrite();
1702  return encodedSize;
1703 }
HTTPCodecFilterChain codec_
virtual size_t generateChunkHeader(folly::IOBufQueue &writeBuf, StreamID stream, size_t length)=0
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
size_t proxygen::HTTPSession::sendChunkTerminator ( HTTPTransaction txn)
overrideprotectedvirtualnoexcept

Implements proxygen::HTTPTransaction::Transport.

Definition at line 1705 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, proxygen::HTTPCodec::generateChunkTerminator(), scheduleWrite(), and writeBuf_.

Referenced by numIncomingStreams().

1706  {
1707  size_t encodedSize = codec_->generateChunkTerminator(writeBuf_,
1708  txn->getID());
1709  scheduleWrite();
1710  return encodedSize;
1711 }
HTTPCodecFilterChain codec_
virtual size_t generateChunkTerminator(folly::IOBufQueue &writeBuf, StreamID stream)=0
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
size_t proxygen::HTTPSession::sendEOM ( HTTPTransaction txn,
const HTTPHeaders trailers 
)
overrideprotectedvirtualnoexcept

Implements proxygen::HTTPTransaction::Transport.

Definition at line 1761 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, commonEom(), proxygen::HTTPCodec::generateEOM(), proxygen::HTTPCodec::generateTrailers(), proxygen::HTTPCodec::getProtocol(), proxygen::isHTTP2CodecProtocol(), and writeBuf_.

Referenced by numIncomingStreams().

1762  {
1763 
1764  VLOG(4) << *this << " sending EOM for streamID=" << txn->getID()
1765  << " trailers=" << (trailers ? "yes" : "no");
1766 
1767  size_t encodedSize = 0;
1768  if (trailers) {
1769  encodedSize = codec_->generateTrailers(writeBuf_, txn->getID(), *trailers);
1770  }
1771 
1772  // Don't send EOM for HTTP2, when trailers sent.
1773  // sendTrailers already flagged end of stream.
1774  bool http2Trailers = trailers && isHTTP2CodecProtocol(codec_->getProtocol());
1775  if (!http2Trailers) {
1776  encodedSize += codec_->generateEOM(writeBuf_, txn->getID());
1777  }
1778 
1779  commonEom(txn, encodedSize, false);
1780  return encodedSize;
1781 }
HTTPCodecFilterChain codec_
virtual CodecProtocol getProtocol() const =0
virtual size_t generateTrailers(folly::IOBufQueue &writeBuf, StreamID stream, const HTTPHeaders &trailers)=0
void commonEom(HTTPTransaction *txn, size_t encodedSize, bool piggybacked) noexcept
virtual size_t generateEOM(folly::IOBufQueue &writeBuf, StreamID stream)=0
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
bool isHTTP2CodecProtocol(CodecProtocol protocol)
void proxygen::HTTPSession::sendHeaders ( HTTPTransaction txn,
const HTTPMessage headers,
HTTPHeaderSize size,
bool  includeEOM 
)
overrideprotectedvirtualnoexcept

Implements proxygen::HTTPTransaction::Transport.

Definition at line 1576 of file HTTPSession.cpp.

References folly::IOBufQueue::append(), byteEventTracker_, proxygen::HTTPSessionBase::codec_, commonEom(), drainImpl(), proxygen::HTTPCodec::generateExHeader(), proxygen::HTTPCodec::generateHeader(), proxygen::HTTPCodec::generatePushPromise(), getHTTP2PrioritiesEnabled(), getMessagePriority(), incrementOutgoingStreams(), isDownstream(), proxygen::HTTPCodec::isReusable(), isUpstream(), folly::IOBufQueue::move(), folly::gen::move, onHeadersSent(), scheduleWrite(), sessionByteOffset(), shouldShutdown(), folly::size(), started_, uint64_t, fizz::detail::writeBuf(), and writeBuf_.

Referenced by numIncomingStreams().

1579  {
1580  CHECK(started_);
1581  unique_ptr<IOBuf> goawayBuf;
1582  if (shouldShutdown()) {
1583  // For HTTP/1.1, add Connection: close
1584  // For SPDY, save the goaway for AFTER the request
1585  auto writeBuf = writeBuf_.move();
1586  drainImpl();
1587  goawayBuf = writeBuf_.move();
1589  }
1590  if (isUpstream() || (txn->isPushed() && headers.isRequest())) {
1591  // upstream picks priority
1592  if (getHTTP2PrioritiesEnabled()) {
1593  auto pri = getMessagePriority(&headers);
1594  txn->onPriorityUpdate(pri);
1595  }
1596  }
1597 
1598  const bool wasReusable = codec_->isReusable();
1599  const uint64_t oldOffset = sessionByteOffset();
1600  auto exAttributes = txn->getExAttributes();
1601  auto assocStream = txn->getAssocTxnId();
1602  if (exAttributes) {
1604  txn->getID(),
1605  headers,
1606  *exAttributes,
1607  includeEOM,
1608  size);
1609  } else if (headers.isRequest() && assocStream) {
1610  // Only PUSH_PROMISE (not push response) has an associated stream
1612  txn->getID(),
1613  headers,
1614  *assocStream,
1615  includeEOM,
1616  size);
1617  } else {
1619  txn->getID(),
1620  headers,
1621  includeEOM,
1622  size);
1623  }
1624  const uint64_t newOffset = sessionByteOffset();
1625 
1626  // for push response count towards the MAX_CONCURRENT_STREAMS limit
1627  if (isDownstream() && headers.isResponse() && txn->isPushed()) {
1629  }
1630 
1631  // For all upstream headers, addFirstHeaderByteEvent should be added
1632  // For all downstream, only response headers need addFirstHeaderByteEvent
1633  bool shouldAddFirstHeaderByteEvent = isUpstream() ||
1634  (isDownstream() && headers.isResponse());
1635  if (shouldAddFirstHeaderByteEvent && newOffset > oldOffset &&
1636  !txn->testAndSetFirstHeaderByteSent() && byteEventTracker_) {
1637  byteEventTracker_->addFirstHeaderByteEvent(newOffset, txn);
1638  }
1639 
1640  if (size) {
1641  VLOG(4) << *this << " sending headers, size=" << size->compressed
1642  << ", uncompressedSize=" << size->uncompressed;
1643  }
1644  if (goawayBuf) {
1645  VLOG(4) << *this << " moved GOAWAY to end of writeBuf";
1646  writeBuf_.append(std::move(goawayBuf));
1647  }
1648  if (includeEOM) {
1649  commonEom(txn, 0, true);
1650  }
1651  scheduleWrite();
1652  onHeadersSent(headers, wasReusable);
1653 }
void append(std::unique_ptr< folly::IOBuf > &&buf, bool pack=false)
Definition: IOBufQueue.cpp:143
HTTPCodecFilterChain codec_
virtual void generateHeader(folly::IOBufQueue &writeBuf, StreamID stream, const HTTPMessage &msg, bool eom=false, HTTPHeaderSize *size=nullptr)=0
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
std::unique_ptr< folly::IOBuf > move()
Definition: IOBufQueue.h:459
virtual void generatePushPromise(folly::IOBufQueue &, StreamID, const HTTPMessage &, StreamID, bool, HTTPHeaderSize *)
Definition: HTTPCodec.h:492
bool isUpstream() const
void commonEom(HTTPTransaction *txn, size_t encodedSize, bool piggybacked) noexcept
bool getHTTP2PrioritiesEnabled() const override
Definition: HTTPSession.h:114
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
void writeBuf(const Buf &buf, folly::io::Appender &out)
virtual void onHeadersSent(const HTTPMessage &, bool)
Definition: HTTPSession.h:300
virtual void generateExHeader(folly::IOBufQueue &, StreamID, const HTTPMessage &, const HTTPCodec::ExAttributes &, bool, HTTPHeaderSize *)
Definition: HTTPCodec.h:499
http2::PriorityUpdate getMessagePriority(const HTTPMessage *msg)
bool shouldShutdown() const
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
std::shared_ptr< ByteEventTracker > byteEventTracker_
Definition: HTTPSession.h:966
virtual bool isReusable() const =0
bool isDownstream() const
uint64_t sessionByteOffset()
Definition: HTTPSession.h:511
size_t proxygen::HTTPSession::sendPing ( )
overridevirtual

Causes a ping to be sent on the session. If the underlying protocol doesn't support pings, this will return 0. Otherwise, it will return the number of bytes written on the transport to send the ping.

Implements proxygen::HTTPSessionBase.

Definition at line 2505 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, proxygen::HTTPCodec::generatePingRequest(), scheduleWrite(), and writeBuf_.

Referenced by getSetupTransportInfo().

2505  {
2506  const size_t bytes = codec_->generatePingRequest(writeBuf_);
2507  if (bytes) {
2508  scheduleWrite();
2509  }
2510  return bytes;
2511 }
HTTPCodecFilterChain codec_
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
virtual size_t generatePingRequest(folly::IOBufQueue &)
Definition: HTTPCodec.h:576
HTTPCodec::StreamID proxygen::HTTPSession::sendPriority ( http2::PriorityUpdate  pri)
overridevirtual

Sends a priority message on this session. If the underlying protocol doesn't support priority, this is a no-op. A new stream identifier will be selected and returned.

Implements proxygen::HTTPPriorityMapFactoryProvider.

Definition at line 2513 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, proxygen::HTTPCodec::createStream(), and proxygen::HTTPCodec::supportsParallelRequests().

Referenced by getSetupTransportInfo(), and numIncomingStreams().

2513  {
2514  if (!codec_->supportsParallelRequests()) {
2515  // For HTTP/1.1, don't call createStream()
2516  return 0;
2517  }
2518  auto id = codec_->createStream();
2519  sendPriority(id, pri);
2520  return id;
2521 }
virtual StreamID createStream()=0
HTTPCodecFilterChain codec_
HTTPCodec::StreamID sendPriority(http2::PriorityUpdate pri) override
virtual bool supportsParallelRequests() const =0
size_t proxygen::HTTPSession::sendPriority ( HTTPCodec::StreamID  id,
http2::PriorityUpdate  pri 
)
overridevirtual

As above, but updates an existing priority node. Do not use for real nodes, prefer HTTPTransaction::changePriority.

Implements proxygen::HTTPSessionBase.

Definition at line 2523 of file HTTPSession.cpp.

References proxygen::HTTP2PriorityQueue::addOrUpdatePriorityNode(), sendPriorityImpl(), and txnEgressQueue_.

2524  {
2525  auto res = sendPriorityImpl(id, pri);
2527  return res;
2528 }
HTTP2PriorityQueue txnEgressQueue_
Definition: HTTPSession.h:690
size_t sendPriorityImpl(HTTPCodec::StreamID streamID, http2::PriorityUpdate pri)
void addOrUpdatePriorityNode(HTTPCodec::StreamID id, http2::PriorityUpdate pri)
size_t proxygen::HTTPSession::sendPriority ( HTTPTransaction txn,
const http2::PriorityUpdate pri 
)
overrideprotectedvirtualnoexcept

Implements proxygen::HTTPTransaction::Transport.

Definition at line 1811 of file HTTPSession.cpp.

References sendPriorityImpl().

1812  {
1813  return sendPriorityImpl(txn->getID(), pri);
1814 }
size_t sendPriorityImpl(HTTPCodec::StreamID streamID, http2::PriorityUpdate pri)
size_t proxygen::HTTPSession::sendPriorityImpl ( HTTPCodec::StreamID  streamID,
http2::PriorityUpdate  pri 
)
protected

Sends a priority message on this session. If the underlying protocol doesn't support priority, this is a no-op. Returns the number of bytes written on the transport

Definition at line 2531 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, proxygen::http2::PriorityUpdate::exclusive, proxygen::HTTPCodec::generatePriority(), std::tr1::make_tuple(), scheduleWrite(), proxygen::http2::PriorityUpdate::streamDependency, proxygen::http2::PriorityUpdate::weight, and writeBuf_.

Referenced by onHeadersSent(), and sendPriority().

2532  {
2533  CHECK_NE(id, 0);
2534  const size_t bytes = codec_->generatePriority(
2535  writeBuf_, id, std::make_tuple(pri.streamDependency,
2536  pri.exclusive,
2537  pri.weight));
2538  if (bytes) {
2539  scheduleWrite();
2540  }
2541  return bytes;
2542 }
HTTPCodecFilterChain codec_
tuple make_tuple()
Definition: gtest-tuple.h:675
virtual size_t generatePriority(folly::IOBufQueue &, StreamID, const HTTPMessage::HTTPPriority &)
Definition: HTTPCodec.h:620
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
size_t proxygen::HTTPSession::sendSettings ( )
overridevirtual

Send a settings frame

Implements proxygen::HTTPSessionBase.

Definition at line 1495 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, proxygen::HTTPCodec::generateSettings(), scheduleWrite(), folly::size(), and writeBuf_.

Referenced by getSetupTransportInfo(), and onNativeProtocolUpgradeImpl().

1495  {
1497  scheduleWrite();
1498  return size;
1499 }
HTTPCodecFilterChain codec_
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
virtual size_t generateSettings(folly::IOBufQueue &)
Definition: HTTPCodec.h:592
size_t proxygen::HTTPSession::sendWindowUpdate ( HTTPTransaction txn,
uint32_t  bytes 
)
overrideprotectedvirtualnoexcept

Implements proxygen::HTTPTransaction::Transport.

Definition at line 1976 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, proxygen::HTTPCodec::generateWindowUpdate(), scheduleWrite(), and writeBuf_.

Referenced by numIncomingStreams().

1977  {
1978  size_t sent = codec_->generateWindowUpdate(writeBuf_, txn->getID(), bytes);
1979  if (sent) {
1980  scheduleWrite();
1981  }
1982  return sent;
1983 }
HTTPCodecFilterChain codec_
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
virtual size_t generateWindowUpdate(folly::IOBufQueue &, StreamID, uint32_t)
Definition: HTTPCodec.h:610
uint64_t proxygen::HTTPSession::sessionByteOffset ( )
inlineprotected
void proxygen::HTTPSession::setByteEventTracker ( std::shared_ptr< ByteEventTracker byteEventTracker)

Definition at line 317 of file HTTPSession.cpp.

References byteEventTracker_, folly::gen::move, and proxygen::HTTPSessionBase::sessionStats_.

Referenced by getByteEventTracker(), and TEST().

318  {
319  if (byteEventTracker && byteEventTracker_) {
320  byteEventTracker->absorb(std::move(*byteEventTracker_));
321  }
322  byteEventTracker_ = byteEventTracker;
323  if (byteEventTracker_) {
324  byteEventTracker_->setCallback(this);
325  byteEventTracker_->setTTLBAStats(sessionStats_);
326  }
327 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
HTTPSessionStats * sessionStats_
std::shared_ptr< ByteEventTracker > byteEventTracker_
Definition: HTTPSession.h:966
void proxygen::HTTPSession::setEgressBytesLimit ( uint64_t  bytesLimit)

Set the maximum number of bytes allowed to be egressed in the session before cutting it off

Definition at line 373 of file HTTPSession.cpp.

References egressBytesLimit_, and started_.

Referenced by getSetupTransportInfo().

373  {
374  CHECK(!started_);
375  egressBytesLimit_ = bytesLimit;
376 }
uint64_t egressBytesLimit_
Definition: HTTPSession.h:971
void proxygen::HTTPSession::setEgressSettings ( const SettingsList inSettings)
overridevirtual

Set outgoing settings for this session

Implements proxygen::HTTPSessionBase.

Definition at line 351 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, proxygen::HTTPCodec::getEgressSettings(), proxygen::HTTPSettings::setSetting(), settings, and started_.

Referenced by getByteEventTracker(), and proxygen::HTTPSessionAcceptor::onNewConnection().

351  {
352  VLOG_IF(4, started_) << "Must flush egress settings to peer";
353  HTTPSettings* settings = codec_->getEgressSettings();
354  if (settings) {
355  for (const auto& setting: inSettings) {
356  settings->setSetting(setting.id, setting.value);
357  }
358  }
359 }
virtual HTTPSettings * getEgressSettings()
Definition: HTTPCodec.h:653
HTTPCodecFilterChain codec_
static http_parser_settings settings
Definition: test.c:1529
void setSetting(SettingsId id, SettingsValue val)
void proxygen::HTTPSession::setFlowControl ( size_t  initialReceiveWindow,
size_t  receiveStreamWindowSize,
size_t  receiveSessionWindowSize 
)
overridevirtual

Set flow control properties on the session.

Parameters
initialReceiveWindowsize of initial receive window for all ingress streams; set via the initial SETTINGS frame
receiveStreamWindowSizeper-stream receive window for NEW streams; sent via a WINDOW_UPDATE frame
receiveSessionWindowSizeper-session receive window; sent via a WINDOW_UPDATE frame

Implements proxygen::HTTPSessionBase.

Definition at line 336 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, proxygen::HTTPCodec::getEgressSettings(), proxygen::INITIAL_WINDOW_SIZE, initialReceiveWindow_, receiveSessionWindowSize_, receiveStreamWindowSize_, proxygen::HTTPSessionBase::setReadBufferLimit(), proxygen::HTTPSettings::setSetting(), settings, and started_.

Referenced by HTTPUpstreamTest< SPDY3CodecPair >::commonSetUp(), CurlService::CurlClient::connectSuccess(), getByteEventTracker(), and proxygen::HTTPSessionAcceptor::onNewConnection().

338  {
339  CHECK(!started_);
340  initialReceiveWindow_ = initialReceiveWindow;
341  receiveStreamWindowSize_ = receiveStreamWindowSize;
342  receiveSessionWindowSize_ = receiveSessionWindowSize;
343  HTTPSessionBase::setReadBufferLimit(receiveSessionWindowSize);
344  HTTPSettings* settings = codec_->getEgressSettings();
345  if (settings) {
348  }
349 }
virtual HTTPSettings * getEgressSettings()
Definition: HTTPCodec.h:653
HTTPCodecFilterChain codec_
size_t receiveSessionWindowSize_
Definition: HTTPSession.h:976
void setReadBufferLimit(uint32_t limit)
size_t receiveStreamWindowSize_
Definition: HTTPSession.h:975
static http_parser_settings settings
Definition: test.c:1529
void setSetting(SettingsId id, SettingsValue val)
void proxygen::HTTPSession::setHeaderCodecStats ( HeaderCodec::Stats stats)
inlineoverridevirtual

Implements proxygen::HTTPSessionBase.

Definition at line 204 of file HTTPSession.h.

References proxygen::HTTPSessionBase::codec_, and proxygen::HTTPCodec::setHeaderCodecStats().

204  {
205  codec_->setHeaderCodecStats(stats);
206  }
HTTPCodecFilterChain codec_
virtual void setHeaderCodecStats(HeaderCodec::Stats *)
Definition: HTTPCodec.h:670
void proxygen::HTTPSession::setHTTP2PrioritiesEnabled ( bool  enabled)
inlineoverridevirtual
void proxygen::HTTPSession::setMaxConcurrentIncomingStreams ( uint32_t  num)
overridevirtual

Set the maximum number of transactions the remote can open at once.

Implements proxygen::HTTPSessionBase.

Definition at line 361 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, proxygen::HTTPCodec::getEgressSettings(), proxygen::MAX_CONCURRENT_STREAMS, maxConcurrentIncomingStreams_, proxygen::HTTPSettings::setSetting(), settings, started_, and proxygen::HTTPCodec::supportsParallelRequests().

Referenced by getSetupTransportInfo(), and proxygen::HTTPSessionAcceptor::onNewConnection().

361  {
362  CHECK(!started_);
365  HTTPSettings* settings = codec_->getEgressSettings();
366  if (settings) {
369  }
370  }
371 }
virtual HTTPSettings * getEgressSettings()
Definition: HTTPCodec.h:653
HTTPCodecFilterChain codec_
static http_parser_settings settings
Definition: test.c:1529
uint32_t maxConcurrentIncomingStreams_
Definition: HTTPSession.h:928
virtual bool supportsParallelRequests() const =0
void setSetting(SettingsId id, SettingsValue val)
void proxygen::HTTPSession::setNewTransactionPauseState ( HTTPCodec::StreamID  streamID)
protected

Definition at line 722 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::egressLimitExceeded(), findTransaction(), and numActiveWrites_.

Referenced by newExTransaction(), newPushedTransaction(), proxygen::HTTPUpstreamSession::newTransaction(), onHeadersSent(), and proxygen::HTTPDownstreamSession::setupOnHeadersComplete().

722  {
723  if (!egressLimitExceeded()) {
724  return;
725  }
726 
727  auto txn = findTransaction(streamID);
728  if (txn) {
729  // If writes are paused, start this txn off in the egress paused state
730  VLOG(4) << *this << " starting streamID=" << txn->getID()
731  << " egress paused, numActiveWrites_=" << numActiveWrites_;
732  txn->pauseEgress();
733  }
734 }
bool egressLimitExceeded() const
HTTPTransaction * findTransaction(HTTPCodec::StreamID streamID)
uint32_t streamID
Definition: SPDYCodec.cpp:131
void proxygen::HTTPSession::setSecondAuthManager ( std::unique_ptr< SecondaryAuthManager secondAuthManager)

Attach a SecondaryAuthManager to this session to control secondary certificate authentication in HTTP/2.

Definition at line 1816 of file HTTPSession.cpp.

References folly::gen::move, and secondAuthManager_.

Referenced by connCloseByRemote().

1817  {
1818  secondAuthManager_ = std::move(secondAuthManager);
1819 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
std::unique_ptr< SecondaryAuthManager > secondAuthManager_
Definition: HTTPSession.h:1055
void proxygen::HTTPSession::setSessionStats ( HTTPSessionStats stats)
overridevirtual

Reimplemented from proxygen::HTTPSessionBase.

Definition at line 329 of file HTTPSession.cpp.

References byteEventTracker_, and proxygen::HTTPSessionBase::setSessionStats().

Referenced by proxygen::HTTPUpstreamSession::attachThreadLocals(), proxygen::HTTPUpstreamSession::detachThreadLocals(), getByteEventTracker(), and proxygen::HTTPSessionAcceptor::onNewConnection().

329  {
331  if (byteEventTracker_) {
332  byteEventTracker_->setTTLBAStats(stats);
333  }
334 }
std::shared_ptr< ByteEventTracker > byteEventTracker_
Definition: HTTPSession.h:966
virtual void setSessionStats(HTTPSessionStats *stats)
void proxygen::HTTPSession::setupCodec ( )
private

Definition at line 243 of file HTTPSession.cpp.

References proxygen::FilterChain< T1, T2, FilterType, set_callback, TakeOwnership >::addFilters(), proxygen::FilterChain< T1, T2, FilterType, set_callback, TakeOwnership >::call(), proxygen::HTTPSessionBase::codec_, connFlowControl_, proxygen::HTTPCodec::generateConnectionPreface(), getCertAuthSettingVal(), proxygen::HTTPCodec::getEgressSettings(), isDownstream(), proxygen::MAX_CONCURRENT_STREAMS, maxConcurrentIncomingStreams_, maxConcurrentOutgoingStreamsRemote_, secondAuthManager_, proxygen::FilterChain< T1, T2, FilterType, set_callback, TakeOwnership >::setCallback(), proxygen::HTTPSettings::setSetting(), settings, proxygen::SETTINGS_HTTP_CERT_AUTH, proxygen::HTTPCodec::supportsParallelRequests(), proxygen::HTTPCodec::supportsSessionFlowControl(), uint32_t, and writeBuf_.

Referenced by getMaxConcurrentOutgoingStreamsRemote(), onNativeProtocolUpgradeImpl(), and proxygen::HTTPSession::WriteSegment::writeErr().

243  {
245  // until we support upstream pipelining
248  }
249 
250  // If a secondary authentication manager is configured for this session, set
251  // the SETTINGS_HTTP_CERT_AUTH to indicate support for HTTP-layer certificate
252  // authentication.
253  uint32_t certAuthSettingVal = 0;
254  if (secondAuthManager_) {
255  certAuthSettingVal = getCertAuthSettingVal();
256  }
257  HTTPSettings* settings = codec_->getEgressSettings();
258  if (settings) {
261  if (certAuthSettingVal != 0) {
262  settings->setSetting(SettingsId::SETTINGS_HTTP_CERT_AUTH,
263  certAuthSettingVal);
264  }
265  }
267 
269  connFlowControl_ = new FlowControlFilter(*this, writeBuf_, codec_.call());
270  codec_.addFilters(std::unique_ptr<FlowControlFilter>(connFlowControl_));
271  // if we really support switching from spdy <-> h2, we need to update
272  // existing flow control filter
273  }
274 
275  codec_.setCallback(this);
276 }
virtual HTTPSettings * getEgressSettings()
Definition: HTTPCodec.h:653
virtual bool supportsSessionFlowControl() const
Definition: HTTPCodec.h:374
HTTPCodecFilterChain codec_
FlowControlFilter * connFlowControl_
Definition: HTTPSession.h:913
std::enable_if< std::is_constructible< C >::value >::type addFilters()
Definition: FilterChain.h:301
static http_parser_settings settings
Definition: test.c:1529
uint32_t maxConcurrentIncomingStreams_
Definition: HTTPSession.h:928
uint32_t maxConcurrentOutgoingStreamsRemote_
Definition: HTTPSession.h:922
virtual size_t generateConnectionPreface(folly::IOBufQueue &)
Definition: HTTPCodec.h:475
void setCallback(T2 *cb) override
Definition: FilterChain.h:235
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
uint32_t getCertAuthSettingVal()
bool isDownstream() const
std::unique_ptr< SecondaryAuthManager > secondAuthManager_
Definition: HTTPSession.h:1055
virtual bool supportsParallelRequests() const =0
void setSetting(SettingsId id, SettingsValue val)
virtual void proxygen::HTTPSession::setupOnHeadersComplete ( HTTPTransaction txn,
HTTPMessage msg 
)
protectedpure virtual

Called by onHeadersComplete(). This function allows downstream and upstream to do any setup (like preparing a handler) when headers are first received from the remote side on a given transaction.

Implemented in proxygen::HTTPUpstreamSession, and proxygen::HTTPDownstreamSession.

Referenced by connCloseByRemote(), and onHeadersComplete().

bool proxygen::HTTPSession::shouldShutdown ( ) const
protected

Returns true iff this session should shutdown at this time. Default behavior is to not shutdown.

Definition at line 2497 of file HTTPSession.cpp.

References allTransactionsStarted(), proxygen::HTTPSessionBase::codec_, draining_, proxygen::HTTPCodec::isReusable(), isUpstream(), and proxygen::HTTPCodec::supportsParallelRequests().

Referenced by detach(), invokeOnAllTransactions(), and sendHeaders().

2497  {
2498  return draining_ &&
2501  isUpstream() ||
2502  !codec_->isReusable());
2503 }
HTTPCodecFilterChain codec_
bool isUpstream() const
virtual bool allTransactionsStarted() const =0
virtual bool isReusable() const =0
virtual bool supportsParallelRequests() const =0
void proxygen::HTTPSession::shutdownTransport ( bool  shutdownReads = true,
bool  shutdownWrites = true,
const std::string errorMsg = "" 
)
protected

Start closing the socket.

Parameters
shutdownReadsWhether to close the read side of the socket. All transactions which are not ingress complete will receive an error.
shutdownWritesWhether to close the write side of the socket. All transactions which are not egress complete will receive an error.
errorMsgadditional error information to pass to each transaction

Definition at line 2283 of file HTTPSession.cpp.

References byteEventTracker_, checkForShutdown(), proxygen::HTTPCodec::closeOnEgressComplete(), proxygen::HTTPSessionBase::codec_, folly::SocketAddress::describe(), proxygen::HTTPException::EGRESS, folly::pushmi::operators::error(), flowControlTimeout_, proxygen::HTTPCodec::generateGoaway(), proxygen::HTTPSessionBase::getConnectionCloseReason(), proxygen::getErrorString(), proxygen::HTTPCodec::getLastIncomingStreamID(), getPeerAddress(), folly::gen::guard(), hasMoreWrites(), proxygen::HTTPSessionBase::infoCallback_, proxygen::HTTPException::INGRESS, proxygen::HTTPException::INGRESS_AND_EGRESS, invokeOnAllTransactions(), proxygen::IO_WRITE_ERROR, folly::HHWheelTimer::Callback::isScheduled(), proxygen::kErrorConnectionReset, proxygen::kErrorEOF, proxygen::kErrorSSL, proxygen::kErrorTimeout, proxygen::kErrorWrite, proxygen::NO_ERROR, proxygen::HTTPTransaction::onError(), proxygen::HTTPSessionBase::InfoCallback::onIngressEOF(), proxygen::HTTPCodec::onIngressEOF(), proxygen::HTTPSessionBase::InfoCallback::onIngressError(), reads_, readsShutdown(), resetAfterDrainingWrites_, resetSocketOnShutdown_, scheduleWrite(), proxygen::HTTPSessionBase::setCloseReason(), proxygen::HTTPCodec::setParserPaused(), proxygen::Exception::setProxygenError(), proxygen::SHUTDOWN, sock_, wangle::TransportInfo::sslError, proxygen::TIMEOUT, transactions_, proxygen::HTTPSessionBase::transportInfo_, proxygen::UNKNOWN, writeBuf_, writes_, writesDraining_, and writesShutdown().

Referenced by detach(), drain(), dropConnection(), flowControlTimeoutExpired(), isDraining(), onDeleteAckEvent(), onEgressMessageFinished(), onError(), onMessageComplete(), onSessionParseError(), onWriteCompleted(), onWriteSuccess(), readEOF(), readErr(), and proxygen::HTTPSession::ShutdownTransportCallback::runLoopCallback().

2285  {
2286  DestructorGuard guard(this);
2287 
2288  // shutdowns not accounted for, shouldn't see any
2290 
2291  VLOG(4) << "shutdown request for " << *this << ": reads="
2292  << shutdownReads << " (currently " << readsShutdown()
2293  << "), writes=" << shutdownWrites << " (currently "
2294  << writesShutdown() << ")";
2295 
2296  bool notifyEgressShutdown = false;
2297  bool notifyIngressShutdown = false;
2298 
2300  if (!transportInfo_.sslError.empty()) {
2301  error = kErrorSSL;
2302  } else if (sock_->error()) {
2303  VLOG(3) << "shutdown request for " << *this
2304  << " on bad socket. Shutting down writes too.";
2306  error = kErrorWrite;
2307  } else {
2308  error = kErrorConnectionReset;
2309  }
2310  shutdownWrites = true;
2312  error = kErrorTimeout;
2313  } else {
2314  error = kErrorEOF;
2315  }
2316 
2317  if (shutdownReads && !shutdownWrites && flowControlTimeout_.isScheduled()) {
2318  // reads are dead and writes are blocked on a window update that will never
2319  // come. shutdown writes too.
2320  VLOG(4) << *this << " Converting read shutdown to read/write due to"
2321  " flow control";
2322  shutdownWrites = true;
2323  }
2324 
2325  if (shutdownWrites && !writesShutdown()) {
2329  scheduleWrite();
2330  }
2331  if (!hasMoreWrites() &&
2332  (transactions_.empty() || codec_->closeOnEgressComplete())) {
2334  if (byteEventTracker_) {
2335  byteEventTracker_->drainByteEvents();
2336  }
2338  VLOG(4) << *this << " writes drained, sending RST";
2339  resetSocketOnShutdown_ = true;
2340  shutdownReads = true;
2341  } else {
2342  VLOG(4) << *this << " writes drained, closing";
2343  sock_->shutdownWriteNow();
2344  }
2345  notifyEgressShutdown = true;
2346  } else if (!writesDraining_) {
2347  writesDraining_ = true;
2348  notifyEgressShutdown = true;
2349  } // else writes are already draining; don't double notify
2350  }
2351 
2352  if (shutdownReads && !readsShutdown()) {
2353  notifyIngressShutdown = true;
2354  // TODO: send an RST if readBuf_ is non empty?
2355  sock_->setReadCB(nullptr);
2357  if (!transactions_.empty() && error == kErrorConnectionReset) {
2358  if (infoCallback_ != nullptr) {
2359  infoCallback_->onIngressError(*this, error);
2360  }
2361  } else if (error == kErrorEOF) {
2362  // Report to the codec that the ingress stream has ended
2363  codec_->onIngressEOF();
2364  if (infoCallback_) {
2366  }
2367  }
2368  // Once reads are shutdown the parser should stop processing
2369  codec_->setParserPaused(true);
2370  }
2371 
2372  if (notifyIngressShutdown || notifyEgressShutdown) {
2373  auto dir = (notifyIngressShutdown && notifyEgressShutdown)
2375  : (notifyIngressShutdown ? HTTPException::Direction::INGRESS
2377  HTTPException ex(
2378  dir,
2379  folly::to<std::string>("Shutdown transport: ", getErrorString(error),
2380  errorMsg.empty() ? "" : " ", errorMsg, ", ",
2381  getPeerAddress().describe()));
2382  ex.setProxygenError(error);
2384  }
2385 
2386  // Close the socket only after the onError() callback on the txns
2387  // and handler has been detached.
2388  checkForShutdown();
2389 }
void onError(const HTTPException &error)
void invokeOnAllTransactions(void(HTTPTransaction::*fn)(Args1...), Args2 &&...args)
Definition: HTTPSession.h:584
virtual bool closeOnEgressComplete() const =0
HTTPCodecFilterChain codec_
virtual void onIngressError(const HTTPSessionBase &, ProxygenError)
folly::AsyncTransportWrapper::UniquePtr sock_
Definition: HTTPSession.h:697
std::string describe() const
requires And< SemiMovable< VN >... > &&SemiMovable< E > auto error(E e)
Definition: error.h:48
const folly::SocketAddress & getPeerAddress() const noexceptoverride
Definition: HTTPSession.h:126
ConnectionCloseReason getConnectionCloseReason() const
virtual void onIngressEOF()=0
void setCloseReason(ConnectionCloseReason reason)
GuardImpl guard(ErrorHandler &&handler)
Definition: Base.h:840
bool readsShutdown() const
Definition: HTTPSession.h:634
bool writesShutdown() const
Definition: HTTPSession.h:646
std::map< HTTPCodec::StreamID, HTTPTransaction > transactions_
Definition: HTTPSession.h:692
virtual StreamID getLastIncomingStreamID() const
Definition: HTTPCodec.h:675
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
std::shared_ptr< ByteEventTracker > byteEventTracker_
Definition: HTTPSession.h:966
virtual size_t generateGoaway(folly::IOBufQueue &writeBuf, StreamID lastStream, ErrorCode code, std::unique_ptr< folly::IOBuf > debugData=nullptr)=0
FlowControlTimeout flowControlTimeout_
Definition: HTTPSession.h:1020
virtual void setParserPaused(bool paused)=0
bool hasMoreWrites() const
wangle::TransportInfo transportInfo_
const char * getErrorString(ProxygenError error)
void proxygen::HTTPSession::shutdownTransportWithReset ( ProxygenError  errorCode,
const std::string errorMsg = "" 
)
protected

Immediately close the socket in both directions, discarding any queued writes that haven't yet been transferred to the kernel, and send a RST to the client. All transactions receive onWriteError.

Parameters
errorCodeError code sent with the onWriteError to transactions.
errorMsgError string included in the final error msg.

Definition at line 2391 of file HTTPSession.cpp.

References byteEventTracker_, folly::EventBase::LoopCallback::cancelLoopCallback(), folly::HHWheelTimer::Callback::cancelTimeout(), checkForShutdown(), destroy(), errorOnAllTransactions(), folly::gen::guard(), folly::EventBase::LoopCallback::isLoopCallbackScheduled(), folly::IOBufQueue::move(), numActiveWrites_, pendingWrites_, reads_, readsShutdown(), resetSocketOnShutdown_, proxygen::SHUTDOWN, sock_, writeBuf_, writes_, writesShutdown(), and writeTimeout_.

Referenced by dropConnection(), isDraining(), onWriteError(), and writeTimeoutExpired().

2393  {
2394  DestructorGuard guard(this);
2395  VLOG(4) << "shutdownTransportWithReset";
2396 
2397  if (!readsShutdown()) {
2398  sock_->setReadCB(nullptr);
2400  }
2401 
2402  if (!writesShutdown()) {
2405  while (!pendingWrites_.empty()) {
2406  pendingWrites_.front().detach();
2407  numActiveWrites_--;
2408  }
2409  VLOG(4) << *this << " cancel write timer";
2411  resetSocketOnShutdown_ = true;
2412  }
2413 
2414  errorOnAllTransactions(errorCode, errorMsg);
2415  // drainByteEvents() can call detach(txn), which can in turn call
2416  // shutdownTransport if we were already draining. To prevent double
2417  // calling onError() to the transactions, we call drainByteEvents()
2418  // after we've given the explicit error.
2419  if (byteEventTracker_) {
2420  byteEventTracker_->drainByteEvents();
2421  }
2422 
2423  // HTTPTransaction::onError could theoretically schedule more callbacks,
2424  // so do this last.
2425  if (isLoopCallbackScheduled()) {
2427  }
2428  // onError() callbacks or drainByteEvents() could result in txns detaching
2429  // due to CallbackGuards going out of scope. Close the socket only after
2430  // the txns are detached.
2431  checkForShutdown();
2432 }
void errorOnAllTransactions(ProxygenError err, const std::string &errorMsg)
WriteTimeout writeTimeout_
Definition: HTTPSession.h:681
folly::AsyncTransportWrapper::UniquePtr sock_
Definition: HTTPSession.h:697
std::unique_ptr< folly::IOBuf > move()
Definition: IOBufQueue.h:459
static void destroy()
WriteSegmentList pendingWrites_
Definition: HTTPSession.h:908
bool isLoopCallbackScheduled() const
Definition: EventBase.h:160
GuardImpl guard(ErrorHandler &&handler)
Definition: Base.h:840
bool readsShutdown() const
Definition: HTTPSession.h:634
bool writesShutdown() const
Definition: HTTPSession.h:646
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
std::shared_ptr< ByteEventTracker > byteEventTracker_
Definition: HTTPSession.h:966
void proxygen::HTTPSession::startNow ( )
overridevirtual

Start reading from the transport and send any introductory messages to the remote side. This function must be called once per session to begin reads.

Implements proxygen::HTTPSessionBase.

Reimplemented in proxygen::HTTPUpstreamSession.

Definition at line 297 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, connFlowControl_, draining_, proxygen::HTTPCodec::generateGoaway(), proxygen::HTTPCodec::generateSettings(), getGracefulGoawayAck(), proxygen::NO_ERROR, receiveSessionWindowSize_, resumeReads(), scheduleWrite(), proxygen::FlowControlFilter::setReceiveWindowSize(), started_, and writeBuf_.

Referenced by getSetupTransportInfo(), proxygen::HTTPDownstreamSession::startNow(), and proxygen::HTTPUpstreamSession::startNow().

297  {
298  CHECK(!started_);
299  started_ = true;
301  if (connFlowControl_) {
304  }
305  // For HTTP/2 if we are currently draining it means we got notified to
306  // shutdown before we sent a SETTINGS frame, so we defer sending a GOAWAY
307  // util we've started and sent SETTINGS.
308  if (draining_) {
312  }
313  scheduleWrite();
314  resumeReads();
315 }
HTTPCodecFilterChain codec_
size_t receiveSessionWindowSize_
Definition: HTTPSession.h:976
FlowControlFilter * connFlowControl_
Definition: HTTPSession.h:913
void setReceiveWindowSize(folly::IOBufQueue &writeBuf, uint32_t capacity)
HTTPCodec::StreamID getGracefulGoawayAck() const
folly::IOBufQueue writeBuf_
Definition: HTTPSession.h:684
virtual size_t generateSettings(folly::IOBufQueue &)
Definition: HTTPCodec.h:592
virtual size_t generateGoaway(folly::IOBufQueue &writeBuf, StreamID lastStream, ErrorCode code, std::unique_ptr< folly::IOBuf > debugData=nullptr)=0
void proxygen::HTTPSession::timeoutExpired ( )
inlineoverridevirtualnoexcept
void proxygen::HTTPSession::transactionTimeout ( HTTPTransaction txn)
overrideprotectedvirtualnoexcept

Implements proxygen::HTTPTransaction::Transport.

Definition at line 1537 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::codec_, getTransactionTimeoutHandler(), handler(), proxygen::HTTPSessionBase::infoCallback_, ingressError_, proxygen::kErrorTimeout, proxygen::HTTPSessionBase::InfoCallback::onIngressError(), and proxygen::HTTPCodec::supportsParallelRequests().

Referenced by numIncomingStreams().

1537  {
1538  // A transaction has timed out. If the transaction does not have
1539  // a Handler yet, because we haven't yet received the full request
1540  // headers, we give it a DirectResponseHandler that generates an
1541  // error page.
1542  VLOG(3) << "Transaction timeout for streamID=" << txn->getID();
1543  if (!codec_->supportsParallelRequests()) {
1544  // this error should only prevent us from reading/handling more errors
1545  // on serial streams
1546  ingressError_ = true;
1547  }
1548 
1549  if (!txn->getHandler() &&
1550  txn->getEgressState() == HTTPTransactionEgressSM::State::Start) {
1551  VLOG(4) << *this << " Timed out receiving headers";
1552  if (infoCallback_) {
1554  }
1556  // This can only happen with HTTP/2 where the HEADERS frame is incomplete
1557  // and we time out waiting for the CONTINUATION. Abort the request.
1558  //
1559  // It would maybe be a little nicer to use the timeout handler for these
1560  // also.
1561  txn->sendAbort();
1562  return;
1563  }
1564 
1565  VLOG(4) << *this << " creating direct error handler";
1567  txn->setHandler(handler);
1568  }
1569 
1570  // Tell the transaction about the timeout. The transaction will
1571  // communicate the timeout to the handler, and the handler will
1572  // decide how to proceed.
1573  txn->onIngressTimeout();
1574 }
HTTPCodecFilterChain codec_
virtual void onIngressError(const HTTPSessionBase &, ProxygenError)
virtual HTTPTransaction::Handler * getTransactionTimeoutHandler(HTTPTransaction *txn)=0
void handler(int, siginfo_t *, void *)
virtual bool supportsParallelRequests() const =0
void proxygen::HTTPSession::updateWriteBufSize ( int64_t  delta)
protected

Definition at line 2249 of file HTTPSession.cpp.

References proxygen::HTTPSessionBase::egressLimitExceeded(), inResume_, invokeOnAllTransactions(), proxygen::HTTPTransaction::pauseEgress(), pendingPause_, pendingWriteSizeDelta_, resumeTransactions(), and proxygen::HTTPSessionBase::updatePendingWriteSize().

Referenced by isDraining(), notifyEgressBodyBuffered(), onWriteSuccess(), and runLoopCallback().

2249  {
2250  // This is the sum of body bytes buffered within transactions_ and in
2251  // the sock_'s write buffer.
2252  delta += pendingWriteSizeDelta_;
2254  bool wasExceeded = egressLimitExceeded();
2255  updatePendingWriteSize(delta);
2256 
2257  if (egressLimitExceeded() && !wasExceeded) {
2258  // Exceeded limit. Pause reading on the incoming stream.
2259  if (inResume_) {
2260  VLOG(3) << "Pausing txn egress for " << *this << " deferred";
2261  pendingPause_ = true;
2262  } else {
2263  VLOG(3) << "Pausing txn egress for " << *this;
2265  }
2266  } else if (!egressLimitExceeded() && wasExceeded) {
2267  // Dropped below limit. Resume reading on the incoming stream if needed.
2268  if (inResume_) {
2269  if (pendingPause_) {
2270  VLOG(3) << "Cancel deferred txn egress pause for " << *this;
2271  pendingPause_ = false;
2272  } else {
2273  VLOG(3) << "Ignoring redundant resume for " << *this;
2274  }
2275  } else {
2276  VLOG(3) << "Resuming txn egress for " << *this;
2278  }
2279  }
2280 }
bool egressLimitExceeded() const
void invokeOnAllTransactions(void(HTTPTransaction::*fn)(Args1...), Args2 &&...args)
Definition: HTTPSession.h:584
void updatePendingWriteSize(int64_t delta)
int64_t pendingWriteSizeDelta_
Definition: HTTPSession.h:954
void proxygen::HTTPSession::updateWriteCount ( )
protected

Update the size of the unwritten egress data and invoke callbacks if the size has crossed the buffering limit.

Definition at line 2236 of file HTTPSession.cpp.

References numActiveWrites_, writes_, writesPaused(), and writesUnpaused().

Referenced by isDraining(), onWriteSuccess(), and runLoopCallback().

2236  {
2237  if (numActiveWrites_ > 0 && writesUnpaused()) {
2238  // Exceeded limit. Pause reading on the incoming stream.
2239  VLOG(3) << "Pausing egress for " << *this;
2240  writes_ = SocketState::PAUSED;
2241  } else if (numActiveWrites_ == 0 && writesPaused()) {
2242  // Dropped below limit. Resume reading on the incoming stream if needed.
2243  VLOG(3) << "Resuming egress for " << *this;
2244  writes_ = SocketState::UNPAUSED;
2245  }
2246 }
bool writesPaused() const
Definition: HTTPSession.h:642
bool writesUnpaused() const
Definition: HTTPSession.h:638
bool proxygen::HTTPSession::verifyCertAuthSetting ( uint32_t  value)
private

Definition at line 211 of file HTTPSession.cpp.

References folly::IOBuf::computeChainDataLength(), fizz::extensions::test::ekm, getTransport(), folly::AsyncTransportWrapper::getUnderlyingTransport(), isUpstream(), fizz::test::label, uint16_t, and uint32_t.

Referenced by getMaxConcurrentOutgoingStreamsRemote(), and onSettings().

211  {
212  uint32_t certAuthSettingVal = 0;
213  constexpr uint16_t settingLen = 4;
214  std::unique_ptr<folly::IOBuf> ekm;
216  if (isUpstream()) {
217  label = kServerLabel;
218  } else {
219  label = kClientLabel;
220  }
221  auto fizzBase = getTransport()->getUnderlyingTransport<AsyncFizzBase>();
222  if (fizzBase) {
223  ekm = fizzBase->getEkm(label, nullptr, settingLen);
224  } else {
225  VLOG(4) << "Underlying transport does not support secondary "
226  "authentication.";
227  return false;
228  }
229  if (ekm && ekm->computeChainDataLength() == settingLen) {
230  folly::io::Cursor cursor(ekm.get());
231  uint32_t ekmVal = cursor.readBE<uint32_t>();
232  certAuthSettingVal = (ekmVal & 0x3fffffff) | 0x80000000;
233  } else {
234  return false;
235  }
236  if (certAuthSettingVal == value) {
237  return true;
238  } else {
239  return false;
240  }
241 }
folly::AsyncTransportWrapper * getTransport() override
Definition: HTTPSession.h:61
bool isUpstream() const
const T * getUnderlyingTransport() const
static const char *const value
Definition: Conv.cpp:50
std::size_t computeChainDataLength() const
Definition: IOBuf.cpp:501
StringPiece label
bool proxygen::HTTPSession::writesPaused ( ) const
inlineprotected

Definition at line 642 of file HTTPSession.h.

References writes_.

Referenced by proxygen::HTTPUpstreamSession::isDetachable(), and updateWriteCount().

642  {
643  return writes_ == SocketState::PAUSED;
644  }
bool proxygen::HTTPSession::writesUnpaused ( ) const
inlineprotected

Definition at line 638 of file HTTPSession.h.

References writes_.

Referenced by updateWriteCount().

638  {
639  return writes_ == SocketState::UNPAUSED;
640  }
void proxygen::HTTPSession::writeTimeoutExpired ( )
protectednoexcept

Definition at line 414 of file HTTPSession.cpp.

References g(), proxygen::kErrorWriteTimeout, pendingWrites_, proxygen::HTTPSessionBase::setCloseReason(), shutdownTransportWithReset(), and proxygen::TIMEOUT.

Referenced by getHTTPPriority(), and proxygen::HTTPSession::WriteTimeout::timeoutExpired().

414  {
415  VLOG(4) << "Write timeout for " << *this;
416 
417  CHECK(!pendingWrites_.empty());
418  DestructorGuard g(this);
419 
422 }
WriteSegmentList pendingWrites_
Definition: HTTPSession.h:908
void setCloseReason(ConnectionCloseReason reason)
g_t g(f_t)
void shutdownTransportWithReset(ProxygenError errorCode, const std::string &errorMsg="")

Member Data Documentation

uint64_t proxygen::HTTPSession::bodyBytesPerWriteBuf_ {0}
private

Number of body un-encoded bytes in the write buffer per write iteration.

Definition at line 959 of file HTTPSession.h.

Referenced by runLoopCallback(), and sendBody().

uint64_t proxygen::HTTPSession::bytesScheduled_ {0}
private

Number of bytes scheduled so far.

Definition at line 948 of file HTTPSession.h.

Referenced by onPingRequest(), runLoopCallback(), and sessionByteOffset().

uint64_t proxygen::HTTPSession::bytesWritten_ {0}
private

Number of bytes written so far.

Definition at line 943 of file HTTPSession.h.

Referenced by getNextToSend(), and onWriteSuccess().

FlowControlFilter* proxygen::HTTPSession::connFlowControl_ {nullptr}
private

Connection level flow control for SPDY >= 3.1 and HTTP/2

Definition at line 913 of file HTTPSession.h.

Referenced by getNextToSend(), isConnWindowFull(), notifyIngressBodyProcessed(), onBody(), onNativeProtocolUpgradeImpl(), runLoopCallback(), setupCodec(), and startNow().

bool proxygen::HTTPSession::draining_
protected

Indicates if the session is waiting for existing transactions to close. Once all transactions close, the session will be deleted.

Definition at line 711 of file HTTPSession.h.

Referenced by drain(), proxygen::HTTPUpstreamSession::isClosing(), isDraining(), newExTransaction(), newPushedTransaction(), proxygen::HTTPUpstreamSession::newTransaction(), shouldShutdown(), startNow(), and proxygen::HTTPSession::WriteSegment::writeErr().

DrainTimeout proxygen::HTTPSession::drainTimeout_
private
uint64_t proxygen::HTTPSession::egressBytesLimit_ {0}
private

Max number of bytes to egress per session

Definition at line 971 of file HTTPSession.h.

Referenced by onWriteSuccess(), and setEgressBytesLimit().

uint32_t proxygen::HTTPSession::incomingStreams_ {0}
private

The number of concurrent transactions initiated by this sessions's peer

Definition at line 938 of file HTTPSession.h.

Referenced by createTransaction(), decrementTransactionCount(), getNumIncomingStreams(), getPipelineStreamCount(), and numIncomingStreams().

bool proxygen::HTTPSession::ingressError_
protected
bool proxygen::HTTPSession::ingressUpgraded_
private

Indicates whether an upgrade request has been received from the codec.

Definition at line 1047 of file HTTPSession.h.

Referenced by onMessageComplete(), proxygen::HTTPSession::ShutdownTransportCallback::runLoopCallback(), and proxygen::HTTPSession::WriteSegment::writeErr().

size_t proxygen::HTTPSession::initialReceiveWindow_ {0}
private
bool proxygen::HTTPSession::inLoopCallback_
private
bool proxygen::HTTPSession::inResume_
private
uint32_t proxygen::HTTPSession::liveTransactions_ {0}
protected
uint32_t proxygen::HTTPSession::maxConcurrentIncomingStreams_ {100}
private

The maximum number of concurrent transactions that this session's peer may create.

Definition at line 928 of file HTTPSession.h.

Referenced by onNativeProtocolUpgradeImpl(), setMaxConcurrentIncomingStreams(), setupCodec(), and proxygen::HTTPSession::WriteSegment::writeErr().

uint32_t proxygen::HTTPSession::maxConcurrentOutgoingStreamsRemote_ {100000}
private

The received setting for the maximum number of concurrent transactions that this session may create. We may assume the remote allows unlimited transactions until we get a SETTINGS frame, but to be reasonable, assume the remote doesn't allow more than 100K concurrent transactions on one connection.

Definition at line 922 of file HTTPSession.h.

Referenced by getMaxConcurrentOutgoingStreamsRemote(), newExTransaction(), newPushedTransaction(), onNativeProtocolUpgradeImpl(), onSetMaxInitiatedStreams(), and setupCodec().

HTTP2PriorityQueue::NextEgressResult proxygen::HTTPSession::nextEgressResults_
private

Container to hold the results of HTTP2PriorityQueue::nextEgress

Definition at line 964 of file HTTPSession.h.

Referenced by getNextToSend(), and proxygen::HTTPSession::WriteSegment::writeErr().

unsigned proxygen::HTTPSession::numActiveWrites_ {0}
protected

Number of writes submitted to the transport for which we haven't yet received completion or failure callbacks.

Definition at line 705 of file HTTPSession.h.

Referenced by getNextToSend(), hasMoreWrites(), proxygen::HTTPUpstreamSession::isReusable(), onWriteCompleted(), onWriteSuccess(), runLoopCallback(), setNewTransactionPauseState(), shutdownTransportWithReset(), and updateWriteCount().

uint32_t proxygen::HTTPSession::outgoingStreams_ {0}
private

The number concurrent transactions initiated by this session

Definition at line 933 of file HTTPSession.h.

Referenced by decrementTransactionCount(), getNumOutgoingStreams(), incrementOutgoingStreams(), newExTransaction(), newPushedTransaction(), and numOutgoingStreams().

bool proxygen::HTTPSession::pendingPause_
private
WriteSegmentList proxygen::HTTPSession::pendingWrites_
private
int64_t proxygen::HTTPSession::pendingWriteSizeDelta_ {0}
private

The net change this event loop in the amount of buffered bytes for all this session's txns and socket write buffer.

Definition at line 954 of file HTTPSession.h.

Referenced by notifyEgressBodyBuffered(), runLoopCallback(), sendBody(), and updateWriteBufSize().

folly::IOBufQueue proxygen::HTTPSession::readBuf_ {folly::IOBufQueue::cacheChainLength()}
protected

Chain of ingress IOBufs

Definition at line 687 of file HTTPSession.h.

Referenced by getReadBuffer(), processReadData(), readBufferAvailable(), readDataAvailable(), and readEOF().

size_t proxygen::HTTPSession::receiveSessionWindowSize_ {0}
private
size_t proxygen::HTTPSession::receiveStreamWindowSize_ {0}
private
bool proxygen::HTTPSession::resetAfterDrainingWrites_
protected
bool proxygen::HTTPSession::resetSocketOnShutdown_
private
std::unique_ptr<SecondaryAuthManager> proxygen::HTTPSession::secondAuthManager_
private
std::unique_ptr<ShutdownTransportCallback> proxygen::HTTPSession::shutdownTransportCb_
private
std::list<ReplaySafetyCallback*> proxygen::HTTPSession::waitingForReplaySafety_
private
bool proxygen::HTTPSession::writesDraining_
protected

The documentation for this class was generated from the following files: