diff --git a/quic/QuicConstants.h b/quic/QuicConstants.h index 3d1ed10c8..48c6c67d1 100644 --- a/quic/QuicConstants.h +++ b/quic/QuicConstants.h @@ -469,7 +469,7 @@ constexpr std::string_view kCongestionControlCopaStr = "copa"; constexpr std::string_view kCongestionControlCopa2Str = "copa2"; constexpr std::string_view kCongestionControlNewRenoStr = "newreno"; constexpr std::string_view kCongestionControlStaticCwndStr = "staticcwnd"; -constexpr std::string_view kCongestionControlNoneStr = "none"; +constexpr std::string_view kCongestionControlNoneStr = "std::nullopt"; constexpr DurationRep kPersistentCongestionThreshold = 3; enum class CongestionControlType : uint8_t { diff --git a/quic/QuicException.h b/quic/QuicException.h index a7dcde4bb..e243feb50 100644 --- a/quic/QuicException.h +++ b/quic/QuicException.h @@ -35,6 +35,10 @@ struct QuicError { return code == other.code && message == other.message; } + bool operator!=(const QuicError& other) const { + return !(*this == other); + } + QuicErrorCode code; std::string message; }; diff --git a/quic/api/QuicAckScheduler.cpp b/quic/api/QuicAckScheduler.cpp index 8f95829a7..c80061cef 100644 --- a/quic/api/QuicAckScheduler.cpp +++ b/quic/api/QuicAckScheduler.cpp @@ -23,7 +23,7 @@ bool hasAcksToSchedule(const AckState& ackState) { Optional largestAckToSend(const AckState& ackState) { if (ackState.acks.empty()) { - return none; + return std::nullopt; } return ackState.acks.back().end; } @@ -44,7 +44,7 @@ folly::Expected, QuicError> AckScheduler::writeNextAcks( : conn_.transportSettings.ackDelayExponent; auto largestAckedPacketNum = *largestAckToSend(ackState_); auto ackingTime = Clock::now(); - DCHECK(ackState_.largestRecvdPacketTime.hasValue()) + DCHECK(ackState_.largestRecvdPacketTime.has_value()) << "Missing received time for the largest acked packet"; // assuming that we're going to ack the largest received with highest pri auto receivedTime = *ackState_.largestRecvdPacketTime; @@ -108,7 +108,7 @@ folly::Expected, QuicError> AckScheduler::writeNextAcks( } if (!ackWriteResult.value()) { - return none; + return std::nullopt; } return largestAckedPacketNum; diff --git a/quic/api/QuicPacketScheduler.cpp b/quic/api/QuicPacketScheduler.cpp index 1b49428dd..297baeba8 100644 --- a/quic/api/QuicPacketScheduler.cpp +++ b/quic/api/QuicPacketScheduler.cpp @@ -355,7 +355,7 @@ FrameScheduler::scheduleFramesForPacket( } return SchedulingResult( - none, std::move(builder).buildPacket(), shortHeaderPadding); + std::nullopt, std::move(builder).buildPacket(), shortHeaderPadding); } bool FrameScheduler::hasData() const { @@ -401,7 +401,7 @@ bool StreamFrameScheduler::writeStreamLossBuffers( bufferLen, // writeBufferLen -- only the len of the single buffer. bufferLen, // flowControlLen -- not relevant, already flow controlled. buffer->eof, - none /* skipLenHint */, + std::nullopt /* skipLenHint */, stream.groupId); if (res.hasError()) { throw QuicInternalException( @@ -650,7 +650,7 @@ bool StreamFrameScheduler::writeStreamFrame( bufferLen, flowControlLen, canWriteFin, - none /* skipLenHint */, + std::nullopt /* skipLenHint */, stream.groupId); if (res.hasError()) { throw QuicInternalException( @@ -1085,7 +1085,7 @@ CloningScheduler::scheduleFramesForPacket( conn_.bufAccessor->trimEnd(conn_.bufAccessor->length() - prevSize); } } - return SchedulingResult(none, none, 0); + return SchedulingResult(std::nullopt, std::nullopt, 0); } folly::StringPiece CloningScheduler::name() const { diff --git a/quic/api/QuicSocketLite.h b/quic/api/QuicSocketLite.h index 15cd64fea..5b5c5cb1a 100644 --- a/quic/api/QuicSocketLite.h +++ b/quic/api/QuicSocketLite.h @@ -369,7 +369,7 @@ class QuicSocketLite { * StopSending. By default when cb is nullptr this function will cause the * transport to send a StopSending frame with * GenericApplicationErrorCode::NO_ERROR. If err is specified to be - * none, no StopSending will be sent. + * std::nullopt, no StopSending will be sent. * * Users should remove the callback via setReadCallback(id, nullptr) after * reading an error or eof to allow streams to be reaped by the transport. @@ -730,7 +730,7 @@ class QuicSocketLite { */ virtual void cancelByteEventCallbacksForStream( const StreamId id, - const Optional& offset = none) = 0; + const Optional& offset = std::nullopt) = 0; /** * Cancel byte event callbacks for given type and stream. @@ -741,7 +741,7 @@ class QuicSocketLite { virtual void cancelByteEventCallbacksForStream( const ByteEvent::Type type, const StreamId id, - const Optional& offset = none) = 0; + const Optional& offset = std::nullopt) = 0; /** * Sets the size of the given stream's receive window, or the connection @@ -879,7 +879,7 @@ class QuicSocketLite { /** * Get the negotiated ALPN. If called before the transport is ready - * returns none + * returns std::nullopt */ virtual Optional getAppProtocol() const = 0; @@ -888,7 +888,7 @@ class QuicSocketLite { */ virtual uint64_t getConnectionBufferAvailable() const = 0; - // Returns none before the handshake is complete, otherwise is always + // Returns std::nullopt before the handshake is complete, otherwise is always // non-empty. virtual Optional> getPeerTransportParams() const = 0; diff --git a/quic/api/QuicStreamAsyncTransport.cpp b/quic/api/QuicStreamAsyncTransport.cpp index 11ff6f054..99d53b45e 100644 --- a/quic/api/QuicStreamAsyncTransport.cpp +++ b/quic/api/QuicStreamAsyncTransport.cpp @@ -37,7 +37,7 @@ void QuicStreamAsyncTransport::setSocket( } void QuicStreamAsyncTransport::setStreamId(quic::StreamId id) { - CHECK(!id_.hasValue()) << "stream id can only be set once"; + CHECK(!id_.has_value()) << "stream id can only be set once"; CHECK(state_ == CloseState::OPEN) << "Current state: " << (int)state_; id_ = id; @@ -238,7 +238,7 @@ bool QuicStreamAsyncTransport::isPending() const { } bool QuicStreamAsyncTransport::connecting() const { - return !id_.hasValue() && (state_ == CloseState::OPEN); + return !id_.has_value() && (state_ == CloseState::OPEN); } bool QuicStreamAsyncTransport::error() const { diff --git a/quic/api/QuicTransportBase.cpp b/quic/api/QuicTransportBase.cpp index 93e131fbb..e54e491b6 100644 --- a/quic/api/QuicTransportBase.cpp +++ b/quic/api/QuicTransportBase.cpp @@ -109,7 +109,7 @@ void QuicTransportBase::closeGracefully() { QuicError(QuicErrorCode(LocalErrorCode::NO_ERROR), "Graceful Close")); // All streams are closed, close the transport for realz. if (conn_->streamManager->streamCount() == 0) { - closeImpl(none); + closeImpl(std::nullopt); } } @@ -391,7 +391,7 @@ QuicTransportBase::consume(StreamId id, uint64_t offset, size_t amount) { using ConsumeError = std::pair>; if (closeState_ != CloseState::OPEN) { return folly::makeUnexpected( - ConsumeError{LocalErrorCode::CONNECTION_CLOSED, none}); + ConsumeError{LocalErrorCode::CONNECTION_CLOSED, std::nullopt}); } [[maybe_unused]] auto self = sharedGuard(); SCOPE_EXIT { @@ -419,11 +419,11 @@ QuicTransportBase::consume(StreamId id, uint64_t offset, size_t amount) { if (stream->streamReadError) { switch (stream->streamReadError->type()) { case QuicErrorCode::Type::LocalErrorCode: - return folly::makeUnexpected( - ConsumeError{*stream->streamReadError->asLocalErrorCode(), none}); + return folly::makeUnexpected(ConsumeError{ + *stream->streamReadError->asLocalErrorCode(), std::nullopt}); default: return folly::makeUnexpected( - ConsumeError{LocalErrorCode::INTERNAL_ERROR, none}); + ConsumeError{LocalErrorCode::INTERNAL_ERROR, std::nullopt}); } } @@ -541,7 +541,8 @@ void QuicTransportBase::schedulePingTimeout( void QuicTransportBase::setAckRxTimestampsEnabled(bool enableAckRxTimestamps) { if (!enableAckRxTimestamps) { - conn_->transportSettings.maybeAckReceiveTimestampsConfigSentToPeer.clear(); + conn_->transportSettings.maybeAckReceiveTimestampsConfigSentToPeer = + std::nullopt; } } diff --git a/quic/api/QuicTransportBaseLite.cpp b/quic/api/QuicTransportBaseLite.cpp index 0367d5d2a..2edd35286 100644 --- a/quic/api/QuicTransportBaseLite.cpp +++ b/quic/api/QuicTransportBaseLite.cpp @@ -373,7 +373,7 @@ Optional QuicTransportBaseLite::shutdownWrite(StreamId id) { if (isReceivingStream(conn_->nodeType, id)) { return LocalErrorCode::INVALID_OPERATION; } - return none; + return std::nullopt; } folly::Expected @@ -698,7 +698,7 @@ Optional QuicTransportBaseLite::setControlStream(StreamId id) { auto stream = conn_->streamManager->getStream(id).value_or(nullptr); CHECK(stream) << "Invalid stream in " << __func__ << ": " << id; conn_->streamManager->setStreamAsControl(*stream); - return none; + return std::nullopt; } folly::Expected @@ -1222,7 +1222,7 @@ void QuicTransportBaseLite::checkForClosedStream() { if (closeState_ == CloseState::GRACEFUL_CLOSING && conn_->streamManager->streamCount() == 0) { - closeImpl(none); + closeImpl(std::nullopt); } } @@ -1716,7 +1716,7 @@ QuicTransportBaseLite::resetStreamInternal( // We can't change the error code across resets for a stream return folly::makeUnexpected(LocalErrorCode::INVALID_OPERATION); } - folly::Optional maybeReliableSize = folly::none; + Optional maybeReliableSize = std::nullopt; if (reliable) { maybeReliableSize = stream->reliableResetCheckpoint; } @@ -2544,21 +2544,21 @@ QuicConnectionStats QuicTransportBaseLite::getConnectionsStats() const { connStats.numStreams = conn_->streamManager->streams().size(); } - if (conn_->clientChosenDestConnectionId.hasValue()) { + if (conn_->clientChosenDestConnectionId.has_value()) { connStats.clientChosenDestConnectionId = conn_->clientChosenDestConnectionId->hex(); } - if (conn_->clientConnectionId.hasValue()) { + if (conn_->clientConnectionId.has_value()) { connStats.clientConnectionId = conn_->clientConnectionId->hex(); } - if (conn_->serverConnectionId.hasValue()) { + if (conn_->serverConnectionId.has_value()) { connStats.serverConnectionId = conn_->serverConnectionId->hex(); } connStats.totalBytesSent = conn_->lossState.totalBytesSent; connStats.totalBytesReceived = conn_->lossState.totalBytesRecvd; connStats.totalBytesRetransmitted = conn_->lossState.totalBytesRetransmitted; - if (conn_->version.hasValue()) { + if (conn_->version.has_value()) { connStats.version = static_cast(*conn_->version); } return connStats; @@ -2752,7 +2752,7 @@ QuicTransportBaseLite::getAdditionalCmsgsForAsyncUDPSocket() { DCHECK(conn_->writeCount == conn_->socketCmsgsState.targetWriteCount); return conn_->socketCmsgsState.additionalCmsgs; } - return none; + return std::nullopt; } void QuicTransportBaseLite::notifyStartWritingFromAppRateLimited() { @@ -2773,12 +2773,12 @@ void QuicTransportBaseLite::notifyStartWritingFromAppRateLimited() { conn_->congestionController ? Optional(conn_->congestionController ->getCongestionWindow()) - : none) + : std::nullopt) .setWritableBytes( conn_->congestionController ? Optional(conn_->congestionController ->getWritableBytes()) - : none) + : std::nullopt) .build()](auto observer, auto observed) { observer->startWritingFromAppLimited(observed, event); }); @@ -2806,12 +2806,12 @@ void QuicTransportBaseLite::notifyPacketsWritten( conn_->congestionController ? Optional(conn_->congestionController ->getCongestionWindow()) - : none) + : std::nullopt) .setWritableBytes( conn_->congestionController ? Optional(conn_->congestionController ->getWritableBytes()) - : none) + : std::nullopt) .setNumPacketsWritten(numPacketsWritten) .setNumAckElicitingPacketsWritten( numAckElicitingPacketsWritten) @@ -2840,12 +2840,12 @@ void QuicTransportBaseLite::notifyAppRateLimited() { conn_->congestionController ? Optional(conn_->congestionController ->getCongestionWindow()) - : none) + : std::nullopt) .setWritableBytes( conn_->congestionController ? Optional(conn_->congestionController ->getWritableBytes()) - : none) + : std::nullopt) .build()](auto observer, auto observed) { observer->appRateLimited(observed, event); }); @@ -2881,12 +2881,12 @@ void QuicTransportBaseLite::processCallbacksAfterWriteData() { auto txCallbacksForStreamIt = txCallbacks_.find(streamId); if (txCallbacksForStreamIt == txCallbacks_.end() || txCallbacksForStreamIt->second.empty()) { - return none; + return std::nullopt; } auto& txCallbacksForStream = txCallbacksForStreamIt->second; if (txCallbacksForStream.front().offset > *largestOffsetTxed) { - return none; + return std::nullopt; } // extract the callback, pop from the queue, then check for cleanup diff --git a/quic/api/QuicTransportBaseLite.h b/quic/api/QuicTransportBaseLite.h index 69e4874db..f0bcfc365 100644 --- a/quic/api/QuicTransportBaseLite.h +++ b/quic/api/QuicTransportBaseLite.h @@ -117,7 +117,7 @@ class QuicTransportBaseLite : virtual public QuicSocketLite, */ void cancelByteEventCallbacksForStream( const StreamId id, - const Optional& offsetUpperBound = none) override; + const Optional& offsetUpperBound = std::nullopt) override; /** * Cancel byte event callbacks for given type and stream. @@ -128,7 +128,7 @@ class QuicTransportBaseLite : virtual public QuicSocketLite, void cancelByteEventCallbacksForStream( const ByteEvent::Type type, const StreamId id, - const Optional& offsetUpperBound = none) override; + const Optional& offsetUpperBound = std::nullopt) override; /** * Register a byte event to be triggered when specified event type occurs for diff --git a/quic/api/QuicTransportFunctions.cpp b/quic/api/QuicTransportFunctions.cpp index d9683531c..91f94cda6 100644 --- a/quic/api/QuicTransportFunctions.cpp +++ b/quic/api/QuicTransportFunctions.cpp @@ -55,12 +55,12 @@ std::string largestAckScheduledToString( optionalToString( conn.ackStates.initialAckState ? conn.ackStates.initialAckState->largestAckScheduled - : quic::none), + : std::nullopt), ",", optionalToString( conn.ackStates.handshakeAckState ? conn.ackStates.handshakeAckState->largestAckScheduled - : quic::none), + : std::nullopt), ",", optionalToString(conn.ackStates.appDataAckState.largestAckScheduled), "]"); @@ -73,12 +73,12 @@ std::string largestAckToSendToString( optionalToString( conn.ackStates.initialAckState ? largestAckToSend(*conn.ackStates.initialAckState) - : quic::none), + : std::nullopt), ",", optionalToString( conn.ackStates.handshakeAckState ? largestAckToSend(*conn.ackStates.handshakeAckState) - : quic::none), + : std::nullopt), ",", optionalToString(largestAckToSend(conn.ackStates.appDataAckState)), "]"); diff --git a/quic/api/test/QuicPacketSchedulerTest.cpp b/quic/api/test/QuicPacketSchedulerTest.cpp index cba9e73d5..c5f4f9eeb 100644 --- a/quic/api/test/QuicPacketSchedulerTest.cpp +++ b/quic/api/test/QuicPacketSchedulerTest.cpp @@ -648,8 +648,8 @@ TEST_P(QuicPacketSchedulerTest, NoCloningForDSR) { auto result = cloningScheduler.scheduleFramesForPacket( std::move(builder), kDefaultUDPSendPacketLen); ASSERT_FALSE(result.hasError()); - EXPECT_FALSE(result->clonedPacketIdentifier.hasValue()); - EXPECT_FALSE(result->packet.hasValue()); + EXPECT_FALSE(result->clonedPacketIdentifier.has_value()); + EXPECT_FALSE(result->packet.has_value()); } TEST_P(QuicPacketSchedulerTest, CloningSchedulerTest) { @@ -731,7 +731,7 @@ TEST_P(QuicPacketSchedulerTest, WriteOnlyOutstandingPacketsTest) { std::move(regularBuilder), kDefaultUDPSendPacketLen); ASSERT_FALSE(result.hasError()); EXPECT_TRUE( - result->clonedPacketIdentifier.hasValue() && result->packet.hasValue()); + result->clonedPacketIdentifier.has_value() && result->packet.has_value()); EXPECT_EQ(packetNum, result->clonedPacketIdentifier->packetNumber); // written packet should not have any frame in the builder auto& writtenPacket = *result->packet; @@ -1113,7 +1113,7 @@ TEST_P(QuicPacketSchedulerTest, CloneSchedulerUseNormalSchedulerFirst) { folly::IOBuf( folly::IOBuf::CopyBufferOp::COPY_BUFFER, "I'm out of the game")); - return SchedulingResult(none, std::move(builtPacket)); + return SchedulingResult(std::nullopt, std::move(builtPacket)); })); RegularQuicPacketBuilder builder( conn.udpSendPacketLen, @@ -1122,7 +1122,7 @@ TEST_P(QuicPacketSchedulerTest, CloneSchedulerUseNormalSchedulerFirst) { auto result = cloningScheduler.scheduleFramesForPacket( std::move(builder), kDefaultUDPSendPacketLen); ASSERT_FALSE(result.hasError()); - EXPECT_EQ(none, result->clonedPacketIdentifier); + EXPECT_EQ(std::nullopt, result->clonedPacketIdentifier); EXPECT_EQ(result->packet->packet.header.getHeaderForm(), HeaderForm::Short); ShortHeader& shortHeader = *result->packet->packet.header.asShort(); EXPECT_EQ(ProtectionType::KeyPhaseOne, shortHeader.getProtectionType()); @@ -1312,7 +1312,7 @@ TEST_P(QuicPacketSchedulerTest, CloningSchedulerWithInplaceBuilderFullPacket) { EXPECT_EQ(conn.udpSendPacketLen, bufferLength); auto updateResult = updateConnection( conn, - none, + std::nullopt, result->packet->packet, Clock::now(), bufferLength, @@ -1390,7 +1390,7 @@ TEST_P(QuicPacketSchedulerTest, CloneLargerThanOriginalPacket) { EXPECT_EQ(encodedSize, conn.udpSendPacketLen); auto updateResult = updateConnection( conn, - none, + std::nullopt, packetResult->packet->packet, Clock::now(), encodedSize, @@ -1414,8 +1414,8 @@ TEST_P(QuicPacketSchedulerTest, CloneLargerThanOriginalPacket) { auto cloneResult = cloningScheduler.scheduleFramesForPacket( std::move(throwawayBuilder), kDefaultUDPSendPacketLen); ASSERT_FALSE(cloneResult.hasError()); - EXPECT_FALSE(cloneResult->packet.hasValue()); - EXPECT_FALSE(cloneResult->clonedPacketIdentifier.hasValue()); + EXPECT_FALSE(cloneResult->packet.has_value()); + EXPECT_FALSE(cloneResult->clonedPacketIdentifier.has_value()); } class AckSchedulingTest : public TestWithParam {}; @@ -1434,7 +1434,7 @@ TEST_P(QuicPacketSchedulerTest, AckStateHasAcksToSchedule) { conn.ackStates.handshakeAckState->largestAckScheduled = 200; EXPECT_FALSE(hasAcksToSchedule(*conn.ackStates.handshakeAckState)); - conn.ackStates.handshakeAckState->largestAckScheduled = none; + conn.ackStates.handshakeAckState->largestAckScheduled = std::nullopt; EXPECT_TRUE(hasAcksToSchedule(*conn.ackStates.handshakeAckState)); } @@ -1458,16 +1458,16 @@ TEST_P(QuicPacketSchedulerTest, AckSchedulerHasAcksToSchedule) { conn.ackStates.handshakeAckState->largestAckScheduled = 200; EXPECT_FALSE(handshakeAckScheduler.hasPendingAcks()); - conn.ackStates.handshakeAckState->largestAckScheduled = none; + conn.ackStates.handshakeAckState->largestAckScheduled = std::nullopt; EXPECT_TRUE(handshakeAckScheduler.hasPendingAcks()); } TEST_P(QuicPacketSchedulerTest, LargestAckToSend) { QuicClientConnectionState conn( FizzClientQuicHandshakeContext::Builder().build()); - EXPECT_EQ(none, largestAckToSend(*conn.ackStates.initialAckState)); - EXPECT_EQ(none, largestAckToSend(*conn.ackStates.handshakeAckState)); - EXPECT_EQ(none, largestAckToSend(conn.ackStates.appDataAckState)); + EXPECT_EQ(std::nullopt, largestAckToSend(*conn.ackStates.initialAckState)); + EXPECT_EQ(std::nullopt, largestAckToSend(*conn.ackStates.handshakeAckState)); + EXPECT_EQ(std::nullopt, largestAckToSend(conn.ackStates.appDataAckState)); conn.ackStates.initialAckState->acks.insert(0, 50); conn.ackStates.handshakeAckState->acks.insert(0, 50); @@ -1475,7 +1475,7 @@ TEST_P(QuicPacketSchedulerTest, LargestAckToSend) { EXPECT_EQ(50, *largestAckToSend(*conn.ackStates.initialAckState)); EXPECT_EQ(150, *largestAckToSend(*conn.ackStates.handshakeAckState)); - EXPECT_EQ(none, largestAckToSend(conn.ackStates.appDataAckState)); + EXPECT_EQ(std::nullopt, largestAckToSend(conn.ackStates.appDataAckState)); } TEST_P(QuicPacketSchedulerTest, NeedsToSendAckWithoutAcksAvailable) { @@ -1503,7 +1503,7 @@ TEST_P(QuicPacketSchedulerTest, NeedsToSendAckWithoutAcksAvailable) { conn.ackStates.handshakeAckState->largestAckScheduled = 200; EXPECT_FALSE(handshakeAckScheduler.hasPendingAcks()); - conn.ackStates.handshakeAckState->largestAckScheduled = none; + conn.ackStates.handshakeAckState->largestAckScheduled = std::nullopt; EXPECT_TRUE(handshakeAckScheduler.hasPendingAcks()); } @@ -1958,7 +1958,7 @@ TEST_P(QuicPacketSchedulerTest, WriteLossWithoutFlowControl) { auto packet1 = std::move(builder1).buildPacket().packet; ASSERT_FALSE( updateConnection( - conn, none, packet1, Clock::now(), 1000, 0, false /* isDSR */) + conn, std::nullopt, packet1, Clock::now(), 1000, 0, false /* isDSR */) .hasError()); EXPECT_EQ(1, packet1.frames.size()); auto& writeStreamFrame1 = *packet1.frames[0].asWriteStreamFrame(); @@ -1988,7 +1988,7 @@ TEST_P(QuicPacketSchedulerTest, WriteLossWithoutFlowControl) { auto packet2 = std::move(builder2).buildPacket().packet; ASSERT_FALSE( updateConnection( - conn, none, packet2, Clock::now(), 1000, 0, false /* isDSR */) + conn, std::nullopt, packet2, Clock::now(), 1000, 0, false /* isDSR */) .hasError()); EXPECT_EQ(1, packet2.frames.size()); auto& writeStreamFrame2 = *packet2.frames[0].asWriteStreamFrame(); @@ -2036,7 +2036,7 @@ TEST_P(QuicPacketSchedulerTest, WriteLossWithoutFlowControlIgnoreDSR) { auto packet1 = std::move(builder1).buildPacket().packet; ASSERT_FALSE( updateConnection( - conn, none, packet1, Clock::now(), 1000, 0, false /* isDSR */) + conn, std::nullopt, packet1, Clock::now(), 1000, 0, false /* isDSR */) .hasError()); EXPECT_EQ(1, packet1.frames.size()); auto& writeStreamFrame1 = *packet1.frames[0].asWriteStreamFrame(); @@ -2081,7 +2081,7 @@ TEST_P(QuicPacketSchedulerTest, WriteLossWithoutFlowControlSequential) { auto packet1 = std::move(builder1).buildPacket().packet; ASSERT_FALSE( updateConnection( - conn, none, packet1, Clock::now(), 1000, 0, false /* isDSR */) + conn, std::nullopt, packet1, Clock::now(), 1000, 0, false /* isDSR */) .hasError()); EXPECT_EQ(1, packet1.frames.size()); auto& writeStreamFrame1 = *packet1.frames[0].asWriteStreamFrame(); @@ -2111,7 +2111,7 @@ TEST_P(QuicPacketSchedulerTest, WriteLossWithoutFlowControlSequential) { auto packet2 = std::move(builder2).buildPacket().packet; ASSERT_FALSE( updateConnection( - conn, none, packet2, Clock::now(), 1000, 0, false /* isDSR */) + conn, std::nullopt, packet2, Clock::now(), 1000, 0, false /* isDSR */) .hasError()); EXPECT_EQ(1, packet2.frames.size()); auto& writeStreamFrame2 = *packet2.frames[0].asWriteStreamFrame(); @@ -2161,7 +2161,7 @@ TEST_P(QuicPacketSchedulerTest, MultipleStreamsRunOutOfFlowControl) { scheduler.writeStreams(builder1); auto packet1 = std::move(builder1).buildPacket().packet; ASSERT_TRUE(updateConnection( - conn, none, packet1, Clock::now(), 1200, 0, false /* isDSR */)); + conn, std::nullopt, packet1, Clock::now(), 1200, 0, false /* isDSR */)); ASSERT_EQ(2, packet1.frames.size()); auto& writeStreamFrame1 = *packet1.frames[0].asWriteStreamFrame(); EXPECT_EQ(highPriStreamId, writeStreamFrame1.streamId); @@ -2196,7 +2196,7 @@ TEST_P(QuicPacketSchedulerTest, MultipleStreamsRunOutOfFlowControl) { scheduler.writeStreams(builder2); auto packet2 = std::move(builder2).buildPacket().packet; ASSERT_TRUE(updateConnection( - conn, none, packet2, Clock::now(), 1000, 0, false /* isDSR */)); + conn, std::nullopt, packet2, Clock::now(), 1000, 0, false /* isDSR */)); ASSERT_EQ(1, packet2.frames.size()); auto& writeStreamFrame3 = *packet2.frames[0].asWriteStreamFrame(); EXPECT_EQ(highPriStreamId, writeStreamFrame3.streamId); @@ -2244,7 +2244,7 @@ TEST_P(QuicPacketSchedulerTest, RunOutFlowControlDuringStreamWrite) { auto packet1 = std::move(builder1).buildPacket().packet; ASSERT_FALSE( updateConnection( - conn, none, packet1, Clock::now(), 1200, 0, false /* isDSR */) + conn, std::nullopt, packet1, Clock::now(), 1200, 0, false /* isDSR */) .hasError()); ASSERT_EQ(2, packet1.frames.size()); auto& writeStreamFrame1 = *packet1.frames[0].asWriteStreamFrame(); @@ -2277,7 +2277,7 @@ TEST_P(QuicPacketSchedulerTest, WritingFINFromBufWithBufMetaFirst) { stream->dsrSender = std::make_unique(); BufferMeta bufferMeta(5000); ASSERT_FALSE(writeBufMetaToQuicStream(*stream, bufferMeta, true).hasError()); - EXPECT_TRUE(stream->finalWriteOffset.hasValue()); + EXPECT_TRUE(stream->finalWriteOffset.has_value()); stream->writeBufMeta.split(5000); ASSERT_EQ(0, stream->writeBufMeta.length); @@ -2321,7 +2321,7 @@ TEST_P(QuicPacketSchedulerTest, NoFINWriteWhenBufMetaWrittenFIN) { stream->dsrSender = std::make_unique(); BufferMeta bufferMeta(5000); ASSERT_FALSE(writeBufMetaToQuicStream(*stream, bufferMeta, true).hasError()); - EXPECT_TRUE(stream->finalWriteOffset.hasValue()); + EXPECT_TRUE(stream->finalWriteOffset.has_value()); PacketNum packetNum = 0; ShortHeader header( ProtectionType::KeyPhaseOne, @@ -2560,7 +2560,7 @@ TEST_P(QuicPacketSchedulerTest, ShortHeaderFixedPaddingAtStart) { ASSERT_FALSE(result.hasError()); // Verify padding frames were added at start - EXPECT_TRUE(result.value().packet.hasValue()); + EXPECT_TRUE(result.value().packet.has_value()); const auto& frames = result.value().packet->packet.frames; ASSERT_EQ(frames.size(), 3); EXPECT_TRUE(frames[0].asPaddingFrame()); @@ -2792,7 +2792,7 @@ TEST_P(QuicPacketSchedulerTest, RstStreamSchedulerReliableReset) { cipherOverhead; ASSERT_FALSE(updateConnection( conn, - none, + std::nullopt, packetResult1.value().packet->packet, Clock::now(), encodedSize1, @@ -2822,7 +2822,7 @@ TEST_P(QuicPacketSchedulerTest, RstStreamSchedulerReliableReset) { cipherOverhead; ASSERT_FALSE(updateConnection( conn, - none, + std::nullopt, packetResult2.value().packet->packet, Clock::now(), encodedSize2, @@ -2935,7 +2935,7 @@ TEST_P(QuicPacketSchedulerTest, FixedShortHeaderPadding) { // Verify padding frames were added // at start - EXPECT_TRUE(result.value().packet.hasValue()); + EXPECT_TRUE(result.value().packet.has_value()); const auto& frames = result.value().packet->packet.frames; ASSERT_EQ(frames.size(), 2); EXPECT_TRUE(frames[0].asPaddingFrame()); @@ -2992,7 +2992,7 @@ TEST_F(QuicAckSchedulerTest, DefaultAckFrame) { auto writeResult = ackScheduler.writeNextAcks(*builder_); ASSERT_FALSE(writeResult.hasError()); - ASSERT_TRUE(writeResult.value() != none); + ASSERT_TRUE(writeResult.value() != std::nullopt); ASSERT_EQ(builder_->frames_.size(), 1); auto ackFrame = builder_->frames_[0].asWriteAckFrame(); @@ -3019,7 +3019,7 @@ TEST_F(QuicAckSchedulerTest, WriteAckEcnWhenReadingEcnOnEgress) { auto writeResult = ackScheduler.writeNextAcks(*builder_); ASSERT_FALSE(writeResult.hasError()); - ASSERT_TRUE(writeResult.value() != none); + ASSERT_TRUE(writeResult.value() != std::nullopt); ASSERT_EQ(builder_->frames_.size(), 1); auto ackFrame = builder_->frames_[0].asWriteAckFrame(); @@ -3051,7 +3051,7 @@ TEST_F(QuicAckSchedulerTest, WriteAckReceiveTimestampsWhenEnabled) { auto writeResult = ackScheduler.writeNextAcks(*builder_); ASSERT_FALSE(writeResult.hasError()); - ASSERT_TRUE(writeResult.value() != none); + ASSERT_TRUE(writeResult.value() != std::nullopt); ASSERT_EQ(builder_->frames_.size(), 1); auto ackFrame = builder_->frames_[0].asWriteAckFrame(); @@ -3083,7 +3083,7 @@ TEST_F(QuicAckSchedulerTest, AckEcnTakesPrecedenceOverReceiveTimestamps) { auto writeResult = ackScheduler.writeNextAcks(*builder_); ASSERT_FALSE(writeResult.hasError()); - ASSERT_TRUE(writeResult.value() != none); + ASSERT_TRUE(writeResult.value() != std::nullopt); ASSERT_EQ(builder_->frames_.size(), 1); auto ackFrame = builder_->frames_[0].asWriteAckFrame(); @@ -3115,7 +3115,7 @@ TEST_F(QuicAckSchedulerTest, AckExtendedNotSentIfNotSupported) { auto writeResult = ackScheduler.writeNextAcks(*builder_); ASSERT_FALSE(writeResult.hasError()); - ASSERT_TRUE(writeResult.value() != none); + ASSERT_TRUE(writeResult.value() != std::nullopt); ASSERT_EQ(builder_->frames_.size(), 1); auto ackFrame = builder_->frames_[0].asWriteAckFrame(); @@ -3146,7 +3146,7 @@ TEST_F(QuicAckSchedulerTest, AckExtendedNotSentIfNotEnabled) { auto writeResult = ackScheduler.writeNextAcks(*builder_); ASSERT_FALSE(writeResult.hasError()); - ASSERT_TRUE(writeResult.value() != none); + ASSERT_TRUE(writeResult.value() != std::nullopt); ASSERT_EQ(builder_->frames_.size(), 1); auto ackFrame = builder_->frames_[0].asWriteAckFrame(); @@ -3177,7 +3177,8 @@ TEST_F( // Peer sent ART config conn_->maybePeerAckReceiveTimestampsConfig = AckReceiveTimestampsConfig(); // We don't have an ART config (i.e. we can't sent ART) - conn_->transportSettings.maybeAckReceiveTimestampsConfigSentToPeer = none; + conn_->transportSettings.maybeAckReceiveTimestampsConfigSentToPeer = + std::nullopt; updateNegotiatedAckFeatures(*conn_); AckScheduler ackScheduler(*conn_, ackState_); @@ -3185,7 +3186,7 @@ TEST_F( auto writeResult = ackScheduler.writeNextAcks(*builder_); ASSERT_FALSE(writeResult.hasError()); - ASSERT_TRUE(writeResult.value() != none); + ASSERT_TRUE(writeResult.value() != std::nullopt); ASSERT_EQ(builder_->frames_.size(), 1); auto ackFrame = builder_->frames_[0].asWriteAckFrame(); @@ -3222,7 +3223,7 @@ TEST_F(QuicAckSchedulerTest, AckExtendedNotSentIfECNFeatureNotSupported) { auto writeResult = ackScheduler.writeNextAcks(*builder_); ASSERT_FALSE(writeResult.hasError()); - ASSERT_TRUE(writeResult.value() != none); + ASSERT_TRUE(writeResult.value() != std::nullopt); ASSERT_EQ(builder_->frames_.size(), 1); auto ackFrame = builder_->frames_[0].asWriteAckFrame(); @@ -3263,7 +3264,7 @@ TEST_F(QuicAckSchedulerTest, AckExtendedWithAllFeatures) { auto writeResult = ackScheduler.writeNextAcks(*builder_); ASSERT_FALSE(writeResult.hasError()); - ASSERT_TRUE(writeResult.value() != none); + ASSERT_TRUE(writeResult.value() != std::nullopt); ASSERT_EQ(builder_->frames_.size(), 1); auto ackFrame = builder_->frames_[0].asWriteAckFrame(); @@ -3304,7 +3305,7 @@ TEST_F(QuicAckSchedulerTest, AckExtendedTakesPrecedenceOverECN) { auto writeResult = ackScheduler.writeNextAcks(*builder_); ASSERT_FALSE(writeResult.hasError()); - ASSERT_TRUE(writeResult.value() != none); + ASSERT_TRUE(writeResult.value() != std::nullopt); ASSERT_EQ(builder_->frames_.size(), 1); auto ackFrame = builder_->frames_[0].asWriteAckFrame(); @@ -3345,7 +3346,7 @@ TEST_F(QuicAckSchedulerTest, AckExtendedTakesPrecedenceOverReceiveTimestamps) { auto writeResult = ackScheduler.writeNextAcks(*builder_); ASSERT_FALSE(writeResult.hasError()); - ASSERT_TRUE(writeResult.value() != none); + ASSERT_TRUE(writeResult.value() != std::nullopt); ASSERT_EQ(builder_->frames_.size(), 1); auto ackFrame = builder_->frames_[0].asWriteAckFrame(); diff --git a/quic/api/test/QuicStreamAsyncTransportTest.cpp b/quic/api/test/QuicStreamAsyncTransportTest.cpp index bca6e5235..73adcf92d 100644 --- a/quic/api/test/QuicStreamAsyncTransportTest.cpp +++ b/quic/api/test/QuicStreamAsyncTransportTest.cpp @@ -181,7 +181,7 @@ class QuicStreamAsyncTransportTest : public Test { void TearDown() override { if (client_) { - client_->close(none); + client_->close(std::nullopt); } clientEvb_.loop(); server_->shutdown(); diff --git a/quic/api/test/QuicTransportBaseTest.cpp b/quic/api/test/QuicTransportBaseTest.cpp index d7bc973a3..febd0c449 100644 --- a/quic/api/test/QuicTransportBaseTest.cpp +++ b/quic/api/test/QuicTransportBaseTest.cpp @@ -277,7 +277,7 @@ class TestQuicTransport Optional> getPeerTransportParams() const override { - return none; + return std::nullopt; } std::chrono::milliseconds getLossTimeoutRemainingTime() { @@ -546,7 +546,7 @@ class TestQuicTransport } void closeWithoutWrite() { - closeImpl(none, false, false); + closeImpl(std::nullopt, false, false); } void invokeWriteSocketData() { @@ -604,7 +604,7 @@ class TestQuicTransport const std::string&, const Optional&, uint16_t) const override { - return none; + return std::nullopt; } void updateWriteLooper(bool thisIteration, bool /* runInline */ = false) { @@ -616,7 +616,7 @@ class TestQuicTransport } void closeImpl( - folly::Optional error, + Optional error, bool drainConnection = true, bool sendCloseImmediately = true) { QuicTransportBase::closeImpl( @@ -836,7 +836,7 @@ TEST_P(QuicTransportImplTestBase, StopSendingClosesIngress) { // suppose we tx a rst stream (and rx its corresponding ack), expect // terminal state and queued in closed streams transport->resetStream(streamID, GenericApplicationErrorCode::NO_ERROR); - ASSERT_FALSE(sendRstAckSMHandler(*stream, folly::none).hasError()); + ASSERT_FALSE(sendRstAckSMHandler(*stream, std::nullopt).hasError()); EXPECT_TRUE(stream->inTerminalStates()); EXPECT_TRUE(streamManager.closedStreams().contains(streamID)); transport->driveReadCallbacks(); @@ -872,7 +872,7 @@ TEST_P(QuicTransportImplTestBase, StopSendingClosesIngress) { // suppose we tx a rst stream (and rx its corresponding ack) transport->resetStream(streamID, GenericApplicationErrorCode::NO_ERROR); - ASSERT_FALSE(sendRstAckSMHandler(*stream, folly::none).hasError()); + ASSERT_FALSE(sendRstAckSMHandler(*stream, std::nullopt).hasError()); EXPECT_EQ(stream->sendState, StreamSendState::Closed); EXPECT_EQ(stream->recvState, StreamRecvState::Open); transport->driveReadCallbacks(); @@ -1996,7 +1996,7 @@ TEST_P(QuicTransportImplTestBase, CloseStreamAfterReadFin) { TEST_P(QuicTransportImplTestBase, CloseTransportCleansupOutstandingCounters) { transport->transportConn->outstandings .packetCount[PacketNumberSpace::Handshake] = 200; - transport->closeNow(none); + transport->closeNow(std::nullopt); EXPECT_EQ( 0, transport->transportConn->outstandings @@ -2020,7 +2020,7 @@ TEST_P(QuicTransportImplTestBase, DeliveryCallbackUnsetAll) { EXPECT_CALL(dcb1, onCanceled(_, _)).Times(0); EXPECT_CALL(dcb2, onCanceled(_, _)).Times(0); - transport->close(none); + transport->close(std::nullopt); } TEST_P(QuicTransportImplTestBase, DeliveryCallbackUnsetOne) { @@ -2040,7 +2040,7 @@ TEST_P(QuicTransportImplTestBase, DeliveryCallbackUnsetOne) { EXPECT_CALL(dcb1, onCanceled(_, _)).Times(0); EXPECT_CALL(dcb2, onCanceled(_, _)); - transport->close(none); + transport->close(std::nullopt); } TEST_P(QuicTransportImplTestBase, ByteEventCallbacksManagementSingleStream) { @@ -2234,7 +2234,7 @@ TEST_P(QuicTransportImplTestBase, RegisterTxDeliveryCallbackLowerThanExpected) { EXPECT_CALL(txcb2, onByteEventCanceled(getTxMatcher(stream, 20))); EXPECT_CALL(dcb1, onCanceled(_, _)); EXPECT_CALL(dcb2, onCanceled(_, _)); - transport->close(none); + transport->close(std::nullopt); Mock::VerifyAndClearExpectations(&txcb1); Mock::VerifyAndClearExpectations(&txcb2); Mock::VerifyAndClearExpectations(&txcb3); @@ -2260,7 +2260,7 @@ TEST_F( EXPECT_CALL(dcb, onCanceled(_, _)); transport->registerTxCallback(stream, 2, &txcb); transport->registerDeliveryCallback(stream, 2, &dcb); - transport->close(none); + transport->close(std::nullopt); qEvb->loopOnce(); Mock::VerifyAndClearExpectations(&txcb); Mock::VerifyAndClearExpectations(&dcb); @@ -2472,7 +2472,7 @@ TEST_P(QuicTransportImplTestBase, RegisterDeliveryCallbackAsyncDeliveryTx) { Mock::VerifyAndClearExpectations(&txcb2); EXPECT_CALL(txcb2, onByteEventCanceled(getTxMatcher(stream, 10))); - transport->close(none); + transport->close(std::nullopt); Mock::VerifyAndClearExpectations(&txcb2); } @@ -2521,7 +2521,7 @@ TEST_P(QuicTransportImplTestBase, RegisterDeliveryCallbackAsyncDeliveryAck) { Mock::VerifyAndClearExpectations(&txcb2); EXPECT_CALL(txcb2, onByteEventCanceled(getAckMatcher(stream, 10))); - transport->close(none); + transport->close(std::nullopt); Mock::VerifyAndClearExpectations(&txcb2); } @@ -2595,7 +2595,7 @@ TEST_P(QuicTransportImplTestBase, CancelAllByteEventCallbacks) { EXPECT_CALL(dcb1, onCanceled(_, _)).Times(0); EXPECT_CALL(dcb2, onCanceled(_, _)).Times(0); - transport->close(none); + transport->close(std::nullopt); Mock::VerifyAndClearExpectations(&txcb1); Mock::VerifyAndClearExpectations(&txcb2); Mock::VerifyAndClearExpectations(&dcb1); @@ -2671,7 +2671,7 @@ TEST_P(QuicTransportImplTestBase, CancelByteEventCallbacksForStream) { EXPECT_CALL(dcb1, onCanceled(stream1, _)).Times(0); EXPECT_CALL(dcb2, onCanceled(_, 20)); - transport->close(none); + transport->close(std::nullopt); Mock::VerifyAndClearExpectations(&txcb1); Mock::VerifyAndClearExpectations(&txcb2); Mock::VerifyAndClearExpectations(&dcb1); @@ -2830,7 +2830,7 @@ TEST_P(QuicTransportImplTestBase, CancelByteEventCallbacksForStreamWithOffset) { EXPECT_CALL(dcb2, onCanceled(stream2, 15)); EXPECT_CALL(dcb2, onCanceled(stream2, 20)); - transport->close(none); + transport->close(std::nullopt); Mock::VerifyAndClearExpectations(&txcb1); Mock::VerifyAndClearExpectations(&txcb2); Mock::VerifyAndClearExpectations(&dcb1); @@ -2931,7 +2931,7 @@ TEST_P(QuicTransportImplTestBase, CancelByteEventCallbacksTx) { EXPECT_CALL(dcb2, onCanceled(stream2, 10)); EXPECT_CALL(dcb2, onCanceled(stream2, 15)); - transport->close(none); + transport->close(std::nullopt); Mock::VerifyAndClearExpectations(&txcb1); Mock::VerifyAndClearExpectations(&txcb2); Mock::VerifyAndClearExpectations(&dcb1); @@ -3013,7 +3013,7 @@ TEST_P(QuicTransportImplTestBase, CancelByteEventCallbacksDelivery) { EXPECT_CALL(txcb2, onByteEventCanceled(getTxMatcher(stream2, 10))); EXPECT_CALL(txcb2, onByteEventCanceled(getTxMatcher(stream2, 15))); - transport->close(none); + transport->close(std::nullopt); Mock::VerifyAndClearExpectations(&txcb1); Mock::VerifyAndClearExpectations(&txcb2); Mock::VerifyAndClearExpectations(&dcb1); @@ -3028,7 +3028,7 @@ TEST_P( wcb, onConnectionWriteError(IsError(GenericApplicationErrorCode::NO_ERROR))); transport->notifyPendingWriteOnConnection(&wcb); - transport->close(none); + transport->close(std::nullopt); qEvb->loopOnce(); } @@ -3044,7 +3044,7 @@ TEST_P(QuicTransportImplTestClose, TestNotifyPendingConnWriteOnCloseWithError) { QuicErrorCode(GenericApplicationErrorCode::UNKNOWN), std::string("Bye"))); } else { - transport->close(none); + transport->close(std::nullopt); } qEvb->loopOnce(); } @@ -3068,7 +3068,7 @@ TEST_P(QuicTransportImplTestBase, TestNotifyPendingWriteOnCloseWithoutError) { onStreamWriteError( stream, IsError(GenericApplicationErrorCode::NO_ERROR))); transport->notifyPendingWriteOnStream(stream, &wcb); - transport->close(none); + transport->close(std::nullopt); qEvb->loopOnce(); } @@ -3085,7 +3085,7 @@ TEST_P(QuicTransportImplTestClose, TestNotifyPendingWriteOnCloseWithError) { QuicErrorCode(GenericApplicationErrorCode::UNKNOWN), std::string("Bye"))); } else { - transport->close(none); + transport->close(std::nullopt); } qEvb->loopOnce(); } @@ -3201,7 +3201,7 @@ TEST_P(QuicTransportImplTestBase, TestGracefulCloseWithNoActiveStream) { transport->transportConn->streamManager->addTx(stream); transport->transportConn->streamManager->addDeliverable(stream); transport->closeStream(stream); - transport->close(none); + transport->close(std::nullopt); ASSERT_TRUE(transport->transportClosed); EXPECT_FALSE(transport->createBidirectionalStream()); @@ -3238,7 +3238,7 @@ TEST_P(QuicTransportImplTestBase, TestResetRemovesDeliveryCb) { .hasError()); EXPECT_EQ(transport->getNumByteEventCallbacksForStream(stream1), 0); EXPECT_EQ(transport->getNumByteEventCallbacksForStream(stream2), 1); - transport->close(none); + transport->close(std::nullopt); } TEST_P(QuicTransportImplTestBase, TestImmediateClose) { @@ -4141,7 +4141,7 @@ TEST_P(QuicTransportImplTestBase, StreamWriteCallbackUnregister) { EXPECT_TRUE(transport->unregisterStreamWriteCallback(stream)); wcb.reset(); })); - transport->close(none); + transport->close(std::nullopt); qEvb->loopOnce(); } @@ -4253,7 +4253,7 @@ TEST_P(QuicTransportImplTestBase, ObserverDetachAfterClose) { EXPECT_CALL(*cb, closeStarted(transport.get(), _)); EXPECT_CALL(*cb, closing(transport.get(), _)); - transport->close(none); + transport->close(std::nullopt); Mock::VerifyAndClearExpectations(cb.get()); EXPECT_CALL(*cb, observerDetach(transport.get())); diff --git a/quic/api/test/QuicTransportFunctionsTest.cpp b/quic/api/test/QuicTransportFunctionsTest.cpp index 3390d2aca..37da62d86 100644 --- a/quic/api/test/QuicTransportFunctionsTest.cpp +++ b/quic/api/test/QuicTransportFunctionsTest.cpp @@ -220,7 +220,13 @@ TEST_F(QuicTransportFunctionsTest, PingPacketGoesToOPListAndLossAlarm) { packet.packet.frames.push_back(PingFrame()); EXPECT_EQ(0, conn->outstandings.packets.size()); auto result = updateConnection( - *conn, none, packet.packet, Clock::now(), 50, 0, false /* isDSRPacket */); + *conn, + std::nullopt, + packet.packet, + Clock::now(), + 50, + 0, + false /* isDSRPacket */); ASSERT_FALSE(result.hasError()); EXPECT_EQ(1, conn->outstandings.packets.size()); EXPECT_TRUE(conn->pendingEvents.setLossDetectionAlarm); @@ -267,7 +273,7 @@ TEST_F(QuicTransportFunctionsTest, TestUpdateConnection) { .WillOnce(Return(true)); auto result = updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint{}, getEncodedSize(packet), @@ -332,7 +338,7 @@ TEST_F(QuicTransportFunctionsTest, TestUpdateConnection) { .WillOnce(Return(false)); result = updateConnection( *conn, - none, + std::nullopt, packet2.packet, TimePoint(), getEncodedSize(packet2), @@ -464,7 +470,7 @@ TEST_F(QuicTransportFunctionsTest, TestUpdateConnectionPacketRetrans) { .WillOnce(Return(true)); auto result = updateConnection( *conn, - none, + std::nullopt, packet1.packet, TimePoint{}, getEncodedSize(packet1), @@ -529,7 +535,7 @@ TEST_F(QuicTransportFunctionsTest, TestUpdateConnectionPacketRetrans) { .WillOnce(Return(false)); result = updateConnection( *conn, - none, + std::nullopt, packet2.packet, TimePoint(), getEncodedSize(packet2), @@ -637,7 +643,7 @@ TEST_F( .WillOnce(Return(true)); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet1.packet, TimePoint{}, getEncodedSize(packet1), @@ -727,7 +733,7 @@ TEST_F( .WillOnce(Return(false)); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet2.packet, TimePoint(), getEncodedSize(packet2), @@ -797,7 +803,7 @@ TEST_F(QuicTransportFunctionsTest, TestUpdateConnectionPacketSorting) { ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, handshakePacket.packet, TimePoint{}, getEncodedSize(handshakePacket), @@ -806,7 +812,7 @@ TEST_F(QuicTransportFunctionsTest, TestUpdateConnectionPacketSorting) { .hasError()); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, initialPacket.packet, TimePoint{}, getEncodedSize(initialPacket), @@ -815,7 +821,7 @@ TEST_F(QuicTransportFunctionsTest, TestUpdateConnectionPacketSorting) { .hasError()); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, appDataPacket.packet, TimePoint{}, getEncodedSize(appDataPacket), @@ -868,7 +874,7 @@ TEST_F(QuicTransportFunctionsTest, TestUpdateConnectionFinOnly) { packet.packet.frames.push_back(WriteStreamFrame(stream1->id, 0, 0, true)); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -920,7 +926,7 @@ TEST_F(QuicTransportFunctionsTest, TestUpdateConnectionAllBytesExceptFin) { WriteStreamFrame(stream1->id, 0, buf->computeChainDataLength(), false)); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -969,7 +975,7 @@ TEST_F(QuicTransportFunctionsTest, TestUpdateConnectionEmptyAckWriteResult) { conn->ackStates.handshakeAckState->largestAckScheduled; auto result = updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -1009,7 +1015,7 @@ TEST_F(QuicTransportFunctionsTest, TestUpdateConnectionPureAckCounter) { packet.packet.frames.push_back(std::move(ackFrame)); auto result2 = updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -1030,7 +1036,7 @@ TEST_F(QuicTransportFunctionsTest, TestUpdateConnectionPureAckCounter) { auto result4 = updateConnection( *conn, - none, + std::nullopt, packet2.packet, TimePoint(), getEncodedSize(packet), @@ -1064,7 +1070,7 @@ TEST_F(QuicTransportFunctionsTest, TestPaddingPureAckPacketIsStillPureAck) { packet.packet.frames.push_back(PaddingFrame()); auto result = updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -1103,7 +1109,7 @@ TEST_F(QuicTransportFunctionsTest, TestImplicitAck) { initialStream->writeBuffer.append(data->clone()); auto result1 = updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -1126,7 +1132,7 @@ TEST_F(QuicTransportFunctionsTest, TestImplicitAck) { initialStream->writeBuffer.append(data->clone()); auto result2 = updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -1159,7 +1165,7 @@ TEST_F(QuicTransportFunctionsTest, TestImplicitAck) { handshakeStream->writeBuffer.append(data->clone()); auto result3 = updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -1178,7 +1184,7 @@ TEST_F(QuicTransportFunctionsTest, TestImplicitAck) { handshakeStream->writeBuffer.append(data->clone()); auto result4 = updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -1238,7 +1244,7 @@ TEST_F(QuicTransportFunctionsTest, TestImplicitAckWithSkippedPacketNumber) { initialStream->writeBuffer.append(data->clone()); auto result1 = updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -1265,7 +1271,7 @@ TEST_F(QuicTransportFunctionsTest, TestImplicitAckWithSkippedPacketNumber) { initialStream->writeBuffer.append(data->clone()); auto result2 = updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -1303,7 +1309,7 @@ TEST_F(QuicTransportFunctionsTest, TestUpdateConnectionHandshakeCounter) { packet.packet.frames.push_back(WriteCryptoFrame(0, 0)); auto result2 = updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -1327,7 +1333,7 @@ TEST_F(QuicTransportFunctionsTest, TestUpdateConnectionHandshakeCounter) { WriteStreamFrame(stream1->id, 0, 0, true)); auto result4 = updateConnection( *conn, - none, + std::nullopt, nonHandshake.packet, TimePoint(), getEncodedSize(packet), @@ -1382,7 +1388,7 @@ TEST_F(QuicTransportFunctionsTest, TestUpdateConnectionForOneRttCryptoData) { packet.packet.frames.push_back(WriteCryptoFrame(0, 0)); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -1401,7 +1407,7 @@ TEST_F(QuicTransportFunctionsTest, TestUpdateConnectionForOneRttCryptoData) { WriteStreamFrame(stream1->id, 0, 0, true)); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, nonHandshake.packet, TimePoint(), getEncodedSize(packet), @@ -1466,7 +1472,7 @@ TEST_F(QuicTransportFunctionsTest, TestUpdateConnectionWithPureAck) { EXPECT_CALL(*rawPacer, onPacketSent()).Times(0); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -1519,7 +1525,7 @@ TEST_F(QuicTransportFunctionsTest, TestUpdateConnectionWithBytesStats) { conn->lossState.totalAckElicitingPacketsSent = 15; ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), 555, @@ -1609,7 +1615,7 @@ TEST_F(QuicTransportFunctionsTest, TestUpdateConnectionWithAppLimitedStats) { // record the packet as having been sent ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), 555, @@ -1670,7 +1676,7 @@ TEST_F( // record the packet as having been sent ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), 555, @@ -1764,7 +1770,7 @@ TEST_F(QuicTransportFunctionsTest, TestUpdateConnectionStreamWindowUpdate) { packet.packet.frames.push_back(std::move(streamWindowUpdate)); auto result = updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -1801,7 +1807,7 @@ TEST_F(QuicTransportFunctionsTest, TestUpdateConnectionConnWindowUpdate) { packet.packet.frames.push_back(std::move(connWindowUpdate)); auto result = updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -1841,7 +1847,7 @@ TEST_F(QuicTransportFunctionsTest, TestUpdateConnectionSkipAPacketNumber) { packet.packet.frames.push_back(std::move(writeStreamFrame)); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -1861,7 +1867,7 @@ TEST_F(QuicTransportFunctionsTest, TestUpdateConnectionSkipAPacketNumber) { auto sentPacketNumber = conn->ackStates.appDataAckState.nextPacketNum; ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -1882,7 +1888,7 @@ TEST_F(QuicTransportFunctionsTest, StreamDetailsEmptyPacket) { auto packet = buildEmptyPacket(*conn, PacketNumberSpace::AppData); auto result = updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -1903,7 +1909,7 @@ TEST_F(QuicTransportFunctionsTest, StreamDetailsNoStreamsInPacket) { packet.packet.frames.push_back(PingFrame()); auto result = updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -1925,7 +1931,7 @@ TEST_F(QuicTransportFunctionsTest, TestPingFrameCounter) { packet.packet.frames.push_back(PingFrame()); auto result = updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -1950,7 +1956,7 @@ TEST_F(QuicTransportFunctionsTest, StreamDetailsSingleStream) { packet.packet.frames.push_back(writeStreamFrame); result = updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -1994,7 +2000,7 @@ TEST_F(QuicTransportFunctionsTest, StreamDetailsSingleStreamMultipleFrames) { packet.packet.frames.push_back(writeStreamFrame2); result = updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -2036,7 +2042,7 @@ TEST_F(QuicTransportFunctionsTest, StreamDetailsSingleStreamRetransmit) { packet.packet.frames.push_back(frame1); result = updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -2074,7 +2080,7 @@ TEST_F(QuicTransportFunctionsTest, StreamDetailsSingleStreamRetransmit) { packet.packet.frames.push_back(frame1); result = updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -2119,7 +2125,7 @@ TEST_F(QuicTransportFunctionsTest, StreamDetailsSingleStreamRetransmit) { packet.packet.frames.push_back(frame2); result = updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -2159,7 +2165,7 @@ TEST_F(QuicTransportFunctionsTest, StreamDetailsSingleStreamRetransmit) { packet.packet.frames.push_back(frame2); result = updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -2210,7 +2216,7 @@ TEST_F(QuicTransportFunctionsTest, StreamDetailsSingleStreamFinWithRetransmit) { packet1.packet.frames.push_back(frame1); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet1.packet, TimePoint(), getEncodedSize(packet1), @@ -2227,7 +2233,7 @@ TEST_F(QuicTransportFunctionsTest, StreamDetailsSingleStreamFinWithRetransmit) { packet2.packet.frames.push_back(frame2); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet2.packet, TimePoint(), getEncodedSize(packet2), @@ -2278,7 +2284,7 @@ TEST_F(QuicTransportFunctionsTest, StreamDetailsSingleStreamFinWithRetransmit) { packet3.packet.frames.push_back(frame2); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet3.packet, TimePoint(), getEncodedSize(packet3), @@ -2332,7 +2338,7 @@ TEST_F( packet1.packet.frames.push_back(frame1); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet1.packet, TimePoint(), getEncodedSize(packet1), @@ -2349,7 +2355,7 @@ TEST_F( packet2.packet.frames.push_back(frame2); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet2.packet, TimePoint(), getEncodedSize(packet2), @@ -2366,7 +2372,7 @@ TEST_F( packet3.packet.frames.push_back(frame3); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet3.packet, TimePoint(), getEncodedSize(packet3), @@ -2426,7 +2432,7 @@ TEST_F( packet4.packet.frames.push_back(frame3); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet4.packet, TimePoint(), getEncodedSize(packet4), @@ -2481,7 +2487,7 @@ TEST_F( packet1.packet.frames.push_back(frame1); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet1.packet, TimePoint(), getEncodedSize(packet1), @@ -2499,7 +2505,7 @@ TEST_F( packet2.packet.frames.push_back(frame2); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet2.packet, TimePoint(), getEncodedSize(packet2), @@ -2517,7 +2523,7 @@ TEST_F( packet3.packet.frames.push_back(frame3); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet3.packet, TimePoint(), getEncodedSize(packet3), @@ -2577,7 +2583,7 @@ TEST_F( packet4.packet.frames.push_back(frame3); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet4.packet, TimePoint(), getEncodedSize(packet4), @@ -2655,7 +2661,7 @@ TEST_F(QuicTransportFunctionsTest, StreamDetailsMultipleStreams) { ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet1.packet, TimePoint(), getEncodedSize(packet1), @@ -2726,7 +2732,7 @@ TEST_F(QuicTransportFunctionsTest, StreamDetailsMultipleStreams) { ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet2.packet, TimePoint(), getEncodedSize(packet1), @@ -4119,7 +4125,7 @@ TEST_F(QuicTransportFunctionsTest, ClearBlockedFromPendingEvents) { conn->streamManager->queueBlocked(stream->id, 1000); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -4167,7 +4173,7 @@ TEST_F(QuicTransportFunctionsTest, TwoConnWindowUpdateWillCrash) { EXPECT_DEATH( (void)updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -4189,7 +4195,7 @@ TEST_F(QuicTransportFunctionsTest, WriteStreamFrameIsNotPureAck) { packet.packet.frames.push_back(std::move(writeStreamFrame)); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -4209,7 +4215,7 @@ TEST_F(QuicTransportFunctionsTest, ClearRstFromPendingEvents) { conn->pendingEvents.resets.emplace(stream->id, rstStreamFrame); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -4253,7 +4259,7 @@ TEST_F(QuicTransportFunctionsTest, TotalBytesSentUpdate) { auto packet = buildEmptyPacket(*conn, PacketNumberSpace::Handshake); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint{}, 4321, @@ -4271,7 +4277,7 @@ TEST_F(QuicTransportFunctionsTest, TotalPacketsSentUpdate) { auto packet = buildEmptyPacket(*conn, PacketNumberSpace::Handshake); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint{}, 4321, @@ -4880,7 +4886,7 @@ TEST_F(QuicTransportFunctionsTest, UpdateConnectionWithBufferMeta) { ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -4910,7 +4916,7 @@ TEST_F(QuicTransportFunctionsTest, UpdateConnectionWithBufferMeta) { retxPacket.packet.frames.push_back(writeStreamFrame); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, retxPacket.packet, TimePoint(), getEncodedSize(retxPacket), @@ -4941,7 +4947,7 @@ TEST_F(QuicTransportFunctionsTest, MissingStreamFrameBytes) { packet.packet.frames.push_back(writeStreamFrame); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -4958,7 +4964,7 @@ TEST_F(QuicTransportFunctionsTest, MissingStreamFrameBytes) { packet.packet.frames.push_back(writeStreamFrame); ASSERT_TRUE(updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -4984,7 +4990,7 @@ TEST_F(QuicTransportFunctionsTest, MissingStreamFrameBytesEof) { packet.packet.frames.push_back(writeStreamFrame); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -5006,7 +5012,7 @@ TEST_F(QuicTransportFunctionsTest, MissingStreamFrameBytesEof) { packet.packet.frames.push_back(writeStreamFrame); ASSERT_TRUE(updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -5032,7 +5038,7 @@ TEST_F(QuicTransportFunctionsTest, MissingStreamFrameBytesSingleByteWrite) { packet.packet.frames.push_back(writeStreamFrame); ASSERT_FALSE(updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), @@ -5049,7 +5055,7 @@ TEST_F(QuicTransportFunctionsTest, MissingStreamFrameBytesSingleByteWrite) { packet.packet.frames.push_back(writeStreamFrame); ASSERT_TRUE(updateConnection( *conn, - none, + std::nullopt, packet.packet, TimePoint(), getEncodedSize(packet), diff --git a/quic/api/test/QuicTransportTest.cpp b/quic/api/test/QuicTransportTest.cpp index 5753824bc..5a2519013 100644 --- a/quic/api/test/QuicTransportTest.cpp +++ b/quic/api/test/QuicTransportTest.cpp @@ -50,12 +50,12 @@ class TransportClosingDeliveryCallback : public QuicSocket::DeliveryCallback { void onDeliveryAck(StreamId, uint64_t offset, std::chrono::microseconds) override { if (offset >= targetOffset_) { - transport_->close(none); + transport_->close(std::nullopt); } } void onCanceled(StreamId, uint64_t) override { - transport_->close(none); + transport_->close(std::nullopt); } private: @@ -298,7 +298,7 @@ TEST_F(QuicTransportTest, WriteDataWithProbing) { })); transport_->writeChain(streamId, buf->clone(), true); loopForWrites(); - transport_->close(none); + transport_->close(std::nullopt); } TEST_F(QuicTransportTest, NotAppLimitedWithLoss) { @@ -328,7 +328,7 @@ TEST_F(QuicTransportTest, NotAppLimitedWithLoss) { EXPECT_CALL(*rawCongestionController, setAppLimited()).Times(0); EXPECT_CALL(connCallback_, onAppRateLimited()).Times(0); loopForWrites(); - transport_->close(none); + transport_->close(std::nullopt); } TEST_F(QuicTransportTest, NotAppLimitedWithNoWritableBytes) { @@ -351,7 +351,7 @@ TEST_F(QuicTransportTest, NotAppLimitedWithNoWritableBytes) { EXPECT_CALL(*rawCongestionController, setAppLimited()).Times(0); EXPECT_CALL(connCallback_, onAppRateLimited()).Times(0); loopForWrites(); - transport_->close(none); + transport_->close(std::nullopt); } TEST_F(QuicTransportTest, NotAppLimitedWithLargeBuffer) { @@ -369,7 +369,7 @@ TEST_F(QuicTransportTest, NotAppLimitedWithLargeBuffer) { EXPECT_CALL(*rawCongestionController, setAppLimited()).Times(0); EXPECT_CALL(connCallback_, onAppRateLimited()).Times(0); loopForWrites(); - transport_->close(none); + transport_->close(std::nullopt); } TEST_F(QuicTransportTest, AppLimited) { @@ -388,7 +388,7 @@ TEST_F(QuicTransportTest, AppLimited) { EXPECT_CALL(*rawCongestionController, setAppLimited()).Times(1); EXPECT_CALL(connCallback_, onAppRateLimited()).Times(1); loopForWrites(); - transport_->close(none); + transport_->close(std::nullopt); } TEST_F(QuicTransportTest, ObserverNotAppLimitedWithNoWritableBytes) { @@ -441,7 +441,7 @@ TEST_F(QuicTransportTest, ObserverNotAppLimitedWithNoWritableBytes) { EXPECT_CALL(*cb1, destroy(transport_.get())); EXPECT_CALL(*cb2, destroy(transport_.get())); EXPECT_CALL(*cb3, destroy(transport_.get())); - transport_->close(none); + transport_->close(std::nullopt); transport_ = nullptr; } @@ -490,7 +490,7 @@ TEST_F(QuicTransportTest, ObserverNotAppLimitedWithLargeBuffer) { EXPECT_CALL(*cb1, destroy(transport_.get())); EXPECT_CALL(*cb2, destroy(transport_.get())); EXPECT_CALL(*cb3, destroy(transport_.get())); - transport_->close(none); + transport_->close(std::nullopt); transport_ = nullptr; } @@ -541,7 +541,7 @@ TEST_F(QuicTransportTest, ObserverAppLimited) { EXPECT_CALL(*cb1, destroy(transport_.get())); EXPECT_CALL(*cb2, destroy(transport_.get())); EXPECT_CALL(*cb3, destroy(transport_.get())); - transport_->close(none); + transport_->close(std::nullopt); transport_ = nullptr; } @@ -929,7 +929,7 @@ TEST_F(QuicTransportTest, ObserverPacketsWrittenCycleCheckDetails) { invokeForAllObservers(([this](MockLegacyObserver& observer) { EXPECT_CALL(observer, destroy(transport_.get())); })); - transport_->close(none); + transport_->close(std::nullopt); transport_ = nullptr; } @@ -1144,7 +1144,7 @@ TEST_F(QuicTransportTest, ObserverPacketsWrittenCheckBytesSent) { invokeForAllObservers(([this](MockLegacyObserver& observer) { EXPECT_CALL(observer, destroy(transport_.get())); })); - transport_->close(none); + transport_->close(std::nullopt); transport_ = nullptr; } @@ -1427,7 +1427,7 @@ TEST_F(QuicTransportTest, ObserverWriteEventsCheckCwndPacketsWritable) { invokeForAllObservers(([this](MockLegacyObserver& observer) { EXPECT_CALL(observer, destroy(transport_.get())); })); - transport_->close(none); + transport_->close(std::nullopt); transport_ = nullptr; } @@ -2135,11 +2135,11 @@ TEST_F(QuicTransportTest, NoWritePendingAckIfHavingData) { ackFound = true; } EXPECT_FALSE(ackFound); - EXPECT_EQ(conn.ackStates.appDataAckState.largestAckScheduled, none); + EXPECT_EQ(conn.ackStates.appDataAckState.largestAckScheduled, std::nullopt); auto pnSpace = packet.header.getPacketNumberSpace(); auto ackState = getAckState(conn, pnSpace); - EXPECT_EQ(ackState.largestAckScheduled, none); + EXPECT_EQ(ackState.largestAckScheduled, std::nullopt); EXPECT_FALSE(ackState.needsToSendAckImmediately); EXPECT_EQ(3, ackState.numNonRxPacketsRecvd); } @@ -2173,11 +2173,11 @@ TEST_F(QuicTransportTest, NoWritePendingAckIfHavingDataNonStream) { ackFound = true; } EXPECT_FALSE(ackFound); - EXPECT_EQ(conn.ackStates.appDataAckState.largestAckScheduled, none); + EXPECT_EQ(conn.ackStates.appDataAckState.largestAckScheduled, std::nullopt); auto pnSpace = packet.header.getPacketNumberSpace(); auto ackState = getAckState(conn, pnSpace); - EXPECT_EQ(ackState.largestAckScheduled, none); + EXPECT_EQ(ackState.largestAckScheduled, std::nullopt); EXPECT_FALSE(ackState.needsToSendAckImmediately); EXPECT_EQ(3, ackState.numNonRxPacketsRecvd); } @@ -2497,7 +2497,7 @@ TEST_F(QuicTransportTest, StopSendingReadCallbackNone) { auto streamId = transport_->createBidirectionalStream().value(); NiceMock readCb; transport_->setReadCallback(streamId, &readCb); - transport_->setReadCallback(streamId, nullptr, none); + transport_->setReadCallback(streamId, nullptr, std::nullopt); loopForWrites(); EXPECT_EQ(0, transport_->getConnectionState().outstandings.packets.size()); } @@ -2508,7 +2508,7 @@ TEST_F(QuicTransportTest, NoStopSendingReadCallback) { transport_->setReadCallback(streamId, &readCb); loopForWrites(); EXPECT_EQ(0, transport_->getConnectionState().outstandings.packets.size()); - transport_->setReadCallback(streamId, nullptr, none); + transport_->setReadCallback(streamId, nullptr, std::nullopt); } TEST_F(QuicTransportTest, SendPathChallenge) { @@ -2612,7 +2612,7 @@ TEST_F(QuicTransportTest, SendPathValidationWhileThereIsOutstandingOne) { PathChallengeFrame pathChallenge2(456); transport_->getPathValidationTimeout().cancelTimerCallback(); conn.pendingEvents.schedulePathValidationTimeout = false; - conn.outstandingPathValidation = none; + conn.outstandingPathValidation = std::nullopt; conn.pendingEvents.pathChallenge = pathChallenge2; EXPECT_EQ(conn.pendingEvents.pathChallenge, pathChallenge2); EXPECT_FALSE(conn.pendingEvents.schedulePathValidationTimeout); @@ -2685,7 +2685,7 @@ TEST_F(QuicTransportTest, OnlyClonePathValidationIfOutstanding) { // Reset outstandingPathValidation // This could happen when an endpoint migrates to an unvalidated address, and // then migrates back to a validated address before timer expires - conn.outstandingPathValidation = none; + conn.outstandingPathValidation = std::nullopt; // Force a timeout with no data so that it clones the packet transport_->lossTimeout().timeoutExpired(); @@ -2805,7 +2805,7 @@ TEST_F(QuicTransportTest, CloneAfterRecvReset) { conn.outstandings.packets.begin(), conn.outstandings.packets.end(), [](const auto& packet) { - return packet.maybeClonedPacketIdentifier.hasValue(); + return packet.maybeClonedPacketIdentifier.has_value(); }); EXPECT_LE(1, cloneCounter); } @@ -2985,7 +2985,7 @@ TEST_F(QuicTransportTest, BusyWriteLoopDetection) { EXPECT_EQ(1, conn.outstandings.packets.size()); EXPECT_EQ(1, conn.writeDebugState.currentEmptyLoopCount); - transport_->close(none); + transport_->close(std::nullopt); } TEST_F(QuicTransportTest, ResendNewConnectionIdOnLoss) { @@ -3416,7 +3416,7 @@ TEST_F(QuicTransportTest, DeliveryCallbackClosesClosedTransport) { .WillRepeatedly(testing::WithArgs<1, 2>(Invoke(getTotalIovecLen))); transport_->writeChain(stream1, buf1->clone(), true, &dc); loopForWrites(); - transport_->close(none); + transport_->close(std::nullopt); } TEST_F(QuicTransportTest, DeliveryCallbackClosesTransportOnDelivered) { @@ -3704,7 +3704,7 @@ TEST_F(QuicTransportTest, InvokeDeliveryCallbacksSingleByte) { // unsentByteDeliveryCb::onByteEvent will never get called // cancel gets called instead EXPECT_CALL(unsentByteDeliveryCb, onCanceled(stream, 1)).Times(1); - transport_->close(none); + transport_->close(std::nullopt); Mock::VerifyAndClearExpectations(&unsentByteDeliveryCb); } @@ -3763,7 +3763,7 @@ TEST_F(QuicTransportTest, InvokeDeliveryCallbacksSingleByteWithFin) { // unsentByteDeliveryCb::onByteEvent will never get called // cancel gets called instead EXPECT_CALL(unsentByteDeliveryCb, onCanceled(stream, 2)).Times(1); - transport_->close(none); + transport_->close(std::nullopt); Mock::VerifyAndClearExpectations(&unsentByteDeliveryCb); } @@ -3826,7 +3826,7 @@ TEST_F(QuicTransportTest, InvokeTxCallbacksSingleByte) { // an error. So, onByteEventCanceled should be called only once. EXPECT_CALL(pastlastByteTxCb, onByteEventCanceled(getTxMatcher(stream, 1))) .Times(1); - transport_->close(none); + transport_->close(std::nullopt); Mock::VerifyAndClearExpectations(&pastlastByteTxCb); } @@ -3887,7 +3887,7 @@ TEST_F(QuicTransportTest, InvokeTxCallbacksSingleByteWithFin) { // cancel gets called instead EXPECT_CALL(pastlastByteTxCb, onByteEventCanceled(getTxMatcher(stream, 2))) .Times(1); - transport_->close(none); + transport_->close(std::nullopt); Mock::VerifyAndClearExpectations(&pastlastByteTxCb); } @@ -3950,7 +3950,7 @@ TEST_F(QuicTransportTest, InvokeTxCallbacksMultipleBytes) { EXPECT_CALL( pastlastByteTxCb, onByteEventCanceled(getTxMatcher(stream, lastByte + 1))) .Times(1); - transport_->close(none); + transport_->close(std::nullopt); Mock::VerifyAndClearExpectations(&pastlastByteTxCb); } @@ -4022,7 +4022,7 @@ TEST_F(QuicTransportTest, InvokeTxCallbacksMultipleBytesWriteRateLimited) { EXPECT_CALL( pastlastByteTxCb, onByteEventCanceled(getTxMatcher(stream, lastByte + 1))) .Times(1); - transport_->close(none); + transport_->close(std::nullopt); Mock::VerifyAndClearExpectations(&pastlastByteTxCb); } @@ -4531,7 +4531,7 @@ TEST_F(QuicTransportTest, NotifyPendingWriteConnDuringClose) { } else { EXPECT_CALL(writeCallback_, onStreamWriteError(streamId, _)); } - transport_->close(none); + transport_->close(std::nullopt); })); PacketNum num = 10; // Give the conn some headroom. @@ -4571,7 +4571,7 @@ TEST_F(QuicTransportTest, NotifyPendingWriteStreamDuringClose) { EXPECT_CALL(connCallback_, onFlowControlUpdate(stream->id)); EXPECT_CALL(writeCallback_, onStreamWriteError(streamId2, _)); EXPECT_CALL(writeCallback_, onStreamWriteReady(stream->id, _)) - .WillOnce(Invoke([&](auto, auto) { transport_->close(none); })); + .WillOnce(Invoke([&](auto, auto) { transport_->close(std::nullopt); })); transport_->onNetworkData( SocketAddress("::1", 10000), NetworkData(ReceivedUdpPacket(IOBuf::copyBuffer("fake data")))); @@ -4663,7 +4663,7 @@ TEST_F(QuicTransportTest, WriteStreamFromMiddleOfMap) { if (oldWriteQueue) { oldWriteQueue->setNextScheduledStream(s2); } else { - conn.streamManager->writeQueue().getNextScheduledID(quic::none); + conn.streamManager->writeQueue().getNextScheduledID(std::nullopt); } writableBytes = kDefaultUDPSendPacketLen; EXPECT_CALL(*socket_, write(_, _, _)) @@ -4691,7 +4691,7 @@ TEST_F(QuicTransportTest, WriteStreamFromMiddleOfMap) { const WriteStreamFrame* streamFrame4 = frame4.asWriteStreamFrame(); EXPECT_TRUE(streamFrame4); EXPECT_EQ(streamFrame4->streamId, s1); - transport_->close(none); + transport_->close(std::nullopt); } TEST_F(QuicTransportTest, NoStream) { @@ -4802,7 +4802,7 @@ TEST_F(QuicTransportTest, CloseTransportCancelsAckTimeout) { transport_->scheduleLossTimeout(500ms); EXPECT_TRUE(transport_->isLossTimeoutScheduled()); - transport_->closeNow(none); + transport_->closeNow(std::nullopt); EXPECT_FALSE(transport_->getAckTimeout()->isTimerCallbackScheduled()); EXPECT_FALSE(transport_->isLossTimeoutScheduled()); } @@ -4816,7 +4816,7 @@ TEST_F(QuicTransportTest, DrainTimeoutExpired) { TEST_F(QuicTransportTest, CloseWithDrainWillKeepSocketAround) { EXPECT_CALL(*socket_, pauseRead()).Times(0); EXPECT_CALL(*socket_, close()).Times(0); - transport_->close(none); + transport_->close(std::nullopt); // Manual shut it, otherwise transport_'s dtor will shut the socket and mess // up the EXPECT_CALLs above @@ -5149,7 +5149,7 @@ TEST_F(QuicTransportTest, PrioritySetAndGet) { auto nonExistStreamPri = transport_->getStreamPriority(stream + 4); EXPECT_TRUE(nonExistStreamPri.hasError()); EXPECT_EQ(LocalErrorCode::STREAM_NOT_EXISTS, nonExistStreamPri.error()); - transport_->close(none); + transport_->close(std::nullopt); auto closedConnStreamPri = transport_->getStreamPriority(stream); EXPECT_TRUE(closedConnStreamPri.hasError()); EXPECT_EQ(LocalErrorCode::CONNECTION_CLOSED, closedConnStreamPri.error()); diff --git a/quic/api/test/QuicTypedTransportTest.cpp b/quic/api/test/QuicTypedTransportTest.cpp index 6e4f996a0..e0023299f 100644 --- a/quic/api/test/QuicTypedTransportTest.cpp +++ b/quic/api/test/QuicTypedTransportTest.cpp @@ -401,7 +401,7 @@ TYPED_TEST(QuicTypedTransportAfterStartTest, RttSampleAckDelayGreater) { // || [ Value Expected ] | // Case | RTT (delay) | RTT w/o delay || mRTT | w/o ACK delay | Updated // -----|-------------|---------------||------- |----------------|---------- - // 1 | 25ms (26 ms)| 25ms || 25 | none | (1) + // 1 | 25ms (26 ms)| 25ms || 25 | std::nullopt | (1) { const auto rtt = 25ms; const auto ackDelay = 26ms; @@ -928,10 +928,9 @@ TYPED_TEST( auto rawPacketProcessor = mockPacketProcessor.get(); this->getNonConstConn().packetProcessors.push_back( std::move(mockPacketProcessor)); - EXPECT_CALL(*rawPacketProcessor, prewrite()).Times(1).WillOnce([]() { PacketProcessor::PrewriteRequest req; - req.cmsgs.assign({{{IPPROTO_IPV6, IPV6_HOPLIMIT}, 255}}); + req.cmsgs = {{{IPPROTO_IPV6, IPV6_HOPLIMIT}, 255}}; return req; }); @@ -943,7 +942,7 @@ TYPED_TEST( EXPECT_CALL(*rawPacketProcessor2, prewrite()).Times(1).WillOnce([]() { PacketProcessor::PrewriteRequest req; - req.cmsgs.assign({{{IPPROTO_IPV6, IPV6_DONTFRAG}, 1}}); + req.cmsgs = {{{IPPROTO_IPV6, IPV6_DONTFRAG}, 1}}; return req; }); @@ -956,7 +955,7 @@ TYPED_TEST( EXPECT_CALL(*rawPacketProcessor3, prewrite()).Times(1).WillOnce([]() { PacketProcessor::PrewriteRequest req; - req.cmsgs.assign({{{IPPROTO_IPV6, IPV6_DONTFRAG}, 0}}); + req.cmsgs = {{{IPPROTO_IPV6, IPV6_DONTFRAG}, 0}}; return req; }); @@ -993,7 +992,7 @@ TYPED_TEST( // Send two packets with the same marking EXPECT_CALL(*rawPacketProcessor, prewrite()).Times(1).WillOnce([]() { PacketProcessor::PrewriteRequest req; - req.cmsgs.assign({{{IPPROTO_IPV6, IPV6_HOPLIMIT}, 255}}); + req.cmsgs = {{{IPPROTO_IPV6, IPV6_HOPLIMIT}, 255}}; return req; }); auto streamId = this->getTransport()->createBidirectionalStream().value(); @@ -1014,7 +1013,7 @@ TYPED_TEST( { // Send two packets with no marking EXPECT_CALL(*rawPacketProcessor, prewrite()).Times(1).WillOnce([]() { - return none; + return std::nullopt; }); auto streamId = this->getTransport()->createBidirectionalStream().value(); const auto bufLength = 1700; // Two packets @@ -1035,7 +1034,7 @@ TYPED_TEST( // Send two packets with the same marking EXPECT_CALL(*rawPacketProcessor, prewrite()).Times(1).WillOnce([]() { PacketProcessor::PrewriteRequest req; - req.cmsgs.assign({{{IPPROTO_IPV6, IPV6_HOPLIMIT}, 255}}); + req.cmsgs = {{{IPPROTO_IPV6, IPV6_HOPLIMIT}, 255}}; return req; }); auto streamId = this->getTransport()->createBidirectionalStream().value(); @@ -1252,7 +1251,7 @@ TYPED_TEST(QuicTypedTransportAfterStartTest, HandleIncomingKeyUpdate) { // // the following technically ignores lost ACK packets from peer, but // // should meet the needs of the majority of tests... // getConn().ackStates.appDataAckState.largestAckedByPeer.value_or(0), - none /* longHeaderOverride */, + std::nullopt /* longHeaderOverride */, false /* eof */, ProtectionType::KeyPhaseZero)); pktBuf->coalesce(); @@ -1874,12 +1873,13 @@ TYPED_TEST( transport, AllOf( // should not be equal to an empty event - testing::Ne(SocketObserverInterface::CloseStartedEvent{none}), + testing::Ne( + SocketObserverInterface::CloseStartedEvent{std::nullopt}), // should be equal to a populated event with default error testing::Eq( SocketObserverInterface::CloseStartedEvent{defaultError})))); EXPECT_CALL(*observer, closing(transport, _)); - transport->close(none); + transport->close(std::nullopt); Mock::VerifyAndClearExpectations(observer.get()); EXPECT_CALL(*observer, destroyed(transport, IsNull())); this->destroyTransport(); @@ -1913,11 +1913,12 @@ TYPED_TEST( transport, AllOf( // should not be equal to an empty event - testing::Ne(SocketObserverInterface::CloseStartedEvent{none}), + testing::Ne( + SocketObserverInterface::CloseStartedEvent{std::nullopt}), // should be equal to a populated event with default error testing::Eq( SocketObserverInterface::CloseStartedEvent{defaultError})))); - transport->close(none); + transport->close(std::nullopt); // wait for the drain EXPECT_CALL(*observer, closing(transport, _)); @@ -1962,11 +1963,12 @@ TYPED_TEST( transport, AllOf( // should not be equal to an empty event - testing::Ne(SocketObserverInterface::CloseStartedEvent{none}), + testing::Ne( + SocketObserverInterface::CloseStartedEvent{std::nullopt}), // should be equal to a populated event with default error testing::Eq( SocketObserverInterface::CloseStartedEvent{defaultError})))); - transport->close(none); + transport->close(std::nullopt); Mock::VerifyAndClearExpectations(observer.get()); // destroy transport without waiting for drain @@ -2002,7 +2004,8 @@ TYPED_TEST( transport, AllOf( // should not be equal to an empty event - testing::Ne(SocketObserverInterface::CloseStartedEvent{none}), + testing::Ne( + SocketObserverInterface::CloseStartedEvent{std::nullopt}), // should be equal to a populated event with default error testing::Eq( SocketObserverInterface::CloseStartedEvent{testError})))); @@ -2043,7 +2046,8 @@ TYPED_TEST( transport, AllOf( // should not be equal to an empty event - testing::Ne(SocketObserverInterface::CloseStartedEvent{none}), + testing::Ne( + SocketObserverInterface::CloseStartedEvent{std::nullopt}), // should be equal to a populated event with default error testing::Eq( SocketObserverInterface::CloseStartedEvent{testError})))); @@ -3864,10 +3868,10 @@ TYPED_TEST( testing::Eq(writeCount)), testing::Field( &SocketObserverInterface::WriteEvent::maybeCwndInBytes, - testing::Eq(Optional(none))), + testing::Eq(Optional(std::nullopt))), testing::Field( &SocketObserverInterface::WriteEvent::maybeWritableBytes, - testing::Eq(Optional(none))), + testing::Eq(Optional(std::nullopt))), testing::Field( &SocketObserverInterface::PacketsWrittenEvent::numPacketsWritten, testing::Eq(1)), diff --git a/quic/api/test/QuicTypedTransportTestUtil.h b/quic/api/test/QuicTypedTransportTestUtil.h index c29d24aca..9ab64f85e 100644 --- a/quic/api/test/QuicTypedTransportTestUtil.h +++ b/quic/api/test/QuicTypedTransportTestUtil.h @@ -52,7 +52,8 @@ class QuicTypedTransportTestBase : protected QuicTransportTestClass { * * If new AppData packets written, returns packet numbers in interval. * - * @return Interval of newly written AppData packet numbers, or none. + * @return Interval of newly written AppData packet numbers, or + * std::nullopt. */ Optional loopForWrites() { // store the next packet number @@ -72,7 +73,7 @@ class QuicTypedTransportTestBase : protected QuicTransportTestClass { true /* includeDeclaredLost */); if (it == getConn().outstandings.packets.rend()) { - return none; + return std::nullopt; } const auto& packet = it->packet; const auto& metadata = it->metadata; @@ -82,7 +83,7 @@ class QuicTypedTransportTestBase : protected QuicTransportTestClass { // if packet number of last AppData packet < nextAppDataPacketNum, then // we sent nothing new and we have nothing to do... if (lastAppDataPacketNum < preSendNextAppDataPacketNum) { - return none; + return std::nullopt; } // we sent new AppData packets @@ -235,7 +236,7 @@ class QuicTypedTransportTestBase : protected QuicTransportTestClass { quic::BufPtr buildPeerPacketWithStreamData( const quic::StreamId streamId, BufPtr data, - Optional shortHeaderProtectionOverride = none) { + Optional shortHeaderProtectionOverride = std::nullopt) { auto buf = quic::test::packetToBuf(createStreamPacket( getSrcConnectionId(), getDstConnectionId(), @@ -247,7 +248,7 @@ class QuicTypedTransportTestBase : protected QuicTransportTestClass { // // the following technically ignores lost ACK packets from peer, but // // should meet the needs of the majority of tests... // getConn().ackStates.appDataAckState.largestAckedByPeer.value_or(0), - none /* longHeaderOverride */, + std::nullopt /* longHeaderOverride */, false /* eof */, shortHeaderProtectionOverride)); buf->coalesce(); @@ -268,7 +269,7 @@ class QuicTypedTransportTestBase : protected QuicTransportTestClass { *data /* stream data */, 0 /* cipherOverhead */, 0 /* largest acked */, - none /* longHeaderOverride */, + std::nullopt /* longHeaderOverride */, true /* eof */)); buf->coalesce(); @@ -467,7 +468,7 @@ class QuicTypedTransportTestBase : protected QuicTransportTestClass { getNonConstConn().outstandings.packets.end(), findFrameInPacketFunc()); if (packetItr == getNonConstConn().outstandings.packets.end()) { - return none; + return std::nullopt; } return packetItr->packet.header.getPacketSequenceNum(); } @@ -503,8 +504,12 @@ class QuicTypedTransportTestBase : protected QuicTransportTestClass { auto go() && { uint64_t sum = 0; - const auto& streamId = *CHECK_NOTNULL(maybeStreamId.get_pointer()); - const auto& packetNums = *CHECK_NOTNULL(maybePacketNums.get_pointer()); + CHECK(maybeStreamId.has_value()) << "Stream ID must be set"; + const auto& streamId = maybeStreamId.value(); + + CHECK(maybePacketNums.has_value()) << "Packet numbers must be set"; + const auto& packetNums = maybePacketNums.value(); + for (const auto& packetNum : packetNums) { const auto packetItr = std::find_if( testObj->getNonConstConn().outstandings.packets.begin(), diff --git a/quic/api/test/TestQuicTransport.h b/quic/api/test/TestQuicTransport.h index 114e9c962..701979865 100644 --- a/quic/api/test/TestQuicTransport.h +++ b/quic/api/test/TestQuicTransport.h @@ -65,7 +65,7 @@ class TestQuicTransport Optional> getPeerTransportParams() const override { - return none; + return std::nullopt; } QuicVersion getVersion() { @@ -202,7 +202,7 @@ class TestQuicTransport const std::string&, const Optional&, uint16_t) const override { - return none; + return std::nullopt; } void validateECN() { diff --git a/quic/client/QuicClientTransportLite.cpp b/quic/client/QuicClientTransportLite.cpp index 92a5a75a8..addf64afa 100644 --- a/quic/client/QuicClientTransportLite.cpp +++ b/quic/client/QuicClientTransportLite.cpp @@ -534,7 +534,7 @@ QuicClientTransportLite::processUdpPacketData( RstStreamFrame& frame = *quicFrame.asRstStreamFrame(); VLOG(10) << "Client received reset stream=" << frame.streamId << " " << *this; - if (frame.reliableSize.hasValue()) { + if (frame.reliableSize.has_value()) { // We're not yet supporting the handling of RESET_STREAM_AT frames return folly::makeUnexpected(QuicError( TransportErrorCode::PROTOCOL_VIOLATION, @@ -2136,7 +2136,7 @@ QuicClientTransportLite::getPeerTransportParams() const { return maybeParams->parameters; } } - return none; + return std::nullopt; } void QuicClientTransportLite::setCongestionControl(CongestionControlType type) { diff --git a/quic/client/connector/QuicConnector.cpp b/quic/client/connector/QuicConnector.cpp index e741ca7a8..10a5289e8 100644 --- a/quic/client/connector/QuicConnector.cpp +++ b/quic/client/connector/QuicConnector.cpp @@ -71,7 +71,7 @@ void QuicConnector::connect( 0 /* connectionIdSize */); quicClient_->setHostname(sni.value_or(connectAddr.getAddressStr())); quicClient_->addNewPeerAddress(connectAddr); - if (localAddr.hasValue()) { + if (localAddr.has_value()) { quicClient_->setLocalAddress(*localAddr); } quicClient_->setCongestionControllerFactory( diff --git a/quic/client/connector/QuicConnector.h b/quic/client/connector/QuicConnector.h index 67cedf0b3..7d841fce1 100644 --- a/quic/client/connector/QuicConnector.h +++ b/quic/client/connector/QuicConnector.h @@ -56,7 +56,7 @@ class QuicConnector : private quic::QuicSocket::ConnectionSetupCallback, std::chrono::milliseconds connectTimeout = std::chrono::milliseconds(1000), const folly::SocketOptionMap& socketOptions = folly::emptySocketOptionMap, - const Optional& sni = none, + const Optional& sni = std::nullopt, std::shared_ptr qLogger = nullptr, std::shared_ptr quicLoopDetectorCallback = nullptr, diff --git a/quic/client/handshake/ClientHandshake.h b/quic/client/handshake/ClientHandshake.h index 950cc4444..eec9cd3f8 100644 --- a/quic/client/handshake/ClientHandshake.h +++ b/quic/client/handshake/ClientHandshake.h @@ -87,7 +87,7 @@ class ClientHandshake : public Handshake { /** * Edge triggered api to obtain whether or not zero rtt data was rejected. - * If zero rtt was never attempted, then this will return none. Once + * If zero rtt was never attempted, then this will return std::nullopt. Once * the result is obtained, the result is cleared out. */ Optional getZeroRttRejected(); diff --git a/quic/client/state/ClientStateMachine.cpp b/quic/client/state/ClientStateMachine.cpp index 4bebf85a9..94a219da9 100644 --- a/quic/client/state/ClientStateMachine.cpp +++ b/quic/client/state/ClientStateMachine.cpp @@ -288,14 +288,14 @@ folly::Expected processServerInitialParams( isAckReceiveTimestampsEnabled.value() == 1) { if (maxReceiveTimestampsPerAck.has_value() && receiveTimestampsExponent.has_value()) { - conn.maybePeerAckReceiveTimestampsConfig.assign( - {std::min( - static_cast(maxReceiveTimestampsPerAck.value()), - static_cast( - conn.transportSettings.maxReceiveTimestampsPerAckStored)), - std::max( - static_cast(receiveTimestampsExponent.value()), - static_cast(0))}); + conn.maybePeerAckReceiveTimestampsConfig = AckReceiveTimestampsConfig{ + std::min( + static_cast(maxReceiveTimestampsPerAck.value()), + static_cast( + conn.transportSettings.maxReceiveTimestampsPerAckStored)), + std::max( + static_cast(receiveTimestampsExponent.value()), + static_cast(0))}; } } @@ -335,16 +335,16 @@ void cacheServerInitialParams( peerAdvertisedReliableStreamResetSupport; if (peerAdvertisedAckReceiveTimestampsEnabled) { - conn.maybePeerAckReceiveTimestampsConfig.assign( - {std::min( - static_cast(peerAdvertisedMaxReceiveTimestampsPerAck), - static_cast( - conn.transportSettings.maxReceiveTimestampsPerAckStored)), - std::max( - static_cast(peerAdvertisedReceiveTimestampsExponent), - static_cast(0))}); + conn.maybePeerAckReceiveTimestampsConfig = AckReceiveTimestampsConfig{ + std::min( + static_cast(peerAdvertisedMaxReceiveTimestampsPerAck), + static_cast( + conn.transportSettings.maxReceiveTimestampsPerAckStored)), + std::max( + static_cast(peerAdvertisedReceiveTimestampsExponent), + static_cast(0))}; } else { - conn.maybePeerAckReceiveTimestampsConfig.clear(); + conn.maybePeerAckReceiveTimestampsConfig = std::nullopt; } conn.peerAdvertisedExtendedAckFeatures = peerAdvertisedExtendedAckFeatures; } @@ -411,16 +411,16 @@ updateTransportParamsFromCachedEarlyParams( conn.peerAdvertisedReliableStreamResetSupport = transportParams.reliableStreamResetSupport; if (transportParams.ackReceiveTimestampsEnabled) { - conn.maybePeerAckReceiveTimestampsConfig.assign( - {std::min( - static_cast(transportParams.maxReceiveTimestampsPerAck), - static_cast( - conn.transportSettings.maxReceiveTimestampsPerAckStored)), - std::max( - static_cast(transportParams.receiveTimestampsExponent), - static_cast(0))}); + conn.maybePeerAckReceiveTimestampsConfig = AckReceiveTimestampsConfig{ + std::min( + static_cast(transportParams.maxReceiveTimestampsPerAck), + static_cast( + conn.transportSettings.maxReceiveTimestampsPerAckStored)), + std::max( + static_cast(transportParams.receiveTimestampsExponent), + static_cast(0))}; } else { - conn.maybePeerAckReceiveTimestampsConfig.clear(); + conn.maybePeerAckReceiveTimestampsConfig = std::nullopt; } conn.peerAdvertisedExtendedAckFeatures = transportParams.extendedAckFeatures; return folly::unit; diff --git a/quic/client/test/ClientStateMachineTest.cpp b/quic/client/test/ClientStateMachineTest.cpp index 457fbd283..580e38b01 100644 --- a/quic/client/test/ClientStateMachineTest.cpp +++ b/quic/client/test/ClientStateMachineTest.cpp @@ -83,8 +83,8 @@ TEST_F(ClientStateMachineTest, TestUpdateTransportParamsFromCachedEarlyParams) { client_->transportSettings.canIgnorePathMTU = true; client_->peerAdvertisedKnobFrameSupport = false; client_->peerAdvertisedExtendedAckFeatures = 0; - client_->maybePeerAckReceiveTimestampsConfig.assign( - {.maxReceiveTimestampsPerAck = 10, .receiveTimestampsExponent = 0}); + client_->maybePeerAckReceiveTimestampsConfig = { + .maxReceiveTimestampsPerAck = 10, .receiveTimestampsExponent = 0}; ASSERT_FALSE( updateTransportParamsFromCachedEarlyParams(*client_, kParams).hasError()); diff --git a/quic/client/test/QuicClientTransportTest.cpp b/quic/client/test/QuicClientTransportTest.cpp index 3d67f0e59..a30d65852 100644 --- a/quic/client/test/QuicClientTransportTest.cpp +++ b/quic/client/test/QuicClientTransportTest.cpp @@ -127,7 +127,7 @@ class QuicClientTransportTest : public Test { } void TearDown() override { - quicClient_->closeNow(folly::none); + quicClient_->closeNow(std::nullopt); } std::shared_ptr evb_; diff --git a/quic/codec/Decode.cpp b/quic/codec/Decode.cpp index c8b06ea37..af41a005c 100644 --- a/quic/codec/Decode.cpp +++ b/quic/codec/Decode.cpp @@ -440,7 +440,7 @@ folly::Expected decodeRstStreamFrame( return folly::makeUnexpected(QuicError( quic::TransportErrorCode::FRAME_ENCODING_ERROR, "Bad offset")); } - folly::Optional> reliableSize = folly::none; + Optional> reliableSize = std::nullopt; if (reliable) { reliableSize = decodeQuicInteger(cursor); if (!reliableSize) { @@ -459,8 +459,7 @@ folly::Expected decodeRstStreamFrame( folly::to(streamId->first), errorCode, finalSize->first, - reliableSize ? folly::Optional(reliableSize->first) - : folly::none); + reliableSize ? Optional(reliableSize->first) : std::nullopt); } folly::Expected decodeStopSendingFrame( @@ -1239,7 +1238,7 @@ Optional decodeVersionNegotiation( if (cursorLength < sizeof(QuicVersionType) || cursorLength % sizeof(QuicVersionType)) { VLOG(4) << "Version negotiation packet invalid"; - return none; + return std::nullopt; } VersionNegotiationPacket packet( @@ -1375,7 +1374,7 @@ folly::Expected parseLongHeader( auto version = parsedLongHeaderInvariant->invariant.version; if (version == QuicVersion::VERSION_NEGOTIATION) { - return ParsedLongHeaderResult(true, none); + return ParsedLongHeaderResult(true, std::nullopt); } auto parsedHeader = parseLongHeaderVariants( type, std::move(*parsedLongHeaderInvariant), cursor); diff --git a/quic/codec/Decode.h b/quic/codec/Decode.h index 1dbec92ca..9ca8dd151 100644 --- a/quic/codec/Decode.h +++ b/quic/codec/Decode.h @@ -23,7 +23,8 @@ struct CodecParameters { // This must not be set to zero. uint8_t peerAckDelayExponent{kDefaultAckDelayExponent}; QuicVersion version{QuicVersion::MVFST}; - Optional maybeAckReceiveTimestampsConfig = none; + Optional maybeAckReceiveTimestampsConfig = + std::nullopt; ExtendedAckFeatureMaskType extendedAckFeatures{0}; CodecParameters() = default; @@ -55,7 +56,7 @@ struct ParsedLongHeaderInvariant { }; /** - * Decodes a version negotiation packet. Returns a none, if it cannot + * Decodes a version negotiation packet. Returns a std::nullopt, if it cannot * decode the packet. */ Optional decodeVersionNegotiation( diff --git a/quic/codec/QuicHeaderCodec.cpp b/quic/codec/QuicHeaderCodec.cpp index 039bb0fb8..bcba87f2c 100644 --- a/quic/codec/QuicHeaderCodec.cpp +++ b/quic/codec/QuicHeaderCodec.cpp @@ -29,7 +29,7 @@ folly::Expected parseHeader( return parseLongHeader(initialByte, cursor) .then([](ParsedLongHeaderResult&& parsedLongHeaderResult) { if (parsedLongHeaderResult.isVersionNegotiation) { - return ParsedHeaderResult(true, none); + return ParsedHeaderResult(true, std::nullopt); } // We compensate for the type byte length by adding it back. DCHECK(parsedLongHeaderResult.parsedLongHeader); diff --git a/quic/codec/QuicInteger.cpp b/quic/codec/QuicInteger.cpp index e35ca5ee6..ff05ee72c 100644 --- a/quic/codec/QuicInteger.cpp +++ b/quic/codec/QuicInteger.cpp @@ -36,7 +36,7 @@ Optional> decodeQuicInteger( if (atMost == 0 || !cursor.canAdvance(1)) { VLOG(10) << "Not enough bytes to decode integer, cursor len=" << cursor.totalLength(); - return none; + return std::nullopt; } // get 2 msb of first byte that determines variable-length size expected @@ -53,7 +53,7 @@ Optional> decodeQuicInteger( // not enough bytes to decode, undo cursor if (!cursor.canAdvance(bytesExpected) || atMost < bytesExpected) { VLOG(10) << "Could not decode integer numBytes=" << bytesExpected; - return none; + return std::nullopt; } // result storage uint64_t result{0}; diff --git a/quic/codec/QuicInteger.h b/quic/codec/QuicInteger.h index d01b1f687..42fe93be6 100644 --- a/quic/codec/QuicInteger.h +++ b/quic/codec/QuicInteger.h @@ -97,7 +97,7 @@ encodeQuicInteger(uint64_t value, BufOp bufop, int outputSize) { /** * Reads an integer out of the cursor and returns a pair with the integer and - * the numbers of bytes read, or none if there are not enough bytes to + * the numbers of bytes read, or std::nullopt if there are not enough bytes to * read the int. It only advances the cursor in case of success. */ Optional> decodeQuicInteger( diff --git a/quic/codec/QuicPacketBuilder.cpp b/quic/codec/QuicPacketBuilder.cpp index abef714f8..a0b0c9337 100644 --- a/quic/codec/QuicPacketBuilder.cpp +++ b/quic/codec/QuicPacketBuilder.cpp @@ -108,7 +108,7 @@ Optional encodeShortHeaderHelper( if (spaceCounter < 1U + packetNumberEncoding.length + shortHeader.getConnectionId().size()) { spaceCounter = 0; - return none; + return std::nullopt; } uint8_t initialByte = ShortHeader::kFixedBitMask | (packetNumberEncoding.length - 1); @@ -254,7 +254,7 @@ void RegularQuicPacketBuilder::markNonEmpty() { } RegularQuicPacketBuilder::Packet RegularQuicPacketBuilder::buildPacket() && { - CHECK(packetNumberEncoding_.hasValue()); + CHECK(packetNumberEncoding_.has_value()); // at this point everything should been set in the packet_ LongHeader* longHeader = packet_.header.asLong(); size_t minBodySize = kMaxPacketNumEncodingSize - @@ -313,7 +313,7 @@ void RegularQuicPacketBuilder::push(const uint8_t* data, size_t len) { } bool RegularQuicPacketBuilder::canBuildPacket() const noexcept { - return remainingBytes_ != 0 && packetNumberEncoding_.hasValue(); + return remainingBytes_ != 0 && packetNumberEncoding_.has_value(); } const PacketHeader& RegularQuicPacketBuilder::getPacketHeader() const { @@ -729,7 +729,7 @@ const PacketHeader& InplaceQuicPacketBuilder::getPacketHeader() const { } PacketBuilderInterface::Packet InplaceQuicPacketBuilder::buildPacket() && { - CHECK(packetNumberEncoding_.hasValue()); + CHECK(packetNumberEncoding_.has_value()); LongHeader* longHeader = packet_.header.asLong(); size_t minBodySize = kMaxPacketNumEncodingSize - packetNumberEncoding_->length + sizeof(Sample); @@ -802,7 +802,7 @@ void InplaceQuicPacketBuilder::push(const uint8_t* data, size_t len) { } bool InplaceQuicPacketBuilder::canBuildPacket() const noexcept { - return remainingBytes_ != 0 && packetNumberEncoding_.hasValue(); + return remainingBytes_ != 0 && packetNumberEncoding_.has_value(); } uint32_t InplaceQuicPacketBuilder::getHeaderBytes() const { @@ -840,7 +840,7 @@ InplaceQuicPacketBuilder::~InplaceQuicPacketBuilder() { folly::Expected RegularQuicPacketBuilder::encodePacketHeader() { - CHECK(!packetNumberEncoding_.hasValue()); + CHECK(!packetNumberEncoding_.has_value()); if (packet_.header.getHeaderForm() == HeaderForm::Long) { LongHeader& longHeader = *packet_.header.asLong(); auto result = encodeLongHeader(longHeader, largestAckedPacketNum_); @@ -856,7 +856,7 @@ RegularQuicPacketBuilder::encodePacketHeader() { folly::Expected InplaceQuicPacketBuilder::encodePacketHeader() { - CHECK(!packetNumberEncoding_.hasValue()); + CHECK(!packetNumberEncoding_.has_value()); if (packet_.header.getHeaderForm() == HeaderForm::Long) { LongHeader& longHeader = *packet_.header.asLong(); auto encodingResult = encodeLongHeaderHelper( diff --git a/quic/codec/QuicPacketRebuilder.cpp b/quic/codec/QuicPacketRebuilder.cpp index 8724e547e..925ee1bdf 100644 --- a/quic/codec/QuicPacketRebuilder.cpp +++ b/quic/codec/QuicPacketRebuilder.cpp @@ -257,7 +257,7 @@ PacketRebuilder::rebuildFromPacket(OutstandingPacketWrapper& packet) { } } if (!writeSuccess) { - return none; + return std::nullopt; } } @@ -282,7 +282,7 @@ PacketRebuilder::rebuildFromPacket(OutstandingPacketWrapper& packet) { // (2) we should write window update, but didn't, and wrote nothing else. if (!notPureAck || (shouldWriteWindowUpdate && !windowUpdateWritten && !writeSuccess)) { - return none; + return std::nullopt; } if (encryptionLevel == EncryptionLevel::Initial) { diff --git a/quic/codec/QuicReadCodec.cpp b/quic/codec/QuicReadCodec.cpp index 900043bb0..af8daf8c5 100644 --- a/quic/codec/QuicReadCodec.cpp +++ b/quic/codec/QuicReadCodec.cpp @@ -26,22 +26,22 @@ Optional QuicReadCodec::tryParsingVersionNegotiation( BufQueue& queue) { Cursor cursor(queue.front()); if (!cursor.canAdvance(sizeof(uint8_t))) { - return none; + return std::nullopt; } uint8_t initialByte = cursor.readBE(); auto headerForm = getHeaderForm(initialByte); if (headerForm != HeaderForm::Long) { - return none; + return std::nullopt; } auto longHeaderInvariant = parseLongHeaderInvariant(initialByte, cursor); if (!longHeaderInvariant) { // if it is an invalid packet, it's definitely not a VN packet, so ignore // it. - return none; + return std::nullopt; } if (longHeaderInvariant->invariant.version != QuicVersion::VERSION_NEGOTIATION) { - return none; + return std::nullopt; } return decodeVersionNegotiation(*longHeaderInvariant, cursor); } diff --git a/quic/codec/QuicReadCodec.h b/quic/codec/QuicReadCodec.h index 282bc3579..8485be93e 100644 --- a/quic/codec/QuicReadCodec.h +++ b/quic/codec/QuicReadCodec.h @@ -124,7 +124,7 @@ class QuicReadCodec { /** * Tries to parse the packet and returns whether or not * it is a version negotiation packet. - * This returns none if the packet is either not + * This returns std::nullopt if the packet is either not * a VN packet or is invalid. */ Optional tryParsingVersionNegotiation( diff --git a/quic/codec/QuicWriteCodec.cpp b/quic/codec/QuicWriteCodec.cpp index 02e2c47e5..e75e92632 100644 --- a/quic/codec/QuicWriteCodec.cpp +++ b/quic/codec/QuicWriteCodec.cpp @@ -37,7 +37,7 @@ folly::Expected, QuicError> writeStreamFrameHeader( OptionalIntegral streamGroupId, bool appendFrame) { if (builder.remainingSpaceInPkt() == 0) { - return none; + return std::nullopt; } if (writeBufferLen == 0 && !fin) { return folly::makeUnexpected(QuicError( @@ -71,7 +71,7 @@ folly::Expected, QuicError> writeStreamFrameHeader( if (builder.remainingSpaceInPkt() < headerSize) { VLOG(4) << "No space in packet for stream header. stream=" << id << " remaining=" << builder.remainingSpaceInPkt(); - return none; + return std::nullopt; } QuicInteger offsetInt(offset); if (offset != 0) { @@ -124,7 +124,7 @@ folly::Expected, QuicError> writeStreamFrameHeader( headerSize + dataLenLen >= builder.remainingSpaceInPkt()) { VLOG(4) << "No space in packet for stream header. stream=" << id << " remaining=" << builder.remainingSpaceInPkt(); - return none; + return std::nullopt; } // We have to encode the actual data length in the header. headerSize += dataLenLen; @@ -135,12 +135,12 @@ folly::Expected, QuicError> writeStreamFrameHeader( bool shouldSetFin = fin && dataLen == writeBufferLen; if (dataLen == 0 && !shouldSetFin) { // This would be an empty non-fin stream frame. - return none; + return std::nullopt; } if (builder.remainingSpaceInPkt() < headerSize) { VLOG(4) << "No space in packet for stream header. stream=" << id << " remaining=" << builder.remainingSpaceInPkt(); - return none; + return std::nullopt; } // Done with the accounting, set the bits and write the actual frame header. @@ -173,7 +173,7 @@ folly::Expected, QuicError> writeStreamFrameHeader( } else { builder.markNonEmpty(); } - return folly::make_optional(dataLen); + return dataLen; } void writeStreamFrameData( @@ -209,7 +209,7 @@ folly::Expected, QuicError> writeCryptoFrame( if (spaceLeftInPkt <= cryptoFrameHeaderSize) { VLOG(3) << "No space left in packet to write cryptoFrame header of size: " << cryptoFrameHeaderSize << ", space left=" << spaceLeftInPkt; - return Optional(none); + return Optional(std::nullopt); } size_t spaceRemaining = spaceLeftInPkt - cryptoFrameHeaderSize; size_t dataLength = data.chainLength(); @@ -511,7 +511,7 @@ maybeWriteAckBaseFields( firstAckBlockLengthIntSize.value(); if (spaceLeft < headerSize) { - return Optional(none); + return Optional(std::nullopt); } WriteAckFrame ackFrame; ackFrame.frameType = frameType; @@ -713,7 +713,7 @@ folly::Expected, QuicError> writeAckFrame( uint64_t maxRecvTimestampsToSend, ExtendedAckFeatureMaskType extendedAckFeatures) { if (ackFrameMetaData.ackState.acks.empty()) { - return Optional(none); + return Optional(std::nullopt); } uint64_t beginningSpace = builder.remainingSpaceInPkt(); uint64_t spaceLeft = beginningSpace; @@ -738,7 +738,7 @@ folly::Expected, QuicError> writeAckFrame( } auto extendedAckRequiredSpace = extendedAckRequiredSpaceResult.value(); if (spaceLeft < extendedAckRequiredSpace) { - return Optional(none); + return Optional(std::nullopt); } spaceLeft -= extendedAckRequiredSpace; } @@ -751,7 +751,7 @@ folly::Expected, QuicError> writeAckFrame( } auto ecnRequiredSpace = ecnRequiredSpaceResult.value(); if (spaceLeft < ecnRequiredSpace) { - return Optional(none); + return Optional(std::nullopt); } spaceLeft -= ecnRequiredSpace; } @@ -766,7 +766,7 @@ folly::Expected, QuicError> writeAckFrame( auto receiveTimestampsMinimumSpace = receiveTimestampsMinimumSpaceResult.value(); if (spaceLeft < receiveTimestampsMinimumSpace) { - return Optional(none); + return Optional(std::nullopt); } spaceLeft -= receiveTimestampsMinimumSpace; } @@ -780,8 +780,8 @@ folly::Expected, QuicError> writeAckFrame( return folly::makeUnexpected(maybeAckFrameResult.error()); } auto& maybeAckFrame = maybeAckFrameResult.value(); - if (!maybeAckFrame.hasValue()) { - return Optional(none); + if (!maybeAckFrame.has_value()) { + return Optional(std::nullopt); } auto& ackFrame = maybeAckFrame.value(); @@ -1158,7 +1158,7 @@ folly::Expected writeFrame( QuicInteger streamId(rstStreamFrame.streamId); QuicInteger finalSize(rstStreamFrame.finalSize); QuicInteger errorCode(static_cast(rstStreamFrame.errorCode)); - folly::Optional maybeReliableSize = folly::none; + Optional maybeReliableSize = std::nullopt; auto intFrameTypeSize = intFrameType.getSize(); if (intFrameTypeSize.hasError()) { return folly::makeUnexpected(intFrameTypeSize.error()); diff --git a/quic/codec/Types.h b/quic/codec/Types.h index 21b582076..375be0500 100644 --- a/quic/codec/Types.h +++ b/quic/codec/Types.h @@ -308,13 +308,13 @@ struct RstStreamFrame { StreamId streamId; ApplicationErrorCode errorCode; uint64_t finalSize; - folly::Optional reliableSize; + Optional reliableSize; RstStreamFrame( StreamId streamIdIn, ApplicationErrorCode errorCodeIn, uint64_t finalSizeIn, - folly::Optional reliableSizeIn = folly::none) + Optional reliableSizeIn = std::nullopt) : streamId(streamIdIn), errorCode(errorCodeIn), finalSize(finalSizeIn), diff --git a/quic/codec/test/DecodeTest.cpp b/quic/codec/test/DecodeTest.cpp index 4f7c7f237..952ac40db 100644 --- a/quic/codec/test/DecodeTest.cpp +++ b/quic/codec/test/DecodeTest.cpp @@ -42,9 +42,9 @@ struct NormalizedAckBlock { template std::unique_ptr createAckFrame( Optional largestAcked, - Optional ackDelay = none, - Optional numAdditionalBlocks = none, - Optional firstAckBlockLength = none, + Optional ackDelay = std::nullopt, + Optional numAdditionalBlocks = std::nullopt, + Optional firstAckBlockLength = std::nullopt, std::vector ackBlocks = {}, bool useRealValuesForLargestAcked = false, bool useRealValuesForAckDelay = false, @@ -100,7 +100,7 @@ std::unique_ptr createRstStreamFrame( StreamId streamId, ApplicationErrorCode errorCode, uint64_t finalSize, - folly::Optional reliableSize = folly::none) { + Optional reliableSize = std::nullopt) { std::unique_ptr rstStreamFrame = folly::IOBuf::create(0); BufAppender wcursor(rstStreamFrame.get(), 10); auto appenderOp = [&](auto val) { wcursor.writeBE(val); }; @@ -136,11 +136,11 @@ std::unique_ptr createRstStreamFrame( template std::unique_ptr createStreamFrame( Optional streamId, - Optional offset = none, - Optional dataLength = none, + Optional offset = std::nullopt, + Optional dataLength = std::nullopt, BufPtr data = nullptr, bool useRealValuesForStreamId = false, - Optional groupId = none) { + Optional groupId = std::nullopt) { std::unique_ptr streamFrame = folly::IOBuf::create(0); BufAppender wcursor(streamFrame.get(), 10); auto appenderOp = [&](auto val) { wcursor.writeBE(val); }; @@ -167,8 +167,8 @@ std::unique_ptr createStreamFrame( } std::unique_ptr createCryptoFrame( - Optional offset = none, - Optional dataLength = none, + Optional offset = std::nullopt, + Optional dataLength = std::nullopt, BufPtr data = nullptr) { std::unique_ptr cryptoFrame = folly::IOBuf::create(0); BufAppender wcursor(cryptoFrame.get(), 10); @@ -369,7 +369,7 @@ TEST_F(DecodeTest, AckExtendedFrameWithECN) { CodecParameters( kDefaultAckDelayExponent, QuicVersion::MVFST, - none, + std::nullopt, static_cast( ExtendedAckFeatureMask::ECN_COUNTS))); ASSERT_TRUE(ackFrameRes.hasValue()); @@ -453,7 +453,7 @@ TEST_F(DecodeTest, AckExtendedFrameThrowsWithUnsupportedFeatures) { CodecParameters( kDefaultAckDelayExponent, QuicVersion::MVFST, - none, + std::nullopt, static_cast( ExtendedAckFeatureMask::RECEIVE_TIMESTAMPS))); EXPECT_TRUE(decodeResult.hasError()); @@ -608,7 +608,11 @@ TEST_F(DecodeTest, AckFrameMissingFields) { ackBlocks.emplace_back(QuicInteger(10), QuicInteger(10)); auto result1 = createAckFrame( - largestAcked, none, numAdditionalBlocks, firstAckBlockLength, ackBlocks); + largestAcked, + std::nullopt, + numAdditionalBlocks, + firstAckBlockLength, + ackBlocks); Cursor cursor1(result1.get()); auto res = decodeAckFrame( @@ -619,7 +623,7 @@ TEST_F(DecodeTest, AckFrameMissingFields) { EXPECT_EQ(res.error().code, TransportErrorCode::FRAME_ENCODING_ERROR); auto result2 = createAckFrame( - largestAcked, ackDelay, none, firstAckBlockLength, ackBlocks); + largestAcked, ackDelay, std::nullopt, firstAckBlockLength, ackBlocks); Cursor cursor2(result2.get()); res = decodeAckFrame( cursor2, @@ -629,7 +633,7 @@ TEST_F(DecodeTest, AckFrameMissingFields) { EXPECT_EQ(res.error().code, TransportErrorCode::FRAME_ENCODING_ERROR); auto result3 = createAckFrame( - largestAcked, ackDelay, none, firstAckBlockLength, ackBlocks); + largestAcked, ackDelay, std::nullopt, firstAckBlockLength, ackBlocks); Cursor cursor3(result3.get()); res = decodeAckFrame( cursor3, @@ -639,7 +643,7 @@ TEST_F(DecodeTest, AckFrameMissingFields) { EXPECT_EQ(res.error().code, TransportErrorCode::FRAME_ENCODING_ERROR); auto result4 = createAckFrame( - largestAcked, ackDelay, numAdditionalBlocks, none, ackBlocks); + largestAcked, ackDelay, numAdditionalBlocks, std::nullopt, ackBlocks); Cursor cursor4(result4.get()); res = decodeAckFrame( cursor4, @@ -784,8 +788,8 @@ TEST_F(DecodeTest, StreamLengthStreamIdInvalid) { QuicInteger streamId(std::numeric_limits::max()); auto streamType = StreamTypeField::Builder().setFin().setOffset().setLength().build(); - auto streamFrame = - createStreamFrame(streamId, none, none, nullptr, true); + auto streamFrame = createStreamFrame( + streamId, std::nullopt, std::nullopt, nullptr, true); BufQueue queue; queue.append(streamFrame->clone()); auto result = decodeStreamFrame(queue, streamType); @@ -798,8 +802,8 @@ TEST_F(DecodeTest, StreamOffsetNotPresent) { QuicInteger length(1); auto streamType = StreamTypeField::Builder().setFin().setOffset().setLength().build(); - auto streamFrame = - createStreamFrame(streamId, none, length, folly::IOBuf::copyBuffer("a")); + auto streamFrame = createStreamFrame( + streamId, std::nullopt, length, folly::IOBuf::copyBuffer("a")); BufQueue queue; queue.append(streamFrame->clone()); auto result = decodeStreamFrame(queue, streamType); @@ -913,7 +917,7 @@ TEST_F(DecodeTest, CryptoDecodeSuccess) { TEST_F(DecodeTest, CryptoOffsetNotPresent) { QuicInteger length(1); auto cryptoFrame = - createCryptoFrame(none, length, folly::IOBuf::copyBuffer("a")); + createCryptoFrame(std::nullopt, length, folly::IOBuf::copyBuffer("a")); Cursor cursor(cryptoFrame.get()); auto result = decodeCryptoFrame(cursor); EXPECT_TRUE(result.hasError()); @@ -922,7 +926,7 @@ TEST_F(DecodeTest, CryptoOffsetNotPresent) { TEST_F(DecodeTest, CryptoLengthNotPresent) { QuicInteger offset(0); - auto cryptoFrame = createCryptoFrame(offset, none, nullptr); + auto cryptoFrame = createCryptoFrame(offset, std::nullopt, nullptr); Cursor cursor(cryptoFrame.get()); auto result = decodeCryptoFrame(cursor); EXPECT_TRUE(result.hasError()); @@ -982,7 +986,7 @@ TEST_F(DecodeTest, DecodeMultiplePaddingTest) { } std::unique_ptr createNewTokenFrame( - Optional tokenLength = none, + Optional tokenLength = std::nullopt, BufPtr token = nullptr) { std::unique_ptr newTokenFrame = folly::IOBuf::create(0); BufAppender wcursor(newTokenFrame.get(), 10); @@ -1006,7 +1010,8 @@ TEST_F(DecodeTest, NewTokenDecodeSuccess) { } TEST_F(DecodeTest, NewTokenLengthNotPresent) { - auto newTokenFrame = createNewTokenFrame(none, folly::IOBuf::copyBuffer("a")); + auto newTokenFrame = + createNewTokenFrame(std::nullopt, folly::IOBuf::copyBuffer("a")); Cursor cursor(newTokenFrame.get()); auto result = decodeNewTokenFrame(cursor); EXPECT_TRUE(result.hasError()); @@ -1122,7 +1127,7 @@ TEST_F(DecodeTest, AckFrequencyFrameDecodeInvalidReserved) { QuicInteger packetTolerance(100); QuicInteger maxAckDelay(100000); // 100 ms auto ackFrequencyFrame = createAckFrequencyFrame( - sequenceNumber, packetTolerance, maxAckDelay, none); + sequenceNumber, packetTolerance, maxAckDelay, std::nullopt); ASSERT_NE(ackFrequencyFrame, nullptr); Cursor cursor(ackFrequencyFrame.get()); @@ -1142,7 +1147,7 @@ TEST_F(DecodeTest, RstStreamFrame) { EXPECT_EQ(rstStreamFrame->streamId, 0); EXPECT_EQ(rstStreamFrame->errorCode, 0); EXPECT_EQ(rstStreamFrame->finalSize, 10); - EXPECT_FALSE(rstStreamFrame->reliableSize.hasValue()); + EXPECT_FALSE(rstStreamFrame->reliableSize.has_value()); } TEST_F(DecodeTest, RstStreamAtFrame) { diff --git a/quic/codec/test/QuicPacketRebuilderTest.cpp b/quic/codec/test/QuicPacketRebuilderTest.cpp index 90d4c1435..3eb00173f 100644 --- a/quic/codec/test/QuicPacketRebuilderTest.cpp +++ b/quic/codec/test/QuicPacketRebuilderTest.cpp @@ -84,7 +84,7 @@ TEST_F(QuicPacketRebuilderTest, RebuildSmallInitial) { ASSERT_FALSE(regularBuilder2.encodePacketHeader().hasError()); auto rebuildResult = rebuilder.rebuildFromPacket(outstanding); ASSERT_FALSE(rebuildResult.hasError()); - ASSERT_TRUE(rebuildResult.value().hasValue()); + ASSERT_TRUE(rebuildResult.value().has_value()); auto rebuilt = std::move(regularBuilder2).buildPacket(); EXPECT_FALSE(rebuilt.header.empty()); ASSERT_EQ(rebuilt.packet.frames.size(), 3); @@ -144,7 +144,7 @@ TEST_F(QuicPacketRebuilderTest, RebuildPacket) { buf->computeChainDataLength(), buf->computeChainDataLength(), true, - none /* skipLenHint */); + std::nullopt /* skipLenHint */); writeStreamFrameData( regularBuilder1, buf->clone(), buf->computeChainDataLength()); ASSERT_FALSE(writeFrame(maxDataFrame, regularBuilder1).hasError()); @@ -167,8 +167,7 @@ TEST_F(QuicPacketRebuilderTest, RebuildPacket) { ChainedByteRangeHead(cryptoBuf), 0, true))); // Write an updated ackState that should be used when rebuilding the AckFrame conn.ackStates.appDataAckState.acks.insert(1000, 1200); - conn.ackStates.appDataAckState.largestRecvdPacketTime.assign( - quic::Clock::now()); + conn.ackStates.appDataAckState.largestRecvdPacketTime = quic::Clock::now(); // rebuild a packet from the built out packet ShortHeader shortHeader2( @@ -180,7 +179,7 @@ TEST_F(QuicPacketRebuilderTest, RebuildPacket) { auto outstanding = makeDummyOutstandingPacket(packet1.packet, 1000); auto rebuildResult = rebuilder.rebuildFromPacket(outstanding); ASSERT_FALSE(rebuildResult.hasError()); - ASSERT_TRUE(rebuildResult.value().hasValue()); + ASSERT_TRUE(rebuildResult.value().has_value()); auto packet2 = std::move(regularBuilder2).buildPacket(); // rebuilder writes frames to regularBuilder2 EXPECT_EQ(packet1.packet.frames.size(), packet2.packet.frames.size()); @@ -280,7 +279,7 @@ TEST_F(QuicPacketRebuilderTest, RebuildAfterResetStream) { buf->computeChainDataLength(), buf->computeChainDataLength(), true, - none /* skipLenHint */); + std::nullopt /* skipLenHint */); writeStreamFrameData( regularBuilder1, buf->clone(), buf->computeChainDataLength()); auto packet1 = std::move(regularBuilder1).buildPacket(); @@ -298,7 +297,7 @@ TEST_F(QuicPacketRebuilderTest, RebuildAfterResetStream) { auto outstanding = makeDummyOutstandingPacket(packet1.packet, 1000); auto rebuildResult = rebuilder.rebuildFromPacket(outstanding); ASSERT_FALSE(rebuildResult.hasError()); - EXPECT_FALSE(rebuildResult.value().hasValue()); + EXPECT_FALSE(rebuildResult.value().has_value()); } TEST_F(QuicPacketRebuilderTest, FinOnlyStreamRebuild) { @@ -316,7 +315,7 @@ TEST_F(QuicPacketRebuilderTest, FinOnlyStreamRebuild) { // Write them with a regular builder writeStreamFrameHeader( - regularBuilder1, streamId, 0, 0, 0, true, none /* skipLenHint */); + regularBuilder1, streamId, 0, 0, 0, true, std::nullopt /* skipLenHint */); auto packet1 = std::move(regularBuilder1).buildPacket(); stream->retransmissionBuffer.emplace( std::piecewise_construct, @@ -334,7 +333,7 @@ TEST_F(QuicPacketRebuilderTest, FinOnlyStreamRebuild) { auto outstanding = makeDummyOutstandingPacket(packet1.packet, 2000); auto rebuildResult = rebuilder.rebuildFromPacket(outstanding); ASSERT_FALSE(rebuildResult.hasError()); - ASSERT_TRUE(rebuildResult.value().hasValue()); + ASSERT_TRUE(rebuildResult.value().has_value()); auto packet2 = std::move(regularBuilder2).buildPacket(); EXPECT_EQ(packet1.packet.frames.size(), packet2.packet.frames.size()); EXPECT_TRUE( @@ -375,7 +374,7 @@ TEST_F(QuicPacketRebuilderTest, RebuildDataStreamAndEmptyCryptoStream) { buf->computeChainDataLength(), buf->computeChainDataLength(), true, - none /* skipLenHint */); + std::nullopt /* skipLenHint */); writeStreamFrameData( regularBuilder1, buf->clone(), buf->computeChainDataLength()); ASSERT_FALSE( @@ -402,7 +401,7 @@ TEST_F(QuicPacketRebuilderTest, RebuildDataStreamAndEmptyCryptoStream) { auto outstanding = makeDummyOutstandingPacket(packet1.packet, 1000); auto rebuildResult = rebuilder.rebuildFromPacket(outstanding); ASSERT_FALSE(rebuildResult.hasError()); - ASSERT_TRUE(rebuildResult.value().hasValue()); + ASSERT_TRUE(rebuildResult.value().has_value()); auto packet2 = std::move(regularBuilder2).buildPacket(); // rebuilder writes frames to regularBuilder2 EXPECT_EQ(packet1.packet.frames.size(), packet2.packet.frames.size() + 1); @@ -451,7 +450,7 @@ TEST_F(QuicPacketRebuilderTest, CannotRebuildEmptyCryptoStream) { auto outstanding = makeDummyOutstandingPacket(packet1.packet, 1000); auto rebuildResult = rebuilder.rebuildFromPacket(outstanding); ASSERT_FALSE(rebuildResult.hasError()); - EXPECT_FALSE(rebuildResult.value().hasValue()); + EXPECT_FALSE(rebuildResult.value().has_value()); } TEST_F(QuicPacketRebuilderTest, CannotRebuild) { @@ -495,7 +494,7 @@ TEST_F(QuicPacketRebuilderTest, CannotRebuild) { buf->computeChainDataLength(), buf->computeChainDataLength(), true, - none /* skipLenHint */); + std::nullopt /* skipLenHint */); writeStreamFrameData( regularBuilder1, buf->clone(), buf->computeChainDataLength()); auto packet1 = std::move(regularBuilder1).buildPacket(); @@ -520,7 +519,7 @@ TEST_F(QuicPacketRebuilderTest, CannotRebuild) { auto outstanding = makeDummyOutstandingPacket(packet1.packet, 1000); auto rebuildResult = rebuilder.rebuildFromPacket(outstanding); ASSERT_FALSE(rebuildResult.hasError()); - EXPECT_FALSE(rebuildResult.value().hasValue()); + EXPECT_FALSE(rebuildResult.value().has_value()); } TEST_F(QuicPacketRebuilderTest, CloneCounter) { @@ -567,7 +566,7 @@ TEST_F(QuicPacketRebuilderTest, PurePingWillRebuild) { PacketRebuilder rebuilder(regularBuilder2, conn); auto rebuildResult = rebuilder.rebuildFromPacket(outstandingPacket); ASSERT_FALSE(rebuildResult.hasError()); - ASSERT_TRUE(rebuildResult.value().hasValue()); + ASSERT_TRUE(rebuildResult.value().has_value()); EXPECT_TRUE(outstandingPacket.maybeClonedPacketIdentifier.has_value()); EXPECT_EQ(1, conn.outstandings.numClonedPackets()); } @@ -595,7 +594,7 @@ TEST_F(QuicPacketRebuilderTest, LastStreamFrameSkipLen) { buf1->computeChainDataLength(), buf1->computeChainDataLength(), false, - none); + std::nullopt); writeStreamFrameData( regularBuilder, buf1->clone(), buf1->computeChainDataLength()); writeStreamFrameHeader( @@ -605,7 +604,7 @@ TEST_F(QuicPacketRebuilderTest, LastStreamFrameSkipLen) { buf2->computeChainDataLength(), buf2->computeChainDataLength(), true, - none); + std::nullopt); writeStreamFrameData( regularBuilder, buf2->clone(), buf2->computeChainDataLength()); auto packet = std::move(regularBuilder).buildPacket(); @@ -649,7 +648,7 @@ TEST_F(QuicPacketRebuilderTest, LastStreamFrameSkipLen) { PacketRebuilder rebuilder(mockBuilder, conn); auto rebuildResult = rebuilder.rebuildFromPacket(outstandingPacket); ASSERT_FALSE(rebuildResult.hasError()); - ASSERT_TRUE(rebuildResult.value().hasValue()); + ASSERT_TRUE(rebuildResult.value().has_value()); } TEST_F(QuicPacketRebuilderTest, LastStreamFrameFinOnlySkipLen) { @@ -674,7 +673,7 @@ TEST_F(QuicPacketRebuilderTest, LastStreamFrameFinOnlySkipLen) { buf1->computeChainDataLength(), buf1->computeChainDataLength(), false, - none); + std::nullopt); writeStreamFrameData( regularBuilder, buf1->clone(), buf1->computeChainDataLength()); writeStreamFrameHeader( @@ -684,7 +683,7 @@ TEST_F(QuicPacketRebuilderTest, LastStreamFrameFinOnlySkipLen) { 0, 0, true, - none); + std::nullopt); writeStreamFrameData(regularBuilder, ChainedByteRangeHead(), 0); auto packet = std::move(regularBuilder).buildPacket(); auto outstandingPacket = makeDummyOutstandingPacket(packet.packet, 1200); @@ -728,6 +727,6 @@ TEST_F(QuicPacketRebuilderTest, LastStreamFrameFinOnlySkipLen) { PacketRebuilder rebuilder(mockBuilder, conn); auto rebuildResult = rebuilder.rebuildFromPacket(outstandingPacket); ASSERT_FALSE(rebuildResult.hasError()); - ASSERT_TRUE(rebuildResult.value().hasValue()); + ASSERT_TRUE(rebuildResult.value().has_value()); } } // namespace quic::test diff --git a/quic/codec/test/QuicReadCodecTest.cpp b/quic/codec/test/QuicReadCodecTest.cpp index 7c58aabe6..8fb71f8b3 100644 --- a/quic/codec/test/QuicReadCodecTest.cpp +++ b/quic/codec/test/QuicReadCodecTest.cpp @@ -304,7 +304,7 @@ TEST_F(QuicReadCodecTest, PacketDecryptFail) { auto aead = std::make_unique(); EXPECT_CALL(*aead, _tryDecrypt(_, _, _)) - .WillOnce(Invoke([](auto&, const auto, auto) { return none; })); + .WillOnce(Invoke([](auto&, const auto, auto) { return std::nullopt; })); auto data = folly::IOBuf::copyBuffer("hello"); auto streamPacket = createStreamPacket( connId, @@ -407,7 +407,7 @@ TEST_F(QuicReadCodecTest, KeyPhaseOnePacket) { *data, 0 /* cipherOverhead */, 0 /* largestAcked */, - none, + std::nullopt, true, ProtectionType::KeyPhaseOne); AckStates ackStates; @@ -433,7 +433,8 @@ TEST_F(QuicReadCodecTest, BadResetFirstTwoBits) { QuicNodeType::Client); EXPECT_CALL(*rawAead, _tryDecrypt(_, _, _)) .Times(AtMost(1)) - .WillRepeatedly(Invoke([](auto&, const auto&, auto) { return none; })); + .WillRepeatedly( + Invoke([](auto&, const auto&, auto) { return std::nullopt; })); PacketNum packetNum = 1; StreamId streamId = 2; auto data = folly::IOBuf::create(30); @@ -446,7 +447,7 @@ TEST_F(QuicReadCodecTest, BadResetFirstTwoBits) { *data, 0 /* cipherOverhead */, 0 /* largestAcked */, - none, + std::nullopt, true, ProtectionType::KeyPhaseZero); overridePacketWithToken(streamPacket, tok); @@ -479,7 +480,8 @@ TEST_F(QuicReadCodecTest, RandomizedShortHeaderLeadsToReset) { QuicNodeType::Client); EXPECT_CALL(*rawAead, _tryDecrypt(_, _, _)) .Times(AtMost(1)) - .WillRepeatedly(Invoke([](auto&, const auto&, auto) { return none; })); + .WillRepeatedly( + Invoke([](auto&, const auto&, auto) { return std::nullopt; })); PacketNum packetNum = 1; StreamId streamId = 2; auto data = folly::IOBuf::create(30); @@ -492,7 +494,7 @@ TEST_F(QuicReadCodecTest, RandomizedShortHeaderLeadsToReset) { *data, 0 /* cipherOverhead */, 0 /* largestAcked */, - none, + std::nullopt, true, ProtectionType::KeyPhaseZero); overridePacketWithToken(streamPacket, tok); @@ -523,7 +525,7 @@ TEST_F(QuicReadCodecTest, StatelessResetTokenMismatch) { QuicNodeType::Client); EXPECT_CALL(*rawAead, _tryDecrypt(_, _, _)) .Times(1) - .WillOnce(Invoke([](auto&, const auto&, auto) { return none; })); + .WillOnce(Invoke([](auto&, const auto&, auto) { return std::nullopt; })); PacketNum packetNum = 1; StreamId streamId = 2; auto data = folly::IOBuf::create(30); @@ -536,7 +538,7 @@ TEST_F(QuicReadCodecTest, StatelessResetTokenMismatch) { *data, 0 /* cipherOverhead */, 0 /* largestAcked */, - none, + std::nullopt, true, ProtectionType::KeyPhaseZero); tok[0] ^= tok[0]; @@ -571,7 +573,7 @@ TEST_F(QuicReadCodecTest, NoOneRttCipherNoReset) { *data, 0 /* cipherOverhead */, 0 /* largestAcked */, - none, + std::nullopt, true, ProtectionType::KeyPhaseZero); overridePacketWithToken(streamPacket, tok); @@ -599,7 +601,7 @@ TEST_F(QuicReadCodecTest, FailToDecryptLongHeaderNoReset) { EXPECT_CALL(*rawAead, _tryDecrypt(_, _, _)) .Times(1) - .WillOnce(Invoke([](auto&, const auto&, auto) { return none; })); + .WillOnce(Invoke([](auto&, const auto&, auto) { return std::nullopt; })); PacketNum packetNum = 1; StreamId streamId = 2; auto data = folly::IOBuf::create(30); @@ -637,7 +639,7 @@ TEST_F(QuicReadCodecTest, FailToDecryptNoTokenNoReset) { EXPECT_CALL(*rawAead, _tryDecrypt(_, _, _)) .Times(1) - .WillOnce(Invoke([](auto&, const auto&, auto) { return none; })); + .WillOnce(Invoke([](auto&, const auto&, auto) { return std::nullopt; })); PacketNum packetNum = 1; StreamId streamId = 2; auto data = folly::IOBuf::create(30); @@ -650,7 +652,7 @@ TEST_F(QuicReadCodecTest, FailToDecryptNoTokenNoReset) { *data, 0 /* cipherOverhead */, 0 /* largestAcked */, - none, + std::nullopt, true, ProtectionType::KeyPhaseZero); AckStates ackStates; @@ -880,7 +882,7 @@ TEST_F(QuicReadCodecTest, KeyUpdateIncomingValid) { *data, 0 /* cipherOverhead */, 0 /* largestAcked */, - none, + std::nullopt, true, ProtectionType::KeyPhaseZero); AckStates ackStates; @@ -907,7 +909,7 @@ TEST_F(QuicReadCodecTest, KeyUpdateIncomingValid) { *data, 0 /* cipherOverhead */, 0 /* largestAcked */, - none, + std::nullopt, true, ProtectionType::KeyPhaseOne); packetQueue = bufToQueue(packetToBuf(streamPacket)); @@ -943,7 +945,7 @@ TEST_F(QuicReadCodecTest, KeyUpdateIncomingValid) { *data, 0 /* cipherOverhead */, 0 /* largestAcked */, - none, + std::nullopt, true, ProtectionType::KeyPhaseZero); packetQueue = bufToQueue(packetToBuf(streamPacket)); @@ -975,7 +977,7 @@ TEST_F(QuicReadCodecTest, KeyUpdateIncomingValid) { *data, 0 /* cipherOverhead */, 0 /* largestAcked */, - none, + std::nullopt, true, ProtectionType::KeyPhaseOne); packetQueue = bufToQueue(packetToBuf(streamPacket)); @@ -1007,7 +1009,7 @@ TEST_F(QuicReadCodecTest, KeyUpdateIncomingValid) { *data, 0 /* cipherOverhead */, 0 /* largestAcked */, - none, + std::nullopt, true, ProtectionType::KeyPhaseZero); packetQueue = bufToQueue(packetToBuf(streamPacket)); @@ -1067,7 +1069,7 @@ TEST_F(QuicReadCodecTest, KeyUpdateIncomingInvalid) { *data, 0 /* cipherOverhead */, 0 /* largestAcked */, - none, + std::nullopt, true, ProtectionType::KeyPhaseZero); AckStates ackStates; @@ -1086,7 +1088,7 @@ TEST_F(QuicReadCodecTest, KeyUpdateIncomingInvalid) { .Times(1) .WillOnce(Invoke([](std::unique_ptr&, const auto&, auto) { // Failed decryption - return none; + return std::nullopt; })); packetNum = 3; streamPacket = createStreamPacket( @@ -1097,7 +1099,7 @@ TEST_F(QuicReadCodecTest, KeyUpdateIncomingInvalid) { *data, 0 /* cipherOverhead */, 0 /* largestAcked */, - none, + std::nullopt, true, ProtectionType::KeyPhaseOne); packetQueue = bufToQueue(packetToBuf(streamPacket)); @@ -1128,7 +1130,7 @@ TEST_F(QuicReadCodecTest, KeyUpdateIncomingInvalid) { *data, 0 /* cipherOverhead */, 0 /* largestAcked */, - none, + std::nullopt, true, ProtectionType::KeyPhaseOne); packetQueue = bufToQueue(packetToBuf(streamPacket)); @@ -1153,7 +1155,7 @@ TEST_F(QuicReadCodecTest, KeyUpdateIncomingInvalid) { .Times(1) .WillOnce(Invoke([](std::unique_ptr&, const auto&, auto) { // Failed decryption - return none; + return std::nullopt; })); packetNum = 1; streamPacket = createStreamPacket( @@ -1164,7 +1166,7 @@ TEST_F(QuicReadCodecTest, KeyUpdateIncomingInvalid) { *data, 0 /* cipherOverhead */, 0 /* largestAcked */, - none, + std::nullopt, true, ProtectionType::KeyPhaseOne); packetQueue = bufToQueue(packetToBuf(streamPacket)); @@ -1185,7 +1187,7 @@ TEST_F(QuicReadCodecTest, KeyUpdateIncomingInvalid) { .Times(1) .WillOnce(Invoke([](std::unique_ptr&, const auto&, auto) { // Failed decryption - return none; + return std::nullopt; })); packetNum = 5; streamPacket = createStreamPacket( @@ -1196,7 +1198,7 @@ TEST_F(QuicReadCodecTest, KeyUpdateIncomingInvalid) { *data, 0 /* cipherOverhead */, 0 /* largestAcked */, - none, + std::nullopt, true, ProtectionType::KeyPhaseZero); packetQueue = bufToQueue(packetToBuf(streamPacket)); @@ -1247,7 +1249,7 @@ TEST_F(QuicReadCodecTest, KeyUpdateCipherUnavailable) { *data, 0 /* cipherOverhead */, 0 /* largestAcked */, - none, + std::nullopt, true, ProtectionType::KeyPhaseZero); AckStates ackStates; @@ -1271,7 +1273,7 @@ TEST_F(QuicReadCodecTest, KeyUpdateCipherUnavailable) { *data, 0 /* cipherOverhead */, 0 /* largestAcked */, - none, + std::nullopt, true, ProtectionType::KeyPhaseOne); packetQueue = bufToQueue(packetToBuf(streamPacket)); @@ -1295,7 +1297,7 @@ TEST_F(QuicReadCodecTest, KeyUpdateCipherUnavailable) { *data, 0 /* cipherOverhead */, 0 /* largestAcked */, - none, + std::nullopt, true, ProtectionType::KeyPhaseOne); packetQueue = bufToQueue(packetToBuf(streamPacket)); @@ -1349,7 +1351,7 @@ TEST_F(QuicReadCodecTest, KeyUpdateInitiate) { *data, 0 /* cipherOverhead */, 0 /* largestAcked */, - none, + std::nullopt, true, ProtectionType::KeyPhaseZero); AckStates ackStates; @@ -1395,7 +1397,7 @@ TEST_F(QuicReadCodecTest, KeyUpdateInitiate) { *data, 0 /* cipherOverhead */, 0 /* largestAcked */, - none, + std::nullopt, true, ProtectionType::KeyPhaseOne); packetQueue = bufToQueue(packetToBuf(streamPacket)); diff --git a/quic/codec/test/QuicWriteCodecTest.cpp b/quic/codec/test/QuicWriteCodecTest.cpp index efde8176f..54d108a8c 100644 --- a/quic/codec/test/QuicWriteCodecTest.cpp +++ b/quic/codec/test/QuicWriteCodecTest.cpp @@ -38,10 +38,10 @@ QuicFrame parseQuicFrame( bool isAckReceiveTimestampsSupported = false, uint64_t extendedAckSupport = 0) { quic::Optional receiveTimeStampsConfig = - quic::none; + std::nullopt; if (isAckReceiveTimestampsSupported) { - receiveTimeStampsConfig.assign( - {.maxReceiveTimestampsPerAck = 5, .receiveTimestampsExponent = 3}); + receiveTimeStampsConfig = AckReceiveTimestampsConfig{ + .maxReceiveTimestampsPerAck = 5, .receiveTimestampsExponent = 3}; } auto result = quic::parseFrame( @@ -308,11 +308,12 @@ WriteAckFrameState createTestWriteAckState( if (shouldIncludeTimestamps) { ackState.recvdPacketInfos = populateReceiveTimestamps(ackBlocks, connTime, countTimestampsToStore); - ackState.lastRecvdPacketInfo.assign( - {ackState.recvdPacketInfos.back().pktNum, - ReceivedUdpPacket::Timings{ - .receiveTimePoint = - ackState.recvdPacketInfos.back().timings.receiveTimePoint}}); + ackState.lastRecvdPacketInfo = WriteAckFrameState::ReceivedPacket{ + .pktNum = ackState.recvdPacketInfos.back().pktNum, + .timings = ReceivedUdpPacket::Timings{ + .receiveTimePoint = + ackState.recvdPacketInfos.back().timings.receiveTimePoint, + .maybeSoftwareTs = std::nullopt}}; } return ackState; } @@ -526,7 +527,13 @@ TEST_F(QuicWriteCodecTest, WriteStreamFrameToEmptyPacket) { uint64_t offset = 0; bool fin = false; auto res = writeStreamFrameHeader( - pktBuilder, streamId, offset, 10, 10, fin, none /* skipLenHint */); + pktBuilder, + streamId, + offset, + 10, + 10, + fin, + std::nullopt /* skipLenHint */); ASSERT_TRUE(res.hasValue()); auto dataLen = *res; ASSERT_TRUE(dataLen); @@ -574,7 +581,13 @@ TEST_F(QuicWriteCodecTest, WriteStreamFrameToPartialPacket) { // 1 byte for length // => 8 bytes of header auto res = writeStreamFrameHeader( - pktBuilder, streamId, offset, 20, 20, fin, none /* skipLenHint */); + pktBuilder, + streamId, + offset, + 20, + 20, + fin, + std::nullopt /* skipLenHint */); ASSERT_TRUE(res.hasValue()); auto dataLen = *res; ASSERT_TRUE(dataLen); @@ -625,7 +638,13 @@ TEST_F(QuicWriteCodecTest, WriteTwoStreamFrames) { bool fin1 = false; auto inputBuf = buildRandomInputData(30); auto res = writeStreamFrameHeader( - pktBuilder, streamId1, offset1, 30, 30, fin1, none /* skipLenHint */); + pktBuilder, + streamId1, + offset1, + 30, + 30, + fin1, + std::nullopt /* skipLenHint */); ASSERT_TRUE(res.hasValue()); auto dataLen = *res; ASSERT_TRUE(dataLen); @@ -654,7 +673,7 @@ TEST_F(QuicWriteCodecTest, WriteTwoStreamFrames) { remainingSpace, remainingSpace, fin2, - none /* skipLenHint */); + std::nullopt /* skipLenHint */); ASSERT_TRUE(res.hasValue()); dataLen = *res; ASSERT_TRUE(dataLen); @@ -728,7 +747,13 @@ TEST_F(QuicWriteCodecTest, WriteStreamFramePartialData) { // 4 bytes for offset // => 7 bytes for header auto res = writeStreamFrameHeader( - pktBuilder, streamId, offset, 50, 50, fin, none /* skipLenHint */); + pktBuilder, + streamId, + offset, + 50, + 50, + fin, + std::nullopt /* skipLenHint */); ASSERT_TRUE(res.hasValue()); auto dataLen = *res; ASSERT_TRUE(dataLen); @@ -769,7 +794,7 @@ TEST_F(QuicWriteCodecTest, WriteStreamFrameTooSmallForStreamHeader) { uint64_t offset = 65535; bool fin = false; auto res = writeStreamFrameHeader( - pktBuilder, streamId, offset, 1, 1, fin, none /* skipLenHint */); + pktBuilder, streamId, offset, 1, 1, fin, std::nullopt /* skipLenHint */); EXPECT_TRUE(res.hasValue()); auto dataLen = *res; EXPECT_FALSE(dataLen); @@ -789,7 +814,13 @@ TEST_F(QuicWriteCodecTest, WriteStreamNoSpaceForData) { // 1 byte for offset // => 3 bytes auto res = writeStreamFrameHeader( - pktBuilder, streamId, offset, 10, 10, fin, none /* skipLenHint */); + pktBuilder, + streamId, + offset, + 10, + 10, + fin, + std::nullopt /* skipLenHint */); ASSERT_TRUE(res.hasValue()); auto dataLen = *res; EXPECT_FALSE(dataLen.has_value()); @@ -813,7 +844,13 @@ TEST_F(QuicWriteCodecTest, WriteStreamSpaceForOneByte) { // 1 byte for offset // => 3 bytes auto res = writeStreamFrameHeader( - pktBuilder, streamId, offset, 100, 100, fin, none /* skipLenHint */); + pktBuilder, + streamId, + offset, + 100, + 100, + fin, + std::nullopt /* skipLenHint */); ASSERT_TRUE(res.hasValue()); auto dataLen = *res; ASSERT_TRUE(dataLen); @@ -862,7 +899,13 @@ TEST_F(QuicWriteCodecTest, WriteFinToEmptyPacket) { uint64_t offset = 0; bool fin = true; auto res = writeStreamFrameHeader( - pktBuilder, streamId, offset, 10, 10, fin, none /* skipLenHint */); + pktBuilder, + streamId, + offset, + 10, + 10, + fin, + std::nullopt /* skipLenHint */); ASSERT_TRUE(res.hasValue()); auto dataLen = *res; ASSERT_TRUE(dataLen); @@ -922,7 +965,7 @@ TEST_F(QuicWriteCodecTest, TestWriteIncompleteDataAndFin) { inDataSize, inDataSize, fin, - none /* skipLenHint */); + std::nullopt /* skipLenHint */); ASSERT_TRUE(res.hasValue()); auto dataLen = *res; ASSERT_TRUE(dataLen); @@ -941,7 +984,7 @@ TEST_F(QuicWriteCodecTest, TestWriteNoDataAndFin) { bool fin = true; BufPtr empty; auto res = writeStreamFrameHeader( - pktBuilder, streamId, offset, 0, 0, fin, none /* skipLenHint */); + pktBuilder, streamId, offset, 0, 0, fin, std::nullopt /* skipLenHint */); ASSERT_TRUE(res.hasValue()); auto dataLen = *res; ASSERT_TRUE(dataLen); @@ -956,7 +999,7 @@ TEST_F(QuicWriteCodecTest, TestWriteNoDataAndNoFin) { bool fin = false; BufPtr empty; auto res = writeStreamFrameHeader( - pktBuilder, streamId, offset, 0, 0, fin, none /* skipLenHint */); + pktBuilder, streamId, offset, 0, 0, fin, std::nullopt /* skipLenHint */); EXPECT_TRUE(res.hasError()); EXPECT_EQ( res.error(), @@ -979,7 +1022,13 @@ TEST_F(QuicWriteCodecTest, PacketOnlyHasSpaceForStreamHeader) { uint64_t offset = 0; bool fin = true; auto res = writeStreamFrameHeader( - pktBuilder, streamId, offset, 20, 20, fin, none /* skipLenHint */); + pktBuilder, + streamId, + offset, + 20, + 20, + fin, + std::nullopt /* skipLenHint */); ASSERT_TRUE(res.hasValue()); auto dataLen = *res; EXPECT_FALSE(dataLen.has_value()); @@ -998,7 +1047,7 @@ TEST_F(QuicWriteCodecTest, PacketOnlyHasSpaceForStreamHeaderWithFin) { uint64_t offset = 0; bool fin = true; auto res = writeStreamFrameHeader( - pktBuilder, streamId, offset, 0, 0, fin, none /* skipLenHint */); + pktBuilder, streamId, offset, 0, 0, fin, std::nullopt /* skipLenHint */); ASSERT_TRUE(res.hasValue()); auto dataLen = *res; ASSERT_TRUE(dataLen.has_value()); @@ -1018,7 +1067,7 @@ TEST_F(QuicWriteCodecTest, PacketNotEnoughSpaceForStreamHeaderWithFin) { uint64_t offset = 0; bool fin = true; auto res = writeStreamFrameHeader( - pktBuilder, streamId, offset, 0, 0, fin, none /* skipLenHint */); + pktBuilder, streamId, offset, 0, 0, fin, std::nullopt /* skipLenHint */); EXPECT_TRUE(res.hasValue()); auto dataLen = *res; ASSERT_FALSE(dataLen.has_value()); @@ -1048,7 +1097,7 @@ TEST_F(QuicWriteCodecTest, WriteStreamFrameHeadeSkipLen) { uint64_t offset = 10; bool fin = false; auto res = writeStreamFrameHeader( - pktBuilder, streamId, offset, 1200 * 2, 1200 * 2, fin, none); + pktBuilder, streamId, offset, 1200 * 2, 1200 * 2, fin, std::nullopt); EXPECT_TRUE(res.hasValue()); auto dataLen = *res; EXPECT_LT(*dataLen, 1200); @@ -1075,8 +1124,8 @@ TEST_F(QuicWriteCodecTest, WriteStreamFrameHeadeNotSkipLen) { StreamId streamId = 0; uint64_t offset = 10; bool fin = false; - auto res = - writeStreamFrameHeader(pktBuilder, streamId, offset, 200, 200, fin, none); + auto res = writeStreamFrameHeader( + pktBuilder, streamId, offset, 200, 200, fin, std::nullopt); EXPECT_TRUE(res.hasValue()); auto dataLen = *res; EXPECT_EQ(*dataLen, 200); @@ -1204,12 +1253,12 @@ TEST_P(QuicWriteCodecTest, AckFrameVeryLargeAckRange) { } } ackState.recvdPacketInfos = pktsReceivedTimestamps; - ackState.lastRecvdPacketInfo.assign({ - ackState.recvdPacketInfos.back().pktNum, - ReceivedUdpPacket::Timings{ - .receiveTimePoint = - ackState.recvdPacketInfos.back().timings.receiveTimePoint}, - }); + WriteAckFrameState::ReceivedPacket receivedPacket; + receivedPacket.pktNum = ackState.recvdPacketInfos.back().pktNum; + receivedPacket.timings.receiveTimePoint = + ackState.recvdPacketInfos.back().timings.receiveTimePoint; + receivedPacket.timings.maybeSoftwareTs = std::nullopt; + ackState.lastRecvdPacketInfo = receivedPacket; } WriteAckFrameMetaData ackFrameMetaData = { @@ -1806,7 +1855,7 @@ TEST_P(QuicWriteCodecTest, NoSpaceForAckBlockSection) { defaultAckReceiveTimestmpsConfig, kMaxReceivedPktsTimestampsStored); ASSERT_FALSE(ackFrameWriteResult.hasError()); - EXPECT_FALSE(ackFrameWriteResult.value().hasValue()); + EXPECT_FALSE(ackFrameWriteResult.value().has_value()); } TEST_P(QuicWriteCodecTest, OnlyHasSpaceForFirstAckBlock) { @@ -1850,7 +1899,7 @@ TEST_P(QuicWriteCodecTest, OnlyHasSpaceForFirstAckBlock) { defaultAckReceiveTimestmpsConfig, kMaxReceivedPktsTimestampsStored); ASSERT_FALSE(ackFrameWriteResultExpected.hasError()); - ASSERT_TRUE(ackFrameWriteResultExpected.value().hasValue()); + ASSERT_TRUE(ackFrameWriteResultExpected.value().has_value()); auto& ackFrameWriteResult = ackFrameWriteResultExpected.value().value(); auto addlBytesConsumed = computeBytesForOptionalAckFields( ackFrameMetaData, ackFrameWriteResult, frameType); @@ -1879,7 +1928,8 @@ TEST_P(QuicWriteCodecTest, OnlyHasSpaceForFirstAckBlock) { EXPECT_EQ(decodedAckFrame.ackBlocks[0].endPacket, 1000); if (frameType == FrameType::ACK_RECEIVE_TIMESTAMPS) { - // No space left for ack blocks, and hence none for received timestamps + // No space left for ack blocks, and hence std::nullopt for received + // timestamps assertsOnDecodedReceiveTimestamps( ackFrameMetaData, ackFrameWriteResult.writeAckFrame, @@ -1927,7 +1977,7 @@ TEST_P(QuicWriteCodecTest, WriteAckFrameWithMultipleTimestampRanges) { 50, /*maxRecvTimestampsToSend*/ extendedAckSupport); ASSERT_FALSE(ackFrameWriteResultExpected.hasError()); - ASSERT_TRUE(ackFrameWriteResultExpected.value().hasValue()); + ASSERT_TRUE(ackFrameWriteResultExpected.value().has_value()); auto& ackFrameWriteResult = ackFrameWriteResultExpected.value().value(); auto addlBytesConsumed = computeBytesForOptionalAckFields( ackFrameMetaData, ackFrameWriteResult, frameType); @@ -2756,7 +2806,7 @@ TEST_F(QuicWriteCodecTest, WriteStreamFrameWithGroup) { 50, 50, fin, - none /* skipLenHint */, + std::nullopt /* skipLenHint */, groupId); ASSERT_TRUE(res.hasValue()); auto dataLen = *res; diff --git a/quic/common/Optional.h b/quic/common/Optional.h index dfe5eced9..8f9c1d339 100644 --- a/quic/common/Optional.h +++ b/quic/common/Optional.h @@ -6,8 +6,6 @@ */ #pragma once -#include - #define TINY_OPTIONAL_USE_SEPARATE_BOOL_INSTEAD_OF_UB_TRICKS 1 #include @@ -15,9 +13,7 @@ namespace quic { template -using Optional = folly::Optional; - -constexpr folly::None none{folly::None::_secret::_token}; +using Optional = tiny::optional; template using OptionalIntegral = tiny::optional_aip; diff --git a/quic/common/TransportKnobs.cpp b/quic/common/TransportKnobs.cpp index 6dc253d31..a8c32a8be 100644 --- a/quic/common/TransportKnobs.cpp +++ b/quic/common/TransportKnobs.cpp @@ -66,7 +66,7 @@ Optional parseTransportKnobs( knobParams.push_back({paramId, expectAsInt.value()}); continue; // triggers next loop iteration } - return none; // error parsing integer parameter + return std::nullopt; // error parsing integer parameter } /* @@ -82,7 +82,7 @@ Optional parseTransportKnobs( {paramId, folly::to(cctype.value())}); } else { LOG(ERROR) << "unknown cc type " << val; - return none; + return std::nullopt; } /* * set rtt factor used in cc algs like bbr or copa @@ -104,7 +104,7 @@ Optional parseTransportKnobs( if (pos == std::string::npos) { LOG(ERROR) << "rtt factor knob expected format {numerator}/{denominator}"; - return none; + return std::nullopt; } uint64_t numerator = folly::tryTo(s.substr(0, pos)).value_or(kKnobFractionMax); @@ -117,7 +117,7 @@ Optional parseTransportKnobs( LOG(ERROR) << "rtt factor knob numerator and denominator must be ints in range (0," << kKnobFractionMax << "]"; - return none; + return std::nullopt; } // transport knobs must be a single int, so we pack numerator and // denominator into a single int here and unpack in the handler @@ -135,7 +135,7 @@ Optional parseTransportKnobs( LOG(ERROR) << "string param type is not valid for this knob with id= " << TransportKnobParamId::_from_integral(paramId); - return none; + return std::nullopt; } continue; } @@ -143,12 +143,12 @@ Optional parseTransportKnobs( // Quic transport knob param values cannot be of type ARRAY, NULLT or // OBJECT LOG(ERROR) << "Invalid transport knob param value type" << val.type(); - return none; + return std::nullopt; } } } catch (const std::exception& e) { LOG(ERROR) << "fail to parse knobs: " << e.what(); - return none; + return std::nullopt; } std::sort(knobParams.begin(), knobParams.end(), compareTransportKnobParam); diff --git a/quic/common/test/TestPacketBuilders.cpp b/quic/common/test/TestPacketBuilders.cpp index e579ebdc5..0b5f5be52 100644 --- a/quic/common/test/TestPacketBuilders.cpp +++ b/quic/common/test/TestPacketBuilders.cpp @@ -61,19 +61,20 @@ RegularQuicPacketBuilder::Packet AckPacketBuilder::build() && { // This function sends ACK to dstConn auto srcConnId = (CHECK_NOTNULL(dstConn)->nodeType == QuicNodeType::Client - ? *CHECK_NOTNULL( - CHECK_NOTNULL(dstConn)->serverConnectionId.get_pointer()) - : *CHECK_NOTNULL( - CHECK_NOTNULL(dstConn)->clientConnectionId.get_pointer())); + ? (CHECK(CHECK_NOTNULL(dstConn)->serverConnectionId.has_value()), + CHECK_NOTNULL(dstConn)->serverConnectionId.value()) + : (CHECK(CHECK_NOTNULL(dstConn)->clientConnectionId.has_value()), + CHECK_NOTNULL(dstConn)->clientConnectionId.value())); auto dstConnId = (CHECK_NOTNULL(dstConn)->nodeType == QuicNodeType::Client - ? *CHECK_NOTNULL( - CHECK_NOTNULL(dstConn)->clientConnectionId.get_pointer()) - : *CHECK_NOTNULL( - CHECK_NOTNULL(dstConn)->serverConnectionId.get_pointer())); + ? (CHECK(CHECK_NOTNULL(dstConn)->clientConnectionId.has_value()), + CHECK_NOTNULL(dstConn)->clientConnectionId.value()) + : (CHECK(CHECK_NOTNULL(dstConn)->serverConnectionId.has_value()), + CHECK_NOTNULL(dstConn)->serverConnectionId.value())); Optional header; - const auto ackPnSpace = *CHECK_NOTNULL(maybePnSpace.get_pointer()); + const auto ackPnSpace = + (CHECK(maybePnSpace.has_value()), maybePnSpace.value()); const auto ackPacketNum = [this, &ackPnSpace]() { Optional maybeAckPacketNum; if (this->ackPacketNumStore) { @@ -138,7 +139,7 @@ RegularQuicPacketBuilder::Packet AckPacketBuilder::build() && { } DCHECK(builder.canBuildPacket()); WriteAckFrameState ackState; - ackState.acks = *CHECK_NOTNULL(maybeAckBlocks.get_pointer()); + ackState.acks = (CHECK(maybeAckBlocks.has_value()), maybeAckBlocks.value()); WriteAckFrameMetaData ackData = { ackState, maybeAckDelay.value(), @@ -225,16 +226,17 @@ OutstandingPacketBuilder::setTotalAppLimitedTimeUsecs( OutstandingPacketWrapper OutstandingPacketBuilder::build() && { return OutstandingPacketWrapper{ - *CHECK_NOTNULL(maybePacket.get_pointer()), - *CHECK_NOTNULL(maybeTime.get_pointer()), - *CHECK_NOTNULL(maybeEncodedSize.get_pointer()), - *CHECK_NOTNULL(maybeEncodedBodySize.get_pointer()), - *CHECK_NOTNULL(maybeTotalBytesSent.get_pointer()), - *CHECK_NOTNULL(maybeInflightBytes.get_pointer()), - CHECK_NOTNULL(maybeLossState.get_pointer())->get(), - *CHECK_NOTNULL(maybeWriteCount.get_pointer()), + (CHECK(maybePacket.has_value()), maybePacket.value()), + (CHECK(maybeTime.has_value()), maybeTime.value()), + (CHECK(maybeEncodedSize.has_value()), maybeEncodedSize.value()), + (CHECK(maybeEncodedBodySize.has_value()), maybeEncodedBodySize.value()), + (CHECK(maybeTotalBytesSent.has_value()), maybeTotalBytesSent.value()), + (CHECK(maybeInflightBytes.has_value()), maybeInflightBytes.value()), + (CHECK(maybeLossState.has_value()), maybeLossState.value().get()), + (CHECK(maybeWriteCount.has_value()), maybeWriteCount.value()), OutstandingPacketWrapper::Metadata::DetailsPerStream( - *CHECK_NOTNULL(maybeDetailsPerStream.get_pointer())), + (CHECK(maybeDetailsPerStream.has_value()), + maybeDetailsPerStream.value())), maybeTotalAppLimitedTimeUsecs.value()}; } diff --git a/quic/common/test/TestUtils.cpp b/quic/common/test/TestUtils.cpp index b4797c3e7..620fb801e 100644 --- a/quic/common/test/TestUtils.cpp +++ b/quic/common/test/TestUtils.cpp @@ -154,8 +154,8 @@ class AcceptingTicketCipher : public fizz::server::TicketCipher { public: ~AcceptingTicketCipher() override = default; - folly::SemiFuture< - Optional, std::chrono::seconds>>> + folly::SemiFuture, std::chrono::seconds>>> encrypt(fizz::server::ResumptionState) const override { // Fake handshake, no need todo anything here. return std::make_pair(folly::IOBuf::create(0), 2s); @@ -193,7 +193,7 @@ class AcceptingTicketCipher : public fizz::server::TicketCipher { } folly::SemiFuture< - std::pair>> + std::pair>> decrypt(std::unique_ptr) const override { return std::make_pair(fizz::PskType::Resumption, createResumptionState()); } @@ -314,8 +314,8 @@ RegularQuicPacketBuilder::Packet createStreamPacket( data.computeChainDataLength(), data.computeChainDataLength(), eof, - none /* skipLenHint */); - CHECK(res.hasValue()) << "failed to write stream frame header"; + std::nullopt /* skipLenHint */); + CHECK(res.has_value()) << "failed to write stream frame header"; auto dataLen = *res; auto dataBuf = data.clone(); writeStreamFrameData( @@ -738,8 +738,8 @@ CongestionController::AckEvent::AckPacket makeAckPacketFromOutstandingPacket( outstandingPacket.packet.header.getPacketSequenceNum()) .setOutstandingPacketMetadata(outstandingPacket.metadata) .setLastAckedPacketInfo( - outstandingPacket.lastAckedPacketInfo - ? &*outstandingPacket.lastAckedPacketInfo + outstandingPacket.lastAckedPacketInfo.has_value() + ? &outstandingPacket.lastAckedPacketInfo.value() : nullptr) .setAppLimited(outstandingPacket.isAppLimited) .setDetailsPerStream( diff --git a/quic/common/test/TestUtils.h b/quic/common/test/TestUtils.h index 0e4f9066d..974e6e171 100644 --- a/quic/common/test/TestUtils.h +++ b/quic/common/test/TestUtils.h @@ -86,9 +86,9 @@ RegularQuicPacketBuilder::Packet createStreamPacket( uint8_t cipherOverhead, PacketNum largestAcked, Optional> longHeaderOverride = - none, + std::nullopt, bool eof = true, - Optional shortHeaderOverride = none, + Optional shortHeaderOverride = std::nullopt, uint64_t offset = 0, uint64_t packetSizeLimit = kDefaultUDPSendPacketLen); @@ -408,7 +408,7 @@ class FakeServerHandshake : public FizzServerHandshake { std::shared_ptr fizzContext, bool chloSync = false, bool cfinSync = false, - Optional clientActiveConnectionIdLimit = none) + Optional clientActiveConnectionIdLimit = std::nullopt) : FizzServerHandshake( &conn, std::move(fizzContext), diff --git a/quic/common/test/TransportKnobsTest.cpp b/quic/common/test/TransportKnobsTest.cpp index 41ceff2ad..97be7ae2a 100644 --- a/quic/common/test/TransportKnobsTest.cpp +++ b/quic/common/test/TransportKnobsTest.cpp @@ -22,9 +22,9 @@ struct QuicKnobsParsingTestFixture { void run(const QuicKnobsParsingTestFixture& fixture) { auto result = parseTransportKnobs(fixture.serializedKnobs); if (fixture.expectError) { - EXPECT_FALSE(result.hasValue()); + EXPECT_FALSE(result.has_value()); } else { - ASSERT_TRUE(result.hasValue()); + ASSERT_TRUE(result.has_value()); EXPECT_EQ(result->size(), fixture.expectParams.size()); for (size_t i = 0; i < result->size(); i++) { auto& actualKnob = (*result)[i]; diff --git a/quic/common/udpsocket/FollyQuicAsyncUDPSocket.cpp b/quic/common/udpsocket/FollyQuicAsyncUDPSocket.cpp index b135cfe62..ad15422f7 100644 --- a/quic/common/udpsocket/FollyQuicAsyncUDPSocket.cpp +++ b/quic/common/udpsocket/FollyQuicAsyncUDPSocket.cpp @@ -444,7 +444,21 @@ folly::Expected FollyQuicAsyncUDPSocket::setAdditionalCmsgsFunc( std::function()>&& additionalCmsgsFunc) { try { - follySocket_.setAdditionalCmsgsFunc(std::move(additionalCmsgsFunc)); + auto adapter = [originalFunc = std::move(additionalCmsgsFunc)]() + -> folly::Optional { + if (!originalFunc) { + return folly::none; + } + + auto result = originalFunc(); + if (result.has_value()) { + return folly::Optional(std::move(result.value())); + } else { + return folly::none; + } + }; + + follySocket_.setAdditionalCmsgsFunc(std::move(adapter)); return folly::unit; } catch (const folly::AsyncSocketException& ex) { std::string errorMsg = diff --git a/quic/common/udpsocket/QuicAsyncUDPSocket.cpp b/quic/common/udpsocket/QuicAsyncUDPSocket.cpp index 3a7b7c9d3..2ee2e70f5 100644 --- a/quic/common/udpsocket/QuicAsyncUDPSocket.cpp +++ b/quic/common/udpsocket/QuicAsyncUDPSocket.cpp @@ -91,7 +91,7 @@ QuicAsyncUDPSocket::convertToSocketTimestampExt( std::chrono::nanoseconds duration = std::chrono::seconds(ts[0].tv_sec) + std::chrono::nanoseconds(ts[0].tv_nsec); if (duration == duration.zero()) { - return none; + return std::nullopt; } ReceivedUdpPacket::Timings::SocketTimestampExt sockTsExt; diff --git a/quic/congestion_control/Bbr.cpp b/quic/congestion_control/Bbr.cpp index bc6935f48..0c8a60394 100644 --- a/quic/congestion_control/Bbr.cpp +++ b/quic/congestion_control/Bbr.cpp @@ -634,7 +634,7 @@ Optional BbrCongestionController::getBandwidth() const noexcept { if (bandwidthSampler_) { return bandwidthSampler_->getBandwidth(); } - return none; + return std::nullopt; } void BbrCongestionController::detectBottleneckBandwidth(bool appLimitedSample) { diff --git a/quic/congestion_control/Bbr.h b/quic/congestion_control/Bbr.h index 2b5bb6c8d..9de37eea3 100644 --- a/quic/congestion_control/Bbr.h +++ b/quic/congestion_control/Bbr.h @@ -130,7 +130,9 @@ class BbrCongestionController : public CongestionController { const LossEvent* FOLLY_NULLABLE) override; void onPacketAckOrLoss(Optional ack, Optional loss) { - onPacketAckOrLoss(ack.get_pointer(), loss.get_pointer()); + onPacketAckOrLoss( + ack.has_value() ? &ack.value() : nullptr, + loss.has_value() ? &loss.value() : nullptr); } uint64_t getWritableBytes() const noexcept override; diff --git a/quic/congestion_control/CongestionController.h b/quic/congestion_control/CongestionController.h index 70daeac18..c00aa86f7 100644 --- a/quic/congestion_control/CongestionController.h +++ b/quic/congestion_control/CongestionController.h @@ -50,7 +50,7 @@ struct CongestionController { struct State { uint64_t writableBytes{0}; uint64_t congestionWindowBytes{0}; - Optional maybeBandwidthBitsPerSec{none}; + Optional maybeBandwidthBitsPerSec{std::nullopt}; }; // Helper struct to group multiple lost packets into one event @@ -120,7 +120,7 @@ struct CongestionController { * Return the congestion controller's bandwidth estimate, if available. */ [[nodiscard]] virtual Optional getBandwidth() const { - return none; + return std::nullopt; } /** diff --git a/quic/congestion_control/Copa.h b/quic/congestion_control/Copa.h index 3c3c035d8..981a186a3 100644 --- a/quic/congestion_control/Copa.h +++ b/quic/congestion_control/Copa.h @@ -37,7 +37,9 @@ class Copa : public CongestionController { const LossEvent* FOLLY_NULLABLE) override; void onPacketAckOrLoss(Optional ack, Optional loss) { - onPacketAckOrLoss(ack.get_pointer(), loss.get_pointer()); + onPacketAckOrLoss( + ack.has_value() ? &ack.value() : nullptr, + loss.has_value() ? &loss.value() : nullptr); } uint64_t getWritableBytes() const noexcept override; @@ -72,7 +74,7 @@ class Copa : public CongestionController { uint64_t numTimesDirectionSame{0}; // updated every srtt uint64_t lastRecordedCwndBytes; - Optional lastCwndRecordTime{none}; + Optional lastCwndRecordTime{std::nullopt}; }; void checkAndUpdateDirection(const TimePoint ackTime); @@ -84,7 +86,7 @@ class Copa : public CongestionController { bool isSlowStart_; // time at which cwnd was last doubled during slow start - Optional lastCwndDoubleTime_{none}; + Optional lastCwndDoubleTime_{std::nullopt}; WindowedFilter< std::chrono::microseconds, diff --git a/quic/congestion_control/Copa2.h b/quic/congestion_control/Copa2.h index 146c7b08d..6be067cbe 100644 --- a/quic/congestion_control/Copa2.h +++ b/quic/congestion_control/Copa2.h @@ -28,7 +28,9 @@ class Copa2 : public CongestionController { const LossEvent* FOLLY_NULLABLE) override; void onPacketAckOrLoss(Optional ack, Optional loss) { - onPacketAckOrLoss(ack.get_pointer(), loss.get_pointer()); + onPacketAckOrLoss( + ack.has_value() ? &ack.value() : nullptr, + loss.has_value() ? &loss.value() : nullptr); } [[nodiscard]] uint64_t getWritableBytes() const noexcept override; diff --git a/quic/congestion_control/NewReno.h b/quic/congestion_control/NewReno.h index a56a100ac..ae8395ff7 100644 --- a/quic/congestion_control/NewReno.h +++ b/quic/congestion_control/NewReno.h @@ -26,7 +26,9 @@ class NewReno : public CongestionController { const LossEvent* FOLLY_NULLABLE) override; void onPacketAckOrLoss(Optional ack, Optional loss) { - onPacketAckOrLoss(ack.get_pointer(), loss.get_pointer()); + onPacketAckOrLoss( + ack.has_value() ? &ack.value() : nullptr, + loss.has_value() ? &loss.value() : nullptr); } uint64_t getWritableBytes() const noexcept override; diff --git a/quic/congestion_control/PacketProcessor.h b/quic/congestion_control/PacketProcessor.h index 3547dfc90..b94252c8c 100644 --- a/quic/congestion_control/PacketProcessor.h +++ b/quic/congestion_control/PacketProcessor.h @@ -27,7 +27,7 @@ class PacketProcessor { * will apply to that write loop only. */ virtual Optional prewrite() { - return none; + return std::nullopt; } /** diff --git a/quic/congestion_control/QuicCubic.cpp b/quic/congestion_control/QuicCubic.cpp index 306449fbd..1395b877d 100644 --- a/quic/congestion_control/QuicCubic.cpp +++ b/quic/congestion_control/QuicCubic.cpp @@ -330,8 +330,8 @@ void Cubic::onPacketAckOrLoss( const AckEvent* FOLLY_NULLABLE ackEvent, const LossEvent* FOLLY_NULLABLE lossEvent) { // TODO: current code in detectLossPackets only gives back a loss event when - // largestLostPacketNum isn't a none. But we should probably also check - // against it here anyway just in case the loss code is changed in the + // largestLostPacketNum isn't a std::nullopt. But we should probably also + // check against it here anyway just in case the loss code is changed in the // future. if (lossEvent) { onPacketLoss(*lossEvent); diff --git a/quic/congestion_control/QuicCubic.h b/quic/congestion_control/QuicCubic.h index 3bc936317..7ae62aeb6 100644 --- a/quic/congestion_control/QuicCubic.h +++ b/quic/congestion_control/QuicCubic.h @@ -81,7 +81,9 @@ class Cubic : public CongestionController { const LossEvent* FOLLY_NULLABLE) override; void onPacketAckOrLoss(Optional ack, Optional loss) { - onPacketAckOrLoss(ack.get_pointer(), loss.get_pointer()); + onPacketAckOrLoss( + ack.has_value() ? &ack.value() : nullptr, + loss.has_value() ? &loss.value() : nullptr); } void onRemoveBytesFromInflight(uint64_t) override; diff --git a/quic/congestion_control/SimulatedTBF.cpp b/quic/congestion_control/SimulatedTBF.cpp index f557f88a1..948c60b1d 100644 --- a/quic/congestion_control/SimulatedTBF.cpp +++ b/quic/congestion_control/SimulatedTBF.cpp @@ -16,7 +16,7 @@ SimulatedTBF::SimulatedTBF(Config config) : config_(std::move(config)) { EmptyIntervalState emptyIntervalState = {}; emptyIntervalState.emptyBucketTimeIntervals_ = std::make_shared>(); - maybeEmptyIntervalState_.assign(emptyIntervalState); + maybeEmptyIntervalState_ = emptyIntervalState; } } @@ -36,8 +36,7 @@ double SimulatedTBF::consumeWithBorrowNonBlockingAndUpdateState( sendTime >= emptyIntervalState.maybeLastSendTimeBucketNotEmpty_.value()); if (!emptyIntervalState.maybeLastForgetEmptyIntervalTime_.has_value()) { - emptyIntervalState.maybeLastForgetEmptyIntervalTime_.assign( - sendTime - 1us); + emptyIntervalState.maybeLastForgetEmptyIntervalTime_ = sendTime - 1us; } } @@ -53,7 +52,7 @@ double SimulatedTBF::consumeWithBorrowNonBlockingAndUpdateState( config_.rateBytesPerSecond, config_.burstSizeBytes, sendTimeDouble); if (config_.trackEmptyIntervals && numTokensAvailable > 0) { auto& emptyIntervalState = getEmptyIntervalState(); - emptyIntervalState.maybeLastSendTimeBucketNotEmpty_.assign(sendTime); + emptyIntervalState.maybeLastSendTimeBucketNotEmpty_ = sendTime; } // If the amount of debt is limited, check if we can consume. @@ -73,12 +72,12 @@ double SimulatedTBF::consumeWithBorrowNonBlockingAndUpdateState( } // Send (consume tokens) and determine if any new debt. - Optional maybeDebtPayOffTimeDouble = consumeWithBorrowNonBlocking( + auto maybeDebtPayOffTimeDouble = consumeWithBorrowNonBlocking( toConsume, config_.rateBytesPerSecond, config_.burstSizeBytes, sendTimeDouble); - DCHECK(maybeDebtPayOffTimeDouble.hasValue()); + DCHECK(maybeDebtPayOffTimeDouble.has_value()); if (maybeDebtPayOffTimeDouble.value() > 0) { // Bucket is in debt now after consuming toConsume tokens const auto debtPayOffTimeUs = @@ -154,7 +153,7 @@ double SimulatedTBF::consumeWithBorrowNonBlockingAndUpdateState( void SimulatedTBF::forgetEmptyIntervalsPriorTo(const TimePoint& time) { auto& emptyIntervalState = getEmptyIntervalState(); // throws if not tracked - emptyIntervalState.maybeLastForgetEmptyIntervalTime_.assign(time); + emptyIntervalState.maybeLastForgetEmptyIntervalTime_ = time; while (!emptyIntervalState.emptyBucketTimeIntervals_->empty()) { if (emptyIntervalState.emptyBucketTimeIntervals_->front().start > time) { return; diff --git a/quic/congestion_control/TokenlessPacer.cpp b/quic/congestion_control/TokenlessPacer.cpp index 210bdc9c8..9162c84d9 100644 --- a/quic/congestion_control/TokenlessPacer.cpp +++ b/quic/congestion_control/TokenlessPacer.cpp @@ -127,7 +127,7 @@ std::chrono::microseconds TokenlessPacer::getTimeUntilNextWrite( uint64_t TokenlessPacer::updateAndGetWriteBatchSize(TimePoint currentTime) { auto sendBatch = batchSize_; - if (lastWriteTime_.hasValue() && writeInterval_ > 0us && + if (lastWriteTime_.has_value() && writeInterval_ > 0us && conn_.congestionController && !conn_.congestionController->isAppLimited()) { // The pacer timer is expected to trigger every writeInterval_ @@ -190,7 +190,7 @@ uint64_t TokenlessPacer::updateAndGetWriteBatchSize(TimePoint currentTime) { } } } - if (!lastWriteTime_.hasValue() || sendBatch > 0) { + if (!lastWriteTime_.has_value() || sendBatch > 0) { lastWriteTime_ = currentTime; } return sendBatch; diff --git a/quic/congestion_control/test/Bbr2Test.cpp b/quic/congestion_control/test/Bbr2Test.cpp index 7a6d8bc58..652d511da 100644 --- a/quic/congestion_control/test/Bbr2Test.cpp +++ b/quic/congestion_control/test/Bbr2Test.cpp @@ -148,8 +148,8 @@ TEST_F(Bbr2Test, GracefullyHandleMissingFields) { Bbr2CongestionController bbr2(*conn_); auto packet = makeTestingWritePacket(0, 0, 0, testStart_); - packet.lastAckedPacketInfo.clear(); - packet.maybeClonedPacketIdentifier.clear(); + packet.lastAckedPacketInfo.reset(); + packet.maybeClonedPacketIdentifier.reset(); EXPECT_NO_THROW(bbr2.onPacketSent(packet)); EXPECT_NO_THROW(bbr2.onPacketAckOrLoss(nullptr, nullptr)); diff --git a/quic/congestion_control/test/BbrTest.cpp b/quic/congestion_control/test/BbrTest.cpp index 12c768145..19cf4231a 100644 --- a/quic/congestion_control/test/BbrTest.cpp +++ b/quic/congestion_control/test/BbrTest.cpp @@ -105,7 +105,7 @@ TEST_F(BbrTest, Recovery) { // This doesn't change endOfRoundTrip_, but move endOfRecovery to new // Clock::now() auto estimatedLossTime = Clock::now(); - bbr.onPacketAckOrLoss(none, loss2); + bbr.onPacketAckOrLoss(std::nullopt, loss2); EXPECT_EQ(expectedRecoveryWindow, bbr.getCongestionWindow()); ackedBytes = 500; @@ -117,7 +117,7 @@ TEST_F(BbrTest, Recovery) { ackedBytes, estimatedLossTime - 1us, estimatedEndOfRoundTrip + 1us), - none); + std::nullopt); EXPECT_TRUE(bbr.inRecovery()); // Since recoveryWindow_ is larger than inflightBytes + recoveryIncrase EXPECT_EQ(expectedRecoveryWindow, bbr.getCongestionWindow()); @@ -127,13 +127,13 @@ TEST_F(BbrTest, Recovery) { loss3.persistentCongestion = true; loss3.lostBytes = inflightBytes / 2; expectedRecoveryWindow = conn.udpSendPacketLen * kMinCwndInMssForBbr; - bbr.onPacketAckOrLoss(none, loss3); + bbr.onPacketAckOrLoss(std::nullopt, loss3); EXPECT_EQ(expectedRecoveryWindow, bbr.getCongestionWindow()); CongestionController::AckEvent ack3 = makeAck( 12, inflightBytes / 2, estimatedLossTime + 10ms, estimatedLossTime + 5ms); // This will exit Recovery - bbr.onPacketAckOrLoss(ack3, none); + bbr.onPacketAckOrLoss(ack3, std::nullopt); EXPECT_FALSE(bbr.inRecovery()); // Only one update should have been issued. ASSERT_EQ(conn.pendingEvents.frames.size(), 1); @@ -165,7 +165,7 @@ TEST_F(BbrTest, StartupCwnd) { // Target cwnd will be 100 * 5000 * 2.885 = 1442500, but you haven't finished // STARTUP, too bad kiddo, you only grow a little today bbr.onPacketAckOrLoss( - makeAck(0, 3000, Clock::now(), packet.metadata.time), none); + makeAck(0, 3000, Clock::now(), packet.metadata.time), std::nullopt); EXPECT_EQ(startingCwnd + 3000, bbr.getCongestionWindow()); } @@ -193,7 +193,7 @@ TEST_F(BbrTest, StartupCwndImplicit) { // STARTUP, too bad kiddo, you only grow a little today auto ack = makeAck(0, 3000, Clock::now(), packet.metadata.time); ack.implicit = true; - bbr.onPacketAckOrLoss(ack, none); + bbr.onPacketAckOrLoss(ack, std::nullopt); EXPECT_EQ(startingCwnd + 3000, bbr.getCongestionWindow()); } @@ -221,7 +221,8 @@ TEST_F(BbrTest, LeaveStartup) { .WillRepeatedly(Return( mockedBandwidth * (growFast ? kExpectedStartupGrowth : 1.0))); bbr.onPacketAckOrLoss( - makeAck(currentLatest, 1000, Clock::now(), packet.metadata.time), none); + makeAck(currentLatest, 1000, Clock::now(), packet.metadata.time), + std::nullopt); conn.lossState.totalBytesAcked += 1000; if (growFast) { mockedBandwidth = mockedBandwidth * kExpectedStartupGrowth; @@ -307,7 +308,7 @@ TEST_F(BbrTest, ProbeRtt) { conn.udpSendPacketLen, Clock::now(), packetToAck.second), - none); + std::nullopt); conn.lossState.totalBytesAcked += conn.udpSendPacketLen; inflightBytes -= conn.udpSendPacketLen; inflightPackets.pop_front(); @@ -325,7 +326,7 @@ TEST_F(BbrTest, ProbeRtt) { conn.udpSendPacketLen, Clock::now(), packetToAck.second), - none); + std::nullopt); conn.lossState.totalBytesAcked += conn.udpSendPacketLen; inflightBytes -= conn.udpSendPacketLen; inflightPackets.pop_front(); @@ -342,7 +343,7 @@ TEST_F(BbrTest, ProbeRtt) { conn.udpSendPacketLen, Clock::now(), packetToAck.second), - none); + std::nullopt); conn.lossState.totalBytesAcked += conn.udpSendPacketLen; inflightBytes -= conn.udpSendPacketLen; inflightPackets.pop_front(); @@ -359,7 +360,7 @@ TEST_F(BbrTest, ProbeRtt) { conn.udpSendPacketLen, currentTime, packetToAck.second), - none); + std::nullopt); conn.lossState.totalBytesAcked += conn.udpSendPacketLen; inflightBytes -= conn.udpSendPacketLen; inflightPackets.pop_front(); @@ -374,7 +375,7 @@ TEST_F(BbrTest, ProbeRtt) { conn.udpSendPacketLen, packetToAck.second + 1ms, packetToAck.second), - none); + std::nullopt); inflightBytes -= conn.udpSendPacketLen; inflightPackets.pop_front(); EXPECT_EQ(BbrCongestionController::BbrState::ProbeRtt, bbr.state()); @@ -391,7 +392,7 @@ TEST_F(BbrTest, ProbeRtt) { conn.udpSendPacketLen, packetToAck.second + 2ms, packetToAck.second), - none); + std::nullopt); inflightBytes -= conn.udpSendPacketLen; inflightPackets.pop_front(); EXPECT_EQ(BbrCongestionController::BbrState::ProbeRtt, bbr.state()); @@ -409,7 +410,7 @@ TEST_F(BbrTest, ProbeRtt) { conn.udpSendPacketLen, packetToAck.second + kProbeRttDuration, packetToAck.second), - none); + std::nullopt); conn.lossState.totalBytesAcked += conn.udpSendPacketLen; inflightBytes -= conn.udpSendPacketLen; inflightPackets.pop_front(); @@ -555,7 +556,7 @@ TEST_F(BbrTest, AckAggregation) { // force send time < ack time Clock::now() + std::chrono::milliseconds(10), packet.metadata.time), - none); + std::nullopt); conn.lossState.totalBytesAcked += 1000; if (growFast) { mockedBandwidth = mockedBandwidth * kExpectedStartupGrowth; @@ -601,7 +602,7 @@ TEST_F(BbrTest, AckAggregation) { .WillRepeatedly(Return(mockedBandwidth * 10)); auto expectedBdp = mockedBandwidth * 50 * std::chrono::microseconds(50) / 1000 / 1000; - bbr.onPacketAckOrLoss(ackEvent, none); + bbr.onPacketAckOrLoss(ackEvent, std::nullopt); auto newCwnd = bbr.getCongestionWindow(); auto currentMaxAckHeight = 0; if (newCwnd != currentCwnd + 1000) { @@ -624,7 +625,7 @@ TEST_F(BbrTest, AckAggregation) { ackEvent.ackTime + 1ms, packet1.metadata.time); - bbr.onPacketAckOrLoss(ackEvent2, none); + bbr.onPacketAckOrLoss(ackEvent2, std::nullopt); newCwnd = bbr.getCongestionWindow(); EXPECT_GT(newCwnd, expectedBdp * kProbeBwGain + currentMaxAckHeight); } @@ -693,7 +694,7 @@ TEST_F(BbrTest, ExtendMinRttExpiration) { 1000, Clock::now(), packet.metadata.time), - none); + std::nullopt); } TEST_F(BbrTest, BytesCounting) { @@ -752,7 +753,7 @@ TEST_F(BbrTest, PacketLossInvokesPacer) { EXPECT_CALL(*rawPacer, onPacketsLoss()).Times(1); CongestionController::LossEvent lossEvent; lossEvent.addLostPacket(packet); - bbr.onPacketAckOrLoss(none, lossEvent); + bbr.onPacketAckOrLoss(std::nullopt, lossEvent); } TEST_F(BbrTest, ProbeRttSetsAppLimited) { @@ -769,13 +770,13 @@ TEST_F(BbrTest, ProbeRttSetsAppLimited) { EXPECT_CALL(*rawRttSampler, minRttExpired()).Times(1).WillOnce(Return(true)); EXPECT_CALL(*rawBandwidthSampler, onAppLimited()).Times(2); bbr.onPacketAckOrLoss( - makeAck(0, 1000, Clock::now(), Clock::now() - 5ms), none); + makeAck(0, 1000, Clock::now(), Clock::now() - 5ms), std::nullopt); EXPECT_EQ(BbrCongestionController::BbrState::ProbeRtt, bbr.state()); bbr.onPacketSent(makeTestingWritePacket(1, 1000, 2000)); EXPECT_CALL(*rawBandwidthSampler, onAppLimited()).Times(1); bbr.onPacketAckOrLoss( - makeAck(1, 1000, Clock::now(), Clock::now() - 5ms), none); + makeAck(1, 1000, Clock::now(), Clock::now() - 5ms), std::nullopt); EXPECT_EQ(BbrCongestionController::BbrState::ProbeRtt, bbr.state()); } diff --git a/quic/congestion_control/test/Copa2Test.cpp b/quic/congestion_control/test/Copa2Test.cpp index 0da79794a..7b92ef2bc 100644 --- a/quic/congestion_control/test/Copa2Test.cpp +++ b/quic/congestion_control/test/Copa2Test.cpp @@ -96,7 +96,7 @@ TEST_F(Copa2Test, PersistentCongestion) { CongestionController::LossEvent loss; loss.persistentCongestion = true; loss.addLostPacket(pkt); - copa2.onPacketAckOrLoss(none, loss); + copa2.onPacketAckOrLoss(std::nullopt, loss); EXPECT_EQ( copa2.getCongestionWindow(), conn.transportSettings.minCwndInMss * conn.udpSendPacketLen); @@ -172,7 +172,7 @@ TEST_F(Copa2Test, TestBwEstimate) { // You get the ack for the first 5 packets after 100ms all at once conn.lossState.lrtt = 100ms; now += 100ms; - copa2.onPacketAckOrLoss(createAckEvent(5, 5 * packetSize, now), none); + copa2.onPacketAckOrLoss(createAckEvent(5, 5 * packetSize, now), std::nullopt); numPacketsInFlight -= 5; EXPECT_EQ(copa2.getBytesInFlight(), numPacketsInFlight * packetSize); // Not enough time has passed for cwnd to increase @@ -184,7 +184,7 @@ TEST_F(Copa2Test, TestBwEstimate) { now += 210ms; conn.lossState.lrtt = 500ms; // Large value should be ignored since // only the min rtt should matter. - copa2.onPacketAckOrLoss(createAckEvent(1, packetSize, now), none); + copa2.onPacketAckOrLoss(createAckEvent(1, packetSize, now), std::nullopt); EXPECT_EQ( copa2.getCongestionWindow(), (6 + alphaParam) * conn.udpSendPacketLen); EXPECT_FALSE(copa2.inLossyMode()); @@ -224,10 +224,10 @@ TEST_F(Copa2Test, PacketLossInvokesPacer) { EXPECT_CALL(*rawPacer, onPacketsLoss()).Times(1); CongestionController::LossEvent lossEvent; lossEvent.addLostPacket(packet); - copa2.onPacketAckOrLoss(none, lossEvent); + copa2.onPacketAckOrLoss(std::nullopt, lossEvent); // Ack one packet to test how we set pacing rate copa2.onPacketSent(createPacket(1, 1000, 2000)); - copa2.onPacketAckOrLoss(createAckEvent(1, 1000, Clock::now()), none); + copa2.onPacketAckOrLoss(createAckEvent(1, 1000, Clock::now()), std::nullopt); } TEST_F(Copa2Test, ProbeRttHappens) { @@ -248,28 +248,28 @@ TEST_F(Copa2Test, ProbeRttHappens) { now += 10ms; // Set the min rtt conn.lossState.lrtt = 100ms; - copa2.onPacketAckOrLoss(createAckEvent(1, packetSize, now), none); + copa2.onPacketAckOrLoss(createAckEvent(1, packetSize, now), std::nullopt); EXPECT_FALSE(copa2.inProbeRtt()); now += kCopa2ProbeRttInterval / 2; conn.lossState.lrtt = 250ms; - copa2.onPacketAckOrLoss(createAckEvent(1, packetSize, now), none); + copa2.onPacketAckOrLoss(createAckEvent(1, packetSize, now), std::nullopt); EXPECT_FALSE(copa2.inProbeRtt()); now += kCopa2ProbeRttInterval / 2; - copa2.onPacketAckOrLoss(createAckEvent(1, packetSize, now), none); + copa2.onPacketAckOrLoss(createAckEvent(1, packetSize, now), std::nullopt); EXPECT_TRUE(copa2.inProbeRtt()); conn.lossState.lrtt = 150ms; now += kCopa2ProbeRttInterval / 2 - 50ms; - copa2.onPacketAckOrLoss(createAckEvent(1, packetSize, now), none); + copa2.onPacketAckOrLoss(createAckEvent(1, packetSize, now), std::nullopt); EXPECT_FALSE(copa2.inProbeRtt()); // If delay is small enough, it will enter probe rtt after half the usual // period conn.lossState.lrtt = 150ms; now += 100ms; - copa2.onPacketAckOrLoss(createAckEvent(1, packetSize, now), none); + copa2.onPacketAckOrLoss(createAckEvent(1, packetSize, now), std::nullopt); EXPECT_TRUE(copa2.inProbeRtt()); } @@ -302,7 +302,7 @@ TEST_F(Copa2Test, LossModeHappens) { loss.lostPackets = 1; loss.largestLostSentTime = now; // Start the cycle - copa2.onPacketAckOrLoss(createAckEvent(1, packetSize, now), none); + copa2.onPacketAckOrLoss(createAckEvent(1, packetSize, now), std::nullopt); now += 21ms; // End it copa2.onPacketAckOrLoss(createAckEvent(8, 7 * packetSize, now), loss); @@ -312,7 +312,7 @@ TEST_F(Copa2Test, LossModeHappens) { // Should shift to loss mode now loss.largestLostPacketNum = 10; - copa2.onPacketAckOrLoss(none, loss); + copa2.onPacketAckOrLoss(std::nullopt, loss); EXPECT_TRUE(copa2.inLossyMode()); // Send the next cycle and ensure that we are sending fewer packets @@ -322,7 +322,7 @@ TEST_F(Copa2Test, LossModeHappens) { // Ack it at 10ms + 10ms * 2 * lossToleranceParam + 1ms now += 12ms; - copa2.onPacketAckOrLoss(createAckEvent(1, packetSize, now), none); + copa2.onPacketAckOrLoss(createAckEvent(1, packetSize, now), std::nullopt); EXPECT_EQ( copa2.getCongestionWindow(), packetSize + alphaParam * conn.udpSendPacketLen); diff --git a/quic/congestion_control/test/CopaTest.cpp b/quic/congestion_control/test/CopaTest.cpp index 9149fd369..653725fb1 100644 --- a/quic/congestion_control/test/CopaTest.cpp +++ b/quic/congestion_control/test/CopaTest.cpp @@ -120,7 +120,7 @@ class CopaTest : public Test { // ack for first packet, lastCwndDoubleTime_ will be initialized now copa.onPacketAckOrLoss( - createAckEvent(packetNumToAck, packetSize, now), none); + createAckEvent(packetNumToAck, packetSize, now), std::nullopt); numPacketsInFlight--; EXPECT_EQ(copa.getBytesInFlight(), numPacketsInFlight * packetSize); @@ -142,7 +142,7 @@ class CopaTest : public Test { conn.lossState.srtt = 100ms; copa.onPacketAckOrLoss( - createAckEvent(packetNumToAck, packetSize, now), none); + createAckEvent(packetNumToAck, packetSize, now), std::nullopt); packetNumToAck++; EXPECT_FALSE(copa.inSlowStart()); uint64_t cwndChange = @@ -199,7 +199,7 @@ TEST_F(CopaTest, PersistentCongestion) { CongestionController::LossEvent loss; loss.persistentCongestion = true; loss.addLostPacket(pkt); - copa.onPacketAckOrLoss(none, loss); + copa.onPacketAckOrLoss(std::nullopt, loss); EXPECT_EQ( copa.getWritableBytes(), conn.transportSettings.minCwndInMss * conn.udpSendPacketLen); @@ -279,7 +279,8 @@ TEST_F(CopaTest, TestSlowStartAck) { conn.lossState.srtt = 280ms; // ack for first packet, lastCwndDoubleTime_ will be initialized now - copa.onPacketAckOrLoss(createAckEvent(packetNumToAck, packetSize, now), none); + copa.onPacketAckOrLoss( + createAckEvent(packetNumToAck, packetSize, now), std::nullopt); numPacketsInFlight--; EXPECT_EQ(copa.getBytesInFlight(), numPacketsInFlight * packetSize); @@ -299,9 +300,11 @@ TEST_F(CopaTest, TestSlowStartAck) { auto lastCwnd = copa.getCongestionWindow(); // Say more time passed and some packets were acked meanwhile. - copa.onPacketAckOrLoss(createAckEvent(packetNumToAck, packetSize, now), none); + copa.onPacketAckOrLoss( + createAckEvent(packetNumToAck, packetSize, now), std::nullopt); packetNumToAck++; - copa.onPacketAckOrLoss(createAckEvent(packetNumToAck, packetSize, now), none); + copa.onPacketAckOrLoss( + createAckEvent(packetNumToAck, packetSize, now), std::nullopt); packetNumToAck++; now += 300ms; @@ -310,7 +313,8 @@ TEST_F(CopaTest, TestSlowStartAck) { // RTTmin = 280ms conn.lossState.srtt = 300ms; - copa.onPacketAckOrLoss(createAckEvent(packetNumToAck, packetSize, now), none); + copa.onPacketAckOrLoss( + createAckEvent(packetNumToAck, packetSize, now), std::nullopt); packetNumToAck++; now += 100ms; @@ -321,7 +325,8 @@ TEST_F(CopaTest, TestSlowStartAck) { // ack for 5th packet, at this point currentRate < targetRate, but not enough // time has passed for cwnd to double again in slow start - copa.onPacketAckOrLoss(createAckEvent(packetNumToAck, packetSize, now), none); + copa.onPacketAckOrLoss( + createAckEvent(packetNumToAck, packetSize, now), std::nullopt); EXPECT_TRUE(copa.inSlowStart()); EXPECT_EQ(copa.getCongestionWindow(), lastCwnd); @@ -335,7 +340,8 @@ TEST_F(CopaTest, TestSlowStartAck) { // ack for 6th packet, at this point even though lrtt has increased, standing // rtt hasn't. Hence it will still not exit slow start - copa.onPacketAckOrLoss(createAckEvent(packetNumToAck, packetSize, now), none); + copa.onPacketAckOrLoss( + createAckEvent(packetNumToAck, packetSize, now), std::nullopt); EXPECT_TRUE(copa.inSlowStart()); // cwnd = 40 packets EXPECT_EQ(copa.getCongestionWindow(), lastCwnd); @@ -347,7 +353,8 @@ TEST_F(CopaTest, TestSlowStartAck) { // ack for 7th packet, at this point currentRate > targetRate, so it would // exit slow start and reduce cwnd - copa.onPacketAckOrLoss(createAckEvent(packetNumToAck, packetSize, now), none); + copa.onPacketAckOrLoss( + createAckEvent(packetNumToAck, packetSize, now), std::nullopt); EXPECT_FALSE(copa.inSlowStart()); EXPECT_LE(copa.getCongestionWindow(), lastCwnd); } @@ -370,7 +377,8 @@ TEST_F(CopaTest, TestSteadyStateChanges) { conn.lossState.lrtt = 100ms; // Rttmin = 100ms conn.lossState.srtt = 100ms; - copa.onPacketAckOrLoss(createAckEvent(packetNumToAck, packetSize, now), none); + copa.onPacketAckOrLoss( + createAckEvent(packetNumToAck, packetSize, now), std::nullopt); packetNumToAck++; uint64_t cwndChange = cwndChangeSteadyState(lastCwnd, 1.0, packetSize, 0.5, conn); @@ -384,7 +392,8 @@ TEST_F(CopaTest, TestSteadyStateChanges) { conn.lossState.lrtt = 50ms; // Rttmin = 60ms conn.lossState.srtt = 100ms; - copa.onPacketAckOrLoss(createAckEvent(packetNumToAck, packetSize, now), none); + copa.onPacketAckOrLoss( + createAckEvent(packetNumToAck, packetSize, now), std::nullopt); packetNumToAck++; cwndChange = cwndChangeSteadyState(lastCwnd, 1.0, packetSize, 0.5, conn); // cwnd = 9.6 + 1 / (0.5 * 9.6) = 9.8 packets @@ -396,7 +405,8 @@ TEST_F(CopaTest, TestSteadyStateChanges) { // Rttmin = 60ms conn.lossState.srtt = 100ms; // Though lrtt has increased, rtt standing has not. Will still increase - copa.onPacketAckOrLoss(createAckEvent(packetNumToAck, packetSize, now), none); + copa.onPacketAckOrLoss( + createAckEvent(packetNumToAck, packetSize, now), std::nullopt); packetNumToAck++; cwndChange = cwndChangeSteadyState(lastCwnd, 1.0, packetSize, 0.5, conn); // cwnd = 9.8 + 1 / (0.5 * 9.8) = 10.0 packets @@ -405,7 +415,8 @@ TEST_F(CopaTest, TestSteadyStateChanges) { // If sufficient time has elapsed, the increased rtt will be noted now += 110ms; - copa.onPacketAckOrLoss(createAckEvent(packetNumToAck, packetSize, now), none); + copa.onPacketAckOrLoss( + createAckEvent(packetNumToAck, packetSize, now), std::nullopt); packetNumToAck++; cwndChange = cwndChangeSteadyState(lastCwnd, 1.0, packetSize, 0.5, conn); // cwnd = 10 - 1 / (0.5 * 10) = 9.8 @@ -437,7 +448,7 @@ TEST_F(CopaTest, TestVelocity) { conn.lossState.srtt = 100ms; now += 100ms; // velocity = 1, direction = 0 - copa.onPacketAckOrLoss(createAckEvent(30, packetSize, now), none); + copa.onPacketAckOrLoss(createAckEvent(30, packetSize, now), std::nullopt); uint64_t cwndChange = cwndChangeSteadyState(lastCwnd, velocity, packetSize, 0.5, conn); @@ -447,7 +458,7 @@ TEST_F(CopaTest, TestVelocity) { // another ack, velocity = 1, direction 0 -> 1 now += 100ms; - copa.onPacketAckOrLoss(createAckEvent(35, packetSize, now), none); + copa.onPacketAckOrLoss(createAckEvent(35, packetSize, now), std::nullopt); cwndChange = cwndChangeSteadyState(lastCwnd, velocity, packetSize, 0.5, conn); // cwnd = 10 + 1 / (0.5 * 10) = 10.2 packets EXPECT_EQ(copa.getCongestionWindow(), lastCwnd + cwndChange); @@ -455,7 +466,7 @@ TEST_F(CopaTest, TestVelocity) { // another ack, velocity = 1, direction = 1 now += 100ms; - copa.onPacketAckOrLoss(createAckEvent(40, packetSize, now), none); + copa.onPacketAckOrLoss(createAckEvent(40, packetSize, now), std::nullopt); cwndChange = cwndChangeSteadyState(lastCwnd, velocity, packetSize, 0.5, conn); // cwnd = 10.2 + 1 / (0.5 * 10.2) = 10.4 packets EXPECT_EQ(copa.getCongestionWindow(), lastCwnd + cwndChange); @@ -463,7 +474,7 @@ TEST_F(CopaTest, TestVelocity) { // another ack, velocity = 1, direction = 1 now += 100ms; - copa.onPacketAckOrLoss(createAckEvent(45, packetSize, now), none); + copa.onPacketAckOrLoss(createAckEvent(45, packetSize, now), std::nullopt); cwndChange = cwndChangeSteadyState(lastCwnd, velocity, packetSize, 0.5, conn); // cwnd = 10.4 + 1 / (0.5 * 10.4) = 10.6 packets EXPECT_EQ(copa.getCongestionWindow(), lastCwnd + cwndChange); @@ -471,7 +482,7 @@ TEST_F(CopaTest, TestVelocity) { // another ack, velocity = 1, direction = 1 now += 100ms; - copa.onPacketAckOrLoss(createAckEvent(50, packetSize, now), none); + copa.onPacketAckOrLoss(createAckEvent(50, packetSize, now), std::nullopt); cwndChange = cwndChangeSteadyState(lastCwnd, velocity, packetSize, 0.5, conn); // cwnd = 10.4 + 1 / (0.5 * 10.4) = 10.6 packets EXPECT_EQ(copa.getCongestionWindow(), lastCwnd + cwndChange); @@ -480,7 +491,7 @@ TEST_F(CopaTest, TestVelocity) { // another ack, velocity = 2, direction = 1 velocity = 2 * velocity; now += 100ms; - copa.onPacketAckOrLoss(createAckEvent(55, packetSize, now), none); + copa.onPacketAckOrLoss(createAckEvent(55, packetSize, now), std::nullopt); cwndChange = cwndChangeSteadyState(lastCwnd, velocity, packetSize, 0.5, conn); // cwnd = 10 + 2 / (0.5 * 10.6) = 11 packets EXPECT_EQ(copa.getCongestionWindow(), lastCwnd + cwndChange); @@ -489,7 +500,7 @@ TEST_F(CopaTest, TestVelocity) { // another ack, velocity = 4, direction = 1 velocity = 2 * velocity; now += 100ms; - copa.onPacketAckOrLoss(createAckEvent(60, packetSize, now), none); + copa.onPacketAckOrLoss(createAckEvent(60, packetSize, now), std::nullopt); cwndChange = cwndChangeSteadyState(lastCwnd, velocity, packetSize, 0.5, conn); // cwnd = 11 + 4 / (0.5 * 11) = 11.8 packets EXPECT_EQ(copa.getCongestionWindow(), lastCwnd + cwndChange); @@ -498,7 +509,7 @@ TEST_F(CopaTest, TestVelocity) { // another ack, velocity = 8, direction = 1 velocity = 2 * velocity; now += 100ms; - copa.onPacketAckOrLoss(createAckEvent(65, packetSize, now), none); + copa.onPacketAckOrLoss(createAckEvent(65, packetSize, now), std::nullopt); cwndChange = cwndChangeSteadyState(lastCwnd, velocity, packetSize, 0.5, conn); // cwnd = 11.8 + 8 / (0.5 * 11.8) = 13.4 packets EXPECT_EQ(copa.getCongestionWindow(), lastCwnd + cwndChange); @@ -512,7 +523,7 @@ TEST_F(CopaTest, TestVelocity) { velocity = 1; // give it some extra time for rtt standing to reset now += 110ms; - copa.onPacketAckOrLoss(createAckEvent(50, packetSize, now), none); + copa.onPacketAckOrLoss(createAckEvent(50, packetSize, now), std::nullopt); cwndChange = cwndChangeSteadyState(lastCwnd, velocity, packetSize, 0.5, conn); // cwnd = 11.8 + 8 / (0.5 * 11.8) = 13.4 packets EXPECT_EQ(copa.getCongestionWindow(), lastCwnd - cwndChange); @@ -563,7 +574,7 @@ TEST_F(CopaTest, PacketLossInvokesPacer) { EXPECT_CALL(*rawPacer, onPacketsLoss()).Times(1); CongestionController::LossEvent lossEvent; lossEvent.addLostPacket(packet); - copa.onPacketAckOrLoss(none, lossEvent); + copa.onPacketAckOrLoss(std::nullopt, lossEvent); } } // namespace quic::test diff --git a/quic/congestion_control/test/CubicHystartTest.cpp b/quic/congestion_control/test/CubicHystartTest.cpp index 57b9f55de..7b025308a 100644 --- a/quic/congestion_control/test/CubicHystartTest.cpp +++ b/quic/congestion_control/test/CubicHystartTest.cpp @@ -28,7 +28,7 @@ TEST_F(CubicHystartTest, SendAndAck) { auto packet = makeTestingWritePacket(0, 1000, 1000); cubic.onPacketSent(packet); cubic.onPacketAckOrLoss( - makeAck(0, 1000, Clock::now(), packet.metadata.time), none); + makeAck(0, 1000, Clock::now(), packet.metadata.time), std::nullopt); EXPECT_EQ(initCwnd + 1000, cubic.getWritableBytes()); EXPECT_EQ(CubicStates::Hystart, cubic.state()); @@ -45,7 +45,7 @@ TEST_F(CubicHystartTest, CwndLargerThanSSThresh) { auto packet = makeTestingWritePacket(0, 1000, 1000); cubic.onPacketSent(packet); cubic.onPacketAckOrLoss( - makeAck(0, 1000, Clock::now(), packet.metadata.time), none); + makeAck(0, 1000, Clock::now(), packet.metadata.time), std::nullopt); EXPECT_EQ(initCwnd + 1000, cubic.getWritableBytes()); EXPECT_EQ(CubicStates::Steady, cubic.state()); } @@ -65,7 +65,7 @@ TEST_F(CubicHystartTest, NoDelayIncrease) { auto packet = makeTestingWritePacket(0, 1000, 1000, realNow); cubic.onPacketSent(packet); cubic.onPacketAckOrLoss( - makeAck(0, 1000, realNow + 2us, packet.metadata.time), none); + makeAck(0, 1000, realNow + 2us, packet.metadata.time), std::nullopt); EXPECT_EQ(initCwnd + 1000, cubic.getWritableBytes()); EXPECT_EQ(CubicStates::Hystart, cubic.state()); } @@ -94,7 +94,7 @@ TEST_F(CubicHystartTest, AckTrain) { kLowSsthreshInMss * conn.udpSendPacketLen, realNow, packet0.metadata.time), - none); + std::nullopt); // Packet 1 is acked: cubic.onPacketAckOrLoss( makeAck( @@ -102,7 +102,7 @@ TEST_F(CubicHystartTest, AckTrain) { kLowSsthreshInMss * conn.udpSendPacketLen, realNow + 2us, packet1.metadata.time), - none); + std::nullopt); EXPECT_EQ( initCwnd + kLowSsthreshInMss * conn.udpSendPacketLen * 2, cubic.getWritableBytes()); @@ -125,7 +125,7 @@ TEST_F(CubicHystartTest, NoAckTrainNoDelayIncrease) { cubic.onPacketSent(packet); cubic.onPacketAckOrLoss( makeAck(0, 1000, realNow + kAckCountingGap + 2us, packet.metadata.time), - none); + std::nullopt); EXPECT_EQ(initCwnd + 1000, cubic.getWritableBytes()); EXPECT_EQ(CubicStates::Hystart, cubic.state()); } @@ -144,7 +144,7 @@ TEST_F(CubicHystartTest, DelayIncrease) { cubic.onPacketSent(packet); cubic.onPacketAckOrLoss( makeAck(packetNum++, fullSize, Clock::now(), packet.metadata.time), - none); + std::nullopt); totalSent += fullSize; } @@ -172,10 +172,12 @@ TEST_F(CubicHystartTest, DelayIncrease) { auto ackTimeIncrease = 2ms; ackTime += ackTimeIncrease; cubic.onPacketAckOrLoss( - makeAck(firstPacketNum, 1000, ackTime, packet0.metadata.time), none); + makeAck(firstPacketNum, 1000, ackTime, packet0.metadata.time), + std::nullopt); ackTime += ackTimeIncrease; cubic.onPacketAckOrLoss( - makeAck(secondPacketNum, 1000, ackTime, packet1.metadata.time), none); + makeAck(secondPacketNum, 1000, ackTime, packet1.metadata.time), + std::nullopt); auto estimatedRttEndTarget = Clock::now(); auto packet2 = makeTestingWritePacket( @@ -186,7 +188,7 @@ TEST_F(CubicHystartTest, DelayIncrease) { // This will end current RTT round and start a new one next time Ack happens: ackTime = packet2.metadata.time + ackTimeIncrease; cubic.onPacketAckOrLoss( - makeAck(packetNum, 1000, ackTime, packet2.metadata.time), none); + makeAck(packetNum, 1000, ackTime, packet2.metadata.time), std::nullopt); packetNum++; auto cwndEndRound = cubic.getWritableBytes(); @@ -206,7 +208,7 @@ TEST_F(CubicHystartTest, DelayIncrease) { packetNum++; } for (auto& ack : moreAcks) { - cubic.onPacketAckOrLoss(ack, none); + cubic.onPacketAckOrLoss(ack, std::nullopt); } // kAckSampling-th onPacketAcked in this round. This will trigger // DelayIncrease: @@ -217,7 +219,7 @@ TEST_F(CubicHystartTest, DelayIncrease) { totalSent += 1000; ackTime += ackTimeIncrease; cubic.onPacketAckOrLoss( - makeAck(packetNum, 1000, ackTime, packetEnd.metadata.time), none); + makeAck(packetNum, 1000, ackTime, packetEnd.metadata.time), std::nullopt); EXPECT_EQ(cwndEndRound + 1000 * kAckSampling, cubic.getWritableBytes()); EXPECT_EQ(CubicStates::Steady, cubic.state()); @@ -246,16 +248,19 @@ TEST_F(CubicHystartTest, DelayIncreaseCwndTooSmall) { auto ackTime = realNow; auto ackTimeIncrease = 2us; ackTime += ackTimeIncrease; - cubic.onPacketAckOrLoss(makeAck(0, 1, ackTime, packet0.metadata.time), none); + cubic.onPacketAckOrLoss( + makeAck(0, 1, ackTime, packet0.metadata.time), std::nullopt); ackTime += ackTimeIncrease; - cubic.onPacketAckOrLoss(makeAck(1, 1, ackTime, packet1.metadata.time), none); + cubic.onPacketAckOrLoss( + makeAck(1, 1, ackTime, packet1.metadata.time), std::nullopt); auto packet2 = makeTestingWritePacket(2, 10, 10 + totalSent, realNow); conn.lossState.largestSent = 2; cubic.onPacketSent(packet2); totalSent += 10; ackTime += ackTimeIncrease; - cubic.onPacketAckOrLoss(makeAck(2, 1, ackTime, packet2.metadata.time), none); + cubic.onPacketAckOrLoss( + makeAck(2, 1, ackTime, packet2.metadata.time), std::nullopt); auto cwndEndRound = cubic.getWritableBytes(); // New RTT round, give currSampledRtt a value larger than previous RTT: @@ -271,7 +276,7 @@ TEST_F(CubicHystartTest, DelayIncreaseCwndTooSmall) { totalSent += 1; } for (auto& ack : moreAcks) { - cubic.onPacketAckOrLoss(ack, none); + cubic.onPacketAckOrLoss(ack, std::nullopt); } // kAckSampling-th onPacketAcked in this round. This will trigger // DelayIncrease: @@ -282,7 +287,7 @@ TEST_F(CubicHystartTest, DelayIncreaseCwndTooSmall) { totalSent += 1; ackTime += ackTimeIncrease; cubic.onPacketAckOrLoss( - makeAck(kAckSampling, 1, ackTime, packetEnd.metadata.time), none); + makeAck(kAckSampling, 1, ackTime, packetEnd.metadata.time), std::nullopt); auto expectedCwnd = cwndEndRound + 1 * kAckSampling; // Cwnd < kLowSsthresh, won't exit Hystart state: ASSERT_LT(expectedCwnd, kLowSsthreshInMss * conn.udpSendPacketLen); @@ -302,7 +307,7 @@ TEST_F(CubicHystartTest, ReduceByCubicReductionFactor) { // this decreases inflight by 1000, and then decreases cwnd by Cubic: CongestionController::LossEvent loss; loss.addLostPacket(packet); - cubic.onPacketAckOrLoss(none, std::move(loss)); + cubic.onPacketAckOrLoss(std::nullopt, std::move(loss)); EXPECT_EQ(initCwnd * kDefaultCubicReductionFactor, cubic.getWritableBytes()); EXPECT_EQ(CubicStates::FastRecovery, cubic.state()); } diff --git a/quic/congestion_control/test/CubicRecoveryTest.cpp b/quic/congestion_control/test/CubicRecoveryTest.cpp index 7af66b7cf..7ba04c483 100644 --- a/quic/congestion_control/test/CubicRecoveryTest.cpp +++ b/quic/congestion_control/test/CubicRecoveryTest.cpp @@ -25,7 +25,7 @@ TEST_F(CubicRecoveryTest, LossBurst) { totalSent += 1000; CongestionController::LossEvent loss; loss.addLostPacket(packet0); - cubic.onPacketAckOrLoss(none, std::move(loss)); + cubic.onPacketAckOrLoss(std::nullopt, std::move(loss)); EXPECT_EQ(CubicStates::FastRecovery, cubic.state()); auto cwndAfterLoss = cubic.getCongestionWindow(); @@ -38,7 +38,7 @@ TEST_F(CubicRecoveryTest, LossBurst) { conn.lossState.largestSent = i; loss2.addLostPacket(packet); } - cubic.onPacketAckOrLoss(none, std::move(loss2)); + cubic.onPacketAckOrLoss(std::nullopt, std::move(loss2)); // Still in recovery: EXPECT_EQ(CubicStates::FastRecovery, cubic.state()); // Cwnd should be reduced. @@ -55,7 +55,7 @@ TEST_F(CubicRecoveryTest, LossBeforeRecovery) { cubic.onPacketSent(packet); totalSent += 1000; cubic.onPacketAckOrLoss( - makeAck(0, 1000, Clock::now(), packet.metadata.time), none); + makeAck(0, 1000, Clock::now(), packet.metadata.time), std::nullopt); EXPECT_EQ(CubicStates::Hystart, cubic.state()); // Send three packets, lose second immediately. @@ -71,7 +71,7 @@ TEST_F(CubicRecoveryTest, LossBeforeRecovery) { conn.lossState.largestSent = 3; CongestionController::LossEvent loss2; loss2.addLostPacket(packet2); - cubic.onPacketAckOrLoss(none, std::move(loss2)); + cubic.onPacketAckOrLoss(std::nullopt, std::move(loss2)); // Should now be in recovery. Send packet4, receive acks for 3 and 4 which // should exit recovery with a certain cwnd. @@ -81,16 +81,16 @@ TEST_F(CubicRecoveryTest, LossBeforeRecovery) { totalSent += 1000; conn.lossState.largestSent = 4; cubic.onPacketAckOrLoss( - makeAck(3, 1000, Clock::now(), packet3.metadata.time), none); + makeAck(3, 1000, Clock::now(), packet3.metadata.time), std::nullopt); cubic.onPacketAckOrLoss( - makeAck(4, 1000, Clock::now(), packet4.metadata.time), none); + makeAck(4, 1000, Clock::now(), packet4.metadata.time), std::nullopt); auto cwndAfterRecovery = cubic.getCongestionWindow(); EXPECT_EQ(CubicStates::Steady, cubic.state()); // Now lose packet1, which should be ignored. CongestionController::LossEvent loss1; loss1.addLostPacket(packet1); - cubic.onPacketAckOrLoss(none, std::move(loss1)); + cubic.onPacketAckOrLoss(std::nullopt, std::move(loss1)); EXPECT_EQ(CubicStates::Steady, cubic.state()); EXPECT_EQ(cwndAfterRecovery, cubic.getCongestionWindow()); } @@ -103,14 +103,14 @@ TEST_F(CubicRecoveryTest, LossAfterRecovery) { auto packet = makeTestingWritePacket(0, 1000, 1000); cubic.onPacketSent(packet); cubic.onPacketAckOrLoss( - makeAck(0, 1000, Clock::now(), packet.metadata.time), none); + makeAck(0, 1000, Clock::now(), packet.metadata.time), std::nullopt); // Lose one packet. auto packet1 = makeTestingWritePacket(1, 1000, 2000); cubic.onPacketSent(packet1); conn.lossState.largestSent = 1; CongestionController::LossEvent loss1; loss1.addLostPacket(packet1); - cubic.onPacketAckOrLoss(none, std::move(loss1)); + cubic.onPacketAckOrLoss(std::nullopt, std::move(loss1)); EXPECT_EQ(CubicStates::FastRecovery, cubic.state()); auto cwndAfterLoss = cubic.getCongestionWindow(); @@ -120,7 +120,7 @@ TEST_F(CubicRecoveryTest, LossAfterRecovery) { conn.lossState.largestSent = 2; CongestionController::LossEvent loss2; loss2.addLostPacket(packet2); - cubic.onPacketAckOrLoss(none, std::move(loss2)); + cubic.onPacketAckOrLoss(std::nullopt, std::move(loss2)); EXPECT_EQ(CubicStates::FastRecovery, cubic.state()); EXPECT_TRUE(cwndAfterLoss > cubic.getCongestionWindow()); } @@ -144,19 +144,19 @@ TEST_F(CubicRecoveryTest, AckNotLargestNotChangeCwnd) { // packet5 is lost: loss.addLostPacket(packet5); - cubic.onPacketAckOrLoss(none, std::move(loss)); + cubic.onPacketAckOrLoss(std::nullopt, std::move(loss)); EXPECT_EQ(CubicStates::FastRecovery, cubic.state()); auto cwndAfterLoss = cubic.getWritableBytes() + 4000; // 4k are in flight // the the rest are acked: cubic.onPacketAckOrLoss( - makeAck(0, 1000, Clock::now(), packet1.metadata.time), none); + makeAck(0, 1000, Clock::now(), packet1.metadata.time), std::nullopt); cubic.onPacketAckOrLoss( - makeAck(1, 1000, Clock::now(), packet2.metadata.time), none); + makeAck(1, 1000, Clock::now(), packet2.metadata.time), std::nullopt); cubic.onPacketAckOrLoss( - makeAck(2, 1000, Clock::now(), packet3.metadata.time), none); + makeAck(2, 1000, Clock::now(), packet3.metadata.time), std::nullopt); cubic.onPacketAckOrLoss( - makeAck(3, 1000, Clock::now(), packet4.metadata.time), none); + makeAck(3, 1000, Clock::now(), packet4.metadata.time), std::nullopt); // Still in recovery: EXPECT_EQ(CubicStates::FastRecovery, cubic.state()); diff --git a/quic/congestion_control/test/CubicStateTest.cpp b/quic/congestion_control/test/CubicStateTest.cpp index 0399d4a40..4d1f743f0 100644 --- a/quic/congestion_control/test/CubicStateTest.cpp +++ b/quic/congestion_control/test/CubicStateTest.cpp @@ -23,7 +23,7 @@ TEST_F(CubicStateTest, HystartLoss) { auto packet = makeTestingWritePacket(0, 0, 0); CongestionController::LossEvent lossEvent(Clock::now()); lossEvent.addLostPacket(packet); - cubic.onPacketAckOrLoss(none, lossEvent); + cubic.onPacketAckOrLoss(std::nullopt, lossEvent); EXPECT_EQ(CubicStates::FastRecovery, cubic.state()); } @@ -33,7 +33,7 @@ TEST_F(CubicStateTest, HystartAck) { auto packet = makeTestingWritePacket(0, 0, 0); cubic.onPacketSent(packet); cubic.onPacketAckOrLoss( - makeAck(0, 0, Clock::now(), packet.metadata.time), none); + makeAck(0, 0, Clock::now(), packet.metadata.time), std::nullopt); EXPECT_EQ(CubicStates::Hystart, cubic.state()); } @@ -50,9 +50,9 @@ TEST_F(CubicStateTest, FastRecoveryAck) { cubic.onPacketSent(packet1); CongestionController::LossEvent loss; loss.addLostPacket(packet); - cubic.onPacketAckOrLoss(none, std::move(loss)); + cubic.onPacketAckOrLoss(std::nullopt, std::move(loss)); cubic.onPacketAckOrLoss( - makeAck(2, 1000, Clock::now(), packet1.metadata.time), none); + makeAck(2, 1000, Clock::now(), packet1.metadata.time), std::nullopt); EXPECT_EQ(CubicStates::FastRecovery, cubic.state()); } @@ -64,11 +64,11 @@ TEST_F(CubicStateTest, FastRecoveryAckToSteady) { cubic.onPacketSent(packet); CongestionController::LossEvent loss; loss.addLostPacket(packet); - cubic.onPacketAckOrLoss(none, std::move(loss)); + cubic.onPacketAckOrLoss(std::nullopt, std::move(loss)); auto packet1 = makeTestingWritePacket(1, 1, 2); cubic.onPacketSent(packet1); cubic.onPacketAckOrLoss( - makeAck(1, 1, Clock::now(), packet1.metadata.time), none); + makeAck(1, 1, Clock::now(), packet1.metadata.time), std::nullopt); EXPECT_EQ(CubicStates::Steady, cubic.state()); } @@ -79,7 +79,7 @@ TEST_F(CubicStateTest, FastRecoveryLoss) { auto packet = makeTestingWritePacket(0, 0, 0); CongestionController::LossEvent lossEvent(Clock::now()); lossEvent.addLostPacket(packet); - cubic.onPacketAckOrLoss(none, lossEvent); + cubic.onPacketAckOrLoss(std::nullopt, lossEvent); EXPECT_EQ(CubicStates::FastRecovery, cubic.state()); } @@ -92,7 +92,7 @@ TEST_F(CubicStateTest, SteadyAck) { auto packet = makeTestingWritePacket(0, 0, 0); cubic.onPacketSent(packet); cubic.onPacketAckOrLoss( - makeAck(0, 0, Clock::now(), packet.metadata.time), none); + makeAck(0, 0, Clock::now(), packet.metadata.time), std::nullopt); EXPECT_EQ(CubicStates::Steady, cubic.state()); } @@ -103,7 +103,7 @@ TEST_F(CubicStateTest, SteadyLoss) { auto packet = makeTestingWritePacket(0, 0, 0); CongestionController::LossEvent lossEvent(Clock::now()); lossEvent.addLostPacket(packet); - cubic.onPacketAckOrLoss(none, lossEvent); + cubic.onPacketAckOrLoss(std::nullopt, lossEvent); EXPECT_EQ(CubicStates::FastRecovery, cubic.state()); } } // namespace quic::test diff --git a/quic/congestion_control/test/CubicSteadyTest.cpp b/quic/congestion_control/test/CubicSteadyTest.cpp index 897f6459b..f461c47e6 100644 --- a/quic/congestion_control/test/CubicSteadyTest.cpp +++ b/quic/congestion_control/test/CubicSteadyTest.cpp @@ -28,7 +28,7 @@ TEST_F(CubicSteadyTest, CubicReduction) { conn.lossState.largestSent = 0; cubic.onPacketSent(packet0); cubic.onPacketAckOrLoss( - makeAck(0, 1000, Clock::now(), packet0.metadata.time), none); + makeAck(0, 1000, Clock::now(), packet0.metadata.time), std::nullopt); EXPECT_EQ(3000, cubic.getWritableBytes()); EXPECT_EQ(CubicStates::Steady, cubic.state()); @@ -39,7 +39,7 @@ TEST_F(CubicSteadyTest, CubicReduction) { cubic.onPacketSent(packet1); CongestionController::LossEvent loss; loss.addLostPacket(packet1); - cubic.onPacketAckOrLoss(none, std::move(loss)); + cubic.onPacketAckOrLoss(std::nullopt, std::move(loss)); EXPECT_EQ(2100, cubic.getWritableBytes()); EXPECT_EQ(CubicStates::FastRecovery, cubic.state()); } diff --git a/quic/congestion_control/test/CubicTest.cpp b/quic/congestion_control/test/CubicTest.cpp index 002bcaff8..cdc188216 100644 --- a/quic/congestion_control/test/CubicTest.cpp +++ b/quic/congestion_control/test/CubicTest.cpp @@ -34,7 +34,7 @@ TEST_F(CubicTest, AckIncreaseWritable) { // Acking 50, now inflight become 50. Cwnd is init + 50 cubic.onPacketAckOrLoss( - makeAck(0, 50, Clock::now(), packet.metadata.time), none); + makeAck(0, 50, Clock::now(), packet.metadata.time), std::nullopt); EXPECT_EQ(initCwnd, cubic.getWritableBytes()); } @@ -50,7 +50,7 @@ TEST_F(CubicTest, PersistentCongestion) { CongestionController::LossEvent loss; loss.addLostPacket(packet); loss.persistentCongestion = true; - cubic.onPacketAckOrLoss(none, std::move(loss)); + cubic.onPacketAckOrLoss(std::nullopt, std::move(loss)); EXPECT_EQ(CubicStates::Hystart, cubic.state()); // Cwnd should be dropped to minCwnd: EXPECT_EQ( @@ -61,7 +61,8 @@ TEST_F(CubicTest, PersistentCongestion) { auto packet2 = makeTestingWritePacket(1, initCwnd / 2, initCwnd / 2 + 1000); cubic.onPacketSent(packet2); cubic.onPacketAckOrLoss( - makeAck(1, initCwnd / 2, Clock::now(), packet2.metadata.time), none); + makeAck(1, initCwnd / 2, Clock::now(), packet2.metadata.time), + std::nullopt); EXPECT_EQ(CubicStates::Steady, cubic.state()); // Verify both lastMaxCwndBytes and lastReductionTime are also reset in @@ -72,7 +73,7 @@ TEST_F(CubicTest, PersistentCongestion) { auto packet3 = makeTestingWritePacket(2, 3000, initCwnd / 2 + 1000 + 3000); cubic.onPacketSent(packet3); cubic.onPacketAckOrLoss( - makeAck(2, 3000, Clock::now(), packet3.metadata.time), none); + makeAck(2, 3000, Clock::now(), packet3.metadata.time), std::nullopt); std::vector indices = getQLogEventIndices(QLogEventType::CongestionMetricUpdate, qLogger); @@ -126,7 +127,7 @@ TEST_F(CubicTest, CwndIncreaseAfterReduction) { conn.lossState.largestSent = 0; cubic.onPacketSent(packet0); cubic.onPacketAckOrLoss( - makeAck(0, 1000, Clock::now(), packet0.metadata.time), none); + makeAck(0, 1000, Clock::now(), packet0.metadata.time), std::nullopt); // Cwnd increased by 1000, inflight = 0: EXPECT_EQ(3000, cubic.getWritableBytes()); EXPECT_EQ(CubicStates::Steady, cubic.state()); @@ -143,17 +144,17 @@ TEST_F(CubicTest, CwndIncreaseAfterReduction) { EXPECT_EQ(0, cubic.getWritableBytes()); cubic.onPacketAckOrLoss( - makeAck(1, 1000, Clock::now(), packet1.metadata.time), none); + makeAck(1, 1000, Clock::now(), packet1.metadata.time), std::nullopt); // Cwnd >= 3000, inflight = 2000: EXPECT_GE(cubic.getWritableBytes(), 1000); CongestionController::LossEvent loss; loss.addLostPacket(packet2); - cubic.onPacketAckOrLoss(none, std::move(loss)); + cubic.onPacketAckOrLoss(std::nullopt, std::move(loss)); // Cwnd >= 2100, inflight = 1000: EXPECT_GE(cubic.getWritableBytes(), 1100); // This won't bring state machine back to Steady since endOfRecovery = 3 cubic.onPacketAckOrLoss( - makeAck(3, 1000, Clock::now(), packet3.metadata.time), none); + makeAck(3, 1000, Clock::now(), packet3.metadata.time), std::nullopt); // Cwnd no change, inflight = 0: EXPECT_GE(cubic.getWritableBytes(), 2100); EXPECT_EQ(CubicStates::FastRecovery, cubic.state()); @@ -163,7 +164,7 @@ TEST_F(CubicTest, CwndIncreaseAfterReduction) { cubic.onPacketSent(packet4); // This will bring state machine back to steady cubic.onPacketAckOrLoss( - makeAck(4, 1000, Clock::now(), packet4.metadata.time), none); + makeAck(4, 1000, Clock::now(), packet4.metadata.time), std::nullopt); EXPECT_GE(cubic.getWritableBytes(), 2100); EXPECT_EQ(CubicStates::Steady, cubic.state()); @@ -189,7 +190,7 @@ TEST_F(CubicTest, AppIdle) { auto maxCwnd = cubic.getCongestionWindow(); CongestionController::LossEvent loss(reductionTime); loss.addLostPacket(packet); - cubic.onPacketAckOrLoss(none, std::move(loss)); + cubic.onPacketAckOrLoss(std::nullopt, std::move(loss)); auto timeToOrigin = ::cbrt( (maxCwnd - cubic.getCongestionWindow()) * 1000 * 1000 / conn.udpSendPacketLen * 2500); @@ -198,7 +199,8 @@ TEST_F(CubicTest, AppIdle) { auto packet1 = makeTestingWritePacket(1, 1000, 2000); cubic.onPacketSent(packet1); cubic.onPacketAckOrLoss( - makeAck(1, 1000, reductionTime + 1000ms, packet1.metadata.time), none); + makeAck(1, 1000, reductionTime + 1000ms, packet1.metadata.time), + std::nullopt); EXPECT_EQ(CubicStates::Steady, cubic.state()); EXPECT_GT(cubic.getCongestionWindow(), cwnd); cwnd = cubic.getCongestionWindow(); @@ -208,7 +210,8 @@ TEST_F(CubicTest, AppIdle) { auto packet2 = makeTestingWritePacket(2, 1000, 3000); cubic.onPacketSent(packet2); cubic.onPacketAckOrLoss( - makeAck(2, 1000, reductionTime + 2000ms, packet2.metadata.time), none); + makeAck(2, 1000, reductionTime + 2000ms, packet2.metadata.time), + std::nullopt); EXPECT_EQ(cubic.getCongestionWindow(), cwnd); // 1 seconds of quiescence @@ -217,7 +220,8 @@ TEST_F(CubicTest, AppIdle) { auto packet3 = makeTestingWritePacket(3, 1000, 4000); cubic.onPacketSent(packet3); cubic.onPacketAckOrLoss( - makeAck(3, 1000, reductionTime + 3000ms, packet3.metadata.time), none); + makeAck(3, 1000, reductionTime + 3000ms, packet3.metadata.time), + std::nullopt); EXPECT_GT(cubic.getCongestionWindow(), cwnd); auto expectedDelta = static_cast(std::floor( @@ -258,7 +262,7 @@ TEST_F(CubicTest, PacingGain) { EXPECT_EQ(cubic.getCongestionWindow() * 2, cwndBytes); })); cubic.onPacketAckOrLoss( - makeAck(0, 1500, Clock::now(), packet.metadata.time), none); + makeAck(0, 1500, Clock::now(), packet.metadata.time), std::nullopt); EXPECT_EQ(CubicStates::Hystart, cubic.state()); auto packet1 = makeTestingWritePacket(1, 1500, 3000); @@ -274,7 +278,7 @@ TEST_F(CubicTest, PacingGain) { static_cast(cubic.getCongestionWindow() * 1.25), cwndBytes); })); - cubic.onPacketAckOrLoss(none, loss); + cubic.onPacketAckOrLoss(std::nullopt, loss); EXPECT_EQ(CubicStates::FastRecovery, cubic.state()); auto packet2 = makeTestingWritePacket(2, 1500, 4500); @@ -286,7 +290,7 @@ TEST_F(CubicTest, PacingGain) { EXPECT_EQ(cubic.getCongestionWindow(), cwndBytes); })); cubic.onPacketAckOrLoss( - makeAck(2, 1500, Clock::now(), packet2.metadata.time), none); + makeAck(2, 1500, Clock::now(), packet2.metadata.time), std::nullopt); EXPECT_EQ(CubicStates::Steady, cubic.state()); std::vector indices = @@ -309,7 +313,7 @@ TEST_F(CubicTest, PacetLossInvokesPacer) { EXPECT_CALL(*rawPacer, onPacketsLoss()).Times(1); CongestionController::LossEvent lossEvent; lossEvent.addLostPacket(packet); - cubic.onPacketAckOrLoss(none, lossEvent); + cubic.onPacketAckOrLoss(std::nullopt, lossEvent); } TEST_F(CubicTest, InitCwnd) { diff --git a/quic/congestion_control/test/NewRenoTest.cpp b/quic/congestion_control/test/NewRenoTest.cpp index 7acea01c4..839b73d5c 100644 --- a/quic/congestion_control/test/NewRenoTest.cpp +++ b/quic/congestion_control/test/NewRenoTest.cpp @@ -109,19 +109,22 @@ TEST_F(NewRenoTest, TestLoss) { EXPECT_EQ(reno.getBytesInFlight(), 41); auto originalWritableBytes = reno.getWritableBytes(); - reno.onPacketAckOrLoss(none, createLossEvent({std::make_pair(loss1, 11)})); + reno.onPacketAckOrLoss( + std::nullopt, createLossEvent({std::make_pair(loss1, 11)})); EXPECT_EQ(reno.getBytesInFlight(), 30); EXPECT_FALSE(reno.inSlowStart()); auto newWritableBytes1 = reno.getWritableBytes(); EXPECT_LE(newWritableBytes1, originalWritableBytes + 11); - reno.onPacketAckOrLoss(none, createLossEvent({std::make_pair(loss2, 10)})); + reno.onPacketAckOrLoss( + std::nullopt, createLossEvent({std::make_pair(loss2, 10)})); auto newWritableBytes2 = reno.getWritableBytes(); EXPECT_LE(newWritableBytes2, newWritableBytes1 + 10); EXPECT_EQ(reno.getBytesInFlight(), 20); - reno.onPacketAckOrLoss(none, createLossEvent({std::make_pair(loss3, 20)})); + reno.onPacketAckOrLoss( + std::nullopt, createLossEvent({std::make_pair(loss3, 20)})); auto newWritableBytes3 = reno.getWritableBytes(); EXPECT_LE(newWritableBytes3, newWritableBytes2 + 20); EXPECT_EQ(reno.getBytesInFlight(), 0); @@ -140,7 +143,7 @@ TEST_F(NewRenoTest, SendMoreThanWritable) { EXPECT_EQ(reno.getBytesInFlight(), originalWritableBytes + 20); EXPECT_EQ(reno.getWritableBytes(), 0); reno.onPacketAckOrLoss( - none, + std::nullopt, createLossEvent({std::make_pair(loss, originalWritableBytes + 20)})); EXPECT_LT(reno.getWritableBytes(), originalWritableBytes); } @@ -159,7 +162,8 @@ TEST_F(NewRenoTest, TestSlowStartAck) { reno.onPacketSent(packet); EXPECT_EQ(reno.getBytesInFlight(), ackedSize); reno.onPacketAckOrLoss( - createAckEvent(ackPacketNum1, ackedSize, packet.metadata.time), none); + createAckEvent(ackPacketNum1, ackedSize, packet.metadata.time), + std::nullopt); EXPECT_TRUE(reno.inSlowStart()); auto newWritableBytes = reno.getWritableBytes(); @@ -176,7 +180,8 @@ TEST_F(NewRenoTest, TestSteadyStateAck) { auto originalWritableBytes = reno.getWritableBytes(); PacketNum loss1 = 4; reno.onPacketSent(createPacket(loss1, 10, Clock::now())); - reno.onPacketAckOrLoss(none, createLossEvent({std::make_pair(loss1, 10)})); + reno.onPacketAckOrLoss( + std::nullopt, createLossEvent({std::make_pair(loss1, 10)})); EXPECT_FALSE(reno.inSlowStart()); auto newWritableBytes1 = reno.getWritableBytes(); EXPECT_LT(newWritableBytes1, originalWritableBytes); @@ -187,7 +192,8 @@ TEST_F(NewRenoTest, TestSteadyStateAck) { ackPacketNum1, ackedSize, Clock::now() - std::chrono::milliseconds(10)); reno.onPacketSent(packet1); reno.onPacketAckOrLoss( - createAckEvent(ackPacketNum1, ackedSize, packet1.metadata.time), none); + createAckEvent(ackPacketNum1, ackedSize, packet1.metadata.time), + std::nullopt); EXPECT_FALSE(reno.inSlowStart()); auto newWritableBytes2 = reno.getWritableBytes(); @@ -197,7 +203,8 @@ TEST_F(NewRenoTest, TestSteadyStateAck) { auto packet2 = createPacket(ackPacketNum2, ackedSize, Clock::now()); reno.onPacketSent(packet2); reno.onPacketAckOrLoss( - createAckEvent(ackPacketNum2, ackedSize, packet2.metadata.time), none); + createAckEvent(ackPacketNum2, ackedSize, packet2.metadata.time), + std::nullopt); EXPECT_FALSE(reno.inSlowStart()); auto newWritableBytes3 = reno.getWritableBytes(); @@ -237,7 +244,7 @@ TEST_F(NewRenoTest, PersistentCongestion) { CongestionController::LossEvent loss; loss.persistentCongestion = true; loss.addLostPacket(pkt); - reno.onPacketAckOrLoss(none, loss); + reno.onPacketAckOrLoss(std::nullopt, loss); EXPECT_EQ( reno.getWritableBytes(), conn.transportSettings.minCwndInMss * conn.udpSendPacketLen); diff --git a/quic/congestion_control/test/SimulatedTBFTest.cpp b/quic/congestion_control/test/SimulatedTBFTest.cpp index da24ef7f3..fd3b53f56 100644 --- a/quic/congestion_control/test/SimulatedTBFTest.cpp +++ b/quic/congestion_control/test/SimulatedTBFTest.cpp @@ -203,7 +203,7 @@ TEST_F(SimulatedTBFTest, MultiConsumeWithEmptyInterval) { /* * Check the size and content of the deque after multiple consumes at increasing - * time intervals, where none of them put the bucket in debt. + * time intervals, where std::nullopt of them put the bucket in debt. */ TEST_F(SimulatedTBFTest, MultiConsumeNoEmptyInterval) { SimulatedTBF::Config config; diff --git a/quic/congestion_control/test/ThrottlingSignalProviderTest.cpp b/quic/congestion_control/test/ThrottlingSignalProviderTest.cpp index ac4d24c79..9d5d734c8 100644 --- a/quic/congestion_control/test/ThrottlingSignalProviderTest.cpp +++ b/quic/congestion_control/test/ThrottlingSignalProviderTest.cpp @@ -25,7 +25,7 @@ class SimpleThrottlingSignalProvider : public PacketProcessor, public: explicit SimpleThrottlingSignalProvider( SimulatedTBF::Config config, - Optional burstRateBytesPerSecond = none) + Optional burstRateBytesPerSecond = std::nullopt) : stbf_(std::move(config)), burstRateBytesPerSecond_(std::move(burstRateBytesPerSecond)) {} @@ -42,10 +42,10 @@ class SimpleThrottlingSignalProvider : public PacketProcessor, ThrottlingSignal signal = {}; signal.state = availTokens > 0 ? ThrottlingSignal::State::Burst : ThrottlingSignal::State::Throttled; - signal.maybeBytesToSend.assign((uint64_t)availTokens); - signal.maybeThrottledRateBytesPerSecond.assign( - (uint64_t)stbf_.getRateBytesPerSecond()); - signal.maybeBurstRateBytesPerSecond.assign(burstRateBytesPerSecond_); + signal.maybeBytesToSend = (uint64_t)availTokens; + signal.maybeThrottledRateBytesPerSecond = + (uint64_t)stbf_.getRateBytesPerSecond(); + signal.maybeBurstRateBytesPerSecond = burstRateBytesPerSecond_; return signal; } @@ -158,7 +158,7 @@ TEST( bbr.onPacketAckOrLoss( makeAck( pn, 2000, now + std::chrono::milliseconds{5}, packet.metadata.time), - none); + std::nullopt); auto maybeSignal = signalProvider->getCurrentThrottlingSignal(); ASSERT_TRUE(maybeSignal.has_value()); ASSERT_TRUE(bbr.getBandwidth().has_value()); diff --git a/quic/docs/docsite/static/img/logo.svg b/quic/docs/docsite/static/img/logo.svg index 9db6d0d06..b6c572f94 100644 --- a/quic/docs/docsite/static/img/logo.svg +++ b/quic/docs/docsite/static/img/logo.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/quic/dsr/frontend/Scheduler.cpp b/quic/dsr/frontend/Scheduler.cpp index 54ab7103b..9a2c72b9d 100644 --- a/quic/dsr/frontend/Scheduler.cpp +++ b/quic/dsr/frontend/Scheduler.cpp @@ -99,7 +99,7 @@ DSRStreamFrameScheduler::writeStreamImpl( auto txn = writeQueue.beginTransaction(); auto guard = folly::makeGuard([&] { writeQueue.rollbackTransaction(std::move(txn)); }); - auto id = writeQueue.getNextScheduledID(quic::none); + auto id = writeQueue.getNextScheduledID(std::nullopt); CHECK(id.isStreamID()); auto streamId = id.asStreamID(); auto stream = conn_.streamManager->findStream(streamId); diff --git a/quic/dsr/frontend/WriteFunctions.cpp b/quic/dsr/frontend/WriteFunctions.cpp index aebcb6bd3..3e27a9845 100644 --- a/quic/dsr/frontend/WriteFunctions.cpp +++ b/quic/dsr/frontend/WriteFunctions.cpp @@ -87,7 +87,7 @@ folly::Expected writePacketizationRequest( // of addSendInstruction() call. auto updateResult = updateConnection( connection, - none /* Packet Event */, + std::nullopt /* Packet Event */, packet.packet, Clock::now(), packet.encodedSize + cipherOverhead, diff --git a/quic/fizz/client/handshake/FizzClientHandshake.cpp b/quic/fizz/client/handshake/FizzClientHandshake.cpp index 1a69e4347..f7a823566 100644 --- a/quic/fizz/client/handshake/FizzClientHandshake.cpp +++ b/quic/fizz/client/handshake/FizzClientHandshake.cpp @@ -34,9 +34,9 @@ FizzClientHandshake::FizzClientHandshake( Optional FizzClientHandshake::connectImpl( Optional hostname) { // Look up psk - Optional quicCachedPsk = getPsk(hostname); + auto quicCachedPsk = getPsk(hostname); - Optional cachedPsk; + folly::Optional cachedPsk; Optional transportParams; if (quicCachedPsk) { cachedPsk = std::move(quicCachedPsk->cachedPsk); @@ -53,41 +53,53 @@ Optional FizzClientHandshake::connectImpl( context->setOmitEarlyRecordLayer(true); Optional> echConfigs; - if (hostname.hasValue()) { - echConfigs = fizzContext_->getECHConfigs(*hostname); + if (hostname.has_value()) { + std::string hostnameStr = hostname.value(); + echConfigs = fizzContext_->getECHConfigs(hostnameStr); } + folly::Optional follyHostname; + if (hostname.has_value()) { + follyHostname = hostname.value(); + } + folly::Optional> follyECHConfigs; + if (echConfigs.has_value()) { + follyECHConfigs = std::move(echConfigs.value()); + } processActions(machine_.processConnect( state_, std::move(context), fizzContext_->getCertificateVerifier(), - std::move(hostname), + std::move(follyHostname), std::move(cachedPsk), std::make_shared( getClientTransportParameters(), fizzContext_->getChloPaddingBytes()), - std::move(echConfigs))); + std::move(follyECHConfigs))); return transportParams; } -Optional FizzClientHandshake::getPsk( +folly::Optional FizzClientHandshake::getPsk( const Optional& hostname) const { auto quicCachedPsk = fizzContext_->getPsk(hostname); if (!quicCachedPsk) { - return none; + return folly::none; } // TODO T32658838 better API to disable early data for current connection const QuicClientConnectionState* conn = getClientConn(); if (!conn->transportSettings.attemptEarlyData) { quicCachedPsk->cachedPsk.maxEarlyDataSize = 0; - } else if ( - conn->earlyDataAppParamsValidator && - !conn->earlyDataAppParamsValidator( - quicCachedPsk->cachedPsk.alpn, - BufHelpers::copyBuffer(quicCachedPsk->appParams))) { - quicCachedPsk->cachedPsk.maxEarlyDataSize = 0; - // Do not remove psk here, will let application decide + } else if (conn->earlyDataAppParamsValidator) { + Optional alpn; + if (quicCachedPsk->cachedPsk.alpn.has_value()) { + alpn = quicCachedPsk->cachedPsk.alpn.value(); + } + if (!conn->earlyDataAppParamsValidator( + alpn, BufHelpers::copyBuffer(quicCachedPsk->appParams))) { + quicCachedPsk->cachedPsk.maxEarlyDataSize = 0; + // Do not remove psk here, will let application decide + } } return quicCachedPsk; @@ -103,11 +115,17 @@ const CryptoFactory& FizzClientHandshake::getCryptoFactory() const { const Optional& FizzClientHandshake::getApplicationProtocol() const { + static thread_local Optional result; auto& earlyDataParams = state_.earlyDataParams(); - if (earlyDataParams) { - return earlyDataParams->alpn; + if (earlyDataParams && earlyDataParams->alpn.has_value()) { + result = earlyDataParams->alpn.value(); + return result; + } else if (state_.alpn().has_value()) { + result = state_.alpn().value(); + return result; } else { - return state_.alpn(); + static Optional empty; + return empty; } } @@ -144,8 +162,8 @@ Optional> FizzClientHandshake::getExportedKeyingMaterial( uint16_t keyLength) { const auto& ems = state_.exporterMasterSecret(); const auto cipherSuite = state_.cipher(); - if (!ems.hasValue() || !cipherSuite.hasValue()) { - return none; + if (!ems.has_value() || !cipherSuite.has_value()) { + return std::nullopt; } auto ekm = fizz::Exporter::getExportedKeyingMaterial( @@ -153,7 +171,7 @@ Optional> FizzClientHandshake::getExportedKeyingMaterial( cipherSuite.value(), ems.value()->coalesce(), label, - context == none ? nullptr : BufHelpers::wrapBuffer(*context), + context == std::nullopt ? nullptr : BufHelpers::wrapBuffer(*context), keyLength); std::vector result(ekm->coalesce()); @@ -227,7 +245,11 @@ void FizzClientHandshake::onNewCachedPsk( } } - fizzContext_->putPsk(state_.sni(), std::move(quicCachedPsk)); + Optional sni; + if (state_.sni().has_value()) { + sni = state_.sni().value(); + } + fizzContext_->putPsk(sni, std::move(quicCachedPsk)); } void FizzClientHandshake::echRetryAvailable( @@ -244,18 +266,18 @@ FizzClientHandshake::getPeerCertificate() const { Handshake::TLSSummary FizzClientHandshake::getTLSSummary() const { Handshake::TLSSummary summary; - if (state_.alpn().hasValue()) { + if (state_.alpn().has_value()) { summary.alpn = state_.alpn().value(); } - if (state_.group().hasValue()) { + if (state_.group().has_value()) { summary.namedGroup = folly::to(fizz::toString(state_.group().value())); } - if (state_.pskType().hasValue()) { + if (state_.pskType().has_value()) { summary.pskType = folly::to(fizz::toString(state_.pskType().value())); } - if (state_.echState().hasValue()) { + if (state_.echState().has_value()) { summary.echStatus = fizz::client::toString(state_.echState().value().status); } diff --git a/quic/fizz/client/handshake/FizzClientHandshake.h b/quic/fizz/client/handshake/FizzClientHandshake.h index 056ccdf03..e5cddc053 100644 --- a/quic/fizz/client/handshake/FizzClientHandshake.h +++ b/quic/fizz/client/handshake/FizzClientHandshake.h @@ -62,7 +62,8 @@ class FizzClientHandshake : public ClientHandshake { TLSSummary getTLSSummary() const override; protected: - Optional getPsk(const Optional& hostname) const; + folly::Optional getPsk( + const Optional& hostname) const; void onNewCachedPsk(fizz::client::NewCachedPsk& newCachedPsk) noexcept; diff --git a/quic/fizz/client/handshake/FizzClientQuicHandshakeContext.cpp b/quic/fizz/client/handshake/FizzClientQuicHandshakeContext.cpp index 065ad438e..0b1fdf213 100644 --- a/quic/fizz/client/handshake/FizzClientQuicHandshakeContext.cpp +++ b/quic/fizz/client/handshake/FizzClientQuicHandshakeContext.cpp @@ -57,36 +57,47 @@ FizzClientQuicHandshakeContext::makeClientHandshake( return handshake; } -Optional FizzClientQuicHandshakeContext::getPsk( +folly::Optional FizzClientQuicHandshakeContext::getPsk( const Optional& hostname) { if (!hostname || !pskCache_) { - return none; + return folly::none; } - return pskCache_->getPsk(*hostname); + auto res = pskCache_->getPsk(hostname.value()); + if (res) { + return res.value(); + } else { + return folly::none; + } } void FizzClientQuicHandshakeContext::putPsk( const Optional& hostname, QuicCachedPsk quicCachedPsk) { if (hostname && pskCache_) { - pskCache_->putPsk(*hostname, std::move(quicCachedPsk)); + pskCache_->putPsk(hostname.value(), std::move(quicCachedPsk)); } } void FizzClientQuicHandshakeContext::removePsk( const Optional& hostname) { if (hostname && pskCache_) { - pskCache_->removePsk(*hostname); + pskCache_->removePsk(hostname.value()); } } Optional> FizzClientQuicHandshakeContext::getECHConfigs(const std::string& sni) const { if (!echPolicy_) { - return none; + return std::nullopt; + } + auto result = echPolicy_->getConfig(sni); + if (result.has_value()) { + return Optional>( + std::move(result.value())); + } else { + return std::nullopt; } - return echPolicy_->getConfig(sni); } std::shared_ptr diff --git a/quic/fizz/client/handshake/FizzClientQuicHandshakeContext.h b/quic/fizz/client/handshake/FizzClientQuicHandshakeContext.h index 6101a56e3..003530313 100644 --- a/quic/fizz/client/handshake/FizzClientQuicHandshakeContext.h +++ b/quic/fizz/client/handshake/FizzClientQuicHandshakeContext.h @@ -39,7 +39,7 @@ class FizzClientQuicHandshakeContext return verifier_; } - Optional getPsk(const Optional& hostname); + folly::Optional getPsk(const Optional& hostname); void putPsk( const Optional& hostname, QuicCachedPsk quicCachedPsk); diff --git a/quic/fizz/client/handshake/QuicPskCache.h b/quic/fizz/client/handshake/QuicPskCache.h index 11349eaec..f799b809d 100644 --- a/quic/fizz/client/handshake/QuicPskCache.h +++ b/quic/fizz/client/handshake/QuicPskCache.h @@ -44,7 +44,7 @@ class BasicQuicPskCache : public QuicPskCache { if (result != cache_.end()) { return result->second; } - return none; + return std::nullopt; } void putPsk(const std::string& identity, QuicCachedPsk psk) override { diff --git a/quic/fizz/client/handshake/QuicTokenCache.h b/quic/fizz/client/handshake/QuicTokenCache.h index 10f3c1f7c..57e30e260 100644 --- a/quic/fizz/client/handshake/QuicTokenCache.h +++ b/quic/fizz/client/handshake/QuicTokenCache.h @@ -36,7 +36,7 @@ class BasicQuicTokenCache : public QuicTokenCache { if (res != cache_.end()) { return res->second; } - return none; + return std::nullopt; } void putToken(const std::string& hostname, std::string token) override { diff --git a/quic/fizz/client/handshake/test/FizzClientHandshakeTest.cpp b/quic/fizz/client/handshake/test/FizzClientHandshakeTest.cpp index 6c653a6be..64afb49e2 100644 --- a/quic/fizz/client/handshake/test/FizzClientHandshakeTest.cpp +++ b/quic/fizz/client/handshake/test/FizzClientHandshakeTest.cpp @@ -302,14 +302,15 @@ class ClientHandshakeTest : public Test, public boost::static_visitor<> { TEST_F(ClientHandshakeTest, TestGetExportedKeyingMaterial) { // Sanity check. getExportedKeyingMaterial () should return nullptr prior to // an handshake. - auto ekm = - handshake->getExportedKeyingMaterial("EXPORTER-Some-Label", none, 32); + auto ekm = handshake->getExportedKeyingMaterial( + "EXPORTER-Some-Label", std::nullopt, 32); EXPECT_TRUE(!ekm.has_value()); clientServerRound(); serverClientRound(); handshake->handshakeConfirmed(); - ekm = handshake->getExportedKeyingMaterial("EXPORTER-Some-Label", none, 32); + ekm = handshake->getExportedKeyingMaterial( + "EXPORTER-Some-Label", std::nullopt, 32); ASSERT_TRUE(ekm.has_value()); EXPECT_EQ(ekm->size(), 32); diff --git a/quic/fizz/client/test/QuicClientTransportTest.cpp b/quic/fizz/client/test/QuicClientTransportTest.cpp index 45633ac34..e62b7405a 100644 --- a/quic/fizz/client/test/QuicClientTransportTest.cpp +++ b/quic/fizz/client/test/QuicClientTransportTest.cpp @@ -381,10 +381,10 @@ TEST_P(QuicClientTransportIntegrationTest, FlowControlLimitedTest) { TEST_P(QuicClientTransportIntegrationTest, ALPNTest) { EXPECT_CALL(clientConnSetupCallback, onTransportReady()).WillOnce(Invoke([&] { ASSERT_EQ(client->getAppProtocol(), "h3"); - client->close(none); + client->close(std::nullopt); eventbase_.terminateLoopSoon(); })); - ASSERT_EQ(client->getAppProtocol(), none); + ASSERT_EQ(client->getAppProtocol(), std::nullopt); client->start(&clientConnSetupCallback, &clientConnCallback); eventbase_.loopForever(); } @@ -401,13 +401,13 @@ TEST_P(QuicClientTransportIntegrationTest, TLSAlert) { const TransportErrorCode* transportError = errorCode.code.asTransportErrorCode(); EXPECT_NE(transportError, nullptr); - client->close(none); + client->close(std::nullopt); this->checkTransportSummaryEvent(qLogger); eventbase_.terminateLoopSoon(); })); - ASSERT_EQ(client->getAppProtocol(), none); + ASSERT_EQ(client->getAppProtocol(), std::nullopt); client->start(&clientConnSetupCallback, &clientConnCallback); eventbase_.loopForever(); @@ -1054,7 +1054,7 @@ TEST_F(QuicClientTransportTest, FirstPacketProcessedCallback) { deliverData(serverAddr, oneMoreAckPacket->coalesce()); EXPECT_FALSE(client->hasWriteCipher()); - client->closeNow(none); + client->closeNow(std::nullopt); } TEST_F(QuicClientTransportTest, CloseSocketOnWriteError) { @@ -1079,7 +1079,7 @@ TEST_F(QuicClientTransportTest, AddNewPeerAddressSetsPacketSize) { client->addNewPeerAddress(v6Address); EXPECT_EQ(kDefaultV6UDPSendPacketLen, client->getConn().udpSendPacketLen); - client->closeNow(none); + client->closeNow(std::nullopt); } TEST_F(QuicClientTransportTest, onNetworkSwitchNoReplace) { @@ -1089,7 +1089,7 @@ TEST_F(QuicClientTransportTest, onNetworkSwitchNoReplace) { EXPECT_CALL(*mockQLogger, addConnectionMigrationUpdate(true)).Times(0); client->onNetworkSwitch(nullptr); - client->closeNow(none); + client->closeNow(std::nullopt); } TEST_F(QuicClientTransportTest, onNetworkSwitchReplaceAfterHandshake) { @@ -1152,7 +1152,7 @@ TEST_F(QuicClientTransportTest, onNetworkSwitchReplaceAfterHandshake) { EXPECT_CALL(*mockQLogger, addConnectionMigrationUpdate(true)); client->onNetworkSwitch(std::move(newSocket)); - client->closeNow(none); + client->closeNow(std::nullopt); } TEST_F(QuicClientTransportTest, onNetworkSwitchReplaceNoHandshake) { @@ -1202,7 +1202,7 @@ TEST_F(QuicClientTransportTest, onNetworkSwitchReplaceNoHandshake) { EXPECT_CALL(*mockQLogger, addConnectionMigrationUpdate(true)).Times(0); EXPECT_CALL(*newSocketPtr, bind(_)).Times(0); client->onNetworkSwitch(std::move(newSocket)); - client->closeNow(none); + client->closeNow(std::nullopt); } TEST_F(QuicClientTransportTest, SocketClosedDuringOnTransportReady) { @@ -1215,7 +1215,7 @@ TEST_F(QuicClientTransportTest, SocketClosedDuringOnTransportReady) { : socket_(std::move(socket)) {} void onTransportReady() noexcept override { - socket_->close(none); + socket_->close(std::nullopt); socket_.reset(); onTransportReadyMock(); } @@ -1327,7 +1327,7 @@ TEST_F(QuicClientTransportTest, SetQLoggerDcid) { EXPECT_CALL( *mockQLogger, setDcid(client->getConn().clientChosenDestConnectionId)); client->setQLogger(mockQLogger); - client->closeNow(none); + client->closeNow(std::nullopt); } TEST_F(QuicClientTransportTest, CheckQLoggerRefCount) { @@ -1359,7 +1359,7 @@ TEST_F(QuicClientTransportTest, CheckQLoggerRefCount) { client->setQLogger(nullptr); CHECK(client->getQLogger() == nullptr); - client->closeNow(none); + client->closeNow(std::nullopt); } TEST_F(QuicClientTransportTest, SwitchServerCidsNoOtherIds) { @@ -1372,7 +1372,7 @@ TEST_F(QuicClientTransportTest, SwitchServerCidsNoOtherIds) { EXPECT_EQ(conn.retireAndSwitchPeerConnectionIds(), false); EXPECT_EQ(conn.pendingEvents.frames.size(), 0); EXPECT_EQ(conn.peerConnectionIds.size(), 1); - client->closeNow(none); + client->closeNow(std::nullopt); } TEST_F(QuicClientTransportTest, SwitchServerCidsOneOtherCid) { @@ -1397,7 +1397,7 @@ TEST_F(QuicClientTransportTest, SwitchServerCidsOneOtherCid) { auto replacedCid = conn.serverConnectionId; EXPECT_NE(originalCid.connId, *replacedCid); EXPECT_EQ(secondCid.connId, *replacedCid); - client->closeNow(none); + client->closeNow(std::nullopt); } TEST_F(QuicClientTransportTest, SwitchServerCidsMultipleCids) { @@ -1426,7 +1426,7 @@ TEST_F(QuicClientTransportTest, SwitchServerCidsMultipleCids) { auto replacedCid = conn.serverConnectionId; EXPECT_NE(originalCid.connId, *replacedCid); EXPECT_EQ(secondCid.connId, *replacedCid); - client->closeNow(none); + client->closeNow(std::nullopt); } enum class ServerFirstPacketType : uint8_t { ServerHello, Retry }; @@ -2470,7 +2470,7 @@ TEST_F(QuicClientTransportAfterStartTest, ReadStream) { eventbase_->loopForever(); } EXPECT_TRUE(dataDelivered); - client->close(none); + client->close(std::nullopt); } TEST_F(QuicClientTransportAfterStartTest, CleanupReadLoopCounting) { @@ -2572,7 +2572,7 @@ TEST_F(QuicClientTransportAfterStartTest, ReadStreamMultiplePackets) { *data, 0 /* cipherOverhead */, 0 /* largestAcked */, - none /* longHeaderOverride */, + std::nullopt /* longHeaderOverride */, false /* eof */)); auto packet2 = packetToBuf(createStreamPacket( *serverChosenConnId /* src */, @@ -2582,9 +2582,9 @@ TEST_F(QuicClientTransportAfterStartTest, ReadStreamMultiplePackets) { *data, 0 /* cipherOverhead */, 0 /* largestAcked */, - none /* longHeaderOverride */, + std::nullopt /* longHeaderOverride */, true /* eof */, - none /* shortHeaderOverride */, + std::nullopt /* shortHeaderOverride */, data->length() /* offset */)); socketReads.emplace_back(TestReadData(packet1->coalesce(), serverAddr)); @@ -2593,7 +2593,7 @@ TEST_F(QuicClientTransportAfterStartTest, ReadStreamMultiplePackets) { eventbase_->loopForever(); } EXPECT_TRUE(dataDelivered); - client->close(none); + client->close(std::nullopt); } TEST_F(QuicClientTransportAfterStartTest, ReadStreamWithRetriableError) { @@ -2603,7 +2603,7 @@ TEST_F(QuicClientTransportAfterStartTest, ReadStreamWithRetriableError) { EXPECT_CALL(readCb, readError(_, _)).Times(0); deliverNetworkError(EAGAIN); client->setReadCallback(streamId, nullptr); - client->close(none); + client->close(std::nullopt); } TEST_F(QuicClientTransportAfterStartTest, ReadStreamWithNonRetriableError) { @@ -2614,7 +2614,7 @@ TEST_F(QuicClientTransportAfterStartTest, ReadStreamWithNonRetriableError) { EXPECT_CALL(readCb, readError(_, _)).Times(0); deliverNetworkError(EBADF); client->setReadCallback(streamId, nullptr); - client->close(none); + client->close(std::nullopt); } TEST_F( @@ -2649,7 +2649,7 @@ TEST_F( eventbase_->loopForever(); } EXPECT_TRUE(dataDelivered); - client->close(none); + client->close(std::nullopt); } TEST_F( @@ -2930,7 +2930,7 @@ TEST_P(QuicClientTransportAfterStartTest, ReadStreamCoalesced) { eventbase_->loopForever(); } EXPECT_TRUE(dataDelivered); - client->close(none); + client->close(std::nullopt); std::vector indices = getQLogEventIndices(QLogEventType::PacketDrop, qLogger); EXPECT_EQ(indices.size(), 1); @@ -2980,7 +2980,7 @@ TEST_F(QuicClientTransportAfterStartTest, ReadStreamCoalescedMany) { auto data = packets.move(); deliverData(data->coalesce()); eventbase_->loopOnce(); - client->close(none); + client->close(std::nullopt); } TEST_F(QuicClientTransportAfterStartTest, RecvPathChallengeNoAvailablePeerIds) { @@ -3105,7 +3105,7 @@ TEST_F(QuicClientTransportAfterStartTest, CloseConnectionWithStreamPending) { *expected, 0 /* cipherOverhead */, 0 /* largestAcked */, - none, + std::nullopt, true)); socketWrites.clear(); deliverData(packet->coalesce()); @@ -3174,12 +3174,12 @@ TEST_F(QuicClientTransportAfterStartTest, CloseConnectionWithNoStreamPending) { *expected, 0 /* cipherOverhead */, 0 /* largestAcked */, - none, + std::nullopt, true)); socketWrites.clear(); deliverData(packet->coalesce()); EXPECT_CALL(readCb, readError(streamId, _)); - client->close(none); + client->close(std::nullopt); EXPECT_TRUE(verifyFramePresent( socketWrites, *makeEncryptedCodec(), @@ -3229,7 +3229,7 @@ TEST_P( EXPECT_TRUE(event->sendCloseImmediately); } else { - client->close(none); + client->close(std::nullopt); EXPECT_TRUE(verifyFramePresent( socketWrites, *makeHandshakeCodec(), @@ -3371,7 +3371,7 @@ TEST_P(QuicClientTransportAfterStartTestClose, CloseConnectionWithError) { *expected, 0 /* cipherOverhead */, 0 /* largestAcked */, - none, + std::nullopt, true)); deliverData(packet->coalesce()); socketWrites.clear(); @@ -3384,7 +3384,7 @@ TEST_P(QuicClientTransportAfterStartTestClose, CloseConnectionWithError) { *makeHandshakeCodec(), QuicFrame::Type::ConnectionCloseFrame)); } else { - client->close(none); + client->close(std::nullopt); EXPECT_TRUE(verifyFramePresent( socketWrites, *makeHandshakeCodec(), @@ -3420,7 +3420,7 @@ TEST_P( *expected, 0 /* cipherOverhead */, 0 /* largestAcked */, - none, + std::nullopt, true)); deliverData(packet->coalesce()); EXPECT_NE(client->getConn().readCodec->getInitialCipher(), nullptr); @@ -3494,7 +3494,7 @@ TEST_F(QuicClientTransportAfterStartTest, IdleTimerNotResetOnDuplicatePacket) { ASSERT_FALSE(client->getConn().receivedNewPacketBeforeWrite); ASSERT_FALSE(client->idleTimeout().isTimerCallbackScheduled()); - client->closeNow(none); + client->closeNow(std::nullopt); } TEST_P(QuicClientTransportAfterStartTestClose, TimeoutsNotSetAfterClose) { @@ -3518,7 +3518,7 @@ TEST_P(QuicClientTransportAfterStartTestClose, TimeoutsNotSetAfterClose) { QuicErrorCode(TransportErrorCode::INTERNAL_ERROR), std::string("how about no"))); } else { - client->close(none); + client->close(std::nullopt); } client->idleTimeout().cancelTimerCallback(); ASSERT_FALSE(client->idleTimeout().isTimerCallbackScheduled()); @@ -3550,7 +3550,7 @@ TEST_F(QuicClientTransportAfterStartTest, IdleTimerNotResetOnWritingOldData) { ASSERT_FALSE(client->getConn().receivedNewPacketBeforeWrite); ASSERT_FALSE(client->idleTimeout().isTimerCallbackScheduled()); - client->closeNow(none); + client->closeNow(std::nullopt); } TEST_F(QuicClientTransportAfterStartTest, IdleTimerResetNoOutstandingPackets) { @@ -3734,7 +3734,7 @@ TEST_F( data->computeChainDataLength(), data->computeChainDataLength(), false, - none /* skipLenHint */); + std::nullopt /* skipLenHint */); writeStreamFrameData(builder2, data->clone(), data->computeChainDataLength()); auto packetObject = std::move(builder2).buildPacket(); auto packet2 = packetToBuf(std::move(packetObject)); @@ -3784,7 +3784,7 @@ TEST_F(QuicClientTransportAfterStartTest, ReceiveRstStreamAfterEom) { deliverData(packet2->coalesce()); EXPECT_TRUE(client->getReadCallbacks().empty()); - client->close(none); + client->close(std::nullopt); } TEST_F( @@ -3832,7 +3832,7 @@ TEST_F( client->getNonConstConn().streamManager->getStream(streamId); ASSERT_FALSE(streamResult.hasError()); ASSERT_EQ(streamResult.value(), nullptr); - client->close(none); + client->close(std::nullopt); } TEST_F(QuicClientTransportAfterStartTest, StreamClosedIfReadCallbackNull) { @@ -3871,7 +3871,7 @@ TEST_F(QuicClientTransportAfterStartTest, StreamClosedIfReadCallbackNull) { client->getNonConstConn().streamManager->getStream(streamId); ASSERT_FALSE(streamResult.hasError()); ASSERT_EQ(streamResult.value(), nullptr); - client->close(none); + client->close(std::nullopt); } TEST_F(QuicClientTransportAfterStartTest, ReceiveAckInvokesDeliveryCallback) { @@ -3895,7 +3895,7 @@ TEST_F(QuicClientTransportAfterStartTest, ReceiveAckInvokesDeliveryCallback) { EXPECT_CALL(deliveryCallback, onDeliveryAck(streamId, 0, _)).Times(1); deliverData(packet->coalesce()); - client->close(none); + client->close(std::nullopt); } TEST_F(QuicClientTransportAfterStartTest, InvokesDeliveryCallbackFinOnly) { @@ -3918,7 +3918,7 @@ TEST_F(QuicClientTransportAfterStartTest, InvokesDeliveryCallbackFinOnly) { EXPECT_CALL(deliveryCallback, onDeliveryAck(streamId, _, _)).Times(1); deliverData(packet->coalesce()); - client->close(none); + client->close(std::nullopt); } TEST_F(QuicClientTransportAfterStartTest, InvokesDeliveryCallbackRange) { @@ -3951,7 +3951,7 @@ TEST_F(QuicClientTransportAfterStartTest, InvokesDeliveryCallbackRange) { PacketNumberSpace::AppData)); deliverData(packet->coalesce()); - client->close(none); + client->close(std::nullopt); } TEST_F( @@ -3981,7 +3981,7 @@ TEST_F( EXPECT_CALL(deliveryCallback, onDeliveryAck(streamId, 0, _)).Times(1); client->registerDeliveryCallback(streamId, 0, &deliveryCallback); eventbase_->loopOnce(); - client->close(none); + client->close(std::nullopt); } TEST_F(QuicClientTransportAfterStartTest, DeliveryCallbackFromWriteChain) { @@ -4007,7 +4007,7 @@ TEST_F(QuicClientTransportAfterStartTest, DeliveryCallbackFromWriteChain) { // DeliveryCallback is called, and offset delivered is 10: EXPECT_CALL(deliveryCallback, onDeliveryAck(streamId, 10, _)).Times(1); deliverData(packet->coalesce()); - client->close(none); + client->close(std::nullopt); } TEST_F(QuicClientTransportAfterStartTest, NotifyPendingWrite) { @@ -4015,7 +4015,7 @@ TEST_F(QuicClientTransportAfterStartTest, NotifyPendingWrite) { EXPECT_CALL(writeCallback, onConnectionWriteReady(_)); client->notifyPendingWriteOnConnection(&writeCallback); loopForWrites(); - client->close(none); + client->close(std::nullopt); } TEST_F(QuicClientTransportAfterStartTest, SwitchEvbWhileAsyncEventPending) { @@ -4027,7 +4027,7 @@ TEST_F(QuicClientTransportAfterStartTest, SwitchEvbWhileAsyncEventPending) { client->detachEventBase(); client->attachEventBase(qEvb2); loopForWrites(); - client->close(none); + client->close(std::nullopt); } TEST_F(QuicClientTransportAfterStartTest, StatelessResetClosesTransport) { @@ -4038,7 +4038,7 @@ TEST_F(QuicClientTransportAfterStartTest, StatelessResetClosesTransport) { // Make the decrypt fail EXPECT_CALL(*aead, _tryDecrypt(_, _, _)) - .WillRepeatedly(Invoke([&](auto&, auto, auto) { return none; })); + .WillRepeatedly(Invoke([&](auto&, auto, auto) { return std::nullopt; })); auto token = *client->getConn().statelessResetToken; StatelessResetPacketBuilder builder(kDefaultUDPSendPacketLen, token); @@ -4064,9 +4064,9 @@ TEST_F(QuicClientTransportAfterStartTest, BadStatelessResetWontCloseTransport) { // Make the decrypt fail ON_CALL(*currentOneRttReadCipherRawPtr, _tryDecrypt(_, _, _)) - .WillByDefault(Invoke([&](auto&, auto, auto) { return none; })); + .WillByDefault(Invoke([&](auto&, auto, auto) { return std::nullopt; })); ON_CALL(*nextOneRttReadCipherRawPtr, _tryDecrypt(_, _, _)) - .WillByDefault(Invoke([&](auto&, auto, auto) { return none; })); + .WillByDefault(Invoke([&](auto&, auto, auto) { return std::nullopt; })); // Alter the expected token so it definitely won't match the one in conn auto token = *client->getConn().statelessResetToken; token[0] = ~token[0]; @@ -4142,7 +4142,7 @@ TEST_F(QuicClientTransportVersionAndRetryTest, RetryPacket) { EXPECT_EQ(header.getDestinationConnId(), serverCid); eventbase_->loopOnce(); - client->close(none); + client->close(std::nullopt); } TEST_F( @@ -4169,7 +4169,7 @@ TEST_F( EXPECT_EQ(client->getConn().oneRttWriteCipher.get(), nullptr); EXPECT_CALL(clientConnSetupCallback, onTransportReady()).Times(0); EXPECT_CALL(clientConnSetupCallback, onReplaySafe()).Times(0); - client->close(none); + client->close(std::nullopt); } TEST_F( @@ -4189,7 +4189,7 @@ TEST_F( {QuicVersion::MVFST}) .buildPacket(); EXPECT_THROW(deliverData(packet.second->coalesce()), std::runtime_error); - client->close(none); + client->close(std::nullopt); } TEST_F(QuicClientTransportVersionAndRetryTest, UnencryptedStreamData) { @@ -4332,7 +4332,7 @@ TEST_F(QuicClientTransportAfterStartTest, SendReset) { deliverData(packet->coalesce()); // Stream is not yet closed because ingress state machine is open EXPECT_TRUE(conn.streamManager->streamExists(streamId)); - client->close(none); + client->close(std::nullopt); EXPECT_TRUE(client->isClosed()); } @@ -4362,7 +4362,7 @@ TEST_F(QuicClientTransportAfterStartTest, ResetClearsPendingLoss) { StreamId streamId = client->createBidirectionalStream().value(); client->setReadCallback(streamId, &readCb); SCOPE_EXIT { - client->close(none); + client->close(std::nullopt); }; client->writeChain(streamId, IOBuf::copyBuffer("hello"), true); loopForWrites(); @@ -4383,7 +4383,7 @@ TEST_F(QuicClientTransportAfterStartTest, LossAfterResetStream) { StreamId streamId = client->createBidirectionalStream().value(); client->setReadCallback(streamId, &readCb); SCOPE_EXIT { - client->close(none); + client->close(std::nullopt); }; client->writeChain(streamId, IOBuf::copyBuffer("hello"), true); loopForWrites(); @@ -4430,7 +4430,7 @@ TEST_F(QuicClientTransportAfterStartTest, SendResetAfterEom) { deliverData(packet->coalesce()); // Stream still exists since ingress state machine is still open EXPECT_TRUE(conn.streamManager->streamExists(streamId)); - client->close(none); + client->close(std::nullopt); EXPECT_TRUE(client->isClosed()); } @@ -4481,7 +4481,7 @@ TEST_F(QuicClientTransportAfterStartTest, HalfClosedLocalToClosed) { EXPECT_EQ(1, readCbs.count(streamId)); EXPECT_EQ(0, conn.streamManager->readableStreams().count(streamId)); EXPECT_TRUE(conn.streamManager->streamExists(streamId)); - client->close(none); + client->close(std::nullopt); EXPECT_EQ(0, readCbs.count(streamId)); EXPECT_FALSE(conn.streamManager->streamExists(streamId)); EXPECT_TRUE(client->isClosed()); @@ -4536,7 +4536,7 @@ TEST_F(QuicClientTransportAfterStartTest, SendResetSyncOnAck) { deliverData(packet->coalesce()); // Stream should be closed after it received the ack for rst EXPECT_FALSE(conn.streamManager->streamExists(streamId)); - client->close(none); + client->close(std::nullopt); EXPECT_TRUE(client->isClosed()); } @@ -4589,7 +4589,7 @@ TEST_F(QuicClientTransportAfterStartTest, HalfClosedRemoteToClosed) { EXPECT_FALSE(conn.streamManager->hasDeliverable()); EXPECT_TRUE(conn.streamManager->streamExists(streamId)); EXPECT_EQ(readCbs.count(streamId), 1); - client->close(none); + client->close(std::nullopt); EXPECT_FALSE(conn.streamManager->streamExists(streamId)); EXPECT_EQ(readCbs.count(streamId), 0); EXPECT_TRUE(client->isClosed()); @@ -4719,7 +4719,7 @@ TEST_F(QuicClientTransportAfterStartTest, DestroyWhileDraining) { EXPECT_CALL(deliveryCallback, onCanceled(_, _)); EXPECT_CALL(readCb, readError(_, _)); - client->close(none); + client->close(std::nullopt); } TEST_F(QuicClientTransportAfterStartTest, CloseNowWhileDraining) { @@ -4989,7 +4989,7 @@ TEST_F(QuicClientTransportAfterStartTest, OneCloseFramePerRtt) { client->close(QuicError( QuicErrorCode(LocalErrorCode::INTERNAL_ERROR), toString(LocalErrorCode::INTERNAL_ERROR).str())); - EXPECT_TRUE(conn.lastCloseSentTime.hasValue()); + EXPECT_TRUE(conn.lastCloseSentTime.has_value()); Mock::VerifyAndClearExpectations(sock); // Then received some server packet, which won't trigger another close @@ -5034,7 +5034,7 @@ TEST_F(QuicClientTransportAfterStartTest, RetryPacketAfterRxInitial) { loopForWrites(); // validate we dropped the retry packet via retryToken str EXPECT_TRUE(client->getConn().retryToken.empty()); - client->close(none); + client->close(std::nullopt); } class QuicClientTransportPskCacheTest @@ -6074,7 +6074,7 @@ TEST(AsyncUDPSocketTest, CloseMultipleTimes) { EmptyReadCallback readCallback; ASSERT_FALSE(happyEyeballsSetUpSocket( socket, - none, + std::nullopt, folly::SocketAddress("127.0.0.1", 12345), transportSettings, 0, // tosValue diff --git a/quic/fizz/client/test/QuicClientTransportTestUtil.h b/quic/fizz/client/test/QuicClientTransportTestUtil.h index 411a4fa91..b2352966d 100644 --- a/quic/fizz/client/test/QuicClientTransportTestUtil.h +++ b/quic/fizz/client/test/QuicClientTransportTestUtil.h @@ -172,14 +172,18 @@ class FakeOneRttHandshakeLayer : public FizzClientHandshake { Optional connectImpl( Optional hostname) override { // Look up psk - Optional quicCachedPsk = getPsk(hostname); + auto quicCachedPsk = getPsk(hostname); Optional transportParams; if (quicCachedPsk) { transportParams = quicCachedPsk->transportParams; } - const_cast(getState()).sni() = hostname; + if (hostname.has_value()) { + const_cast(getState()).sni() = hostname.value(); + } else { + const_cast(getState()).sni() = folly::none; + } connected_ = true; writeDataToQuicStream( @@ -352,7 +356,7 @@ class FakeOneRttHandshakeLayer : public FizzClientHandshake { std::unique_ptr oneRttWriteCipher_; std::unique_ptr oneRttWriteHeaderCipher_; - Optional alpn_{folly::none}; + Optional alpn_{std::nullopt}; FizzCryptoFactory cryptoFactory_; @@ -715,7 +719,7 @@ class QuicClientTransportTestBase : public virtual testing::Test { recvServerHello(serverAddr); } - void recvTicket(Optional offsetOverride = none) { + void recvTicket(Optional offsetOverride = std::nullopt) { auto negotiatedVersion = *client->getConn().version; auto ticket = folly::IOBuf::copyBuffer("NST"); ChainedByteRangeHead ticketRch(ticket); diff --git a/quic/fizz/handshake/FizzBridge.cpp b/quic/fizz/handshake/FizzBridge.cpp index 6363144be..d048c7bef 100644 --- a/quic/fizz/handshake/FizzBridge.cpp +++ b/quic/fizz/handshake/FizzBridge.cpp @@ -27,11 +27,11 @@ EncryptionLevel getEncryptionLevelFromFizz( Optional FizzAead::getKey() const { if (!fizzAead) { - return none; + return std::nullopt; } auto fizzKey = fizzAead->getKey(); if (!fizzKey) { - return none; + return std::nullopt; } TrafficKey quicKey; quicKey.key = std::move(fizzKey->key); diff --git a/quic/fizz/handshake/FizzBridge.h b/quic/fizz/handshake/FizzBridge.h index 6939c22ea..aba6ffea1 100644 --- a/quic/fizz/handshake/FizzBridge.h +++ b/quic/fizz/handshake/FizzBridge.h @@ -57,8 +57,13 @@ class FizzAead final : public Aead { uint64_t seqNum) const override { fizz::Aead::AeadOptions options; options.bufferOpt = fizz::Aead::BufferOption::AllowInPlace; - return fizzAead->tryDecrypt( + auto result = fizzAead->tryDecrypt( std::move(ciphertext), associatedData, seqNum, options); + if (result.has_value()) { + return Optional>(std::move(result.value())); + } else { + return Optional>(); + } } size_t getCipherOverhead() const override { diff --git a/quic/fizz/handshake/FizzTransportParameters.h b/quic/fizz/handshake/FizzTransportParameters.h index 860a1dad5..20ce3e147 100644 --- a/quic/fizz/handshake/FizzTransportParameters.h +++ b/quic/fizz/handshake/FizzTransportParameters.h @@ -123,7 +123,7 @@ inline quic::Optional getClientExtension( auto extensionType = getQuicTransportParametersExtention(encodingVersion); auto it = findExtension(extensions, extensionType); if (it == extensions.end()) { - return quic::none; + return std::nullopt; } quic::ClientTransportParameters parameters; quic::Cursor cursor(it->extension_data.get()); @@ -137,7 +137,7 @@ inline quic::Optional getServerExtension( auto extensionType = getQuicTransportParametersExtention(encodingVersion); auto it = findExtension(extensions, extensionType); if (it == extensions.end()) { - return quic::none; + return std::nullopt; } quic::ServerTransportParameters parameters; quic::Cursor cursor(it->extension_data.get()); @@ -151,7 +151,7 @@ inline quic::Optional getTicketExtension( auto extensionType = getQuicTransportParametersExtention(encodingVersion); auto it = findExtension(extensions, extensionType); if (it == extensions.end()) { - return quic::none; + return std::nullopt; } quic::TicketTransportParameters parameters; quic::Cursor cursor(it->extension_data.get()); diff --git a/quic/fizz/handshake/QuicFizzFactory.cpp b/quic/fizz/handshake/QuicFizzFactory.cpp index 1f805f475..20dc2418e 100644 --- a/quic/fizz/handshake/QuicFizzFactory.cpp +++ b/quic/fizz/handshake/QuicFizzFactory.cpp @@ -18,7 +18,7 @@ class QuicPlaintextReadRecordLayer : public fizz::PlaintextReadRecordLayer { folly::IOBufQueue& buf, fizz::Aead::AeadOptions) override { if (buf.empty()) { - return quic::none; + return folly::none; } fizz::TLSMessage msg; msg.type = fizz::ContentType::handshake; @@ -38,7 +38,7 @@ class QuicEncryptedReadRecordLayer : public fizz::EncryptedReadRecordLayer { folly::IOBufQueue& buf, fizz::Aead::AeadOptions) override { if (buf.empty()) { - return quic::none; + return folly::none; } fizz::TLSMessage msg; msg.type = fizz::ContentType::handshake; diff --git a/quic/fizz/handshake/test/FizzTransportParametersTest.cpp b/quic/fizz/handshake/test/FizzTransportParametersTest.cpp index 458ff3803..2bcd9d1c4 100644 --- a/quic/fizz/handshake/test/FizzTransportParametersTest.cpp +++ b/quic/fizz/handshake/test/FizzTransportParametersTest.cpp @@ -72,7 +72,7 @@ TEST_F(QuicExtensionsTest, TestClientParamsV1) { // Confirm D29 parameters are not parsed for V1. auto d29Exts = getExtensions(clientParamsD29); auto d2Ext = getClientExtension(exts, kQuicDraft); - EXPECT_EQ(d2Ext, none); + EXPECT_EQ(d2Ext, std::nullopt); } TEST_F(QuicExtensionsTest, TestClientParamsD29) { @@ -113,7 +113,7 @@ TEST_F(QuicExtensionsTest, TestServerParamsV1) { // Confirm D29 parameters are not parsed for V1. auto d29Exts = getExtensions(serverParamsD29); auto d2Ext = getServerExtension(exts, kQuicDraft); - EXPECT_EQ(d2Ext, none); + EXPECT_EQ(d2Ext, std::nullopt); } TEST_F(QuicExtensionsTest, TestServerParamsD29) { @@ -155,7 +155,7 @@ TEST_F(QuicExtensionsTest, TestTicketParamsV1) { // Confirm D29 parameters are not parsed for V1. auto d29Exts = getExtensions(ticketParamsD29); auto d2Ext = getTicketExtension(exts, kQuicDraft); - EXPECT_EQ(d2Ext, none); + EXPECT_EQ(d2Ext, std::nullopt); } TEST_F(QuicExtensionsTest, TestTicketParamsD29) { diff --git a/quic/fizz/server/handshake/AppToken.cpp b/quic/fizz/server/handshake/AppToken.cpp index e61272d83..7604a0d22 100644 --- a/quic/fizz/server/handshake/AppToken.cpp +++ b/quic/fizz/server/handshake/AppToken.cpp @@ -44,7 +44,7 @@ Optional decodeAppToken(const folly::IOBuf& buf) { fizz::detail::read(appToken.version, cursor); fizz::detail::readBuf(appToken.appParams, cursor); } catch (const std::exception&) { - return none; + return std::nullopt; } return appToken; } diff --git a/quic/flowcontrol/QuicFlowController.cpp b/quic/flowcontrol/QuicFlowController.cpp index 0ec7a7d59..fedfa1062 100644 --- a/quic/flowcontrol/QuicFlowController.cpp +++ b/quic/flowcontrol/QuicFlowController.cpp @@ -29,7 +29,7 @@ Optional calculateNewWindowUpdate( auto nextAdvertisedOffset = curReadOffset + windowSize; if (nextAdvertisedOffset == curAdvertisedOffset) { // No change in flow control - return none; + return std::nullopt; } bool enoughTimeElapsed = lastSendTime && updateTime > *lastSendTime && (updateTime - *lastSendTime) > @@ -53,7 +53,7 @@ Optional calculateNewWindowUpdate( if (enoughWindowElapsed) { return nextAdvertisedOffset; } - return none; + return std::nullopt; } template @@ -223,7 +223,7 @@ folly::Expected updateFlowControlOnRead( uint64_t diff = 0; if (stream.reliableSizeFromPeer && stream.currentReadOffset >= *stream.reliableSizeFromPeer) { - CHECK(stream.finalReadOffset.hasValue()) + CHECK(stream.finalReadOffset.has_value()) << "We got a reset from the peer, but the finalReadOffset is not set."; // We've read all reliable bytes, so we can advance the currentReadOffset // to the final size. @@ -255,10 +255,10 @@ folly::Expected updateFlowControlOnRead( folly::Expected updateFlowControlOnReceiveReset( QuicStreamState& stream, TimePoint resetTime) { - CHECK(stream.reliableSizeFromPeer.hasValue()) + CHECK(stream.reliableSizeFromPeer.has_value()) << "updateFlowControlOnReceiveReset has been called, " << "but reliableSizeFromPeer has not been set"; - CHECK(stream.finalReadOffset.hasValue()) + CHECK(stream.finalReadOffset.has_value()) << "updateFlowControlOnReceiveReset has been called, " << "but finalReadOffset has not been set"; if (stream.currentReadOffset >= *stream.reliableSizeFromPeer) { @@ -313,7 +313,7 @@ folly::Expected updateFlowControlOnWriteToStream( folly::Expected updateFlowControlOnResetStream( QuicStreamState& stream, - folly::Optional reliableSize) { + Optional reliableSize) { uint64_t decrementAmount = 0; if (reliableSize && *reliableSize > 0) { // This is the amount of pending data that we are "throwing away" diff --git a/quic/flowcontrol/QuicFlowController.h b/quic/flowcontrol/QuicFlowController.h index c8a108846..91eab7269 100644 --- a/quic/flowcontrol/QuicFlowController.h +++ b/quic/flowcontrol/QuicFlowController.h @@ -61,7 +61,7 @@ updateFlowControlOnWriteToStream(QuicStreamState& stream, uint64_t length); [[nodiscard]] folly::Expected updateFlowControlOnResetStream( QuicStreamState& stream, - folly::Optional reliableSize = folly::none); + Optional reliableSize = std::nullopt); void maybeWriteBlockAfterAPIWrite(QuicStreamState& stream); diff --git a/quic/handshake/Aead.h b/quic/handshake/Aead.h index 82a48f3ef..ebf056b3d 100644 --- a/quic/handshake/Aead.h +++ b/quic/handshake/Aead.h @@ -50,8 +50,8 @@ class Aead { } /** - * Decrypt ciphertext. Will return none if the ciphertext does not decrypt - * successfully. May still throw from errors unrelated to ciphertext. + * Decrypt ciphertext. Will return std::nullopt if the ciphertext does not + * decrypt successfully. May still throw from errors unrelated to ciphertext. */ virtual Optional> tryDecrypt( std::unique_ptr&& ciphertext, diff --git a/quic/handshake/TransportParameters.cpp b/quic/handshake/TransportParameters.cpp index e0886e254..7d0714043 100644 --- a/quic/handshake/TransportParameters.cpp +++ b/quic/handshake/TransportParameters.cpp @@ -17,7 +17,7 @@ Optional getIntegerParameter( const std::vector& parameters) { auto it = findParameter(parameters, id); if (it == parameters.end()) { - return none; + return std::nullopt; } auto parameterCursor = Cursor(it->value.get()); auto parameter = decodeQuicInteger(parameterCursor); @@ -35,7 +35,7 @@ Optional getConnIdParameter( const std::vector& parameters) { auto it = findParameter(parameters, id); if (it == parameters.end()) { - return none; + return std::nullopt; } auto value = it->value->clone(); @@ -50,7 +50,7 @@ Optional getStatelessResetTokenParameter( auto it = findParameter(parameters, TransportParameterId::stateless_reset_token); if (it == parameters.end()) { - return none; + return std::nullopt; } auto value = it->value->clone(); diff --git a/quic/logging/FileQLogger.cpp b/quic/logging/FileQLogger.cpp index ddb6c657f..daf748124 100644 --- a/quic/logging/FileQLogger.cpp +++ b/quic/logging/FileQLogger.cpp @@ -14,7 +14,7 @@ namespace quic { void FileQLogger::setDcid(Optional connID) { - if (connID.hasValue()) { + if (connID.has_value()) { dcid = connID.value(); if (streaming_) { setupStream(); @@ -23,14 +23,14 @@ void FileQLogger::setDcid(Optional connID) { } void FileQLogger::setScid(Optional connID) { - if (connID.hasValue()) { + if (connID.has_value()) { scid = connID.value(); } } void FileQLogger::setupStream() { // create the output file - if (!dcid.hasValue()) { + if (!dcid.has_value()) { LOG(ERROR) << "Error: No dcid found"; return; } @@ -543,7 +543,7 @@ void FileQLogger::outputLogsToFile(const std::string& path, bool prettyJson) { if (streaming_) { return; } - if (!dcid.hasValue()) { + if (!dcid.has_value()) { LOG(ERROR) << "Error: No dcid found"; return; } diff --git a/quic/logging/FileQLogger.h b/quic/logging/FileQLogger.h index d6ff427e9..bb5a1e770 100644 --- a/quic/logging/FileQLogger.h +++ b/quic/logging/FileQLogger.h @@ -43,7 +43,7 @@ class FileQLogger : public BaseQLogger { compress_{compress} {} ~FileQLogger() override { - if (streaming_ && dcid.hasValue()) { + if (streaming_ && dcid.has_value()) { finishStream(); } } diff --git a/quic/logging/QLoggerCommon.cpp b/quic/logging/QLoggerCommon.cpp index d7f24d45a..6adf4fc69 100644 --- a/quic/logging/QLoggerCommon.cpp +++ b/quic/logging/QLoggerCommon.cpp @@ -233,7 +233,7 @@ void QLoggerCommon::addMetricUpdate( void QLoggerCommon::addStreamStateUpdate( quic::StreamId id, std::string update, - folly::Optional timeSinceStreamCreation) { + Optional timeSinceStreamCreation) { auto refTime = std::chrono::duration_cast( std::chrono::steady_clock::now().time_since_epoch()); @@ -297,14 +297,14 @@ void QLoggerCommon::addNetworkPathModelUpdate( refTime)); } -void QLoggerCommon::setDcid(folly::Optional connID) { - if (connID.hasValue()) { +void QLoggerCommon::setDcid(Optional connID) { + if (connID.has_value()) { dcid = connID; } } -void QLoggerCommon::setScid(folly::Optional connID) { - if (connID.hasValue()) { +void QLoggerCommon::setScid(Optional connID) { + if (connID.has_value()) { scid = connID; } } diff --git a/quic/logging/QLoggerCommon.h b/quic/logging/QLoggerCommon.h index 89c9b316a..cbc160ff6 100644 --- a/quic/logging/QLoggerCommon.h +++ b/quic/logging/QLoggerCommon.h @@ -79,8 +79,7 @@ class QLoggerCommon : public quic::BaseQLogger { void addStreamStateUpdate( quic::StreamId id, std::string update, - folly::Optional timeSinceStreamCreation) - override; + Optional timeSinceStreamCreation) override; void addConnectionMigrationUpdate(bool intentionalMigration) override; void addPathValidationEvent(bool success) override; void addPriorityUpdate( @@ -95,8 +94,8 @@ class QLoggerCommon : public quic::BaseQLogger { std::chrono::microseconds bandwidthHiInterval, uint64_t bandwidthLoBytes, std::chrono::microseconds bandwidthLoInterval) override; - void setDcid(folly::Optional connID) override; - void setScid(folly::Optional connID) override; + void setDcid(Optional connID) override; + void setScid(Optional connID) override; virtual void logTrace(std::unique_ptr event) = 0; }; diff --git a/quic/logging/QLoggerTypes.h b/quic/logging/QLoggerTypes.h index 2fc9bd8c5..911d5b536 100644 --- a/quic/logging/QLoggerTypes.h +++ b/quic/logging/QLoggerTypes.h @@ -39,13 +39,13 @@ class RstStreamFrameLog : public QLogFrame { StreamId streamId; ApplicationErrorCode errorCode; uint64_t offset; - folly::Optional reliableOffset; + Optional reliableOffset; RstStreamFrameLog( StreamId streamIdIn, ApplicationErrorCode errorCodeIn, uint64_t offsetIn, - folly::Optional reliableOffsetIn = folly::none) + Optional reliableOffsetIn = std::nullopt) : streamId{streamIdIn}, errorCode{errorCodeIn}, offset{offsetIn}, diff --git a/quic/logging/test/QLoggerTest.cpp b/quic/logging/test/QLoggerTest.cpp index b177bb1ae..1292b63d9 100644 --- a/quic/logging/test/QLoggerTest.cpp +++ b/quic/logging/test/QLoggerTest.cpp @@ -655,9 +655,9 @@ TEST_F(QLoggerTest, AddingMultiplePacketEvents) { *buf, 0 /* cipherOverhead */, 0 /* largestAcked */, - none /* longHeaderOverride */, + std::nullopt /* longHeaderOverride */, fin, - none /* shortHeaderOverride */, + std::nullopt /* shortHeaderOverride */, offset); auto regularQuicPacket = packet.packet; @@ -1210,7 +1210,7 @@ TEST_F( ])"); FileQLogger q(VantagePoint::Client); - q.addStreamStateUpdate(streamId, kOnEOM, none); + q.addStreamStateUpdate(streamId, kOnEOM, std::nullopt); folly::dynamic gotDynamic = q.toDynamic(); gotDynamic["traces"][0]["events"][0][0] = "0"; // hardcode reference time folly::dynamic gotEvents = gotDynamic["traces"][0]["events"]; diff --git a/quic/loss/QuicLossFunctions.cpp b/quic/loss/QuicLossFunctions.cpp index 95a3e8aa3..c4586c676 100644 --- a/quic/loss/QuicLossFunctions.cpp +++ b/quic/loss/QuicLossFunctions.cpp @@ -586,7 +586,7 @@ detectLossPackets( getLossTime(conn, pnSpace) = delayUntilLost + earliest->metadata.time; } - if (lossEvent.largestLostPacketNum.hasValue()) { + if (lossEvent.largestLostPacketNum.has_value()) { DCHECK(lossEvent.largestLostSentTime && lossEvent.smallestLostSentTime); if (conn.qLogger) { conn.qLogger->addPacketsLost( @@ -600,7 +600,7 @@ detectLossPackets( return lossEvent; } } - return none; + return std::nullopt; } folly::Expected, QuicError> diff --git a/quic/loss/QuicLossFunctions.h b/quic/loss/QuicLossFunctions.h index 6a48d10d5..b883480a6 100644 --- a/quic/loss/QuicLossFunctions.h +++ b/quic/loss/QuicLossFunctions.h @@ -97,7 +97,7 @@ calculateAlarmDuration(const QuicConnectionStateBase& conn) { << (lastSentPacketTime + alarmDuration).time_since_epoch().count() << " " << conn; } - DCHECK(alarmMethod.hasValue()) << "Alarm method must have a value"; + DCHECK(alarmMethod.has_value()) << "Alarm method must have a value"; return std::make_pair(adjustedAlarmDuration, *alarmMethod); } @@ -252,7 +252,7 @@ template if (conn.congestionController && lossEvent) { DCHECK(lossEvent->largestLostSentTime && lossEvent->smallestLostSentTime); conn.congestionController->onPacketAckOrLoss( - nullptr, lossEvent.get_pointer()); + nullptr, lossEvent.has_value() ? &lossEvent.value() : nullptr); } } else { auto result = onPTOAlarm(conn); @@ -343,7 +343,7 @@ template } conn.lossState.rtxCount += lossEvent.lostPackets; - if (conn.congestionController && lossEvent.largestLostPacketNum.hasValue()) { + if (conn.congestionController && lossEvent.largestLostPacketNum.has_value()) { conn.congestionController->onRemoveBytesFromInflight(lossEvent.lostBytes); } VLOG(10) << __func__ << " marked=" << lossEvent.lostPackets; diff --git a/quic/loss/test/QuicLossFunctionsTest.cpp b/quic/loss/test/QuicLossFunctionsTest.cpp index 73530f5e3..89b5e479a 100644 --- a/quic/loss/test/QuicLossFunctionsTest.cpp +++ b/quic/loss/test/QuicLossFunctionsTest.cpp @@ -95,7 +95,7 @@ class QuicLossFunctionsTest : public TestWithParam { TimePoint time, Optional maybeClonedPacketIdentifier, PacketType packetType, - Optional forcedSize = none, + Optional forcedSize = std::nullopt, bool isDsr = false); std::unique_ptr createConn() { @@ -352,7 +352,7 @@ TEST_F(QuicLossFunctionsTest, AllPacketsProcessed) { TEST_F(QuicLossFunctionsTest, HasDataToWrite) { auto conn = createConn(); // There needs to be at least one outstanding packet. - sendPacket(*conn, Clock::now(), none, PacketType::OneRtt); + sendPacket(*conn, Clock::now(), std::nullopt, PacketType::OneRtt); conn->streamManager->addLoss(1); conn->pendingEvents.setLossDetectionAlarm = true; EXPECT_CALL(timeout, cancelLossTimeout()).Times(2); @@ -368,9 +368,9 @@ TEST_F(QuicLossFunctionsTest, ClearEarlyRetranTimer) { conn->lossState.lrtt = 1s; auto currentTime = Clock::now(); auto firstPacketNum = - sendPacket(*conn, currentTime, none, PacketType::Initial); + sendPacket(*conn, currentTime, std::nullopt, PacketType::Initial); auto secondPacketNum = - sendPacket(*conn, currentTime, none, PacketType::Initial); + sendPacket(*conn, currentTime, std::nullopt, PacketType::Initial); ASSERT_GT(secondPacketNum, firstPacketNum); ASSERT_EQ(2, conn->outstandings.packets.size()); // detectLossPackets will set lossTime on Initial space. @@ -419,7 +419,7 @@ TEST_F(QuicLossFunctionsTest, ClearEarlyRetranTimer) { .hasError()); // Send out a AppData packet that isn't retransmittable - sendPacket(*conn, Clock::now(), none, PacketType::OneRtt); + sendPacket(*conn, Clock::now(), std::nullopt, PacketType::OneRtt); conn->pendingEvents.setLossDetectionAlarm = false; // setLossDetectionAlarm will cancel loss timer, and not schedule another one. @@ -439,7 +439,7 @@ TEST_F(QuicLossFunctionsTest, TestOnLossDetectionAlarm) { EXPECT_CALL(*rawCongestionController, onPacketSent(_)) .WillRepeatedly(Return()); - sendPacket(*conn, Clock::now(), none, PacketType::OneRtt); + sendPacket(*conn, Clock::now(), std::nullopt, PacketType::OneRtt); MockClock::mockNow = []() { return TimePoint(123ms); }; std::vector lostPacket; MockClock::mockNow = []() { return TimePoint(23ms); }; @@ -456,7 +456,7 @@ TEST_F(QuicLossFunctionsTest, TestOnLossDetectionAlarm) { MockClock::mockNow = []() { return TimePoint(3ms); }; EXPECT_CALL(*quicStats_, onPTO()); - sendPacket(*conn, TimePoint(), none, PacketType::OneRtt); + sendPacket(*conn, TimePoint(), std::nullopt, PacketType::OneRtt); setLossDetectionAlarm(*conn, timeout); EXPECT_CALL(*rawCongestionController, onPacketAckOrLoss(_, _)).Times(0); ASSERT_FALSE( @@ -812,7 +812,7 @@ TEST_F(QuicLossFunctionsTest, TestReorderingThreshold) { return folly::unit; }; for (int i = 0; i < 6; ++i) { - sendPacket(*conn, Clock::now(), none, PacketType::Handshake); + sendPacket(*conn, Clock::now(), std::nullopt, PacketType::Handshake); } EXPECT_EQ(6, conn->outstandings.packetCount[PacketNumberSpace::Handshake]); // Assume some packets are already acked @@ -884,7 +884,7 @@ TEST_F(QuicLossFunctionsTest, TestReorderingThresholdWithSkippedPacket) { conn->ackStates.handshakeAckState->nextPacketNum; increaseNextPacketNum(*conn, PacketNumberSpace::Handshake); } - sendPacket(*conn, Clock::now(), none, PacketType::Handshake); + sendPacket(*conn, Clock::now(), std::nullopt, PacketType::Handshake); } EXPECT_EQ(7, conn->outstandings.packetCount[PacketNumberSpace::Handshake]); @@ -978,7 +978,7 @@ TEST_F(QuicLossFunctionsTest, TestHandleAckedPacket) { conn->lossState.ptoCount = 10; conn->lossState.reorderingThreshold = 10; - sendPacket(*conn, TimePoint(), none, PacketType::OneRtt); + sendPacket(*conn, TimePoint(), std::nullopt, PacketType::OneRtt); ReadAckFrame ackFrame; ackFrame.largestAcked = conn->lossState.largestSent.value_or(0); @@ -1092,7 +1092,8 @@ TEST_F(QuicLossFunctionsTest, ReorderingThresholdChecksSamePacketNumberSpace) { }; PacketNum latestSent = 0; for (size_t i = 0; i < conn->lossState.reorderingThreshold + 1; i++) { - latestSent = sendPacket(*conn, Clock::now(), none, PacketType::Handshake); + latestSent = + sendPacket(*conn, Clock::now(), std::nullopt, PacketType::Handshake); } auto& ackState = getAckState(*conn, PacketNumberSpace::AppData); @@ -1158,8 +1159,8 @@ TEST_F(QuicLossFunctionsTest, TestTimeReordering) { PacketNum largestSent = 0; for (int i = 0; i < 7; ++i) { - largestSent = - sendPacket(*conn, TimePoint(i * 100ms), none, PacketType::OneRtt); + largestSent = sendPacket( + *conn, TimePoint(i * 100ms), std::nullopt, PacketType::OneRtt); } // Some packets are already acked conn->lossState.srtt = 400ms; @@ -1208,9 +1209,9 @@ TEST_F(QuicLossFunctionsTest, LossTimePreemptsCryptoTimer) { 500ms / conn->transportSettings.timeReorderingThreshDivisor; auto sendTime = Clock::now(); // Send two: - sendPacket(*conn, sendTime, none, PacketType::Handshake); + sendPacket(*conn, sendTime, std::nullopt, PacketType::Handshake); PacketNum second = - sendPacket(*conn, sendTime + 1ms, none, PacketType::Handshake); + sendPacket(*conn, sendTime + 1ms, std::nullopt, PacketType::Handshake); auto lossTime = sendTime + 50ms; auto& ackState = getAckState(*conn, PacketNumberSpace::Handshake); @@ -1269,7 +1270,7 @@ TEST_F(QuicLossFunctionsTest, PTONoLongerMarksPacketsToBeRetransmitted) { MockClock::mockNow = [&]() { return startTime; }; std::vector lostPackets; for (auto i = 0; i < kPacketToSendForPTO + 10; i++) { - sendPacket(*conn, startTime, none, PacketType::OneRtt); + sendPacket(*conn, startTime, std::nullopt, PacketType::OneRtt); setLossDetectionAlarm(*conn, timeout); startTime += 1ms; } @@ -1303,7 +1304,7 @@ TEST_F(QuicLossFunctionsTest, PTOWithHandshakePackets) { auto sentPacketNum = sendPacket( *conn, TimePoint(100ms), - none, + std::nullopt, (i % 2 ? PacketType::OneRtt : PacketType::Handshake)); expectedLargestLostNum = std::max( expectedLargestLostNum, i % 2 ? sentPacketNum : expectedLargestLostNum); @@ -1463,7 +1464,7 @@ TEST_F(QuicLossFunctionsTest, AlarmDurationHasLossTime) { conn->lossState.srtt = 200ms; conn->lossState.lrtt = 150ms; - sendPacket(*conn, lastPacketSentTime, none, PacketType::OneRtt); + sendPacket(*conn, lastPacketSentTime, std::nullopt, PacketType::OneRtt); auto duration = calculateAlarmDuration(*conn); EXPECT_EQ(100ms, duration.first); EXPECT_EQ( @@ -1482,7 +1483,7 @@ TEST_F(QuicLossFunctionsTest, AlarmDurationLossTimeIsZero) { conn->lossState.srtt = 200ms; conn->lossState.lrtt = 150ms; - sendPacket(*conn, lastPacketSentTime, none, PacketType::OneRtt); + sendPacket(*conn, lastPacketSentTime, std::nullopt, PacketType::OneRtt); auto duration = calculateAlarmDuration(*conn); EXPECT_EQ(0ms, duration.first); EXPECT_EQ( @@ -1496,7 +1497,7 @@ TEST_F(QuicLossFunctionsTest, AlarmDurationNonHandshakeOutstanding) { conn->lossState.maxAckDelay = 25ms; TimePoint lastPacketSentTime = Clock::now(); MockClock::mockNow = [=]() { return lastPacketSentTime; }; - sendPacket(*conn, lastPacketSentTime, none, PacketType::OneRtt); + sendPacket(*conn, lastPacketSentTime, std::nullopt, PacketType::OneRtt); auto duration = calculateAlarmDuration(*conn); EXPECT_EQ(duration.second, LossState::AlarmMethod::PTO); setLossDetectionAlarm(*conn, timeout); @@ -1524,7 +1525,8 @@ TEST_F(QuicLossFunctionsTest, NoSkipLossVisitor) { // Send 5 packets, so when we ack the last one, we mark the first one loss PacketNum lastSent; for (size_t i = 0; i < 5; i++) { - lastSent = sendPacket(*conn, Clock::now(), none, PacketType::OneRtt); + lastSent = + sendPacket(*conn, Clock::now(), std::nullopt, PacketType::OneRtt); } auto& ackState = getAckState(*conn, PacketNumberSpace::AppData); @@ -1592,7 +1594,7 @@ TEST_F(QuicLossFunctionsTest, NoDoubleProcess) { // Send 6 packets, so when we ack the last one, we mark the first two loss EXPECT_EQ(1, conn->ackStates.appDataAckState.nextPacketNum); PacketNum lastSent; - lastSent = sendPacket(*conn, Clock::now(), none, PacketType::OneRtt); + lastSent = sendPacket(*conn, Clock::now(), std::nullopt, PacketType::OneRtt); EXPECT_EQ(1, conn->outstandings.packetCount[PacketNumberSpace::AppData]); ClonedPacketIdentifier clonedPacketIdentifier( PacketNumberSpace::AppData, lastSent); @@ -1633,10 +1635,11 @@ TEST_F(QuicLossFunctionsTest, DetectPacketLossClonedPacketsCounter) { PacketNumberSpace::AppData, conn->ackStates.appDataAckState.nextPacketNum); sendPacket(*conn, Clock::now(), clonedPacketIdentifier1, PacketType::OneRtt); - sendPacket(*conn, Clock::now(), none, PacketType::OneRtt); - sendPacket(*conn, Clock::now(), none, PacketType::OneRtt); - sendPacket(*conn, Clock::now(), none, PacketType::OneRtt); - auto ackedPacket = sendPacket(*conn, Clock::now(), none, PacketType::OneRtt); + sendPacket(*conn, Clock::now(), std::nullopt, PacketType::OneRtt); + sendPacket(*conn, Clock::now(), std::nullopt, PacketType::OneRtt); + sendPacket(*conn, Clock::now(), std::nullopt, PacketType::OneRtt); + auto ackedPacket = + sendPacket(*conn, Clock::now(), std::nullopt, PacketType::OneRtt); auto noopLossMarker = [](auto&, auto&, bool) { return folly::unit; }; auto& ackState = getAckState(*conn, PacketNumberSpace::AppData); @@ -1748,7 +1751,8 @@ TEST_F(QuicLossFunctionsTest, TotalLossCount) { conn->congestionController = nullptr; PacketNum largestSent = 0; for (int i = 0; i < 10; i++) { - largestSent = sendPacket(*conn, Clock::now(), none, PacketType::OneRtt); + largestSent = + sendPacket(*conn, Clock::now(), std::nullopt, PacketType::OneRtt); } EXPECT_EQ(10, conn->outstandings.packets.size()); uint32_t lostPackets = 0; @@ -1786,8 +1790,8 @@ TEST_F(QuicLossFunctionsTest, TestZeroRttRejected) { // outstandings.clonedPacketIdentifiers, they are all processed and will skip // lossVisitor for (auto i = 0; i < 2; i++) { - sendPacket(*conn, TimePoint(), none, PacketType::OneRtt); - sendPacket(*conn, TimePoint(), none, PacketType::ZeroRtt); + sendPacket(*conn, TimePoint(), std::nullopt, PacketType::OneRtt); + sendPacket(*conn, TimePoint(), std::nullopt, PacketType::ZeroRtt); } EXPECT_FALSE(conn->outstandings.packets.empty()); EXPECT_EQ(4, conn->outstandings.packets.size()); @@ -1834,7 +1838,7 @@ TEST_F(QuicLossFunctionsTest, TestZeroRttRejectedWithClones) { zeroRttPackets.emplace(packetNum); } zeroRttPackets.emplace( - sendPacket(*conn, TimePoint(), none, PacketType::ZeroRtt)); + sendPacket(*conn, TimePoint(), std::nullopt, PacketType::ZeroRtt)); for (auto zeroRttPacketNum : zeroRttPackets) { ClonedPacketIdentifier zeroRttPacketEvent( PacketNumberSpace::AppData, zeroRttPacketNum); @@ -1890,11 +1894,11 @@ TEST_F(QuicLossFunctionsTest, TimeThreshold) { conn->lossState.srtt = 10ms; auto referenceTime = Clock::now(); auto packet1 = - sendPacket(*conn, referenceTime - 10ms, none, PacketType::OneRtt); + sendPacket(*conn, referenceTime - 10ms, std::nullopt, PacketType::OneRtt); auto packet2 = sendPacket( *conn, referenceTime + conn->lossState.srtt / 2, - none, + std::nullopt, PacketType::OneRtt); auto lossVisitor = [&](const auto& /*conn*/, const auto& packet, bool) { EXPECT_EQ(packet1, packet.header.getPacketSequenceNum()); @@ -1919,7 +1923,8 @@ TEST_F(QuicLossFunctionsTest, OutstandingInitialCounting) { conn->lossState.srtt = 100s; PacketNum largestSent = 0; while (largestSent < 10) { - largestSent = sendPacket(*conn, Clock::now(), none, PacketType::Initial); + largestSent = + sendPacket(*conn, Clock::now(), std::nullopt, PacketType::Initial); } EXPECT_EQ(10, conn->outstandings.packetCount[PacketNumberSpace::Initial]); auto noopLossVisitor = @@ -1946,7 +1951,8 @@ TEST_F(QuicLossFunctionsTest, OutstandingHandshakeCounting) { conn->lossState.srtt = 100s; PacketNum largestSent = 0; while (largestSent < 10) { - largestSent = sendPacket(*conn, Clock::now(), none, PacketType::Handshake); + largestSent = + sendPacket(*conn, Clock::now(), std::nullopt, PacketType::Handshake); } EXPECT_EQ(10, conn->outstandings.packetCount[PacketNumberSpace::Handshake]); auto noopLossVisitor = @@ -1971,7 +1977,7 @@ TEST_P(QuicLossFunctionsTest, CappedShiftNoCrash) { conn->outstandings.reset(); conn->lossState.ptoCount = std::numeric_limitslossState.ptoCount)>::max(); - sendPacket(*conn, Clock::now(), none, PacketType::OneRtt); + sendPacket(*conn, Clock::now(), std::nullopt, PacketType::OneRtt); calculateAlarmDuration(*conn); } @@ -2133,8 +2139,8 @@ TEST_F(QuicLossFunctionsTest, ObserverLossEventReorder) { // send 7 packets PacketNum largestSent = 0; for (int i = 0; i < 7; ++i) { - largestSent = - sendPacket(*conn, TimePoint(i * 10ms), none, PacketType::OneRtt); + largestSent = sendPacket( + *conn, TimePoint(i * 10ms), std::nullopt, PacketType::OneRtt); } // Some packets are already acked conn->outstandings.packets.erase( @@ -2218,8 +2224,8 @@ TEST_F(QuicLossFunctionsTest, ObserverLossEventTimeout) { // send 7 packets PacketNum largestSent = 0; for (int i = 0; i < 7; ++i) { - largestSent = - sendPacket(*conn, TimePoint(i * 10ms), none, PacketType::OneRtt); + largestSent = sendPacket( + *conn, TimePoint(i * 10ms), std::nullopt, PacketType::OneRtt); } // setting a very high reordering threshold to force loss by timeout only @@ -2325,8 +2331,8 @@ TEST_F(QuicLossFunctionsTest, ObserverLossEventTimeoutAndReorder) { // send 7 packets PacketNum largestSent = 0; for (int i = 0; i < 7; ++i) { - largestSent = - sendPacket(*conn, TimePoint(i * 10ms), none, PacketType::OneRtt); + largestSent = sendPacket( + *conn, TimePoint(i * 10ms), std::nullopt, PacketType::OneRtt); } // Some packets are already acked @@ -2412,8 +2418,8 @@ TEST_F(QuicLossFunctionsTest, TotalPacketsMarkedLostByReordering) { // send 7 packets PacketNum largestSent = 0; for (int i = 0; i < 7; ++i) { - largestSent = - sendPacket(*conn, TimePoint(i * 10ms), none, PacketType::OneRtt); + largestSent = sendPacket( + *conn, TimePoint(i * 10ms), std::nullopt, PacketType::OneRtt); } // Some packets are already acked @@ -2443,8 +2449,8 @@ TEST_F(QuicLossFunctionsTest, TotalPacketsMarkedLostByReordering) { .hasError()); // Sent 7 packets, out of 0, 1, 2, 3, 4, 5, 6 -- we deleted (acked) 2,3,4 - // 0, 1, and 5 should be marked lost due to reordering, none due to timeout - // 6 is outstanding / on the wire still (no determination made) + // 0, 1, and 5 should be marked lost due to reordering, std::nullopt due to + // timeout 6 is outstanding / on the wire still (no determination made) EXPECT_EQ(3, conn->lossState.totalPacketsMarkedLost); EXPECT_EQ(0, conn->lossState.totalPacketsMarkedLostByTimeout); EXPECT_EQ(3, conn->lossState.totalPacketsMarkedLostByReorderingThreshold); @@ -2457,8 +2463,8 @@ TEST_F(QuicLossFunctionsTest, TotalPacketsMarkedLostByTimeout) { // send 7 packets PacketNum largestSent = 0; for (int i = 0; i < 7; ++i) { - largestSent = - sendPacket(*conn, TimePoint(i * 10ms), none, PacketType::OneRtt); + largestSent = sendPacket( + *conn, TimePoint(i * 10ms), std::nullopt, PacketType::OneRtt); } // setting a very high reordering threshold to force loss by timeout only @@ -2495,8 +2501,8 @@ TEST_F(QuicLossFunctionsTest, TotalPacketsMarkedLostByTimeoutPartial) { // send 7 packets PacketNum largestSent = 0; for (int i = 0; i < 7; ++i) { - largestSent = - sendPacket(*conn, TimePoint(i * 10ms), none, PacketType::OneRtt); + largestSent = sendPacket( + *conn, TimePoint(i * 10ms), std::nullopt, PacketType::OneRtt); } // Some packets are already acked @@ -2526,7 +2532,8 @@ TEST_F(QuicLossFunctionsTest, TotalPacketsMarkedLostByTimeoutPartial) { .hasError()); // Sent 7 packets, out of 0, 1, 2, 3, 4, 5, 6 -- we deleted (acked) 2,3,4 - // 0, 1, 5, and 6 should be marked lost due to timeout, none due to reordering + // 0, 1, 5, and 6 should be marked lost due to timeout, std::nullopt due to + // reordering EXPECT_EQ(4, conn->lossState.totalPacketsMarkedLost); EXPECT_EQ(4, conn->lossState.totalPacketsMarkedLostByTimeout); EXPECT_EQ(0, conn->lossState.totalPacketsMarkedLostByReorderingThreshold); @@ -2539,8 +2546,8 @@ TEST_F(QuicLossFunctionsTest, TotalPacketsMarkedLostByTimeoutAndReordering) { // send 7 packets PacketNum largestSent = 0; for (int i = 0; i < 7; ++i) { - largestSent = - sendPacket(*conn, TimePoint(i * 10ms), none, PacketType::OneRtt); + largestSent = sendPacket( + *conn, TimePoint(i * 10ms), std::nullopt, PacketType::OneRtt); } // Some packets are already acked @@ -2754,7 +2761,13 @@ TEST_F(QuicLossFunctionsTest, TestReorderingThresholdDSRNormal) { return folly::unit; }; for (int i = 0; i < 6; ++i) { - sendPacket(*conn, Clock::now(), none, PacketType::OneRtt, none, true); + sendPacket( + *conn, + Clock::now(), + std::nullopt, + PacketType::OneRtt, + std::nullopt, + true); } // Add some DSR frames for (auto& op : conn->outstandings.packets) { @@ -2852,7 +2865,13 @@ TEST_F(QuicLossFunctionsTest, TestReorderingThresholdDSRNormalOverflow) { return folly::unit; }; for (int i = 0; i < 6; ++i) { - sendPacket(*conn, Clock::now(), none, PacketType::OneRtt, none, true); + sendPacket( + *conn, + Clock::now(), + std::nullopt, + PacketType::OneRtt, + std::nullopt, + true); } // Add some DSR frames for (auto& op : conn->outstandings.packets) { @@ -2931,7 +2950,13 @@ TEST_F(QuicLossFunctionsTest, TestReorderingThresholdDSRIgnoreReorder) { return folly::unit; }; for (int i = 0; i < 6; ++i) { - sendPacket(*conn, Clock::now(), none, PacketType::OneRtt, none, true); + sendPacket( + *conn, + Clock::now(), + std::nullopt, + PacketType::OneRtt, + std::nullopt, + true); } // Add some DSR frames for (auto& op : conn->outstandings.packets) { @@ -2947,7 +2972,7 @@ TEST_F(QuicLossFunctionsTest, TestReorderingThresholdDSRIgnoreReorder) { conn->outstandings.dsrCount++; } // Add another non-DSR after - sendPacket(*conn, Clock::now(), none, PacketType::OneRtt); + sendPacket(*conn, Clock::now(), std::nullopt, PacketType::OneRtt); EXPECT_EQ(7, conn->outstandings.packetCount[PacketNumberSpace::AppData]); // Assume some packets are already acked for (auto iter = @@ -3031,7 +3056,7 @@ TEST_F(QuicLossFunctionsTest, TestReorderingThresholdNonDSRIgnoreReorder) { return folly::unit; }; for (int i = 0; i < 6; ++i) { - sendPacket(*conn, Clock::now(), none, PacketType::OneRtt); + sendPacket(*conn, Clock::now(), std::nullopt, PacketType::OneRtt); } EXPECT_EQ(6, conn->outstandings.packetCount[PacketNumberSpace::AppData]); // Assume some packets are already acked @@ -3110,7 +3135,7 @@ TEST_F( return folly::unit; }; for (int i = 0; i < 6; ++i) { - sendPacket(*conn, Clock::now(), none, PacketType::OneRtt); + sendPacket(*conn, Clock::now(), std::nullopt, PacketType::OneRtt); } EXPECT_EQ(6, conn->outstandings.packetCount[PacketNumberSpace::AppData]); // Assume some packets are already acked @@ -3195,7 +3220,13 @@ TEST_F(QuicLossFunctionsTest, TestReorderingThresholdDSRIgnoreReorderBurst) { return folly::unit; }; for (int i = 0; i < 4; ++i) { - sendPacket(*conn, Clock::now(), none, PacketType::OneRtt, none, true); + sendPacket( + *conn, + Clock::now(), + std::nullopt, + PacketType::OneRtt, + std::nullopt, + true); } // Add some DSR frames and build the ACK auto ack = AckEvent::Builder() @@ -3232,7 +3263,13 @@ TEST_F(QuicLossFunctionsTest, TestReorderingThresholdDSRIgnoreReorderBurst) { } // Add another non-DSR burst and ACK all of them for (int i = 0; i < 4; ++i) { - sendPacket(*conn, Clock::now(), none, PacketType::OneRtt, none, false); + sendPacket( + *conn, + Clock::now(), + std::nullopt, + PacketType::OneRtt, + std::nullopt, + false); auto& op = *getLastOutstandingPacket(*conn, PacketNumberSpace::AppData); ack.ackedPackets.emplace_back( CongestionController::AckEvent::AckPacket::Builder() @@ -3244,7 +3281,13 @@ TEST_F(QuicLossFunctionsTest, TestReorderingThresholdDSRIgnoreReorderBurst) { .build()); } // Add one more DSR packet from the same stream, ACKed - sendPacket(*conn, Clock::now(), none, PacketType::OneRtt, none, true); + sendPacket( + *conn, + Clock::now(), + std::nullopt, + PacketType::OneRtt, + std::nullopt, + true); auto& op = *getLastOutstandingPacket(*conn, PacketNumberSpace::AppData); WriteStreamFrame f{0, 10, 100, false, true, std::nullopt, 5}; AckEvent::AckPacket::DetailsPerStream detailsPerStream; @@ -3309,7 +3352,13 @@ TEST_F(QuicLossFunctionsTest, TestReorderingThresholdNonDSRIgnoreReorderBurst) { return folly::unit; }; for (int i = 0; i < 4; ++i) { - sendPacket(*conn, Clock::now(), none, PacketType::OneRtt, none, false); + sendPacket( + *conn, + Clock::now(), + std::nullopt, + PacketType::OneRtt, + std::nullopt, + false); } // Add some non-DSR frames and build the ACK auto ack = AckEvent::Builder() @@ -3338,7 +3387,13 @@ TEST_F(QuicLossFunctionsTest, TestReorderingThresholdNonDSRIgnoreReorderBurst) { } // Add a DSR burst and ACK all of them for (int i = 0; i < 4; ++i) { - sendPacket(*conn, Clock::now(), none, PacketType::OneRtt, none, true); + sendPacket( + *conn, + Clock::now(), + std::nullopt, + PacketType::OneRtt, + std::nullopt, + true); auto& op = *getLastOutstandingPacket(*conn, PacketNumberSpace::AppData); WriteStreamFrame f{ 4, 10, 100, false, true, std::nullopt, conn->outstandings.dsrCount++}; @@ -3355,7 +3410,7 @@ TEST_F(QuicLossFunctionsTest, TestReorderingThresholdNonDSRIgnoreReorderBurst) { op.isDSRPacket = true; } // Add one more non-DSR packet from the same stream, ACKed - sendPacket(*conn, Clock::now(), none, PacketType::OneRtt); + sendPacket(*conn, Clock::now(), std::nullopt, PacketType::OneRtt); auto& op = *getLastOutstandingPacket(*conn, PacketNumberSpace::AppData); WriteStreamFrame f{0, 10, 100, false, false, std::nullopt, 0}; AckEvent::AckPacket::DetailsPerStream detailsPerStream; diff --git a/quic/observer/SocketObserverInterface.cpp b/quic/observer/SocketObserverInterface.cpp index 427a915f6..675c43df5 100644 --- a/quic/observer/SocketObserverInterface.cpp +++ b/quic/observer/SocketObserverInterface.cpp @@ -60,9 +60,14 @@ SocketObserverInterface::WriteEvent::Builder::build() && { SocketObserverInterface::WriteEvent::WriteEvent( const WriteEvent::BuilderFields& builderFields) - : outstandingPackets(*CHECK_NOTNULL( - builderFields.maybeOutstandingPacketsRef.get_pointer())), - writeCount(*CHECK_NOTNULL(builderFields.maybeWriteCount.get_pointer())), + : outstandingPackets([&]() { + CHECK(builderFields.maybeOutstandingPacketsRef.has_value()); + return builderFields.maybeOutstandingPacketsRef.value(); + }()), + writeCount([&]() { + CHECK(builderFields.maybeWriteCount.has_value()); + return builderFields.maybeWriteCount.value(); + }()), maybeLastPacketSentTime(builderFields.maybeLastPacketSentTime), maybeCwndInBytes(builderFields.maybeCwndInBytes), maybeWritableBytes(builderFields.maybeWritableBytes) {} @@ -294,12 +299,18 @@ SocketObserverInterface::PacketsWrittenEvent::Builder::build() && { SocketObserverInterface::PacketsWrittenEvent::PacketsWrittenEvent( SocketObserverInterface::PacketsWrittenEvent::BuilderFields&& builderFields) : WriteEvent(builderFields), - numPacketsWritten( - *CHECK_NOTNULL(builderFields.maybeNumPacketsWritten.get_pointer())), - numAckElicitingPacketsWritten(*CHECK_NOTNULL( - builderFields.maybeNumAckElicitingPacketsWritten.get_pointer())), - numBytesWritten( - *CHECK_NOTNULL(builderFields.maybeNumBytesWritten.get_pointer())) {} + numPacketsWritten([&]() { + CHECK(builderFields.maybeNumPacketsWritten.has_value()); + return builderFields.maybeNumPacketsWritten.value(); + }()), + numAckElicitingPacketsWritten([&]() { + CHECK(builderFields.maybeNumAckElicitingPacketsWritten.has_value()); + return builderFields.maybeNumAckElicitingPacketsWritten.value(); + }()), + numBytesWritten([&]() { + CHECK(builderFields.maybeNumBytesWritten.has_value()); + return builderFields.maybeNumBytesWritten.value(); + }()) {} SocketObserverInterface::PacketsReceivedEvent::ReceivedUdpPacket::Builder&& SocketObserverInterface::PacketsReceivedEvent::ReceivedUdpPacket::Builder:: @@ -339,11 +350,18 @@ SocketObserverInterface::PacketsReceivedEvent::ReceivedUdpPacket::Builder:: SocketObserverInterface::PacketsReceivedEvent::ReceivedUdpPacket:: ReceivedUdpPacket(SocketObserverInterface::PacketsReceivedEvent:: ReceivedUdpPacket::BuilderFields&& builderFields) - : packetReceiveTime( - *CHECK_NOTNULL(builderFields.maybePacketReceiveTime.get_pointer())), - packetNumBytes( - *CHECK_NOTNULL(builderFields.maybePacketNumBytes.get_pointer())), - packetTos(*CHECK_NOTNULL(builderFields.maybePacketTos.get_pointer())), + : packetReceiveTime([&]() { + CHECK(builderFields.maybePacketReceiveTime.has_value()); + return builderFields.maybePacketReceiveTime.value(); + }()), + packetNumBytes([&]() { + CHECK(builderFields.maybePacketNumBytes.has_value()); + return builderFields.maybePacketNumBytes.value(); + }()), + packetTos([&]() { + CHECK(builderFields.maybePacketTos.has_value()); + return builderFields.maybePacketTos.value(); + }()), maybePacketSoftwareRxTimestamp( builderFields.maybePacketSoftwareRxTimestamp) {} @@ -383,12 +401,18 @@ SocketObserverInterface::PacketsReceivedEvent::Builder::build() && { SocketObserverInterface::PacketsReceivedEvent::PacketsReceivedEvent( SocketObserverInterface::PacketsReceivedEvent::BuilderFields&& builderFields) - : receiveLoopTime( - *CHECK_NOTNULL(builderFields.maybeReceiveLoopTime.get_pointer())), - numPacketsReceived( - *CHECK_NOTNULL(builderFields.maybeNumPacketsReceived.get_pointer())), - numBytesReceived( - *CHECK_NOTNULL(builderFields.maybeNumBytesReceived.get_pointer())), + : receiveLoopTime([&]() { + CHECK(builderFields.maybeReceiveLoopTime.has_value()); + return builderFields.maybeReceiveLoopTime.value(); + }()), + numPacketsReceived([&]() { + CHECK(builderFields.maybeNumPacketsReceived.has_value()); + return builderFields.maybeNumPacketsReceived.value(); + }()), + numBytesReceived([&]() { + CHECK(builderFields.maybeNumBytesReceived.has_value()); + return builderFields.maybeNumBytesReceived.value(); + }()), receivedPackets(std::move(builderFields.receivedPackets)) { CHECK_EQ(numPacketsReceived, receivedPackets.size()); } @@ -407,7 +431,9 @@ SocketObserverInterface::AcksProcessedEvent::Builder::build() && { SocketObserverInterface::AcksProcessedEvent::AcksProcessedEvent( SocketObserverInterface::AcksProcessedEvent::BuilderFields builderFields) - : ackEvents(*CHECK_NOTNULL(builderFields.maybeAckEventsRef.get_pointer())) { -} + : ackEvents([&]() { + CHECK(builderFields.maybeAckEventsRef.has_value()); + return builderFields.maybeAckEventsRef.value(); + }()) {} } // namespace quic diff --git a/quic/observer/test/SocketObserverInterfaceTest.cpp b/quic/observer/test/SocketObserverInterfaceTest.cpp index 85c909891..9f3d7063c 100644 --- a/quic/observer/test/SocketObserverInterfaceTest.cpp +++ b/quic/observer/test/SocketObserverInterfaceTest.cpp @@ -82,8 +82,8 @@ TEST_F(SocketObserverInterfaceTest, InvokeForEachNewOutstandingPacketOrdered) { .setOutstandingPackets(outstandingPackets) .setWriteCount(10) .setLastPacketSentTime(TimePoint()) - .setCwndInBytes(none) - .setWritableBytes(none) + .setCwndInBytes(std::nullopt) + .setWritableBytes(std::nullopt) .setNumPacketsWritten(0) .setNumAckElicitingPacketsWritten(0) .setNumBytesWritten(0) @@ -121,8 +121,8 @@ TEST_F(SocketObserverInterfaceTest, InvokeForEachNewOutstandingPacketOrdered) { .setOutstandingPackets(outstandingPackets) .setWriteCount(10) .setLastPacketSentTime(TimePoint()) - .setCwndInBytes(none) - .setWritableBytes(none) + .setCwndInBytes(std::nullopt) + .setWritableBytes(std::nullopt) .setNumPacketsWritten(0) .setNumAckElicitingPacketsWritten(0) .setNumBytesWritten(0) @@ -151,8 +151,8 @@ TEST_F(SocketObserverInterfaceTest, InvokeForEachNewOutstandingPacketOrdered) { .setOutstandingPackets(outstandingPackets) .setWriteCount(10) .setLastPacketSentTime(TimePoint()) - .setCwndInBytes(none) - .setWritableBytes(none) + .setCwndInBytes(std::nullopt) + .setWritableBytes(std::nullopt) .setNumPacketsWritten(1) .setNumAckElicitingPacketsWritten(0) .setNumBytesWritten(0) @@ -190,8 +190,8 @@ TEST_F(SocketObserverInterfaceTest, InvokeForEachNewOutstandingPacketOrdered) { .setOutstandingPackets(outstandingPackets) .setWriteCount(10) .setLastPacketSentTime(TimePoint()) - .setCwndInBytes(none) - .setWritableBytes(none) + .setCwndInBytes(std::nullopt) + .setWritableBytes(std::nullopt) .setNumPacketsWritten(1) .setNumAckElicitingPacketsWritten(0) .setNumBytesWritten(0) @@ -249,8 +249,8 @@ TEST_F(SocketObserverInterfaceTest, InvokeForEachNewOutstandingPacketOrdered) { .setOutstandingPackets(outstandingPackets) .setWriteCount(1) .setLastPacketSentTime(TimePoint()) - .setCwndInBytes(none) - .setWritableBytes(none) + .setCwndInBytes(std::nullopt) + .setWritableBytes(std::nullopt) .setNumPacketsWritten(3) .setNumAckElicitingPacketsWritten(3) .setNumBytesWritten(0) @@ -328,8 +328,8 @@ TEST_F(SocketObserverInterfaceTest, InvokeForEachNewOutstandingPacketOrdered) { .setOutstandingPackets(outstandingPackets) .setWriteCount(1) .setLastPacketSentTime(TimePoint()) - .setCwndInBytes(none) - .setWritableBytes(none) + .setCwndInBytes(std::nullopt) + .setWritableBytes(std::nullopt) .setNumPacketsWritten(3) .setNumAckElicitingPacketsWritten(3) .setNumBytesWritten(0) @@ -408,8 +408,8 @@ TEST_F(SocketObserverInterfaceTest, InvokeForEachNewOutstandingPacketOrdered) { .setOutstandingPackets(outstandingPackets) .setWriteCount(1) .setLastPacketSentTime(TimePoint()) - .setCwndInBytes(none) - .setWritableBytes(none) + .setCwndInBytes(std::nullopt) + .setWritableBytes(std::nullopt) .setNumPacketsWritten(3) .setNumAckElicitingPacketsWritten(3) .setNumBytesWritten(0) @@ -487,8 +487,8 @@ TEST_F(SocketObserverInterfaceTest, InvokeForEachNewOutstandingPacketOrdered) { .setOutstandingPackets(outstandingPackets) .setWriteCount(3) .setLastPacketSentTime(TimePoint()) - .setCwndInBytes(none) - .setWritableBytes(none) + .setCwndInBytes(std::nullopt) + .setWritableBytes(std::nullopt) .setNumPacketsWritten(1) .setNumAckElicitingPacketsWritten(1) .setNumBytesWritten(0) @@ -552,8 +552,8 @@ TEST_F(SocketObserverInterfaceTest, InvokeForEachNewOutstandingPacketOrdered) { .setOutstandingPackets(outstandingPackets) .setWriteCount(3) .setLastPacketSentTime(TimePoint()) - .setCwndInBytes(none) - .setWritableBytes(none) + .setCwndInBytes(std::nullopt) + .setWritableBytes(std::nullopt) .setNumPacketsWritten(1) .setNumAckElicitingPacketsWritten(1) .setNumBytesWritten(0) @@ -627,8 +627,8 @@ TEST_F(SocketObserverInterfaceTest, InvokeForEachNewOutstandingPacketOrdered) { .setOutstandingPackets(outstandingPackets) .setWriteCount(2) .setLastPacketSentTime(TimePoint()) - .setCwndInBytes(none) - .setWritableBytes(none) + .setCwndInBytes(std::nullopt) + .setWritableBytes(std::nullopt) .setNumPacketsWritten(1) .setNumAckElicitingPacketsWritten(1) .setNumBytesWritten(0) @@ -722,8 +722,8 @@ TEST_F(SocketObserverInterfaceTest, InvokeForEachNewOutstandingPacketOrdered) { .setOutstandingPackets(outstandingPackets) .setWriteCount(2) .setLastPacketSentTime(TimePoint()) - .setCwndInBytes(none) - .setWritableBytes(none) + .setCwndInBytes(std::nullopt) + .setWritableBytes(std::nullopt) .setNumPacketsWritten(3) .setNumAckElicitingPacketsWritten(3) .setNumBytesWritten(0) @@ -781,8 +781,8 @@ TEST_F(SocketObserverInterfaceTest, InvokeForEachNewOutstandingPacketOrdered) { .setOutstandingPackets(outstandingPackets) .setWriteCount(9) .setLastPacketSentTime(TimePoint()) - .setCwndInBytes(none) - .setWritableBytes(none) + .setCwndInBytes(std::nullopt) + .setWritableBytes(std::nullopt) .setNumPacketsWritten(1) .setNumAckElicitingPacketsWritten(1) .setNumBytesWritten(0) @@ -826,8 +826,8 @@ TEST_F(SocketObserverInterfaceTest, InvokeForEachNewOutstandingPacketOrdered) { .setOutstandingPackets(outstandingPackets) .setWriteCount(9) .setLastPacketSentTime(TimePoint()) - .setCwndInBytes(none) - .setWritableBytes(none) + .setCwndInBytes(std::nullopt) + .setWritableBytes(std::nullopt) .setNumPacketsWritten(2) .setNumAckElicitingPacketsWritten(1) .setNumBytesWritten(0) @@ -881,8 +881,8 @@ TEST_F(SocketObserverInterfaceTest, InvokeForEachNewOutstandingPacketOrdered) { .setOutstandingPackets(outstandingPackets) .setWriteCount(9) .setLastPacketSentTime(TimePoint()) - .setCwndInBytes(none) - .setWritableBytes(none) + .setCwndInBytes(std::nullopt) + .setWritableBytes(std::nullopt) .setNumPacketsWritten(2) .setNumAckElicitingPacketsWritten(2) .setNumBytesWritten(0) @@ -944,8 +944,8 @@ TEST_F(SocketObserverInterfaceTest, InvokeForEachNewOutstandingPacketOrdered) { .setOutstandingPackets(outstandingPackets) .setWriteCount(9) .setLastPacketSentTime(TimePoint()) - .setCwndInBytes(none) - .setWritableBytes(none) + .setCwndInBytes(std::nullopt) + .setWritableBytes(std::nullopt) .setNumPacketsWritten(3) .setNumAckElicitingPacketsWritten(2) .setNumBytesWritten(0) @@ -1027,8 +1027,8 @@ TEST_F(SocketObserverInterfaceTest, InvokeForEachNewOutstandingPacketOrdered) { .setOutstandingPackets(outstandingPackets) .setWriteCount(9) .setLastPacketSentTime(TimePoint()) - .setCwndInBytes(none) - .setWritableBytes(none) + .setCwndInBytes(std::nullopt) + .setWritableBytes(std::nullopt) .setNumPacketsWritten(2) .setNumAckElicitingPacketsWritten(2) .setNumBytesWritten(0) @@ -1100,8 +1100,8 @@ TEST_F(SocketObserverInterfaceTest, InvokeForEachNewOutstandingPacketOrdered) { .setOutstandingPackets(outstandingPackets) .setWriteCount(9) .setLastPacketSentTime(TimePoint()) - .setCwndInBytes(none) - .setWritableBytes(none) + .setCwndInBytes(std::nullopt) + .setWritableBytes(std::nullopt) .setNumPacketsWritten(1) .setNumAckElicitingPacketsWritten(1) .setNumBytesWritten(0) diff --git a/quic/priority/BUCK b/quic/priority/BUCK index bd1a25a0c..c8ff96bf5 100644 --- a/quic/priority/BUCK +++ b/quic/priority/BUCK @@ -43,6 +43,7 @@ mvfst_cpp_library( exported_deps = [ ":priority_queue", ":round_robin", + "//folly:cpp_attributes", "//quic:config", ], ) diff --git a/quic/priority/HTTPPriorityQueue.cpp b/quic/priority/HTTPPriorityQueue.cpp index dd1e790e1..9455757c4 100644 --- a/quic/priority/HTTPPriorityQueue.cpp +++ b/quic/priority/HTTPPriorityQueue.cpp @@ -61,7 +61,7 @@ quic::Optional HTTPPriorityQueue::find( } } } - return quic::none; + return std::nullopt; } void HTTPPriorityQueue::addIndex(Identifier id, IndexMapElem indexElem) { diff --git a/quic/priority/HTTPPriorityQueue.h b/quic/priority/HTTPPriorityQueue.h index 647c8294b..6a9736695 100644 --- a/quic/priority/HTTPPriorityQueue.h +++ b/quic/priority/HTTPPriorityQueue.h @@ -9,6 +9,7 @@ #include +#include #include #include @@ -126,7 +127,7 @@ class HTTPPriorityQueue : public quic::PriorityQueue { const PriorityQueue::Priority& pri) const override; [[nodiscard]] bool contains(Identifier id) const override { - return find(id) != quic::none; + return find(id) != std::nullopt; } void insertOrUpdate(Identifier id, PriorityQueue::Priority priority) override; diff --git a/quic/priority/test/HTTPPriorityQueueTest.cpp b/quic/priority/test/HTTPPriorityQueueTest.cpp index 8ff0a82c8..1479a942d 100644 --- a/quic/priority/test/HTTPPriorityQueueTest.cpp +++ b/quic/priority/test/HTTPPriorityQueueTest.cpp @@ -52,7 +52,7 @@ TEST_F(HTTPPriorityQueueTest, InsertSingleElement) { auto priority = HTTPPriorityQueue::Priority(0, false); queue_.insertOrUpdate(id, priority); EXPECT_FALSE(queue_.empty()); - EXPECT_EQ(queue_.getNextScheduledID(quic::none), id); + EXPECT_EQ(queue_.getNextScheduledID(std::nullopt), id); } TEST_F(HTTPPriorityQueueTest, InsertMultipleElements) { @@ -62,10 +62,10 @@ TEST_F(HTTPPriorityQueueTest, InsertMultipleElements) { auto priority2 = HTTPPriorityQueue::Priority(1, false); queue_.insertOrUpdate(id1, priority1); queue_.insertOrUpdate(id2, priority2); - EXPECT_EQ(queue_.getNextScheduledID(quic::none), id1); - EXPECT_EQ(queue_.getNextScheduledID(quic::none), id1); + EXPECT_EQ(queue_.getNextScheduledID(std::nullopt), id1); + EXPECT_EQ(queue_.getNextScheduledID(std::nullopt), id1); queue_.erase(id1); - EXPECT_EQ(queue_.getNextScheduledID(quic::none), id2); + EXPECT_EQ(queue_.getNextScheduledID(std::nullopt), id2); } TEST_F(HTTPPriorityQueueTest, UpdatePriority) { @@ -74,9 +74,9 @@ TEST_F(HTTPPriorityQueueTest, UpdatePriority) { queue_.insertOrUpdate(id, priority); auto newPriority = HTTPPriorityQueue::Priority(1, false); queue_.updateIfExist(id, newPriority); - EXPECT_EQ(queue_.getNextScheduledID(quic::none), id); + EXPECT_EQ(queue_.getNextScheduledID(std::nullopt), id); queue_.updateIfExist(id, newPriority); - EXPECT_EQ(queue_.getNextScheduledID(quic::none), id); + EXPECT_EQ(queue_.getNextScheduledID(std::nullopt), id); } TEST_F(HTTPPriorityQueueTest, EraseElement) { @@ -100,7 +100,7 @@ TEST_F(HTTPPriorityQueueTest, HeapUpOnErase) { if (i == 5) { continue; } - EXPECT_EQ(queue_.getNextScheduledID(quic::none).asUint64(), i); + EXPECT_EQ(queue_.getNextScheduledID(std::nullopt).asUint64(), i); queue_.erase(Identifier::fromStreamID(i)); } EXPECT_TRUE(queue_.empty()); @@ -115,9 +115,9 @@ TEST_F(HTTPPriorityQueueTest, UpdateIncrementalToNonIncremental) { // Update from incremental to non-incremental (updateIfExist) queue_.updateIfExist(id, HTTPPriorityQueue::Priority(0, false)); - EXPECT_TRUE(queue_.getNextScheduledID(quic::none) == id); + EXPECT_TRUE(queue_.getNextScheduledID(std::nullopt) == id); queue_.erase(id); - EXPECT_TRUE(queue_.getNextScheduledID(quic::none) == id2); + EXPECT_TRUE(queue_.getNextScheduledID(std::nullopt) == id2); // Update from incremental to non-incremental (insertOrUpdate) queue_.insertOrUpdate(id2, HTTPPriorityQueue::Priority(0, false)); EXPECT_TRUE(queue_.headPriority() == HTTPPriorityQueue::Priority(0, false)); @@ -134,8 +134,8 @@ TEST_F(HTTPPriorityQueueTest, UpdateNonIncrementalToIncremental) { priority = HTTPPriorityQueue::Priority(0, true); queue_.updateIfExist(id, priority); EXPECT_TRUE(queue_.contains(id)); - EXPECT_TRUE(queue_.getNextScheduledID(quic::none) == id2); - EXPECT_TRUE(queue_.getNextScheduledID(quic::none) == id); + EXPECT_TRUE(queue_.getNextScheduledID(std::nullopt) == id2); + EXPECT_TRUE(queue_.getNextScheduledID(std::nullopt) == id); } TEST_F(HTTPPriorityQueueTest, UpdateIncrementalUrgency) { @@ -147,7 +147,7 @@ TEST_F(HTTPPriorityQueueTest, UpdateIncrementalUrgency) { priority = HTTPPriorityQueue::Priority(1, true); queue_.updateIfExist(id, priority); EXPECT_TRUE(queue_.contains(id)); - EXPECT_TRUE(queue_.getNextScheduledID(quic::none) == id); + EXPECT_TRUE(queue_.getNextScheduledID(std::nullopt) == id); EXPECT_TRUE(queue_.headPriority() == HTTPPriorityQueue::Priority(1, true)); } @@ -159,7 +159,7 @@ TEST_F(HTTPPriorityQueueTest, InsertOrUpdateNoOp) { // Update urgency of incremental priority from 0 -> 1 queue_.updateIfExist(id, HTTPPriorityQueue::Priority(1, true)); EXPECT_TRUE(queue_.contains(id)); - EXPECT_TRUE(queue_.getNextScheduledID(quic::none) == id); + EXPECT_TRUE(queue_.getNextScheduledID(std::nullopt) == id); EXPECT_TRUE(queue_.headPriority() == HTTPPriorityQueue::Priority(1, true)); } @@ -274,7 +274,7 @@ TEST_F(HTTPPriorityQueueTest, ComplexOperations) { CHECK(lastPriority == headPriority || lastPriority < headPriority); lastPriority = headPriority; auto nextId = queue_.peekNextScheduledID(); - queue_.consume(quic::none); + queue_.consume(std::nullopt); CHECK_EQ(nextId.asUint64(), expectedOrder.front()); expectedOrder.pop_front(); auto expectedPri = ids[nextId.asUint64()]; diff --git a/quic/priority/test/QuicPriorityQueueBenchmark.cpp b/quic/priority/test/QuicPriorityQueueBenchmark.cpp index 31fd91c0e..f5dce9802 100644 --- a/quic/priority/test/QuicPriorityQueueBenchmark.cpp +++ b/quic/priority/test/QuicPriorityQueueBenchmark.cpp @@ -37,10 +37,10 @@ static inline void processQueueIncremental( for (size_t i = 0; i < (numConcurrentStreams / 8 + shift) * (packetsPerStream - 1); i++) { - (void)pq.getNextScheduledID(quic::none); + (void)pq.getNextScheduledID(std::nullopt); } for (size_t i = 0; i < (numConcurrentStreams / 8); i++) { - auto id = pq.getNextScheduledID(quic::none); + auto id = pq.getNextScheduledID(std::nullopt); // LOG(INFO) << id.asStreamID(); pq.erase(id); } @@ -55,7 +55,7 @@ static inline void processQueueSequential( for (size_t i = 0; i < numConcurrentStreams; i++) { quic::PriorityQueue::Identifier id; for (size_t p = 0; p < packetsPerStream; p++) { - id = pq.getNextScheduledID(quic::none); + id = pq.getNextScheduledID(std::nullopt); // LOG(INFO) << id.asStreamID(); } pq.erase(id); @@ -158,7 +158,7 @@ BENCHMARK(eraseSequential, n) { insert(pq, nStreams, false); } while (!pq.empty()) { - pq.erase(pq.getNextScheduledID(quic::none)); + pq.erase(pq.getNextScheduledID(std::nullopt)); } } } @@ -172,7 +172,7 @@ BENCHMARK(eraseIncremental, n) { insert(pq, nStreams, true); } while (!pq.empty()) { - pq.erase(pq.getNextScheduledID(quic::none)); + pq.erase(pq.getNextScheduledID(std::nullopt)); } } } diff --git a/quic/priority/test/RoundRobinTests.cpp b/quic/priority/test/RoundRobinTests.cpp index 2063ca63e..654bc34e0 100644 --- a/quic/priority/test/RoundRobinTests.cpp +++ b/quic/priority/test/RoundRobinTests.cpp @@ -28,24 +28,24 @@ class RoundRobinTest : public ::testing::Test { TEST_F(RoundRobinTest, AdvanceAfterNext) { rr_.advanceAfterBytes(3); // force 100% coverage in next call rr_.advanceAfterNext(3); - EXPECT_EQ(rr_.getNext(quic::none), Identifier::fromStreamID(1)); - EXPECT_EQ(rr_.getNext(quic::none), Identifier::fromStreamID(1)); - EXPECT_EQ(rr_.getNext(quic::none), Identifier::fromStreamID(1)); - EXPECT_EQ(rr_.getNext(quic::none), Identifier::fromStreamID(2)); - EXPECT_EQ(rr_.getNext(quic::none), Identifier::fromStreamID(2)); - EXPECT_EQ(rr_.getNext(quic::none), Identifier::fromStreamID(2)); - EXPECT_EQ(rr_.getNext(quic::none), Identifier::fromStreamID(3)); - EXPECT_EQ(rr_.getNext(quic::none), Identifier::fromStreamID(3)); - EXPECT_EQ(rr_.getNext(quic::none), Identifier::fromStreamID(3)); + EXPECT_EQ(rr_.getNext(std::nullopt), Identifier::fromStreamID(1)); + EXPECT_EQ(rr_.getNext(std::nullopt), Identifier::fromStreamID(1)); + EXPECT_EQ(rr_.getNext(std::nullopt), Identifier::fromStreamID(1)); + EXPECT_EQ(rr_.getNext(std::nullopt), Identifier::fromStreamID(2)); + EXPECT_EQ(rr_.getNext(std::nullopt), Identifier::fromStreamID(2)); + EXPECT_EQ(rr_.getNext(std::nullopt), Identifier::fromStreamID(2)); + EXPECT_EQ(rr_.getNext(std::nullopt), Identifier::fromStreamID(3)); + EXPECT_EQ(rr_.getNext(std::nullopt), Identifier::fromStreamID(3)); + EXPECT_EQ(rr_.getNext(std::nullopt), Identifier::fromStreamID(3)); } TEST_F(RoundRobinTest, AdvanceAfterBytes) { rr_.advanceAfterBytes(10); - EXPECT_EQ(rr_.getNext(quic::none), Identifier::fromStreamID(1)); + EXPECT_EQ(rr_.getNext(std::nullopt), Identifier::fromStreamID(1)); EXPECT_EQ(rr_.getNext(5), Identifier::fromStreamID(1)); EXPECT_EQ(rr_.getNext(5), Identifier::fromStreamID(1)); EXPECT_EQ(rr_.getNext(10), Identifier::fromStreamID(2)); - EXPECT_EQ(rr_.getNext(quic::none), Identifier::fromStreamID(3)); + EXPECT_EQ(rr_.getNext(std::nullopt), Identifier::fromStreamID(3)); } TEST_F(RoundRobinTest, Empty) { @@ -59,13 +59,13 @@ TEST_F(RoundRobinTest, Erase) { EXPECT_FALSE(rr_.erase(Identifier())); // doesn't match anything auto id1 = Identifier::fromStreamID(1); - EXPECT_EQ(rr_.getNext(quic::none), id1); + EXPECT_EQ(rr_.getNext(std::nullopt), id1); EXPECT_TRUE(rr_.erase(id1)); // erase head resets current - id2 gets two nexts auto id2 = Identifier::fromStreamID(2); - EXPECT_EQ(rr_.getNext(quic::none), id2); - EXPECT_EQ(rr_.getNext(quic::none), id2); + EXPECT_EQ(rr_.getNext(std::nullopt), id2); + EXPECT_EQ(rr_.getNext(std::nullopt), id2); // erase head - 1 EXPECT_TRUE(rr_.erase(id2)); rr_.insert(id1); @@ -74,28 +74,28 @@ TEST_F(RoundRobinTest, Erase) { EXPECT_TRUE(rr_.erase(id1)); auto id3 = Identifier::fromStreamID(3); - EXPECT_EQ(rr_.getNext(quic::none), id3); + EXPECT_EQ(rr_.getNext(std::nullopt), id3); EXPECT_TRUE(rr_.erase(id3)); EXPECT_TRUE(rr_.empty()); } TEST_F(RoundRobinTest, EraseInMiddleBeforeHead) { - rr_.getNext(quic::none); - rr_.getNext(quic::none); + rr_.getNext(std::nullopt); + rr_.getNext(std::nullopt); auto id2 = Identifier::fromStreamID(2); EXPECT_TRUE(rr_.erase(id2)); auto id3 = Identifier::fromStreamID(3); - EXPECT_EQ(rr_.getNext(quic::none), id3); + EXPECT_EQ(rr_.getNext(std::nullopt), id3); auto id1 = Identifier::fromStreamID(1); - EXPECT_EQ(rr_.getNext(quic::none), id1); + EXPECT_EQ(rr_.getNext(std::nullopt), id1); } TEST_F(RoundRobinTest, GetNext) { - EXPECT_EQ(rr_.getNext(quic::none), Identifier::fromStreamID(1)); + EXPECT_EQ(rr_.getNext(std::nullopt), Identifier::fromStreamID(1)); } TEST_F(RoundRobinTest, PeekAndClear) { @@ -128,7 +128,7 @@ TEST_F(RoundRobinTest, Index) { rr_.insert(Identifier::fromStreamID(i)); } for (size_t i = 0; i < 20; i++) { - rr_.getNext(quic::none); + rr_.getNext(std::nullopt); } for (size_t i = 1; i < 20; i++) { EXPECT_TRUE(rr_.erase(Identifier::fromStreamID(i))); diff --git a/quic/samples/echo/EchoClient.h b/quic/samples/echo/EchoClient.h index 1f40526ed..6ad3141ae 100644 --- a/quic/samples/echo/EchoClient.h +++ b/quic/samples/echo/EchoClient.h @@ -271,7 +271,7 @@ class EchoClient : public quic::QuicSocket::ConnectionSetupCallback, if (connectOnly_) { evb->runInEventBaseThreadAndWait( - [this] { quicClient_->closeNow(folly::none); }); + [this] { quicClient_->closeNow(std::nullopt); }); return folly::unit; } @@ -291,7 +291,7 @@ class EchoClient : public quic::QuicSocket::ConnectionSetupCallback, auto sendMessageInStream = [&]() { if (message == "/close") { - quicClient_->close(none); + quicClient_->close(std::nullopt); closed = true; return; } diff --git a/quic/samples/echo/LogQuicStats.h b/quic/samples/echo/LogQuicStats.h index 6d46672cc..ba9a73bee 100644 --- a/quic/samples/echo/LogQuicStats.h +++ b/quic/samples/echo/LogQuicStats.h @@ -109,7 +109,7 @@ class LogQuicStats : public quic::QuicTransportStatsCallback { VLOG(2) << prefix_ << __func__; } - void onConnectionClose(Optional code = none) override { + void onConnectionClose(Optional code = std::nullopt) override { VLOG(2) << prefix_ << __func__ << " reason=" << quic::toString(code.value_or(LocalErrorCode::NO_ERROR)); } diff --git a/quic/server/QuicServer.cpp b/quic/server/QuicServer.cpp index e2a94cd61..dd645edb9 100644 --- a/quic/server/QuicServer.cpp +++ b/quic/server/QuicServer.cpp @@ -110,7 +110,7 @@ void QuicServer::setRateLimit( std::function count, std::chrono::seconds window) { checkRunningInThread(mainThreadId_); - rateLimit_ = folly::make_optional(std::move(count), window); + rateLimit_ = tiny::make_optional(std::move(count), window); } void QuicServer::setUnfinishedHandshakeLimit(std::function limitFn) { diff --git a/quic/server/QuicServerTransport.cpp b/quic/server/QuicServerTransport.cpp index 346b5ee5f..3ef8f6698 100644 --- a/quic/server/QuicServerTransport.cpp +++ b/quic/server/QuicServerTransport.cpp @@ -127,7 +127,7 @@ void QuicServerTransport::setOriginalPeerAddress( void QuicServerTransport::setServerConnectionIdParams( ServerConnectionIdParams params) noexcept { - serverConn_->serverConnIdParams.assign(std::move(params)); + serverConn_->serverConnIdParams = std::move(params); } void QuicServerTransport::setTransportStatsCallback( @@ -431,14 +431,14 @@ std::shared_ptr QuicServerTransport::sharedGuard() { void QuicServerTransport::setClientConnectionId( const ConnectionId& clientConnectionId) { - conn_->clientConnectionId.assign(clientConnectionId); + conn_->clientConnectionId = clientConnectionId; conn_->peerConnectionIds.emplace_back( clientConnectionId, kInitialSequenceNumber); } void QuicServerTransport::setClientChosenDestConnectionId( const ConnectionId& clientChosenDestConnectionId) { - conn_->clientChosenDestConnectionId.assign(clientChosenDestConnectionId); + conn_->clientChosenDestConnectionId = clientChosenDestConnectionId; } void QuicServerTransport::onCryptoEventAvailable() noexcept { @@ -589,7 +589,7 @@ QuicServerTransport::maybeWriteNewSessionTicket() { conn_->qLogger->addTransportStateUpdate(kWriteNst); } newSessionTicketWrittenTimestamp_ = Clock::now(); - Optional cwndHint = none; + Optional cwndHint = std::nullopt; if (conn_->transportSettings.includeCwndHintsInSessionTicket && conn_->congestionController) { const auto& bdp = conn_->congestionController->getBDP(); @@ -647,7 +647,8 @@ void QuicServerTransport::maybeNotifyConnectionIdRetired() { void QuicServerTransport::maybeNotifyConnectionIdBound() { // make this connId bound only when the keys are available - if (!notifiedConnIdBound_ && routingCb_ && conn_->serverConnectionId && + if (!notifiedConnIdBound_ && routingCb_ && + conn_->serverConnectionId.has_value() && serverConn_->serverHandshakeLayer->isHandshakeDone()) { notifiedConnIdBound_ = true; routingCb_->onConnectionIdBound(shared_from_this()); @@ -749,7 +750,7 @@ void QuicServerTransport::onTransportKnobs(BufPtr knobBlob) { reinterpret_cast(knobBlob->data()), knobBlob->length()); VLOG(4) << "Received transport knobs: " << serializedKnobs; auto params = parseTransportKnobs(serializedKnobs); - if (params.hasValue()) { + if (params.has_value()) { handleTransportKnobParams(*params); } else { QUIC_STATS( @@ -924,7 +925,7 @@ void QuicServerTransport::registerAllTransportKnobParamHandlers() { } if (serverTransport->serverConn_->maybeLastMaxPacingRateKnobSeqNum >= - folly::make_optional(expectedSeqNum.value())) { + tiny::make_optional(expectedSeqNum.value())) { QUIC_STATS( serverTransport->serverConn_->statsCallback, onTransportKnobOutOfOrder, @@ -1542,7 +1543,7 @@ QuicServerTransport::getPeerTransportParams() const { return maybeParams->parameters; } } - return none; + return std::nullopt; } void QuicServerTransport::setCongestionControl(CongestionControlType type) { diff --git a/quic/server/QuicServerWorker.cpp b/quic/server/QuicServerWorker.cpp index ffcd90e06..951521a2f 100644 --- a/quic/server/QuicServerWorker.cpp +++ b/quic/server/QuicServerWorker.cpp @@ -294,7 +294,7 @@ bool QuicServerWorker::maybeSendVersionNegotiationPacketOrDrop( VersionNegotiationPacketBuilder builder( invariant.dstConnId, invariant.srcConnId, supportedVersions_); versionNegotiationPacket = - folly::make_optional(std::move(builder).buildPacket()); + tiny::make_optional(std::move(builder).buildPacket()); } } if (versionNegotiationPacket) { @@ -364,8 +364,7 @@ void QuicServerWorker::onDataAvailable( // we've flushed it. BufPtr data = std::move(readBuffer_); - folly::Optional - maybeSockTsExt; + Optional maybeSockTsExt; if (params.ts.has_value()) { maybeSockTsExt = QuicAsyncUDPSocket::convertToSocketTimestampExt(*params.ts); @@ -474,12 +473,12 @@ void QuicServerWorker::handleNetworkData( false, /* isInitial */ false, /* is0Rtt */ std::move(maybeParsedShortHeader->destinationConnId), - none); + std::nullopt); return forwardNetworkData( client, std::move(routingData), NetworkData(std::move(udpPacket)), - none, /* quicVersion */ + std::nullopt, /* quicVersion */ isForwardedData); } } else if ( @@ -947,7 +946,7 @@ void QuicServerWorker::dispatchPacketData( // token or a new token) Cursor cursor(networkData.getPackets().front().buf.front()); auto maybeEncryptedToken = maybeGetEncryptedToken(cursor); - bool hasTokenSecret = transportSettings_.retryTokenSecret.hasValue(); + bool hasTokenSecret = transportSettings_.retryTokenSecret.has_value(); // If the retryTokenSecret is not set, just skip evaluating validity of // token and assume true @@ -1035,19 +1034,19 @@ void QuicServerWorker::sendResetPacket( Optional QuicServerWorker::maybeGetEncryptedToken(Cursor& cursor) { // Move cursor to the byte right after the initial byte if (!cursor.canAdvance(1)) { - return none; + return std::nullopt; } auto initialByte = cursor.readBE(); // We already know this is an initial packet, which uses a long header auto parsedLongHeader = parseLongHeader(initialByte, cursor); if (!parsedLongHeader || !parsedLongHeader->parsedLongHeader.has_value()) { - return none; + return std::nullopt; } auto header = parsedLongHeader->parsedLongHeader.value().header; if (!header.hasToken()) { - return none; + return std::nullopt; } return header.getToken(); } @@ -1075,7 +1074,7 @@ bool QuicServerWorker::validRetryToken( std::string& encryptedToken, const ConnectionId& dstConnId, const folly::IPAddress& clientIp) { - CHECK(transportSettings_.retryTokenSecret.hasValue()); + CHECK(transportSettings_.retryTokenSecret.has_value()); TokenGenerator tokenGenerator(transportSettings_.retryTokenSecret.value()); @@ -1092,7 +1091,7 @@ bool QuicServerWorker::validRetryToken( bool QuicServerWorker::validNewToken( std::string& encryptedToken, const folly::IPAddress& clientIp) { - CHECK(transportSettings_.retryTokenSecret.hasValue()); + CHECK(transportSettings_.retryTokenSecret.has_value()); TokenGenerator tokenGenerator(transportSettings_.retryTokenSecret.value()); @@ -1110,7 +1109,7 @@ void QuicServerWorker::sendRetryPacket( const folly::SocketAddress& client, const ConnectionId& dstConnId, const ConnectionId& srcConnId) { - if (!transportSettings_.retryTokenSecret.hasValue()) { + if (!transportSettings_.retryTokenSecret.has_value()) { VLOG(4) << "Not sending retry packet since retry token secret is not set"; return; } diff --git a/quic/server/SlidingWindowRateLimiter.h b/quic/server/SlidingWindowRateLimiter.h index bc8e7a64d..86b5e2418 100644 --- a/quic/server/SlidingWindowRateLimiter.h +++ b/quic/server/SlidingWindowRateLimiter.h @@ -37,7 +37,7 @@ class SlidingWindowRateLimiter : public RateLimiter { private: const std::function count_; const std::chrono::microseconds window_; - Optional currentWindowStartPoint_{none}; + Optional currentWindowStartPoint_{std::nullopt}; uint64_t countInPrevWindow_{0}; uint64_t countInCurWindow_{0}; }; diff --git a/quic/server/handshake/AppToken.h b/quic/server/handshake/AppToken.h index 2bd1491ff..26e64ab80 100644 --- a/quic/server/handshake/AppToken.h +++ b/quic/server/handshake/AppToken.h @@ -37,6 +37,6 @@ TicketTransportParameters createTicketTransportParameters( uint64_t initialMaxStreamsBidi, uint64_t initialMaxStreamsUni, ExtendedAckFeatureMaskType extendedAckSupport, - Optional cwndHintBytes = none); + Optional cwndHintBytes = std::nullopt); } // namespace quic diff --git a/quic/server/handshake/DefaultAppTokenValidator.cpp b/quic/server/handshake/DefaultAppTokenValidator.cpp index cd11eeafc..777ffdbba 100644 --- a/quic/server/handshake/DefaultAppTokenValidator.cpp +++ b/quic/server/handshake/DefaultAppTokenValidator.cpp @@ -150,7 +150,10 @@ bool DefaultAppTokenValidator::validate( // If application did not set validator, it's valid. if (conn_->earlyDataAppParamsValidator && !conn_->earlyDataAppParamsValidator( - resumptionState.alpn, appToken->appParams)) { + resumptionState.alpn + ? quic::Optional(*resumptionState.alpn) + : std::nullopt, + appToken->appParams)) { VLOG(10) << "Invalid app params"; return validated = false; } diff --git a/quic/server/handshake/ServerHandshake.cpp b/quic/server/handshake/ServerHandshake.cpp index bf5bbceb2..eb3aa3752 100644 --- a/quic/server/handshake/ServerHandshake.cpp +++ b/quic/server/handshake/ServerHandshake.cpp @@ -211,8 +211,8 @@ Optional> ServerHandshake::getExportedKeyingMaterial( uint16_t keyLength) { const auto cipherSuite = state_.cipher(); const auto& ems = state_.exporterMasterSecret(); - if (!ems.hasValue() || !cipherSuite.hasValue()) { - return none; + if (!ems.has_value() || !cipherSuite.has_value()) { + return std::nullopt; } auto ekm = fizz::Exporter::getExportedKeyingMaterial( @@ -220,7 +220,7 @@ Optional> ServerHandshake::getExportedKeyingMaterial( cipherSuite.value(), ems.value()->coalesce(), label, - context == none ? nullptr : BufHelpers::wrapBuffer(*context), + context == std::nullopt ? nullptr : BufHelpers::wrapBuffer(*context), keyLength); std::vector result(ekm->coalesce()); @@ -228,7 +228,13 @@ Optional> ServerHandshake::getExportedKeyingMaterial( } const Optional& ServerHandshake::getApplicationProtocol() const { - return state_.alpn(); + static Optional empty; + if (!state_.alpn().has_value()) { + return empty; + } + static thread_local Optional result; + result = state_.alpn().value(); + return result; } void ServerHandshake::onError( @@ -322,23 +328,29 @@ void ServerHandshake::processPendingEvents() { } const Optional& ServerHandshake::getAppToken() const { - return state_.appToken(); + static Optional empty; + if (!state_.appToken().has_value()) { + return empty; + } + static thread_local Optional result; + result = state_.appToken().value()->clone(); + return result; } Handshake::TLSSummary ServerHandshake::getTLSSummary() const { Handshake::TLSSummary summary; - if (state_.alpn().hasValue()) { + if (state_.alpn().has_value()) { summary.alpn = state_.alpn().value(); } - if (state_.group().hasValue()) { + if (state_.group().has_value()) { summary.namedGroup = folly::to(fizz::toString(state_.group().value())); } - if (state_.pskType().hasValue()) { + if (state_.pskType().has_value()) { summary.pskType = folly::to(fizz::toString(state_.pskType().value())); } - if (state_.echState().hasValue()) { + if (state_.echState().has_value()) { summary.echStatus = fizz::server::toString(state_.echStatus()); } return summary; diff --git a/quic/server/handshake/TokenGenerator.cpp b/quic/server/handshake/TokenGenerator.cpp index d7acf8d64..cd8215a8f 100644 --- a/quic/server/handshake/TokenGenerator.cpp +++ b/quic/server/handshake/TokenGenerator.cpp @@ -36,10 +36,11 @@ Optional TokenGenerator::encryptToken( if (!maybeEncryptedToken) { LOG(ERROR) << "Failed to encypt addr validation token with IP " << token.clientIp.str(); + return Optional(); } - // If the encryption failed, this will be empty optional - return maybeEncryptedToken; + // Convert folly::Optional to quic::Optional (tiny::optional) + return Optional(std::move(maybeEncryptedToken.value())); } uint64_t TokenGenerator::decryptToken( diff --git a/quic/server/handshake/test/RetryTokenGeneratorTest.cpp b/quic/server/handshake/test/RetryTokenGeneratorTest.cpp index 9f996b725..10e8db8db 100644 --- a/quic/server/handshake/test/RetryTokenGeneratorTest.cpp +++ b/quic/server/handshake/test/RetryTokenGeneratorTest.cpp @@ -28,7 +28,7 @@ TEST_F(RetryTokenGeneratorTest, EncryptDecryptRetryToken) { TokenGenerator tokenGenerator(secret); RetryToken token(connId, clientIp, clientPort); auto maybeEncryptedToken = tokenGenerator.encryptToken(token); - ASSERT_TRUE(maybeEncryptedToken.hasValue()); + ASSERT_TRUE(maybeEncryptedToken.has_value()); // Decrypt the token using another generator TokenGenerator tokenGenerator1(secret); @@ -52,7 +52,7 @@ TEST_F(RetryTokenGeneratorTest, EncryptDecryptNewToken) { TokenGenerator tokenGenerator(secret); NewToken token(clientIp); auto maybeEncryptedToken = tokenGenerator.encryptToken(token); - ASSERT_TRUE(maybeEncryptedToken.hasValue()); + ASSERT_TRUE(maybeEncryptedToken.has_value()); // Decrypt the token using another generator TokenGenerator tokenGenerator1(secret); diff --git a/quic/server/handshake/test/ServerHandshakeTest.cpp b/quic/server/handshake/test/ServerHandshakeTest.cpp index 625e44e3f..f595825c2 100644 --- a/quic/server/handshake/test/ServerHandshakeTest.cpp +++ b/quic/server/handshake/test/ServerHandshakeTest.cpp @@ -136,7 +136,7 @@ class ServerHandshakeTest : public Test { verifier, hostname, cachedPsk, - Optional>(none), + folly::Optional>(folly::none), std::make_shared(clientExtensions, 0)); } @@ -391,13 +391,14 @@ class ServerHandshakeTest : public Test { TEST_F(ServerHandshakeTest, TestGetExportedKeyingMaterial) { // Sanity check. getExportedKeyingMaterial() should return nullptr prior to // an handshake. - auto ekm = - handshake->getExportedKeyingMaterial("EXPORTER-Some-Label", none, 32); + auto ekm = handshake->getExportedKeyingMaterial( + "EXPORTER-Some-Label", std::nullopt, 32); EXPECT_TRUE(!ekm.has_value()); clientServerRound(); serverClientRound(); - ekm = handshake->getExportedKeyingMaterial("EXPORTER-Some-Label", none, 32); + ekm = handshake->getExportedKeyingMaterial( + "EXPORTER-Some-Label", std::nullopt, 32); ASSERT_TRUE(ekm.has_value()); EXPECT_EQ(ekm->size(), 32); @@ -456,8 +457,8 @@ class AsyncRejectingTicketCipher : public fizz::server::TicketCipher { public: ~AsyncRejectingTicketCipher() override = default; - folly::SemiFuture< - Optional, std::chrono::seconds>>> + folly::SemiFuture, std::chrono::seconds>>> encrypt(fizz::server::ResumptionState) const override { if (!encryptAsync_) { return std::make_pair(folly::IOBuf::create(0), 2s); @@ -465,7 +466,7 @@ class AsyncRejectingTicketCipher : public fizz::server::TicketCipher { encryptAsync_ = false; return std::move(encryptFuture_).deferValue([](auto&&) { VLOG(1) << "got ticket async"; - return folly::makeSemiFuture, std::chrono::seconds>>>( std::make_pair(folly::IOBuf::create(0), 2s)); }); @@ -487,13 +488,13 @@ class AsyncRejectingTicketCipher : public fizz::server::TicketCipher { } folly::SemiFuture< - std::pair>> + std::pair>> decrypt(std::unique_ptr) const override { if (!decryptAsync_) { if (error_) { throw std::runtime_error("test decrypt error"); } - return std::make_pair(fizz::PskType::Rejected, none); + return std::make_pair(fizz::PskType::Rejected, folly::none); } else { decryptAsync_ = false; return std::move(decryptFuture_).deferValue([&](auto&&) { @@ -501,9 +502,10 @@ class AsyncRejectingTicketCipher : public fizz::server::TicketCipher { if (error_) { throw std::runtime_error("test decrypt error"); } - return folly::makeSemiFuture< - std::pair>>( - std::make_pair(fizz::PskType::Rejected, none)); + return folly::makeSemiFuture>>( + std::make_pair(fizz::PskType::Rejected, folly::none)); }); } } @@ -672,7 +674,7 @@ TEST_F(ServerHandshakeHRRTest, TestAsyncCancel) { promise.setValue(); evb.loop(); - EXPECT_EQ(handshake->getApplicationProtocol(), none); + EXPECT_EQ(handshake->getApplicationProtocol(), std::nullopt); expectOneRttCipher(false); } @@ -787,7 +789,7 @@ class ServerHandshakeZeroRttDefaultAppTokenValidatorTest public: ~AcceptingTicketCipher() override = default; - folly::SemiFuture, std::chrono::seconds>>> encrypt(fizz::server::ResumptionState) const override { // Fake handshake, no need todo anything here. @@ -804,8 +806,9 @@ class ServerHandshakeZeroRttDefaultAppTokenValidatorTest resState.serverCert = psk.serverCert; } - folly::SemiFuture< - std::pair>> + folly::SemiFuture>> decrypt(std::unique_ptr) const override { return std::make_pair(fizz::PskType::Resumption, std::move(resState)); } diff --git a/quic/server/state/ServerStateMachine.cpp b/quic/server/state/ServerStateMachine.cpp index 6f68d4ee6..7d0835e64 100644 --- a/quic/server/state/ServerStateMachine.cpp +++ b/quic/server/state/ServerStateMachine.cpp @@ -355,10 +355,10 @@ folly::Expected processClientInitialParams( } conn.peerAckDelayExponent = ackDelayExponent.value_or(kDefaultAckDelayExponent); - if (minAckDelay.hasValue()) { + if (minAckDelay.has_value()) { conn.peerMinAckDelay = std::chrono::microseconds(minAckDelay.value()); } - if (maxDatagramFrameSize.hasValue()) { + if (maxDatagramFrameSize.has_value()) { if (maxDatagramFrameSize.value() > 0 && maxDatagramFrameSize.value() <= kMaxDatagramPacketOverhead) { return folly::makeUnexpected(QuicError( @@ -390,14 +390,14 @@ folly::Expected processClientInitialParams( isAckReceiveTimestampsEnabled.value() == 1) { if (maxReceiveTimestampsPerAck.has_value() && receiveTimestampsExponent.has_value()) { - conn.maybePeerAckReceiveTimestampsConfig.assign( - {std::min( - static_cast(maxReceiveTimestampsPerAck.value()), - static_cast( - conn.transportSettings.maxReceiveTimestampsPerAckStored)), - std::max( - static_cast(receiveTimestampsExponent.value()), - static_cast(0))}); + conn.maybePeerAckReceiveTimestampsConfig = { + std::min( + static_cast(maxReceiveTimestampsPerAck.value()), + static_cast( + conn.transportSettings.maxReceiveTimestampsPerAckStored)), + std::max( + static_cast(receiveTimestampsExponent.value()), + static_cast(0))}; } } @@ -1242,7 +1242,7 @@ folly::Expected onServerReadDataFromOpen( } case QuicFrame::Type::RstStreamFrame: { RstStreamFrame& frame = *quicFrame.asRstStreamFrame(); - if (frame.reliableSize.hasValue()) { + if (frame.reliableSize.has_value()) { return folly::makeUnexpected(QuicError( TransportErrorCode::PROTOCOL_VIOLATION, "Reliable resets not supported")); @@ -1752,7 +1752,7 @@ QuicServerConnectionState::createAndAddNewSelfConnId() { LOG_IF(ERROR, encodedTimes == kConnIdEncodingRetryLimit) << "Quic CIDRejector rejected all conneectionIDs"; if (encodedCid.hasError()) { - return none; + return std::nullopt; } QUIC_STATS(statsCallback, onConnectionIdCreated, encodedTimes); auto newConnIdData = diff --git a/quic/server/state/ServerStateMachine.h b/quic/server/state/ServerStateMachine.h index a541cc3ef..32764baf0 100644 --- a/quic/server/state/ServerStateMachine.h +++ b/quic/server/state/ServerStateMachine.h @@ -151,7 +151,7 @@ struct QuicServerConnectionState : public QuicConnectionStateBase { MaxPacingRateKnobState maxPacingRateKnobState{}; // Sequence number of the last received MAX_PACING_RATE_KNOB_SEQUENCED. - Optional maybeLastMaxPacingRateKnobSeqNum{none}; + Optional maybeLastMaxPacingRateKnobSeqNum{std::nullopt}; Optional createAndAddNewSelfConnId() override; diff --git a/quic/server/test/QuicClientServerIntegrationTest.cpp b/quic/server/test/QuicClientServerIntegrationTest.cpp index 8b4f9e1a6..ac88e6998 100644 --- a/quic/server/test/QuicClientServerIntegrationTest.cpp +++ b/quic/server/test/QuicClientServerIntegrationTest.cpp @@ -55,7 +55,7 @@ class ServerTransportParameters : public testing::Test { void TearDown() override { if (client_) { - client_->close(none); + client_->close(std::nullopt); } evb_.loop(); } diff --git a/quic/server/test/QuicServerTest.cpp b/quic/server/test/QuicServerTest.cpp index 7d9b5d77f..666a04aed 100644 --- a/quic/server/test/QuicServerTest.cpp +++ b/quic/server/test/QuicServerTest.cpp @@ -343,7 +343,8 @@ void QuicServerWorkerTest::testSendReset( auto aead = createNoOpAead(); // Make the decrypt fail EXPECT_CALL(*aead, _tryDecrypt(_, _, _)) - .WillRepeatedly(Invoke([&](auto&, auto, auto) { return none; })); + .WillRepeatedly( + Invoke([&](auto&, auto, auto) { return std::nullopt; })); codec.setOneRttReadCipher(std::move(aead)); codec.setOneRttHeaderCipher(test::createNoOpHeaderCipher()); StatelessResetToken token = generateStatelessResetToken(); @@ -359,12 +360,16 @@ void QuicServerWorkerTest::testSendReset( })); RoutingData routingData( - HeaderForm::Short, false, false, shortHeader.getConnectionId(), none); + HeaderForm::Short, + false, + false, + shortHeader.getConnectionId(), + std::nullopt); worker_->dispatchPacketData( kClientAddr, std::move(routingData), NetworkData(packet->clone(), Clock::now(), 0), - none); + std::nullopt); eventbase_.loopIgnoreKeepAlive(); } @@ -414,12 +419,12 @@ TEST_F(QuicServerWorkerTest, SmallPacketTestNoReset) { false, false, shortHeaderConnId.getConnectionId(), - none); + std::nullopt); worker_->dispatchPacketData( kClientAddr, std::move(routingData), NetworkData(data->clone(), Clock::now(), 0), - none); + std::nullopt); eventbase_.loopIgnoreKeepAlive(); } @@ -706,12 +711,13 @@ TEST_F(QuicServerWorkerTest, QuicServerMultipleConnIdsRouting) { EXPECT_CALL( *transport_, onNetworkData(kClientAddr, NetworkDataMatches(*data))) .Times(1); - RoutingData routingData2(HeaderForm::Short, false, false, connId, none); + RoutingData routingData2( + HeaderForm::Short, false, false, connId, std::nullopt); worker_->dispatchPacketData( kClientAddr, std::move(routingData2), NetworkData(data->clone(), Clock::now(), 0), - none); + std::nullopt); eventbase_.loopIgnoreKeepAlive(); auto connId2 = connId; @@ -723,12 +729,13 @@ TEST_F(QuicServerWorkerTest, QuicServerMultipleConnIdsRouting) { EXPECT_CALL( *transport_, onNetworkData(kClientAddr, NetworkDataMatches(*data))) .Times(1); - RoutingData routingData3(HeaderForm::Short, false, false, connId2, none); + RoutingData routingData3( + HeaderForm::Short, false, false, connId2, std::nullopt); worker_->dispatchPacketData( kClientAddr, std::move(routingData3), NetworkData(data->clone(), Clock::now(), 0), - none); + std::nullopt); eventbase_.loopIgnoreKeepAlive(); EXPECT_CALL(*transport_, setRoutingCallback(nullptr)); @@ -823,12 +830,12 @@ TEST_F(QuicServerWorkerTest, QuicServerNewConnection) { false, false, shortHeaderConnId.getConnectionId(), - none); + std::nullopt); worker_->dispatchPacketData( kClientAddr, std::move(routingData), NetworkData(data->clone(), Clock::now(), 0), - none); + std::nullopt); eventbase_.loopIgnoreKeepAlive(); ConnectionId newConnId = getTestConnectionId(hostId_); @@ -857,12 +864,12 @@ TEST_F(QuicServerWorkerTest, QuicServerNewConnection) { false, false, shortHeaderConnId.getConnectionId(), - none); + std::nullopt); worker_->dispatchPacketData( kClientAddr, std::move(routingData2), NetworkData(data->clone(), Clock::now(), 0), - none); + std::nullopt); eventbase_.loopIgnoreKeepAlive(); // routing by address after transport_'s connid available, but before @@ -894,12 +901,12 @@ TEST_F(QuicServerWorkerTest, QuicServerNewConnection) { false, false, shortHeaderConnId2.getConnectionId(), - none); + std::nullopt); worker_->dispatchPacketData( clientAddr2, std::move(routingData3), NetworkData(data->clone(), Clock::now(), 0), - none); + std::nullopt); eventbase_.loopIgnoreKeepAlive(); EXPECT_CALL(*transport_, setRoutingCallback(nullptr)).Times(2); @@ -1428,12 +1435,12 @@ TEST_F(QuicServerWorkerTest, PacketWithZeroHostIdFromExistingConnection) { false, false, shortHeaderConnId.getConnectionId(), - none); + std::nullopt); worker_->dispatchPacketData( kClientAddr, std::move(routingData), NetworkData(data->clone(), Clock::now(), 0), - none); + std::nullopt); EXPECT_CALL(*transport_, setRoutingCallback(nullptr)).Times(2); EXPECT_CALL(*transport_, setTransportStatsCallback(nullptr)).Times(2); } @@ -1468,7 +1475,7 @@ auto createInitialStream( streamData->computeChainDataLength(), streamData->computeChainDataLength(), true, - none /* skipLenHint */); + std::nullopt /* skipLenHint */); EXPECT_TRUE(res.hasValue()); auto dataLen = *res; EXPECT_TRUE(dataLen); @@ -2951,7 +2958,7 @@ void QuicServerTest::testReset(BufPtr packet) { auto aead = createNoOpAead(); // Make the decrypt fail EXPECT_CALL(*aead, _tryDecrypt(_, _, _)) - .WillRepeatedly(Invoke([&](auto&, auto, auto) { return none; })); + .WillRepeatedly(Invoke([&](auto&, auto, auto) { return std::nullopt; })); codec.setOneRttReadCipher(std::move(aead)); codec.setOneRttHeaderCipher(test::createNoOpHeaderCipher()); StatelessResetToken token = generateStatelessResetToken(); diff --git a/quic/server/test/QuicServerTransportTest.cpp b/quic/server/test/QuicServerTransportTest.cpp index 2868857c4..b87aab3b0 100644 --- a/quic/server/test/QuicServerTransportTest.cpp +++ b/quic/server/test/QuicServerTransportTest.cpp @@ -46,14 +46,14 @@ Optional getFrameIfPresent( return frame; } } - return none; + return std::nullopt; } bool verifyFramePresent( std::vector>& socketWrites, QuicReadCodec& readCodec, QuicFrame::Type frameType) { - return getFrameIfPresent(socketWrites, readCodec, frameType).hasValue(); + return getFrameIfPresent(socketWrites, readCodec, frameType).has_value(); } struct MigrationParam { @@ -95,7 +95,7 @@ TEST_F(QuicServerTransportTest, TestReadMultipleStreams) { buf1->computeChainDataLength(), buf1->computeChainDataLength(), true, - none /* skipLenHint */); + std::nullopt /* skipLenHint */); ASSERT_TRUE(res.hasValue()); auto dataLen = *res; ASSERT_TRUE(dataLen); @@ -109,7 +109,7 @@ TEST_F(QuicServerTransportTest, TestReadMultipleStreams) { buf1->computeChainDataLength(), buf1->computeChainDataLength(), true, - none /* skipLenHint */); + std::nullopt /* skipLenHint */); ASSERT_TRUE(res.hasValue()); dataLen = *res; ASSERT_TRUE(dataLen); @@ -121,13 +121,13 @@ TEST_F(QuicServerTransportTest, TestReadMultipleStreams) { // Clear out the existing acks to make sure that we are the cause of the acks. server->getNonConstConn().ackStates.initialAckState->acks.clear(); server->getNonConstConn().ackStates.initialAckState->largestRecvdPacketTime = - none; + std::nullopt; server->getNonConstConn().ackStates.handshakeAckState->acks.clear(); server->getNonConstConn() - .ackStates.handshakeAckState->largestRecvdPacketTime = none; + .ackStates.handshakeAckState->largestRecvdPacketTime = std::nullopt; server->getNonConstConn().ackStates.appDataAckState.acks.clear(); server->getNonConstConn().ackStates.appDataAckState.largestRecvdPacketTime = - none; + std::nullopt; EXPECT_CALL(*quicStats_, onNewQuicStream()).Times(2); // for x08, x0C deliverData(packetToBuf(packet)); @@ -564,7 +564,7 @@ TEST_F(QuicServerTransportTest, NoDataExceptCloseProcessedAfterClosing) { buf->computeChainDataLength(), buf->computeChainDataLength(), true, - none /* skipLenHint */) + std::nullopt /* skipLenHint */) .hasError()); writeStreamFrameData(builder, buf->clone(), buf->computeChainDataLength()); std::string errMsg = "Mind the gap"; @@ -783,7 +783,7 @@ TEST_F(QuicServerTransportTest, ReceiveRstStreamNonExistentAndOtherFrame) { data->computeChainDataLength(), data->computeChainDataLength(), false, - none /* skipLenHint */) + std::nullopt /* skipLenHint */) .hasError()); writeStreamFrameData(builder2, data->clone(), data->computeChainDataLength()); auto packetObject = std::move(builder2).buildPacket(); @@ -1100,7 +1100,7 @@ TEST_F(QuicServerTransportTest, RecvStopSendingFrameAfterHalfCloseRemote) { 0, 10, true, - none /* skipLenHint */); + std::nullopt /* skipLenHint */); ASSERT_TRUE(res.hasValue()); auto dataLen = *res; ASSERT_TRUE(dataLen.has_value()); @@ -1207,7 +1207,7 @@ TEST_F(QuicServerTransportTest, RecvStopSendingFrameAfterReset) { EXPECT_CALL( connCallback, onStopSending(_, GenericApplicationErrorCode::UNKNOWN)) .WillOnce(Invoke([&](StreamId /*sid*/, ApplicationErrorCode /*e*/) { - server->close(none); + server->close(std::nullopt); })); EXPECT_THROW(deliverData(packetToBuf(packet)), std::runtime_error); } @@ -1937,7 +1937,7 @@ INSTANTIATE_TEST_SUITE_P( QuicServerTransportMigrationTests, QuicServerTransportAllowMigrationTest, Values( - MigrationParam{none}, + MigrationParam{std::nullopt}, MigrationParam{2}, MigrationParam{4}, MigrationParam{9}, @@ -3182,7 +3182,7 @@ TEST_F(QuicServerTransportTest, ImmediateAckValid) { ASSERT_NO_THROW(deliverData(packetToBuf(packet))); // An ACK has been scheduled for AppData number space. EXPECT_TRUE(server->getConn() - .ackStates.appDataAckState.largestAckScheduled.hasValue()); + .ackStates.appDataAckState.largestAckScheduled.has_value()); EXPECT_EQ( server->getConn().ackStates.appDataAckState.largestAckScheduled.value_or( packetNum + 1), @@ -3210,7 +3210,7 @@ TEST_F(QuicServerTransportTest, ImmediateAckProtocolViolation) { auto packet = std::move(builder).buildPacket(); // This should throw a protocol violation error ASSERT_THROW(deliverData(packetToBuf(packet)), std::runtime_error); - // Verify that none of the ack states have changed + // Verify that std::nullopt of the ack states have changed EXPECT_FALSE( server->getConn().ackStates.initialAckState->needsToSendAckImmediately); EXPECT_FALSE( @@ -3531,7 +3531,7 @@ TEST_F(QuicServerTransportTest, InvokeTxCallbacksSingleByteDSR) { // an error. So, onByteEventCanceled should be called only once. EXPECT_CALL(pastlastByteTxCb, onByteEventCanceled(getTxMatcher(stream, 2))) .Times(1); - server->close(none); + server->close(std::nullopt); Mock::VerifyAndClearExpectations(&pastlastByteTxCb); } @@ -3589,7 +3589,7 @@ TEST_F(QuicServerTransportTest, InvokeDeliveryCallbacksSingleByteWithDSR) { // unsentByteDeliveryCb::onByteEvent will never get called // cancel gets called instead EXPECT_CALL(unsentByteDeliveryCb, onCanceled(stream, 2)).Times(1); - server->close(none); + server->close(std::nullopt); Mock::VerifyAndClearExpectations(&unsentByteDeliveryCb); } @@ -3880,8 +3880,8 @@ TEST_F( data->computeChainDataLength(), data->computeChainDataLength(), /*fin=*/true, - /*skipLenHint=*/none); - ASSERT_TRUE(res.hasValue()); + /*skipLenHint=*/std::nullopt); + ASSERT_TRUE(res.has_value()); auto dataLen = *res; writeStreamFrameData( builder, @@ -3924,8 +3924,8 @@ TEST_F( data->computeChainDataLength(), data->computeChainDataLength(), /*eof=*/true, - /*skipLenHint=*/none); - ASSERT_TRUE(res.hasValue()); + /*skipLenHint=*/std::nullopt); + ASSERT_TRUE(res.has_value()); auto dataLen = *res; writeStreamFrameData( builder, @@ -3969,8 +3969,8 @@ TEST_F( data->computeChainDataLength(), data->computeChainDataLength(), /*eof=*/true, - /*skipLenHint=*/none); - ASSERT_TRUE(res.hasValue()); + /*skipLenHint=*/std::nullopt); + ASSERT_TRUE(res.has_value()); auto dataLen = *res; writeStreamFrameData( builder, @@ -4567,7 +4567,8 @@ TEST_F(QuicUnencryptedServerTransportTest, TestSendHandshakeDoneNewTokenFrame) { QuicFrame::Type::ReadNewTokenFrame); EXPECT_TRUE( - clientParsedFrame.hasValue() && clientParsedFrame->asReadNewTokenFrame()); + clientParsedFrame.has_value() && + clientParsedFrame->asReadNewTokenFrame()); auto clientReadNewTokenFrame = clientParsedFrame->asReadNewTokenFrame(); @@ -4860,7 +4861,7 @@ TEST_P( *data, 0 /* cipherOverhead */, 0 /* largestAcked */, - none, + std::nullopt, false)); deliverData(std::move(packetData)); EXPECT_EQ(server->getConn().streamManager->streamCount(), 0); diff --git a/quic/server/test/QuicServerTransportTestUtil.h b/quic/server/test/QuicServerTransportTestUtil.h index 959d0ee72..d5227341a 100644 --- a/quic/server/test/QuicServerTransportTestUtil.h +++ b/quic/server/test/QuicServerTransportTestUtil.h @@ -329,9 +329,9 @@ class QuicServerTransportTestBase : public virtual testing::Test { data, 0 /* cipherOverhead */, 0 /* largestAcked */, - none /* longHeaderOverride */, + std::nullopt /* longHeaderOverride */, eof, - none, + std::nullopt, offset)); deliverData(packetData->clone()); return packetData; diff --git a/quic/state/AckEvent.cpp b/quic/state/AckEvent.cpp index 7a9fd5158..cfb34c66f 100644 --- a/quic/state/AckEvent.cpp +++ b/quic/state/AckEvent.cpp @@ -120,7 +120,7 @@ AckEvent::AckPacket AckEvent::AckPacket::Builder::build() && { detailsPerStream.value(), lastAckedPacketInfo ? Optional( *lastAckedPacketInfo) - : none, + : std::nullopt, isAppLimited, std::move(receiveRelativeTimeStampUsec)); } @@ -137,7 +137,7 @@ void AckEvent::AckPacket::Builder::buildInto( detailsPerStream.value(), lastAckedPacketInfo ? Optional( *lastAckedPacketInfo) - : none, + : std::nullopt, isAppLimited, std::move(receiveRelativeTimeStampUsec)); } @@ -191,14 +191,26 @@ AckEvent AckEvent::Builder::build() && { } AckEvent::AckEvent(AckEvent::BuilderFields&& builderFields) - : ackTime(*CHECK_NOTNULL(builderFields.maybeAckTime.get_pointer())), - adjustedAckTime( - *CHECK_NOTNULL(builderFields.maybeAdjustedAckTime.get_pointer())), - ackDelay(builderFields.maybeAckDelay.value()), - packetNumberSpace( - *CHECK_NOTNULL(builderFields.maybePacketNumberSpace.get_pointer())), - largestAckedPacket( - *CHECK_NOTNULL(builderFields.maybeLargestAckedPacket.get_pointer())), + : ackTime([&]() { + CHECK(builderFields.maybeAckTime.has_value()); + return builderFields.maybeAckTime.value(); + }()), + adjustedAckTime([&]() { + CHECK(builderFields.maybeAdjustedAckTime.has_value()); + return builderFields.maybeAdjustedAckTime.value(); + }()), + ackDelay([&]() { + CHECK(builderFields.maybeAckDelay.has_value()); + return builderFields.maybeAckDelay.value(); + }()), + packetNumberSpace([&]() { + CHECK(builderFields.maybePacketNumberSpace.has_value()); + return builderFields.maybePacketNumberSpace.value(); + }()), + largestAckedPacket([&]() { + CHECK(builderFields.maybeLargestAckedPacket.has_value()); + return builderFields.maybeLargestAckedPacket.value(); + }()), ecnECT0Count(builderFields.ecnECT0Count), ecnECT1Count(builderFields.ecnECT1Count), ecnCECount(builderFields.ecnCECount), diff --git a/quic/state/AckHandlers.cpp b/quic/state/AckHandlers.cpp index df2784575..611b1557d 100644 --- a/quic/state/AckHandlers.cpp +++ b/quic/state/AckHandlers.cpp @@ -102,7 +102,7 @@ folly::Expected processAckFrame( skippedPacketNum.value() + kDistanceToClearSkippedPacketNumber) { // The skipped packet number is far enough in the past, we can stop // checking it, or potentially skip another number. - skippedPacketNum = folly::none; + skippedPacketNum = std::nullopt; } } @@ -119,8 +119,8 @@ folly::Expected processAckFrame( getFirstOutstandingPacket(conn, PacketNumberSpace::AppData); Optional firstPacketNum = (firstOutstandingPacket != conn.outstandings.packets.end()) - ? folly::make_optional(firstOutstandingPacket->getPacketSequenceNum()) - : none; + ? tiny::make_optional(firstOutstandingPacket->getPacketSequenceNum()) + : std::nullopt; uint64_t dsrPacketsAcked = 0; Optional @@ -295,7 +295,7 @@ folly::Expected processAckFrame( const auto& packetFrame) -> Optional { // check if it's a WriteStreamFrame being ACKed if (packetFrame.type() != QuicWriteFrame::Type::WriteStreamFrame) { - return none; + return std::nullopt; } // check if the stream is alive (could be ACK for dead stream) @@ -303,7 +303,7 @@ folly::Expected processAckFrame( maybeAckedStreamState = conn.streamManager->findStream(ackedFrame.streamId); if (!maybeAckedStreamState) { - return none; + return std::nullopt; } // stream is alive and frame is WriteStreamFrame @@ -411,7 +411,8 @@ folly::Expected processAckFrame( QUIC_STATS(conn.statsCallback, onPersistentCongestion); } } - conn.congestionController->onPacketAckOrLoss(&ack, lossEvent.get_pointer()); + conn.congestionController->onPacketAckOrLoss( + &ack, lossEvent.has_value() ? &lossEvent.value() : nullptr); for (auto& packetProcessor : conn.packetProcessors) { packetProcessor->onPacketAck(&ack); } diff --git a/quic/state/OutstandingPacket.h b/quic/state/OutstandingPacket.h index b5715ccb4..323db8d87 100644 --- a/quic/state/OutstandingPacket.h +++ b/quic/state/OutstandingPacket.h @@ -179,7 +179,7 @@ struct OutstandingPacket { Optional lastAckedPacketInfo; // ClonedPacketIdentifier associated with this OutstandingPacketWrapper. This - // will be a none if the packet isn't a clone and hasn't been cloned. + // will be a std::nullopt if the packet isn't a clone and hasn't been cloned. Optional maybeClonedPacketIdentifier; OptionalIntegral nonDsrPacketSequenceNumber; diff --git a/quic/state/QuicStateFunctions.cpp b/quic/state/QuicStateFunctions.cpp index bbb26cb31..0a8be7934 100644 --- a/quic/state/QuicStateFunctions.cpp +++ b/quic/state/QuicStateFunctions.cpp @@ -102,7 +102,7 @@ void updateAckSendStateOnRecvPacket( DCHECK(!pktHasCryptoData || pktHasRetransmittableData); auto thresh = kNonRtxRxPacketsPendingBeforeAck; if (pktHasRetransmittableData || ackState.numRxPacketsRecvd) { - if (ackState.tolerance.hasValue()) { + if (ackState.tolerance.has_value()) { thresh = ackState.tolerance.value(); } else { thresh = ackState.largestRecvdPacketNum.value_or(0) > @@ -373,7 +373,7 @@ std::pair, PacketNumberSpace> earliestTimeAndSpace( const EnumArray>& times, bool considerAppData) noexcept { std::pair, PacketNumberSpace> res = { - none, PacketNumberSpace::Initial}; + std::nullopt, PacketNumberSpace::Initial}; for (PacketNumberSpace pns : times.keys()) { if (!times[pns]) { continue; @@ -417,7 +417,7 @@ uint64_t addPacketToAckState( } static_assert(Clock::is_steady, "Needs steady clock"); - ackState.lastRecvdPacketInfo.assign({packetNum, udpPacket.timings}); + ackState.lastRecvdPacketInfo = {packetNum, udpPacket.timings}; if (packetNum >= expectedNextPacket) { if (ackState.recvdPacketInfos.size() == diff --git a/quic/state/QuicStreamFunctions.cpp b/quic/state/QuicStreamFunctions.cpp index 8f2c34f8f..a3cb3bf6d 100644 --- a/quic/state/QuicStreamFunctions.cpp +++ b/quic/state/QuicStreamFunctions.cpp @@ -530,7 +530,7 @@ Optional getLargestWriteOffsetTxed(const QuicStreamState& stream) { // currentWriteOffset is really nextWriteOffset // when 0, it indicates nothing has been written yet if (stream.currentWriteOffset == 0 && stream.writeBufMeta.offset == 0) { - return none; + return std::nullopt; } uint64_t currentWriteOffset = std::max(stream.currentWriteOffset, stream.writeBufMeta.offset); @@ -543,7 +543,7 @@ Optional getLargestDeliverableOffset(const QuicStreamState& stream) { // zero then we cannot deliver any offsets. if (stream.ackedIntervals.empty() || stream.ackedIntervals.front().start != 0) { - return none; + return std::nullopt; } return stream.ackedIntervals.front().end; } diff --git a/quic/state/QuicStreamFunctions.h b/quic/state/QuicStreamFunctions.h index 2e26c6ff0..445c03c46 100644 --- a/quic/state/QuicStreamFunctions.h +++ b/quic/state/QuicStreamFunctions.h @@ -102,7 +102,7 @@ void appendPendingStreamReset( QuicConnectionStateBase& conn, const QuicStreamState& stream, ApplicationErrorCode errorCode, - Optional reliableSize = folly::none); + Optional reliableSize = std::nullopt); /** * Get the largest write offset the stream has seen @@ -112,7 +112,7 @@ uint64_t getLargestWriteOffsetSeen(const QuicStreamState& stream); /** * Get the largest write offset the stream has transmitted / written to socket. * - * If no bytes have been written to the socket yet, returns none. + * If no bytes have been written to the socket yet, returns std::nullopt. */ Optional getLargestWriteOffsetTxed(const QuicStreamState& stream); diff --git a/quic/state/QuicStreamManager.h b/quic/state/QuicStreamManager.h index b6c81313f..37bbba69f 100644 --- a/quic/state/QuicStreamManager.h +++ b/quic/state/QuicStreamManager.h @@ -367,7 +367,7 @@ class QuicStreamManager { const auto next = nextAcceptablePeerBidirectionalStreamId_; CHECK_GE(max, next); if (max == next) { - return none; + return std::nullopt; } return next; } @@ -377,7 +377,7 @@ class QuicStreamManager { const auto next = nextAcceptablePeerUnidirectionalStreamId_; CHECK_GE(max, next); if (max == next) { - return none; + return std::nullopt; } return next; } @@ -387,7 +387,7 @@ class QuicStreamManager { const auto next = nextAcceptableLocalBidirectionalStreamId_; CHECK_GE(max, next); if (max == next) { - return none; + return std::nullopt; } return next; } @@ -397,7 +397,7 @@ class QuicStreamManager { const auto next = nextAcceptableLocalUnidirectionalStreamId_; CHECK_GE(max, next); if (max == next) { - return none; + return std::nullopt; } return next; } @@ -620,7 +620,7 @@ class QuicStreamManager { Optional popDeliverable() { auto itr = deliverableStreams_.begin(); if (itr == deliverableStreams_.end()) { - return none; + return std::nullopt; } StreamId ret = *itr; deliverableStreams_.erase(itr); @@ -650,7 +650,7 @@ class QuicStreamManager { Optional popTx() { auto itr = txStreams_.begin(); if (itr == txStreams_.end()) { - return none; + return std::nullopt; } else { StreamId ret = *itr; txStreams_.erase(itr); @@ -696,7 +696,7 @@ class QuicStreamManager { Optional popFlowControlUpdated() { auto itr = flowControlUpdated_.begin(); if (itr == flowControlUpdated_.end()) { - return none; + return std::nullopt; } else { StreamId ret = *itr; flowControlUpdated_.erase(itr); diff --git a/quic/state/QuicTransportStatsCallback.h b/quic/state/QuicTransportStatsCallback.h index 817bbcc9d..d7fd308c6 100644 --- a/quic/state/QuicTransportStatsCallback.h +++ b/quic/state/QuicTransportStatsCallback.h @@ -102,7 +102,8 @@ class QuicTransportStatsCallback { // connection level metrics: virtual void onNewConnection() = 0; - virtual void onConnectionClose(Optional code = none) = 0; + virtual void onConnectionClose( + Optional code = std::nullopt) = 0; virtual void onConnectionCloseZeroBytesWritten() = 0; diff --git a/quic/state/SimpleFrameFunctions.cpp b/quic/state/SimpleFrameFunctions.cpp index 654fa2069..a036b48e4 100644 --- a/quic/state/SimpleFrameFunctions.cpp +++ b/quic/state/SimpleFrameFunctions.cpp @@ -23,7 +23,7 @@ Optional updateSimpleFrameOnPacketClone( case QuicSimpleFrame::Type::StopSendingFrame: if (!conn.streamManager->streamExists( frame.asStopSendingFrame()->streamId)) { - return none; + return std::nullopt; } return QuicSimpleFrame(frame); case QuicSimpleFrame::Type::PathChallengeFrame: @@ -31,7 +31,7 @@ Optional updateSimpleFrameOnPacketClone( // or a different path validation was scheduled if (!conn.outstandingPathValidation || *frame.asPathChallengeFrame() != *conn.outstandingPathValidation) { - return none; + return std::nullopt; } return QuicSimpleFrame(frame); case QuicSimpleFrame::Type::PathResponseFrame: @@ -145,7 +145,7 @@ folly::Expected updateSimpleFrameOnPacketReceived( } case QuicSimpleFrame::Type::PathResponseFrame: { const PathResponseFrame& pathResponse = *frame.asPathResponseFrame(); - // Ignore the response if outstandingPathValidation is none or + // Ignore the response if outstandingPathValidation is std::nullopt or // the path data doesn't match what's in outstandingPathValidation if (fromChangedPeerAddress || !conn.outstandingPathValidation || pathResponse.pathData != conn.outstandingPathValidation->pathData) { diff --git a/quic/state/StateData.h b/quic/state/StateData.h index 1e519fba1..c7d4b8913 100644 --- a/quic/state/StateData.h +++ b/quic/state/StateData.h @@ -437,7 +437,7 @@ struct QuicConnectionStateBase : public folly::DelayedDestruction { // number and stateless reset token for itself, and if successful, returns it // and updates the connection's state to ensure its peer can use it. virtual Optional createAndAddNewSelfConnId() { - return none; + return std::nullopt; } uint64_t nextSelfConnectionIdSequence{0}; diff --git a/quic/state/StreamData.h b/quic/state/StreamData.h index dc809c39e..474a525f8 100644 --- a/quic/state/StreamData.h +++ b/quic/state/StreamData.h @@ -182,7 +182,8 @@ struct QuicStreamLike { Optional finalReadOffset; // This is set if we send a RELIABLE_RESET_STREAM frame to the peer. If we - // subsequently send a RESET_STREAM frame, we reset this value to none. + // subsequently send a RESET_STREAM frame, we reset this value to + // std::nullopt. Optional reliableSizeToPeer; // When the application calls updateReliableDeliveryCheckpoint() on the diff --git a/quic/state/TransportSettings.h b/quic/state/TransportSettings.h index 18bfd6a2e..a01da7a09 100644 --- a/quic/state/TransportSettings.h +++ b/quic/state/TransportSettings.h @@ -403,7 +403,7 @@ struct TransportSettings { // Whether to initiate key updates bool initiateKeyUpdate{false}; // How many packets to send before initiating the first key update. - // This is reset to none after the first key update is initiated. + // This is reset to std::nullopt after the first key update is initiated. OptionalIntegral firstKeyUpdatePacketCount{ kFirstKeyUpdatePacketCount}; // How many packets to send before initiating periodic key updates diff --git a/quic/state/TransportSettingsFunctions.cpp b/quic/state/TransportSettingsFunctions.cpp index b2e5d079d..fc557c2c4 100644 --- a/quic/state/TransportSettingsFunctions.cpp +++ b/quic/state/TransportSettingsFunctions.cpp @@ -112,7 +112,7 @@ quic::CongestionControlConfig parseCongestionControlConfig( return ccaConfig; } -// Same as parse function but returns none on error instead of throwing. +// Same as parse function but returns std::nullopt on error instead of throwing. Optional tryParseCongestionControlConfig( const std::string& ccaConfigJson) { try { @@ -120,7 +120,7 @@ Optional tryParseCongestionControlConfig( ccaConfig = parseCongestionControlConfig(ccaConfigJson); return ccaConfig; } catch (const std::exception&) { - return none; + return std::nullopt; } folly::assume_unreachable(); } diff --git a/quic/state/TransportSettingsFunctions.h b/quic/state/TransportSettingsFunctions.h index 5ccdd3c68..f222c7fec 100644 --- a/quic/state/TransportSettingsFunctions.h +++ b/quic/state/TransportSettingsFunctions.h @@ -23,7 +23,7 @@ void populateAckFrequencyConfig( quic::CongestionControlConfig parseCongestionControlConfig( const std::string& ccaConfigJson); -// Same as parse function but returns none on error instead of throwing. +// Same as parse function but returns std::nullopt on error instead of throwing. Optional tryParseCongestionControlConfig( const std::string& ccaConfigJson); } // namespace quic diff --git a/quic/state/stream/StreamSendHandlers.cpp b/quic/state/stream/StreamSendHandlers.cpp index 8e5ddf65c..ac883eb94 100644 --- a/quic/state/stream/StreamSendHandlers.cpp +++ b/quic/state/stream/StreamSendHandlers.cpp @@ -206,13 +206,13 @@ folly::Expected sendAckSMHandler( folly::Expected sendRstAckSMHandler( QuicStreamState& stream, - folly::Optional reliableSize) { + Optional reliableSize) { switch (stream.sendState) { case StreamSendState::ResetSent: { VLOG(10) << "ResetSent: Transition to closed stream=" << stream.id << " " << stream.conn; // Note that we set minReliableSizeAcked to 0 for non-reliable resets. - if (!stream.minReliableSizeAcked.hasValue()) { + if (!stream.minReliableSizeAcked.has_value()) { stream.minReliableSizeAcked = reliableSize.value_or(0); } else { stream.minReliableSizeAcked = diff --git a/quic/state/stream/StreamSendHandlers.h b/quic/state/stream/StreamSendHandlers.h index 90b0b822d..41fb1ab65 100644 --- a/quic/state/stream/StreamSendHandlers.h +++ b/quic/state/stream/StreamSendHandlers.h @@ -18,7 +18,7 @@ namespace quic { [[nodiscard]] folly::Expected sendRstSMHandler( QuicStreamState& stream, ApplicationErrorCode errorCode, - const Optional& reliableSize = folly::none); + const Optional& reliableSize = std::nullopt); [[nodiscard]] folly::Expected sendAckSMHandler( QuicStreamState& stream, @@ -26,6 +26,6 @@ namespace quic { [[nodiscard]] folly::Expected sendRstAckSMHandler( QuicStreamState& stream, - folly::Optional reliableSize); + Optional reliableSize); } // namespace quic diff --git a/quic/state/stream/StreamStateFunctions.cpp b/quic/state/stream/StreamStateFunctions.cpp index 655da3d8e..46caef2fd 100644 --- a/quic/state/stream/StreamStateFunctions.cpp +++ b/quic/state/stream/StreamStateFunctions.cpp @@ -30,7 +30,7 @@ folly::Expected resetQuicStream( stream.removeFromLossBufMetasStartingAtOffset(*reliableSize); stream.streamWriteError = error; } else { - stream.reliableSizeToPeer = folly::none; + stream.reliableSizeToPeer = std::nullopt; stream.retransmissionBuffer.clear(); stream.writeBuffer.move(); ChainedByteRangeHead(std::move(stream.pendingWrites)); // Will be destructed @@ -81,7 +81,7 @@ folly::Expected onResetQuicStream( } stream.reliableSizeFromPeer = - frame.reliableSize.hasValue() ? *frame.reliableSize : 0; + frame.reliableSize.has_value() ? *frame.reliableSize : 0; // Mark eofoffset: if (stream.maxOffsetObserved > frame.finalSize) { return folly::makeUnexpected(QuicError( diff --git a/quic/state/stream/StreamStateFunctions.h b/quic/state/stream/StreamStateFunctions.h index 7e4fb289b..6f43017b7 100644 --- a/quic/state/stream/StreamStateFunctions.h +++ b/quic/state/stream/StreamStateFunctions.h @@ -15,7 +15,7 @@ namespace quic { [[nodiscard]] folly::Expected resetQuicStream( QuicStreamState& stream, ApplicationErrorCode error, - Optional reliableSize = folly::none); + Optional reliableSize = std::nullopt); // Common operations to conduct on QuicStreamState when receive reset on it [[nodiscard]] folly::Expected onResetQuicStream( diff --git a/quic/state/stream/test/StreamStateFunctionsTest.cpp b/quic/state/stream/test/StreamStateFunctionsTest.cpp index 86996c8ea..de0b5731b 100644 --- a/quic/state/stream/test/StreamStateFunctionsTest.cpp +++ b/quic/state/stream/test/StreamStateFunctionsTest.cpp @@ -287,7 +287,7 @@ TEST_F(StreamStateFunctionsTests, SendResetDSRStream) { ASSERT_FALSE( resetQuicStream(stream, GenericApplicationErrorCode::UNKNOWN).hasError()); EXPECT_EQ(getSendConnFlowControlBytesAPI(conn), initialConnWindow); - EXPECT_TRUE(stream.streamWriteError.hasValue()); + EXPECT_TRUE(stream.streamWriteError.has_value()); EXPECT_TRUE(stream.writeBuffer.empty()); EXPECT_EQ(0, stream.writeBufMeta.length); EXPECT_TRUE(stream.lossBufMetas.empty()); diff --git a/quic/state/stream/test/StreamStateMachineTest.cpp b/quic/state/stream/test/StreamStateMachineTest.cpp index 437c5cb02..4241c7a1b 100644 --- a/quic/state/stream/test/StreamStateMachineTest.cpp +++ b/quic/state/stream/test/StreamStateMachineTest.cpp @@ -101,7 +101,7 @@ TEST_F(QuicOpenStateTest, InvalidEvent) { StreamId id = 5; QuicStreamState stream(id, *conn); RstStreamFrame frame(1, GenericApplicationErrorCode::UNKNOWN, 0); - auto result = sendRstAckSMHandler(stream, folly::none); + auto result = sendRstAckSMHandler(stream, std::nullopt); ASSERT_TRUE(result.hasError()); EXPECT_NE(result.error().code.asTransportErrorCode(), nullptr); } @@ -321,7 +321,7 @@ TEST_F(QuicResetSentStateTest, RstAck) { stream.readBuffer.emplace_back( folly::IOBuf::copyBuffer("One more thing"), 0xABCD, false); RstStreamFrame frame(id, GenericApplicationErrorCode::UNKNOWN, 0); - auto result = sendRstAckSMHandler(stream, folly::none); + auto result = sendRstAckSMHandler(stream, std::nullopt); ASSERT_FALSE(result.hasError()); EXPECT_EQ(stream.sendState, StreamSendState::Closed); @@ -418,7 +418,7 @@ TEST_F(QuicResetSentStateTest, RstAfterReliableRst) { stream.readBuffer.emplace_back( folly::IOBuf::copyBuffer("One more thing"), 0xABCD, false); RstStreamFrame frame(id, GenericApplicationErrorCode::UNKNOWN, 0); - auto result = sendRstAckSMHandler(stream, folly::none); + auto result = sendRstAckSMHandler(stream, std::nullopt); ASSERT_FALSE(result.hasError()); EXPECT_EQ(stream.sendState, StreamSendState::Closed); @@ -504,7 +504,7 @@ TEST_F(QuicClosedStateTest, RstAck) { QuicStreamState stream(id, *conn); stream.sendState = StreamSendState::Closed; RstStreamFrame frame(id, GenericApplicationErrorCode::UNKNOWN, 0); - auto result = sendRstAckSMHandler(stream, folly::none); + auto result = sendRstAckSMHandler(stream, std::nullopt); ASSERT_FALSE(result.hasError()); EXPECT_EQ(stream.sendState, StreamSendState::Closed); } diff --git a/quic/state/test/AckEventTestUtil.h b/quic/state/test/AckEventTestUtil.h index 9152e6ddf..0e7c1ffe3 100644 --- a/quic/state/test/AckEventTestUtil.h +++ b/quic/state/test/AckEventTestUtil.h @@ -35,8 +35,9 @@ struct AckEventStreamDetailsMatcherBuilder { Builder&& clearDupAckedStreamIntervals(); auto build() && { + CHECK(maybeStreamId.has_value()); return ::testing::Pair( - *CHECK_NOTNULL(maybeStreamId.get_pointer()), + maybeStreamId.value(), ::testing::Field( &AckEvent::AckPacket::StreamDetails::dupAckedStreamIntervals, dupAckedStreamIntervals)); diff --git a/quic/state/test/AckHandlersTest.cpp b/quic/state/test/AckHandlersTest.cpp index 491f16f8b..9e42ddf92 100644 --- a/quic/state/test/AckHandlersTest.cpp +++ b/quic/state/test/AckHandlersTest.cpp @@ -2480,7 +2480,8 @@ TEST_P(AckHandlersTest, AckEventCreation) { .WillOnce(Return(writableBytes)); EXPECT_CALL(*rawCongestionController, getCongestionWindow()) .WillOnce(Return(congestionWindow)); - EXPECT_CALL(*rawCongestionController, getBandwidth()).WillOnce(Return(none)); + EXPECT_CALL(*rawCongestionController, getBandwidth()) + .WillOnce(Return(std::nullopt)); EXPECT_CALL(*rawPacketProcessor, onPacketAck(_)).Times(1); // check the AckEvent returned by processAckFrame so everything is filled @@ -2497,12 +2498,8 @@ TEST_P(AckHandlersTest, AckEventCreation) { auto ackEvent = ackEventResult.value(); checkAck(ackEvent); ASSERT_TRUE(ackEvent.ccState.has_value()); - EXPECT_EQ( - writableBytes, - CHECK_NOTNULL(ackEvent.ccState.get_pointer())->writableBytes); - EXPECT_EQ( - congestionWindow, - CHECK_NOTNULL(ackEvent.ccState.get_pointer())->congestionWindowBytes); + EXPECT_EQ(writableBytes, ackEvent.ccState.value().writableBytes); + EXPECT_EQ(congestionWindow, ackEvent.ccState.value().congestionWindowBytes); } TEST_P(AckHandlersTest, AckEventCreationSingleWrite) { @@ -2610,7 +2607,8 @@ TEST_P(AckHandlersTest, AckEventCreationSingleWrite) { .WillOnce(Return(writableBytes)); EXPECT_CALL(*rawCongestionController, getCongestionWindow()) .WillOnce(Return(congestionWindow)); - EXPECT_CALL(*rawCongestionController, getBandwidth()).WillOnce(Return(none)); + EXPECT_CALL(*rawCongestionController, getBandwidth()) + .WillOnce(Return(std::nullopt)); EXPECT_CALL(*rawPacketProcessor, onPacketAck(_)).Times(1); // check the AckEvent returned by processAckFrame so everything is filled @@ -2627,12 +2625,8 @@ TEST_P(AckHandlersTest, AckEventCreationSingleWrite) { auto ackEvent = ackEventResult.value(); checkAck(ackEvent); ASSERT_TRUE(ackEvent.ccState.has_value()); - EXPECT_EQ( - writableBytes, - CHECK_NOTNULL(ackEvent.ccState.get_pointer())->writableBytes); - EXPECT_EQ( - congestionWindow, - CHECK_NOTNULL(ackEvent.ccState.get_pointer())->congestionWindowBytes); + EXPECT_EQ(writableBytes, ackEvent.ccState.value().writableBytes); + EXPECT_EQ(congestionWindow, ackEvent.ccState.value().congestionWindowBytes); } TEST_P(AckHandlersTest, AckEventCreationNoCongestionController) { @@ -2759,9 +2753,9 @@ TEST_P(AckHandlersTest, AckEventReceiveTimestamps) { UnorderedMap expectedReceiveTimestamps; if (GetParam().frameType == FrameType::ACK_RECEIVE_TIMESTAMPS) { - conn.transportSettings.maybeAckReceiveTimestampsConfigSentToPeer.assign( + conn.transportSettings.maybeAckReceiveTimestampsConfigSentToPeer = AckReceiveTimestampsConfig{ - .maxReceiveTimestampsPerAck = 10, .receiveTimestampsExponent = 3}); + .maxReceiveTimestampsPerAck = 10, .receiveTimestampsExponent = 3}; ackFrame.maybeLatestRecvdPacketNum = 9; ackFrame.maybeLatestRecvdPacketTime = 500ms; RecvdPacketsTimestampsRange recvdPacketsTimestampsRange1 = { @@ -2826,9 +2820,9 @@ TEST_P(AckHandlersTest, AckEventReceiveTimestampsGaps) { const auto ackTime = startTime + 10ms + ackFrame.ackDelay; if (GetParam().frameType == FrameType::ACK_RECEIVE_TIMESTAMPS) { - conn.transportSettings.maybeAckReceiveTimestampsConfigSentToPeer.assign( + conn.transportSettings.maybeAckReceiveTimestampsConfigSentToPeer = AckReceiveTimestampsConfig{ - .maxReceiveTimestampsPerAck = 10, .receiveTimestampsExponent = 3}); + .maxReceiveTimestampsPerAck = 10, .receiveTimestampsExponent = 3}; ackFrame.maybeLatestRecvdPacketNum = 9; ackFrame.maybeLatestRecvdPacketTime = 500ms; RecvdPacketsTimestampsRange recvdPacketsTimestampsRange1 = { @@ -2923,9 +2917,9 @@ TEST_P(AckHandlersTest, AckEventReceiveTimestampsDuplicatesAll) { // Build the expected received timestamps map. UnorderedMap expectedReceiveTimestamps; if (GetParam().frameType == FrameType::ACK_RECEIVE_TIMESTAMPS) { - conn.transportSettings.maybeAckReceiveTimestampsConfigSentToPeer.assign( + conn.transportSettings.maybeAckReceiveTimestampsConfigSentToPeer = AckReceiveTimestampsConfig{ - .maxReceiveTimestampsPerAck = 10, .receiveTimestampsExponent = 3}); + .maxReceiveTimestampsPerAck = 10, .receiveTimestampsExponent = 3}; ackFrame.maybeLatestRecvdPacketNum = 9; ackFrame.maybeLatestRecvdPacketTime = 500ms; RecvdPacketsTimestampsRange recvdPacketsTimestampsRange1 = { @@ -3016,10 +3010,9 @@ TEST_P(AckHandlersTest, AckEventReceiveTimestampsPartialDuplicates) { auto ackTime = startTime + 10ms + ackFrame.ackDelay; if (GetParam().frameType == FrameType::ACK_RECEIVE_TIMESTAMPS) { - conn.transportSettings.maybeAckReceiveTimestampsConfigSentToPeer.assign( + conn.transportSettings.maybeAckReceiveTimestampsConfigSentToPeer = AckReceiveTimestampsConfig{ - .maxReceiveTimestampsPerAck = 10, - .receiveTimestampsExponent = 3}); + .maxReceiveTimestampsPerAck = 10, .receiveTimestampsExponent = 3}; ackFrame.maybeLatestRecvdPacketNum = 5; ackFrame.maybeLatestRecvdPacketTime = 500ms; RecvdPacketsTimestampsRange recvdPacketsTimestampsRange1 = { @@ -3134,9 +3127,9 @@ TEST_P(AckHandlersTest, AckEventReceiveTimestampsOutOfOrderAcks) { auto ackTime = startTime + 10ms + ackFrame.ackDelay; if (GetParam().frameType == FrameType::ACK_RECEIVE_TIMESTAMPS) { - conn.transportSettings.maybeAckReceiveTimestampsConfigSentToPeer.assign( + conn.transportSettings.maybeAckReceiveTimestampsConfigSentToPeer = AckReceiveTimestampsConfig{ - .maxReceiveTimestampsPerAck = 5, .receiveTimestampsExponent = 3}); + .maxReceiveTimestampsPerAck = 5, .receiveTimestampsExponent = 3}; ackFrame.maybeLatestRecvdPacketNum = 9; ackFrame.maybeLatestRecvdPacketTime = 500ms; RecvdPacketsTimestampsRange recvdPacketsTimestampsRange1 = { @@ -3264,9 +3257,9 @@ TEST_P(AckHandlersTest, AckEventReceiveTimestampsMaxCheck) { UnorderedMap expectedReceiveTimestamps; if (GetParam().frameType == FrameType::ACK_RECEIVE_TIMESTAMPS) { // Set max requested receive timestamps to 5 and send more than that. - conn.transportSettings.maybeAckReceiveTimestampsConfigSentToPeer.assign( + conn.transportSettings.maybeAckReceiveTimestampsConfigSentToPeer = AckReceiveTimestampsConfig{ - .maxReceiveTimestampsPerAck = 5, .receiveTimestampsExponent = 3}); + .maxReceiveTimestampsPerAck = 5, .receiveTimestampsExponent = 3}; ackFrame.maybeLatestRecvdPacketNum = 9; ackFrame.maybeLatestRecvdPacketTime = 100ms; // Send 10 timestamps, more than requested. @@ -3341,10 +3334,9 @@ TEST_P(AckHandlersTest, AckEventReceiveTimestampsInvalidCases) { ackFrame.ackDelay = 5ms; if (GetParam().frameType == FrameType::ACK_RECEIVE_TIMESTAMPS) { - conn.transportSettings.maybeAckReceiveTimestampsConfigSentToPeer.assign( + conn.transportSettings.maybeAckReceiveTimestampsConfigSentToPeer = AckReceiveTimestampsConfig{ - .maxReceiveTimestampsPerAck = 10, - .receiveTimestampsExponent = 3}); + .maxReceiveTimestampsPerAck = 10, .receiveTimestampsExponent = 3}; ackFrame.maybeLatestRecvdPacketNum = 5; ackFrame.maybeLatestRecvdPacketTime = 100ms; } @@ -3470,7 +3462,8 @@ TEST_P(AckHandlersTest, AckEventCreationInvalidAckDelay) { .WillOnce(Return(writableBytes)); EXPECT_CALL(*rawCongestionController, getCongestionWindow()) .WillOnce(Return(congestionWindow)); - EXPECT_CALL(*rawCongestionController, getBandwidth()).WillOnce(Return(none)); + EXPECT_CALL(*rawCongestionController, getBandwidth()) + .WillOnce(Return(std::nullopt)); EXPECT_CALL(*rawPacketProcessor, onPacketAck(_)).Times(1); ASSERT_FALSE(processAckFrame( @@ -3571,7 +3564,8 @@ TEST_P(AckHandlersTest, AckEventCreationRttMinusAckDelayIsZero) { .WillOnce(Return(writableBytes)); EXPECT_CALL(*rawCongestionController, getCongestionWindow()) .WillOnce(Return(congestionWindow)); - EXPECT_CALL(*rawCongestionController, getBandwidth()).WillOnce(Return(none)); + EXPECT_CALL(*rawCongestionController, getBandwidth()) + .WillOnce(Return(std::nullopt)); EXPECT_CALL(*rawPacketProcessor, onPacketAck(_)).Times(1); ASSERT_FALSE(processAckFrame( @@ -3699,7 +3693,7 @@ TEST_P(AckHandlersTest, AckEventCreationReorderingLargestPacketAcked) { EXPECT_CALL(*rawCongestionController, getCongestionWindow()) .WillOnce(Return(congestionWindow)); EXPECT_CALL(*rawCongestionController, getBandwidth()) - .WillOnce(Return(none)); + .WillOnce(Return(std::nullopt)); EXPECT_CALL(*rawPacketProcessor, onPacketAck(_)).Times(1); ASSERT_FALSE(processAckFrame( @@ -3756,7 +3750,7 @@ TEST_P(AckHandlersTest, AckEventCreationReorderingLargestPacketAcked) { EXPECT_CALL(*rawCongestionController, getCongestionWindow()) .WillOnce(Return(congestionWindow)); EXPECT_CALL(*rawCongestionController, getBandwidth()) - .WillOnce(Return(none)); + .WillOnce(Return(std::nullopt)); EXPECT_CALL(*rawPacketProcessor, onPacketAck(_)).Times(1); ASSERT_FALSE(processAckFrame( @@ -3813,7 +3807,7 @@ TEST_P(AckHandlersTest, AckEventCreationReorderingLargestPacketAcked) { EXPECT_CALL(*rawCongestionController, getCongestionWindow()) .WillOnce(Return(congestionWindow)); EXPECT_CALL(*rawCongestionController, getBandwidth()) - .WillOnce(Return(none)); + .WillOnce(Return(std::nullopt)); EXPECT_CALL(*rawPacketProcessor, onPacketAck(_)).Times(1); ASSERT_FALSE(processAckFrame( @@ -3933,7 +3927,7 @@ TEST_P(AckHandlersTest, AckEventCreationNoMatchingPacketDueToLoss) { EXPECT_CALL(*rawCongestionController, getCongestionWindow()) .WillOnce(Return(congestionWindow)); EXPECT_CALL(*rawCongestionController, getBandwidth()) - .WillOnce(Return(none)); + .WillOnce(Return(std::nullopt)); EXPECT_CALL(*rawPacketProcessor, onPacketAck(_)).Times(1); ASSERT_FALSE(processAckFrame( @@ -4059,7 +4053,8 @@ TEST_P(AckHandlersTest, ImplictAckEventCreation) { .WillOnce(Return(writableBytes)); EXPECT_CALL(*rawCongestionController, getCongestionWindow()) .WillOnce(Return(congestionWindow)); - EXPECT_CALL(*rawCongestionController, getBandwidth()).WillOnce(Return(none)); + EXPECT_CALL(*rawCongestionController, getBandwidth()) + .WillOnce(Return(std::nullopt)); EXPECT_CALL(*rawPacketProcessor, onPacketAck(_)).Times(1); ASSERT_FALSE(processAckFrame( @@ -4557,7 +4552,7 @@ class AckEventForAppDataTest : public Test { const TimePoint timepoint = Clock::now()) { CHECK(!updateConnection( *conn_, - none, + std::nullopt, packet.packet, timepoint, getEncodedSize(packet), diff --git a/quic/state/test/QuicStateFunctionsTest.cpp b/quic/state/test/QuicStateFunctionsTest.cpp index b07dbe440..c304635a4 100644 --- a/quic/state/test/QuicStateFunctionsTest.cpp +++ b/quic/state/test/QuicStateFunctionsTest.cpp @@ -965,12 +965,12 @@ TEST_F(QuicStateFunctionsTest, RttCalculationExtraRttMetricsStoredInLossState) { // 1 | 31ms (5 ms) | 26ms || 31 | 26 | (both) // 2 | 30ms (3 ms) | 27ms || 30 | 26 | (1) // 3 | 30ms (8 ms) | 22ms || 30 | 22 | (2) - // 4 | 37ms (8 ms) | 29ms || 30 | 22 | (none) - // 5 | 25ms (0 ms) | 29ms || 25 | 22 | (1) - // 6 | 25ms (4 ms) | 29ms || 25 | 21 | (2) - // 7 | 20ms (0 ms) | 29ms || 20 | 20 | (both) - // 8 | 0ms (0 ms) | 0ms || 0 | 0 | (both) - // 9 | 0ms (10 ms) | 0ms || 0 | 0 | (none) + // 4 | 37ms (8 ms) | 29ms || 30 | 22 | + // (std::nullopt) 5 | 25ms (0 ms) | 29ms || 25 | 22 | + // (1) 6 | 25ms (4 ms) | 29ms || 25 | 21 | (2) 7 + // | 20ms (0 ms) | 29ms || 20 | 20 | (both) 8 | + // 0ms (0 ms) | 0ms || 0 | 0 | (both) 9 | 0ms + // (10 ms) | 0ms || 0 | 0 | (std::nullopt) // case 1 updateRtt(conn, 31ms /* RTT sample */, 5ms /* ack delay */); @@ -1075,7 +1075,7 @@ TEST_F(QuicStateFunctionsTest, TestInvokeStreamStateMachineStreamError) { FizzServerQuicHandshakeContext::Builder().build()); QuicStreamState stream(1, conn); RstStreamFrame rst(1, GenericApplicationErrorCode::UNKNOWN, 100); - auto result = sendRstAckSMHandler(stream, folly::none); + auto result = sendRstAckSMHandler(stream, std::nullopt); ASSERT_TRUE(result.hasError()); ASSERT_NE(result.error().code.asTransportErrorCode(), nullptr); EXPECT_EQ( diff --git a/quic/state/test/QuicStreamFunctionsTest.cpp b/quic/state/test/QuicStreamFunctionsTest.cpp index b769e0126..4502bca66 100644 --- a/quic/state/test/QuicStreamFunctionsTest.cpp +++ b/quic/state/test/QuicStreamFunctionsTest.cpp @@ -1727,7 +1727,7 @@ TEST_P( EXPECT_EQ(0us, stream->totalHolbTime); EXPECT_EQ(1, stream->holbCount); - // uRL 0.1 - expected state transition: none + // uRL 0.1 - expected state transition: std::nullopt conn.streamManager->updateReadableStreams(*stream); EXPECT_EQ(lastHolbTimeMark, stream->lastHolbTime); @@ -1746,7 +1746,7 @@ TEST_P( EXPECT_FALSE(stream->lastHolbTime); EXPECT_EQ(1, stream->holbCount); - // uRL 1.1 - expected state transition: none + // uRL 1.1 - expected state transition: std::nullopt conn.streamManager->updateReadableStreams(*stream); EXPECT_FALSE(stream->lastHolbTime); EXPECT_EQ(totalHolbTimeMark, stream->totalHolbTime); @@ -1764,7 +1764,7 @@ TEST_P( EXPECT_EQ(totalHolbTimeMark, stream->totalHolbTime); EXPECT_EQ(1, stream->holbCount); - // uRL 2.1 - expected state transition: none + // uRL 2.1 - expected state transition: std::nullopt conn.streamManager->updateReadableStreams(*stream); EXPECT_FALSE(stream->lastHolbTime); EXPECT_EQ(totalHolbTimeMark, stream->totalHolbTime); @@ -1779,7 +1779,7 @@ TEST_P( EXPECT_EQ(totalHolbTimeMark, stream->totalHolbTime); auto lastHolbTimeMark2 = stream->lastHolbTime; - // uRL 3.1 - expected state transition: none + // uRL 3.1 - expected state transition: std::nullopt conn.streamManager->updateReadableStreams(*stream); EXPECT_EQ(lastHolbTimeMark2, stream->lastHolbTime); EXPECT_EQ(totalHolbTimeMark, stream->totalHolbTime); @@ -1802,7 +1802,7 @@ TEST_P( EXPECT_FALSE(stream->lastHolbTime); EXPECT_EQ(2, stream->holbCount); - // uRL 4.1 - expected state change: none + // uRL 4.1 - expected state change: std::nullopt conn.streamManager->updateReadableStreams(*stream); EXPECT_FALSE(stream->lastHolbTime); EXPECT_EQ(2, stream->holbCount); @@ -2431,7 +2431,7 @@ TEST_P(QuicStreamFunctionsTestBase, StreamLargestWriteOffsetTxedNothingTxed) { QuicStreamState stream(3, conn); stream.currentWriteOffset = 0; stream.writeBufMeta.offset = 0; - EXPECT_EQ(none, getLargestWriteOffsetTxed(stream)); + EXPECT_EQ(std::nullopt, getLargestWriteOffsetTxed(stream)); } TEST_F( @@ -2507,7 +2507,7 @@ TEST_F( TEST_P(QuicStreamFunctionsTestBase, StreamNextOffsetToDeliverNothingAcked) { QuicStreamState stream(3, conn); stream.currentWriteOffset = 100; - EXPECT_EQ(none, getLargestDeliverableOffset(stream)); + EXPECT_EQ(std::nullopt, getLargestDeliverableOffset(stream)); } TEST_P(QuicStreamFunctionsTestBase, StreamNextOffsetToDeliverAllAcked) { diff --git a/quic/state/test/QuicStreamManagerTest.cpp b/quic/state/test/QuicStreamManagerTest.cpp index eb79beced..4e0a81fcb 100644 --- a/quic/state/test/QuicStreamManagerTest.cpp +++ b/quic/state/test/QuicStreamManagerTest.cpp @@ -523,7 +523,7 @@ TEST_P(QuicStreamManagerTest, NextAcceptableLocalUnidirectionalStreamIdLimit) { serverStreamId2, manager.nextAcceptableLocalUnidirectionalStreamId()); ASSERT_TRUE(manager.createStream(serverStreamId2).hasValue()); - EXPECT_EQ(none, manager.nextAcceptableLocalUnidirectionalStreamId()); + EXPECT_EQ(std::nullopt, manager.nextAcceptableLocalUnidirectionalStreamId()); } TEST_P(QuicStreamManagerTest, NextAcceptableLocalBidirectionalStreamIdLimit) { @@ -541,7 +541,7 @@ TEST_P(QuicStreamManagerTest, NextAcceptableLocalBidirectionalStreamIdLimit) { serverStreamId2, manager.nextAcceptableLocalBidirectionalStreamId()); ASSERT_TRUE(manager.createStream(serverStreamId2).hasValue()); - EXPECT_EQ(none, manager.nextAcceptableLocalBidirectionalStreamId()); + EXPECT_EQ(std::nullopt, manager.nextAcceptableLocalBidirectionalStreamId()); } TEST_P(QuicStreamManagerTest, NextAcceptablePeerUnidirectionalStreamId) { @@ -598,7 +598,7 @@ TEST_P(QuicStreamManagerTest, NextAcceptablePeerUnidirectionalStreamIdLimit) { clientStreamId2, manager.nextAcceptablePeerUnidirectionalStreamId()); ASSERT_TRUE(manager.getStream(clientStreamId2).hasValue()); - EXPECT_EQ(none, manager.nextAcceptablePeerUnidirectionalStreamId()); + EXPECT_EQ(std::nullopt, manager.nextAcceptablePeerUnidirectionalStreamId()); } TEST_P(QuicStreamManagerTest, NextAcceptablePeerBidirectionalStreamIdLimit) { @@ -616,7 +616,7 @@ TEST_P(QuicStreamManagerTest, NextAcceptablePeerBidirectionalStreamIdLimit) { EXPECT_EQ(clientStreamId2, manager.nextAcceptablePeerBidirectionalStreamId()); ASSERT_TRUE(manager.getStream(clientStreamId2).hasValue()); - EXPECT_EQ(none, manager.nextAcceptablePeerBidirectionalStreamId()); + EXPECT_EQ(std::nullopt, manager.nextAcceptablePeerBidirectionalStreamId()); } TEST_P(QuicStreamManagerTest, TestClearActionable) { diff --git a/quic/state/test/StateDataTest.cpp b/quic/state/test/StateDataTest.cpp index eff51467d..d921a3e3e 100644 --- a/quic/state/test/StateDataTest.cpp +++ b/quic/state/test/StateDataTest.cpp @@ -30,7 +30,8 @@ TEST_F(StateDataTest, CongestionControllerState) { .WillOnce(Return(1000)); EXPECT_CALL(*mockCongestionController, getWritableBytes()) .WillOnce(Return(2000)); - EXPECT_CALL(*mockCongestionController, getBandwidth()).WillOnce(Return(none)); + EXPECT_CALL(*mockCongestionController, getBandwidth()) + .WillOnce(Return(std::nullopt)); EXPECT_THAT( mockCongestionController->getState(), testing::AllOf( @@ -38,7 +39,8 @@ TEST_F(StateDataTest, CongestionControllerState) { &CongestionController::State::congestionWindowBytes, 1000), testing::Field(&CongestionController::State::writableBytes, 2000), testing::Field( - &CongestionController::State::maybeBandwidthBitsPerSec, none))); + &CongestionController::State::maybeBandwidthBitsPerSec, + std::nullopt))); { Bandwidth testBandwidth( 300 /* bytes delivered */, 20us /* time interval */); @@ -81,7 +83,8 @@ TEST_F(StateDataTest, CongestionControllerState) { &CongestionController::State::congestionWindowBytes, 3000), testing::Field(&CongestionController::State::writableBytes, 4000), testing::Field( - &CongestionController::State::maybeBandwidthBitsPerSec, none))); + &CongestionController::State::maybeBandwidthBitsPerSec, + std::nullopt))); } } diff --git a/quic/tools/tperf/TperfClient.cpp b/quic/tools/tperf/TperfClient.cpp index 04186d19e..d47619f39 100644 --- a/quic/tools/tperf/TperfClient.cpp +++ b/quic/tools/tperf/TperfClient.cpp @@ -55,7 +55,7 @@ TPerfClient::TPerfClient( } void TPerfClient::timeoutExpired() noexcept { - quicClient_->closeNow(none); + quicClient_->closeNow(std::nullopt); constexpr double bytesPerMegabit = 131072; LOG(INFO) << "Received " << receivedBytes_ << " bytes in " << duration_.count() << " seconds."; @@ -212,8 +212,8 @@ void TPerfClient::start() { if (useAckReceiveTimestamps_) { LOG(INFO) << " Using ACK receive timestamps on client"; - settings.maybeAckReceiveTimestampsConfigSentToPeer.assign( - {maxAckReceiveTimestampsToSend_, kDefaultReceiveTimestampsExponent}); + settings.maybeAckReceiveTimestampsConfigSentToPeer = { + maxAckReceiveTimestampsToSend_, kDefaultReceiveTimestampsExponent}; } if (useInplaceWrite_) { settings.maxBatchSize = 1; diff --git a/quic/tools/tperf/TperfServer.cpp b/quic/tools/tperf/TperfServer.cpp index 786d61d50..0dd8cff35 100644 --- a/quic/tools/tperf/TperfServer.cpp +++ b/quic/tools/tperf/TperfServer.cpp @@ -394,9 +394,9 @@ class TperfStaticCwndCongestionControllerFactory } else if (pacerIntervalSource == "lrtt") { pacerIntervalSource_ = StaticCwndCongestionController::PacerIntervalSource::LatestRtt; - } else if (pacerIntervalSource != "none") { + } else if (pacerIntervalSource != "std::nullopt") { throw std::runtime_error(fmt::format( - "Invalid pacer interval source: {}. Valid values are mrtt, srtt, lrtt, none for min rtt, smoothed rtt, latest rtt, and no pacing respectively.", + "Invalid pacer interval source: {}. Valid values are mrtt, srtt, lrtt, std::nullopt for min rtt, smoothed rtt, latest rtt, and no pacing respectively.", pacerIntervalSource)); } } @@ -583,8 +583,8 @@ TPerfServer::TPerfServer( settings.copaDeltaParam = latencyFactor_; if (useAckReceiveTimestamps_) { LOG(INFO) << " Using ACK receive timestamps on server"; - settings.maybeAckReceiveTimestampsConfigSentToPeer.assign( - {maxAckReceiveTimestampsToSend_, kDefaultReceiveTimestampsExponent}); + settings.maybeAckReceiveTimestampsConfigSentToPeer = { + maxAckReceiveTimestampsToSend_, kDefaultReceiveTimestampsExponent}; } if (useL4sEcn_) { diff --git a/quic/tools/tperf/tperf.cpp b/quic/tools/tperf/tperf.cpp index 4f4fb571f..c6f1f9c90 100644 --- a/quic/tools/tperf/tperf.cpp +++ b/quic/tools/tperf/tperf.cpp @@ -24,7 +24,7 @@ DEFINE_uint64( DEFINE_uint64(writes_per_loop, 44, "Amount of socket writes per event loop"); DEFINE_uint64(window, 1024 * 1024, "Flow control window size"); DEFINE_bool(autotune_window, true, "Automatically increase the receive window"); -DEFINE_string(congestion, "cubic", "newreno/cubic/bbr/none"); +DEFINE_string(congestion, "cubic", "newreno/cubic/bbr/std::nullopt"); DEFINE_bool(pacing, false, "Enable pacing"); DEFINE_uint64( max_pacing_rate, @@ -52,8 +52,8 @@ DEFINE_uint64( "0 (the default) means the stream lives for the whole duration of the test."); DEFINE_string( pacing_observer, - "none", - "none/time/rtt/ack: Pacing observer bucket type: per 3ms, per rtt or per ack"); + "std::nullopt", + "std::nullopt/time/rtt/ack: Pacing observer bucket type: per 3ms, per rtt or per ack"); DEFINE_uint32( max_receive_packet_size, quic::kDefaultMaxUDPPayload, @@ -101,8 +101,8 @@ DEFINE_uint64( "If the StaticCwnd congestion controller is used, this is the static cwnd in bytes"); DEFINE_string( pacer_interval_source, - "none", - "If the StaticCwnd congestion controller is used with a pacer, this is the rtt that will be used to updated the pacer. (mrtt, lrtt, srtt, none)"); + "std::nullopt", + "If the StaticCwnd congestion controller is used with a pacer, this is the rtt that will be used to updated the pacer. (mrtt, lrtt, srtt, std::nullopt)"); DEFINE_bool(experimental_pacer, false, "Whether to use the experimental pacer"); namespace quic::tperf { diff --git a/quic/xsk/XskSender.cpp b/quic/xsk/XskSender.cpp index 515ff1301..52a15947f 100644 --- a/quic/xsk/XskSender.cpp +++ b/quic/xsk/XskSender.cpp @@ -50,8 +50,8 @@ quic::Optional XskSender::getXskBuffer(bool isIpV6) { auto maybeFreeUmemLoc = getFreeUmemIndex(); - if (!maybeFreeUmemLoc.hasValue()) { - return quic::none; + if (!maybeFreeUmemLoc.has_value()) { + return std::nullopt; } XskBuffer xskBuffer; @@ -151,7 +151,7 @@ SendResult XskSender::writeUdpPacket( guard.release(); - if (!freeUmemLoc.hasValue()) { + if (!freeUmemLoc.has_value()) { return SendResult::NO_FREE_DESCRIPTORS; } @@ -413,7 +413,7 @@ xdp_desc* XskSender::getTxDescriptor() { quic::Optional XskSender::getFreeUmemIndex() { if (freeUmemIndices_.empty()) { - return quic::none; + return std::nullopt; } uint32_t freeLoc = freeUmemIndices_.front(); freeUmemIndices_.pop(); diff --git a/quic/xsk/XskSender.h b/quic/xsk/XskSender.h index 3dcdb43fb..5ec1eee32 100644 --- a/quic/xsk/XskSender.h +++ b/quic/xsk/XskSender.h @@ -58,8 +58,8 @@ struct SharedState { // XskSender. The members are initialized by the primary XskSender (the one // with an ownerId of 0). // - // What must hold though, is that either all members are initialized, or none - // are. + // What must hold though, is that either all members are initialized, or + // std::nullopt are. void* sharedUmemAddr{nullptr}; void* sharedCxMap{nullptr}; int sharedXskFd{-1};